@adhdev/daemon-standalone 1.0.60-rc.62 → 1.0.60-rc.64
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/index.js +4 -4
- package/package.json +2 -2
- package/public/assets/{DashboardMeshGraphDialog-DtFpO2PQ.js → DashboardMeshGraphDialog-zKlWvAFM.js} +1 -1
- package/public/assets/common-CMA7YhWW.js +1 -0
- package/public/assets/common-Cw-N7oC7.js +1 -0
- package/public/assets/common-DMhfgNQ0.js +1 -0
- package/public/assets/common-d2kkUuhU.js +1 -0
- package/public/assets/index-BfRUbeFT.js +115 -0
- package/public/assets/index-CKh2UwjR.css +1 -0
- package/public/index.html +2 -2
- package/vendor/mcp-server/index.js +1 -1
- package/public/assets/common-BPFzWFQt.js +0 -1
- package/public/assets/common-D3xpMHz6.js +0 -1
- package/public/assets/common-D8_bJv3R.js +0 -1
- package/public/assets/common-DepW94Rn.js +0 -1
- package/public/assets/index-BYZgs8N1.js +0 -115
- package/public/assets/index-CpFTgx9d.css +0 -1
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-COe_yvHR.js","assets/vendor-CgFxQ3Rd.js","assets/terminal-6GBZ9nXN.css","assets/DashboardMeshGraphDialog-zKlWvAFM.js","assets/mesh-graph-7mv6fb91.js","assets/DashboardMeshGraphDialog-Cf4jCsgG.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var qx=Object.defineProperty;var zx=(e,t,s)=>t in e?qx(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var qe=(e,t,s)=>zx(e,typeof t!="symbol"?t+"":t,s);import{r as l,j as n,u as ve,i as at,M as rd,b as Gx,d as Vx,e as Yx,t as Qx,f as Jx,a as Qn,h as Xx,R as It,T as Wa,k as rr,l as Zl,m as ec,D as Zx,n as fi,o as wp,p as ey,q as ty,L as Sp,B as ny,v as sy,w as Kn,N as tc,x as ry}from"./vendor-CgFxQ3Rd.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const a of o)if(a.type==="childList")for(const i of a.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function s(o){const a={};return o.integrity&&(a.integrity=o.integrity),o.referrerPolicy&&(a.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?a.credentials="include":o.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(o){if(o.ep)return;o.ep=!0;const a=s(o);fetch(o.href,a)}})();function oy(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),s=[];return{record(r){const o={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...r,payload:r.payload?{...r.payload}:{}};return s.push(o),s.length>t&&s.splice(0,s.length-t),o},list(r={}){const o=Math.max(1,Math.floor(r.limit||100));return s.filter(a=>!r.interactionId||a.interactionId===r.interactionId).filter(a=>!r.topic||a.topic===r.topic).filter(a=>!r.kind||a.kind===r.kind).slice(-o).map(a=>({...a,payload:a.payload?{...a.payload}:{}}))},clear(){s.splice(0,s.length)}}}const Xs=oy();function wu(e){const t={};for(const s of e)s.transport&&(t[s.transport]=(t[s.transport]||0)+1);return{count:e.length,ids:e.map(s=>s.id),statuses:e.map(s=>String(s.status||"unknown")),transports:t}}function ay(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Su(e){return Array.isArray(e)?[...e]:[]}function kp(e,t){if(!e)return t??null;const s=Object.prototype.hasOwnProperty.call(e,"messages"),r=Object.prototype.hasOwnProperty.call(e,"activeModal"),o=typeof e.id=="string"?e.id.trim():"",a=typeof(t==null?void 0:t.id)=="string"?t.id.trim():"",i=!!o&&!!a&&o!==a;return t?{...t,...e,messages:s?Su(e.messages):i?[]:t.messages,activeModal:r?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...s?{messages:Su(e.messages)}:{},...r?{activeModal:e.activeModal??null}:{}}}function uo(e,t){const s=ay(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:s??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??s??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:kp(e.activeChat,t==null?void 0:t.activeChat),activeInteractivePrompt:Object.prototype.hasOwnProperty.call(e,"activeInteractivePrompt")?e.activeInteractivePrompt??null:(t==null?void 0:t.activeInteractivePrompt)??null,controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),launch:e.launch??(t==null?void 0:t.launch),model:e.model??(t==null?void 0:t.model),modelSource:e.modelSource??(t==null?void 0:t.modelSource),thinkingLevel:e.thinkingLevel??(t==null?void 0:t.thinkingLevel),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),muted:e.muted??(t==null?void 0:t.muted),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel),settings:e.settings??(t==null?void 0:t.settings)}}function jp(e,t,s){if(!(t!=null&&t.length))return(s==null?void 0:s.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const r=t.map(o=>{const a=e.find(i=>i.id===o.id);return a?uo(o,a):o});if((s==null?void 0:s.preserveMissing)!==!1){const o=new Set(t.map(a=>a.id));for(const a of e)o.has(a.id)||r.push(a)}return r}function gt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ae(...e){for(const t of e){if(typeof t!="string")continue;const s=t.trim();if(s)return s}}function xn(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Qt(...e){for(const t of e)if(typeof t=="boolean")return t}function nl(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function iy(e,t){const s=typeof e=="string"?e.trim().replace(/[\\/]+$/,""):"",r=typeof t=="string"?t.trim():"";if(r){if(/^(?:[A-Za-z]:[\\/]|\/)/.test(r))return r;if(s)return`${s}/${r.replace(/^[\\/]+/,"")}`}}function od(e){switch(e){case"fresh":return 30;case"no_upstream":return 4;case"unchecked":case void 0:return 0;case"stale":return-10;case"unavailable":return-15;default:return 0}}function ly(e,t){if(!Array.isArray(e))return;const s=e.map(r=>{const o=gt(r),a=Ae(o.path),i=Ae(o.commit),c=Ae(o.repoPath,o.repo_root)??iy(t,a);if(!a||!i)return null;const d={path:a,commit:i,dirty:Qt(o.dirty)??!1,outOfSync:Qt(o.outOfSync,o.out_of_sync)??!1},u=xn(o.lastCheckedAt,o.last_checked_at);u!==void 0&&(d.lastCheckedAt=u),c&&(d.repoPath=c);const m=Ae(o.error);return m&&(d.error=m),d}).filter(r=>r!==null);return s.length>0?s:void 0}function cy(e){return Qt(e.isGitRepo)!==void 0||!!Ae(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!Ae(e.repoRoot,e.repo_root,e.workspace)||xn(e.ahead,e.behind,e.staged,e.modified,e.untracked,e.deleted,e.renamed,e.lastCheckedAt,e.last_checked_at)!==void 0||Array.isArray(e.submodules)&&e.submodules.length>0}function Ca(e,t,s){const r=Qt(e.isGitRepo);if(!Object.keys(e).length||!cy(e))return;const o=r??!0,a=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(_=>typeof _=="string"):[],i=xn(e.conflicts)??a.length,c=Qt(e.hasConflicts)??i>0,d=Ae(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,u=ly(e.submodules,d),m=Ae(e.upstreamStatus,e.upstream_status),h=xn(e.upstreamFetchedAt,e.upstream_fetched_at),p=Ae(e.upstreamFetchError,e.upstream_fetch_error),g=Ae(e.error),f=xn(e.staged)??0,x=xn(e.modified)??0,b=xn(e.untracked)??0,k=xn(e.deleted)??0,j=xn(e.renamed)??0,v=xn(e.lastCheckedAt,e.last_checked_at);return{workspace:Ae(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:o,branch:Ae(e.branch)??null,headCommit:Ae(e.headCommit)??null,headMessage:Ae(e.headMessage)??null,upstream:Ae(e.upstream)??null,upstreamStatus:m??"unchecked",...h!==void 0?{upstreamFetchedAt:h}:{},...p?{upstreamFetchError:p}:{},ahead:xn(e.ahead)??0,behind:xn(e.behind)??0,staged:f,modified:x,untracked:b,deleted:k,renamed:j,dirty:Qt(e.dirty,e.isDirty,e.is_dirty)??(f+x+b+k+j>0||c),hasConflicts:c,conflictFiles:a,stashCount:xn(e.stashCount,e.stash_count)??0,...v!==void 0?{lastCheckedAt:v}:{},...u?{submodules:u}:{},...e.daemonBuildBehind&&typeof e.daemonBuildBehind=="object"?{daemonBuildBehind:e.daemonBuildBehind}:{},...g?{error:g}:{}}}function dy(e){if(!e)return Number.NEGATIVE_INFINITY;let t=0;return e.isGitRepo===!0&&(t+=50),e.isGitRepo===!1&&(t-=10),e.branch&&(t+=20),e.headCommit&&(t+=20),e.upstream&&(t+=10),t+=od(e.upstreamStatus),typeof e.ahead=="number"&&(t+=2),typeof e.behind=="number"&&(t+=2),Array.isArray(e.submodules)&&e.submodules.length>0&&(t+=4+e.submodules.length),e.error&&(t-=20),t}function uy(e,t){const s=gt(e.lastGit??e.last_git),r=gt(s.result),o=gt(s.status),a=gt(r.status),i=gt(e.lastProbe??e.last_probe),c=gt(i.git),d=gt(c.result),u=gt(c.status),m=gt(d.status);let h=null;for(const p of[o,a,u,m]){const g=Ca(p,e);if(!g)continue;const f=dy(g);(!h||f>h.score)&&(h={git:g,score:f})}return h==null?void 0:h.git}function my(e){const t=[Ae(e.workspace),Ae(e.providerType,e.provider),Ae(e.role),Ae(e.state,e.status),Ae(e.title),Ae(e.createdAt,e.created_at),Ae(e.startedAt,e.started_at)].filter(s=>!!s);if(t.length!==0)return`synthetic:${t.join("|")}`}function Ua(e){const t=gt(e),s=Ae(t.sessionId,t.session_id,t.id)??my(t);return s?{sessionId:s,...Ae(t.providerType,t.provider)?{providerType:Ae(t.providerType,t.provider)}:{},...Ae(t.state,t.status)?{state:Ae(t.state,t.status)}:{},...Ae(t.chatStatus,t.chat_status)?{chatStatus:Ae(t.chatStatus,t.chat_status)}:{},...Ae(t.lifecycle)?{lifecycle:Ae(t.lifecycle)}:{},...Ae(t.surfaceKind,t.surface_kind)?{surfaceKind:Ae(t.surfaceKind,t.surface_kind)}:{},...Ae(t.recoveryState,t.recovery_state)?{recoveryState:Ae(t.recoveryState,t.recovery_state)}:{},...Ae(t.workspace)?{workspace:Ae(t.workspace)}:{},...Ae(t.title)?{title:Ae(t.title)}:{},...Ae(t.role)?{role:Ae(t.role)}:{},...Qt(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:Qt(t.isSelfCoordinator,t.is_self_coordinator)}:{},...Ae(t.statusNote,t.status_note)?{statusNote:Ae(t.statusNote,t.status_note)}:{},...Ae(t.createdAt,t.created_at)?{createdAt:Ae(t.createdAt,t.created_at)}:{},...Ae(t.startedAt,t.started_at)?{startedAt:Ae(t.startedAt,t.started_at)}:{},...Ae(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:Ae(t.lastActivityAt,t.last_activity_at)}:{},...Qt(t.isCached,t.is_cached)!==void 0?{isCached:Qt(t.isCached,t.is_cached)}:{}}:null}function hy(e){const t=e&&typeof e=="object"?e:{};return Ae(t.id,t.nodeId,t.node_id)}function py(e,t){if(!t)return!1;const s=t.trim();return s?hy(e)===s:!1}var fy=["antigravity-cli","claude-cli","codex-cli","cursor-cli","grok-cli","kimi","opencode"];function nc(e){const t=e==null?void 0:e.metadata,s=typeof(t==null?void 0:t.accountEmail)=="string"?t.accountEmail.trim():"",r=typeof(t==null?void 0:t.planType)=="string"?t.planType.trim():"",o=[s,r].filter(Boolean);return o.length>0?o.join(" · "):null}var gy=["daemon_","standalone_"];function by(e){const t=Ae(e);return!!t&&/^[0-9a-f]{64}$/i.test(t)}function Np(e){var s,r;return!e||!by(e.id)?!1:!!!(Ae(e.machineNickname)||Ae(e.nickname)||Ae(e.hostname)||Ae(e.platform)||Ae((s=e.machine)==null?void 0:s.hostname)||Ae((r=e.machine)==null?void 0:r.platform)||Ae(e.machineId)||Array.isArray(e.sessions)&&e.sessions.length>0)}function sc(e){const t=Ae(e);if(t){for(const s of gy)if(t.startsWith(s))return t.slice(s.length).trim()||void 0;return t}}function xy(e){const t=sc(e);if(t)return t.startsWith("mach_")?`daemon_${t}`:t}function on(e,t){const s=sc(e),r=sc(t);return!s||!r?!1:s===r}var Cp=["easy","medium","difficult","freeform"];function yy(e){return typeof e=="string"&&Cp.includes(e)}function vy(e){const t=e&&typeof e=="object"?e:{},s=typeof t.provider=="string"?t.provider.trim():"";if(!s)return null;const r=typeof t.model=="string"?t.model.trim():"",o=typeof t.thinkingLevel=="string"?t.thinkingLevel.trim():"",a=Array.isArray(t.difficulty)?t.difficulty.filter(yy):[],i=Array.isArray(t.capability)?t.capability.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[],c=Number(t.maxParallel),d=Number.isFinite(c)&&c>0?Math.floor(c):void 0;return{provider:s,...r?{model:r}:{},...o?{thinkingLevel:o}:{},...a.length?{difficulty:a}:{},...i.length?{capability:i}:{},...d!==void 0?{maxParallel:d}:{}}}function _p(e){if(!Array.isArray(e))return[];const t=[];for(const s of e){const r=vy(s);r&&t.push(r)}return t}function wy(e){const t=new Set,s=[];for(const r of _p(e))t.has(r.provider)||(t.add(r.provider),s.push(r.provider));return s}function cn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var Ap=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress","monitor:long_generating"];cn(Ap);var Sy=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];cn(Sy);var ky=["p2p_offer","p2p_ice"];cn(ky);var jy=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];cn(jy);var Ny=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","beacon_vectors","daemon_mesh_command","p2p_offer","p2p_ice"];cn(Ny);var Cy=["auth_ok","auth_error","machine_evicted","force_disconnect","token_revoked","version_mismatch","force_update_required","command","agent_command","resolve_action","beacon_vectors_result","daemon_mesh_result","p2p_ready","p2p_offer","p2p_answer","p2p_ice","mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];cn(Cy);var _y=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],Ay=[...Ap,..._y];cn(Ay);var Ty=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];cn(Ty);var Iy=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];cn(Iy);var My=["p2p_ready","p2p_answer","p2p_ice"];cn(My);var Ry=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];cn(Ry);var Py=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];cn(Py);var Tp=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];cn(Tp);var Ip=["ping","pong","p2p_evicted","status_report","status_event","topic_update","topic_update_chunk","session_output","session_output_chunk","session_io_error","command_result","command_result_chunk","response"];cn(Ip);[...new Set([...Tp,...Ip])];var Ly="Claude TUI review page is not focused",Ey="Claude TUI answer delivered but not confirmed",ad=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"],Mp={generating:"working",finalizing:"working",starting:"working",waiting_approval:"blocked",waiting_choice:"blocked",idle:"ready",panel_hidden:"ready",not_monitored:"ready",error:"dead",stopped:"dead",disconnected:"dead"},Rp={running:"generating",streaming:"generating",busy:"generating",working:"generating",loading:"generating",loading_reference:"generating",thinking:"generating",active:"generating",no_progress:"generating",long_generating:"generating",initializing:"starting",waiting:"waiting_approval"},Dy=new Set(ad);function gi(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return Dy.has(t)?t:Rp[t]??null}function id(e){const t=gi(e);return t?Mp[t]:"unknown"}function bi(e){return id(e)==="working"}function Oy(e){return id(e)==="dead"}function Pp(e){const t=id(e);return t==="working"||t==="blocked"}function ku(e){return ad.filter(t=>Mp[t]===e)}var $y=["pending","assigned","completed","failed","cancelled"],Fy=["completed","failed","cancelled"],Hy=["code_change","validation","live_debug_readonly","launch_app","convergence"],By=["low","normal","high"],Wy=["low","medium","high"],Uy=["when_idle","interrupt"],Ky=["preserve","stop","delete_stopped","stop_and_delete"],Lp=["completed","blocked","failed"],Ep=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function ls(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}ls($y);ls(Fy);ls(Hy);ls(By);ls(Wy);ls(Uy);ls(Ky);ls(Lp);ls(Ep);var qy=["not_ready","send_in_flight","not_generating","not_supported","platform_unsupported","modal_parked","interrupt_not_implemented","interrupt_refused","idle_timeout","session_exited","unsupported_input","no_target","bootstrap_pending","duplicate_dispatch","internal_error"],zy=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(zy);var Gy=["fsm_edge","short_gen_inline","completion_flush_genuine","completion_flush_weak","monitor_final_summary","pre_cleanup_transcript","stall_transcript","startup_grace_collapse","acp_prompt_response","cdp_state","approval_gate","modal_button","mesh_stall_watchdog","status_monitor","pty_exit","provider_error","coordinator_probe","mcp_probe","worker_tool","dispatch","input_service","operator","intentional_cleanup","scheduler","git_probe","session_registry"],Vy=["mesh_queue","mesh_direct","plain"],Yy=["delivered","queued"],Qy=["local","p2p"],Jy=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],Xy=["default","native_source"],Zy=["restart","live_holder"],ev=["approval","choice"],tv=["approved","rejected","answered"],nv=["modal_button","auto_approve","prompt_answer"],sv=["genuine","weak"],rv=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],ov=["completed","aborted"],av=["alive","unknown","read_failed","dead"],iv=["auth_failed","billing_failed"],lv=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],cv=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],dv=["completed","failed"],uv=["operator_update","refine_terminal","validation_terminal"],mv=["delivered","queued","duplicate"],hv=[...ad,"unknown"],Dp=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],pv=["completed","failed","cancelled"],fv=["genuine","weak","tool_report","operator"],gv=["turn_end","weak_end_confirmed","transcript_final","worker_reported","finalization_timeout_no_response","session_error","provider_auth_failed","provider_billing_failed","operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded","operator_update","refine_terminal","validation_terminal","hard_ceiling","reclaim_budget_exhausted","hollow_max_retries","migration_orphan","dispatch_refused_session_exited","dispatch_refused_no_target","dispatch_refused_unsupported_input","dispatch_failed","session_exit","session_exit_before_turn","session_dead","hollow_completion","assigned_stranded_dispatch_unconfirmed","delivered_not_consumed_redrive","delivered_no_turn_deadline"],Op=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],ar={t:"id"},ir={t:"id",optional:!0},hs={t:"bool"},Xo={t:"bool",optional:!0},ju={t:"ms"},bv={t:"ms",optional:!0},Zo={t:"int",optional:!0},$t=e=>({t:"enum",values:e}),zr=e=>({t:"enum",values:e,optional:!0}),xv={dispatch_accepted:{scope:$t(Vy),messageId:ar,meshId:ir,nodeId:ir,providerType:ir,attemptNo:Zo,dispatchNonce:Zo,consumeProfile:zr(Xy),maxTaskRetries:Zo,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:ar,outcome:$t(Yy),via:$t(Qy)},delivery_refused:{messageId:ar,reason:$t(qy)},dispatch_failed:{workerAbsent:hs,reason:$t(Jy),refusalCode:ir},duplicate_dispatch_refusal:{holderSessionId:ar,holderAttemptId:ir},session_rebound:{toSessionId:ar,reason:$t(Zy)},turn_started:{retro:hs},suspension:{modal:$t(ev),modalKey:ir},suspension_resolved:{resolution:$t(tv),via:$t(nv)},turn_end:{strength:$t(sv),afterFinalizationTimeout:Xo,hollow:Xo,summary:{t:"summary_ref",optional:!0},blockReason:zr(rv),releasedByHardCap:Xo,nativeOutcome:zr(ov),live:{t:"live",optional:!0},reportExpected:Xo},transcript_final:{selfAttributing:hs,nativeRead:hs,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:bv},transcript_activity:{newestActivityAt:ju},no_progress:{stalledMs:ju,observedStatus:$t(hv),finalAssistantPresent:hs},liveness:{result:$t(av)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:zr(iv)},session_error:{reason:$t(lv)},worker_report:{outcome:$t(Lp),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:hs,branchState:zr(Ep),touchedFileCount:Zo},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:hs,commitsSinceDispatch:{t:"int"},attributable:hs},cancel:{reason:$t(cv)},operator_status:{status:$t(dv),reason:$t(uv)},coordinator_ack:{notify:$t(Op),outcome:$t(mv)},hold_expired:{holdId:ar,reason:$t(Dp)}},yv=Object.keys(xv);function As(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}As(Gy);As(yv);As(gv);As(Op);As(Dp);As(pv);As(fv);var vv=["turn.evidence","turn.committed","turn.notify","mesh.record"];As(vv);var wv=["user","remembered","mesh_slot","task_override","provider_default","unspecified"];function ld(e){return typeof e=="string"&&wv.includes(e)}var Sv=["dashboard","mesh","cli","api","restore"];function kv(e){return typeof e=="string"&&Sv.includes(e)}function jv(e){if(!e)return;const t=Array.isArray(e.history)?e.history[e.history.length-1]:void 0;return(t==null?void 0:t.value)??e.current??e.observed??$p(e)}function $p(e){if(!e)return;const t=Array.isArray(e.history)?e.history.find(s=>s.via==="launch"):void 0;return(t==null?void 0:t.value)??e.launchValue??e.requested??e.resolvedDefault}function Nv(e){const t=jv(e);if(!e||!t)return;const s=$p(e);return{value:t,...s&&s!==t?{changedFrom:s}:{},source:ld(e.source)?e.source:"unspecified"}}function Pn(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function rc(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Nu(e){if(!e||typeof e!="object")return;const t=e,s=[];if(Array.isArray(t.history))for(const u of t.history){if(!u||typeof u!="object")continue;const m=u,h=Pn(m.value),p=rc(m.at),g=m.via==="launch"||m.via==="change_model"||m.via==="observed"?m.via:void 0;h&&p!==void 0&&g&&s.push({at:p,value:h,via:g})}const r=Pn(t.requested),o=Pn(t.launchValue),a=Pn(t.resolvedDefault),i=Pn(t.current),c=Pn(t.observed),d=rc(t.observedAt);return{source:ld(t.source)?t.source:"unspecified",...r?{requested:r}:{},...o?{launchValue:o}:{},...a?{resolvedDefault:a}:{},...i?{current:i}:{},...c?{observed:c}:{},...d!==void 0?{observedAt:d}:{},history:s.slice(-20)}}function Cv(e){if(!e||typeof e!="object")return;const t=e,s=Pn(t.sessionId),r=Pn(t.providerType),o=rc(t.launchedAt),a=Nu(t.model),i=Nu(t.thinkingLevel);if(!s||!r||o===void 0||!a||!i)return;const c=Pn(t.providerVersion),d=Pn(t.workspace),u=Pn(t.autoApproveModeId);return{sessionId:s,providerType:r,...c?{providerVersion:c}:{},...t.providerChannel==="stable"||t.providerChannel==="preview"?{providerChannel:t.providerChannel}:{},launchedBy:kv(t.launchedBy)?t.launchedBy:"api",launchedAt:o,...d?{workspace:d}:{},model:a,thinkingLevel:i,...u?{autoApproveModeId:u}:{}}}var _v=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];function Fn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Fn(_v);var Av=["applied","recorded","rejected"];Fn(Av);var Tv=["taskId","deliveryId","attemptId","missionId","checkpointId","promptId","providerSessionId","targetNoteId","nodeId","sessionId","providerType","transport","attemptedSessionId","holderSessionId","reason","status","outcome","terminalKind","event","source","intentionalStopReason","retryable","rebound","forced","fallback","membershipRemoved","requestedForce","removedByRemoteDaemon","completedViaReady","intentional","weak","attempt","attemptCount","count"];new Set(Tv);var Iv=["completed","failed"];Fn(Iv);var Mv=["operator_update","refine_terminal","validation_terminal"];Fn(Mv);var Rv=["own","fleet"];Fn(Rv);var Pv=["active","paused","completed","abandoned"];Fn(Pv);var Lv=["magi","coordinator"];Fn(Lv);var Ev=["provider_quirk","pattern_to_avoid","recovery_lesson"];Fn(Ev);var Dv=["coordinator","unknown"];Fn(Dv);var Ov=["gate_claimed","gate_released","gate_abandoned","node_patched"];Fn(Ov);var $v=["turn_observe","mesh_record","turn_cancel","operator_status","turn_query","mesh_index_query","mission_upsert","mission_query","note_upsert","note_forget","tool_call_record","ledger_query","mission_list_query","record_local","queue_query","queue_enqueue","queue_enqueue_graph","queue_cancel","queue_requeue","direct_dispatch_record","graph_audit_record","active_work_query","recovery_context_query","graph_gate_claim","graph_gate_release","graph_gate_abandon","graph_node_patch","graph_view_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];Fn($v);const Fv=new Set(["no_progress","long_generating"]);function Cu(e){return!e||Fv.has(e)?e:gi(e)??e}function _u(e){return!!e&&typeof e=="object"&&"text"in e}function cd(e,t){const s=(t==null?void 0:t.joiner)??" ",r=(t==null?void 0:t.normalizeWhitespace)??!1;let o="";return typeof e=="string"?o=e:Array.isArray(e)?o=e.map(a=>typeof a=="string"?a:_u(a)?String(a.text||""):"").join(s):_u(e)?o=String(e.text||""):o=String(e||""),r?o.replace(/\s+/g," ").trim():o}function _r(e){return cd(e,{normalizeWhitespace:!0})}function Hv(e){let t="";for(let s=0;s<e.length;s++){const r=e[s],o=e.charCodeAt(s);if(!(o<=31&&r!==`
|
|
3
|
+
`&&r!==" ")&&!(o>=127&&o<=159)&&!(o>=8203&&o<=8207||o>=8234&&o<=8238||o===8288||o===65279)&&o!==65533){if(o===65038||o===65039){const a=t.length>0?t[t.length-1]:"";if(!a||a===`
|
|
4
|
+
`||a===" "||a===" ")continue}t+=r}}return t}function Au(e){var s,r;let t=0;return e.activeChat!==void 0&&(t+=4),e.activeInteractivePrompt!==void 0&&(t+=2),(s=e.childSessions)!=null&&s.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(r=e.agents)!=null&&r.length&&(t+=1),t}function Fp(e,t,s){if(s.type!=="adhdev-daemon")return s;const r={...s},o=t.version??s.version??e.version,a=t.serverVersion??e.serverVersion??s.serverVersion,i=t.versionMismatch===!0||e.versionMismatch===!0,c=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??s.versionUpdateReason;return o&&(r.version=o),a&&(r.serverVersion=a),d&&(r.versionUpdateReason=d),o&&a&&o===a?(delete r.versionMismatch,delete r.serverVersion,delete r.versionUpdateRequired,delete r.versionUpdateReason,r):((t.versionMismatch===!0||i&&o&&a&&o!==a)&&(r.versionMismatch=!0),c&&(r.versionUpdateRequired=!0),r)}function Bv(e){let t=2166136261;for(let s=0;s<e.length;s+=1)t^=e.charCodeAt(s),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function sl(e){if(!e||typeof e!="object")return"";const t=e,s=Bv(_r(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),s].join(":")}function Wv(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let s=2166136261;for(const r of e){const o=sl(r);for(let a=0;a<o.length;a+=1)s^=o.charCodeAt(a),s=Math.imul(s,16777619)>>>0}return{count:e.length,hash:s.toString(16).padStart(8,"0"),first:sl(e[0]),last:sl(e[e.length-1])}}function oc(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function ac(e,t,s){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(oc(e)&&oc(t)){const i=e.messages;Array.isArray(i)&&i===t.messages&&s.add(i)}if(Array.isArray(e)&&Array.isArray(t)){const i=Math.min(e.length,t.length);for(let c=0;c<i;c+=1)ac(e[c],t[c],s);return}const r=e,o=t,a=new Set([...Object.keys(r),...Object.keys(o)]);for(const i of a)i!=="messages"&&ac(r[i],o[i],s)}function xo(e,t){return Array.isArray(e)?e.map(s=>xo(s,t)):!e||typeof e!="object"?e:oc(e)?Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>[r,r==="messages"?Wv(o,t):xo(o,t)])):Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,xo(r,t)]))}function Uv(e,t){try{const s=new WeakSet;return ac(e,t,s),JSON.stringify(xo(e,s))===JSON.stringify(xo(t,s))}catch{return!1}}function ic(e,t,s){return Uv(e,t)?(e._lastUpdate=s,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Hp(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Kv(e,t,s){t[s]!==void 0&&(e[s]=t[s])}function Tu(e,t,s,r){var d;const o=(d=t.chats)!=null&&d.length?t.chats:e.chats,a=jp(e.childSessions,t.childSessions,{preserveMissing:r}),i=kp(t.activeChat,e.activeChat),c=t.workspace||e.workspace;return Fp(e,t,{...e,...t,chats:o,childSessions:a,activeChat:i,workspace:c,_lastUpdate:s})}function qv(e,t,s){var o,a;const r={};t.status&&t.status!==e.status&&(r.status=t.status),t.cdpConnected!==void 0&&(r.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(r.childSessions=jp(e.childSessions,t.childSessions,{preserveMissing:s})),(o=t.chats)!=null&&o.length&&!((a=e.chats)!=null&&a.length)&&(r.chats=t.chats),t.workspace&&(r.workspace=t.workspace);for(const i of["title","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","muted","model","modelSource","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])Kv(r,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(r.machineNickname=t.machineNickname),t.versionMismatch===!0&&(r.versionMismatch=!0),r}function zv(e,t,s,r){const o=qv(e,t,r),a=Object.keys(o).length>0?Fp(e,t,{...e,...o,_lastUpdate:s}):{...e,_lastUpdate:s};return ic(e,a,s)}function Gv(e){const t=new Set(e.map(a=>a.id)),s=new Set,r=new Set,o=new Set;for(const a of e){const i=Hp(a);i&&s.add(i),i&&a.type!=="adhdev-daemon"&&r.add(i),i&&a.type==="adhdev-daemon"&&a._sessionListAuthoritative&&o.add(i)}return{incomingIds:t,incomingDaemonIds:s,daemonIdsWithSessionEntries:r,daemonIdsWithAuthoritativeSessionList:o}}function Vv(e,t,s,r,o,a){return!o.has(t)||!a.has(t)||r.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?s>1e4:e.transport==="cdp-page"?s>3e4:!1}function Yv(e,t,s,r,o){return e.transport?s.has(t)&&!r.has(t)?!0:o.has(t):!1}function Qv(e,t,s){var m,h;const r=Date.now(),o=new Set((s==null?void 0:s.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(p=>({...p,_lastUpdate:r}));const a=new Map;for(const p of t)a.set(p.id,p);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:u}=Gv(e);for(const p of e){const g=a.get(p.id);if(!g){a.set(p.id,{...p,_lastUpdate:r});continue}const f=Au(p),x=Au(g),b=Hp(p),k=!o.has(b);if(f>x){const w=Tu(g,p,r,k);a.set(p.id,ic(g,w,r));continue}if(f<x){a.set(p.id,zv(g,p,r,k));continue}const j=w=>typeof w=="number"&&Number.isFinite(w),v=j(p.timestamp)&&j(g.timestamp),_=v?p.timestamp:p.timestamp||r,y=v?g.timestamp:g._lastUpdate||g.timestamp||0;if(_>=y){const w=Tu(g,p,r,k);a.set(p.id,ic(g,w,r));continue}(m=p.chats)!=null&&m.length&&!((h=g.chats)!=null&&h.length)&&a.set(p.id,{...g,chats:p.chats})}for(const[p,g]of a){const f=g.daemonId||p.split(":")[0];if(!c.has(f))continue;if(o.has(f)&&u.has(f)&&!i.has(p)){a.delete(p);continue}const x=r-(g._lastUpdate||g.timestamp||0);Vv(g,f,x,i,o,d)&&a.delete(p)}for(const[p,g]of a){const f=g.daemonId||p.split(":")[0];if(Yv(g,f,c,d,a))continue;r-(g._lastUpdate||g.timestamp||0)>3e5&&g.status!=="online"&&a.delete(p)}return Array.from(a.values())}function Jv(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}function Xv(e,t){return e.id===t||e.sessionId===t||e.instanceId===t}function Zv(e,t,s){const r=t.trim();if(!r)return e;let o=!1;const a=e.map(i=>{if(!Xv(i,r))return i;const c=i.activeInteractivePrompt;return c&&c.promptId===s.promptId?i:(o=!0,{...i,activeInteractivePrompt:s})});return o?a:e}const Bp=l.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},usesP2P:!0,userRole:void 0,connectionRetryStatuses:void 0}),Wp=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[],hydrateInteractivePrompt:()=>{}}),Up=l.createContext({userName:void 0,setUserName:()=>{},userRole:void 0,usesP2P:!0});function ew({children:e,connectionOverrides:t}){const[s,r]=l.useState([]),[o,a]=l.useState(!1),[i,c]=l.useState([]),[d,u]=l.useState(void 0),m=l.useRef(s);l.useEffect(()=>{m.current=s},[s]);const h=l.useCallback((v,_)=>{r(y=>{let w=!1;const S=y.map(C=>C.id!==v||C.chats===_?C:(w=!0,{...C,chats:_}));return w?S:y})},[]),p=l.useCallback((v,_)=>{r(y=>{const w=y.length===0?v:Qv(v,y,_),S=!Jv(y,w);return S&&Xs.record({kind:"dashboard.entries_applied",payload:{incoming:wu(v),next:wu(w)}}),S?w:y})},[]),g=l.useCallback(()=>a(!0),[]),f=l.useCallback((v,_)=>{r(y=>Zv(y,v,_))},[]),x=l.useMemo(()=>({injectEntries:p,markLoaded:g,getIdes:()=>m.current,hydrateInteractivePrompt:f}),[p,g,f]),b=t,k=l.useMemo(()=>({ides:s,updateRouteChats:h,initialLoaded:o,toasts:i,setToasts:c,wsStatus:(b==null?void 0:b.wsStatus)??"connected",isConnected:(b==null?void 0:b.isConnected)??!0,connectionStates:(b==null?void 0:b.connectionStates)??{},connectionTransports:(b==null?void 0:b.connectionTransports)??{},showReconnected:(b==null?void 0:b.showReconnected)??!1,retryConnection:b==null?void 0:b.retryConnection,retryServerConnection:b==null?void 0:b.retryServerConnection,connectionLoginUrl:b==null?void 0:b.connectionLoginUrl,isP2PActive:(b==null?void 0:b.isP2PActive)??!1,p2pStates:(b==null?void 0:b.p2pStates)??{},usesP2P:(b==null?void 0:b.usesP2P)??!0,userRole:b==null?void 0:b.userRole,connectionRetryStatuses:b==null?void 0:b.connectionRetryStatuses,userName:d,setUserName:u}),[s,h,o,i,b==null?void 0:b.wsStatus,b==null?void 0:b.isConnected,b==null?void 0:b.connectionStates,b==null?void 0:b.connectionTransports,b==null?void 0:b.showReconnected,b==null?void 0:b.retryConnection,b==null?void 0:b.retryServerConnection,b==null?void 0:b.connectionLoginUrl,b==null?void 0:b.isP2PActive,b==null?void 0:b.p2pStates,b==null?void 0:b.usesP2P,b==null?void 0:b.userRole,b==null?void 0:b.connectionRetryStatuses,d]),j=l.useMemo(()=>({userName:d,setUserName:u,userRole:b==null?void 0:b.userRole,usesP2P:(b==null?void 0:b.usesP2P)??!0}),[d,u,b==null?void 0:b.userRole,b==null?void 0:b.usesP2P]);return n.jsx(Wp.Provider,{value:x,children:n.jsx(Up.Provider,{value:j,children:n.jsx(Bp.Provider,{value:k,children:e})})})}function An(){return l.useContext(Bp)}function tw(){return l.useContext(Up)}function Ar(){return l.useContext(Wp)}const nw=new Proxy({},{get(e,t){if(!(t==="then"||typeof t=="symbol"))return()=>{throw new Error(`ApiProvider not installed — cannot call ApiClient.${String(t)}(). Wrap this tree in <ApiProvider client={...}>.`)}}}),sw=l.createContext(nw);function rw({client:e,children:t}){return n.jsx(sw.Provider,{value:e,children:t})}const ow={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Kp=l.createContext(ow);function aw({value:e,children:t}){return n.jsx(Kp.Provider,{value:e,children:t})}function _t(){return l.useContext(Kp)}function qp(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function iw(e){const t=qp(e);if(!t||t.error!=="untrusted_external_provider")return null;const s=t.provider&&typeof t.provider=="object"?t.provider:null;return{providerType:typeof(s==null?void 0:s.type)=="string"?s.type:null,sourceName:typeof(s==null?void 0:s.sourceName)=="string"?s.sourceName:null,description:typeof t.hint=="string"?t.hint:void 0}}function lw(e){const[t,s]=l.useState(null),r=l.useCallback(async(i,c)=>{const d=h=>e(i,"launch_cli",{...c,...h}),u=await d({}),m=iw(u);return m?new Promise(h=>{s({providerType:m.providerType||String(c.cliType??"?"),sourceName:m.sourceName,description:m.description,retry:()=>d({confirmExternalUntrusted:!0}),resolve:p=>{p.cancelled?h({success:!1,error:"user_cancelled_untrusted_launch"}):h(p.response)}})}):u},[e]),o=l.useCallback(async()=>{const i=t;if(i){s(null);try{const c=await i.retry(),d=qp(c);d!=null&&d.success?i.resolve({ok:!0,response:c}):i.resolve({ok:!1,error:(d==null?void 0:d.error)||"launch failed after confirm",response:c})}catch(c){i.resolve({ok:!1,error:(c==null?void 0:c.message)||String(c)})}}},[t]),a=l.useCallback(()=>{const i=t;i&&(s(null),i.resolve({ok:!1,cancelled:!0}))},[t]);return{launchCli:r,pending:t,confirm:o,cancel:a}}const Xe={size:18};function zp({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),n.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),n.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),n.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function dd({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Tr({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),n.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),n.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),n.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),n.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),n.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function cw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"9",cy:"7",r:"4"}),n.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),n.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function dw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function uw({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Gp({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),n.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),n.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),n.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function ud({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),n.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),n.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),n.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),n.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Dr({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("polyline",{points:"20 6 9 17 4 12"})})}function mw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"}),n.jsx("path",{d:"m15 5 4 4"})]})}function Or({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Po({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),n.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function H5({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),n.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function hw({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Jn({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Xn({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),n.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Vp({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"}),n.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),n.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Zs({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function $r({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polyline",{points:"23 4 23 10 17 10"}),n.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function an({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),n.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),n.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Ir({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M12 22v-5"}),n.jsx("path",{d:"M9 8V2"}),n.jsx("path",{d:"M15 8V2"}),n.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function On({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"5",r:"2"}),n.jsx("circle",{cx:"5",cy:"19",r:"2"}),n.jsx("circle",{cx:"19",cy:"19",r:"2"}),n.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),n.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),n.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function pw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),n.jsx("polyline",{points:"2 12 12 17 22 12"}),n.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function md({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function xi({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),n.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),n.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),n.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function hd({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function fw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),n.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),n.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function pd({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polyline",{points:"4 17 10 11 4 5"}),n.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function gw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Yp({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function _o({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function bw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}),n.jsx("line",{x1:"10",y1:"11",x2:"10",y2:"17"}),n.jsx("line",{x1:"14",y1:"11",x2:"14",y2:"17"})]})}function Bt({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Qp({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",className:t,children:[n.jsx("circle",{cx:"5",cy:"12",r:"1.9"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.9"}),n.jsx("circle",{cx:"19",cy:"12",r:"1.9"})]})}function yi({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),n.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),n.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),n.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function xw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),n.jsx("path",{d:"M12 2v6"}),n.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),n.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function yw({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function Jp({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})})}function vw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),n.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function js({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),n.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function lc({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M8.7 3A6 6 0 0 1 18 8c0 3 .6 5 1.4 6.5"}),n.jsx("path",{d:"M17 17H3s3-2 3-9a5.98 5.98 0 0 1 .6-2.6"}),n.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"}),n.jsx("line",{x1:"2",y1:"2",x2:"22",y2:"22"})]})}function Xp({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"5"}),n.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),n.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),n.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),n.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),n.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),n.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),n.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),n.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Zp({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function ef({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),n.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),n.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function vi({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),n.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Iu({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function ww({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),n.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Sw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),n.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),n.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function kw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),n.jsx("path",{d:"M13 2h9v9"}),n.jsx("path",{d:"M22 2L13 11"})]})}function jw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polyline",{points:"9 14 4 9 9 4"}),n.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function tf({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),n.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),n.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),n.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),n.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),n.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),n.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),n.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),n.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),n.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Nw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),n.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function Cw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),n.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),n.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function nf({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),n.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}function Mr({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`animate-spin ${t??""}`,children:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.22-8.56"})})}function sf({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"}),n.jsx("path",{d:"M13 13l6 6"})]})}function _w({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M18 11V6a2 2 0 0 0-4 0v5"}),n.jsx("path",{d:"M14 10V4a2 2 0 0 0-4 0v6"}),n.jsx("path",{d:"M10 10.5V6a2 2 0 0 0-4 0v8"}),n.jsx("path",{d:"M18 8a2 2 0 0 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15"})]})}function Aw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"16.5",y1:"9.4",x2:"7.5",y2:"4.21"}),n.jsx("path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"}),n.jsx("polyline",{points:"3.27 6.96 12 12.01 20.73 6.96"}),n.jsx("line",{x1:"12",y1:"22.08",x2:"12",y2:"12"})]})}function Tw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2",ry:"2"}),n.jsx("line",{x1:"12",y1:"18",x2:"12.01",y2:"18"})]})}function cc({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),n.jsx("circle",{cx:"18",cy:"6",r:"3"}),n.jsx("circle",{cx:"6",cy:"18",r:"3"}),n.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function Iw({providerType:e,sourceName:t,description:s,onConfirm:r,onCancel:o}){const{t:a}=ve("common"),i=l.useRef(null);return l.useEffect(()=>{var c;(c=i.current)==null||c.focus()},[]),l.useEffect(()=>{const c=d=>{d.key==="Escape"&&o()};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[o]),n.jsx("div",{role:"dialog","aria-modal":"true","aria-label":a("machine.confirmExternal.dialogAria"),className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:o,style:{pointerEvents:"auto"},children:n.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-amber-500/40 rounded-lg shadow-xl max-w-lg w-full",onClick:c=>c.stopPropagation(),children:[n.jsxs("div",{className:"px-4 py-3 border-b border-border-subtle flex items-center gap-2",children:[n.jsx("span",{"aria-hidden":!0,className:"text-amber-400",children:n.jsx(an,{size:16})}),n.jsx("h2",{className:"text-sm font-semibold",children:a("machine.confirmExternal.title")})]}),n.jsxs("div",{className:"px-4 py-3 text-xs flex flex-col gap-3",children:[n.jsx("p",{children:t?a("machine.confirmExternal.aboutToActivateFrom",{provider:e,source:t}):a("machine.confirmExternal.aboutToActivate",{provider:e})}),n.jsx("p",{className:"text-text-secondary",children:s??a("machine.confirmExternal.description")}),n.jsx("p",{className:"text-text-secondary",children:a("machine.confirmExternal.proceedWarning")})]}),n.jsxs("div",{className:"px-4 py-2 border-t border-border-subtle flex justify-end gap-2",children:[n.jsx("button",{ref:i,type:"button",onClick:o,className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:a("machine.confirmExternal.cancel")}),n.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-amber-500 text-black font-semibold hover:opacity-90",children:a("machine.confirmExternal.activate")})]})]})})}const rf=l.createContext(null);function Mw({sendDaemonCommand:e,children:t}){const s=lw(e),r=l.useMemo(()=>({launchCli:s.launchCli}),[s.launchCli]);return n.jsxs(rf.Provider,{value:r,children:[t,s.pending&&n.jsx(Iw,{providerType:s.pending.providerType,sourceName:s.pending.sourceName,description:s.pending.description,onConfirm:s.confirm,onCancel:s.cancel})]})}function wi(){const e=l.useContext(rf);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function Rw(e){const{baseUrl:t,getToken:s,onUnauthorized:r}=e;function o(c){return c.startsWith("http")?c:`${t}${c.startsWith("/")?"":"/"}${c}`}function a(c){const d=s==null?void 0:s(),u=o(c),m=c.startsWith("http")?new URL(u):new URL(u,typeof window<"u"?window.location.origin:"http://localhost");return d&&m.searchParams.set("token",d),!c.startsWith("http")&&!t?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function i(c,d={}){const u={"Content-Type":"application/json",...d.headers||{}},m=s==null?void 0:s();m&&(u.Authorization=`Bearer ${m}`);const h=o(c),p=new AbortController,g=setTimeout(()=>p.abort(),15e3);try{const f=await fetch(h,{...d,headers:u,signal:p.signal});if(f.status===401)throw r==null||r(),new Error("Unauthorized");if(!f.ok){const x=await f.json().catch(()=>({error:f.statusText}));throw new Error(x.error||`API Error: ${f.status}`)}return f.json()}finally{clearTimeout(g)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,u={})=>i(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:u})}),execTerminal:(c,d,u)=>i(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:u})}),sendAgentMessage:(c,d,u)=>i(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:u})}),getAgentStatus:c=>i(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,u)=>i(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:u?"approve":"reject"})}),getMuxState:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,d,u={})=>i(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:u})}),getMuxEventsUrl:c=>a(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>a(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:i}}function Si(e,t={}){if(!e)return"";const{suffix:s="",nowLabel:r="now",nowThreshold:o=60}=t,a=Date.now()-e,i=Math.floor(a/1e3);if(i<o)return r;const c=Math.floor(i/60);if(c<60)return`${c}m${s}`;const d=Math.floor(c/60);if(d<24)return`${d}h${s}`;const u=Math.floor(d/24);return u<7?`${u}d${s}`:new Date(e).toLocaleDateString()}const of=e=>Si(e);function Lo(e){if(e==null||e==="")return null;const t=e instanceof Date?e.getTime():typeof e=="number"?e:Date.parse(e);return Number.isFinite(t)&&t>0?t:null}function Eo(e){var s,r;if(e)return e;const t=((s=at)==null?void 0:s.resolvedLanguage)||((r=at)==null?void 0:r.language);return t&&t!=="cimode"?t:void 0}function Ka(e,t={}){const s=Lo(e);if(s===null)return"";const r=Eo(t.locale),o=t.now??Date.now(),a=Math.round((s-o)/1e3),i=Math.abs(a);let c;try{c=new Intl.RelativeTimeFormat(r,{numeric:"auto",style:"short"})}catch{c=new Intl.RelativeTimeFormat(void 0,{numeric:"auto",style:"short"})}return i<45?c.format(0,"second"):i<3600?c.format(Math.round(a/60),"minute"):i<86400?c.format(Math.round(a/3600),"hour"):i<7*86400?c.format(Math.round(a/86400),"day"):gd(s,{locale:r})}function fd(e,t){try{return new Intl.DateTimeFormat(e,t)}catch{return new Intl.DateTimeFormat(void 0,t)}}function Do(e,t={}){const s=Lo(e);return s===null?"":fd(Eo(t.locale),{dateStyle:"medium",timeStyle:t.seconds?"medium":"short"}).format(s)}function gd(e,t={}){const s=Lo(e);return s===null?"":fd(Eo(t.locale),{dateStyle:"medium"}).format(s)}function ki(e,t={}){const s=Lo(e);return s===null?"":fd(Eo(t.locale),{timeStyle:t.seconds?"medium":"short"}).format(s)}function B5(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const s=Math.floor(t/60);if(s<60)return`${s}m`;const r=Math.floor(s/60);return r<48?`${r}h ${s%60}m`:`${Math.floor(r/24)}d ${r%24}h`}function ps(e,t,s){try{return new Intl.NumberFormat(s,{style:"unit",unit:t,unitDisplay:"short"}).format(e)}catch{return`${e}${t[0]}`}}function Pw(e,t={}){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";const s=Eo(t.locale),r=Math.round(e/1e3);if(r<60)return ps(r,"second",s);const o=Math.floor(r/60);if(o<60)return ps(o,"minute",s);const a=Math.floor(o/60);if(a<48){const d=o%60;return d?`${ps(a,"hour",s)} ${ps(d,"minute",s)}`:ps(a,"hour",s)}const i=Math.floor(a/24),c=a%24;return c?`${ps(i,"day",s)} ${ps(c,"hour",s)}`:ps(i,"day",s)}function dc(e){return e?ki(e):""}function Lw(e,t,s){return Number(e.receivedAt||s[ji(e)]||0)||0}function af(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Ew(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}const Dw=new Set(["https:","http:","mailto:","file:"]);function Mu(e){if(e)try{const t=new URL(e);return Dw.has(t.protocol)?e:void 0}catch{return}}function Gr(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function rl(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function Ru(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t^e.charCodeAt(s),t|=0;return(t>>>0).toString(36)}function Ow(e){const t=e.toolBlockRef;if(!t||typeof t!="object")return null;const{recordIndex:s,blockIndex:r}=t;return!Number.isInteger(s)||!Number.isInteger(r)?null:`toolblock:${s}:${r}`}function ji(e,t){const s=e,r=cd(e.content,{joiner:`
|
|
5
|
+
`}),o=[e.id?`id:${e.id}`:"",s._localId?`local:${s._localId}`:"",e.bubbleId?`bubble:${e.bubbleId}`:"",e.providerUnitKey?`unit:${e.providerUnitKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",typeof e.sequence=="number"?`seq:${e.sequence}`:""].filter(Boolean),a=[e.id?`id:${e.id}`:"",s._localId?`local:${s._localId}`:"",s._turnKey?`turn:${s._turnKey}`:"",e.bubbleId?`bubble:${e.bubbleId}`:"",e.providerUnitKey?`unit:${e.providerUnitKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",typeof e.sequence=="number"?`seq:${e.sequence}`:""].filter(Boolean);if(a.length>0){if(o.length===0){const d=e.receivedAt||e.timestamp||0;return[...a,`role:${e.role??""}`,`chash:${Ru(r)}`,...d?[`ts:${d}`]:[]].join("|")}return a.join("|")}const i=e.receivedAt||e.timestamp||0;return[e.role?`role:${e.role}`:"role:",`chash:${Ru(r)}`,i?`ts:${i}`:""].filter(Boolean).join("|")}function $w(e){const t=e.map((o,a)=>ji(o)),s=new Map;for(const o of t)s.set(o,(s.get(o)??0)+1);const r=new Map;return t.map(o=>{if((s.get(o)??0)<2)return o;const a=r.get(o)??0;return r.set(o,a+1),`${o}|dup:${a}`})}function Fw(e){let t=2166136261;for(const s of e){const r=String(s||"");for(let o=0;o<r.length;o+=1)t^=r.charCodeAt(o),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function Hw(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function lf(e){return e?Fw([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Hw(e.content)]):""}const bd=200,Bw=80,Pu=650,Vr=new Map;function qa(e,t){if(!e)return!1;const s=String(e.messageFingerprint||"");return s?s===String(t||""):!0}function Ww(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=String(t||"").trim();if(s)return`${e.length}:${s}`;const r=e[e.length-1];return`${e.length}:${lf(r)}`}function Uw(e,t,s,r){return e||!t?!1:qa(s,r)}function Kw({scrollTop:e,scrollHeight:t,clientHeight:s,topThresholdPx:r=Bw,bottomThresholdPx:o=bd}){const a=Math.max(0,Number(e)||0),i=Math.max(0,Number(t)||0),c=Math.max(0,Number(s)||0);return Math.max(0,i-c)<=0?{showTop:!1,showBottom:!1}:{showTop:a>r,showBottom:Math.max(0,i-a-c)>o}}function qw(e){return Kw({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function mo(e,t=bd){return!!e&&e.fromBottom>=t}function zw(e,t){return qa(e,t)?!mo(e):!0}function Gw({hasSelection:e,userScrolledUp:t,hasChatContentChanged:s=!0}){return!(e||t||!s)}function Vw({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:s}){return e?!1:s||!t}function ol(e,t){const s=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(s)?s:t.top}const xd="adhdev_chat_activity_visible",Lu=new Set(["hidden","debug","internal"]),Eu=new Set(["visible","user","chat"]),Yw=new Set(["debug","trace","internal"]),Qw=new Set(["tool_call","terminal_command","runtime_activity"]),Jw=new Set(["runtime_status","provider_chrome","control"]),Xw=new Set(["thought","tool","terminal"]);function cf(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function xr(e){return typeof e=="string"?e.trim().toLowerCase():""}function al(e,t,s){return e[s]??(t==null?void 0:t[s])}function Du(e,t,s){const r=e;return s.some(o=>r[o]===!0||(t==null?void 0:t[o])===!0)}function Zw(e,t){const s=xr(e.kind);return s||(t==="tool"?"tool":"standard")}function il(e,t,s){const r=cf(e),o=typeof(r==null?void 0:r.label)=="string"?r.label.trim():"";return o||(t==="terminal"||s==="terminal_command"?"Terminal":t==="tool"||s==="tool_call"?"Tool":t==="thought"?"Thought":s==="runtime_activity"?"Runtime":"Activity")}function e0(e){const t=e.content;return Array.isArray(t)&&t.some(s=>!!s&&typeof s=="object"&&s.type!=="text")}function Ni(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=cf(e),s=xr(e.role),r=Zw(e,s),o=xr(al(e,t,"visibility")),a=xr(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??o),i=xr(al(e,t,"audience")),c=xr(al(e,t,"source")),d=Lu.has(o)||Lu.has(a)||Yw.has(i)||Du(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),u=Eu.has(o)||Eu.has(a)||i==="chat"||Du(e,t,["userFacing"]),m=Xw.has(r)||Qw.has(c);if(d)return{surface:m?"activity":"internal",isUserFacing:!1,isActivityFacing:m,isInternal:!m,role:s,kind:r,label:il(e,r,c)};if(u)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:s,kind:r,label:il(e,r,c)};if((s==="system"||r==="system")&&e0(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:s,kind:r,label:"Chat"};if(Jw.has(c)||s==="system"||r==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:s,kind:r,label:"Internal"};if(m)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:s,kind:r,label:il(e,r,c)};const h=(s==="user"||s==="human"||s==="assistant")&&(r==="standard"||r==="");return{surface:h?"chat":"internal",isUserFacing:h,isActivityFacing:!1,isInternal:!h,role:s,kind:r,label:h?"Chat":"Internal"}}function t0(e){return(Array.isArray(e)?e:[]).filter(t=>Ni(t).isActivityFacing)}const Ou=new WeakMap;function df(e){const t=Ou.get(e);if(t!==void 0)return t;const s=e.content,r=typeof s=="string"?s:(()=>{try{return JSON.stringify(s??"")}catch{return String(s??"")}})();return Ou.set(e,r),r}function n0(e){return`${String(e.role||"")}::${df(e)}`}function s0(e){if(e.length<2)return e;const t=[];let s="";for(const r of e){const o=n0(r);df(r).trim().length>0&&o===s||(t.push(r),s=o)}return t}function r0(e,t,s){return!s||t.length===0?e:[...e,...t].sort((r,o)=>{const a=Number(r.receivedAt??r.timestamp??0)||0,i=Number(o.receivedAt??o.timestamp??0)||0;if(a!==i)return a-i;const c=Number(r.index??0)||0,d=Number(o.index??0)||0;return c-d})}function qs(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(xd))!=="0"}catch{return!0}}function o0(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(xd,e?"1":"0")}catch{}}const uc="adhdev:chat-activity-visibility-change";function uf(e){o0(e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(uc,{detail:e}))}function yd(e){if(typeof window>"u")return()=>{};const t=r=>{const o=r.detail;e(typeof o=="boolean"?o:qs())},s=r=>{r.key&&r.key!==xd||e(qs())};return window.addEventListener(uc,t),window.addEventListener("storage",s),()=>{window.removeEventListener(uc,t),window.removeEventListener("storage",s)}}const $u=100,Fu=600;function Hu({text:e}){const{t}=ve("common"),[s,r]=l.useState(!1),o=l.useCallback(()=>{navigator.clipboard.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)}).catch(()=>{})},[e]);return n.jsx("button",{type:"button",onClick:o,"aria-label":t("chat.copyMessage"),className:"chat-copy-btn",children:s?n.jsx(Dr,{size:11}):n.jsx(ud,{size:11})})}function a0({text:e}){const{t}=ve("common"),[s,r]=l.useState(!1),o=l.useCallback(a=>{a.preventDefault(),a.stopPropagation(),navigator.clipboard.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)}).catch(()=>{})},[e]);return n.jsx("button",{type:"button",onClick:o,"aria-label":t("chat.copyCode"),title:t("chat.copyCode"),className:"chat-code-copy-btn",children:s?n.jsx(Dr,{size:12}):n.jsx(ud,{size:12})})}function i0(e){const t=mc(e.children);return n.jsxs("pre",{...e,children:[e.children,n.jsx(a0,{text:t})]})}function mc(e){var t;if(e==null||typeof e=="boolean")return"";if(typeof e=="string"||typeof e=="number")return String(e);if(Array.isArray(e))return e.map(mc).join("");if(l.isValidElement(e)){const s=(t=e.props)==null?void 0:t.children;return mc(s)}return""}const mf={pre:i0},hf=[Gx,{singleTilde:!1}],pf=[hf,Vx,Yx],l0=[hf];function ea(e,t,s){return n.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[n.jsx("span",{className:"font-medium",children:e}),t?n.jsx("span",{className:"ml-1 break-all",children:t}):null,s?n.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:s}):null]})}function Bu(e,t){return e?t?n.jsx("pre",{className:"chat-preformatted",children:e}):af(e)?n.jsx(rd,{remarkPlugins:pf,components:mf,children:e}):n.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const c0=l.memo(function({content:t,renderAsPreformatted:s,renderAsMarkdown:r}){return s?n.jsx("pre",{className:"chat-preformatted",children:t}):r?n.jsx(rd,{remarkPlugins:pf,components:mf,children:t}):n.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function Yr({parts:e,renderAsPreformatted:t}){return n.jsx("div",{className:"flex flex-col gap-2",children:e.map((s,r)=>{if(s.type==="text")return n.jsx("div",{children:Bu(String(s.text||""),t)},`text-${r}`);if(s.type==="image"){const o=rl(s),a=s.alt||s.description||Gr(s.uri,"image");return o?n.jsx("img",{src:o,alt:a,className:"max-w-full rounded-md border border-border-subtle"},`image-${r}`):n.jsx("div",{children:ea("Image",a,s.mimeType)},`image-fallback-${r}`)}if(s.type==="audio"){const o=rl(s);return o?n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("audio",{controls:!0,src:o,className:"max-w-full"}),s.transcript?n.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:s.transcript}):null]},`audio-${r}`):n.jsx("div",{children:ea("Audio",Gr(s.uri,"audio"),s.transcript||s.mimeType)},`audio-fallback-${r}`)}if(s.type==="video"){const o=rl(s),a=s.title||s.name||s.alt||Gr(s.uri,"video"),i=[s.transcript,s.description,s.mimeType].filter(Boolean).join(`
|
|
6
|
+
`);return n.jsxs("div",{className:"flex flex-col gap-1",children:[o?n.jsx("video",{controls:!0,src:o,poster:s.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):ea("Video",a,i),o&&i?n.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:i}):null]},`video-${r}`)}if(s.type==="resource_link"){const o=s.title||s.name||Gr(s.uri,"resource"),a=[s.description,s.mimeType].filter(Boolean).join(`
|
|
7
|
+
`),i=Mu(s.uri);return n.jsxs("div",{className:"flex flex-col gap-1",children:[i?n.jsx("a",{href:i,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:o}):ea("Resource",o,a),i&&a?n.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:a}):null]},`resource-link-${r}`)}if(s.type==="resource"&&s.resource){const o=Gr(s.resource.uri,"resource");if(s.resource.text)return n.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[n.jsx("div",{className:"text-2xs opacity-70 mb-1",children:o}),Bu(s.resource.text,!0)]},`resource-${r}`);const a=Mu(s.resource.uri);if(a)return n.jsx("a",{href:a,target:"_blank",rel:"noreferrer",className:"underline break-all",children:o},`resource-uri-${r}`)}return null})})}const d0=l.memo(function({log:t}){return n.jsxs("div",{className:"self-center chat-msg-action",children:[n.jsx(rd,{remarkPlugins:l0,children:t.text}),n.jsx("span",{className:"action-time",children:dc(t.timestamp)})]})},(e,t)=>e.log===t.log);function Wu({state:e,onExpand:t,onCollapse:s}){const{t:r}=ve("common");if((e==null?void 0:e.status)==="loading")return n.jsx("div",{className:"chat-msg-tool-expand","aria-live":"polite",children:r("chat.toolExpandLoading")});if((e==null?void 0:e.status)==="error"){const o=e.error==="source_changed";return n.jsx("div",{className:"chat-msg-tool-expand chat-msg-tool-expand-error",role:"status","data-expand-error-reason":e.error??"unknown",children:r(o?"chat.toolExpandStale":"chat.toolExpandUnavailable")})}return(e==null?void 0:e.status)==="expanded"?n.jsx("button",{type:"button",className:"chat-msg-tool-expand",onClick:s,children:r("chat.toolCollapse")}):n.jsx("button",{type:"button",className:"chat-msg-tool-expand",onClick:t,children:r("chat.toolExpand")})}function u0(e){const t=e.meta,s=t==null?void 0:t.pendingId;return typeof s=="string"?s:""}function m0(e){const t=e.meta;return(t==null?void 0:t.pendingLocal)===!0&&(t==null?void 0:t.queued)===!0}const Uu=new WeakMap;function Ku(e){const t=Uu.get(e);if(t!==void 0)return t;const s=h0(e);return Uu.set(e,s),s}function h0(e){const t=e.meta;return[lf(e),e.kind||"",e.senderName||"",e.bubbleId||"",e.bubbleState||"",e.visibility||"",e.transcriptVisibility||"",e.audience||"",e.source||"",e.userFacing===void 0?"":String(e.userFacing),e.internal===void 0?"":String(e.internal),e.isInternal===void 0?"":String(e.isInternal),e.debug===void 0?"":String(e.debug),t?String(t.label??""):"",t?String(t.isRunning??""):"",t?String(t.renderMode??""):"",t?String(t.pendingLocal??""):"",t?String(t.queued??""):"",t?String(t.pendingId??""):""].join("")}const p0=l.memo(function({message:t,receivedAt:s,agentName:r,userName:o,isCliMode:a,isTextExpanded:i,onToggleTextExpanded:c,onSendNow:d,isSendingNow:u,onCancelQueued:m,onExpandToolBlock:h,onCollapseToolBlock:p,toolExpand:g}){var T,F,q,Q;const{t:f}=ve("common"),x=m0(t),b=u0(t),k=(t.role||"").toLowerCase(),j=k==="user"||k==="human",v=t.kind||(k==="tool"?"tool":"standard"),_=Ni(t),y=Ew(t.content)?t.content:null,w=!!(y!=null&&y.some(K=>K.type!=="text")),S=cd(t.content,{joiner:`
|
|
8
|
+
`});if(_.isActivityFacing&&v!=="thought"&&v!=="tool"&&v!=="terminal"){const K=_.label||f("chat.activityFallback");return n.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[n.jsxs("div",{className:"chat-msg-activity-meta","aria-label":f("chat.activityMessageAria"),children:[n.jsx("span",{className:"activity-dot"}),n.jsx("span",{children:K})]}),w&&y?n.jsx("div",{className:"chat-msg-activity-body",children:n.jsx(Yr,{parts:y,renderAsPreformatted:!1})}):n.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:S})]})}if(v==="thought"){const K=typeof((T=t.meta)==null?void 0:T.label)=="string"?t.meta.label:f("chat.thought");return n.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":_.isActivityFacing?"true":void 0,children:[n.jsxs("div",{className:"chat-msg-header",children:[n.jsx(yw,{size:13}),n.jsx("span",{children:K})]}),n.jsx("div",{className:"chat-msg-body",children:S})]})}if(v==="tool"){const K=t.toolBlockRef,R=typeof((F=t.meta)==null?void 0:F.label)=="string"&&t.meta.label?t.meta.label:typeof t.toolName=="string"&&t.toolName?t.toolName:"Tool",D=(g==null?void 0:g.text)??S,P=!K&&!w&&D.length>Fu,W=P&&!i&&(g==null?void 0:g.status)!=="expanded"?`${D.slice(0,Fu-1)}…`:D;return n.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":_.isActivityFacing?"true":void 0,children:[n.jsxs("span",{className:"chat-bubble-header-end chat-msg-tool-header-end",children:[n.jsx(Hu,{text:S}),s!=null&&n.jsx("span",{className:"chat-time",children:dc(s)})]}),n.jsxs("div",{className:"chat-msg-tool-meta","aria-label":f("chat.toolMessageAria"),children:[n.jsx("span",{className:"tool-icon","aria-hidden":"true"}),n.jsx("span",{className:"tool-label",children:R})]}),w&&y?n.jsx("div",{className:"tool-text w-full",children:n.jsx(Yr,{parts:y,renderAsPreformatted:!1})}):n.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:W}),K&&h?n.jsx(Wu,{state:g,onExpand:()=>h(K),onCollapse:p}):P?n.jsx(Wu,{state:i||(g==null?void 0:g.status)==="expanded"?{status:"expanded"}:void 0,onExpand:c,onCollapse:c}):null]})}if(v==="terminal"){const K=typeof((q=t.meta)==null?void 0:q.label)=="string"?t.meta.label:"Ran command";return n.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":_.isActivityFacing?"true":void 0,children:[n.jsxs("div",{className:"chat-msg-header",children:[n.jsx("span",{children:(Q=t.meta)!=null&&Q.isRunning?n.jsx(Mr,{size:12}):n.jsx(Dr,{size:12})}),n.jsx("span",{children:K})]}),w&&y?n.jsx("div",{className:"chat-msg-body",children:n.jsx(Yr,{parts:y,renderAsPreformatted:!0})}):n.jsx("pre",{className:"chat-msg-body",children:S})]})}if(v==="system"){const K=S.length>$u,R=i||!K?S:`${S.slice(0,$u)}…`;return n.jsx("div",{className:"self-center chat-msg-system",title:S,children:w&&y?n.jsx(Yr,{parts:y,renderAsPreformatted:!1}):n.jsxs(n.Fragment,{children:[R,K&&c&&n.jsx("button",{type:"button",onClick:c,className:"chat-msg-system-expand ml-1.5 text-3xs font-semibold underline opacity-70 hover:opacity-100",children:f(i?"chat.showLess":"chat.showMore")})]})})}const C=t.meta,O=(typeof(C==null?void 0:C.renderMode)=="string"?C.renderMode.trim():"")==="preformatted",L=S,M=!1,$=L,N=O,I=!j&&!N&&af($),B=["chat-message-row",j?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return n.jsx("div",{className:B,children:(L||w||j)&&n.jsxs("div",{className:`chat-bubble ${j?"chat-bubble-user":"chat-bubble-assistant"}`,children:[n.jsxs("div",{className:`chat-bubble-header ${L||w?"mb-1.5":"mb-0"}`,children:[n.jsx("span",{className:"chat-sender",children:j?o||f("chat.you"):t.senderName||r}),n.jsxs("span",{className:"chat-bubble-header-end",children:[(L||w)&&n.jsx(Hu,{text:S}),s!=null&&n.jsx("span",{className:"chat-time",children:dc(s)})]})]}),(L||w)&&n.jsx("div",{className:"chat-markdown",children:w&&y?n.jsx(Yr,{parts:y,renderAsPreformatted:N}):n.jsx(c0,{content:$,renderAsPreformatted:N,renderAsMarkdown:I})}),M,x&&n.jsxs("div",{className:"chat-bubble-queued","data-chat-queued-row":"true",children:[n.jsx("span",{className:"chat-bubble-queued-label","aria-label":f("chat.waitingToSendAria"),children:f("chat.waitingToSend")}),d&&n.jsx("button",{type:"button",onClick:()=>d(b||void 0),disabled:u,className:"chat-bubble-send-now","aria-label":f("chat.sendNowAria"),title:f("chat.sendNowTitle"),children:f(u?"chat.sending":"chat.sendNow")}),m&&b&&n.jsx("button",{type:"button",onClick:()=>m(b),disabled:u,className:"chat-bubble-cancel-queued","aria-label":f("chat.cancelQueuedAria"),title:f("chat.cancelQueuedTitle"),children:f("chat.cancelQueued")})]})]})})},(e,t)=>(e.message===t.message||Ku(e.message)===Ku(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded&&e.isSendingNow===t.isSendingNow&&e.onSendNow===t.onSendNow&&e.onCancelQueued===t.onCancelQueued&&e.toolExpand===t.toolExpand),f0=l.forwardRef(function({messages:t,actionLogs:s,agentName:r="Agent",userName:o,isCliMode:a=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:u,showActivityMessages:m=!1,emptyState:h,onLoadMore:p,isLoadingMore:g,hasMoreHistory:f,hiddenLiveCount:x=0,loadError:b,scrollToBottomRequestNonce:k,isVisible:j=!0,onSendNow:v,isSendingNow:_,onCancelQueued:y,onExpandToolBlock:w,onCollapseToolBlock:S,toolExpansions:C},A){const{t:O}=ve("common"),L=l.useRef(null),M=l.useRef(null),$=l.useRef(null),N=l.useRef(0),I=l.useRef(""),B=l.useRef(""),T=l.useRef(!1),F=l.useRef(null),q=l.useRef(!1),Q=l.useRef(null),K=l.useRef(!1),[R,D]=l.useState(new Set),[P,H]=l.useState({showTop:!1,showBottom:!1}),W=l.useRef(!1),U=l.useRef(!1),ae=l.useRef(j),be=l.useRef(j),V=l.useRef(null);be.current=j;const we=()=>{const Y=L.current;return Y?Y.scrollHeight-Y.scrollTop-Y.clientHeight<bd:!0},ce=l.useCallback(()=>{const Y=L.current,me=Y?qw(Y):{showTop:!1,showBottom:!1};H(fe=>fe.showTop===me.showTop&&fe.showBottom===me.showBottom?fe:me)},[]),de=l.useCallback((Y="auto")=>{var fe;const me=L.current;me&&(me.scrollTo({top:me.scrollHeight,behavior:Y}),(fe=me.ownerDocument.defaultView)==null||fe.requestAnimationFrame(()=>ce()))},[ce]),ne=l.useCallback((Y="auto")=>{var fe;const me=L.current;me&&(me.scrollTo({top:0,behavior:Y}),(fe=me.ownerDocument.defaultView)==null||fe.requestAnimationFrame(()=>ce()))},[ce]),ee=l.useCallback(()=>{var oe;const Y=L.current,me=(oe=window.getSelection)==null?void 0:oe.call(window);if(!Y||!me||me.rangeCount===0||me.isCollapsed){K.current=!1;return}const fe=me.anchorNode,E=me.focusNode;K.current=!!(fe&&E&&Y.contains(fe)&&Y.contains(E))},[]),ue=l.useMemo(()=>{const Y=[],me=[];for(const fe of Array.isArray(t)?t:[]){const E=Ni(fe);E.isUserFacing?Y.push(fe):E.isActivityFacing&&me.push(fe)}return s0(r0(Y,me,m))},[t,m]),je=ue.length===t.length?u:void 0,X=Ww(ue,je),G=l.useCallback(()=>{const Y=L.current;if(!Y||!c||!be.current)return;const me={top:Y.scrollTop,fromBottom:Math.max(0,Y.scrollHeight-Y.scrollTop-Y.clientHeight),messageFingerprint:X};V.current={contextKey:c,snapshot:me},Vr.set(c,me)},[c,X]),z=l.useCallback((Y="auto")=>{F.current!=null&&cancelAnimationFrame(F.current),F.current=requestAnimationFrame(()=>{F.current=null,de(Y)})},[de]),ie=l.useCallback(()=>{W.current=!1,q.current=!0,U.current=!0,Q.current!=null&&window.clearTimeout(Q.current),Q.current=window.setTimeout(()=>{q.current=!1,Q.current=null},Pu)},[]);l.useEffect(()=>{const Y=!T.current,me=B.current!==c;if(B.current=c,Y||me){T.current=!0;const E=c?Vr.get(c):null,oe=!!E&&qa(E,X);W.current=oe?mo(E):!1,q.current=zw(E,X),K.current||(oe?requestAnimationFrame(()=>{const Ie=L.current;Ie&&(ol(Ie,E),W.current=mo(E),ce(),U.current=!0)}):z("auto")),N.current=ue.length,I.current=X;return}ue.length>N.current;const fe=X!==I.current;Gw({hasSelection:K.current,userScrolledUp:W.current,hasChatContentChanged:fe})&&z("auto"),N.current=ue.length,I.current=X},[X,c,ue.length,z,ce]),l.useEffect(()=>{k&&(ie(),K.current||z("auto"))},[ie,z,k]),l.useEffect(()=>{const Y=ae.current;Y&&!j&&G(),be.current=j,ae.current=j;const me=c?Vr.get(c):null;if(Uw(Y,j,me,X)){if(!me)return;W.current=mo(me),q.current=!1,K.current||requestAnimationFrame(()=>{const fe=L.current;fe&&(ol(fe,me),ce())});return}},[j,c,X,ie,G,z,ce]),l.useEffect(()=>()=>{const Y=V.current;Y&&Vr.set(Y.contextKey,Y.snapshot),F.current!=null&&cancelAnimationFrame(F.current),Q.current!=null&&window.clearTimeout(Q.current)},[]),l.useEffect(()=>{const Y=M.current,me=L.current;if(!Y||!me)return;const fe=()=>{Q.current!=null&&window.clearTimeout(Q.current),Q.current=window.setTimeout(()=>{q.current=!1,Q.current=null},Pu)},E=new ResizeObserver(()=>{ce();const oe=q.current;Vw({hasSelection:K.current,userScrolledUp:W.current,contextAutoScrollActive:oe})&&(z("auto"),oe&&fe())});return E.observe(Y),me!==Y&&E.observe(me),()=>{E.disconnect(),Q.current!=null&&(window.clearTimeout(Q.current),Q.current=null)}},[z,c,ce]),l.useImperativeHandle(A,()=>({scrollToBottom:(Y="smooth")=>{de(Y)}}),[de]),l.useEffect(()=>{const Y=L.current;if(!Y)return;let me;const fe=()=>{G(),clearTimeout(me),me=setTimeout(()=>{W.current=!we(),ce()},50)};return Y.addEventListener("scroll",fe,{passive:!0}),()=>{Y.removeEventListener("scroll",fe),clearTimeout(me)}},[G,ce]),l.useEffect(()=>(document.addEventListener("selectionchange",ee),()=>document.removeEventListener("selectionchange",ee)),[ee]);const Ne=l.useRef(0),Be=l.useRef(!1);l.useEffect(()=>{const Y=L.current;if(!Y||!Be.current||Ne.current===0)return;const me=Y.scrollHeight-Ne.current;me>0&&(Y.scrollTop=me),ce(),G(),Ne.current=0,Be.current=!1},[ue.length,G,ce]),l.useEffect(()=>{if(U.current||!c)return;const Y=Vr.get(c),me=L.current;if(!(!Y||!me)){if(!qa(Y,X)){de("auto"),U.current=!0;return}ol(me,Y),W.current=mo(Y),ce(),U.current=!0}},[c,X,ue.length,de,ce]);const Le=()=>{const Y=L.current;Y&&(Ne.current=Y.scrollHeight),Be.current=!0,p==null||p()},Je=()=>{W.current=!0,ne("smooth"),G()},Se=()=>{ie(),de("smooth"),G()},he=l.useMemo(()=>{const Y=$w(ue),me=ue.map((Ie,Z)=>({type:"message",data:Ie,index:Z,ts:Lw(Ie,Z,d),stableKey:Y[Z]}));if(!s||s.length===0)return me;const fe=[...s].sort((Ie,Z)=>Ie.timestamp-Z.timestamp).map((Ie,Z)=>({type:"action",data:Ie,index:Z,ts:Ie.timestamp})),E=[];let oe=0;for(const Ie of me){for(;oe<fe.length&&Ie.ts>0&&fe[oe].ts<Ie.ts;)E.push(fe[oe++]);E.push(Ie)}for(;oe<fe.length;)E.push(fe[oe++]);return E},[ue,s,d]),pe=x>0||!!f,Ee=x>0?x>80?O("chatList.showEarlierMessagesHidden",{count:Math.min(x,80),total:x}):O("chatList.showEarlierMessages",{count:Math.min(x,80)}):b?O("chatList.loadErrorRetry",{error:b}):O("chatList.loadOlderMessages");return n.jsxs("div",{className:"chat-scroll-frame",children:[n.jsx("div",{ref:L,"data-chat-scroll":!0,className:"chat-container",children:n.jsxs("div",{ref:M,className:"chat-container-content",children:[g&&n.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:O("chatList.loadingOlderMessages")}),pe&&!g&&n.jsx("div",{className:"text-center py-2",children:n.jsx("button",{type:"button",onClick:Le,className:`text-2xs rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${b&&x===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:Ee})}),he.length===0&&!pe&&(h||n.jsx("div",{className:"text-center mt-16 opacity-20 text-xxs",children:O("chatList.waitingForMessages")})),he.map(Y=>{if(Y.type==="action"){const se=Y.data;return n.jsx(d0,{log:se},`action-${Y.index}`)}const me=Y.data;Y.index;const fe=Y.stableKey,E=me.receivedAt||d[ji(me)],oe=`${c}-${fe}`,Ie=R.has(oe),Z=Ow(me)??fe;return n.jsx(p0,{message:me,receivedAt:E,agentName:r,userName:o,isCliMode:a,isTextExpanded:Ie,onSendNow:v,isSendingNow:_,onCancelQueued:y,toolExpand:C==null?void 0:C[Z],onExpandToolBlock:w?se=>w(Z,se):void 0,onCollapseToolBlock:S?()=>S(Z):void 0,onToggleTextExpanded:()=>D(se=>{const ye=new Set(se);return Ie?ye.delete(oe):ye.add(oe),ye})},`msg-${fe}`)}),i&&n.jsx("div",{className:"self-start chat-typing-wrapper",children:n.jsxs("div",{className:"typing-indicator",children:[n.jsx("div",{className:"dot"}),n.jsx("div",{className:"dot"}),n.jsx("div",{className:"dot"}),n.jsx("span",{className:"text-2xs text-text-muted ml-1",children:O("chatList.agentGenerating")})]})}),n.jsx("div",{className:"min-h-10",ref:$})]})}),(P.showTop||P.showBottom)&&n.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":O("chatList.jumpToTop"),children:[P.showTop&&n.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:Je,"aria-label":O("chatList.jumpToOldestMessages"),title:O("chatList.jumpToTop"),children:O("chatList.top")}),P.showBottom&&n.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:Se,"aria-label":O("chatList.jumpToLatestMessages"),title:O("chatList.jumpToBottom"),children:O("chatList.latest")})]})]})}),g0=l.memo(f0,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.showActivityMessages===t.showActivityMessages&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible&&e.onSendNow===t.onSendNow&&e.isSendingNow===t.isSendingNow&&e.onCancelQueued===t.onCancelQueued&&e.toolExpansions===t.toolExpansions&&e.onExpandToolBlock===t.onExpandToolBlock&&e.onCollapseToolBlock===t.onCollapseToolBlock),b0="modulepreload",x0=function(e){return"/"+e},qu={},kr=function(t,s,r){let o=Promise.resolve();if(s&&s.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));o=Promise.allSettled(s.map(d=>{if(d=x0(d),d in qu)return;qu[d]=!0;const u=d.endsWith(".css"),m=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${m}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":b0,u||(h.as="script"),h.crossOrigin="",h.href=d,c&&h.setAttribute("nonce",c),document.head.appendChild(h),u)return new Promise((p,g)=>{h.addEventListener("load",p),h.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function a(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return o.then(i=>{for(const c of i||[])c.status==="rejected"&&a(c.reason);return t().catch(a)})};let zu=!1;const ff=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:s,fontSize:r=13,readOnly:o=!1,sizingMode:a="measured"},i)=>{const c=l.useRef(null),[d,u]=l.useState(null),m=l.useRef([]),h=l.useRef(!1),p=l.useRef(!1),g=l.useRef(!1),f=l.useRef(!1),x=()=>{const b=c.current;if(b){h.current&&(b.clear(),h.current=!1);for(const k of m.current)b.write(k.data,k.onProcessed);m.current=[],p.current&&(b.fit(),p.current=!1),g.current&&(b.bumpResize(),g.current=!1),f.current&&(b.scrollToTop(),f.current=!1)}};return l.useImperativeHandle(i,()=>({write:(b,k)=>{c.current?c.current.write(b,k):m.current.push({data:b,onProcessed:k})},clear:()=>{c.current?c.current.clear():(m.current=[],h.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(m.current=[],h.current=!0)},resize:(b,k)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(b,k)},fit:()=>{c.current?c.current.fit():p.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():g.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():f.current=!0},getSelection:()=>{var b,k;return((k=(b=c.current)==null?void 0:b.getSelection)==null?void 0:k.call(b))||""},getVisibleText:()=>{var b,k;return((k=(b=c.current)==null?void 0:b.getVisibleText)==null?void 0:k.call(b))||""}}),[]),l.useEffect(()=>{d&&x()},[d]),l.useEffect(()=>{let b=!1;return kr(()=>import("./terminal-COe_yvHR.js"),__vite__mapDeps([0,1,2])).then(k=>{zu||(zu=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),b||u(()=>k.GhosttyTerminalView)}).catch(k=>{console.error("[CliTerminal] failed to load terminal renderer",k)}),()=>{b=!0}},[]),d?n.jsx(d,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:s,fontSize:r,readOnly:o,sizingMode:a,className:"w-full h-full rounded-lg overflow-hidden"}):n.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});ff.displayName="CliTerminal";function ft(...e){return Qx(Jx(e))}const y0={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},v0={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},wn=l.forwardRef(function({radius:t="xl",padding:s="md",className:r,...o},a){return n.jsx("div",{ref:a,className:ft("border border-border-subtle bg-bg-secondary",y0[t],v0[s],r),...o})});function ta({label:e,value:t,sub:s,icon:r}){return n.jsxs(wn,{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsx("span",{className:"text-base flex items-center",children:r}),n.jsx("span",{className:"text-3xs text-text-muted uppercase tracking-wide font-semibold",children:e})]}),n.jsx("div",{className:"text-[22px] leading-[30px] font-bold text-text-primary tracking-tight",children:t}),s&&n.jsx("div",{className:"text-2xs text-text-muted mt-0.5",children:s})]})}function gf({title:e,description:t,confirmLabel:s,cancelLabel:r,tone:o="default",busy:a=!1,onConfirm:i,onCancel:c}){const{t:d}=ve("common");l.useEffect(()=>{const m=h=>{h.key==="Escape"&&c()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[c]);const u=n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 backdrop-blur-[2px] p-4",role:"dialog","aria-modal":"true","aria-labelledby":"confirm-dialog-title",onClick:m=>{m.target===m.currentTarget&&c()},children:n.jsxs("div",{className:"w-full max-w-sm rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden",children:[n.jsxs("div",{className:"px-5 py-4",children:[n.jsx("div",{id:"confirm-dialog-title",className:"text-sm font-semibold text-text-primary",children:e}),t&&n.jsx("div",{className:"mt-1.5 text-xs text-text-secondary whitespace-pre-line break-words",children:t})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-border-subtle",children:[n.jsx("button",{type:"button",className:"btn btn-secondary h-9 px-4 text-sm",disabled:a,onClick:c,children:r??d("common.cancel")}),n.jsx("button",{type:"button",autoFocus:!0,className:`btn ${o==="danger"?"btn-danger":"btn-primary"} h-9 px-4 text-sm font-semibold`,disabled:a,onClick:i,children:s})]})]})});return Qn.createPortal(u,document.body)}function vd(e){if(!e||typeof e!="object")return;const t=e;return"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Fr(){const[e,t]=l.useState(null),s=l.useRef(null),r=l.useCallback(i=>{t(null);const c=s.current;s.current=null,c==null||c(i)},[]),o=l.useCallback(i=>new Promise(c=>{var d;(d=s.current)==null||d.call(s,!1),s.current=c,t(i)}),[]);l.useEffect(()=>()=>{var i;(i=s.current)==null||i.call(s,!1)},[]);const a=e?n.jsx(gf,{title:e.title,description:e.description,confirmLabel:e.confirmLabel,cancelLabel:e.cancelLabel,tone:e.tone,onConfirm:()=>r(!0),onCancel:()=>r(!1)}):null;return{confirm:o,confirmDialog:a}}function Gu({value:e,max:t,label:s,color:r="#8b5cf6",detail:o,compact:a=!1}){const i=t>0?Math.min(Math.round(e/t*100),100):0,c=i>85?"#ef4444":i>60?"var(--status-warning)":r;return a?n.jsxs("div",{className:"flex-1",children:[n.jsxs("div",{className:"flex justify-between mb-0.5",children:[n.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide font-semibold",children:s}),n.jsxs("span",{className:"text-3xs text-text-secondary font-semibold",children:[i,"%"]})]}),n.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:n.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${i}%`,background:c}})})]}):n.jsxs("div",{className:"flex-1",children:[n.jsxs("div",{className:"flex justify-between mb-1.5",children:[n.jsx("span",{className:"text-2xs text-text-secondary font-medium",children:s}),n.jsxs("span",{className:"text-xxs text-text-primary font-bold",children:[i,"%"]})]}),n.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:n.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${i}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),o&&n.jsx("div",{className:"text-3xs text-text-muted mt-0.5",children:o})]})}function w0({cursorPos:e,viewportRef:t,imgRef:s}){var j;if(!e||!s.current)return null;const r=s.current,o=r.getBoundingClientRect(),a=(j=t.current)==null?void 0:j.getBoundingClientRect();if(!a)return null;const i=r.naturalWidth||o.width,c=r.naturalHeight||o.height,d=i/c,u=o.width/o.height;let m,h,p,g;d>u?(m=o.width,h=o.width/d,p=0,g=(o.height-h)/2):(h=o.height,m=o.height*d,p=(o.width-m)/2,g=0);const f=o.left-a.left+p+m*e.nx,x=o.top-a.top+g+h*e.ny,b=Math.max(8,Math.min(a.width-8,f)),k=Math.max(8,Math.min(a.height-8,x));return n.jsxs("div",{style:{position:"absolute",left:b-8,top:k-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[n.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),n.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),n.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function ll(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function S0({inputMode:e,onToggleInputMode:t,isImeOpen:s,setIsImeOpen:r,isMenuOpen:o,setIsMenuOpen:a,imeText:i,setImeText:c,handleImeSubmit:d,isConnActive:u,zoom:m,isMobile:h,mobileFillZoom:p,onZoomOut:g,onZoomReset:f,onZoomIn:x,transportType:b,screenshotUsage:k,lastActionStatus:j}){const{t:v}=ve("common");return n.jsxs(n.Fragment,{children:[n.jsxs("div",{onTouchStart:_=>_.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[n.jsxs("div",{role:"button",tabIndex:0,onClick:t,onKeyDown:ll(t),className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[n.jsx("span",{className:"text-sm",children:e==="mouse"?n.jsx(sf,{size:14}):n.jsx(_w,{size:14})}),n.jsx("span",{className:`text-3xs font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:v(e==="mouse"?"remote.mouse":"remote.touch")})]}),n.jsxs("div",{className:"relative",children:[n.jsx("div",{role:"button",tabIndex:0,onClick:()=>{r(_=>!_),a(!1)},onKeyDown:ll(()=>{r(_=>!_),a(!1)}),className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${s?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:n.jsx("span",{className:"text-sm",children:n.jsx(tf,{size:14})})}),s&&n.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:n.jsx("input",{type:"text",placeholder:v("remote.typeAndEnter"),value:i,autoFocus:!0,onTouchStart:_=>_.stopPropagation(),onChange:_=>c(_.target.value),onKeyDown:_=>{d(_)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-xxs outline-none"})})]}),n.jsx("div",{className:"relative",children:n.jsx("div",{role:"button",tabIndex:0,onClick:()=>{a(_=>!_),r(!1)},onKeyDown:ll(()=>{a(_=>!_),r(!1)}),className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${o?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:n.jsx("span",{className:"text-sm",children:n.jsx(Or,{size:14})})})}),n.jsx("div",{className:"w-px h-[18px] bg-white/10"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:u?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[n.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:u?"#22c55e":"#eab308",boxShadow:u?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),n.jsx("span",{className:"text-5xs font-extrabold",style:{color:u?"#22c55e":"#eab308"},children:v(u?"remote.connected":"remote.ws")})]}),m>1&&n.jsxs("span",{className:"text-5xs font-bold text-indigo-400",children:[Math.round(m*100),"%"]}),b==="direct"&&n.jsx("span",{className:"text-5xs font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:v("remote.directP2PTitle"),children:v("remote.direct")}),b==="relay"&&n.jsx("span",{className:"text-5xs font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:v("remote.turnRelayTitle"),children:v("remote.relay")}),k&&k.dailyBudgetMinutes>0&&n.jsx("span",{className:"text-5xs font-bold px-1 py-0.5 rounded",style:{color:k.budgetExhausted?"#ef4444":"#c4b5fd",background:k.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:v("remote.dailyTurnTitle"),children:k.budgetExhausted?v("remote.turnBlocked"):v("remote.turnUsage",{used:k.dailyUsedMinutes,budget:k.dailyBudgetMinutes})}),j&&n.jsx("span",{className:"text-5xs text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:j})]})]}),o&&n.jsxs("div",{onTouchStart:_=>_.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[n.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:v("remote.settings")}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[n.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:[v("remote.zoom")," ",m<=(h?p:1)+.01?v(h?"remote.fill":"remote.fit"):`${Math.round(m*100)}%`]}),n.jsxs("div",{style:{display:"flex",gap:4},children:[n.jsx("button",{onClick:_=>{_.stopPropagation(),g()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),n.jsx("button",{onClick:_=>{_.stopPropagation(),f()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:v(h?"remote.fill":"remote.fit")}),n.jsx("button",{onClick:_=>{_.stopPropagation(),x()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function k0({waitingLabel:e,waitingHint:t,transportType:s}){const{t:r}=ve("common");return n.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[n.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:n.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),n.jsx("div",{className:"text-white/85 text-xxs font-semibold tracking-wide",children:e}),n.jsx("div",{className:"text-2xs text-white/40",children:t}),s==="relay"&&n.jsx("div",{className:"text-3xs font-medium",style:{color:"var(--status-warning)",opacity:.8},children:r("remote.waitingState.turnRelayActive")})]})}function j0({connState:e,onRetry:t}){const{t:s}=ve("common"),r=e==="failed"?"remote.error.reasonFailed":"remote.error.reasonDisconnected";return n.jsxs("div",{"data-testid":"remote-error-state",className:"text-center flex flex-col items-center gap-3 px-6",children:[n.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-red-500/25 bg-red-500/10 shadow-[0_10px_30px_rgba(0,0,0,0.35)]",children:n.jsx(an,{size:22,className:"text-red-400"})}),n.jsx("div",{className:"text-white/90 text-[13px] leading-[1.45] font-semibold tracking-wide",children:s("remote.error.title")}),n.jsx("div",{className:"text-2xs text-white/50 max-w-[260px]",children:s(r)}),t&&n.jsxs("button",{type:"button",onClick:t,className:"mt-1 h-8 px-3.5 rounded-lg flex items-center gap-1.5 bg-white/[0.08] border border-white/15 text-white/90 text-2xs font-bold hover:bg-white/[0.14] transition-colors",children:[n.jsx($r,{size:13}),s("remote.error.retry")]})]})}function N0(){if(typeof window>"u")return!1;try{return window.__ADHDEV_DEBUG_RENDERS__===!0||window.localStorage.getItem("adhdev_debug_renders")==="1"}catch{return window.__ADHDEV_DEBUG_RENDERS__===!0}}function Vu(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function Oo(e,t){const s=l.useRef(null),r=l.useRef(0);l.useEffect(()=>{if(!N0())return;r.current+=1;const o=s.current;if(!o){console.debug(`[render-trace] ${e}#${r.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,c])=>[i,Vu(c)]))}),s.current=t;return}const a=Object.keys({...o,...t}).filter(i=>!Object.is(o[i],t[i]));a.length>0&&console.debug(`[render-trace] ${e}#${r.current}`,{changed:a,snapshot:Object.fromEntries(a.map(i=>[i,Vu(t[i])]))}),s.current=t})}function C0({containerRef:e,viewportRef:t,imgRef:s,inputMode:r,setInputMode:o,minZoom:a,zoomRef:i,panXRef:c,panYRef:d,setPanX:u,setPanY:m,setZoom:h,lastWheelTimeRef:p,onAction:g,setLastActionStatus:f,spawnRippleFromNormalized:x,clampPan:b,isMobile:k,mobileFillZoom:j}){const[v,_]=l.useState(null),y=l.useRef(null),w=l.useRef(null),S=l.useRef(null),C=l.useRef(!1),A=l.useRef(null),O=l.useRef(0),L=l.useRef(null),M=l.useRef(1),$=l.useRef({x:0,y:0}),N=l.useRef(!1),I=l.useRef(r),B=l.useRef(g),T=30,F=550,q=18,Q=60,K=400,R=12,D=()=>{if(y.current)return;const W={nx:.5,ny:.5};y.current=W,_(W)};return l.useEffect(()=>{I.current=r,r==="mouse"&&D()},[r]),l.useEffect(()=>{B.current=g},[g]),l.useEffect(()=>{const W=e.current;if(!W)return;const U=de=>{if(!s.current)return null;const ne=s.current.getBoundingClientRect();return!ne.width||!ne.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-ne.left)/ne.width)),ny:Math.max(0,Math.min(1,(de.clientY-ne.top)/ne.height))}},ae=(de,ne)=>{if(!s.current)return{dnx:0,dny:0};const ee=s.current,ue=ee.getBoundingClientRect(),je=ee.naturalWidth||ue.width,X=ee.naturalHeight||ue.height,G=je/X,z=ue.width/ue.height;let ie,Ne;return G>z?(ie=ue.width,Ne=ue.width/G):(Ne=ue.height,ie=ue.height*G),{dnx:de/ie,dny:ne/Ne}},be=(de,ne,ee)=>{if(ee<=1.05)return;const ue=-(de-.5)*100,je=-(ne-.5)*100,X=b(ue,je,ee);(Math.abs(X.x-c.current)>.1||Math.abs(X.y-d.current)>.1)&&(u(X.x),m(X.y),c.current=X.x,d.current=X.y)},V=de=>{const ne=t.current;if(ne&&de.target instanceof Node&&ne.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const ee=de.touches[0];w.current={x:ee.clientX,y:ee.clientY,time:Date.now()},S.current={x:ee.clientX,y:ee.clientY},N.current||(C.current=!1),A.current=setTimeout(()=>{if(!C.current&&!N.current)if(C.current=!0,I.current==="mouse"){const ue=y.current||{nx:.5,ny:.5};f("Right Click"),x(ue.nx,ue.ny,"right"),B.current("input_click",{...ue,button:"right"}).catch(()=>{})}else{const ue=U(ee);ue&&(f("Right Click"),x(ue.nx,ue.ny,"right"),B.current("input_click",{...ue,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){A.current&&clearTimeout(A.current),C.current=!0,N.current=!0;const ee=de.touches[1].clientX-de.touches[0].clientX,ue=de.touches[1].clientY-de.touches[0].clientY;L.current=Math.sqrt(ee*ee+ue*ue),M.current=i.current,$.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},we=de=>{const ne=t.current;if(ne&&de.target instanceof Node&&ne.contains(de.target)&&de.preventDefault(),de.touches.length===1&&S.current){const ee=de.touches[0],ue=ee.clientX-S.current.x,je=ee.clientY-S.current.y;if(!C.current&&w.current){const X=ee.clientX-w.current.x,G=ee.clientY-w.current.y;Math.sqrt(X*X+G*G)>8&&(C.current=!0,A.current&&clearTimeout(A.current))}if(C.current)if(I.current==="mouse"){const X=ae(ue,je),G=y.current||{nx:.5,ny:.5},z=Math.max(0,Math.min(1,G.nx+X.dnx)),ie=Math.max(0,Math.min(1,G.ny+X.dny));y.current={nx:z,ny:ie},_({nx:z,ny:ie}),f(`Cursor: ${Math.round(z*100)}%, ${Math.round(ie*100)}%`),be(z,ie,i.current);const Ne=Date.now();Ne-p.current>=30&&(p.current=Ne,B.current("input_mouseMoved",{nx:z,ny:ie}).catch(()=>{}))}else if(i.current>1){const X=t.current;if(X){const G=X.clientWidth,z=X.clientHeight,ie=c.current+ue/G*100,Ne=d.current+je/z*100,Be=b(ie,Ne,i.current);u(Be.x),m(Be.y),c.current=Be.x,d.current=Be.y}}else{const X=U(ee);if(X){const G=Date.now();G-p.current>=40&&(p.current=G,f("Scroll"),B.current("input_wheel",{nx:X.nx,ny:X.ny,deltaX:Math.round(-ue*2.5),deltaY:Math.round(-je*2.5)}).catch(()=>{}))}}S.current={x:ee.clientX,y:ee.clientY};return}if(de.touches.length===2&&L.current!==null){const ee=de.touches[1].clientX-de.touches[0].clientX,ue=de.touches[1].clientY-de.touches[0].clientY,X=Math.sqrt(ee*ee+ue*ue)/L.current,G=(de.touches[0].clientX+de.touches[1].clientX)/2,z=(de.touches[0].clientY+de.touches[1].clientY)/2,ie=G-$.current.x,Ne=z-$.current.y,Be=Math.abs(X-1)>.03;if(I.current==="mouse"){if(Be){const Le=Math.max(a,Math.min(5,M.current*X));h(Le),i.current=Le}else if(Math.abs(ie)>2||Math.abs(Ne)>2){const Le=y.current||{nx:.5,ny:.5},Je=Date.now();Je-p.current>=30&&(p.current=Je,f("Scroll"),B.current("input_wheel",{nx:Le.nx,ny:Le.ny,deltaX:Math.round(-ie*3),deltaY:Math.round(-Ne*3)}).catch(()=>{}))}}else{const Le=Math.max(a,Math.min(5,M.current*X));h(Le),i.current=Le;const Je=t.current;if(Je&&Le>1){const Se=Je.clientWidth,he=Je.clientHeight,pe=c.current+ie/Se*100,Ee=d.current+Ne/he*100,Y=b(pe,Ee,Le);u(Y.x),m(Y.y),c.current=Y.x,d.current=Y.y}}$.current={x:G,y:z}}},ce=de=>{var ne;if(A.current&&clearTimeout(A.current),L.current=null,de.touches.length===1&&N.current){const ee=de.touches[0];w.current={x:ee.clientX,y:ee.clientY,time:Date.now()},S.current={x:ee.clientX,y:ee.clientY},C.current=!0;return}if(de.touches.length===0){if(N.current){N.current=!1,C.current=!1;return}if(de.changedTouches.length===1){const ee=de.changedTouches[0],ue=Date.now(),je=ue-(((ne=w.current)==null?void 0:ne.time)||0),X=w.current?ee.clientX-w.current.x:0,G=w.current?ee.clientY-w.current.y:0,z=Math.sqrt(X*X+G*G);if(I.current==="mouse"){if(je<T||je>F||z>q){C.current=!1;return}const ie=y.current||U(ee);ie&&(f(`Click: ${Math.round(ie.nx*100)}%, ${Math.round(ie.ny*100)}%`),x(ie.nx,ie.ny,"left"),B.current("input_click",{...ie}).catch(()=>{}))}else{if(C.current){C.current=!1;return}if(je<Q||je>K||z>R){C.current=!1;return}const ie=U(ee);if(!ie)return;ue-O.current<300?(f("Double tap"),x(ie.nx,ie.ny,"double"),B.current("input_click",{...ie,clickCount:2}).catch(()=>{}),O.current=0):(f(`Tap: ${Math.round(ie.nx*100)}%, ${Math.round(ie.ny*100)}%`),x(ie.nx,ie.ny,"left"),B.current("input_click",{...ie}).catch(()=>{}),O.current=ue)}}C.current=!1}};return W.addEventListener("touchstart",V,{passive:!1}),W.addEventListener("touchmove",we,{passive:!1}),W.addEventListener("touchend",ce,{passive:!1}),()=>{W.removeEventListener("touchstart",V),W.removeEventListener("touchmove",we),W.removeEventListener("touchend",ce),A.current&&clearTimeout(A.current)}},[e,t,s,a,i,c,d,u,m,h,p,f,x,b]),{cursorPos:v,cursorPosRef:y,handleToggleInputMode:()=>{o(W=>{const U=W==="touch"?"mouse":"touch";return U==="mouse"&&D(),U})},handleZoomReset:()=>{const W=k?j:1;h(W),i.current=W,u(0),m(0),c.current=0,d.current=0}}}const _0=15e3;function bf({onAction:e,addLog:t,connState:s,connScreenshot:r,screenshotUsage:o,transportType:a,onRetry:i}){const{t:c}=ve("common"),d=l.useRef(null),u=l.useRef(null),m=l.useRef(null),[h,p]=l.useState(null),[g,f]=l.useState(""),[,x]=l.useState(!1),[b,k]=l.useState(!1),[j,v]=l.useState(!1),[_,y]=l.useState([]),w=l.useRef(0),S=l.useRef(new Set),[C,A]=l.useState(!1),[O,L]=l.useState(!1),M=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[$,N]=l.useState(M?"mouse":"touch"),[I,B]=l.useState(1),T=l.useRef(!1),[F,q]=l.useState(1),[Q,K]=l.useState(0),[R,D]=l.useState(0);Oo("RemoteView",{connState:s,hasScreenshot:!!r,inputMode:$,zoom:F,panX:Q,panY:R,isMenuOpen:C,isImeOpen:O});const P=l.useRef(0),H=l.useRef(F),W=l.useRef(Q),U=l.useRef(R);l.useEffect(()=>{H.current=F},[F]),l.useEffect(()=>{W.current=Q},[Q]),l.useEffect(()=>{U.current=R},[R]),l.useEffect(()=>{var Se;(Se=d.current)==null||Se.focus()},[]),l.useEffect(()=>{s!=="connected"&&k(!1)},[s]),l.useEffect(()=>{if(s==="connected"){v(!1);return}v(!1);const Se=setTimeout(()=>v(!0),_0);return()=>clearTimeout(Se)},[s]);const ae=s==="connected",be=r,V=s==="failed"||s==="disconnected"&&j,we=c(ae?"remote.waiting.connectedLabel":s==="connecting"?"remote.waiting.connectingLabel":"remote.waiting.reconnectingLabel"),ce=c(ae?"remote.waiting.connectedHint":"remote.waiting.reconnectingHint");l.useEffect(()=>{if(!M||T.current||!be)return;const Se=m.current,he=u.current;if(!Se||!he)return;const pe=()=>{const Ee=he.clientWidth,Y=he.clientHeight,me=Se.naturalWidth,fe=Se.naturalHeight;if(!me||!fe||!Ee||!Y)return;const E=Math.min(Ee/me,Y/fe),Ie=Math.max(Ee/me,Y/fe)/E;Ie>1.01&&(B(Ie),q(Ie),H.current=Ie),T.current=!0};if(Se.complete&&Se.naturalWidth){pe();return}return Se.addEventListener("load",pe,{once:!0}),()=>Se.removeEventListener("load",pe)},[be,M]);const de=.5;l.useEffect(()=>{F<=de&&(K(0),D(0))},[F,de]);const ne=(Se,he,pe)=>{if(pe<=de)return{x:0,y:0};const Ee=(pe-1)/(2*pe)*100,Y=(pe-1)/(2*pe)*100;return{x:Math.max(-Ee,Math.min(Ee,Se)),y:Math.max(-Y,Math.min(Y,he))}},ee=(Se,he)=>{if(!m.current)return null;const pe=m.current.getBoundingClientRect();return!pe.width||!pe.height?null:{nx:Math.max(0,Math.min(1,(Se-pe.left)/pe.width)),ny:Math.max(0,Math.min(1,(he-pe.top)/pe.height))}},ue=Se=>{const he=setTimeout(()=>{S.current.delete(he),y(pe=>pe.filter(Ee=>Ee.id!==Se))},600);S.current.add(he)};l.useEffect(()=>{const Se=S.current;return()=>{for(const he of Se)clearTimeout(he);Se.clear()}},[]);const je=(Se,he,pe)=>{const Ee=u.current;if(!Ee)return;const Y=Ee.getBoundingClientRect(),me=++w.current;y(fe=>[...fe,{id:me,x:Se-Y.left,y:he-Y.top,type:pe}]),ue(me)},X=(Se,he,pe)=>{const Ee=m.current,Y=u.current;if(!Ee||!Y)return;const me=Ee.getBoundingClientRect(),fe=Y.getBoundingClientRect(),E=Ee.naturalWidth||me.width,oe=Ee.naturalHeight||me.height,Ie=E/oe,Z=me.width/me.height;let se,ye,$e,Me;Ie>Z?(se=me.width,ye=me.width/Ie,$e=0,Me=(me.height-ye)/2):(ye=me.height,se=me.height*Ie,$e=(me.width-se)/2,Me=0);const De=me.left-fe.left+$e+se*Se,Te=me.top-fe.top+Me+ye*he,He=++w.current;y(tt=>[...tt,{id:He,x:De,y:Te,type:pe}]),ue(He)},G=async Se=>{var pe;const he=ee(Se.clientX,Se.clientY);if(he){p(`Click: ${Math.round(he.nx*100)}%, ${Math.round(he.ny*100)}%`),(pe=d.current)==null||pe.focus(),k(!0);try{const Ee=await e("input_click",{nx:he.nx,ny:he.ny});if(!(Ee!=null&&Ee.success)){t(`❌ Click failed: ${Ee==null?void 0:Ee.error}`);return}je(Se.clientX,Se.clientY,"left")}catch(Ee){t(`❌ Click error: ${Ee.message||Ee}`)}}},z=async(Se,he,pe,Ee=0)=>{try{await e("input_key",{type:pe?"char":"keyDown",key:Se,code:he,text:pe?Se:void 0,unmodifiedText:pe?Se:void 0,modifiers:Ee})}catch(Y){t(`❌ Key error: ${Y.message||Y}`)}},ie=async Se=>{if(Se.target.tagName==="INPUT"||!b||Se.key==="Escape")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter"].includes(Se.key)&&Se.preventDefault();let pe=0;Se.altKey&&(pe|=1),Se.ctrlKey&&(pe|=2),Se.metaKey&&(pe|=4),Se.shiftKey&&(pe|=8),p(`Key: ${Se.key}`),await z(Se.key,Se.code,Se.key.length===1,pe)},Ne=async Se=>{if(Se.key==="Enter"){if(Se.nativeEvent.isComposing)return;if(g){const he=g;f(""),p(`IME Sent: ${he}`);try{const pe=await e("input_type",{text:he});pe!=null&&pe.success||t(`❌ IME error: ${pe==null?void 0:pe.error}`)}catch(pe){t(`❌ IME error: ${pe.message}`)}}else p("Key: Enter"),await z("Enter","Enter",!1)}};l.useEffect(()=>{const Se=d.current;if(!Se)return;const he=pe=>{var Ee;if((Ee=m.current)!=null&&Ee.contains(pe.target)){pe.preventDefault();const Y=Date.now();if(Y-P.current<40)return;P.current=Y;const me=ee(pe.clientX,pe.clientY);if(!me)return;p(`Scroll: ${Math.round(pe.deltaY)}`),e("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(pe.deltaX),deltaY:Math.round(pe.deltaY)}).catch(()=>{})}};return Se.addEventListener("wheel",he,{passive:!1}),()=>Se.removeEventListener("wheel",he)},[e]);const{cursorPos:Be,handleToggleInputMode:Le,handleZoomReset:Je}=C0({containerRef:d,viewportRef:u,imgRef:m,inputMode:$,setInputMode:N,minZoom:de,zoomRef:H,panXRef:W,panYRef:U,setPanX:K,setPanY:D,setZoom:q,lastWheelTimeRef:P,onAction:e,setLastActionStatus:p,spawnRippleFromNormalized:X,clampPan:ne,isMobile:M,mobileFillZoom:I});return n.jsxs("div",{ref:d,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ie,onContextMenu:Se=>Se.preventDefault(),onFocus:()=>x(!0),onBlur:()=>x(!1),tabIndex:0,children:[n.jsxs("div",{ref:u,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[V?n.jsx(j0,{connState:s,onRetry:i}):be?n.jsx("img",{ref:m,src:be,alt:c("remote.screenshotAlt"),style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${F}) translate(${Q}%, ${R}%)`,transformOrigin:"center center",cursor:$==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:G,onContextMenu:Se=>Se.preventDefault(),onDragStart:Se=>Se.preventDefault()}):n.jsx(k0,{waitingLabel:we,waitingHint:ce,transportType:a}),$==="mouse"&&!V&&be&&n.jsx(w0,{cursorPos:Be,viewportRef:u,imgRef:m}),_.map(Se=>{const pe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[Se.type];return n.jsxs("div",{style:{position:"absolute",left:Se.x,top:Se.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${pe}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),n.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${pe}, 0.9)`,boxShadow:`0 0 12px rgba(${pe}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},Se.id)})]}),n.jsx(S0,{inputMode:$,onToggleInputMode:Le,isImeOpen:O,setIsImeOpen:L,isMenuOpen:C,setIsMenuOpen:A,imeText:g,setImeText:f,handleImeSubmit:Ne,isConnActive:ae,zoom:F,isMobile:M,mobileFillZoom:I,onZoomOut:()=>q(Se=>Math.max(.5,Se-.25)),onZoomReset:Je,onZoomIn:()=>q(Se=>Math.min(5,Se+.25)),transportType:a,screenshotUsage:o,lastActionStatus:h}),n.jsx("style",{children:`
|
|
9
|
+
@keyframes slideUp {
|
|
10
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
11
|
+
to { opacity: 1; transform: translateY(0); }
|
|
12
|
+
}
|
|
13
|
+
@keyframes slideUpSidebar {
|
|
14
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
15
|
+
to { opacity: 1; transform: translateY(0); }
|
|
16
|
+
}
|
|
17
|
+
@keyframes click-ripple-ring {
|
|
18
|
+
0% { transform: scale(0.3); opacity: 1; }
|
|
19
|
+
100% { transform: scale(2.2); opacity: 0; }
|
|
20
|
+
}
|
|
21
|
+
@keyframes click-ripple-dot {
|
|
22
|
+
0% { transform: scale(1); opacity: 0.9; }
|
|
23
|
+
50% { transform: scale(1.8); opacity: 0.6; }
|
|
24
|
+
100% { transform: scale(0.5); opacity: 0; }
|
|
25
|
+
}
|
|
26
|
+
@keyframes remote-float {
|
|
27
|
+
0% { transform: translateY(0px); }
|
|
28
|
+
50% { transform: translateY(-7px); }
|
|
29
|
+
100% { transform: translateY(0px); }
|
|
30
|
+
}
|
|
31
|
+
`})]})}function hc(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.promptId!="string"||!t.promptId.trim()||typeof t.providerType!="string"||!t.providerType.trim()||!Array.isArray(t.questions)||t.questions.length===0?null:t}function A0(e){var t;return hc(e.activeInteractivePrompt)||hc((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function T0(e){return e.sessionId||e.instanceId||e.id}function I0(e,t){let s;t==null?s={}:typeof t=="string"?s={sessionId:t,includeHidden:!!t.trim()}:s=t;const r=typeof s.sessionId=="string"?s.sessionId.trim():"",o=s.includeHidden===!0;for(const a of e){const i=A0(a);if(!i)continue;const c=T0(a);if(r&&r!==c&&r!==a.id||!o&&a.surfaceHidden===!0)continue;return{daemonId:a.daemonId||a.id.split(":")[0]||a.id,sessionId:c,routeId:a.id,providerType:a.type,title:a.title||a.cliName||a.type,prompt:i}}return null}function xf(e,t){var r;const s={};for(const o of e.questions){const a=t[o.questionId]||{},i=Array.from(new Set((a.selectedLabels||[]).map(d=>d.trim()).filter(Boolean))),c=(r=a.freeformText)==null?void 0:r.trim();s[o.questionId]={selectedLabels:i,...c?{freeformText:c}:{}}}return{promptId:e.promptId,answers:s}}function es({children:e}){return typeof document>"u"?n.jsx(n.Fragment,{children:e}):Qn.createPortal(e,document.body)}function M0(e,t){const s=r=>{r.key==="Escape"&&(r.stopPropagation(),t())};return e.addEventListener("keydown",s,!0),()=>e.removeEventListener("keydown",s,!0)}const Yu='a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',R0=200;function Qu(e){const t={};for(const s of(e==null?void 0:e.prompt.questions)||[])t[s.questionId]={selectedLabels:[],freeformText:""};return t}function Ju(e,t){var s,r;return!!((s=t==null?void 0:t.freeformText)!=null&&s.trim())||(((r=t==null?void 0:t.selectedLabels)==null?void 0:r.length)||0)>0||e.options.length===0&&!!e.allowFreeform}function P0({label:e,description:t,selected:s,multiSelect:r,disabled:o,onClick:a}){return n.jsx("button",{type:"button",disabled:o,role:r?"checkbox":"radio","aria-checked":s,onClick:a,className:`w-full text-left rounded-md border px-3 py-2 transition ${s?"border-accent-primary bg-accent-primary/15 text-text-primary":"border-border-default bg-surface-secondary text-text-secondary hover:bg-surface-secondary hover:text-text-primary"} ${o?"cursor-not-allowed opacity-60":""}`,children:n.jsxs("span",{className:"flex items-start gap-2",children:[n.jsx("span",{className:`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border ${r?"rounded-sm":"rounded-full"} ${s?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-subtle"}`,children:s?r?n.jsx(vi,{size:12}):n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-accent-on-primary"}):null}),n.jsxs("span",{className:"min-w-0",children:[n.jsx("span",{className:"block text-sm font-semibold leading-5",children:e}),t&&n.jsx("span",{className:"mt-0.5 line-clamp-3 block text-xs leading-5 text-text-muted",children:t})]})]})})}function wd({promptSession:e,isSubmitting:t=!1,error:s,onSubmit:r,onCancel:o}){const{t:a}=ve("common"),[i,c]=l.useState(()=>Qu(e)),[d,u]=l.useState(!1),m=l.useRef(!1),h=l.useRef(null),p="interactive-prompt-title";l.useEffect(()=>{if(c(Qu(e)),u(!1),m.current=!1,!(e==null?void 0:e.prompt.promptId))return;const A=setTimeout(()=>{m.current=!0,u(!0)},R0);return()=>clearTimeout(A)},[e==null?void 0:e.prompt.promptId]),l.useEffect(()=>{if(e)return M0(window,o)},[e,o]);const g=e==null?void 0:e.prompt.promptId,f=e==null?void 0:e.sessionId,x=e==null?void 0:e.daemonId;l.useEffect(()=>{if(!g)return;const C=h.current;if(!C)return;const A=()=>Array.from(C.querySelectorAll(Yu)),O=L=>{if(L.key!=="Tab")return;const M=A();if(M.length===0)return;const $=M[0],N=M[M.length-1],I=document.activeElement;L.shiftKey?(I===$||!C.contains(I))&&(L.preventDefault(),N.focus()):(I===N||!C.contains(I))&&(L.preventDefault(),$.focus())};return C.addEventListener("keydown",O),()=>C.removeEventListener("keydown",O)},[g,f,x]),l.useEffect(()=>{if(!g)return;const C=h.current;if(!C)return;const A=document.activeElement;if(A instanceof Node&&C.contains(A))return;(Array.from(C.querySelectorAll(Yu))[0]||C).focus()},[g,f,x]);const b=(e==null?void 0:e.prompt.questions)||[],k=b.length===1,j=l.useMemo(()=>e?e.prompt.questions.every(C=>Ju(C,i[C.questionId])):!1,[e,i]),v=l.useMemo(()=>b.filter(C=>!Ju(C,i[C.questionId])).length,[b,i]);if(!e)return null;const _=(C,A)=>{c(O=>{const L=O[C.questionId]||{selectedLabels:[]},M=L.selectedLabels||[],$=C.multiSelect?M.includes(A)?M.filter(N=>N!==A):[...M,A]:[A];return{...O,[C.questionId]:{...L,selectedLabels:$}}})},y=(C,A)=>{c(O=>({...O,[C]:{...O[C]||{selectedLabels:[]},freeformText:A}}))},w=()=>{!j||t||!m.current||r(i)},S=xf(e.prompt,i);return n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50 px-4 pt-[calc(24px+env(safe-area-inset-top,0px))] pb-[calc(24px+env(safe-area-inset-bottom,0px))]",children:n.jsxs("div",{ref:h,role:"dialog","aria-modal":"true","aria-labelledby":p,tabIndex:-1,className:"flex max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-48px)] w-full max-w-2xl flex-col overflow-hidden rounded-lg border border-border-default bg-surface-primary shadow-2xl outline-none",children:[n.jsxs("div",{className:"flex shrink-0 items-start justify-between gap-4 border-b border-border-default px-5 py-4",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-normal text-status-warning",children:[n.jsx(an,{size:15})," ",a("interactivePrompt.actionRequired")]}),n.jsx("h2",{id:p,className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("button",{type:"button",onClick:o,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":a("interactivePrompt.cancelAria"),children:n.jsx(Bt,{size:16})})})]}),n.jsxs("div",{className:"interactive-prompt-question-list min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-4",children:[b.map((C,A)=>{var M,$;const O=((M=S.answers[C.questionId])==null?void 0:M.selectedLabels)||[],L=C.multiSelect?a("interactivePrompt.multipleChoice"):a("interactivePrompt.singleChoice");return n.jsxs("section",{className:A>0?"space-y-3 border-t border-border-default pt-5":"space-y-3",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[C.header&&n.jsx("span",{className:"text-xs font-semibold uppercase tracking-normal text-text-muted",children:C.header}),n.jsx("span",{className:"rounded-full border border-border-subtle px-2 py-0.5 text-3xs font-semibold uppercase tracking-normal text-text-muted",children:L})]}),n.jsxs("div",{className:"mt-1 text-sm font-semibold text-text-primary",children:[k?"":`${A+1}. `,C.question]}),C.multiSelect&&C.options.length>0&&n.jsx("div",{className:"mt-0.5 text-xs text-text-muted",children:a("interactivePrompt.selectAllThatApply")})]}),n.jsx("div",{className:"grid gap-2",role:C.multiSelect?"group":"radiogroup","aria-label":C.question,children:C.options.map(N=>n.jsx(P0,{label:N.label,description:N.description||N.preview,selected:O.includes(N.label),multiSelect:C.multiSelect,disabled:t,onClick:()=>_(C,N.label)},N.label))}),C.allowFreeform&&n.jsxs("label",{className:"block",children:[n.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:a("interactivePrompt.other")}),n.jsx("textarea",{value:(($=i[C.questionId])==null?void 0:$.freeformText)||"",disabled:t,onChange:N=>y(C.questionId,N.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-default bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]},C.questionId)}),s&&n.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:s})]}),n.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border-default px-5 pt-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))]",children:[!j&&v>0&&n.jsx("span",{className:"mr-auto text-xs text-text-muted",children:a("interactivePrompt.answersRequired",{count:v})}),n.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:o,disabled:t,children:a("common.cancel")}),n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:w,disabled:!j||t||!d,children:a(t?"interactivePrompt.submitting":"interactivePrompt.submit")})]})]})})})}function dn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var yf=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress","monitor:long_generating"];dn(yf);var L0=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];dn(L0);var E0=["p2p_offer","p2p_ice"];dn(E0);var D0=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];dn(D0);var O0=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","beacon_vectors","daemon_mesh_command","p2p_offer","p2p_ice"];dn(O0);var $0=["auth_ok","auth_error","machine_evicted","force_disconnect","token_revoked","version_mismatch","force_update_required","command","agent_command","resolve_action","beacon_vectors_result","daemon_mesh_result","p2p_ready","p2p_offer","p2p_answer","p2p_ice","mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];dn($0);var F0=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],H0=[...yf,...F0];dn(H0);var B0=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];dn(B0);var W0=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];dn(W0);var U0=["p2p_ready","p2p_answer","p2p_ice"];dn(U0);var K0=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];dn(K0);var q0=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];dn(q0);var vf=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];dn(vf);var wf=["ping","pong","p2p_evicted","status_report","status_event","topic_update","topic_update_chunk","session_output","session_output_chunk","session_io_error","command_result","command_result_chunk","response"];dn(wf);[...new Set([...vf,...wf])];var Sf=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"],z0={running:"generating",streaming:"generating",busy:"generating",working:"generating",loading:"generating",loading_reference:"generating",thinking:"generating",active:"generating",no_progress:"generating",long_generating:"generating",initializing:"starting",waiting:"waiting_approval"},G0=new Set(Sf);function V0(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return G0.has(t)?t:z0[t]??null}var Y0=["pending","assigned","completed","failed","cancelled"],Q0=["completed","failed","cancelled"],J0=["code_change","validation","live_debug_readonly","launch_app","convergence"],X0=["low","normal","high"],Z0=["low","medium","high"],eS=["when_idle","interrupt"],tS=["preserve","stop","delete_stopped","stop_and_delete"],kf=["completed","blocked","failed"],jf=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function cs(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}cs(Y0);cs(Q0);cs(J0);cs(X0);cs(Z0);cs(eS);cs(tS);cs(kf);cs(jf);var nS=["not_ready","send_in_flight","not_generating","not_supported","platform_unsupported","modal_parked","interrupt_not_implemented","interrupt_refused","idle_timeout","session_exited","unsupported_input","no_target","bootstrap_pending","duplicate_dispatch","internal_error"],sS=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(sS);var rS=["fsm_edge","short_gen_inline","completion_flush_genuine","completion_flush_weak","monitor_final_summary","pre_cleanup_transcript","stall_transcript","startup_grace_collapse","acp_prompt_response","cdp_state","approval_gate","modal_button","mesh_stall_watchdog","status_monitor","pty_exit","provider_error","coordinator_probe","mcp_probe","worker_tool","dispatch","input_service","operator","intentional_cleanup","scheduler","git_probe","session_registry"],oS=["mesh_queue","mesh_direct","plain"],aS=["delivered","queued"],iS=["local","p2p"],lS=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],cS=["default","native_source"],dS=["restart","live_holder"],uS=["approval","choice"],mS=["approved","rejected","answered"],hS=["modal_button","auto_approve","prompt_answer"],pS=["genuine","weak"],fS=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],gS=["completed","aborted"],bS=["alive","unknown","read_failed","dead"],xS=["auth_failed","billing_failed"],yS=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],vS=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],wS=["completed","failed"],SS=["operator_update","refine_terminal","validation_terminal"],kS=["delivered","queued","duplicate"],jS=[...Sf,"unknown"],Nf=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],NS=["completed","failed","cancelled"],CS=["genuine","weak","tool_report","operator"],_S=["turn_end","weak_end_confirmed","transcript_final","worker_reported","finalization_timeout_no_response","session_error","provider_auth_failed","provider_billing_failed","operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded","operator_update","refine_terminal","validation_terminal","hard_ceiling","reclaim_budget_exhausted","hollow_max_retries","migration_orphan","dispatch_refused_session_exited","dispatch_refused_no_target","dispatch_refused_unsupported_input","dispatch_failed","session_exit","session_exit_before_turn","session_dead","hollow_completion","assigned_stranded_dispatch_unconfirmed","delivered_not_consumed_redrive","delivered_no_turn_deadline"],Cf=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],lr={t:"id"},cr={t:"id",optional:!0},fs={t:"bool"},na={t:"bool",optional:!0},Xu={t:"ms"},AS={t:"ms",optional:!0},sa={t:"int",optional:!0},Ft=e=>({t:"enum",values:e}),Qr=e=>({t:"enum",values:e,optional:!0}),TS={dispatch_accepted:{scope:Ft(oS),messageId:lr,meshId:cr,nodeId:cr,providerType:cr,attemptNo:sa,dispatchNonce:sa,consumeProfile:Qr(cS),maxTaskRetries:sa,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:lr,outcome:Ft(aS),via:Ft(iS)},delivery_refused:{messageId:lr,reason:Ft(nS)},dispatch_failed:{workerAbsent:fs,reason:Ft(lS),refusalCode:cr},duplicate_dispatch_refusal:{holderSessionId:lr,holderAttemptId:cr},session_rebound:{toSessionId:lr,reason:Ft(dS)},turn_started:{retro:fs},suspension:{modal:Ft(uS),modalKey:cr},suspension_resolved:{resolution:Ft(mS),via:Ft(hS)},turn_end:{strength:Ft(pS),afterFinalizationTimeout:na,hollow:na,summary:{t:"summary_ref",optional:!0},blockReason:Qr(fS),releasedByHardCap:na,nativeOutcome:Qr(gS),live:{t:"live",optional:!0},reportExpected:na},transcript_final:{selfAttributing:fs,nativeRead:fs,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:AS},transcript_activity:{newestActivityAt:Xu},no_progress:{stalledMs:Xu,observedStatus:Ft(jS),finalAssistantPresent:fs},liveness:{result:Ft(bS)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:Qr(xS)},session_error:{reason:Ft(yS)},worker_report:{outcome:Ft(kf),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:fs,branchState:Qr(jf),touchedFileCount:sa},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:fs,commitsSinceDispatch:{t:"int"},attributable:fs},cancel:{reason:Ft(vS)},operator_status:{status:Ft(wS),reason:Ft(SS)},coordinator_ack:{notify:Ft(Cf),outcome:Ft(kS)},hold_expired:{holdId:lr,reason:Ft(Nf)}},IS=Object.keys(TS);function Ts(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Ts(rS);Ts(IS);Ts(_S);Ts(Cf);Ts(Nf);Ts(NS);Ts(CS);var MS=["turn.evidence","turn.committed","turn.notify","mesh.record"];Ts(MS);var RS=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];function Hn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Hn(RS);var PS=["applied","recorded","rejected"];Hn(PS);var LS=["taskId","deliveryId","attemptId","missionId","checkpointId","promptId","providerSessionId","targetNoteId","nodeId","sessionId","providerType","transport","attemptedSessionId","holderSessionId","reason","status","outcome","terminalKind","event","source","intentionalStopReason","retryable","rebound","forced","fallback","membershipRemoved","requestedForce","removedByRemoteDaemon","completedViaReady","intentional","weak","attempt","attemptCount","count"];new Set(LS);var ES=["completed","failed"];Hn(ES);var DS=["operator_update","refine_terminal","validation_terminal"];Hn(DS);var OS=["own","fleet"];Hn(OS);var $S=["active","paused","completed","abandoned"];Hn($S);var FS=["magi","coordinator"];Hn(FS);var HS=["provider_quirk","pattern_to_avoid","recovery_lesson"];Hn(HS);var BS=["coordinator","unknown"];Hn(BS);var WS=["gate_claimed","gate_released","gate_abandoned","node_patched"];Hn(WS);var US=["turn_observe","mesh_record","turn_cancel","operator_status","turn_query","mesh_index_query","mission_upsert","mission_query","note_upsert","note_forget","tool_call_record","ledger_query","mission_list_query","record_local","queue_query","queue_enqueue","queue_enqueue_graph","queue_cancel","queue_requeue","direct_dispatch_record","graph_audit_record","active_work_query","recovery_context_query","graph_gate_claim","graph_gate_release","graph_gate_abandon","graph_node_patch","graph_view_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];Hn(US);function KS(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function vn(e,t){return KS(t==null?void 0:t.activeModal)?"waiting_approval":V0(e)??"idle"}function pc(e){return vn(e)==="generating"}function Zu(e,t){return vn(e,t)==="waiting_approval"}function qS(e){return(e==null?void 0:e.surfaceHidden)===!0}function zS(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function or(e){const t=e.connectionState==="failed"||e.connectionState==="closed",s=e.connectionState==="connecting"||e.connectionState==="new",r=bi(e.status),o=vn(e.status),a=o==="waiting_approval",i=o==="waiting_choice",c=Oy(o);return{isReconnecting:t,isConnecting:s,isGenerating:r,isWaiting:a,isWaitingChoice:i,isErrored:c}}function er(e){return or(e).isGenerating}function GS(e){let t=0;for(const s of e)er(s)&&t++;return t}function em(e){let t=0;return e.unread!==void 0&&(t+=1),e.lastSeenAt!==void 0&&(t+=1),e.lastUpdated!==void 0&&(t+=1),e.inboxBucket!==void 0&&(t+=1),e.surfaceHidden!==void 0&&(t+=1),e.muted!==void 0&&(t+=1),e.completionMarker!==void 0&&(t+=1),e.seenCompletionMarker!==void 0&&(t+=1),t}function VS(e,t){const s=e.lastUpdated||0,r=t.lastUpdated||0;if(r!==s)return r>s;const o=em(e),a=em(t);return a!==o?a>o:!1}function tm(e,t,s){return e===void 0?t:t===void 0?e:s?t:e}function _f(e){const t=new Map,s=new Map,r=(o,a)=>{if(!o)return;const i=s.get(o),c=t.get(o),d=(a.lastUpdated||0)>((i==null?void 0:i.lastUpdated)||0),u=tm(c==null?void 0:c.surfaceHidden,typeof a.surfaceHidden=="boolean"?a.surfaceHidden:void 0,d),m=tm(c==null?void 0:c.muted,typeof a.muted=="boolean"?a.muted:void 0,d);if(i&&!VS(i,a)){c&&t.set(o,{...c,surfaceHidden:u,muted:m});return}s.set(o,a),t.set(o,{sessionId:o,...zS(a),surfaceHidden:u,muted:m})};for(const o of e)if(o.type!=="adhdev-daemon"){r(o.sessionId,o);for(const a of o.childSessions||[])r(a.id,a)}return t}function Ns(e,t){if(e.sessionId){const s=t.get(e.sessionId);if(s)return s}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:void 0,muted:void 0,completionMarker:"",seenCompletionMarker:""}}function Ci(e,t,s){const r=Ns(e,t),o=or(e),a=o.isReconnecting,i=o.isConnecting,c=o.isGenerating,d=o.isWaiting,u=o.isWaitingChoice,m=r.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d||u,h=r.inboxBucket==="working"||c,g=!!(r.inboxBucket==="task_complete"&&r.unread&&!(s!=null&&s.hideOpenTaskCompleteUnread&&(s!=null&&s.isOpenConversation)));return{unread:g,requiresAction:m,isWorking:h,isReconnecting:a,isConnecting:i,isGenerating:c,isWaiting:d,inboxBucket:m?"needs_attention":h?"working":g?"task_complete":"idle"}}function YS(e,t,s){return Ci(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:s==null?void 0:s.isOpenConversation}).unread}function QS(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function JS(e){const t=(e==null?void 0:e.result)??e;return typeof(t==null?void 0:t.error)=="string"?t.error:"Interactive prompt response failed"}async function XS(e,t,s){const r=await s(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let o=`HTTP ${r.status}`;try{const a=await r.json();typeof(a==null?void 0:a.error)=="string"&&(o=a.error)}catch{}throw new Error(o)}}async function ZS({promptSession:e,response:t,useP2PCommand:s,sendCommand:r,fetchImpl:o=fetch}){if(s){const a=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!QS(a))throw new Error(JS(a));return}await XS(e.sessionId,t,o)}let fc=null;const gc=new Set;function ek(e){return gc.add(e),()=>{gc.delete(e)}}function nm(){return fc}function ra(e){if(fc!==e){fc=e;for(const t of gc)t()}}function _i(e,t){const{t:s}=ve("common"),{ides:r,isP2PActive:o,p2pStates:a}=An(),{sendCommand:i}=_t(),c=l.useSyncExternalStore(ek,nm,nm),[d,u]=l.useState(!1),[m,h]=l.useState(null),p=l.useRef(!1),g=(t==null?void 0:t.includeHidden)===!0,f=l.useMemo(()=>I0(r,{sessionId:e,includeHidden:g}),[r,e,g]),x=!!f,b=l.useMemo(()=>f?f.prompt.promptId===c?null:f:null,[c,f]),k=(f==null?void 0:f.prompt.promptId)??null;l.useEffect(()=>{h(null)},[k]);const j=l.useCallback(async y=>{if(!b||p.current)return;p.current=!0;const w=xf(b.prompt,y);u(!0),h(null);try{const S=(a==null?void 0:a[b.daemonId])==="connected"||o===!0;await ZS({promptSession:b,response:w,useP2PCommand:S,sendCommand:i}),ra(b.prompt.promptId)}catch(S){let C=S instanceof Error?S.message:String(S);throw C.includes(Ey)?(ra(b.prompt.promptId),h(s("interactivePrompt.errorReviewUnconfirmed",{defaultValue:"The answer keys reached the terminal, but the question is still on screen — the answer may not have been submitted. Check the terminal: if it was not submitted, answer there; resending from here could submit it twice."})),S):(C.includes(Ly)&&(C=s("interactivePrompt.errorReviewPageNotFocused",{defaultValue:"The terminal is showing a different screen, so the answer was not submitted — check the terminal screen or close this and try again."})),h(C),S)}finally{u(!1),p.current=!1}},[o,a,b,i]),v=l.useCallback(()=>{b&&ra(b.prompt.promptId)},[b]),_=l.useCallback(()=>{if(ra(null),!f){h(s("interactivePrompt.errorUnavailable",{defaultValue:"Could not load the question — answer it in the terminal view instead."}));return}h(null)},[f,s]);return{promptSession:b,hasActivePrompt:x,responseError:m,isSubmitting:d,submit:j,cancel:v,reopen:_}}function Af(e){return e.sessionId??e.routeId}const cl=e=>e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*\(\s*\b(?:Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)\b(?:\s*\+\s*\w+)*\s*\)/gi,"").replace(/\s*\b(?:Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)\b(?:\s*\+\s*\w+)*/gi,"").trim(),tk=12e3;function Tf({activeConv:e,onModalButton:t}){const{t:s}=ve(),[r,o]=l.useState(null),{hasActivePrompt:a,promptSession:i,reopen:c}=_i(Af(e));l.useEffect(()=>{o(null)},[e.modalMessage,e.status,e.connectionState]),l.useEffect(()=>{if(!r)return;const h=setTimeout(()=>o(null),tk);return()=>clearTimeout(h)},[r]);const d=or(e);if(!d.isWaiting&&!d.isWaitingChoice||!e.modalButtons)return null;const u=h=>{r||(o(h),t(h))},m=()=>n.jsx("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:n.jsx("div",{className:"flex items-center gap-2",children:n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(an,{size:14}),s("approval.questionUnavailable",{defaultValue:"Question waiting — could not load it here. Answer it in the terminal view."})]})})});return a&&!i?m():a?n.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&n.jsx("div",{className:"text-2xs opacity-85 mb-1.5 line-clamp-3 max-w-full whitespace-pre-wrap break-words",title:e.modalMessage,children:e.modalMessage}),n.jsxs("div",{className:"flex justify-between items-center gap-2",children:[n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(an,{size:14})," ",s("approval.questionPending",{defaultValue:"Question waiting"})]}),n.jsx("button",{onClick:c,className:"btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold cursor-pointer whitespace-nowrap shrink-0",style:{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"},children:s("approval.answerQuestion",{defaultValue:"Answer the question"})})]})]}):d.isWaitingChoice?m():n.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&n.jsx("div",{className:"text-2xs opacity-85 mb-1.5 line-clamp-3 max-w-full whitespace-pre-wrap break-words",title:e.modalMessage,children:e.modalMessage}),n.jsxs("div",{className:"flex justify-between items-center",children:[n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(an,{size:14})," ",s(r?"approval.processing":"approval.actionRequired")]}),n.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((h,p)=>{const g=cl(h).toLowerCase(),f=/^always\b/.test(g),x=!f&&/^(run|approve|accept|yes|allow|always)/.test(g),b=/^(reject|deny|delete|remove|abort)/.test(g),k=r===h,j=r!==null;return n.jsx("button",{onClick:()=>u(h),disabled:j,title:f?s("approval.alwaysAllowWarning"):void 0,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${x?"font-extrabold":b?"bg-red-500/30 text-white font-semibold":f?"text-white/90 font-semibold":"text-white font-semibold"} ${j&&!k?"opacity-40":"opacity-100"} ${j?"cursor-not-allowed":"cursor-pointer"}`,style:x?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:f?{background:"transparent",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 55%, transparent)"}:b?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:k?n.jsx(Mr,{size:12}):f?n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(an,{size:11}),cl(h)]}):cl(h)},p)})})]})]})}const Sd="adhdev_controls_bar_visible",bc="adhdev:controlsbarvisibilitychange";function dl(e){if(!e)return!1;try{return e.getItem(Sd)==="1"}catch{return!1}}function nk(e,t){if(t)try{t.setItem(Sd,e?"1":"0")}catch{}}function sk(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(bc,{detail:{visible:e}}))}function kd(){const[e,t]=l.useState(()=>typeof window>"u"?!1:dl(window.localStorage)),s=l.useRef(e),r=l.useCallback((i,c=!0)=>{s.current=i,t(i),typeof window<"u"&&nk(i,window.localStorage),c&&sk(i)},[]);l.useEffect(()=>{const i=d=>{const u=d.detail,m=typeof(u==null?void 0:u.visible)=="boolean"?u.visible:dl(window.localStorage);s.current=m,t(m)},c=d=>{if(d.key!==Sd)return;const u=dl(window.localStorage);s.current=u,t(u)};return window.addEventListener(bc,i),window.addEventListener("storage",c),()=>{window.removeEventListener(bc,i),window.removeEventListener("storage",c)}},[]);const o=l.useCallback(i=>{r(i)},[r]),a=l.useCallback(()=>{r(!s.current)},[r]);return{isVisible:e,setVisibility:o,toggleVisibility:a}}const If=["en","ko","ja","zh-CN","es"],zs="en",Ps=[{code:"en",label:"English"},{code:"ko",label:"한국어"},{code:"ja",label:"日本語"},{code:"zh-CN",label:"中文(简体)"},{code:"es",label:"Español"}];function Us(e){return typeof e=="string"&&If.includes(e)}function rk(e){if(!e)return zs;const t=e.trim().toLowerCase();if(!t)return zs;if(t==="zh"||t.startsWith("zh-")||t.startsWith("zh_"))return"zh-CN";const s=t.split(/[-_]/)[0];return s==="en"?"en":s==="ko"?"ko":s==="ja"?"ja":s==="es"?"es":zs}const ok={runFailed:"Couldn't run {{label}}",updateFailed:"Couldn't update {{label}}",loadOptionsFailed:"Couldn't load {{label}} options"},ak={unknown:"Unknown",starting:"Starting",stopped:"Stopped",failed:"Failed",idle:"Idle",generating:"Working",awaitingApproval:"Needs approval"},ik={label:"Language",select:"Select language"},lk={copy:"Copy",no:"No",yes:"Yes",diagnostics:"Diagnostics",done:"Done",edit:"Edit",copied:"Copied",copyId:"Copy ID",technicalDetails:"Technical details",saveFailed:"Couldn't save: {{error}}",saved:"Saved",refresh:"Refresh",moreInfo:"More info",closeDialog:"Close dialog",noRecords:"No records found.",close:"Close",back:"Back",cancel:"Cancel",confirm:"Confirm",confirmTitle:"Are you sure?"},ck={loadingShort:"Loading…",loadingDashboard:"Loading your dashboard...",machinesConnectedCount:"{{connected}}/{{total}} machines connected",disconnected:"Disconnected",connected:"Connected",connectedToDashboard:"Connected to dashboard",networkOffline:"Network offline",reconnecting:"Reconnecting",sessionExpired:"Session expired.",logInAgain:"Log in again",connectionFailed:"Connection failed — refresh the page or try again shortly.",reconnectNow:"Reconnect now"},dk={details:"Details",label:{success:"Done",warning:"Attention",info:"Update"},dismiss:"Dismiss"},uk={actionNeeded:"Action needed",taskComplete:"Task complete",markRead:"Mark read",markUnread:"Mark unread",delete:"Delete"},mk={browser:{error:"Stopped with an error",finished:"Finished",approvalWithMessage:"Needs approval: {{message}}",approval:"Needs approval",questionWithMessage:"Question: {{message}}",question:"Waiting for your answer"},taskCompleted:"{{label}} agent task completed",taskCompletedWithDuration:"{{label}} agent task completed ({{duration}})",approvalNeeded:"{{label}} approval needed",questionNeeded:"{{label}} question needs an answer",noProgress:"{{label}} agent shows no progress",noProgressWithDuration:"{{label}} agent shows no progress ({{minutes}}m)",noProgressTitle:"{{label}} — No Progress",noProgressBody:"Agent has shown no progress for over {{duration}}",viewRequest:"{{requester}} wants to view your session",viewRequestTitle:"View Request",viewRequestApproved:"View request approved",viewRequestDeclined:"{{target}} declined your view request",someoneRequester:"A team member",someoneTarget:"Team member"},hk={header:{moreActions:"More actions",title:"Dashboard",guide:"Dashboard guide",guideOpen:"Open dashboard guide",guideShort:"Guide",openGitStatus:"Open git status",meshGraph:"Mesh graph",stopAcpSession:"Stop ACP session",stopCliProcess:"Stop CLI process",chatHistory:"Chat History",remoteControl:"Remote Control",generating:"generating",activityInbox:"Notifications"},hidden:{title:"Hidden tabs",dragHint:"Drag a tab here to hide it.",resetPanels:"Reset panels",restoreAll:"Restore all",hideCurrentTab:"Hide current tab",empty:"No hidden tabs.",resetPanelsConfirm:"Move every floating or popout panel back into the main dashboard grid?"},inbox:{unread:"Unread",read:"Read",empty:"No pending activity."},metaChips:{queuePending:"{{count}} waiting",queueTooltip:"Queue: {{pending}} waiting, {{assigned}} assigned, {{completed}} completed, {{failed}} failed"},meshRole:{coordinator:"Coordinator",worker:"Worker",coordinatorFor:"Coordinator for {{mesh}}",workerFor:"Worker for {{mesh}}",coordinatorUnknownMesh:"Mesh coordinator",workerUnknownMesh:"Mesh worker",openMeshGraph:"Open mesh graph"},versionBanner:{restarting:"restarting",upgrading:"updating…",unknownVersion:"unknown",updateAvailable:"Update available",required:"required",retry:"retry"},remoteDialog:{liveRemoteView:"Live remote view",remoteUnavailable:"Remote view unavailable",remoteOnly:"Remote only",splitView:"Split view",remoteFallback:"Remote",history:"History"},guide:{title:"Dashboard guide",subtitle:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune.",close:"Close dashboard guide",tabs:{overview:"Overview",quickstart:"Quick start",shortcuts:"Shortcuts"},overview:{whatLivesWhere:{title:"What lives where",tabsLabel:"Tabs:",tabsText:"active sessions across IDE, CLI, and ACP agents.",hiddenLabel:"Hidden tabs:",hiddenText:"stash sessions you do not want in the main strip but still want to keep around.",inboxLabel:"Activity inbox:",inboxText:"sessions waiting for approval or finished tasks you have not reviewed yet.",cliToggleLabel:"CLI view toggle:",cliToggleText:"switch a PTY session between terminal and chat rendering without relaunching it."},usefulFlows:{title:"Useful flows",reviewLabel:"Review notifications:",reviewText:"open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane.",clutterLabel:"Reduce clutter:",clutterText:"hide less important sessions instead of closing them, then restore from hidden tabs when needed.",splitLabel:"Split work:",splitText:"keep one pane active for input and let secondary panes stay read-only until you focus them.",detachedLabel:"Detached views:",detachedText:"float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor.",dockingLabel:"Docking:",dockingText:"use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard.",perTabLabel:"Per-tab shortcuts:",perTabText:"right-click a Dockview tab to assign a direct shortcut for that specific session.",approvalLabel:"Approval buttons:",approvalText:"use {{keys}} for the first three visible approval actions on the active session."}},quickstart:{desktop:{title:"Desktop quick start",step1:"Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions.",step2:"Keep the main strip focused on active work and push overflow into Hidden tabs.",step3:"Use the inbox for approval-required or completed sessions instead of scanning every tab.",step4:"Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."},mobile:{title:"Mobile quick start",step1:"Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions.",step2:"Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there.",step3:"Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."}},shortcuts:{sections:{all:"All",workspace:"Workspace",panes:"Panes",approvals:"Approvals"},disableAll:"Disable all",resetToDefaults:"Reset to defaults",default:"Default:",listening:"Listening...",set:"Set",disable:"Disable",off:"Off",footer:"Use modifier shortcuts like {{keys}}, or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs.",resetConfirm:"Reset all dashboard shortcuts back to their default values?",setListening:"Listening"}},shortcutDefs:{openShortcutHelp:{label:"Open shortcuts",description:"Show the keyboard shortcuts panel."},openNewSession:{label:"New session",description:"Open the new session launcher."},hideCurrentTab:{label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs."},toggleHiddenTabs:{label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover."},openHistoryForActiveTab:{label:"Open history",description:"Open history for the active session."},openRemoteForActiveTab:{label:"Open remote",description:"Open remote control for the active session when available."},floatActiveTab:{label:"Float active tab",description:"Move the active tab into a floating panel."},popoutActiveTab:{label:"Open active tab in new window",description:"Move the active tab into a detached popout window."},dockActiveTab:{label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window."},splitActiveTabRight:{label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it."},splitActiveTabDown:{label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it."},focusLeftPane:{label:"Focus left pane",description:"Move focus to the pane on the left."},focusRightPane:{label:"Focus right pane",description:"Move focus to the pane on the right."},focusUpPane:{label:"Focus upper pane",description:"Move focus to the pane above."},focusDownPane:{label:"Focus lower pane",description:"Move focus to the pane below."},moveActiveTabToLeftPane:{label:"Move active tab left",description:"Move the active tab into the pane on the left."},moveActiveTabToRightPane:{label:"Move active tab right",description:"Move the active tab into the pane on the right."},moveActiveTabToUpPane:{label:"Move active tab up",description:"Move the active tab into the pane above."},moveActiveTabToDownPane:{label:"Move active tab down",description:"Move the active tab into the pane below."},triggerPrimaryApprovalAction:{label:"Approval action 1",description:"Press the first approval/action button for the active session."},triggerSecondaryApprovalAction:{label:"Approval action 2",description:"Press the second approval/action button for the active session."},triggerTertiaryApprovalAction:{label:"Approval action 3",description:"Press the third approval/action button for the active session."},setActiveTabShortcut:{label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab."},selectPreviousGroupTab:{label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group."},selectNextGroupTab:{label:"Next tab in group",description:"Move to the next tab inside the active Dockview group."},toggleCliView:{label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view."}}},pk={stopProcess:"Stop CLI process",title:"Stop {{agent}}?",gracefulDescription:"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.",forceOnlyDescription:"This provider does not support graceful stop. Force Stop will end the runtime immediately.",stop:"Stop",forceStop:"Force Stop"},fk={processing:"PROCESSING...",actionRequired:"ACTION REQUIRED",alwaysAllowWarning:"Grants this permission permanently — future runs will not ask again",questionPending:"QUESTION WAITING",answerQuestion:"Answer the question"},gk={loading:"Loading…",launchModelChanged:"{{from}} → {{to}} (changed)",launchModelSource:{user:"chosen",remembered:"remembered",mesh_slot:"mesh slot",task_override:"task override",provider_default:"default"}},bk={noMeshesShort:"No meshes on this machine",noProvidersShort:"No agents available",advancedOptions:"Advanced options",agent:"Agent",defaultResolvesTo:"Default resolves to {{model}}",title:"Start session",close:"Close new session dialog",detectedLocally:"Detected locally",availableToOpen:"Available to open",machine:"Machine",selectMachine:"Select machine {{name}}",workspace:"Workspace",browse:"Browse…",launchTargetType:"Launch target type",modeWorkspace:"Workspace",modeWorkspaceDesc:"Normal session",modeMesh:"Mesh",modeMeshDesc:"Coordinator session",homeDirectory:"Home directory",customFolder:"Custom folder…",launchWithoutWorkspace:"Launch without a workspace.",selectWorkspaceFolder:"Select a workspace folder.",selectFolder:"Select folder",saving:"Saving…",saveWorkspace:"Save workspace",loadingMeshes:"Loading meshes…",noMeshes:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker.",mesh:"Mesh",repoMesh:"Repo mesh",nodeCount_one:"{{count}} node",nodeCount_other:"{{count}} nodes",coordinatorWorkspace:"Coordinator workspace: {{path}}",noProviders:"Nothing usable on the selected machine. If an agent is installed outside the default location, set its executable path in Machine → Providers.",startupArguments:"Startup arguments",optionalFlags:"Optional flags...",autoApproveMode:"Auto-approve mode",autoApproveModeDescription:"Choose how this session handles approval prompts.",autoApproveLegacy:"Auto approve",autoApproveLegacyDescription:"Automatically accept supported approval prompts for this session.",autoApproveRisk:{safe:"Safe",caution:"Caution",dangerous:"Dangerous"},dangerousModeTitle:"Confirm dangerous auto-approve mode",dangerousModeFallbackWarning:"This mode can bypass approval or sandbox protections. Use it only in a trusted workspace.",dangerousModeRisk:"Risk",dangerousModeLaunchArgs:"Injected launch arguments",dangerousModeConfirm:"Use dangerous mode",modelAndThinking:"Model & thinking (optional)",model:"Model",providerDefault:"(provider default)",custom:"Custom…",typeModelName:"Type a model name",backToModelList:"← Back to model list",thinkingLevel:"Thinking level",selectWorkspaceTitle:"Select workspace",start:"Start",starting:"Starting…",startMeshCoordinator:"Start mesh coordinator",startingCoordinator:"Starting coordinator…",startIde:"Start IDE",startingIde:"Starting IDE…",startAcpSession:"Start ACP session",startingAcpSession:"Starting ACP session…",startFresh:"Start fresh",startingFresh:"Starting fresh…",resumeSavedHistory:"Resume saved history",resumingSavedHistory:"Resuming saved history…",errorLoadMeshes:"Could not load meshes",errorLoadFolder:"Could not load folder",errorLoadSavedSessions:"Could not load saved sessions",errorSaveWorkspace:"Could not save workspace",workspaceSaved:"Workspace saved. It will appear in the list once the machine state refreshes.",errorManualMcpSetup:"Manual MCP setup required before this provider can act as mesh coordinator.",errorStartMeshCoordinator:"Could not start mesh coordinator",errorStartSession:"Could not start session",errorResumeSession:"Could not resume session",errorWorkspaceContextRequired:"Choose a workspace — a directory, a saved/default workspace, or your home directory — before launching.",defaultWorkspace:"Default workspace"},xk={undo:"Undo",hiddenToast:"Hid {{title}}",moreActionsFor:"More actions for {{title}}",loading:"Loading...",loadingSubtitle:"Fetching your machines and sessions.",machines:"Machines",chats:"Chats",networkOffline:"Network offline",sessionExpired:"Session expired",reconnecting:"Reconnecting",waitingForNetwork:"Waiting for network…",pleaseLogInAgain:"Please log in again.",restoringConnection:"Restoring the server connection…",waitingForDaemon:"Waiting for your daemon",connectYourMachines:"Connect your machines",waitingForDaemonSubtitle:"Start the ADHDev daemon to connect.",connectYourMachinesSubtitle:"Install ADHDev on a machine and sign in.",newCount:"{{count}} new",chatCount_one:"{{count}} chat",chatCount_other:"{{count}} chats",idle:"Idle",unreadSuffix:" · {{count}} unread",noActiveChats:"No active chats",needsAttention:"Needs attention",taskComplete:"Task complete",workingNow:"Working now",earlier:"Earlier",connecting:"Connecting…",connectingSubtitle:"Waiting for server connection before loading conversations.",noMachinesConnected:"No machines connected",noMachinesSubtitle:"Connect a machine from the Machines tab.",noConversations:"No conversations yet",allCaughtUp:"All caught up.",hiddenTabs:"Hidden tabs",collapsedCount_one:"{{count}} collapsed conversation",collapsedCount_other:"{{count}} collapsed conversations",generatingCount:"{{count}} generating",collapsedGeneratingSuffix:" · {{count}} generating",restoreAll:"Restore all",hide:"Hide",reconnectingItem:"Reconnecting…",connectingItem:"Connecting…",actionNeeded:"Action needed",done:"Done",openMeshGraphFor:"Open mesh graph for {{title}}",openLiveMeshGraph:"Open live repo mesh graph",stopSessionTitle:"Stop session (terminates the agent)"},yk={hint:{daemon:{followUp:"Needs follow-up",merged:"Merged",notMergeable:"Can't merge yet — changes or conflicts",cleanup:"Merged — worktree can be cleaned up",needsMerge:"Pushed — ready to merge",blockedReview:"Needs review before merging"},anchorEmpty:"No workspace on the default branch",anchorWorkspaces:"{{count}} workspace(s) on {{branch}}",anchorNeedsFollowUp:"{{count}} on {{branch}} need follow-up",submoduleSynced:"{{path}} is in sync",submoduleChanged:"{{path}} has local changes",submoduleOutOfSync:"{{path}} is out of sync with its parent",gitAgeUnknown:"Git status age unknown",staleGit:"Git status is over 5 min old",missingSubmodule:"Submodule not reported: {{paths}}",noGitYet:"No git status received yet",noGitYetOnline:"Online — git status not received yet",waitingForGit:"Waiting for git status…",nodeError:"Node reported an error",upstreamUnverified:"Upstream not verified yet",noUpstream:"Push {{branch}} to set its upstream",mergeConflicts:"Resolve merge conflicts",detachedHead:"Detached HEAD — check out a branch",notGitRepo:"Not a git repository",noGitStatus:"No git status yet"},sessionCleanup:{stopAndDeleteHint:"Stop matching sessions, then remove their chat records.",stopAndDelete:"Stop and delete sessions",deleteStoppedHint:"Clear finished or stopped chats without stopping running sessions.",deleteStopped:"Delete stopped sessions only",stopHint:"Stop running session processes but keep their chat records.",stop:"Stop running sessions only",preserveHint:"Keep finished chat history and leave running sessions alone.",preserve:"Keep history and running sessions"},nodeHealth:{failed:"Failed",completed:"Completed",assigned:"Assigned",pending:"Pending",enabled:"Enabled",unknown:"Connecting…",wrongBranch:"Other branch",degradedHint:"The connection to this machine is down or timed out — often temporary. Wait a moment or reconnect the machine.",degraded:"Unreachable",offline:"Offline",dirty:"Uncommitted changes",online:"Online"},activity:{noKeyEvents:"No recent key events",rawData:"Raw data",showKey:"Show key events only",showAll:"Show all activity",nodeChanged:"Machine joined or left",sessionStarted:"Agent started",needsInput:"Needs your input",taskFailed:"Task failed",taskFinished:"Task finished",taskStarted:"Task started"},drift:{clean:"Clean",conflicts:"conflicts",submoduleOutOfSync_other:"{{count}} submodules out of sync",submoduleOutOfSync_one:"{{count}} submodule out of sync",submoduleChanged_other:"{{count}} submodules changed",submoduleChanged_one:"{{count}} submodule changed",changed_other:"{{count}} changed",changed_one:"{{count}} changed",upstreamUnverified:"upstream unverified",noGit:"No git info",probePending:"Checking git…"},graph:{slowLinkChip:"Slow link",observationUnreachableChip:"Unreachable",observationStaleChip:"Stale",remoteBadge:"remote",activeSessionAria:"active session",observationAsOf:"as of {{age}} ago",observationRefreshing:"as of {{age}} ago · refreshing",observationFetching:"fetching state…",observationUnreachable:"unreachable · last known {{age}} ago",observationUnreachableNoState:"unreachable · no state yet"},statusTab:{v2ScopeHint:"Pending events by scope",providerSkewHint:"Providers running different versions on different nodes",providerSkew:"{{count}} provider version mismatch",v2RatioHint:"Share of pending coordinator events in the current message format",daemonBuildHint:"Exact daemon build (version@commit) running on this node",quotaFailedHint:"This machine couldn't read this provider's usage",quotaOkNoWindowHint:"Read successfully — this provider has no percentage limit to show",nodeCountHint:"Mesh nodes (workspaces/worktrees) on this machine — they share one plan quota",nodeCount_other:"{{count}} nodes",nodeCount_one:"{{count}} node",daemonVersionHint:"Daemon version running on this machine",blockedReasonHint:"Why this node can't take a new code-changing task right now",providerCapHint:"Active tasks per provider on this node vs its declared limit",priorityHint:"Scheduling preference (higher is preferred)",priority:"priority {{value}}",loadHint:"Active tasks assigned to this node",load:"load {{count}}",readonlyCapHint:"Active read-only investigation tasks vs their limit (2× the write limit)",readonlyCap:"read-only {{active}}/{{max}}",writeCapHint:"Active tasks that change code vs the mesh-wide parallel limit",writeCap:"write {{active}}/{{max}}"},manualSetup:{restartHint:"Start a fresh CLI session after editing config.",configPath:"Config path:",format:"Format:",server:"Server:",titleFor:"Manual MCP setup required for {{provider}}",title:"Manual MCP setup required"},help:{toggleAria:"Mesh help",toggleTitle:"Mesh concept help",regionAria:"Mesh concept help",kicker:"Help",title:"Mesh concepts at a glance",close:"Close help",sections:{node:{term:"Node",summary:"A workspace participating in the mesh — a repo checkout or an isolated git worktree.",details:["Base node vs worktree clone node — a clone isolates parallel work without conflicts.","Shows health (online/offline) alongside git state (branch · ahead/behind · dirty).","Multiple nodes can share the same daemon."]},p2p:{term:"P2P connection",summary:"How the selected coordinator reaches each remote node over WebRTC.",details:["direct — a direct host/STUN path; lowest latency.","relay — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed — no live P2P link from the coordinator right now.","P2P connectivity is shown as transport and RTT chips on each node card (and in the node detail panel), not as a graph edge."]},session:{term:"Session",summary:"An agent CLI session running on a node.",details:["status = idle / generating / waiting_approval.","Distinguishes coordinator sessions (which dispatch and collect work) from delegated worker sessions (which do the work)."]},task:{term:"Task",summary:"A single unit of work handled by the queue-based pull model.",details:["States: pending → assigned → completed / failed / cancelled.","Idle nodes claim from the queue automatically; direct dispatch targets a specific session."]},mission:{term:"Mission",summary:"A multi-task batch aimed at one goal, and the durable record of that effort.",details:["States: active / paused / completed / abandoned.","Progress is derived from the states of its member tasks."]},refinery:{term:"Refinery (refine)",summary:"The process of safely converging and merging a worktree branch into the base.",details:["Config-driven (.adhdev/refine.*) — guarded by a patch-equivalence preflight and a no-op guard.","ff-only by principle; no force-push.","If a submodule commit is unreachable from origin it must be published → classified as blocked_review."]},completion:{term:"Completion model",summary:"Completion of delegated work is persisted to the queue (pending-events).",details:["The coordinator learns of completion via periodic polling or events.","Because it is persisted to the queue, completion signals are never lost."]},magi:{term:"MAGI",summary:"Cross-verification: several independent AI agents answer the same question in parallel.",details:["Confidence comes from independence — different AIs on different machines fail in different ways.","When the agents disagree, the disagreement itself flags what to double-check.","The synthesis weighs agreement against source coupling."]},magiPanel:{term:"MAGI panel",summary:"A saved, reusable team of (machine × AI) members you invoke by name across investigations.",details:["Each member is one provider (AI) optionally pinned to a node (machine), with a replica count.","independent — spans ≥2 providers AND ≥2 machines, so agreement adds real confidence.","coupled — collapses to one AI or one machine; repeated members repeat the same mistakes.","Managed machine-locally from the Panels tab; defined in ~/.adhdev/meshes.json."]},convergence:{term:"Branch convergence states",summary:"After worktree work, each branch is classified into exactly one final state.",details:["merged_to_main — merged into the base.","pushed_feature_branch_needs_merge — pushed, awaiting merge.","blocked_review — held back by review/reachability issues.","cleanup_candidate — ready to clean up.","not_mergeable — cannot be merged."]},graph:{term:"Orchestration graph",summary:"A batch of tasks enqueued together with declared dependencies, conditions and gates.",details:["Created by mesh_enqueue_batch; each graph is one executable plan inside a mission.","Settled graphs collapse to a single chip on the blueprint — click to expand in place."]},gate:{term:"Coordinator gate",summary:"A step that holds the graph until a human-directed coordinator acts.",details:["States: declared → awaiting_coordinator → claimed → released (or expired).","The blueprint draws a waiting gate at full card width with its instructions and deadline.","Acting on a gate is done by instructing the coordinator; the dashboard is read-only here."]},condition:{term:"Condition (run_if)",summary:"A declarative predicate deciding whether a planned step runs at all.",details:["Grammar is a closed set: all / any / not over exists, ==, != and in.","The blueprint renders it as a card wired into the edge, e.g. review.outcome == rejected.","A step whose condition never holds is skipped, not failed."]},blueprint:{term:"Blueprint",summary:"The plan view: live queue work, graph gates and planned steps on one canvas.",details:["One axis — dependency depth, left to right. Root tasks are ordered newest first.","Cards carry their own time, so position never has to encode it.","Finished graphs sit below the live work as a collapsed archive."]},routingPreview:{term:"Routing preview",summary:"A read-only forecast of where a hypothetical task would land.",details:["Shown per difficulty; a task pinned to a node gets its own pinned preview (📌).","It is a prediction, not the owner — a card that already ran shows its real node below."]},worktree:{term:"Worktree node",summary:"A node backed by a git worktree rather than the main checkout.",details:["Labelled by its branch (⎇). Lets several tasks run on one machine without sharing a branch.","Orphan worktrees are reported as cleanup candidates and are never deleted automatically."]}}},approvals:{title:"PENDING APPROVALS",empty:"No sessions are awaiting an approval decision.",sessionFallback:"session {{id}}",approve:"Approve",reject:"Reject",waitingFor:"Waiting for {{duration}}"},difficulty:{intro:"Map each task difficulty to a brain. The coordinator classifies a task's difficulty; easy work then runs on a cheaper model at low effort, hard work on a stronger model at high effort. Leave a field blank to keep the routed default.",connectPrompt:"Connect to a coordinator daemon to edit brain presets.",errorLoad:"Failed to load brain presets",errorSave:"Failed to save brain presets",provider:"Provider",model:"Model",thinking:"Thinking",routedDefault:"(routed default)",defaultOption:"(default)",modelPlaceholder:"e.g. haiku, sonnet, opus",savePresets:"Save presets",saving:"Saving…",reset:"Reset",loading:"Loading…",easy:"Easy",easyHint:"trivial fixes, renames, docs — save tokens",medium:"Medium",mediumHint:"ordinary feature / bugfix work",difficult:"Difficult",difficultHint:"architecture, tricky debugging, hard reasoning",freeform:"Freeform",freeformHint:"no fixed shape"},magiKind:{refresh:"Refresh",loading:"Loading…",connectPrompt:"Connect to a coordinator daemon to manage kind → panel bindings.",errorLoad:"Failed to load kind panels",errorSave:"Failed to save kind binding",errorRemove:"Failed to remove kind binding",errorSlotProvider:"Slot {{slot}}: provider is required",errorSlotReplica:"Slot {{slot}}: replica count must be ≥ 1",errorNoSlot:"A kind binding needs at least one slot",removeConfirm:'Remove the MAGI panel binding for "{{kind}}"?',kindRca:"Root-cause analysis",kindDesign:"Design / approach review",kindClaimAudit:"Verify specific claims",kindFreeform:"Freeform review",agentCount_one:"{{count}} agent",agentCount_other:"{{count}} agents",off:"off",noAgents:"No agents yet — add one to enable this review type.",machine:"Machine",machineTitle:'Which machine runs this agent. Leave on "any" to let the coordinator route by tags.',anyMachine:"Any machine",offlineSuffix:"{{label}} (offline)",worktreeSuffix:"{{label}} — worktree ({{branch}})",worktreeUnknownBranch:"unknown branch",worktreeDisabledTitle:"Ephemeral worktree nodes can't be newly assigned to a MAGI slot — they can disappear on cleanup. An existing assignment stays visible here so it can be reviewed or cleared.",provider:"Provider",providerTitle:"The AI agent this slot runs.",selectProvider:"Select provider…",model:"Model",modelTitle:"Optional model override (best-effort). Blank uses the provider default.",modelDefault:"default",modelCustom:"Custom…",backToModelList:"← Back to model list",copies:"Copies",copiesTitle:"How many parallel copies of this agent to run. Blank = 1.",removeAgent:"Remove agent",addAgent:"+ Add agent",save:"Save",saving:"Saving…",removeBinding:"Remove binding",removeBindingTitle:"Clear this kind binding",removeBindingDisabledTitle:"Nothing to remove — this kind is unconfigured"},synthesis:{rawUnavailable:"Raw answers unavailable",empty:"No cross-verification results for this mesh yet.",synthesized:"synthesized",running:"running",answered:"{{answered}}/{{total}} answered",needsVerificationCount:"{{count}} needs verification",agreedCount:"{{count}} agreed",staleCount:"{{count}} stale",gitSkewLabel:"Git skew: ",gitSkewNote_one:"{{count}} branch ({{branches}}) — evidence compares different code.",gitSkewNote_other:"{{count}} branches ({{branches}}) — evidence compares different code.",needsVerification:"Needs verification",openQuestions:"Open questions",rawReplicaAnswers:"Raw replica answers",rawTitleLive:"Best-effort: raw replica text is not persisted — recoverable only from a live coordinator with the replica sessions still reachable.",rawTitleOffline:"A live coordinator daemon is required to fetch raw replica answers.",loading:"Loading…",reloadRaw:"Reload raw answers",loadRaw:"Load raw answers",rawNotice:"Raw per-replica text is not persisted (only this synthesis summary is). It is fetched live from the coordinator and is unavailable once the replica sessions age out or no live session exists.",errorLoadRaw:"Failed to load raw answers",rawEmpty:"No raw answers were returned — the replica transcripts are not retained (raw not persisted), aged out, or no live session is reachable for this group.",truncated:"truncated"},panel:{selectNode:"Select a node to view details.",submoduleBadge:"Submodule",dirtyBadge:"Dirty",outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",orphanBadge:"Orphan",fieldWorkspace:"Workspace",fieldBranch:"Branch",fieldUpstream:"Upstream",fieldUpstreamState:"Upstream state",fieldHead:"HEAD",fieldSubmodulePath:"Submodule path",fieldSubmoduleCommit:"Submodule commit",fieldParentNode:"Parent node",fieldAhead:"Ahead",fieldBehind:"Behind",fieldDirtyFiles:"Dirty files",fieldActiveSessions:"Active sessions",fieldProviders:"Providers",fieldConnection:"Connection",fieldError:"Error",orphanReasons:"Orphan reasons",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusCoordinator:"coordinator",statusWorker:"worker",upstreamVerified:"verified",upstreamUnverifiedFetch:"unverified (fetch failed)",upstreamUnverified:"unverified",upstreamUnavailable:"unavailable",needsFollowUp:"needs follow-up",refined:"refined",tooltipLocalChanges:"Local changes",tooltipHasConflicts:"Has conflicts",tooltipOutOfSync:"Out of sync",tooltipNeedsFollowUp:"Needs follow-up",tooltipUpstreamUnverified:"Upstream unverified",tooltipRefineCompleted:"refine completed",tooltipRefinedBranch:"refined {{branch}}",tooltipP2PRelayed:"P2P link relayed through TURN (slower path)",tooltipPrefixStatus:"Status:",tooltipPrefixBranch:"Branch:",tooltipPrefixNote:"Note:",defaultBranch:"default branch",submoduleSynced:"synced",moreChats_one:"+{{count}} more chat",moreChats_other:"+{{count}} more chats",remote:"remote",chats_one:"{{count}} chat",chats_other:"{{count}} chats",generatingCount:"{{count}} generating",coordinatorAttached:"coordinator attached",coordinators:"{{count}} coordinators",workers_one:"{{count}} worker",workers_other:"{{count}} workers",sampledStatus:"sampled status"},legendEdge:{parentBranch:"default branch",cloneLink:"worktree clone",worktreeLink:"same branch",submoduleLink:"submodule",sessionLink:"session",orphanLink:"needs follow-up"},attention:{submoduleDrift:"submodule drift",submoduleDirty:"submodule dirty",conflictsPresent:"conflicts present",dirtyWorkspace:"dirty workspace",upstreamUnverified:"upstream unverified",pushBranch:"push branch",blockedReview:"blocked review",refineFailed:"refine failed",refining:"refining…",needsMerge:"needs merge",refineWorktree:"refine worktree",needsFollowUp:"needs follow-up",offline:"offline",ahead:"ahead {{count}}",behind:"behind {{count}}",aheadBehind:"ahead {{ahead}} / behind {{behind}}"},summary:{anchor:"Default branch anchor",parent:"parent {{label}}",localChanges:"local changes",sessions_one:"{{count}} session",sessions_other:"{{count}} sessions",conflicts:"conflicts",clean:"Clean and even with upstream"},taskDag:{plan:{depsFailed_one:"{{count}} upstream failed",depsFailed_other:"{{count}} upstream failed",openTask:"Open this task"},gate:{holding_one:"holding {{count}} step",holding_other:"holding {{count}} steps",converged:"commits on main",notConverged_one:"{{count}} commits not on main",notConverged_other:"{{count}} commits not on main",deadline:"due {{time}} · then {{onTimeout}}",needsYou:"Needs you"},edge:{conditionMore:"+ more",conditional:"if condition"},time:{now:"just now",minutes_one:"{{count}}m ago",minutes_other:"{{count}}m ago",hours_one:"{{count}}h ago",hours_other:"{{count}}h ago",days_one:"{{count}}d ago",days_other:"{{count}}d ago"},collapsed:{expand:"Click to expand this finished graph",counts:"{{nodes}} steps · {{gates}} gates"},empty:"No tasks yet",waitsOn_one:"waits on {{count}}",waitsOn_other:"waits on {{count}}",blocked:"blocked",missingDeps_one:"{{count}} unknown dep",missingDeps_other:"{{count}} unknown deps",selectedTask:"Selected task",finalSummary:"Final summary",finalSummaryFull:"Show full report",finalSummaryLoading:"Loading final summary…",finalSummaryUnavailable:"Final summary unavailable",statsTasks_one:"{{count}} task",statsTasks_other:"{{count}} tasks",statsEdges_one:"{{count}} dependency",statsEdges_other:"{{count}} dependencies",statsMissions_one:"{{count}} mission",statsMissions_other:"{{count}} missions",statsWaiting_one:"{{count}} waiting",statsWaiting_other:"{{count}} waiting",statsBlocked_one:"{{count}} blocked",statsBlocked_other:"{{count}} blocked",legend:{satisfied:"done",waiting:"waiting",failed:"failed"},hiddenTasks_one:"{{count}} older task hidden",hiddenTasks_other:"{{count}} older tasks hidden",loadMore_one:"Load {{count}} more task",loadMore_other:"Load {{count}} more tasks",predictedSlot:"Predicted next routing slot",predictedSlotPinned:"Pinned to a target node — predicted slot on that node",statsPending:"{{count}} queued",statsAssigned:"{{count}} assigned",jumpToState:"Click to jump to the next card in this state"},obs:{fieldEdgeId:"Link ID",fieldHealthRaw:"Health",fieldNodeId:"Node ID",machineSection:"Machine",behindCount:"{{count}} behind",aheadCount:"{{count}} ahead",healUnavailableHint:"Only a clean checkout that is strictly behind a verified upstream can be updated here.",healHint:"Fast-forward this checkout to its upstream. It has no local changes, so nothing can be lost.",healFailed:"Couldn't update {{label}}: {{reason}}",healDone:"{{label}} is up to date",directionTBShort:"↓",directionLRShort:"→",tabMap:"Map",closeDetailAria:"Close detail panel",layoutDirectionAria:"Graph layout direction",viewAria:"Mesh view",tabOverview:"Overview",tabTasks:"Tasks",planeNeedsDaemon:"Connect to the daemon to view graphs and gates.",panHint:"drag or scroll to pan",headlineFollowUp_one:"{{count}} needs attention",headlineFollowUp_other:"{{count}} need attention",headlineIncomplete:"Some machines not visible",headlineConverged:"All synced",badgeBlocked:"{{count}} blocked",badgeBlockedTitle:"{{count}} blocked review",badgeNotMergeable:"{{count}} not mergeable",badgeNeedMerge_one:"{{count}} needs merge",badgeNeedMerge_other:"{{count}} need merge",badgeCleanupTitle:"{{count}} refine/cleanup",badgeOffline:"{{count}} offline",badgeIncompleteTitle:"{{count}} incomplete peer snapshot",badgeNoGitTitle:"{{count}} no git snapshot",badgeNoSubmodTitle:"{{count}} missing submodule visibility",badgeStaleTitle:"{{count}} stale peer snapshot",badgeActiveQueue:"{{count}} active queue",badgeNodes_one:"{{count}} node",badgeNodes_other:"{{count}} nodes",badgeAttachedChats_one:"{{count}} attached chat",badgeAttachedChats_other:"{{count}} attached chats",legendDirty:"{{count}} dirty",legendOrphan:"{{count}} orphan",legendRecentFailures_one:"{{count}} recent failure",legendRecentFailures_other:"{{count}} recent failures",legendAnchor:"Anchor = default branch",legendPeerLink:"Peer link = same-branch worktree",legendSubmoduleLink:"Submodule link = child checkout",healthRefineFailed:"{{count}} refine failed",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedEdge:"Selected edge",activeSessions:"Active Sessions",queueTasks:"Queue tasks",keyWarning:"Key warning",noResultCode:"No result code returned.",legend:"Legend",checking:"Updating…",heal:"Update",loadingGraph:"Loading graph…",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",connecting:"connecting...",providerUnknown:"provider unknown",directionLRTitle:"Left to right",directionTBTitle:"Top to bottom"},notes:{sectionHint:"Lessons the coordinator keeps between sessions — provider quirks, patterns to avoid, recovery steps.",expired:"expired",neverExpires:"never expires",durable:"durable",expiresIn:"expires {{when}}",tab:"Notes",addTitle:"Add operating note",listTitle:"Operating notes",textPlaceholder:"Record a provider quirk, a pattern to avoid, or a recovery lesson...",categoryLabel:"Category",categoryUncategorized:"Uncategorized",categoryProviderQuirk:"Provider quirk",categoryPatternToAvoid:"Pattern to avoid",categoryRecoveryLesson:"Recovery lesson",add:"Add",edit:"Edit",delete:"Delete",save:"Save",cancel:"Cancel",refresh:"Refresh",loading:"Loading notes...",empty:"No operating notes recorded yet.",unavailable:"Operating notes are unavailable — the coordinator is not reachable over P2P.",loadFailed:"Failed to load operating notes.",saveFailed:"Failed to save the operating note.",deleteFailed:"Failed to delete the operating note.",editFailed:"Failed to update the operating note.",showMore:"Show more",showLess:"Show less",pinned:"pinned"},dialog:{liveUpdatesOn:"Live updates on",liveUpdatesPaused:"Live updates paused — showing the last loaded state",refreshedAt:"Refreshed {{time}}",refreshFailedQuiet:"refresh failed · showing last loaded",refreshTitle:"Refresh live mesh graph",refresh:"Refresh",refreshing:"Refreshing…",loadingStatus:"Loading live mesh status…",noGraph:"No live mesh graph is available for this coordinator yet. Tap the ? above to learn what a Repo Mesh does.",errorNoMeshId:"This coordinator does not expose a live mesh id.",errorUnexpectedPayload:"Couldn't load graph data. Please try again shortly."},health:{statFailed:"Failed",statPending:"Waiting"},blueprint:{schedPrediction:"Prediction",gateActsViaCoordinatorHint:"The coordinator claims and releases this gate — ask it in the coordinator chat.",gateFallback:"gate",readonlyBadge:"read-only",liveQueue:"Live queue",scheduling:"Scheduling preview",schedObservedAt:"as of {{time}}",schedNoNodes:"No routable nodes.",schedQuotaButton:"Quota",schedQuotaButtonTitle:"Per-machine plan quota at a glance",schedNoWinner:"no eligible slot",leaseExpired:"lease expired",emptyGraph:"This graph has no nodes.",gateActsViaCoordinator:"Coordinator-managed",schedNext:"Next up",schedWaiting:"Ready",schedFull:"At capacity",schedFloorExcluded:"Below difficulty",schedQuotaGated:"Quota-gated",schedCapFree:"Free",schedColSlot:"Slot",schedColScore:"Score",schedColQuota:"Quota",schedColParallel:"Parallel",schedColStatus:"Status",schedColMachine:"Machine",schedNextTitle:"Dispatch a task of this difficulty now and this slot takes it",schedTargetWorktreeTitle:"The task would run in this worktree checkout",schedUnpinned:"no pin",schedUnpinnedTitle:"Hypothetical dispatch with no target pin — tasks pinned to a node show their own forecast on their cards",schedPointInTime:"Point-in-time prediction, not a settled assignment: slot capacity can go stale as soon as a slot is claimed or released",schedulingShort:"Scheduling",gate:{release:"Release",abandon:"Abandon",extend24h:"Extend 24h",outcomePassed:"Passed",outcomeFailed:"Failed",evidencePlaceholder:"Evidence (optional)",reasonPlaceholder:"Reason for abandoning this gate",abandonReasonRequired:"A reason is required to abandon a gate.",submitRelease:"Submit release",submitAbandon:"Submit abandon",extendConfirmTitle:'Extend "{{ref}}" by 24 hours?',expiredBadge:"Expired · {{age}} ago",commandUnavailable:"No daemon connection to send this command."},list:{barActive:"Active {{count}}",barBlocked:"Blocked {{count}}",barRecent:"Recent {{count}}",barMissions_one:"{{count}} mission",barMissions_other:"{{count}} missions",sectionRunning:"Running",sectionBlocked:"Blocked",sectionRecent:"Recent",sectionHistory:"History",generating:"generating",approvalNeeded:"approval needed",choiceNeeded:"choice needed",planShow:"plan",planHide:"hide",planTitle:"Show this task's dependency plan",noMission:"No mission",loadMore_one:"Show {{count}} more",loadMore_other:"Show {{count}} more",emptyActive:"Nothing running",blockedByGate:"blocked by: {{ref}}, {{age}}",waitingOn:"waiting on:",waitingOnMore:"+{{count}} more",blockedByDeadDependency:"blocked by failed/cancelled dependency:",chainGroup:"Chain: {{title}}"},graph:{viewSwitchLabel:"Blueprint view",viewList:"List",viewGraph:"Graph",activeOnly:"Active only",activeOnlyTitle:"Hide lanes where everything has finished",hiddenLanes_one:"{{count}} finished lane hidden",hiddenLanes_other:"{{count}} finished lanes hidden",emptyActive:"Nothing running",showFinished:"Show finished lanes",layoutFailed:"Graph layout failed: {{error}}",laneGraph:"Graph {{id}}",laneAdhoc:"Independent tasks",laneCollapse:"Collapse",laneExpand:"Expand",foldCompleted:"Fold completed",unfoldCompleted:"Show completed",foldNode_one:"{{count}} completed",foldNode_other:"{{count}} completed",countRunning_one:"{{count}} running",countRunning_other:"{{count}} running",countGates_one:"{{count}} gate waiting",countGates_other:"{{count}} gates waiting",countDead_one:"{{count}} stuck",countDead_other:"{{count}} stuck",countWaiting_one:"{{count}} waiting",countWaiting_other:"{{count}} waiting",countFailed_one:"{{count}} failed",countFailed_other:"{{count}} failed",countDone_one:"{{count}} done",countDone_other:"{{count}} done",timeRunning:"running {{age}}",timeFinished:"ended {{time}}",timeQueued:"queued {{age}}",deadlineIn:"due in {{age}}",deadlineOverdue:"overdue {{age}}",tooltipTask:"Task: {{id}}",tooltipMission:"Mission: {{id}}",tooltipGraph:"Graph: {{id}} · {{ref}}",tooltipGate:"Gate: {{id}}",tooltipStatus:"Status: {{status}}",deadDirect:"A dependency failed or was cancelled — this task will not start on its own.",deadTransitive:"Something upstream failed or was cancelled — this task will not start on its own.",legendDepends:"depends on",legendGate:"gate",legendRunning:"running",legendDead:"can never start",heldUntil:"until {{time}}",gateDetails:"Open gate details",tone:{pending:"pending",running:"running",completed:"completed",failed:"failed",cancelled:"cancelled",dead:"stuck",plan:"planned",held:"held"},gateTone:{declared:"declared",awaiting:"awaiting",claimed:"claimed",expired:"expired",released:"released",abandoned:"abandoned"}}},page:{title:"Repo Mesh",subtitle:"Multi-workspace orchestration",waitingForDaemon:"Waiting for daemon connection...",observabilitySecondary:"Mesh observability"},list:{nodeCount_other:"{{count}} nodes",nodeCount_one:"{{count}} node",machinesOnline:"{{online}}/{{total}} machines online",settings:"Settings",open:"Open",title:"Repo Meshes",count_one:"{{count}} mesh",count_other:"{{count}} meshes",createMesh:"+ Create Mesh",createTitle:"Create Repo Mesh",createOnMachine:"Create on machine",noConnectedDaemon:"No connected daemon",workspace:"Workspace",workspaceHint:"Choose from workspaces registered by the selected daemon.",selectMachineFirst:"Select a machine first",noRegisteredWorkspaces:"No registered workspaces",name:"Name",remoteUrl:"Repo remote URL (recommended)",remoteUrlHint:"Paste your repo URL — the identity (github.com/user/repo) is filled in automatically.",repoIdentity:"Repo identity",repoIdentityHint:"For a repo with no remote, or when the URL differs per machine. e.g. github.com/user/repo",advancedIdentityToggle:"Advanced: set identity manually",create:"Create",creating:"Creating…",cancel:"Cancel",loading:"Loading meshes...",emptyTitle:"No Repo Meshes",emptyWithDaemons:"Run several coding agents on one repo across your machines.",emptyNoDaemons:"Connect a machine first.",createFirst:"Create First Mesh",noRepoIdentity:"No repo identity",repoMeshFallback:"Repo Mesh"},detail:{useFromCli:"Use from CLI",optionNo:"No",optionYes:"Yes",distributionInOrderSummary:"First available node, in the order added",distributionSmartSummary:"Best-fit node for each task, spread by load",tabGeneral:"General",back:"← Back",delete:"Delete",observabilityOpenTitle:"Open the live view (overview, tasks, map)",observabilityDisabledTitle:"The host machine must be connected first",observabilityOpen:"Open",tabsAriaLabel:"Mesh settings sections",tabAdvanced:"Advanced",quotaBusyFallback:"Quota fallback when busy",quotaBusyFallbackHint:"When the best provider by quota has no free slot, try the next provider with quota on the same node instead of waiting. Never falls back to a provider that is low on quota, and never moves the task to another node.",distribution:"Distribution",distributionSmart:"Smart",distributionSmartDescription:"Match each task to the node whose capability slot fits it best (difficulty + capability tags), then spread by priority and load. Without slots it still spreads work evenly. Recommended when any node has slots.",distributionInOrder:"In order",distributionInOrderDescription:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading.",recommended:"Recommended",saving:"Saving…",visibilityTitle:"Dashboard visibility",visibilityLabel:"Coordinator-spawned worker sessions",visibilityHint:"Hidden = keep the inbox quiet and mute their notifications; you interact through the coordinator session. Visible = show every spawned worker as its own conversation.",visibilityHidden:"Hidden",visibilityVisible:"Visible",magiTitle:"Cross-check reviewers",magiDescription:"MAGI (Multi-Agent Ground-truth Insight) runs a panel of AI agents that cross-check each other's work to surface the ground truth. Choose which agents handle each review type.",coordinatorPromptTitle:"Coordinator prompt",thisMeshHint:"Applies only to coordinator sessions for {{name}}. Leave empty to keep the daemon default.",overrideLabel:"Override (replaces default)",overrideHint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",overridePlaceholder:"(empty — daemon default applies)",appendLabel:"Append (added after the base)",appendHint:"Always added after whichever base prompt wins.",appendPlaceholder:"(empty — nothing appended)",availablePlaceholders:"Available placeholders",placeholdersIntro:"These tokens are replaced when rendering an override or append prompt:",saveCoordinatorPrompt:"Save coordinator prompt",clear:"Clear",clearTitle:"Clear both fields. Click Save to commit.",safetyTitle:"Safety & Git",safetyDescription:"Checkpointing, approval gates, and git safety behavior for coordinator-driven tasks.",checkpointBefore:"Auto-commit a checkpoint before each task",checkpointAfter:"Auto-commit a checkpoint after each task",pushApproval:"Push approval",requireApprovalBeforePush:"Require approval before push",doNotRequireApproval:"Do not require approval",destructiveGitApproval:"Destructive git approval",requireApproval:"Require approval",uncommittedChanges:"When the workspace has uncommitted changes",warnAndContinue:"Warn and continue",blockTask:"Block task",checkpointThenContinue:"Checkpoint then continue",autoPublishSubmodule:"Auto-publish submodule commits (advanced)",requireExplicitApproval:"Require explicit approval",allowRefineryPublish:"Allow Refinery non-force publish",autoFastForward:"Auto fast-forward idle nodes",ffEnabled:"Enabled (catch up online, clean, behind nodes)",ffDisabled:"Disabled",includeRemoteNodes:"Include remote nodes",includeRemoteNodesHint:"Off = only the coordinator's local workspace is auto fast-forwarded.",remoteNo:"No (local workspace only)",remoteYes:"Yes (delegate to remote owning daemons)",detectionMode:"Detection mode",detectionModeHint:"Idle = on a node's idle edge. Continuous = also scan periodically (base nodes only).",idleEdgeOnly:"Idle edge only",continuousScan:"Continuous (periodic scan)",sessionCleanupLabel:"When removing a node, its sessions…",sessionCleanupHint:"Separate transcript cleanup from runtime/process cleanup.",mcpDescription:"· The mesh MCP server can be used directly from your CLI agent.",repoMeshJsonTitle:"From repo file (read-only)",repoMeshJsonHint:"This repo commits coordinator prompt text that stacks with the fields above. Edit it in the repo file, not here:",repoMeshJsonOverrideLabel:"Repo override",repoMeshJsonAppendLabel:"Repo append",repoMeshJsonInvalid:"This repo's .adhdev/mesh.json could not be parsed, so its prompt layer is ignored."},nodeList:{advanced:"Advanced",launchBlockedChip:"No provider detected",usesTools:"Uses {{tools}}",addingIsExplicit:"Adding it is still up to you.",compatibleWorkspace:"Compatible Git workspace detected.",inspectingRepo:"Inspecting the Git repository (read-only)…",title:"Nodes & Providers ({{count}})",descriptionCloud:"Workspaces in this mesh and their preferred AI tools.",descriptionStandalone:"Workspaces participating in this mesh and their preferred AI tools.",daemonCandidates:"Machine daemon candidates",available:"{{count}} available",noDaemonsAvailable:"No connected machine daemons are currently available.",allDaemonsAttached:"All connected machine daemons are already attached.",selectedHost:"selected host",attachMachine:"Attach machine",addNode:"Add node",attachMachineTitle:"Attach Machine Daemon",addNodeTitle:"Add Node",machine:"Machine",selectMachine:"Select a machine...",workspacePath:"Workspace Path",enterCustomPath:"Or enter a custom path →",preferredTools:"Preferred AI tools (in order)",preferredToolsHint:"Order used when launching without an explicit provider.",add:"Add",cancel:"Cancel",emptyTitle:"No nodes",emptyDescription:"Add a workspace to this mesh.",slotsLabel:"Preferred AI tools (capability slots)",slotsHint:"Each slot = provider + model + thinking + the task difficulty/capability it handles + a per-slot parallel cap. Tasks are matched to the best-fit slot (order = preference). With no slots, this node uses its legacy provider order.",nodeInstruction:"Node instruction (optional)",nodeInstructionHint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",nodeInstructionPlaceholder:"e.g. 'Run only smoke tests here', 'Use opus on this node'",saveInstruction:"Save instruction",saving:"Saving…",removeNode:"Remove node",nodeId:"Node ID:",repoRoot:"Repo root:",activeSessionsLabel:"Active sessions:",added:"Added:",activeQueueAssignments:"Active queue assignments",noActiveAssignment:"No active assigned queue task for this node.",activeSessions:"Active sessions",launchBlocked:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)",titleNoCount:"Nodes & Providers",workspacesDetected:"{{count}} workspace(s) detected",pickFromSaved:"← Pick from saved workspaces",ownerMachine:"Owner: {{owner}} · Machine: {{machine}}",machineTabsLabel:"Machines in this mesh",machineTabCounts:"{{nodes}} node(s) · {{slots}} slot(s)"},host:{setHostConfirmTitle:"Set {{name}} as the host?",setupNode:"setup node",willHostOn:"Will host on",coordinatorProvider:"Coordinator CLI provider",coordinatorProviderHint:"Tool launched for the host coordinator session.",useNodePriority:"Use node provider priority",title:"Host machine",descriptionSet:"The machine that runs this mesh's coordinator. It is set once and not changed here.",descriptionUnset:"Choose the machine that will run this mesh's coordinator.",hostLabel:"Host:",hostNode:"Host node:",unknown:"Unknown",hostOffline:"Host offline",hostOfflineText:"Live status won't load until the host reconnects. Meanwhile you can send commands through another connected machine — this doesn't change the host.",reconnectToCommand:"Reconnect to command",reconnectToCommandHint:"Route commands through this connected daemon until the host is back. Does not change the mesh host.",waitForHost:"Wait for host to reconnect",noDaemonsToRoute:"No connected daemons available to route commands through. Bring the host (or another daemon) online.",launching:"Launching...",launchHost:"Launch Host Coordinator",setHostBanner:"Choose a host machine",hostDaemon:"Host daemon",hostDaemonHint:'Pick the daemon that will host this mesh, then confirm with "Set as host".',resolvingHost:"Resolving host… (or pick a daemon to host)",launchHostSetsHost:"Launch Host Coordinator",noDaemonsToHost:"No connected daemons. Bring a daemon online to host this mesh.",online:"online",offline:"offline",noCommandTarget:"No command target available — bring the host or a daemon online.",pickHostFirst:"Pick a host daemon (or wait for the host pin to resolve) first.",attachNodeFirst:"Attach a workspace from this daemon as a node first.",setHostAction:"Set as host",settingHost:"Setting host…",setHostActionHint:"Pins this daemon as the mesh host. Effectively permanent — it is not reassigned from here afterwards.",confirmSetsHost:"Confirm below to set it as the mesh host.",attachNodeThenSetHost:"Attach one of its workspaces as a node first, then set it as the host."},slotEditor:{emptyHint:"Without slots this node still runs tasks using its provider order. Add a slot to send specific task difficulties or capabilities to a specific tool.",empty:"No slots (optional)",moveUp:"Move up",moveDown:"Move down",removeSlot:"Remove slot",provider:"Provider",select:"(select)",model:"Model",providerDefault:"(provider default)",custom:"Custom…",modelPlaceholder:"model",backToModelList:"← Back to model list",thinking:"Thinking",thinkingDefault:"(default)",difficulty:"Difficulty (blank = freeform tasks only)",capabilityTags:"Capability tags (comma-separated)",maxParallel:"Max parallel (per slot)",maxParallelPlaceholder:"unlimited",addSlot:"Add slot",saving:"Saving…",saveSlots:"Save slots"},tagEditor:{emptyHint:"Tasks can run here without matching any specific tag. Add tags to target this node from a task's required tags.",noSpaces:"Tags cannot contain spaces.",reservedPrefix:"That prefix is auto-derived — pick a different tag.",alreadyAdded:"Already added.",routingTags:"Routing tags",autoDerivedTitle:"Auto-derived — can't be edited",customTagTitle:"Custom tag",remove:"Remove {{tag}}",addPlaceholder:"add a custom tag (e.g. test-runner)",add:"Add",saving:"Saving…",saveTags:"Save tags",empty:"No tags (optional)"},queue:{title:"Queue",description:"Inspect active queue work separately from historical completed, failed, and cancelled task records.",statActive:"Active",statPending:"Pending",statAssigned:"Assigned",statStale:"Stale",statHistorical:"Historical",statCompleted:"Completed",statFailed:"Failed",loading:"Loading...",refresh:"Refresh Queue",refreshHint:"Refresh the queue to view host-owned task counts and recent assignments.",empty:"Queue is empty.",staleBadge:"stale",staleTitle:"Stale assignment",waitingOnTitle:"Waiting on: {{tasks}}",waitsOn_one:"waits on {{count}} task",waitsOn_other:"waits on {{count}} tasks",blocked:"blocked",durationTitle:"Dispatched → terminal wall clock",retry_one:" · {{count}} retry",retry_other:" · {{count}} retries",node:"node {{id}}",session:"session {{id}}"},promptPreview:{connectPrompt:"Connect a daemon to preview the default.",errorRender:"Failed to render the default prompt",hide:"Hide the default prompt",view:"View the default prompt",rendering:"Rendering…",retry:"Retry",info:"This is what a coordinator session gets when Override is empty.",launchScopeNote:"Mission, recent activity and operating notes are added at launch and are not shown here."},hermesMcp:{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",fallbackProvider:"Hermes CLI"},providerAutoApprove:{partialInventoryChip_other:"{{count}} nodes pending",partialInventoryChip_one:"{{count}} node pending",title:"Provider auto-approve defaults",loading:"Loading provider defaults…",loadError:"Failed to load provider auto-approve defaults.",noProviders:"No CLI providers with auto-approve modes detected on this mesh's machines.",awaitingNodes:"Waiting for {{count}} node(s) to report their installed providers…",partialInventory:"Provider list may be incomplete — {{count}} node(s) have not reported yet.",noHostDaemon:"Connect the mesh host daemon to configure provider auto-approve defaults.",repoSection:{chip:"Shared with team",title:"Repository default",hint:"Committed to .adhdev/mesh.json — shared with the whole team. Sets which mode a delegated worker requests; it does not grant permission to run it.",usesProviderDefault:"Uses provider default",clear:"Use provider default"},machineSection:{chip:"This machine only",title:"This machine authorization",hint:"Local only (meshes.json) — never committed. Controls whether workers on THIS machine auto-approve at all, and whether dangerous modes are allowed.",autoApproveToggleLabel:"Delegated worker auto-approve",autoApproveToggleHint:"When off, workers delegated to this machine stop at every approval prompt.",dangerousToggleLabel:"Allow dangerous modes on this machine",dangerousToggleHint:"Opt-in: workers on this machine may run dangerous modes that execute tools with no approval at all.",dangerousDisabledHint:"No effect while auto-approve above is off.",confirmTitle:"Opt in to dangerous modes",confirmDescription:"This allows delegated workers on this machine to run dangerous provider modes. In a dangerous mode the agent executes tools and commands with no approval prompts at all.",confirmScopeLabel:"Scope",confirmScopeValue:"This machine only (local meshes.json — never committed)",confirmEffectLabel:"Effect",confirmEffectValue:"Repo-requested dangerous modes (e.g. Force, fully autonomous) are no longer downgraded to a safer interactive mode on this machine.",confirmConfirm:"Opt in"},effectiveSection:{statusDowngradedHint:"{{requested}} was requested, but this machine hasn't allowed dangerous modes, so it runs {{mode}}.",statusRequested:"Runs: {{mode}}",statusInvalidFallback:"Requested mode not found → runs provider default: {{mode}}",statusDowngraded:"{{mode}} (downgraded)",statusDisabled:"Auto-approve disabled on this machine — worker will ask for approval.",statusNone:"No usable auto-approve mode — worker will ask for approval."},dangerous:{sharedWarningDetail:"Saved in .adhdev/mesh.json. Each machine runs it only after opting in (delegatedWorkerDangerousModeAllow).",sharedWarningTitle:"This is committed to the repository",sharedWarning:"Committed to the repo and shared with your team. Machines that haven't allowed dangerous modes run a safer mode instead."},saving:"Saving…",saved:"Saved to .adhdev/mesh.json",saveError:"Failed to save provider defaults."},graphs:{includeTerminal:"Include finished",loading:"Loading graphs…",shown_one:"{{count}} graph shown",shown_other:"{{count}} graphs shown",loadMore_one:"Load {{count}} more graph",loadMore_other:"Load {{count}} more graphs",serverLimitHidden_one:"{{count}} older graph hidden · maximum 100",serverLimitHidden_other:"{{count}} older graphs hidden · maximum 100",serverLimitReached:"The daemon returns at most 100 graphs."},status:{healthErrorChip:"Error",offlineMachinesTitle:"Not reporting: {{machines}}",badgeBootstrap:"Setting up",badgeUpdatePending:"Update pending",quotaClaudeRefreshChip:"Needs refresh",quotaClaudeSetupChip:"Set up",machineNotReportingHint:"We haven't heard from this machine, so its plan quota is unknown.",quotaNotCollectedHint:"A machine reports its plan quota after its first refresh (about 15 minutes) and only while an agent has been active.",schedulingNotReportedHint:"This machine runs an older version that doesn't report scheduling details.",schedulingNotReported:"Update the daemon to see scheduling",schedulingTitle:"Scheduling",distributionTitle:"Distribution decides how work without a target is spread across nodes. Per-node load and limits are listed below.",protocolTitle:"Protocol & provider versions",noNodesReporting:"No nodes reporting runtime yet.",quotaNotCollected:"No quota yet",quotaFreshnessHint:"Last updated",machineNotReporting:"Offline · quota unknown",quotaClaudeSetupHint:"Set up Claude quota with `adhdev quota claude:install`.",quotaClaudeRefreshHint:"Open a Claude Code session once to refresh quota.",quotaAccountHint:"The signed-in account this quota belongs to, as reported by the provider CLI",quotaOkNoWindows:"No limit",healthNotGitRepo:"Not a git repo",healthProbePending:"Checking…",healthPeerConnection:"Connection {{state}}",healthNoLiveReport:"No report yet",badgeWorktree:"worktree",badgeWorktreeTitle:"Local worktree node",badgeWorktreeBranchTitle:"Worktree branch {{branch}}",badgeBootstrapTitle:"Worktree bootstrap is still in progress",badgeConnectionTitle:"Mesh peer connection state",badgeSessions_one:"{{count}} session",badgeSessions_other:"{{count}} sessions",badgeFastForwardReady:"fast-forward ready",badgeFastForwardReadyTitle:"Clean, behind upstream — safe for fast-forward",badgeStaleBuildTitle:"Live daemon was built behind workspace HEAD — merged fixes may not be live",badgeDeployLagTitle:"Running daemon build commit differs from origin/main — deploy + restart pending for this node",machinesNotReporting_one:"{{count}} offline",machinesNotReporting_other:"{{count}} offline",machinesSection:"Machines — plan · nodes",versionSkewTitle:"Version differs from this machine’s consensus (stale report or partial install)",machineVersionsTitle:"Provider CLI versions installed on this machine — shared by all its nodes"},overview:{tasksCount_other:"{{count}} tasks",tasksCount_one:"{{count}} task",sessionCount_other:"{{count}} sessions",sessionCount_one:"{{count}} session",leaseExpired:"lease expired",providerUnknown:"provider unknown",truncated:"(truncated)",missionCard:"Missions",ledgerCard:"Activity",queueCard:"Queue",nodesCard:"Nodes",sessionsCard:"Active sessions",refineCard:"Refine jobs",recentActivity:"Recent activity",recentTasks:"Recent tasks",missionTasksHeading:"Mission tasks",showFewer:"Show fewer",showMore:"+{{count}} more",noActiveMissions:"No active missions",missionDataUnavailable:"Update the daemon to see missions",completedHistory:"Completed / abandoned history",noQueueActivity:"No queue activity.",noNodes:"No nodes in this mesh yet.",noActiveSessions:"No active sessions.",noRefineJobs:"No refine jobs.",closeDetail:"Close detail",loadingGoal:"Loading…",showFullGoal:"Show full goal",statCompleted:"Completed",statAssigned:"Assigned",statPending:"Pending",statFailed:"Failed",statBlocked:"Blocked",statCancelled:"Cancelled",statWallClock:"Wall clock",statTotalRuntime:"Total runtime",statRetries:"Retries",statDispatched:"Dispatched",statStalled:"Stalled",statSessions:"Sessions",statCheckpoints:"Checkpoints",statActive:"Active",statPaused:"Paused",statAbandoned:"Abandoned",recentFailures:"{{count}} recent failures",activeCount:"{{count}} active",failedCount:"{{count}} failed",detailKickerMission:"Mission",detailKickerLedger:"Ledger entry",detailKickerQueue:"Queue task",detailKickerSession:"Session",detailKickerGate:"Gate",detailLabelGraph:"Graph",detailLabelRef:"Step",detailLabelOutcome:"Outcome",detailLabelMissionId:"Mission id",detailLabelCreated:"Created",detailLabelUpdated:"Updated",detailLabelElapsed:"Elapsed",detailLabelFullInstruction:"Show full instruction",detailLabelLastActivity:"Last task activity",detailLabelIncompleteEvidence:"Incomplete evidence",incompleteTaskCount_one:"{{count}} task",incompleteTaskCount_other:"{{count}} tasks",detailLabelEntryId:"Entry id",detailLabelWhen:"When",detailLabelNode:"Node",detailLabelDependsOn:"Depends on",detailLabelSession:"Session",detailLabelProvider:"Provider",detailLabelPayload:"Show raw payload",detailLabelTaskId:"Task id",detailLabelFinalSummary:"Final summary",detailLabelFullFinalSummary:"Show full report",detailFinalSummaryLoading:"Loading final summary…",detailFinalSummaryUnavailable:"Final summary unavailable",detailLabelAutoLaunch:"Auto launch",detailLabelCancelReason:"Cancel reason",detailLabelRequeueReason:"Requeue reason",detailLabelRequeued:"requeued {{count}}",detailLabelSessionId:"Session id",detailLabelBranch:"Branch",detailLabelRole:"Role",detailLabelStarted:"Started",detailLabelWorkspace:"Workspace",routingHeading:"Routing",routingDevice:"Device",routingDaemon:"Daemon",routingExecution:"Execution",routingVia:"Via",routingDifficulty:"Difficulty",routingFitness:"Fitness",routingReason:"Reason",routingRequiredTags:"Required tags",routingTagsUnsatisfied:"unsatisfied",routingSkipped:"Skipped candidates",routingSkippedMore:"+{{count}} more",pausedMissions:"Paused missions",ledgerAllTime:"all-time totals",detailLabelGateAfter:"After",detailLabelGateUnlocks:"Unlocks",sessionTasksHeading:"Tasks in this session",showOnCanvas:"Show on canvas"}},vk={showMoreChars:"Show more ({{count}} characters)",collapse:"Collapse",you:"You",toolMessageAria:"Tool message",activityMessageAria:"Activity message",activityFallback:"Activity",copyMessage:"Copy message",copyCode:"Copy code",showMore:"Show more",showLess:"Show less",thought:"Thought",toolExpand:"Show full output",toolCollapse:"Show less",toolExpandLoading:"Loading…",toolExpandUnavailable:"Full output could not be fetched for this step.",toolExpandStale:"Full output has moved — the transcript changed since this was read. Reload the conversation to fetch it.",waitingToSend:"Waiting to send — the agent is still working.",waitingToSendAria:"Waiting to send",notDelivered:"Not delivered — the agent never received this.",notDeliveredAria:"Not delivered",sendNow:"Send now",sending:"Sending…",sendNowAria:"Send now to the agent's queue, without interrupting its current turn",sendNowTitle:"Send this message to the agent now. It goes into the agent's own queue and is answered next — the turn in progress keeps running.",cancelQueued:"Cancel",cancelQueuedAria:"Cancel this queued message",cancelQueuedTitle:"Remove this message from the queue. It will not be sent to the agent."},wk={debugBundleFailed:"Couldn't collect debug info",replicaDegradedShort:"Sync degraded",connectingToMachine:"Connecting to your machine",establishingP2P:"Establishing P2P connection",agentNotMonitored:"Agent not monitored",clickToSwitchMonitoring:"Click to switch monitoring to this agent",agentPanelHidden:"Agent panel is not visible yet",openPanelHint:"Open the chat in your IDE",noMessagesYet:"No messages yet",loadingChat:"Loading chat...",openPanel:"Open {{label}} Panel",switchingPanel:"Switching...",openingPanel:"Opening...",replicaDegraded:"Live sync is having trouble — showing messages the previous way",busyNoProgress:"Agent shows no progress.",busyGenerating:"Agent is generating.",busyWaitingApproval:"Waiting for approval",activityToggleLabel:"Tool steps",activityToggleTitle:"Show tool, terminal and thinking steps",reconnectMachine:"Reconnect",reconnectingMachine:"Reconnecting…",reconnectMachineTitle:"Automatic reconnection gave up on this machine — reconnect now"},Sk={addMessageOptional:"Add a message (optional)…",showControls:"Show controls",hideControls:"Hide controls",sendTo:"Send message to {{panel}}",attachImage:"Attach image",placeholder:"Send message to {{panel}}...",sendMessage:"Send message",dropImage:"Drop image here"},kk={cdpDisconnectedShort:"IDE disconnected",hideFromDashboard:"Hide from dashboard",removeShortcut:"Remove shortcut",changeShortcut:"Change shortcut ({{shortcut}})",dropSplitRight:"Split right",dropMoveHere:"Move here",dropSplitLeft:"Split left",relaunchWithCdp:"Relaunch with connection",cdpDisconnected:"Not connected to the IDE — chat history and screenshots are unavailable.",resizeHandleHint:"Drag to resize · Double-click to merge",shortcutListening:"Listening…",shortcutPressCombo:"Press a key combination (e.g. {{example1}}, {{example2}})",shortcutSetTitle:"Set shortcut",loadingSessions:"Loading sessions...",noConversations:"No conversations yet",waitingForDaemon:"Waiting for your daemon",connectYourMachines:"Connect your machines",daemonDescription:"Start the ADHDev daemon to connect.",installDescription:"Install ADHDev on a machine and sign in.",newSession:"New session",newSessionDescription:"Start a session with any installed agent.",noTabsInGroup:"No tabs in this group",pressEscToCancel:"Press Esc to cancel",noActiveAgent:"No active agent",moveTabHere:"Move a tab here to view"},jk={growViewport:"Enlarge terminal view",shrinkViewport:"Shrink terminal view",sendInterrupt:"Send interrupt (Ctrl-C)",arrowRight:"Arrow right",arrowDown:"Arrow down",arrowLeft:"Arrow left",arrowUp:"Arrow up",keysPanelTitle:"Terminal keys",keysButton:"Keys",copyHint:"Copy the selected terminal text, or the visible screen if nothing is selected",specDebugHint:"Spec debug — inspect current state, sections, and transition history",replayScrollbackHint:"Load earlier terminal output so you can scroll farther up",loadOlderOutput:"Load older terminal output",loadingOlder:"Loading older...",debug:"Debug",copy:"Copy",openControlKeys:"Open terminal control keys",closeControlKeys:"Close terminal control keys"},Nk={muteThis:"Mute this chat",unmuteThis:"Unmute this chat"},Ck={switchToTerminal:"Switch to Terminal view",switchToChat:"Switch to Chat view"},_k={updatedAt:"Updated {{time}}",messageCountShort_other:"{{count}} msgs",messageCountShort_one:"{{count}} msg",workspaceUnknown:"Workspace unknown",clearSelection:"Clear",selectedSavedHistory:"Selected saved history",loadingShort:"Loading…",savedHistoryNoneYet:"No saved history",savedHistoryLoadedCount_other:"{{count}} saved histories loaded. Open saved history to choose one.",savedHistoryLoadedCount_one:"{{count}} saved history loaded. Open saved history to choose one.",savedHistoryBadge:"Saved history",resumeSavedHistory:"Resume saved history",startFresh:"Start fresh",resumingSavedHistory:"Resuming saved history…",startingFresh:"Starting fresh…",startIde:"Start IDE",startingIde:"Starting IDE…",startAcpSession:"Start ACP session",startingAcpSession:"Starting ACP session…",recoverHostedRuntime:"Recover hosted runtime",hostedRuntimeRecoveryDescription:"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead.",openSavedHistory:"Open saved history",savedHistoryTitle:"Saved History",savedHistoryHelper:"Use saved history when you want continuity in the same provider conversation.",savedHistoryEmpty:"No saved history found yet.",refreshSavedHistory:"Refresh saved history",refreshingSavedHistory:"Refreshing saved history…",startFreshWith:"Start fresh with {{label}}?",restart:"Restart {{label}}?",startFreshReview:"Review the provider and target folder before starting fresh.",restartIdeReview:"Review or change the target workspace before restarting this IDE.",restartStoppedReview:"Review or change the target workspace before restarting this stopped session.",confirmStartFresh:"Start fresh",confirmRestart:"Restart",confirmStartingFresh:"Starting fresh…",confirmRestarting:"Restarting…",resumeWith:"Resume saved history with {{label}}?",resumeReview:"Review or change the target workspace before resuming saved history."},Ak={layout:{expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse"},auth:{loading:"Loading standalone dashboard…",loadError:"Failed to load standalone auth status: {{error}}",signInTitle:"Standalone sign-in",passwordProtected:"This self-hosted dashboard is protected by a local password.",tokenProtected:"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session.",passwordPlaceholder:"Enter standalone password",unlock:"Unlock dashboard",signingIn:"Signing in…",noPasswordEnabled:"Password login is not enabled on this server."},machine:{loading:"Loading machine...",awaitingInput:"Awaiting your input ↑"},settings:{restartToApply:"Restart to apply",providersLink:"Providers",providersIntro:"IDEs and agents on this machine:",title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",publicHostWarning:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token.",daemonSection:"Daemon",versionLabel:"Version",statusLabel:"Status",statusRunning:"● Running",statusNotConnected:"○ Not connected",authLabel:"Auth",authPassword:"Password enabled",authToken:"Token enabled",authNone:"No auth configured",networkSection:"Network Access",networkHint:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token.",localhostLabel:"Localhost only",localhostHint:"Bind to 127.0.0.1. Best when only this machine should open the dashboard.",allInterfacesLabel:"All interfaces",allInterfacesHint:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points.",saveNetworkMode:"Save default network mode",saving:"Saving…",networkRestartHint:"Applies on next standalone restart. Current run stays bound to {{host}}.",networkSavedAll:"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.",networkSavedLocal:"Default standalone network mode set to localhost only. Restart standalone to apply it.",securitySection:"Dashboard Security",passwordSet:"A local password is currently required for browser access. Existing sessions are rotated when you change it.",passwordNotSet:"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended.",currentPasswordPlaceholder:"Current password",currentPasswordFirstTimePlaceholder:"Current password (not needed for first setup)",newPasswordPlaceholder:"New password",newPasswordFirstTimePlaceholder:"New standalone password",confirmPasswordPlaceholder:"Confirm new password",updatePassword:"Update password",enablePassword:"Enable password",disablePassword:"Disable password",passwordUpdated:"Standalone password updated.",passwordEnabled:"Standalone password enabled.",passwordDisabled:"Standalone password disabled.",passwordTooShort:"Password must be at least 4 characters.",passwordMismatch:"New password and confirmation do not match.",appearanceSection:"Appearance",fontsLabel:"Fonts",fontsDescription:"Standalone-only typography overrides for chat text, markdown code, and terminal output.",fontsSaved:"Standalone chat fonts saved for this self-hosted dashboard.",profileSection:"Profile",displayNameLabel:"Display Name",displayNameHint:"Your name shown in chat threads and on the team dashboard.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Welcome to ADHDev",selectedCount_one:"{{count}} provider selected",selectedCount_other:"{{count}} providers selected",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",intro:"Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from Machines → Providers.",loadingRegistry:"Loading registry…",loadError:"Failed to load registry: {{error}}",noProviders:"No providers in this category.",installed:"✓ installed",installFailed:"✗ {{error}}"},about:{title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",selfHostedEdition:"Self-hosted edition",headline:"Keep the same dashboard experience, with the runtime fully on-device.",description:"Standalone keeps the browser, daemon, screenshots, and control path entirely on your own machine. Aside from multi-machine connectivity and mobile notifications, it is the same core product experience as Cloud.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Try Cloud ↗",includedSection:"Included in standalone",includedDescription:"The local-first feature set available without the cloud control plane.",inventorySection:"Built-in inventory",inventoryDescription:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",cloudExtrasSection:"Cloud-only extras",cloudExtrasDescription:"Capabilities that need the hosted control plane or team infrastructure.",comparisonSection:"Self-hosted vs Cloud",comparisonDescription:"The product split at a glance.",featureHeader:"Feature",selfhostHeader:"Selfhost",cloudHeader:"Cloud",cloudOptional:"Cloud is optional, not required",cloudOptionalDescription:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",compareCloud:"Compare Cloud ↗",discord:"Discord ↗",features:{localFirst:{title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},chatRelay:{title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},screenshots:{title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},remoteControl:{title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},multiIde:{title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},cliAcp:{title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}},extras:{anywhere:{title:"Access from anywhere",desc:"Reach your machines from another laptop or phone without opening local ports."},p2pStream:{title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},mobileNotifications:{title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},restApi:{title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},teamWorkspace:{title:"Team workspace",desc:"Share machines, activity views, and policies across a team workspace."},enterpriseControls:{title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}},comparison:{chatRelay:"Agent chat relay",screenshots:"Live IDE screenshots",remoteControl:"Remote IDE control",multiIde:"Multi-IDE monitoring",extensionCli:"Extension and CLI agents",anyNetwork:"Access from any network",webrtc:"WebRTC P2P streaming",mobilePush:"Mobile push notifications",restApi:"REST API and webhooks",teamCollaboration:"Team collaboration",multiMachineDashboards:"Multi-machine dashboards",ssoRbacAuditLogs:"SSO, RBAC, audit logs"}},fonts:{fontOverridesNotice:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below.",chat:"Chat text",chatDescription:"Assistant/user prose, markdown text, thought cards, and system notes.",code:"Code blocks",codeDescription:"Markdown code fences, inline code, and preformatted command output.",terminal:"Terminal",terminalDescription:"Terminal transcript cards and tool/command rows in chat mode.",livePreview:"Live preview",resolvedStack:"Resolved stack:",saveFontSettings:"Save font settings",revertToSaved:"Revert to saved",resetToDefaults:"Reset to defaults",saving:"Saving…",customFamilyPlaceholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',previewSummary:"Chat: {{chat}} · Code: {{code}} · Terminal: {{terminal}}",defaultsSummary:"Defaults: {{chat}} / {{code}}",previewNow:"now",previewProse:"Readable prose, <strong>bold text</strong>, and <code>inline code</code> should all follow your standalone font choices.",presets:{default:"Default",defaultMono:"Default mono",custom:"Custom…",serif:"Serif"}}},Tk={login:{eyebrow:"Cloud sign-in",title:"Sign in to ADHDev",subtitle:"Connect your machines, get approval and completion notifications, and keep your coding agents moving when you are away from your desk.",continueWith:"Continue with {{provider}}",connecting:"Connecting...",devDivider:"dev",devLogin:"Dev Login (test_jwt_token)",providerNote:"GitHub and Google are used only for authentication.",errorUnverifiedEmail:"This login provider did not return a verified email, so we could not safely sign you in.",termsPrefix:"By continuing, you agree to our ",termsLink:"Terms of Service",termsAnd:" and ",privacyLink:"Privacy Policy",termsSuffix:"."},account:{openMachines:"Open Machines",machinesSummaryShort:"{{count}} of {{limit}}",title:"Account",subtitle:"Profile, plan & activity",tabAccount:"Account",tabBilling:"Billing",tabActivity:"Activity",profile:"Profile",noName:"No name",displayName:"Display Name",displayNameDesc:"Your name shown in the dashboard and team workspaces.",nicknamePlaceholder:"Nickname",save:"Save",saving:"...",cancel:"Cancel",saved:"Saved",edit:"Edit",failedToSave:"Failed to save",userId:"User ID",loadingProfile:"Loading profile...",planLimits:"Plan limits",limitMachines:"Machines",limitP2P:"Connected machines",limitPushNotifications:"Daily Push Notifications",limitTurnRelay:"Relay fallback",enabled:"Enabled",disabled:"Disabled",frozen:"Frozen",session:"Session",logout:"Logout",logoutDesc:"Sign out of your ADHDev account on this device.",dangerZone:"Danger zone",dangerZoneDesc:"Permanently delete your account and all associated data. This action cannot be undone.",deleteAccount:"Delete account",deleteWillRemove:"This will permanently delete:",deleteItemProfile:"Your profile and login credentials",deleteItemKeys:"All API keys and connection tokens",deleteItemWebhooks:"Webhooks and delivery history",deleteItemPush:"Push notification subscriptions",deleteItemSessions:"Shared sessions and audit logs",deleteTypeConfirm:"Type {{keyword}} to confirm:",deleting:"Deleting...",permanentlyDelete:"Permanently delete",failedToDeleteAccount:"Failed to delete account",registeredMachines:"Registered Machines",machinesSummary:"{{count}} registered · {{online}} online",machinesLimit:"(limit: {{limit}})",loadingMachines:"Loading machines...",noMachinesRegistered:"No machines registered",runSetupPrefix:"Run ",runSetupMiddle:", then start ",runSetupSuffix:" on a machine to register it here.",removeMachineConfirm:"Remove this machine? It will need to run `adhdev setup` again to reconnect.",failedToDeleteMachine:"Failed to delete machine",failedToUpdate:"Failed to update",rename:"Rename",online:"Online",connecting:"Connecting",removeMachine:"Remove machine",never:"Never",frozenFeatureTitle:"Frozen — this feature is paused and not available."},billing:{currentPlan:"Current Plan:",statusTrial:"Trial",statusActive:"Active",statusPastDue:"Past Due",statusCanceled:"Canceled",nextBilling:"Next billing: {{date}}",trialEnds:"Trial ends: {{date}}",accessUntil:"Access until: {{date}}",updatePayment:"Please update your payment method",managePayment:"Manage Payment & Invoices",couldNotOpenPortal:"Could not open billing portal",checkoutSuccess:"Your subscription is active. Thanks for upgrading!",statMachines:"Machines",statSharedSessions:"Shared Sessions",statTurnRelay:"TURN Relay",statTurnOn:"On",resetsDailyUtc:"Resets daily at 00:00 UTC",resetsInHours_one:"~{{count}}h left",resetsInHours_other:"~{{count}}h left",resetsInMinutes_one:"~{{count}}m left",resetsInMinutes_other:"~{{count}}m left",resetsDailyUtcWithLeft:"Resets daily at 00:00 UTC · {{left}}",monthly:"Monthly",yearly:"Yearly",savePercent:"Save up to {{pct}}% yearly",pricesInUsd:"All prices in USD",paddleLoading:"Paddle is loading, please try again.",cancelConfirm:"Are you sure you want to cancel your subscription? You will retain access until the end of your billing period.",cancelSubscription:"Cancel Subscription",cancelRetainAccess:"You will retain access to {{plan}} features until the end of your current billing period.",cancelTeamDowngrade:" All team members will be downgraded to their personal plans.",cancelFailed:"Failed to cancel subscription"},about:{title:"About",subtitle:"Cloud overview, supported surfaces, and plan-level capabilities",cloudEdition:"Cloud edition",heroTitle:"Control your local CLI agents from anywhere — web or mobile.",heroDesc:"ADHDev Cloud surfaces the agents running on your machines in your browser: send prompts, approve actions, orchestrate work across machines, and get notified on your phone — code flows P2P directly to your daemon, never through the server.",openDashboard:"Open Dashboard",viewMachines:"View Machines",docs:"Docs ↗",whyTitle:"Why ADHDev Cloud",whyDesc:"Core capabilities available when your machines are connected through the cloud control plane.",howTitle:"How it works",howDesc:"The cloud onboarding path from install to remote control.",repoMeshTitle:"Repo Mesh",repoMeshDesc:"Orchestrate agents across machines — cloud only.",meshCard1Title:"One coordinator, many agents",meshCard1Desc:"Enqueue tasks against a mission and let idle nodes claim work from a local-first, pull-based queue. Fan out across machines and providers — Claude Code on one, Codex on another — then converge the results from a single coordinator session.",meshCard2Title:"Same repo, many machines at once",meshCard2Desc:"Each node is a checkout or an isolated git worktree, so parallel agents never collide. The refinery converges every branch — validate, merge, push, clean up — with safe submodule handling. Runs over a direct daemon-to-daemon P2P channel; the server only signals and authorizes same-account peers.",worksWith:"Works with",worksWithDesc:"Supported CLI agents, IDEs, and AI extensions.",groupCli:"CLI Agents",groupIdes:"IDEs",groupExtensions:"AI Agents",pricingTitle:"Pricing",pricingDesc:"Current cloud plans and machine capacity by tier.",planPopular:"Popular",readyTitle:"Ready to connect a machine",readyDesc:"Jump into your dashboard, inspect your connected machines, or continue in the docs if you are still setting up.",dashboard:"Dashboard",machines:"Machines",discord:"Discord ↗",github:"GitHub ↗",features:{webControlTitle:"Web control of local CLI agents",webControlDesc:"Drive any local CLI agent — Claude Code, Codex, Cursor CLI — from your browser: send prompts, approve actions, and steer sessions without touching the terminal.",chatRelayTitle:"Agent chat relay",chatRelayDesc:"Read and respond to agent conversations from anywhere, including mobile surfaces.",liveViewTitle:"Live session view",liveViewDesc:"Watch agent activity in real time; for IDE sessions, view and control the screen over P2P without switching windows.",mobileTitle:"Mobile-ready",mobileDesc:"Receive approvals and check progress while away from your development machine.",secureTitle:"Secure by default",secureDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC — the cloud handles auth and signaling metadata only. Your code never routes through the server."},steps:{step1Title:"One-line Install",step1Desc:"Run a single command on any machine you want to drive. It installs the ADHDev daemon plus the adhdev CLI.",step2Title:"Sign In",step2Desc:"Sign in with GitHub or Google and the daemon pairs itself to your account — no token to copy.",step3Title:"Drive Your Agents from Anywhere",step3Desc:"The machine appears in your dashboard instantly. Launch and control Claude Code, Codex, Cursor CLI, and other CLI agents from the web — IDE sessions too."},plans:{freeName:"Free",proName:"Pro",ultraName:"Ultra",freePer:"/mo",proPer:"/mo",ultraPer:"/mo",freeFeature1:"1 machine",freeFeature2:"Real-time chat relay",freeFeature3:"Web control for your local agents",proFeature1:"2 machines",proFeature2:"Unlimited AI agents",proFeature3:"P2P remote view",ultraFeature1:"5 machines — flat, not per-seat",ultraFeature2:"Everything in Pro",ultraFeature3:"Higher concurrency & usage limits",ultraFeature4:"Unlimited daily screenshot minutes"}},layout:{adminSection:"Admin",adminOverview:"Overview",adminUsers:"Users",adminAuditLogs:"Audit Logs",adminSystem:"System",adminTokens:"Admin Tokens",adminEntry:"Admin",footerPlanTitle:"Current plan: {{plan}} — manage or upgrade",expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse",logout:"Logout",machineLimitBadge:"Machines full",machineLimitBadgeTitle:"You've reached your plan limit of {{count}} machine{{plural}} — open billing to upgrade",pushBudget:"Daily notifications {{used}}/{{limit}}"},settings:{title:"Settings",subtitle:"Appearance & preferences",appearanceTitle:"Appearance"},planCard:{unlimited:"Unlimited",machineSingular:"{{count}} machine",machinePlural:"{{count}} machines",sharedSessionSingular:"{{count}} shared session",sharedSessionPlural:"{{count}} shared sessions",teamMemberSingular:"{{count}} team member",teamMemberPlural:"{{count}} team members",turnIncluded:"TURN relay included",recommended:"Recommended",currentPlan:"Current Plan",contactUs:"Contact Us",freeForever:"Free Forever",startTrial:"Start 7-day free trial",upgradeTo:"Upgrade to {{name}}",noChargeCancel:"No charge for 7 days. Cancel anytime.",periodSeatMo:"seat/mo",periodMo:"mo",yearlyNote:"${{yearly}}/year — Save ${{saved}}",pricingCustom:"Custom"},activity:{origin:{ide:"IDE",extension:"Extension",admin:"Admin",webhook:"Webhook",web:"Dashboard",user:"User",terminal:"Terminal",system:"System",registry:"Registry",mesh:"Mesh",machine:"Machine",daemon:"Daemon",connection:"Connection",cli:"CLI",auth:"Sign-in",api_key:"API key",api:"API",agent:"Agent"},filterPlaceholder:"Filter by action, resource, or source...",refresh:"Refresh",loading:"Loading...",noLogs:"No logs",noMatchingLogs:"No matching logs found.",logsWillAppear:"Actions will appear here as they happen.",colAction:"Action",colResource:"Resource",colSource:"Source",colTime:"Time",logCount:"{{count}} logs",logCountFiltered:" (filtered from {{total}})",action:{login:"Logged in",logout:"Logged out",api_key_create:"Created API key",api_key_revoke:"Revoked API key",agent_command:"Sent agent command",terminal_exec:"Ran terminal command",ide_command:"Sent IDE command",daemon_command:"Sent daemon command",daemon_disconnect:"Disconnected daemon",daemon_revoke:"Revoked daemon",webhook_create:"Created webhook",webhook_delete:"Deleted webhook",webhook_toggle:"Toggled webhook",registry_publish:"Published provider",registry_promote:"Promoted provider",registry_yank:"Yanked provider",registry_publish_token_issued:"Issued registry publish token",machine_registered:"Registered machine",machine_secret_rotated:"Rotated machine secret",shortcut_launch:"Launched session",shortcut_stop:"Stopped session",shortcut_chat:"Sent chat message",shortcut_chat_debug_bundle:"Exported chat debug bundle",shortcut_approve:"Approved agent action",shortcut_reject:"Rejected agent action",shortcut_git_push:"Pushed git changes",shortcut_git_checkpoint:"Created git checkpoint",shortcut_mesh_clone_node:"Cloned mesh node",shortcut_mesh_remove_node:"Removed mesh node",shortcut_mesh_refine_node:"Refined mesh node",admin_plan_change:"Changed user plan",admin_role_change:"Changed user role",admin_user_suspend:"Suspended user",admin_user_unsuspend:"Unsuspended user",admin_machine_delete:"Deleted machine",admin_token_create:"Created admin token",admin_apikey_rate_limit:"Changed API key rate limit",admin_apikey_scopes:"Changed API key scopes",admin_apikey_revoke:"Revoked API key",admin_plan_limits_update:"Updated plan limits",admin_plan_limits_reset:"Reset plan limits",admin_config_update:"Updated system config",admin_announcement:"Posted system announcement",admin_disconnect:"Disconnected connection"}},webhooks:{title:"Webhooks",subtitle:"Real-time event notifications",addWebhook:"+ Add Webhook",eventDaemonConnect:"Daemon Connected",eventDaemonDisconnect:"Daemon Disconnected",eventAgentStatus:"Agent Status Change",eventApprovalRequired:"Approval Required",failed:"Failed",deleteConfirm:"Delete this webhook?",testFailed:"Test failed",secretTitle:"Webhook Secret",secretShownOncePrefix:"Shown ",secretShownOnce:"only once",secretShownOnceSuffix:". Use to verify ",copy:"Copy",done:"Done",newWebhook:"New Webhook",labelUrl:"URL",urlPlaceholder:"https://your-service.com/webhook",labelEvents:"Events",allEvents:"All Events (*)",creating:"Creating...",create:"Create",cancel:"Cancel",loading:"Loading...",noWebhooks:"No webhooks",noWebhooksDesc:"Receive real-time notifications about events.",setupFirst:"Set up first webhook",off:"OFF",autoDisabled:"Auto-disabled",autoDisabledTitle:"Auto-disabled after 10 consecutive failures",failuresWarning:"{{count}} failures",failuresTitle:"{{count}} consecutive failures — will auto-disable at 10",all:"ALL",history:"History",test:"Test",delete:"Delete",deleting:"...",recentDeliveries:"Recent Deliveries",refresh:"Refresh",noDeliveries:"No deliveries yet. Send a test to verify the endpoint.",request:"REQUEST",response:"RESPONSE",securityTitle:"Security",securityVerifyPrefix:"Verify ",securityVerifySuffix:" with your secret",securityHttps:"Use HTTPS endpoints only",securityAsync:"Return 2xx immediately, process async",securityAutoDisable:"Auto-disabled after 10 consecutive failures"},apiKeys:{title:"API Keys",keyCount:"{{count}} keys",playground:"Playground",create:"+ Create",scopeDaemonRead:"Daemon Read",scopeDaemonReadDesc:"List daemons & status",scopeDaemonControl:"Daemon Control",scopeDaemonControlDesc:"Commands, launch/stop, disconnect",scopeAgentRead:"Agent Read",scopeAgentReadDesc:"Status & chat history",scopeAgentControl:"Agent Control",scopeAgentControlDesc:"Send, approve/reject",scopeTerminal:"Terminal",scopeTerminalDesc:"Execute commands",scopeWebhooks:"Webhooks",scopeWebhooksDesc:"Manage hooks & deliveries",frozen:"Frozen",revokeConfirm:"Revoke this API key? This cannot be undone.",failedToLoad:"Failed to load",failed:"Failed",upgradePlan:"Upgrade your plan →",keyCreated:"Key Created!",copyNow:"Copy now — shown only once.",copied:"Copied",copy:"Copy",testKey:"Test",dismiss:"Dismiss",playgroundTitle:"API Playground",enterKeyToTest:"Enter an API key to test.",open:"Open",createKeyTitle:"Create API Key",labelName:"Name",namePlaceholder:"e.g. Production Bot",permissions:"Permissions ({{count}})",createBtn:"Create",cancel:"Cancel",loading:"Loading...",noKeys:"No API Keys",noKeysDesc:"Create a key to integrate with external services.",createFirstKey:"Create First Key",usedDate:"Used {{date}}",neverUsed:"Never used",revoke:"Revoke",usageLabel:"Usage:",apiReference:"API Reference →",frozenFeatureTitle:"Frozen — this feature is paused."},shareModal:{title:"Share Session",chatLabel:"Chat",chatDesc:"AI conversation only",remoteLabel:"Remote",remoteDesc:"Screenshot + desktop",permissionLabel:"Permission Level",authRequired:"Account required",expiresAfter:"Expires After",maxViewers:"Max Viewers",hide:"Hide",activeShares:"Active Shares",creating:"Creating...",createChatLink:"Create Chat Link",createRemoteLink:"Create Remote Link",expires:"expires",revoke:"Revoke",shareLinkCreated:"Share link created!",viewerMustLogin:"Viewer must be logged in to use this link",copy:"Copy",copied:"Copied!",expiresAt:"Expires:",done:"Done",failedToCreate:"Failed to create share link",expiry1h:"1 hour",expiry6h:"6 hours",expiry24h:"24 hours",expiry7d:"7 days",chatView:{label:"View Only",desc:"Read AI conversation in real-time"},chatControl:{label:"Control",desc:"Read + send messages + approve/reject actions"},remoteView:{label:"View Only",desc:"Watch screenshots + chat in real-time"},remoteControl:{label:"Control",desc:"Screenshots + send messages + approve/reject"},remoteFull:{label:"Full Access",desc:"Full remote control including desktop input"}},onboarding:{title:"Connect your first machine",subtitle:"Install ADHDev on a machine and sign in — it pairs itself and shows up here. Then drive every agent on it from this dashboard.",platformMac:"macOS / Linux",platformWindows:"Windows",copyTitle:"Click to copy",copiedLabel:"✓ Copied",copyLabel:"Copy",listeningLabel:"Listening for your daemon — keep this page open, it will appear automatically.",connectingLabel:"Connecting to ADHDev…",step1Title:"Install the daemon",step1Desc:"Run the command above on any machine you want to drive. It installs the daemon plus the adhdev CLI.",step2Title:"Sign in — the machine pairs itself",step2Desc:"The daemon links to this account automatically. No token to copy; it appears here the moment it connects.",step3Title:"Launch your first session",step3Desc:"Once a machine is online, start Claude Code, Codex, Cursor, and other agents straight from the dashboard.",readDocs:"Read the documentation →",reconnectingLabel:"Connection lost — reconnecting… Check your network if this persists.",offlineLabel:"You're offline. Reconnect to the internet and this page will resume automatically.",authFailedLabel:"Session expired — sign in again to continue.",machineLimitLabel:"Machine limit reached — your plan allows up to {{limit}}. Remove a machine or upgrade your plan to connect this one.",machineLimitManage:"Manage machines →",machineLimitUpgrade:"Upgrade plan →",setupWizardLink:"Prefer a guided setup? Open the Setup Wizard →"},legal:{navHome:"Home",navDashboard:"Dashboard",footerHome:"Home",footerTerms:"Terms",footerPrivacy:"Privacy",footerRefund:"Refund Policy",footerCopyright:"© 2026 RacoLab. All rights reserved."},authCallback:{authFailed:"Authentication Failed",backToLogin:"Back to Login",completing:"Completing authentication...",noTokenError:"No access token received"},cliAuth:{title:"ADHDev CLI Authentication",verifying:"Verifying...",authorizeAs:"Authorize CLI as {{name}}?",noCodeError:"No authentication code provided.",approve:"✓ Approve",signInFirst:"Please sign in first to authorize the CLI.",signIn:"Sign In →",failed:"Failed",successMessage:"CLI authentication complete!",returnToTerminal:"You can return to the terminal.",registryPublishTitle:"Authorize Registry Publishing",authorizeRegistryPublishAs:"Grant provider registry publishing access as {{name}}?",registryPublishWarning:"This grants a short-lived token (15 minutes) that can publish, promote and yank provider packages in the registry. It is not a daemon registration. Only approve this if you started a registry publish yourself. Requires an admin account.",signInFirstRegistryPublish:"Please sign in with an admin account to authorize registry publishing.",approving:"Approving…",errorFriendly:"Couldn't complete CLI authorization.",tryAgain:"Try again"},privacy:{title:"Privacy Policy",lastUpdated:"Last updated: September 27, 2026",intro:'This Privacy Policy describes how RacoLab ("we", "us", "our") collects, uses, and protects your information when you use the ADHDev service ("Service") at',s1Title:"1. Information We Collect",s1h1:"1.1 Account Information",s1p1:"When you create an account, we collect information provided by your authentication provider (GitHub or Google), including your name, email address, and profile picture.",s1h2:"1.2 IDE & Agent Data",s1p2:"When you connect your development environment to the Service, the local daemon may transmit:",s1l1:'IDE type and version (e.g., "Cursor 0.49.1")',s1l2:"Active AI agent information (name, status, current model)",s1l3:"Chat messages between you and AI agents",s1l4:"IDE screenshots (transmitted via P2P, not stored on our servers)",s1l5:"Workspace paths and open file names",s1l6:"Machine information (hostname, OS, memory usage)",s1h3:"1.3 Usage Data",s1p3:"We automatically collect usage information including API calls, feature usage patterns, and connection logs for service improvement and debugging purposes.",s1p3Attribution:"We also count visits by traffic source in aggregate only (campaign tags such as utm_source, the referring website's domain and the landing page, kept in your browser's local storage — no IP address, device identifier or cookie), and when you create an account we record the source of your first visit so we can see which channels bring new users.",s1h4:"1.4 Payment Information",s1p4:"Payment processing is handled entirely by our Merchant of Record, Paddle (Paddle.com Market Limited). We do not directly collect or store credit card numbers, bank account details, or other financial information. Please refer to",s1p4PaddleLink:"Paddle's Privacy Policy",s1p4Suffix:"for their data handling practices.",s2Title:"2. How We Use Your Information",s2p1:"We use collected information to:",s2l1:"Provide and maintain the Service",s2l2:"Authenticate your identity and manage your account",s2l3:"Route commands and data between your dashboard and connected machines",s2l4:"Send notifications (browser and push) about agent status changes",s2l5:"Process billing and subscription management (via Paddle)",s2l6:"Detect and prevent abuse or unauthorized access",s2l7:"Improve the Service and develop new features",s2l8:"Respond to support requests",s3Title:"3. Data Storage & Security",s3h1:"3.1 Infrastructure",s3p1:"Our Service runs on Cloudflare's global network using Cloudflare Workers, Durable Objects, and D1 Database. Data is stored in Cloudflare's infrastructure and is subject to",s3p1CloudflareLink:"Cloudflare's Privacy Policy",s3h2:"3.2 P2P Data",s3p2:"IDE screenshots and real-time terminal data are transmitted directly between your browser and your machine via WebRTC peer-to-peer connections. This data does not pass through or get stored on our servers.",s3h3:"3.3 Security Measures",s3p3:"We implement the following security measures:",s3l1:"JWT-based authentication with short-lived access tokens and refresh token rotation",s3l2:"Encrypted WebSocket connections (WSS/TLS)",s3l3:"Per-connection tokens for daemon authentication",s3l4:"Rate limiting on all API endpoints",s3l5:"Audit logging for security-sensitive operations",s4Title:"4. Data Sharing",s4p1:"We do not sell your personal data to third parties. We may share data with:",s4l1:"Payment processing as Merchant of Record",s4l2:"Infrastructure provider (hosting, CDN, database)",s4l3Label:"Authentication providers",s4l3:"GitHub/Google for OAuth login",s4p2:"We may disclose data if required by law, legal process, or to protect our rights and the safety of our users.",s5Title:"5. Data Retention",s5p1:"We retain your account data for the duration of your active account. Chat messages and agent activity data are retained for up to 90 days for service functionality.",s5p2:"Upon account deletion, we will remove your personal data within 30 days. Some anonymized usage data may be retained for analytical purposes.",s6Title:"6. Your Rights",s6p1:"You have the right to:",s6l1Label:"Access",s6l1:"Request a copy of your personal data",s6l2Label:"Correction",s6l2:"Update or correct your personal information",s6l3Label:"Deletion",s6l3:"Request deletion of your account and associated data",s6l4Label:"Export",s6l4:"Download your data in a portable format",s6l5Label:"Object",s6l5:"Object to certain data processing activities",s6p2:"To exercise these rights, contact us at",s7Title:"7. Cookies",s7p1:"We use essential cookies only for authentication (session tokens) and user preferences (theme, notification settings). We do not use advertising or tracking cookies.",s8Title:"8. Children's Privacy",s8p1:"The Service is not intended for users under the age of 16. We do not knowingly collect personal information from children under 16.",s9Title:"9. International Data Transfers",s9p1:"Your data may be processed in various locations through Cloudflare's global network. By using the Service, you consent to the transfer and processing of your data in these locations.",s10Title:"10. Changes to This Policy",s10p1:"We may update this Privacy Policy from time to time. We will notify you of any material changes by email or through the Service. Your continued use after changes constitutes acceptance of the updated policy.",s11Title:"11. Contact",s11p1:"For questions about this Privacy Policy or data practices:",s11l1Prefix:"Email:",s11l2Prefix:"Website:"},terms:{title:"Terms of Service",lastUpdated:"Last updated: April 11, 2026",intro:'Welcome to ADHDev ("Service"), operated by RacoLab ("we", "us", "our"). By accessing or using our Service at',introSuffix:'you agree to be bound by these Terms of Service ("Terms"). If you do not agree, do not use the Service.',s1Title:"1. Service Description",s1p1:"ADHDev is a cloud developer tool that provides remote monitoring and control of AI coding agents (such as Cursor, VS Code, Antigravity, Claude Code, and others) through web and mobile dashboard surfaces. The Service includes a local daemon, remote dashboards, REST API access, and browser and push notifications.",s2Title:"2. Account Registration",s2p1:"You must create an account to use the Service. You are responsible for maintaining the confidentiality of your account credentials. You agree to provide accurate and complete information during registration and to keep your account information up to date.",s2p2:"You must be at least 16 years old to use the Service. By creating an account, you represent that you meet this age requirement.",s3Title:"3. Subscription Plans & Billing",s3p1:"The Service offers the following plans:",s3l1:"Limited features, 1 connected machine",s3l2:"2 connected machines, unlimited agents, P2P remote view, 7-day free trial",s3l3:"5 connected machines, everything in Pro plus higher concurrency and usage limits (flat price, not per-seat)",s3p2:"Paid subscriptions are billed in advance on a monthly or yearly basis. All payments are processed by our payment partner, Paddle (Paddle.com Market Limited), who acts as the Merchant of Record for all transactions.",s4Title:"4. Refund Policy",s4p1:"We offer a 14-day money-back guarantee for all paid plans. If you are not satisfied with the Service, you may request a full refund within 14 days of your initial purchase by contacting us at",s4p2:"Refunds for renewals are handled on a case-by-case basis. Paddle's refund policies also apply as they are the Merchant of Record.",s5Title:"5. Acceptable Use",s5p1:"You agree not to:",s5l1:"Use the Service for any unlawful purpose or in violation of any applicable laws",s5l2:"Attempt to gain unauthorized access to other users' accounts or data",s5l3:"Reverse-engineer, decompile, or attempt to extract the source code of the Service's server components",s5l4:"Use the Service to transmit malware, spam, or other harmful content",s5l5:"Resell or redistribute the Service without our written consent",s5l6:"Interfere with or disrupt the integrity or performance of the Service",s6Title:"6. Intellectual Property",s6p1:"The Service, including its original content, features, and functionality, is owned by RacoLab and is protected by applicable intellectual property laws. The local daemon component is available under an open-source license as specified in the project repository.",s6p2:"You retain ownership of all data and content you transmit through the Service.",s7Title:"7. Data & Privacy",s7p1:"Your use of the Service is also governed by our",s7PrivacyLink:"Privacy Policy",s7p1Suffix:"The Service processes IDE interactions, chat messages, and screenshots for the purpose of remote monitoring and control. We do not sell your data to third parties.",s8Title:"8. Service Availability",s8p1:"We strive to maintain high availability but do not guarantee uninterrupted access. The Service may be temporarily unavailable due to maintenance, updates, or circumstances beyond our control. We are not liable for any losses resulting from service interruptions.",s9Title:"9. Limitation of Liability",s9p1:"TO THE MAXIMUM EXTENT PERMITTED BY LAW, RacoLab SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR ANY LOSS OF PROFITS OR REVENUES, WHETHER INCURRED DIRECTLY OR INDIRECTLY, ARISING OUT OF YOUR USE OF THE SERVICE.",s9p2:"Our total liability for any claim arising from the Service shall not exceed the amount you paid us in the 12 months preceding the claim.",s10Title:"10. Termination",s10p1:"We may suspend or terminate your access to the Service at any time for violations of these Terms or for any other reason at our sole discretion. You may cancel your account at any time through the Settings page. Upon cancellation, your data will be deleted within 30 days.",s11Title:"11. Changes to Terms",s11p1:"We reserve the right to modify these Terms at any time. We will notify you of material changes via email or through the Service. Your continued use after changes constitutes acceptance of the modified Terms.",s12Title:"12. Governing Law",s12p1:"These Terms shall be governed by and construed in accordance with the laws of the Republic of Korea, without regard to conflict of law provisions.",s13Title:"13. Contact",s13p1:"If you have any questions about these Terms, please contact us:",s13l1Prefix:"Email:",s13l2Prefix:"Website:"},refund:{title:"Refund Policy",lastUpdated:"Last updated: March 24, 2026",intro:"ADHDev is operated by RacoLab. All payments are processed by our Merchant of Record,",introSuffix:"who manages billing, invoicing, and refunds on our behalf.",s1Title:"1. 14-Day Money-Back Guarantee",s1p1:"We offer a 14-day money-back guarantee on all paid plans (Pro). If you are not satisfied with the Service for any reason, you may request a full refund within 14 days of your initial subscription purchase.",s1p2:"To request a refund, contact us at",s1p2Suffix:"with your account email and order details. We will process your request within 3 business days.",s2Title:"2. Renewal Refunds",s2p1:"Refunds for subscription renewals (monthly or yearly) are handled on a case-by-case basis. If you were charged for a renewal you did not intend, please contact us within 7 days of the charge at",s3Title:"3. Non-Refundable Cases",s3p1:"Refunds will not be issued for:",s3l1:"Requests made after the 14-day guarantee period for initial purchases",s3l2Prefix:"Accounts suspended or terminated due to violations of our",s3l2Link:"Terms of Service",s3l3:"Partial months of service already used beyond the refund window",s4Title:"4. How Refunds Are Processed",s4p1:"Approved refunds are processed through Paddle and returned to the original payment method. Depending on your bank or card issuer, refunds may take 5–10 business days to appear. Paddle's own",s4p1RefundLink:"refund terms",s4p1Suffix:"also apply.",s5Title:"5. Cancellation",s5p1Prefix:"You may cancel your subscription at any time from the",s5p1BillingLink:"Billing",s5p1Suffix:"page in your dashboard. Cancellation stops future charges. You retain access to your plan's features until the end of the current billing period. Cancellation alone does not trigger a refund.",s6Title:"6. Contact",s6p1:"For refund requests or billing questions:",s6l1Prefix:"Email:",s6l2Prefix:"Website:"},sessionShare:{loading:"Loading session...",sessionNotFound:"Session Not Found",noLongerAvailable:"This session is no longer available",homeBtn:"← ADHDev Home",sharedSession:"Shared Session",host:"Host",mode:"Mode",permission:"Permission",auth:"Auth",authRequired:"Account required",viewers:"Viewers",joinChat:"Join Chat",joinSession:"Join Session",expires:"Expires: {{date}}",chatLabel:"Chat",remoteLabel:"Remote",waitingMessages:"Waiting for messages...",connecting:"Connecting... ({{state}})",sendMessageAs:"Send message as {{name}}...",sendAs:"Send as {{name}}...",ownerChat:"{{name}}'s Chat",ownerSession:"{{name}}'s Session",agentName:"{{name}}'s Agent",fullControlBadge:"Full Control Active",failedToJoin:"Failed to join session",sessionRevoked:"Session has been revoked by the host",sessionExpired:"Session has expired",authRequired2:"Authentication required for control share",unknownError:"Unknown error"},apiPlayground:{title:"API Playground",history:"History ({{count}})",apiRelayWarning:"Daemon API relay is opt-in. REST command/chat proxy routes stay disabled unless that daemon explicitly enables them with `adhdev daemon:api enable`.",authBearer:"Authorization: Bearer {{key}}",copyAsCurl:"cURL",copied:"Copied",targetDaemon:"Target Daemon",quickActions:"Quick Actions",requestBody:"Request Body (JSON)",recentRequests:"Recent Requests",clearHistory:"Clear",noDaemonsWarning:"No daemons connected. Start a daemon first or replace {daemonId} manually.",send:"▶ Send",sending:"⏳"},announcementBanner:{visibleUntil:"Visible until {{time}}",dismiss:"Dismiss"},push:{budgetResetsShort:"Resets at {{time}}",budgetRemainingShort:"{{count}} left on your plan today",budgetShort:"{{used}}/{{limit}} today",title:"Push Notifications",descUnsupported:"Not supported in this browser",descDenied:"Blocked — enable in browser settings",descEnabled:"On",descDefault:"Alerts even when the tab is closed",docsLink:"Push Notifications docs",sent:"Sent",test:"Test",iosHint:"On iPhone and iPad, push only works from the installed Safari PWA. A normal Safari tab cannot receive ADHDev push notifications.",unsupportedWarning:"This browser does not support Web Push here. Use Safari PWA on iPhone/iPad or a Chromium browser on desktop/Android.",deniedWarning:"Notifications are blocked in browser or site settings. Re-enable them there, then turn Push Notifications on again.",registeredDevices:"Registered devices: {{count}}",noDevices:"No active push devices found.",deviceLabel:"Device {{number}}",thisDevice:"This device",lastActive:"Last active",removing:"Removing...",removeHere:"Remove here",remove:"Remove"},mesh:{manualMcpSetup:"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",couldNotLoadMeshes:"Could not load meshes",untitledMesh:"Untitled mesh",chooseMachineFirst:"Choose a machine first.",launchFailed:"Launch failed",coordinatorLaunchFailed:"Coordinator launch failed",coordinatorLaunched:"Coordinator launched ({{sessionId}})",coordinatorLaunchSent:"Coordinator launch command sent"},plans:{free:"Free",pro:"Pro",ultra:"Ultra",team:"Team",enterprise:"Enterprise"},adminAudit:{title:"Global Audit",subtitle:"System-wide event tracking",allActions:"All Actions",allSources:"All Sources",filter:"Filter",noLogs:"No logs found",loading:"Loading...",loadMore:"Load More ↓"},adminDashboard:{failedToLoad:"Failed to load admin data",title:"Admin Dashboard",subtitle:"Service overview & management",accessDenied:"Admin access denied",backToDashboard:"Back to Dashboard",loading:"Loading admin dashboard",loadingDesc:"Collecting service stats and recent audit activity.",totalUsers:"Total Users",todayCommands:"Today Commands",activeApiKeys:"Active API Keys",todayLogins:"Today Logins",planDistribution:"Plan Distribution",quickActions:"Quick Actions",manageUsers:"Manage Users",apiKeys:"API Keys",auditLogs:"Audit Logs",systemConfig:"System Config",recentActivity:"Recent Activity",viewAll:"View All",noRecentActivity:"No recent activity"},adminTokens:{title:"Admin Tokens",subtitle:"Issue admin-scoped API tokens for deploy automation",superAdminOnly:"Super admin only",superAdminOnlyDesc:"Only a super admin can issue admin tokens. Ask a super admin if you need one.",issueTitle:"Issue a new token",nameLabel:"Name",namePlaceholder:"e.g. deploy-ci",scopesLabel:"Scopes",scopesHint:"admin covers most admin APIs. super_admin also allows issuing tokens and changing roles — grant it only when required.",expiryLabel:"Expires in",expiryDays:"{{count}} days",expiryHint:"Admin tokens always expire. The server caps the lifetime at 90 days.",issue:"Issue token",issuing:"Issuing...",issuedTitle:"Copy your token now",issuedWarning:"This is the only time the token is shown. Store it somewhere safe — you cannot retrieve it again.",issuedMeta:"Scopes: {{scopes}} · Expires: {{expiresAt}}",copy:"Copy",copied:"Copied",copyFailed:"Copy failed — select the token and copy it manually",dismiss:"Dismiss",expiryClamped:"Expiry was shortened to the 90-day maximum",existingTitle:"Active admin tokens",emptyTitle:"No admin tokens",emptyDesc:"Issue one above to authenticate deploys without the browser login.",expiresAt:"Expires: {{time}}",lastUsed:"Last used {{time}}",neverUsed:"Never used",noExpiry:"No expiry",expired:"Expired",revoke:"Revoke",revokeConfirm:'Revoke the token "{{name}}"? Anything using it will stop working immediately.',revoked:"Token revoked",loading:"Loading...",error:"Error: {{message}}"},adminSystem:{error:"Error: {{message}}",announcementSent:"Announcement sent",announcementCleared:"Announcement cleared",title:"System Settings",subtitle:"Announcements & system configuration",loading:"Loading system settings",loadingDesc:"Fetching current announcement state.",announcement:"Announcement",current:"Current:",untilTime:"(until {{time}})",untilCleared:"(until cleared)",announcementPlaceholder:"Enter announcement message...",severityInfo:"Info",severityWarning:"Warning",severityCritical:"Critical",duration1h:"1 hour",duration6h:"6 hours",duration24h:"24 hours",duration7d:"7 days",durationUntilCleared:"Until cleared",send:"Send"},adminUsers:{error:"Error: {{message}}",roleUpdated:"Role updated",planUpdated:"Plan updated",suspensionReasonPrompt:"Enter suspension reason:",userSuspended:"User suspended",userUnsuspended:"User unsuspended",title:"User Management",subtitle:"Manage users, roles, and suspension",usersTotal:"users total",searchPlaceholder:"Search email or name...",allRoles:"All Roles",roleUser:"User",roleAdmin:"Admin",roleSuperAdmin:"Super Admin",allPlans:"All Plans",search:"Search",colUser:"User",colRole:"Role",colPlan:"Plan",colStatus:"Status",colCreated:"Created",colActions:"Actions",noName:"No name",statusSuspended:"Suspended",statusActive:"Active",unsuspend:"Unsuspend",suspend:"Suspend",loading:"Loading...",prev:"← Prev",next:"Next →"}},Ik={onboardingTour:{next:"Next",getStarted:"Get started",learnMore:"Learn more in the docs",closeAria:"Close onboarding",allSetStandalone:{desc:"This dashboard is already connected to your local daemon. Start a session from the Dashboard tab, or add more providers under Machines → Providers.",title:"You're all set"},getStartedCloud:{desc:"Run this on any machine you want to drive, then sign in — the daemon pairs itself to your dashboard automatically.",title:"Get started"},orchestrate:{desc:"Repo Mesh (Cloud Pro) lets one coordinator hand work to agents across many machines — parallel git worktrees, automatic branch convergence, and cross-checking the same repo from several angles.",title:"Orchestrate your agents"},watchAndSteer:{desc:"Follow each agent's session in real time and steer it as it works — switch sessions, take screenshots, and (for IDE sessions) view and control the screen over a direct connection.",title:"Watch and steer, live"},realtimeChat:{desc:"See what your AI agent is doing in real time. Send messages, approve or reject actions — all from your browser or phone.",title:"Real-time chat"},welcome:{desc:"Drive any local CLI coding agent — Claude Code, Codex, Antigravity CLI — straight from your browser or phone. The agents keep running on your machine; you control them from the web.",title:"Welcome to ADHDev"}},installCommand:{orViaNpm:"Or via npm:",clickToCopy:"Click to copy"},errorBoundary:{reload:"Reload page",description:"An unexpected error occurred. Please reload the page to continue.",title:"Something went wrong"},shellFreshness:{dismissAria:"Dismiss update notice",later:"Later",reload:"Reload",message:"A new version of ADHDev is available."},openMenu:"Open menu",closeMenu:"Close menu"},Mk={loadingOlderMessages:"Loading older messages...",waitingForMessages:"Waiting for messages...",agentGenerating:"Agent generating...",jumpToTop:"Jump to top",jumpToOldestMessages:"Jump to oldest messages",top:"↑ Top",latest:"↓ Latest",jumpToLatestMessages:"Jump to latest messages",jumpToBottom:"Jump to bottom",showEarlierMessages:"↑ Show {{count}} earlier messages...",showEarlierMessagesHidden:"↑ Show {{count}} earlier messages... ({{total}} hidden)",loadOlderMessages:"↑ Load older messages",loadErrorRetry:"↻ {{error}}"},Rk={zoomOut:"Zoom Out",zoomIn:"Zoom In",resetZoom:"Reset Zoom",toggleFullscreen:"Toggle Fullscreen"},Pk={screenshotAlt:"Remote View",mouse:"Mouse",touch:"Touch",connected:"Connected",ws:"Reconnecting",direct:"Direct",relay:"Relay",turnBlocked:"Relay limit reached",turnUsage:"TURN {{used}}/{{budget}}m",typeAndEnter:"Type & Enter...",settings:"SETTINGS",zoom:"ZOOM:",fill:"FILL",fit:"FIT",directP2PTitle:"Direct P2P connection",turnRelayTitle:"TURN relay in use",dailyTurnTitle:"Daily TURN relay usage",waitingState:{turnRelayActive:"TURN relay active"},waiting:{connectedLabel:"Connected. Waiting for first frame...",connectingLabel:"Connecting to Host...",reconnectingLabel:"Reconnecting to Host...",connectedHint:"The remote stream is warming up",reconnectingHint:"Waiting for the remote stream to catch up"},error:{title:"Remote connection lost",reasonFailed:"The connection to this host failed. Check that the daemon is running and try again.",reasonDisconnected:"Lost connection to the host and could not reconnect after 15 seconds.",retry:"Retry"},screenshotViewer:{altText:"IDE Screenshot",waitingForStream:"Waiting for screenshot stream...",p2pStatus:"P2P: {{state}}"}},Lk={openChat:"Open chat",openCoordinatorChat:"Open coordinator chat",coordinatorGone:"coordinator session ended",chatNotFound:"No chat tab for this session on this dashboard — it may be running on another machine.",openChatHint:"Click to open this session’s chat"},Ek={meshNodeUnavailable:"Mesh node info unavailable",roleCoordinator:"Mesh coordinator",rowProviderType:"Provider type",rowStarted:"Started",copyDiagnostics:"Copy diagnostics",gitClean:"clean",gitDirty:"uncommitted changes",gitDetached:"(detached)",blockRawMetadata:"Raw runtime metadata",blockFinalPrompt:"Final system prompt",blockExtraPrompt:"Extra prompt for this launch",quotaOkNoWindows:"No limit",sectionMeshWorker:"Spawned by coordinator",rowMeshId:"Mesh ID",rowTaskId:"Task",rowCoordinator:"Coordinator",title:"Session info",loading:"Loading…",close:"Close",failedToLoad:"Failed to load session info",stampedToNode:"This session is stamped to a mesh node that the coordinator no longer reports.",sectionSession:"Session",sectionLaunch:"Launch",sectionMeshNode:"Mesh node",sectionMeshCoordinator:"Mesh coordinator",sectionRuntime:"Runtime",rowSessionId:"Session ID",rowProvider:"Provider",rowTransport:"Transport",rowWorkspace:"Workspace",rowSpawnedAt:"Spawned at",rowProviderSessionId:"Provider session ID",rowMachine:"Machine",rowConnection:"Connection",rowCommand:"Command",rowWorkingDirectory:"Working directory",rowArgs:"Args",rowExtraArgs:"Extra args",rowExtraEnv:"Extra env",rowNodeId:"Node ID",rowRepoRoot:"Repo root",rowDaemonId:"Daemon ID",rowRole:"Role",rowMachineStatus:"Machine status",rowHealth:"Health",rowWorktree:"Worktree",rowLaunchReady:"Launch ready",rowGit:"Git",rowProviders:"Providers",rowProviderPriority:"Provider priority",rowCoordinatorCli:"Coordinator CLI",rowStartedAt:"Started at",rowPromptInjection:"Prompt injection",rowMcpConfig:"MCP config",rowRuntimeId:"Runtime ID",rowLifecycle:"Lifecycle",rowSurface:"Surface",rowRecoveryState:"Recovery state",rowRestoredFromStorage:"Restored from storage",rowAttachedClients:"Attached clients"},Dk={mobile:{noHistoryMatches:"No saved history matches these filters.",workspaceMissing:"(workspace missing)",resumableOnly:"Only ones that can be resumed",sortMessages:"Most messages",sortOldest:"Oldest first",sortRecent:"Most recent",filterModel:"Filter by model",filterWorkspace:"Filter by workspace",searchHistory:"Search title or preview",useThisFolder:"Use this folder",browseDescription:"Move through folders like a normal file browser, then use the current folder for this machine.",browseTitle:"Select workspace",machineDetails:"Machine details",inspect:"Inspect",createFolder:"Create folder",showMore:"Show {{count}} more",showFewer:"Show fewer",recentLaunches:"Recent launches",currentChats:"Current chats",machineFallback:"machine"},daemonUpdate:{previewUnknownDescription:"The app is connected to preview, but the server hasn't reported a preview target version yet.",previewUpToDateDescription:"This machine already runs the current preview daemon.",previewUnknownTitle:"Preview update status unknown",previewUpToDateTitle:"Preview daemon is up to date",mismatchDescription:"This machine runs a different daemon version than the current app. Update it before starting more sessions.",previewUpgradeDescription:"This machine can be updated to the current preview daemon without opening a remote shell.",requiredDescription:"This machine is on an incompatible daemon version. Update it before starting more sessions.",mismatchTitle:"Version mismatch detected",requiredTitle:"Daemon update required",upgrade:"Update",updateNow:"Update now"},launchPick:{empty:"No saved workspaces yet. Add one in the Workspace tab or type a path above.",description:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path.",title:"Where should this run?"},workspacePicker:{noneSelected:"No workspace selected. This starts in the home folder.",selectedWorkspace:"Selected workspace",defaultWorkspace:"Default workspace",enterPathFirst:"Enter a full folder path to start there.",browseFirst:"Browse to a folder before starting there.",enterPath:"Enter a full folder path…",customPath:"Custom path…",selectWorkspace:"Select workspace…",noneSaved:"(no saved workspaces — add one in the Workspace tab)",noWorkspaceHome:"(no workspace — start in home folder)"},trustBadge:{externalUntrustedHint:"From a source you added, and it includes code that ADHDev will run. Review the source before enabling.",externalSafeHint:"From a source you added. Settings only — ADHDev never runs code from it.",trustedWithScriptsHint:"Provided officially by ADHDev. Includes scripts that ADHDev runs.",trustedHint:"Provided officially by ADHDev. Settings only — no provider code runs.",userCustomHint:"You wrote this provider in your own providers folder. It runs your own code.",externalUntrusted:"External · runs code",externalSafe:"External",trustedWithScripts:"Official · scripts",trusted:"Official",userCustom:"Custom"},providerSettings:{option:{high:"High",medium:"Medium",low:"Low"},notifications:{description:"Show notifications when {{provider}} changes state.",label:"Notifications"},showCoordinatorSystemPrompt:{description:"Show the injected system prompt as a message in the chat. Off by default — you can always see it in the chat header's Session Info (ⓘ).",label:"Show system prompt message"},showTerminal:{description:"Show terminal commands and their output in the chat.",label:"Show terminal"},showToolCalls:{description:"Show short summaries of tool calls (searched, edited, …) in the chat.",label:"Show tool calls"},showThinking:{description:"Show the agent's reasoning in the chat.",label:"Show thinking"},longGeneratingThresholdSec:{description:"How long a reply can run before the long-running alert fires.",label:"Long-running threshold (seconds)"},longGeneratingAlert:{description:"Notify you when a reply takes unusually long.",label:"Long-running alert"},approvalAlert:{description:"Notify you when {{provider}} is waiting for your approval.",label:"Approval notifications"},appPathOverride:{description:"Optional full path to the IDE app. Leave blank to look in the usual install locations.",label:"App path"},cliPathOverride:{description:"Optional full path to the IDE command-line launcher. Leave blank to use the detected one.",label:"CLI launcher path"},executableArgs:{description:"Optional arguments that replace the default ones when {{provider}} starts. Leave blank to use the defaults.",label:"Launch arguments"},executablePath:{description:"Optional full path to the {{provider}} program. Leave blank to find it on your PATH.",label:"Executable path"},autoApprove:{description:"Approve {{provider}} tool calls and prompts automatically, without asking you first.",label:"Auto approve"},enabled:{description:"Turn this on before ADHDev detects, launches, or checks {{provider}} on this machine.",label:"Enabled on this machine"},thisProvider:"this provider"},launchConfirm:{workspace:"Workspace",languageModel:"Language Model (Optional)",autoDetect:"Auto-detect or default",cliArgs:"CLI Arguments (Optional)",cliArgsPlaceholder:"e.g. --experimental",cancel:"Cancel",closeAria:"Close launch confirmation",launch:"Launch",launching:"Launching…"},confirmExternal:{aboutToActivateFrom:"You're about to turn on {{provider}} from {{source}}.",aboutToActivate:"You're about to turn on {{provider}}.",dialogAria:"Confirm untrusted external provider",title:"Activate untrusted external provider?",description:"This manifest ships JavaScript that the daemon will execute. Treat as untrusted code — review the source before enabling.",proceedWarning:"Only proceed if you trust the source URL you added and have reviewed the manifest.",cancel:"Cancel",activate:"Activate"},providers:{advancedHint:"Sources, load paths and provider details",filter:"Filter",sourceConfigTitle:"Provider source config",sourceConfigDesc:"Where the daemon looks for provider manifests. Affects resolution and reloads.",sourceMode:"Source mode",explicitProviderDir:"Explicit providerDir",providerDirPlaceholder:"Leave blank to use ~/.adhdev/providers",applying:"Applying…",applyReload:"Apply + Reload",userRoot:"User root:",upstreamRoot:"Upstream root:",providerRoots:"Provider roots:",loadingSettings:"Loading provider settings…",noProviders:"No providers installed yet — use Install above, or add a source under Advanced.",noFilteredProviders:"No {{filter}} providers installed.",refresh:"Refresh",updateAll:"Update all",advanced:"Advanced",newChannelTypesTitle:"Available to install",newChannelTypesDesc:"Published to the verified channel but never installed on this machine. Install activates the digest-verified bundle.",installNewType:"Install",modelListTitle:"Model lists",modelListStaleDesc:"Could not read the model list from these CLIs (signed out, offline, or unsupported output). The provider manifest's list is being used and may be out of date.",modelListStaleBadge:"unverified",installFailedTitle:"Install failed",installFailedDigestMismatch:"Install failed — try later",loadFailed:"Failed to load provider settings: {{error}}",quotaToggleFailed:"Failed to update quota probe for {{provider}}: {{error}}"},sourcesPanel:{title:"External sources",description:"3rd-party git URLs you've added. Providers here may ship JavaScript the daemon will execute — activation requires a confirmation.",addSource:"+ Add source",empty:'No external sources registered. Use "+ Add source" to register a 3rd-party provider git URL.',remove:"Remove",removing:"…",removeConfirmTitle:"Remove provider source {{name}}?",removeConfirmDescription:"This deletes the cloned manifests and clears any active-source entries that pointed here.",removeConfirmLabel:"Remove",conflictsTitle:"Conflicts",conflictsDescription:"Multiple sources expose the same provider type. Pick which source's copy should be active.",active:"Active",switchActiveTo:"Switch active to {{name}}",addTitle:"Add external source",gitUrl:"Git URL",ref:"Ref (branch/tag)",name:"Name (optional, auto-derived from URL)",cancel:"Cancel",cloning:"Cloning…",cloneAndRegister:"Clone + register",loadFailed:"Failed to load sources",addFailed:"Failed to add source",removeFailed:"Failed to remove source",setActiveFailed:"Failed to set active source"},providerRow:{detectDisabledHint:"Turn the provider on before checking it",detectHint:"Check that the configured program can be found and run",lifecycleDeprecated:"No longer supported",lifecycleExperimental:"Experimental",lifecycleBeta:"Beta",lifecycleStable:"Stable",checkFailed:"Failed",checkOk:"OK",statusDetected:"Detected",statusNotDetected:"Not detected",statusEnabledUnchecked:"Enabled (unchecked)",statusDisabled:"Disabled",labelType:"Type:",labelVersion:"Version:",labelBinary:"Binary:",labelStatus:"Status:",labelDetails:"Details:",labelSource:"Source:",labelTrust:"Trust:",labelLinks:"Links:",labelDetection:"Detection:",labelVerification:"Verification:",saving:"saving…",disable:"Disable",enable:"Enable",detect:"Detect",resetCommand:"Reset command",quotaAccountLabel:"Show account on quota",quotaAccountLabelHint:"Label this provider's plan quota with the signed-in account. Off means the account is never fetched, not just hidden.",quotaAccountLabelOn:"On",quotaAccountLabelOff:"Off",quotaTracking:"Quota tracking",quotaTrackingHint:"Periodically read this provider's plan quota for the dashboards. Off stops the reads entirely.",quotaTrackingOn:"On",quotaTrackingOff:"Off",quotaClaudeConfirmTitle:"Enable Claude quota tracking?",quotaClaudeConfirmBody:"Claude Code has no quota API, so ADHDev reads usage through its statusLine — the only path available. Enabling replaces the statusLine command in ~/.claude/settings.json with the ADHDev wrapper. Your existing command keeps running inside the wrapper and its output is passed through unchanged, so your prompt looks the same. No other setting in the file is modified. The current value is backed up first and can be restored with `adhdev quota claude:uninstall`.",quotaClaudeConfirmOk:"Enable and install",quotaClaudeConfirmCancel:"Cancel",labelSpecPin:"Spec pin:",labelActivatedAt:"Activated:",labelPreviousPin:"Previous pin:",labelDigest:"Digest:",specPinStale:"update {{latest}}",specPinStaleHint:"This machine loads an older spec. Channel offers {{latest}}.",updateInline:"Update",updateInlineHint:"Channel offers {{latest}}. Download, verify and activate it on this machine.",specPinUpdating:"Updating…",specPinRollback:"Roll back",specPinRollbackHint:"Return to spec {{version}} (local, no download).",specPinRollingBack:"Rolling back…"},installOptions:{title:"Set up {{provider}}",quotaLabel:"Track plan usage",quotaHint:"Periodically read this provider's plan quota so the dashboards and `adhdev quota` can show what's left. Off stops the reads entirely — nothing is collected.",quotaClaudeNote:"Claude Code has no quota API, so this installs the ADHDev statusLine wrapper into ~/.claude/settings.json. Your existing command keeps running inside it, and the original is backed up.",autoApproveLabel:"Approve tool calls automatically",autoApproveHint:"When this agent asks permission to run a command, edit a file or use a tool, ADHDev answers yes for you. You will not see the approval prompt, and the action runs without waiting.",autoApproveWarning:"The agent can run commands on this machine without asking you first. Turn this off to approve each one yourself.",cancel:"Cancel",confirm:"Enable provider"},card:{status:{offline:"Offline",failed:"Connection failed",connecting:"Connecting…",attention:"Online · sync delayed",online:"Online"},slowLink:"Slow link",coresCount_other:"{{count}} cores",coresCount_one:"{{count}} core",onMachine:"on {{machine}}",sectionIDEs:"IDEs",sectionCLIs:"CLIs",sectionACPAgents:"ACP Agents",cpu:"CPU",mem:"MEM",loading:"Loading your machines…",emptyHeadline:"Welcome to ADHDev",emptyBody:"Connect your first machine to the dashboard. Install ADHDev on that machine and sign in — it pairs automatically and appears here:",emptyDocsLink:"Read the documentation →",hidden:"Hidden",pageTitle:"Machines",burrowCount_one:"{{count}} machine",burrowCount_other:"{{count}} machines",onlineCount_one:"{{count}} online",onlineCount_other:"{{count}} online",agentsActive_one:"{{count}} agent active",agentsActive_other:"{{count}} agents active",activeNow:"Active Now",generating:"generating",connectionFailed:"Connection failed",reconnect:"Reconnect",transportRelay:"Connected through a relay server — slower than a direct link. Usually a firewall or NAT blocks the direct path.",transportDirect:"Direct connection",beacon:{lastSyncedBehindPart_other:", {{count}} records still to receive",lastSyncedBehindPart_one:", {{count}} record still to receive",soleCopyTooltip_other:"{{entries}} records on this machine are not yet backed up on another machine. Keep it online until another machine has synced.",soleCopyTooltip_one:"{{entries}} record on this machine is not yet backed up on another machine. Keep it online until another machine has synced.",soleCopyLabel_other:"{{count}} records not backed up",soleCopyLabel_one:"{{count}} record not backed up",behindTooltip_other:"This machine hasn't received {{count}} recent records from your other machines yet. It usually catches up on its own.",behindTooltip_one:"This machine hasn't received {{count}} recent record from your other machines yet. It usually catches up on its own.",behindLabel:"Sync delayed",deferredLabel:"Backup unconfirmed",deferredTooltip:"Couldn't confirm that everything on this machine is backed up: only some of your machines could be compared. This is not an error.",lastSyncedTooltip:"Last synced {{minutes}} min ago{{behindPart}}."},fleetPeer:{stateOffline:"offline",stateOnline:"online",divergedLabel:"Sync delayed",tooltip:"The server sees this machine as {{wsState}} with {{wsCount}} sessions, but another of your machines saw {{peerState}} with {{peerCount}} sessions ({{age}}s ago). This usually settles within a few seconds."},noAgentsRunning:"No agents running yet",launchCta:"Launch →"},detail:{relaunchFailed:"Couldn't relaunch",launchProvider:"Provider",launchType:"Type",tabsAriaLabel:"Machine sections",tabSessions:"Sessions",notFound:"Machine not found",save:"Save",cancel:"Cancel",loading:"Loading machine...",offlineHint:"The machine may be offline or not yet connected.",back:"← Back",tabHostedRuntimes:"Hosted Runtimes",tabProviders:"Providers",tabSystem:"System",tabLogs:"Logs",clickToSetNickname:"Click to set nickname",nicknamePlaceholder:"Machine nickname...",reconnect:"Reconnect",p2pConnected:"connected",providerUpdatesAvailable:"Provider updates available",providerSyncSuccess:"Provider channel synced — {{count}} updated",providerSyncAlreadyCurrent:"Provider channel is already current",providerSyncFailed:"Provider update failed"},commandCenter:{updateStatusUnknown:"Update status unknown",upToDate:"Up to date",updateDaemon:"Update daemon",updateToVersion:"Update to v{{version}}",updateChannel:{preview:"preview",stable:"stable"},updateTargetWithChannel:"Target: v{{version}} ({{channel}})",updateTarget:"Target: v{{version}}",currentChats:"Current Chats",recentLaunches:"Recent Launches",daemonUpdate:"Daemon Update"},workspaceBrowse:{currentFolder:"Current folder",parent:"Parent",go:"Go",pathPlaceholder:"Type a folder path",loading:"Loading folders…",noSubfolders:"No subfolders here.",useThisFolder:"Use this folder"},managedWorkspaces:{setDefaultHint:"Set as default workspace",unsetDefaultHint:"Default workspace — click to unset",title:"Workspaces",addWorkspace:"Add workspace",empty:'No saved workspaces yet. Click "{{button}}" to pick a folder.',addDialogDescription:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",remove:"Remove",newSession:"Start a new session in this workspace",newSessionShort:"Session",newMeshSession:"Start a mesh coordinator session in this workspace",newMeshSessionShort:"Mesh",removeConfirmTitle:"Remove workspace",removeConfirmDescription:'Remove "{{label}}" from the list? The folder itself is not deleted.',rename:"Rename",renamePlaceholder:"Workspace name",saveName:"Save",cancelRename:"Cancel",renameFailed:"Could not update workspace name"},overview:{diagnostics:"Diagnostics",p2p:"P2P",daemonVersion:"Daemon version",cores:"CPU cores",platform:"Platform",hostname:"Hostname",aboutMachine:"This machine",approx:"(approx.)",memory:"Memory",cpuDetail:"{{load}} avg / {{cores}} cores",cpuLoad:"CPU load",resourceUsage:"Resource usage",waiting:"Waiting…",uptime:"Uptime",waitingForStats:"Waiting for live stats…",waitingForStatsWithTotal:"Waiting for live stats… · {{total}} total"},quota:{text:{failureKind:{unknown:"unknown error","no-data":"no reading yet","setup-required":"setup required",unsupported:"not supported","cli-unavailable":"program not found",parse:"unreadable response",server:"provider server error",network:"network error","rate-limited":"rate limited","quota-exhausted":"plan limit reached",unauthorized:"access denied","expired-token":"sign-in expired","missing-credentials":"not signed in"},agoDays:"{{days}}d {{hours}}h ago",agoHours:"{{hours}}h {{minutes}}m ago",agoMinutes:"{{minutes}}m ago",justNow:"just now",unreadable:"could not read quota",unavailable:"not available on this machine",pool:"pool",usageSessions:"{{count}} sess",usageTokens:"{{count}} tok",windowReset:"reset · awaiting refresh",cue:{stale:"stale",refreshing:"refreshing"},resetsInDays:"resets in {{days}}d {{hours}}h",resetsInHours:"resets in {{hours}}h {{minutes}}m",resetsInMinutes:"resets in {{minutes}}m",resetsNow:"resets now",used:"{{percent}}% used"},title:"Plan quota",sessionHint:"Rolling 5-hour plan window reported by this machine",weeklyHint:"Rolling 7-day plan window reported by this machine",monthlyHint:"Rolling 30-day billing window reported by this machine",bucketHint:"Per-pool quota bucket reported by this machine — pools on one plan reset independently",failureHint:"This machine reported that it could not read this provider's quota",okNoWindows:"No limit",okNoWindowsHint:"The quota fetch succeeded; this provider reports no percentage window (e.g. included-usage plans).",accountHint:"The signed-in account this quota belongs to, as reported by the provider CLI",usageHint:"Absolute usage over the trailing window — this provider routes to your own upstream accounts, so there is no plan limit to show a percentage against."},actions:{nicknameSyncFailed:"Nickname updated on the machine, but account sync failed",nicknameFailed:"Couldn't save nickname",nicknameSaved:"Nickname saved",pathMissing:"The path may be missing on disk",workspaceActionFailed:"Workspace update failed",workspaceAdded:"Workspace added",detectFailed:"IDE detection failed",usingDefaultWorkspace:"Using the default workspace",runningInHome:"Running in the home directory",launchPending:"{{name}} is starting — it will appear shortly",launchFailed:"Couldn't launch {{name}}",launching:"Launching {{name}}…",stopCliConfirmDescription:"This will terminate the process.",stopIdeConfirmDescription:"This will disconnect CDP and optionally kill the process.",stopped:"{{name}} stopped",launched:"{{name}} launched",stopFailed:"Couldn't stop",restartInitiated:"{{name}} restart initiated",restartFailed:"Couldn't restart",selectProviderFirst:"Select a CLI or ACP provider first",selectProvider:"Select a provider",workspaceRemoved:"Workspace removed",workspaceLabelUpdated:"Workspace name updated",defaultWorkspaceUpdated:"Default workspace updated",defaultWorkspaceCleared:"Default workspace cleared",idesFound_one:"Found {{count}} IDE",idesFound_other:"Found {{count}} IDEs"},logsTabSections:{view:"View",filterInfo:"Info+ ({{count}})",filterIssues:"Issues ({{count}})",filterAll:"All ({{count}})",searchPlaceholder:"Search diagnostics…",copyDiagnostics:"Copy diagnostics",copyVisible:"Copy visible",pause:"Pause",resume:"Resume",refresh:"↻ Refresh",clear:"Clear",advancedSourceScope:"Advanced source scope",daemonLevelPlus:"Daemon {{level}}+",diagnosticsTimeline:"Diagnostics timeline",visibleEventsIssues:"{{events}} visible event(s) · {{issues}} issue signal(s)",filteredBy:"Filtered by “{{query}}”",mergedByTime:"Daemon, trace, and browser signals merged by time",latestIssue:"Latest issue",noVisibleIssue:"No visible warn/error signal",sourceStatus:"Source status",needsAttention:"Needs attention",livePolling:"Live polling every 3s",paused:"Paused",lastUpdate:"Last update: {{time}}",notYetLoaded:"Not yet loaded",rawFile:"raw file",sourceDaemon:"daemon",sourceTrace:"trace",sourceBrowser:"browser",repeatedIssuePatterns:"Repeated issue patterns",unifiedTimeline:"Unified timeline",visibleDiagnosticEvents:"{{count}} visible diagnostic event(s)",hide:"Hide",show:"Show",loadingDiagnostics:"Loading diagnostics…",daemonLogsError:"Daemon logs: {{error}}",daemonTraceError:"Daemon trace: {{error}}",noDiagnosticsMatch:"No diagnostics match the current view.",rawSourceDaemonLogs:"Raw source · daemon logs",visibleRawLinesFallback:"{{count}} visible raw line(s) from file fallback",visibleStructuredLines:"{{count}} visible structured line(s)",loadingDaemonLogs:"Loading daemon logs…",noDaemonLogsYet:"No daemon logs captured yet for this machine.",noRawLinesMatchSearch:"No raw daemon log lines match the current search.",rawFallbackOnlyInAll:"Raw file-fallback logs are available only in All view.",noStructuredLogsMatch:"No structured daemon logs match the current view.",rawSourceDaemonTrace:"Raw source · daemon trace",sessionHostOnly:"session_host only",visibleTraceEvents:"{{count}} visible trace event(s)",loadingDaemonTrace:"Loading daemon trace…",noTraceEntriesMatchSearch:"No trace entries match the current search.",noSessionHostTraceYet:"No session host trace entries yet.",noTraceEntriesYet:"No trace entries yet.",noPayload:"No payload",rawSourceBrowserEvents:"Raw source · browser debug events",visibleBrowserEvents:"{{count}} visible browser event(s)",noBrowserEventsMatchSearch:"No browser debug events match the current search.",noBrowserEventsYet:"No browser debug events captured yet."}},Ok={transition:{recover:"Recovered",detach:"Detached",attach:"Attached",start:"Started",stop:"Stopped",restart:"Restarted",resume:"Resumed"},lastErrorLabel:"Last error",endpointLabel:"Endpoint",activeAgo:"active {{time}}",title:"Hosted Runtime Recovery",stopConfirmTitle:"Stop {{name}}?",stopConfirmDescription:"This will terminate the hosted runtime.",pruneConfirmTitle:"Prune duplicate hosted runtimes?",pruneConfirmDescription:"The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.",prune:"Prune",pruning:"Pruning…",pruneDuplicatesCount:"Prune duplicates ({{count}})",toastResumed:"Session host resumed: {{name}}",toastRestarted:"Session host restarted: {{name}}",toastStopped:"Session host stopped: {{name}}",toastPruned:"Pruned {{pruned}} duplicate runtime(s) across {{groups}} group(s)",actionFailed:"Session host action failed",pruneFailed:"Duplicate prune failed",diagnosticsFailed:"Could not load hosted runtime diagnostics",diagnosticsAttention:"Hosted runtime diagnostics need attention",stop:"Stop",stopping:"Stopping…",restart:"Restart",restarting:"Restarting…",resume:"Resume",resuming:"Resuming…",recover:"Recover",recovering:"Recovering…",refresh:"Refresh",refreshing:"Refreshing…",noWorkspace:"No workspace",clientsCount_one:"{{count}} client",clientsCount_other:"{{count}} clients",dashboardSessions_one:"{{count}} dashboard session",dashboardSessions_other:"{{count}} dashboard sessions",statLive:"Live runtimes",statRecovery:"Recovery",statRequests:"Requests",statStarted:"Started",latestWarning:"Latest host warning",liveTitle:"Live Hosted Runtimes",recoveryTitle:"Recovery Snapshots",inactiveTitle:"Inactive Records",recentActivity:"Recent Host Activity",liveEmpty:"No live hosted runtimes on this machine right now.",recoveryEmpty:"No recovery snapshots currently need attention.",transitionsEmpty:"No recent runtime transitions yet.",nextAction:"Next: {{action}}"},$k={managed:"Managed",checking:"Checking…",diagnosticsIssue:"Diagnostics issue",unavailable:"Unavailable",restoredAfterRestart:"restored after restart",restoreFailed:"restore failed",hostRestartInterrupted:"host restart interrupted",snapshotRecovered:"snapshot recovered",attach:"Attach",recover:"Recover",restart:"Restart",hintLive:"These runtimes are live now and are the only attachable targets.",hintRecovery:"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.",hintInactive:"These inactive records are shown for reference and usually need restart before they are useful again.",lifecycleStarting:"Starting",lifecycleRunning:"Running",lifecycleStopping:"Stopping",lifecycleStopped:"Stopped",lifecycleFailed:"Failed",lifecycleInterrupted:"Interrupted"},Fk={advancedTitle:"Advanced",mobileMode:{workspaceMode:"Workspace",chatMode:"Chat mode",descriptionWorkspace:"Use the full workspace layout on phones and tablets.",descriptionChat:"Use the chat-first mobile inbox layout, closer to a messaging app.",label:"Mobile inbox (chat mode)"},theme:{preset:{honey:"Warm yellow accents",aurora:"Pink accent theme",ember:"Default amber theme, inspired by the landing page",midnight:"Classic violet theme"},presetCustomDescription:"Full app + chat customization",helloHelp:"Hello! How can I help?",fixBug:"Fix the bug please",onIt:"On it! ✨",customEditorTitle:"Custom Theme Editor",darkMode:"Dark mode",lightMode:"Light mode",sectionAppBackground:"App Background",sectionAppText:"App Text",sectionBordersAccent:"Borders & Accent",sectionChatBubbles:"Chat Bubbles",sectionChatLayout:"Chat Layout",colorBackground:"Background",colorSurface:"Surface",colorCard:"Card",colorPrimary:"Primary",colorSecondary:"Secondary",colorMuted:"Muted",colorBorderSubtle:"Border subtle",colorBorderDefault:"Border default",colorAccent:"Accent",colorUserBubble:"User bubble",colorUserText:"User text",colorAgentBubble:"Agent bubble",colorAgentText:"Agent text",colorChatBg:"Chat BG",colorSendButton:"Send button",colorInputBorder:"Input border",labelBubbleRadius:"Bubble radius",resetToDefaults:"Reset to defaults",customLabel:"Custom"},providerPriority:{undetectedHint_other:"{{count}} providers aren't detected here — kept in order, skipped until available.",undetectedHint_one:"{{count}} provider isn't detected here — kept in order, skipped until available.",orderHint:"Launches use this order, top to bottom.",noMoreProviders:"No other CLI providers detected",selectProvider:"Select provider…",moveDown:"Move down",moveUp:"Move up",keptUntilDetected:"Kept in order; skipped at launch until it's detected on this machine.",emptyWarning:"No provider priority configured. Launches that don't name a CLI provider will be refused.",available:"available",notOnMachine:"Not detected",remove:"Remove",addCliLabel:"Add available CLI provider",addProvider:"Add provider"},coordinatorPrompts:{saveFailed:"Couldn't save",loadFailed:"Couldn't load coordinator prompts",save:"Save",saved:"Saved",saving:"Saving…",appendPlaceholder:"(empty — nothing added at this layer)",overridePlaceholder:"(empty — use the default base prompt)",placeholdersHint:"Placeholders you can use:",resetHint:"Leave a field empty and save to remove it (back to the default).",intro:"Customize the prompt that this daemon's mesh coordinator sessions receive.",loading:"Loading…",connectDaemon:"Connect a daemon to edit coordinator prompts.",overrideDesc:"<strong>Override</strong> replaces the daemon's built-in base prompt for that CLI.",appendDesc:"<strong>Append</strong> stacks after whichever base wins.",overrideLabel:"Override",appendLabel:"Append",expandLabel:"Edit prompts",collapseLabel:"Collapse",customizedBadge:"Customized",collapsedNone:"No custom prompts — using daemon defaults.",tabsAriaLabel:"Coordinator prompt provider",sectionTitle:"Coordinator prompts",sectionDescription:"Per-CLI base prompt for mesh coordinator sessions on this machine. Mesh-level prompts live on the Repo Mesh page."},appearance:{modeSystem:"System",modeLight:"Light",modeDark:"Dark",modeLabel:"Mode",themeLabel:"Theme",mobileLabel:"Mobile",chatLabel:"Chat"},chatActivity:{rowLabel:"Show agent activity in chat",descriptionOn:"Tool calls, terminal output and thinking are shown between chat messages.",descriptionOff:"Only the conversation is shown. Tool calls, terminal output and thinking stay hidden."}},Hk={chatHistory:"Chat History",startNewChat:"+ Start New Chat Session",creating:"Creating...",searchPlaceholder:"Search title or preview",filterWorkspace:"Filter by workspace",filterModel:"Filter by model",sortRecent:"Most recent",sortOldest:"Oldest first",sortMessages:"Most messages",resumeReadyOnly:"Resume-ready only",untitledSession:"Untitled Session",noSavedPreview:"No saved preview yet",workspaceUnknown:"Workspace unknown",selectedWorkspaceSuffix:" · selected workspace",msgCount:"{{count}} msgs",statusActive:"ACTIVE",statusMissingWorkspace:"MISSING WORKSPACE",statusResumeSelectedWorkspace:"RESUME IN SELECTED WORKSPACE",statusResuming:"RESUMING...",statusResume:"RESUME",noMatchingHistory:"No saved history matches these filters.",noRecentChats:"No recent chat sessions found.",refreshHistory:"Refresh History",refreshing:"Refreshing...",confirmSwitchTitle:"Switch session?",confirmSwitchDescription:'Switch to "{{target}}"? This will leave your current view.',confirmSwitchAction:"Switch"},Bk={gallery:{next:"Next view",previous:"Previous view"},nav:{home:"ADHDev Home",mesh:"Mesh",what:"What",agents:"Agents",pricing:"Pricing",install:"Install",github:"GitHub",docs:"Docs",getStarted:"Get started",toggleMenu:"Toggle menu",mainNavigation:"Main navigation"},hero:{badge:"Multi-vendor, multi-machine agent control plane",title:"Manage the coding agents running on your computer — from anywhere.",subtitleInstall:"Install ADHDev on your <os></os>.",subtitlePlace:"use your <device></device>",subtitleAsk:"to ask <coordinator></coordinator> to send <worker></worker> to <verb></verb> your repo.",subtitleFrom:"from <place></place>",anywhere:"anywhere",subtitleLand:"Ten agents at once — none of them step on each other.",axes:{os:["Mac","Windows","Linux"],place:["the subway","a cafe","your parents' place","bed","the couch","the garden","the passenger seat","the ferry","the toilet","inside a container","the moon","a server rack"],device:["desktop","laptop","tablet","mobile phone"],verb:["debug","build","test","review"]},copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",getStarted:"Get started free",orInstall:"Or install the CLI",openSource:"Open source on GitHub",joinDiscord:"Join Discord",selfHost:"Self-host it",demoDesktop:"ADHDev command center driving live agent sessions across multiple machines",demoPush:"ADHDev mobile push notification and one-tap approval"},mesh:{sectionTitle:"Parallel agents that don't step on each other.",sectionSubtitle:"Running agents in parallel is the easy part — every tool does it now. The hard part is what comes after: a pile of branches that still have to be checked and merged. ADHDev does that for you, so finished work arrives on main instead of in your review queue.",refineryHighlight:"Automatic landing",refineryTitle:"Finished work merges to main on its own",refineryDesc:"Anyone can run ten agents at once. ADHDev then checks each branch against your project's own tests and lint, merges the ones that pass cleanly into main, and tidies up — automatically, and never with a force-push. Anything unclear is held back for you to review instead of merged.",asyncHighlight:"One place to drive it",asyncTitle:"You talk to one place. It runs the rest.",asyncDesc:"You hand work to a single coordinator, and it runs every agent across every machine for you. It only pings you when something needs approval or finishes — so there's no queue of agent windows to watch and nothing to sit in front of.",crossPlatformHighlight:"Every OS at once",crossPlatformTitle:"Mac, Windows, Linux — all at once",crossPlatformDesc:"Send a task to a specific operating system with one tag. A single prompt can build, test, or verify across Mac, Windows, and Linux machines you already own — in parallel, with no SSH setup and no virtual machines.",monoHighlight:"Works with real repos",monoTitle:"Safe even with git submodules",monoDesc:"Real production repos nest submodules — exactly where naive auto-merge breaks. ADHDev handles them safely: it makes sure submodule changes are published and pointed at correctly before it touches main. This project is itself a repo with two submodules, merged this way every day.",crossHighlight:"Second opinion",crossTitle:"Consensus over a single opinion",crossSubtitle:"MAGI — Multi-Agent Ground-truth Insight",crossDesc:"Ask the same read-only question to several machines and models at once, then see where they agree and disagree (MAGI) — more trustworthy than one agent's answer.",tryMesh:"Try Repo Mesh →",seePlans:"See plans",availableOn:"Connect a machine and open the <strong>Repo Mesh</strong> page to get started.",readGuide:"Read the guide"},compare:{sectionTitle:"Everyone runs agents in parallel. Not everyone keeps them out of each other's way.",sectionSubtitle:"A fair question. Local CLIs spawn subagents; desktop orchestrators fan work across worktrees with a slick native UI. Both stop at the branch. Here's the honest line — including where each of them beats us — with no hand-waving.",colLocalCli:"Local CLI + subagents",colDesktop:"Desktop orchestrator",colAdhdev:"ADHDev Repo Mesh",rowLandsMain:"Lands finished work on main",rowLandsMainLocalCli:"You run the gates and merge by hand",rowLandsMainDesktop:"Parallelizes the work, then hands you the branches to review",rowLandsMainAdhdev:"The Refinery runs your repo's gates, checks patch equivalence, and fast-forwards main — unattended, no force-push",rowSubmodules:"Safe with git submodules",rowSubmodulesLocalCli:"No merge automation to be aware of them",rowSubmodulesDesktop:"Worktree parallelism, but the merge is yours to get right",rowSubmodulesAdhdev:"Submodule-aware convergence: reachability gate, patch-equivalence check, atomic pointer bump — dogfooded on this monorepo daily",rowAsync:"Talk to one place, async",rowAsyncLocalCli:"One session at a time, synchronously",rowAsyncDesktop:"You supervise each agent window yourself",rowAsyncAdhdev:"One coordinator drives every worker on an event loop — it waits on completion/approval events, you don't poll or babysit",rowMultiMachine:"Multiple physical machines",rowMultiMachineLocalCli:"One host's processes only",rowMultiMachineDesktop:"Bound to the one machine it runs on",rowMultiMachineAdhdev:"Remote daemons over P2P — Mac, Windows, and Linux nodes in one mesh, no SSH plumbing",rowParallelBranch:"Parallel isolated-branch work",rowParallelBranchLocalCli:"Subagents share one working tree — concurrent writes collide",rowParallelBranchDesktop:"One git worktree per task — a core strength",rowParallelBranchAdhdev:"One git worktree per node — parallel across machines, not just cores",rowBrowser:"Drive it from a browser or phone",rowBrowserLocalCli:"You have to be at the terminal",rowBrowserDesktop:"Native desktop app — you're at that desk",rowBrowserAdhdev:"Web-first: control sessions and approve from any browser or phone",rowNativeApp:"Native desktop app",rowNativeAppLocalCli:"Terminal only",rowNativeAppDesktop:"Polished native window — genuinely nicer to sit in front of",rowNativeAppAdhdev:"We're web-first — a browser tab, not a native app",rowRestarts:"Survives restarts & context loss",rowRestartsLocalCli:"State lives in a session — close it and it's gone",rowRestartsDesktop:"State tied to the app process",rowRestartsAdhdev:"Missions persist to disk and resume after a coordinator or daemon restart — append-only, tamper-evident audit trail",rowCrossCheck:"Cross-check the answer",rowCrossCheckLocalCli:"One agent's take, no second opinion",rowCrossCheckDesktop:"Parallel work, single verdict",rowCrossCheckAdhdev:"MAGI fans the same read-only question to independent machine × provider agents and surfaces where they diverge",footnote:"For a single machine, a single branch, a one-shot task — a local CLI with subagents is lighter and works great, and a native desktop orchestrator is a nicer place to sit. Repo Mesh earns its keep when work fans out across machines and branches, needs to survive restarts, and should land on main automatically — controlled from wherever you are."},what:{sectionTitle:"Any agent, mixed freely",sectionSubtitle:"Vendor-neutral by design. Run Claude Code on the Mac, Codex on the Windows GPU box, Cursor CLI for review passes — in the same mesh, under the same policies. Switch vendors without switching platforms.",cliHighlight:"CLI agents",cliTitle:"Drive any terminal agent from the web",cliDesc:"Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Grok, Hermes, Kimi, and OpenCode — attached on your machine through a PTY adapter with proper resume and reconnect, driven from your browser. Send prompts and provide visual context instantly (paste, drag & drop, or upload multiple images at once, up to 5 images / 10MB each). Aider, Goose, and other ACP agents connect over stdio.",uiHighlight:"One UI",uiTitle:"Same dashboard, any device",uiDesc:"Cloud-hosted at adhf.dev — drive every agent from a laptop or phone, whether you're at your desk or away from it.",ideHighlight:"IDE agents",ideTitle:"Also: attach to running editors",ideDesc:"Cursor, VS Code, VSCodium, Windsurf, Antigravity, Kiro, PearAI, Trae. Read live chat, send prompts, switch sessions, capture screenshots.",p2pHighlight:"Yours, end to end",p2pTitle:"P2P-first: your data stays yours",p2pDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC. The cloud sees auth and signaling metadata, nothing else — your code never routes through the server."},oss:{sectionTitle:"Open source & self-hostable",sectionSubtitle:"The daemon and dashboard are AGPL-3.0 and available on GitHub. Run them yourself on any machine or server — no account required.",github:"GitHub",selfHostDocs:"Self-hosting docs"},agents:{sectionTitle:"Supported agents",sectionSubtitle:"{{ides}} built-in IDE integrations, {{clis}} built-in CLI agents, {{extensions}} IDE-resident extension agents, and {{acp}}+ ACP (stdio MCP) agents. Provider scripts live in <code>adhdev-providers/</code> — add your own under <code>~/.adhdev/providers/</code>.",tierTested:"Tested",tierTestedDesc:"validated against a real app + version",tierCommunity:"Community",tierCommunityDesc:"built-in and community-supported",groupIdes:"IDEs",hintIdes:"Attached via Chrome DevTools Protocol. Read chat, send prompts, switch sessions, screenshot.",groupCli:"CLI agents",hintCli:"Driven through a PTY adapter with resume and reconnect.",groupExtensions:"In-IDE extension agents",hintExtensions:"CDP webview attachment for agents that live inside another IDE.",acpFootnote:"Plus {{count}}+ ACP agents over stdio (Agent Client Protocol): Codex, Claude Agent, Goose, Cline, OpenHands, and more."},pricing:{sectionTitle:"Simple pricing as your agents grow",sectionSubtitle:"Start free on one machine. Go Pro for two, or Ultra for five. No per-seat math, no enterprise sales call — just the plans below.",mostPopular:"Most popular",upgradeToPro:"Upgrade to Pro",footnote:"Simple, transparent pricing — the prices above are what you'll pay. Prefer to self-host? The daemon and dashboard are open source. Prices in USD.",plans:{free:{period:"forever",tagline:"Everything you need to drive one machine from anywhere.",cta:"Start free",features:{machine:"One machine, paired in a single command",p2p:"P2P chat, commands, screenshots, remote input",providers:"Every provider — CLI, IDE, and ACP agents",push:"Push notifications for approvals & completions",share:"One shared session link"}},pro:{period:"/mo",tagline:"Two machines, more concurrent sessions, and TURN for restrictive networks — plus Repo Mesh to orchestrate agents across both.",cta:"Start 7-day Pro trial",features:{machines:"2 machines — run agents on both",p2p:"More concurrent P2P sessions",push:"Unlimited push notifications",turn:"TURN relay for restrictive networks",share:"More shared sessions"}},ultra:{period:"/mo",tagline:"Everything in Pro, scaled up — more machines and higher limits for heavy parallel work.",cta:"Go Ultra",features:{machines:"5 machines — flat price, not per-seat",everything:"Everything in Pro",p2p:"Highest concurrent P2P sessions",screenshots:"Unlimited daily screenshot minutes",webhooks:"Higher API call limits",share:"More shared sessions"}}}},install:{sectionTitle:"Three steps to a working dashboard",sectionSubtitle:"No configuration files. No API keys to wire up. ADHDev does not manage agent auth — each tool keeps its own login.",selectOs:"Select OS",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",platformNote:"macOS and Windows are the validated install paths. Linux runs the same Unix script and is community-tested.",arrow:"→",steps:{step1:{title:"Install the daemon",desc:"One curl command installs the daemon plus the adhdev CLI — the launcher you run to pair machines and start the daemon (not to be confused with the CLI agents it drives, like Claude Code or Codex). Same binary powers cloud and standalone."},step2:{title:"Link a machine",desc:"Sign in once with GitHub or Google and the daemon pairs itself — no token to copy."},step3:{title:"Drive your agents",desc:"Launch Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi, and other agents from the dashboard. Read chat, send prompts, provide visual context (paste, drag & drop, or upload multiple images at once), approve actions, and switch sessions."}}},cta:{headline:"Stop juggling tabs. Drive every agent from one dashboard.",subtitle:"One curl command, one daemon, every agent you already use. Drive them all from the web — Cloud is live.",getStarted:"Get started →",github:"GitHub",discord:"Discord"},footer:{docs:"Docs",github:"GitHub",discord:"Discord",dashboard:"Dashboard",terms:"Terms",privacy:"Privacy",contact:"Contact",copyright:"© {{year}} RacoLab. All rights reserved."},imagePaste:{sectionTitle:"Paste a screenshot. A terminal agent on another machine sees it instantly.",sectionSubtitle:"Grab a screenshot on your laptop or phone, paste it into the chat, and a CLI agent running in a terminal on a different machine gets it as visual context — no file juggling, no SSH. Paste, drag & drop, or upload up to 5 images (10MB each) at once.",point1:"Paste from clipboard, drag & drop, or upload",point2:"Up to 5 images, 10MB each",point3:"Lands in a PTY terminal agent on any of your machines",step1Label:"Paste the image, type a question",step2Label:"Sent — the agent picks it up",step3Label:"It saw the image and answered"},mobile:{sectionTitle:"Leave your desk. Your agents keep going.",sectionSubtitle:"A push notification hits your phone when an agent needs approval or finishes. Tap it, approve or reject, then follow up in chat — all from the mobile dashboard, wherever you are.",point1:"Push notification on approval or completion",point2:"One tap to approve or reject",point3:"Follow up with a chat instruction, then put your phone away",notificationLabel:"Mobile push notification for an agent approval",resumeLabel:"Approving and following up from the mobile dashboard",deviceShotLabel:"Real iOS lock-screen notifications showing grouped ADHDev push alerts for agent completions and approvals",deviceShotCaption:"Real device — actual push notifications on a phone",point4:"No port forwarding, no VPN, no DMZ — P2P with TURN relay connects from cafés, hotspots, desktop or laptop, anywhere with internet"},brain:{sectionTitle:"Cheap models for easy work. Expensive ones only when it's hard.",sectionSubtitle:"Tag a task easy, medium, or difficult and the mesh applies a matching preset — provider, model, and thinking budget. Routine work runs on a cheap fast model; only the hard tasks reach for the expensive one. You spend tokens where they matter.",point1:"Difficulty-based presets: easy / medium / difficult",point2:"Each preset picks provider, model, and thinking level",point3:"Save tokens without hand-tuning every task"},scenario:{sectionTitle:"One prompt. Mac builds, Windows tests, main lands.",sectionSubtitle:"A real session in three steps: you describe the work once, agents run in parallel across your machines, and finished code arrives on main — without you sitting at the terminal.",step1Label:"Describe the work",step1Desc:"Tell it what to build, in one sentence. No config, no setup per machine.",step2Label:"Agents run in parallel",step2Desc:"The work splits across your Mac and Windows machines at once — each on its own branch, each running your project's tests and checks.",step3Label:"Finished code lands on main",step3Desc:"When the checks pass, the work merges into main automatically and safely. Anything unclear is held back for you to review — never force-pushed.",caveat:"Mac and Windows are the verified daily-driver machines. Linux is also supported."}},Wk={submit:"Submit",submitting:"Submitting…",cancelAria:"Cancel the question",actionRequired:"Action Required",selectAllThatApply:"Select all that apply",multipleChoice:"Multiple choice",singleChoice:"Single choice",other:"Other",answersRequired_one:"{{count}} question still needs an answer",answersRequired_other:"{{count}} questions still need answers",errorReviewPageNotFocused:"The terminal is showing a different screen, so the answer was not submitted — check the terminal screen or close this and try again.",errorReviewUnconfirmed:"The answer keys reached the terminal, but the question is still on screen — the answer may not have been submitted. Check the terminal: if it was not submitted, answer there; resending from here could submit it twice."},Uk={diffPreview:{truncatedAfter:"locally for the full output.",truncatedBefore:"Changes truncated — run",empty:"No changes to show.",binary:"Binary file — changes can't be shown.",loading:"Loading changes…"},changeList:{stagedHint:"Staged",noChanges:"No changed files.",binaryBadge:"bin",truncatedNote:"File list truncated — run <code>git status</code> locally for full output."},statusDialog:{working:"Working…",includeUntracked:"Include untracked files",messageRequired:"Message (required)",fileFallback:"file",confirmRevert:"Revert changes to {{path}}?",confirmPop:"Restore latest stash?",confirmStash:"Stash changes",confirmCheckpoint:"Create checkpoint commit",copySummary:"Copy summary",copied:"Copied to clipboard",checkoutSelected:"Revert selected",selectFileToRevert:"Select a file to revert",revertFile:"Revert changes to {{path}}",popStash:"Restore stash",noStashes:"No stashes to restore",popHint:"Restore the latest stash",resolveBeforePop:"Resolve conflicts before restoring a stash",stash:"Stash",stashHint:"Set current changes aside (git stash)",resolveBeforeStash:"Resolve conflicts before stashing",checkpoint:"Checkpoint",checkpointHint:"Create a git commit as a checkpoint",resolveBeforeCheckpoint:"Resolve conflicts before creating a checkpoint",selectFile:"Select a file to view its changes",noDiffData:"No diff data.",loading:"Loading…",fileCount_other:"{{count}} files",fileCount_one:"{{count}} file",stashed:"{{count}} stashed",deleted:"{{count}} deleted",untracked:"{{count}} untracked",modified:"{{count}} modified",staged:"{{count}} staged",behind:"{{count}} behind",ahead:"{{count}} ahead",refresh:"Refresh",openOnGithub:"Open on GitHub",title:"Git status",conflicts:"conflicts",clean:"clean"}},Kk={machineProviders:"Machine → Providers",perProviderIntro:"Per-provider alerts and auto-approve:",mixed:"(some off)",agentAlert:{noProgressDesc:"Alert when an agent has shown no progress for a while.",noProgress:"No progress",approvalDesc:"Alert when an agent is waiting for your approval.",approval:"Approval needed"},agentAlertsDesc:"Applies to every provider on your online machines. Fine-tune one provider in Machine → Providers.",permissionUnsupportedChip:"Not supported",permissionBlockedChip:"Blocked",permissionNeededChip:"Permission needed",permissionAllowedChip:"Allowed",title:"Notifications",subtitle:"Browser, push and agent alerts",sectionBrowserAlerts:"Browser alerts",masterToggleLabel:"Notifications",masterToggleDesc:"Master toggle for all alerts",browserNotificationsLabel:"Browser Notifications",browserNotificationsDesc:"Desktop alerts when tab is inactive",browserBackgroundInfo:"Browser alerts only fire while this dashboard tab stays open in the background.",browserBackgroundInfoWithPush:"Browser alerts only fire while this dashboard tab stays open in the background. If you close the tab, use Push Notifications instead.",permissionDefault:"This browser has not granted notification permission yet. Allow it to receive browser alerts.",allowNotifications:"Allow notifications",permissionDenied:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive desktop alerts.",permissionUnsupported:"This browser cannot show desktop notifications here. Use a supported desktop browser, or rely on Push Notifications where available.",completionAlertsLabel:"Completion Alerts",completionAlertsDesc:"Notify when agent finishes a task",approvalAlertsLabel:"Approval Alerts",approvalAlertsDesc:"Notify when agent needs approval",connectionAlertsLabel:"Connection Alerts",connectionAlertsDesc:"Alert when a machine disconnects",allDisabled:"All notifications are off.",sectionProviderAlerts:"Agent alerts",loading:"Loading...",refresh:"Refresh",noOnlineMachines:"No machines online.",loadingProviderSettings:"Loading provider settings...",soundEffectsLabel:"Sound Effects",soundEffectsDesc:"Play a sound when agent completes or needs approval"},qk={pageTitle:"Approvals",pageSubtitle:"Sessions waiting on your decision.",pending:"Pending",loading:"Loading approvals…",emptyHint:"Approvals from any connected machine will appear here automatically."},zk={title:"Guided mesh setup",close:"Close",machines:{title:"Select machines",description:"Pick the mesh to set up and attach the machines that should run its work. Creating a mesh also attaches the chosen workspace as its first node.",noMachinesDescription:"No machine is registered yet. Install the daemon on a machine first — it pairs automatically once signed in.",noMachinesFallback:"Start the local daemon and return here.",nodeCount:"{{count}} nodes",createNew:"Create new mesh",loadingMeshes:"Loading meshes…",meshName:"Mesh name",machine:"Machine",machineSelectPlaceholder:"Select a machine",workspace:"Workspace (repo path)",workspacePlaceholder:"/path/to/repo",workspaceSelectPlaceholder:"Select a workspace",workspaceCustom:"Enter a path manually…",pickFromKnown:"Pick from known workspaces",planChecking:"Checking the workspace…",planOk:"Workspace looks good: {{identity}}",planExists:"This workspace already belongs to an existing mesh — add it as a node there instead of creating a new mesh.",creating:"Creating…",create:"Create mesh",createFailed:"Create failed",attachTitle:"Attach another machine",allMachinesAttached:"Every registered machine is already attached to this mesh.",attaching:"Attaching…",addMachine:"Add machine"},quotaPolicy:{blankMeansDefaultShort:"Blank = default",title:"Quota-aware routing",description:"When a node reports how much of its AI provider quota is left, the coordinator can skip nodes that are nearly exhausted and prefer nodes with more headroom. These thresholds decide when that happens. Missing or outdated readings are always ignored, so a node is never excluded on stale data.",sessionMin:"Session floor",sessionMinHint:"Skip a provider whose short rolling window has less than this left.",weeklyMin:"Weekly floor",weeklyMinHint:"Skip a provider whose weekly window has less than this left.",resetImminent:"Reset grace",resetImminentHint:"Ignore a low session window when it resets within this long.",staleAfter:"Reading expiry",staleAfterHint:"Fallback only: a measured window stays valid until its own reset; this age limit applies just to readings without a reset time.",spreadBonus:"Headroom preference",spreadBonusHint:"How strongly more remaining quota is preferred. Never overrides a task-difficulty match.",sessionAxisWeeklyHeadroom:"Weekly headroom for session urgency",sessionAxisWeeklyHeadroomHint:"Only prioritize an imminent 5-hour session-window reset when weekly quota remaining is at or above this. Unused 5-hour quota is lost forever, but burning it when the weekly window is already tight costs more than it saves.",minutes:"min",blankMeansDefault:"Leave a field blank to use its default (shown as the greyed-out value).",useDefaults:"Use defaults",saving:"Saving…",errors:{notANumber:"Enter a number.",percentRange:"Must be between 0 and 100.",negative:"Cannot be negative."}},continueToMesh:"Continue to Mesh"},Gk={dashboard:"Dashboard",machines:"Machines",notifications:"Notifications",mesh:"Mesh",marketplace:"Marketplace",api:"API",webhooks:"Webhooks",account:"Account",settings:"Settings",docs:"Docs",about:"About",chats:"Chats"},Vk={controls:ok,sessionStatus:ak,language:ik,common:lk,connection:ck,toast:dk,notification:uk,event:mk,dashboard:hk,cliStop:pk,approval:fk,chatControls:gk,newSession:bk,mobileInbox:xk,mesh:yk,chat:vk,chatPane:wk,chatInput:Sk,paneGroup:kk,terminal:jk,conversation:Nk,cliView:Ck,launch:_k,standalone:Ak,cloud:Tk,app:Ik,chatList:Mk,screenshot:Rk,remote:Pk,sessionNav:Lk,sessionInfo:Ek,machine:Dk,sessionHost:Ok,sessionHostSurface:$k,settings:Fk,historyModal:Hk,landing:Bk,interactivePrompt:Wk,git:Uk,notifications:Kk,approvals:qk,setupWizard:zk,nav:Gk},xc="lang",yo="common",Yk={ko:()=>kr(()=>import("./common-d2kkUuhU.js"),[]),ja:()=>kr(()=>import("./common-DMhfgNQ0.js"),[]),"zh-CN":()=>kr(()=>import("./common-Cw-N7oC7.js"),[]),es:()=>kr(()=>import("./common-CMA7YhWW.js"),[])};async function Qk(e){return!Us(e)||e===zs?null:(await Yk[e]()).default}const Jk={type:"backend",init(){},read(e,t,s){if(t!==yo){s(null,{});return}Qk(e).then(r=>s(null,r??{}),r=>s(r instanceof Error?r:new Error(String(r)),!1))}};function Xk(e){return{resources:{[zs]:{[yo]:Vk}},partialBundledLanguages:!0,lng:e,fallbackLng:zs,supportedLngs:If,ns:[yo],defaultNS:yo,interpolation:{escapeValue:!1},returnEmptyString:!1,react:{transKeepBasicHtmlNodesFor:["br","strong","i","p","em"]}}}function Zk(){try{const e=localStorage.getItem(xc);if(Us(e))return e}catch{}return null}function Mf(){const e=Zk();return e||(typeof navigator<"u"?rk(navigator.language):zs)}function yc(e){typeof document>"u"||document.documentElement.setAttribute("lang",e)}let Ao=null,Rf=!1;function Pf(){if(Ao)return at;const e=Mf();return Ao=at.use(Jk).use(Xx).init(Xk(e)).then(()=>{},()=>{}).finally(()=>{Rf=!0}),yc(e),at}function ej(){return Rf?!0:!!Ao&&at.isInitialized&&at.hasLoadedNamespace(yo)}function tj(){return Ao||Pf(),Ao}function Gt(e){return(typeof e=="string"?e.trim():"")||void 0}function rs(e,t){const s=Gt(t);return s?`${e}:${s}`:void 0}function ys(e,t,s){const r=rs(t,s),o=Gt(s);r&&e.push(r),o&&e.push(o)}function jr(e){const t=[],s=new Set;for(const r of e)!r||s.has(r)||(s.add(r),t.push(r));return t}function Lf(e){return Gt(e.providerSessionId)||Gt(e.sessionId)||Gt(e.tabKey)||Gt(e.routeId)}function Ai(e){return jr([Gt(e.historySessionId),Gt(e.providerSessionId),Gt(e.sessionId)])}function vo(e){const t=[];return ys(t,"provider",e.providerSessionId),ys(t,"session",e.sessionId),ys(t,"tab",e.tabKey),ys(t,"route",e.routeId),jr(t)}function nj(e){const t=[];return Gt(e.providerSessionId)?(ys(t,"provider",e.providerSessionId),jr(t)):Gt(e.sessionId)?(ys(t,"session",e.sessionId),jr(t)):Gt(e.tabKey)?(ys(t,"tab",e.tabKey),jr(t)):Gt(e.routeId)?(ys(t,"route",e.routeId),jr(t)):[]}function Ef(e){return rs("provider",e.providerSessionId)||rs("session",e.sessionId)||rs("tab",e.tabKey)||rs("route",e.routeId)||"unknown:"}function Ti(e){return Ai(e)[0]}function Ii(e){const t=Gt(e.sessionId),s=Ti(e);if(s&&!(t&&s===t))return s}function sj(e){const t=Gt(e.providerSessionId),s=Gt(e.sessionId),r=Gt(e.tabKey),o=Gt(e.routeId),a=[rs("provider",t),rs("session",s),rs("tab",r),rs("route",o)].filter(d=>typeof d=="string"),i=vo({providerSessionId:t,sessionId:s,tabKey:r,routeId:o}),c=Ef({providerSessionId:t,sessionId:s,tabKey:r,routeId:o});return{providerSessionId:t,sessionId:s,tabKey:r,routeId:o,canonicalKey:c,targetKey:c,targetValue:Lf({providerSessionId:t,sessionId:s,tabKey:r,routeId:o}),historySessionId:Ti({providerSessionId:t,sessionId:s}),runtimeSessionId:s,allKeys:a,lookupKeys:i}}function ho(e,t){const s=sj(e);return nj(t).some(r=>s.lookupKeys.includes(r))}function Df(e){const t=String(e.daemonId||"").trim(),s=String(e.id||"").trim();return t&&s.startsWith(`${t}:`)?s.slice(t.length+1):s}function vc(e){if(String(e.ownerDaemonId||"").trim())return!0;const t=e.settings;return t?!!t.meshNodeFor||!!t.meshNodeId||t.launchedByCoordinator===!0||t._remoteOwnedSession===!0:!1}function rj(e,t){const s=String(e.daemonId||"").trim(),r=String(e.id||"").trim(),o=Df(e);if(o&&t.has(o))return`mesh:${o}`;const a=String(e.ownerDaemonId||"").trim()||s;return a?o?`${a}:${o}`:a:r}function ul(e,t){return t||e||"unknown"}function oj(e,t){return e.ownerDaemonId&&(t==null?void 0:t[e.ownerDaemonId])||e.ownerMachineName||void 0||e.daemonId&&(t==null?void 0:t[e.daemonId])||void 0}const aj={vscode:"VS Code",pearai:"PearAI"};function Kt(e){return e?e.split("-").map(t=>aj[t.toLowerCase()]||t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function ij(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const s=Math.floor(t/60),r=t%60;if(s<24)return r>0?`${s}h ${r}m`:`${s}h`;const o=Math.floor(s/24),a=s%24;return`${o}d ${a}h`}function ml(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function _a(e,t){const s=typeof t=="string"?t.trim():"";if(s)return s;const r=typeof e=="string"?e.trim():"";if(!r)return"";const o=r.replace(/[\\/]+$/,""),a=o.split(/[\\/]/).filter(Boolean);return a[a.length-1]||o}function lj(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),s=t[t.length-1];return s.length>12?`Machine-${s.substring(0,8)}`:s}return e}function cj(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function dj(e){return lj(e.trim().replace(/\.local$/i,""))}function Of(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function jd(e,t={}){var o,a;const s=[e.hostname,(o=e.machine)==null?void 0:o.hostname,(a=e.system)==null?void 0:a.hostname].find(i=>typeof i=="string"&&i.trim().length>0&&!cj(i));if(s&&s!=="Unknown")return dj(s);const r=t.fallbackId||e.id;return r?`Machine-${r.substring(0,8)}`:t.fallbackLabel||"Machine"}function Tn(e,t={}){return Of(e)||jd(e,t)}function $f(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function Ff(e,t,s={}){const r=String(t).trim();if(!e||!Array.isArray(e.items)||!r)return"";const o=e.items.find(a=>String((a==null?void 0:a.id)||"").trim()===r);return o?String(s.preferShortValue?o.shortValue||o.value||"":o.value||o.shortValue||"").trim():""}function tr(e,t){return $f(e).join(" · ")}function To(e){return e.transport==="pty"}function Nr(e){return e.transport==="acp"}const Hf={darwin:"macOS",linux:"Linux",win32:"Windows"};function uj(e,t){var s,r;return(s=t==null?void 0:t.providerLabels)!=null&&s[e]?t.providerLabels[e]:(r=t==null?void 0:t.providerLabels)!=null&&r[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:Kt(e)}function sm(e,t,s){const r=(e||"").trim().toLowerCase();if(!r)return!0;const o=(t||"").trim().toLowerCase(),a=(s||"").trim().toLowerCase(),i=Kt(s||"").trim().toLowerCase();return r===o||r===a||r===i}function mj(e,t=[],s=[]){var d,u,m,h;const r=vn(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(r==="waiting_approval")return"waiting_approval";if(r==="waiting_choice")return"waiting_choice";if(r==="generating")return"generating";const o=t.find(p=>Zu(p.status,{activeModal:p.activeModal})||pc(p.status));if(o)return vn(o.status,{activeModal:o.activeModal});const a=s.find(p=>Zu(p.status,{activeModal:p.activeModal})||pc(p.status));if(a)return vn(a.status,{activeModal:a.activeModal});if(r&&r!=="idle")return r;const i=vn((d=t[0])==null?void 0:d.status,{activeModal:(u=t[0])==null?void 0:u.activeModal});if(i!=="idle")return i;const c=vn((m=s[0])==null?void 0:m.status,{activeModal:(h=s[0])==null?void 0:h.activeModal});return c!=="idle"?c:"idle"}function hj(e){return vn(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function pj(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,s=["generating","finalizing","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const r of e){const o=(r.name||r.id||"").toLowerCase().replace(/\s+/g,"-"),a=t.get(o),i=vn(r.status);if(!a){t.set(o,{...r,status:i});continue}const c=s.indexOf(a.status||"idle"),d=s.indexOf(i||"idle");d>=0&&(c<0||d<c)&&t.set(o,{...r,status:i})}return Array.from(t.values())}function fj(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function gj(e){var s,r;const t=(r=(s=e==null?void 0:e.messages)==null?void 0:s.at)==null?void 0:r.call(s,-1);return t&&fj(t.receivedAt)||0}function bj(e){return(e.recentLaunches||[]).reduce((s,r)=>Math.max(s,r.lastLaunchedAt||0),0)}function wc(e){return Math.max(bj(e),gj(e.activeChat))}function xj(e,t,s,r,o,a){const i=t-e;if(i!==0)return i;const c=s.localeCompare(r);return c!==0?c:o.localeCompare(a)}function za(e,t){return xj(wc(e),wc(t),Tn(e,{fallbackId:e.id}),Tn(t,{fallbackId:t.id}),e.id,t.id)}const Bf="adhdev_notification_prefs",rm={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function yj(){try{const e=localStorage.getItem(Bf);if(e){const t=JSON.parse(e);return{...rm,...t}}}catch{}return{...rm}}function vj(e){try{localStorage.setItem(Bf,JSON.stringify(e))}catch{}}let ss=yj(),Aa=[];function wj(){Aa.forEach(e=>e())}function Sj(e){ss={...ss,...e},vj(ss),wj()}function kj(){const[,e]=l.useState(0);l.useEffect(()=>{const s=()=>e(r=>r+1);return Aa.push(s),()=>{Aa=Aa.filter(r=>r!==s)}},[]);const t=l.useCallback(s=>{Sj(s)},[]);return[{...ss},t]}function wo(e){if(!ss.globalEnabled)return!1;switch(e){case"disconnect":return ss.disconnectAlert;case"completion":return ss.completionAlert;case"approval":return ss.approvalAlert;case"browser":return ss.browserNotifications;default:return!0}}const jj={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Wf(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Uf(){return"Notification"in window&&Notification.permission==="granted"}function Nj(e,t,s){return e?!(s==="waiting_choice"&&t!=="waiting_choice"):!1}let Ls=null;function Cj(e){return e!==!1}async function _j(){if(Ls!==null)return Ls;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Ls=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Ls=!!await e.pushManager.getSubscription(),Ls):(Ls=!1,!1)}catch{return Ls=!1,!1}}function Sc(e,t,s){if(Uf())try{const r=new Notification(e,{body:t,icon:"/otter-logo.png",tag:s||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>r.close(),8e3),r.onclick=()=>{window.focus(),r.close()}}catch{}}function Aj(e){const{name:t,prev:s,curr:r,questionEntered:o}=e,a=String(e.modalMessage||"").replace(/\s+/g," ").trim().slice(0,120);return o&&e.onApproval?{kind:"question",title:t,body:a?at.t("event.browser.questionWithMessage",{message:a}):at.t("event.browser.question")}:e.onApproval&&r==="waiting_approval"&&s!=="waiting_approval"?{kind:"approval",title:t,body:a?at.t("event.browser.approvalWithMessage",{message:a}):at.t("event.browser.approval")}:e.onComplete&&pc(s)&&r==="idle"?{kind:"complete",title:t,body:at.t("event.browser.finished")}:e.onError&&r==="error"&&s!=="error"?{kind:"error",title:t,body:at.t("event.browser.error")}:null}function Tj(e,t={}){const s={...jj,...t},r=l.useRef(new Map),o=l.useRef(0),[a,i]=l.useState(null);l.useEffect(()=>{let d=!1;return _j().then(u=>{d||i(u)}),()=>{d=!0}},[]);const c=l.useCallback((d,u,m)=>{const h=Date.now();h-o.current<s.throttleMs||(o.current=h,Sc(d,u,m))},[s.throttleMs]);l.useEffect(()=>{var d;if(!(!s.enabled||!Uf())&&wo("browser")&&!Cj(a)){if(document.hasFocus()){for(const u of e)r.current.set(u.id,vn(u.status,{activeModal:u.activeModal}));return}for(const u of e){const m=r.current.get(u.id),h=vn(u.status,{activeModal:u.activeModal}),p=u.name||u.id,g=h==="waiting_choice"&&m!=="waiting_choice";if(Nj(u.muted,m,h)){r.current.set(u.id,h);continue}const f=Aj({name:p,prev:m,curr:h,modalMessage:(d=u.activeModal)==null?void 0:d.message,questionEntered:g,onApproval:s.onApproval&&wo("approval"),onComplete:s.onComplete&&wo("completion"),onError:s.onError});f&&c(f.title,f.body,`${f.kind}-${u.id}`),r.current.set(u.id,h)}}},[e,s.enabled,s.onApproval,s.onComplete,s.onError,a,c])}const Ij=/^(run|approve|accept|yes|allow|always)/,Mj=/^(run|approve|accept|yes|allow|always|proceed|save)/,Rj=/^(reject|deny|delete|remove|abort|cancel|no)/;function Nd(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Pj(e){const t=Nd(e).toLowerCase();return Ij.test(t)?"primary":Rj.test(t)?"danger":"default"}function Lj(e){return Mj.test(Nd(e).toLowerCase())?"approve":"reject"}function Ej(e){return e.map((t,s)=>({label:Nd(t),variant:Pj(t),action:Lj(t),button:t,buttonIndex:s}))}function Dj(e,t,s){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:s}function Oj(e,t,s,r){return[{label:"Approve",variant:"primary",onClick:()=>{s(e,t,"approve").catch(o=>r==null?void 0:r("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{s(e,t,"reject").catch(o=>r==null?void 0:r("reject",o))}}]}function Cd(e){if(!(e==null||e==="")){if(typeof e=="string")return e.trim()||void 0;if(e instanceof Error)return e.message||String(e);if(typeof e=="object"){const t=e,s=t.error??t.message??t.reason;if(typeof s=="string"&&s.trim())return s.trim();if(s&&typeof s=="object")return Cd(s);try{return JSON.stringify(e)}catch{return}}return String(e)}}class $j{constructor(){qe(this,"dedupMap",new Map);qe(this,"DEDUP_WINDOW_MS",5e3);qe(this,"DEDUP_MAX_SIZE",50);qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);qe(this,"toastCallbacks",[]);qe(this,"statusEventCallbacks",[]);qe(this,"resolveActionFn",null);qe(this,"viewRequestRespondFn",null);qe(this,"hydrateInteractivePromptFn",null);qe(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(s=>s!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(s=>s!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}setHydrateInteractivePrompt(t){this.hydrateInteractivePromptFn=t}hydrateInteractivePromptFromEvent(t){const s=this.hydrateInteractivePromptFn;if(!s)return;const r=t.targetSessionId;if(!r)return;const o=hc(t.interactivePrompt);o&&s(r,o)}emitToast(t){for(const s of this.toastCallbacks)s(t)}showToast(t,s="info",r){const o=(r==null?void 0:r.id)||Date.now();this.emitToast({id:o,message:t,type:s,timestamp:o,duration:5e3,...r})}showErrorToast(t,s,r){const o=Cd(s);this.showToast(t,"warning",{duration:8e3,...o&&o!==t?{details:o}:{},...r})}isDuplicate(t){const s=Date.now(),r=this.dedupMap.get(t)||0;if(s-r<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,s),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[o,a]of this.dedupMap)s-a>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(o);return!1}resolveOwningDaemon(t){if(t.daemonId){const o=this.ides.find(a=>a.id===t.daemonId&&a.type==="adhdev-daemon");if(o)return o}const s=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(s){const o=s.daemonId;if(o){const a=this.ides.find(i=>i.id===o&&i.type==="adhdev-daemon");if(a)return a}}const r=this.ides.filter(o=>o.type==="adhdev-daemon");return r.length===1?r[0]:null}findOwningSession(t){for(const s of this.ides)if(s.id===t||s.sessionId===t||(Array.isArray(s.childSessions)?s.childSessions:[]).some(o=>(o==null?void 0:o.id)===t))return s;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const s=this.findOwningSession(t.targetSessionId);return(s==null?void 0:s.id)||(s==null?void 0:s.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}isConversationEventMuted(t){const s=t.targetSessionId;if(!s)return!1;for(const r of this.ides){if(r.id===s||r.sessionId===s)return!!r.muted;const a=(Array.isArray(r.childSessions)?r.childSessions:[]).find(i=>(i==null?void 0:i.id)===s);if(a)return!!a.muted}return!1}handleRawEvent(t,s){var x;const r=this.resolveConversationKey(t),o=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),a=r||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(o),c=`${a}:${t.event}:${i}`;if(t.event==="agent:waiting_choice"&&this.hydrateInteractivePromptFromEvent(t),this.isDuplicate(c))return;for(const b of this.statusEventCallbacks)b(t);const d=this.isConversationEventMuted(t),u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let h=Kt(m);const p=this.resolveOwningDaemon(t);if(p){const b=Tn(p,{fallbackId:p.id});b&&(h=!m||m==="adhdev-daemon"?b:`${b}/${h}`)}let g="",f="info";if(t.event==="agent:generating_completed"){if(g=t.duration?`✅ ${at.t("event.taskCompletedWithDuration",{label:h,duration:Pw(Number(t.duration)*1e3)})}`:`✅ ${at.t("event.taskCompleted",{label:h})}`,f="success",!d)try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started"){if(t.event==="agent:waiting_approval"){if(g=`⚡ ${at.t("event.approvalNeeded",{label:h})}`,f="warning",d)g="";else if((x=t.modalButtons)!=null&&x.length&&this.resolveActionFn){const b=this.resolveActionRouteTarget(t);if(!b)return;const k=this.resolveActionFn,j=Ej(t.modalButtons).map(y=>({label:y.label,variant:y.variant,onClick:()=>{k(b,"resolve_action",{action:y.action,button:y.button,buttonIndex:y.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),v=Dj(h,t.modalMessage,g),_=Date.now();this.emitToast({id:_,message:v,type:f,timestamp:_,targetKey:r||b,actions:j,duration:15e3}),g=""}}else if(t.event==="agent:waiting_choice"){g=`❓ ${at.t("event.questionNeeded",{label:h})}`,f="warning";const b=typeof t.modalMessage=="string"&&t.modalMessage.trim()?t.modalMessage.replace(/[\n\r]+/g," ").slice(0,120):"";b&&(g=`${g} — ${b}`);const k=Date.now();this.emitToast({id:k,message:g,type:f,timestamp:k,targetKey:r||t.daemonId,duration:1e4}),g=""}else if(t.event==="monitor:no_progress"||t.event==="monitor:long_generating"){const b=t.elapsedSec?Math.round(t.elapsedSec/60):0;g=b?`⚠️ ${at.t("event.noProgressWithDuration",{label:h,minutes:b})}`:`⚠️ ${at.t("event.noProgress",{label:h})}`,f="warning",!d&&wo("browser")&&!document.hasFocus()&&Sc(`⚠️ ${at.t("event.noProgressTitle",{label:h})}`,at.t("event.noProgressBody",{duration:b?`${b}m`:""}),`no-progress-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const b=t.requesterName||at.t("event.someoneRequester"),k=t.requestId,j=t.orgId;if(g=`${at.t("event.viewRequest",{requester:b})}`,f="warning",k&&j&&this.viewRequestRespondFn){const v=Date.now(),_=Oj(j,k,this.viewRequestRespondFn,(y,w)=>console.error(`[EventManager] ${y} view request failed:`,w));this.emitToast({id:v,message:g,type:f,timestamp:v,actions:_,duration:3e4}),g=""}wo("browser")&&!document.hasFocus()&&Sc(`${at.t("event.viewRequestTitle")}`,at.t("event.viewRequest",{requester:b}),`view-request-${k}`)}else if(t.event==="team:view_request_approved")g=`✅ ${at.t("event.viewRequestApproved")}`,f="success";else if(t.event==="team:view_request_rejected"){const b=t.targetName||at.t("event.someoneTarget");g=`❌ ${at.t("event.viewRequestDeclined",{target:b})}`,f="warning"}}if(g&&!d){const b=Date.now();this.emitToast({id:b,message:g,type:f,timestamp:b,targetKey:r||t.daemonId,duration:5e3})}}}const ct=new $j,om=new Map;function Kf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Cr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Mi(e){return vd(e)??null}function Fj(e){const t=Mi(e);return!t||!Kf(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function oa(e){const t=Mi(e);return!t||!Kf(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Jr(e){const t=Mi(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function aa(e){const t=Mi(e);return!!t&&t.success===!1}function Hj(e){var t,s;for(const r of e||[]){if(r.type==="toast"&&((t=r.toast)!=null&&t.message)){const o=r.toast.level==="warning"?"warning":r.toast.level==="success"?"success":"info";ct.showToast(r.toast.message,o);continue}if(r.type==="notification"&&((s=r.notification)!=null&&s.body)){const o=r.notification.level==="warning"?"warning":r.notification.level==="success"?"success":"info";ct.showToast(r.notification.body,o)}}}function Bj(e,t){return e&&Cr(e.currentValue)?e.currentValue:t}function Wj(e,t){const s=Object.keys(e).filter(o=>t[o]!==void 0);if(s.length===0)return e;const r={...e};for(const o of s)delete r[o];return r}function Uj(e,t){return Cr(t)?Cr(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Kj(e,t){var a,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Cr(c))return c}const r=(a=t.controlValues)==null?void 0:a[e];if(Cr(r))return r;const o=(i=t.defaultValues)==null?void 0:i[e];return Cr(o)?o:void 0}function Ta(e,t){return e.options||t[e.id]||[]}const qj={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session","stop"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function zj(e,t,s){var r;return((r=qj[t])==null?void 0:r.has(s.id))===!0}function Gj(e){if(e){if(bi(e))return["busy","generating","starting"];switch(e){case"idle":return["idle"];case"waiting_approval":case"approval":return["approval"];case"waiting_choice":return["picker"];default:return}}}function Vj(e,t){const s=e.visibleWhenState;if(!s||s.length===0)return!0;const r=Gj(t);return r?r.some(o=>s.includes(o)):!0}function _d(e,t){return(e||[]).filter(s=>s.placement==="bar"&&s.hidden!==!0&&!zj(t.hostIdeType,t.providerType,s)&&Vj(s,t.currentStatus)).sort((s,r)=>(s.order??50)-(r.order??50))}function hl(e,t){return{value:t}}function Yj(e,t,s){var o;return s?((o=Ta(e,t).find(a=>a.value===s))==null?void 0:o.label)||s:""}const Qj={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Jj({routeId:e,sessionId:t,hostIdeType:s,providerType:r,displayLabel:o,controls:a,controlValues:i,currentStatus:c,coordinatorHint:d}){const{t:u}=ve("common"),{sendCommand:m}=_t(),{confirm:h,confirmDialog:p}=Fr(),g=`${e}:${t||r}`,f=Qj[r]||"#94a3b8",[x,b]=l.useState({}),k=l.useRef({}),j=l.useRef(i);k.current=x,j.current=i;const v=l.useRef(0),_={};for(const R of a||[])R.defaultValue!==void 0&&(_[R.id]=R.defaultValue);const y={..._,...i||{},...Date.now()<v.current?x:{}};l.useEffect(()=>{i&&Date.now()>v.current&&b(R=>Wj(R,i))},[i]);const[w,S]=l.useState(om.get(g)||{}),[C,A]=l.useState(null),[O,L]=l.useState(null),M=l.useCallback(async(R,D={})=>{const P={...D,...t&&{targetSessionId:t},...d??{}};return await m(e,R,P)},[e,t,m,d]),$=l.useCallback(async(R,D={})=>{const P=t?{targetSessionId:t}:{agentType:r,...s?{ideType:s}:{}};return await M("invoke_provider_script",{...P,scriptName:R,...D})},[M,r,s,t]),N=l.useCallback((R,D,P)=>{const H=Bj(P,D);b(W=>({...W,[R.id]:H})),Hj(P==null?void 0:P.effects)},[]),I=l.useCallback((R,D)=>{b(P=>{const H={...P};return D===void 0?delete H[R.id]:H[R.id]=D,H}),v.current=0},[]);if(!a||a.length===0)return null;const B=_d(a,{hostIdeType:s,providerType:r,currentStatus:c});if(B.length===0)return null;const T=async R=>{if(C===R.id){A(null);return}if(Ta(R,w).length>0){A(R.id);return}if(R.dynamic&&R.listScript){L(R.id);try{const P=await $(R.listScript,{}),H=Fj(P);if(!H){const ae=Jr(P);ae&&ct.showErrorToast(u("controls.loadOptionsFailed",{label:R.label}),ae);return}const W=H.options;S(ae=>{const be={...ae,[R.id]:W};return om.set(g,be),be});const U=Kj(R.id,{localOverrideUntil:v.current,localValues:k.current,controlValues:j.current,defaultValues:_});if(Uj(U,H.currentValue)){const ae=H.currentValue;b(be=>({...be,[R.id]:ae}))}A(R.id)}catch(P){ct.showErrorToast(u("controls.loadOptionsFailed",{label:R.label}),P)}finally{L(null)}}},F=async(R,D)=>{A(null);const P=(i==null?void 0:i[R.id])??_[R.id];b(H=>({...H,[R.id]:D})),v.current=Date.now()+5e3;try{if(!R.setScript)return;const H=await $(R.setScript,hl(R,D)),W=oa(H);if(W&&!W.ok||aa(H))throw new Error((W==null?void 0:W.error)||Jr(H)||`Could not update ${R.label}`);N(R,D,W)}catch(H){I(R,P),ct.showErrorToast(u("controls.updateFailed",{label:R.label}),H)}},q=async R=>{const D=Ta(R,w).map(be=>be.value);if(D.length===0)return;const P=String(y[R.id]||""),W=(D.indexOf(P)+1)%D.length,U=D[W];if(typeof U!="string")return;const ae=(i==null?void 0:i[R.id])??_[R.id];b(be=>({...be,[R.id]:U})),v.current=Date.now()+5e3;try{if(!R.setScript)return;const be=await $(R.setScript,hl(R,U)),V=oa(be);if(V&&!V.ok||aa(be))throw new Error((V==null?void 0:V.error)||Jr(be)||`Could not update ${R.label}`);N(R,U,V)}catch(be){I(R,ae),ct.showErrorToast(u("controls.updateFailed",{label:R.label}),be)}},Q=async R=>{const P=!y[R.id],H=(i==null?void 0:i[R.id])??_[R.id];b(W=>({...W,[R.id]:P})),v.current=Date.now()+5e3;try{if(!R.setScript)return;const W=await $(R.setScript,hl(R,P)),U=oa(W);if(U&&!U.ok||aa(W))throw new Error((U==null?void 0:U.error)||Jr(W)||`Could not update ${R.label}`);N(R,P,U)}catch(W){I(R,H),ct.showErrorToast(u("controls.updateFailed",{label:R.label}),W)}},K=async R=>{var P,H,W;if(!R.invokeScript||R.confirmMessage&&!await h({title:((P=R.confirmTitle)==null?void 0:P.trim())||R.confirmMessage,description:(H=R.confirmTitle)!=null&&H.trim()?R.confirmMessage:void 0,confirmLabel:((W=R.confirmLabel)==null?void 0:W.trim())||u("common.confirm")}))return;const D=(i==null?void 0:i[R.id])??_[R.id];try{const U=await $(R.invokeScript),ae=oa(U);if(ae&&!ae.ok||aa(U))throw new Error((ae==null?void 0:ae.error)||Jr(U)||`Could not run ${R.label}`);ae&&N(R,D??!0,ae)}catch(U){I(R,D),ct.showErrorToast(u("controls.runFailed",{label:R.label}),U)}};return n.jsxs("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-2xs font-semibold tracking-[0.02em]",style:{borderColor:`${f}33`,background:`${f}12`,color:f},children:o}),B.map(R=>{const D=String(y[R.id]||""),P=Yj(R,w,D),H=C===R.id,W=O===R.id,U=Ta(R,w),ae="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-xs font-medium transition-colors whitespace-nowrap";switch(R.type){case"select":return n.jsxs("div",{className:"relative max-w-full",children:[n.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:H?`${f}55`:"var(--border-default)",background:H?`${f}10`:"var(--surface-tertiary)",color:D?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(R),title:R.label,children:[R.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:R.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?u("chatControls.loading"):P||R.label}),n.jsx("span",{className:"text-4xs opacity-55",children:"▼"})]}),H&&U.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-[var(--z-dropdown)]",onClick:()=>A(null)}),n.jsxs("div",{className:"absolute bottom-full left-0 z-[var(--z-dropdown)] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[n.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-3xs font-semibold uppercase tracking-[0.08em] text-text-muted",children:R.label}),U.map(be=>n.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-xs transition-colors",style:{background:be.value===D?`${f}14`:"transparent",color:be.value===D?"var(--text-primary)":"var(--text-secondary)",borderLeft:be.value===D?`2px solid ${f}`:"2px solid transparent"},title:be.description||be.label,onMouseEnter:V=>{V.currentTarget.style.background=`${f}10`},onMouseLeave:V=>{V.currentTarget.style.background=be.value===D?`${f}14`:"transparent"},onClick:()=>void F(R,be.value),children:[n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:be.label}),be.value===D&&n.jsx("span",{className:"shrink-0 text-2xs font-semibold",style:{color:f},children:"✓"})]},be.value))]})]})]},R.id);case"cycle":return n.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:D?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void q(R),title:`Click to cycle: ${U.map(be=>be.label).join(" → ")}`,children:[R.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:R.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P||R.label}),n.jsx("span",{className:"text-3xs opacity-55",children:"⟳"})]},R.id);case"toggle":return n.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:D?`${f}44`:"var(--border-default)",background:D?`${f}14`:"var(--surface-tertiary)",color:D?f:"var(--text-muted)"},onClick:()=>void Q(R),"aria-pressed":!!D,children:[R.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:R.icon}),R.label]},R.id);case"action":return n.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void K(R),children:[R.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:R.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:R.resultDisplay==="inline"&&D?`${R.label}: ${D}`:R.label})]},R.id);case"display":return n.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-xs font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:D?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:R.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:D?`${R.label}: ${D}`:R.label})]},R.id);default:return null}})]}),p]})}function Xj(e){if(!e||typeof e!="object")return{};const t=e,s=Cv(t.launch);return{...s?{launch:s}:{},...typeof t.model=="string"&&t.model.trim()?{model:t.model.trim()}:{},...ld(t.modelSource)?{modelSource:t.modelSource}:{}}}const am={user:"chosen",remembered:"remembered",mesh_slot:"mesh slot",task_override:"task",provider_default:"default",unspecified:""};function Zj(e,t){return String(t.defaultValue??"").replace(/\{\{(\w+)\}\}/g,(s,r)=>String(t[r]??""))}function qf(e,t=Zj){const s=e.launch?Nv(e.launch.model):void 0,r=(s==null?void 0:s.value)??e.model;if(!r)return null;const o=(s==null?void 0:s.source)??e.modelSource??"unspecified";if(s!=null&&s.changedFrom)return{text:t("chatControls.launchModelChanged",{from:s.changedFrom,to:r,defaultValue:"{{from}} → {{to}} (changed)"}),source:o};const a=am[o]?t(`chatControls.launchModelSource.${o}`,{defaultValue:am[o]}):"";return{text:a?`${r} · ${a}`:r,source:o}}function eN({surface:e}){const{t}=ve("common"),s=qf(e,t);return s?n.jsx("span",{className:"inline-flex items-center rounded-full border border-border-subtle px-2 py-0.5 text-2xs text-text-muted","data-testid":"session-launch-chip","data-model-source":s.source,children:s.text}):null}function tN({isActive:e=!0,isCliTerminal:t=!1,routeId:s,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:c,controlValues:d,currentStatus:u,coordinatorHint:m,launchSurface:h}){const{isVisible:p}=kd(),g=_d(c,{hostIdeType:o,providerType:a,currentStatus:u}),f=g.length>0&&p,x=!!h&&!!qf(h);return!e||t||!f&&!x?null:n.jsxs("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:[x&&h&&n.jsx("div",{className:"flex justify-end px-3 pt-1",children:n.jsx(eN,{surface:h})}),f&&n.jsx(Jj,{routeId:s,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:g,controlValues:d,currentStatus:u,coordinatorHint:m})]})}const Xr=5,zf=10*1024*1024;function nN({hasDraft:e,isBusy:t=!1}){return!e||t}function sN(e){return new Promise((t,s)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>s(new Error("Failed to read file")),r.readAsDataURL(e)})}async function rN(e){if(e.size>zf)return null;const t=await sN(e),s=t.indexOf(",");if(s<0)return null;const r=t.slice(s+1);return{mimeType:e.type||"image/png",data:r,name:e.name,previewUrl:t}}function oN(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}function aN(e){return/[\u1100-\u11FF\u3130-\u318F\uAC00-\uD7A3]/.test(e)}const Gf=l.memo(function({contextKey:t,panelLabel:s,isSending:r,isBusy:o=!1,statusMessage:a=null,inlineStatusMessage:i=null,onSend:c,isActive:d=!0,showControlsToggle:u=!1,animateVisibility:m=!0,onControlsToggle:h,messageInput:p}){const{t:g}=ve("common"),f=l.useRef(null),x=l.useRef(null),[b,k]=l.useState(""),[j,v]=l.useState([]),[_,y]=l.useState(null),[w,S]=l.useState(!1),C=l.useRef(!1),A=l.useRef(0),O=50,L=l.useRef(""),M=l.useRef(!1),$=l.useRef(null),N=30,{isVisible:I,toggleVisibility:B}=kd(),T=oN(p),F=!!b.trim()||j.length>0;l.useEffect(()=>{k(""),v([]),y(null)},[t]),l.useEffect(()=>{var U;d&&((U=f.current)==null||U.focus({preventScroll:!0}))},[t,d]),l.useEffect(()=>{const U=f.current;U&&(U.style.height="auto",b&&(U.style.height=`${Math.min(U.scrollHeight,160)}px`))},[b]);const q=l.useCallback(async U=>{y(null);const ae=Array.from(U).filter(ne=>ne.type.startsWith("image/"));if(ae.length===0)return;const be=Xr-j.length;if(be<=0){y(`Max ${Xr} images`);return}const V=ae.slice(0,be);if(V.filter(ne=>ne.size>zf).length>0){y("Image too large (max 10 MB)");return}const de=(await Promise.all(V.map(rN))).filter(ne=>ne!==null);v(ne=>[...ne,...de])},[j.length]),Q=l.useCallback(U=>{v(ae=>ae.filter((be,V)=>V!==U))},[]),K=l.useCallback(async()=>{const U=b.trim();if(!U&&j.length===0||o||C.current)return;C.current=!0;const ae=j.length>0?[...j]:void 0;try{await c(U,ae)!==!1&&(k(""),v([]),y(null))}finally{C.current=!1}},[b,j,o,c]),R=l.useRef(K);R.current=K;const D=l.useCallback(()=>{M.current&&(M.current=!1,$.current&&(clearTimeout($.current),$.current=null),setTimeout(()=>{R.current()},0))},[]);l.useEffect(()=>()=>{$.current&&clearTimeout($.current)},[]);const P=l.useCallback(U=>{T&&(U.preventDefault(),S(!0))},[T]),H=l.useCallback(()=>S(!1),[]),W=l.useCallback(U=>{T&&(U.preventDefault(),S(!1),U.dataTransfer.files.length>0&&q(U.dataTransfer.files))},[T,q]);return n.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",w?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:d?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:d?200:0,opacity:d?1:0,transform:d?"translateY(0)":"translateY(10px)",padding:d?"10px 12px":"0 12px",pointerEvents:d?"auto":"none"},"aria-hidden":!d,onDragOver:P,onDragLeave:H,onDrop:W,children:[j.length>0&&n.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:j.map((U,ae)=>n.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[n.jsx("img",{src:U.previewUrl,alt:U.name,className:"w-full h-full object-cover"}),n.jsx("button",{type:"button",onClick:()=>Q(ae),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-3xs leading-none","aria-label":`Remove ${U.name}`,children:"✕"})]},ae))}),n.jsxs("div",{className:"flex gap-2 items-center",title:d?g("chatInput.sendTo",{panel:s}):void 0,children:[u&&n.jsx("button",{type:"button",onClick:()=>{B(),h==null||h()},"aria-label":g(I?"chatInput.hideControls":"chatInput.showControls"),"aria-pressed":I,title:g(I?"chatInput.hideControls":"chatInput.showControls"),className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:n.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[n.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),n.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),n.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),T&&n.jsxs(n.Fragment,{children:[n.jsx("input",{ref:x,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:U=>{U.target.files&&q(U.target.files),U.target.value=""}}),n.jsx("button",{type:"button",onClick:()=>{var U;return(U=x.current)==null?void 0:U.click()},disabled:j.length>=Xr,title:j.length>=Xr?`Max ${Xr} images`:g("chatInput.attachImage"),className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":g("chatInput.attachImage"),children:n.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),n.jsx("div",{className:"flex-1 relative",children:n.jsx("textarea",{ref:f,rows:1,placeholder:a||(T&&j.length>0?g("chatInput.addMessageOptional"):g("chatInput.placeholder",{panel:s})),value:b,onChange:U=>k(U.target.value),onPaste:U=>{if(T&&U.clipboardData.files.length>0&&Array.from(U.clipboardData.files).some(ue=>ue.type.startsWith("image/"))){U.preventDefault(),q(U.clipboardData.files);return}const ae=U.clipboardData.getData("text/plain"),be=Hv(ae);if(be===ae)return;U.preventDefault();const V=f.current,we=(V==null?void 0:V.selectionStart)??b.length,ce=(V==null?void 0:V.selectionEnd)??b.length,de=b.slice(0,we)+be+b.slice(ce);k(de);const ne=we+be.length;requestAnimationFrame(()=>{V==null||V.setSelectionRange(ne,ne)})},onCompositionUpdate:U=>{L.current=U.data||""},onCompositionEnd:U=>{A.current=Date.now(),U.data&&(L.current=U.data),D()},onKeyDown:U=>{if(U.key!=="Enter"||U.shiftKey)return;if(U.nativeEvent.isComposing||U.keyCode===229||Date.now()-A.current<O){U.preventDefault(),aN(L.current)&&!M.current&&(M.current=!0,$.current=setTimeout(D,N));return}U.preventDefault(),K()},className:"w-full rounded-[20px] px-4 py-2 bg-bg-secondary text-sm text-text-primary resize-none leading-[1.4] block",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))",minHeight:40,maxHeight:160,overflowY:"auto",whiteSpace:"pre-wrap"}})}),n.jsx("button",{onClick:()=>{K()},disabled:nN({hasDraft:F,isBusy:o}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${F&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:F&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":g("chatInput.sendMessage"),children:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:F?"text-white":"text-text-muted",children:n.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(_||T&&w)&&n.jsx("div",{className:`pt-1.5 px-1 text-2xs ${_?"text-red-400":"text-[var(--accent-primary)]"}`,children:_||g("chatInput.dropImage")}),i&&!_&&n.jsx("div",{className:"pt-2 px-1 text-2xs text-text-muted opacity-80",children:i})]})});function iN({entries:e,onSendNow:t,onCancelQueued:s,isSendingNow:r}){const{t:o}=ve(),a=e.filter(d=>d.queued===!0&&!!d.id);if(a.length===0)return null;const i=a.some(d=>d.stale!==!0),c=o(i?"chat.waitingToSendAria":"chat.notDeliveredAria");return n.jsx("div",{className:"chat-pending-queue-strip","data-testid":"pending-queue-strip","data-pending-queue-count":a.length,role:"region","aria-label":c,children:a.map(d=>n.jsxs("div",{className:"chat-pending-queue-row","data-chat-queued-row":"true","data-chat-queued-stale":d.stale===!0?"true":void 0,children:[n.jsxs("div",{className:"chat-bubble chat-bubble-user chat-pending-queue-bubble",title:d.content,children:[n.jsx("div",{className:"chat-pending-queue-body",children:d.content}),n.jsx("span",{className:d.stale===!0?"chat-pending-queue-clock chat-pending-queue-stale":"chat-pending-queue-clock",role:"img","aria-label":d.stale===!0?o("chat.notDeliveredAria"):o("chat.waitingToSendAria"),title:d.stale===!0?o("chat.notDelivered"):o("chat.waitingToSendAria"),children:d.stale===!0?"⚠":"⏱"})]}),t&&n.jsx("button",{type:"button",onClick:()=>t(d.id),disabled:r,className:"chat-pending-queue-send","aria-label":o("chat.sendNowAria"),title:o("chat.sendNowTitle"),children:"↑"}),s&&n.jsx("button",{type:"button",onClick:()=>s(d.id),disabled:r,className:"chat-pending-queue-cancel","aria-label":o("chat.cancelQueuedAria"),title:o("chat.cancelQueuedTitle"),children:"✕"})]},d.id))})}const lN=l.memo(iN,(e,t)=>e.onSendNow===t.onSendNow&&e.onCancelQueued===t.onCancelQueued&&e.isSendingNow===t.isSendingNow&&e.entries.length===t.entries.length&&e.entries.every((s,r)=>{const o=t.entries[r];return!!o&&s.id===o.id&&s.content===o.content&&s.queued===o.queued&&s.stale===o.stale})),cN={accent:{track:"--accent-primary",head:"--accent-primary-light"},success:{track:"--status-online",head:"--status-online"},muted:{track:"--text-muted",head:"--text-muted"}};function ln({size:e=28,thickness:t=2.5,color:s="accent",className:r,label:o}){const a=cN[s],i={width:e,height:e,border:`${t}px solid color-mix(in srgb, var(${a.track}) 20%, transparent)`,borderTopColor:`var(${a.head})`};return n.jsx("span",{className:ft("block shrink-0 rounded-full animate-spin",r),style:i,role:o?"status":void 0,"aria-label":o,"aria-hidden":o?void 0:!0})}const dN=1e4;function uN({machineId:e,blocked:t,retryConnection:s}){const{t:r}=ve("common"),[o,a]=l.useState(!1),i=l.useRef(null);if(l.useEffect(()=>{t||a(!1)},[t]),l.useEffect(()=>{if(!o)return;const d=setTimeout(()=>a(!1),dN);return()=>clearTimeout(d)},[o]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),!e||!t||!s)return null;const c=()=>{o||(a(!0),s(e))};return n.jsxs("button",{type:"button","data-testid":"chat-machine-reconnect",onClick:c,disabled:o,"aria-label":r("chatPane.reconnectMachine"),title:r("chatPane.reconnectMachineTitle"),className:"inline-flex items-center justify-center gap-1 h-6 px-2 rounded-full leading-none text-3xs font-bold transition-colors bg-red-500/10 border border-red-500/25 text-red-400 hover:bg-red-500/20 disabled:opacity-60 disabled:cursor-not-allowed",style:{pointerEvents:"auto"},children:[o?n.jsx(ln,{size:11,thickness:2,color:"muted"}):n.jsx(Ir,{size:12}),n.jsx("span",{children:r(o?"chatPane.reconnectingMachine":"chatPane.reconnectMachine")})]})}let Vf=An;function Ad(){return Vf()}class mN{constructor(){qe(this,"listeners",new Map)}send(t,s){return!1}isConnected(){return!1}on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>{var r;(r=this.listeners.get(t))==null||r.delete(s)}}emit(t,...s){var r;(r=this.listeners.get(t))==null||r.forEach(o=>o(...s))}}let Yf=new mN;class hN{sendPtyInput(t,s,r){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,s){return!1}get(t){}onScreenshot(t,s){return()=>{}}onRuntimeEvent(t,s,r){return()=>{}}requestRuntimeSnapshot(t,s,r){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let Et=new hN;function pN(e){e.dashboardWS&&(Yf=e.dashboardWS),e.connectionManager&&(Et=e.connectionManager),e.useDaemonsHook&&(Vf=e.useDaemonsHook)}function Ia(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Qf="adhdev-pending-queued-messages-v1",fN=256*1024,gN=24*60*60*1e3,Jf=10*60*1e3;function Xf(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Qf)||"{}");return{byKey:e.byKey&&typeof e.byKey=="object"?e.byKey:{}}}catch{return{byKey:{}}}}function bN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Qf,JSON.stringify(e))}catch{}}function xN(e,t){if(!e||typeof e!="object")return;const s=e;if(!Array.isArray(s.parts))return;let r=0;const o=new Set(s.omitted&&typeof s.omitted=="object"&&Array.isArray(s.omitted.partTypes)?s.omitted.partTypes.filter(c=>typeof c=="string"):[]),a=[];for(const c of s.parts){if(!c||typeof c!="object")continue;const d=c,u=typeof d.type=="string"?d.type:"";if(!u)continue;if(u==="text"){a.push({type:"text",text:typeof d.text=="string"?d.text:""});continue}const m=typeof d.data=="string"?d.data:void 0,h=m?m.length:0;if(m&&r+h<=fN){r+=h,a.push({type:u,mimeType:typeof d.mimeType=="string"?d.mimeType:void 0,uri:typeof d.uri=="string"?d.uri:void 0,data:m,alt:typeof d.alt=="string"?d.alt:void 0});continue}if(!m){a.push({type:u,mimeType:typeof d.mimeType=="string"?d.mimeType:void 0,uri:typeof d.uri=="string"?d.uri:void 0,alt:typeof d.alt=="string"?d.alt:void 0});continue}o.add(u),a.push({type:u,mimeType:typeof d.mimeType=="string"?d.mimeType:void 0,alt:typeof d.alt=="string"?d.alt:void 0})}const i=typeof s.textFallback=="string"?s.textFallback:t;return{parts:a,textFallback:i,...o.size>0?{omitted:{omitted:!0,partTypes:[...o]}}:{}}}function Zf(e,t){if(!Array.isArray(e))return[];const s=new Set,r=[];let o=0;for(const a of e){if(!a||typeof a!="object")continue;const i=a,c=typeof i.content=="string"?i.content:"",d=typeof i.sentAt=="number"&&Number.isFinite(i.sentAt)?i.sentAt:0,u=typeof i.id=="string"&&i.id?i.id:"";if(!c.trim()||!d||!u||t-d>gN||s.has(u))continue;s.add(u);const m=i.stale===!0||t-d>Jf,h=xN(i.input,c);r.push({entry:{id:u,content:c,sentAt:d,queued:i.queued===!0,settled:!0,stale:m,...h?{input:h}:{}},index:o}),o+=1}return r.sort((a,i)=>a.entry.sentAt-i.entry.sentAt||a.index-i.index),r.map(a=>a.entry).slice(-20)}let im=0;function yN(e=Date.now()){try{const t=typeof globalThis<"u"?globalThis.crypto:void 0;if(typeof(t==null?void 0:t.randomUUID)=="function")return t.randomUUID()}catch{}return im+=1,`pq-${e}-${im}`}function vN(e,t=Date.now()){const s=String(e||"").trim();return s?Zf(Xf().byKey[s],t):[]}function wN(e,t,s=Date.now()){const r=String(e||"").trim();if(!r)return;const o=Xf(),a=Zf(t,s);a.length>0?o.byKey[r]=a:delete o.byKey[r],bN(o)}function eg(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}const SN=12e4;function kN(e){if(typeof e=="string")return e.trim();if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}const jN=/^(?:\s*(?:\[Image #\d+\]|\[image: [^\]\n]{1,100}\]))+\s*/;function NN(e,t){const s=kN(e);if(s===t)return!0;const r=s.replace(jN,"").trim();return r!==s&&r.length>0&&r===t}function CN(e,t){if(!t)return!1;const s=e.meta;return typeof(s==null?void 0:s.sourceMessageId)=="string"&&s.sourceMessageId===t}function lm(e){const t=e.meta;return typeof(t==null?void 0:t.sourceMessageId)=="string"&&t.sourceMessageId.length>0}function tg(e,t){if(!t)return 0;let s=0;for(const r of e)String(r.role||"").toLowerCase()==="user"&&NN(r.content,t)&&(s+=1);return s}function _N(e,t,s=Date.now(),r=Jf){if(!e||e.length===0)return{entries:[],changed:!1,retiredByEcho:0,markedStale:0};const o=new Map,a=[];let i=0,c=0,d=!1;const u=t.some(m=>lm(m))?t.filter(m=>!lm(m)):t;for(const m of e){const h=m.content.trim();if(!h){d=!0;continue}if(t.some(f=>CN(f,m.id))){i+=1,d=!0;continue}o.has(h)||o.set(h,tg(u,h));const p=o.get(h)||0;if(p>0){o.set(h,p-1),i+=1,d=!0;continue}if(s-m.sentAt>r&&m.stale!==!0){c+=1,d=!0,a.push({...m,stale:!0});continue}a.push(m)}return d?{entries:a,changed:!0,retiredByEcho:i,markedStale:c}:{entries:e,changed:!1,retiredByEcho:0,markedStale:0}}function AN(e){return{id:`pending-local:${e.id||e.sentAt}`,role:"user",kind:"standard",content:e.content,senderName:"User",timestamp:e.sentAt,receivedAt:e.sentAt,meta:{pendingLocal:!0,queued:e.queued===!0,pendingId:e.id||String(e.sentAt)}}}function TN(e,t,s=Date.now(),r={}){if(!t||t.length===0)return e;const o=new Map,a=[];for(const i of t){const c=i.content.trim();if(!c||s-i.sentAt>SN)continue;o.has(c)||o.set(c,tg(e,c));const d=o.get(c)||0;if(d>0){o.set(c,d-1);continue}r.excludeQueued&&i.queued===!0&&i.id||a.push(AN(i))}return a.length===0?e:[...e,...a]}function IN(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const s=String(e.kind||"standard").toLowerCase();return s===""||s==="standard"}function pl(e){return IN(e)?String(e.role||"").toLowerCase():""}const MN=4;function RN(e,t){if(e.length===0)return[];for(let a=t.length-1;a>=0;a-=1)if(pl(t[a])==="assistant")return[];const s=t.some(a=>pl(a)==="user"),r=[];let o=!1;for(let a=e.length-1;a>=0&&r.length<MN;a-=1){const i=e[a],c=pl(i);if(c){if(!o&&c==="assistant"){r.unshift(i),o=!0;continue}if(o&&c==="user"){s||r.unshift(i);break}}}return r}function PN(e){let t=!0;for(let s=1;s<e.length;s+=1)if(Ia(e[s-1])>Ia(e[s])){t=!1;break}return t?e:e.map((s,r)=>({message:s,index:r,ts:Ia(s)})).sort((s,r)=>s.ts-r.ts||s.index-r.index).map(s=>s.message)}function LN(e){const{historyMessages:t,liveMessages:s,visibleLiveCount:r}=e,o=Math.max(0,s.length-r),a=o>0?s.slice(0,o):[],i=o>0?s.slice(-r):s,c=RN(a,i),d=c.length>0?[...c,...i]:i,u=t.length===0?d:[...t,...d];return PN(u)}const St=e=>e.transport==="pty",Hr=(e,t)=>St(e)&&e.mode||"chat",ng=(e,t)=>St(e)&&Hr(e)==="terminal",vt=e=>e.transport==="acp",EN=180;function Ss(e){return e.streamSource!=="agent-stream"}function as(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Ri(e){var s;const t=typeof((s=e.settings)==null?void 0:s.meshCoordinatorDaemonId)=="string"?e.settings.meshCoordinatorDaemonId:void 0;return t?{meshCoordinatorDaemonId:t}:{}}function sg(e){return e.machineName||""}function Cs(e){return as(e)}function Vn(e){return e.agentType||""}function Ga(e){return e.hostIdeType||""}function Td(e){return e.displayPrimary||e.agentName||"Agent"}function rg(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function DN(e,t){const s=eg(e,t),r=[...s].reverse();return r.find(o=>!(o!=null&&o._localId)&&Ni(o).isUserFacing)||r.find(o=>!(o!=null&&o._localId))||s[s.length-1]}function og(e,t){const s=DN(e,t),r=_r(s==null?void 0:s.content),o=_r(e.lastMessagePreview);return o&&e.lastMessageRole==="assistant"&&(s==null?void 0:s.role)==="user"?o:r||o||""}function ON(e,t=EN){const s=_r(e);if(!s||t<=0)return"";const r=Array.from(s);return r.length<=t?s:`${r.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function $N(e){return ON(og(e)||e.displaySecondary||"")}function ag(e){return[e.displaySecondary,sg(e)].filter(Boolean)}function Rr(e){return e.agentName||Kt(Vn(e))}function FN(e){var t,s;if(!Ss(e)){const r=(s=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:s.trim();if(r)return r}return Kt(Ga(e)||Vn(e))}function ig(e){return Ss(e)?e.sessionId:e.nativeSessionId}function cm(e){return Ss(e)?"native":e.tabKey}function HN(e){return e.sessionId}function lg(e,t){if(t)return Ss(e)||!t.childSessions?t:t.childSessions.find(s=>s.id===e.sessionId||s.providerType===e.agentType)||t}function BN(e,t){const s=Vn(e),r=Ss(e),o=St(e)||vt(e),a=r?o?Rr(e)||(t==null?void 0:t.cliName)||Kt(Ga(e)||s):t!=null&&t.type?Kt(t.type):Kt(Ga(e)||s):Rr(e);return{isNativeConversation:r,isCli:St(e),isAcp:vt(e),isCliTerminal:ng(e),providerType:s,displayLabel:a,targetEntry:lg(e,t)}}function ks(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:St(e)||vt(e)?{agentType:Vn(e)}:e.streamSource==="agent-stream"?{agentType:Vn(e)}:t}function vs(e){return e?Cs(e):""}function yr(e,t){e(s=>[...s,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}const WN="Waiting for approval…",UN="Waiting for your answer…";function Pi(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?e.status==="waiting_choice"?"Answer the pending question above.":"Approve or reject the pending request above.":null}function cg(e){return Pi(e)?(e==null?void 0:e.status)==="waiting_choice"?UN:WN:null}function ia(e){const t=e instanceof Error?e.message:String(e||""),s=t.toLowerCase();return s.includes("awaiting confirmation")?"Approve or reject the pending request above.":s.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":s.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}function dg(){return"select_session"}function KN(){return"open_panel"}function qN({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function zN(e,t,s=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<s:!1}function dm(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Ks(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}const po="Waiting to send — the agent is still working.",GN="Too late to cancel — this message was already sent to the agent.";function um(e){return!e||typeof e!="object"?!1:e.queued===!0}function VN({feedbackMessage:e,lastSendQueued:t,isGenerating:s}){return!t||e!==po?!1:!s}function Id(e){return e instanceof Error?e.message:String(e||"")}function mm(e){const t=Id(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function hm(e,t){const s=Id(t);return s?s.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${s}`:`⚠️ **${e}** unavailable`}const YN=5e3;function QN(e,t,s=YN){const r=e.get(t);if(!r)return Promise.resolve("unknown");let o;const a=new Promise(i=>{o=setTimeout(()=>i("unknown"),s)});return Promise.race([r,a]).finally(()=>{o&&clearTimeout(o)})}function JN(e,t){if(!t||t.length===0)return;const s=t.map(r=>({type:"image",mimeType:r.mimeType,data:r.data,alt:r.name}));return e&&s.push({type:"text",text:e}),{parts:s,textFallback:e}}function pm(e,t,s,r,o={mode:"queue"}){const a=s?{parts:s.parts,textFallback:s.textFallback}:{parts:[{type:"text",text:t}],textFallback:t};return{messageId:e,input:a,policy:o,...ks(r)}}function Li({sendDaemonCommand:e,activeConv:t,setActionLogs:s,isStandalone:r}){const[o,a]=l.useState(!1),[i,c]=l.useState(!1),[d,u]=l.useState(null),[m,h]=l.useState(!1),[p,g]=l.useState([]),f=l.useRef(!1),x=l.useRef(null),b=l.useRef([]);b.current=p;const k=l.useRef(new Map),j=(t==null?void 0:t.tabKey)||"",v=l.useRef(j);v.current=j;const _=l.useCallback(N=>{g(I=>{const B=N(I);return B===I?I:(wN(v.current,B),B)})},[]),y=l.useCallback(N=>{_(I=>{const B=_N(I,N);return B.changed?B.entries:I})},[_]);l.useEffect(()=>{u(null),h(!1),g(j?vN(j):[])},[t==null?void 0:t.tabKey,j]);const w=t?er(t):!1;l.useEffect(()=>{u(N=>VN({feedbackMessage:N,lastSendQueued:m,isGenerating:w})?null:N),!w&&m&&h(!1)},[w,m]);const S=l.useCallback(async(N,I)=>{if(!t||f.current)return!1;const B=N.trim(),T=Pi(t);if(qN({hasMessage:!!B,blockedMessage:T,sendInFlight:f.current}))return T&&u(T),!1;const F=Date.now(),q={tabKey:t.tabKey,message:B,timestamp:F};if(zN(x.current,q))return u(null),!0;f.current=!0,c(!0),u(null),h(!1),x.current=q;const Q=yN(F),K=JN(B,I);let R=()=>{};k.current.set(Q,new Promise(P=>{R=P}));let D="not-parked";_(P=>[...P,{id:Q,content:B,sentAt:F,...K?{input:K}:{}}].slice(-20));try{const P=vs(t);if(!P)return x.current=dm(x.current,q),_(U=>U.filter(ae=>ae.id!==Q)),u("Unable to send message right now."),!1;const H=await e(P,"send_chat",pm(Q,B,K,t)),W=Ks(H);if(W!=null&&W.deduplicated)return u(null),!0;if(um(W))return D="parked",h(!0),_(U=>U.map(ae=>ae.id===Q?{...ae,queued:!0}:ae)),u(po),!0;if((W==null?void 0:W.sent)===!1)throw new Error((W==null?void 0:W.error)||"Send failed");if((W==null?void 0:W.success)===!1)throw new Error((W==null?void 0:W.error)||"Send failed");return h(!1),u(null),!0}catch(P){const H=Id(P);return H.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",H):console.warn("Send blocked/failed",P),x.current=dm(x.current,q),_(W=>W.filter(U=>U.id!==Q)),u(ia(P)),!1}finally{k.current.delete(Q),R(D),_(P=>P.map(H=>H.id===Q?{...H,settled:!0}:H)),f.current=!1,c(!1)}},[t,e,_]),C=l.useCallback(async N=>{if(!t||f.current)return!1;const I=b.current,B=N?I.find(q=>q.id===N):I.find(q=>q.queued===!0);if(!B||!B.queued)return!1;const T=B.content.trim();if(!T)return!1;const F=B.id;f.current=!0,c(!0),u(null);try{const q=vs(t);if(!q)return u("Unable to send message right now."),!1;const Q=await e(q,"send_chat",pm(F,T,B.input,t,{mode:"send_now"})),K=Ks(Q);return(K==null?void 0:K.success)===!1?(u(ia(new Error((K==null?void 0:K.error)||"Send now failed"))),!1):(K==null?void 0:K.queuedWithAgent)===!0?(h(!1),_(R=>R.map(D=>D.id===F?{...D,queued:!1}:D)),u(null),!0):um(K)?(h(!0),_(R=>R.map(D=>D.id===F?{...D,queued:!0}:D)),u(po),!0):(h(!1),_(R=>R.map(D=>D.id===F?{...D,queued:!1}:D)),u(null),!0)}catch(q){return console.warn("Send now blocked/failed",q),u(ia(q)),!1}finally{f.current=!1,c(!1)}},[t,e,_]),A=l.useCallback(async N=>{if(!t||!N)return!1;const I=b.current.find(T=>T.id===N);if(!I)return!1;const B=I.content.trim();if(I.settled&&!I.queued)return _(T=>T.filter(F=>F.id!==N)),!0;if(!I.settled&&await QN(k.current,N)==="not-parked")return _(F=>F.filter(q=>q.id!==N)),!0;try{const T=vs(t);if(!T)return u("Unable to cancel this message right now."),!1;const F=await e(T,"cancel_queued_chat",{messageId:N,message:B,...ks(t)}),q=Ks(F),Q=typeof(q==null?void 0:q.cancelled)=="number"&&q.cancelled===0;return Q&&I.stale===!0?(_(K=>K.filter(R=>R.id!==N)),u(K=>K===po?null:K),!0):(q==null?void 0:q.success)===!1||Q?(u(GN),!1):(_(K=>K.filter(R=>R.id!==N)),u(K=>K===po?null:K),!0)}catch(T){return console.warn("Cancel queued send failed",T),u(ia(T)),!1}},[t,e,_]),O=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(N){console.error("Relaunch failed",N)}},[t,e]),L=l.useCallback(async N=>{if(t)try{const B=(t.modalButtons||[]).indexOf(N),T=N.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),F=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(T),q=vs(t);if(!q)return;const Q=await e(q,"resolve_action",{button:N,action:F?"approve":"reject",...B>=0&&{buttonIndex:B},...ks(t),...Ri(t)}),K=Ks(Q);K.success||s(R=>[...R,{routeId:t.tabKey,text:hm(N,K==null?void 0:K.error),timestamp:Date.now()}])}catch(I){mm(I)||console.error("[ModalButton] Error:",I),s(B=>[...B,{routeId:t.tabKey,text:mm(I)?hm(N,I):`❌ **${N}** error`,timestamp:Date.now()}])}},[t,e,s]),M=l.useCallback(async()=>{if(!(!t||o)){a(!0);try{await e(t.routeId,KN(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(N){console.error("Focus agent failed",N)}finally{a(!1)}}},[t,o,e]),$=p.length>0?p[p.length-1]:null;return l.useMemo(()=>({isSendingChat:i,sendFeedbackMessage:d,lastSendQueued:m,pendingLocalMessage:$,pendingLocalMessages:p,isFocusingAgent:o,handleSendChat:S,handleSendNowQueued:C,handleCancelQueued:A,retireEchoedPendingMessages:y,handleRelaunch:O,handleModalButton:L,handleFocusAgent:M}),[i,d,m,$,p,o,S,C,A,y,O,L,M])}const XN=10,ZN=8e3,eC=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function tC(e){return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s'"`]+/gi,"$1[REDACTED:bearer]").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]{12,}=*/gi,"$1[REDACTED:bearer]").replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{20,}\b/g,"[REDACTED:github-token]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:api-key]").replace(/\b(?:adk|adm)_[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:adhdev-token]").replace(/((?:api[_-]?key|token|secret|password|passwd|client[_-]?secret)\s*[:=]\s*)[^\s,'"`}&]+/gi,"$1[REDACTED:secret]").replace(/([?&](?:api[_-]?key|token|secret|password|client_secret)=)[^&#\s]+/gi,"$1[REDACTED:secret]")}function kc(e,t="",s=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(eC.test(t)&&e.trim())return"[REDACTED:secret-field]";const r=tC(e);return r.length>8e3?`${r.slice(0,8e3)}…[truncated ${r.length-8e3} chars]`:r}if(typeof e!="object")return String(e);if(s>=6)return"[MaxDepth]";if(Array.isArray(e)){const r=e.slice(-20).map(o=>kc(o,t,s+1));return e.length>20?[{truncatedBefore:e.length-20},...r]:r}return Object.fromEntries(Object.entries(e).slice(0,80).map(([r,o])=>[r,kc(o,r,s+1)]))}function Zr(e,t){return Array.isArray(e)?e.slice(-t):[]}function nC(e,t=Date.now()){const s=e&&t-e.firstAt<=ZN,r=s?e.count+1:1;return r>=XN?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:r,firstAt:s?e.firstAt:t},shouldCollect:!1}}function ug(e){var r,o;const{activeConv:t}=e,s={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((r=e.chatTailState.liveMessages)==null?void 0:r.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((o=e.chatTailState.historyMessages)==null?void 0:o.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Zr(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:Zr(t.messages,10),visibleMessagesTail:Zr(e.visibleMessages,5),historyMessagesTail:Zr(e.chatTailState.historyMessages,5),actionLogsTail:Zr(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{hasLiveSnapshot:!!e.chatTailState.hasLiveSnapshot,hasMoreHistory:!!e.chatTailState.hasMoreHistory,historyError:e.chatTailState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return kc(s)}function mg(e,t={}){const s=e&&typeof e=="object"?e:{},r=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),o=r==="copied"?"locator copied":r==="manual"?"locator shown for manual copy":"locator copy failed";return s.delivery==="daemon_file"?`Chat debug signal sent${typeof s.bundleId=="string"&&s.bundleId.trim()?` (${s.bundleId})`:""}; saved on daemon, ${o}.`:`Chat debug signal sent; ${o}.`}async function hg(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(s){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",s)}if(typeof document<"u"&&document.body){let s=null;try{if(s=document.createElement("textarea"),s.value=e,s.setAttribute("readonly","true"),s.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(s),s.focus(),s.select(),document.execCommand("copy"))return"copied"}catch{}finally{s==null||s.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function pg(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const s=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&s.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&s.push("","warnings:",...t.warnings.map(r=>`- ${String(r)}`)),s.join(`
|
|
32
|
+
`)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
|
|
33
|
+
|
|
34
|
+
\`\`\`json
|
|
35
|
+
${JSON.stringify(t.bundle,null,2)}
|
|
36
|
+
\`\`\``:`# ADHDev Chat Debug Bundle
|
|
37
|
+
|
|
38
|
+
\`\`\`json
|
|
39
|
+
${JSON.stringify(t,null,2)}
|
|
40
|
+
\`\`\``}function fl(e,t){return`${e}:${t}`}const sC=new Set(["intervalMs"]);function fm(e){const t={};for(const s of e)for(const[r,o]of Object.entries(s)){if(!(r in t)||t[r]===void 0){t[r]=o;continue}const a=t[r];typeof a=="boolean"&&typeof o=="boolean"?t[r]=a||o:typeof a=="number"&&typeof o=="number"?t[r]=sC.has(r)?Math.min(a,o):Math.max(a,o):t[r]=o}return t}function gm(e){const t=e.params;return t&&typeof t=="object"?{...t}:{}}function bm(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function rC(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function dr(e,t){rC()&&console.debug(`[subscription-manager] ${e}`,t)}class oC{constructor(){qe(this,"active",new Map);qe(this,"retryTimers",new Map)}subscribe(t,s,r,o,a){var h,p;const i=fl(r.topic,r.key),c=this.active.get(i);let d=!0;if(c){c.handlers.add(o),c.handlerParams.set(o,gm(r));const g={...r,params:fm(c.handlerParams.values())};(!bm(c.request,g)||c.daemonId!==s)&&(c.daemonId=s,c.request=g,d=((h=t.sendData)==null?void 0:h.call(t,s,g))??!1,!d&&(a!=null&&a.retryIntervalMs)?this.scheduleRetry(i,t,a.retryIntervalMs):d&&this.clearRetry(i),dr("subscribe_update",{daemonId:s,topic:r.topic,key:r.key,accepted:d})),c.lastUpdate&&o(c.lastUpdate)}else{const g={daemonId:s,request:r,handlers:new Set([o]),handlerParams:new Map([[o,gm(r)]])};this.active.set(i,g),dr("subscribe",{daemonId:s,topic:r.topic,key:r.key}),d=((p=t.sendData)==null?void 0:p.call(t,s,r))??!1,!d&&(a!=null&&a.retryIntervalMs)&&this.scheduleRetry(i,t,a.retryIntervalMs)}let u=!1;const m=()=>{var b,k;if(u)return;u=!0,this.clearRetry(i);const g=this.active.get(i);if(!g)return;if(g.handlers.delete(o),g.handlerParams.delete(o),g.handlers.size>0){const j={...g.request,params:fm(g.handlerParams.values())};bm(g.request,j)||(g.request=j,(b=t.sendData)==null||b.call(t,g.daemonId,j));return}this.active.delete(i);const f=g.daemonId,x={type:"unsubscribe",topic:r.topic,key:r.key};dr("unsubscribe",{daemonId:f,topic:r.topic,key:r.key}),(k=t.sendData)==null||k.call(t,f,x)};return m.initialSendAccepted=d,m}publish(t){const s=fl(t.topic,t.key),r=this.active.get(s);r&&(this.clearRetry(s),r.lastUpdate=t,Xs.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),r.handlers.forEach(o=>{o(t),Xs.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,s,r){const o=fl(t,s),a=this.active.get(o);if(a){a.request={...a.request,params:{...a.request.params,...r}};for(const[i,c]of a.handlerParams)a.handlerParams.set(i,{...c,...r})}}resubscribeAll(t){var s;dr("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(r=>({daemonId:r.daemonId,topic:r.request.topic,key:r.request.key}))});for(const r of this.active.values())(s=t.sendData)==null||s.call(t,r.daemonId,r.request)}resubscribeForDaemon(t,s){var o;const r=Array.from(this.active.values()).filter(a=>a.daemonId===t);dr("resubscribe_daemon",{daemonId:t,count:r.length,subscriptions:r.map(a=>({topic:a.request.topic,key:a.request.key}))});for(const a of r)(o=s.sendData)==null||o.call(s,a.daemonId,a.request)}scheduleRetry(t,s,r){if(this.retryTimers.has(t))return;const o=setTimeout(()=>{var c;this.retryTimers.delete(t);const a=this.active.get(t);if(!a)return;const i=((c=s.sendData)==null?void 0:c.call(s,a.daemonId,a.request))??!1;dr("subscribe_retry",{id:t,accepted:i,topic:a.request.topic,key:a.request.key}),i||this.scheduleRetry(t,s,r)},r);this.retryTimers.set(t,o)}clearRetry(t){const s=this.retryTimers.get(t);s!==void 0&&(clearTimeout(s),this.retryTimers.delete(t))}}const _n=new oC;function aC(e,t){const s=new Map;for(const r of e||[])if((r.daemonId||r.id.includes(":")&&r.id.split(":")[0]||"")===t&&r.sessionId){s.set(r.sessionId,{parentSessionId:r.parentSessionId,providerSessionId:r.providerSessionId,workspace:r.workspace??null,sessionCapabilities:r.sessionCapabilities,cdpConnected:r.cdpConnected,activeChat:r.activeChat,controlValues:r.controlValues,providerControls:r.providerControls,summaryMetadata:r.summaryMetadata,runtimeWriteOwner:r.runtimeWriteOwner,runtimeAttachedClients:r.runtimeAttachedClients,cliName:r.cliName,type:r.type,mode:r.mode,status:r.status,lastMessagePreview:r.lastMessagePreview,lastMessageRole:r.lastMessageRole,lastMessageAt:r.lastMessageAt,lastMessageHash:r.lastMessageHash,completionMarker:r.completionMarker,seenCompletionMarker:r.seenCompletionMarker,settings:r.settings,activeInteractivePrompt:r.activeInteractivePrompt});for(const a of r.childSessions||[]){if(!(a!=null&&a.id))continue;const i=s.get(a.id)||{};s.set(a.id,{...i,...a})}}return s}function iC(e){const t=[],s=new Map;for(const r of e)if(r.parentId){const o=s.get(r.parentId)||[];o.push(r),s.set(r.parentId,o)}else t.push(r);return{topLevel:t,childrenByParent:s}}function gl(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function lC(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function cC(e){lC()&&console.debug("[dashboard-conversations] statusPayloadToEntries",e.map(t=>({id:t.id,daemonId:t.daemonId,sessionId:t.sessionId,instanceId:t.instanceId,providerSessionId:t.providerSessionId,transport:t.transport,type:t.type})))}function Va(e,t){const s=[],{daemonId:r,existingDaemon:o,existingEntries:a,timestamp:i}=t,c=i||e.timestamp||Date.now(),d=e.sessions||[],u=on(r,e.instanceId),{topLevel:m,childrenByParent:h}=iC(d),p=aC(a,r),g=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,f=m.filter(k=>k.kind==="workspace"&&k.transport==="cdp-page"),x=m.filter(k=>k.kind==="agent"&&k.transport==="pty"),b=m.filter(k=>k.kind==="agent"&&k.transport==="acp");s.push({...o||{},id:r,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...g&&{machine:g,platform:g.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},...e.beacon&&{beacon:u?e.beacon:void 0},...e.fleetStatusPeerView&&{fleetStatusPeerView:e.fleetStatusPeerView},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:f.some(k=>!!k.cdpConnected)});for(const k of f){const j=p.get(k.id),v=uo(k,j),_=(h.get(k.id)||[]).map(y=>uo(y,p.get(y.id)));s.push({id:`${r}:ide:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:v.parentId,sessionKind:v.kind,transport:v.transport,sessionCapabilities:v.capabilities,type:v.providerType,status:v.cdpConnected?"online":"detected",daemonId:r,instanceId:gl(r,k.id),workspace:v.workspace,terminals:0,childSessions:_,agents:_.map(y=>({id:y.id,name:y.providerName||y.providerType,type:y.providerType,status:y.status})),activeChat:v.activeChat,...v.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:v.activeInteractivePrompt},chats:[],cdpConnected:v.cdpConnected,...v.lastMessagePreview!==void 0&&{lastMessagePreview:v.lastMessagePreview},...v.lastMessageRole!==void 0&&{lastMessageRole:v.lastMessageRole},...v.lastMessageAt!==void 0&&{lastMessageAt:v.lastMessageAt},...v.lastMessageHash!==void 0&&{lastMessageHash:v.lastMessageHash},lastUpdated:v.lastUpdated,unread:v.unread,lastSeenAt:v.lastSeenAt,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,seenCompletionMarker:v.seenCompletionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,...v.controlValues!==void 0&&{controlValues:v.controlValues},...v.providerControls!==void 0&&{providerControls:v.providerControls},...v.summaryMetadata!==void 0&&{summaryMetadata:v.summaryMetadata},...v.settings!==void 0&&{settings:v.settings},...v.messageInput!==void 0&&{messageInput:v.messageInput},timestamp:c})}for(const k of x){const j=p.get(k.id),v=uo(k,j);s.push({id:`${r}:cli:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:v.parentId,sessionKind:v.kind,transport:v.transport,sessionCapabilities:v.capabilities,type:v.providerType,agentType:v.providerType,status:Cu(v.status)||"generating",daemonId:r,instanceId:gl(r,k.id),cliName:v.providerName||v.providerType,mode:v.mode||(j==null?void 0:j.mode)||"terminal",workspace:v.workspace||"",...k.ownerDaemonId&&{ownerDaemonId:k.ownerDaemonId},...k.ownerMachineName&&{ownerMachineName:k.ownerMachineName},activeChat:v.activeChat,...v.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:v.activeInteractivePrompt},...v.resume!==void 0&&{resume:v.resume},...v.runtimeKey!==void 0&&{runtimeKey:v.runtimeKey},...v.runtimeDisplayName!==void 0&&{runtimeDisplayName:v.runtimeDisplayName},...v.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:v.runtimeWorkspaceLabel},...v.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:v.runtimeWriteOwner},...v.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:v.runtimeAttachedClients},...v.lastMessagePreview!==void 0&&{lastMessagePreview:v.lastMessagePreview},...v.lastMessageRole!==void 0&&{lastMessageRole:v.lastMessageRole},...v.lastMessageAt!==void 0&&{lastMessageAt:v.lastMessageAt},...v.lastMessageHash!==void 0&&{lastMessageHash:v.lastMessageHash},lastUpdated:v.lastUpdated,unread:v.unread,lastSeenAt:v.lastSeenAt,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,seenCompletionMarker:v.seenCompletionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,...v.controlValues!==void 0&&{controlValues:v.controlValues},...v.providerControls!==void 0&&{providerControls:v.providerControls},...v.summaryMetadata!==void 0&&{summaryMetadata:v.summaryMetadata},...v.settings!==void 0&&{settings:v.settings},...v.messageInput!==void 0&&{messageInput:v.messageInput},timestamp:c,_isCli:!0})}for(const k of b){const j=p.get(k.id),v=uo(k,j);s.push({id:`${r}:acp:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:v.parentId,sessionKind:v.kind,transport:v.transport,sessionCapabilities:v.capabilities,type:v.providerType,agentType:v.providerType,status:Cu(v.status)||"generating",daemonId:r,instanceId:gl(r,k.id),cliName:v.providerName||v.providerType,mode:"chat",workspace:v.workspace||"",...k.ownerDaemonId&&{ownerDaemonId:k.ownerDaemonId},...k.ownerMachineName&&{ownerMachineName:k.ownerMachineName},activeChat:v.activeChat,...v.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:v.activeInteractivePrompt},...v.runtimeKey!==void 0&&{runtimeKey:v.runtimeKey},...v.runtimeDisplayName!==void 0&&{runtimeDisplayName:v.runtimeDisplayName},...v.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:v.runtimeWorkspaceLabel},...v.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:v.runtimeWriteOwner},...v.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:v.runtimeAttachedClients},...v.lastMessagePreview!==void 0&&{lastMessagePreview:v.lastMessagePreview},...v.lastMessageRole!==void 0&&{lastMessageRole:v.lastMessageRole},...v.lastMessageAt!==void 0&&{lastMessageAt:v.lastMessageAt},...v.lastMessageHash!==void 0&&{lastMessageHash:v.lastMessageHash},lastUpdated:v.lastUpdated,unread:v.unread,lastSeenAt:v.lastSeenAt,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,seenCompletionMarker:v.seenCompletionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,...v.controlValues!==void 0&&{controlValues:v.controlValues},...v.providerControls!==void 0&&{providerControls:v.providerControls},...v.summaryMetadata!==void 0&&{summaryMetadata:v.summaryMetadata},...v.settings!==void 0&&{settings:v.settings},...v.messageInput!==void 0&&{messageInput:v.messageInput},timestamp:c,_isAcp:!0})}return cC(s),s}const dC=15e3,uC=15e3,mC=6e4,xm=12,hC=8e3,pC=4e3;function fC(e){const{force:t,hasSubscription:s,loadedAt:r,now:o,minFreshMs:a}=e;return t||r<=0?!0:s?!1:o-r>=a}const bl=new Map,xl=new Map,eo=new Set;function gC(e){if(!e||typeof e!="object")return null;const t=e,s=t.status;if(s&&typeof s=="object")return s;const r=t.result;if(r&&typeof r=="object"&&"status"in r){const o=r.status;if(o&&typeof o=="object")return o}return t}function Br(){const{sendCommand:e,sendData:t}=_t(),{injectEntries:s,getIdes:r}=Ar(),o=l.useRef(new Map);return l.useEffect(()=>{const a=o.current;return()=>{for(const[i,c]of a)c(),eo.delete(i);a.clear()}},[]),l.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??mC;if(!fC({force:i==null?void 0:i.force,hasSubscription:eo.has(a),loadedAt:xl.get(a)||0,now:Date.now(),minFreshMs:c}))return;const d=bl.get(a);if(d)return d;const u=(async()=>{var x;if(t&&!eo.has(a)){const b=_n.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},k=>{const j=r(),v=j.find(y=>y.id===a),_=Va(k.status,{daemonId:a,existingDaemon:v,existingEntries:j,timestamp:k.timestamp});_.length>0&&s(_),xl.set(a,Date.now())});(x=o.current.get(a))==null||x(),o.current.set(a,b),b.initialSendAccepted?eo.add(a):eo.delete(a)}const m=await e(a,"get_status_metadata"),h=gC(m);if(!h)return;const p=r(),g=p.find(b=>b.id===a),f=Va(h,{daemonId:a,existingDaemon:g,existingEntries:p,timestamp:h.timestamp||Date.now()});f.length>0&&s(f,{authoritativeDaemonIds:[a]}),xl.set(a,Date.now())})().finally(()=>{bl.delete(a)});return bl.set(a,u),u},[r,s,e,t])}const Es=8,ym=6;function bC(e,t,s){const r=Math.max(Es,s.width-t.width-Es),o=e.left+e.width/2-t.width/2,a=Math.min(Math.max(Es,o),r),i=e.bottom+ym,c=i+t.height<=s.height-Es,d=e.top-ym-t.height;return!c&&d>=Es?{top:d,left:a,placement:"above"}:{top:Math.max(Es,Math.min(i,s.height-t.height-Es)),left:a,placement:"below"}}function Md(){const e=l.useRef(null),t=l.useRef(null),[s,r]=l.useState({pinned:!1,peeking:!1}),[o,a]=l.useState(null),i=s.pinned||s.peeking,c=l.useCallback(()=>r({pinned:!1,peeking:!1}),[]),d=l.useCallback(()=>r(h=>h.pinned?{pinned:!1,peeking:!1}:{pinned:!0,peeking:!1}),[]),u=l.useCallback(h=>r(p=>p.peeking===h?p:{...p,peeking:h}),[]),m=l.useCallback(()=>{const h=e.current,p=t.current;if(!h||!p||typeof window>"u")return;const g=h.getBoundingClientRect(),f=p.getBoundingClientRect();a(bC({top:g.top,bottom:g.bottom,left:g.left,width:g.width},{width:f.width,height:f.height},{width:window.innerWidth,height:window.innerHeight}))},[]);return l.useLayoutEffect(()=>{if(!i){a(null);return}m()},[i,m]),l.useEffect(()=>{if(!i||typeof window>"u")return;const h=f=>{var x,b;f.key==="Escape"&&(f.stopPropagation(),f.preventDefault(),c(),(b=(x=e.current)==null?void 0:x.focus)==null||b.call(x))},p=f=>{var b,k;const x=f.target;x&&((b=e.current)!=null&&b.contains(x)||(k=t.current)!=null&&k.contains(x)||c())},g=()=>m();return window.addEventListener("keydown",h,!0),document.addEventListener("pointerdown",p,!0),document.addEventListener("mousedown",p,!0),window.addEventListener("resize",g),window.addEventListener("scroll",g,!0),()=>{window.removeEventListener("keydown",h,!0),document.removeEventListener("pointerdown",p,!0),document.removeEventListener("mousedown",p,!0),window.removeEventListener("resize",g),window.removeEventListener("scroll",g,!0)}},[c,i,m]),{anchorRef:e,popoverRef:t,open:i,pinned:s.pinned,position:o,close:c,togglePinned:d,setPeeking:u}}function Rd({id:e,popoverRef:t,position:s,children:r,className:o,role:a="tooltip",ariaLabel:i}){return typeof document>"u"?null:Qn.createPortal(n.jsx("div",{ref:t,id:e,role:a,"aria-label":i,"data-placement":(s==null?void 0:s.placement)??"below",className:ft("fixed z-[var(--z-tooltip)] max-w-[min(20rem,calc(100vw-16px))] rounded-lg border border-border-default bg-bg-card px-3 py-2 text-xs leading-relaxed text-text-secondary shadow-xl backdrop-blur-xl","whitespace-pre-line break-words normal-case tracking-normal font-normal text-left",o),style:s?{top:s.top,left:s.left}:{top:-9999,left:-9999,visibility:"hidden"},children:r}),document.body)}function fg(e){return e==null||e===!1||e===""}function dt({content:e,label:t,size:s=13,className:r,popoverClassName:o}){const{t:a}=ve("common"),i=l.useId(),c=`${i}-pop`,d=`${i}-desc`,{anchorRef:u,popoverRef:m,open:h,position:p,togglePinned:g,setPeeking:f}=Md();return fg(e)?null:n.jsxs("span",{className:"inline-flex items-center align-middle",children:[n.jsx("button",{ref:x=>{u.current=x},type:"button","data-infotip":"","aria-label":t??a("common.moreInfo"),"aria-expanded":h,"aria-controls":h?c:void 0,"aria-describedby":d,onClick:x=>{x.preventDefault(),x.stopPropagation(),g()},onPointerEnter:x=>{x.pointerType==="mouse"&&f(!0)},onPointerLeave:x=>{x.pointerType==="mouse"&&f(!1)},className:ft("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded-full border-none bg-transparent p-0 text-text-muted transition-colors hover:text-text-primary focus-visible:text-text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent",h&&"text-text-primary",r),children:n.jsx(Po,{size:s})}),n.jsx("span",{id:d,className:"sr-only",children:e}),h&&n.jsx(Rd,{id:c,popoverRef:m,position:p,className:o,children:e})]})}function tn({content:e,children:t,className:s,popoverClassName:r}){const o=l.useId(),a=`${o}-pop`,i=`${o}-desc`,{anchorRef:c,popoverRef:d,open:u,position:m,togglePinned:h,setPeeking:p}=Md();if(fg(e))return n.jsx(n.Fragment,{children:t});const g=n.jsx("span",{ref:f=>{c.current=f},"data-tooltip":"",tabIndex:0,"aria-describedby":i,className:ft("inline-flex max-w-full cursor-default items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-accent/60",s),onPointerEnter:f=>{f.pointerType==="mouse"&&p(!0)},onPointerLeave:f=>{f.pointerType==="mouse"&&p(!1)},onPointerUp:f=>{f.pointerType!=="mouse"&&h()},onFocus:()=>p(!0),onBlur:()=>p(!1),onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),h())},children:t});return n.jsxs(n.Fragment,{children:[g,n.jsx("span",{id:i,className:"sr-only",children:e}),u&&n.jsx(Rd,{id:a,popoverRef:d,position:m,className:r,children:e})]})}function W5({children:e,content:t,label:s,className:r,popoverClassName:o}){const i=`${l.useId()}-pop`,{anchorRef:c,popoverRef:d,open:u,position:m,togglePinned:h}=Md();return n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:p=>{c.current=p},type:"button","aria-label":s,"aria-expanded":u,"aria-haspopup":"dialog","aria-controls":u?i:void 0,onClick:p=>{p.preventDefault(),p.stopPropagation(),h()},className:r,children:e}),u&&n.jsx(Rd,{id:i,popoverRef:d,position:m,role:"dialog",ariaLabel:s,className:ft("whitespace-normal",o),children:t})]})}const xC=60,yC=50;function gg(e={}){return e.isCliLike?yC:xC}function vC(e={}){return gg(e)}const bg=new Map;function vm(e,t){if(!e)return t;const s=bg.get(e);return typeof s=="number"&&s>t?s:t}function wC(e,t){e&&bg.set(e,t)}function SC(e){return{"data-transcript-read-source":e.transcriptReadSource,...e.transcriptFallbackReason?{"data-transcript-fallback-reason":e.transcriptFallbackReason}:{},...e.stale?{"data-transcript-stale":"true"}:{},...e.omittedBefore?{"data-transcript-omitted-before":"true"}:{},...e.transcriptReplicaDegraded?{"data-transcript-replica-degraded":"true"}:{}}}function kC(e){const t={role:e.role,kind:e.kind,content:e.content};return e.receivedAt!==null&&(t.receivedAt=e.receivedAt),e.timestamp!==null&&(t.timestamp=e.timestamp),e.bubbleState!==null&&(t.bubbleState=e.bubbleState),e.senderName!==null&&(t.senderName=e.senderName),e.toolName!==null&&e.toolName&&(t.toolName=e.toolName,t.meta={...t.meta??{},label:e.toolName}),e.toolBlockRef!==null&&(t.toolBlockRef=e.toolBlockRef),e.turnKey!==null&&(t._turnKey=e.turnKey),typeof e.sequence=="number"&&(t.sequence=e.sequence),t}function jC(e){if(e.messageSource)return{selected:e.messageSource}}function xg(e){if(!e||typeof e!="object")return!1;const t=e;if(typeof t.sessionId!="string"||!t.sessionId||typeof t.status!="string"||!t.status||!Array.isArray(t.messages)||!t.provenance||typeof t.provenance!="object"||!("activeModal"in t))return!1;const s=t.activeModal;if(s!==null){if(!s||typeof s!="object")return!1;const r=s;if(typeof r.message!="string"||!Array.isArray(r.buttons))return!1}return!0}function yg(e,t){const s=jC(e.provenance);return{topic:"session.chat_tail",key:t.subscriptionKey,sessionId:e.sessionId,...e.historySessionId?{historySessionId:e.historySessionId}:{},seq:e.revision,timestamp:0,messages:e.messages.map(kC),status:e.status,...e.title?{title:e.title}:{},activeModal:e.activeModal?{message:e.activeModal.message,buttons:[...e.activeModal.buttons]}:null,activeInteractivePrompt:null,...s?{messageSource:s}:{},omittedBefore:t.omittedBefore,stale:t.stale,transcriptReadSource:"replica"}}const NC=new Set([...ku("working"),...ku("blocked"),...Object.keys(Rp).filter(e=>Pp(e))]);function fo(e){return bi(e)}const CC=new Set(["agent:generating_completed","agent:stopped","agent:waiting_approval","agent:waiting_choice"]);function vg(e){return typeof e=="string"&&CC.has(e)}function jc(e){return Pp(e)}const $o=60;function _C(e,t=$o){return{tailLimit:t}}function wm(e,t){const s=e[e.length-1];if(!s)return"empty:";let r="";try{r=JSON.stringify(s.content??"")}catch{r=String(s.content??"")}return["",e.length,String(s.id||""),String(s.index??""),String(s.receivedAt??s.timestamp??""),r].join("|")}function Ya(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(Ya).join(`
|
|
41
|
+
`);if(typeof e=="object"){const t=e;return Ya(t.text??t.content??t.value??"")}return String(e)}function Pd(e){return Ya(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function AC(e){return e.length===0||e.every(Pd)}function Sm(e){for(let t=e.length-1;t>=0;t-=1){const s=e[t],r=typeof(s==null?void 0:s.role)=="string"?s.role:"",o=typeof(s==null?void 0:s.kind)=="string"?s.kind:"";if(!(r==="system"||o==="system")&&!(o==="tool"||o==="thought"||o==="terminal"||o==="activity")&&!Pd(e[t]))return r}return""}function km(e){for(let t=e.length-1;t>=0;t-=1){const s=e[t],r=typeof(s==null?void 0:s.role)=="string"?s.role:"",o=typeof(s==null?void 0:s.kind)=="string"?s.kind:"";if(r==="system"||o==="system"||o==="tool"||o==="thought"||o==="terminal"||o==="activity"||Pd(e[t]))continue;if(r!=="assistant")return"";const a=e[t];return`${String(a.bubbleId??a.providerUnitKey??a.id??"")}#${Ya(a.content).length}`}return""}function wg(e,t){if(Sm(t)!=="assistant")return!1;const s=Array.isArray(e.liveMessages)?e.liveMessages:[];return Sm(s)!=="assistant"}function Ei(e){return typeof e=="string"?{selected:e}:e}function TC(e){const t=Ei(e);return!!t&&t.selected==="native-history"}function IC(e,t,s){return TC(s)?wg(e,t):!1}function Sg(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function MC(e,t,s,r,o,a,i){const c=jc(r)||fo(r),d=a&&e.hasLiveSnapshot;if(!c&&!d)return!1;const u=c?Sg(e,t):Array.isArray(e.liveMessages)?e.liveMessages.length:0;if(u<=0)return!1;if(AC(s))return!0;if(d&&!c&&wg(e,s))return!1;const m=Ei(o);if(m){const h=m.selected,p=m.fallbackReason;if(h==="native-history"||typeof p=="string"&&p!==""&&!p.startsWith("native_history_"))return!1}return i==="replica"?!1:s.length<u}function RC(e,t,s,r){if(s.length!==0||Sg(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0)return!1;const a=Ei(r);if(!a)return!1;const i=a.selected,c=a.fallbackReason,d=a.nativeSource;return i==="native-history"?c==="native_history_transient_gap_held":d==="native-unavailable"?!0:typeof c=="string"&&c.startsWith("native_history_")}function PC(e,t,s,r,o,a,i){return MC(e,t,s,r,o,a,i)?"defer-busy-shrink":RC(e,t,s,o)?"skip-transient-empty":"apply"}function LC(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function jm(e,t){const s=e[t];return typeof s=="string"?s:""}function Nm(e){return e.transcriptReadSource==="replica"?"replica":"legacy"}function Cm(e,t){return e[t]===!0}function _m(e,t){const s=e[t];return typeof s=="string"&&s.length>0?s:void 0}function EC(e,t){const{sendData:s,sendCommand:r,isConnected:o}=_t(),a=(t==null?void 0:t.enabled)!==!1,i=(t==null?void 0:t.refreshEnabled)!==!1,c=Cs(e),d=e.sessionId||"",u=Ii(e),m=`daemon:${c}:session:${d}`,h=Math.max(0,(t==null?void 0:t.tailLimit)??$o),p=e.messages.length,g=l.useMemo(()=>!a||!c||!d?null:Cg({daemonId:c,sessionId:d,historySessionId:u,subscriptionKey:m,sendData:s,tailLimit:h,fallbackRecentCount:p,includeActivity:qs()}),[c,a,u,s,d,m,h]);l.useEffect(()=>{g==null||g.updateOptions({fallbackRecentCount:p})},[g,p]);const[f,x]=l.useState(()=>(g==null?void 0:g.getSnapshot())||Qa(h));l.useEffect(()=>{if(!g){x(Qa(h));return}g.retain(),x(g.getSnapshot());const v=g.subscribe(_=>{x(_)});return()=>{v(),g.release()}},[g,h]);const b=l.useCallback(async()=>{!g||!c||!d||await g.loadHistoryPage(async({offset:v,excludeRecentCount:_,excludeFromIdentity:y})=>{const w=e.agentType,S=await r(c,"chat_history",{agentType:w,offset:v,limit:30,targetSessionId:d,historySessionId:u,excludeRecentCount:_,...y?{excludeFromIdentity:y}:{},...qs()?{includeActivity:!0}:{}}),C=S&&typeof S=="object"&&"result"in S?S.result||{}:S||{};return{messages:Array.isArray(C.messages)?C.messages:[],hasMore:C.hasMore===!0}})},[e.agentType,g,c,u,r,d]),k=l.useCallback((v=!1)=>!g||!c||!d?Promise.resolve():g.refreshAuthoritativeTail(async()=>{const _=await r(c,"read_chat",{agentType:e.agentType,targetSessionId:d,historySessionId:u,...h>0?{tailLimit:h}:{},...qs()?{includeActivity:!0}:{}}),y=_&&typeof _=="object"&&"result"in _?_.result:_;if(!y||typeof y!="object"||y.success===!1)return null;const w=Array.isArray(y.messages)?y.messages:Array.isArray(y.messagesTail)?y.messagesTail:[];return{topic:"session.chat_tail",key:m,sessionId:d,historySessionId:u,seq:0,timestamp:0,messages:w,status:typeof y.status=="string"?y.status:"idle",...y.messageSource&&typeof y.messageSource=="object"?{messageSource:y.messageSource}:{}}},{force:v}),[e.agentType,g,c,u,r,d,m,h]);l.useEffect(()=>{if(g)return yd(v=>{g.updateOptions({includeActivity:v}),v&&k(!0)})},[g,c,d,u]),l.useEffect(()=>{if(!g||!a||!i||!c||!d)return;k(!0);const v=()=>{typeof document<"u"&&document.visibilityState==="visible"&&k()},_=S=>{S.persisted&&k()};typeof document<"u"&&document.addEventListener("visibilitychange",v),typeof window<"u"&&window.addEventListener("pageshow",_);let y=o?o(c):!0;const w=setInterval(()=>{if(!o)return;const S=o(c);S&&!y&&k(),y=S},2e3);return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",v),typeof window<"u"&&window.removeEventListener("pageshow",_),clearInterval(w)}},[g,c,a,i,d,u]);const j=n_({hasController:!!g,enabled:a,daemonId:c,sessionId:d,refreshEnabled:i});return l.useEffect(()=>{if(!g||!j.armed)return;const v=setInterval(()=>{g.shouldRefreshForLiveness({visible:j.visible})&&k()},BC),_=()=>{typeof document>"u"||g.noteVisibilityChange(document.hidden)},y=()=>{g.noteVisibilityChange(!0)},w=()=>{g.noteVisibilityChange(!1)};return _(),typeof document<"u"&&document.addEventListener("visibilitychange",_),typeof window<"u"&&(window.addEventListener("pagehide",y),window.addEventListener("pageshow",w)),()=>{clearInterval(v),typeof document<"u"&&document.removeEventListener("visibilitychange",_),typeof window<"u"&&(window.removeEventListener("pagehide",y),window.removeEventListener("pageshow",w))}},[g,j.armed,j.visible,d,u]),l.useMemo(()=>JC(f,b),[b,f])}function DC(e,t){const{sendData:s}=_t(),r=(t==null?void 0:t.enabled)!==!1,o=Math.max(0,(t==null?void 0:t.tailLimit)??$o),a=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Di)),i=e_(a),[c,d]=l.useState(0);l.useEffect(()=>{if(!r||e.length===0)return;const m=setInterval(()=>{d(h=>h+1)},i);return()=>{clearInterval(m)}},[e.length,r,i]);const u=l.useMemo(()=>t_(e,{recentActivityMs:a}),[e,a,c]);l.useEffect(()=>{if(!r||!s||u.descriptors.length===0)return;const m=u.descriptors.map(h=>Cg({...h,sendData:s,tailLimit:o}));return m.forEach(h=>{h.retain()}),()=>{m.forEach(h=>h.release())}},[u.signature,r,s,o])}function OC(e){const[t,s]=l.useState(0),r=l.useMemo(()=>{const i=[];for(const c of e){const d=Cs(c),u=c.sessionId||"";if(!d||!u)continue;const m=Ii(c);i.push(Fo(d,u,m||u))}return i},[e]),o=r.join("|"),a=l.useSyncExternalStore(Ng,Tm,Tm);return l.useEffect(()=>{if(r.length===0)return;const i=[];for(const c of r){const d=is.get(c);if(!d)continue;let u=!1;i.push(d.subscribe(()=>{if(!u){u=!0;return}s(m=>m+1)}))}return()=>{for(const c of i)c()}},[o,a]),t}function $C(e){if(!e)return"";const t=e;return t.providerUnitKey?`unit:${t.providerUnitKey}`:t.bubbleId?`bubble:${t.bubbleId}`:typeof t.sequence=="number"&&Number.isFinite(t.sequence)?`seq:${t.sequence}`:""}const FC=1e3,HC=750,BC=5e3,kg=2e4,WC=12e4,UC=6e4,yl=kg,Am=500,Di=12e4,is=new Map;let jg=0;const Nc=new Set;function Cc(){jg+=1;for(const e of Nc)e()}function Ng(e){return Nc.add(e),()=>{Nc.delete(e)}}function Tm(){return jg}function Fo(e,t,s){return`${e}::${t}::${s||t}`}function Qa(e=$o){return{liveMessages:[],hasLiveSnapshot:!1,cursor:_C([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null,transcriptReadSource:"legacy",omittedBefore:!1,stale:!1,transcriptReplicaDegraded:!1}}class KC{constructor(t){qe(this,"manager");qe(this,"sendData");qe(this,"daemonId");qe(this,"sessionId");qe(this,"historySessionId");qe(this,"subscriptionKey");qe(this,"fallbackRecentCount");qe(this,"includeActivity");qe(this,"snapshot");qe(this,"transportSubscription",null);qe(this,"listeners",new Set);qe(this,"retainCount",0);qe(this,"loadHistoryPromise",null);qe(this,"pendingDisconnectTimer",null);qe(this,"authoritativeRefreshPromise",null);qe(this,"lastAuthoritativeRefreshAt",0);qe(this,"now");qe(this,"lastActiveStatusAt",0);qe(this,"lastAppliedAt",0);qe(this,"lastInboundAt",0);qe(this,"lastKnownStatus");qe(this,"lastMappedRevisionSnapshot",null);qe(this,"lastMappedOmittedBefore",!1);qe(this,"lastMappedStale",!1);qe(this,"terminalStatusRefreshPending",!1);qe(this,"lastLivenessAttemptAt",0);qe(this,"replicaHealthy",!1);qe(this,"lastReportedTransportSelection",null);qe(this,"everHadHealthyReplica",!1);qe(this,"lastReplicaAdvanceAt",0);qe(this,"lastReplicaRevision",0);qe(this,"lastReplicaBusyAt",0);qe(this,"hiddenSinceAt",0);qe(this,"hiddenElapsedMs",0);this.manager=t.manager||_n,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.includeActivity=t.includeActivity===!0,this.now=t.now??(()=>Date.now()),this.snapshot=Qa(Math.max(0,t.tailLimit??$o))}updateOptions(t){const s=this.sendData,r=this.daemonId,o=this.sessionId;if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.now&&(this.now=t.now),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const a=Math.max(0,t.tailLimit);a!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:a}},this.transportSubscription&&(this.disconnect(),this.connect()))}t.includeActivity!==void 0&&t.includeActivity!==this.includeActivity&&(this.includeActivity=t.includeActivity,this.transportSubscription&&(this.disconnect(),this.connect())),this.retainCount>0&&(s!==this.sendData||r!==this.daemonId||o!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...Qa(this.snapshot.cursor.tailLimit),hasLiveSnapshot:!0},this.lastMappedRevisionSnapshot=null,this.emit()}reportTranscriptReplicaFallback(t){const s=this.replicaHealthy;this.replicaHealthy=!1,(s||!this.transportSubscription)&&this.syncLegacySubscription();const r=this.everHadHealthyReplica;this.snapshot.transcriptReadSource==="legacy"&&this.snapshot.transcriptFallbackReason===t&&this.snapshot.transcriptReplicaDegraded===r||(this.snapshot={...this.snapshot,transcriptReadSource:"legacy",transcriptFallbackReason:t,transcriptReplicaDegraded:r},this.emit())}applyTranscriptReplicaSnapshot(t,s){if(!xg(t)){this.reportTranscriptReplicaFallback("revision_invalid");return}const r=this.lastMappedRevisionSnapshot===t&&this.lastMappedOmittedBefore===s.omittedBefore&&this.lastMappedStale===(s.stale===!0);let o;if(r){const c=this.now();this.lastInboundAt=c,this.lastKnownStatus=t.status,(jc(t.status)||fo(t.status))&&(this.lastActiveStatusAt=c),o="noop"}else o=this.handleUpdate(s.mapped??yg(t,{subscriptionKey:this.subscriptionKey,omittedBefore:s.omittedBefore,stale:s.stale===!0})),o==="noop"?(this.lastMappedRevisionSnapshot=t,this.lastMappedOmittedBefore=s.omittedBefore,this.lastMappedStale=s.stale===!0):this.lastMappedRevisionSnapshot=null;const a=typeof t.revision=="number"?t.revision:0;a>this.lastReplicaRevision&&(this.lastReplicaRevision=a,this.lastReplicaAdvanceAt=this.now(),this.hiddenElapsedMs=0),fo(t.status)&&(this.lastReplicaBusyAt=this.now()),!this.replicaHealthy&&o==="applied"&&(this.replicaHealthy=!0,this.everHadHealthyReplica=!0,this.lastReplicaAdvanceAt===0&&(this.lastReplicaAdvanceAt=this.now()),this.syncLegacySubscription()),this.snapshot.transcriptReplicaDegraded&&(this.snapshot={...this.snapshot,transcriptReplicaDegraded:!1},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.syncLegacySubscription(),this.retainCount===1&&Cc()}isRetained(){return this.retainCount>0}getIdentity(){return{daemonId:this.daemonId,sessionId:this.sessionId}}release(){const t=this.retainCount>0;this.retainCount=Math.max(0,this.retainCount-1),t&&this.retainCount===0&&Cc(),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const s=(async()=>{try{const r=this.snapshot.hasLiveSnapshot,o=r?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),a=await t({offset:this.snapshot.historyOffset,excludeRecentCount:o,excludeFromIdentity:$C(this.snapshot.liveMessages[0])}),i=Array.isArray(a.messages)?a.messages:[],c=!r&&i.length===0&&a.hasMore!==!0&&this.fallbackRecentCount>0,d=[...i,...this.snapshot.historyMessages],u=d.length>Am?d.slice(d.length-Am):d;this.snapshot={...this.snapshot,historyMessages:u,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:a.hasMore===!0,historyError:null}}catch(r){this.snapshot={...this.snapshot,historyError:r instanceof Error?r.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=s,s}expireStaleReplicaLease(){if(!this.replicaHealthy||this.lastReplicaBusyAt===0)return;const t=this.now(),s=this.hiddenElapsedMs+(this.hiddenSinceAt>0?Math.max(0,t-this.hiddenSinceAt):0);if(t-this.lastReplicaBusyAt-s>yl)return;const r=t-this.lastReplicaAdvanceAt-s>=yl,o=this.lastAppliedAt>0&&t-this.lastAppliedAt-s>=yl;!r&&!o||this.reportTranscriptReplicaFallback(r?"replica_lease_expired":"replica_screen_stalled")}noteTerminalStatusEvent(t){vg(t)&&(this.terminalStatusRefreshPending=!0)}noteVisibilityChange(t){const s=this.now();if(t){this.hiddenSinceAt===0&&(this.hiddenSinceAt=s);return}this.hiddenSinceAt!==0&&(this.hiddenElapsedMs+=Math.max(0,s-this.hiddenSinceAt),this.hiddenSinceAt=0)}shouldRefreshForLiveness(t={}){if(this.expireStaleReplicaLease(),this.lastInboundAt===0||this.authoritativeRefreshPromise)return!1;if(this.terminalStatusRefreshPending)return this.terminalStatusRefreshPending=!1,!0;if(this.replicaHealthy)return!1;const s=Math.max(this.lastAppliedAt,this.lastLivenessAttemptAt),r=this.now()-s,o=fo(this.lastKnownStatus)?kg:WC,a=t.visible===!0?o:Math.max(o,UC);return r>=a}getLivenessStateForTest(){return{lastInboundAt:this.lastInboundAt,lastAppliedAt:this.lastAppliedAt,lastKnownStatus:this.lastKnownStatus}}refreshAuthoritativeTail(t,s={}){if(this.authoritativeRefreshPromise)return this.authoritativeRefreshPromise;const r=this.now();if(!s.force&&this.lastAuthoritativeRefreshAt>0&&r-this.lastAuthoritativeRefreshAt<HC)return Promise.resolve();this.lastAuthoritativeRefreshAt=r;const o=(async()=>{try{const a=await t();a&&this.handleUpdate(a),this.lastInboundAt=this.now(),this.lastLivenessAttemptAt=this.now()}catch{this.lastInboundAt=this.now(),this.lastLivenessAttemptAt=this.now()}})().finally(()=>{this.authoritativeRefreshPromise=null});return this.authoritativeRefreshPromise=o,o}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{},...this.includeActivity?{includeActivity:!0}:{}}}}shouldRunLegacySubscription(){return!this.replicaHealthy}syncLegacySubscription(){this.retainCount<=0||(this.shouldRunLegacySubscription()?this.connect():this.disconnect(),this.reportTransportSelection())}reportTransportSelection(){if(!this.sendData||!this.daemonId)return;const t=this.replicaHealthy?"replica":"legacy";if(this.lastReportedTransportSelection!==t){this.lastReportedTransportSelection=t;try{this.sendData(this.daemonId,{type:"command",commandType:"report_transcript_transport",data:{selection:t}})}catch{}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||this.shouldRunLegacySubscription()&&(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:FC}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null,this.replicaHealthy=!1,this.lastReportedTransportSelection=null,this.everHadHealthyReplica=!1,this.lastReplicaAdvanceAt=0,this.lastReplicaRevision=0,this.lastReplicaBusyAt=0,this.hiddenSinceAt=0,this.hiddenElapsedMs=0,this.lastMappedRevisionSnapshot=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return"rejected";const s=jm(t,"sessionId");if(s&&s!==this.sessionId)return"rejected";const r=jm(t,"historySessionId");if(r&&this.historySessionId&&r!==this.historySessionId)return"rejected";const o=LC(t),a=t.messageSource,i=this.now();this.lastInboundAt=i,this.lastKnownStatus=t.status;const c=this.lastActiveStatusAt>0&&i-this.lastActiveStatusAt<=Di;(jc(t.status)||fo(t.status))&&(this.lastActiveStatusAt=i);const d=IC(this.snapshot,o,a);if(!d&&PC(this.snapshot,this.fallbackRecentCount,o,t.status,a,c,Nm(t))!=="apply")return"deferred";const u={tailLimit:this.snapshot.cursor.tailLimit};return!d&&wm(this.snapshot.liveMessages)===wm(o)&&km(this.snapshot.liveMessages)===km(o)&&this.snapshot.cursor.tailLimit===u.tailLimit?"noop":(this.lastAppliedAt=i,this.hiddenElapsedMs=0,this.snapshot={...this.snapshot,liveMessages:o,hasLiveSnapshot:!0,cursor:u,messageSource:Ei(a),transcriptReadSource:Nm(t),omittedBefore:Cm(t,"omittedBefore"),stale:Cm(t,"stale"),..._m(t,"transcriptFallbackReason")!==void 0?{transcriptFallbackReason:_m(t,"transcriptFallbackReason")}:{}},this.emit(),"applied")}}function Cg(e){const t=Fo(e.daemonId,e.sessionId,e.historySessionId),s=is.get(t);if(s)return s.updateOptions(e),s;const r=new KC(e);return is.set(t,r),Cc(),r}function qC(e,t,s){if(!e||!t)return;const r=`${e}::${t}::`,o=Fo(e,t,s);for(const[a,i]of is.entries())(a===o||a.startsWith(r))&&i.clearLiveSnapshot()}function _g(e){const t=Cs(e),s=e.sessionId||"";if(!t||!s)return;const r=Ii(e),o=Fo(t,s,r||s),a=is.get(o);if(!a)return;const i=a.getSnapshot();return i.hasLiveSnapshot?i:void 0}function zC(e,t,s,r){if(!e||!t)return 0;const o=`${e}::${t}::`;let a,i=0;for(const[c,d]of is.entries())c.startsWith(o)&&(!a&&xg(s)&&(a=yg(s,{subscriptionKey:`daemon:${e}:session:${t}`,omittedBefore:r.omittedBefore,stale:r.stale===!0})),d.applyTranscriptReplicaSnapshot(s,{...r,mapped:a}),i+=1);return i}function GC(e,t,s){if(!e||!t||!vg(s))return 0;const r=`${e}::${t}::`;let o=0;for(const[a,i]of is.entries())a.startsWith(r)&&(i.noteTerminalStatusEvent(s),o+=1);return o}function VC(e,t,s){if(!e||!t)return;const r=`${e}::${t}::`;for(const[o,a]of is.entries())o.startsWith(r)&&a.reportTranscriptReplicaFallback(s)}function YC(){const e=new Map;for(const s of is.values()){if(!s.isRetained())continue;const{daemonId:r,sessionId:o}=s.getIdentity();if(!r||!o)continue;const a=e.get(r);a?a.add(o):e.set(r,new Set([o]))}const t=new Map;for(const[s,r]of e.entries())t.set(s,[...r].sort());return t}function QC(e){return Ng(e)}function JC(e,t){return{...e,loadHistoryPage:t}}function XC(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function ZC(e,t={}){const s=String(e.status||"").trim().toLowerCase();if(NC.has(s)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const r=t.now??Date.now(),o=Math.max(0,Number(t.recentActivityMs??Di)),a=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return a>0?r-a<=o:Array.isArray(e.messages)&&e.messages.length>0}function e_(e=Di){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function t_(e,t={}){const s=new Set,r=[];for(const o of e){if(!ZC(o,t))continue;const a=Cs(o),i=o.sessionId||"";if(!a||!i)continue;const c=Ii(o),d=Fo(a,i,c||i);s.has(d)||(s.add(d),r.push({daemonId:a,sessionId:i,historySessionId:c,subscriptionKey:`daemon:${a}:session:${i}`}))}return r.sort(XC),{descriptors:r,signature:r.map(o=>`${o.subscriptionKey}|${o.historySessionId}`).join("||")}}function n_(e){return{armed:!!(e.hasController&&e.enabled&&e.daemonId&&e.sessionId),visible:e.refreshEnabled}}const s_=5e3;function r_(e,t,s=s_){const[r,o]=l.useState(!1);return l.useEffect(()=>{if(!e){o(!1);return}o(!1);const a=setTimeout(()=>{o(!0)},s);return()=>clearTimeout(a)},[e,t,s]),r}const _c="https://adhf.dev",Ag="https://dev.adhf.dev";function Tg(e){return e==="adhf.dev"||e==="adhdev-web.pages.dev"||e==="localhost"||e==="127.0.0.1"?_c:Ag}function o_(){return typeof window>"u"?_c:Tg(window.location.hostname)}function a_(){const e=o_();return{unix:{cmd:`curl -fsSL ${e}/install | sh`,shell:"Terminal",prompt:"$ "},powershell:{cmd:`irm ${e}/install.ps1 | iex`,shell:"PowerShell",prompt:"PS> "},cmd:{cmd:`curl -fsSL ${e}/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd`,shell:"CMD",prompt:"> "}}}function i_(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function l_(e){return i_(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Ma=new Map,Ac=new Set;function Im(e,t){!e||Ma.get(e)===t||(t?Ma.set(e,!0):Ma.delete(e),Ac.forEach(r=>r(e,t)))}function c_(e){return e?Ma.get(e)===!0:!1}function d_(e){return Ac.add(e),()=>{Ac.delete(e)}}function u_(e,t,s=`${t}s`){return`${e} ${e===1?t:s}`}function m_(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function h_(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Ig(e){return bi(e.status)||e.inboxBucket==="working"}function Mg(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function p_(e){return Ig(e)?!1:e.inboxBucket==="task_complete"&&Mg(e).length>0}function Mm(e){return e.branch||"detached HEAD"}function f_(e){if(e.error)return`${Mm(e)} · Git error: ${e.error}`;const t=[Mm(e)];return e.changedFiles>0?t.push(u_(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function g_(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${f_(t)}`}function b_(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function x_(e,t={}){if(t.enabled===!1)return[];if(!h_(e))return[];const s=Ig(e)?"working":p_(e)?"complete":null;if(!s)return[];const r=s==="complete"?Mg(e):"";return[{id:s==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${m_(r)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:g_(s,e.git),timestamp:b_(e,e.git),meta:{source:"git-system-bubble",phase:s,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const y_=60,v_=3e4;function w_(e){return{enabled:!!e.sessionId,refreshEnabled:e.isVisible,tailLimit:e.tailLimit}}function S_(e,t){return e.status==="no_progress"||e.status==="long_generating"?t("chatPane.busyNoProgress"):e.status==="generating"?t("chatPane.busyGenerating"):e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?t("chatPane.busyWaitingApproval"):null}const k_=["unsupported_source","source_unavailable","source_changed","block_not_found","not_a_tool_block"];function j_(e){return k_.find(t=>t===e)}function N_(){return typeof window>"u"?!1:Tg(window.location.hostname)===Ag}function C_(e,t){return!t||!e?"":` (${e})`}function Rg({activeConv:e,ideEntry:t,handleSendChat:s,handleSendNowQueued:r,handleCancelQueued:o,isSendingChat:a=!1,sendFeedbackMessage:i=null,pendingLocalMessage:c=null,pendingLocalMessages:d=null,retireEchoedPendingMessages:u,handleFocusAgent:m,isFocusingAgent:h,actionLogs:p,userName:g,scrollToBottomRequestNonce:f,isInputActive:x=!0,isVisible:b=!0}){var E,oe,Ie,Z,se,ye,$e;const{t:k}=ve("common"),j=l.useRef(new Map),v=l.useRef(void 0),_=Br(),{sendCommand:y}=_t(),{isVisible:w}=kd(),S=Ad(),C=Cs(e),A=It.useMemo(()=>{const Me=S.connectionRetryStatuses;if(!Me||!C)return;const De=Me[C];if(De)return De;const Te=Object.keys(Me).find(He=>on(He,C));return Te?Me[Te]:void 0},[S.connectionRetryStatuses,C]);Oo("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:p.length,isSendingChat:a});const O=It.useMemo(()=>or(e),[e.status,e.connectionState]);It.useEffect(()=>{const Me=e.sessionId;if(Me)return Im(Me,O.isGenerating),()=>{Im(Me,!1)}},[e.sessionId,O.isGenerating]);const L=l.useMemo(()=>BN(e,t),[e,t]),M=l.useMemo(()=>Xj(L.targetEntry),[L.targetEntry]),$=l.useMemo(()=>{var Me;return _d((Me=L.targetEntry)==null?void 0:Me.providerControls,{hostIdeType:e.hostIdeType,providerType:L.providerType})},[e.hostIdeType,L.providerType,(E=L.targetEntry)==null?void 0:E.providerControls]),N=gg({isCliLike:L.isCli||L.isAcp}),I=vC({isCliLike:L.isCli||L.isAcp}),B=EC(e,w_({sessionId:e.sessionId,isVisible:b,tailLimit:I})),T=r_(B.transcriptReplicaDegraded,e.tabKey),[F,q]=l.useState(()=>vm(e.tabKey,N)),[Q,K]=l.useState(()=>qs()),R=e.tabKey,D=B.historyMessages,P=B.hasMoreHistory,H=B.historyError,W=eg(e,B),U=TN(W,d??(c?[c]:null),void 0,{excludeQueued:!0}),ae=((d==null?void 0:d.length)??0)>0;l.useEffect(()=>{if(!u||(u(W),!ae))return;const Me=setInterval(()=>u(W),v_);return()=>clearInterval(Me)},[u,W,ae]);const be=l.useMemo(()=>t0(U).length,[U]);l.useEffect(()=>{q(vm(R,N))},[N,R]);const V=Math.max(0,U.length-F),we=Td(e),ce=Cs(e),de=l_(e),ne=Pi(e),ee=S_(e,k),ue=i||null,je=cg(e)||i||ee,X=!!ne,[G,z]=l.useState(!1);l.useEffect(()=>{const Me=L.targetEntry;ce&&(!Me||Me.providerControls===void 0||Me.controlValues===void 0)&&_(ce,{minFreshMs:3e4}).catch(()=>{})},[ce,L.isAcp,(oe=L.targetEntry)==null?void 0:oe.providerControls,(Ie=L.targetEntry)==null?void 0:Ie.controlValues,_]);const ie=l.useCallback(async()=>{if(!G){if(U.length>F){q(Me=>{const De=Math.min(U.length,Me+y_);return wC(R,De),De});return}z(!0);try{await B.loadHistoryPage()}finally{z(!1)}}},[B,G,U.length,R,F]),{allMessages:Ne,receivedAtMap:Be}=l.useMemo(()=>{const Me=LN({historyMessages:D,liveMessages:U,visibleLiveCount:F}),De=x_(e),Te=De.length>0?[...Me,...De]:Me,He={};return Te.forEach((tt,Ct)=>{const J=ji(tt),re=`${e.tabKey}:${J}`;let le=Ia(tt)||j.current.get(re)||0;le||(le=Date.now(),j.current.set(re,le)),He[J]=le}),{allMessages:Te,receivedAtMap:He}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,V,D,U,F]),Le=l.useMemo(()=>p.filter(Me=>Me.routeId===e.tabKey).sort((Me,De)=>Me.timestamp-De.timestamp),[p,e.tabKey]),[Je,Se]=l.useState({});l.useEffect(()=>{Se({})},[e.tabKey]);const he=l.useCallback(async(Me,De)=>{if(ce){Se(Te=>({...Te,[Me]:{status:"loading"}}));try{const Te=await y(ce,"expand_tool_block",{targetSessionId:e.sessionId,agentType:L.providerType||e.agentType,toolBlockRef:De}),He=Ks(Te),tt=He!=null&&He.success?He.callArgs!==void 0?`${He.toolName?`${He.toolName}: `:""}${He.callArgs}`:He.result:void 0;Se(Ct=>({...Ct,[Me]:tt!==void 0?{status:"expanded",text:tt}:{status:"error",error:j_(He==null?void 0:He.reason)}}))}catch{Se(Te=>({...Te,[Me]:{status:"error"}}))}}},[e.agentType,e.sessionId,L.providerType,ce,y]),pe=l.useCallback(Me=>{Se(De=>{if(!De[Me])return De;const Te={...De};return delete Te[Me],Te})},[]),Ee=l.useCallback(async()=>{var Ct,J;if(!ce)return;const Me=ug({activeConv:e,visibleMessages:Ne,actionLogs:p,controls:(Ct=L.targetEntry)==null?void 0:Ct.providerControls,controlValues:(J=L.targetEntry)==null?void 0:J.controlValues,visibleBarControlCount:$.length,chatTailState:{liveMessages:B.liveMessages,hasLiveSnapshot:B.hasLiveSnapshot,hasMoreHistory:P,historyError:H,historyMessages:D},ui:{controlsVisible:w,visibleLiveCount:F,activityVisible:Q,activityCount:be,hiddenLiveCount:V,isInputActive:x,isVisible:b}}),De=await y(ce,"get_chat_debug_bundle",{agentType:L.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:Me}),Te=Ks(De),He=pg(Te),tt=await hg(He);tt==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ct.showToast(mg(Te,{locatorCopyStatus:tt}),tt==="failed"?"warning":"success")},[e,p,be,Ne,w,B.hasLiveSnapshot,B.liveMessages,L.providerType,(Z=L.targetEntry)==null?void 0:Z.controlValues,(se=L.targetEntry)==null?void 0:se.providerControls,ce,P,V,D,x,b,H,y,Q,$.length,F]);l.useEffect(()=>yd(K),[]);const Y=l.useCallback(()=>{K(Me=>{const De=!Me;return uf(De),De})},[]),me=l.useCallback(()=>{const Me=nC(v.current);v.current=Me.state,Me.shouldCollect&&Ee().catch(De=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",De),ct.showErrorToast(k("chatPane.debugBundleFailed"),De)})},[Ee,k]),fe=l.useMemo(()=>{if(U.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[n.jsx("div",{className:"connecting-logo-float",children:n.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),n.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[n.jsxs("div",{className:"text-xxs text-blue-400 font-medium",children:[k("chatPane.connectingToMachine"),n.jsx("span",{className:"connecting-dots"})]}),n.jsx("div",{className:"text-2xs opacity-35",children:k("chatPane.establishingP2P")})]})]});if(O.isGenerating&&z(!1),e.status==="not_monitored"&&de)return n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[n.jsx("div",{className:"text-3xl opacity-60",children:n.jsx(Ir,{size:28})}),n.jsx("div",{className:"text-xxs opacity-50",children:k("chatPane.agentNotMonitored")}),n.jsx("button",{onClick:m,disabled:h,className:"btn btn-primary",children:h?n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(Mr,{size:12}),k("chatPane.switchingPanel")]}):n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Zs,{size:14})," ",k("chatPane.openPanel",{label:we})]})}),n.jsx("div",{className:"text-2xs opacity-35 max-w-[280px]",children:k("chatPane.clickToSwitchMonitoring")})]});if(e.status==="panel_hidden"&&de)return n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[n.jsx("div",{className:"text-3xl opacity-60",children:n.jsx(md,{size:28})}),n.jsx("div",{className:"text-xxs opacity-50",children:k("chatPane.agentPanelHidden")}),n.jsx("button",{onClick:m,disabled:h,className:"btn btn-primary",children:h?n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(Mr,{size:12}),k("chatPane.openingPanel")]}):n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Zs,{size:14})," ",k("chatPane.openPanel",{label:we})]})}),n.jsx("div",{className:"text-2xs opacity-35 max-w-[280px]",children:k("chatPane.openPanelHint")})]});if(e.status==="idle"&&!G)return!P&&D.length===0?n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[n.jsx("div",{className:"opacity-40",children:n.jsx(Jn,{size:26})}),n.jsx("div",{className:"text-xxs opacity-40",children:k("chatPane.noMessagesYet")})]}):n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[n.jsx("div",{className:"opacity-40 animate-pulse",children:n.jsx(Jn,{size:26})}),n.jsx("div",{className:"text-xxs opacity-40",children:k("chatPane.loadingChat")})]})}},[e.connectionState,e.status,de,m,P,D.length,h,G,U.length,we,O.isGenerating]);return n.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",...SC(B),children:[n.jsxs("div",{className:"chat-activity-toggle-bar",children:[n.jsxs("button",{type:"button",className:`chat-activity-toggle ${Q?"chat-activity-toggle-active":""}`,onClick:Y,"aria-pressed":Q,title:k("chatPane.activityToggleTitle"),children:[n.jsx("span",{className:"chat-activity-toggle-dot"}),k("chatPane.activityToggleLabel"),be>0&&n.jsx("span",{className:"chat-activity-toggle-count",children:be})]}),n.jsx("div",{className:"ml-auto flex items-center gap-1",children:n.jsx(uN,{machineId:C,blocked:!!(A!=null&&A.blocked),retryConnection:S.retryConnection})})]}),T&&n.jsxs("div",{className:"flex items-center gap-1 px-3 py-1 text-2xs text-amber-400/90 bg-amber-500/10 border-b border-amber-500/20",role:"status","data-testid":"transcript-replica-degraded-notice",children:[n.jsx("span",{className:"font-semibold",children:k("chatPane.replicaDegradedShort")}),n.jsx(dt,{content:k("chatPane.replicaDegraded"),size:12}),C_(B.transcriptFallbackReason,N_())]}),n.jsx(g0,{messages:Ne,actionLogs:Le,agentName:Rr(e)||we||"Agent",userName:g,isCliMode:L.isCli||L.isAcp,isWorking:O.isGenerating,contextKey:e.tabKey,receivedAtMap:Be,lastMessageHash:e.lastMessageHash,showActivityMessages:Q,onLoadMore:ie,isLoadingMore:G,hasMoreHistory:P,hiddenLiveCount:V,loadError:H??void 0,emptyState:fe,scrollToBottomRequestNonce:f,isVisible:b,onSendNow:r,isSendingNow:a,onCancelQueued:o,toolExpansions:Je,onExpandToolBlock:he,onCollapseToolBlock:pe}),n.jsx(lN,{entries:d??(c?[c]:[]),onSendNow:r,onCancelQueued:o,isSendingNow:a}),n.jsx(tN,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:L.providerType,displayLabel:L.displayLabel,controls:(ye=L.targetEntry)==null?void 0:ye.providerControls,controlValues:($e=L.targetEntry)==null?void 0:$e.controlValues,currentStatus:e.status,coordinatorHint:Ri(e),isActive:x,isCliTerminal:L.isCliTerminal,launchSurface:M}),!L.isCliTerminal&&n.jsx(Gf,{contextKey:e.tabKey,panelLabel:we,isSending:a,isBusy:X,statusMessage:je,inlineStatusMessage:ue,onSend:s,isActive:x,showControlsToggle:$.length>0,onControlsToggle:me,messageInput:e.messageInput})]})}const __=.5,A_=1.25,Mn="\x1B",Rm={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function T_(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function Pm(e,t){let s=e;if(t.shift&&s.length===1&&(s=s.toUpperCase()),t.ctrl){const r=s.toUpperCase().charCodeAt(0);return String.fromCharCode(r&31)}return s}function I_(e,t){if(t in Rm){const r=Rm[t],o=T_(e);return o===1?`${Mn}[${r}`:`${Mn}[1;${o}${r}`}switch(t){case"Enter":return e.alt?`${Mn}\r`:"\r";case"Escape":return e.alt?`${Mn}${Mn}`:Mn;case"Backspace":{const r=e.ctrl?"\b":"";return e.alt?`${Mn}${r}`:r}case"Tab":{const r=e.shift?`${Mn}[Z`:" ";return e.alt&&!e.shift?`${Mn} `:r}case"Space":{const r=Pm(" ",e);return e.alt?`${Mn}${r}`:r}}const s=Pm(t,e);return e.alt?`${Mn}${s}`:s}const Pg="adhdev:mesh-names:v1",M_=200;let to=null,Lg=0;const Tc=new Set;function Eg(){if(to)return to;to=new Map;try{const e=typeof localStorage<"u"?localStorage.getItem(Pg):null,t=e?JSON.parse(e):null;if(t&&typeof t=="object"&&!Array.isArray(t))for(const[s,r]of Object.entries(t))typeof r=="string"&&r.trim()&&to.set(s,r.trim())}catch{}return to}function R_(e){try{if(typeof localStorage>"u")return;const t=[...e.entries()].slice(-M_);localStorage.setItem(Pg,JSON.stringify(Object.fromEntries(t)))}catch{}}function Ja(e){const t=Eg();let s=!1;for(const r of e){const o=typeof(r==null?void 0:r.id)=="string"?r.id.trim():"",a=typeof(r==null?void 0:r.name)=="string"?r.name.trim():"";!o||!a||a===o||t.get(o)!==a&&(t.delete(o),t.set(o,a),s=!0)}if(s){Lg+=1,R_(t);for(const r of[...Tc])try{r()}catch{}}}function P_(e,t){Ja([{id:e,name:t}])}function L_(e){return e?Eg().get(e)??null:null}function E_(e){return Tc.add(e),()=>{Tc.delete(e)}}function Lm(){return Lg}const Em=Object.freeze({role:null,meshId:null,meshName:null});function vl(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ld(e,t=L_){var a;if(!e)return Em;const s=e.settings||{},r=vl((a=e.coordinator)==null?void 0:a.meshId)||vl(s.meshCoordinatorFor);if(r)return{role:"coordinator",meshId:r,meshName:t(r)};const o=vl(s.meshNodeFor);return o?{role:"worker",meshId:o,meshName:t(o)}:s.launchedByCoordinator===!0?{role:"worker",meshId:null,meshName:null}:Em}function D_(e){return Ld(e).role==="coordinator"}function Dg(e){return!!(e!=null&&e.daemonId)&&D_(e)}function O_(e){return e.meshName||e.meshId}function Oi(e){return l.useSyncExternalStore(E_,Lm,Lm),Ld(e)}function Rt(e){return Td(e)}function Ho(e){return ag(e).join(" · ")}function Og(e,t){const s=og(e,t);return s||(e.title?e.title:Ho(e)||"No messages yet")}function $g(e,t){const{isReconnecting:s,isConnecting:r,isErrored:o}=or(e);return s?"Reconnecting…":r?"Connecting…":t!=null&&t.requiresAction?"Action needed":o?"Needs attention":null}function $_(e,t){const s=["Chat",...ag(e)];return t!=null&&t.timestampLabel&&s.push(t.timestampLabel),s.filter(Boolean).join(" · ")}function Gs(e){return $g(e)||Ho(e)}function F_(e,t){return`${Rt(e)} · ${Og(e,t)}`}function H_(e){const t=Ga(e),s=t?Kt(t):Rr(e);return`${Rt(e)} — ${s||"Agent"}`}function B_(e){return Rr(e)||"CLI"}function Fg(e){return rg(e)}function Hg(e){return e?`Remote · ${Rt(e)||e.workspaceName||"Session"}`:"Remote"}const Dm=[{kind:"regex",label:"section matches",hint:"regex against a screen section",make:e=>({section:e[0],matches:""})},{kind:"elapsed",label:"elapsed_ms",hint:"N ms since state entered",make:()=>({elapsed_ms:1e3})},{kind:"stable",label:"stable_ms",hint:"region unchanged for N ms",make:()=>({stable_ms:1e3,cursor_above:5})},{kind:"changed",label:"changed",hint:"region changed vs prev frame",make:()=>({cursor_above:3,changed:!0})},{kind:"all",label:"all (AND)",hint:"every child must match",make:()=>({all:[]})},{kind:"any",label:"any (OR)",hint:"some child must match",make:()=>({any:[]})},{kind:"not",label:"not",hint:"invert a condition",make:()=>({not:{matches:""}})}],W_=[{label:"active spinner (busy)",cond:{section:"body",matches:"(?:^|\\n)\\s*[·✢✳✶✽✷✸✹]\\s+\\w.*?(?:…|\\.\\.\\.)"}},{label:"completion marker (done)",cond:{section:"body",matches:"✻\\s+\\w+ed\\s+for\\s+(?:\\d+h\\s+)?(?:\\d+m\\s+)?\\d+s"}},{label:"approval prompt (❯ 1.)",cond:{section:"footer",matches:"(?:^|\\n)\\s*[❯›>]\\s*1\\.\\s*.+"}},{label:"picker (Select a …)",cond:{section:"modal",matches:"Select (?:a |an )?(?:model|mode|option)\\b"}},{label:"stable 1.2s (settled)",cond:{stable_ms:1200,cursor_above:5}}];function U_(e){return"all"in e?"all":"any"in e?"any":"not"in e?"not":"elapsed_ms"in e?"elapsed":"stable_ms"in e&&!("changed"in e)?"stable":"changed"in e?"changed":"regex"}function Ed({cond:e,path:t,sections:s,onChange:r,onRemove:o,onPreview:a,preview:i}){const c=U_(e),d=i[t],u=m=>{const h=Dm.find(p=>p.kind===m);h&&r(h.make(s))};return n.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-1.5 space-y-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("select",{value:c,onChange:m=>u(m.target.value),className:"bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1 py-0.5",children:Dm.map(m=>n.jsx("option",{value:m.kind,children:m.label},m.kind))}),(c==="regex"||c==="stable"||c==="changed"||c==="elapsed")&&n.jsx("button",{type:"button",className:"text-3xs text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>a(t,e),children:"test"}),d&&d!=="loading"&&n.jsx("span",{className:`text-3xs font-mono px-1.5 py-0.5 rounded ${d.result?"text-status-online bg-status-online/20":"text-text-secondary bg-bg-glass"}`,children:d.result?"match ✓":"no match"}),d==="loading"&&n.jsx("span",{className:"text-3xs text-text-muted",children:"testing…"}),o&&n.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-xs px-1",onClick:o,children:"×"})]}),c==="regex"&&n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsxs("select",{value:e.section??"",onChange:m=>r({...e,section:m.target.value||void 0}),className:"bg-bg-secondary text-accent-primary text-3xs font-mono rounded border border-border-default px-1 py-0.5",children:[n.jsx("option",{value:"",children:"(whole screen)"}),s.map(m=>n.jsx("option",{value:m,children:m},m))]}),n.jsx("input",{value:e.matches??"",onChange:m=>r({...e,matches:m.target.value}),placeholder:"regex",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),c==="elapsed"&&n.jsx(ws,{label:"elapsed_ms",value:e.elapsed_ms,onChange:m=>r({elapsed_ms:m})}),c==="stable"&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ws,{label:"stable_ms",value:e.stable_ms,onChange:m=>r({...e,stable_ms:m})}),n.jsx(ws,{label:"cursor_above",value:e.cursor_above??0,onChange:m=>r({...e,cursor_above:m||void 0})})]}),c==="changed"&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ws,{label:"cursor_above",value:e.cursor_above,onChange:m=>r({...e,cursor_above:m})}),n.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:[n.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:m=>r({...e,changed:m.target.checked}),className:"accent-[var(--accent-primary)]"}),"changed"]})]}),(c==="all"||c==="any")&&n.jsx(K_,{kind:c,cond:e,path:t,sections:s,onChange:r,onPreview:a,preview:i}),c==="not"&&n.jsx("div",{className:"pl-2 border-l border-border-default",children:n.jsx(Ed,{cond:e.not,path:`${t}.not`,sections:s,onChange:m=>r({not:m}),onPreview:a,preview:i})})]})}function K_({kind:e,cond:t,path:s,sections:r,onChange:o,onPreview:a,preview:i}){const c=(e==="all"?t.all:t.any)??[],d=u=>o(e==="all"?{all:u}:{any:u});return n.jsxs("div",{className:"pl-2 border-l border-border-default space-y-1",children:[c.map((u,m)=>n.jsx(Ed,{cond:u,path:`${s}.${e}[${m}]`,sections:r,onChange:h=>d(c.map((p,g)=>g===m?h:p)),onRemove:()=>d(c.filter((h,p)=>p!==m)),onPreview:a,preview:i},m)),n.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d([...c,{section:r[0],matches:""}]),children:"+ condition"}),W_.map(u=>n.jsxs("button",{type:"button",className:"text-3xs text-accent-primary/80 hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>d([...c,JSON.parse(JSON.stringify(u.cond))]),title:"insert verified pattern",children:["+ ",u.label]},u.label))]})]})}function ws({label:e,value:t,onChange:s}){return n.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary font-mono",children:[e,n.jsx("input",{type:"number",value:Number.isFinite(t)?t:0,onChange:r=>s(Number(r.target.value)),className:"w-20 bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5 outline-none focus:border-accent"})]})}function q_({sections:e,otherSectionIds:t,onChange:s,onTest:r,testResult:o}){const a=Object.keys(e),i=o&&o!=="loading"&&!("error"in o)?Object.fromEntries(o.sections.map(h=>[h.id,h])):{},c=(h,p)=>{if(!p||p===h||e[p])return;const g={};for(const[f,x]of Object.entries(e))g[f===h?p:f]=x;s(g)},d=(h,p)=>s({...e,[h]:p}),u=h=>{const p={...e};delete p[h],s(p)},m=()=>{let h="section",p=1;for(;e[h];)h=`section${p++}`;s({...e,[h]:{from_top:0}})};return n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"Sections"}),n.jsx("span",{className:"text-text-muted text-3xs",children:"— how the screen is split; conditions match against these"}),n.jsx("button",{type:"button",className:"ml-auto text-3xs text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:r,title:"Resolve all sections against the live session screen",children:o==="loading"?"testing…":"test on live screen"}),n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:m,children:"+ section"})]}),o&&o!=="loading"&&"error"in o&&n.jsx("div",{className:"text-status-error bg-status-error/15 border border-status-error/40 rounded p-1.5 text-3xs mb-1",children:o.error}),n.jsx("div",{className:"space-y-1.5",children:a.map(h=>{var x;const p=e[h],g=p.anchor!=null?"anchor":"positional",f=b=>{b==="anchor"?d(h,{anchor:p.anchor??"^",anchor_last:p.anchor_last,until:p.until}):d(h,{from_top:p.from_top??0,until:p.until})};return n.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{value:h,onChange:b=>c(h,b.target.value.trim()),className:"w-28 bg-bg-secondary text-accent-primary font-mono text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),n.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-3xs",children:[n.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="positional"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>f("positional"),children:"positional"}),n.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="anchor"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>f("anchor"),children:"anchor"})]}),n.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-sm px-1",onClick:()=>u(h),children:"×"})]}),g==="positional"?n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx(ws,{label:"from_top",value:typeof p.from_top=="number"?p.from_top:0,onChange:b=>d(h,{...p,from_top:b,from_bottom:void 0})}),n.jsx(ws,{label:"from_bottom",value:typeof p.from_bottom=="number"?p.from_bottom:0,onChange:b=>d(h,{...p,from_bottom:b||void 0})}),n.jsx(Om,{def:p,otherIds:t(h),onChange:b=>d(h,b)})]}):n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"text-3xs text-text-muted w-16",children:"anchor"}),n.jsx("input",{value:p.anchor??"",onChange:b=>d(h,{...p,anchor:b.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),n.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:[n.jsx("input",{type:"checkbox",checked:!!p.anchor_last,onChange:b=>d(h,{...p,anchor_last:b.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"last"]})]}),n.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:n.jsx(Om,{def:p,otherIds:t(h),onChange:b=>d(h,b)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"text-3xs text-text-muted w-16",children:"ctx next"}),n.jsx("input",{value:((x=p.anchor_context)==null?void 0:x.next)??"",onChange:b=>d(h,{...p,anchor_context:{...p.anchor_context,next:b.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-secondary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})]}),i[h]&&n.jsxs("div",{className:"border-t border-border-subtle pt-1",children:[n.jsxs("div",{className:"text-4xs text-text-muted mb-0.5",children:["captured lines ",i[h].fromLine,"–",i[h].toLine,i[h].text.trim()===""&&n.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),n.jsx("pre",{className:"font-mono text-3xs text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary rounded border border-border-subtle px-2 py-1 max-h-28 overflow-y-auto",children:i[h].text||"(empty)"})]})]},h)})})]})}function Om({def:e,otherIds:t,onChange:s}){const r=e.until??"",o=r.startsWith("^");return n.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:["until",n.jsxs("select",{value:o?"__regex__":r,onChange:a=>{const i=a.target.value;s(i===""?{...e,until:void 0}:i==="__regex__"?{...e,until:r.startsWith("^")?r:"^"}:{...e,until:i})},className:"bg-bg-secondary text-accent-primary rounded border border-border-default px-1 py-0.5",children:[n.jsx("option",{value:"",children:"(none)"}),t.map(a=>n.jsx("option",{value:a,children:a},a)),n.jsx("option",{value:"__regex__",children:"regex…"})]}),o&&n.jsx("input",{value:r,onChange:a=>s({...e,until:a.target.value}),spellCheck:!1,className:"w-40 bg-bg-secondary text-text-primary font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})}function z_({model:e,onChange:t,onPreview:s,preview:r,onTestSections:o,sectionPreview:a}){const i=e.states.map(h=>h.id),c=Object.keys(e.sections??{}),d=l.useCallback(h=>t({...e,...h}),[e,t]),u=(h,p)=>d({states:e.states.map((g,f)=>f===h?{...g,...p}:g)}),m=(h,p)=>d({transitions:e.transitions.map((g,f)=>f===h?{...g,...p}:g)});return n.jsxs("div",{className:"space-y-3",children:[n.jsx(q_,{sections:e.sections??{},otherSectionIds:h=>c.filter(p=>p!==h),onChange:h=>d({sections:h}),onTest:()=>o(e.sections??{}),testResult:a}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"States"}),n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),n.jsx("div",{className:"space-y-1.5",children:e.states.map((h,p)=>n.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1",children:[n.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[n.jsxs("label",{className:"flex flex-col gap-0.5",children:[n.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide",children:"id (used by transitions)"}),n.jsx("input",{value:h.id,onChange:g=>u(p,{id:g.target.value}),placeholder:"idle",className:"w-32 bg-bg-secondary text-accent-primary font-mono text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),n.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[n.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide",children:"label (shown in dashboard)"}),n.jsx("input",{value:h.label,onChange:g=>u(p,{label:g.target.value}),placeholder:"Ready",className:"w-full bg-bg-secondary text-text-primary text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),n.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1 pb-0.5",onClick:()=>d({states:e.states.filter((g,f)=>f!==p)}),children:"×"})]}),n.jsxs("div",{className:"flex items-center gap-3 text-3xs text-text-secondary flex-wrap",children:[n.jsxs("label",{className:"flex items-center gap-1",children:[n.jsx("input",{type:"radio",name:"initial",checked:!!h.initial,onChange:()=>d({states:e.states.map((g,f)=>({...g,initial:f===p}))}),className:"accent-[var(--accent-primary)]"}),"initial"]}),n.jsxs("label",{className:"flex items-center gap-1",children:[n.jsx("input",{type:"checkbox",checked:!!h.modal,onChange:g=>u(p,{modal:g.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"modal"]}),n.jsxs("label",{className:"flex items-center gap-1",children:["status",n.jsxs("select",{value:h.status??"",onChange:g=>u(p,{status:g.target.value||void 0}),className:"bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5",children:[n.jsx("option",{value:"",children:"(auto)"}),n.jsx("option",{value:"idle",children:"idle"}),n.jsx("option",{value:"generating",children:"generating"}),n.jsx("option",{value:"approval",children:"approval"})]})]})]})]},p))})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"Transitions"}),n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d({transitions:[...e.transitions,{from:i[0]??"",to:i[0]??""}]}),children:"+ transition"})]}),n.jsx("div",{className:"space-y-1.5",children:e.transitions.map((h,p)=>n.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:"text-3xs text-text-muted",children:"from"}),n.jsx(G_,{value:h.from,states:i,onChange:g=>m(p,{from:g})}),n.jsx("span",{className:"text-3xs text-text-muted",children:"→"}),n.jsx("select",{value:h.to,onChange:g=>m(p,{to:g.target.value}),className:"bg-bg-secondary text-status-online font-mono text-3xs rounded border border-border-default px-1 py-0.5",children:i.map(g=>n.jsx("option",{value:g,children:g},g))}),n.jsx("span",{className:"text-3xs text-text-muted ml-1",children:"label"}),n.jsx("input",{value:h.label??"",onChange:g=>m(p,{label:g.target.value||void 0}),placeholder:"debug name only (optional)",title:"Display name shown in the debug history/transition table. Does not affect behaviour.",className:"flex-1 min-w-[120px] bg-bg-secondary text-text-secondary text-3xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),n.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1",onClick:()=>d({transitions:e.transitions.filter((g,f)=>f!==p)}),children:"×"})]}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(ws,{label:"min_hold_ms",value:h.min_hold_ms??0,onChange:g=>m(p,{min_hold_ms:g||void 0})}),n.jsx(ws,{label:"priority",value:h.priority??0,onChange:g=>m(p,{priority:g||void 0})})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-3xs text-text-muted",children:"when"}),!h.when&&n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>m(p,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),h.when&&n.jsx("button",{type:"button",className:"text-3xs text-text-muted hover:text-status-error",onClick:()=>m(p,{when:void 0}),children:"remove guard"})]}),h.when&&n.jsx(Ed,{cond:h.when,path:`t${p}`,sections:c,onChange:g=>m(p,{when:g}),onPreview:s,preview:r})]})]},p))})]})]})}function G_({value:e,states:t,onChange:s}){const r=new Set(Array.isArray(e)?e:e==="*"?t:[e]),o=e==="*",a=i=>{const c=new Set(r);c.has(i)?c.delete(i):c.add(i);const d=t.filter(u=>c.has(u));s(d.length===1?d[0]:d)};return n.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>n.jsx("button",{type:"button",onClick:()=>a(i),className:`font-mono text-3xs px-1 py-0.5 rounded border ${o||r.has(i)?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-muted border-border-default hover:border-border-default"}`,children:i},i))})}function Cn(e){return e&&typeof e=="object"?e:{}}function At(e){return typeof e=="string"?e:""}function V_(e){const t=Cn(e);return!!(typeof t.spec_id=="string"&&t.spec_id.length>0||"current_state"in t||Array.isArray(t.stateHistory))}function Y_(e){const t=Cn(e.parser),s=Cn(t.parsedStatusCache),r=Cn(e.activeModal).buttons!=null?Cn(e.activeModal):Cn(s.activeModal),o=Array.isArray(r.buttons)?r.buttons:null;if(!o||o.length===0){const a=At(r.message)||At(r.title);return a?{title:a,buttons:[]}:null}return{title:At(r.message)||At(r.title)||null,buttons:o.map((a,i)=>({index:i,label:typeof a=="string"?a:String(a)}))}}function Q_(e){const t=Array.isArray(e.messages)?e.messages:null;return t?t.map(s=>Cn(s)).filter(s=>typeof s.role=="string").map(s=>({role:At(s.role),content:At(s.content),receivedAt:typeof s.receivedAt=="number"?s.receivedAt:void 0})):[]}function $m(e){if(e==null||typeof e!="object")return null;const t=e;if(V_(e))return{cliType:At(t.cliType),spec_id:At(t.spec_id),specPath:typeof t.specPath=="string"?t.specPath:void 0,current_state:t.current_state??null,current_modal:t.current_modal??null,activeInteractivePrompt:t.activeInteractivePrompt,exited:t.exited===!0,screen:At(t.screen),sections:t.sections??void 0,stateHistory:Array.isArray(t.stateHistory)?t.stateHistory:[],statusHistory:[],idleHoldPending:t.idleHoldPending===!0,lastBusyAt:typeof t.lastBusyAt=="number"?t.lastBusyAt:0,cursorPosition:t.cursorPosition??null,completionIdleDebounce:t.completionIdleDebounce??null,fsm:t.fsm??null,name:typeof t.name=="string"?t.name:void 0,status:typeof t.status=="string"?t.status:void 0,workingDir:typeof t.workingDir=="string"?t.workingDir:void 0,spawnedAtMs:typeof t.spawnedAtMs=="number"?t.spawnedAtMs:void 0,providerSessionId:t.providerSessionId??null,messages:t.messages??void 0,committedMessages:t.committedMessages??void 0,nativeSource:!1,transcriptAuthority:void 0};const s=Cn(t.terminal),r=Cn(t.parser),o=Cn(r.parsedStatusCache),a=Cn(t.runtimeMetadata),i=At(s.screenText)||At(s.lastScreenText)||At(t.screenText),c=At(o.status)||At(t.currentStatus)||At(t.status),d=At(o.providerSessionId)||At(a.providerSessionId)||null,u=At(o.transcriptAuthority)||At(t.transcriptAuthority)||void 0,m=(Array.isArray(t.statusHistory)?t.statusHistory:[]).map(h=>Cn(h)).filter(h=>typeof h.status=="string"&&typeof h.at=="number").map(h=>({status:h.status,at:h.at,trigger:typeof h.trigger=="string"?h.trigger:null}));return{cliType:At(t.cliType)||At(t.type),spec_id:At(t.cliType)||At(t.type)||"native-source",specPath:typeof t.specPath=="string"?t.specPath:void 0,current_state:c?{id:c,label:c,title:null}:null,current_modal:Y_(t),activeInteractivePrompt:t.activeInteractivePrompt??null,exited:t.exited===!0,screen:i,sections:void 0,stateHistory:[],statusHistory:m,idleHoldPending:!1,lastBusyAt:typeof t.lastBusyAt=="number"?t.lastBusyAt:0,cursorPosition:null,completionIdleDebounce:null,fsm:null,name:At(t.cliName)||At(t.name)||void 0,status:c||void 0,workingDir:typeof t.workingDir=="string"?t.workingDir:void 0,spawnedAtMs:typeof a.spawnedAtMs=="number"?a.spawnedAtMs:typeof t.spawnAt=="number"?t.spawnAt:void 0,providerSessionId:d,messages:Q_(t),committedMessages:void 0,nativeSource:!0,transcriptAuthority:u}}function ur(e){const t=Date.now()-e;return t<0?Ka(e):t<2e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:Ka(e)}function Fm(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const J_={busy_hold_expired:"text-status-warning bg-status-warning/20 border border-status-warning/40",idle_hold_committed:"text-status-online bg-status-online/20 border border-status-online/40",completion_idle_after:"text-accent-primary bg-accent-primary/20 border border-accent",forced_completion:"text-orange-200 bg-orange-500/20 border border-orange-500/30",forceEmit:"text-purple-200 bg-purple-500/20 border border-purple-500/30",spec_reload:"text-purple-200 bg-purple-500/20 border border-purple-500/30",eval_match:"text-text-secondary bg-bg-glass border border-border-default"},X_={idle:"text-status-online bg-status-online/20 border border-status-online/40",busy:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",generating:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",waiting_approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",picker:"text-accent-primary bg-accent-primary/20 border border-accent",signing_in:"text-accent-primary bg-accent-primary/20 border border-accent"};function la(e){return X_[e]??"text-text-primary bg-bg-glass border border-border-default"}function mr({children:e}){return n.jsx("div",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function ca(){return n.jsx("div",{className:"border-t border-white/8 my-2"})}function Bg({node:e,depth:t=0}){var o;const s=e.result?"text-status-online":"text-text-muted",r=e.result?"●":"○";return n.jsxs("div",{style:{marginLeft:t*10},className:"font-mono text-3xs leading-relaxed",children:[n.jsxs("span",{className:s,children:[r," "]}),n.jsx("span",{className:"text-text-secondary",children:e.kind}),n.jsxs("span",{className:"text-text-muted",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&n.jsxs("span",{className:"text-status-warning",children:[" (",e.remainingMs,"ms left)"]}),(o=e.children)==null?void 0:o.map((a,i)=>n.jsx(Bg,{node:a,depth:t+1},i))]})}function Z_({t:e}){const[t,s]=l.useState(!1),r=e.fires?"text-status-online bg-status-online/20 border-status-online/40":e.holdSatisfied?"text-text-secondary bg-bg-glass border-border-default":"text-status-warning bg-status-warning/20 border-status-warning/40";return n.jsxs("div",{className:"border border-border-default rounded bg-surface-secondary overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-bg-glass-hover text-left",onClick:()=>s(o=>!o),children:[n.jsx("span",{className:"text-3xs text-text-muted w-3",children:e.cond?t?"▾":"▸":" "}),n.jsxs("span",{className:`font-mono text-2xs px-1.5 py-0.5 rounded border ${r}`,children:["→ ",e.to]}),n.jsx("span",{className:"text-text-secondary font-mono text-3xs truncate",children:e.label}),n.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.fires&&n.jsx("span",{className:"text-status-online text-3xs font-mono",children:"FIRES"}),!e.holdSatisfied&&n.jsxs("span",{className:"text-status-warning text-3xs font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),n.jsx("span",{className:`text-3xs font-mono ${e.condResult?"text-status-online":"text-text-muted"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&n.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-bg-secondary border-t border-border-default",children:n.jsx(Bg,{node:e.cond})})]})}function e1({activeConv:e,onClose:t}){var de,ne,ee,ue,je;const{sendCommand:s}=_t(),[r,o]=l.useState(!0),[a,i]=l.useState(null),[c,d]=l.useState(null),[u,m]=l.useState(!1),[h,p]=l.useState(new Set(["footer"])),[g,f]=l.useState("Snapshot"),[x,b]=l.useState(!1),[k,j]=l.useState(null),[v,_]=l.useState(!1),[y,w]=l.useState(""),[S,C]=l.useState(!1),[A,O]=l.useState("idle"),[L,M]=l.useState(null),[$,N]=l.useState([]),[I,B]=l.useState({}),[T,F]=l.useState(null),[q,Q]=l.useState(!1),K=e.daemonId||((de=e.routeId)==null?void 0:de.split(":")[0])||e.routeId||"",R=e.sessionId||"",D=l.useCallback(async()=>{o(!0),d(null);try{const X=await s(K,"get_spec_debug",{targetSessionId:R}),G=X&&typeof X=="object"?X:{},z=G.result&&typeof G.result=="object"?G.result:G;z!=null&&z.success?i(z):(d((z==null?void 0:z.error)||"Failed to load spec debug"),i(null))}catch(X){d((X==null?void 0:X.message)||String(X)),i(null)}finally{o(!1)}},[s,K,R]);l.useEffect(()=>{D()},[D]),l.useEffect(()=>{if(!q)return;const X=setInterval(()=>{D()},1e3);return()=>clearInterval(X)},[q,D]),l.useEffect(()=>{const X=G=>{G.key==="Escape"&&!x&&t()};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[t,x]);const P=l.useCallback(async X=>{try{const G=await s(K,"validate_spec",{content:JSON.stringify(X)}),z=G&&typeof G=="object"?G:{},ie=z.result&&typeof z.result=="object"?z.result:z;N(ie!=null&&ie.valid?[]:(ie==null?void 0:ie.errors)??["validation failed"])}catch(G){N([(G==null?void 0:G.message)||String(G)])}},[s,K]),H=l.useCallback(async()=>{M(null),O("idle"),B({});try{const X=await s(K,"get_spec_source",{targetSessionId:R}),G=X&&typeof X=="object"?X:{},z=G.result&&typeof G.result=="object"?G.result:G;if(!(z!=null&&z.success)||typeof z.content!="string"){M((z==null?void 0:z.error)||"Failed to load spec source");return}w(z.content);let ie=null;try{ie=JSON.parse(z.content)}catch{}ie&&ie.$schema==="adhdev:cli/spec@4"?(j(ie),_(!1),P(ie)):(j(null),_(!0)),C(!1),b(!0)}catch(X){M((X==null?void 0:X.message)||String(X))}},[s,K,R,P]),W=l.useCallback(X=>{j(X),w(JSON.stringify(X,null,2)),C(!0),O("idle"),P(X)},[P]),U=l.useCallback(async(X,G)=>{B(z=>({...z,[X]:"loading"}));try{const z=await s(K,"eval_condition_preview",{targetSessionId:R,condition:G}),ie=z&&typeof z=="object"?z:{},Ne=ie.result&&typeof ie.result=="object"?ie.result:ie;!(Ne!=null&&Ne.success)||!Ne.result?B(Be=>({...Be,[X]:{result:!1,detail:Ne==null?void 0:Ne.error}})):B(Be=>({...Be,[X]:{result:Ne.result.result,detail:Ne.result.detail}}))}catch(z){B(ie=>({...ie,[X]:{result:!1,detail:z==null?void 0:z.message}}))}},[s,K,R]),ae=l.useCallback(async X=>{F("loading");try{const G=await s(K,"resolve_section_preview",{targetSessionId:R,sections:X}),z=G&&typeof G=="object"?G:{},ie=z.result&&typeof z.result=="object"?z.result:z;!(ie!=null&&ie.success)||!Array.isArray(ie.sections)?F({error:(ie==null?void 0:ie.error)||"resolve failed"}):F({sections:ie.sections,screenLineCount:ie.screenLineCount??0})}catch(G){F({error:(G==null?void 0:G.message)||String(G)})}},[s,K,R]),be=l.useCallback(async()=>{var z,ie;const X=(z=a==null?void 0:a.snapshot)==null?void 0:z.specPath;if(!X){M("No spec path on this session");return}if(!v&&$.length>0){M("Fix validation errors before saving");return}const G=!v&&k?JSON.stringify(k,null,2):y;O("saving"),M(null);try{const Ne=await s(K,"write_spec_source",{specPath:X,content:G}),Be=Ne&&typeof Ne=="object"?Ne:{},Le=Be.result&&typeof Be.result=="object"?Be.result:Be;if(!(Le!=null&&Le.success)){O("error"),M(((ie=Le==null?void 0:Le.validationErrors)==null?void 0:ie.join(`
|
|
42
|
+
`))||(Le==null?void 0:Le.error)||"Save failed");return}O("saved"),C(!1),setTimeout(()=>{D()},400),setTimeout(()=>O("idle"),1500)}catch(Ne){O("error"),M((Ne==null?void 0:Ne.message)||String(Ne))}},[s,K,(ne=a==null?void 0:a.snapshot)==null?void 0:ne.specPath,y,k,v,$,D]),V=$m(a==null?void 0:a.snapshot),we=async()=>{var Je,Se,he;let X=a;X||(await D(),X=a);const G=$m(X==null?void 0:X.snapshot),z=[],ie=(G==null?void 0:G.nativeSource)===!0;if(z.push("# Spec Debug Snapshot"),z.push(`Generated: ${new Date().toISOString()}`),z.push(`Session: ${(X==null?void 0:X.sessionId)??""} (${(X==null?void 0:X.providerType)??""})`),ie&&(z.push("Provider kind: native-source (no state-machine spec — State History / FSM / Sections are N/A)"),G!=null&&G.transcriptAuthority&&z.push(`transcriptAuthority: ${G.transcriptAuthority}`)),z.push(`Spec: ${(G==null?void 0:G.spec_id)??""} (${(G==null?void 0:G.specPath)??""})`),z.push(`Provider: ${(G==null?void 0:G.name)??""} (${(G==null?void 0:G.cliType)??""})`),z.push(`Working dir: ${(G==null?void 0:G.workingDir)??""}`),z.push(`Spawned: ${G!=null&&G.spawnedAtMs?new Date(G.spawnedAtMs).toISOString():""}`),z.push(""),z.push("## Current State"),z.push(`State: ${((Je=G==null?void 0:G.current_state)==null?void 0:Je.id)??"none"} (${((Se=G==null?void 0:G.current_state)==null?void 0:Se.label)??""})`),z.push(`Status: ${(G==null?void 0:G.status)??""}`),z.push(`Idle hold pending: ${(G==null?void 0:G.idleHoldPending)??!1}`),z.push(`Exited: ${(G==null?void 0:G.exited)??!1}`),z.push(`Last busy: ${G!=null&&G.lastBusyAt?ur(G.lastBusyAt):""}`),z.push(`Cursor: ${(G==null?void 0:G.cursorPosition)!=null?`(${G.cursorPosition.row},${G.cursorPosition.col})`:"n/a"}`),(he=G==null?void 0:G.completionIdleDebounce)!=null&&he.active){const pe=G.completionIdleDebounce;z.push(`completion_idle_after: age=${pe.ageMs}ms hold=${pe.holdMs}ms force=${pe.forceAfterMs}ms remaining=${Math.max(0,pe.holdMs-pe.ageMs)}ms`)}if(z.push(""),z.push("## Modal"),G!=null&&G.current_modal){const pe=G.current_modal.buttons.map(Ee=>Ee.label).join(" / ");z.push(`${G.current_modal.title??""} [${pe}]`)}else z.push("none");if(z.push(""),z.push("## State History (last 20)"),ie&&!(G!=null&&G.statusHistory&&G.statusHistory.length>0)&&z.push("N/A (native-source provider — no state-machine rules)"),ie&&(G!=null&&G.statusHistory)&&G.statusHistory.length>0){z.push("(legacy engine status transitions — native-source provider has no state-machine rules)");for(const pe of[...G.statusHistory].reverse().slice(0,20))z.push(`- ${pe.status} @ ${new Date(pe.at).toISOString()}${pe.trigger?` | trigger: ${pe.trigger}`:""}`)}const Ne=G!=null&&G.stateHistory?[...G.stateHistory].reverse().slice(0,20):[];for(const pe of Ne){const Ee=pe.reason!=null?typeof pe.reason=="string"?pe.reason:JSON.stringify(pe.reason):"",Y=pe.debounceKind!=null?typeof pe.debounceKind=="string"?pe.debounceKind:JSON.stringify(pe.debounceKind):"",me=pe.matchedStateId!=null?String(pe.matchedStateId):"",fe=(pe.matchedRules??[]).map(E=>typeof E=="string"?E:JSON.stringify(E)).join(", ");z.push(`- ${pe.stateId} @ ${new Date(pe.at).toISOString()} held ${pe.durationMs}ms | reason: ${Ee} | debounce: ${Y} | eval→${me} | rules: ${fe}`)}if(z.push(""),z.push("## Sections"),ie)z.push("N/A (native-source provider — no state-machine sections)");else if(G!=null&&G.sections)for(const[pe,Ee]of Object.entries(G.sections)){const Y=Ee.split(`
|
|
43
|
+
`).slice(0,3).join(`
|
|
44
|
+
`);z.push(`${pe}: ${Y}`)}z.push(""),z.push("## Last Assistant Message");const Le=[...(G==null?void 0:G.messages)??(G==null?void 0:G.committedMessages)??[]].reverse().find(pe=>pe.role==="assistant");z.push(Le?Le.content.slice(0,400):""),z.push(""),z.push("## Screen (first 50 lines)"),z.push(G!=null&&G.screen?G.screen.split(`
|
|
45
|
+
`).slice(0,50).join(`
|
|
46
|
+
`):"");try{await navigator.clipboard.writeText(z.join(`
|
|
47
|
+
`)),f("Copied!"),setTimeout(()=>f("Snapshot"),1500)}catch(pe){console.error("[SpecDebugPanel] clipboard write failed",pe)}},ce=X=>{p(G=>{const z=new Set(G);return z.has(X)?z.delete(X):z.add(X),z})};return n.jsx(es,{children:n.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Spec debug",className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center bg-black/60 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] px-0 sm:items-center sm:p-4",onClick:t,style:{pointerEvents:"auto"},children:n.jsxs("div",{className:"bg-bg-secondary text-text-primary border border-border-default rounded-t-xl sm:rounded-lg shadow-2xl max-w-2xl w-full max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[88vh] flex flex-col",onClick:X=>X.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-border-default px-4 py-2.5 shrink-0 gap-2 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 overflow-hidden",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary shrink-0",children:"Spec Debug"}),V&&n.jsx("span",{className:"text-2xs text-text-secondary font-mono bg-surface-secondary px-1.5 py-0.5 rounded truncate",children:V.spec_id})]}),n.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(V==null?void 0:V.specPath)&&n.jsx("button",{type:"button",className:`text-2xs transition-colors px-2 py-1 rounded border ${x?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-secondary hover:text-text-primary hover:bg-bg-glass-hover border-transparent hover:border-border-default"}`,onClick:()=>{x?b(!1):H()},disabled:r,children:x?"Close Editor":"Edit Spec"}),n.jsx("button",{type:"button",className:"text-2xs text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{we()},disabled:r,children:g}),n.jsx("button",{type:"button",className:"text-2xs text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{D()},disabled:r,children:r?"Loading…":"Refresh"}),n.jsx("button",{type:"button",className:"text-text-secondary hover:text-text-primary transition-colors text-xl leading-none w-7 h-7 flex items-center justify-center rounded hover:bg-bg-glass-hover",onClick:t,"aria-label":"Close",children:"×"})]})]}),x&&n.jsxs("div",{className:"flex-1 flex flex-col min-h-0 px-4 py-3 gap-2",children:[n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[n.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-3xs",children:[n.jsx("button",{type:"button",className:`px-2 py-0.5 ${v?"text-text-secondary hover:bg-bg-glass-hover":"bg-accent-primary/20 text-accent-primary"}`,onClick:()=>{if(v)try{const X=JSON.parse(y);j(X),P(X)}catch{return}_(!1)},disabled:!k&&v,children:"Form"}),n.jsx("button",{type:"button",className:`px-2 py-0.5 ${v?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>{k&&w(JSON.stringify(k,null,2)),_(!0)},children:"JSON"})]}),n.jsx("span",{className:"text-3xs text-text-muted font-mono truncate flex-1",title:V==null?void 0:V.specPath,children:((V==null?void 0:V.specPath)??"").split("/").slice(-3).join("/")}),S&&n.jsx("span",{className:"text-status-warning text-3xs",children:"unsaved"}),!v&&$.length>0&&n.jsxs("span",{className:"text-status-error text-3xs",children:[$.length," error",$.length>1?"s":""]}),n.jsx("button",{type:"button",className:`text-2xs px-2.5 py-1 rounded border transition-colors ${A==="saving"||!v&&$.length>0?"text-text-muted border-border-default cursor-not-allowed":"text-status-online bg-status-online/20 border-status-online/40 hover:bg-status-online/20"}`,onClick:()=>{be()},disabled:A==="saving"||!v&&$.length>0,children:A==="saving"?"Saving…":A==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),L&&n.jsx("pre",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2 text-3xs whitespace-pre-wrap shrink-0 max-h-28 overflow-y-auto",children:L}),!v&&$.length>0&&n.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-1.5 text-3xs shrink-0 max-h-24 overflow-y-auto space-y-0.5",children:$.map((X,G)=>n.jsx("div",{className:"font-mono",children:X},G))}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:v||!k?n.jsx("textarea",{value:y,onChange:X=>{w(X.target.value),C(!0),O("idle")},spellCheck:!1,className:"w-full h-full min-h-[300px] font-mono text-2xs leading-relaxed bg-bg-secondary text-text-primary border border-border-default rounded p-3 resize-none outline-none focus:border-accent"}):n.jsx(z_,{model:k,onChange:W,onPreview:U,preview:I,onTestSections:ae,sectionPreview:T})}),n.jsx("div",{className:"text-3xs text-text-muted shrink-0",children:v?"Raw JSON — validated on save.":'Build the FSM; from/to are constrained to existing states. "test" evaluates a condition against the live screen. Save hot-reloads the session.'})]}),!x&&n.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))] space-y-3 text-xs",children:[c&&n.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2",children:c}),r&&!a&&n.jsx("div",{className:"text-text-muted text-center py-6",children:"Loading…"}),a&&!a.isSpecProvider&&n.jsxs("div",{className:"text-text-muted text-center py-6",children:["Not a spec-driven provider (",a.providerType||"unknown",")."]}),V&&n.jsxs(n.Fragment,{children:[V.nativeSource&&n.jsxs("div",{className:"text-2xs text-text-secondary bg-surface-secondary border border-border-default rounded-md px-3 py-2",children:[n.jsx("span",{className:"text-accent-primary font-semibold",children:"Native-source provider"}),n.jsx("span",{className:"text-text-muted",children:" — no state-machine spec."}),n.jsx("span",{className:"text-text-muted",children:" State History, FSM transitions, and Sections are "}),n.jsx("span",{className:"text-text-secondary font-mono",children:"N/A"}),n.jsx("span",{className:"text-text-muted",children:". Status, screen, modal, and transcript below are live."}),V.transcriptAuthority&&n.jsxs("span",{className:"text-text-muted font-mono",children:[" (transcriptAuthority: ",V.transcriptAuthority,")"]})]}),n.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-2xs bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[V.name&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-text-muted",children:"Provider"}),n.jsxs("span",{className:"font-mono text-text-primary",children:[V.name," ",n.jsxs("span",{className:"text-text-muted",children:["(",V.cliType,")"]})]})]}),V.workingDir&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-text-muted",children:"Dir"}),n.jsx("span",{className:"font-mono text-text-secondary truncate min-w-0",title:V.workingDir,children:V.workingDir})]}),V.spawnedAtMs?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-text-muted",children:"Spawned"}),n.jsx("span",{className:"text-text-secondary",children:ur(V.spawnedAtMs)})]}):null,V.providerSessionId&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-text-muted",children:"Session"}),n.jsx("span",{className:"font-mono text-text-muted text-3xs truncate min-w-0",title:V.providerSessionId,children:V.providerSessionId})]})]}),n.jsxs("div",{className:"flex items-center gap-2 flex-wrap bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[n.jsx("span",{className:`font-semibold font-mono text-xs px-2 py-0.5 rounded ${V.current_state?la(V.current_state.id):"text-text-muted"}`,children:V.current_state?V.current_state.id:"none"}),((ee=V.current_state)==null?void 0:ee.label)&&V.current_state.label!==V.current_state.id&&n.jsx("span",{className:"text-text-secondary text-2xs",children:V.current_state.label}),V.status&&V.status!==((ue=V.current_state)==null?void 0:ue.id)&&n.jsxs("span",{className:"text-text-muted text-2xs",children:["engine: ",n.jsx("span",{className:`font-mono ${la(V.status)} px-1 py-0.5 rounded text-3xs`,children:V.status})]}),V.idleHoldPending&&n.jsx("span",{className:"text-yellow-200 text-3xs bg-yellow-600/25 border border-yellow-500/35 px-1.5 py-0.5 rounded font-mono",children:"idle hold pending"}),V.exited&&n.jsx("span",{className:"text-status-error text-3xs bg-status-error/20 border border-status-error/40 px-1.5 py-0.5 rounded font-mono",children:"exited"}),V.cursorPosition!=null&&n.jsxs("span",{className:"text-text-muted text-2xs font-mono",children:["cursor: ",n.jsxs("span",{className:"text-text-secondary",children:[V.cursorPosition.row,",",V.cursorPosition.col]})]}),V.lastBusyAt>0&&n.jsxs("span",{className:"text-text-muted text-2xs ml-auto",children:["last busy: ",n.jsx("span",{className:"text-text-secondary",children:ur(V.lastBusyAt)})]})]}),((je=V.completionIdleDebounce)==null?void 0:je.active)&&n.jsxs("div",{className:"flex items-center gap-2 text-2xs bg-accent-primary/20 border border-accent rounded-md px-3 py-1.5 font-mono",children:[n.jsx("span",{className:"text-accent-primary",children:"completion_idle_after"}),n.jsxs("span",{className:"text-text-secondary",children:["age: ",n.jsxs("span",{className:"text-accent-primary",children:[V.completionIdleDebounce.ageMs,"ms"]})]}),n.jsx("span",{className:"text-text-muted",children:"/"}),n.jsxs("span",{className:"text-text-secondary",children:["hold: ",n.jsxs("span",{className:"text-text-secondary",children:[V.completionIdleDebounce.holdMs,"ms"]})]}),n.jsxs("span",{className:"text-text-secondary",children:["force: ",n.jsxs("span",{className:"text-text-secondary",children:[V.completionIdleDebounce.forceAfterMs,"ms"]})]}),n.jsx("span",{className:"text-text-muted ml-auto",children:V.completionIdleDebounce.ageMs<V.completionIdleDebounce.holdMs?n.jsxs("span",{className:"text-status-warning",children:["hold remaining: ",V.completionIdleDebounce.holdMs-V.completionIdleDebounce.ageMs,"ms"]}):V.completionIdleDebounce.ageMs<V.completionIdleDebounce.forceAfterMs?n.jsxs("span",{className:"text-orange-300",children:["force in: ",V.completionIdleDebounce.forceAfterMs-V.completionIdleDebounce.ageMs,"ms"]}):n.jsx("span",{className:"text-status-error",children:"overdue"})})]}),V.current_modal&&n.jsxs("div",{className:"bg-orange-900/30 border border-orange-600/40 rounded-md p-2.5",children:[n.jsx("span",{className:"text-orange-200 font-semibold",children:"Modal: "}),n.jsx("span",{className:"text-text-secondary",children:V.current_modal.title||""}),V.current_modal.buttons.length>0&&n.jsxs("span",{className:"text-text-secondary ml-2",children:["[",V.current_modal.buttons.map(X=>X.label).join(" / "),"]"]})]}),V.fsm&&n.jsxs(n.Fragment,{children:[n.jsx(ca,{}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsxs(mr,{children:["FSM — outgoing from ",n.jsx("span",{className:"text-accent-primary font-mono normal-case",children:V.fsm.currentState})," (held ",Fm(V.fsm.stateAgeMs),")"]}),n.jsxs("label",{className:"ml-auto flex items-center gap-1 text-3xs text-text-muted cursor-pointer select-none mb-1.5",children:[n.jsx("input",{type:"checkbox",checked:q,onChange:X=>Q(X.target.checked),className:"accent-[var(--accent-primary)]"}),"live"]})]}),n.jsxs("div",{className:"space-y-1",children:[V.fsm.transitions.length===0&&n.jsx("div",{className:"text-text-muted text-2xs italic px-1",children:"no outgoing transitions (terminal state)"}),V.fsm.transitions.map((X,G)=>n.jsx(Z_,{t:X},G))]})]})]}),n.jsx(ca,{}),V.nativeSource&&n.jsxs("div",{children:[n.jsx(mr,{children:"Sections"}),n.jsx("div",{className:"text-text-muted text-2xs italic px-1",children:"N/A (native-source provider)"})]}),!V.nativeSource&&V.sections&&Object.keys(V.sections).length>0&&n.jsxs("div",{children:[n.jsx(mr,{children:"Sections"}),n.jsx("div",{className:"space-y-1",children:Object.entries(V.sections).map(([X,G])=>{var Be;const z=h.has(X),ie=G.split(`
|
|
48
|
+
`),Ne=((Be=ie[0])==null?void 0:Be.slice(0,80))||"(empty)";return n.jsxs("div",{className:"border border-border-default rounded overflow-hidden bg-surface-secondary",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-bg-glass-hover transition-colors text-left",onClick:()=>ce(X),children:[n.jsx("span",{className:"text-3xs text-text-muted w-3",children:z?"▾":"▸"}),n.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-2xs",children:X}),!z&&n.jsx("span",{className:"text-text-secondary truncate font-mono text-2xs",children:Ne}),n.jsxs("span",{className:"ml-auto text-text-muted text-3xs shrink-0",children:[ie.length,"L"]})]}),z&&n.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-2xs text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary max-h-40 overflow-y-auto border-t border-border-default",children:G||"(empty)"})]},X)})})]}),n.jsx(ca,{}),V.nativeSource&&n.jsxs("div",{children:[n.jsxs(mr,{children:["Status History",V.statusHistory&&V.statusHistory.length>0?` (${V.statusHistory.length})`:""]}),V.statusHistory&&V.statusHistory.length>0?n.jsx("div",{className:"space-y-px",children:[...V.statusHistory].reverse().slice(0,20).map((X,G)=>n.jsx("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:`font-mono text-2xs font-semibold px-1.5 py-0.5 rounded shrink-0 ${la(X.status)}`,children:X.status}),n.jsx("span",{className:"text-text-secondary text-2xs shrink-0 tabular-nums",children:ur(X.at)}),X.trigger&&n.jsx("span",{className:"text-3xs px-1.5 py-0.5 rounded font-mono shrink-0 text-text-secondary bg-bg-glass border border-border-default",children:X.trigger})]})},G))}):n.jsx("div",{className:"text-text-muted text-2xs italic px-1",children:"N/A (native-source provider — no state-machine rules)"})]}),!V.nativeSource&&V.stateHistory&&V.stateHistory.length>0&&n.jsxs("div",{children:[n.jsxs(mr,{children:["State History (",V.stateHistory.length,")"]}),n.jsx("div",{className:"space-y-px",children:[...V.stateHistory].reverse().slice(0,20).map((X,G)=>n.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:`font-mono text-2xs font-semibold px-1.5 py-0.5 rounded shrink-0 ${la(X.stateId)}`,children:X.stateId}),n.jsx("span",{className:"text-text-secondary text-2xs shrink-0 tabular-nums",children:ur(X.at)}),X.durationMs>0&&n.jsxs("span",{className:"text-text-muted text-2xs",children:["held ",n.jsx("span",{className:"text-text-secondary",children:Fm(X.durationMs)})]}),X.reason&&n.jsx("span",{className:`text-3xs px-1.5 py-0.5 rounded font-mono shrink-0 ${J_[String(X.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(X.reason)}),X.debounceKind&&String(X.debounceKind)!=="none"&&n.jsxs("span",{className:"text-text-muted text-3xs font-mono",children:["debounce:",String(X.debounceKind)]}),X.matchedStateId&&String(X.matchedStateId)!==X.stateId&&n.jsxs("span",{className:"text-text-muted text-3xs font-mono",children:["eval→",n.jsx("span",{className:"text-text-secondary",children:String(X.matchedStateId)})]})]}),X.matchedRules&&X.matchedRules.length>0&&n.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-border-default",children:[X.matchedRules.slice(0,3).map((z,ie)=>n.jsx("span",{className:"font-mono text-3xs text-accent-primary bg-accent-primary/20 border border-accent px-1.5 py-0.5 rounded break-all",children:typeof z=="string"?z:JSON.stringify(z)},ie)),X.matchedRules.length>3&&n.jsxs("span",{className:"text-3xs text-text-muted",children:["+",X.matchedRules.length-3," more"]})]})]},G))})]}),n.jsx(ca,{}),(()=>{const X=V.messages??V.committedMessages??[];if(X.length===0)return null;const G=X.filter(Ne=>Ne.role==="user").length,z=X.filter(Ne=>Ne.role==="assistant").length,ie=[...X].reverse().find(Ne=>Ne.role==="assistant");return n.jsxs("div",{children:[n.jsxs(mr,{children:["Transcript (",X.length," — ",G,"u / ",z,"a)"]}),ie&&n.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-md p-2.5 text-2xs",children:[n.jsxs("div",{className:"text-text-muted mb-1 text-3xs",children:["Last assistant ",ie.receivedAt?ur(ie.receivedAt):""]}),n.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[ie.content.slice(0,400),ie.content.length>400?"…":""]})]})]})})(),V.specPath&&n.jsx("div",{className:"text-3xs text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:V.specPath,children:V.specPath}),n.jsxs("div",{children:[n.jsxs("button",{type:"button",className:"text-2xs text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>m(X=>!X),children:[n.jsx("span",{className:"text-text-muted",children:u?"▾":"▸"}),n.jsxs("span",{children:["Raw screen (",V.screen?V.screen.split(`
|
|
49
|
+
`).length:0," lines)"]})]}),u&&n.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-2xs text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:V.screen||"(empty)"})]})]})]})]})})})}function Wg(e,t){if(typeof window>"u")return!1;try{return window[e]===!0||window.localStorage.getItem(t)==="1"}catch{return window[e]===!0}}function t1(){return Wg("__ADHDEV_DEBUG_SPEC__","adhdev_debug_spec")}function n1(){return Wg("__ADHDEV_DEBUG_MOBILE_BUNDLE__","adhdev_debug_mobile_bundle")}function s1({activeConv:e,clearToken:t=0,terminalRef:s,handleSendChat:r,isSendingChat:o=!1,sendFeedbackMessage:a=null,isVisible:i=!0,isInputActive:c=!0}){var Qe;const{t:d}=ve("common");An();const{sendPtyInput:u}=_t(),[m,h]=l.useState(!1),p=l.useRef(!1);p.current=m;const[g,f]=l.useState("Runtime terminal unavailable"),[x,b]=l.useState(!1),[k,j]=l.useState(null),[v,_]=l.useState(!1),[y,w]=l.useState(!1),[S,C]=l.useState(1),[A,O]=l.useState(!1),[L,M]=l.useState(!1),[$,N]=l.useState(!1),[I,B]=l.useState(!1),[T,F]=l.useState(!1),q=t1(),[Q,K]=l.useState({width:0,height:0}),[R,D]=l.useState({width:0,height:0}),[P,H]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[W,U]=l.useState(null),ae=l.useRef(null),be=l.useRef(null),V=l.useRef(!1),we=l.useRef(!1),ce=l.useRef(i),de=l.useRef(0),ne=l.useRef(!1),ee=l.useRef(""),ue=l.useRef(null),je=l.useRef(!1),X=l.useRef(!1),G=l.useRef(null),z=l.useRef(null),ie=l.useRef(null),Ne=32*1024,Be=()=>{var ge,_e,Pe,nt;return((_e=(ge=ae.current)==null?void 0:ge.ownerDocument)==null?void 0:_e.defaultView)||((nt=(Pe=be.current)==null?void 0:Pe.ownerDocument)==null?void 0:nt.defaultView)||window},Le=ge=>{const _e=Be();return{ownerWindow:_e,frameId:_e.requestAnimationFrame(ge)}},Je=()=>{const ge=G.current;if(ge){try{ge.ownerWindow.cancelAnimationFrame(ge.frameId)}catch{}G.current=null}},Se=()=>{const ge=z.current;if(ge){try{ge.ownerWindow.clearTimeout(ge.timeoutId)}catch{}z.current=null}},he=()=>{const ge=ie.current;if(ge){try{ge.ownerWindow.clearTimeout(ge.timeoutId)}catch{}ie.current=null}},pe=()=>{i&&G.current===null&&(G.current=Le(()=>{re()}))},Ee=e.tabKey,Y=e.sessionId||"",me=e.daemonId||((Qe=e.routeId)==null?void 0:Qe.split(":")[0])||e.routeId||"",fe=Pi(e),E=m?cg(e)||a:g,oe=m&&a||null,Ie=__,Z=A_,se=.05,ye=()=>{const ge=R.width,_e=R.height;if(!Number.isFinite(Q.width)||Q.width<=0||!Number.isFinite(Q.height)||Q.height<=0||!Number.isFinite(ge)||ge<=0||!Number.isFinite(_e)||_e<=0)return 1;const Pe=Q.width/ge,nt=Q.height/_e;return Number(Math.min(Z,Math.max(Ie,Math.min(Pe,nt))).toFixed(2))},$e=ye(),Me=V.current&&S>$e,De=Number.isFinite(R.width)&&R.width>0?Math.max(Q.width,Math.round(R.width*S)):Q.width,Te=Number.isFinite(R.height)&&R.height>0?Math.max(Q.height,Math.round(R.height*S)):Q.height,He=()=>{Le(()=>{const ge=be.current;ge&&(ge.scrollLeft=0,ge.scrollTop=ge.scrollHeight-ge.clientHeight)})},tt=()=>{var ge,_e;de.current=0,ne.current=!1,ee.current="",ue.current=null,je.current=!1,X.current=!1,V.current||(we.current=!1,C(1)),G.current!==null&&Je(),h(!1),f("Runtime terminal unavailable"),he(),Se(),j(null),U(null),O(!1),b(!1),_(!1),w(!1),(_e=(ge=s.current)==null?void 0:ge.reset)==null||_e.call(ge)},Ct=()=>{var ge,_e;de.current=0,ne.current=!1,ee.current="",ue.current=null,je.current=!1,X.current=!1,G.current!==null&&Je(),h(!0),f(""),he(),Se(),j(null),U(null),O(!1),b(!1),_(!1),w(!1),(_e=(ge=s.current)==null?void 0:ge.reset)==null||_e.call(ge)},J=()=>{X.current&&(X.current=!1,Le(()=>{var ge,_e;(_e=(ge=s.current)==null?void 0:ge.scrollToTop)==null||_e.call(ge)}))},re=()=>{if(G.current=null,!i)return;const ge=ee.current;if(!ge)return;const _e=ge.slice(0,Ne);ee.current=ge.slice(_e.length);const Pe=s.current;if(!Pe){ee.current=_e+ee.current,pe();return}Pe.write(_e,()=>{if(ee.current.length>0){pe();return}J()})},le=ge=>{ge&&(ee.current+=ge,pe())},xe=(ge,_e=0,Pe,nt,ze={})=>{var Ge,bt,Mt,Pt;const ut=!!ze.force;!ut&&_e>0&&de.current>=_e||!ut&&_e===0&&ne.current||(de.current=_e,_e>0&&_(!0),h(!0),f(""),typeof Pe=="number"&&typeof nt=="number"&&Pe>0&&nt>0&&((bt=(Ge=s.current)==null?void 0:Ge.resize)==null||bt.call(Ge,Pe,nt)),ee.current="",(Pt=(Mt=s.current)==null?void 0:Mt.reset)==null||Pt.call(Mt),ge?le(ge):J())};l.useEffect(()=>{tt()},[Y]),l.useEffect(()=>{var _e;if(!Y)return;const ge=((_e=Et.onRuntimeEvent)==null?void 0:_e.call(Et,Y,Pe=>{if(!(!Pe||Pe.sessionId!==Y)){if(Pe.type==="runtime_snapshot"){if(!i){ue.current={text:Pe.text||"",seq:Pe.seq||0,cols:Pe.cols,rows:Pe.rows,force:!!Pe.force};return}xe(Pe.text||"",Pe.seq||0,Pe.cols,Pe.rows,{force:!!Pe.force});return}if(Pe.type==="session_output"){ne.current=!0,typeof Pe.seq=="number"&&(de.current=Math.max(de.current,Pe.seq),Pe.seq>0&&_(!0)),p.current||h(!0),p.current||f(""),typeof Pe.data=="string"&&le(Pe.data);return}if(Pe.type==="session_cleared"){if(!i){je.current=!0,ee.current="",ue.current=null;return}Ct();return}if(Pe.type==="session_io_error"){const nt=typeof Pe.error=="string"&&Pe.error?Pe.error:typeof Pe.reason=="string"&&Pe.reason?Pe.reason:"unknown error";h(!1),f(`Runtime input failed: ${nt}`);return}}},me))||(()=>{});return()=>{ge()}},[me,Y,s,i]);const Ce=async(ge={})=>{var _e;if(!me||!Y)return{success:!1,error:"daemonId and sessionId are required"};ge.preserveStatus||f(ge.loadingMessage||"Loading runtime terminal...");try{const Pe=await((_e=Et.requestRuntimeSnapshot)==null?void 0:_e.call(Et,me,Y,{sinceSeq:ge.sinceSeq,force:ge.force}));return Pe&&Pe.success===!1?(ge.preserveStatus||(h(!1),f(`Runtime terminal unavailable: ${Pe.error}`)),Pe):Pe||{success:!0}}catch(Pe){const nt=(Pe==null?void 0:Pe.message)||String(Pe);return ge.preserveStatus||(h(!1),f(`Runtime terminal unavailable: ${nt}`)),{success:!1,error:nt}}},Re=async ge=>{var ut,Ge;const _e=((ut=ae.current)==null?void 0:ut.ownerDocument)||document,Pe=_e.defaultView||window,nt=(Ge=Pe.navigator)==null?void 0:Ge.clipboard;if(nt!=null&&nt.writeText&&Pe.isSecureContext)try{return await nt.writeText(ge),!0}catch{}let ze=null;try{return ze=_e.createElement("textarea"),ze.value=ge,ze.setAttribute("readonly","true"),ze.style.position="fixed",ze.style.left="-9999px",ze.style.top="0",_e.body.appendChild(ze),ze.focus(),ze.select(),_e.execCommand("copy")}catch{return!1}finally{ze==null||ze.remove()}},Ue=ge=>{Se(),U(ge);const _e=Be();z.current={ownerWindow:_e,timeoutId:_e.setTimeout(()=>{z.current=null,U(Pe=>Pe===ge?null:Pe)},2200)}},Fe=ge=>{he(),j(ge);const _e=Be();ie.current={ownerWindow:_e,timeoutId:_e.setTimeout(()=>{ie.current=null,j(Pe=>Pe===ge?null:Pe)},2200)}},ke=async()=>{var ze,ut,Ge,bt;const ge=((ut=(ze=s.current)==null?void 0:ze.getSelection)==null?void 0:ut.call(ze))||"",_e=((bt=(Ge=s.current)==null?void 0:Ge.getVisibleText)==null?void 0:bt.call(Ge))||"",Pe=ge.trimEnd()||_e.trimEnd();if(!Pe){Ue("Nothing to copy");return}if(!await Re(Pe)){Ue("Copy failed");return}Ue(ge.trimEnd()?"Copied selection":"Copied visible terminal")},Ze=ge=>{if(!m||!i)return;((u==null?void 0:u(me,Y,ge))??!1)||Ue("Terminal input failed")},et=ge=>{Ze(I_({ctrl:L,alt:$,shift:I},ge)),M(!1),N(!1),B(!1)},Ve=async()=>{if(x)return;b(!0),j("Loading older terminal output..."),X.current=!0;const ge=await Ce({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(b(!1),(ge==null?void 0:ge.success)===!1){X.current=!1,j(`Older terminal output unavailable: ${ge.error}`);return}w(!0),Fe("Older terminal output loaded"),Le(()=>{var _e;(_e=s.current)==null||_e.bumpResize()})};l.useEffect(()=>{var _e,Pe;if(!Y)return;me&&((_e=Et.getState)==null?void 0:_e.call(Et,me))==="connected"&&Ce();const ge=(Pe=Et.onStateChange)==null?void 0:Pe.call(Et,(nt,ze)=>{nt!==me||ze!=="connected"||Ce()});return()=>{ge==null||ge()}},[me,Y,s]),l.useEffect(()=>{t&&tt()},[t,Ee,s]),l.useEffect(()=>{var nt,ze;const ge=ae.current,_e=(ze=(nt=ge==null?void 0:ge.ownerDocument)==null?void 0:nt.defaultView)==null?void 0:ze.ResizeObserver;if(!ge||!_e)return;const Pe=new _e(ut=>{const Ge=ut[0];if(!Ge)return;const{width:bt,height:Mt}=Ge.contentRect;K(Pt=>{const mn=Math.round(bt),nn=Math.round(Mt);return Pt.width===mn&&Pt.height===nn?Pt:{width:mn,height:nn}})});return Pe.observe(ge),()=>Pe.disconnect()},[]),l.useEffect(()=>{if(V.current)return;const ge=ye();!Number.isFinite(ge)||ge<=0||C(_e=>we.current?ge<_e-se?ge:_e:(we.current=!0,ge))},[R.height,R.width,Q.height,Q.width]),l.useEffect(()=>{Me&&He()},[Me,Te,De]),l.useEffect(()=>{var Pe;const ge=ce.current;if(ce.current=i,!i)return;ge||w(!1),je.current&&(je.current=!1,Ct());const _e=ue.current;_e&&(ue.current=null,xe(_e.text,_e.seq,_e.cols,_e.rows,{force:!!_e.force})),me&&Y&&((Pe=Et.getState)==null?void 0:Pe.call(Et,me))==="connected"&&Ce(),ee.current&&G.current===null&&pe(),Le(()=>{var nt;(nt=s.current)==null||nt.bumpResize()})},[me,i,Y]),l.useEffect(()=>()=>{G.current!==null&&Je(),Se(),he()},[]),l.useEffect(()=>{const ge=nt=>{var ut;const ze=nt.detail;ze!=null&&ze.sessionId&&ze.sessionId!==Y||m&&((ut=s.current)==null||ut.bumpResize())},_e=Be(),Pe=_e===window?[window]:[window,_e];for(const nt of Pe)nt.addEventListener("adhdev:fit-cli-terminal",ge);return()=>{for(const nt of Pe)nt.removeEventListener("adhdev:fit-cli-terminal",ge)}},[m,Y,s]);const lt=m&&v&&!y&&(P.atTop||!P.canScroll)||x||!!k;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{ref:ae,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[lt&&n.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[n.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-2xs font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ve()},disabled:!Y||x,title:d("terminal.replayScrollbackHint"),children:d(x?"terminal.loadingOlder":"terminal.loadOlderOutput")}),k&&n.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-3xs text-white/70 backdrop-blur-sm",children:k})]}),n.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[W&&n.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-3xs text-white/70 backdrop-blur-sm",children:W}),q&&n.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-2xs font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>F(ge=>!ge),title:d("terminal.specDebugHint"),children:d("terminal.debug")}),n.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-2xs font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{ke()},disabled:!m,title:d("terminal.copyHint"),children:d("terminal.copy")}),n.jsxs("div",{className:"relative",children:[n.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-2xs font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>O(ge=>!ge),disabled:!m,"aria-label":d(A?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":A,"aria-controls":"terminal-control-keys-popover",title:d("terminal.openControlKeys"),children:d("terminal.keysButton")}),A&&n.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":d("terminal.openControlKeys"),className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-3xs font-semibold uppercase tracking-[0.14em] text-white/45",children:d("terminal.keysPanelTitle")}),n.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-2xs text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>O(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),n.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",L,M],["Alt",$,N],["Shift",I,B]].map(([ge,_e,Pe])=>n.jsx("button",{type:"button","aria-pressed":_e,className:`h-9 rounded-lg border text-xs font-semibold transition-colors ${_e?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>Pe(nt=>!nt),children:ge},ge))}),n.jsx("div",{className:"my-2 h-px bg-white/10"}),n.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>et("Escape"),children:"Esc"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>et("Tab"),children:"Tab"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>et("Enter"),children:"Enter"}),n.jsx("span",{"aria-hidden":"true"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] leading-[22px] font-semibold hover:bg-white/[0.12]",onClick:()=>et("ArrowUp"),"aria-label":d("terminal.arrowUp"),children:"↑"}),n.jsx("span",{"aria-hidden":"true"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] leading-[22px] font-semibold hover:bg-white/[0.12]",onClick:()=>et("ArrowLeft"),"aria-label":d("terminal.arrowLeft"),children:"←"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] leading-[22px] font-semibold hover:bg-white/[0.12]",onClick:()=>et("ArrowDown"),"aria-label":d("terminal.arrowDown"),children:"↓"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] leading-[22px] font-semibold hover:bg-white/[0.12]",onClick:()=>et("ArrowRight"),"aria-label":d("terminal.arrowRight"),children:"→"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>Ze(""),title:d("terminal.sendInterrupt"),children:"Ctrl-C"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>et("Space"),children:"Space"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>et("Backspace"),children:"Bksp"})]})]})]}),n.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{V.current=!0,C(ge=>{const _e=Math.max($e,Number((ge-.1).toFixed(2)));return _e>$e&&He(),_e})},title:d("terminal.shrinkViewport"),children:"-"}),n.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{V.current=!0,C(ge=>{const _e=Math.min(Z,Number((ge+.1).toFixed(2)));return _e>$e&&He(),_e})},title:d("terminal.growViewport"),children:"+"})]}),n.jsx("div",{ref:be,className:Me?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:n.jsx("div",{style:{width:De>0?`${De}px`:"100%",height:Te>0?`${Te}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:n.jsx("div",{style:{width:R.width>0?`${R.width}px`:"100%",height:R.height>0?`${R.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:S},children:n.jsx(ff,{ref:s,readOnly:!m||!i,sizingMode:"measured",onViewportMetrics:D,onScrollMetrics:H,onInput:ge=>{!m||(u==null||u(me,Y,ge))}})})})}),!m&&n.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-2xs text-red-300 pointer-events-none",children:g})]}),n.jsx(Gf,{contextKey:e.tabKey,panelLabel:Rt(e),isSending:o,isBusy:!!fe,statusMessage:E,inlineStatusMessage:oe,onSend:async ge=>fe?!1:r(ge),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),T&&n.jsx(e1,{activeConv:e,onClose:()=>F(!1)})]})}const r1=5e3,o1=12e3,a1=15e3;function i1(e){return e==="disconnected"||e==="reconnecting"}function l1({wsStatus:e,showReconnected:t,loginUrl:s,onReconnect:r,reconnectDelayMs:o=r1,reconnectActionDelayMs:a=o1}){const{t:i}=ve(),c=i1(e),[d,u]=l.useState(()=>!c||o<=0),[m,h]=l.useState(()=>!c||a<=0),p=l.useRef(!1),[g,f]=l.useState(!1);l.useEffect(()=>{if(!c){u(!1);return}if(p.current=!1,o<=0){p.current=!0,u(!0);return}u(!1);const A=setTimeout(()=>{p.current=!0,u(!0)},o);return()=>clearTimeout(A)},[o,c]),l.useEffect(()=>{if(!c){h(!1);return}if(a<=0){h(!0);return}h(!1);const A=setTimeout(()=>{h(!0)},a);return()=>clearTimeout(A)},[a,c]),l.useEffect(()=>{e!=="reconnecting"&&f(!1)},[e]),l.useEffect(()=>{if(!g)return;const A=setTimeout(()=>f(!1),a1);return()=>clearTimeout(A)},[g]);const x=()=>{f(!0),r==null||r()},b=c?d:e==="offline"||e==="auth_failed",k=!!(r&&e!=="auth_failed"&&(!c||m)),j=l.useMemo(()=>!t||e!=="connected"?!1:o<=0||p.current,[o,t,e]),v=e==="auth_failed"?"red":e==="offline"?"orange":"accent",_={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},y={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},w={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},S="fixed left-1/2 top-[calc(env(safe-area-inset-top,0px)+64px)] sm:top-[calc(env(safe-area-inset-top,0px)+16px)] z-[var(--z-toast)] flex items-center justify-center pointer-events-none",C={transform:"translateX(-50%)"};return n.jsxs(n.Fragment,{children:[b&&n.jsx("div",{className:S,style:C,children:n.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-xxs font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:_[v],border:y[v],color:w[v]},children:[n.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),n.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(s?n.jsxs(n.Fragment,{children:[i("connection.sessionExpired")," ",n.jsx("a",{href:s,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),k&&n.jsxs("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-xs font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center gap-1.5",onClick:x,disabled:e==="offline"||g,children:[g&&n.jsx(ln,{size:11,thickness:2,color:"muted"}),i(g?"connection.reconnecting":"connection.reconnectNow")]})]})}),j&&n.jsx("div",{className:S,style:C,children:n.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[n.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),i("connection.connected")]})})]})}function Ug({mode:e,onChange:t,compact:s=!1}){const{t:r}=ve("common"),o=s?14:15;return n.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:r(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?n.jsx(pd,{size:o}):n.jsx(Jn,{size:o})})}function c1(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function d1(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function u1(e){switch(e){case"conflict":return"border-status-error/40 bg-status-error/10 text-status-error";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-status-online/40 bg-status-online/10 text-status-online"}}function Dd({git:e,className:t="",compact:s=!1}){const r=c1(e),o=d1(e);if(!r||!o)return null;const a=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return n.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${u1(o)} ${t}`.trim(),title:a.join(" · ")||r,"data-git-tone":o,children:[n.jsx("span",{"aria-hidden":"true",children:"⑂"}),n.jsx("span",{className:"truncate",children:r})]})}function Kg({value:e,live:t=!0,fallback:s="",className:r}){const{i18n:o}=ve("common"),[,a]=l.useState(0),i=Lo(e);if(l.useEffect(()=>{if(!t||i===null||typeof window>"u")return;const d=window.setInterval(()=>a(u=>u+1),3e4);return()=>window.clearInterval(d)},[t,i]),i===null)return s?n.jsx("span",{className:r,children:s}):null;const c=(o==null?void 0:o.resolvedLanguage)||(o==null?void 0:o.language);return n.jsx(tn,{content:Do(i,{locale:c,seconds:!0}),children:n.jsx("time",{dateTime:new Date(i).toISOString(),className:r,children:Ka(i,{locale:c})})})}async function qg(e){var t;try{if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText))return await navigator.clipboard.writeText(e),!0}catch{}try{if(typeof document>"u")return!1;const s=document.createElement("textarea");s.value=e,s.setAttribute("readonly",""),s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s),s.select();const r=document.execCommand("copy");return document.body.removeChild(s),r}catch{return!1}}function zg({value:e,label:t,className:s}){const{t:r}=ve("common"),[o,a]=l.useState(!1),i=l.useRef(null);return l.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),n.jsx("button",{type:"button",onClick:async c=>{c.stopPropagation(),await qg(e)&&(a(!0),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500))},title:e,"aria-label":`${t??r("common.copyId")}: ${e}`,className:ft("inline-flex shrink-0 items-center rounded-md border border-border-subtle bg-transparent px-1.5 py-0.5 text-3xs font-medium text-text-muted transition-colors hover:border-border-default hover:text-text-primary",s),children:n.jsx("span",{"aria-live":"polite",children:o?r("common.copied"):t??r("common.copyId")})})}function Od({rows:e=[],children:t,summary:s,className:r,summaryClassName:o}){const{t:a}=ve("common"),i=e.filter(c=>typeof c.value=="string"&&c.value);return i.length===0&&!t?null:n.jsxs("details",{className:ft("group text-xs",r),"data-technical-details":"",children:[n.jsxs("summary",{className:ft("cursor-pointer select-none list-none text-3xs font-medium uppercase tracking-wide text-text-muted [&::-webkit-details-marker]:hidden",o),children:[n.jsx("span",{className:"mr-1 inline-block transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),s??a("common.technicalDetails")]}),n.jsxs("div",{className:"mt-2 flex flex-col gap-1.5",children:[i.map(c=>n.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[n.jsx("span",{className:"shrink-0 text-3xs text-text-muted",children:c.label}),n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx("span",{className:"min-w-0 truncate font-mono text-3xs text-text-secondary",title:c.value,children:c.value}),c.copyable!==!1&&n.jsx(zg,{value:c.value})]})]},c.label)),t]})]})}function Gg(e){const t=e.replace(/[\\/]+$/,""),s=t.split(/[\\/]/);return s[s.length-1]||t||e}const m1=l.createContext(null);function $d(){return l.useContext(m1)}function h1(e){const t=e.replace(/^(daemon_|standalone_)/,"");return t.length<=20?t:`${t.slice(0,17)}…`}function p1(e){return uy(e)}function f1(e){const t=Array.isArray(e==null?void 0:e.submodules)?e.submodules:[];let s=!1,r=!1;for(const o of t)o!=null&&o.outOfSync&&(r=!0),o!=null&&o.dirty&&(s=!0);return{dirty:s,outOfSync:r}}function g1(e){return e?(e.staged??0)>0||(e.modified??0)>0||(e.untracked??0)>0||(e.deleted??0)>0||(e.renamed??0)>0||e.hasConflicts===!0:!1}function Xa(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=f1(e);return t.outOfSync?"degraded":t.dirty||g1(e)?"dirty":"online"}function b1(e,t){const s=t?Xa(t):void 0;return!e||e==="unknown"?s:e}function x1(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:Array.isArray(e.sessions)?e.sessions:null;if(t){const a=t.map(Ua).filter(i=>i!==null);if(a.length>0)return a}const s=gt(e.activeSession??e.active_session),r={...s,sessionId:Ae(s.sessionId,s.id,s.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id)},o=Ua(r);return o?[o]:void 0}function y1(e){const t=gt(e.connection);return Object.keys(t).length>0?t:void 0}function v1(e){const t=e==null?void 0:e.source,s=e==null?void 0:e.transport;return{...e,perspective:(e==null?void 0:e.perspective)??"selected_coordinator",source:t&&t!=="not_reported"?t:"mesh_peer_status",state:"connected",transport:s&&s!=="unknown"?s:"direct",reported:!0,reason:"Live peer git snapshot reported by the selected coordinator."}}function Vg(e){var s;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((s=t.submodules)==null?void 0:s.length)??0)>0))}function Hm(e){var r,o,a,i,c,d;let t=0;const s=e.git;return Vg(e)&&(t+=80,(s==null?void 0:s.isGitRepo)===!0&&(t+=20),(s==null?void 0:s.isGitRepo)===!1&&(t+=5),s!=null&&s.branch&&(t+=20),s!=null&&s.upstream&&(t+=12),s!=null&&s.headCommit&&(t+=12),t+=od(s==null?void 0:s.upstreamStatus),typeof(s==null?void 0:s.lastCheckedAt)=="number"&&(t+=6),t+=(((r=s==null?void 0:s.submodules)==null?void 0:r.length)??0)*6),(o=e.branchConvergence)!=null&&o.status&&(t+=12),(((a=e.connection)==null?void 0:a.state)==="connected"||((i=e.connection)==null?void 0:i.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((d=e.connection)==null?void 0:d.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function w1(e,t){var f,x,b,k;const s=Hm(e),o=Hm(t)>s?t:e,a=o===t?e:t,i=o.git??a.git,c=(((f=o.providers)==null?void 0:f.length)??0)>0?o.providers:a.providers,d=(((x=o.activeSessions)==null?void 0:x.length)??0)>0?o.activeSessions:a.activeSessions,u=(((b=o.activeSessionDetails)==null?void 0:b.length)??0)>0?o.activeSessionDetails:a.activeSessionDetails,m=(((k=o.providerPriority)==null?void 0:k.length)??0)>0?o.providerPriority:a.providerPriority,h=o.connection??a.connection,p={...a,...o,machineLabel:o.machineLabel||a.machineLabel,workspace:o.workspace||a.workspace,...o.repoRoot||a.repoRoot?{repoRoot:o.repoRoot||a.repoRoot}:{},...o.daemonId||a.daemonId?{daemonId:o.daemonId||a.daemonId}:{},...o.machineId||a.machineId?{machineId:o.machineId||a.machineId}:{},...o.machineStatus||a.machineStatus?{machineStatus:o.machineStatus||a.machineStatus}:{},health:i&&(!o.health||o.health==="unknown")?Xa(i):o.health,providers:c??[],activeSessions:d??[],...u&&u.length>0?{activeSessionDetails:u}:{},...m&&m.length>0?{providerPriority:m}:{},...h?{connection:h}:{},...i?{git:i}:{}},g=gt(o.branchConvergence);return Object.keys(g).length>0?Object.assign(p,{branchConvergence:g}):delete p.branchConvergence,i&&(delete p.gitProbePending,delete p.error),p}const S1=new Set(["self","local","member_push","coordinator_probe","none"]);function Ic(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Bm(e){const t=gt(e),s=Ae(t.source);if(!s||!S1.has(s))return null;const r=Ae(t.lastRefreshError);return{source:s,observedAt:Ic(t.observedAt),refreshing:t.refreshing===!0,unreachableSince:Ic(t.unreachableSince),...r?{lastRefreshError:r}:{}}}function Yg(e){const t=gt(e),s=Ae(t.nodeId,t.id);if(!s)return null;const r=gt(t.cachedStatus),o=p1(t),a=o?void 0:Ca(gt(t.git),t)??Ca(t,t),i=o??a,c=i?void 0:Ca(gt(r.git),t),d=i??c,u=Ae(t.machineStatus,t.machine_status,r.machineStatus,r.machine_status),m=Ae(t.health),h=o?Xa(d):b1(m,i)||(d?Xa(d):void 0)||Ae(r.health)||u||Ae(t.status)||"unknown",g=(o?void 0:Ae(t.error))??(i?void 0:Ae(r.error)),f=x1(t),x=nl(t.activeSessions),b=(f==null?void 0:f.map(C=>C.sessionId))??[],k=nl(t.providerPriority),j=Qt(t.gitProbePending,t.git_probe_pending),v=i?void 0:j,_=y1(t),y=gt(t.branchConvergence??t.branch_convergence),w=_==null?void 0:_.state,S=o&&(!(_!=null&&_.reported)||w==="unknown")?v1(_):_;return{nodeId:s,machineLabel:Ae(t.machineLabel,t.machine_label,t.hostname)||h1(Ae(t.daemonId,t.daemon_id,t.machineId,t.machine_id,s)||s),workspace:Ae(t.workspace,d==null?void 0:d.workspace)||"",...Ae(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Ae(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Ae(t.daemonId,t.daemon_id)?{daemonId:Ae(t.daemonId,t.daemon_id)}:{},...Ae(t.machineId,t.machine_id)?{machineId:Ae(t.machineId,t.machine_id)}:{},...u?{machineStatus:u}:{},...Qt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Qt(t.isLocalWorktree,t.is_local_worktree)}:{},...Ae(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Ae(t.worktreeBranch,t.worktree_branch)}:{},...Ae(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:Ae(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:h,...d?{git:d}:{},...v!==void 0?{gitProbePending:v}:{},providers:nl(t.providers),activeSessions:x.length>0?x:b,...f&&f.length>0?{activeSessionDetails:f}:{},...k.length>0?{providerPriority:k}:{},...Qt(t.launchReady)!==void 0?{launchReady:Qt(t.launchReady)}:o?{launchReady:!0}:{},...Ae(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)?{lastSeenAt:Ae(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)}:{},...Ae(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)?{updatedAt:Ae(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)}:{},...S?{connection:S}:{},...Object.keys(y).length>0?{branchConvergence:y}:{},...t.scheduling&&typeof t.scheduling=="object"?{scheduling:t.scheduling}:{},...Qt(t.autoFastForwardEligible,t.auto_fast_forward_eligible)===!0?{autoFastForwardEligible:!0}:{},...t.worktreeBootstrap&&typeof t.worktreeBootstrap=="object"?{worktreeBootstrap:t.worktreeBootstrap}:{},...t.staleDaemonBuild&&typeof t.staleDaemonBuild=="object"?{staleDaemonBuild:t.staleDaemonBuild}:{},...t.providerVersions&&typeof t.providerVersions=="object"&&!Array.isArray(t.providerVersions)?{providerVersions:t.providerVersions}:{},...Ae(t.daemonBuildVersion,t.daemon_build_version)?{daemonBuildVersion:Ae(t.daemonBuildVersion,t.daemon_build_version)}:{},...t.nodeFacts&&typeof t.nodeFacts=="object"&&!Array.isArray(t.nodeFacts)?{nodeFacts:t.nodeFacts}:{},...Bm(t.gitObservation)?{gitObservation:Bm(t.gitObservation)}:{},...Wm(t.heldRuntime??t.held_runtime)?{heldRuntime:Wm(t.heldRuntime??t.held_runtime)}:{},...Ae(t.role)?{role:Ae(t.role)}:{},...Ae(t.nodeLabel,t.node_label)?{nodeLabel:Ae(t.nodeLabel,t.node_label)}:{},...g?{error:g}:{}}}const k1=new Set(["member_push","coordinator_probe","none"]);function Wm(e){const t=gt(e);if(Object.keys(t).length===0)return null;const s=Ae(t.source)||"none";if(!k1.has(s))return null;const r=Array.isArray(t.sessions)?t.sessions.filter(o=>Object.keys(gt(o)).length>0):[];return{...t,source:s,observedAt:Ic(t.observedAt),refreshing:t.refreshing===!0,sessions:r}}function j1(e,t,s){const r=gt(e),o=gt(r.settings),a=gt(r.activeChat),i=Ae(gt(r.coordinator).meshId,o.meshCoordinatorFor),c=t&&i===t?"coordinator":t&&Ae(o.meshNodeFor)===t?"worker":void 0,d=Ua({sessionId:Ae(r.instanceId,r.id,r.sessionId),providerType:Ae(r.providerType),state:Ae(r.status),chatStatus:Ae(a.status),...c?{role:c}:{},...s?{workspace:s}:{}});return d?{...d,isSelfCoordinator:!1}:null}function N1(e,t,s,r){const o=gt(e),a=gt(o.settings),i=Ae(a.meshNodeId);return i?i===s.nodeId:!r||!t?!1:Ae(gt(o.coordinator).meshId,a.meshCoordinatorFor)===t||Ae(a.meshNodeFor)===t}function Qg(e,t){const s=new Map;for(const r of t)!r.heldRuntime||!r.daemonId||s.set(r.daemonId,(s.get(r.daemonId)??0)+1);return t.map(r=>{const o=r.heldRuntime;if(!o||o.source==="none"||!Array.isArray(o.sessions)||o.sessions.length===0)return r;const a=!!r.daemonId&&s.get(r.daemonId)===1,i=o.sessions.filter(d=>N1(d,e,r,a)).map(d=>j1(d,e,r.workspace||void 0)).filter(d=>d!==null);if(i.length===0)return r;const c=Za([...r.activeSessionDetails??[],...i]);return{...r,activeSessionDetails:c,activeSessions:Za([...c,...(r.activeSessions??[]).map(d=>({sessionId:d}))]).map(d=>d.sessionId)}})}function Za(e){const t=new Map;for(const s of e){const r=t.get(s.sessionId);t.set(s.sessionId,r?{...r,...s}:s)}return[...t.values()]}function Jg(e,t){const s=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],r=s.map(Ua).filter(o=>o!==null);return r.length===0?t:t.map(o=>{const a=r.filter(c=>{const d=gt(s.find(p=>{const g=gt(p);return Ae(g.sessionId,g.session_id,g.id)===c.sessionId})),u=Ae(d.nodeId,d.node_id),m=Ae(d.daemonId,d.daemon_id),h=Ae(d.workspace);return u&&u===o.nodeId?!0:on(m,o.daemonId)?!h||!o.workspace||h===o.workspace:!!(h&&o.workspace&&h===o.workspace)});if(a.length===0)return o;const i=Za([...o.activeSessionDetails??[],...a]);return{...o,activeSessionDetails:i,activeSessions:Za([...o.activeSessionDetails??[],...a,...(o.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function C1(e){const t=gt(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||Ae(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||Qt(t.is_local_worktree)!==void 0}function Xg(e){const t=new Map,s=[];for(const r of e){const o=C1(r)?Yg(r)??r:r;if(!(o!=null&&o.nodeId))continue;const a=t.get(o.nodeId);if(!a){t.set(o.nodeId,o),s.push(o);continue}const i=w1(a,o);t.set(o.nodeId,i);const c=s.findIndex(d=>d.nodeId===o.nodeId);c>=0&&(s[c]=i)}return s}function U5(e){const t=e??{},s=Xg(t.nodes??[]);return{...t,nodes:Qg(Ae(t.meshId)||"",Jg(t,s))}}function K5(e){var s;const t=e==null?void 0:e.git;return{nodeId:(e==null?void 0:e.nodeId)??null,chosenSource:t?"live_git":e!=null&&e.gitProbePending?"pending_git":"no_git",hasLiveGit:Vg(e??{git:void 0}),branch:(t==null?void 0:t.branch)??null,upstream:(t==null?void 0:t.upstream)??null,headCommit:(t==null?void 0:t.headCommit)??null,submoduleCount:((s=t==null?void 0:t.submodules)==null?void 0:s.length)??0,pendingGit:(e==null?void 0:e.gitProbePending)===!0,connection:e!=null&&e.connection?{state:e.connection.state,transport:e.connection.transport,source:e.connection.source}:null}}function _1(e){const t=Ae(e.meshId,e.mesh_id,e.id),s=e.nodes,r=Array.isArray(s)?s.map(d=>Yg(d)).filter(d=>d!==null):null;if(!t||!r)return null;const o=Qg(t,Jg(e,Xg(r))),a=Ae(e.meshName,e.mesh_name,e.name),i=Ae(e.repoIdentity,e.repo_identity),c=Ae(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!a||!i||!c?null:{...e,meshId:t,meshName:a,repoIdentity:i,refreshedAt:c,nodes:o}}function A1(e){var a;let t=0;const s=gt(e.sourceOfTruth),r=gt(s.directPeerTruth);Ae(s.currentStatus)==="live_git_and_session_probes"&&(t+=100),s.coordinatorOwnsLiveTruth===!0&&(t+=25),r.satisfied===!0&&(t+=15);for(const i of e.nodes){const c=i.git;if(!c){i.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=od(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((a=c.submodules)==null?void 0:a.length)??0)*2}return t}function T1(e){const t=e.refreshedAt;if(typeof t!="string"||t.length===0)return 0;const s=Date.parse(t);return Number.isFinite(s)?s:0}const I1=20;function Um(e){let t=null;for(const s of e){const r=_1(gt(s));if(!r)continue;const o=A1(r),a=T1(r);if(!t){t={status:r,score:o,refreshedAt:a};continue}(Math.abs(o-t.score)<=I1?a>t.refreshedAt||a===t.refreshedAt&&o>t.score:o>t.score)&&(t={status:r,score:o,refreshedAt:a})}return(t==null?void 0:t.status)??null}function Fd(e){const s=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,r=Um([s==null?void 0:s.status,s]);return r||Um([e==null?void 0:e.status,e])}function M1(e){var c;const t=typeof e.heldCoordinatorDaemonId=="string"?e.heldCoordinatorDaemonId.trim():"";if(t)return t;const s=e.conv,r=(s==null?void 0:s.settings)||{};if((typeof((c=s==null?void 0:s.coordinator)==null?void 0:c.meshId)=="string"&&s.coordinator.meshId.trim()||typeof r.meshCoordinatorFor=="string"&&r.meshCoordinatorFor.trim()||"")&&e.sessionDaemonId)return e.sessionDaemonId;const a=typeof r.meshCoordinatorDaemonId=="string"?r.meshCoordinatorDaemonId.trim():"";return a||(typeof e.reportedCoordinatorDaemonId=="string"?e.reportedCoordinatorDaemonId.trim():"")||null}function R1(e){var r;if(!e)return null;const t=(r=e.coordinator)==null?void 0:r.meshId;if(typeof t=="string"&&t.trim())return t.trim();const s=e.settings||{};for(const o of["meshNodeFor","meshCoordinatorFor"]){const a=s[o];if(typeof a=="string"&&a.trim())return a.trim()}return null}function P1(e){const t=(e==null?void 0:e.settings)||{};for(const s of["meshNodeId","nodeId"]){const r=t[s];if(typeof r=="string"&&r.trim())return r.trim()}return null}function L1(e,t){var o,a;if(!t)return null;const s=Fd(e),r=(o=s==null?void 0:s.nodes)==null?void 0:o.find(i=>py(i,t));return r?{nodeId:r.nodeId,workspace:r.workspace,repoRoot:r.repoRoot,daemonId:r.daemonId,role:r.role,machineStatus:r.machineStatus,health:r.health,isLocalWorktree:r.isLocalWorktree,worktreeBranch:r.worktreeBranch,launchReady:r.launchReady,providers:r.providers,providerPriority:r.providerPriority,git:r.git?{branch:r.git.branch,headCommit:r.git.headCommit,ahead:r.git.ahead,behind:r.git.behind,dirty:r.git.dirty,upstream:r.git.upstream}:void 0,connection:r.connection?{transport:r.connection.transport,state:r.connection.state,rttMs:r.connection.rttMs}:void 0,...(a=r.nodeFacts)!=null&&a.quota&&typeof r.nodeFacts.quota=="object"?{quota:r.nodeFacts.quota}:{}}:null}const E1={sm:"max-w-md",md:"max-w-lg",lg:"max-w-3xl"},Km={center:"items-center justify-center",sheet:"items-end justify-center sm:items-center",stretch:"items-stretch justify-center md:items-center"};function Pr({open:e=!0,onClose:t,align:s="center",size:r="md",chrome:o=!0,closeOnBackdrop:a=!0,closeOnEsc:i=!0,ariaLabel:c,ariaLabelledBy:d,overlayClassName:u,surfaceClassName:m,children:h}){l.useEffect(()=>{if(!e||!i)return;const b=k=>{k.key==="Escape"&&t()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[e,i,t]);const p=l.useCallback(b=>{a&&b.target===b.currentTarget&&t()},[a,t]);if(!e)return null;const g=o?ft("fixed inset-0 flex",Km[s],"bg-black/60 px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",u):ft("fixed inset-0 flex",Km[s],u),f=o?ft("relative flex max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-2rem)] w-full flex-col overflow-hidden","rounded-xl border border-border-default bg-surface-primary shadow-2xl",E1[r],m):ft(m),x=n.jsx("div",{className:g,style:o?{zIndex:"var(--z-modal-backdrop)"}:void 0,onClick:p,children:n.jsx("div",{role:"dialog","aria-modal":"true","aria-label":c,"aria-labelledby":d,className:f,style:o?{zIndex:"var(--z-modal)"}:void 0,onClick:b=>b.stopPropagation(),children:h})});return typeof document>"u"?x:Qn.createPortal(x,document.body)}function Zg({open:e,onClose:t,size:s="md",title:r,footer:o,children:a,showClose:i=!0,closeOnBackdrop:c=!0,closeOnEsc:d=!0,ariaLabel:u,className:m,contentClassName:h}){const p=r!=null||i;return n.jsxs(Pr,{open:e,onClose:t,size:s,closeOnBackdrop:c,closeOnEsc:d,ariaLabel:r==null?u:void 0,overlayClassName:m,surfaceClassName:h,children:[p&&n.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-4 border-b border-border-default px-5 py-4",children:[n.jsx("div",{className:"min-w-0",children:typeof r=="string"||typeof r=="number"?n.jsx("h2",{className:"truncate text-lg font-bold text-text-primary",children:r}):r}),i&&n.jsx("button",{type:"button",onClick:t,className:"-m-1.5 inline-flex h-11 w-11 shrink-0 items-center justify-center","aria-label":at.t("common.closeDialog"),children:n.jsx("span",{className:"btn btn-ghost btn-sm inline-flex h-8 w-8 items-center justify-center p-0",children:n.jsx(Bt,{size:16})})})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-5 py-4",children:a}),o!=null&&n.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border-default px-5 py-4",children:o})]})}const Mc=new Map;function D1(e){return{meshId:e,daemonId:null,status:null,response:null,loadedAt:null,loading:!1,refreshing:!1,error:null}}function Hd(e){let t=Mc.get(e);return t||(t={snapshot:D1(e),inFlight:null,queuedRefresh:null,listeners:new Set},Mc.set(e,t)),t}function vr(e,t){var r;const s=Hd(e);(r=t.status)!=null&&r.meshName&&P_(e,t.status.meshName),s.snapshot={...s.snapshot,...t};for(const o of[...s.listeners])try{o()}catch{}}function So(e){var t;return e?((t=Mc.get(e))==null?void 0:t.snapshot)??null:null}function O1(e,t){const s=Hd(e);return s.listeners.add(t),()=>{s.listeners.delete(t)}}function $1(e,t,s=null){vr(e,{status:t,daemonId:s,loadedAt:t?Date.now():null,error:null})}function F1(e){return e instanceof Error?e.message:typeof e=="string"?e:"Failed to load mesh status"}function $i(e){const{meshId:t,daemonId:s,load:r}=e,o=e.refresh===!0,a=e.extract??(m=>Fd(m));if(!t||!s)return Promise.resolve(null);const i=Hd(t),c=i.inFlight;if(c&&c.daemonId===s)return!o||c.refresh?c.promise:(i.queuedRefresh||(i.queuedRefresh=c.promise.then(()=>(i.queuedRefresh=null,$i(e)))),i.queuedRefresh);const d=i.snapshot.status!==null;vr(t,{loading:!d,refreshing:d,error:null});const u=(async()=>{var m;await null;try{const h=await r(s,t,{refresh:o}),p=a(h);return p?(vr(t,{status:p,response:h,daemonId:s,loadedAt:Date.now(),error:null}),p):(vr(t,{error:"mesh_status returned an unexpected payload."}),null)}catch(h){return vr(t,{error:F1(h)}),null}finally{((m=i.inFlight)==null?void 0:m.promise)===u&&(i.inFlight=null),vr(t,{loading:!1,refreshing:!1})}})();return i.inFlight={daemonId:s,refresh:o,promise:u},u}const ei=new Set;function H1(e){if(ei.size===0)return!1;for(const t of[...ei])try{t(e)}catch{}return!0}function B1(e){return ei.add(e),()=>ei.delete(e)}const Is={used:e=>`${e}% used`,resetsNow:()=>"resets now",resetsInMinutes:e=>`resets in ${e}m`,resetsInHours:(e,t)=>`resets in ${e}h ${t}m`,resetsInDays:(e,t)=>`resets in ${e}d ${t}h`,cue:e=>e,windowReset:()=>"reset · awaiting refresh",usageTokens:e=>`${e} tok`,usageSessions:e=>`${e} sess`,pool:()=>"pool",failureKind:(e,t)=>t,unavailable:()=>"not available on this node",unreadable:()=>"could not read quota",justNow:()=>"just now",agoMinutes:e=>`${e}m ago`,agoHours:(e,t)=>`${e}h ${t}m ago`,agoDays:(e,t)=>`${e}d ${t}h ago`},W1=new Set(["missing-credentials","expired-token","unauthorized","quota-exhausted","rate-limited","network","server","parse","cli-unavailable","unsupported","setup-required","no-data","unknown"]);function Bd(e){const t="machine.quota.text.";return{used:s=>e(`${t}used`,{percent:s}),resetsNow:()=>e(`${t}resetsNow`),resetsInMinutes:s=>e(`${t}resetsInMinutes`,{minutes:s}),resetsInHours:(s,r)=>e(`${t}resetsInHours`,{hours:s,minutes:r}),resetsInDays:(s,r)=>e(`${t}resetsInDays`,{days:s,hours:r}),cue:s=>e(`${t}cue.${s}`),windowReset:()=>e(`${t}windowReset`),usageTokens:s=>e(`${t}usageTokens`,{count:s}),usageSessions:s=>e(`${t}usageSessions`,{count:s}),pool:()=>e(`${t}pool`),failureKind:(s,r)=>W1.has(s)?e(`${t}failureKind.${s}`):r,unavailable:()=>e(`${t}unavailable`),unreadable:()=>e(`${t}unreadable`),justNow:()=>e(`${t}justNow`),agoMinutes:s=>e(`${t}agoMinutes`,{minutes:s}),agoHours:(s,r)=>e(`${t}agoHours`,{hours:s,minutes:r}),agoDays:(s,r)=>e(`${t}agoDays`,{days:s,hours:r})}}const U1={"antigravity-cli":"Antigravity CLI","claude-cli":"Claude Code","codex-cli":"Codex CLI","cursor-cli":"Cursor CLI","grok-cli":"Grok CLI","hermes-cli":"Hermes CLI",kimi:"Kimi Code",opencode:"opencode"};function K1(e){return e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function q1(e,t=Is){var i;const s=(i=e.metadata)==null?void 0:i.usage;if(!s||typeof s.days!="number")return null;const r=[];typeof s.totalCostUsd=="number"&&r.push(`$${s.totalCostUsd.toFixed(2)}`);const o=typeof s.inputTokens=="number"?s.inputTokens:null,a=typeof s.outputTokens=="number"?s.outputTokens:null;return(o!==null||a!==null)&&r.push(t.usageTokens(K1((o??0)+(a??0)))),typeof s.sessions=="number"&&r.push(t.usageSessions(s.sessions)),r.length===0?null:`${s.days}d ${r.join(" · ")}`}function Lr(e){return U1[e]??e}function qm(e){return Number.isFinite(e)?e>=90?"danger":e>=70?"warn":"good":"default"}function z1(e,t=Date.now(),s=Is){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;const r=e-t;if(r<=0)return s.resetsNow();const o=Math.round(r/6e4);if(o<60)return s.resetsInMinutes(o);const a=Math.floor(o/60);return a<24?s.resetsInHours(a,o%60):s.resetsInDays(Math.floor(a/24),a%24)}function Ra(e,t=Date.now()){const s=e==null?void 0:e.resetsAt;return typeof s=="number"&&Number.isFinite(s)&&s>0&&s<=t}Is.windowReset();function zm(e){return!!e&&typeof e.usedPercent=="number"&&Number.isFinite(e.usedPercent)}function G1(e){var s;const t=(s=e.metadata)==null?void 0:s.failureKind;return!(t==="no-data"||t==="expired-token"&&e.provider==="antigravity-cli")}function V1(e){return zm(e.session)||zm(e.weekly)?!0:Array.isArray(e.buckets)&&e.buckets.some(t=>!!t&&typeof t.usedPercent=="number"&&Number.isFinite(t.usedPercent))}function Y1(e){var t;if(!G1(e)&&V1(e))return"stale";if(((t=e.metadata)==null?void 0:t.lastGoodWindows)===!0)return"refreshing"}function Gm(e,t=Date.now(),s=!1,r=Is){if(!e||typeof e.usedPercent!="number"||!Number.isFinite(e.usedPercent))return null;if(Ra(e,t))return r.windowReset();const o=r.used(e.usedPercent.toFixed(1)),a=z1(e.resetsAt,t,r),i=a?`${o} · ${a}`:o,c=s===!0||s==="refreshing"?"refreshing":s==="stale"?"stale":null;return c?`${i} · ${r.cue(c)}`:i}function Q1(e){const t=s=>Math.abs(e-s)<=s*.1;return t(300)?"5h":t(10080)?"7d":t(43200)?"30d":e>=24*60?`${Math.round(e/(24*60))}d`:`${Math.round(e/60)}h`}function J1(e,t=Is){var o;const s=e.buckets;if(!Array.isArray(s)||s.length<2)return[];const r=[];for(const a of s){if(!a||typeof a!="object")continue;const i=Number(a.usedPercent),c=Number(a.windowMinutes);if(!Number.isFinite(i)||!Number.isFinite(c)||c<=0)continue;const u=(o=(typeof a.name=="string"?a.name:"").split("·")[0])==null?void 0:o.trim().replace(/\s+(Models?|Bundled Models?)$/i,"").trim();r.push({label:`${u||t.pool()} ${Q1(c)}`,usedPercent:i,window:{usedPercent:i,windowMinutes:c,resetsAt:typeof a.resetsAt=="number"?a.resetsAt:null}})}return r.sort((a,i)=>a.label.localeCompare(i.label))}function X1(e){var s;if(e.status!=="ok")return null;const t=(s=e.metadata)==null?void 0:s.cursorUsage;if(t&&typeof t=="object"){const r=t.displayMessage;if(typeof r=="string"&&r.trim()!=="")return r.trim()}return null}function Z1(e,t=Is){var c;const s=typeof e.error=="string"?e.error.trim():"",r=(c=e.metadata)==null?void 0:c.failureKind,o=typeof r=="string"?r.trim():"",a=o?o.replace(/[_-]+/g," "):"",i=o?t.failureKind(o,a):"";return s&&a&&!s.toLowerCase().includes(a.toLowerCase())?`${s} (${i})`:s||i||(e.status==="unavailable"?t.unavailable():t.unreadable())}function eA(e,t=Date.now(),s=Is){const r=Y1(e),o=(g,f,x)=>{const b=Gm(g,t,r,s);if(!b)return null;const k=g.usedPercent,j=Ra(g,t);return{key:f,label:`${x} ${b}`,usedPercent:j?null:k,hint:f,tone:j?"default":qm(k)}},a=o(e.session,"session","5h"),i=o(e.weekly,"weekly","7d"),c=o(e.monthly,"monthly","30d"),d=J1(e,s).map(g=>({key:g.label,label:`${g.label} ${Gm(g.window,t,r,s)}`,usedPercent:Ra(g.window,t)?null:g.usedPercent,hint:"bucket",tone:Ra(g.window,t)?"default":qm(g.usedPercent)})),u=d.length>0?d:[a,i,c].filter(g=>g!==null),m=q1(e,s),h=m?{key:"usage",label:m,usedPercent:null,hint:"usage",tone:"info"}:null,p=a??i??h;return u.length>0?{kind:"chips",cue:r,chips:u,usageLabel:null,message:null,compactChip:p}:h?{kind:"usage",cue:r,chips:[],usageLabel:m,message:null,compactChip:p}:e.status==="ok"?{kind:"okNoWindows",cue:r,chips:[],usageLabel:null,message:X1(e),compactChip:null}:{kind:"failure",cue:r,chips:[],usageLabel:null,message:Z1(e,s),compactChip:null}}function Wd(e){return(t,s=Date.now())=>eA(t,s,e)}function q5(e,t){var o,a;if(e!=="claude-cli"||t.status==="ok")return null;const s=(o=t.metadata)==null?void 0:o.failureKind,r=typeof t.error=="string"?t.error.toLowerCase():"";return s==="setup-required"||r.includes("claude:install")||r.includes("not set up")||r.includes("wrapper is missing")?"setup":((a=t.metadata)==null?void 0:a.lastGoodWindows)===!0||s==="no-data"?"refresh":null}function eb(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[];for(const[s,r]of Object.entries(e))!r||typeof r!="object"||Array.isArray(r)||t.push({provider:s,quota:r});return t.sort((s,r)=>Lr(s.provider).localeCompare(Lr(r.provider)))}function z5(e,t=Date.now(),s=Is){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;const r=t-e;if(r<0)return s.justNow();const o=Math.floor(r/6e4);if(o<1)return s.justNow();if(o<60)return s.agoMinutes(o);const a=Math.floor(o/60);return a<24?s.agoHours(a,o%60):s.agoDays(Math.floor(a/24),a%24)}function Vm(e){return Do(e,{seconds:!0})||"—"}function tA({sessionId:e,daemonId:t,conv:s,onClose:r}){var T;const{t:o}=ve("common"),a=Wd(Bd(o)),{sendCommand:i}=_t(),c=$d(),[d,u]=l.useState(!0),[m,h]=l.useState(null),[p,g]=l.useState(null),[f,x]=l.useState(null),[b,k]=l.useState(null),j=l.useMemo(()=>R1(s),[s]),v=l.useMemo(()=>P1(s),[s]),_=l.useCallback(async()=>{u(!0),g(null);try{const F=await i(t,"get_session_info",{targetSessionId:e}),q=F&&typeof F=="object"?F:{},Q=q.result&&typeof q.result=="object"?q.result:q;Q!=null&&Q.success?h(Q):(g((Q==null?void 0:Q.error)||o("sessionInfo.failedToLoad")),h(null))}catch(F){g((F==null?void 0:F.message)||String(F)),h(null)}finally{u(!1)}},[i,t,e,o]);l.useEffect(()=>{_()},[_]);const y=l.useMemo(()=>{var F,q;return M1({conv:s,sessionDaemonId:t,heldCoordinatorDaemonId:j?(F=So(j))==null?void 0:F.daemonId:null,reportedCoordinatorDaemonId:(q=m==null?void 0:m.meshWorker)==null?void 0:q.coordinatorDaemonId})},[s,t,j,(T=m==null?void 0:m.meshWorker)==null?void 0:T.coordinatorDaemonId]),w=l.useCallback(async()=>{var K,R;if(x(null),k(null),!j||!v||!y)return;const q=((K=So(j))==null?void 0:K.status)??null??await $i({meshId:j,daemonId:y,refresh:!1,load:(D,P,H)=>c!=null&&c.loadMeshStatus?c.loadMeshStatus(D,P,{refresh:H.refresh}):i(D,"mesh_status",{meshId:P})});if(!q){k(((R=So(j))==null?void 0:R.error)||o("sessionInfo.meshNodeUnavailable"));return}const Q=L1(q,v);if(!Q){k(o("sessionInfo.stampedToNode"));return}x(Q)},[c,i,y,j,v,o]);l.useEffect(()=>{w()},[w]);const[S,C]=l.useState(!1),A=l.useCallback(async()=>{await qg(nA({sessionId:e,daemonId:t,conv:s,data:m,meshNode:f,meshNodeError:b}))&&(C(!0),setTimeout(()=>C(!1),1500))},[s,t,m,f,b,e]),O=n.jsxs(n.Fragment,{children:[(m||p)&&n.jsx("button",{type:"button",onClick:()=>void A(),"data-testid":"session-info-copy-diagnostics",className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:n.jsx("span",{"aria-live":"polite",children:o(S?"common.copied":"sessionInfo.copyDiagnostics")})}),n.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:o("sessionInfo.close")})]}),L=F=>o(F?"common.yes":"common.no"),M=m==null?void 0:m.session,$=(M==null?void 0:M.workspace)||(s==null?void 0:s.workspacePath)||"",N=(s==null?void 0:s.machineName)||(m==null?void 0:m.machineNickname)||"",I=m==null?void 0:m.meshWorker,B=eb((f==null?void 0:f.quota)??(m==null?void 0:m.quota));return n.jsx(Zg,{open:!0,onClose:r,title:o("sessionInfo.title"),size:"lg",footer:O,children:n.jsxs("div",{className:"text-sm space-y-4",children:[d&&n.jsx("div",{className:"text-text-secondary",children:o("sessionInfo.loading")}),p&&n.jsx("div",{className:"text-red-500",children:o("sessionInfo.failedToLoad")}),M&&n.jsxs("div",{className:"space-y-1.5","data-testid":"session-info-summary",children:[n.jsx(it,{k:o("sessionInfo.rowProvider"),v:M.providerName||M.providerType}),$&&n.jsx(it,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(tn,{content:$,children:n.jsx("span",{className:"truncate",children:Gg($)})})}),N&&n.jsx(it,{k:o("sessionInfo.rowMachine"),v:N}),M.spawnedAtMs?n.jsx(it,{k:o("sessionInfo.rowStarted"),v:n.jsx(Kg,{value:M.spawnedAtMs})}):null,(s==null?void 0:s.git)&&n.jsx(it,{k:o("sessionInfo.rowGit"),v:n.jsxs("span",{children:[s.git.branch||o("sessionInfo.gitDetached"),s.git.ahead?` ↑${s.git.ahead}`:"",s.git.behind?` ↓${s.git.behind}`:"",s.git.dirty?` · ${o("sessionInfo.gitDirty")}`:` · ${o("sessionInfo.gitClean")}`]})}),(m==null?void 0:m.coordinator)&&n.jsx(it,{k:o("sessionInfo.rowRole"),v:o("sessionInfo.roleCoordinator")}),B.map(({provider:F,quota:q})=>{const Q=a(q);return n.jsx(it,{k:[Lr(F),nc(q)].filter(Boolean).join(" · "),v:Q.kind==="chips"?n.jsx("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:Q.chips.map(K=>n.jsx(Ym,{label:K.label,tone:K.tone},K.key))}):Q.kind==="usage"?n.jsx(Ym,{label:Q.usageLabel,tone:"info"}):Q.kind==="okNoWindows"?n.jsx("span",{className:"text-text-secondary",children:Q.message??o("sessionInfo.quotaOkNoWindows")}):n.jsx("span",{className:"text-text-secondary",children:Q.message})},F)}),(I==null?void 0:I.coordinatorSessionId)&&n.jsx(it,{k:o("sessionInfo.sectionMeshWorker"),v:n.jsxs("span",{className:"inline-flex flex-wrap items-center gap-2",children:[I.coordinatorCliType&&n.jsx("span",{className:"text-text-secondary",children:I.coordinatorCliType}),I.coordinatorAlive===!1?n.jsx("span",{className:"text-text-secondary",children:o("sessionNav.coordinatorGone")}):n.jsx("button",{type:"button",className:"rounded border border-border-default px-2 py-0.5 text-xs hover:bg-surface-secondary",onClick:()=>{H1({sessionId:I.coordinatorSessionId,source:"session-info-dialog"}),r()},children:o("sessionNav.openCoordinatorChat")})]})})]}),(M||f||(m==null?void 0:m.coordinator)||b&&(j||v))&&n.jsxs("details",{className:"group rounded-lg border border-border-subtle px-3 py-2","data-testid":"session-info-technical-details",children:[n.jsxs("summary",{className:"cursor-pointer select-none list-none text-xs font-medium text-text-secondary [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"mr-1 inline-block transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),o("common.technicalDetails")]}),n.jsxs("div",{className:"mt-3 space-y-4",children:[M&&n.jsxs(Fs,{title:o("sessionInfo.sectionSession"),children:[n.jsx(it,{k:o("sessionInfo.rowSessionId"),v:n.jsx(Lt,{children:M.sessionId})}),n.jsx(it,{k:o("sessionInfo.rowProviderType"),v:n.jsx(Lt,{children:M.providerType})}),M.transport&&n.jsx(it,{k:o("sessionInfo.rowTransport"),v:M.transport}),$&&n.jsx(it,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(Lt,{children:$})}),M.spawnedAtMs?n.jsx(it,{k:o("sessionInfo.rowSpawnedAt"),v:Vm(M.spawnedAtMs)}):null,M.providerSessionId&&n.jsx(it,{k:o("sessionInfo.rowProviderSessionId"),v:n.jsx(Lt,{children:M.providerSessionId})}),(s==null?void 0:s.connectionState)&&n.jsx(it,{k:o("sessionInfo.rowConnection"),v:s.connectionState})]}),I&&(I.meshId||I.taskId||I.coordinatorSessionId)&&n.jsxs(Fs,{title:o("sessionInfo.sectionMeshWorker"),children:[I.meshId&&n.jsx(it,{k:o("sessionInfo.rowMeshId"),v:n.jsx(Lt,{children:I.meshId})}),I.taskId&&n.jsx(it,{k:o("sessionInfo.rowTaskId"),v:n.jsx(Lt,{children:I.taskId})}),I.coordinatorSessionId&&n.jsx(it,{k:o("sessionInfo.rowCoordinator"),v:n.jsx(Lt,{children:I.coordinatorSessionId})})]}),(M==null?void 0:M.launch)&&n.jsxs(Fs,{title:o("sessionInfo.sectionLaunch"),children:[M.launch.command&&n.jsx(it,{k:o("sessionInfo.rowCommand"),v:n.jsx(Lt,{children:M.launch.command})}),M.launch.cwd&&n.jsx(it,{k:o("sessionInfo.rowWorkingDirectory"),v:n.jsx(Lt,{children:M.launch.cwd})}),Array.isArray(M.launch.args)&&M.launch.args.length>0&&n.jsx(it,{k:o("sessionInfo.rowArgs"),v:n.jsx(Lt,{children:M.launch.args.join(" ")})}),Array.isArray(M.launch.extraArgs)&&M.launch.extraArgs.length>0&&n.jsx(it,{k:o("sessionInfo.rowExtraArgs"),v:n.jsx(Lt,{children:M.launch.extraArgs.join(" ")})}),Array.isArray(M.launch.extraEnvKeys)&&M.launch.extraEnvKeys.length>0&&n.jsx(it,{k:o("sessionInfo.rowExtraEnv"),v:n.jsx(Lt,{children:M.launch.extraEnvKeys.join(", ")})})]}),f&&n.jsxs(Fs,{title:o("sessionInfo.sectionMeshNode"),children:[f.nodeId&&n.jsx(it,{k:o("sessionInfo.rowNodeId"),v:n.jsx(Lt,{children:f.nodeId})}),f.workspace&&n.jsx(it,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(Lt,{children:f.workspace})}),f.repoRoot&&f.repoRoot!==f.workspace&&n.jsx(it,{k:o("sessionInfo.rowRepoRoot"),v:n.jsx(Lt,{children:f.repoRoot})}),f.daemonId&&n.jsx(it,{k:o("sessionInfo.rowDaemonId"),v:n.jsx(Lt,{children:f.daemonId})}),f.role&&n.jsx(it,{k:o("sessionInfo.rowRole"),v:f.role}),f.machineStatus&&n.jsx(it,{k:o("sessionInfo.rowMachineStatus"),v:f.machineStatus}),f.health&&n.jsx(it,{k:o("sessionInfo.rowHealth"),v:f.health}),f.isLocalWorktree&&n.jsx(it,{k:o("sessionInfo.rowWorktree"),v:f.worktreeBranch?n.jsx(Lt,{children:f.worktreeBranch}):o("common.yes")}),typeof f.launchReady=="boolean"&&n.jsx(it,{k:o("sessionInfo.rowLaunchReady"),v:L(f.launchReady)}),f.git&&n.jsx(it,{k:o("sessionInfo.rowGit"),v:n.jsxs("span",{children:[f.git.branch||o("sessionInfo.gitDetached"),f.git.headCommit?` @ ${String(f.git.headCommit).slice(0,10)}`:"",f.git.ahead?` ↑${f.git.ahead}`:"",f.git.behind?` ↓${f.git.behind}`:"",f.git.dirty?` · ${o("sessionInfo.gitDirty")}`:` · ${o("sessionInfo.gitClean")}`,f.git.upstream?` · ${f.git.upstream}`:""]})}),f.connection&&n.jsx(it,{k:o("sessionInfo.rowConnection"),v:n.jsxs("span",{children:[f.connection.transport||"—",f.connection.state?` · ${f.connection.state}`:"",typeof f.connection.rttMs=="number"?` · RTT ${f.connection.rttMs}ms`:""]})}),Array.isArray(f.providers)&&f.providers.length>0&&n.jsx(it,{k:o("sessionInfo.rowProviders"),v:n.jsx(Lt,{children:f.providers.join(", ")})}),Array.isArray(f.providerPriority)&&f.providerPriority.length>0&&n.jsx(it,{k:o("sessionInfo.rowProviderPriority"),v:n.jsx(Lt,{children:f.providerPriority.join(" › ")})})]}),!f&&b&&(j||v)&&n.jsx(Fs,{title:o("sessionInfo.sectionMeshNode"),children:n.jsx("div",{className:"text-text-secondary italic",children:b})}),(m==null?void 0:m.coordinator)&&n.jsxs(Fs,{title:o("sessionInfo.sectionMeshCoordinator"),children:[n.jsx(it,{k:o("sessionInfo.rowMeshId"),v:n.jsx(Lt,{children:m.coordinator.meshId})}),m.coordinator.cliType&&n.jsx(it,{k:o("sessionInfo.rowCoordinatorCli"),v:m.coordinator.cliType}),m.coordinator.startedAt?n.jsx(it,{k:o("sessionInfo.rowStartedAt"),v:Vm(m.coordinator.startedAt)}):null,m.coordinator.injection&&n.jsx(it,{k:o("sessionInfo.rowPromptInjection"),v:`${m.coordinator.injection.mode}${m.coordinator.injection.target?` → ${m.coordinator.injection.target}`:""}`}),m.coordinator.mcpConfigPath&&n.jsx(it,{k:o("sessionInfo.rowMcpConfig"),v:n.jsx(Lt,{children:m.coordinator.mcpConfigPath})}),m.coordinator.extraSystemPrompt&&n.jsx(Rc,{title:o("sessionInfo.blockExtraPrompt"),body:m.coordinator.extraSystemPrompt}),m.coordinator.systemPrompt&&n.jsx(Rc,{title:o("sessionInfo.blockFinalPrompt"),body:m.coordinator.systemPrompt})]}),(M==null?void 0:M.runtimeMetadata)!=null&&n.jsx(sA,{meta:M.runtimeMetadata}),p&&n.jsx("div",{className:"font-mono text-xs text-text-secondary break-all",children:p})]})]})]})})}function nA(e){const{sessionId:t,daemonId:s,conv:r,data:o,meshNode:a,meshNodeError:i}=e,c={sessionId:t,daemonId:s,machine:(r==null?void 0:r.machineName)||(o==null?void 0:o.machineNickname)||null,connectionState:(r==null?void 0:r.connectionState)??null,git:(r==null?void 0:r.git)??null,session:(o==null?void 0:o.session)??null,meshWorker:(o==null?void 0:o.meshWorker)??null,coordinator:(o==null?void 0:o.coordinator)??null,meshNode:a??null,meshNodeError:i??null,error:(o==null?void 0:o.error)??null};try{return JSON.stringify(c,null,2)}catch{return String(c)}}function Fs({title:e,children:t}){return n.jsxs("div",{children:[n.jsx("h3",{className:"text-xs uppercase tracking-wide text-text-secondary mb-1",children:e}),n.jsx("div",{className:"space-y-1",children:t})]})}function it({k:e,v:t}){return n.jsxs("div",{className:"flex flex-col sm:flex-row gap-1 sm:gap-3",children:[n.jsx("div",{className:"w-full sm:w-36 sm:shrink-0 text-text-secondary font-medium sm:font-normal",children:e}),n.jsx("div",{className:"min-w-0 break-all",children:t})]})}function Lt({children:e}){return n.jsx("code",{className:"font-mono text-xs",children:e})}function Ym({label:e,tone:t}){const s=t==="danger"?"bg-red-500/10 text-red-500":t==="warn"?"bg-amber-500/10 text-amber-500":t==="good"?"bg-emerald-500/10 text-emerald-500":"bg-white/5 text-text-secondary";return n.jsx("span",{className:`rounded-full px-2 py-0.5 text-3xs font-medium ${s}`,children:e})}function sA({meta:e}){const{t}=ve("common");if(!e||typeof e!="object")return null;const s=e,r=u=>typeof u=="string"&&u.trim()?u:null,o=r(s.runtimeId),a=r(s.lifecycle),i=r(s.surfaceKind),c=r(s.recoveryState),d=Array.isArray(s.attachedClients)?s.attachedClients.length:null;return n.jsxs(Fs,{title:t("sessionInfo.sectionRuntime"),children:[o&&n.jsx(it,{k:t("sessionInfo.rowRuntimeId"),v:n.jsx(Lt,{children:o})}),a&&n.jsx(it,{k:t("sessionInfo.rowLifecycle"),v:a}),i&&n.jsx(it,{k:t("sessionInfo.rowSurface"),v:i}),c&&n.jsx(it,{k:t("sessionInfo.rowRecoveryState"),v:c}),typeof s.restoredFromStorage=="boolean"&&n.jsx(it,{k:t("sessionInfo.rowRestoredFromStorage"),v:s.restoredFromStorage?t("common.yes"):t("common.no")}),d!=null&&n.jsx(it,{k:t("sessionInfo.rowAttachedClients"),v:String(d)}),n.jsx(Rc,{title:t("sessionInfo.blockRawMetadata"),body:rA(e)})]})}function rA(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Rc({title:e,body:t,defaultOpen:s=!1}){const[r,o]=l.useState(s);return n.jsxs("div",{className:"mt-2",children:[n.jsxs("button",{type:"button",onClick:()=>o(a=>!a),className:"text-xs uppercase tracking-wide text-text-secondary hover:text-text-primary",style:{pointerEvents:"auto"},children:[r?"▾":"▸"," ",e]}),r&&n.jsx("pre",{className:"mt-1 p-2 bg-[var(--surface-secondary)] border border-border-subtle rounded text-xs whitespace-pre-wrap overflow-x-auto max-h-96 overflow-y-auto",children:t})]})}const oA=8e3;function aA({sessionId:e,daemonId:t,muted:s,sendDaemonCommand:r}){const[o,a]=l.useState(null),i=l.useRef(null);l.useEffect(()=>{o!==null&&s===o&&a(null)},[s,o]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]);const c=o!==null?o:s,d=!!e&&!!t,u=l.useCallback(()=>{if(!e||!t)return;const m=!c;a(m),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(null),oA),r(t,"set_conversation_prefs",{sessionId:e,muted:m}).catch(h=>{console.warn("[conversation-prefs] toggle mute failed",h),a(null)})},[t,c,r,e]);return{available:d,muted:c,toggle:u}}const da=220;function tb({conversation:e,onOpenHistory:t,onOpenRemote:s,onOpenGit:r,className:o,iconSize:a=16}){const{t:i}=ve("common"),{ides:c}=An(),{sendCommand:d}=_t(),[u,m]=l.useState(!1),[h,p]=l.useState(!1),[g,f]=l.useState(null),x=l.useRef(null),b=l.useRef(null),k=St(e)&&!vt(e),j=vt(e),v=l.useMemo(()=>{const C=c.find(A=>A.id===e.routeId);return lg(e,C)},[e,c]),_=aA({sessionId:e.sessionId,daemonId:e.daemonId,muted:!!(v!=null&&v.muted),sendDaemonCommand:d}),y=[];if(t&&!j&&y.push({key:"history",label:i("dashboard.header.chatHistory"),icon:n.jsx(Vp,{size:15}),onSelect:()=>t(e)}),s&&!k&&!j&&y.push({key:"remote",label:i("dashboard.header.remoteControl"),icon:n.jsx(Xn,{size:15}),onSelect:()=>s(e)}),r&&e.git&&e.daemonId&&e.workspacePath){const C=e.daemonId,A=e.workspacePath;y.push({key:"git",label:i("dashboard.header.openGitStatus"),icon:n.jsx(cc,{size:15}),onSelect:()=>r(C,A)})}_.available&&y.push({key:"mute",label:_.muted?i("conversation.unmuteThis"):i("conversation.muteThis"),icon:_.muted?n.jsx(lc,{size:15}):n.jsx(js,{size:15}),onSelect:_.toggle,pressed:_.muted}),e.sessionId&&e.daemonId&&y.push({key:"info",label:i("sessionInfo.title"),icon:n.jsx(Po,{size:15}),onSelect:()=>p(!0)});const w=l.useCallback((C=!1)=>{var A;m(!1),C&&((A=x.current)==null||A.focus())},[]);if(l.useLayoutEffect(()=>{var O;if(!u||typeof window>"u"){f(null);return}const C=(O=x.current)==null?void 0:O.getBoundingClientRect();if(!C)return;const A=Math.min(Math.max(8,C.right-da),window.innerWidth-da-8);f({top:C.bottom+6,left:A})},[u]),l.useEffect(()=>{if(!u||typeof window>"u")return;const C=L=>{L.key==="Escape"&&(L.stopPropagation(),w(!0))},A=L=>{var $,N;const M=L.target;M&&(($=x.current)!=null&&$.contains(M)||(N=b.current)!=null&&N.contains(M)||w())},O=()=>w();return window.addEventListener("keydown",C,!0),document.addEventListener("mousedown",A,!0),window.addEventListener("resize",O),()=>{window.removeEventListener("keydown",C,!0),document.removeEventListener("mousedown",A,!0),window.removeEventListener("resize",O)}},[w,u]),l.useEffect(()=>{var C,A;u&&((A=(C=b.current)==null?void 0:C.querySelector('[role="menuitem"]'))==null||A.focus())},[u,g]),y.length===0)return null;const S=C=>{var M;if(C.key!=="ArrowDown"&&C.key!=="ArrowUp")return;C.preventDefault();const A=Array.from(((M=b.current)==null?void 0:M.querySelectorAll('[role="menuitem"]'))??[]),O=A.indexOf(document.activeElement),L=A[(O+(C.key==="ArrowDown"?1:-1)+A.length)%A.length];L==null||L.focus()};return n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:x,type:"button","data-testid":"conversation-actions-menu","aria-label":i("dashboard.header.moreActions"),title:i("dashboard.header.moreActions"),"aria-haspopup":"menu","aria-expanded":u,onClick:()=>m(C=>!C),className:o??"btn btn-secondary btn-sm",style:{pointerEvents:"auto"},children:n.jsx(Qp,{size:a})}),u&&typeof document<"u"&&Qn.createPortal(n.jsx("div",{ref:b,role:"menu","aria-label":i("dashboard.header.moreActions"),onKeyDown:S,className:"fixed z-[var(--z-popover)] flex flex-col rounded-xl border border-border-default bg-bg-card p-1 shadow-xl backdrop-blur-xl",style:g?{top:g.top,left:g.left,width:da}:{top:-9999,left:-9999,width:da,visibility:"hidden"},children:y.map(C=>n.jsxs("button",{type:"button",role:"menuitem","data-menu-item":C.key,"aria-pressed":C.pressed,onClick:()=>{w(),C.onSelect()},className:ft("flex w-full items-center gap-2.5 rounded-lg border-none bg-transparent px-2.5 py-2 text-left text-xs font-medium text-text-secondary transition-colors hover:bg-bg-secondary hover:text-text-primary focus-visible:bg-bg-secondary focus-visible:text-text-primary focus-visible:outline-none",C.pressed&&"text-amber-500"),children:[n.jsx("span",{className:"flex w-4 shrink-0 justify-center","aria-hidden":!0,children:C.icon}),n.jsx("span",{className:"min-w-0 truncate",children:C.label})]},C.key))}),document.body),h&&e.sessionId&&e.daemonId&&n.jsx(tA,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e,onClose:()=>p(!1)})]})}function Fi(e){const{t}=ve("common");if(!e.role)return null;const s=O_(e);return e.role==="coordinator"?{short:t("dashboard.meshRole.coordinator"),full:s?t("dashboard.meshRole.coordinatorFor",{mesh:s}):t("dashboard.meshRole.coordinatorUnknownMesh"),mesh:s}:{short:t("dashboard.meshRole.worker"),full:s?t("dashboard.meshRole.workerFor",{mesh:s}):t("dashboard.meshRole.workerUnknownMesh"),mesh:s}}function Ud(e){var s;const t=Oi(e);return((s=Fi(t))==null?void 0:s.full)??null}function _s({conversation:e,className:t,size:s=12}){const r=Oi(e),o=Fi(r);return!r.role||!o?null:n.jsx("span",{role:"img","aria-label":o.full,title:o.full,"data-mesh-role":r.role,className:ft("mesh-role-icon",`is-${r.role}`,t),children:n.jsx(On,{size:s})})}function Wr({conversation:e,className:t,separator:s=!1}){const r=Oi(e),o=Fi(r);return!r.role||!o?null:n.jsxs("span",{className:ft("mesh-role-label",`is-${r.role}`,t),"data-mesh-role":r.role,title:o.full,children:[n.jsx("span",{className:"mesh-role-label-role",children:o.short}),o.mesh&&n.jsxs("span",{className:"mesh-role-label-mesh",children:[" · ",o.mesh]}),s&&n.jsx("span",{className:"mesh-role-label-sep","aria-hidden":"true",children:" · "})]})}function iA({conversation:e,className:t}){const s=Oi(e),r=Fi(s);return!s.role||!r?null:n.jsxs("span",{className:ft("conversation-meta-chip mesh-role-chip",`is-${s.role}`,t),"data-mesh-role":s.role,title:r.full,"aria-label":r.full,children:[n.jsx(On,{size:12}),n.jsx("span",{className:"truncate",children:r.mesh?`${r.short} · ${r.mesh}`:r.short})]})}function Pc(){return kr(()=>import("./DashboardMeshGraphDialog-zKlWvAFM.js"),__vite__mapDeps([3,1,4,5]))}const lA=l.lazy(Pc);function cA({onClose:e}){const{t}=ve(),s=t("connection.loadingShort");return n.jsx(Pr,{onClose:e,size:"sm",ariaLabel:s,children:n.jsx("div",{className:"flex items-center justify-center p-8","data-testid":"mesh-graph-dialog-loading",children:n.jsx(ln,{label:s})})})}function Kd(e){return n.jsx(l.Suspense,{fallback:n.jsx(cA,{onClose:e.onClose}),children:n.jsx(lA,{...e})})}function nb({conversation:e,onOpenMeshGraph:t,showLabel:s=!1,iconSize:r=14,className:o}){const{t:a}=ve("common"),i=Ud(e);if(!t||!Dg(e))return null;const c=i?`${a("dashboard.meshRole.openMeshGraph")} · ${i}`:a("dashboard.meshRole.openMeshGraph");return n.jsxs("button",{type:"button","data-testid":"conversation-mesh-graph-button",onClick:()=>t(e),onPointerEnter:()=>{Pc()},onFocus:()=>{Pc()},className:ft("btn btn-secondary btn-sm dashboard-header-mesh-button inline-flex items-center gap-1.5",o),title:c,"aria-label":c,children:[n.jsx(On,{size:r}),s&&n.jsx("span",{className:"hidden lg:inline",children:a("dashboard.header.meshGraph")})]})}function dA({wsStatus:e,isConnected:t,daemonCount:s,p2pStates:r={},usesP2P:o=!0}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};if(s>0&&!o)return t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null};const i=Object.values(r).filter(c=>c==="connected").length;return s>0?i>=s?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.machinesConnectedCount",subtitleParams:{connected:i,total:s}}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function Qm({value:e}){return e?n.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Jm({notification:e,shortcutIndex:t,onOpen:s,onMarkRead:r,onMarkUnread:o,onDelete:a}){const{t:i}=ve(),c=Si(e.updatedAt),d=!e.readAt;return n.jsxs("div",{className:`dashboard-header-inbox-item ${d?"is-attention":""}`.trim(),children:[n.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:s,children:[n.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),n.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?n.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?i("notification.actionNeeded"):i("notification.taskComplete"),c].filter(Boolean).join(" · ")]}),e.preview?n.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),n.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[d?n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),r()},children:i("notification.markRead")}):n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),o()},children:i("notification.markUnread")}),n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:i("notification.delete")})]})]})}function uA({activeConv:e,wsStatus:t,isConnected:s,conversations:r,onOpenHistory:o,onOpenRemote:a,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:u,hiddenConversations:m=[],onShowConversation:h,onShowAllHidden:p,onResetPanelsToMain:g,inboxOpen:f,onInboxOpenChange:x,hiddenOpen:b,onHiddenOpenChange:k,onOpenNewSession:j,onOpenDashboardGuide:v,guideNudgeVisible:_=!1,actionShortcuts:y,notifications:w,notificationUnreadCount:S,onOpenNotification:C,onMarkNotificationRead:A,onMarkNotificationUnread:O,onDeleteNotification:L,onOpenGitDialog:M,onOpenMeshGraph:$}){const{t:N}=ve(),{ides:I,p2pStates:B={},usesP2P:T=!0}=An(),F=!!e&&St(e)&&!vt(e),q=!!e&&vt(e),Q=c||(e?ng(e)?"terminal":"chat":null),[K,R]=l.useState(!1),[D,P]=l.useState(!1),H=l.useRef(null),W=l.useRef(null),U=l.useRef(null),ae=I.filter(z=>z.type==="adhdev-daemon"),be=dA({wsStatus:t,isConnected:s,daemonCount:ae.length,p2pStates:B,usesP2P:T}),V=N(be.titleKey),we=be.subtitleKey?N(be.subtitleKey,be.subtitleParams):null,ce=be.tone==="connected"?"#22c55e":be.tone==="limited"?"#eab308":"#ef4444",de=be.tone==="connected"?"0 0 4px #22c55e80":be.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",ne=l.useMemo(()=>w.filter(z=>!z.readAt),[w]),ee=l.useMemo(()=>w.filter(z=>!!z.readAt),[w]),ue=l.useMemo(()=>ne.slice(0,9),[ne]),je=S;l.useEffect(()=>{if(!f)return;const z=ie=>{var Ne;(Ne=W.current)!=null&&Ne.contains(ie.target)||x(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[f,x]),l.useEffect(()=>{if(!b)return;const z=ie=>{var Ne;(Ne=U.current)!=null&&Ne.contains(ie.target)||k(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[b,k]),l.useEffect(()=>{if(!b&&!f)return;const z=ie=>{if(!ie.altKey)return;const Ne=ie.code.match(/^Digit([1-9])$/);if(!Ne)return;const Be=Number(Ne[1])-1,Le=b?m[Be]:void 0,Je=f?ue[Be]:void 0;if(!(!Le&&!Je)){if(ie.preventDefault(),ie.stopPropagation(),Le){h==null||h(Le),k(!1);return}Je&&(C(Je),x(!1))}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[m,b,f,ue,k,x,C,h]),l.useEffect(()=>{const z=m.length;if(H.current===null){H.current=z;return}z>H.current&&P(!0),H.current=z},[m.length]);const X=()=>P(!1),G=z=>{if(!z)return;const ie=r.find(Ne=>Ne.tabKey===z);ie&&(u==null||u(ie))};return n.jsxs("div",{className:"dashboard-header",children:[n.jsx("div",{className:"flex items-center gap-3",children:n.jsx("div",{className:"header-title-block",children:n.jsxs("div",{className:"header-title-row",children:[n.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[n.jsx(Jn,{size:18}),n.jsx("span",{className:"header-title-desktop",children:N("dashboard.header.title")}),e&&n.jsx(_s,{conversation:e,size:14,className:"header-title-mobile-role"}),n.jsx("span",{className:"header-title-mobile",children:e?Rt(e):N("dashboard.header.title")}),n.jsx(tn,{content:we?`${V} · ${we}`:V,className:"ml-0.5",children:n.jsx("span",{role:"img","aria-label":V,"data-connection-tone":be.tone,className:"header-title-status-dot",style:{background:ce,boxShadow:de}})})]}),n.jsx("div",{className:"header-subtitle flex items-center",children:j&&n.jsx("button",{type:"button",onClick:j,className:"btn btn-secondary btn-sm ml-2",title:`${N("paneGroup.newSession")}${y!=null&&y.openNewSession?` (${y.openNewSession})`:""}`,"aria-label":N("paneGroup.newSession"),children:n.jsx(_o,{size:14})})})]})})}),n.jsxs("div",{className:"flex gap-2 items-center",children:[v&&n.jsxs("button",{type:"button",onClick:v,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:N("dashboard.header.guide"),"aria-label":N("dashboard.header.guideOpen"),children:[n.jsx("span",{className:"font-semibold leading-none",children:"?"}),_&&n.jsx("span",{children:N("dashboard.header.guideShort")})]}),e&&n.jsxs("div",{className:"dashboard-header-actions-group","data-testid":"dashboard-pane-toolbar",children:[n.jsx(Dd,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),F&&d&&Q&&n.jsx(Ug,{mode:Q,onChange:d,compact:!0}),(F||q)&&i&&n.jsx("button",{type:"button",onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:N(q?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),"aria-label":N(q?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),"data-testid":"dashboard-pane-stop",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:n.jsx(Bt,{size:14})}),n.jsx(nb,{conversation:e,onOpenMeshGraph:$,showLabel:!0}),n.jsx(tb,{conversation:e,onOpenHistory:o,onOpenRemote:a?()=>a():void 0,onOpenGit:M,iconSize:14})]}),n.jsxs("div",{className:"dashboard-header-inbox",ref:W,children:[n.jsxs("div",{className:`dashboard-header-hidden${K?" is-drop-target":""}${D?" hidden-spawn-flash":""}${(m??[]).some(er)?" hidden-generating-spin":""}`,onAnimationEnd:X,ref:U,onDragEnter:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),R(!0))},onDragOver:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),z.dataTransfer.dropEffect="move",R(!0))},onDragLeave:z=>{z.currentTarget.contains(z.relatedTarget)||R(!1)},onDrop:z=>{const ie=z.dataTransfer.getData("text/tab-key");z.preventDefault(),R(!1),G(ie)},children:[n.jsxs("button",{type:"button",onClick:()=>k(!b),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${N("dashboard.hidden.title")}${y!=null&&y.toggleHiddenTabs?` (${y.toggleHiddenTabs})`:""}. ${N("dashboard.hidden.dragHint")}`,children:[n.jsx(xi,{size:16}),m.length>0&&n.jsx("span",{className:`dashboard-header-hidden-badge${D?" hidden-badge-pop":""}`,children:m.length})]}),b&&n.jsxs("div",{className:"dashboard-header-hidden-popover",children:[n.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:N("dashboard.hidden.title")}),n.jsx(Qm,{value:y==null?void 0:y.toggleHiddenTabs})]}),n.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:N("dashboard.hidden.resetPanels")}),m.length>0&&p&&n.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{p(),k(!1)},children:N("dashboard.hidden.restoreAll")})]})]}),e&&u&&n.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>u(e),children:[n.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[n.jsx("span",{className:"dashboard-header-hidden-current-label",children:N("dashboard.hidden.hideCurrentTab")}),n.jsx(Qm,{value:y==null?void 0:y.hideCurrentTab})]}),n.jsx("span",{className:"dashboard-header-hidden-current-title",children:Rt(e)})]}),m.length>0?n.jsx("div",{className:"dashboard-header-hidden-list",children:m.map(z=>n.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(z),k(!1)},children:[n.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[er(z)&&n.jsx(ln,{size:12,thickness:2,color:"success",label:N("dashboard.header.generating")}),n.jsx(_s,{conversation:z,size:12}),Rt(z)]}),n.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[m.indexOf(z)<9?n.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",m.indexOf(z)+1]}):null,n.jsx(Wr,{conversation:z,separator:!0}),Ho(z)]})]},z.tabKey))}):n.jsx("div",{className:"dashboard-header-inbox-empty",children:N("dashboard.hidden.empty")})]})]}),n.jsxs("button",{type:"button",onClick:()=>x(!f),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:N("dashboard.header.activityInbox"),children:[n.jsx(js,{size:16}),je>0&&n.jsx("span",{className:"dashboard-header-inbox-badge",children:je})]}),f&&n.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ne.length>0&&n.jsxs("div",{className:"dashboard-header-inbox-section",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title",children:N("dashboard.inbox.unread")}),ne.map(z=>n.jsx(Jm,{notification:z,shortcutIndex:ue.indexOf(z)>=0?ue.indexOf(z)+1:void 0,onOpen:()=>C(z),onMarkRead:()=>A(z.id),onMarkUnread:()=>O(z.id),onDelete:()=>L(z.id)},z.id))]}),ee.length>0&&n.jsxs("div",{className:"dashboard-header-inbox-section",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title",children:N("dashboard.inbox.read")}),ee.map(z=>n.jsx(Jm,{notification:z,onOpen:()=>C(z),onMarkRead:()=>A(z.id),onMarkUnread:()=>O(z.id),onDelete:()=>L(z.id)},z.id))]}),w.length===0&&n.jsx("div",{className:"dashboard-header-inbox-empty",children:N("dashboard.inbox.empty")})]})]})]})]})}function yn(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function mA(e,t){return String(e||"")!==String(t||"")}function hA(e,t={}){const s=String(t.textQuery||"").trim().toLowerCase(),r=String(t.workspaceQuery||"").trim().toLowerCase(),o=String(t.modelQuery||"").trim().toLowerCase(),a=!!t.resumableOnly;return!s&&!r&&!o&&!a?e:e.filter(i=>!(a&&!i.canResume||s&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
50
|
+
`).includes(s)||r&&!String(i.workspace||"").toLowerCase().includes(r)||o&&!$f(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
51
|
+
`).includes(o)))}function pA(e,t="recent"){const s=e.slice();return s.sort((r,o)=>{if(t==="oldest")return(Number(r.lastMessageAt)||0)-(Number(o.lastMessageAt)||0);if(t==="messages"){const a=(Number(o.messageCount)||0)-(Number(r.messageCount)||0);if(a!==0)return a}return(Number(o.lastMessageAt)||0)-(Number(r.lastMessageAt)||0)}),s}function qd(e,t={}){return pA(hA(e,t),t.sortMode||"recent")}function Lc(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function sb(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function fA(e){return e?e("launch.startFresh"):"Start fresh"}function gA(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function bA(e){return e?e("launch.openSavedHistory"):"Open saved history"}function Ec(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function zd(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function rb(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function xA(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function yA(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function ti(e,t,s){if(typeof e=="function"){const a=t,i=s;return a==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const r=e,o=t;return r==="start-fresh"?`Start fresh with ${o}?`:`Restart ${o}?`}function ni(e,t){if(typeof e=="function"){const r=t;return e(r==="start-fresh"?"launch.startFreshReview":r==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const s=e;return s==="start-fresh"?"Review the provider and target folder before starting fresh.":s==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function si(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function ri(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function ob(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function ab(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function Xm(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function vA({activeConv:e,ides:t,isCreatingChat:s,isRefreshingHistory:r,savedSessions:o=[],isSavedSessionsLoading:a=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:u,onClose:m,onNewChat:h,onSwitchSession:p,onRefreshHistory:g,onResumeSavedSession:f}){var $;const{t:x}=ve("common"),b=t.find(N=>N.id===e.routeId),k=(b==null?void 0:b.chats)||[],j=($=b==null?void 0:b.activeChat)==null?void 0:$.id,v=St(e)&&!vt(e),[_,y]=l.useState(()=>yn()),[w,S]=l.useState(null),C=c||_,A=String(d||"").trim(),O=N=>{if(u){u(N);return}y(N)},L=l.useMemo(()=>o.map(N=>{const I=String(N.workspace||"").trim();return N.canResume||I||!A?N:{...N,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,o]),M=l.useMemo(()=>qd(L,{textQuery:C.textQuery,workspaceQuery:C.workspaceQuery,modelQuery:C.modelQuery,resumableOnly:C.resumableOnly,sortMode:C.sortMode}),[L,C.modelQuery,C.resumableOnly,C.sortMode,C.textQuery,C.workspaceQuery]);return n.jsxs(n.Fragment,{children:[n.jsxs(Pr,{chrome:!1,onClose:m,closeOnEsc:!w,ariaLabel:v?Ec(x):x("historyModal.chatHistory"),overlayClassName:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4 bg-black/60 backdrop-blur-sm",surfaceClassName:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[n.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"m-0 text-lg font-extrabold",children:v?Ec(x):x("historyModal.chatHistory")}),n.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:H_(e)}),v&&n.jsx("div",{className:"text-2xs text-text-muted mt-1",children:zd(x)})]}),n.jsx("button",{onClick:m,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:n.jsx(Bt,{size:16})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!v&&n.jsx("button",{onClick:h,disabled:s,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:x(s?"historyModal.creating":"historyModal.startNewChat")}),v?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[n.jsx("input",{type:"text",value:C.textQuery,onChange:N=>O({...C,textQuery:N.target.value}),placeholder:x("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),n.jsx("input",{type:"text",value:C.workspaceQuery,onChange:N=>O({...C,workspaceQuery:N.target.value}),placeholder:x("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),n.jsx("input",{type:"text",value:C.modelQuery,onChange:N=>O({...C,modelQuery:N.target.value}),placeholder:x("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),n.jsxs("select",{value:C.sortMode,onChange:N=>O({...C,sortMode:N.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[n.jsx("option",{value:"recent",children:x("historyModal.sortRecent")}),n.jsx("option",{value:"oldest",children:x("historyModal.sortOldest")}),n.jsx("option",{value:"messages",children:x("historyModal.sortMessages")})]})]}),n.jsxs("label",{className:"mt-2 flex items-center gap-2 text-2xs text-text-muted",children:[n.jsx("input",{type:"checkbox",checked:C.resumableOnly,onChange:N=>O({...C,resumableOnly:N.target.checked})}),x("historyModal.resumeReadyOnly")]})]}),M.map(N=>{const I=e.providerSessionId===N.providerSessionId,B=I||!N.canResume||!!i,T=N.workspaceFallbackSource==="selected-workspace";return n.jsxs("button",{type:"button",onClick:()=>{B||!f||S({kind:"saved",session:N})},disabled:B,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${I?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${B?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:`font-bold text-sm mb-1 truncate ${I?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:N.title||x("historyModal.untitledSession")}),n.jsx("div",{className:"text-2xs text-text-muted font-mono truncate",children:N.providerSessionId})]}),n.jsx("div",{className:"text-2xs text-text-muted shrink-0",children:Xm(N.lastMessageAt)})]}),n.jsx("div",{className:"mt-2 text-xs text-text-muted line-clamp-2",children:N.preview||x("historyModal.noSavedPreview")}),n.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-2xs text-text-muted",children:[n.jsxs("div",{className:"truncate",children:[N.workspace||x("historyModal.workspaceUnknown"),T?x("historyModal.selectedWorkspaceSuffix"):"",tr(N.summaryMetadata)?` · ${tr(N.summaryMetadata)}`:"",N.messageCount>0?` · ${x("historyModal.msgCount",{count:N.messageCount})}`:""]}),n.jsx("div",{className:"shrink-0",children:I?x("historyModal.statusActive"):N.canResume?T?x("historyModal.statusResumeSelectedWorkspace"):i===N.providerSessionId?x("historyModal.statusResuming"):x("historyModal.statusResume"):x("historyModal.statusMissingWorkspace")})]})]},N.id)})]}):k.map(N=>n.jsxs("div",{onClick:()=>{N.id!==j&&S({kind:"chat",id:N.id,title:N.title||x("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${j===N.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[n.jsx("div",{className:`font-bold text-sm mb-1 ${j===N.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:N.title||x("historyModal.untitledSession")}),n.jsxs("div",{className:"flex justify-between items-center",children:[n.jsxs("div",{className:"text-2xs text-text-muted font-mono",children:[N.id.substring(0,12),"..."]}),j===N.id&&n.jsx("span",{className:"text-3xs bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:x("historyModal.statusActive")})]})]},N.id)),(v&&!a&&M.length===0||!v&&k.length===0)&&n.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[n.jsx("div",{className:"text-3xl mb-3 opacity-60",children:n.jsx(vw,{size:32})}),n.jsx("div",{className:"text-xxs",children:v?o.length>0?x("historyModal.noMatchingHistory"):rb(x):x("historyModal.noRecentChats")})]}),v&&a&&n.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:n.jsx("div",{className:"text-xxs",children:yA(x)})})]}),n.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:n.jsx("button",{onClick:g,disabled:r||a,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||a?x("historyModal.refreshing"):n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx($r,{size:13})," ",v?xA(x):x("historyModal.refreshHistory")]})})})]}),w&&n.jsxs(Pr,{chrome:!1,onClose:()=>S(null),overlayClassName:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm",surfaceClassName:"card fade-in relative w-full sm:w-[min(92vw,420px)] max-w-[420px] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[n.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[n.jsx("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:x("historyModal.confirmSwitchTitle")}),n.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:x("historyModal.confirmSwitchDescription",{target:w.kind==="chat"?w.title:w.session.title||x("historyModal.untitledSession")})}),w.kind==="saved"&&n.jsxs("div",{className:"mt-2 text-2xs text-text-muted font-mono truncate",children:[w.session.workspace||x("historyModal.workspaceUnknown"),w.session.lastMessageAt?` · ${Xm(w.session.lastMessageAt)}`:""]})]}),n.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[n.jsx("button",{onClick:()=>{const N=w;S(null),N.kind==="chat"?(p(e.routeId,N.id),m()):f&&f(N.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:x("historyModal.confirmSwitchAction")}),n.jsx("button",{onClick:()=>S(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:x("common.cancel")})]})]})]})}const Zm={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.success"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.warning"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.info"}};function wA({toast:e}){const{t}=ve(),{setToasts:s}=An(),[r,o]=l.useState(!1);return e.details?n.jsxs("div",{className:"mt-2","data-toast-details":"",children:[n.jsxs("button",{type:"button",className:"bg-transparent border-none p-0 text-xs font-semibold text-text-muted hover:text-text-primary cursor-pointer","aria-expanded":r,onClick:a=>{a.stopPropagation();const i=!r;o(i),i&&s(c=>c.map(d=>d.id===e.id?{...d,pinned:!0}:d))},children:[n.jsx("span",{className:"mr-1 inline-block transition-transform",style:{transform:r?"rotate(90deg)":void 0},"aria-hidden":!0,children:"▸"}),t("toast.details")]}),r&&n.jsx("pre",{className:"mt-1.5 max-h-40 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-border-subtle bg-bg-secondary/60 px-2.5 py-2 font-mono text-3xs leading-relaxed text-text-secondary",children:e.details})]}):null}function ib({toasts:e,onDismiss:t,onClickToast:s}){const{t:r}=ve();return n.jsx("div",{className:"fixed right-4 top-[calc(env(safe-area-inset-top,0px)+64px)] z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none sm:top-[calc(env(safe-area-inset-top,0px)+16px)]",children:e.map(o=>{const a=Zm[o.type]||Zm.info;return n.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=o.actions)!=null&&i.length||s&&s(o)},children:[n.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),n.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(o.id)},"aria-label":r("toast.dismiss"),children:n.jsx(Bt,{size:14})}),n.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[n.jsx("div",{className:"flex items-center gap-2 pr-8",children:n.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-3xs font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:r(a.labelKey)})}),n.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:o.message}),n.jsx(wA,{toast:o}),o.actions&&o.actions.length>0&&n.jsx("div",{className:"flex gap-2 mt-3",children:o.actions.map((i,c)=>n.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),t(o.id)},children:i.label},c))})]})]},o.id)})})}const SA=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function kA(e){const t=e.workspace||"";if(!t)return"";const s=t.split(/[/\\]/).filter(Boolean);return s.length>0?s[s.length-1]:t}function jA(e,t){return lb(e)||t}function lb(e){var o,a,i;const t=(a=(o=e.summaryMetadata)==null?void 0:o.items)==null?void 0:a.find(c=>(c==null?void 0:c.id)==="model"),s=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(s)return s;const r=(i=e.controlValues)==null?void 0:i.model;return typeof r=="string"&&r.trim()?r.trim():""}function NA(e){return lb(e)||void 0}function CA(e){return e.sessionId||e.instanceId||e.agentType}function cb(e=[]){const t={};for(const s of e)s.type==="adhdev-daemon"&&(t[s.id]=Tn(s,{fallbackId:s.id}));return t}function db(e,t={}){var r;const s=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:oj(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[s]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Gd(e,t={}){return _A(e,db(e,t))}function _A(e,t={}){var p,g,f,x,b,k,j,v,_;const s=[],r=t.machineName,o=t.connectionState,a=kA(e),i=e.workspace||"",c=uj(e.type,{agentName:e.cliName}),d=St(e)||vt(e)?c:Kt(e.type),u=jA(e,d),m=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var w,S,C;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,activeChatId:(w=y.activeChat)==null?void 0:w.id,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||Kt(y.providerType),model:NA(y),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((S=y.activeChat)==null?void 0:S.messages)||[],activeModal:((C=y.activeChat)==null?void 0:C.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,surfaceHidden:y.surfaceHidden,muted:y.muted,git:y.git,settings:y.settings,coordinator:y.coordinator,messageInput:y.messageInput}}):[],h=SA(e);if(h){const y=e.sessionId||e.instanceId,w=(p=e.settings)==null?void 0:p.meshCoordinatorFor,S=((g=e.settings)==null?void 0:g.meshNodeFor)||!((f=e.settings)!=null&&f.meshCoordinatorFor)&&((x=e.settings)==null?void 0:x.launchedByCoordinator),C=w?" (Coordinator)":S?" (Mesh Node)":"",A=c+C,O=(b=e.activeChat)==null?void 0:b.activeModal,L=O&&Array.isArray(O.buttons)&&O.buttons.length>0,M=mj(e.activeChat,[{status:e.status,activeModal:(k=e.activeChat)==null?void 0:k.activeModal}],e.agents||[]),$=e.activeChat||{title:"",messages:[]};let N=$.title&&String($.title).trim()?String($.title).trim():"";const I=(j=e.activeChat)==null?void 0:j.id,B=e.chats;if(I&&Array.isArray(B)&&B.length>0){const P=B.find(H=>H.id===I||H.id&&String(H.id)===String(I));P!=null&&P.title&&String(P.title).trim()&&(N=String(P.title).trim())}const T=(St(e)||vt(e),e.type),F=(St(e)||vt(e))&&sm(N,A,T)?"":N,q=$.messages||[],Q=typeof I=="string"?I.trim():"",K=(St(e)||vt(e))&&Q===String(e.type||"").trim(),R=Q&&!K?Q:e.providerSessionId,D=e.coordinator||(typeof((v=e.settings)==null?void 0:v.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);s.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,historySessionId:R,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:St(e)&&e.mode||"chat",agentName:A,agentType:T,status:M,title:F,messages:q,resume:e.resume,hostIdeType:!St(e)&&!vt(e)?e.type:void 0,workspaceName:a,workspacePath:i,git:e.git,displayPrimary:a||F||(St(e)?e.mode==="chat"?A:`Terminal${C}`:A),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:L?O.buttons:void 0,modalMessage:L?O.message:void 0,streamSource:"native",tabKey:ul(y,e.id),machineName:r,connectionState:o,settings:e.settings,coordinator:D,messageInput:e.messageInput})}if(h&&(St(e)||vt(e)))return s;for(const y of m){const w=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,S=hj(y),C=CA(y),A=`${e.id}:${C}`,O=y.title&&String(y.title).trim()||"",L=sm(O,y.agentName,y.agentType)?"":O,M=y.messages||[];if(!(y.transport==="cdp-webview"||!!y.sessionId||!!y.providerSessionId||M.length>0||w||!!L||!["idle","panel_hidden","disconnected","not_monitored"].includes(S)))continue;const N=y.coordinator||(typeof((_=y.settings)==null?void 0:_.meshCoordinatorFor)=="string"&&y.settings.meshCoordinatorFor?{meshId:y.settings.meshCoordinatorFor,role:"coordinator"}:void 0);s.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,historySessionId:y.activeChatId||y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:S,title:L,messages:M,hostIdeType:e.type,workspaceName:a,workspacePath:i,git:y.git||e.git,displayPrimary:a||L||y.agentName||d,displaySecondary:y.model&&y.model.trim()?y.model.trim():`${d} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,modalButtons:w?y.activeModal.buttons:void 0,modalMessage:w?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:ul(y.sessionId||y.instanceId,A),machineName:r,connectionState:o,settings:y.settings,coordinator:N,messageInput:y.messageInput})}return s.length===0&&s.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:a,workspacePath:i,git:e.git,displayPrimary:a||d,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:ul(e.sessionId||e.instanceId,e.id),connectionState:o,settings:e.settings,messageInput:e.messageInput}),s}function ub(e){return String(e.type||e.id||"").trim()}function oi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function AA(e,t){const s=(t||"").trim();if(!s)return[];const r=(e||[]).find(o=>o.type===s);return oi(r==null?void 0:r.modelOptions)}function TA(e,t){const s=(t||"").trim();if(!s)return[];const r=(e||[]).find(o=>o.type===s);return oi(r==null?void 0:r.thinkingLevelOptions)}function mb(e){const t=new Map;for(const s of e||[])s!=null&&s.type&&t.set(s.type,{models:oi(s.modelOptions),thinking:oi(s.thinkingLevelOptions)});return t}function IA(e){var t;return e.category!=="cli"||!ub(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function Zn(e){var r;const t=new Set,s=[];for(const o of e||[]){if(!IA(o))continue;const a=ub(o);if(!a||t.has(a))continue;t.add(a);const i=String(o.displayName||o.name||a),c=o.detectedPath||((r=o.lastDetection)==null?void 0:r.path)||null;s.push({type:a,label:i,icon:o.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(o.modelOptions)&&o.modelOptions.length?{modelOptions:o.modelOptions}:{},...Array.isArray(o.thinkingLevelOptions)&&o.thinkingLevelOptions.length?{thinkingLevelOptions:o.thinkingLevelOptions}:{}})}return s}function Bo(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],s=new Set,r=[];for(const o of t){const a=typeof o=="string"?o.trim():"";!a||s.has(a)||(s.add(a),r.push(a))}return r}function nr(e){return e.map(t=>t.type)}function MA(e,t){const s=Bo(e),r=t.trim();return!r||s.includes(r)?s:[...s,r]}function RA(e,t){return Bo(e).filter(s=>s!==t)}function eh(e,t,s){const r=Bo(e),o=r.indexOf(t);if(o<0)return r;const a=r.filter(c=>c!==t);if(s==="top")return[t,...a];if(s==="bottom")return[...a,t];const i=s==="up"?Math.max(0,o-1):Math.min(a.length,o+1);return a.splice(i,0,t),a}const PA={"claude-cli":{monogram:"CL",hue:"#D97757"},"codex-cli":{monogram:"CX",hue:"#10A37F"},"gemini-cli":{monogram:"GM",hue:"#4285F4"},"kimi-cli":{monogram:"KM",hue:"#6366F1"},"antigravity-cli":{monogram:"AG",hue:"#8B5CF6"},"cursor-cli":{monogram:"CU",hue:"#64748B"},"opencode-cli":{monogram:"OC",hue:"#CA8A04"},"hermes-cli":{monogram:"HM",hue:"#14B8A6"},"grok-cli":{monogram:"GK",hue:"#475569"},antigravity:{monogram:"AG",hue:"#8B5CF6"},cursor:{monogram:"CU",hue:"#64748B"},kiro:{monogram:"KI",hue:"#F59E0B"},pearai:{monogram:"PA",hue:"#22C55E"},trae:{monogram:"TR",hue:"#EF4444"},vscode:{monogram:"VS",hue:"#3B82F6"},vscodium:{monogram:"VC",hue:"#2DD4BF"},windsurf:{monogram:"WS",hue:"#0EA5E9"},cline:{monogram:"CN",hue:"#0284C7"},"roo-code":{monogram:"RC",hue:"#F97316"}},th=["#0EA5E9","#8B5CF6","#10B981","#F59E0B","#EF4444","#14B8A6","#6366F1","#EC4899","#84CC16","#F97316","#06B6D4","#A855F7"];function LA(e){let t=0;for(let s=0;s<e.length;s+=1)t=(t<<5)-t+e.charCodeAt(s)|0;return Math.abs(t)}function EA(e){const t=e.replace(/[-_./]+/g," ").split(/\s+/).map(s=>s.trim()).filter(Boolean);return t.length===0?"?":t.length===1?t[0].slice(0,2).toUpperCase():(t[0][0]+t[1][0]).toUpperCase()}function Hi({type:e,label:t,size:s=16,className:r}){const o=(e||"").trim().toLowerCase(),a=(t==null?void 0:t.trim())||o;if(!a)return n.jsx(Aw,{size:s,className:r});const i=PA[o],c=(i==null?void 0:i.monogram)??EA((t==null?void 0:t.trim())||o.replace(/-cli$/,"")),d=(i==null?void 0:i.hue)??th[LA(o||a)%th.length];return n.jsx("span",{"aria-hidden":!0,className:`inline-flex shrink-0 select-none items-center justify-center font-semibold ${r??""}`,style:{width:s,height:s,borderRadius:Math.max(4,Math.round(s*.3)),backgroundColor:`${d}21`,border:`1px solid ${d}4D`,color:d,fontSize:Math.max(7,Math.round(s*.42)),letterSpacing:"0.02em",lineHeight:1},children:c})}function nh({direction:e}){return n.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?n.jsx("polyline",{points:"18 15 12 9 6 15"}):n.jsx("polyline",{points:"6 9 12 15 18 9"})})}function DA({value:e,availableProviders:t,onChange:s,disabled:r=!1,saveButton:o}){const{t:a}=ve("common"),[i,c]=l.useState(""),d=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),u=l.useMemo(()=>Bo(e),[e]),m=u.filter(g=>!d.has(g)).length,h=t.filter(g=>!u.includes(g.type)),p=()=>{i&&(s(MA(u,i)),c(""))};return n.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[n.jsx("div",{className:"flex flex-col gap-2",children:u.length===0?n.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-300",children:a("settings.providerPriority.emptyWarning")}):u.map((g,f)=>{const x=d.get(g),b=!!x;return n.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${b?"bg-bg-primary":"bg-bg-primary/40"}`,children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsxs("span",{className:"text-3xs font-semibold text-text-muted",children:["#",f+1]}),n.jsx(Hi,{type:g,label:x==null?void 0:x.label,size:14}),n.jsx("span",{className:`font-mono text-xs ${b?"text-text-primary":"text-text-muted"}`,children:g}),b?n.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-4xs font-semibold text-green-400",children:a("settings.providerPriority.available")}):n.jsx(tn,{content:a("settings.providerPriority.keptUntilDetected"),children:n.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-4xs font-semibold text-amber-400",children:a("settings.providerPriority.notOnMachine")})})]}),x&&n.jsx("div",{className:"mt-1 text-3xs text-text-muted",children:`${x.label} · ${x.statusLabel}`})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":a("settings.providerPriority.moveUp"),disabled:r||f===0,title:a("settings.providerPriority.moveUp"),onClick:()=>s(eh(u,g,"up")),children:n.jsx(nh,{direction:"up"})}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":a("settings.providerPriority.moveDown"),disabled:r||f===u.length-1,title:a("settings.providerPriority.moveDown"),onClick:()=>s(eh(u,g,"down")),children:n.jsx(nh,{direction:"down"})}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>s(RA(u,g)),children:a("settings.providerPriority.remove")})]})]},g)})}),n.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[n.jsxs("label",{className:"flex-1 text-2xs text-text-secondary",children:[n.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:a("settings.providerPriority.addCliLabel")}),n.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:g=>c(g.target.value),disabled:r||h.length===0,children:[n.jsx("option",{value:"",children:h.length?a("settings.providerPriority.selectProvider"):a("settings.providerPriority.noMoreProviders")}),h.map(g=>n.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:r||!i,onClick:p,children:a("settings.providerPriority.addProvider")}),o]}),n.jsx("div",{className:"mt-2 flex items-center gap-1 text-2xs text-text-muted",children:n.jsx(dt,{content:[a("settings.providerPriority.orderHint"),m>0?a("settings.providerPriority.undetectedHint",{count:m}):""].filter(Boolean).join(`
|
|
52
|
+
|
|
53
|
+
`)})})]})}function OA(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function hb(e,t){const s=OA(e);return{daemonId:s.daemonId,payload:{...t,...s.targetSessionId&&!t.targetSessionId?{targetSessionId:s.targetSessionId}:{}}}}const $A=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],FA=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"grok-cli",name:"Grok",icon:"🛰️"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],HA=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}];function pb({icon:e,title:t,subtitle:s,subtitleInline:r=!1,badge:o,actions:a,className:i}){return n.jsxs("div",{className:ft("dashboard-header",i),children:[n.jsxs("div",{children:[n.jsxs("h1",{className:"header-title flex items-center gap-2",children:[n.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,s&&!r&&n.jsx(dt,{content:s}),o&&n.jsxs("span",{className:"text-3xs font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[o.count!==void 0?o.count:""," ",o.text]})]}),s&&r&&n.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:s})]}),a&&n.jsx("div",{className:"flex gap-2",children:a})]})}function Wo({icon:e,title:t,subtitle:s,subtitleInline:r,badge:o,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:d}){return n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsx(pb,{icon:e,title:t,subtitle:s,subtitleInline:r,badge:o,actions:a}),n.jsx("div",{className:"page-content",children:n.jsx("div",{className:ft("mx-auto flex w-full flex-col gap-4",i,c),children:d})})]})}const Dc="adhdev:themechange";function BA(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function wr(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Sr(e){return e==="system"?BA():e}function fb(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Pa(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Dc,{detail:{preference:e,theme:t}}))}function WA(){const e=wr(),t=Sr(e);fb(t),Pa(e,t)}function Uo(){const[e,t]=l.useState(wr),[s,r]=l.useState(()=>Sr(wr()));l.useEffect(()=>{fb(s)},[s]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const u=d.matches?"light":"dark";r(u),Pa("system",u)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const u=d.detail||{},m=u.preference,h=u.theme;t(m==="dark"||m==="light"||m==="system"?m:wr()),r(h==="dark"||h==="light"?h:Sr(wr()))},c=d=>{if(d.key!=="theme")return;const u=wr(),m=Sr(u);t(u),r(m)};return window.addEventListener(Dc,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Dc,i),window.removeEventListener("storage",c)}},[]);const o=l.useCallback(i=>{const c=Sr(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}Pa(i,c)},[]),a=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=Sr(c);r(d);try{localStorage.setItem("theme",c)}catch{}return Pa(c,d),c})},[]);return{theme:s,preference:e,setPreference:o,cycleTheme:a,isDark:s==="dark"}}const sh={dark:"Dark",light:"Light",system:"System"};function UA({collapsed:e}){const{preference:t,cycleTheme:s}=Uo(),r=t==="dark"?n.jsx(Zp,{size:16}):t==="light"?n.jsx(Xp,{size:16}):n.jsx(ef,{size:16});return n.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:s,title:`Theme: ${sh[t]} (click to cycle)`,children:[n.jsx("span",{className:"nav-icon",children:r}),!e&&n.jsx("span",{className:"text-xs",children:sh[t]})]})}const Oc="adhdev:langchange";function KA(){const e=at.language;return Us(e)?e:Mf()}function qA(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Oc,{detail:{language:e}}))}function zA(){const[e,t]=l.useState(KA);l.useEffect(()=>{const r=i=>{Us(i)&&t(i)},o=i=>{const c=i.detail||{};Us(c.language)&&t(c.language)},a=i=>{if(i.key!==xc)return;const c=i.newValue;Us(c)&&c!==at.language&&(at.changeLanguage(c),yc(c))};return at.on("languageChanged",r),window.addEventListener(Oc,o),window.addEventListener("storage",a),()=>{at.off("languageChanged",r),window.removeEventListener(Oc,o),window.removeEventListener("storage",a)}},[]);const s=l.useCallback(r=>{if(Us(r)){t(r);try{localStorage.setItem(xc,r)}catch{}at.changeLanguage(r),yc(r),qA(r)}},[]);return{language:e,setLanguage:s}}function GA({trigger:e,viewport:t,menu:s,variant:r,gap:o=6,margin:a=8}){const i=e.top-a,c=t.height-e.bottom-a,d=r==="sidebar";let u=d;d&&i<s.height&&c>i&&(u=!1),!d&&c<s.height&&i>c&&(u=!0);const m=u?i:c,h=Math.max(80,Math.min(s.height,m));let p;u?p=e.top-o-h:p=e.bottom+o,p=rh(p,a,Math.max(a,t.height-h-a));const g=rh(e.left,a,Math.max(a,t.width-s.width-a));return{top:p,left:g,maxHeight:h}}function rh(e,t,s){return Math.min(Math.max(e,t),s)}function VA({open:e}){return n.jsx("svg",{width:12,height:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:`lang-switch-caret${e?" open":""}`,children:n.jsx("polyline",{points:"6 9 12 15 18 9"})})}function YA({collapsed:e,variant:t="sidebar"}){const{language:s,setLanguage:r}=zA(),{t:o}=ve("common"),[a,i]=l.useState(!1),[c,d]=l.useState(0),u=l.useRef(null),m=l.useRef(null),h=l.useRef(null),p=l.useId(),[g,f]=l.useState(null),x=l.useCallback(()=>{const M=m.current;if(!M)return;const $=M.getBoundingClientRect(),N=h.current,I=Math.max((N==null?void 0:N.offsetWidth)??0,168),B=(N==null?void 0:N.scrollHeight)??Ps.length*36+12;f(GA({trigger:{top:$.top,left:$.left,right:$.right,bottom:$.bottom,width:$.width,height:$.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:I,height:B},variant:t}))},[t]),b=Math.max(0,Ps.findIndex(M=>M.code===s)),k=Ps[b]??Ps[0],j=o("language.label",{defaultValue:"Language"}),v=o("language.select",{defaultValue:"Select language"}),_=M=>`${p}-opt-${M}`,y=l.useCallback(()=>{d(b),i(!0)},[b]),w=l.useCallback((M=!0)=>{var $;i(!1),M&&(($=m.current)==null||$.focus())},[]),S=l.useCallback(M=>{const $=Ps[M];$&&r($.code),w()},[r,w]);l.useEffect(()=>{if(!a)return;const M=I=>{var B,T;return!!((B=u.current)!=null&&B.contains(I)||(T=h.current)!=null&&T.contains(I))},$=I=>{M(I.target)||i(!1)},N=I=>{M(I.target)||i(!1)};return document.addEventListener("pointerdown",$,!0),document.addEventListener("focusin",N,!0),()=>{document.removeEventListener("pointerdown",$,!0),document.removeEventListener("focusin",N,!0)}},[a]),l.useLayoutEffect(()=>{if(!a){f(null);return}x();const M=()=>x();return window.addEventListener("resize",M),window.addEventListener("scroll",M,!0),()=>{window.removeEventListener("resize",M),window.removeEventListener("scroll",M,!0)}},[a,x]),l.useEffect(()=>{var M;a&&g&&((M=h.current)==null||M.focus())},[a,g]);const C=M=>{const $=Ps.length-1;switch(M.key){case"ArrowDown":M.preventDefault(),d(N=>N>=$?0:N+1);break;case"ArrowUp":M.preventDefault(),d(N=>N<=0?$:N-1);break;case"Home":M.preventDefault(),d(0);break;case"End":M.preventDefault(),d($);break;case"Enter":case" ":M.preventDefault(),S(c);break;case"Escape":M.preventDefault(),w();break;case"Tab":i(!1);break}},A=M=>{a||(M.key==="ArrowDown"||M.key==="ArrowUp"||M.key==="Enter"||M.key===" ")&&(M.preventDefault(),y())},O=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,L=t==="landing"||!e;return n.jsxs("div",{ref:u,className:"lang-switch",children:[n.jsxs("button",{ref:m,type:"button",className:O,"aria-haspopup":"listbox","aria-expanded":a,"aria-label":`${j}: ${k.label}`,title:`${j}: ${k.label}`,onClick:()=>a?w(!1):y(),onKeyDown:A,children:[n.jsx("span",{className:"nav-icon lang-switch-icon",children:n.jsx(nf,{size:16})}),L&&n.jsx("span",{className:"lang-switch-label text-xs",children:k.label}),L&&n.jsx(VA,{open:a})]}),a&&typeof document<"u"&&Qn.createPortal(n.jsx("ul",{ref:h,role:"listbox",tabIndex:-1,"aria-label":v,"aria-activedescendant":_(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:C,children:Ps.map((M,$)=>{const N=M.code===k.code,I=$===c;return n.jsxs("li",{id:_($),role:"option","aria-selected":N,className:`lang-switch-option${I?" is-active":""}${N?" is-selected":""}`,onMouseEnter:()=>d($),onClick:()=>S($),children:[n.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:N?n.jsx(Dr,{size:14}):null}),n.jsx("span",{className:"lang-switch-option-label",children:M.label})]},M.code)})}),document.body)]})}const QA=[],JA=[];function wl(e,t){return e?typeof e=="function"?e(t):e:null}const XA=l.memo(function({renderState:t,brand:s,navItems:r,sidebarSections:o,footerItems:a,footerInfo:i,footerActions:c,closeMobileMenu:d}){const{t:u}=ve("common"),{collapsed:m,mobileMenuOpen:h}=t,p=f=>`nav-item${f.active?" active":""} cursor-pointer ${m?"justify-center py-2.5 px-0":""}${f.className?` ${f.className}`:""}`,g=f=>n.jsxs("div",{className:p(f),id:`nav-${f.id}`,onClick:()=>{f.onSelect(),d()},title:m?f.title??(typeof f.label=="string"?f.label:void 0):f.title,children:[n.jsx("span",{className:"nav-icon",children:f.icon}),!m&&f.label]},f.id);return n.jsxs("aside",{className:`sidebar ${h?"sidebar-open":""}`,children:[n.jsxs("div",{className:"sidebar-header",children:[n.jsx("div",{className:`sidebar-logo ${m?"justify-center gap-0":""}`,children:wl(s,t)}),n.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":u("app.closeMenu"),onClick:d,children:n.jsx(Bt,{size:16})})]}),n.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),o.map(f=>n.jsxs("div",{className:f.className??"border-t border-border-subtle pt-2 mt-2",children:[!m&&f.title?n.jsx("div",{className:"px-3 py-1 text-3xs text-text-muted uppercase tracking-widest",children:f.title}):null,f.items.map(g)]},f.key)),n.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(g),wl(i,t),n.jsx(UA,{collapsed:m}),n.jsx(YA,{collapsed:m}),wl(c,t)]})]})});function ZA({children:e,brand:t,navItems:s,sidebarSections:r=QA,footerItems:o=JA,footerInfo:a,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const{t:u}=ve("common"),[m,h]=l.useState(!1),[p,g]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),f=l.useCallback(()=>h(!0),[]),x=l.useCallback(()=>h(!1),[]),b=l.useCallback(()=>{g(j=>{const v=!j;try{localStorage.setItem(d,v?"1":"0")}catch{}return v})},[d]),k=l.useMemo(()=>({collapsed:p,mobileMenuOpen:m,openMobileMenu:f,closeMobileMenu:x,toggleCollapsed:b}),[p,m,f,x,b]);return n.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${p?" sidebar-collapsed":""}`,children:[n.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":u("app.openMenu"),onClick:f,children:[n.jsx("span",{className:"mobile-menu-icon"}),n.jsx("span",{className:"mobile-menu-icon"}),n.jsx("span",{className:"mobile-menu-icon"})]}),m&&n.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":u("app.closeMenu"),onClick:x,onKeyDown:j=>j.key==="Escape"&&x()}),n.jsx(XA,{renderState:k,brand:t,navItems:s,sidebarSections:r,footerItems:o,footerInfo:a,footerActions:i,closeMobileMenu:x}),n.jsx("main",{className:"main-content relative",children:n.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function Nt({title:e,icon:t,description:s,descriptionInline:r=!1,accentColor:o,className:a,collapsible:i,defaultOpen:c=!0,badge:d,action:u,children:m}){const[h,p]=l.useState(c),g=i?h:!0,f=()=>p(k=>!k),x=n.jsxs(n.Fragment,{children:[t&&n.jsx("span",{children:t}),n.jsx("span",{children:e})]}),b=(e||s||u)&&n.jsxs("div",{className:ft("flex items-start justify-between gap-3",g&&"mb-4",i&&"cursor-pointer"),onClick:i?f:void 0,children:[n.jsxs("div",{className:"min-w-0",children:[e&&n.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[i?n.jsx("button",{type:"button",className:"inline-flex items-center gap-1.5 bg-transparent border-none p-0 text-left font-semibold text-text-primary cursor-pointer",onClick:k=>{k.stopPropagation(),f()},"aria-expanded":g,children:x}):x,s&&!r&&n.jsx("span",{onClick:k=>k.stopPropagation(),className:"inline-flex",children:n.jsx(dt,{content:s})}),d]}),s&&(r||!e)&&n.jsx("p",{className:"text-xxs text-text-muted mt-1",children:s})]}),u&&n.jsx("div",{className:"flex shrink-0 items-center gap-2",onClick:k=>k.stopPropagation(),children:u}),i&&n.jsx("span",{className:ft("mt-0.5 shrink-0 text-text-muted transition-transform select-none",g?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return n.jsxs("div",{className:ft("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",o&&"border-l-[3px]",a),style:o?{borderLeftColor:o}:void 0,children:[b,g&&m]})}function Bi({icon:e,title:t,description:s,action:r,className:o,variant:a="default"}){return a==="compact"?n.jsxs("div",{className:ft("flex flex-wrap items-center justify-center gap-2 rounded-xl border border-dashed border-border-subtle px-4 py-5 text-center text-xs text-text-muted",o),children:[e&&n.jsx("span",{className:"flex items-center opacity-60","aria-hidden":!0,children:e}),n.jsx("span",{className:"font-medium text-text-secondary",children:t}),s?n.jsx(dt,{content:s}):null,r]}):n.jsxs("div",{className:ft("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),children:[e&&n.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),n.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s?n.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:s}):n.jsx("div",{className:"mb-3"}),r]})}const eT={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},tT={error:an,warning:an,success:vi,info:Po};function zt({variant:e,children:t,onDismiss:s,className:r}){return n.jsxs("div",{className:ft("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-xxs",eT[e],r),children:[n.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const o=tT[e];return n.jsx(o,{size:14})})(),n.jsx("span",{children:t})]}),s&&n.jsx("button",{onClick:s,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function qt({label:e,hint:t,hintInline:s=!1,children:r,className:o}){return n.jsxs("div",{className:ft("mb-5",o),children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1",children:[n.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider",children:e}),t&&!s&&n.jsx(dt,{content:t})]}),r,t&&s&&n.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function Dn(e){const{className:t,...s}=e;return n.jsx("input",{...s,className:ft("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const nT={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},os=l.forwardRef(function({variant:t="secondary",size:s="md",type:r,className:o,...a},i){return n.jsx("button",{ref:i,type:r??"button",className:ft("btn",nT[t],s==="sm"&&"btn-sm",o),...a})}),sT=l.forwardRef(function({options:t,children:s,className:r,...o},a){return n.jsx("select",{ref:a,className:ft("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",r),...o,children:s??(t==null?void 0:t.map(i=>n.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})});function Vd({tabs:e,activeKey:t,onSelect:s,variant:r="pill",ariaLabel:o,className:a,tabIdPrefix:i,panelIdPrefix:c}){const d=r==="underline",u=m=>{var x;if(m.key!=="ArrowRight"&&m.key!=="ArrowLeft"&&m.key!=="Home"&&m.key!=="End")return;const h=Math.max(0,e.findIndex(b=>b.key===t)),p=m.key==="Home"?0:m.key==="End"?e.length-1:(h+(m.key==="ArrowRight"?1:-1)+e.length)%e.length,g=e[p];if(!g)return;m.preventDefault(),s(g.key),(x=m.currentTarget.querySelectorAll('[role="tab"]')[p])==null||x.focus()};return n.jsx("div",{className:ft(d?"flex shrink-0 items-center gap-1 overflow-x-auto border-b border-border-subtle px-4 md:px-6 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden":"mb-5 inline-flex w-full flex-wrap items-center gap-1 rounded-xl border border-border-subtle bg-bg-secondary/60 p-1 sm:w-fit",a),role:"tablist","aria-label":o,onKeyDown:u,children:e.map(m=>{const h=m.key===t;return n.jsxs("button",{id:i?`${i}-${m.key}`:void 0,type:"button",role:"tab","aria-selected":h,"aria-controls":c?`${c}-${m.key}`:void 0,tabIndex:h?0:-1,className:ft(d?["-mb-px flex shrink-0 cursor-pointer items-center gap-1.5 whitespace-nowrap border-b-2 bg-transparent px-3 py-2.5 text-xxs font-medium transition-colors",h?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"]:["flex flex-1 items-center justify-center gap-1.5 rounded-lg px-3.5 py-1.5 text-xxs font-medium transition-colors sm:flex-none",h?"bg-bg-card text-text-primary shadow-sm border border-border-default":"text-text-muted border border-transparent hover:text-text-secondary hover:bg-white/[0.03]"]),onClick:()=>s(m.key),children:[m.icon,m.label,m.trailing]},m.key)})})}function gb({tabs:e,defaultTabKey:t,activeKey:s,onTabChange:r,variant:o="pill",ariaLabel:a,className:i,tabListClassName:c,panelClassName:d,tabIdPrefix:u,unmountInactivePanels:m=!1}){var b;const[h,p]=l.useState(t??((b=e[0])==null?void 0:b.key)),g=s!==void 0,f=g?s:h,x=k=>{g||p(k),r==null||r(k)};return n.jsxs("div",{className:i,children:[n.jsx(Vd,{tabs:e,activeKey:f,onSelect:x,variant:o,ariaLabel:a,className:c,tabIdPrefix:u}),e.map(k=>{const j=k.key===f;return m&&!j?null:n.jsx("div",{role:"tabpanel","aria-labelledby":u?`${u}-${k.key}`:void 0,className:j?ft("flex flex-col gap-4",d):"hidden",children:k.content},k.key)})]})}class rT extends l.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,s){console.error("[ErrorBoundary] Uncaught error:",t,s)}render(){return this.state.hasError?n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",background:"var(--bg-primary, #0a0e1a)",color:"var(--text-secondary, #c4c9d4)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:n.jsxs("div",{style:{textAlign:"center",maxWidth:420,padding:24},children:[n.jsx("div",{style:{display:"flex",justifyContent:"center",marginBottom:16},children:n.jsx(an,{size:44,className:"text-status-warning"})}),n.jsx("h2",{style:{margin:"0 0 8px",fontSize:18,fontWeight:600,color:"var(--text-primary, #eee)"},children:at.t("app.errorBoundary.title")}),n.jsx("p",{style:{margin:"0 0 20px",fontSize:14,opacity:.7,lineHeight:1.5},children:at.t("app.errorBoundary.description")}),n.jsx("button",{onClick:()=>window.location.reload(),style:{padding:"10px 24px",borderRadius:8,border:"1px solid rgba(99, 102, 241, 0.4)",background:"rgba(99, 102, 241, 0.1)",color:"#a5b4fc",fontSize:14,fontWeight:500,cursor:"pointer"},children:at.t("app.errorBoundary.reload")})]})}):this.props.children}}const oT={sm:"w-[34px] h-[19px]",md:"w-[40px] h-[22px]"},oh={sm:{base:"w-[16px] h-[16px]",on:"translate-x-[15px]"},md:{base:"w-[19px] h-[19px]",on:"translate-x-[18px]"}};function Ur({checked:e,onChange:t,disabled:s=!1,busy:r=!1,size:o="md",id:a,title:i,className:c,as:d="button",...u}){const m=s||r,h=f=>{f.stopPropagation(),!m&&t(!e)},p={id:a,title:i,role:"switch","aria-checked":e,"aria-disabled":s||void 0,"aria-busy":r||void 0,"aria-label":u["aria-label"],"aria-labelledby":u["aria-labelledby"],"aria-describedby":u["aria-describedby"],"data-state":e?"on":"off",className:ft("relative inline-flex shrink-0 items-center rounded-full border-none bg-transparent p-0 outline-none","focus-visible:ring-2 focus-visible:ring-accent/60 focus-visible:ring-offset-1 focus-visible:ring-offset-bg-primary",s?"cursor-not-allowed opacity-50":r?"cursor-wait opacity-60":"cursor-pointer",c)},g=n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,className:ft("inline-block rounded-full transition-colors duration-200 ease-in-out",oT[o]),style:{backgroundColor:e?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),n.jsx("span",{"aria-hidden":!0,className:ft("absolute left-[1.5px] top-[1.5px] rounded-full bg-white shadow-[0_1px_2px_rgba(0,0,0,0.15)] transition-transform duration-200 ease-in-out",oh[o].base,e?oh[o].on:"translate-x-0")})]});return d==="span"?n.jsx("span",{...p,tabIndex:s?-1:0,onClick:h,onKeyDown:f=>{(f.key===" "||f.key==="Enter")&&(f.preventDefault(),h(f))},children:g}):n.jsx("button",{type:"button",...p,disabled:s,onClick:h,children:g})}function Wi({onClick:e,refreshing:t=!1,disabled:s=!1,label:r,size:o=14,showLabel:a=!1,className:i}){const{t:c}=ve("common"),d=r??c("common.refresh");return n.jsxs("button",{type:"button",onClick:e,disabled:s||t,"aria-label":a?void 0:d,"aria-busy":t||void 0,title:d,className:ft("inline-flex shrink-0 items-center justify-center gap-1.5 rounded-lg border border-border-subtle bg-transparent text-text-muted transition-colors","hover:border-border-default hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-50","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent",a?"px-2.5 py-1 text-xs font-medium":"h-8 w-8",i),children:[n.jsx($r,{size:o,className:t?"animate-spin":void 0}),a&&n.jsx("span",{children:d})]})}const G5={recentFailures:0};function V5(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}const aT={online:"mesh.nodeHealth.online",dirty:"mesh.nodeHealth.dirty",offline:"mesh.nodeHealth.offline",degraded:"mesh.nodeHealth.degraded",wrong_branch:"mesh.nodeHealth.wrongBranch",unknown:"mesh.nodeHealth.unknown",enabled:"mesh.nodeHealth.enabled",pending:"mesh.nodeHealth.pending",assigned:"mesh.nodeHealth.assigned",completed:"mesh.nodeHealth.completed",failed:"mesh.nodeHealth.failed"};function iT(e,t){const s=aT[(e||"unknown").toLowerCase()];return s?t(s):String(e)}function Y5(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function bb(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return{bucket:"other",normalized:""};const r=gi(t)??t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?{bucket:"awaiting_approval",normalized:r}:r.includes("generating")||r.includes("running")||r.includes("busy")?{bucket:"generating",normalized:r}:r.includes("failed")||r==="error"||r.includes("stopped")||r.includes("interrupted")?{bucket:"failed",normalized:r}:r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?{bucket:"idle",normalized:r}:{bucket:"other",normalized:r}}function Q5(e){const{bucket:t,normalized:s}=bb(e);if(!s&&t==="other")return"unknown";switch(t){case"awaiting_approval":return"awaiting approval";case"generating":return"generating";case"idle":return"idle";default:return s.replace(/_/g," ")}}function J5(e,t){const{bucket:s,normalized:r}=bb(e);switch(s){case"awaiting_approval":return t("sessionStatus.awaitingApproval");case"generating":return t("sessionStatus.generating");case"idle":return t("sessionStatus.idle");case"failed":return r.includes("stopped")||r.includes("interrupted")?t("sessionStatus.stopped"):t("sessionStatus.failed");default:return r?r==="starting"||r==="pending"||r==="launching"?t("sessionStatus.starting"):r.replace(/_/g," "):t("sessionStatus.unknown")}}function X5(e,t){if(e.isSelfCoordinator)return t("mesh.panel.statusCoordinator");const s=typeof e.role=="string"?e.role.trim():"";return!s||s==="worker"?t("mesh.panel.statusWorker"):s==="coordinator"?t("mesh.panel.statusCoordinator"):s}function lT(e){return e.startedAt||e.createdAt||null}function Z5(e){const t=lT(e);if(!t)return"runtime age not reported";const s=Date.parse(t);if(!Number.isFinite(s))return"runtime age not reported";const r=Math.max(0,Math.floor((Date.now()-s)/1e3));if(r<60)return`${r}s`;const o=Math.floor(r/60);if(o<60)return`${o}m`;const a=Math.floor(o/60);return a<48?`${a}h ${o%60}m`:`${Math.floor(a/24)}d ${a%24}h`}function e3(e,t){const s=(d,u,m)=>t?t(d,m):u,r=e.git;if(!r)return e.gitProbePending?s("mesh.drift.probePending","Git probe pending"):s("mesh.drift.noGit","No git probe");const o=(r.staged??0)+(r.modified??0)+(r.untracked??0)+(r.deleted??0)+(r.renamed??0),a=[];r.branch&&a.push(r.branch),r.upstream&&r.upstreamStatus!=="fresh"&&a.push(s("mesh.drift.upstreamUnverified","upstream unverified")),r.upstreamStatus==="fresh"&&((r.ahead??0)>0||(r.behind??0)>0)&&a.push(`↑${r.ahead??0}/↓${r.behind??0}`),o>0&&a.push(s("mesh.drift.changed",`${o} dirty`,{count:o}));const i=(r.submodules??[]).filter(d=>d.dirty),c=(r.submodules??[]).filter(d=>d.outOfSync||d.error);return i.length>0&&a.push(s("mesh.drift.submoduleChanged",`${i.length} submodule dirty`,{count:i.length})),c.length>0&&a.push(s("mesh.drift.submoduleOutOfSync",`${c.length} submodule drift`,{count:c.length})),r.hasConflicts&&a.push(s("mesh.drift.conflicts","conflicts")),a.join(" · ")||s("mesh.drift.clean","Clean")}function cT(e){var r;const t=(r=e.nodeFacts)==null?void 0:r.quota;if(!t||typeof t!="object"||Array.isArray(t))return[];const s=[];for(const[o,a]of Object.entries(t))!a||typeof a!="object"||Array.isArray(a)||s.push({provider:o,quota:a});return s.sort((o,a)=>Lr(o.provider).localeCompare(Lr(a.provider)))}function xb(e){return xy(e.daemonId)||e.machineId||e.nodeId}function t3(e){var s;const t=new Map;for(const r of e.nodes){const o=r.nodeFacts,a=xb(r);if(!a)continue;let i=t.get(a);i||(i={machineKey:a,label:"",nodeCount:0,hasReported:!1,quota:[]},t.set(a,i)),i.nodeCount+=1;const c=typeof(o==null?void 0:o.reportedAt)=="number"&&Number.isFinite(o.reportedAt)?o.reportedAt:void 0,d=c!==void 0&&(i.reportedAt===void 0||c>i.reportedAt);d&&(i.reportedAt=c),o&&(i.hasReported=!0);const u=cT(r);u.length>0&&(d||i.quota.length===0)&&(i.quota=u);const m=((s=o==null?void 0:o.daemonBuild)==null?void 0:s.version)||r.daemonBuildVersion;m&&(d||!i.daemonBuildVersion)&&(i.daemonBuildVersion=m)}for(const r of t.values())r.label=mT(e,r.machineKey);return[...t.values()].sort((r,o)=>r.label.localeCompare(o.label)||r.machineKey.localeCompare(o.machineKey))}function dT(e){const t=typeof e.worktreeBranch=="string"&&e.worktreeBranch.trim()?e.worktreeBranch.trim():"";if(t)return`⎇ ${t}`;const s=typeof e.nodeLabel=="string"&&e.nodeLabel.trim()?e.nodeLabel.trim():"";return s||(typeof e.workspace=="string"?e.workspace.replace(/[\\/]+$/,"").split(/[\\/]/).pop():"")||e.machineLabel||(e.nodeId?e.nodeId.slice(0,12):"node")}function uT(e){const t=dT(e),s=typeof e.machineLabel=="string"?e.machineLabel.trim():"";return!s||s===t?t:`${t} · ${s}`}function mT(e,t){var i,c,d;const s=[],r=[],o=[];for(const u of e.nodes){if(xb(u)!==t)continue;const h=(i=u.nodeFacts)==null?void 0:i.machineNickname;typeof h=="string"&&h.trim()&&s.push(h.trim());const p=u.machine,g=(p!=null&&p.sameMachine?p.coordinatorHostname:void 0)??((d=(c=p==null?void 0:p.identityEvidence)==null?void 0:c.find(x=>((x==null?void 0:x.label)==="hostname"||(x==null?void 0:x.label)==="machineName")&&typeof x.value=="string"&&x.value.trim()))==null?void 0:d.value);typeof g=="string"&&g.trim()&&r.push(g.trim().replace(/\.local$/i,""));const f=typeof u.machineLabel=="string"?u.machineLabel.trim():"";f&&f!==u.nodeId&&f!==u.daemonId&&f!==t&&o.push(f)}const a=u=>u.length===0?void 0:[...u].sort((m,h)=>m.localeCompare(h))[0];return a(s)??a(r)??a(o)??yb(t)}function yb(e){const t=e.replace(/^(daemon_|standalone_)/,"");return t.length<=20?t:`${t.slice(0,17)}…`}const n3={first_eligible:"In order",fitness:"Smart",least_loaded:"Smart",round_robin:"Smart (round-robin)",priority_only:"Smart (priority)"};function s3(e){if(e.startsWith("max_provider_parallel_reached:"))return`provider cap reached (${e.slice(30)})`;switch(e){case"global_max_parallel_tasks_reached":return"global parallel cap reached";case"node_has_active_assignment":return"already running a write task";default:return e.replace(/_/g," ")}}function r3(e){var s;const t=[];for(const r of e.nodes){const o=r.activeSessionDetails&&r.activeSessionDetails.length>0?r.activeSessionDetails:(r.activeSessions??[]).map(a=>({sessionId:a,workspace:r.workspace,isCached:!0}));for(const a of o)t.push({nodeId:r.nodeId,machineLabel:r.machineLabel,workspace:r.workspace,branch:((s=r.git)==null?void 0:s.branch)??null,nodeHealth:r.health,session:a})}return t}function o3(e){return e.assignedNodeId||e.targetNodeId||null}function ah(e){return e?e.slice(0,7):null}function hT(e,t){var a,i,c;const s=ah((a=e==null?void 0:e.git)==null?void 0:a.headCommit),r=((c=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:c.trim())||"";if(s||r)return[s,r].filter(Boolean).join(" · ");const o=t[0];return o?[ah(o.commit),o.message].filter(Boolean).join(" · "):null}function a3(e,t){const s=hT(e,t);return s||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function i3(e){const t=(e==null?void 0:e.result)??e,s=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(s==null?void 0:s.entries)?s.entries:[]}function l3(e){var o,a,i,c,d,u,m;const t=((o=e.selectedSessionEntry)==null?void 0:o.session.workspace)||((a=e.selectedSessionEntry)==null?void 0:a.workspace)||((c=(i=e.selectedNodeStatus)==null?void 0:i.git)==null?void 0:c.workspace)||((d=e.selectedNodeStatus)==null?void 0:d.workspace)||null;if(!t||!e.selectedSessionEntry&&!e.selectedNodeStatus)return null;const s=((u=e.selectedNodeStatus)==null?void 0:u.nodeId)||((m=e.selectedSessionEntry)==null?void 0:m.nodeId)||null,r=e.coordinatorDaemonId||null;return r&&s?{daemonId:r,workspace:t,nodeId:s}:null}function c3(e){var s;const t=e.source;return t!=null&&t.kind?t.kind:((s=t==null?void 0:t.connection)==null?void 0:s.source)??"mesh_status"}function d3(e,t){return t?e.nodes.find(s=>s.id===t)??null:null}function u3(e){var t,s,r,o;return[e.meshId,e.refreshedAt,e.nodes.length,((s=(t=e.queue)==null?void 0:t.summary)==null?void 0:s.active)??"",((o=(r=e.ledger)==null?void 0:r.summary)==null?void 0:o.recentFailures)??"",...e.nodes.map(a=>{var i,c,d,u,m,h,p,g,f,x,b,k,j,v,_,y,w,S,C,A,O,L;return[a.nodeId,a.daemonId??"",a.machineId??"",a.machineLabel,a.machineStatus??"",((i=a.connection)==null?void 0:i.state)??"",((c=a.connection)==null?void 0:c.transport)??"",((d=a.connection)==null?void 0:d.source)??"",a.health,a.gitProbePending?1:0,((u=a.git)==null?void 0:u.branch)??"",((m=a.git)==null?void 0:m.upstream)??"",((h=a.git)==null?void 0:h.upstreamStatus)??"",((p=a.git)==null?void 0:p.ahead)??"",((g=a.git)==null?void 0:g.behind)??"",((f=a.git)==null?void 0:f.headCommit)??"",((x=a.git)==null?void 0:x.staged)??"",((b=a.git)==null?void 0:b.modified)??"",((k=a.git)==null?void 0:k.untracked)??"",((j=a.git)==null?void 0:j.deleted)??"",((v=a.git)==null?void 0:v.renamed)??"",(_=a.git)!=null&&_.hasConflicts?1:0,((y=a.git)==null?void 0:y.lastCheckedAt)??"",((w=a.activeSessions)==null?void 0:w.join(","))??"",((S=a.activeSessionDetails)==null?void 0:S.length)??"",((C=a.activeSessionDetails)==null?void 0:C.map(M=>[M.sessionId,M.providerType??"",M.state??"",M.chatStatus??"",M.lifecycle??"",M.role??"",M.isSelfCoordinator?1:0,M.statusNote??"",M.startedAt??"",M.createdAt??""].join("/")).join(","))??"",((A=a.providers)==null?void 0:A.join(","))??"",((O=a.providerPriority)==null?void 0:O.join(","))??"",a.error??"",(((L=a.git)==null?void 0:L.submodules)??[]).map(M=>[M.path,M.commit,M.dirty?1:0,M.outOfSync?1:0,M.error??""].join("/")).join(",")].join("|")})].join("::")}function m3(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function ns({label:e,description:t,descriptionInline:s=!1,checked:r,disabled:o,onChange:a,extra:i}){const c=l.useId();return n.jsxs("div",{className:`flex justify-between items-center ${o?"opacity-60":""}`,children:[n.jsxs("div",{className:"pr-4 min-w-0",children:[n.jsxs("div",{className:"font-medium text-sm flex items-center gap-1",children:[n.jsx("span",{id:c,children:e}),t&&!s&&n.jsx(dt,{content:t})]}),t&&s&&n.jsx("div",{className:"text-2xs text-text-muted mt-0.5",children:t})]}),n.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,n.jsx(Ur,{checked:r,disabled:o,onChange:a,"aria-labelledby":c})]})]})}const pT=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli"];function fT({daemonId:e,knownCliTypes:t=pT,embedded:s=!1}){const{t:r}=ve("common"),{sendCommand:o}=_t(),[a,i]=l.useState({}),[c,d]=l.useState({}),[u,m]=l.useState(!0),[h,p]=l.useState(null),[g,f]=l.useState(null),[x,b]=l.useState(""),[k,j]=l.useState(!1),v=s||k,[_,y]=l.useState(null),w=l.useCallback(async()=>{if(e){m(!0),f(null);try{const N=await o(e,"list_coordinator_prompts",{}),I=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(I!=null&&I.success)){f((I==null?void 0:I.error)||r("settings.coordinatorPrompts.loadFailed"));return}const B=I.entries||{};b(I.dir||"");const T={};for(const F of t)T[F]=B[F]||{override:"",append:""};for(const F of Object.keys(B))T[F]||(T[F]=B[F]);i(T),d(JSON.parse(JSON.stringify(T)))}catch(N){f((N==null?void 0:N.message)||String(N))}finally{m(!1)}}},[o,e,t,r]);l.useEffect(()=>{w()},[w]);const S=l.useCallback(async(N,I)=>{var B;if(e){p(`${N}:${I}`),f(null);try{const T=((B=a[N])==null?void 0:B[I])||"",F=await o(e,"write_coordinator_prompt",{key:N,kind:I,content:T}),q=F!=null&&F.result&&typeof F.result=="object"?F.result:F;if(!(q!=null&&q.success)){f((q==null?void 0:q.error)||r("settings.coordinatorPrompts.saveFailed"));return}d(Q=>({...Q,[N]:{...Q[N]||{override:"",append:""},[I]:T}}))}catch(T){f((T==null?void 0:T.message)||String(T))}finally{p(null)}}},[o,e,a,r]),C=l.useMemo(()=>(N,I)=>{var B,T;return(((B=a[N])==null?void 0:B[I])||"")!==(((T=c[N])==null?void 0:T[I])||"")},[a,c]),A=l.useCallback(async N=>{C(N,"override")&&await S(N,"override"),C(N,"append")&&await S(N,"append")},[C,S]),O=l.useCallback(N=>{const I=c[N];return!!(I&&((I.override||"").trim()||(I.append||"").trim()))},[c]),L=Object.keys(a),M=L.filter(O),$=_&&a[_]?_:L[0];return e?v?n.jsxs("div",{className:"flex flex-col gap-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1 text-xs text-text-muted",children:[n.jsx("span",{className:"truncate font-mono text-2xs",children:x||"~/.adhdev/coordinator-prompts/"}),n.jsx(dt,{content:n.jsxs("span",{children:[r("settings.coordinatorPrompts.intro")," ",x||"~/.adhdev/coordinator-prompts/",`
|
|
54
|
+
|
|
55
|
+
`,n.jsx(Wa,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:n.jsx("strong",{})}})," ",n.jsx(Wa,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:n.jsx("strong",{})}}),`
|
|
56
|
+
|
|
57
|
+
`,r("settings.coordinatorPrompts.resetHint")," ",r("settings.coordinatorPrompts.placeholdersHint")," ",n.jsxs("span",{className:"font-mono",children:["{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}"]}),"…"]})})]}),!s&&n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>j(!1),children:r("settings.coordinatorPrompts.collapseLabel")})]}),g&&n.jsx("div",{className:"text-xs text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:g}),u&&n.jsx("div",{className:"text-xs text-text-muted",children:r("settings.coordinatorPrompts.loading")}),L.length>0&&n.jsx(gb,{activeKey:$,onTabChange:y,ariaLabel:r("settings.coordinatorPrompts.tabsAriaLabel"),tabIdPrefix:"coordinator-prompt-tab",tabs:L.map(N=>{const I=a[N],B=C(N,"override")||C(N,"append");return{key:N,label:n.jsxs("span",{className:"flex items-center gap-1.5 font-mono text-xs",children:[N,O(N)&&n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-accent-primary",title:r("settings.coordinatorPrompts.customizedBadge")}),B&&n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:"var(--status-warning)"},"aria-hidden":!0})]}),content:n.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[n.jsx("label",{className:"block text-2xs uppercase tracking-wide text-text-muted mb-1",children:r("settings.coordinatorPrompts.overrideLabel")}),n.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-xs font-mono text-text-primary",rows:4,value:I.override,onChange:T=>i(F=>({...F,[N]:{...F[N],override:T.target.value}})),placeholder:r("settings.coordinatorPrompts.overridePlaceholder"),disabled:h===`${N}:override`}),n.jsx("div",{className:"mb-3"}),n.jsx("label",{className:"block text-2xs uppercase tracking-wide text-text-muted mb-1",children:r("settings.coordinatorPrompts.appendLabel")}),n.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-xs font-mono text-text-primary",rows:3,value:I.append,onChange:T=>i(F=>({...F,[N]:{...F[N],append:T.target.value}})),placeholder:r("settings.coordinatorPrompts.appendPlaceholder"),disabled:h===`${N}:append`}),n.jsx("div",{className:"mt-2 flex justify-end",children:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm","data-testid":"coordinator-prompt-save",onClick:()=>void A(N),disabled:!!(h!=null&&h.startsWith(`${N}:`))||!B,children:h!=null&&h.startsWith(`${N}:`)?r("settings.coordinatorPrompts.saving"):r(B?"settings.coordinatorPrompts.save":"settings.coordinatorPrompts.saved")})})]})}})})]}):n.jsxs("div",{className:"flex flex-col gap-3",children:[g&&n.jsx("div",{className:"text-xs text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:g}),n.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[n.jsx("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5 text-xs text-text-muted",children:u?n.jsx("span",{children:r("settings.coordinatorPrompts.loading")}):M.length===0?n.jsx("span",{children:r("settings.coordinatorPrompts.collapsedNone")}):n.jsxs(n.Fragment,{children:[n.jsxs("span",{children:[r("settings.coordinatorPrompts.customizedBadge"),":"]}),M.map(N=>n.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-accent-primary/10 px-1.5 py-0.5 font-mono text-2xs text-accent-primary",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-accent-primary","aria-hidden":!0}),N]},N))]})}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>j(!0),children:r("settings.coordinatorPrompts.expandLabel")})]})]}):n.jsx("div",{className:"text-xs text-text-muted",children:r("settings.coordinatorPrompts.connectDaemon")})}const gT=[{id:"dark",labelKey:"settings.appearance.modeDark",icon:Zp},{id:"light",labelKey:"settings.appearance.modeLight",icon:Xp},{id:"system",labelKey:"settings.appearance.modeSystem",icon:ef}];function bT(){const{preference:e,setPreference:t}=Uo(),{t:s}=ve("common");return n.jsx("div",{className:"flex gap-2",children:gT.map(r=>n.jsxs("button",{onClick:()=>t(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[n.jsx(r.icon,{size:14}),s(r.labelKey)]},r.id))})}function xT(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function yT(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Sl(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function ih(e){const{r:t,g:s,b:r}=yT(e);return .2126*Sl(t)+.7152*Sl(s)+.0722*Sl(r)}function lh(e,t){const s=ih(e),r=ih(t),o=Math.max(s,r),a=Math.min(s,r);return(o+.05)/(a+.05)}function vb(e){const t=xT(e);if(!t)return"#111827";const s="#111827",r="#ffffff";return lh(t,s)>=lh(t,r)?s:r}const $c={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},Fc={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},vT=[{id:"midnight",name:"Midnight",description:"Classic violet theme",preview:{dark:{userBubble:"#8b5cf6",assistantBubble:"#18181d",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0f0f13",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#7c3aed",assistantBubble:"#ffffff",assistantBorder:"1px solid rgba(0,0,0,0.08)",containerBg:"#f0f1f5",textColor:"#52525b"}}},{id:"ember",name:"Ember",description:"Default landing-inspired amber theme",preview:{dark:{userBubble:"#f59e0b",assistantBubble:"#111726",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0a0e1a",textColor:"#9ca3af"},light:{userBubble:"#f59e0b",assistantBubble:"#fffaf4",assistantBorder:"1px solid rgba(146,64,14,0.10)",containerBg:"#fff8ee",textColor:"#6f6255"}}},{id:"aurora",name:"Aurora",description:"Pink accent theme",preview:{dark:{userBubble:"#ec4899",assistantBubble:"#1e1b2e",assistantBorder:"1px solid rgba(236,72,153,0.12)",containerBg:"#0f0d17",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#ec4899",assistantBubble:"#fef2f8",assistantBorder:"1px solid rgba(236,72,153,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}},{id:"honey",name:"Honey",description:"Warm yellow accents",preview:{dark:{userBubble:"#fbbf24",assistantBubble:"#1c1c1e",assistantBorder:"1px solid rgba(255,255,255,0.06)",containerBg:"#111113",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#fbbf24",assistantBubble:"#fffbeb",assistantBorder:"1px solid rgba(251,191,36,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}}],wb="adhdev-chat-theme",Sb="adhdev-chat-theme-custom";function La(){if(typeof window>"u")return"ember";try{return localStorage.getItem(wb)||"ember"}catch{return"ember"}}function En(e){try{const t=localStorage.getItem(Sb);if(t){const s=JSON.parse(t);return{...e==="dark"?$c:Fc,...s[e]}}}catch{}return e==="dark"?$c:Fc}function ua(e,t){try{localStorage.setItem(Sb,JSON.stringify({dark:e,light:t}))}catch{}}function jn(e,t){const s=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16);return`rgba(${s}, ${r}, ${o}, ${t})`}function ai(e,t){const s=Math.min(255,parseInt(e.slice(1,3),16)+t),r=Math.min(255,parseInt(e.slice(3,5),16)+t),o=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${s.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}const wT={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ko(e,t){var o;const s=(o=wT[e])==null?void 0:o[t];if(!s)return;const r=document.documentElement;r.style.setProperty("--accent-primary",s),r.style.setProperty("--accent-primary-light",ai(s,24)),r.style.setProperty("--accent-on-primary",vb(s)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${s}, ${ai(s,18)})`),r.style.setProperty("--border-accent",jn(s,.35)),r.style.setProperty("--nav-active-bg",jn(s,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${s}, 0 0 12px ${jn(s,.06)}`)}function Vs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",jn(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",jn(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",jn(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",jn(e.borderSubtle,.5)),t.style.setProperty("--border-default",jn(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",ai(e.accentColor,30)),t.style.setProperty("--accent-on-primary",vb(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${ai(e.accentColor,40)})`),t.style.setProperty("--border-accent",jn(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",jn(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${jn(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${jn(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Yd(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(s=>e.style.removeProperty(s))}function ST(e){try{localStorage.setItem(wb,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Ys()?"dark":"light";Vs(En(t))}else Yd(),ko(e,Ys()?"dark":"light")}function kT(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=La();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Ys()?"dark":"light";Vs(En(t))}else Yd(),ko(e,Ys()?"dark":"light")}function Ys(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Xt({label:e,value:t,onChange:s}){return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[n.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[n.jsx("input",{type:"color",value:t,onChange:r=>s(r.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),n.jsx("input",{type:"text",value:t,onChange:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&s(r.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function no({title:e,children:t}){return n.jsxs("div",{style:{marginBottom:14},children:[n.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function jT({dark:e,onColorsChange:t}){const{t:s}=ve("common"),r=e?"dark":"light",[o,a]=l.useState(()=>En(r));l.useEffect(()=>{a(En(r))},[r]);const i=l.useCallback((c,d)=>{a(u=>{const m={...u,[c]:d},p=En(r==="dark"?"light":"dark");return r==="dark"?ua(m,p):ua(p,m),Vs(m),t(m),m})},[r,t]);return n.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[n.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[s("settings.theme.customEditorTitle"),n.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:s(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[n.jsxs("div",{children:[n.jsxs(no,{title:s("settings.theme.sectionAppBackground"),children:[n.jsx(Xt,{label:s("settings.theme.colorBackground"),value:o.bgPrimary,onChange:c=>i("bgPrimary",c)}),n.jsx(Xt,{label:s("settings.theme.colorSurface"),value:o.bgSecondary,onChange:c=>i("bgSecondary",c)}),n.jsx(Xt,{label:s("settings.theme.colorCard"),value:o.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),n.jsxs(no,{title:s("settings.theme.sectionAppText"),children:[n.jsx(Xt,{label:s("settings.theme.colorPrimary"),value:o.textPrimary,onChange:c=>i("textPrimary",c)}),n.jsx(Xt,{label:s("settings.theme.colorSecondary"),value:o.textSecondary,onChange:c=>i("textSecondary",c)}),n.jsx(Xt,{label:s("settings.theme.colorMuted"),value:o.textMuted,onChange:c=>i("textMuted",c)})]}),n.jsxs(no,{title:s("settings.theme.sectionBordersAccent"),children:[n.jsx(Xt,{label:s("settings.theme.colorBorderSubtle"),value:o.borderSubtle,onChange:c=>i("borderSubtle",c)}),n.jsx(Xt,{label:s("settings.theme.colorBorderDefault"),value:o.borderDefault,onChange:c=>i("borderDefault",c)}),n.jsx(Xt,{label:s("settings.theme.colorAccent"),value:o.accentColor,onChange:c=>i("accentColor",c)})]})]}),n.jsxs("div",{children:[n.jsxs(no,{title:s("settings.theme.sectionChatBubbles"),children:[n.jsx(Xt,{label:s("settings.theme.colorUserBubble"),value:o.userBubble,onChange:c=>i("userBubble",c)}),n.jsx(Xt,{label:s("settings.theme.colorUserText"),value:o.userText,onChange:c=>i("userText",c)}),n.jsx(Xt,{label:s("settings.theme.colorAgentBubble"),value:o.assistantBubble,onChange:c=>i("assistantBubble",c)}),n.jsx(Xt,{label:s("settings.theme.colorAgentText"),value:o.assistantText,onChange:c=>i("assistantText",c)})]}),n.jsxs(no,{title:s("settings.theme.sectionChatLayout"),children:[n.jsx(Xt,{label:s("settings.theme.colorChatBg"),value:o.containerBg,onChange:c=>i("containerBg",c)}),n.jsx(Xt,{label:s("settings.theme.colorSendButton"),value:o.sendButton,onChange:c=>i("sendButton",c)}),n.jsx(Xt,{label:s("settings.theme.colorInputBorder"),value:o.inputBorder,onChange:c=>i("inputBorder",c)}),n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[n.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:s("settings.theme.labelBubbleRadius")}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[n.jsx("input",{type:"range",min:4,max:24,value:o.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),n.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[o.bubbleRadius,"px"]})]})]})]})]})]}),n.jsx("button",{onClick:()=>{const c=e?$c:Fc,u=En(e?"light":"dark");e?ua(c,u):ua(u,c),a(c),Vs(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:s("settings.theme.resetToDefaults")})]})}function NT(){const{t:e}=ve("common"),[t,s]=l.useState(La),[r,o]=l.useState(!0),[a,i]=l.useState(()=>En("dark"));l.useEffect(()=>{o(Ys());const u=new MutationObserver(()=>{const p=Ys();o(p);const g=La();g==="custom"?Vs(En(p?"dark":"light")):ko(g,p?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),h=()=>{const p=Ys();o(p);const g=La();g==="custom"?Vs(En(p?"dark":"light")):ko(g,p?"dark":"light")};return m.addEventListener("change",h),()=>{u.disconnect(),m.removeEventListener("change",h)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Vs(En(r?"dark":"light")):(Yd(),ko(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(En(r?"dark":"light"))},[r]);const c=u=>{s(u),ST(u)},d=[...vT,{id:"custom",name:"Custom",description:e("settings.theme.presetCustomDescription"),preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return n.jsxs("div",{children:[n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(u=>{const m=t===u.id,h=r?u.preview.dark:u.preview.light,p=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return n.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[n.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:h.containerBg},children:[n.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-3xs max-w-[75%]",style:{background:h.assistantBubble,border:h.assistantBorder,color:h.textColor},children:e("settings.theme.helloHelp")}),n.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-3xs max-w-[75%]",style:{background:h.userBubble,color:p},children:e("settings.theme.fixBug")}),n.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-3xs max-w-[75%]",style:{background:h.assistantBubble,border:h.assistantBorder,color:h.textColor},children:e("settings.theme.onIt")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[m&&n.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?e("settings.theme.customLabel"):u.name}),n.jsx("div",{className:"text-3xs text-text-muted",children:u.id==="custom"?u.description:e(`settings.theme.preset.${u.id}`,{defaultValue:u.description})})]})]})]},u.id)})}),t==="custom"&&n.jsx(jT,{dark:r,onColorsChange:u=>i(u)})]})}const Qd="adhdev_mobileDashboardMode_v1",Hc="adhdev:mobile-dashboard-mode-change";function Jd(){try{return localStorage.getItem(Qd)==="workspace"?"workspace":"chat"}catch{return"chat"}}function CT(e){if(typeof window>"u")return()=>{};const t=o=>{e(o??Jd())},s=o=>{const a=o.detail;t(a)},r=o=>{o.key&&o.key!==Qd||t()};return window.addEventListener(Hc,s),window.addEventListener("storage",r),()=>{window.removeEventListener(Hc,s),window.removeEventListener("storage",r)}}function _T(e){try{localStorage.setItem(Qd,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Hc,{detail:e}))}function AT(){const{t:e}=ve("common"),[t,s]=l.useState(!0);return l.useEffect(()=>{s(Jd()==="chat")},[]),n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Jn,{size:15})," ",e("settings.mobileMode.label")]}),description:e(t?"settings.mobileMode.descriptionChat":"settings.mobileMode.descriptionWorkspace"),checked:t,onChange:r=>{s(r),_T(r?"chat":"workspace")},extra:n.jsx("span",{className:"text-2xs text-text-muted",children:e(t?"settings.mobileMode.chatMode":"settings.mobileMode.workspaceMode")})})}function TT(){const{t:e}=ve("common"),[t,s]=l.useState(()=>qs());return l.useEffect(()=>yd(s),[]),n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Jp,{size:15})," ",e("settings.chatActivity.rowLabel")]}),description:e(t?"settings.chatActivity.descriptionOn":"settings.chatActivity.descriptionOff"),checked:t,onChange:r=>{s(r),uf(r)}})}function IT({fontsSlot:e}){const{t}=ve("common");return n.jsxs("div",{className:"flex flex-col gap-5",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:t("settings.appearance.modeLabel")}),n.jsx(bT,{})]}),n.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[n.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:t("settings.appearance.themeLabel")}),n.jsx(NT,{})]}),n.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[n.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:t("settings.appearance.chatLabel")}),n.jsx(TT,{})]}),e,n.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[n.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:t("settings.appearance.mobileLabel")}),n.jsx(AT,{})]})]})}function MT({children:e,fallback:t=null}){const[s,r]=l.useState(ej);return l.useEffect(()=>{if(s)return;let o=!0;return tj().then(()=>{o&&r(!0)}),()=>{o=!1}},[s]),n.jsx(n.Fragment,{children:s?e:t})}const kl=new Map,ch=new Map;function RT(e){if(!e||typeof e!="object")return null;const t=e,s=t.result&&typeof t.result=="object"?t.result:t,r=s.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof s.timestamp=="number"?s.timestamp:void 0}}function PT(e,t,s,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r,platform:s.platform,machine:s}}function kb(){const{sendCommand:e}=_t(),{injectEntries:t,getIdes:s}=Ar();return l.useCallback(async(r,o)=>{if(!r)return;const a=(o==null?void 0:o.minFreshMs)??uC,i=ch.get(r)||0;if(!(o!=null&&o.force)&&i>0&&Date.now()-i<a)return;const c=kl.get(r);if(c)return c;const d=(async()=>{const u=await e(r,"get_machine_runtime_stats"),m=RT(u);if(!m)return;const h=s().find(g=>g.id===r),p=PT(h,r,m.machine,m.timestamp||Date.now());t([p]),ch.set(r,Date.now())})().finally(()=>{kl.delete(r)});return kl.set(r,d),d},[s,t,e])}function LT(e,t,s){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:s.timestamp,platform:s.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...s.machine}}}function ET(e,t){const{sendData:s}=_t(),{injectEntries:r,getIdes:o}=Ar(),a=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!s)return;const i=a?a.split("|"):[];if(i.length===0)return;const c=i.map(d=>_n.subscribe({sendData:s},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},m=>{const h=o().find(g=>g.id===d),p=LT(h,d,m);r([p])}));return()=>{c.forEach(d=>d())}},[a,o,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,s])}function DT(e,t){const{sendData:s}=_t(),[r,o]=l.useState(null),[a,i]=l.useState(!1);return l.useEffect(()=>{if(!e){o(null),i(!1);return}if(!(t!=null&&t.enabled)||!s){i(!1);return}o(null),i(!0);let c=null;const d=_n.subscribe({sendData:s},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},u=>{c&&(clearTimeout(c),c=null),o(u.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},pC):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,s]),{diagnostics:r,loading:a,applyDiagnostics:o}}function dh(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function jb(e){const{sendData:t,isConnected:s}=_t(),[r,o]=l.useState({}),a=l.useRef(null);return l.useEffect(()=>{const i=dh(e);if(!i||!e.sessionId||!t){o({});return}const c=_n.subscribe({sendData:t},i,{type:"subscribe",topic:"session.modal",key:`daemon:${i}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},d=>{o({status:d.status,modalMessage:d.modalMessage,modalButtons:d.modalButtons}),Xs.record({interactionId:d.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:d.status,modalButtonCount:Array.isArray(d.modalButtons)?d.modalButtons.length:0}})});return c.initialSendAccepted||o({}),a.current=()=>{_n.resubscribeForDaemon(i,{sendData:t}),Xs.record({kind:"dashboard.session_modal_resync",topic:"session.modal",payload:{sessionId:e.sessionId}})},()=>{a.current=null,c()}},[e.daemonId,e.routeId,e.sessionId,t]),l.useEffect(()=>{const i=dh(e);if(!i||!e.sessionId||!t)return;const c=()=>{var p;return(p=a.current)==null?void 0:p.call(a)},d=()=>{typeof document>"u"||document.visibilityState==="visible"&&c()},u=p=>{p.persisted&&c()};typeof document<"u"&&document.addEventListener("visibilitychange",d),typeof window<"u"&&window.addEventListener("pageshow",u);let m=s?s(i):!0;const h=()=>{if(!s)return;const p=s(i);p&&!m&&c(),m=p};return typeof document<"u"&&document.addEventListener("visibilitychange",h),typeof window<"u"&&window.addEventListener("online",h),()=>{typeof document<"u"&&(document.removeEventListener("visibilitychange",d),document.removeEventListener("visibilitychange",h)),typeof window<"u"&&(window.removeEventListener("pageshow",u),window.removeEventListener("online",h))}},[e.daemonId,e.routeId,e.sessionId,t,s]),r}function Nb(e){return e instanceof Error?e.message:String(e||"")}function OT(e){const t=Nb(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function $T(e){const t=Nb(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Cb({conversation:e,mode:t,ides:s,sendDaemonCommand:r,setCliViewModeOverrides:o}){if(!e||!St(e)||vt(e))return;const a=Hr(e);if(a===t)return;const i=e.sessionId;i&&o(c=>({...c,[i]:t}));try{await r(as(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Vn(e),mode:t})}catch(c){const d=$T(c);i&&!d&&o(u=>{const m={...u};return a===HT(s,i)?delete m[i]:m[i]=a,m}),OT(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function uh(e,t){const s=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!s||e.transport!=="pty")return e;const r=t[s];return!r||e.mode===r?e:{...e,mode:r}}function FT(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let s=!1;const r=e.map(o=>{const a=uh(o,t),i=Array.isArray(o.childSessions)?o.childSessions.map(d=>uh(d,t)):o.childSessions,c=i!==o.childSessions;return a!==o||c?(s=!0,{...a,...c?{childSessions:i}:{}}):o});return s?r:e}function HT(e,t){if(!t)return null;for(const s of e){if(s.sessionId===t&&s.transport==="pty")return s.mode==="chat"?"chat":"terminal";for(const r of s.childSessions||[])if(r.id===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal"}return null}function BT({visibleConversations:e,clearedTabs:t,setClearedTabs:s,setActionLogs:r,isConversationMuted:o}){l.useEffect(()=>{Wf()},[]);const a=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Fg(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:o?o(i):!1})),[e,o]);return Tj(a),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{s(d=>{const u=Date.now(),m={};for(const[h,p]of Object.entries(d))u-p<5e3&&(m[h]=p);return Object.keys(m).length===Object.keys(d).length?d:m})},5500);return()=>clearTimeout(c)},[t,s]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;r(d=>{const u=d.filter(m=>m.timestamp>c).slice(-100);return u.length===d.length?d:u})},6e4);return()=>clearInterval(i)},[r]),null}function mh(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Qs(e){const t=[...e.messages].reverse().find(o=>!(o!=null&&o._localId))||e.messages[e.messages.length-1],s=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=mh(t==null?void 0:t.receivedAt)||mh(t==null?void 0:t.timestamp)||0;return Math.max(s,r)}function Bc(e,t=0){return Qs(e)||e.lastUpdated||t||0}function _b(e){return Qs(e)||e.lastUpdated||0}function Ab(e,t,s=_b){const r=s(t)-s(e);if(r!==0)return r;const o=(e.machineName||"").localeCompare(t.machineName||"");if(o!==0)return o;const a=e.displayPrimary.localeCompare(t.displayPrimary);if(a!==0)return a;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function Wc(e){var s;const t=vn(e.status,{activeModal:(s=e.modalButtons)!=null&&s.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function WT(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Wc(e)&&!e.title.trim()}function UT(e){return e.length===0?null:[...e].sort((t,s)=>{const r=Number(Wc(s))-Number(Wc(t));if(r!==0)return r;const o=s.messages.length-t.messages.length;return o!==0?o:Ab(t,s)})[0]||null}function $n(e,t){const s=e.filter(i=>i.routeId===t);if(s.length===0)return null;const r=s.find(i=>i.streamSource==="native")||null,o=s.filter(i=>i.streamSource==="agent-stream"),a=UT(o);return r?a&&WT(r)?a:r:a||s[0]||null}function KT(e){const t=e.filter(o=>o.type!=="adhdev-daemon"),s=new Set;for(const o of t){if(!vc(o))continue;const a=Df(o);a&&s.add(a)}const r=new Map;for(const o of t){const a=rj(o,s),i=r.get(a);if(!i){r.set(a,o);continue}const c=h=>(h.workspace?1:0)+(h.activeChat?1:0)+(h.lastMessagePreview?1:0),d=c(i),u=c(o),m=u>d||u===d&&(o.timestamp||0)>(i.timestamp||0)?o:i;r.set(a,qT(m,m===o?i:o))}return Array.from(r.values())}function qT(e,t){const s=vc(t),r=vc(e);if(!s&&!r)return e;const o=r?s?void 0:t:e,a=r?e:s?t:void 0,i=o&&String(o.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=a==null?void 0:a.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!r&&{settings:{...d,...e.settings??{}}}}}function jl(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}function zT(e){let t=2166136261;for(let s=0;s<e.length;s+=1)t^=e.charCodeAt(s),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function hh(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],s=t[t.length-1],r=s?zT(_r(s.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((s==null?void 0:s.id)||""),String((s==null?void 0:s.index)??""),String((s==null?void 0:s.receivedAt)??(s==null?void 0:s.timestamp)??""),r].join(":")}function GT(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),hh(e.activeChat),...t.map(s=>[s.id||"",s.providerSessionId||"",s.transport||"",s.mode||"",s.status||"",s.title||"",s.lastMessageHash||"",String(s.lastMessageAt||""),s.lastMessagePreview||"",s.lastMessageRole||"",String(s.lastUpdated||""),hh(s.activeChat)].join(":"))].join("|")}function VT(e,t){const s=Date.now();return e.map(r=>{const o=t[r.tabKey];return o&&s-o<5e3?{...r,messages:[],title:""}:r})}function YT(e,t){const s=new Map;for(const r of e){const o=t.get(r.routeId)||r;for(const a of vo({routeId:r.routeId}))s.set(a,o);for(const a of vo({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))s.set(a,r.streamSource==="native"?o:r);for(const a of vo({tabKey:r.tabKey}))s.set(a,r)}return s}function QT(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function JT(e){const t=QT(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const s=String(t.role||""),r=_r(t.content).slice(0,240);return`${e.messages.length}:${s}:${r}`}function XT({ides:e,connectionStates:t,clearedTabs:s}){const r=l.useMemo(()=>KT(e),[e]),o=l.useMemo(()=>_f(e),[e]),a=l.useMemo(()=>cb(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),u=l.useRef(new Map),m=l.useRef(new Map),h=l.useMemo(()=>{const _=new Map,y=[];for(const A of r){const{connectionState:O="new",machineName:L}=db(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),M=GT(A),$=u.current.get(A.id);if($&&$.ide===A&&$.sourceSignature===M&&$.connectionState===O&&$.machineName===L){_.set(A.id,$),y.push(...$.conversations);continue}const N=Gd(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),I={ide:A,sourceSignature:M,connectionState:O,machineName:L,conversations:N};_.set(A.id,I),y.push(...N)}u.current=_;const w=new Map,S=A=>{const O=JT(A),L=m.current.get(A.tabKey);if(L&&L.signature===O)return w.set(A.tabKey,L),L.timestamp;const M={signature:O,timestamp:_b(A)||(L==null?void 0:L.timestamp)||0};return w.set(A.tabKey,M),M.timestamp},C=[...y].sort((A,O)=>Ab(A,O,S));return m.current=w,C},[r,t,a]),p=l.useMemo(()=>{const _=VT(h,s);return jl(i.current,_)?i.current:(i.current=_,_)},[h,s]),g=l.useMemo(()=>{const _=new Map,y=Array.from(new Set(p.map(w=>w.routeId)));for(const w of y){const S=$n(p,w);S&&_.set(w,S)}return _},[p]),f=l.useMemo(()=>{const _=new Map;for(const y of p){const w=g.get(y.routeId),S=y.streamSource==="native"&&w?w:y;for(const C of vo({providerSessionId:y.providerSessionId,sessionId:y.sessionId,tabKey:y.tabKey}))_.set(C,S)}return _},[p,g]),x=l.useMemo(()=>YT(p,g),[p,g]),b=l.useCallback(_=>{if(_)return f.get(_)},[f]),k=l.useCallback(_=>{if(_)return x.get(_)},[x]),j=l.useMemo(()=>{const _=p.filter(y=>!Ns(y,o).surfaceHidden);return jl(c.current,_)?c.current:(c.current=_,_)},[p,o]),v=l.useMemo(()=>{const _=j.map(y=>y.tabKey);return jl(d.current,_)?d.current:(d.current=_,_)},[j]);return{chatIdes:r,conversations:p,visibleConversations:j,visibleTabKeys:v,resolveConversationBySessionId:b,resolveConversationByTarget:k}}function ZT({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:s,setSearchParams:r}){const o=l.useMemo(()=>{var c;return e||!t?null:((c=s(t))==null?void 0:c.tabKey)??null},[e,s,t]),a=l.useMemo(()=>{var c;return!e||!t?null:((c=s(t))==null?void 0:c.tabKey)??null},[e,s,t]),i=l.useCallback(()=>{t&&r(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[r,t]);return{requestedDesktopTabKey:o,requestedMobileTabKey:a,consumeRequestedActiveTab:i}}function e2({ides:e,sendDaemonCommand:t,setToasts:s,resolveConversationByTarget:r,hydrateInteractivePrompt:o}){l.useEffect(()=>{ct.setIdes(e)},[e]),l.useEffect(()=>{ct.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),l.useEffect(()=>{ct.setHydrateInteractivePrompt(o)},[o]),l.useEffect(()=>{const a=ct.onToast(i=>{s(d=>d.some(m=>m.message===i.message&&i.timestamp-m.timestamp<3e3)?d:[...d.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions,details:i.details}]);const c=i.duration||5e3;setTimeout(()=>s(d=>d.filter(u=>u.id!==i.id||u.pinned)),c)});return()=>{a()}},[s]),l.useEffect(()=>{const a=Yf.on("status_event",i=>{ct.handleRawEvent(i,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var i;const a=c=>{var b;const d=c.data;if((d==null?void 0:d.type)!=="notification_action"||typeof d.action!="string"||!d.action.startsWith("approval_")||!(d.daemonId||d.targetSessionId||d.targetKey))return;const u=d.targetSessionId||d.targetKey||d.daemonId,m=r(u),h=(m==null?void 0:m.routeId)||d.daemonId;if(!h)return;const p=Number(d.buttonIndex),g=d.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[p])||"Approve",f=String(g).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),x=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(f);t(h,"resolve_action",{action:x?"approve":"reject",button:g,...Number.isFinite(p)&&{buttonIndex:p},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...d.targetSessionId&&{targetSessionId:d.targetSessionId}}).catch(k=>console.error("[SW Action] approval failed:",k))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[r,t])}const t2="adhdev_dashboardLayout_v1",n2="adhdev_dashboardDockview_v1",s2="adhdev_dashboardDockviewHiddenRestore_v1",so={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Xd(e,t){try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}}function r2(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Tb(e){return`${t2}:${e}`}function o2(e){const t=Tb(e);return Xd(t,null)}function a2(e,t){try{const s=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,r=Tb(e);if(s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Ib(e){return`${n2}:${e}`}function i2(e){const t=Ib(e);return Xd(t,null)}function l2(e,t){try{const s=Ib(e);if(!t){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function Mb(e){return`${s2}:${e}`}function c2(e){const t=Mb(e);return Xd(t,{})}function d2(e,t){try{const s=Mb(e);if(Object.keys(t).length===0){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function u2(){return{groupAssignments:[...so.groupAssignments],focusedGroup:so.focusedGroup,groupActiveTabIds:{...so.groupActiveTabIds},groupTabOrders:{...so.groupTabOrders},groupSizes:[...so.groupSizes]}}function m2(e,t){return e?e.length===t.length&&e.every((s,r)=>s===t[r]):t.length===0}function h2(){const[e]=l.useState(()=>r2(typeof window<"u"?window.innerWidth:1280)),[t,s]=l.useState(()=>new Map),[r,o]=l.useState(0),[a,i]=l.useState({}),[c,d]=l.useState({}),[u,m]=l.useState([]),[h,p]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,f]=l.useState(!1),x=l.useCallback(()=>{if(g)return;const A=o2(e)??u2();s(new Map(A.groupAssignments)),o(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),m(A.groupSizes),f(!0)},[g,e]);l.useEffect(()=>{g&&a2(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:a,groupTabOrders:c,groupSizes:u})},[g,e,t,r,a,c,u]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),O=L=>p(L.matches);return A.addEventListener("change",O),()=>A.removeEventListener("change",O)},[]);const b=l.useCallback(A=>{s(A)},[]),k=l.useCallback(A=>{o(A)},[]),j=l.useCallback(A=>{i(A)},[]),v=l.useCallback(A=>{d(A)},[]),_=l.useCallback(A=>{m(A)},[]),y=l.useCallback(A=>{k(A)},[k]),w=l.useCallback((A,O)=>{i(L=>(L[A]??null)===(O??null)?L:{...L,[A]:O})},[]),S=l.useCallback((A,O)=>{d(L=>{const M=L[A];return m2(M,O)?L:{...L,[A]:O}})},[]),C=l.useCallback((A,O)=>{const L=O.get(A)??0;return w(L,A),y(L),L},[y,w]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:b,focusedGroup:r,updateFocusedGroup:k,focusGroup:y,groupActiveTabIds:a,updateGroupActiveTabIds:j,setGroupActiveTab:w,groupTabOrders:c,updateGroupTabOrders:v,setGroupTabOrder:S,groupSizes:u,updateGroupSizes:_,isMobile:h,hasHydratedStoredLayout:g,hydrateStoredLayout:x,focusConversationTab:C}}function p2(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const s=e[0],r=Ai(t);return typeof(s==null?void 0:s.id)=="string"&&r.includes(s.id)}function f2({urlActiveTab:e,conversations:t,resolveConversationBySessionId:s,normalizedGroupAssignments:r,hasHydratedStoredLayout:o,hydrateStoredLayout:a,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:u,isRefreshingHistory:m,ides:h,handleRefreshHistory:p}){const g=l.useRef(!1),f=l.useRef(!1),x=l.useRef(null),b=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!o){a();return}const k=s(e);k&&(i(k.tabKey,r),g.current=!0,f.current=!0,x.current!=null&&(window.clearTimeout(x.current),x.current=null),c(j=>{const v=new URLSearchParams(j);return v.delete("activeTab"),v},{replace:!0}))},[e,t,s,r,o,a,i,c]),l.useEffect(()=>{if(!(f.current||o)&&t.length!==0){if(!e){a(),f.current=!0;return}if(g.current){f.current=!0;return}if(x.current==null)return x.current=window.setTimeout(()=>{x.current=null,!(f.current||o)&&(a(),f.current=!0)},1500),()=>{x.current!=null&&(window.clearTimeout(x.current),x.current=null)}}},[e,t.length,o,a]),l.useEffect(()=>{if(!d){b.current=!1;return}if(!u||b.current||m)return;const k=h.find(j=>j.id===u.routeId);k&&(!k.chats||k.chats.length===0||p2(k.chats,u))&&(b.current=!0,p())},[d,u,m,h,p])}function Nl(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const s=e[0];if((s==null?void 0:s.active)===!0)return!0;const r=Ai(t);return typeof(s==null?void 0:s.id)=="string"&&r.includes(s.id)}function Rb({sendDaemonCommand:e,activeConv:t,chats:s,updateRouteChats:r,setToasts:o,setClearedTabs:a}){const[i,c]=l.useState(!1),[d,u]=l.useState(!1),m=l.useCallback(async f=>{try{await e("standalone","launch_ide",{ideType:f,enableCdp:!0})}catch(x){console.error("Launch failed",x)}},[e]),h=l.useCallback(async(f,x)=>{try{const b=f||(t==null?void 0:t.daemonId)||"",k=await e(b,"switch_chat",{id:x,sessionId:x,...ks(t)}),j=k==null?void 0:k.result;if((k==null?void 0:k.success)===!0||j==="switched"||j==="switched-by-title")return;j===!1||j==="not_found"?yr(o,"⚠️ Session tab not found — try refreshing history"):typeof j=="string"&&j.startsWith("error:")?yr(o,`⚠️ Switch error: ${j}`):yr(o,"⚠️ Session switch failed")}catch(b){console.error("Switch failed",b),yr(o,`❌ Switch failed: ${b.message||"connection error"}`)}},[t,e,o]),p=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const f=vs(t);await e(f,"new_chat",{...ks(t)}),qC(f,t.sessionId,Ai(t)[0]),a(x=>({...x,[t.tabKey]:Date.now()}))}catch(f){console.error("New chat failed",f)}finally{c(!1)}}},[t,i,e,a]),g=l.useCallback(async()=>{var f,x;if(!(!t||d)){u(!0);try{const b=vs(t),k=async()=>e(b,"list_chats",{forceExpand:!0,...ks(t)});let j=await k(),v=(j==null?void 0:j.chats)||((f=j==null?void 0:j.result)==null?void 0:f.chats);Nl(v,t)&&(await new Promise(_=>setTimeout(_,450)),j=await k(),v=(j==null?void 0:j.chats)||((x=j==null?void 0:j.result)==null?void 0:x.chats)),j!=null&&j.success&&Array.isArray(v)&&(r(t.routeId,v),Nl(v,t)&&!Nl(s,t)&&yr(o,"⚠️ History dialog did not fully open — try once more"))}catch(b){console.error("Refresh history failed",b)}finally{u(!1)}}},[t,s,d,e,r,o]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:m,handleSwitchSession:h,handleNewChat:p,handleRefreshHistory:g}}function g2(e,t){if(e.size!==t.size)return!1;for(const[s,r]of e)if(t.get(s)!==r)return!1;return!0}function b2(e,t){return e.length!==t.length?!1:e.every((s,r)=>s===t[r])}function ph(e,t){const s=Object.keys(e),r=Object.keys(t);return s.length!==r.length?!1:s.every(o=>t[Number(o)]===e[Number(o)])}function ma(e,t){const s=new Set(t),r=t.length>0?[0]:[];for(const[i,c]of e)!s.has(i)||c<=0||r.includes(c)||r.push(c);r.sort((i,c)=>i-c);const o={};r.forEach((i,c)=>{o[i]=c}),r.length===0&&(o[0]=0);const a=new Map;for(const[i,c]of e){if(!s.has(i)||c<=0)continue;const d=o[c];typeof d=="number"&&d>0&&a.set(i,d)}return{assignments:a,groupCount:Math.max(1,r.length),mapping:o,usedGroups:r}}function fh(e,t){const s={};for(const[r,o]of Object.entries(e)){const a=t[Number(r)];typeof a=="number"&&(s[a]=o)}return s}function x2(e,t,s){if(t.length===0)return 0;if(typeof s[e]=="number")return s[e];const r=[...t].reverse().find(o=>o<e)??t[0];return s[r]??0}function y2(e,t,s){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),o=r.length===t.length?r:Array(s).fill(100/s),a=o.reduce((i,c)=>i+c,0);return a>0?o.map(i=>i/a*100):Array(s).fill(100/s)}function gh(e,t){const s={};for(const[r,o]of Object.entries(e)){const a=Number(r);s[a>=t?a+1:a]=o}return s}function bh(e){return Array(e).fill(100/e)}function v2({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:s,updateGroupActiveTabIds:r,updateGroupTabOrders:o,groupSizes:a,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:u}){const m=l.useRef(null),h=l.useMemo(()=>ma(e,u),[e,u]),p=h.assignments,g=l.useMemo(()=>c?1:h.groupCount,[h.groupCount,c]),f=g>1,x=l.useCallback((y,w)=>{t(S=>{const C=new Map(ma(S,u).assignments);return w===0?C.delete(y):C.set(y,w),C}),r(S=>({...S,[w]:y})),s(w)},[t,u,r,s]),b=l.useCallback(y=>{t(w=>{const S=ma(w,u).assignments,C=new Map;for(const[A,O]of S)O!==y&&(O>y?C.set(A,O-1):C.set(A,O));return C}),i(w=>{if(w.length<=1)return[];const S=[...w];S.splice(y,1);const C=S.reduce((A,O)=>A+O,0);return C>0?S.map(A=>A/C*100):[]}),s(0)},[t,u,i,s]),k=l.useCallback((y,w)=>{w.preventDefault();const S=m.current;if(!S)return;const C=w.clientX,A=S.offsetWidth,O=a.length===g?[...a]:bh(g),L=$=>{const I=($.clientX-C)/A*100,B=[...O];B[y]=Math.max(15,O[y]+I),B[y+1]=Math.max(15,O[y+1]-I),i(B)},M=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",M)},[a,g,i]),j=l.useCallback((y,w,S)=>{if(g>=4)return;const C=S==="left"?w:w+1;t(A=>{const O=ma(A,u).assignments,L=new Map;for(const M of d){const $=O.get(M.tabKey)??0,N=$>=C?$+1:$;N>0&&L.set(M.tabKey,N)}return C>0&&L.set(y,C),L}),i(A=>{const O=A.length===g?[...A]:bh(g),L=O[w]??100/g,M=Math.max(15,L/2),$=Math.max(15,L/2),N=[...O];N[w]=M,N.splice(C,0,$);const I=N.reduce((B,T)=>B+T,0);return N.map(B=>B/I*100)}),r(A=>{const O=gh(A,C);return O[C]=y,O}),o(A=>{const O=gh(A,C);return O[C]=[y],O}),s(C)},[g,t,u,d,i,r,o,s]);l.useEffect(()=>{g2(e,p)||t(p)},[e,p,t]),l.useEffect(()=>{const{mapping:y,usedGroups:w}=h;r(S=>{const C=fh(S,y);return ph(S,C)?S:C}),o(S=>{const C=fh(S,y);return ph(S,C)?S:C}),s(S=>{const C=c?0:x2(S,w,y);return S===C?S:C}),i(S=>{const C=c?[]:y2(S,w,h.groupCount);return b2(S,C)?S:C})},[h,c,r,o,s,i]);const v=l.useMemo(()=>{const y=Array.from({length:g},()=>[]);for(const w of d){const S=p.get(w.tabKey)??0,C=Math.min(S,g-1);y[C].push(w)}return y},[d,p,g]),_=l.useCallback(()=>{t(new Map),s(0)},[t,s]);return{containerRef:m,normalizedGroupAssignments:p,numGroups:g,isSplitMode:f,groupedConvs:v,moveTabToGroup:x,closeGroup:b,handleResizeStart:k,splitTabRelative:j,clearAllSplits:_}}function Cl(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function w2(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function go(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Zd(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},s=Cl(t.channel)||Cl(e.updateChannel)||Cl(e.releaseChannel)||void 0,r=w2(t.npmTag)||(s==="preview"?"next":s==="stable"?"latest":void 0),o=go(t.targetVersion)||go(e.serverVersion)||void 0,a=go(t.minVersion)||void 0,i=go(t.updateCommand)||(s?"adhdev update":void 0);return{...s?{channel:s}:{},...r?{npmTag:r}:{},...o?{targetVersion:o}:{},...a?{minVersion:a}:{},...i?{updateCommand:i}:{}}}function Bs(e,t=null){return Zd(e).targetVersion||t}function S2(e){return Zd(e).channel||null}function eu(e){return!e||!Zd(e).channel?null:{}}function Pb(e,t={},s){const r=go(t.targetVersion);return r?s?s("machine.commandCenter.updateToVersion",{version:r}):`Update to v${r}`:t.fallback?t.fallback:s?t.required?s("machine.daemonUpdate.updateNow"):s("machine.daemonUpdate.upgrade"):t.required?"Update now":"Upgrade"}function ii(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const s=t[4]??null;let r=null;if(s){const o=s.match(/(?:^|\.)(\d+)$/);r=o?Number(o[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:s!==null}}function xh(e){var t;return((t=ii(e))==null?void 0:t.base)??null}function Lb(e,t){const s=ii(e),r=ii(t);if(!s||!r)return e!==t;for(let o=0;o<3;o+=1){if(s.base[o]<r.base[o])return!0;if(s.base[o]>r.base[o])return!1}return s.isPrerelease&&r.isPrerelease?s.prereleaseNumber===null||r.prereleaseNumber===null?!1:s.prereleaseNumber<r.prereleaseNumber:!1}function tu(e,t){const s=e.version||null;return!s||!t||e.versionMismatch===!0&&!ii(t)?!1:Lb(s,t)}function Ea(e,t){if(e.versionUpdateRequired===!0)return!0;const s=e.version||null;if(!s||!t||!Lb(s,t))return!1;const r=xh(s),o=xh(t);return!r||!o?!1:r[0]!==o[0]||r[1]!==o[1]}function k2({ides:e,sendDaemonCommand:t}){const s="1.0.59",r=l.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:tu(h,Bs(h,s))).sort((h,p)=>Number(Ea(p,Bs(p,s)))-Number(Ea(h,Bs(h,s)))),[s,e]),o=l.useMemo(()=>r.some(h=>Ea(h,Bs(h,s))),[s,r]),a=l.useMemo(()=>r.map(h=>Bs(h,s)).find(h=>typeof h=="string"&&h.trim().length>0)||s,[s,r]),[i,c]=l.useState(!1),[d,u]=l.useState({}),m=l.useCallback(async h=>{var f,x;const p=e.find(b=>b.id===h);if(!p)return;u(b=>({...b,[h]:"upgrading"}));const g=eu(p);if(!g){u(b=>({...b,[h]:"error"}));return}try{const b=await t(h,"daemon_upgrade",g);(f=b==null?void 0:b.result)!=null&&f.upgraded||(x=b==null?void 0:b.result)!=null&&x.success?u(k=>({...k,[h]:"done"})):u(k=>({...k,[h]:"error"}))}catch{u(b=>({...b,[h]:"error"}))}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:o,targetVersion:a,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:m}}const Eb=80;function Da(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function j2(e){return{...e,createdAt:Da(e.createdAt),updatedAt:Da(e.updatedAt,e.createdAt),lastEventAt:Da(e.lastEventAt,e.updatedAt||e.createdAt)}}function N2(e){const t=Ef(e);return t==="unknown:"?e.id:t}function C2(e){return[e.type,Lf(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function _2(e,t=Eb){const s=new Map;for(const r of e){if(r.deletedAt)continue;const o=N2(r),a=s.get(o);if(!a){s.set(o,r);continue}(r.updatedAt>a.updatedAt||r.updatedAt===a.updatedAt&&r.createdAt>a.createdAt)&&s.set(o,r)}return Array.from(s.values()).sort((r,o)=>{const a=o.updatedAt-r.updatedAt;return a!==0?a:o.createdAt-r.createdAt}).slice(0,Math.max(0,t))}function A2(e,t){const s=Date.now(),r=[];for(const o of e){const a=o.sessionId?t.get(o.sessionId):void 0;if(a!=null&&a.surfaceHidden||a!=null&&a.muted)continue;const i=Ci(o,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=Da(o.lastMessageAt||(a==null?void 0:a.lastUpdated)||o.lastUpdated,s),u=C2({type:c,sessionId:o.sessionId,providerSessionId:o.providerSessionId,tabKey:o.tabKey,lastMessageHash:o.lastMessageHash,lastMessageAt:o.lastMessageAt,lastUpdated:(a==null?void 0:a.lastUpdated)||o.lastUpdated});r.push(j2({id:u,dedupKey:u,type:c,routeId:o.routeId,machineId:o.daemonId||o.routeId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,tabKey:o.tabKey,title:rg(o),preview:$N(o),createdAt:d,updatedAt:d,lastEventAt:d}))}return _2(r)}function T2(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function I2(e){const{conversations:t,liveSessionInboxState:s,maxItems:r=Eb}=e,o=l.useMemo(()=>A2(t,s).slice(0,Math.max(0,r)),[t,s,r]),a=l.useMemo(()=>T2(o),[o]);return{notifications:o,unreadCount:a}}function M2({notifications:e,sendDaemonCommand:t}){const s=l.useCallback(a=>{const i=e.find(d=>d.id===a),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),r=l.useCallback(a=>{const i=e.find(c=>c.id===a);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),o=l.useCallback(a=>{const i=e.find(c=>c.id===a);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:s,handleMarkDashboardNotificationUnread:r,handleDeleteDashboardNotification:o}}function nu(...e){const t=new Set,s=[],r=o=>{const a=typeof o=="string"?o.trim():"";if(!a)return;const i=a.toLowerCase();t.has(i)||(t.add(i),s.push(a))};for(const o of e){if(Array.isArray(o)){for(const a of o)r(a);continue}r(o)}return s}function R2(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const s=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(s){const r=s[1].toUpperCase(),o=(s[2]||"").replace(/[\\/]+/g,"\\");return o?`${r}:\\${o}`:`${r}:\\`}return null}function su(e,t=[]){if(e==="win32"){for(const s of t){if(typeof s!="string")continue;const r=R2(s);if(r)return r}return"C:\\"}for(const s of t){const r=typeof s=="string"?s.trim():"";if(r)return r}return"~"}function P2(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const s=t.includes("\\")?"\\":"/",r=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(r[0]||"")?r.length<=2?`${r[0]}\\`:r.slice(0,-1).join("\\"):r.length<=2?s:r.slice(0,-1).join(s)||s}function L2(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function ru(e,t,s){const r=await e(t,"file_list_browse",{path:s}),o=L2(r);if(!(o!=null&&o.success))throw new Error((o==null?void 0:o.error)||(r==null?void 0:r.error)||"Could not browse folder");const a=typeof(o==null?void 0:o.path)=="string"?o.path:s,i=a.includes("\\")?"\\":"/",c=(u,m)=>/^[A-Za-z]:\\?$/.test(u)?`${u.replace(/\\?$/,"\\")}${m}`:u==="/"||u==="\\"?`${i}${m}`:`${u.replace(/[\\/]+$/,"")}${i}${m}`,d=Array.isArray(o==null?void 0:o.files)?o.files.filter(u=>(u==null?void 0:u.type)==="directory"&&typeof(u==null?void 0:u.name)=="string").map(u=>({name:u.name,path:typeof(u==null?void 0:u.path)=="string"&&u.path.trim()?u.path:c(a,u.name)})).sort((u,m)=>u.name.localeCompare(m.name)):[];return{path:a,directories:d}}function yh(e,t){const s=t.meshId||"",r={meshId:s,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${s}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(o,a)=>r[a]||"")}function Db(e,t={}){const s=e==null?void 0:e.mcpConfig;if((s==null?void 0:s.mode)!=="manual")return null;const o=yh(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"}).trim();return!o.includes(`
|
|
58
|
+
`)&&!o.startsWith("{")?null:{serverName:s.serverName||"adhdev-mesh",configFormat:s.format,configPathCommand:s.configPathCommand,requiresRestart:s.requiresRestart===!0,instructions:s.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:yh(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"})}}function E2(e){if(!e||typeof e!="object")return null;const t=e,s=typeof t.instructions=="string"?t.instructions:"",r=typeof t.template=="string"?t.template:"";return!s&&!r?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:s||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:r}}function Io(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ob(e){return Ti(e)||e.tabKey||e.routeId||null}function $b(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",s=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",o=e.conversations.find(a=>{if(r&&a.routeId!==r)return!1;const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||s&&i.includes(s)||r&&a.routeId===r)});if(o!=null&&o.tabKey)return o.tabKey;if(r){const a=$n(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(a!=null&&a.tabKey)return a.tabKey}return t||s||r||null}function xs(e){return String(e||"").trim()}function Fb(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function li(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function D2(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function O2(e,t){const s=xs(e.providerSessionId),r=xs(e.targetSessionId),o=t.find(a=>{const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey,a.routeId].map(xs).filter(Boolean);return!!(s&&i.includes(s)||r&&i.includes(r))});return o?o.tabKey:r||s||null}function $2(e,t,s){if(t.event!=="agent:generating_completed")return null;const r=Fb(t.daemonId);if(r&&r!==e.machineId)return null;const o=xs(t.providerType);if(e.providerType&&o!==e.providerType)return null;const a=xs(e.resumeSessionId),i=xs(e.launchedSessionId),c=xs(t.providerSessionId),d=xs(t.targetSessionId);if(a&&a!==c&&a!==d||i&&i!==c&&i!==d)return null;const u=li(e.workspacePath);if(u){const m=li(t.workspaceName);if(m&&!D2(m,u))return null}return O2(t,s)}function vh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function F2({ides:e,conversations:t,onOpenSession:s}){const[r,o]=l.useState(null),a=l.useRef(null),i=l.useCallback(()=>{a.current=null,o(null)},[]),c=l.useCallback(d=>{a.current=d,o(d)},[]);return l.useEffect(()=>{if(!r)return;const d=li(r.workspacePath),u=e.find(h=>{var b,k,j,v;if(!h||h.type==="adhdev-daemon"||Fb(h.daemonId||h.id)!==r.machineId||(To(h)?"cli":Nr(h)?"acp":"ide")!==r.kind)return!1;const f=String(h.agentType||h.type||"");if(r.providerType&&f!==r.providerType)return!1;if(r.resumeSessionId)return String(h.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const _=String(r.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(w=>String(w||"")).filter(Boolean).includes(_)}if(d){const _=li(h.workspace||h.runtimeWorkspaceLabel);return _?_===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((v=(j=(k=(b=h.activeChat)==null?void 0:b.messages)==null?void 0:k.at)==null?void 0:j.call(k,-1))==null?void 0:v.timestamp)||0)>=r.startedAt-5e3});if(!u)return;const m=$b({entrySessionId:u.sessionId,entryInstanceId:u.instanceId,entryRouteId:u.id,conversations:t});m&&(i(),s(m))},[i,t,e,s,r]),l.useEffect(()=>ct.onStatusEvent(d=>{const u=a.current;if(!u)return;const m=$2(u,d,t);m&&(i(),s(m))}),[i,t,s]),l.useEffect(()=>{if(!r)return;const d=window.setTimeout(()=>{o(u=>!u||u.startedAt!==r.startedAt?u:(a.current=null,null))},45e3);return()=>window.clearTimeout(d)},[r]),{trackPendingLaunch:c}}function H2(e,t){var r,o,a,i;const s={cliType:e};return(r=t==null?void 0:t.workspacePath)!=null&&r.trim()?s.dir=t.workspacePath.trim():t!=null&&t.workspaceId?s.workspaceId=t.workspaceId:t!=null&&t.useHome&&(s.useHome=!0),(o=t==null?void 0:t.resumeSessionId)!=null&&o.trim()&&(s.resumeSessionId=t.resumeSessionId.trim()),Array.isArray(t==null?void 0:t.cliArgs)&&t.cliArgs.length>0&&(s.cliArgs=t.cliArgs),(a=t==null?void 0:t.initialModel)!=null&&a.trim()&&(s.initialModel=t.initialModel.trim()),(i=t==null?void 0:t.initialThinkingLevel)!=null&&i.trim()&&(s.initialThinkingLevel=t.initialThinkingLevel.trim()),s.launchedBy="dashboard",s.initialModel&&(t!=null&&t.modelSource)&&(s.modelSource=t.modelSource),s.initialThinkingLevel&&(t!=null&&t.thinkingLevelSource)&&(s.thinkingLevelSource=t.thinkingLevelSource),t!=null&&t.settings&&(s.settings=t.settings),s}function B2(e,t,s){var i,c,d,u;const r={meshId:e.trim()};t.trim()&&(r.cliType=t.trim());const o=(i=s==null?void 0:s.initialModel)==null?void 0:i.trim(),a=(c=s==null?void 0:s.initialThinkingLevel)==null?void 0:c.trim();return o&&(r.initialModel=o),a&&(r.initialThinkingLevel=a),o&&(s!=null&&s.modelSource)&&(r.modelSource=s.modelSource),a&&(s!=null&&s.thinkingLevelSource)&&(r.thinkingLevelSource=s.thinkingLevelSource),(d=s==null?void 0:s.settings)!=null&&d.autoApproveMode?r.autoApproveMode=s.settings.autoApproveMode:typeof((u=s==null?void 0:s.settings)==null?void 0:u.autoApprove)=="boolean"&&(r.autoApprove=s.settings.autoApprove),r}function W2({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:s,activeConv:r,ides:o,setCliViewModeOverrides:a}){const i=$d(),{launchCli:c}=wi(),d=l.useCallback(async(b,k)=>ru(e,b,k),[e]),u=l.useCallback(async(b,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const j=await e(b,"workspace_add",{path:k.trim()});return j!=null&&j.success?{ok:!0}:{ok:!1,error:(j==null?void 0:j.error)||"Could not save workspace"}}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not save workspace"}}},[e]),m=l.useCallback(async(b,k,j)=>{var v;try{const _={ideType:k,enableCdp:!0};(v=j==null?void 0:j.workspacePath)!=null&&v.trim()&&(_.workspace=j.workspacePath.trim());const y=await e(b,"launch_ide",_);return!(y!=null&&y.success)&&(y==null?void 0:y.success)!==void 0?{ok:!1,error:(y==null?void 0:y.error)||"Could not launch IDE"}:(t({machineId:b,kind:"ide",providerType:k,workspacePath:(j==null?void 0:j.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(_){return{ok:!1,error:_ instanceof Error?_.message:"Could not launch IDE"}}},[e,t]),h=l.useCallback(async(b,k,j,v)=>{const _=Date.now();try{const y=H2(j,v),w=await c(b,y),S=(w==null?void 0:w.result)||w,C=(S==null?void 0:S.sessionId)||(S==null?void 0:S.id);return w!=null&&w.success&&C?(t({machineId:b,kind:k,providerType:j,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,launchedSessionId:C,startedAt:_}),{ok:!0}):w!=null&&w.success?(t({machineId:b,kind:k,providerType:j,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:_}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(S==null?void 0:S.error)||`Could not launch ${k.toUpperCase()} session`,code:(w==null?void 0:w.code)||(S==null?void 0:S.code)||void 0}}catch(y){return vh(y)?(t({machineId:b,kind:k,providerType:j,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:_}),{ok:!0}):{ok:!1,error:y instanceof Error?y.message:`Could not launch ${k.toUpperCase()} session`}}},[c,e,t]),p=l.useCallback(async b=>{var k;if(i!=null&&i.listMeshes){const j=await i.listMeshes(b);return Ja(j),j}if(!b)return[];try{const j=await e(b,"list_meshes",{}),v=(j==null?void 0:j.result)??j;if((v==null?void 0:v.success)===!1)throw new Error((v==null?void 0:v.error)||"Could not load meshes");const y=(Array.isArray(v==null?void 0:v.meshes)?v.meshes:Array.isArray((k=v==null?void 0:v.result)==null?void 0:k.meshes)?v.result.meshes:[]).map(w=>{var S;return{id:String((w==null?void 0:w.id)||""),name:String((w==null?void 0:w.name)||(w==null?void 0:w.id)||"Untitled mesh"),repoIdentity:(w==null?void 0:w.repoIdentity)||(w==null?void 0:w.repo_identity)||null,workspace:Array.isArray(w==null?void 0:w.nodes)&&w.nodes.length>0?String(((S=w.nodes[0])==null?void 0:S.workspace)||""):null,nodesCount:Array.isArray(w==null?void 0:w.nodes)?w.nodes.length:void 0,status:(w==null?void 0:w.status)||null}}).filter(w=>w.id);return Ja(y),y}catch(j){throw console.error("List meshes failed",j),j}},[i,e]),g=l.useCallback(async(b,k,j,v)=>{if(!k.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(b,k,j,v);const _=Date.now();try{const y=B2(k,j,v),w=await e(b,"launch_mesh_coordinator",y),S=(w==null?void 0:w.result)??w;if((S==null?void 0:S.success)===!1||(w==null?void 0:w.success)===!1){const A=String((S==null?void 0:S.code)||(w==null?void 0:w.code)||""),O=E2((S==null?void 0:S.meshCoordinatorSetup)||(S==null?void 0:S.manualSetup)||(w==null?void 0:w.meshCoordinatorSetup)||(w==null?void 0:w.manualSetup));return{ok:!1,error:(S==null?void 0:S.error)||(w==null?void 0:w.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:O}}const C=(S==null?void 0:S.sessionId)||(S==null?void 0:S.id);return C?s(C):t({machineId:b,kind:"cli",providerType:(S==null?void 0:S.cliType)||j.trim()||void 0,workspacePath:(S==null?void 0:S.workspace)||null,startedAt:_}),{ok:!0}}catch(y){return vh(y)?(t({machineId:b,kind:"cli",providerType:j.trim()||void 0,startedAt:_}),{ok:!0}):{ok:!1,error:y instanceof Error?y.message:"Could not launch mesh coordinator"}}},[i,s,e,t]),f=l.useCallback(async(b,k)=>{if(!b||!k)return[];try{const j=await e(b,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),v=(j==null?void 0:j.result)??j;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(j){return console.error("List saved sessions failed",j),[]}},[e]),x=l.useCallback(async b=>{await Cb({conversation:r,mode:b,ides:o,sendDaemonCommand:e,setCliViewModeOverrides:a})},[r,o,e,a]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:u,handleLaunchMachineIde:m,handleLaunchMachineProvider:h,handleListMachineMeshes:p,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:f,setActiveCliViewMode:x}}function U2(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function K2(e,t,s=Date.now()){return!e||!U2(t)?null:{tabKey:e,nonce:s}}function q2({isMobile:e,conversations:t,visibleConversations:s,groupActiveTabIds:r,focusedGroup:o,groupedConvs:a,setSearchParams:i}){const[c,d]=l.useState(null),[u,m]=l.useState(null),h=l.useMemo(()=>{var b,k;if(!e){if(c){const j=t.find(v=>v.tabKey===c);if(j)return j}return s[0]}const x=r[o];if(x){const j=t.find(v=>v.tabKey===x);if(j)return j}return((b=a[o])==null?void 0:b[0])||((k=a[0])==null?void 0:k[0])},[t,c,o,r,a,e,s]),p=l.useCallback(x=>{d(x)},[]),g=l.useCallback(x=>{d(x.tabKey),i(b=>{const k=new URLSearchParams(b),j=HN(x);return j?k.set("activeTab",j):k.delete("activeTab"),k},{replace:!0})},[i]),f=l.useCallback((x,b)=>{const k=K2(x,b);k&&m(k)},[]);return{activeConv:h,openDesktopConversation:g,requestScrollToBottom:f,scrollToBottomRequest:u,setDesktopActiveTab:p}}function z2(e){const t=e.completedKey||null,s=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:s!==null&&s!==e.autoReadKey,nextPendingKey:s===e.autoReadKey?s:null}:s===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:s}:{shouldSchedule:!0,shouldCancelPending:s!==null&&s!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!s,nextPendingKey:null}}function G2(e){const t=String(e.liveState.completionMarker||""),s=String(e.liveState.seenCompletionMarker||""),r=String(e.liveState.inboxBucket||"idle"),o=!!e.liveState.unread,a=[e.tabKey,e.historySessionId||"",t,s,r,o?"1":"0"].join(":");return{shouldMarkSeen:!!(r==="task_complete"&&o&&(!t||t!==s)),autoReadKey:a,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function V2({activeConv:e,isMobile:t,liveSessionInboxState:s,sendDaemonCommand:r}){const o=l.useRef(null),a=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),a.current=null};if(t){u(),o.current=null;return}if(!(e!=null&&e.sessionId)){u(),o.current=null;return}const m=Ns(e,s),h=G2({tabKey:e.tabKey,historySessionId:Ti(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Qs(e),liveState:m}),p=h.autoReadKey,g=z2({autoReadKey:p,shouldMarkSeen:h.shouldMarkSeen,completedKey:o.current,pendingKey:a.current});if(!h.shouldMarkSeen){g.shouldCancelPending&&u(),o.current=p;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&u();const f=()=>{if(document.visibilityState!=="visible"||o.current===p)return;o.current=p,a.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const b=h.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:b,completionMarker:h.completionMarker}).catch(()=>{})};if(a.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(f,1500);const b=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=b,document.addEventListener("visibilitychange",b);return}const x=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(f,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=x,document.addEventListener("visibilitychange",x)},[e,t,s,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function _l(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const s=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(s)?s:""}function Y2({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:s,ides:r,sendDaemonCommand:o,updateRouteChats:a,setToasts:i,setClearedTabs:c,setSearchParams:d}){var F;const{launchCli:u}=wi(),[m,h]=l.useState(!1),[p,g]=l.useState([]),[f,x]=l.useState(()=>yn()),[b,k]=l.useState(!1),[j,v]=l.useState(null),_=l.useRef(null),y=l.useMemo(()=>s||t||e,[e,s,t]),w=!!y&&St(y)&&!vt(y),S=l.useMemo(()=>{if(!y||!w)return null;const q=y.daemonId||y.routeId||"",Q=Vn(y),K=_l(y);return`${q}:${Q}:${y.providerSessionId||""}:${K}`},[y,w]),C=l.useMemo(()=>!y||!w?"":_l(y),[y,w]),{isCreatingChat:A,isRefreshingHistory:O,handleSwitchSession:L,handleNewChat:M,handleRefreshHistory:$}=Rb({sendDaemonCommand:o,activeConv:y,chats:(F=r.find(q=>q.id===(y==null?void 0:y.routeId)))==null?void 0:F.chats,updateRouteChats:a,setToasts:i,setClearedTabs:c}),N=l.useCallback(()=>{h(!0)},[]),I=l.useCallback(()=>{h(!1)},[]),B=l.useCallback(async()=>{if(!(!y||!w||b)){k(!0);try{const q=y.daemonId||y.routeId,Q=Vn(y),K=_l(y),R=await o(q,"list_saved_sessions",{agentType:Q,providerType:Q,kind:"cli",limit:50,...y.providerSessionId?{providerSessionId:y.providerSessionId}:{},...K?{workspace:K}:{}}),D=(R==null?void 0:R.result)??R;g(Array.isArray(D==null?void 0:D.sessions)?D.sessions:[])}catch(q){console.error("Refresh saved sessions failed",q),g([])}finally{k(!1)}}},[y,b,w,o]);l.useEffect(()=>{if(!m){_.current=null;return}if(!w){_.current=null,g([]),k(!1);return}!S||b||_.current!==S&&(_.current=S,B())},[B,m,b,w,S]);const T=l.useCallback(async q=>{if(!y||!w||!q.providerSessionId||!q.workspace)return;const Q=y.daemonId||y.routeId,K=Vn(y);try{v(q.providerSessionId);const R=Ff(q.summaryMetadata,"model",{preferShortValue:!0})||void 0,D=await u(Q,{cliType:K,dir:q.workspace,resumeSessionId:q.providerSessionId,initialModel:R,...R?{modelSource:"remembered"}:{}}),P=(D==null?void 0:D.result)??D,H=typeof(P==null?void 0:P.sessionId)=="string"?P.sessionId:typeof(P==null?void 0:P.id)=="string"?P.id:"";H&&d(W=>{const U=new URLSearchParams(W);return U.set("activeTab",H),U},{replace:!0}),I()}catch(R){console.error("Resume saved session failed",R)}finally{v(null)}},[I,y,w,o,d]);return{historyModalOpen:m,openHistoryModal:N,closeHistoryModal:I,historyTargetConv:y,isSavedSessionHistoryTarget:w,isHistoryCreatingChat:A,isHistoryRefreshingHistory:O,handleHistorySwitchSession:L,handleHistoryNewChat:M,handleHistoryRefresh:$,savedHistorySessions:p,savedHistoryFilters:f,setSavedHistoryFilters:x,missingWorkspaceResumePath:C,isSavedHistoryLoading:b,resumingSavedHistorySessionId:j,handleRefreshSavedHistory:B,handleResumeSavedHistorySession:T}}function Q2({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c}){const[d,u]=l.useState(null),[m,h]=l.useState(null),p=l.useMemo(()=>{if(e||!r)return null;const k=c(r);return k&&!St(k)&&!vt(k)?k:null},[e,r,c]),g=l.useMemo(()=>{const k=d==null?void 0:d.routeId;if(!k)return null;const j=d!=null&&d.tabKey?a.find(v=>v.tabKey===d.tabKey):o?a.find(v=>v.tabKey===o):null;return(j==null?void 0:j.routeId)===k?j:$n(a,k)},[a,d,o]),f=l.useMemo(()=>{if(g)return i.find(k=>k.id===g.routeId)},[i,g]);l.useEffect(()=>{p&&(u({routeId:p.routeId,tabKey:cm(p)}),h(p),s({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,s,p]);const x=l.useCallback(k=>{k&&(u({routeId:k.routeId,tabKey:cm(k)}),h(k))},[]),b=l.useCallback(()=>{u(null),h(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:f,remoteDialogActiveConv:m,setRemoteDialogActiveConv:h,openRemoteDialog:x,closeRemoteDialog:b}}function J2({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:u}){const{remoteDialogConv:m,remoteDialogIdeEntry:h,remoteDialogActiveConv:p,setRemoteDialogActiveConv:g,openRemoteDialog:f,closeRemoteDialog:x}=Q2({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c}),[b,k]=l.useState(!1),[j,v]=l.useState(null),_=l.useCallback(async S=>{const C=S||d;!C||!St(C)&&!vt(C)||(v(C),k(!0))},[d]),y=l.useCallback(()=>{k(!1),v(null)},[]),w=l.useCallback(async S=>{const C=j||d;if(!C||!St(C)&&!vt(C)){y();return}k(!1);try{const A=Vn(C),O=C.routeId||C.daemonId||"";await u(O,"stop_cli",{cliType:A,targetSessionId:C.sessionId,mode:S,...Ri(C)})}catch(A){console.error("Stop CLI failed:",A)}finally{v(null)}},[d,y,j,u]);return{remoteDialogConv:m,remoteDialogIdeEntry:h,remoteDialogActiveConv:p,setRemoteDialogActiveConv:g,openRemoteDialog:f,closeRemoteDialog:x,cliStopDialogOpen:b,cliStopTargetConv:j,requestCliStop:_,cancelCliStop:y,confirmCliStop:w}}function Al(e,t=!0){return(e??!0)&&t}const ou=l.memo(function({activeConv:t,clearToken:s,isCliTerminal:r,ideEntry:o,terminalRef:a,commands:i,actionLogs:c,userName:d,scrollToBottomRequestNonce:u,isInputActive:m=!0,isVisible:h=!0}){const{handleModalButton:p,handleRelaunch:g,handleSendChat:f,handleSendNowQueued:x,handleCancelQueued:b,isSendingChat:k,sendFeedbackMessage:j,pendingLocalMessage:v,pendingLocalMessages:_,retireEchoedPendingMessages:y,handleFocusAgent:w,isFocusingAgent:S}=i,C=r,A=!r,O=Al(h,C),L=Al(h,A),M=Al(h),$=jb(t),{t:N}=ve("common"),I=$.status||$.modalMessage||$.modalButtons?{...t,...$.status?{status:$.status}:{},...$.modalMessage!==void 0?{modalMessage:$.modalMessage}:{},...$.modalButtons!==void 0?{modalButtons:$.modalButtons}:{}}:t,B=T=>n.jsx(Rg,{activeConv:I,ideEntry:o,handleSendChat:f,handleSendNowQueued:x,handleCancelQueued:b,isSendingChat:k,sendFeedbackMessage:j,pendingLocalMessage:v,pendingLocalMessages:_,retireEchoedPendingMessages:y,handleFocusAgent:w,isFocusingAgent:S,actionLogs:c,userName:d,scrollToBottomRequestNonce:u,isInputActive:m&&T,isVisible:T});return n.jsxs(n.Fragment,{children:[n.jsx(Tf,{activeConv:I,onModalButton:p}),I.transport!=="pty"&&I.transport!=="acp"&&I.cdpConnected===!1?n.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:n.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[n.jsx("span",{className:"text-sm",children:n.jsx(an,{size:14})}),n.jsxs("span",{className:"flex flex-1 items-center gap-1",children:[n.jsx("span",{className:"font-semibold",children:N("paneGroup.cdpDisconnectedShort")}),n.jsx(dt,{content:N("paneGroup.cdpDisconnected"),size:12})]}),n.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-3xs whitespace-nowrap shrink-0",onClick:g,children:N("paneGroup.relaunchWithCdp")})]})}):null,I.transport==="pty"?n.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[n.jsx("div",{"aria-hidden":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:n.jsx(s1,{activeConv:I,clearToken:s,terminalRef:a,handleSendChat:f,isSendingChat:k,sendFeedbackMessage:j,isVisible:O,isInputActive:m&&O})}),n.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:A?"visible":"hidden",pointerEvents:A?"auto":"none"},children:B(L)})]}):B(M)]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.commands===t.commands&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function X2({conversation:e,className:t="",onOpenNativeConversation:s,onOpenMachine:r,interactive:o=!0,meshOnly:a=!1}){const{t:i}=ve("common"),c=rr(),d=as(e),u=a?null:sg(e),m=!a&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),h=!a&&e.streamSource==="agent-stream"&&!!e.agentName,p=!a&&!h&&(e.transport==="pty"||e.transport==="acp"),g=Rr(e),f=FN(e),x=Ld(e).role,b=e.meshQueueStats,k=x==="coordinator",j=l.useCallback(()=>{if(r){r();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,r]),v=l.useCallback(()=>{if(s){s();return}const _=Ob(e);_&&c(Io(_))},[e,c,s]);return!m&&!h&&!p&&!u&&!x&&!b?null:n.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[n.jsx(iA,{conversation:e}),m&&(o?n.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:v,title:f,children:[n.jsx(Xn,{size:12}),n.jsx("span",{children:f})]}):n.jsxs("span",{className:"conversation-meta-chip",title:f,children:[n.jsx(Xn,{size:12}),n.jsx("span",{children:f})]})),h&&n.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[n.jsx(Ir,{size:12}),n.jsx("span",{children:g})]}),p&&n.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[n.jsx(Ir,{size:12}),n.jsx("span",{children:g})]}),u&&(o?n.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:u,children:[n.jsx(Tr,{size:12}),n.jsx("span",{children:u})]}):n.jsxs("span",{className:"conversation-meta-chip",title:u,children:[n.jsx(Tr,{size:12}),n.jsx("span",{children:u})]})),k&&b&&n.jsxs("span",{className:`conversation-meta-chip ${b.pending>0?"is-active":""}`,style:b.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:i("dashboard.metaChips.queueTooltip",{pending:b.pending,assigned:b.assigned,completed:b.completed,failed:b.failed}),children:[n.jsx(pw,{size:12}),n.jsx("span",{children:i("dashboard.metaChips.queuePending",{count:b.pending})})]})]})}function Z2({selectedConversation:e,isAcp:t,isStandalone:s,selectedIdeEntry:r,actionLogs:o,userName:a,commands:i,onBack:c,onOpenNativeConversation:d,onOpenMachine:u,onOpenHistory:m,onOpenRemote:h,onOpenMeshGraph:p,onStopCli:g,cliViewMode:f,onSetCliViewMode:x}){const{t:b}=ve("common"),k=l.useRef(null),j=_i(Af(e)),v=St(e)&&!t,_=v&&f==="terminal",y=s?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:`flex items-center justify-between gap-3 ${y} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[n.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[n.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:c,type:"button","aria-label":b("common.back"),children:n.jsx(dd,{size:18})}),n.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 text-[17px] leading-[26px] font-extrabold tracking-tight text-text-primary",children:[n.jsx(_s,{conversation:e,size:15}),n.jsx("span",{className:"min-w-0 truncate",children:Rt(e)})]}),n.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:n.jsx(X2,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>u(e)})})]})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[v&&f&&n.jsx(Ug,{mode:f,onChange:x,compact:!0}),v&&g&&n.jsx("button",{onClick:()=>{g(e)},className:"btn btn-secondary btn-sm",title:b("cliStop.stopProcess"),"aria-label":b("cliStop.stopProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:n.jsx(Bt,{size:14})}),n.jsx(nb,{conversation:e,onOpenMeshGraph:p}),n.jsx(tb,{conversation:e,onOpenHistory:m,onOpenRemote:h,iconSize:14})]})]}),n.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:n.jsx(ou,{activeConv:e,clearToken:0,isCliTerminal:_,ideEntry:r,terminalRef:k,commands:i,actionLogs:o,userName:a})}),n.jsx(wd,{promptSession:j.promptSession,isSubmitting:j.isSubmitting,error:j.responseError,onSubmit:j.submit,onCancel:j.cancel})]})}function eI(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Hb({isStandalone:e=!1}={}){const{t}=ve("common"),[s,r]=l.useState("unix"),[o,a]=l.useState("powershell"),[i,c]=l.useState(!1),d=s==="unix"?"unix":o,u=l.useMemo(()=>a_(),[]);l.useEffect(()=>{r(eI())},[]);const m=l.useCallback(()=>{navigator.clipboard.writeText(u[d].cmd).catch(()=>{}),c(!0),setTimeout(()=>c(!1),2e3)},[d]);return n.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[n.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[n.jsx("button",{className:`text-3xs px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${s==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>r("unix"),children:"macOS / Linux"}),n.jsx("button",{className:`text-3xs px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${s==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>r("windows"),children:"Windows"})]}),s==="windows"&&n.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[n.jsx("button",{className:`text-4xs px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${o==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("powershell"),children:"PowerShell"}),n.jsx("button",{className:`text-4xs px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${o==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("cmd"),children:">_ CMD"})]}),n.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:m,title:t("app.installCommand.clickToCopy"),children:[n.jsx("span",{className:"text-text-muted select-none",children:u[d].prompt}),n.jsx("span",{className:"flex-1 break-all",children:u[d].cmd}),n.jsx("span",{className:"text-4xs font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:i?n.jsx(Dr,{size:12}):n.jsx(ud,{size:12})})]}),n.jsxs("div",{className:"text-text-muted text-3xs font-sans mt-2",children:[t("app.installCommand.orViaNpm")," ",n.jsx("span",{className:"text-text-secondary font-mono",children:e?"npm i -g @adhdev/daemon-standalone && adhdev-standalone":"npm i -g adhdev && adhdev login"})]})]})}function Bb({section:e,onSectionChange:t}){const{t:s}=ve("common"),r=[{key:"machines",label:s("nav.machines"),icon:Xn},{key:"chats",label:s("nav.chats"),icon:Jn}];return n.jsx("div",{className:"px-3 py-2.5 pb-[calc(20px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:n.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:o,label:a,icon:i})=>{const c=e===o;return n.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-xxs font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(o),type:"button","aria-pressed":c,children:[n.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:n.jsx(i,{size:15})}),n.jsx("span",{children:a})]},o)})})})}function ha({title:e,className:t=""}){return n.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:n.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function hr({children:e,className:t=""}){return n.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function Ds({icon:e,title:t,subtitle:s,children:r}){return n.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[n.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),n.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),n.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:s}),r]})}function tI({title:e,isMuted:t,onToggleMute:s,onHide:r,onStop:o}){const{t:a}=ve(),[i,c]=l.useState(!1),d=l.useRef(null);if(l.useEffect(()=>{if(!i)return;const h=g=>{var f;(f=d.current)!=null&&f.contains(g.target)||c(!1)},p=g=>{g.key==="Escape"&&c(!1)};return document.addEventListener("pointerdown",h,!0),document.addEventListener("mousedown",h,!0),window.addEventListener("keydown",p),()=>{document.removeEventListener("pointerdown",h,!0),document.removeEventListener("mousedown",h,!0),window.removeEventListener("keydown",p)}},[i]),!s&&!r&&!o)return null;const u="flex w-full items-center gap-2.5 rounded-lg border-none bg-transparent px-3 py-2.5 text-left text-sm font-medium text-text-secondary hover:bg-bg-secondary hover:text-text-primary",m=h=>p=>{p.preventDefault(),p.stopPropagation(),c(!1),h()};return n.jsxs("div",{ref:d,className:"relative",children:[n.jsx("button",{type:"button",className:`mobile-inbox-row-menu-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${t?"border-amber-500/60 bg-amber-500/15 text-amber-500":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:h=>{h.preventDefault(),h.stopPropagation(),c(p=>!p)},"aria-haspopup":"menu","aria-expanded":i,"aria-label":a("mobileInbox.moreActionsFor",{title:e}),title:a("dashboard.header.moreActions"),children:t?n.jsx(lc,{size:13}):n.jsx(Qp,{size:14})}),i&&n.jsxs("div",{role:"menu",className:"absolute right-0 top-full z-[var(--z-popover)] mt-1 flex w-48 flex-col rounded-xl border border-border-default bg-bg-card p-1 shadow-xl",children:[s&&n.jsxs("button",{type:"button",role:"menuitem",className:`mobile-inbox-mute-button ${u}`,onClick:m(s),children:[t?n.jsx(js,{size:15}):n.jsx(lc,{size:15}),a(t?"conversation.unmuteThis":"conversation.muteThis")]}),r&&n.jsxs("button",{type:"button",role:"menuitem",className:`mobile-inbox-hide-button ${u}`,onClick:m(r),children:[n.jsx(xi,{size:15}),a("mobileInbox.hide")]}),o&&n.jsxs("button",{type:"button",role:"menuitem",className:`mobile-inbox-stop-button ${u} !text-status-error`,onClick:m(o),children:[n.jsx(Bt,{size:15}),a("mobileInbox.stopSessionTitle")]})]})]})}function pa({item:e,type:t,getAvatarText:s,onOpenConversation:r,onRequestHideConversation:o,onRequestStopCli:a,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:u}){const{t:m}=ve(),h=t==="needs_attention"||t==="task_complete",p=t==="working",g=t==="earlier",f=t==="task_complete",{isReconnecting:x,isConnecting:b,isErrored:k}=or(e.conversation),j=Rt(e.conversation),v=Ho(e.conversation),_=$g(e.conversation,{requiresAction:t==="needs_attention"}),y=h?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":p?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",w=h?"bg-accent-primary shadow-glow":p?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",S=g?"text-text-secondary":"text-text-primary",C=g?"text-text-muted":"text-text-secondary",A=g?"text-text-secondary opacity-80":"text-text-muted",O=g?"text-text-muted opacity-80":"text-text-muted",L=!p&&!f,M=Dg(e.conversation),$="text-[color:var(--status-warning)]",N=I=>{if(!c||!n1())return;I.preventDefault(),I.stopPropagation();const B=c==null?void 0:c(e.conversation);Promise.resolve(B).catch(T=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",T)})};return n.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${y}`,children:n.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[h||p?n.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,n.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[n.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${w}`,style:h?{color:"var(--accent-on-primary)"}:void 0,children:s(j)}),M&&i&&n.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-[color:color-mix(in_srgb,var(--mesh-coordinator)_34%,transparent)] bg-bg-primary/70 text-[color:var(--mesh-coordinator)] transition-colors hover:bg-[color:color-mix(in_srgb,var(--mesh-coordinator)_10%,transparent)]",onClick:I=>{I.preventDefault(),I.stopPropagation(),i(e.conversation)},"aria-label":m("mobileInbox.openMeshGraphFor",{title:j}),title:m("mobileInbox.openLiveMeshGraph"),children:n.jsx(On,{size:13})})]}),n.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>r(e.conversation),onContextMenu:N,type:"button",children:[n.jsxs("div",{className:"flex items-center gap-1.5 pr-[92px]",children:[n.jsx(_s,{conversation:e.conversation,size:13}),n.jsx("span",{className:`text-[15px] leading-[22px] font-bold truncate tracking-tight ${S}`,children:j})]}),n.jsxs("div",{className:`text-xs font-medium truncate flex items-center ${C}`,children:[n.jsx(Wr,{conversation:e.conversation,separator:!0}),n.jsx("span",{className:"truncate",children:v}),n.jsx(Dd,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),x?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:`${$} animate-pulse`,children:m("mobileInbox.reconnectingItem")})]}):b?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:"text-text-muted",children:m("mobileInbox.connectingItem")})]}):_==="Action needed"?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:$,children:m("mobileInbox.actionNeeded")})]}):k&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:"text-[color:var(--status-error)]",children:m("mobileInbox.needsAttention")})]})]}),n.jsx("div",{className:`mt-0.5 truncate text-xxs ${A}`,children:e.preview})]}),n.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[L&&n.jsx("span",{className:`mr-0.5 text-2xs font-medium shrink-0 ${O}`,children:of(e.timestamp)}),f&&n.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-3xs font-bold text-accent-primary",children:m("mobileInbox.done")}),n.jsx(tI,{title:j,isMuted:d,onToggleMute:u,onHide:o,onStop:a})]})]})},e.conversation.tabKey)}function wh({count:e,label:t}){return e<=0?null:n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-accent-primary","aria-live":"polite",children:[n.jsxs("span",{className:"relative flex h-2 w-2 shrink-0",children:[n.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-accent-primary/60"}),n.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-accent-primary"})]}),n.jsx("span",{className:"font-semibold",children:t})]})}function nI({section:e,attentionItems:t,unreadItems:s,workingItems:r,completedItems:o,hiddenConversations:a,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:u,onOpenConversation:m,onShowAllHidden:h,onHideConversation:p,onShowHiddenConversation:g,onOpenMeshGraph:f,onStopCli:x,onOpenNewSession:b,onOpenMachine:k,onOpenSettings:j,onSectionChange:v,wsStatus:_="connected",initialDataLoaded:y=!0,conversationsLoaded:w,isStandalone:S=!1,onCollectChatDebugBundle:C,isConversationMuted:A,onToggleMuteConversation:O}){const{t:L}=ve(),M=_==="disconnected"||_==="reconnecting"||_==="offline"||_==="auth_failed",$=!M&&!y,N=!M&&!(w??y),I=i.length>0,B=t.length>0||s.length>0||r.length>0||o.length>0,T=L(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),F=S?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",q=S?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",Q=l.useCallback(async D=>{const P=vs(D);if(!P)return;const H=Array.isArray(D.messages)?D.messages:[],W=ug({activeConv:D,visibleMessages:H,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:H.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),U=await u(P,"get_chat_debug_bundle",{...ks(D),delivery:"daemon_file",frontendSnapshot:W}),ae=Ks(U),be=pg(ae),V=await hg(be);V==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ct.showToast(mg(ae,{locatorCopyStatus:V}),V==="failed"?"warning":"success")},[d,u]),K=C||Q,R=l.useCallback(D=>{p&&(p(D),ct.showToast(L("mobileInbox.hiddenToast",{title:Rt(D)}),"info",{duration:6e3,actions:[{label:L("mobileInbox.undo"),variant:"primary",onClick:()=>{g?g(D):h()}}]}))},[p,h,g,L]);return n.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[n.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${F}`,children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:T}),n.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||s.length>0)&&n.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-2xs font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[n.jsx(js,{size:13}),n.jsx("span",{children:t.length+s.length})]}),n.jsx("button",{onClick:j,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:n.jsx(Or,{size:18})})]})]})}),n.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${q}`,children:[e==="machines"&&n.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?n.jsx(Ds,{icon:n.jsx(ln,{size:32}),title:L(_==="offline"?"mobileInbox.networkOffline":_==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:L(_==="offline"?"mobileInbox.waitingForNetwork":_==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):$?n.jsx(Ds,{icon:n.jsx(ln,{size:32}),title:L("mobileInbox.loading"),subtitle:L("mobileInbox.loadingSubtitle")}):i.length===0?n.jsx(Ds,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:L(S?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:L(S?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!S&&n.jsx("div",{className:"w-full max-w-[360px] mt-4",children:n.jsx(Hb,{})})}):n.jsx(hr,{children:i.map((D,P)=>n.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${P>0?"border-t border-border-subtle/70":""}`,onClick:()=>k(D.id),type:"button",children:[n.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(D.label)}),n.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-[15px] leading-[22px] font-bold text-text-primary truncate tracking-tight",children:D.label}),n.jsxs("span",{className:"flex items-center gap-2 text-2xs font-medium text-text-muted shrink-0",children:[n.jsx(wh,{count:D.generatingCount,label:L("mobileInbox.generatingCount",{count:D.generatingCount})}),D.unread>0?n.jsx("span",{className:"text-accent-primary",children:L("mobileInbox.newCount",{count:D.unread})}):D.total>0?L("mobileInbox.chatCount",{count:D.total}):L("mobileInbox.idle")]})]}),n.jsx("div",{className:"text-xs font-medium text-text-secondary truncate",children:D.subtitle}),D.total>0?n.jsxs("div",{className:"text-xxs text-text-muted mt-0.5",children:[L("mobileInbox.chatCount",{count:D.total}),D.unread>0?L("mobileInbox.unreadSuffix",{count:D.unread}):"",D.generatingCount>0?L("mobileInbox.collapsedGeneratingSuffix",{count:D.generatingCount}):""]}):D.generatingCount>0?n.jsx("div",{className:"text-xxs text-accent-primary mt-0.5 font-medium",children:L("mobileInbox.generatingCount",{count:D.generatingCount})}):n.jsx("div",{className:"text-xxs text-text-muted mt-0.5 italic opacity-70",children:L("mobileInbox.noActiveChats")})]})]},D.id))})}),e==="chats"&&t.length>0&&n.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[n.jsx(ha,{title:L("mobileInbox.needsAttention"),className:"mb-0"}),n.jsx(hr,{children:t.map((D,P)=>n.jsx("div",{className:P>0?"border-t border-border-subtle/70":"",children:n.jsx(pa,{item:D,type:"needs_attention",getAvatarText:c,onOpenConversation:m,onRequestHideConversation:p?()=>R(D.conversation):void 0,onRequestStopCli:x?()=>x(D.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:K,isMuted:A==null?void 0:A(D.conversation),onToggleMute:O?()=>O(D.conversation):void 0})},D.conversation.tabKey))})]}),e==="chats"&&s.length>0&&n.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[n.jsx(ha,{title:L("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),n.jsx(hr,{children:s.map((D,P)=>n.jsx("div",{className:P>0?"border-t border-border-subtle/70":"",children:n.jsx(pa,{item:D,type:"task_complete",getAvatarText:c,onOpenConversation:m,onRequestHideConversation:p?()=>R(D.conversation):void 0,onRequestStopCli:x?()=>x(D.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:K,isMuted:A==null?void 0:A(D.conversation),onToggleMute:O?()=>O(D.conversation):void 0})},D.conversation.tabKey))})]}),e==="chats"&&r.length>0&&n.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[n.jsx(ha,{title:L("mobileInbox.workingNow"),className:"mb-0 mt-2"}),n.jsx(hr,{children:r.map((D,P)=>n.jsx("div",{className:P>0?"border-t border-border-subtle/70":"",children:n.jsx(pa,{item:D,type:"working",getAvatarText:c,onOpenConversation:m,onRequestHideConversation:p?()=>R(D.conversation):void 0,onRequestStopCli:x?()=>x(D.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:K,isMuted:A==null?void 0:A(D.conversation),onToggleMute:O?()=>O(D.conversation):void 0})},D.conversation.tabKey))})]}),e==="chats"&&n.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&n.jsx(ha,{title:L("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?n.jsx(hr,{children:o.map((D,P)=>n.jsx("div",{className:P>0?"border-t border-border-subtle/70":"",children:n.jsx(pa,{item:D,type:"earlier",getAvatarText:c,onOpenConversation:m,onRequestHideConversation:p?()=>R(D.conversation):void 0,onRequestStopCli:x?()=>x(D.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:K,isMuted:A==null?void 0:A(D.conversation),onToggleMute:O?()=>O(D.conversation):void 0})},D.conversation.tabKey))}):B?n.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:L("mobileInbox.allCaughtUp")}):M?n.jsx(Ds,{icon:n.jsx(ln,{size:28}),title:L("mobileInbox.connecting"),subtitle:L("mobileInbox.connectingSubtitle")}):N?n.jsx(Ds,{icon:n.jsx(ln,{size:28}),title:L("mobileInbox.loading"),subtitle:L("mobileInbox.loadingSubtitle")}):I?n.jsx(Ds,{icon:n.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:n.jsx(Jn,{size:20})}),title:L("mobileInbox.noConversations"),subtitle:L("paneGroup.newSessionDescription"),children:b&&n.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:b,"aria-label":L("paneGroup.newSession"),title:L("paneGroup.newSession"),children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),n.jsx("span",{children:L("paneGroup.newSession")})]})}):n.jsx(Ds,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:L("mobileInbox.noMachinesConnected"),subtitle:L("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&a.length>0&&(()=>{const D=GS(a);return n.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:n.jsx(hr,{className:"mt-4 border-dashed bg-bg-secondary/20",children:n.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-xs font-bold uppercase tracking-wider text-text-secondary",children:L("mobileInbox.hiddenTabs")}),n.jsx(wh,{count:D,label:L("mobileInbox.generatingCount",{count:D})})]}),n.jsxs("div",{className:"mt-0.5 text-xxs text-text-muted",children:[L("mobileInbox.collapsedCount",{count:a.length}),D>0?L("mobileInbox.collapsedGeneratingSuffix",{count:D}):""]})]}),n.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-xs font-semibold text-accent-primary hover:border-border-default",onClick:h,children:L("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&b&&B&&n.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:b,"aria-label":L("paneGroup.newSession"),title:L("paneGroup.newSession"),children:n.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),n.jsx(Bb,{section:e,onSectionChange:v})]})}function sI(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function Wb(e,t){const s=[e.workspace||(t?t("launch.workspaceUnknown"):"Workspace unknown")],r=tr(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(t?t("launch.messageCountShort",{count:e.messageCount}):`${e.messageCount} msgs`);const o=sI(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:o?t?t("launch.updatedAt",{time:o}):`Updated ${o}`:"",preview:(e.preview||"").trim()}}function au({title:e,description:t,currentPath:s,directories:r,busy:o=!1,error:a="",confirmLabel:i,inline:c=!1,onClose:d,onNavigate:u,onConfirm:m}){const[h,p]=l.useState(s),{t:g}=ve("common"),f=i??g("machine.workspaceBrowse.useThisFolder");l.useEffect(()=>{p(s)},[s]);const x=P2(s),b=h.trim(),k=n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t&&!c&&n.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),n.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:d,"aria-label":g("common.close"),children:n.jsx(Bt,{size:16})})]}),n.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[n.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!x||o||u(x)},disabled:!x||o,children:[n.jsx(dd,{size:15}),g("machine.workspaceBrowse.parent")]}),n.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:g("machine.workspaceBrowse.currentFolder")}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"text",value:h,onChange:j=>p(j.target.value),onKeyDown:j=>{j.key!=="Enter"||!b||o||(j.preventDefault(),u(b))},placeholder:g("machine.workspaceBrowse.pathPlaceholder"),className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),n.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!b||o||u(b)},disabled:!b||o,children:g("machine.workspaceBrowse.go")})]})]})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?n.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:g("machine.workspaceBrowse.loading")}):a?n.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:a}):r.length===0?n.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:g("machine.workspaceBrowse.noSubfolders")}):n.jsx("div",{className:"p-3",children:r.map(j=>n.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(j.path),children:[n.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:n.jsx(Zs,{size:17})}),n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:j.name}),n.jsx("span",{className:"block text-2xs text-text-muted truncate",children:j.path})]})]},j.path))})}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[n.jsx("button",{type:"button",className:"btn btn-secondary h-9 px-4 text-sm",onClick:d,children:g("common.cancel")}),n.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(b||s),disabled:!b&&!s||o,children:f})]})]});return c?n.jsx("div",{className:"mt-3 flex max-h-[min(60vh,440px)] flex-col overflow-hidden rounded-xl border border-border-subtle bg-bg-secondary",role:"region","aria-labelledby":"workspace-browse-title","data-testid":"workspace-browse-inline",children:k}):n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:n.jsx("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:k})})})}function Ui({title:e,description:t,details:s,workspaceOptions:r,selectedWorkspaceKey:o,onWorkspaceChange:a,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:u,argsValue:m,onArgsChange:h,showModelInput:p,modelValue:g,onModelChange:f,historyProviderNode:x,onConfirm:b,onCancel:k}){const{t:j}=ve("common"),v=i??j("machine.launchConfirm.launch"),_=c??j("machine.launchConfirm.launching"),y=r==null?void 0:r.find(S=>S.key===o),w=n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:n.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),n.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),n.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:k,"aria-label":j("machine.launchConfirm.closeAria"),children:n.jsx(Bt,{size:16})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[r&&r.length>0&&a&&n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:j("machine.launchConfirm.workspace")}),n.jsx("select",{value:o||"",onChange:S=>a(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:r.map(S=>n.jsx("option",{value:S.key,children:S.label},S.key))}),(y==null?void 0:y.description)&&n.jsx("div",{className:"mt-2 text-2xs text-text-muted break-all",children:y.description})]}),x,s.map((S,C)=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:S.label}),n.jsx("div",{className:"text-sm text-text-primary break-all",children:S.value})]},`${S.label}:${C}`)),p&&f&&n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:j("machine.launchConfirm.languageModel")}),n.jsx("input",{type:"text",value:g||"",onChange:S=>f(S.target.value),placeholder:j("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),u&&h&&n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:j("machine.launchConfirm.cliArgs")}),n.jsx("input",{type:"text",value:m||"",onChange:S=>h(S.target.value),placeholder:j("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[n.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:k,disabled:d,children:j("machine.launchConfirm.cancel")}),n.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:d,children:[n.jsx(Yp,{size:14}),d?_:v]})]})]})});return typeof document>"u"?w:Qn.createPortal(w,document.body)}function Sh(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Ub(e){const{machine:t,currentWorkspacePath:s,currentWorkspaceId:r,includeHome:o=!0,homeLabel:a="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];o&&c.push({key:"__home__",label:a,description:i,workspaceId:null,workspacePath:null});for(const m of t.workspaces||[])c.push({key:`saved:${m.id}`,label:`${m.id===t.defaultWorkspaceId?"⭐ ":""}${Sh(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const d=(s==null?void 0:s.trim())||"",u=d?(t.workspaces||[]).find(m=>m.path===d):null;if(d&&!u&&c.push({key:`custom:${d}`,label:Sh(d),description:d,workspaceId:null,workspacePath:d}),r){const m=`saved:${r}`;if(c.some(h=>h.key===m))return{options:c,selectedKey:m}}return u?{options:c,selectedKey:`saved:${u.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function rI(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function oI(e,t){return[rI(e.kind),e.subtitle||"",e.providerSessionId?t?t("launch.savedHistoryBadge"):"Saved history":""].filter(Boolean).join(" · ")}function aI(e){return e.lastLaunchedAt?Si(e.lastLaunchedAt):""}function Kb(e,t){return{metaText:oI(e,t),updatedLabel:aI(e)}}function Tl(e,t,s){return e?"ide":t>0?"cli":s>0?"acp":null}function iI({selectedMachineEntry:e,cliProviders:t,acpProviders:s,machineAction:r,onBrowseDirectory:o,onListSavedSessions:a}){var ye,$e,Me,De;const i=Br(),[c,d]=l.useState(!1),u=(((ye=e.detectedIdes)==null?void 0:ye.length)||0)>0,m=l.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),h=e.defaultWorkspaceId||null,[p,g]=l.useState(h||(($e=m[0])==null?void 0:$e.id)||""),[f,x]=l.useState(""),[b,k]=l.useState(""),[j,v]=l.useState([]),[_,y]=l.useState(!1),[w,S]=l.useState(""),[C,A]=l.useState(!1),[O,L]=l.useState(Tl(u,t.length,s.length)),M=l.useRef(null),[$,N]=l.useState(null),I=l.useRef("__home__"),[B,T]=l.useState("__home__"),[F,q]=l.useState(""),[Q,K]=l.useState(""),[R,D]=l.useState(""),[P,H]=l.useState([]),[W,U]=l.useState(()=>yn().textQuery),[ae,be]=l.useState(()=>yn().workspaceQuery),[V,we]=l.useState(()=>yn().modelQuery),[ce,de]=l.useState(()=>yn().resumableOnly),[ne,ee]=l.useState(()=>yn().sortMode),[ue,je]=l.useState(!1),[X,G]=l.useState(!1),z=l.useRef(0),ie=l.useRef(0),Ne=l.useRef(null),Be=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const Le=p==="__custom__"?f.trim():((Me=m.find(Te=>Te.id===p))==null?void 0:Me.path)||"",Je=p==="__custom__"&&!!Le&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),Se=p!=="__custom__"&&((De=m.find(Te=>Te.id===p))==null?void 0:De.path)||"",he=l.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),pe=l.useCallback(async Te=>{const He=z.current+1;z.current=He,y(!0),S("");try{const tt=await o(Te);if(z.current!==He)return;k(tt.path),x(tt.path),v(tt.directories)}catch(tt){if(z.current!==He)return;S(tt instanceof Error?tt.message:"Could not load folder")}finally{z.current===He&&y(!1)}},[o]),Ee=l.useCallback(()=>{var He;g("__custom__"),A(!0);const Te=su(e.platform,nu(f.trim(),Se,he,e.defaultWorkspacePath,(He=m.find(tt=>tt.id===h))==null?void 0:He.path,m.map(tt=>tt.path)));pe(Te)},[f,h,pe,he,Se,e.platform,m]),Y=l.useCallback(Te=>{if(Te!=null&&Te.workspaceId){g(Te.workspaceId),x("");return}if(Te!=null&&Te.workspacePath){g("__custom__"),x(Te.workspacePath);return}g(""),x("")},[]),me=l.useCallback(Te=>{if(g(Te),Te==="__custom__"){Ee();return}x("")},[Ee]),fe=l.useCallback(Te=>{g("__custom__"),x(Te)},[]),E=l.useCallback((Te,He)=>{const tt=ie.current+1;ie.current=tt,M.current=He,I.current=Te.selectedWorkspaceKey||"__home__",T(Te.selectedWorkspaceKey||"__home__"),q(Te.initialArgs||""),K(Te.initialModel||""),D(""),H([]);const Ct=Te.providerType?`${e.id}:${Te.providerType}`:null;if(mA(Be.current,Ct)){const J=yn();U(J.textQuery),be(J.workspaceQuery),we(J.modelQuery),de(J.resumableOnly),ee(J.sortMode)}Be.current=Ct,N(Te),Te.providerType&&a?(je(!0),a(Te.providerType).then(J=>{ie.current===tt&&H(J||[])}).catch(J=>{ie.current===tt&&console.warn("Failed to load saved sessions",J)}).finally(()=>{ie.current===tt&&je(!1)})):je(!1)},[a,e.id]),oe=l.useMemo(()=>qd(P,{textQuery:W,workspaceQuery:ae,modelQuery:V,resumableOnly:ce,sortMode:ne}),[V,ce,P,ne,W,ae]);l.useEffect(()=>{R&&(oe.some(Te=>Te.providerSessionId===R)||D(""))},[oe,R]);const Ie=l.useCallback(()=>{M.current&&(G(!0),M.current().finally(()=>{M.current=null,G(!1),N(null)}))},[]),Z=l.useCallback(()=>{ie.current+=1,M.current=null,je(!1),N(null)},[]),se=l.useCallback(Te=>{I.current=Te,T(Te)},[]);return l.useEffect(()=>{var Te;Ne.current!==e.id&&(z.current+=1,ie.current+=1,Ne.current=e.id,g(h||((Te=m[0])==null?void 0:Te.id)||"__custom__"),x(""),k(""),v([]),y(!1),S(""),A(!1),M.current=null,N(null),H([]),je(!1),G(!1),U(yn().textQuery),be(yn().workspaceQuery),we(yn().modelQuery),de(yn().resumableOnly),ee(yn().sortMode),Be.current=null,L(Tl(u,t.length,s.length)))},[s.length,t.length,h,u,e.id,m]),l.useEffect(()=>{var Te;p!=="__custom__"&&(p&&m.some(He=>He.id===p)||g(h||((Te=m[0])==null?void 0:Te.id)||"__custom__"))},[h,p,m]),l.useEffect(()=>{O==="ide"&&u||O==="cli"&&t.length>0||O==="acp"&&s.length>0||L(Tl(u,t.length,s.length))},[O,s.length,t.length,u]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:u,workspaceRows:m,defaultWorkspaceId:h,workspaceChoice:p,customWorkspacePath:f,browseCurrentPath:b,browseDirectories:j,browseBusy:_,browseError:w,browseDialogOpen:C,activeLauncherKind:O,launchConfirm:$,launchConfirmWorkspaceKeyRef:I,launchConfirmWorkspaceKey:B,launchConfirmArgs:F,launchConfirmModel:Q,launchConfirmResumeId:R,launchConfirmSavedSessions:P,launchConfirmTextFilter:W,launchConfirmWorkspaceFilter:ae,launchConfirmModelFilter:V,launchConfirmResumableOnly:ce,launchConfirmSortMode:ne,filteredLaunchConfirmSavedSessions:oe,launchConfirmSessionsLoading:ue,launchConfirmBusy:X,resolvedWorkspacePath:Le,canCreateMissingWorkspace:Je,openBrowseDialog:Ee,loadBrowsePath:pe,handleWorkspaceChoiceChange:me,chooseCustomWorkspacePath:fe,setCustomWorkspacePath:x,setBrowseDialogOpen:A,setActiveLauncherKind:L,openLaunchConfirm:E,handleConfirmLaunch:Ie,closeLaunchConfirm:Z,setWorkspaceSelectionFromOption:Y,setLaunchConfirmWorkspaceKeyAndSync:se,setLaunchConfirmArgs:q,setLaunchConfirmModel:K,setLaunchConfirmResumeId:D,setLaunchConfirmTextFilter:U,setLaunchConfirmWorkspaceFilter:be,setLaunchConfirmModelFilter:we,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:ee}}function lI({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:s,cliProviders:r,acpProviders:o,selectedMachineNeedsUpgrade:a,appVersion:i,machineAction:c,isStandalone:d,section:u,showBottomNav:m,onBack:h,onSectionChange:p,onOpenConversation:g,onOpenRecent:f,onOpenMachineDetails:x,onMachineUpgrade:b,onBrowseDirectory:k,onListSavedSessions:j}){const{t:v}=ve("common"),_=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",y=s.slice(0,4),w=t.slice(0,3),S=iI({selectedMachineEntry:e,cliProviders:r,acpProviders:o,machineAction:c,onBrowseDirectory:k,onListSavedSessions:j}),C=l.useMemo(()=>y.map(N=>{const{metaText:I,updatedLabel:B}=Kb(N,v);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:I,updatedLabel:B,onClick:()=>{const{options:T,selectedKey:F}=Ub({machine:{workspaces:S.workspaceRows,defaultWorkspaceId:S.defaultWorkspaceId},currentWorkspacePath:N.workspace,homeLabel:v("newSession.homeDirectory"),homeDescription:v("newSession.launchWithoutWorkspace")});S.openLaunchConfirm({title:N.kind==="ide"?ti(v,"restart-ide",N.label):N.providerSessionId?ob(v,N.label):ti(v,"start-fresh",N.label),description:N.kind==="ide"?ni(v,"restart-ide"):N.providerSessionId?ab(v):ni(v,"start-fresh"),confirmLabel:N.kind==="ide"?si(v,"restart-ide"):N.providerSessionId?Lc(v,!0):si(v,"start-fresh"),busyLabel:N.kind==="ide"?ri(v,"restart-ide"):N.providerSessionId?sb(v,!0):ri(v,"start-fresh"),workspaceOptions:T,selectedWorkspaceKey:F,details:[{label:"Mode",value:_(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const q=T.find(Q=>Q.key===S.launchConfirmWorkspaceKeyRef.current);S.setWorkspaceSelectionFromOption(q),await f({...N,workspace:(q==null?void 0:q.workspacePath)??null})})}}}),[S,f,y,v]),A=l.useMemo(()=>w.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,conversation:N.conversation,primary:Rt(N.conversation),secondary:$_(N.conversation,{timestampLabel:N.timestamp?of(N.timestamp):null}),unread:N.unread,onClick:()=>g(N.conversation)})),[g,w]),O=S.showAllRecent?C:C.slice(0,4),L=C.length>0,M=A.length>0,$=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`flex items-center justify-between gap-3 ${$} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:n.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[n.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":v("common.back"),children:n.jsx(dd,{size:18})}),n.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[n.jsx("div",{className:"flex items-center gap-2 text-[17px] leading-[26px] font-extrabold tracking-tight text-text-primary truncate",children:Tn(e,{fallbackId:e.id})}),n.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||v("machine.mobile.machineFallback"),e.version?` · v${e.version}`:""]})]})]})}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[M&&n.jsxs("section",{className:"flex flex-col gap-0",children:[n.jsx("div",{className:"text-2xs font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:v("machine.mobile.currentChats")}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(N=>n.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${N.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:N.onClick,children:[n.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 text-sm font-bold text-text-primary",children:[n.jsx(_s,{conversation:N.conversation,size:13}),n.jsx("span",{className:"min-w-0 truncate",children:N.primary})]}),n.jsxs("span",{className:"text-xs leading-relaxed text-text-secondary",children:[n.jsx(Wr,{conversation:N.conversation,separator:!0}),N.secondary]})]},N.key))})]}),L&&n.jsxs("section",{className:"flex flex-col gap-0",children:[n.jsx("div",{className:"text-2xs font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:v("machine.mobile.recentLaunches")}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:O.map(N=>n.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:N.onClick,children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[n.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:N.primary}),N.updatedLabel&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:N.updatedLabel})]}),n.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))}),C.length>4&&n.jsx("div",{className:"flex justify-center px-4 pt-2",children:n.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>S.setShowAllRecent(N=>!N),children:S.showAllRecent?v("machine.mobile.showFewer"):v("machine.mobile.showMore",{count:C.length-4})})})]}),n.jsxs("section",{className:"flex flex-col gap-0",children:[n.jsx("div",{className:"text-2xs font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:v("machine.mobile.inspect")}),n.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[a&&n.jsx("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:b,children:n.jsx("span",{className:"text-sm font-bold text-text-primary",children:v("machine.commandCenter.updateToVersion",{version:i})})}),n.jsx("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:x,children:n.jsx("span",{className:"text-sm font-bold text-text-primary",children:v("machine.mobile.machineDetails")})})]})]})]}),S.browseDialogOpen&&n.jsx(au,{title:v("machine.mobile.browseTitle"),description:v("machine.mobile.browseDescription"),currentPath:S.browseCurrentPath,directories:S.browseDirectories,busy:S.browseBusy,error:S.browseError,confirmLabel:v("machine.mobile.useThisFolder"),onClose:()=>S.setBrowseDialogOpen(!1),onNavigate:N=>{S.loadBrowsePath(N)},onConfirm:N=>{S.chooseCustomWorkspacePath(N),S.setBrowseDialogOpen(!1)}}),S.launchConfirm&&n.jsx(Ui,{title:S.launchConfirm.title,description:S.launchConfirm.description,details:S.launchConfirm.details,workspaceOptions:S.launchConfirm.workspaceOptions,selectedWorkspaceKey:S.launchConfirmWorkspaceKey,onWorkspaceChange:S.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:S.launchConfirm.providerType?Lc(v,!!S.launchConfirmResumeId):S.launchConfirm.confirmLabel,busyLabel:S.launchConfirm.providerType?void 0:S.launchConfirm.busyLabel,busy:S.launchConfirmBusy,showArgsInput:S.launchConfirm.showArgsInput,argsValue:S.launchConfirmArgs,onArgsChange:S.setLaunchConfirmArgs,showModelInput:S.launchConfirm.showModelInput,modelValue:S.launchConfirmModel,onModelChange:S.setLaunchConfirmModel,historyProviderNode:S.launchConfirm.providerType&&(S.launchConfirmSessionsLoading||S.launchConfirmSavedSessions.length>0)&&n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsxs("div",{className:"flex items-center justify-between mb-1",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted",children:v("launch.resumeSavedHistory")}),S.launchConfirmSessionsLoading&&n.jsx("div",{className:"text-3xs text-text-secondary font-medium",children:v("launch.loadingShort")})]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2",children:zd(v)}),n.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[n.jsx("input",{type:"text",value:S.launchConfirmTextFilter,onChange:N=>S.setLaunchConfirmTextFilter(N.target.value),placeholder:v("machine.mobile.searchHistory"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:S.launchConfirmBusy||S.launchConfirmSessionsLoading}),n.jsx("input",{type:"text",value:S.launchConfirmWorkspaceFilter,onChange:N=>S.setLaunchConfirmWorkspaceFilter(N.target.value),placeholder:v("machine.mobile.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:S.launchConfirmBusy||S.launchConfirmSessionsLoading}),n.jsx("input",{type:"text",value:S.launchConfirmModelFilter,onChange:N=>S.setLaunchConfirmModelFilter(N.target.value),placeholder:v("machine.mobile.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:S.launchConfirmBusy||S.launchConfirmSessionsLoading}),n.jsxs("select",{value:S.launchConfirmSortMode,onChange:N=>S.setLaunchConfirmSortMode(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:S.launchConfirmBusy||S.launchConfirmSessionsLoading,children:[n.jsx("option",{value:"recent",children:v("machine.mobile.sortRecent")}),n.jsx("option",{value:"oldest",children:v("machine.mobile.sortOldest")}),n.jsx("option",{value:"messages",children:v("machine.mobile.sortMessages")})]})]}),n.jsxs("label",{className:"mb-2 flex items-center gap-2 text-2xs text-text-muted",children:[n.jsx("input",{type:"checkbox",checked:S.launchConfirmResumableOnly,onChange:N=>S.setLaunchConfirmResumableOnly(N.target.checked),disabled:S.launchConfirmBusy||S.launchConfirmSessionsLoading}),v("machine.mobile.resumableOnly")]}),n.jsxs("select",{value:S.launchConfirmResumeId,onChange:N=>S.setLaunchConfirmResumeId(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:S.launchConfirmBusy||S.launchConfirmSessionsLoading,children:[n.jsx("option",{value:"",children:fA(v)}),S.filteredLaunchConfirmSavedSessions.map(N=>n.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":v("machine.mobile.workspaceMissing")]},N.providerSessionId))]}),!S.launchConfirmSessionsLoading&&S.launchConfirmSavedSessions.length>0&&S.filteredLaunchConfirmSavedSessions.length===0&&n.jsx("div",{className:"mt-2 text-2xs text-text-muted",children:v("machine.mobile.noHistoryMatches")}),S.launchConfirmResumeId&&(()=>{const N=S.filteredLaunchConfirmSavedSessions.find(B=>B.providerSessionId===S.launchConfirmResumeId);if(!N)return null;const I=Wb(N,v);return n.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-2xs text-text-muted leading-relaxed",children:[n.jsx("div",{className:"font-semibold text-text-primary truncate",children:I.title}),n.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),n.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&n.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&n.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:S.handleConfirmLaunch,onCancel:S.closeLaunchConfirm}),m&&n.jsx(Bb,{section:u,onSectionChange:p})]})}const kh=8e3;function cI(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,s=t&&typeof t=="object",r=s&&t.success===!1,o=s&&t.mirrorStale===!0;return!r&&!o?{confirmed:!0}:{confirmed:!1,reason:r&&typeof t.error=="string"?t.error:o?"the coordinator did not confirm the change":"command was rejected"}}function qb(e,t,s){const r=l.useRef(new Map),[,o]=l.useState(0),a=l.useCallback(()=>o(g=>g+1),[]);l.useEffect(()=>{const g=r.current;if(g.size===0)return;const f=Date.now();let x=!1;for(const[b,k]of g){const j=e.get(b),v=k.muted===void 0||(j?j.muted===k.muted:!1),_=k.hidden===void 0||(j?j.surfaceHidden===k.hidden:!1),y=f-k.at>kh;(v&&_||y)&&(g.delete(b),x=!0)}x&&a()},[e,a]),l.useEffect(()=>{if(r.current.size===0)return;const g=setInterval(()=>{const f=r.current,x=Date.now();let b=!1;for(const[k,j]of f)x-j.at>kh&&(f.delete(k),b=!0);b&&a(),f.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,f)=>{const x=r.current.get(g);r.current.set(g,{...x,...f,at:Date.now()}),a()},[a]),c=l.useCallback(g=>{const f=g.sessionId,x=f?r.current.get(f):void 0;return(x==null?void 0:x.muted)!==void 0?x.muted:Ns(g,e).muted??!1},[e]),d=l.useCallback(g=>{const f=g.sessionId,x=f?r.current.get(f):void 0;return(x==null?void 0:x.hidden)!==void 0?x.hidden:Ns(g,e).surfaceHidden??!1},[e]),u=l.useCallback((g,f)=>{const x=as(g),b=g.sessionId;!x||!b||(i(b,f),t(x,"set_conversation_prefs",{sessionId:b,...f,...Ri(g)}).then(k=>{const j=cI(k);j.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",j.reason),r.current.delete(b),a(),s==null||s(`Couldn't update conversation — ${j.reason}`))}).catch(k=>{console.warn("[conversation-prefs] set_conversation_prefs failed",k),r.current.delete(b),a();const j=k instanceof Error?k.message:String(k??"the daemon is unreachable");s==null||s(`Couldn't update conversation — ${j}`)}))},[t,i,a,s]),m=l.useCallback(g=>{u(g,{muted:!c(g)})},[u,c]),h=l.useCallback((g,f)=>{u(g,{hidden:f})},[u]),p=l.useCallback(g=>{u(g,{hidden:!d(g)})},[u,d]);return{isMuted:c,isHidden:d,toggleMute:m,setHidden:h,toggleHidden:p}}function Oa(e){return[...e].sort((t,s)=>{const r=s.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(s.conversation.tabKey)})}function dI(e,t=[]){const s=new Map(e.map(o=>[o.conversation.tabKey,o])),r=t.map(o=>s.get(o)).filter(o=>!!o);return r.length===e.length?r:Oa(e)}function uI(e,t=[]){const s=e.filter(i=>i.requiresAction),r=e.filter(i=>i.unread&&!i.requiresAction),o=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),a=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:Oa(s),unreadItems:Oa(r),workingItems:dI(o,t),completedItems:Oa(a)}}function Ki(e,t){if(!t)return!1;const s=e.filter(r=>r.type==="adhdev-daemon"&&zb(r)==="Connected");return s.length===0?!0:s.every(r=>r._sessionListAuthoritative===!0)}function zb(e){var r,o,a;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((o=e.p2p)!=null&&o.available)||!!((a=e.p2p)!=null&&a.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function mI(e,t){if(!e)return[];const s=e.recentLaunches||[];return s.length>0?s.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:tr(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var i;const o=To(r)?"cli":Nr(r)?"acp":"ide",a=tr(r.summaryMetadata);return{id:`${o}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(To(r)?r.cliName||r.type:Nr(r)&&r.cliName||r.type),kind:o,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:Nr(r)?a||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,o)=>o.timestamp-r.timestamp).map(({timestamp:r,...o})=>o)}function hI(e,t,s=[]){const r=new Map;for(const a of t){const i=as(a.conversation),c=r.get(i);c?c.push(a):r.set(i,[a])}const o=new Map;for(const a of s){const i=as(a),c=o.get(i);c?c.push(a):o.set(i,[a])}return e.map(a=>{const i=r.get(a.id)||[],c=o.get(a.id)||[],d=[...i].sort((x,b)=>b.timestamp-x.timestamp)[0]||null,u=(d==null?void 0:d.conversation)||null,m=wc(a),h=i.filter(x=>x.unread||x.requiresAction).length,p=i.filter(x=>er(x.conversation)).length+c.filter(er).length,g=zb(a),f=[a.platform||"machine",g].filter(Boolean);return{id:a.id,label:Tn(a,{fallbackId:a.id}),subtitle:f.join(" · "),unread:h,total:i.length,generatingCount:p,latestConversation:u,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:m,preview:u?F_(u,_g(u)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((a,i)=>{const c=a.latestTimestamp||a.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==c?d-c:a.label.localeCompare(i.label)})}function pI(e){return e==="chat"}function fa(e,t){var s;if(!(typeof window>"u"))try{if(!(!!((s=import.meta.env)!=null&&s.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function fI({conversations:e,machineEntries:t,items:s,selectedConversation:r,selectedTabKey:o,screen:a,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:g,setSelectedTabKey:f,setScreen:x,setSelectedMachineId:b,setSection:k,setMachineBackTarget:j,resetMachineAction:v}){const _=l.useRef(null),y=l.useCallback(w=>{if(!(w!=null&&w.sessionId))return;const S=Ns(w,i),C=Math.max(Date.now(),Qs(w),S.lastUpdated||0);fa("mark_read:start",{tabKey:w.tabKey,sessionId:w.sessionId,displayPrimary:Rt(w),inboxBucket:S.inboxBucket,unread:S.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:Qs(w),readAt:C}),c(as(w)||w.routeId,"mark_session_seen",{sessionId:w.sessionId,providerSessionId:w.providerSessionId,seenAt:C,completionMarker:S.completionMarker}).then(A=>{fa("mark_read:result",{tabKey:w.tabKey,sessionId:w.sessionId,result:A})}).catch(A=>{fa("mark_read:error",{tabKey:w.tabKey,sessionId:w.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var S;if(!r){pI(a)&&x("inbox"),f(((S=e[0])==null?void 0:S.tabKey)||null),_.current=null;return}if(a!=="chat"){_.current=null;return}const w=`${r.tabKey}:${r.sessionId||""}`;_.current!==w&&(_.current=w,y(r))},[e,y,a,r,x,f]),l.useEffect(()=>{if(!d)return;const w=e.find(S=>S.tabKey===d);w&&(f(w.tabKey),x("chat"),u==null||u())},[e,u,d,x,f]),l.useEffect(()=>{if(!m)return;const w=t.find(S=>S.id===m);w&&(b(w.id),v(),k("machines"),j("inbox"),x("machine"),h==null||h())},[t,h,m,v,j,x,k,b]),l.useEffect(()=>{p&&(k(p),x("inbox"),g==null||g())},[g,p,x,k]),l.useEffect(()=>{const w=s.filter(S=>S.inboxBucket==="task_complete"||S.unread);w.length!==0&&fa("inbox_state",{screen:a,selectedTabKey:o,items:w.map(S=>{const C=Ns(S.conversation,i);return{liveState:C,tabKey:S.conversation.tabKey,sessionId:S.conversation.sessionId,displayPrimary:Rt(S.conversation),serverBucket:C.inboxBucket,computedBucket:S.inboxBucket,serverUnread:C.unread,computedUnread:S.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:Qs(S.conversation)}})})},[s,i,a,o]),{markConversationRead:y}}const gI="Cannot update: node update policy unavailable; refresh and try again";async function bI(e,t,s){var o,a,i,c,d,u;const r=eu(s);if(!r)return{state:"error",message:gI};try{const m=await e(t,"daemon_upgrade",r);return(o=m==null?void 0:m.result)!=null&&o.alreadyLatest?{state:"done",message:`Already on v${((a=m==null?void 0:m.result)==null?void 0:a.version)||"latest"}.`}:(i=m==null?void 0:m.result)!=null&&i.upgraded||(c=m==null?void 0:m.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((d=m==null?void 0:m.result)==null?void 0:d.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((u=m==null?void 0:m.result)==null?void 0:u.error)||"Upgrade failed"}}catch(m){return{state:"error",message:m instanceof Error?m.message:"Upgrade failed"}}}function xI(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function jh(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function yI(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function vI({sendDaemonCommand:e,navigate:t,ides:s,conversations:r}){const{launchCli:o}=wi(),[a,i]=l.useState("idle"),[c,d]=l.useState(""),[u,m]=l.useState(null),h=l.useCallback(()=>{i("idle"),d(""),m(null)},[]),p=l.useCallback(async(v,_,y)=>{var w;try{i("loading"),d(`Launching ${_}…`);const S={ideType:_,enableCdp:!0};(w=y==null?void 0:y.workspacePath)!=null&&w.trim()&&(S.workspace=y.workspacePath.trim()),await e(v,"launch_ide",S),i("done"),d(`${_} launch requested`)}catch(S){i("error"),d(S instanceof Error?S.message:"Launch IDE failed"),console.error("Launch IDE failed",S)}},[e]),g=l.useCallback(async(v,_,y)=>{if(_.trim())try{i("loading"),d(y!=null&&y.createIfMissing?"Creating folder…":"Saving workspace…");const w=await e(v,"workspace_add",{path:_.trim(),createIfMissing:(y==null?void 0:y.createIfMissing)===!0});if(w!=null&&w.success){i("done"),d(y!=null&&y.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((w==null?void 0:w.error)||"Could not save workspace")}catch(w){i("error"),d(w instanceof Error?w.message:"Could not save workspace")}},[e]),f=l.useCallback(async v=>{i("loading"),d("Starting daemon upgrade…");const _=s.find(w=>w.id===v||w.daemonId===v),y=await bI(e,v,_);i(y.state),d(y.message)},[s,e]),x=l.useCallback(async(v,_,y,w)=>{var A,O,L;const S=Date.now(),C={machineId:v,kind:_,providerType:y,workspaceId:(w==null?void 0:w.workspaceId)||null,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:S};try{i("loading"),d(`Launching ${y}…`),m(C);const M={cliType:y};(A=w==null?void 0:w.workspacePath)!=null&&A.trim()?M.dir=w.workspacePath.trim():w!=null&&w.workspaceId?M.workspaceId=w.workspaceId:w!=null&&w.useHome&&(M.useHome=!0),w!=null&&w.resumeSessionId&&(M.resumeSessionId=w.resumeSessionId),(O=w==null?void 0:w.args)!=null&&O.trim()&&(M.cliArgs=w.args.trim().split(/\s+/).filter(Boolean)),(L=w==null?void 0:w.model)!=null&&L.trim()&&(M.initialModel=w.model.trim());const $=await o(v,M),N=($==null?void 0:$.result)||$,I=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);if($!=null&&$.success&&I){m(null),i("done"),d(`${y} launched`),t(Io(I));return}if($!=null&&$.success){i("loading"),d(`${y} launch requested — waiting for session…`);return}m(null),i("error"),d(($==null?void 0:$.error)||(N==null?void 0:N.error)||`Could not launch ${_.toUpperCase()} workspace`)}catch(M){if(yI(M)){i("loading"),d(`${y} launch requested — waiting for session…`);return}m(null),i("error"),d(M instanceof Error?M.message:`Could not launch ${_.toUpperCase()} workspace`)}},[t,e]),b=l.useCallback(async(v,_)=>{try{const y=await e(v,"list_saved_sessions",{providerType:_,kind:"cli",limit:30}),w=(y==null?void 0:y.result)??y;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(y){return console.error("Failed to list saved sessions on mobile:",y),[]}},[e]),k=l.useCallback(async(v,_)=>ru(e,v,_),[e]);l.useEffect(()=>{if(!u)return;const v=jh(u.workspacePath),_=s.find(w=>{var M,$,N,I;if(!w||w.type==="adhdev-daemon"||xI(w.daemonId||w.id)!==u.machineId||(w.transport==="acp"?"acp":w.transport==="pty"?"cli":null)!==u.kind||String(w.agentType||w.type||"")!==u.providerType)return!1;const O=String(w.providerSessionId||"");if(u.resumeSessionId&&O)return O===u.resumeSessionId;if(v){const B=jh(w.workspace||w.runtimeWorkspaceLabel);return B?B===v:!1}return Number(w.lastUpdated||w._lastUpdate||w.timestamp||((I=(N=($=(M=w.activeChat)==null?void 0:M.messages)==null?void 0:$.at)==null?void 0:N.call($,-1))==null?void 0:I.timestamp)||0)>=u.startedAt-5e3});if(!_)return;const y=$b({entrySessionId:_.sessionId,entryInstanceId:_.instanceId,entryRouteId:_.id,conversations:r});y&&(m(null),i("done"),d(`${u.providerType} launched`),t(Io(y)))},[r,s,t,u]),l.useEffect(()=>{if(!u)return;const v=window.setTimeout(()=>{m(_=>!_||_.startedAt!==u.startedAt?_:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(v)},[u]);const j=l.useCallback(async(v,_)=>{var y;if(_.kind==="ide"&&_.providerType){await p(v,_.providerType,{workspacePath:_.workspace||null});return}if((_.kind==="cli"||_.kind==="acp")&&_.providerType){const w=((y=_.workspace)==null?void 0:y.trim())||"";await x(v,_.kind,_.providerType,{workspacePath:w||null,useHome:!w,resumeSessionId:_.providerSessionId||null})}},[p,x]);return{machineAction:{state:a,message:c},resetMachineAction:h,handleLaunchDetectedIde:p,handleAddWorkspace:g,handleMachineUpgrade:f,handleLaunchWorkspaceProvider:x,handleListSavedSessions:b,handleBrowseDirectory:k,handleOpenRecent:j}}function wI({conversations:e,selectedConversation:t,machineBackTarget:s,markConversationRead:r,resetMachineAction:o,setSelectedTabKey:a,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:u}){const m=l.useCallback(k=>{a(k.tabKey),i("chat"),r(k)},[r,i,a]),h=l.useCallback(k=>{const j=e.find(v=>v.routeId===k.routeId&&v.streamSource==="native");j&&(a(j.tabKey),i("chat"),r(j))},[e,r,i,a]),p=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),g=l.useCallback((k,j="inbox")=>{c(k),o(),d("machines"),u(j),i("machine")},[o,u,i,d,c]),f=l.useCallback(k=>{const j=as(k);j&&g(j,"chat")},[g]),x=l.useCallback(()=>{o(),i(s)},[s,o,i]),b=l.useCallback(k=>{d(k),i("inbox")},[i,d]);return{openConversation:m,openNativeConversation:h,backFromConversation:p,openMachine:g,openConversationMachine:f,backFromMachine:x,changeMachineSection:b}}function Mo(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function SI(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function kI({conversations:e,hiddenConversations:t,ides:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:g,onOpenHistory:f,onOpenRemote:x,onStopCli:b,wsStatus:k,isConnected:j,initialDataLoaded:v=!0,onShowAllHiddenConversations:_,onHideConversation:y,onShowHiddenConversation:w,onOpenMeshGraph:S,onOpenNewSession:C,liveSessionInboxState:A,setCliViewModeOverrides:O}){const[L,M]=l.useState(()=>{var Y;return((Y=e[0])==null?void 0:Y.tabKey)||null}),[$,N]=l.useState(()=>e[0]?"chat":"inbox"),[I,B]=l.useState("chats"),[T,F]=l.useState(null),[q,Q]=l.useState("inbox"),K=l.useRef([]),R=rr(),D="1.0.59",P=l.useMemo(()=>e.find(Y=>Y.tabKey===L)||e[0]||null,[e,L]),H=l.useMemo(()=>P?s.find(Y=>Y.id===P.routeId):void 0,[s,P]),W=l.useMemo(()=>!P||vt(P)||!St(P)?null:Hr(P),[P]),U=l.useMemo(()=>s.filter(Y=>Y.type==="adhdev-daemon").sort(za),[s]),ae=l.useMemo(()=>U.find(Y=>Y.id===T)||null,[U,T]),be=Li({sendDaemonCommand:o,activeConv:P||void 0,setActionLogs:a,isStandalone:i}),V=vI({sendDaemonCommand:o,navigate:R,ides:s,conversations:e}),we=OC(e),ce=l.useMemo(()=>e.map(Y=>{const me=$==="chat"&&(P==null?void 0:P.tabKey)===Y.tabKey,fe=Ci(Y,A,{hideOpenTaskCompleteUnread:!0,isOpenConversation:me}),E=Qs(Y),oe=_g(Y),Ie=Og(Y,oe);return{conversation:Y,timestamp:E,preview:Ie,unread:fe.unread,requiresAction:fe.requiresAction,isWorking:fe.isWorking,inboxBucket:fe.inboxBucket}}),[e,A,$,P,we]),{markConversationRead:de}=fI({conversations:e,machineEntries:U,items:ce,selectedConversation:P,selectedTabKey:L,screen:$,liveSessionInboxState:A,sendDaemonCommand:o,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:g,setSelectedTabKey:M,setScreen:N,setSelectedMachineId:F,setSection:B,setMachineBackTarget:Q,resetMachineAction:V.resetMachineAction}),ne=wI({conversations:e,selectedConversation:P,machineBackTarget:q,markConversationRead:de,resetMachineAction:V.resetMachineAction,setSelectedTabKey:M,setScreen:N,setSelectedMachineId:F,setSection:B,setMachineBackTarget:Q}),{isMuted:ee,toggleMute:ue}=qb(A,o),{attentionItems:je,unreadItems:X,workingItems:G,completedItems:z}=l.useMemo(()=>uI(ce,K.current),[ce]);l.useEffect(()=>{K.current=G.map(Y=>Y.conversation.tabKey)},[G]);const ie=l.useMemo(()=>ae?ce.filter(Y=>as(Y.conversation)===ae.id):[],[ce,ae]),Ne=l.useMemo(()=>mI(ae,s),[s,ae]),Be=!!ae&&tu(ae,Bs(ae,D)),Le=l.useMemo(()=>(ae==null?void 0:ae.availableProviders)||[],[ae]),Je=l.useMemo(()=>Le.filter(Y=>Mo(Y,"cli")).map(Y=>({type:Y.type,displayName:Y.displayName||Y.type,icon:Y.icon})),[Le]),Se=l.useMemo(()=>Le.filter(Y=>Mo(Y,"acp")).map(Y=>({type:Y.type,displayName:Y.displayName||Y.type,icon:Y.icon})),[Le]),he=l.useMemo(()=>hI(U,ce,t),[ce,U,t]),pe=l.useMemo(()=>Ki(s,v),[s,v]),Ee=l.useCallback(async Y=>{ae&&await V.handleOpenRecent(ae.id,Y)},[V,ae]);return n.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:$==="chat"&&P?n.jsx(Z2,{selectedConversation:P,isAcp:vt(P),isStandalone:i,selectedIdeEntry:H,actionLogs:r,userName:c,commands:be,onBack:ne.backFromConversation,onOpenNativeConversation:ne.openNativeConversation,onOpenMachine:ne.openConversationMachine,onOpenHistory:f,onOpenRemote:x,onOpenMeshGraph:S,onStopCli:b,cliViewMode:W,onSetCliViewMode:async Y=>{await Cb({conversation:P,mode:Y,ides:s,sendDaemonCommand:o,setCliViewModeOverrides:O})}}):$==="machine"&&ae?n.jsx(lI,{selectedMachineEntry:ae,selectedMachineConversations:ie,selectedMachineRecentLaunches:Ne,cliProviders:Je,acpProviders:Se,selectedMachineNeedsUpgrade:Be,appVersion:D,machineAction:V.machineAction,isStandalone:i,section:I,showBottomNav:q==="inbox",onBack:ne.backFromMachine,onSectionChange:ne.changeMachineSection,onOpenConversation:ne.openConversation,onOpenRecent:Ee,onOpenMachineDetails:()=>R(`/machines/${ae.id}`),onMachineUpgrade:()=>V.handleMachineUpgrade(ae.id),onBrowseDirectory:Y=>V.handleBrowseDirectory(ae.id,Y),onListSavedSessions:Y=>V.handleListSavedSessions(ae.id,Y)}):n.jsx(nI,{section:I,attentionItems:je,unreadItems:X,workingItems:G,completedItems:z,hiddenConversations:t,machineCards:he,getAvatarText:SI,actionLogs:r,sendDaemonCommand:o,onOpenConversation:ne.openConversation,onShowAllHidden:_,onHideConversation:y,onShowHiddenConversation:w,onOpenMeshGraph:S,onStopCli:b,onOpenNewSession:C,onOpenMachine:ne.openMachine,onOpenSettings:()=>R("/settings"),onSectionChange:B,wsStatus:k,isConnected:j,initialDataLoaded:v,conversationsLoaded:pe,isStandalone:i,isConversationMuted:ee,onToggleMuteConversation:ue})})}function Il(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function jI({conversations:e,numGroups:t,onMoveTab:s,onReceiveTab:r,onOwnTabDrop:o,onClearPreviewOrder:a}){const i=l.useRef(0),[c,d]=l.useState(!1),[u,m]=l.useState(null),h=l.useCallback(()=>{i.current=0,d(!1),m(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const p=l.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!Il(t,s)){m("merge");return}const k=b.currentTarget.getBoundingClientRect(),j=b.clientX-k.left,v=k.width/3;j<v?m("split-left"):j>v*2?m("split-right"):m("merge")},[t,s]),f=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),m(null))},[]),x=l.useCallback(b=>{i.current=0,d(!1);const k=b.dataTransfer.getData("text/tab-key"),j=k?e.some(_=>_.tabKey===k):!1,v=u;if(m(null),a(),!!k){if(b.preventDefault(),v==="split-left"&&Il(t,s)){s==null||s(k,"split-left");return}if(v==="split-right"&&Il(t,s)){s==null||s(k,"split-right");return}if(j){o(k);return}r==null||r(k)}},[e,u,t,s,r,o,a]);return{dragOver:c,dropAction:u,resetDragState:h,handleDragEnter:p,handleDragOver:g,handleDragLeave:f,handleDrop:x}}function NI(e,t){const s=new Set(t.map(a=>a.tabKey)),r=e.filter(a=>s.has(a)),o=t.filter(a=>!e.includes(a.tabKey)).map(a=>a.tabKey);return[...r,...o]}function CI({conversations:e,initialActiveTabId:t,initialTabOrder:s,onActiveTabChange:r,onTabOrderChange:o}){const[a,i]=l.useState(t??null),[c,d]=l.useState(s??[]),[u,m]=l.useState(null),h=l.useRef(null),p=l.useRef(null),g=l.useRef(r),f=l.useRef(o);l.useEffect(()=>{g.current=r},[r]),l.useEffect(()=>{f.current=o},[o]),l.useEffect(()=>{t&&t!==a&&i(t)},[t,a]),l.useEffect(()=>{d(S=>{const C=NI(S,e);return C.length===S.length&&C.every((A,O)=>A===S[O])?S:C})},[e]);const x=l.useMemo(()=>{const S=u??c;if(S.length===0)return e;const C=new Map(S.map((A,O)=>[A,O]));return[...e].sort((A,O)=>{const L=C.get(A.tabKey)??999,M=C.get(O.tabKey)??999;return L-M})},[e,u,c]);l.useEffect(()=>{var C,A;if(x.length===0){a!==null&&(i(null),(C=g.current)==null||C.call(g,null));return}if(a&&x.some(O=>O.tabKey===a))return;const S=x[0].tabKey;S!==a&&(i(S),(A=g.current)==null||A.call(g,S))},[x,a]);const b=l.useMemo(()=>x.find(S=>S.tabKey===a),[x,a]),k=l.useCallback(S=>{var C;i(S),(C=g.current)==null||C.call(g,S)},[]),j=l.useCallback((S,C,A)=>{d(O=>{var N;const L=O.filter(I=>I!==S),M=L.indexOf(C);if(M<0)return O;const $=A==="left"?M:M+1;return L.splice($,0,S),(N=f.current)==null||N.call(f,L),L}),m(null)},[]),v=l.useCallback((S,C,A)=>{const L=(c.length>0?c:e.map(N=>N.tabKey)).filter(N=>N!==S),M=L.indexOf(C);if(M<0)return;const $=A==="left"?M:M+1;L.splice($,0,S),h.current=L,m(L)},[c,e]),_=l.useCallback(()=>{var C;const S=h.current;S&&(d(S),(C=f.current)==null||C.call(f,S))},[]),y=l.useCallback(()=>{h.current=null,m(null)},[]),w=l.useCallback(S=>{d(C=>{var O;const A=C.filter(L=>L!==S);return A.push(S),(O=f.current)==null||O.call(f,A),A})},[]);return{activeTabId:a,activeConv:b,sortedConversations:x,previewOrderRef:h,draggingTabRef:p,selectTab:k,handleTabReorder:j,updatePreviewOrder:v,commitPreviewOrder:_,clearPreviewOrder:y,moveTabToEnd:w,setDraggingTabKey:S=>{p.current=S}}}function _I({dropAction:e,canSplit:t}){const{t:s}=ve("common");return n.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[n.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:n.jsx("div",{className:"px-3 py-1.5 rounded-full text-2xs font-semibold text-white bg-black/45 backdrop-blur-sm",children:s("paneGroup.dropSplitLeft")})}),n.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:n.jsx("div",{className:"px-3 py-1.5 rounded-full text-2xs font-semibold text-white bg-black/45 backdrop-blur-sm",children:s("paneGroup.dropMoveHere")})}),n.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:n.jsx("div",{className:"px-3 py-1.5 rounded-full text-2xs font-semibold text-white bg-black/45 backdrop-blur-sm",children:s("paneGroup.dropSplitRight")})})]})}function iu({conversationsCount:e,isSplitMode:t,isStandalone:s,hasRegisteredMachines:r=!1,suppressGuide:o=!1,onOpenNewSession:a,isLoading:i=!1}){const{t:c}=ve("common");if(o)return n.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:c("paneGroup.noActiveAgent")});if(i)return n.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center gap-3 -mt-8 text-text-muted",children:[n.jsx(ln,{}),n.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const d=!s&&!r,u=r&&!!a,m=c(r?"paneGroup.noConversations":s?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),h=c(r?"paneGroup.newSessionDescription":s?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?n.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[n.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),n.jsxs("div",{className:"text-center max-w-lg",children:[n.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:m}),n.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:h}),u&&n.jsx("div",{className:"flex items-center justify-center mb-4",children:n.jsxs("button",{type:"button",onClick:a,className:"btn btn-primary btn-sm inline-flex items-center gap-2",title:c("paneGroup.newSession"),"aria-label":c("paneGroup.newSession"),children:[n.jsx(_o,{size:14}),n.jsx("span",{children:c("paneGroup.newSession")})]})}),d&&n.jsx(Hb,{}),d&&n.jsx("div",{className:"mt-8",children:n.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:c("machine.card.emptyDocsLink")})})]})]}):n.jsx("div",{className:"text-sm text-text-muted opacity-50",children:c(t?"paneGroup.moveTabHere":"paneGroup.noActiveAgent")})}const Gb="adhdev-tab-shortcuts";function Vb(){try{return JSON.parse(localStorage.getItem(Gb)||"{}")}catch{return{}}}function Yb({enabled:e=!0,sortedTabKeys:t,onFocus:s,onSelectTab:r}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[a,i]=l.useState(()=>Vb()),[c,d]=l.useState(null),u=l.useCallback(h=>{const p=[];return h.metaKey&&p.push(o?"⌘":"Meta"),h.ctrlKey&&p.push("Ctrl"),h.altKey&&p.push(o?"⌥":"Alt"),h.shiftKey&&p.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(p.push(h.key.length===1?h.key.toUpperCase():h.key),p.join("+"))},[o]),m=l.useCallback(h=>{i(h);try{localStorage.setItem(Gb,JSON.stringify(h))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const h=p=>{if(p.preventDefault(),p.stopPropagation(),p.key==="Escape"){d(null);return}const g=u(p);if(!g)return;const f={...a};for(const[x,b]of Object.entries(f))b===g&&delete f[x];f[c]=g,m(f),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,c,a,m,u]),l.useEffect(()=>{if(!e)return;const h=p=>{if(!(!p.ctrlKey&&!p.metaKey&&!p.altKey)){for(const[g,f]of Object.entries(a))if(t.includes(g)&&u(p)===f){p.preventDefault(),s(),r(g);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,a,t,s,r,u]),{isMac:o,tabShortcuts:a,shortcutListening:c,setShortcutListening:d,saveShortcuts:m}}const Ml=e=>{e.preventDefault()},AI=l.memo(function({conv:t,isActive:s,isDraggedTab:r,isTaskCompleteUnread:o,shortcut:a,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:u,onConversationActivated:m,onPreviewReorder:h,onReorderTab:p,onCommitPreviewOrder:g,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:b,onReceiveTab:k,onOpenContextMenu:j,longPressTimer:v,isGroupActive:_}){const y=or(t),w=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",S=y.isReconnecting,C=Ud(t),A=l.useCallback(F=>{c.current=t.tabKey,b(t.tabKey),F.dataTransfer.setData("text/tab-key",t.tabKey),F.dataTransfer.effectAllowed="move"},[t.tabKey,c,b]),O=l.useCallback(()=>{c.current=null,b(null),g(),f(),x()},[c,b,g,f,x]),L=l.useCallback(F=>{const q=c.current;if(!(!q||q===t.tabKey)&&F.dataTransfer.types.includes("text/tab-key")){F.preventDefault(),F.stopPropagation();const Q=F.currentTarget.getBoundingClientRect(),K=F.clientX<Q.left+Q.width/2?"left":"right";h(q,t.tabKey,K)}},[t.tabKey,c,h]),M=l.useCallback(F=>{F.preventDefault(),F.stopPropagation();const q=F.dataTransfer.getData("text/tab-key");if(q&&q!==t.tabKey){const Q=F.currentTarget.getBoundingClientRect(),K=F.clientX<Q.left+Q.width/2?"left":"right";i.includes(q)?p(q,t.tabKey,K):k&&k(q)}f()},[t.tabKey,i,p,k,f]),$=l.useCallback(F=>{F.stopPropagation(),d(),u(t.tabKey),m(t)},[t,m,d,u]),N=l.useCallback(F=>{F.preventDefault(),j(F.clientX,F.clientY,t.tabKey)},[t.tabKey,j]),I=l.useCallback(F=>{const q=F.touches[0];v.current=setTimeout(()=>{j(q.clientX,q.clientY,t.tabKey)},600)},[t.tabKey,v,j]),B=l.useCallback(()=>{v.current&&clearTimeout(v.current)},[v]),T=["adhdev-dockview-tab",w,s&&"is-active",_&&"is-group-active",S&&"is-reconnecting"].filter(Boolean).join(" ");return n.jsxs("div",{"data-tabkey":t.tabKey,className:T,draggable:!0,onDragStart:A,onDragEnd:O,onDragOver:L,onDrop:M,onClick:$,onContextMenu:N,onTouchStart:I,onTouchEnd:B,onTouchMove:B,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[o&&n.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),n.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?n.jsx(ln,{size:12,thickness:2,color:"success"}):y.isWaiting?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):S?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.isConnecting?n.jsx(ln,{size:12,thickness:2}):t.connectionState==="connected"?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):n.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),n.jsx(_s,{conversation:t,size:12}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("span",{className:"adhdev-dockview-tab-primary",title:C?`${Rt(t)} · ${C}`:Rt(t),children:Rt(t)}),n.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[n.jsx(Wr,{conversation:t}),S?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Gs(t)}):y.isConnecting?n.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Gs(t),n.jsx("span",{className:"connecting-dots"})]}):n.jsx("span",{className:"truncate",children:Gs(t)}),n.jsx(Dd,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),a&&n.jsx("span",{className:"text-4xs opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:a,children:a})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function TI({conversations:e,activeTabId:t,groupIndex:s,unreadTabKeys:r,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:u,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:g,onReceiveTab:f,onHideTab:x,isGroupActive:b,allowTabShortcuts:k=!0}){const{t:j}=ve("common"),[v,_]=l.useState(null),y=l.useRef(null),w=l.useRef(null),S=l.useMemo(()=>e.map(N=>N.tabKey),[e]);Oo("PaneGroupTabBar",{groupIndex:s,activeTabId:t,tabCount:e.length,ctxMenuTab:(v==null?void 0:v.tabKey)||null});const{isMac:C,tabShortcuts:A,shortcutListening:O,setShortcutListening:L,saveShortcuts:M}=Yb({enabled:k,sortedTabKeys:e.map(N=>N.tabKey),onFocus:a,onSelectTab:i});l.useEffect(()=>{if(!v)return;const N=I=>{const B=document.querySelector("[data-pane-context-menu]");B&&B.contains(I.target)||_(null)};return window.addEventListener("mousedown",N,!0),()=>window.removeEventListener("mousedown",N,!0)},[v]),l.useEffect(()=>{const N=w.current;if(!N)return;const I=B=>{Math.abs(B.deltaY)<=Math.abs(B.deltaX)||(B.preventDefault(),N.scrollLeft+=B.deltaY)};return N.addEventListener("wheel",I,{passive:!1}),()=>N.removeEventListener("wheel",I)},[]);const $=l.useCallback((N,I,B)=>{_({x:N,y:I,tabKey:B})},[]);return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:n.jsxs("div",{ref:w,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(N=>n.jsx(AI,{conv:N,isActive:t===N.tabKey,isDraggedTab:o.current===N.tabKey,isTaskCompleteUnread:r.has(N.tabKey),shortcut:k?A[N.tabKey]:void 0,conversationKeys:S,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:u,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:g,onReceiveTab:f,onOpenContextMenu:$,longPressTimer:y,isGroupActive:b},N.tabKey)),e.length===0&&n.jsx("div",{className:"p-2 text-xs opacity-40",children:j("paneGroup.noTabsInGroup")})]})}),v&&n.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:v.x,top:v.y},children:[k&&n.jsxs(n.Fragment,{children:[n.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Ml,onClick:N=>{N.stopPropagation(),L(v.tabKey),_(null)},children:["⌨ ",A[v.tabKey]?j("paneGroup.changeShortcut",{shortcut:A[v.tabKey]}):j("paneGroup.shortcutSetTitle")]}),A[v.tabKey]&&n.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Ml,onClick:()=>{const N={...A};delete N[v.tabKey],M(N),_(null)},children:["✕ ",j("paneGroup.removeShortcut")]})]}),x&&n.jsxs(n.Fragment,{children:[k&&n.jsx("div",{className:"border-t border-border-subtle my-1"}),n.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Ml,onClick:()=>{x(v.tabKey),_(null)},children:n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(xi,{size:12}),j("paneGroup.hideFromDashboard")]})})]})]}),k&&O&&n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>L(null),children:n.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:N=>N.stopPropagation(),children:[n.jsxs("div",{className:"text-sm font-bold text-text-primary mb-2",children:["⌨ ",j("paneGroup.shortcutSetTitle")]}),n.jsx("div",{className:"text-xs text-text-secondary mb-4",children:j("paneGroup.shortcutPressCombo",{example1:C?"⌘+1":"Ctrl+1",example2:C?"⌥+A":"Alt+A"})}),n.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:j("paneGroup.shortcutListening")}),n.jsx("div",{className:"text-3xs text-text-muted mt-3",children:j("paneGroup.pressEscToCancel")})]})})})]})}function II({conversations:e,ides:t,clearedTabs:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d=!0,userName:u,groupIndex:m,onFocus:h,isSplitMode:p,numGroups:g,onMoveTab:f,onReceiveTab:x,style:b,onActiveTabChange:k,initialActiveTabId:j,initialTabOrder:v,onTabOrderChange:_,onHideTab:y,isFocused:w,allowTabShortcuts:S=!0,onOpenNewSession:C,liveSessionInboxState:A}){const{sendCommand:O}=_t(),L=l.useRef(null),{activeTabId:M,activeConv:$,sortedConversations:N,draggingTabRef:I,selectTab:B,handleTabReorder:T,updatePreviewOrder:F,commitPreviewOrder:q,clearPreviewOrder:Q,moveTabToEnd:K,setDraggingTabKey:R}=CI({conversations:e,initialActiveTabId:j,initialTabOrder:v,onActiveTabChange:k,onTabOrderChange:_}),D=Li({sendDaemonCommand:o,activeConv:$,setActionLogs:a,isStandalone:i}),{dragOver:P,dropAction:H,resetDragState:W,handleDragEnter:U,handleDragOver:ae,handleDragLeave:be,handleDrop:V}=jI({conversations:e,numGroups:g,onMoveTab:f,onReceiveTab:x,onOwnTabDrop:K,onClearPreviewOrder:Q}),we=$&&!vt($)&&Hr($)==="terminal",ce=l.useMemo(()=>$?t.find(ue=>ue.id===$.routeId):void 0,[t,$]),de=l.useMemo(()=>$?r.filter(ue=>ue.routeId===$.tabKey):[],[r,$]),ne=l.useMemo(()=>new Set(N.filter(ue=>YS(ue,A,{isOpenConversation:ue.tabKey===M})).map(ue=>ue.tabKey)),[M,A,N]);Oo("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:M,dragOver:P});const ee=l.useCallback(ue=>{ue.streamSource==="agent-stream"&&ue.agentType&&O(ue.routeId,dg(),{agentType:ue.agentType,...ue.sessionId&&{targetSessionId:ue.sessionId}}).catch(()=>{})},[O]);return n.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...b,outline:P?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[n.jsx(TI,{conversations:N,activeTabId:M,groupIndex:m,numGroups:g,unreadTabKeys:ne,draggingTabRef:I,onFocus:h,onSelectTab:B,onConversationActivated:ee,onPreviewReorder:F,onReorderTab:T,onCommitPreviewOrder:q,onClearPreviewOrder:Q,onDragStateReset:W,onDragTabKeyChange:R,onMoveTab:f,onReceiveTab:x,onHideTab:y,isGroupActive:w??!1,allowTabShortcuts:S}),n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:U,onDragOver:ae,onDragLeave:be,onDrop:V,children:[P&&n.jsx(_I,{dropAction:H,canSplit:!!(g<4&&f)}),$?n.jsx(ou,{activeConv:$,clearToken:s[$.tabKey]||0,isCliTerminal:!!we,ideEntry:ce,terminalRef:L,commands:D,actionLogs:de,userName:u,isInputActive:!p||!!w}):n.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:n.jsx(iu,{conversationsCount:e.length,isSplitMode:p,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:C,isLoading:!Ki(t,d)})})]})]})}function MI({containerRef:e,isSplitMode:t,numGroups:s,groupSizes:r,groupedConvs:o,clearedTabs:a,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:u,isStandalone:m,hasRegisteredMachines:h,initialDataLoaded:p,userName:g,focusedGroup:f,focusGroup:x,moveTabToGroup:b,splitTabRelative:k,closeGroup:j,handleResizeStart:v,groupActiveTabIds:_,setGroupActiveTab:y,groupTabOrders:w,setGroupTabOrder:S,toggleHiddenTab:C,onOpenNewSession:A,allowTabShortcuts:O=!0,liveSessionInboxState:L}){const{t:M}=ve("common");return n.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:o.map(($,N)=>{const I=t&&r.length===s?`${r[N]}%`:void 0;return n.jsxs(It.Fragment,{children:[t&&N>0&&n.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:B=>v(N-1,B),onDoubleClick:()=>j(N),title:M("paneGroup.resizeHandleHint"),children:n.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),n.jsx(II,{style:t?{flexBasis:I??`${100/s}%`,flexGrow:I?0:1,flexShrink:I?0:1}:void 0,conversations:$,clearedTabs:a,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:u,isStandalone:m,hasRegisteredMachines:h,initialDataLoaded:p,userName:g,groupIndex:N,isFocused:t&&f===N,onFocus:()=>x(N),isSplitMode:t,numGroups:s,onMoveTab:(B,T)=>{T==="left"&&N>0?b(B,N-1):T==="right"&&N<s-1?b(B,N+1):T==="split-left"&&s<4?k(B,N,"left"):T==="split-right"&&s<4&&k(B,N,"right")},onReceiveTab:B=>b(B,N),onActiveTabChange:B=>y(N,B),initialActiveTabId:_[N],initialTabOrder:w[N],onTabOrderChange:B=>S(N,B),onHideTab:C,onOpenNewSession:A,allowTabShortcuts:O,liveSessionInboxState:L})]},N)})})}const Qb="adhdev-dashboard-action-shortcuts",RI=1200,PI=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function LI(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function wt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Jb(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:wt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:wt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:wt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:wt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:wt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:wt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:wt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:wt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:wt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:wt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:wt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:wt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:wt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:wt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:wt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:wt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:wt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:wt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:wt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:wt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:wt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:wt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:wt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:wt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:wt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:wt("toggleCliView",e)}]}function Uc(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function ci(e){const t=Object.fromEntries(Jb(e).map(s=>[s.id,s.defaultShortcut]));try{const s=JSON.parse(localStorage.getItem(Qb)||"{}"),r={...t,...s};for(const[o,a]of PI)r[o]===a&&(r[o]=t[o]);return r}catch{return t}}function Xb(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function EI({enabled:e=!0,onTrigger:t}){const s=LI(),[r,o]=l.useState(()=>ci(s)),[a,i]=l.useState(null),[c,d]=l.useState([]),u=l.useRef({parts:[],timer:null}),m=l.useCallback(x=>{const b=[];return x.metaKey&&b.push(s?"⌘":"Meta"),x.ctrlKey&&b.push("Ctrl"),x.altKey&&b.push(s?"⌥":"Alt"),x.shiftKey&&x.key.length!==1&&b.push(s?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(b.push(Xb(x.key)),b.join("+"))},[s]),h=l.useCallback(x=>{o(x);try{localStorage.setItem(Qb,JSON.stringify(x))}catch{}},[]);l.useEffect(()=>{const x=ci(s),b=Object.entries(r),k=Object.entries(x);b.length===k.length&&b.every(([j,v])=>x[j]===v)||h(x)},[r,s,h]);const p=l.useCallback(()=>{typeof window<"u"&&u.current.timer!=null&&window.clearTimeout(u.current.timer),u.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(u.current.timer!=null&&window.clearTimeout(u.current.timer),u.current.timer=window.setTimeout(()=>{u.current={parts:[],timer:null}},RI))},[]);l.useEffect(()=>{if(!a)return;const x=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){i(null),d([]);return}const k=m(b);if(!k)return;const v=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(k);if(c.length===0&&v){d([k]);return}const y=[...c,k].slice(0,2).join(" "),w={...r};for(const[S,C]of Object.entries(w))C===y&&delete w[S];w[a]=y,h(w),i(null),d([])};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[r,m,h,a,c]),l.useEffect(()=>{if(!e||a)return;const x=b=>{if(b.defaultPrevented)return;const k=m(b);if(!k)return;const j=b.metaKey||b.ctrlKey||b.altKey;if(Uc(b.target))return;const v=u.current.parts,_=j?[k]:[...v.slice(-1),k].slice(-2),y=_.join(" "),w=_[_.length-1],S=Object.entries(r).filter(([,M])=>!!M),C=S.find(([,M])=>M===y);if(C){b.preventDefault(),p(),t(C[0]);return}if(S.some(([,M])=>M.startsWith(`${y} `))){b.preventDefault(),u.current.parts=_,g();return}const O=S.find(([,M])=>M===w);if(O){b.preventDefault(),p(),t(O[0]);return}if(S.some(([,M])=>M.startsWith(`${w} `))){b.preventDefault(),u.current.parts=[w],g();return}p()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[r,g,e,m,t,p,a]),l.useEffect(()=>()=>p(),[p]);const f=l.useMemo(()=>Jb(s),[s]);return{isMac:s,actionDefinitions:f,actionShortcuts:r,shortcutListening:a,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:h}}function DI({isTabInPopout:e,isTabFloating:t,tabShortcut:s,actionShortcuts:r}){const o=[];return e?(t&&o.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:r.dockActiveTab}),o.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:r.dockActiveTab})):t?o.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:r.dockActiveTab}):o.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:r.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:r.popoutActiveTab}),o.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:s?`Change shortcut (${s})`:"Set shortcut",shortcut:r.setActiveTabShortcut}),s&&o.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),o.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:r.hideCurrentTab,tone:"muted"}),o}function Zb(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Nh({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:s,ides:r}){return!e||s>0?!1:t?!Zb(r):!0}function OI({previousVisibleConversationCount:e,visibleConversationCount:t,ides:s}){return t>0||e<=0?!1:Zb(s)}const ex=1e3,$I=4;function Ch(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function _h(e,t,s){return Math.abs(t.clientX-e.clientX)>s||Math.abs(t.clientY-e.clientY)>s}function FI({detachDelayMs:e=ex,stillnessThresholdPx:t=$I,onDetach:s,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:o=globalThis.clearTimeout.bind(globalThis)}){let a=null,i=null,c=null,d=null,u=null,m=!1;const h=()=>{u!=null&&(o(u),u=null)},p=()=>{h(),c=null},g=()=>{h(),a=null,i=null,c=null,d=null,m=!1},f=()=>{!a||!c||!d||m||u!=null||(u=r(()=>{u=null,!(!a||!c||!d||m)&&Ch(d,i)&&(_h(c,d,t)||(m=!0,s({panelId:a,clientX:d.clientX,clientY:d.clientY})))},e))},x=k=>{if(!(!a||m)){if(!Ch(k,i)){d={clientX:k.clientX,clientY:k.clientY},p();return}(!c||_h(c,k,t))&&(h(),c={clientX:k.clientX,clientY:k.clientY}),d={clientX:k.clientX,clientY:k.clientY},f()}},b=k=>{!a||m||(k&&(d={clientX:k.clientX,clientY:k.clientY}),p())};return{startDrag:k=>{h(),a=k.panelId,i=k.selfPanelBounds??null,c=null,d={clientX:k.clientX,clientY:k.clientY},m=!1},markSelfPanel:x,markNonSelfPanel:b,markNoDropTarget:b,markDockTarget:b,endDrag:g,isDragging:()=>a!=null,hasDetached:()=>m,dispose:g}}function HI(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function $a(e){return Rt(e)||e.tabKey}function BI(e){return`remote:${e}`}function Rn(e){return e.startsWith("remote:")}function Ah(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Rl(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const s=o=>{if(o)try{o.focus({preventScroll:!0})}catch{try{o.focus()}catch{}}};try{t.focus(),s(e==null?void 0:e.body),s(e==null?void 0:e.documentElement),(r=t.requestAnimationFrame)==null||r.call(t,()=>{try{t.focus(),s(e==null?void 0:e.body)}catch{}})}catch{}}function Pl(e,t){e.classList.remove(Zl.className,ec.className),e.classList.add(t==="light"?Zl.className:ec.className)}function Th(e){return e?Array.from(new Set(e.groups.map(t=>{var s,r;return(r=(s=t.element)==null?void 0:s.ownerDocument)==null?void 0:r.defaultView}).filter(t=>!!t&&t!==window))):[]}function WI(e,t,s){var i;const r=[t];let o;for(const c of r){let d;for(const u of c){const m=e.addPanel({id:u.tabKey,component:"conversation",title:$a(u),params:{kind:"conversation",tabKey:u.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});d||(d=m.id)}o=d??o}return s??((i=t[0])==null?void 0:i.tabKey)??null}function Ih(e,t){const s=new Set(t.map(o=>o.tabKey)),r=new Map;for(const o of t)r.set(o.tabKey,(r.get(o.tabKey)||0)+1);for(const o of[...e.panels])Rn(o.id)||s.has(o.id)||e.removePanel(o);for(const o of t){const a=e.getPanel(o.tabKey);if(a){(r.get(o.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:o.tabKey,daemonId:o.daemonId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,panelId:a.id}),a.update({params:{tabKey:o.tabKey}}),a.title!==$a(o)&&a.api.setTitle($a(o));continue}e.addPanel({id:o.tabKey,component:"conversation",title:$a(o),params:{kind:"conversation",tabKey:o.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Mh(e,t,s){var d,u;const r=s?BI(s):null;for(const m of[...e.panels])Rn(m.id)&&(!r||m.id!==r)&&e.removePanel(m);if(!s||!r)return;const o=$n(t,s);if(!o&&e.totalPanels===0)return;const a=e.getPanel(r),i=Hg(o);if(a){a.title!==i&&a.api.setTitle(i);return}const c=(o==null?void 0:o.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((u=e.panels.find(m=>!Rn(m.id)))==null?void 0:u.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:s},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function tx({doId:e,targetSessionId:t,connState:s,viewMode:r}){const[o,a]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?Et.onScreenshot("ide-page",(m,h)=>{if(m!==e)return;const p=new FileReader;p.onload=()=>a(p.result),p.readAsDataURL(h)}):void 0,[e]),l.useEffect(()=>{s!=="connected"&&a(null)},[s]),l.useEffect(()=>{var m;return e?((m=Et.onStatus)==null?void 0:m.call(Et,(h,p)=>{h===e&&p!=null&&p.screenshotUsage&&c(p.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{a(null)},[e,t]),l.useEffect(()=>{const u=e?Et.get(e):null;if(!(!u||s!=="connected"))return r!=="chat"&&t?u.startScreenshots(t):u.stopScreenshots(t),()=>{u.stopScreenshots(t)}},[r,s,t,e]);const d=l.useCallback(async(u,m)=>{const h=e?Et.get(e):null;return!h||s!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(u,m,t)},[e,s,t]);return{connScreenshot:o,screenshotUsage:i,handleRemoteAction:d}}const nx=l.createContext(null);function qi(){const e=l.useContext(nx);if(!e)throw new Error("DashboardDockviewContext missing");return e}function UI(e){const[,t]=l.useState(0);l.useEffect(()=>{const s=()=>t(o=>o+1),r=[e.api.onDidActiveGroupChange(s),e.api.onDidTitleChange(s),e.api.onDidGroupChange(s),e.containerApi.onDidActivePanelChange(s)];return()=>{for(const o of r)o.dispose()}},[e.api,e.containerApi])}function KI({params:e}){var u;const t=qi(),{t:s}=ve("common"),r=l.useMemo(()=>$n([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),o=l.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:d}=tx({doId:a,targetSessionId:r?ig(r):(o==null?void 0:o.sessionId)||(o==null?void 0:o.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:n.jsx(bf,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:d})}):n.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:s("dashboard.remoteDialog.remoteUnavailable")})}function qI(){const e=qi();return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:n.jsx(iu,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!Ki(e.ides,e.initialDataLoaded)})})}function zI(e){var _,y;UI(e);const t=qi(),{t:s}=ve("common"),r=l.useCallback(w=>{"button"in w&&w.button!==0||e.api.setActive()},[e.api]),o=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=o==null?void 0:o.sessionId,i=l.useCallback(w=>d_(w),[]),c=l.useCallback(()=>c_(a),[a]),d=l.useSyncExternalStore(i,c,c),u=Ud(o);if(e.params.kind==="remote"){const w=$n([...t.conversationsByTabKey.values()],e.params.routeId),S=((_=e.api.group.activePanel)==null?void 0:_.id)===e.api.id,C=e.api.isGroupActive;return n.jsxs("div",{className:`adhdev-dockview-tab${S?" is-active":""}${C?" is-group-active":""}`,title:e.api.title||s("dashboard.remoteDialog.remoteFallback"),"data-tab-key":(w==null?void 0:w.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[n.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:n.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||s("dashboard.remoteDialog.remoteFallback")}),n.jsx("div",{className:"adhdev-dockview-tab-meta",children:w!=null&&w.machineName?n.jsxs(n.Fragment,{children:[n.jsx("span",{children:s("dashboard.remoteDialog.liveRemoteView")}),n.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),n.jsx("span",{className:"adhdev-dockview-tab-machine",children:w.machineName})]}):n.jsx("span",{children:s("dashboard.remoteDialog.liveRemoteView")})})]})]})}const m=t.conversationsByTabKey.get(e.params.tabKey);if(!m)return n.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:n.jsx("div",{className:"adhdev-dockview-tab-copy",children:n.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const h=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,p=e.api.isGroupActive,g=Ci(m,t.liveSessionInboxState,{isOpenConversation:h}),f=g.isReconnecting,x=g.isConnecting,b=g.isGenerating||d,k=g.isWaiting,j=g.unread,v=t.tabShortcuts[m.tabKey];return n.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${p?" is-group-active":""}${f?" is-reconnecting":""}`,title:u?`${Rt(m)} · ${u}`:Rt(m),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:w=>{var S;w.preventDefault(),r(w),t.openTabContextMenu({x:w.clientX,y:w.clientY,tabKey:m.tabKey,sourceDocument:((S=w.target)==null?void 0:S.ownerDocument)??document})},children:[j&&n.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),n.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:b?n.jsx(ln,{size:12,thickness:2,color:"success"}):k?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):x?n.jsx(ln,{size:12,thickness:2}):m.connectionState==="connected"?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):n.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),n.jsx(_s,{conversation:m,size:12}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("div",{className:"adhdev-dockview-tab-primary",children:Rt(m)}),n.jsxs("div",{className:"adhdev-dockview-tab-meta",children:[n.jsx(Wr,{conversation:m,separator:!0}),f?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Gs(m)}):x?n.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Gs(m)}):n.jsx("span",{children:Gs(m)})]})]}),v&&n.jsx("span",{className:"text-4xs opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:v,children:v})]})}const GI=[];function ga(e){return e.isActive}function Rh(e){return e.isVisible}function VI(e){e.preventDefault()}function YI({params:e,api:t}){var f;const s=qi(),r=l.useRef(null),[o,a]=l.useState(()=>ga(t)),[i,c]=l.useState(()=>Rh(t)),d=s.conversationsByTabKey.get(e.tabKey),u=Li({sendDaemonCommand:s.sendDaemonCommand,activeConv:d,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone});l.useEffect(()=>{a(ga(t)),c(Rh(t));const x=[t.onDidActiveChange(b=>a(b.isActive)),t.onDidActiveGroupChange(b=>{if(!ga(t)&&!b.isActive){a(!1);return}a(ga(t))}),t.onDidVisibilityChange(b=>c(b.isVisible))];return()=>{for(const b of x)b.dispose()}},[t]);const m=l.useMemo(()=>d?s.ides.find(x=>x.id===d.routeId):void 0,[s.ides,d]),h=d==null?void 0:d.tabKey,p=l.useMemo(()=>h?s.actionLogs.filter(x=>x.routeId===h):GI,[s.actionLogs,h]);if(!d)return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:n.jsx(iu,{conversationsCount:0,isSplitMode:!1,isStandalone:s.isStandalone,hasRegisteredMachines:s.hasRegisteredMachines,onOpenNewSession:s.onOpenNewSession,suppressGuide:s.hasDetachedConversationPanels,isLoading:!Ki(s.ides,s.initialDataLoaded)})});const g=!vt(d)&&Hr(d)==="terminal";return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:n.jsx(ou,{activeConv:d,clearToken:s.clearedTabs[d.tabKey]||0,isCliTerminal:g,ideEntry:m,terminalRef:r,commands:u,actionLogs:p,userName:s.userName,scrollToBottomRequestNonce:((f=s.scrollToBottomRequest)==null?void 0:f.tabKey)===d.tabKey?s.scrollToBottomRequest.nonce:void 0,isInputActive:o,isVisible:i})})}function QI({visibleConversations:e,clearedTabs:t,ides:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:u,toggleHiddenTab:m,actionShortcuts:h,registerActionHandlers:p,onActiveTabChange:g,onOpenNewSession:f,onRequestScrollToBottom:x,requestedActiveTabKey:b,requestedRemoteIdeId:k,onRequestedActiveTabConsumed:j,scrollToBottomRequest:v,liveSessionInboxState:_,layoutProfile:y}){var He,tt,Ct;const{t:w}=ve("common"),{theme:S}=Uo(),{sendCommand:C}=_t(),A=l.useRef(null),O=l.useRef(null),L=l.useRef(null),M=l.useRef(!1),$=l.useRef(!1),N=l.useRef(!1),I=l.useRef(null),B=l.useRef([]),[T,F]=l.useState(null),[q,Q]=l.useState(0),K=l.useRef(typeof window>"u"?{}:c2(y)),R=l.useMemo(()=>new Map(e.map(J=>[J.tabKey,J])),[e]),D=l.useMemo(()=>{const J=A.current;return J?J.groups.some(re=>{try{const le=re.model.location.type;return le!=="floating"&&le!=="popout"?!1:re.panels.some(xe=>R.has(xe.id))}catch{return!1}}):!1},[R,q,e]),P=l.useCallback(()=>{var J;(J=A.current)==null||J.focus()},[]),H=l.useCallback((J,re)=>{x==null||x(J,re)},[x]),W=l.useCallback(J=>{const re=document,le=J.document;for(const Fe of re.querySelectorAll('link[rel="stylesheet"]')){const ke=le.createElement("link");ke.rel="stylesheet",ke.href=Fe.href,Fe.crossOrigin&&(ke.crossOrigin=Fe.crossOrigin),le.head.appendChild(ke)}for(const Fe of re.querySelectorAll("style")){const ke=le.createElement("style");ke.textContent=Fe.textContent,le.head.appendChild(ke)}const xe=[];for(const Fe of re.styleSheets)try{for(const ke of Fe.cssRules)ke instanceof CSSStyleRule&&(ke.selectorText===":root"||ke.selectorText==="html")&&xe.push(ke.cssText)}catch{}if(xe.length>0){const Fe=le.createElement("style");Fe.textContent=xe.join(`
|
|
59
|
+
`),le.head.appendChild(Fe)}const Ce=re.documentElement.getAttribute("data-theme");Ce&&le.documentElement.setAttribute("data-theme",Ce),le.documentElement.style.colorScheme=Ce==="light"?"light":"dark",le.body.className=re.body.className;const Re=re.documentElement.getAttribute("style");Re&&le.documentElement.setAttribute("style",Re);const Ue=le.getElementById("dv-popout-window");Ue instanceof HTMLElement&&(Ue.classList.add("adhdev-dockview"),Pl(Ue,S))},[S]),U=l.useCallback(()=>{var re;const J=A.current;if(J)for(const le of J.groups)try{const xe=(re=le.element)==null?void 0:re.ownerDocument;if(!xe||xe===document)continue;const Ce=xe.getElementById("dv-popout-window");Ce instanceof HTMLElement&&(Ce.classList.add("adhdev-dockview"),Pl(Ce,S));const Re=document.documentElement.getAttribute("data-theme");Re&&xe.documentElement.setAttribute("data-theme",Re),xe.documentElement.style.colorScheme=Re==="light"?"light":"dark",xe.body.className=document.body.className;const Ue=document.documentElement.getAttribute("style");Ue?xe.documentElement.setAttribute("style",Ue):xe.documentElement.removeAttribute("style")}catch{}},[S]),ae=l.useCallback(J=>{const re=A.current;if(!re)return;const le=re.getPanel(J);le&&re.addPopoutGroup(le,{popoutUrl:"/popout.html",onDidOpen:({window:xe})=>{W(xe),je();const Ce=R.get(J);xe.document.title=Ce?`${Rt(Ce)} — ADHDev`:"ADHDev — Popout"}})},[R,W]),be=l.useCallback(J=>{const re=A.current,le=re==null?void 0:re.getPanel(J);if(!re||!le)return;const xe=re.groups.filter(Ce=>{var Re;try{return((Re=Ce.element)==null?void 0:Re.ownerDocument)===document}catch{return!0}});xe.length>0?le.api.moveTo({group:xe[0],position:"center"}):le.api.moveTo({position:"center"}),le.api.setActive()},[]),V=l.useCallback(J=>{var xe;const re=A.current;if(!re)return!1;const le=re.getPanel(J);if(!le)return!1;try{return((xe=le.group.element)==null?void 0:xe.ownerDocument)!==document}catch{return!1}},[]),we=l.useCallback(J=>{V(J)&&be(J),m(J)},[V,be,m]),ce=l.useCallback(J=>{const re=A.current,le=re==null?void 0:re.getPanel(J);!re||!le||re.addFloatingGroup(le,{width:600,height:500})},[]),de=l.useCallback(J=>{var le;const re=(le=A.current)==null?void 0:le.getPanel(J);if(!re)return!1;try{return re.group.model.location.type==="floating"}catch{return!1}},[]),ne=l.useCallback(()=>{var re,le;const J=(le=(re=A.current)==null?void 0:re.activePanel)==null?void 0:le.id;return!J||Rn(J)?null:R.has(J)?J:null},[R]),ee=l.useCallback(J=>{const re=A.current,le=re==null?void 0:re.getPanel(J);if(!re||!le)return;const xe=re.groups.filter(Ce=>{try{return Ce.model.location.type==="grid"}catch{return!0}});xe.length>0?le.api.moveTo({group:xe[0],position:"center"}):le.api.moveTo({position:"center"}),le.api.setActive()},[]),ue=l.useCallback(()=>{var Re;const J=A.current;if(!J)return;const le=J.groups.filter(Ue=>{var Fe;try{return((Fe=Ue.element)==null?void 0:Fe.ownerDocument)===document&&Ue.model.location.type==="grid"}catch{return!1}})[0]||null,xe=[...J.panels];for(const Ue of xe){const Fe=(Re=Ue.group.element)==null?void 0:Re.ownerDocument,ke=Ue.group.model.location.type;Fe===document&&ke==="grid"||(le&&le.id!==Ue.group.id?Ue.api.moveTo({group:le,position:"center"}):Ue.api.moveTo({position:"center"}))}const Ce=J.activePanel;Ce&&(Ce.group.model.openPanel(Ce),Ce.api.setActive()),Rl(document)},[]),je=l.useCallback(()=>{var re,le;const J=A.current;if(J)for(const xe of J.groups){const Ce=(re=xe.element)==null?void 0:re.ownerDocument;if(!Ce||Ce===document)continue;const Re=Ce.getElementById("dv-popout-window");if(!(Re instanceof HTMLElement))continue;let Ue=null,Fe=Ce.title||"ADHDev",ke="Popout workspace";const Ze=xe.activePanel;if(Ze)if(Ue=Ze.id,Rn(Ze.id)){const Qe=((le=Ze.params)==null?void 0:le.routeId)||Ze.id.slice(7),ge=$n([...R.values()],Qe);Fe=Hg(ge),ke=ge!=null&&ge.machineName?`Remote view · ${ge.machineName}`:"Remote view"}else{const Qe=R.get(Ze.id);Fe=Qe?Rt(Qe):Ze.title||Ze.id,ke=Qe?Gs(Qe):"Dockview panel"}Ce.title=`${Fe} — ADHDev`;const et=Array.from(Ce.querySelectorAll("#adhdev-popout-header"));for(const Qe of et)Qe.remove();const Ve=Ce.createElement("div");Ve.id="adhdev-popout-header",Ce.body.appendChild(Ve),Ve.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Ve.innerHTML=`
|
|
60
|
+
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
61
|
+
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
62
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ah(Fe)}</div>
|
|
63
|
+
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ah(ke)}</div>
|
|
64
|
+
</div>
|
|
65
|
+
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
66
|
+
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
67
|
+
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
68
|
+
</div>
|
|
69
|
+
`,Re.style.top="52px",Re.style.height="calc(100% - 52px)";const st=Ve.querySelector("[data-adhdev-popout-focus]");st&&(st.onclick=()=>{window.focus()});const lt=Ve.querySelector("[data-adhdev-popout-dock]");lt&&(lt.disabled=!Ue,lt.style.opacity=Ue?"1":"0.5",lt.style.cursor=Ue?"pointer":"default",lt.onclick=()=>{var Qe;Ue&&be(Ue),(Qe=Ce.defaultView)==null||Qe.focus()})}},[R,be]),X=l.useCallback(J=>{var xe;const re=A.current,le=re==null?void 0:re.getPanel(J);if(!(!re||!le)){le.group.model.openPanel(le),le.api.setActive(),H(J,"dockview-shortcut");try{const Ce=le.group.model.location;Ce.type==="popout"?Ce.getWindow().focus():Rl((xe=le.group.element)==null?void 0:xe.ownerDocument)}catch{}}},[H]),G=l.useCallback(J=>{const re=A.current,le=re==null?void 0:re.activePanel,xe=(re==null?void 0:re.activeGroup)||(le==null?void 0:le.group);if(!re||!le||!xe)return;const Ce=xe.panels||[];if(Ce.length<=1)return;const Re=Ce.findIndex(ke=>ke.id===le.id);if(Re<0)return;const Ue=(Re+J+Ce.length)%Ce.length,Fe=Ce[Ue];Fe&&(Fe.group.model.openPanel(Fe),Fe.api.setActive(),Rn(Fe.id)||H(Fe.id,"dockview-shortcut"))},[H]),z=l.useCallback(J=>{var st;const re=A.current,le=(re==null?void 0:re.activeGroup)||((st=re==null?void 0:re.activePanel)==null?void 0:st.group);if(!re||!le)return;const xe=re.groups||[],Ce=xe.find(lt=>lt.id===le.id);if(!Ce)return;const Re=Ce.element.getBoundingClientRect(),Ue=Re.left+Re.width/2,Fe=Re.top+Re.height/2,ke=(lt,Qe,ge,_e)=>Math.max(0,Math.min(Qe,_e)-Math.max(lt,ge)),Ze=lt=>{const Qe=lt.element.getBoundingClientRect(),ge=Qe.left+Qe.width/2,_e=Qe.top+Qe.height/2;let Pe=0,nt=0,ze=0,ut=!1;if(J==="left"?(ut=ge<Ue,Pe=Math.max(0,Re.left-Qe.right),nt=Math.abs(_e-Fe),ze=ke(Re.top,Re.bottom,Qe.top,Qe.bottom)):J==="right"?(ut=ge>Ue,Pe=Math.max(0,Qe.left-Re.right),nt=Math.abs(_e-Fe),ze=ke(Re.top,Re.bottom,Qe.top,Qe.bottom)):J==="above"?(ut=_e<Fe,Pe=Math.max(0,Re.top-Qe.bottom),nt=Math.abs(ge-Ue),ze=ke(Re.left,Re.right,Qe.left,Qe.right)):(ut=_e>Fe,Pe=Math.max(0,Qe.top-Re.bottom),nt=Math.abs(ge-Ue),ze=ke(Re.left,Re.right,Qe.left,Qe.right)),!ut)return Number.POSITIVE_INFINITY;const Ge=ze>0?0:120;return Pe*3+nt+Ge};let et=null,Ve=Number.POSITIVE_INFINITY;for(const lt of xe){if(lt.id===Ce.id)continue;const Qe=Ze(lt);Number.isFinite(Qe)&&(Qe>=Ve||(Ve=Qe,et=lt))}return et||void 0},[]),ie=l.useCallback(J=>{var xe;const re=z(J);if(!re)return;const le=re.activePanel||re.panels[0];le&&(re.model.openPanel(le),le.api.setActive(),Rn(le.id)||H(le.id,"dockview-focus"),Rl((xe=re.element)==null?void 0:xe.ownerDocument))},[z,H]),Ne=l.useCallback((J,re)=>{const le=A.current,xe=le==null?void 0:le.activePanel,Ce=(le==null?void 0:le.activeGroup)||(xe==null?void 0:xe.group);if(!le||!xe||!Ce)return;let Re=z(J);!Re&&(re!=null&&re.createGroupIfMissing)&&(Re=le.addGroup({referenceGroup:Ce,direction:J})),Re&&(xe.api.moveTo({group:Re,position:"center"}),xe.group.model.openPanel(xe),xe.api.setActive(),Rn(xe.id)||H(xe.id,re!=null&&re.createGroupIfMissing?"dockview-split":"dockview-move"))},[z,H]),{isMac:Be,tabShortcuts:Le,shortcutListening:Je,setShortcutListening:Se,saveShortcuts:he}=Yb({sortedTabKeys:e.map(J=>J.tabKey),onFocus:P,onSelectTab:X}),pe=l.useCallback(()=>{var le;const J=A.current;if(!J)return;const re=J.activePanel;if(re){if(Rn(re.id)){const xe=((le=re.params)==null?void 0:le.routeId)||re.id.slice(7),Ce=$n(e,xe);Ce!=null&&Ce.tabKey&&Se(Ce.tabKey);return}R.has(re.id)&&Se(re.id)}},[R,X,Se,e]),Ee=l.useCallback(J=>{const re=[];return J.metaKey&&re.push(Be?"⌘":"Meta"),J.ctrlKey&&re.push("Ctrl"),J.altKey&&re.push(Be?"⌥":"Alt"),J.shiftKey&&J.key.length!==1&&re.push(Be?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(J.key)?null:(re.push(Xb(J.key)),re.join("+"))},[Be]),Y=l.useCallback(J=>{var re,le;switch(J){case"splitActiveTabRight":Ne("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Ne("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const xe=ne();xe&&ce(xe);return}case"popoutActiveTab":{const xe=ne();xe&&ae(xe);return}case"dockActiveTab":{const xe=ne();if(!xe)return;V(xe)?be(xe):de(xe)&&ee(xe);return}case"focusLeftPane":ie("left");return;case"focusRightPane":ie("right");return;case"focusUpPane":ie("above");return;case"focusDownPane":ie("below");return;case"moveActiveTabToLeftPane":Ne("left");return;case"moveActiveTabToRightPane":Ne("right");return;case"moveActiveTabToUpPane":Ne("above");return;case"moveActiveTabToDownPane":Ne("below");return;case"selectPreviousGroupTab":G(-1);return;case"selectNextGroupTab":G(1);return;case"setActiveTabShortcut":pe();return;case"hideCurrentTab":{const xe=(le=(re=A.current)==null?void 0:re.activePanel)==null?void 0:le.id;xe&&!Rn(xe)&&we(xe);return}default:return}},[G,ee,ie,ce,ne,we,de,V,be,Ne,ae,pe]);l.useEffect(()=>{if(!T)return;const J=T.sourceDocument,re=J.defaultView??window,le=xe=>{const Ce=J.querySelector("[data-dockview-tab-context-menu]");Ce&&Ce.contains(xe.target)||F(null)};return re.addEventListener("mousedown",le,!0),re!==window&&window.addEventListener("mousedown",()=>F(null),!0),()=>{re.removeEventListener("mousedown",le,!0),re!==window&&window.removeEventListener("mousedown",()=>F(null),!0)}},[T]);const me=l.useMemo(()=>({actionLogs:r,clearedTabs:t,conversationsByTabKey:R,hasDetachedConversationPanels:D,ides:s,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,onOpenNewSession:f,liveSessionInboxState:_,sendDaemonCommand:o,setActionLogs:a,toggleHiddenTab:we,userName:u,scrollToBottomRequest:v,tabShortcuts:Le,openTabContextMenu:({x:J,y:re,tabKey:le,sourceDocument:xe})=>F({x:J,y:re,tabKey:le,sourceDocument:xe??document}),popoutTab:ae,moveTabBackToMain:be,isTabInPopout:V,floatTab:ce,isTabFloating:de}),[r,t,R,D,s,i,c,d,f,_,o,a,we,u,v,Le,ae,be,V,ce,de]),fe=T?DI({isTabInPopout:V(T.tabKey),isTabFloating:de(T.tabKey),tabShortcut:Le[T.tabKey],actionShortcuts:h}):[],E=l.useCallback(J=>{var xe;const re=A.current;if((((xe=re==null?void 0:re.activePanel)==null?void 0:xe.id)??null)===J.id){J.group.model.openPanel(J);return}J.group.model.openPanel(J),J.api.setActive()},[]),oe=l.useCallback((J,re="requested-tab")=>{if(!J)return!1;const le=A.current;if(!le)return!1;const xe=le.getPanel(J);return xe?(E(xe),H(J,re),j==null||j(),!0):!1},[E,j,H]),Ie=l.useCallback(()=>{if(N.current)return!1;const J=oe(I.current,"stored-layout-restore");return J&&(N.current=!0),J},[oe]),Z=l.useCallback(()=>{var re;const J=A.current;J&&l2(y,{activeTabId:((re=J.activePanel)==null?void 0:re.id)??null,layout:J.toJSON()})},[y]),se=l.useCallback(()=>{d2(y,K.current)},[y]),ye=l.useCallback(J=>{var xe,Ce,Re,Ue;const re=A.current;if(!re)return{kind:"grid"};const le=re.toJSON();for(const Fe of le.floatingGroups||[])if((Ce=(xe=Fe.data)==null?void 0:xe.views)!=null&&Ce.includes(J)&&Fe.position)return{kind:"floating",position:Fe.position};for(const Fe of le.popoutGroups||[])if((Ue=(Re=Fe.data)==null?void 0:Re.views)!=null&&Ue.includes(J))return{kind:"popout",position:Fe.position,popoutUrl:Fe.url};return{kind:"grid"}},[]),$e=l.useCallback(J=>{const re=A.current;if(!re)return;const le=re.getPanel(J),xe=K.current[J];if(!le||!xe||xe.kind==="grid")return;if(le.group.model.location.type===xe.kind){delete K.current[J],se();return}if(xe.kind==="floating"){re.addFloatingGroup(le,{x:xe.position.left??24,y:xe.position.top??24,width:xe.position.width,height:xe.position.height}),delete K.current[J],se();return}delete K.current[J],se()},[se]);l.useEffect(()=>(p==null||p({setShortcutForActiveTab:pe,restoreHiddenTabToSavedLocation:$e,activateConversationTab:X,resetAllPanelsToMain:ue,activatePreviousTabInGroup:()=>G(-1),activateNextTabInGroup:()=>G(1),floatActiveTab:()=>{const J=ne();J&&ce(J)},popoutActiveTab:()=>{const J=ne();J&&ae(J)},dockActiveTab:()=>{const J=ne();J&&(V(J)?be(J):de(J)&&ee(J))},splitActiveTabRight:()=>Ne("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Ne("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ie("left"),focusRightPane:()=>ie("right"),focusUpPane:()=>ie("above"),focusDownPane:()=>ie("below"),moveActiveTabToLeftPane:()=>Ne("left"),moveActiveTabToRightPane:()=>Ne("right"),moveActiveTabToUpPane:()=>Ne("above"),moveActiveTabToDownPane:()=>Ne("below")}),()=>p==null?void 0:p(null)),[G,ee,ce,ie,ne,de,V,Ne,be,ae,p,ue,$e,X,pe]),l.useEffect(()=>()=>{var J;(J=L.current)==null||J.call(L),L.current=null},[]);const Me=l.useCallback(J=>{var le,xe;A.current=J.api,(le=L.current)==null||le.call(L),L.current=null;const re=i2(y);if(I.current=(re==null?void 0:re.activeTabId)??null,re!=null&&re.layout&&J.api.fromJSON(re.layout,{reuseExistingPanels:!1}),$.current=Nh({hasStoredLayout:!!(re!=null&&re.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:s}),$.current||(Ih(J.api,e),Mh(J.api,e,k)),J.api.totalPanels===0&&e.length>0){const Ce=WI(J.api,e,b);if(Ce){const Re=J.api.getPanel(Ce);Re&&E(Re)}}else!$.current&&!oe(b)&&Ie();if(M.current=!0,J.api.onDidActivePanelChange(Ce=>{var Ue;if(I.current=(Ce==null?void 0:Ce.id)??null,N.current=!0,je(),Ce&&Rn(Ce.id)){const Fe=((Ue=Ce.params)==null?void 0:Ue.routeId)||Ce.id.slice(7),ke=$n(e,Fe);g((ke==null?void 0:ke.tabKey)??null),Z();return}if(g((Ce==null?void 0:Ce.id)??null),Z(),!Ce)return;const Re=R.get(Ce.id);(Re==null?void 0:Re.streamSource)==="agent-stream"&&Re.agentType&&C(Re.routeId,dg(),{agentType:Re.agentType,...Re.sessionId&&{targetSessionId:Re.sessionId}}).catch(()=>{})}),J.api.onDidLayoutChange(()=>{Z(),je(),Q(Ce=>Ce+1)}),HI()){const Ce=Ve=>({clientX:Ve.clientX,clientY:Ve.clientY}),Re=Ve=>{const st=Ve==null?void 0:Ve.getBoundingClientRect();return st?{left:st.left,right:st.right,top:st.top,bottom:st.bottom}:null},Ue=Ve=>{var lt;const st=(lt=O.current)==null?void 0:lt.getBoundingClientRect();return st?Ve.clientX<st.left||Ve.clientX>st.right||Ve.clientY<st.top||Ve.clientY>st.bottom:!1},Fe=FI({detachDelayMs:ex,onDetach:({panelId:Ve,clientX:st,clientY:lt})=>{var ze,ut;const Qe=J.api.getPanel(Ve);if(!Qe)return;try{if(Qe.group.model.location.type!=="grid")return}catch{return}const ge=(ze=O.current)==null?void 0:ze.getBoundingClientRect(),_e=(ut=Qe.group.element)==null?void 0:ut.getBoundingClientRect(),Pe=Math.round(Math.min(Math.max((_e==null?void 0:_e.width)??600,360),720)),nt=Math.round(Math.min(Math.max((_e==null?void 0:_e.height)??500,260),640));J.api.addFloatingGroup(Qe,{x:ge?Math.max(0,st-ge.left-32):void 0,y:ge?Math.max(0,lt-ge.top-18):void 0,width:Pe,height:nt}),Qe.api.setActive(),Z(),je(),Q(Ge=>Ge+1)}}),ke=[J.api.onWillDragPanel(Ve=>{if(!(Ve.nativeEvent.defaultPrevented||Ve.nativeEvent.shiftKey)){try{if(Ve.panel.group.model.location.type!=="grid")return}catch{return}Fe.startDrag({panelId:Ve.panel.id,selfPanelBounds:Re(Ve.panel.group.element),...Ce(Ve.nativeEvent)})}}),J.api.onWillShowOverlay(Ve=>{if(Fe.hasDetached()){Ve.preventDefault();return}Fe.markDockTarget(Ce(Ve.nativeEvent))}),J.api.onWillDrop(Ve=>{if(Fe.hasDetached()){Ve.preventDefault(),Fe.endDrag();return}Fe.markDockTarget(Ce(Ve.nativeEvent))}),J.api.onDidDrop(()=>Fe.endDrag()),J.api.onUnhandledDragOverEvent(Ve=>{Fe.isDragging()&&Fe.markSelfPanel(Ce(Ve.nativeEvent))})],Ze=Ve=>{if(!Fe.isDragging())return;const st=Ce(Ve);Ue(st)&&Fe.markNonSelfPanel(st)},et=()=>Fe.endDrag();window.addEventListener("dragover",Ze,!0),window.addEventListener("drop",et,!0),window.addEventListener("dragend",et,!0),L.current=()=>{Fe.dispose();for(const Ve of ke)Ve.dispose();window.removeEventListener("dragover",Ze,!0),window.removeEventListener("drop",et,!0),window.removeEventListener("dragend",et,!0)}}J.api.onDidAddGroup(Ce=>{requestAnimationFrame(()=>{var Re,Ue;try{const Fe=(Re=Ce.element)==null?void 0:Re.ownerDocument;if(!Fe||Fe===document)return;(Ue=Fe.getElementById("dv-popout-window"))==null||Ue.classList.add("adhdev-dockview");const ke=document.documentElement.getAttribute("data-theme");ke&&Fe.documentElement.setAttribute("data-theme",ke),Fe.body.className=document.body.className;const Ze=document.documentElement.getAttribute("style");Ze&&Fe.documentElement.setAttribute("style",Ze)}catch{}je(),Q(Fe=>Fe+1)})}),g(((xe=J.api.activePanel)==null?void 0:xe.id)??null)},[E,oe,R,s,d,y,g,Z,b,k,C,je,e]);l.useLayoutEffect(()=>{const J=A.current;if(!J||!M.current||$.current&&Nh({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:s}))return;$.current&&($.current=!1);const re=B.current,le=new Set(re),xe=e.map(et=>et.tabKey),Ce=new Set(xe),Re=OI({previousVisibleConversationCount:re.length,visibleConversationCount:e.length,ides:s});let Ue=!1;for(const et of re)Ce.has(et)||Re||(K.current[et]=ye(et),Ue=!0);Ue&&se(),Re||(Ih(J,e),Mh(J,e,k));const Fe=xe.filter(et=>!le.has(et));let ke=!1;for(const et of Fe){const Ve=J.getPanel(et),st=K.current[et];if(!Ve||!st||st.kind==="grid")continue;if(Ve.group.model.location.type===st.kind){delete K.current[et],ke=!0;continue}if(st.kind==="floating"){J.addFloatingGroup(Ve,{x:st.position.left??24,y:st.position.top??24,width:st.position.width,height:st.position.height}),delete K.current[et],ke=!0;continue}}if(ke&&se(),B.current=xe,b&&oe(b))return;!J.activePanel&&J.panels[0]&&E(J.panels[0]),!!(J.activePanel&&J.getPanel(J.activePanel.id))||Ie()},[E,oe,Ie,s,d,se,ye,b,k,e]),l.useEffect(()=>{M.current&&oe(b)},[oe,b]),l.useEffect(()=>{const J=le=>{const xe=le.target;if(!xe)return;const Ce=xe.querySelector("[data-tab-key]")||xe.closest("[data-tab-key]");if(Ce){const Re=Ce.getAttribute("data-tab-key");if(Re&&le.dataTransfer){const Ue=xe.closest(".dv-tab")||Ce.closest(".dv-tab")||Ce;le.dataTransfer.effectAllowed="move",le.dataTransfer.setData("text/tab-key",Re),Ue instanceof HTMLElement&&le.dataTransfer.setDragImage(Ue,Math.max(12,Math.round(Ue.clientWidth/2)),Math.max(10,Math.round(Ue.clientHeight/2)))}}};window.addEventListener("dragstart",J);const re=Th(A.current);for(const le of re)le.addEventListener("dragstart",J);return()=>{window.removeEventListener("dragstart",J);for(const le of re)le.removeEventListener("dragstart",J)}},[q]),l.useEffect(()=>{var re;const J=(re=O.current)==null?void 0:re.querySelector(".adhdev-dockview");J instanceof HTMLElement&&Pl(J,S),U(),je()},[je,U,S]),l.useEffect(()=>{je()},[je]),l.useEffect(()=>{const J=re=>{if(re.defaultPrevented||Je)return;const le=Ee(re);if(!le)return;const xe=re.metaKey||re.ctrlKey||re.altKey;Uc(re.target)&&!xe||ci(Be).setActiveTabShortcut!==le||(re.preventDefault(),re.stopPropagation(),pe())};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[Ee,Be,Je,pe]),l.useEffect(()=>{const J=O.current;if(!J)return;const re=le=>{var Fe,ke;if(!le.isTrusted)return;const xe=(ke=(Fe=le.target)==null?void 0:Fe.closest)==null?void 0:ke.call(Fe,".dv-scrollable");if(!xe)return;le.preventDefault(),le.stopPropagation();const Ce=Math.abs(le.deltaX),Re=Math.abs(le.deltaY),Ue=Ce>Re?le.deltaX:le.deltaY;xe.dispatchEvent(new WheelEvent("wheel",{deltaY:Ue,deltaMode:le.deltaMode,bubbles:!1,cancelable:!0}))};return J.addEventListener("wheel",re,{passive:!1,capture:!0}),()=>J.removeEventListener("wheel",re,{capture:!0})},[]),l.useEffect(()=>{const J=Th(A.current);if(J.length===0)return;const re=J.map(le=>{let xe=[],Ce=null;const Re=()=>{Ce!=null&&le.clearTimeout(Ce),Ce=null,xe=[]},Ue=()=>{Ce!=null&&le.clearTimeout(Ce),Ce=le.setTimeout(()=>{Ce=null,xe=[]},1200)},Fe=Ze=>{if(!Ze.ctrlKey&&!Ze.metaKey&&!Ze.altKey)return;const et=Ee(Ze);if(!et)return;const Ve=Vb();for(const[st,lt]of Object.entries(Ve))if(e.some(Qe=>Qe.tabKey===st)&<===et){Ze.preventDefault(),X(st);return}},ke=Ze=>{if(Ze.defaultPrevented||Je)return;const et=Ee(Ze);if(!et)return;const Ve=Ze.metaKey||Ze.ctrlKey||Ze.altKey;if(Uc(Ze.target))return;const st=ci(Be),lt=Object.entries(st).filter(([Ge,bt])=>!!bt&&(Ge==="splitActiveTabRight"||Ge==="splitActiveTabDown"||Ge==="floatActiveTab"||Ge==="popoutActiveTab"||Ge==="dockActiveTab"||Ge==="focusLeftPane"||Ge==="focusRightPane"||Ge==="focusUpPane"||Ge==="focusDownPane"||Ge==="moveActiveTabToLeftPane"||Ge==="moveActiveTabToRightPane"||Ge==="moveActiveTabToUpPane"||Ge==="moveActiveTabToDownPane"||Ge==="selectPreviousGroupTab"||Ge==="selectNextGroupTab"||Ge==="setActiveTabShortcut"||Ge==="hideCurrentTab")),Qe=Ve?[et]:[...xe.slice(-1),et].slice(-2),ge=Qe.join(" "),_e=Qe[Qe.length-1],Pe=lt.find(([,Ge])=>Ge===ge);if(Pe){Ze.preventDefault(),Re(),Y(Pe[0]);return}if(lt.some(([,Ge])=>Ge.startsWith(`${ge} `))){Ze.preventDefault(),xe=Qe,Ue();return}const ze=lt.find(([,Ge])=>Ge===_e);if(ze){Ze.preventDefault(),Re(),Y(ze[0]);return}if(lt.some(([,Ge])=>Ge.startsWith(`${_e} `))){Ze.preventDefault(),xe=[_e],Ue();return}Re()};return le.addEventListener("keydown",Fe),le.addEventListener("keydown",ke),()=>{Re(),le.removeEventListener("keydown",Fe),le.removeEventListener("keydown",ke)}});return()=>{for(const le of re)le()}},[Ee,Be,q,X,Je,Y,e]);const De=S==="light"?Zl:ec,Te=((Ct=(tt=(He=A.current)==null?void 0:He.activePanel)==null?void 0:tt.group.element)==null?void 0:Ct.ownerDocument)??document;return n.jsxs(nx.Provider,{value:me,children:[n.jsx("div",{ref:O,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:n.jsx(Zx,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:YI,remote:KI},defaultTabComponent:zI,watermarkComponent:qI,onReady:Me,singleTabMode:"default",tabAnimation:"smooth",theme:De,popoutUrl:"/popout.html"})}),T&&Qn.createPortal(n.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[var(--z-popover)] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:T.x,top:T.y},children:fe.map(J=>{if(J.type==="separator")return n.jsx("div",{className:"border-t border-border-subtle my-1"},J.id);let re=n.jsx(tf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{};switch(J.id){case"dockInWindow":case"dockBackToGrid":re=n.jsx(Cw,{size:13,className:"shrink-0 opacity-70"}),le=()=>{ee(T.tabKey),F(null)};break;case"moveBackToMain":re=n.jsx(jw,{size:13,className:"shrink-0 opacity-70"}),le=()=>{be(T.tabKey),F(null)};break;case"floatAsPanel":re=n.jsx(Nw,{size:13,className:"shrink-0 opacity-70"}),le=()=>{ce(T.tabKey),F(null)};break;case"openInNewWindow":re=n.jsx(kw,{size:13,className:"shrink-0 opacity-70"}),le=()=>{ae(T.tabKey),F(null)};break;case"setShortcut":le=xe=>{xe.stopPropagation(),Se(T.tabKey),F(null)};break;case"removeShortcut":re=n.jsx(Bt,{size:13,className:"shrink-0 opacity-70"}),le=()=>{const xe={...Le};delete xe[T.tabKey],he(xe),F(null)};break;case"hideTab":re=n.jsx(xi,{size:13,className:"shrink-0 opacity-70"}),le=()=>{we(T.tabKey),F(null)};break}return n.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${J.tone==="muted"?"text-text-muted":""}`,onMouseDown:VI,onClick:le,children:[re,n.jsx("span",{className:"flex-1 min-w-0",children:J.label}),J.shortcut?n.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:J.shortcut}):null]},J.id)})}),T.sourceDocument.body),Je&&Qn.createPortal(n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>Se(null),children:n.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:J=>J.stopPropagation(),children:[n.jsxs("div",{className:"text-sm font-bold text-text-primary mb-2",children:["⌨ ",w("paneGroup.shortcutSetTitle")]}),n.jsx("div",{className:"text-xs text-text-secondary mb-4",children:w("paneGroup.shortcutPressCombo",{example1:Be?"⌘+1":"Ctrl+1",example2:Be?"⌥+A":"Alt+A"})}),n.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:w("paneGroup.shortcutListening")}),n.jsx("div",{className:"text-3xs text-text-muted mt-3",children:w("paneGroup.pressEscToCancel")})]})}),Te.body)]})}const sx="adhdev-recent-launch-args-v1",JI=8;function XI(e){return String(e||"").trim().replace(/\s+/g," ")}function rx(e,t){return`${e.trim()}::${t.trim()}`}function ox(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(sx)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function ZI(e){if(!(typeof window>"u"))try{window.localStorage.setItem(sx,JSON.stringify(e))}catch{}}function eM(e,t){var a;const s=String(e||"").trim(),r=String(t||"").trim();return!s||!r?[]:((a=ox().byKey[rx(s,r)])==null?void 0:a.items)||[]}function tM(e,t,s){var m;const r=String(e||"").trim(),o=String(t||"").trim(),a=XI(s);if(!r||!o||!a)return;const i=ox(),c=rx(r,o),d=((m=i.byKey[c])==null?void 0:m.items)||[],u=[a,...d.filter(h=>h!==a)].slice(0,JI);i.byKey[c]={items:u},ZI(i)}const nM="adhdev.remember.";function Kc(e){return`${nM}${e.trim()}`}function Ll(e){if(typeof window>"u"||!e.trim())return null;try{const t=window.localStorage.getItem(Kc(e));if(!t)return null;const s=JSON.parse(t);if(!s||typeof s!="object"||Array.isArray(s))return null;const r={};for(const[o,a]of Object.entries(s))typeof a=="string"&&a&&(r[o]=a);return Object.keys(r).length>0?r:null}catch{return null}}function ba(e,t){if(!(typeof window>"u"||!e.trim()))try{const s={};for(const[r,o]of Object.entries(t))typeof o=="string"&&o&&(s[r]=o);if(Object.keys(s).length===0){window.localStorage.removeItem(Kc(e));return}window.localStorage.setItem(Kc(e),JSON.stringify(s))}catch{}}function sM({sessions:e,loading:t,busy:s=!1,resumingSessionId:r=null,fallbackWorkspacePath:o,onResume:a,onRefresh:i,onClose:c}){const{t:d}=ve("common"),[u,m]=l.useState(""),h=String(o||"").trim(),p=l.useMemo(()=>{const g=e.map(f=>f.canResume||String(f.workspace||"").trim()||!h?f:{...f,workspace:h,canResume:!0,workspaceFallbackSource:"selected-workspace"});return qd(g,{textQuery:u,sortMode:"recent"})},[h,u,e]);return n.jsxs("div",{className:"mt-3 flex max-h-[min(55vh,420px)] flex-col overflow-hidden rounded-xl border border-border-subtle bg-bg-secondary",role:"region","aria-label":Ec(d),"data-testid":"saved-history-inline",children:[n.jsxs("div",{className:"flex items-center gap-2 border-b border-border-subtle px-3 py-2",children:[n.jsx("input",{type:"search",value:u,onChange:g=>m(g.target.value),placeholder:d("historyModal.searchPlaceholder"),"aria-label":d("historyModal.searchPlaceholder"),className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-1.5 text-sm text-text-primary"}),n.jsx(Wi,{onClick:i,refreshing:t,className:"h-8 w-8"}),n.jsx("button",{type:"button",onClick:c,"aria-label":d("common.close"),className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border-subtle bg-transparent text-text-muted hover:text-text-primary",children:n.jsx(Bt,{size:14})})]}),n.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-2",children:[p.map(g=>{const f=r===g.providerSessionId,x=String(g.workspace||"").trim();return n.jsxs("div",{className:"flex items-center gap-3 rounded-lg px-2.5 py-2 hover:bg-bg-primary/60",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"truncate text-sm font-semibold text-text-primary",children:g.title||d("historyModal.untitledSession")}),n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-2xs text-text-muted",children:[n.jsx(Kg,{value:g.lastMessageAt}),x&&n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx(tn,{content:x,children:n.jsx("span",{className:"truncate",children:Gg(x)})})]}),g.messageCount>0&&n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:"shrink-0",children:d("historyModal.msgCount",{count:g.messageCount})})]})]})]}),g.canResume?n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",disabled:s||!!r,onClick:()=>a(g),children:d(f?"historyModal.statusResuming":"historyModal.statusResume")}):n.jsx("span",{className:"shrink-0 text-2xs text-text-muted",children:d("historyModal.statusMissingWorkspace")})]},g.id)}),!t&&p.length===0&&n.jsx("div",{className:"px-3 py-6 text-center text-xs text-text-muted",children:e.length>0?d("historyModal.noMatchingHistory"):rb(d)}),t&&p.length===0&&n.jsx("div",{className:"px-3 py-6 text-center text-xs text-text-muted",children:d("launch.loadingShort")})]})]})}function rM(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Hs({title:e,description:t,action:s,children:r,className:o="",contentClassName:a=""}){return n.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${o}`.trim(),children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted",children:e}),t&&n.jsx(dt,{content:t,size:12})]}),s?n.jsx("div",{className:"flex items-center gap-2",children:s}):null]}),r?n.jsx("div",{className:s?`mt-3 ${a}`.trim():`mt-2 ${a}`.trim(),children:r}):null]})}function oM(e,{savedSessionsLoading:t,savedSessionsLoaded:s,savedSessionsCount:r=0}){return t?e("launch.refreshingSavedHistory"):s?r>0?e("launch.savedHistoryLoadedCount",{count:r}):e("launch.savedHistoryNoneYet"):""}function aM({busy:e,savedSessionsLoading:t,savedSessionsError:s,savedSessionsLoaded:r,savedSessionsCount:o=0,selectedSession:a,historyOpen:i=!1,onOpenHistory:c,onClearSelection:d}){const{t:u}=ve("common"),m=a?Wb(a,u):null,h=oM(u,{savedSessionsLoading:t,savedSessionsLoaded:r,savedSessionsCount:o}),p=!!m||!!h||!!s;return n.jsx(Hs,{title:u("launch.savedHistoryBadge"),description:zd(u),action:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,"aria-expanded":i,onClick:c,children:bA(u)}),children:p?n.jsxs(n.Fragment,{children:[m?n.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-2xs text-text-muted leading-relaxed",children:n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted",children:u("launch.selectedSavedHistory")}),n.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",title:m.providerSessionId,children:m.title}),n.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&n.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&n.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:u("launch.clearSelection")})]})}):h?n.jsx("div",{className:"text-2xs text-text-muted","aria-live":"polite",children:h}):null,s?n.jsx("div",{className:"mt-2 text-2xs text-status-error",children:s}):null]}):null})}function ax({setup:e,providerName:t,className:s=""}){const{t:r}=ve("common");return e?n.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${s}`,children:[n.jsx("div",{className:"font-semibold",children:t?r("mesh.manualSetup.titleFor",{provider:t}):r("mesh.manualSetup.title")}),e.instructions&&n.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-2xs text-text-muted",children:[e.serverName&&n.jsxs("span",{children:[r("mesh.manualSetup.server")," ",n.jsx("code",{children:e.serverName})]}),e.configFormat&&n.jsxs("span",{children:[r("mesh.manualSetup.format")," ",n.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&n.jsxs("span",{children:[r("mesh.manualSetup.configPath")," ",n.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&n.jsx("span",{children:r("mesh.manualSetup.restartHint")})]}),e.template&&n.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}const iM={cli:"CLI",ide:"IDE",acp:"ACP"},lM=new Set(["--dangerously-skip-permissions","--dangerously-bypass-approvals-and-sandbox","bypassPermissions","sandbox_mode=danger-full-access","approval_policy=never"]);function cM(e){const t=e.trim();return lM.has(t)||t.startsWith("--dangerously-skip-permissions=")||t.startsWith("--dangerously-bypass-approvals-and-sandbox=")}function Yn(e){var t;return(t=e.launchArgs)!=null&&t.some(cM)?"dangerous":e.risk}function dM(e){var s,r;if(!e)return"";const t=e.modes.find(o=>o.id===e.default);return t&&Yn(t)!=="dangerous"?t.id:((s=e.modes.find(o=>o.strategy==="pty-parse-default"&&Yn(o)!=="dangerous"))==null?void 0:s.id)||((r=e.modes.find(o=>Yn(o)!=="dangerous"))==null?void 0:r.id)||""}function uM(e,t,s){return e?t?{autoApproveMode:t}:{autoApprove:!1}:{autoApprove:s}}const mM={safe:"border-status-online/25 bg-status-online/10 text-status-online",caution:"border-status-warning/30 bg-status-warning/10 text-status-warning",dangerous:"border-status-error/30 bg-status-error/10 text-status-error"};function ix({risk:e}){const{t}=ve();return n.jsx("span",{className:`rounded-full border px-2 py-0.5 text-3xs font-semibold uppercase tracking-wide ${mM[e]}`,children:t(`newSession.autoApproveRisk.${e}`)})}function lx({config:e,selectedModeId:t,disabled:s=!1,onSelectMode:r}){const{t:o}=ve();return n.jsx("div",{className:"space-y-2",children:n.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":o("newSession.autoApproveMode"),children:e.modes.map(a=>{const i=Yn(a),c=t===a.id;return n.jsxs("button",{type:"button",role:"radio","aria-checked":c,className:`flex w-full items-center justify-between gap-3 rounded-xl border px-3.5 py-3 text-left transition-colors ${c?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>r(a),disabled:s,children:[n.jsx("span",{className:"min-w-0 text-sm font-semibold text-text-primary",children:a.label}),n.jsx(ix,{risk:i})]},a.id)})})})}function hM({checked:e,disabled:t=!1,onChange:s}){const{t:r}=ve();return n.jsxs("div",{className:"flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-secondary/40 px-3.5 py-3",children:[n.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[n.jsx("span",{id:"legacy-auto-approve-label",className:"text-sm font-semibold text-text-primary",children:r("newSession.autoApproveLegacy")}),n.jsx(dt,{content:r("newSession.autoApproveLegacyDescription")})]}),n.jsx(Ur,{checked:e,onChange:s,disabled:t,"aria-labelledby":"legacy-auto-approve-label"})]})}function cx({mode:e,onConfirm:t,onCancel:s}){const{t:r}=ve();return n.jsx(Ui,{title:r("newSession.dangerousModeTitle"),description:e.warning||r("newSession.dangerousModeFallbackWarning"),details:[{label:r("newSession.dangerousModeRisk"),value:r("newSession.autoApproveRisk.dangerous")},{label:r("newSession.dangerousModeLaunchArgs"),value:JSON.stringify(e.launchArgs||[])}],confirmLabel:r("newSession.dangerousModeConfirm"),onConfirm:t,onCancel:s})}function jo(e,t){var s;return e?t==="ide"?(((s=e.detectedIdes)==null?void 0:s.length)||0)>0:(e.availableProviders||[]).some(r=>Mo(r,t)):!1}function El(e){return e?jo(e,"cli")?"cli":jo(e,"ide")?"ide":jo(e,"acp")?"acp":null:null}const Dl="new-session-dialog",Ph="new-session-workspace",Lh="new-session-mesh",qc={value:"",source:null};function Eh(e,t){return e?{value:e,source:t}:qc}function Dh(e,t){return{...e.value.trim()&&e.source?{modelSource:e.source}:{},...t.value.trim()&&t.source?{thinkingLevelSource:t.source}:{}}}function pM(e){return e==="cli"||e==="ide"||e==="acp"}function pr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function fM({machines:e,ides:t,onClose:s,onBrowseDirectory:r,onSaveWorkspace:o,onLaunchIde:a,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:u,initialMachineId:m,initialWorkspaceId:h,initialLaunchMode:p,initialMeshWorkspacePath:g}){var Yt,us,pu,fu,gu,bu,xu,yu,vu;const{t:f}=ve(),x=Br(),b=l.useMemo(()=>[...e].sort(za),[e]),[k]=l.useState(()=>({dialog:Ll(Dl),workspace:Ll(Ph),mesh:Ll(Lh)})),[j,v]=l.useState(()=>{var Ke,We;if(m&&e.some(ot=>ot.id===m))return m;const te=(Ke=k.dialog)==null?void 0:Ke.machineId;return te&&e.some(ot=>ot.id===te)?te:((We=[...e].sort(za)[0])==null?void 0:We.id)||""}),_=l.useMemo(()=>b.find(te=>te.id===j)||b[0],[j,b]),y=l.useMemo(()=>((_==null?void 0:_.workspaces)||[]).map(te=>({id:te.id,path:te.path,label:te.label})),[_]),w=(_==null?void 0:_.defaultWorkspaceId)||null,[S,C]=l.useState("workspace"),[A,O]=l.useState(""),[L,M]=l.useState(""),[$,N]=l.useState([]),[I,B]=l.useState(""),[T,F]=l.useState(!1),[q,Q]=l.useState(null),[K,R]=l.useState(""),[D,P]=l.useState(El(b[0])),[H,W]=l.useState(""),[U,ae]=l.useState(""),[be,V]=l.useState(!1),[we,ce]=l.useState(""),[de,ne]=l.useState(null),[ee,ue]=l.useState(qc),[je,X]=l.useState(qc),G=ee.value,z=je.value,ie=l.useCallback((te,Ke)=>{ue(Eh(te,Ke))},[]),Ne=l.useCallback((te,Ke)=>{X(Eh(te,Ke))},[]),[Be,Le]=l.useState(!1),[Je,Se]=l.useState([]),[he,pe]=l.useState(""),[Ee,Y]=l.useState([]),[me,fe]=l.useState(!1),[E,oe]=l.useState(!1),[Ie,Z]=l.useState(""),[se,ye]=l.useState(!1),[$e,Me]=l.useState(null),[De,Te]=l.useState(!1),[He,tt]=l.useState(""),[Ct,J]=l.useState("error"),[re,le]=l.useState(null),[xe,Ce]=l.useState(!1),[Re,Ue]=l.useState(""),[Fe,ke]=l.useState([]),[Ze,et]=l.useState(!1),[Ve,st]=l.useState(""),[lt,Qe]=l.useState(!1),ge=l.useRef(null),_e=l.useRef(h||null),Pe=l.useRef(p||(((Yt=k.dialog)==null?void 0:Yt.mode)==="mesh"||((us=k.dialog)==null?void 0:us.mode)==="workspace"?k.dialog.mode:null)),nt=l.useRef(g||null),ze=l.useRef(h?null:((pu=k.workspace)==null?void 0:pu.workspaceChoice)||null),ut=(fu=k.workspace)==null?void 0:fu.kind,Ge=l.useRef(pM(ut)?ut:null),bt=l.useRef(((gu=k.workspace)==null?void 0:gu.target)||null),Mt=l.useRef(((bu=k.mesh)==null?void 0:bu.meshId)||null),Pt=l.useRef(((xu=k.mesh)==null?void 0:xu.cliType)||null),mn=l.useRef(!0),nn=l.useRef(!0),Jt=l.useRef(0),Dt=l.useRef(0),hn=l.useRef(0);l.useEffect(()=>{var te,Ke;if(!j&&((te=b[0])!=null&&te.id)){const We=(Ke=k.dialog)==null?void 0:Ke.machineId,ot=m&&b.some(bn=>bn.id===m)?m:We&&b.some(bn=>bn.id===We)?We:b[0].id;v(ot)}},[m,k,j,b]),l.useEffect(()=>{!_||!(!_.workspaces||!_.availableProviders||!_.detectedIdes||!_.recentLaunches)||x(_.id,{minFreshMs:3e4}).catch(()=>{})},[x,_]);const Wn=l.useCallback(te=>{te&&x(te,{minFreshMs:3e4}).catch(()=>{})},[x]),Tt=l.useMemo(()=>((_==null?void 0:_.availableProviders)||[]).filter(te=>Mo(te,"cli")),[_]),Vt=l.useMemo(()=>((_==null?void 0:_.availableProviders)||[]).filter(te=>Mo(te,"acp")),[_]),pn=l.useMemo(()=>((_==null?void 0:_.detectedIdes)||[]).map(te=>({id:te.type,label:te.name||te.type,meta:te.running?f("newSession.detectedLocally"):f("newSession.availableToOpen")})),[_,f]),Oe=l.useMemo(()=>D==="cli"?Tt.map(te=>({id:te.type,label:te.displayName||te.type,meta:""})):D==="acp"?Vt.map(te=>({id:te.type,label:te.displayName||te.type,meta:""})):pn,[Vt,D,Tt,pn]),rt=l.useMemo(()=>{const te=Tt.map(ot=>({kind:"cli",id:ot.type,label:ot.displayName||ot.type,meta:""}));if(S==="mesh")return te;const Ke=Vt.map(ot=>({kind:"acp",id:ot.type,label:ot.displayName||ot.type,meta:""})),We=pn.map(ot=>({kind:"ide",...ot}));return[...te,...Ke,...We]},[Vt,Tt,pn,S]),pt=l.useMemo(()=>$.find(te=>te.id===I)||null,[$,I]),xt=l.useMemo(()=>Tt.find(te=>te.type===H)||null,[Tt,H]),yt=l.useMemo(()=>[...Tt,...Vt].find(te=>te.type===H),[Tt,Vt,H]),kt=D==="cli"?yt==null?void 0:yt.autoApproveModes:void 0,fn=JSON.stringify(kt||null),Ye=dM(kt),mt=l.useMemo(()=>AA(yt?[yt]:[],yt==null?void 0:yt.type),[yt]),Zt=l.useMemo(()=>{const te=TA(yt?[yt]:[],yt==null?void 0:yt.type);return te.length?te:["low","medium","high"]},[yt]),Sn=l.useMemo(()=>Db(xt==null?void 0:xt.meshCoordinator,{meshId:(pt==null?void 0:pt.id)||"",workspace:(pt==null?void 0:pt.workspace)||""}),[xt,pt]),sn=re||Sn,rn=l.useCallback(async te=>{const Ke=hn.current+1;hn.current=Ke,F(!0),R("");try{const We=await c(te);if(hn.current!==Ke)return;N(We),B(ot=>{var bn;return We.some(ms=>ms.id===ot)?ot:((bn=We[0])==null?void 0:bn.id)||""}),Q(te)}catch(We){if(hn.current!==Ke)return;N([]),B(""),Q(te),R(We instanceof Error?We.message:f("newSession.errorLoadMeshes"))}finally{hn.current===Ke&&F(!1)}},[c,f]);l.useEffect(()=>{var bn,ms;if(!_)return;if(ge.current!==_.id){Dt.current+=1,hn.current+=1,ge.current!==null&&(_e.current=null,Pe.current=null,nt.current=null,ze.current=null,Ge.current=null,bt.current=null,Mt.current=null,Pt.current=null,mn.current=!1,nn.current=!1),ge.current=_.id;const Ot=Pe.current;Pe.current=null,C(Ot||"workspace");const Un=_e.current,ts=ze.current;M(""),Ce(!1),Ue(""),ke([]),et(!1),st(""),Un&&y.some(tl=>tl.id===Un)?(_e.current=null,O(Un)):ts==="__home__"?(ze.current=null,O("__home__")):ts==="__custom__"&&((bn=k.workspace)!=null&&bn.customWorkspacePath)?(ze.current=null,O("__custom__"),M(k.workspace.customWorkspacePath)):ts&&y.some(tl=>tl.id===ts)?(ze.current=null,O(ts)):O(w||((ms=y[0])==null?void 0:ms.id)||"__home__"),N([]),B(""),F(!1),Q(null),R("");const el=Ge.current;el&&jo(_,el)?(Ge.current=null,P(el)):P(El(_)),W(""),ae(""),V(!1),ce(""),ne(null),ie("","user"),Ne("","user"),Le(!1),pe(""),Y([]),oe(!1),Z(""),ye(!1),tt(""),le(null);return}const Ke=_e.current,We=ze.current;Ke&&y.some(Ot=>Ot.id===Ke)?(_e.current=null,O(Ke)):We&&y.some(Ot=>Ot.id===We)?(ze.current=null,O(We)):O(Ot=>{var Un;return Ot==="__custom__"||Ot==="__home__"||y.some(ts=>ts.id===Ot)?Ot:w||((Un=y[0])==null?void 0:Un.id)||"__home__"});const ot=Ge.current;ot&&jo(_,ot)?(Ge.current=null,P(ot)):P(Ot=>Ot==="ide"&&pn.length>0||Ot==="cli"&&Tt.length>0||Ot==="acp"&&Vt.length>0?Ot:El(_))},[Vt.length,Tt.length,w,pn.length,k,_,y]),l.useEffect(()=>{!_||S!=="mesh"||q===_.id||T||rn(_.id)},[rn,q,T,_,S]),l.useEffect(()=>{if($.length===0)return;const te=nt.current;if(te){nt.current=null,Mt.current=null;const We=$.find(ot=>pr(ot.workspace)===pr(te));We&&B(We.id);return}const Ke=Mt.current;Ke&&(Mt.current=null,$.some(We=>We.id===Ke)&&B(Ke))},[$]),l.useEffect(()=>{S==="mesh"&&D!=="cli"&&Tt.length>0&&P("cli")},[D,Tt.length,S]),l.useEffect(()=>{var We;if(!D||Oe.some(ot=>ot.id===H))return;let te=((We=Oe[0])==null?void 0:We.id)||"";const Ke=bt.current;S!=="mesh"&&Ke&&Oe.length>0&&D===ut&&(bt.current=null,Oe.some(ot=>ot.id===Ke)&&(te=Ke)),W(te)},[D,Oe,ut,H,S]),l.useEffect(()=>{if(S!=="mesh")return;const te=Pt.current;!te||Tt.length===0||(Pt.current=null,Tt.some(Ke=>Ke.type===te)&&W(te))},[Tt,S]),l.useEffect(()=>{le(null)},[_==null?void 0:_.id,I,H,S]),l.useEffect(()=>{ie("","user"),Ne("","user"),Le(!1)},[H,ie,Ne]),l.useEffect(()=>{ce(Ye),V(!1),ne(null)},[fn,Ye,_==null?void 0:_.id,H]),l.useEffect(()=>{if(!H)return;const te=S==="mesh",Ke=te?nn:mn;if(!Ke.current)return;const We=te?k.mesh:k.workspace,ot=te?We==null?void 0:We.cliType:We==null?void 0:We.target;if(!We||ot!==H)return;Ke.current=!1;const bn=We.model||"";bn&&(mt.length>0&&!mt.includes(bn)&&Le(!0),ie(bn,"remembered"));const ms=We.thinkingLevel||"";ms&&Zt.includes(ms)&&Ne(ms,"remembered");const Ot=We.autoApproveModeId||"";if(Ot&&kt){const Un=kt.modes.find(ts=>ts.id===Ot);Un&&Yn(Un)!=="dangerous"&&ce(Un.id)}},[kt,fn,mt,k,H,ie,Ne,Zt,S]);const In=l.useCallback(te=>{if(Yn(te)==="dangerous"){ne(te);return}ce(te.id)},[]),jt=l.useMemo(()=>uM(kt,we,be),[kt,be,we]),en=l.useCallback(async(te,Ke)=>{const We=Jt.current+1;return Jt.current=We,fe(!0),Z(""),u(te,Ke).then(ot=>{Jt.current===We&&Y(ot)}).catch(ot=>{Jt.current===We&&(Y([]),Z(ot instanceof Error?ot.message:f("newSession.errorLoadSavedSessions")))}).finally(()=>{Jt.current===We&&(fe(!1),oe(!0))})},[u,f]),gn=l.useCallback((te,Ke)=>{Se(eM(te,Ke))},[]);l.useEffect(()=>{Jt.current+=1,pe(""),ye(!1),!_||!H||D==="ide"?Se([]):gn(_.id,H),oe(!1),Y([]),Z(""),fe(!1)},[D,gn,en,_,H]),l.useEffect(()=>{if(!he)return;const te=Ee.find(Ke=>Ke.providerSessionId===he);te!=null&&te.canResume||pe("")},[Ee,he]);const Wt=A==="__custom__"?L.trim():A==="__home__"?"":((yu=y.find(te=>te.id===A))==null?void 0:yu.path)||"",Rs=l.useMemo(()=>_?t.filter(te=>te.id!==_.id&&te.daemonId===_.id).map(te=>te.workspace):[],[t,_]),kn=l.useMemo(()=>((_==null?void 0:_.recentLaunches)||[]).map(te=>te.workspace),[_]),Ko=l.useCallback(te=>{const Ke=String(te.workspace||"").trim();if(!Ke)return;const We=y.find(ot=>pr(ot.path)===pr(Ke));if(We){O(We.id),M("");return}O("__custom__"),M(Ke)},[y]),qo=l.useCallback(te=>{const Ke=String(te.workspace||"").trim();if(!Ke)return{workspaceId:null,workspacePath:null,useHome:!0};const We=y.find(ot=>pr(ot.path)===pr(Ke));return We?{workspaceId:We.id,workspacePath:null,useHome:!1}:{workspaceId:null,workspacePath:Ke,useHome:!1}},[y]),Ji=l.useMemo(()=>Ee.find(te=>te.providerSessionId===he)||null,[Ee,he]),Xi=l.useCallback(te=>{if(!_||!H||$e||!te.canResume)return;const Ke=qo(te);pe(te.providerSessionId),Ko(te),Me(te.providerSessionId),ye(!1),Te(!0),tt(""),i(_.id,"cli",H,{workspaceId:Ke.workspaceId,workspacePath:Ke.workspacePath,useHome:Ke.useHome,resumeSessionId:te.providerSessionId,settings:jt}).then(We=>{if(!We.ok){J("error"),tt(We.code==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"?f("newSession.errorWorkspaceContextRequired"):We.error||f("newSession.errorResumeSession"));return}s()}).finally(()=>{Te(!1),Me(We=>We===te.providerSessionId?null:We)})},[Ko,jt,s,i,qo,$e,_,H,f]),zo=((vu=kt==null?void 0:kt.modes.find(te=>te.id===we))==null?void 0:vu.label)||"",Go=[U.trim(),G.trim(),z.trim(),D==="cli"||S==="mesh"?kt?zo:be?f("newSession.autoApproveLegacy"):"":""].filter(Boolean).join(" · "),Kr=l.useCallback(()=>{var We;if(!_)return;const te=Dt.current+1;Dt.current=te,O("__custom__"),Ce(!0),st("");const Ke=su(_.platform,nu(L.trim(),Wt,Rs,kn,_.defaultWorkspacePath,(We=y.find(ot=>ot.id===w))==null?void 0:We.path,y.map(ot=>ot.path)));et(!0),r(_.id,Ke).then(ot=>{Dt.current===te&&(Ue(ot.path),M(ot.path),ke(ot.directories))}).catch(ot=>{Dt.current===te&&st(ot instanceof Error?ot.message:f("newSession.errorLoadFolder"))}).finally(()=>{Dt.current===te&&et(!1)})},[L,w,kn,Rs,r,Wt,_,y]),Zi=l.useCallback(te=>{if(!_)return;const Ke=Dt.current+1;Dt.current=Ke,et(!0),st(""),r(_.id,te).then(We=>{Dt.current===Ke&&(Ue(We.path),M(We.path),ke(We.directories))}).catch(We=>{Dt.current===Ke&&st(We instanceof Error?We.message:f("newSession.errorLoadFolder"))}).finally(()=>{Dt.current===Ke&&et(!1)})},[r,_]),Vo=l.useCallback(async()=>{if(!_||!Wt)return;Qe(!0),tt("");const te=await o(_.id,Wt);if(Qe(!1),!te.ok){J("error"),tt(te.error||f("newSession.errorSaveWorkspace"));return}J("info"),tt(f("newSession.workspaceSaved"))},[o,Wt,_,f]),Yo=l.useCallback(async()=>{if(!_)return;if(S==="mesh"){if(!I||!H)return;Te(!0),tt(""),le(null);const We=await d(_.id,I,H,{initialModel:G.trim()?G.trim():null,initialThinkingLevel:z.trim()?z.trim():null,...Dh(ee,je),settings:jt});if(Te(!1),!We.ok){if(We.code==="mesh_coordinator_manual_mcp_setup_required"&&We.manualSetup){le(We.manualSetup),J("info"),tt(f("newSession.errorManualMcpSetup"));return}J("error"),tt(We.error||f("newSession.errorStartMeshCoordinator"));return}ba(Dl,{machineId:_.id,mode:"mesh"}),ba(Lh,{meshId:I,cliType:H,model:G.trim(),thinkingLevel:z.trim(),autoApproveModeId:we}),s();return}if(!D||!H)return;Te(!0),tt("");const te=U.trim()?U.trim().split(/\s+/).filter(Boolean):[],Ke=D==="ide"?await a(_.id,H,{workspacePath:Wt||null}):await i(_.id,D,H,{workspaceId:A!=="__home__"&&A!=="__custom__"?A:null,workspacePath:A==="__custom__"&&Wt||null,useHome:A==="__home__",resumeSessionId:D==="cli"&&he?he:null,cliArgs:te,initialModel:G.trim()?G.trim():null,initialThinkingLevel:z.trim()?z.trim():null,...Dh(ee,je),settings:jt});if(Te(!1),!Ke.ok){J("error"),tt(Ke.code==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"?f("newSession.errorWorkspaceContextRequired"):Ke.error||f("newSession.errorStartSession"));return}D!=="ide"&&U.trim()&&(tM(_.id,H,U),gn(_.id,H)),ba(Dl,{machineId:_.id,mode:"workspace"}),ba(Ph,{workspaceChoice:A,customWorkspacePath:A==="__custom__"?Wt:"",kind:D,target:H,model:D==="ide"?"":G.trim(),thinkingLevel:D==="ide"?"":z.trim(),autoApproveModeId:D==="cli"?we:""}),s()},[D,U,G,z,ee,je,jt,gn,s,a,d,i,Wt,we,_,I,he,H,A,S,f]),qr=D==="cli"&&!!he,Qo=f(S==="mesh"?"newSession.startMeshCoordinator":D==="cli"?qr?"newSession.resumeSavedHistory":"newSession.startFresh":D==="ide"?"newSession.startIde":D==="acp"?"newSession.startAcpSession":"newSession.start"),Jo=f(S==="mesh"?"newSession.startingCoordinator":D==="cli"?qr?"newSession.resumingSavedHistory":"newSession.startingFresh":D==="ide"?"newSession.startingIde":D==="acp"?"newSession.startingAcpSession":"newSession.starting"),ht=b.length>5;return _?n.jsxs(n.Fragment,{children:[n.jsxs(Pr,{chrome:!1,onClose:s,closeOnBackdrop:!1,closeOnEsc:!1,ariaLabelledBy:"dashboard-new-title",overlayClassName:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",surfaceClassName:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[n.jsx("div",{className:"min-w-0",children:n.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:f("newSession.title")})}),n.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:s,"aria-label":f("newSession.close"),children:n.jsx(Bt,{size:16})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[b.length>1&&n.jsx(Hs,{title:f("newSession.machine"),children:ht?n.jsx("select",{"aria-label":f("newSession.machine"),value:_.id,onChange:te=>v(te.target.value),onFocus:()=>b.forEach(te=>Wn(te.id)),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:De,children:b.map(te=>n.jsx("option",{value:te.id,children:Tn(te,{fallbackId:te.id})},te.id))}):n.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":f("newSession.machine"),children:b.map(te=>{const Ke=Tn(te,{fallbackId:te.id}),We=_.id===te.id;return n.jsxs("button",{type:"button","aria-label":f("newSession.selectMachine",{name:Ke}),"aria-pressed":We,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${We?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>v(te.id),onMouseEnter:()=>Wn(te.id),onFocus:()=>Wn(te.id),disabled:De,title:Ke,children:[n.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${te.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),n.jsx("span",{className:"truncate",children:Ke})]},te.id)})})}),n.jsxs(Hs,{title:f("newSession.workspace"),action:S==="workspace"?n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Kr,disabled:De,children:f("newSession.browse")}):void 0,children:[n.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":f("newSession.launchTargetType"),children:[{id:"workspace",label:f("newSession.modeWorkspace"),desc:f("newSession.modeWorkspaceDesc")},{id:"mesh",label:f("newSession.modeMesh"),desc:f("newSession.modeMeshDesc")}].map(te=>n.jsxs("button",{type:"button",role:"radio","aria-checked":S===te.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${S===te.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{C(te.id),tt(""),te.id==="mesh"&&_&&q!==_.id&&!T&&rn(_.id)},disabled:De,children:[n.jsx("div",{className:"text-sm font-semibold",children:te.label}),n.jsx("div",{className:"mt-0.5 text-2xs opacity-80",children:te.desc})]},te.id))}),S==="workspace"?n.jsxs(n.Fragment,{children:[n.jsxs("select",{value:A,onChange:te=>{const Ke=te.target.value;ze.current=null,O(Ke),Ke==="__custom__"?Kr():tt("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:De,children:[n.jsx("option",{value:"__home__",children:f("newSession.homeDirectory")}),y.map(te=>n.jsxs("option",{value:te.id,children:[te.id===w?"★ ":"",_a(te.path,te.label)||te.path]},te.id)),n.jsx("option",{value:"__custom__",children:f("newSession.customFolder")})]}),n.jsx("div",{className:"mt-2 text-2xs text-text-muted break-all",children:A==="__home__"?f("newSession.launchWithoutWorkspace"):Wt||f("newSession.selectWorkspaceFolder")}),xe&&n.jsx(au,{inline:!0,title:f("newSession.selectWorkspaceTitle"),description:"",currentPath:Re,directories:Fe,busy:Ze,error:Ve,onClose:()=>Ce(!1),onNavigate:Zi,onConfirm:te=>{M(te),Ue(te),O("__custom__"),Ce(!1)}}),!xe&&A==="__custom__"&&Wt&&n.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[n.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Kr,disabled:De,children:[n.jsx(Zs,{size:14}),f("newSession.selectFolder")]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Vo,disabled:De||lt,children:f(lt?"newSession.saving":"newSession.saveWorkspace")})]})]}):n.jsxs("div",{className:"space-y-3",children:[T&&n.jsx("div",{className:"text-sm text-text-muted",children:f("newSession.loadingMeshes")}),!T&&K&&n.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:K}),!T&&!K&&$.length===0&&n.jsxs("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:[f("newSession.noMeshesShort"),n.jsx(dt,{content:f("newSession.noMeshes")})]}),$.length>0&&n.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":f("newSession.mesh"),children:$.map(te=>n.jsxs("button",{type:"button",role:"radio","aria-checked":I===te.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${I===te.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>{Mt.current=null,B(te.id)},disabled:De,children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:te.name}),n.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[te.repoIdentity||f("newSession.repoMesh"),typeof te.nodesCount=="number"?` · ${f("newSession.nodeCount",{count:te.nodesCount})}`:""]}),te.workspace&&n.jsx("div",{className:"mt-1 text-2xs text-text-muted break-all",children:f("newSession.coordinatorWorkspace",{path:te.workspace})})]},te.id))})]})]}),n.jsx(Hs,{title:f("newSession.agent"),children:n.jsxs("div",{className:"grid grid-cols-1 gap-1.5",role:"radiogroup","aria-label":f("newSession.agent"),children:[rt.map(te=>{const Ke=D===te.kind&&H===te.id;return n.jsxs("button",{type:"button",role:"radio","aria-checked":Ke,"data-launch-kind":te.kind,className:`flex w-full items-center justify-between gap-3 rounded-xl border px-3.5 py-2.5 text-left transition-colors ${Ke?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>{Ge.current=null,bt.current=null,Pt.current=null,P(te.kind),W(te.id)},disabled:De,children:[n.jsx("span",{className:"min-w-0 truncate text-sm font-semibold text-text-primary",children:te.label}),n.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[te.meta&&n.jsx("span",{className:"text-2xs text-text-muted",children:te.meta}),S!=="mesh"&&n.jsx("span",{className:"rounded-full border border-border-subtle px-1.5 py-px text-3xs font-semibold uppercase tracking-wide text-text-muted",children:iM[te.kind]})]})]},`${te.kind}:${te.id}`)}),rt.length===0&&n.jsxs("div",{className:"flex items-center gap-1 text-sm text-text-muted",children:[f("newSession.noProvidersShort"),n.jsx(dt,{content:f("newSession.noProviders")})]})]})}),S==="mesh"&&sn&&n.jsx(ax,{setup:sn,providerName:(xt==null?void 0:xt.displayName)||(xt==null?void 0:xt.name)||H}),(S==="mesh"&&!!H||S!=="mesh"&&D!=="ide")&&n.jsxs("details",{className:"group rounded-xl border border-border-subtle bg-bg-primary","data-testid":"new-session-advanced",children:[n.jsxs("summary",{className:"flex cursor-pointer select-none list-none items-center gap-2 px-4 py-3 [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"inline-block text-text-muted transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),n.jsx("span",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted",children:f("newSession.advancedOptions")}),Go&&n.jsx("span",{className:"ml-auto min-w-0 truncate text-2xs text-text-secondary","data-testid":"new-session-advanced-summary",children:Go})]}),n.jsxs("div",{className:"space-y-3 px-3 pb-3",children:[S!=="mesh"&&D!=="ide"&&n.jsxs(Hs,{title:f("newSession.startupArguments"),children:[n.jsx("input",{type:"text",value:U,onChange:te=>ae(te.target.value),placeholder:f("newSession.optionalFlags"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:De}),Je.length>0&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Je.map(te=>n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>ae(te),disabled:De,title:te,children:te},te))})]}),(S==="mesh"&&!!H||S!=="mesh"&&D==="cli")&&n.jsx(Hs,{title:f("newSession.autoApproveMode"),description:kt?f("newSession.autoApproveModeDescription"):void 0,children:kt?n.jsx(lx,{config:kt,selectedModeId:we,disabled:De,onSelectMode:In}):n.jsx(hM,{checked:be,disabled:De,onChange:V})}),(S==="mesh"&&!!H||S!=="mesh"&&D!=="ide")&&n.jsx(Hs,{title:f("newSession.modelAndThinking"),children:n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:f("newSession.model")}),mt.length>0&&!Be?n.jsxs(n.Fragment,{children:[n.jsxs("select",{value:mt.includes(G)?G:"",onChange:te=>{te.target.value==="__custom__"?(Le(!0),ie("","user")):ie(te.target.value,"user")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:De,children:[n.jsx("option",{value:"",children:f("newSession.providerDefault")}),mt.map(te=>n.jsx("option",{value:te,children:te},te)),n.jsx("option",{value:"__custom__",children:f("newSession.custom")})]}),!G.trim()&&n.jsx("span",{className:"text-2xs text-text-muted","data-testid":"new-session-default-model",children:f("newSession.defaultResolvesTo",{model:mt[0],defaultValue:"Default resolves to {{model}}"})})]}):n.jsxs(n.Fragment,{children:[n.jsx("input",{type:"text",value:G,onChange:te=>ie(te.target.value,"user"),placeholder:f("newSession.typeModelName"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:De,autoFocus:Be}),mt.length>0&&n.jsx("button",{type:"button",className:"self-start text-2xs text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{Le(!1),ie("","user")},disabled:De,children:f("newSession.backToModelList")})]})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:f("newSession.thinkingLevel")}),n.jsxs("select",{value:z,onChange:te=>Ne(te.target.value,"user"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:De,children:[n.jsx("option",{value:"",children:f("newSession.providerDefault")}),Zt.map(te=>n.jsx("option",{value:te,children:te},te))]})]})]})})]})]}),S!=="mesh"&&D==="cli"&&n.jsx(aM,{busy:De,savedSessionsLoading:me,savedSessionsError:Ie,savedSessionsLoaded:E,savedSessionsCount:Ee.length,selectedSession:Ji,historyOpen:se,onOpenHistory:()=>{if(!(!_||!H)){if(se){ye(!1);return}ye(!0),rM({hasLoadedInitialResults:E,isLoading:me})&&en(_.id,H)}},onClearSelection:()=>pe("")}),S!=="mesh"&&D==="cli"&&se&&n.jsx(sM,{sessions:Ee,loading:me,busy:De,resumingSessionId:$e,fallbackWorkspacePath:Wt||null,onRefresh:()=>{!_||!H||en(_.id,H)},onClose:()=>ye(!1),onResume:Xi}),He&&n.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${Ct==="info"?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:He})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[n.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:s,disabled:De,children:f("common.cancel")}),n.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:Yo,disabled:De||(S==="mesh"?!I||!H||D!=="cli"||T:!D||!H||A==="__custom__"&&!Wt),children:[n.jsx(Yp,{size:14}),De?Jo:Qo]})]})]}),de&&n.jsx(cx,{mode:de,onConfirm:()=>{ce(de.id),ne(null)},onCancel:()=>ne(null)})]}):null}function gM(e,t){const{sendCommand:s}=_t(),[r,o]=l.useState(null),[a,i]=l.useState(!1),c=l.useRef(0);l.useEffect(()=>{const u=c.current+1;if(c.current=u,o(null),!e||!t){i(!1);return}return i(!0),s(e,"git_remote_url",{workspace:t}).then(m=>{if(c.current!==u)return;const h=(m==null?void 0:m.result)??m;o(typeof(h==null?void 0:h.remoteUrl)=="string"?h.remoteUrl:null)}).catch(()=>{c.current===u&&o(null)}).finally(()=>{c.current===u&&i(!1)}),()=>{c.current+=1}},[e,t,s]);const d=bM(r);return{remoteUrl:r,githubUrl:d,loading:a}}function bM(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const s=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return s?`https://github.com/${s[1]}`:null}const dx=5e3;function xM(e,t){return t?`git:${t}:${e}`:`git:${e}`}function yM({workspace:e,daemonId:t,includeDiffSummary:s=!1,intervalMs:r=dx}){return{type:"subscribe",topic:"workspace.git",key:xM(e,t),params:{workspace:e,includeDiffSummary:s,intervalMs:r}}}function lu(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function sr(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const s=e;if(typeof s.error=="string"&&s.error.trim())return s.error;if(typeof s.message=="string"&&s.message.trim())return s.message}return t}function vM(e){const t=lu(e);return(t==null?void 0:t.success)===!1?{status:null,error:sr(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:sr(t,"Git status response did not include status")}}function wM(e){const t=lu(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:sr(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:sr(t,"Git diff summary response did not include diffSummary")}}function Ol(e){return e===void 0||typeof e=="boolean"}function SM(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Ol(t.binary)&&Ol(t.truncated)&&Ol(t.staged)}function kM(e){const t=lu(e);return(t==null?void 0:t.success)===!1?{diff:null,error:sr(t,"Git file diff request failed")}:SM(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:sr(t,"Git file diff response did not include a valid diff object")}}function jM({daemonId:e,workspace:t,enabled:s=!0,includeDiffSummary:r=!1,intervalMs:o=dx}){const{sendCommand:a,sendData:i}=_t(),c=typeof t=="string"?t.trim():"",d=!!(s&&e&&c),[u,m]=l.useState(null),[h,p]=l.useState(null),[g,f]=l.useState(!1),[x,b]=l.useState(null),k=l.useRef(0),j=l.useCallback(async()=>{if(!d||!e||!c)return;const _=k.current+1;k.current=_,f(!0),b(null);try{const y=vM(await a(e,"git_status",{workspace:c}));if(k.current!==_)return;if(y.error){m(null),p(null),b(y.error);return}if(m(y.status),!r){p(null);return}const w=wM(await a(e,"git_diff_summary",{workspace:c}));if(k.current!==_)return;if(w.error){p(null),b(w.error);return}p(w.diffSummary)}catch(y){if(k.current!==_)return;b(sr(y,"Git status request failed"))}finally{k.current===_&&f(!1)}},[d,e,r,a,c]),v=l.useMemo(()=>c?yM({workspace:c,daemonId:e,includeDiffSummary:r,intervalMs:o}):null,[e,r,o,c]);return l.useEffect(()=>{if(k.current+=1,m(null),p(null),f(!1),b(null),!d||!e||!c||!v)return;const _=i?_n.subscribe({sendData:i},e,v,y=>{var w,S;y.workspace===c&&(m(y.status),p(y.diffSummary??null),b(((w=y.status)==null?void 0:w.error)||((S=y.diffSummary)==null?void 0:S.error)||null),f(!1))},{retryIntervalMs:1e3}):null;return j(),()=>{k.current+=1,_==null||_()}},[d,e,j,v,i,c]),{status:u,diffSummary:h,loading:g,error:x,refresh:j}}const NM={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},CM={added:"text-status-online",modified:"text-orange-400",deleted:"text-status-error",renamed:"text-accent-primary",copied:"text-accent-primary",untracked:"text-text-muted",conflict:"text-status-error font-bold"};function Oh(e){return e.split("/").pop()??e}function _M(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function AM({files:e,truncated:t,onFileClick:s,selectedPath:r,className:o=""}){const{t:a}=ve("common");return e.length===0?n.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:a("git.changeList.noChanges")}):n.jsxs("div",{className:`flex flex-col ${o}`,children:[n.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(i=>{const c=r===i.path,d=NM[i.status]??"?",u=CM[i.status]??"text-text-muted",m=_M(i.path),h=Oh(i.path),p=i.staged?n.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-status-online align-middle",title:a("git.changeList.stagedHint")}):null;return n.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${c?"bg-surface-elevated":""}`,onClick:()=>s==null?void 0:s(i),children:[n.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${u}`,title:i.status,children:d}),n.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&n.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),n.jsx("span",{className:"text-text-primary",children:h}),i.oldPath&&n.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Oh(i.oldPath)]}),p]}),!i.binary&&(i.insertions>0||i.deletions>0)&&n.jsxs("span",{className:"shrink-0 font-mono text-3xs",children:[i.insertions>0&&n.jsxs("span",{className:"text-status-online",children:["+",i.insertions]}),i.insertions>0&&i.deletions>0&&n.jsx("span",{className:"text-text-secondary",children:" "}),i.deletions>0&&n.jsxs("span",{className:"text-status-error",children:["-",i.deletions]})]}),i.binary&&n.jsx("span",{className:"shrink-0 text-3xs text-text-secondary",children:a("git.changeList.binaryBadge")})]},`${i.path}-${i.staged?"S":"U"}`)})}),t&&n.jsx("p",{className:"px-3 py-1.5 text-3xs text-text-secondary",children:n.jsx(Wa,{i18nKey:"git.changeList.truncatedNote",ns:"common",components:{code:n.jsx("code",{className:"font-mono"})}})})]})}function TM(e,t){let s="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?s="bg-status-online/10 text-status-online":e.startsWith("-")&&!e.startsWith("---")?s="bg-status-error/10 text-status-error":e.startsWith("@@")?s="text-accent-primary":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(s="text-text-secondary"),n.jsx("div",{className:`px-3 ${s}`,children:n.jsx("code",{className:"whitespace-pre font-mono text-2xs leading-5",children:e})},t)}function IM({diff:e,binary:t,truncated:s,loading:r,error:o,className:a=""}){const{t:i}=ve("common"),c=l.useRef(null);if(l.useEffect(()=>{c.current&&(c.current.scrollTop=0)},[e]),r)return n.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${a}`,children:i("git.diffPreview.loading")});if(o)return n.jsx("div",{className:`px-3 py-4 text-xs text-status-error ${a}`,children:o});if(t)return n.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${a}`,children:i("git.diffPreview.binary")});if(!e)return n.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${a}`,children:i("git.diffPreview.empty")});const d=e.split(`
|
|
70
|
+
`);return n.jsxs("div",{ref:c,className:`overflow-auto ${a}`,children:[n.jsx("div",{className:"py-1",children:d.map((u,m)=>TM(u,m))}),s&&n.jsxs("p",{className:"px-3 py-1.5 text-3xs text-text-secondary border-t border-border/30",children:[i("git.diffPreview.truncatedBefore")," ",n.jsx("code",{className:"font-mono",children:"git diff"})," ",i("git.diffPreview.truncatedAfter")]})]})}function MM(e,t){const s=[`Branch: ${e||"unknown"}`];s.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const r={};for(const o of t.files)r[o.status]||(r[o.status]=[]),r[o.status].push(o.path);for(const[o,a]of Object.entries(r))s.push(`${o}: ${a.slice(0,5).join(", ")}${a.length>5?` (+${a.length-5} more)`:""}`);return s.join(`
|
|
71
|
+
`)}function ux({daemonId:e,workspace:t,onClose:s}){const{t:r}=ve("common"),{sendCommand:o}=_t(),{status:a,diffSummary:i,loading:c,error:d,refresh:u}=jM({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,h]=l.useState(null),[p,g]=l.useState(null),[f,x]=l.useState(""),[b,k]=l.useState(!1),[j,v]=l.useState(!1),[_,y]=l.useState(null),[w,S]=l.useState(null),{githubUrl:C}=gM(e,t),A=l.useCallback(async I=>{if(!((m==null?void 0:m.path)===I.path&&!m.loading)){h({path:I.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const B=await o(e,"git_diff_file",{workspace:t,path:I.path,staged:I.staged}),T=kM(B);if(T.error||!T.diff){h({path:I.path,diff:"",binary:!1,truncated:!1,loading:!1,error:T.error??"Failed to load diff"});return}h({path:I.path,diff:T.diff.diff,binary:T.diff.binary??!1,truncated:T.diff.truncated??!1,loading:!1,error:null})}catch(B){const T=B instanceof Error?B.message:"Failed to load diff";h({path:I.path,diff:"",binary:!1,truncated:!1,loading:!1,error:T})}}},[e,o,m,t]),O=l.useCallback(I=>{x(""),k(!1),y(null),S(null),g(I)},[]),L=l.useCallback(()=>{g(null),y(null),v(!1)},[]),M=l.useCallback(async()=>{var I,B,T;if(p){v(!0),y(null);try{let F;p==="checkpoint"?F=await o(e,"git_checkpoint",{workspace:t,message:f,includeUntracked:b}):p==="stash"?F=await o(e,"git_stash_push",{workspace:t,message:f,includeUntracked:b}):p==="stash_pop"?F=await o(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&m&&(F=await o(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const q=(F==null?void 0:F.result)??F;if((q==null?void 0:q.success)===!1||q!=null&&q.error){y((q==null?void 0:q.error)??"Action failed"),v(!1);return}p==="checkpoint"?S(`Checkpoint created: ${((B=(I=q==null?void 0:q.checkpoint)==null?void 0:I.commit)==null?void 0:B.slice(0,7))??"done"}`):p==="stash"?S(`Stashed as ${((T=q==null?void 0:q.stash)==null?void 0:T.stashRef)??"stash@{0}"}`):p==="stash_pop"?S("Stash restored"):(S("File reverted"),h(null)),g(null),await u()}catch(F){y(F instanceof Error?F.message:"Action failed")}finally{v(!1)}}},[p,o,e,t,f,b,m,u]),$=!!(a!=null&&a.hasConflicts);l.useEffect(()=>{const I=B=>{B.key==="Escape"&&(p?L():s())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[p,L,s]);const N=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",onClick:I=>{I.target===I.currentTarget&&s()},children:n.jsxs("div",{className:"relative flex h-[80dvh] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-2rem)] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[n.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[n.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??r("git.statusDialog.title")}),n.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),C&&n.jsx("a",{href:`${C}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-3xs text-text-secondary hover:text-accent-primary underline",title:r("git.statusDialog.openOnGithub"),children:"GitHub ↗"})]}),n.jsx("button",{onClick:u,disabled:c,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:r("git.statusDialog.refresh"),children:"↺"}),n.jsx("button",{type:"button",onClick:s,className:"-m-1.5 flex h-11 w-11 shrink-0 items-center justify-center rounded text-text-secondary hover:text-text-primary","aria-label":r("common.close"),children:n.jsx(Bt,{className:"h-4 w-4"})})]}),a&&n.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&n.jsxs("span",{title:a.headMessage??void 0,children:[n.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&n.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&n.jsxs("span",{className:"text-orange-400",children:["↑",r("git.statusDialog.ahead",{count:a.ahead})]}),a.behind>0&&n.jsxs("span",{className:"text-orange-400",children:["↓",r("git.statusDialog.behind",{count:a.behind})]}),a.staged>0&&n.jsx("span",{className:"text-status-online",children:r("git.statusDialog.staged",{count:a.staged})}),a.modified>0&&n.jsx("span",{children:r("git.statusDialog.modified",{count:a.modified})}),a.untracked>0&&n.jsx("span",{children:r("git.statusDialog.untracked",{count:a.untracked})}),a.deleted>0&&n.jsx("span",{className:"text-status-error",children:r("git.statusDialog.deleted",{count:a.deleted})}),a.stashCount>0&&n.jsx("span",{children:r("git.statusDialog.stashed",{count:a.stashCount})}),a.hasConflicts&&n.jsx("span",{className:"font-bold text-status-error",children:r("git.statusDialog.conflicts")}),N===0&&!a.error&&n.jsx("span",{className:"text-status-online",children:r("git.statusDialog.clean")}),i&&i.files.length>0&&n.jsxs("span",{className:"text-text-secondary",children:[r("git.statusDialog.fileCount",{count:i.files.length}),i.totalInsertions>0&&n.jsxs("span",{className:"text-status-online",children:[" +",i.totalInsertions]}),i.totalDeletions>0&&n.jsxs("span",{className:"text-status-error",children:[" -",i.totalDeletions]})]})]}),d&&n.jsx("div",{className:"shrink-0 border-b border-border/50 bg-status-error/10 px-4 py-2 text-xs text-status-error",children:d}),n.jsxs("div",{className:"flex min-h-0 flex-1",children:[n.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[c&&!i&&n.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:r("git.statusDialog.loading")}),i&&n.jsx(AM,{files:i.files,truncated:i.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:A}),!c&&!i&&!d&&n.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:r("git.statusDialog.noDiffData")})]}),n.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?n.jsx(IM,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):n.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:r("git.statusDialog.selectFile")})})]}),w&&n.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-status-online/10 px-4 py-2 text-xs text-status-online flex items-center justify-between",children:[n.jsx("span",{children:w}),n.jsx("button",{onClick:()=>S(null),className:"ml-2 text-status-online hover:text-text-primary",children:"×"})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[n.jsx("button",{onClick:()=>O("checkpoint"),disabled:$,title:r($?"git.statusDialog.resolveBeforeCheckpoint":"git.statusDialog.checkpointHint"),className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:r("git.statusDialog.checkpoint")}),n.jsx("button",{onClick:()=>O("stash"),disabled:$,title:r($?"git.statusDialog.resolveBeforeStash":"git.statusDialog.stashHint"),className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:r("git.statusDialog.stash")}),n.jsx("button",{onClick:()=>O("stash_pop"),disabled:$||!(a!=null&&a.stashCount),title:$?r("git.statusDialog.resolveBeforePop"):a!=null&&a.stashCount?r("git.statusDialog.popHint"):r("git.statusDialog.noStashes"),className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:r("git.statusDialog.popStash")}),n.jsx("button",{onClick:()=>O("checkout_files"),disabled:!m,title:m?r("git.statusDialog.revertFile",{path:m.path}):r("git.statusDialog.selectFileToRevert"),className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:r("git.statusDialog.checkoutSelected")}),i&&i.files.length>0&&n.jsx("button",{onClick:()=>{const I=MM((a==null?void 0:a.branch)??null,i);navigator.clipboard.writeText(I),S(r("git.statusDialog.copied")),setTimeout(()=>S(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:r("git.statusDialog.copySummary")})]}),p&&n.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:n.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[n.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[p==="checkpoint"&&r("git.statusDialog.confirmCheckpoint"),p==="stash"&&r("git.statusDialog.confirmStash"),p==="stash_pop"&&r("git.statusDialog.confirmPop"),p==="checkout_files"&&r("git.statusDialog.confirmRevert",{path:(m==null?void 0:m.path)??r("git.statusDialog.fileFallback")})]}),(p==="checkpoint"||p==="stash")&&n.jsxs(n.Fragment,{children:[n.jsx("input",{type:"text",value:f,onChange:I=>x(I.target.value),maxLength:200,placeholder:r("git.statusDialog.messageRequired"),className:"rounded border border-border bg-surface-secondary px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),n.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:b,onChange:I=>k(I.target.checked)}),r("git.statusDialog.includeUntracked")]})]}),_&&n.jsx("p",{className:"text-xs text-status-error",children:_}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{onClick:L,disabled:j,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:r("common.cancel")}),n.jsx("button",{onClick:M,disabled:j||(p==="checkpoint"||p==="stash")&&!f.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:r(j?"git.statusDialog.working":"common.confirm")})]})]})})]})})})}function RM({isMobile:e,showMobileChatMode:t,visibleConversationCount:s}){const[r,o]=l.useState(!1),[a,i]=l.useState(!1),[c,d]=l.useState(!1),[u,m]=l.useState(!1),[h,p]=l.useState(!1),[g,f]=l.useState("quickstart"),[x,b]=l.useState("workspace"),k=l.useMemo(()=>!t&&!e,[t,e]),j=l.useCallback(C=>{o(C),C&&i(!1)},[]),v=l.useCallback(C=>{i(C),C&&o(!1)},[]),_=l.useCallback(()=>{f(s===0?"quickstart":"shortcuts"),b("workspace"),d(!0),o(!1),i(!1)},[s]),y=l.useCallback(()=>{d(!1)},[]),w=l.useCallback(()=>{m(!0)},[]),S=l.useCallback(()=>{m(!1)},[]);return l.useEffect(()=>{if(!k){p(!1);return}p(!0);const C=window.setTimeout(()=>{p(!1)},1e4);return()=>window.clearTimeout(C)},[k]),{inboxOpen:r,hiddenOpen:a,shortcutHelpOpen:c,newSessionOpen:u,guideNudgeVisible:h,guideTab:g,shortcutSection:x,isDesktopDashboard:k,setGuideTab:f,setShortcutSection:b,handleInboxOpenChange:j,handleHiddenOpenChange:v,handleOpenShortcutHelp:_,closeShortcutHelp:y,openNewSession:w,closeNewSession:S}}function PM(e){switch(e.id){case"triggerPrimaryApprovalAction":case"triggerSecondaryApprovalAction":case"triggerTertiaryApprovalAction":return"approvals";case"splitActiveTabRight":case"splitActiveTabDown":case"focusLeftPane":case"focusRightPane":case"focusUpPane":case"focusDownPane":case"moveActiveTabToLeftPane":case"moveActiveTabToRightPane":case"moveActiveTabToUpPane":case"moveActiveTabToDownPane":return"panes";default:return"workspace"}}function LM(e){return e instanceof Error?e.message:String(e||"")}function EM(e){const t=LM(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function DM({showMobileChatMode:e,isMobile:t,activeConv:s,wsStatus:r,isConnected:o,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:u,mobileChatConversations:m,hiddenConversations:h,ides:p,actionLogs:g,sendDaemonCommand:f,setActionLogs:x,setCliViewModeOverrides:b,isStandalone:k,initialDataLoaded:j,userName:v,requestedMobileTabKey:_,onRequestedMobileTabConsumed:y,requestedMachineId:w,onRequestedMachineConsumed:S,requestedNewSessionLaunch:C,onRequestedNewSessionLaunchConsumed:A,requestedMobileSection:O,onRequestedMobileSectionConsumed:L,containerRef:M,isSplitMode:$,numGroups:N,groupSizes:I,groupedConvs:B,clearedTabs:T,focusedGroup:F,focusGroup:q,moveTabToGroup:Q,splitTabRelative:K,closeGroup:R,handleResizeStart:D,groupActiveTabIds:P,setGroupActiveTab:H,groupTabOrders:W,setGroupTabOrder:U,toggleHiddenTab:ae,visibleConversations:be,requestedDesktopTabKey:V,onRequestedDesktopTabConsumed:we,onDesktopActiveTabChange:ce,onRequestScrollToBottom:de,onHideConversation:ne,onShowHiddenConversation:ee,onShowAllHiddenConversations:ue,scrollToBottomRequest:je,machineEntries:X,layoutProfile:G,onBrowseMachineDirectory:z,onSaveMachineWorkspace:ie,onLaunchMachineIde:Ne,onLaunchMachineProvider:Be,onListMachineMeshes:Le,onLaunchMeshCoordinator:Je,onListMachineSavedSessions:Se,notifications:he,notificationUnreadCount:pe,liveSessionInboxState:Ee,onMarkNotificationRead:Y,onMarkNotificationUnread:me,onDeleteNotification:fe}){const{t:E}=ve(),oe=It.useRef(null),{inboxOpen:Ie,hiddenOpen:Z,shortcutHelpOpen:se,newSessionOpen:ye,guideNudgeVisible:$e,guideTab:Me,shortcutSection:De,isDesktopDashboard:Te,setGuideTab:He,setShortcutSection:tt,handleInboxOpenChange:Ct,handleHiddenOpenChange:J,handleOpenShortcutHelp:re,closeShortcutHelp:le,openNewSession:xe,closeNewSession:Ce}=RM({isMobile:t,showMobileChatMode:e,visibleConversationCount:be.length}),[Re,Ue]=It.useState(null);It.useEffect(()=>{C&&(Ue({machineId:C.machineId,workspaceId:C.workspaceId??null,mode:C.mode||"workspace",meshWorkspacePath:C.meshWorkspacePath??null}),xe(),A==null||A())},[C,xe,A]);const Fe=It.useCallback(()=>{Ue(null),Ce()},[Ce]),{confirm:ke,confirmDialog:Ze}=Fr(),[et,Ve]=It.useState(null),[st,lt]=It.useState(null),Qe=It.useCallback((Oe,rt)=>{Ve({daemonId:Oe,workspace:rt})},[]),ge=It.useCallback(Oe=>{lt(Oe)},[]),_e=It.useCallback(Oe=>{var rt;Qn.flushSync(()=>{ee(Oe)}),(rt=oe.current)==null||rt.restoreHiddenTabToSavedLocation(Oe.tabKey)},[ee]),Pe=It.useCallback(Oe=>{var pt;const rt=m.find(xt=>ho(xt,Oe))||h.find(xt=>ho(xt,Oe));rt&&(h.some(xt=>xt.tabKey===rt.tabKey)&&_e(rt),ce(rt.tabKey),(pt=oe.current)==null||pt.activateConversationTab(rt.tabKey),de(rt.tabKey,"notification-open")),Y(Oe.id),Ct(!1)},[_e,h,m,ce,Y,de]);It.useEffect(()=>B1(Oe=>{var xt;const rt=[{sessionId:Oe.sessionId},...Oe.providerSessionId?[{providerSessionId:Oe.providerSessionId}]:[]];let pt;for(const yt of rt)if(pt=m.find(kt=>ho(kt,yt))||h.find(kt=>ho(kt,yt)),pt)break;if(!pt){ct.showToast(E("sessionNav.chatNotFound"),"info");return}h.some(yt=>yt.tabKey===pt.tabKey)&&_e(pt),lt(null),ce(pt.tabKey),(xt=oe.current)==null||xt.activateConversationTab(pt.tabKey),de(pt.tabKey,"conversation-open")}),[_e,h,m,ce,de,E]);const nt=It.useCallback(async()=>{var rt;await ke({title:E("common.confirmTitle"),description:E("dashboard.hidden.resetPanelsConfirm"),confirmLabel:E("common.confirm")})&&((rt=oe.current)==null||rt.resetAllPanelsToMain(),J(!1))},[ke,J,E]),ze=It.useCallback(async Oe=>{var kt;if(!s)return;const rt=(kt=s.modalButtons)==null?void 0:kt[Oe];if(!rt)return;const pt=vs(s);if(!pt)return;const xt=rt.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),yt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(xt);try{await f(pt,"resolve_action",{button:rt,action:yt?"approve":"reject",buttonIndex:Oe,...ks(s)})}catch(fn){EM(fn)||console.error("[Shortcut approval] Failed:",fn)}},[s,f]),{isMac:ut,actionDefinitions:Ge,actionShortcuts:bt,shortcutListening:Mt,shortcutListeningDraft:Pt,setShortcutListening:mn,setShortcutListeningDraft:nn,saveShortcuts:Jt}=EI({enabled:Te&&!se,onTrigger:Oe=>{var rt,pt,xt,yt,kt,fn,Ye,mt,Zt,Sn,sn,rn,In,jt,en,gn;if(Oe==="openShortcutHelp"){re();return}if(Oe==="openNewSession"){xe();return}if(Oe==="hideCurrentTab"){s&&ne(s);return}if(Oe==="toggleHiddenTabs"){J(!Z);return}if(Oe==="openHistoryForActiveTab"){s&&!vt(s)&&a(s);return}if(Oe==="openRemoteForActiveTab"){s&&!St(s)&&!vt(s)&&i(s);return}if(Oe==="splitActiveTabRight"){(rt=oe.current)==null||rt.splitActiveTabRight();return}if(Oe==="splitActiveTabDown"){(pt=oe.current)==null||pt.splitActiveTabDown();return}if(Oe==="floatActiveTab"){(xt=oe.current)==null||xt.floatActiveTab();return}if(Oe==="popoutActiveTab"){(yt=oe.current)==null||yt.popoutActiveTab();return}if(Oe==="dockActiveTab"){(kt=oe.current)==null||kt.dockActiveTab();return}if(Oe==="focusLeftPane"){(fn=oe.current)==null||fn.focusLeftPane();return}if(Oe==="focusRightPane"){(Ye=oe.current)==null||Ye.focusRightPane();return}if(Oe==="focusUpPane"){(mt=oe.current)==null||mt.focusUpPane();return}if(Oe==="focusDownPane"){(Zt=oe.current)==null||Zt.focusDownPane();return}if(Oe==="moveActiveTabToLeftPane"){(Sn=oe.current)==null||Sn.moveActiveTabToLeftPane();return}if(Oe==="moveActiveTabToRightPane"){(sn=oe.current)==null||sn.moveActiveTabToRightPane();return}if(Oe==="moveActiveTabToUpPane"){(rn=oe.current)==null||rn.moveActiveTabToUpPane();return}if(Oe==="moveActiveTabToDownPane"){(In=oe.current)==null||In.moveActiveTabToDownPane();return}if(Oe==="triggerPrimaryApprovalAction"){ze(0);return}if(Oe==="triggerSecondaryApprovalAction"){ze(1);return}if(Oe==="triggerTertiaryApprovalAction"){ze(2);return}if(Oe==="setActiveTabShortcut"){(jt=oe.current)==null||jt.setShortcutForActiveTab();return}if(Oe==="selectPreviousGroupTab"){(en=oe.current)==null||en.activatePreviousTabInGroup();return}if(Oe==="selectNextGroupTab"){(gn=oe.current)==null||gn.activateNextTabInGroup();return}!s||!St(s)||vt(s)||Oe==="toggleCliView"&&u(d==="chat"?"terminal":"chat")}}),Dt=It.useCallback(()=>{le(),mn(null),nn([])},[le,mn,nn]),hn=It.useMemo(()=>De==="all"?Ge:Ge.filter(Oe=>PM(Oe)===De),[Ge,De]),Wn=It.useMemo(()=>[wt("triggerPrimaryApprovalAction",ut),wt("triggerSecondaryApprovalAction",ut),wt("triggerTertiaryApprovalAction",ut)].filter(Boolean).join(" / "),[ut]),Tt=ut?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",Vt=It.useCallback(()=>{const Oe=Object.fromEntries(Ge.map(rt=>[rt.id,""]));Jt(Oe)},[Ge,Jt]),pn=It.useCallback(async()=>{if(!await ke({title:E("common.confirmTitle"),description:E("dashboard.guide.shortcuts.resetConfirm"),confirmLabel:E("common.confirm")}))return;const rt=Object.fromEntries(Ge.map(pt=>[pt.id,pt.defaultShortcut]));Jt(rt)},[Ge,ke,Jt,E]);return It.useEffect(()=>{const Oe=rt=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?rt.metaKey&&rt.key.toLowerCase()==="w":rt.ctrlKey&&rt.key.toLowerCase()==="w")&&(rt.preventDefault(),s&&ne&&ne(s))};return window.addEventListener("keydown",Oe),()=>window.removeEventListener("keydown",Oe)},[s,ne]),It.useEffect(()=>{if(!se||Mt)return;const Oe=rt=>{rt.key==="Escape"&&(rt.preventDefault(),Dt())};return window.addEventListener("keydown",Oe,!0),()=>window.removeEventListener("keydown",Oe,!0)},[Dt,se,Mt]),n.jsxs(n.Fragment,{children:[!e&&n.jsx(uA,{activeConv:s,wsStatus:r,isConnected:o,conversations:be,hiddenConversations:h,onOpenHistory:a,onHideConversation:ne,onShowConversation:_e,onShowAllHidden:ue,onResetPanelsToMain:nt,notifications:he,notificationUnreadCount:pe,onOpenNotification:Pe,onMarkNotificationRead:Y,onMarkNotificationUnread:me,onDeleteNotification:fe,inboxOpen:Ie,onInboxOpenChange:Ct,hiddenOpen:Z,onHiddenOpenChange:J,onOpenNewSession:t?void 0:xe,onOpenDashboardGuide:re,guideNudgeVisible:$e,actionShortcuts:bt,onOpenRemote:()=>{!s||St(s)||vt(s)||i(s)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:u,onOpenGitDialog:Qe,onOpenMeshGraph:ge}),e?n.jsx(kI,{conversations:m,hiddenConversations:h,ides:p,actionLogs:g,sendDaemonCommand:f,setActionLogs:x,setCliViewModeOverrides:b,isStandalone:k,userName:v,requestedActiveTabKey:_,onRequestedActiveTabConsumed:y,requestedMachineId:w,onRequestedMachineConsumed:S,requestedMobileSection:O,onRequestedMobileSectionConsumed:L,onOpenHistory:a,onOpenRemote:i,onStopCli:c,wsStatus:r,isConnected:o,initialDataLoaded:j,onShowAllHiddenConversations:ue,onHideConversation:ne,onShowHiddenConversation:_e,onOpenMeshGraph:ge,onOpenNewSession:xe,liveSessionInboxState:Ee}):t?n.jsx(MI,{containerRef:M,isSplitMode:$,numGroups:N,groupSizes:I,groupedConvs:B,clearedTabs:T,ides:p,actionLogs:g,sendDaemonCommand:f,setActionLogs:x,isStandalone:k,hasRegisteredMachines:X.length>0,initialDataLoaded:j,userName:v,focusedGroup:F,focusGroup:q,moveTabToGroup:Q,splitTabRelative:K,closeGroup:R,handleResizeStart:D,groupActiveTabIds:P,setGroupActiveTab:H,groupTabOrders:W,setGroupTabOrder:U,toggleHiddenTab:ae,onOpenNewSession:xe,allowTabShortcuts:!1,liveSessionInboxState:Ee}):n.jsx(QI,{visibleConversations:be,clearedTabs:T,ides:p,actionLogs:g,sendDaemonCommand:f,setActionLogs:x,isStandalone:k,hasRegisteredMachines:X.length>0,initialDataLoaded:j,userName:v,toggleHiddenTab:ae,actionShortcuts:bt,registerActionHandlers:Oe=>{oe.current=Oe},onActiveTabChange:ce,requestedActiveTabKey:V,onRequestedActiveTabConsumed:we,onRequestScrollToBottom:de,scrollToBottomRequest:je,onOpenNewSession:xe,liveSessionInboxState:Ee,layoutProfile:G}),ye&&n.jsx(fM,{machines:X,ides:p,initialMachineId:(Re==null?void 0:Re.machineId)||null,initialWorkspaceId:(Re==null?void 0:Re.workspaceId)||null,initialLaunchMode:(Re==null?void 0:Re.mode)||null,initialMeshWorkspacePath:(Re==null?void 0:Re.meshWorkspacePath)||null,onClose:Fe,onBrowseDirectory:z,onSaveWorkspace:ie,onLaunchIde:Ne,onLaunchProvider:Be,onListMeshes:Le,onLaunchMeshCoordinator:Je,onListSavedSessions:Se},Re?`${Re.machineId}:${Re.workspaceId||""}:${Re.mode||""}:${Re.meshWorkspacePath||""}`:"default"),st&&n.jsx(Kd,{activeConv:st,sendDaemonCommand:f,onClose:()=>lt(null)}),Ze,et&&n.jsx(ux,{daemonId:et.daemonId,workspace:et.workspace,onClose:()=>Ve(null)}),se&&n.jsxs(Pr,{chrome:!1,onClose:Dt,closeOnEsc:!1,ariaLabel:E("dashboard.guide.title"),overlayClassName:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50 backdrop-blur-[2px]",surfaceClassName:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",children:[n.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-bold text-text-primary",children:E("dashboard.guide.title")}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:E("dashboard.guide.subtitle")})]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Dt,"aria-label":E("dashboard.guide.close"),children:n.jsx(Bt,{size:14})})]}),n.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:E("dashboard.guide.tabs.overview")},{id:"quickstart",label:E("dashboard.guide.tabs.quickstart")},{id:"shortcuts",label:E("dashboard.guide.tabs.shortcuts")}].map(Oe=>n.jsx("button",{type:"button",className:`btn btn-sm ${Me===Oe.id?"btn-primary":"btn-secondary"}`,onClick:()=>He(Oe.id),children:Oe.label},Oe.id))}),Me==="overview"&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E("dashboard.guide.overview.whatLivesWhere.title")}),n.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.whatLivesWhere.tabsLabel")})," ",E("dashboard.guide.overview.whatLivesWhere.tabsText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.whatLivesWhere.hiddenLabel")})," ",E("dashboard.guide.overview.whatLivesWhere.hiddenText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.whatLivesWhere.inboxLabel")})," ",E("dashboard.guide.overview.whatLivesWhere.inboxText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.whatLivesWhere.cliToggleLabel")})," ",E("dashboard.guide.overview.whatLivesWhere.cliToggleText")]})]})]}),n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.title")}),n.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.reviewLabel")})," ",E("dashboard.guide.overview.usefulFlows.reviewText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.clutterLabel")})," ",E("dashboard.guide.overview.usefulFlows.clutterText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.splitLabel")})," ",E("dashboard.guide.overview.usefulFlows.splitText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.detachedLabel")})," ",E("dashboard.guide.overview.usefulFlows.detachedText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.dockingLabel")})," ",E("dashboard.guide.overview.usefulFlows.dockingText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.perTabLabel")})," ",E("dashboard.guide.overview.usefulFlows.perTabText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.approvalLabel")})," ",E("dashboard.guide.overview.usefulFlows.approvalText",{keys:Wn})]})]})]})]}),Me==="quickstart"&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E("dashboard.guide.quickstart.desktop.title")}),n.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," ",E("dashboard.guide.quickstart.desktop.step1")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," ",E("dashboard.guide.quickstart.desktop.step2")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," ",E("dashboard.guide.quickstart.desktop.step3")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," ",E("dashboard.guide.quickstart.desktop.step4")]})]})]}),n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E("dashboard.guide.quickstart.mobile.title")}),n.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," ",E("dashboard.guide.quickstart.mobile.step1")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," ",E("dashboard.guide.quickstart.mobile.step2")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," ",E("dashboard.guide.quickstart.mobile.step3")]})]})]})]}),Me==="shortcuts"&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[n.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:E("dashboard.guide.shortcuts.sections.all")},{id:"workspace",label:E("dashboard.guide.shortcuts.sections.workspace")},{id:"panes",label:E("dashboard.guide.shortcuts.sections.panes")},{id:"approvals",label:E("dashboard.guide.shortcuts.sections.approvals")}].map(Oe=>n.jsx("button",{type:"button",className:`btn btn-sm ${De===Oe.id?"btn-primary":"btn-secondary"}`,onClick:()=>tt(Oe.id),children:Oe.label},Oe.id))}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Vt,children:E("dashboard.guide.shortcuts.disableAll")}),n.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:pn,children:E("dashboard.guide.shortcuts.resetToDefaults")})]})]}),n.jsx("div",{className:"space-y-2",children:hn.map(Oe=>n.jsx("div",{className:`rounded-xl border px-4 py-3 ${Mt===Oe.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E(`dashboard.shortcutDefs.${Oe.id}.label`,Oe.label)}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:E(`dashboard.shortcutDefs.${Oe.id}.description`,Oe.description)}),n.jsxs("div",{className:"text-2xs text-text-muted mt-2",children:[E("dashboard.guide.shortcuts.default")," ",n.jsx("span",{className:"font-mono",children:Oe.defaultShortcut})]})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[n.jsx("span",{className:"text-2xs font-mono px-2 py-1 rounded bg-surface-secondary border border-border-subtle min-w-[72px] text-center",children:Mt===Oe.id?Pt.length>0?`${Pt.join(" ")} ...`:E("dashboard.guide.shortcuts.listening"):bt[Oe.id]||E("dashboard.guide.shortcuts.off")}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{mn(Oe.id),nn([])},children:Mt===Oe.id?E("dashboard.guide.shortcuts.setListening"):E("dashboard.guide.shortcuts.set")}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const rt={...bt};rt[Oe.id]="",Jt(rt)},children:E("dashboard.guide.shortcuts.disable")})]})]})},Oe.id))}),n.jsx("div",{className:"text-2xs text-text-muted mt-4",children:E("dashboard.guide.shortcuts.footer",{keys:Tt})})]})]})]})}const OM=[{icon:yi,key:"welcome",visual:nf},{icon:Jn,key:"realtimeChat",visual:Tw},{icon:md,key:"watchAndSteer",visual:sf},{icon:cc,key:"orchestrate",visual:cc}],$M={icon:yi,key:"getStartedCloud",code:"curl -fsSL https://adhf.dev/install | sh"},FM={icon:yi,key:"allSetStandalone",visual:vi};function HM({onClose:e,standalone:t=!1}){const[s,r]=l.useState(0),{t:o}=ve("common"),a=[...OM,t?FM:$M],i=a[s],c=s===a.length-1;return l.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]),n.jsx(es,{children:n.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:"var(--z-modal)",background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",padding:"calc(16px + env(safe-area-inset-top, 0px)) 16px calc(16px + env(safe-area-inset-bottom, 0px))",animation:"fadeIn 0.3s ease-out"},onClick:d=>{d.stopPropagation()},children:[n.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",maxHeight:"calc(100dvh - env(safe-area-inset-top, 0px) - env(safe-area-inset-bottom, 0px) - 32px)",overflowY:"auto",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[n.jsx("button",{onClick:e,"aria-label":o("app.onboardingTour.closeAria"),className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",style:{minWidth:44,minHeight:44,margin:-6,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:n.jsx(Bt,{size:20})}),n.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:a.map((d,u)=>n.jsx("div",{style:{width:u===s?24:8,height:8,borderRadius:4,background:u===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},u))}),n.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:(()=>{const d=i.visual||i.icon;return n.jsx(d,{size:44})})()}),n.jsxs("div",{style:{textAlign:"center"},children:[n.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[n.jsx(i.icon,{size:18})," ",o(`app.onboardingTour.${i.key}.title`)]}),n.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:o(`app.onboardingTour.${i.key}.desc`)}),i.code&&n.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[n.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),i.code]}),c&&n.jsxs("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:[o("app.onboardingTour.learnMore")," →"]})]}),n.jsx("div",{className:"flex justify-end items-center mt-6",children:n.jsx("button",{onClick:()=>c?e():r(d=>d+1),className:"btn btn-primary",children:c?`${o("app.onboardingTour.getStarted")} →`:`${o("app.onboardingTour.next")} →`})})]}),n.jsx("style",{children:`
|
|
72
|
+
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
73
|
+
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
74
|
+
`})]})})}function BM({hasExtensions:e,ideName:t,activeChatTab:s,extensionTabs:r,onSelectTab:o}){return e?n.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[n.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-2xs font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${s==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o("native"),children:t}),r.map(a=>{const i=s===a.tabKey,c=a.status==="waiting_approval",d=er(a);return n.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-2xs font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${i?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o(a.tabKey),children:[n.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),a.title,c&&n.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-3xs font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},a.tabKey)})]}):null}function WM({ideData:e,allIdes:t,connectionStates:s,ideName:r,preferredTabKey:o}){const[a,i]=l.useState(()=>o||"native"),c=l.useMemo(()=>cb(t),[t]),d=l.useMemo(()=>e?Gd(e,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}):[],[e,c,s]),u=l.useMemo(()=>d.find(x=>x.streamSource==="native"),[d]),m=l.useMemo(()=>d.filter(x=>x.streamSource==="agent-stream"),[d]),h=l.useMemo(()=>e?$n(d,e.id):null,[d,e]);l.useEffect(()=>{o&&i(o)},[o]),l.useEffect(()=>{if(o||!h)return;const x=h.streamSource==="native"?"native":h.tabKey;!x||a===x||a==="native"&&i(x)},[a,h,o]),l.useEffect(()=>{var x;a!=="native"&&(m.some(b=>b.tabKey===a)||i(((x=m[0])==null?void 0:x.tabKey)||"native"))},[a,m]),l.useEffect(()=>{a==="native"&&(u||m[0]&&i(m[0].tabKey))},[a,u,m]);const p=l.useMemo(()=>a==="native"&&u?u:m.find(x=>x.tabKey===a)||h||u||m[0],[a,u,h,m]),g=l.useMemo(()=>m.map(x=>({tabKey:x.tabKey,title:Fg(x)||r,status:x.status})),[m,r]),f=l.useCallback(x=>{if(x)return d.find(b=>ho(b,{sessionId:x,routeId:x,tabKey:x,providerSessionId:x}))},[d]);return{activeChatTab:a,setActiveChatTab:i,activeConv:p,conversations:d,extensionTabs:g,hasExtensions:g.length>0,resolveConversationByTarget:f}}function UM({activeConv:e,ideEntry:t,ides:s,connectionStates:r,actionLogs:o,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:d,onOpenHistory:u,onConversationChange:m,onClose:h,onRetryConnection:p}){const{t:g}=ve("common"),[f,x]=l.useState("split"),[b,k]=l.useState(()=>Ss(e)?"native":e.tabKey),j=l.useRef(null),v=l.useMemo(()=>t||s.find(D=>D.id===e.routeId),[e.routeId,t,s]),_=l.useMemo(()=>Kt((v==null?void 0:v.type)||""),[v==null?void 0:v.type]),{conversations:y,extensionTabs:w,hasExtensions:S}=WM({ideData:v,allIdes:s,connectionStates:r,ideName:_||"IDE",preferredTabKey:Ss(e)?void 0:e.tabKey}),C=l.useMemo(()=>v?$n(y,v.id):null,[v,y]);l.useEffect(()=>{const D=j.current,P={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(j.current=P,!(D&&D.routeId===P.routeId&&D.tabKey===P.tabKey&&D.streamSource===P.streamSource)){if(Ss(e)){k("native");return}k(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(b==="native"){if(y.some(D=>D.streamSource==="native"))return;(C==null?void 0:C.streamSource)==="agent-stream"&&k(C.tabKey);return}if(!y.some(D=>D.tabKey===b)){if((C==null?void 0:C.streamSource)==="agent-stream"){k(C.tabKey);return}k("native")}},[y,b,C]);const A=l.useMemo(()=>b==="native"?y.find(D=>D.streamSource==="native")||e:y.find(D=>D.tabKey===b)||e,[e,y,b]),O=jb(A),L=l.useMemo(()=>O.status||O.modalMessage||O.modalButtons?{...A,...O.status?{status:O.status}:{},...O.modalMessage!==void 0?{modalMessage:O.modalMessage}:{},...O.modalButtons!==void 0?{modalButtons:O.modalButtons}:{}}:A,[A,O]),M=Cs(L),$=Li({sendDaemonCommand:a,activeConv:L,setActionLogs:i,isStandalone:c}),{connScreenshot:N,screenshotUsage:I,handleRemoteAction:B}=tx({doId:M,targetSessionId:ig(L),connState:L.connectionState||"new",viewMode:f}),T=l.useMemo(()=>o.filter(D=>D.routeId===L.tabKey),[o,L.tabKey]),F=L.tabKey,q=l.useCallback(D=>{i(P=>[...P,{routeId:F,text:D,timestamp:Date.now()}])},[F,i]),Q=v==null?void 0:v.machineId,K=l.useMemo(()=>{if(!(!p||!Q))return()=>p(Q)},[p,Q]);l.useEffect(()=>{m==null||m(L)},[L,m]),l.useEffect(()=>{const D=P=>{P.key==="Escape"&&h()};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[h]);const R=l.useCallback(D=>{D.stopPropagation()},[]);return n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center p-0 md:p-3 bg-black/60 backdrop-blur-md",onClick:h,children:n.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:R,children:[n.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[n.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:n.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-lg md:text-xl tracking-tight text-text-primary",children:[n.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:n.jsx(Xn,{size:16})}),n.jsx("span",{className:"truncate",children:Td(A)||g("dashboard.remoteDialog.remoteFallback")})]})}),n.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:g("common.close")})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[n.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(D=>{const P=f===D;return n.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${P?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>x(D),title:g(D==="split"?"dashboard.remoteDialog.splitView":"dashboard.remoteDialog.remoteOnly"),children:D==="split"?n.jsx(gw,{size:15}):n.jsx(Xn,{size:15})},D)})}),n.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),n.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>u(A),title:g("dashboard.remoteDialog.history"),children:[n.jsx(Vp,{size:14,className:"md:mr-1.5"}),n.jsx("span",{className:"hidden md:inline",children:g("dashboard.remoteDialog.history")})]}),n.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:g("common.close")})]})]}),n.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[f!=="remote"&&n.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[n.jsx(BM,{hasExtensions:S,ideName:_||"IDE",activeChatTab:b,extensionTabs:w,onSelectTab:k}),n.jsx(Tf,{activeConv:L,onModalButton:$.handleModalButton}),n.jsx(Rg,{activeConv:L,ideEntry:v,showMetaChips:!1,handleSendChat:$.handleSendChat,handleSendNowQueued:$.handleSendNowQueued,handleCancelQueued:$.handleCancelQueued,isSendingChat:$.isSendingChat,sendFeedbackMessage:$.sendFeedbackMessage,pendingLocalMessage:$.pendingLocalMessage,pendingLocalMessages:$.pendingLocalMessages,retireEchoedPendingMessages:$.retireEchoedPendingMessages,handleFocusAgent:$.handleFocusAgent,isFocusingAgent:$.isFocusingAgent,actionLogs:T,userName:d})]}),n.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-1 md:order-2":""}`,children:n.jsx(bf,{addLog:q,connState:L.connectionState||"new",connScreenshot:N,screenshotUsage:I,transportType:L.transport,onAction:B,onRetry:K})})]})]})})})}function KM({activeConv:e,canSaveAndStop:t=!1,onCancel:s,onStopNow:r,onSaveAndStop:o}){const{t:a}=ve(),i=B_(e);return n.jsx(es,{children:n.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[n.jsx("div",{onClick:s,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),n.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[n.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[n.jsx("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:a("cliStop.title",{agent:i})}),n.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a(t?"cliStop.gracefulDescription":"cliStop.forceOnlyDescription")})]}),n.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&n.jsx("button",{onClick:o,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("cliStop.stop")}),n.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:a("cliStop.forceStop")}),n.jsx("button",{onClick:s,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})})}function qM({historyModal:e,remoteDialog:t,cliStopDialog:s,connectionBanner:r,toastOverlay:o,onboarding:a,interactivePrompt:i,suppressInteractivePrompt:c=!1}){var d;return n.jsxs(n.Fragment,{children:[!r.suppress&&n.jsx(l1,{wsStatus:r.wsStatus,showReconnected:r.showReconnected,loginUrl:r.loginUrl,onReconnect:r.onReconnect}),e.open&&e.targetConv&&n.jsx(vA,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&n.jsx(UM,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose,onRetryConnection:t.onRetryConnection}),s.open&&s.targetConv&&(St(s.targetConv)||vt(s.targetConv))&&n.jsx(KM,{activeConv:s.targetConv,canSaveAndStop:St(s.targetConv)&&!vt(s.targetConv)&&!!((d=s.targetConv.resume)!=null&&d.supported),onCancel:s.onCancel,onStopNow:s.onStopNow,onSaveAndStop:s.onSaveAndStop}),n.jsx(ib,{toasts:o.toasts,onDismiss:o.onDismiss,onClickToast:o.onClick}),!c&&n.jsx(wd,{promptSession:(i==null?void 0:i.promptSession)??null,isSubmitting:(i==null?void 0:i.isSubmitting)??!1,error:(i==null?void 0:i.responseError)??null,onSubmit:(i==null?void 0:i.submit)??(async()=>{}),onCancel:(i==null?void 0:i.cancel)??(()=>{})}),a.open&&n.jsx(HM,{onClose:a.onClose,standalone:a.standalone})]})}function zM({daemons:e,targetVersion:t,required:s=!1,upgradingDaemons:r,onUpgrade:o,onDismiss:a}){const{t:i}=ve("common");return e.length===0?null:n.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:s?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:s?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[n.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:s?"var(--status-danger)":"var(--status-warning)"},children:n.jsx($r,{size:14})}),n.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[n.jsxs("span",{children:[i(s?"machine.daemonUpdate.requiredTitle":"dashboard.versionBanner.updateAvailable"),t?n.jsxs(n.Fragment,{children:[": ",n.jsxs("strong",{children:["v",t]})]}):null]}),e.map(c=>{const d=Tn(c,{fallbackId:c.id}),u=r[c.id],m=c.version||c.daemonVersion||i("dashboard.versionBanner.unknownVersion"),h=c.versionUpdateRequired===!0,p=Pb(c,{targetVersion:t,required:h},i);return n.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:h?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${h?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[n.jsx("span",{className:"font-medium text-text-primary",children:d}),n.jsxs("span",{className:"text-3xs text-text-muted",children:["v",m]}),h&&n.jsx("span",{className:"text-3xs",style:{color:"var(--status-danger)"},children:i("dashboard.versionBanner.required")}),u==="upgrading"?n.jsx("span",{className:"text-3xs animate-pulse",style:{color:h?"var(--status-danger)":"var(--status-warning)"},children:i("dashboard.versionBanner.upgrading")}):u==="done"?n.jsxs("span",{className:"text-3xs text-green-400",children:["✓ ",i("dashboard.versionBanner.restarting")]}):u==="error"?n.jsx("button",{className:"text-3xs text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>o(c.id),children:i("dashboard.versionBanner.retry")}):n.jsx("button",{className:"text-3xs font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:h?"var(--status-danger)":"var(--status-warning)",background:h?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${h?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(c.id),children:p})]},c.id)})]}),!s&&n.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:a,title:i("toast.dismiss"),children:n.jsx(Bt,{size:16})})]})}function GM(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function VM(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function YM(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>VM(t)).map(t=>t.id)}}function QM({suppressConnectionBanner:e=!1}={}){var Vo,Yo,qr,Qo,Jo;const{sendCommand:t}=_t(),s=Br(),r=kb(),o=fi(),a=rr(),[i,c]=wp(),d=i.get("activeTab"),u=((Vo=o.state)==null?void 0:Vo.openRemoteForTabKey)||null,m=((Yo=o.state)==null?void 0:Yo.openMachineId)||null,h=((qr=o.state)==null?void 0:qr.openNewSession)||null,p=((Qo=o.state)==null?void 0:Qo.mobileSection)||null,g=Ad(),f=g.ides||[],x=g.initialLoaded??!0,{updateRouteChats:b,setToasts:k}=g,{hydrateInteractivePrompt:j}=Ar(),[v,_]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=g.toasts||[],w=g.wsStatus||"connected",S=g.isConnected??!0,C=g.connectionStates||{},A=g.showReconnected||!1,{layoutProfile:O,groupAssignments:L,updateGroupAssignments:M,focusedGroup:$,updateFocusedGroup:N,focusGroup:I,groupActiveTabIds:B,updateGroupActiveTabIds:T,setGroupActiveTab:F,groupTabOrders:q,updateGroupTabOrders:Q,setGroupTabOrder:K,groupSizes:R,updateGroupSizes:D,isMobile:P,hasHydratedStoredLayout:H,hydrateStoredLayout:W,focusConversationTab:U}=h2(),[ae,be]=l.useState(()=>Jd());l.useEffect(()=>CT(be),[]);const V=l.useMemo(()=>GM({isMobile:P,mobileViewMode:ae}),[P,ae]),[we,ce]=l.useState([]),[de,ne]=l.useState({}),[ee,ue]=l.useState({});Oo("Dashboard",{ideCount:f.length,toastCount:y.length,focusedGroup:$,groupCount:Object.keys(L).length,actionLogCount:we.length});const je=l.useMemo(()=>f.filter(ht=>ht.type==="adhdev-daemon").sort(za),[f]),G=!!je[0];l.useEffect(()=>{const{metadataDaemonIds:ht,runtimeDaemonIds:Yt}=YM(je);for(const us of ht)s(us,{minFreshMs:3e4}).catch(()=>{});for(const us of Yt)r(us,{minFreshMs:3e4}).catch(()=>{})},[s,r,je]);const z=l.useMemo(()=>FT(f,de),[f,de]),{conversations:ie,visibleConversations:Ne,visibleTabKeys:Be,resolveConversationBySessionId:Le,resolveConversationByTarget:Je}=XT({ides:z,connectionStates:C,clearedTabs:ee}),Se=l.useMemo(()=>new Map(ie.map(ht=>[ht.tabKey,ht])),[ie]);DC(Ne,V);const he=l.useMemo(()=>_f(f),[f]),pe=qb(he,t,l.useCallback(ht=>yr(k,ht),[k])),{notifications:Ee,unreadCount:Y}=I2({conversations:ie,liveSessionInboxState:he}),{handleMarkDashboardNotificationRead:me,handleMarkDashboardNotificationUnread:fe,handleDeleteDashboardNotification:E}=M2({notifications:Ee,sendDaemonCommand:t}),{containerRef:oe,normalizedGroupAssignments:Ie,numGroups:Z,isSplitMode:se,groupedConvs:ye,moveTabToGroup:$e,closeGroup:Me,handleResizeStart:De,splitTabRelative:Te}=v2({groupAssignments:L,updateGroupAssignments:M,updateFocusedGroup:N,updateGroupActiveTabIds:T,updateGroupTabOrders:Q,groupSizes:R,updateGroupSizes:D,isMobile:P,visibleConversations:Ne,visibleTabKeys:Be}),{activeConv:He,openDesktopConversation:tt,requestScrollToBottom:Ct,scrollToBottomRequest:J,setDesktopActiveTab:re}=q2({isMobile:P,conversations:ie,visibleConversations:Ne,groupActiveTabIds:B,focusedGroup:$,groupedConvs:ye,setSearchParams:c});V2({activeConv:He,isMobile:P,liveSessionInboxState:he,sendDaemonCommand:t});const{requestedDesktopTabKey:le,requestedMobileTabKey:xe,consumeRequestedActiveTab:Ce}=ZT({isMobile:P,urlActiveTab:d,resolveConversationBySessionId:Le,setSearchParams:c}),{remoteDialogConv:Re,remoteDialogIdeEntry:Ue,remoteDialogActiveConv:Fe,setRemoteDialogActiveConv:ke,openRemoteDialog:Ze,closeRemoteDialog:et,cliStopDialogOpen:Ve,cliStopTargetConv:st,requestCliStop:lt,cancelCliStop:Qe,confirmCliStop:ge}=J2({isMobile:P,location:o,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:le,conversations:ie,ides:f,resolveConversationByTarget:Je,activeConv:He,sendDaemonCommand:t}),{historyModalOpen:_e,openHistoryModal:Pe,closeHistoryModal:nt,historyTargetConv:ze,isSavedSessionHistoryTarget:ut,isHistoryCreatingChat:Ge,isHistoryRefreshingHistory:bt,handleHistorySwitchSession:Mt,handleHistoryNewChat:Pt,handleHistoryRefresh:mn,savedHistorySessions:nn,savedHistoryFilters:Jt,setSavedHistoryFilters:Dt,missingWorkspaceResumePath:hn,isSavedHistoryLoading:Wn,resumingSavedHistorySessionId:Tt,handleRefreshSavedHistory:Vt,handleResumeSavedHistorySession:pn}=Y2({activeConv:He,remoteDialogConv:Re,remoteDialogActiveConv:Fe,ides:f,sendDaemonCommand:t,updateRouteChats:b,setToasts:k,setClearedTabs:ue,setSearchParams:c}),Oe=l.useMemo(()=>Ne,[Ne]),rt=P&&ae==="chat",pt=l.useMemo(()=>ie.filter(ht=>qS(Ns(ht,he))),[ie,he]),xt=l.useCallback(ht=>{const Yt=new URLSearchParams(i);Yt.set("activeTab",ht),c(Yt,{replace:!0})},[i,c]),{trackPendingLaunch:yt}=F2({ides:f,conversations:ie,onOpenSession:xt}),{handleBrowseMachineDirectory:kt,handleSaveMachineWorkspace:fn,handleLaunchMachineIde:Ye,handleLaunchMachineProvider:mt,handleListMachineMeshes:Zt,handleLaunchMeshCoordinator:Sn,handleListMachineSavedSessions:sn,setActiveCliViewMode:rn}=W2({sendDaemonCommand:t,trackPendingLaunch:yt,onOpenSession:xt,activeConv:He,ides:f,setCliViewModeOverrides:ne});BT({visibleConversations:Ne,clearedTabs:ee,setClearedTabs:ue,setActionLogs:ce,isConversationMuted:pe.isMuted}),e2({ides:f,sendDaemonCommand:t,setToasts:k,resolveConversationByTarget:Je,hydrateInteractivePrompt:j});const In=_i((He==null?void 0:He.sessionId)??(He==null?void 0:He.routeId)??null),{isRefreshingHistory:jt,handleRefreshHistory:en}=Rb({sendDaemonCommand:t,activeConv:He,chats:(Jo=f.find(ht=>ht.id===(He==null?void 0:He.routeId)))==null?void 0:Jo.chats,updateRouteChats:b,setToasts:k,setClearedTabs:ue});f2({urlActiveTab:P&&!rt?d:null,conversations:ie,resolveConversationBySessionId:Le,normalizedGroupAssignments:Ie,hasHydratedStoredLayout:P&&!rt?H:!0,hydrateStoredLayout:P&&!rt?W:()=>{},focusConversationTab:U,setSearchParams:c,historyModalOpen:_e,activeConv:He,isRefreshingHistory:jt,ides:f,handleRefreshHistory:en});const gn=l.useMemo(()=>!He||!St(He)||vt(He)?null:Hr(He),[He]),{versionMismatchDaemons:Wt,hasRequiredVersionDaemons:Rs,targetVersion:kn,versionBannerDismissed:Ko,setVersionBannerDismissed:qo,upgradingDaemons:Ji,handleBannerUpgrade:Xi}=k2({ides:f,sendDaemonCommand:t}),zo=l.useCallback(ht=>{pe.setHidden(ht,!1),tt(ht)},[tt,pe]),Go=l.useCallback(()=>{for(const ht of pt)pe.setHidden(ht,!1)},[pt,pe]),Kr=l.useCallback(ht=>{pe.setHidden(ht,!0)},[pe]),Zi=l.useCallback(ht=>{pe.toggleHidden(ht)},[pe]);return n.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!Ko||Rs)&&n.jsx(zM,{daemons:Wt,targetVersion:kn,required:Rs,upgradingDaemons:Ji,onUpgrade:Xi,onDismiss:()=>qo(!0)}),n.jsx(DM,{showMobileChatMode:rt,isMobile:P,activeConv:He,wsStatus:w,isConnected:S,onOpenHistory:ht=>{ht&&ke(ht),Pe()},onOpenRemote:Ze,onStopCli:lt,activeCliViewMode:gn,onSetActiveCliViewMode:rn,mobileChatConversations:Oe,ides:f,actionLogs:we,sendDaemonCommand:t,setActionLogs:ce,setCliViewModeOverrides:ne,isStandalone:G,initialDataLoaded:x,userName:g.userName,requestedMobileTabKey:xe,onRequestedMobileTabConsumed:Ce,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(o.pathname+o.search,{replace:!0,state:null})},requestedNewSessionLaunch:h,onRequestedNewSessionLaunchConsumed:()=>{a(o.pathname+o.search,{replace:!0,state:null})},requestedMobileSection:p,onRequestedMobileSectionConsumed:()=>{a(o.pathname+o.search,{replace:!0,state:null})},containerRef:oe,isSplitMode:se,numGroups:Z,groupSizes:R,groupedConvs:ye,clearedTabs:ee,focusedGroup:$,focusGroup:I,moveTabToGroup:$e,splitTabRelative:Te,closeGroup:Me,handleResizeStart:De,groupActiveTabIds:B,setGroupActiveTab:F,groupTabOrders:q,setGroupTabOrder:K,toggleHiddenTab:ht=>{const Yt=Se.get(ht);Yt&&Zi(Yt)},visibleConversations:Ne,hiddenConversations:pt,requestedDesktopTabKey:le,onRequestedDesktopTabConsumed:Ce,onDesktopActiveTabChange:re,onRequestScrollToBottom:Ct,onHideConversation:Kr,onShowHiddenConversation:zo,onShowAllHiddenConversations:Go,scrollToBottomRequest:J,machineEntries:je,layoutProfile:O,onBrowseMachineDirectory:kt,onSaveMachineWorkspace:fn,onLaunchMachineIde:Ye,onLaunchMachineProvider:mt,onListMachineMeshes:Zt,onLaunchMeshCoordinator:Sn,onListMachineSavedSessions:sn,notifications:Ee,notificationUnreadCount:Y,liveSessionInboxState:he,onMarkNotificationRead:me,onMarkNotificationUnread:fe,onDeleteNotification:E}),n.jsx("style",{children:`
|
|
75
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
76
|
+
`}),n.jsx(qM,{historyModal:{open:_e,targetConv:ze,ides:f,isCreatingChat:Ge,isRefreshingHistory:ut?!1:bt,savedSessions:nn,savedHistoryFilters:Jt,missingWorkspaceResumePath:hn||null,onSavedHistoryFiltersChange:Dt,isSavedSessionsLoading:Wn,isResumingSavedSessionId:Tt,onClose:nt,onNewChat:Pt,onSwitchSession:Mt,onRefreshHistory:ut?Vt:mn,onResumeSavedSession:pn},remoteDialog:{conversation:Re,ideEntry:Ue,ides:f,connectionStates:C,actionLogs:we,sendDaemonCommand:t,setActionLogs:ce,isStandalone:G,userName:g.userName,onOpenHistory:ht=>{ht&&ke(ht),Pe()},onConversationChange:ke,onClose:et,onRetryConnection:g.retryConnection},cliStopDialog:{open:Ve,targetConv:st,onCancel:Qe,onStopNow:async()=>{await ge("hard")},onSaveAndStop:async()=>{await ge("save")}},connectionBanner:{wsStatus:w,showReconnected:A,loginUrl:g.connectionLoginUrl,onReconnect:g.retryServerConnection,suppress:e},toastOverlay:{toasts:y,onDismiss:ht=>k(Yt=>Yt.filter(us=>us.id!==ht)),onClick:ht=>{if(ht.targetKey){const Yt=Je(ht.targetKey);Yt&&(U(Yt.tabKey,Ie),zo(Yt),Ct(Yt.tabKey,"toast-open"))}}},onboarding:{open:v,standalone:G,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}_(!1)}},interactivePrompt:In,suppressInteractivePrompt:rt})]})}function JM({machineId:e,registeredMachineId:t,sendDaemonCommand:s,onNicknameSynced:r,logsEndRef:o}){const{t:a}=ve("common"),{launchCli:i}=wi(),{confirm:c,confirmDialog:d}=Fr(),[u,m]=l.useState([]),[h,p]=l.useState(null),[g,f]=l.useState(null),[x,b]=l.useState(!1),[k,j]=l.useState(null),[v,_]=l.useState(!1),[y,w]=l.useState(""),S=l.useRef(null),C=l.useCallback(P=>{S.current=P},[]),A=l.useCallback((P,H,W=!1,U)=>{const ae=Cd(U),be=ae&&ae!==H?`${H} — ${ae}`:H;m(V=>[...V.slice(-100),{timestamp:Date.now(),level:P,message:be}]),setTimeout(()=>{var V;return(V=o.current)==null?void 0:V.scrollIntoView({behavior:"smooth"})},100),W&&(P==="error"||P==="warn"?ct.showErrorToast(H,U):ct.showToast(H,"success"))},[o]),O=l.useCallback(P=>{const H=P instanceof Error?P.message:String(P||"");return H.includes("P2P command timeout")||H.includes("P2P not connected")||H.includes("P2P not available")},[]),L=l.useCallback(async(P,H)=>{var W;if(!e||h)return!1;p(P),A("info",a("machine.actions.launching",{name:Kt(P)}));try{const U={ideType:P,enableCdp:!0};(W=H==null?void 0:H.workspace)!=null&&W.trim()?U.workspace=H.workspace.trim():H!=null&&H.useDefaultWorkspace&&(U.useDefaultWorkspace=!0);const ae=await s(e,"launch_ide",U);return ae!=null&&ae.success?A("info",a("machine.actions.launched",{name:Kt(P)}),!0):A("error",a("machine.actions.launchFailed",{name:Kt(P)}),!0,ae==null?void 0:ae.error),!!(ae!=null&&ae.success)}catch(U){return A("error",a("machine.actions.launchFailed",{name:Kt(P)}),!0,U),!1}finally{p(null)}},[e,h,A,s,a]),M=l.useCallback(async P=>{if(!e)return{success:!1};const{cliType:H,dir:W,workspaceId:U,useDefaultWorkspace:ae,useHome:be,argsStr:V,model:we,resumeSessionId:ce}=P;if(!H)return A("warn",a("machine.actions.selectProviderFirst"),!0),{success:!1};const de=V?V.split(/\s+/).filter(Boolean):void 0,ne=(W==null?void 0:W.trim())||(U?"(saved id)":ae?"(default workspace)":be?"(home)":"");A("info",a("machine.actions.launching",{name:H}),!1,[ne,we].filter(Boolean).join(" · ")||void 0),f(H);try{const ee={cliType:H,cliArgs:de,initialModel:we||void 0};W!=null&&W.trim()?ee.dir=W.trim():U?ee.workspaceId=U:ae?ee.useDefaultWorkspace=!0:be&&(ee.useHome=!0),ce&&(ee.resumeSessionId=ce);const ue=await i(e,ee),je=(ue==null?void 0:ue.result)||ue;return ue!=null&&ue.success?(A("info",a("machine.actions.launched",{name:H}),!0),(je==null?void 0:je.launchSource)==="home"?A("info",a("machine.actions.runningInHome")):(je==null?void 0:je.launchSource)==="defaultWorkspace"&&A("info",a("machine.actions.usingDefaultWorkspace")),{success:!0,sessionId:je==null?void 0:je.sessionId}):(A("error",a("machine.actions.launchFailed",{name:H}),!0,(ue==null?void 0:ue.error)||(je==null?void 0:je.error)),(ue==null?void 0:ue.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&j({cliType:H,argsStr:V,model:we}),{success:!1,sessionId:je==null?void 0:je.sessionId})}catch(ee){return O(ee)?(A("warn",a("machine.actions.launchPending",{name:H}),!0),{success:!1,pending:!0}):(A("error",a("machine.actions.launchFailed",{name:H}),!0,ee),{success:!1})}finally{f(null)}},[e,A,O,s,a]),$=l.useCallback(async(P,H,W,U)=>e?P?H.trim()?M({cliType:P,dir:H,argsStr:W,model:U}):(j({cliType:P,argsStr:W,model:U}),{success:!1}):(A("warn",a("machine.actions.selectProvider"),!0),{success:!1}):{success:!1},[e,A,M,a]),N=l.useCallback(async(P,H,W)=>{if(e&&await c({title:a("cliStop.title",{agent:P}),description:a("machine.actions.stopCliConfirmDescription"),confirmLabel:a("cliStop.stop"),tone:"danger"}))try{const U=await s(e,"stop_cli",{cliType:P,dir:H,targetSessionId:W});U!=null&&U.success?A("info",a("machine.actions.stopped",{name:P}),!0):A("error",a("machine.actions.stopFailed"),!0,U==null?void 0:U.error)}catch(U){A("error",a("machine.actions.stopFailed"),!0,U)}},[e,A,c,s,a]),I=l.useCallback(async P=>{try{await s(P.daemonId,"restart_ide",{ideType:P.type}),A("info",a("machine.actions.restartInitiated",{name:Kt(P.type)}),!0)}catch(H){A("error",a("machine.actions.restartFailed"),!0,H)}},[A,s,a]),B=l.useCallback(async P=>{if(await c({title:a("cliStop.title",{agent:Kt(P.type)}),description:a("machine.actions.stopIdeConfirmDescription"),confirmLabel:a("cliStop.stop"),tone:"danger"}))try{const H=await s(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});H!=null&&H.success?A("info",a("machine.actions.stopped",{name:Kt(P.type)}),!0):A("error",a("machine.actions.stopFailed"),!0,H==null?void 0:H.error)}catch(H){A("error",a("machine.actions.stopFailed"),!0,H)}},[A,c,s,a]),T=l.useCallback(async()=>{if(e)try{const P=await s(e,"detect_ides",{});A("info",a("machine.actions.idesFound",{count:((P==null?void 0:P.result)||[]).length}),!0)}catch(P){A("error",a("machine.actions.detectFailed"),!0,P)}},[e,A,s,a]),F=l.useCallback(async P=>{if(!e||!P.trim())return!1;b(!0);try{const H=await s(e,"workspace_add",{path:P.trim()});return H!=null&&H.success?(A("info",a("machine.actions.workspaceAdded"),!1,P.trim()),!0):(A("error",a("machine.actions.workspaceActionFailed"),!1,H==null?void 0:H.error),!1)}catch(H){return A("error",a("machine.actions.workspaceActionFailed"),!1,H),!1}finally{b(!1)}},[e,A,s,a]),q=l.useCallback(async P=>{if(e){b(!0);try{const H=await s(e,"workspace_remove",{id:P});H!=null&&H.success?A("info",a("machine.actions.workspaceRemoved"),!0):A("error",a("machine.actions.workspaceActionFailed"),!0,H==null?void 0:H.error)}catch(H){A("error",a("machine.actions.workspaceActionFailed"),!0,H)}finally{b(!1)}}},[e,A,s,a]),Q=l.useCallback(async P=>{var H;if(e){b(!0);try{const W=await s(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(W!=null&&W.success){A("info",a(P?"machine.actions.defaultWorkspaceUpdated":"machine.actions.defaultWorkspaceCleared"),!0);const U=typeof W.defaultWorkspacePath=="string"?W.defaultWorkspacePath:"";U&&((H=S.current)==null||H.call(S,U))}else A("error",a("machine.actions.workspaceActionFailed"),!0,W==null?void 0:W.error)}catch(W){A("error",a("machine.actions.workspaceActionFailed"),!0,W)}finally{b(!1)}}},[e,A,s,a]),K=l.useCallback(async(P,H)=>{if(!e||!P.trim())return!1;b(!0);try{const W=await s(e,"workspace_set_label",{path:P.trim(),label:H});return W!=null&&W.success?(await s(e,"workspace_list",{}),A("info",a("machine.actions.workspaceLabelUpdated"),!0),!0):(A("error",a("machine.managedWorkspaces.renameFailed"),!0,W==null?void 0:W.error),!1)}catch(W){return A("error",a("machine.managedWorkspaces.renameFailed"),!0,W),!1}finally{b(!1)}},[e,A,s,a]),R=l.useCallback(async P=>{var W;if(!e||!P.trim())return;const H=P.trim();b(!0);try{const U=await s(e,"workspace_set_default",{path:H});U!=null&&U.success?(A("info",a("machine.actions.defaultWorkspaceUpdated")),(W=S.current)==null||W.call(S,H)):A("error",a("machine.actions.workspaceActionFailed"),!1,(U==null?void 0:U.error)||a("machine.actions.pathMissing"))}catch(U){A("error",a("machine.actions.workspaceActionFailed"),!1,U)}finally{b(!1)}},[e,A,s,a]),D=l.useCallback(async()=>{if(e)try{if(await s(e,"set_machine_nickname",{nickname:y}),r)try{await r({machineRuntimeId:e,registeredMachineId:t,nickname:y})}catch(P){A("warn",a("machine.actions.nicknameSyncFailed"),!1,P)}A("info",a("machine.actions.nicknameSaved")),_(!1)}catch(P){A("error",a("machine.actions.nicknameFailed"),!0,P)}},[e,y,t,A,r,s,a]);return{logs:u,launchingIde:h,launchingAgentType:g,workspaceBusy:x,launchPick:k,setLaunchPick:j,editingNickname:v,setEditingNickname:_,nicknameInput:y,setNicknameInput:w,addLog:A,handleLaunchIde:L,runLaunchCliCore:M,handleLaunchCli:$,handleStopCli:N,handleRestartIde:I,handleStopIde:B,handleDetectIdes:T,handleWorkspaceAdd:F,handleWorkspaceRemove:q,handleWorkspaceSetDefault:Q,handleWorkspaceSetLabel:K,handleWorkspaceResumePath:R,handleSaveNickname:D,confirmDialog:d,setOnDefaultWorkspaceChanged:C}}const $h={good:"bg-emerald-500/10 text-emerald-500",warn:"bg-amber-500/10 text-amber-500",danger:"bg-red-500/10 text-red-500",default:"bg-white/5 text-text-secondary",info:"bg-blue-500/10 text-blue-500"},XM={bucket:"machine.quota.bucketHint",session:"machine.quota.sessionHint",weekly:"machine.quota.weeklyHint",monthly:"machine.quota.monthlyHint",usage:"machine.quota.usageHint"};function Fh({label:e,tone:t,title:s}){return n.jsx("span",{title:s,className:`rounded-full px-2 py-0.5 text-3xs font-medium ${$h[t]??$h.default}`,children:e})}function ZM({machine:e}){const{t}=ve("common"),s=Wd(Bd(t)),r=eb(e.quota);return r.length===0?null:n.jsxs(wn,{padding:"lg",className:"mb-5",children:[n.jsx("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mb-3",children:t("machine.quota.title")}),n.jsx("div",{className:"flex flex-col gap-2",children:r.map(({provider:o,quota:a})=>{const i=s(a);return n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"text-xs text-text-primary min-w-[92px]",children:Lr(o)}),nc(a)&&n.jsx("span",{className:"text-3xs text-text-secondary",title:t("machine.quota.accountHint"),children:nc(a)}),i.kind==="chips"&&i.chips.map(c=>n.jsx(Fh,{label:c.label,tone:c.tone,title:t(XM[c.hint])},c.key)),i.kind==="usage"&&n.jsx(Fh,{label:i.usageLabel,tone:"info",title:t("machine.quota.usageHint")}),i.kind==="okNoWindows"&&n.jsx("span",{className:"text-2xs text-text-secondary",title:t("machine.quota.okNoWindowsHint"),children:i.message??t("machine.quota.okNoWindows")}),i.kind==="failure"&&n.jsx("span",{className:"text-2xs text-text-secondary",title:t("machine.quota.failureHint"),children:i.message})]},o)})})]})}function Hh({title:e,defaultOpen:t=!1,testId:s,children:r}){const[o,a]=l.useState(t),[i,c]=l.useState(t);return n.jsxs("details",{className:"group rounded-xl border border-border-subtle bg-bg-glass",open:o,"data-testid":s,onToggle:d=>{const u=d.currentTarget.open;a(u),u&&c(!0)},children:[n.jsxs("summary",{className:"flex cursor-pointer select-none list-none items-center gap-2 px-4 py-3 text-sm font-semibold text-text-primary [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"inline-block text-text-muted transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),e]}),i&&n.jsx("div",{className:"px-4 pb-4",children:r()})]})}function eR({machine:e,ideSessions:t,cliSessions:s,acpSessions:r,daemonVersion:o,renderHostedRuntimes:a,renderLogs:i,initialDiagnostics:c=null}){var g,f;const{t:d}=ve("common"),u=typeof e.uptime=="number"||typeof e.freeMem=="number"||typeof e.availableMem=="number"||Array.isArray(e.loadavg)&&e.loadavg.length>0,m=e.availableMem??e.freeMem??e.totalMem,h=u&&e.totalMem>0?Math.min(100,Math.max(0,Math.round((e.totalMem-m)/e.totalMem*100))):0,p=((g=e.loadavg)==null?void 0:g[0])||0;return n.jsxs("div",{children:[n.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[n.jsx(ta,{icon:n.jsx(hd,{size:16}),label:d("machine.overview.uptime"),value:typeof e.uptime=="number"?ij(e.uptime):d("machine.overview.waiting")}),n.jsx(ta,{icon:n.jsx(Xn,{size:16}),label:"IDEs",value:`${t.length}`}),n.jsx(ta,{icon:n.jsx(pd,{size:16}),label:"CLIs",value:`${s.length}`}),n.jsx(ta,{icon:n.jsx(xw,{size:16}),label:"ACPs",value:`${r.length}`})]}),n.jsxs(wn,{padding:"lg",className:"mb-5",children:[n.jsx("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mb-3",children:d("machine.overview.resourceUsage")}),n.jsxs("div",{className:"flex gap-6",children:[n.jsx(Gu,{value:u?Math.min(Math.round(p/e.cpus*100),100):0,max:100,label:d("machine.overview.cpuLoad"),color:"#8b5cf6",detail:u?d("machine.overview.cpuDetail",{load:p.toFixed(2),cores:e.cpus}):d("machine.overview.waitingForStats")}),n.jsx(Gu,{value:h,max:100,label:d("machine.overview.memory"),color:"#3b82f6",detail:u?`${ml(e.totalMem-m)} / ${ml(e.totalMem)}${e.platform==="darwin"?` ${d("machine.overview.approx")}`:""}`:d("machine.overview.waitingForStatsWithTotal",{total:ml(e.totalMem)})})]})]}),n.jsx(ZM,{machine:e}),n.jsxs(wn,{padding:"lg",className:"mb-5",children:[n.jsx("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mb-3",children:d("machine.overview.aboutMachine")}),n.jsxs("dl",{className:"grid grid-cols-1 gap-x-6 gap-y-2 text-xs sm:grid-cols-2","data-testid":"machine-about",children:[n.jsx(ro,{label:d("machine.overview.hostname"),value:e.hostname}),n.jsx(ro,{label:d("machine.overview.platform"),value:[Hf[e.platform]||e.platform,e.arch].filter(Boolean).join(" · ")}),e.cpus>0&&n.jsx(ro,{label:d("machine.overview.cores"),value:String(e.cpus)}),o&&n.jsx(ro,{label:d("machine.overview.daemonVersion"),value:`v${o}`}),((f=e.p2p)==null?void 0:f.available)&&n.jsx(ro,{label:d("machine.overview.p2p"),value:e.p2p.state==="connected"?d("machine.detail.p2pConnected"):e.p2p.state})]})]}),(a||i)&&n.jsxs("details",{className:"group mb-5","data-testid":"machine-diagnostics",open:c?!0:void 0,children:[n.jsxs("summary",{className:"mb-3 flex cursor-pointer select-none list-none items-center gap-2 text-2xs font-semibold uppercase tracking-wider text-text-muted [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"inline-block transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),d("machine.overview.diagnostics")]}),n.jsxs("div",{className:"flex flex-col gap-3",children:[a&&n.jsx(Hh,{title:d("machine.detail.tabHostedRuntimes"),defaultOpen:c==="hosted-runtimes",testId:"machine-diagnostics-hosted-runtimes",children:a}),i&&n.jsx(Hh,{title:d("machine.detail.tabLogs"),defaultOpen:c==="logs",testId:"machine-diagnostics-logs",children:i})]})]})]})}function ro({label:e,value:t}){return t?n.jsxs("div",{className:"flex min-w-0 items-baseline justify-between gap-3 sm:justify-start",children:[n.jsx("dt",{className:"shrink-0 text-text-muted sm:w-28",children:e}),n.jsx("dd",{className:"m-0 min-w-0 truncate text-text-primary",children:t})]}):null}function mx(e){if(!e||typeof e!="object")return null;const t=e,s=t.result&&typeof t.result=="object"?t.result:t;return!s.settings||typeof s.settings!="object"?null:{settings:s.settings,values:s.values&&typeof s.values=="object"?s.values:{}}}function hx(e,t,s){const r=[];for(const[o,a]of Object.entries(e.settings)){const i=s!=null&&s.filterSchema?s.filterSchema(a):a;if(i.length===0)continue;const c=t.find(d=>d.type===o);r.push({type:o,displayName:(c==null?void 0:c.displayName)||o,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:i,values:e.values[o]||{}})}return r}function $l(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function Bh(e){if(!e||typeof e!="object")return null;if($l(e))return e;const t=e,s=t.result;return $l(s)?s:$l(t.sourceConfig)?t.sourceConfig:null}function tR(e){const t=e.trim();return t||null}function nR({providerType:e,displayName:t,supportsQuota:s,quotaInstallsClaudeStatusline:r,onCancel:o,onConfirm:a}){const{t:i}=ve("common"),[c,d]=l.useState(!0),[u,m]=l.useState(!0);return n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:o,children:n.jsxs("div",{className:"w-[min(520px,92vw)] rounded-xl border border-border-default bg-surface-primary p-5 shadow-2xl",onClick:h=>h.stopPropagation(),role:"dialog","aria-modal":"true",children:[n.jsx("div",{className:"text-xxs font-semibold text-text-primary",children:i("machine.installOptions.title",{provider:t})}),n.jsxs("div",{className:"mt-4 flex flex-col gap-3",children:[s&&n.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5",children:[n.jsx("input",{type:"checkbox",checked:c,onChange:h=>d(h.target.checked),className:"mt-0.5 h-3.5 w-3.5 shrink-0 accent-accent-primary"}),n.jsx("span",{className:"min-w-0",children:n.jsxs("span",{className:"flex items-center gap-1 text-xs font-medium text-text-primary",children:[i("machine.installOptions.quotaLabel"),n.jsx(dt,{content:[i("machine.installOptions.quotaHint"),r&&c?i("machine.installOptions.quotaClaudeNote"):""].filter(Boolean).join(`
|
|
77
|
+
|
|
78
|
+
`),size:12})]})})]}),n.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5",children:[n.jsx("input",{type:"checkbox",checked:u,onChange:h=>m(h.target.checked),className:"mt-0.5 h-3.5 w-3.5 shrink-0 accent-accent-primary"}),n.jsxs("span",{className:"min-w-0",children:[n.jsx("span",{className:"block text-xs font-medium text-text-primary",children:i("machine.installOptions.autoApproveLabel")}),n.jsx("span",{className:"mt-0.5 block text-2xs text-text-muted",children:i("machine.installOptions.autoApproveHint")}),u&&n.jsx("span",{className:"mt-1 block text-2xs text-amber-400",children:i("machine.installOptions.autoApproveWarning")})]})]})]}),n.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[n.jsx("button",{onClick:o,className:"machine-btn text-2xs px-3 py-1",children:i("machine.installOptions.cancel")}),n.jsx("button",{onClick:()=>a({quotaEnabled:s?c:void 0,autoApprove:u}),className:"machine-btn text-2xs px-3 py-1 border-accent-primary/30 bg-accent-primary/15 text-accent-primary","data-provider-type":e,children:i("machine.installOptions.confirm")})]})]})})})}const Wh={"user-custom":"machine.trustBadge.userCustom",trusted:"machine.trustBadge.trusted","trusted-with-scripts":"machine.trustBadge.trustedWithScripts","external-safe":"machine.trustBadge.externalSafe","external-untrusted":"machine.trustBadge.externalUntrusted"},Uh={"user-custom":"machine.trustBadge.userCustomHint",trusted:"machine.trustBadge.trustedHint","trusted-with-scripts":"machine.trustBadge.trustedWithScriptsHint","external-safe":"machine.trustBadge.externalSafeHint","external-untrusted":"machine.trustBadge.externalUntrustedHint"},sR={"user-custom":"bg-violet-500/[0.10] border-violet-500/25 text-violet-300",trusted:"bg-green-500/[0.10] border-green-500/25 text-green-400","trusted-with-scripts":"bg-emerald-500/[0.10] border-emerald-500/25 text-emerald-400","external-safe":"bg-sky-500/[0.10] border-sky-500/25 text-sky-400","external-untrusted":"bg-amber-500/[0.10] border-amber-500/30 text-amber-300"};function rR({trust:e,sourceName:t,description:s}){const{t:r}=ve("common"),o=Wh[e]?r(Wh[e]):e,a=t&&(e==="external-safe"||e==="external-untrusted")?`${o} · ${t}`:o,i=Uh[e]?r(Uh[e]):s;return n.jsx("span",{className:`text-3xs px-1.5 py-0.5 rounded border whitespace-nowrap ${sR[e]??""}`,title:i,children:a})}const oR={ide:{badge:"bg-blue-500/10 text-blue-300 border-blue-500/20",accent:"border-blue-500/[0.12]"},cli:{badge:"bg-indigo-500/10 text-indigo-300 border-indigo-500/20",accent:"border-indigo-500/[0.12]"},acp:{badge:"bg-fuchsia-500/10 text-fuchsia-300 border-fuchsia-500/20",accent:"border-fuchsia-500/[0.12]"},extension:{badge:"bg-teal-500/10 text-teal-300 border-teal-500/20",accent:"border-teal-500/[0.12]"}},aR=["enabled","autoApprove","executablePath","executableArgs","cliPathOverride","appPathOverride","approvalAlert","longGeneratingAlert","longGeneratingThresholdSec","showThinking","showToolCalls","showTerminal","showCoordinatorSystemPrompt","notifications"],iR=new Set(aR);function lR(e,t,s){if(!iR.has(t.key))return{label:t.label||t.key,description:t.description||""};const r={provider:s||e("machine.providerSettings.thisProvider")};return{label:e(`machine.providerSettings.${t.key}.label`,r),description:e(`machine.providerSettings.${t.key}.description`,r)}}function cR(e,t){const s=String(t??""),r=s.replace(/[-_]+/g," ").trim().replace(/^./,o=>o.toUpperCase());return/^[a-z0-9][a-z0-9_-]*$/i.test(s)?e(`machine.providerSettings.option.${s.toLowerCase()}`,{defaultValue:r||s}):r||s}function dR(e){if(typeof e!="string")return null;try{const t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?t.toString():null}catch{return null}}const Kh={detected:"bg-green-500/[0.10] border-green-500/25 text-green-400",not_detected:"bg-red-500/[0.10] border-red-500/25 text-red-400",enabled_unchecked:"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400",disabled:"bg-white/[0.04] border-white/[0.10] text-text-muted"},uR={bucket:"machine.quota.bucketHint",session:"machine.quota.sessionHint",weekly:"machine.quota.weeklyHint",monthly:"machine.quota.monthlyHint",usage:"machine.quota.usageHint"},mR={default:"bg-white/[0.04] border-white/[0.10] text-text-muted",good:"bg-green-500/[0.10] border-green-500/25 text-green-400",warn:"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400",danger:"bg-red-500/[0.10] border-red-500/25 text-red-400",info:"bg-sky-500/[0.10] border-sky-500/25 text-sky-300"};function qh(e,t){if(!t)return"—";const s=t.ok?e("machine.providerRow.checkOk"):e("machine.providerRow.checkFailed"),r=t.message||t.path||t.command||"";return r?`${s} — ${r}`:s}const zh={Stable:"machine.providerRow.lifecycleStable",Beta:"machine.providerRow.lifecycleBeta",Experimental:"machine.providerRow.lifecycleExperimental",Deprecated:"machine.providerRow.lifecycleDeprecated"};function hR(e){return e==="cli"||e==="acp"}function Fl({checked:e,busy:t,label:s,onToggle:r}){return n.jsx(Ur,{as:"span",size:"sm",checked:e,busy:t,"aria-label":s,onChange:()=>r()})}function pR({prov:e,quota:t,providerInfo:s,savingKey:r,onSetSetting:o,onEnableToggle:a,onDetect:i,onResetCommand:c,quotaAccountLabelEnabled:d,onQuotaAccountLabelToggle:u,quotaEnabled:m,onQuotaToggle:h,pin:p,onUpdate:g,updating:f,onRollbackUpdate:x,showAdvanced:b=!1}){var N;const[k,j]=l.useState(null),[v,_]=l.useState(!1),{t:y}=ve("common"),w={detected:y("machine.providerRow.statusDetected"),not_detected:y("machine.providerRow.statusNotDetected"),enabled_unchecked:y("machine.providerRow.statusEnabledUnchecked"),disabled:y("machine.providerRow.statusDisabled")},[S,C]=l.useState(!1),A=(s==null?void 0:s.enabled)===!0||e.values.enabled===!0,O=s==null?void 0:s.machineStatus,L=A&&O==="disabled"?"enabled_unchecked":O||(A?"enabled_unchecked":"disabled"),M=hR(e.category),$=(()=>{if(!t)return null;const B=Wd(Bd(y))(t).compactChip;return B?{label:B.label,tone:mR[B.tone],title:y(uR[B.hint])}:null})();return n.jsxs(wn,{padding:"none",children:[n.jsxs("button",{onClick:()=>C(I=>!I),className:"w-full px-4 py-2.5 flex items-center gap-3 text-left",children:[n.jsx(Hi,{type:e.type,label:e.displayName,size:20,className:"shrink-0"}),n.jsx("span",{className:"text-xxs font-semibold text-text-primary truncate",children:e.displayName}),n.jsx("span",{className:`text-4xs font-semibold px-1.5 py-px rounded border ${((N=oR[e.category])==null?void 0:N.badge)??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(s==null?void 0:s.trust)&&n.jsx(rR,{trust:s.trust,sourceName:s.sourceName??null,description:s.trustDescription}),M&&n.jsx("span",{className:`text-4xs font-semibold px-1.5 py-px rounded border ${Kh[L]??Kh.disabled}`,children:w[L]??L}),n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[g&&(p==null?void 0:p.stale)&&p.latestVersion&&n.jsx("span",{role:"button",tabIndex:0,"aria-disabled":f?!0:void 0,title:y("machine.providerRow.updateInlineHint",{latest:p.latestVersion}),onClick:I=>{I.stopPropagation(),!f&&g()},onKeyDown:I=>{I.key!=="Enter"&&I.key!==" "||(I.preventDefault(),I.stopPropagation(),!f&&g())},className:`text-3xs font-semibold px-2 py-0.5 rounded-md border border-amber-500/30 text-amber-400 shrink-0 ${f?"opacity-60 cursor-wait":"cursor-pointer hover:bg-amber-500/15"}`,children:y(f?"machine.providerRow.specPinUpdating":"machine.providerRow.updateInline")}),$&&n.jsx("span",{className:`text-4xs font-semibold px-1.5 py-px rounded border shrink-0 ${$.tone}`,title:$.title,children:$.label}),M&&n.jsx(Fl,{checked:A,busy:r===`${e.type}.enabled`,label:y(A?"machine.providerRow.disable":"machine.providerRow.enable"),onToggle:()=>{a(e.type,!A)}}),n.jsx("span",{className:"text-text-muted text-xs",children:S?"▾":"▸"})]})]}),S&&n.jsxs("div",{className:"border-t border-border-subtle px-4 py-3 flex flex-col gap-3",children:[e.schema.length>0&&n.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(I=>{const B=lR(y,I,e.displayName);return n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("div",{className:"flex-1 min-w-0",children:n.jsxs("div",{className:"flex items-center gap-1 text-2xs font-medium text-text-primary",children:[B.label,B.description&&n.jsx(dt,{content:B.description,size:11}),r===`${e.type}.${I.key}`&&n.jsx("span",{className:"ml-1.5 text-4xs text-accent-primary",children:y("machine.providerRow.saving")})]})}),n.jsx("div",{className:"shrink-0",children:I.type==="boolean"?n.jsx(Ur,{checked:!!(e.values[I.key]??I.default),busy:r===`${e.type}.${I.key}`,"aria-label":B.label,onChange:T=>void o(e.type,I.key,T)}):I.type==="number"?n.jsx("input",{type:"number",value:Number(e.values[I.key]??I.default??0)||0,min:I.min,max:I.max,onChange:T=>{const F=parseInt(T.target.value)||0;I.min!==void 0&&F<I.min||I.max!==void 0&&F>I.max||o(e.type,I.key,F)},className:"machine-input w-20 text-center text-2xs"}):I.type==="select"&&I.options?n.jsx("select",{value:String(e.values[I.key]??I.default??""),onChange:T=>void o(e.type,I.key,T.target.value),className:"machine-input text-2xs",children:I.options.map(T=>n.jsx("option",{value:T,children:cR(y,T)},T))}):n.jsx("input",{type:"text",defaultValue:String(e.values[I.key]??I.default??""),onBlur:T=>void o(e.type,I.key,T.target.value),className:"machine-input w-[180px] text-2xs"})})]},I.key)})}),h&&m!==void 0&&n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1 text-2xs text-text-secondary font-medium",children:[y("machine.providerRow.quotaTracking"),n.jsx(dt,{content:y("machine.providerRow.quotaTrackingHint"),size:11})]}),v?n.jsxs("div",{className:"flex flex-col items-end gap-1.5 shrink-0",children:[n.jsx("div",{className:"text-2xs font-medium text-amber-400",children:y("machine.providerRow.quotaClaudeConfirmTitle")}),n.jsx("div",{className:"text-3xs text-text-muted max-w-[420px] text-right",children:y("machine.providerRow.quotaClaudeConfirmBody")}),n.jsxs("div",{className:"flex gap-1.5",children:[n.jsx("button",{onClick:I=>{I.stopPropagation(),_(!1),h(e.type,!0)},className:"machine-btn text-3xs px-2 py-0.5 text-amber-400 border-amber-500/25",children:y("machine.providerRow.quotaClaudeConfirmOk")}),n.jsx("button",{onClick:I=>{I.stopPropagation(),_(!1)},className:"machine-btn text-3xs px-2 py-0.5",children:y("machine.providerRow.quotaClaudeConfirmCancel")})]})]}):n.jsx(Fl,{checked:m,label:y("machine.providerRow.quotaTracking"),onToggle:()=>{e.type==="claude-cli"&&!m?_(!0):h(e.type,!m)}})]}),u&&d!==void 0&&n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1 text-2xs text-text-secondary font-medium",children:[y("machine.providerRow.quotaAccountLabel"),n.jsx(dt,{content:y("machine.providerRow.quotaAccountLabelHint"),size:11})]}),n.jsx(Fl,{checked:d,label:y("machine.providerRow.quotaAccountLabel"),onToggle:()=>{u(!d)}})]}),b&&n.jsxs("div",{className:"grid gap-1 text-3xs text-text-muted","data-testid":"provider-row-metadata",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelType")})," ",n.jsx("span",{className:"font-mono",children:e.type})]}),(s==null?void 0:s.providerVersion)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelVersion")})," ",s.providerVersion]}),(p==null?void 0:p.activeVersion)&&n.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelSpecPin")}),n.jsx("span",{className:"font-mono",children:p.activeVersion}),p.stale&&p.latestVersion&&n.jsx("span",{className:"px-1 py-px rounded border border-amber-500/30 text-amber-400",title:y("machine.providerRow.specPinStaleHint",{latest:p.latestVersion}),children:y("machine.providerRow.specPinStale",{latest:p.latestVersion})})]}),(p==null?void 0:p.activatedAt)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelActivatedAt")})," ",Do(p.activatedAt)]}),(p==null?void 0:p.previousVersion)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelPreviousPin")})," ",n.jsx("span",{className:"font-mono",children:p.previousVersion})]}),(p==null?void 0:p.digest)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelDigest")})," ",n.jsx("span",{className:"font-mono",children:p.digest.replace(/^sha256:/,"").slice(0,12)})]}),b&&(s==null?void 0:s.binary)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelBinary")})," ",n.jsx("span",{className:"font-mono",children:s.binary})]}),(s==null?void 0:s.status)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelStatus")})," ",zh[s.status]?y(zh[s.status]):s.status]}),b&&(s==null?void 0:s.details)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelDetails")})," ",s.details]}),b&&(s==null?void 0:s.sourceLayer)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelSource")})," ",n.jsx("span",{className:"font-mono",children:s.sourceLayer}),s.sourceName?` · ${s.sourceName}`:""]}),b&&(s==null?void 0:s.trust)&&(s==null?void 0:s.trustDescription)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelTrust")})," ",n.jsx("span",{className:"font-mono",children:s.trust})," — ",s.trustDescription]}),(()=>{const I=s==null?void 0:s.links;if(!I)return null;const B=Object.entries(I).map(([T,F])=>({k:T,href:dR(F)})).filter(T=>T.href!==null);return B.length===0?null:n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelLinks")})," ",B.map(({k:T,href:F})=>n.jsx("a",{href:F,target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary hover:underline mr-2",children:T},T))]})})()]}),M&&(b||(s==null?void 0:s.lastDetection)||(s==null?void 0:s.lastVerification))&&n.jsxs("div",{className:"grid gap-1 text-3xs text-text-muted",children:[(b||(s==null?void 0:s.lastDetection))&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelDetection")})," ",qh(y,s==null?void 0:s.lastDetection)]}),(b||(s==null?void 0:s.lastVerification))&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:y("machine.providerRow.labelVerification")})," ",qh(y,s==null?void 0:s.lastVerification)]})]}),n.jsxs("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:[M&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>void i(e.type),disabled:!A||r===`${e.type}.detect`,className:`machine-btn text-3xs px-2 py-0.5 text-blue-400 border-blue-500/25 ${A?"":"opacity-40 cursor-not-allowed"}`,title:y(A?"machine.providerRow.detectHint":"machine.providerRow.detectDisabledHint"),children:y("machine.providerRow.detect")}),n.jsx("button",{onClick:()=>void c(e.type),className:"machine-btn text-3xs px-2 py-0.5",children:y("machine.providerRow.resetCommand")})]}),x&&(p==null?void 0:p.previousVersion)&&n.jsx("button",{onClick:()=>{j("rollback"),x().finally(()=>j(null))},disabled:k!==null||f===!0,className:"machine-btn text-3xs px-2 py-0.5",title:y("machine.providerRow.specPinRollbackHint",{version:p.previousVersion}),children:y(k==="rollback"?"machine.providerRow.specPinRollingBack":"machine.providerRow.specPinRollback")})]})]})]})}function fR(e){if(!e||typeof e!="object")return null;const t=e,s=t.result;return s&&typeof s=="object"?s:t}function Gh(e){const t=fR(e);if(!t)return[];const s=[];t.success===!1&&typeof t.error=="string"&&t.error.trim()&&s.push({code:"COMMAND_FAILED",message:t.error});const r=t.channelSync,o=r&&typeof r=="object"?r.errors:void 0;if(Array.isArray(o))for(const a of o){if(!a||typeof a!="object")continue;const i=a,c=typeof i.code=="string"?i.code:"UNKNOWN",d=typeof i.message=="string"?i.message:"";s.push({code:c,message:d,...typeof i.providerType=="string"?{providerType:i.providerType}:{}})}return s}function gR(e){return e.some(t=>t.code==="DIGEST_MISMATCH")}function xa(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function bR({machineId:e,sendDaemonCommand:t,onChange:s,reloadToken:r=0}){const{t:o}=ve("common"),{confirm:a,confirmDialog:i}=Fr(),[c,d]=l.useState([]),[u,m]=l.useState([]),[h,p]=l.useState(!1),[g,f]=l.useState(null),[x,b]=l.useState(!1),[k,j]=l.useState(""),[v,_]=l.useState("main"),[y,w]=l.useState(""),[S,C]=l.useState(!1),[A,O]=l.useState(null),[L,M]=l.useState(null),$=l.useCallback(async()=>{if(e){p(!0),f(null);try{const T=xa(await t(e,"list_provider_sources",{}));if(!(T!=null&&T.success)){f((T==null?void 0:T.error)||o("machine.sourcesPanel.loadFailed"));return}d(T.sources||[]),m(T.conflicts||[])}catch(T){f((T==null?void 0:T.message)||o("machine.sourcesPanel.loadFailed"))}finally{p(!1)}}},[e,t,o]);l.useEffect(()=>{$()},[$,r]);const N=async()=>{if(k.trim()){C(!0),f(null);try{const T=xa(await t(e,"add_provider_source",{url:k.trim(),ref:v.trim()||"main",...y.trim()?{name:y.trim()}:{}}));T!=null&&T.success?(b(!1),j(""),_("main"),w(""),await $(),s==null||s()):f((T==null?void 0:T.error)||o("machine.sourcesPanel.addFailed"))}catch(T){f((T==null?void 0:T.message)||o("machine.sourcesPanel.addFailed"))}finally{C(!1)}}},I=async T=>{if(await a({title:o("machine.sourcesPanel.removeConfirmTitle",{name:T}),description:o("machine.sourcesPanel.removeConfirmDescription"),confirmLabel:o("machine.sourcesPanel.removeConfirmLabel"),cancelLabel:o("machine.sourcesPanel.cancel"),tone:"danger"})){O(T),f(null);try{const q=xa(await t(e,"remove_provider_source",{name:T}));q!=null&&q.success?(await $(),s==null||s()):f((q==null?void 0:q.error)||o("machine.sourcesPanel.removeFailed"))}catch(q){f((q==null?void 0:q.message)||o("machine.sourcesPanel.removeFailed"))}finally{O(null)}}},B=async(T,F)=>{M(`${T}:${F}`),f(null);try{const q=xa(await t(e,"set_active_provider_source",{type:T,sourceName:F}));q!=null&&q.success?(await $(),s==null||s()):f((q==null?void 0:q.error)||o("machine.sourcesPanel.setActiveFailed"))}catch(q){f((q==null?void 0:q.message)||o("machine.sourcesPanel.setActiveFailed"))}finally{M(null)}};return n.jsxs(wn,{padding:"none",className:"px-4.5 py-3.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[n.jsxs("div",{className:"flex items-center gap-1 text-2xs font-semibold uppercase tracking-wider text-sky-400",children:[o("machine.sourcesPanel.title"),n.jsx(dt,{content:o("machine.sourcesPanel.description"),size:12}),h&&n.jsx("span",{className:"ml-1 normal-case tracking-normal font-normal text-text-muted",children:"…"})]}),n.jsx("div",{className:"flex gap-1.5",children:n.jsx("button",{onClick:()=>b(!0),className:"machine-btn text-3xs bg-sky-500/[0.08] border-sky-500/20 text-sky-300 hover:bg-sky-500/[0.14]",children:o("machine.sourcesPanel.addSource")})})]}),g&&n.jsx("div",{className:"mb-2 text-2xs text-red-400 bg-red-500/10 border border-red-500/20 rounded px-2 py-1",children:g}),c.length===0?n.jsx("div",{className:"text-2xs text-text-muted italic",children:o("machine.sourcesPanel.empty")}):n.jsx("ul",{className:"flex flex-col gap-2",children:c.map(T=>n.jsxs("li",{className:"rounded border border-border-subtle bg-bg-primary/40 px-3 py-2",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"font-mono text-xs text-text-primary",children:T.name}),n.jsxs("div",{className:"text-3xs text-text-muted truncate",children:[T.url," ",n.jsxs("span",{className:"opacity-60",children:["@ ",T.ref]})]})]}),n.jsx("button",{type:"button",onClick:()=>void I(T.name),disabled:A===T.name,className:"machine-btn text-3xs text-red-400 hover:bg-red-500/[0.10]",children:A===T.name?o("machine.sourcesPanel.removing"):o("machine.sourcesPanel.remove")})]}),n.jsx("div",{className:"mt-1.5 text-3xs text-text-muted",children:Object.entries(T.providers).map(([F,q])=>n.jsxs("span",{className:"mr-3",children:[n.jsxs("span",{className:"text-text-secondary",children:[F,":"]})," ",q.length]},F))})]},T.name))}),u.length>0&&n.jsxs("div",{className:"mt-3 rounded border border-amber-500/30 bg-amber-500/[0.06] px-3 py-2",children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1 text-2xs font-semibold text-amber-300",children:[o("machine.sourcesPanel.conflictsTitle"),n.jsx(dt,{content:o("machine.sourcesPanel.conflictsDescription"),size:12})]}),n.jsx("ul",{className:"flex flex-col gap-1.5",children:u.map(T=>n.jsxs("li",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"font-mono text-2xs",children:[T.type," ",n.jsxs("span",{className:"text-text-muted",children:["(",T.category,")"]})]}),n.jsx("div",{className:"flex gap-1.5 flex-wrap",children:T.candidates.map(F=>n.jsxs("button",{type:"button",onClick:()=>void B(T.type,F),disabled:L===`${T.type}:${F}`,className:`text-3xs px-2 py-0.5 rounded border ${T.active===F?"bg-amber-500/[0.18] border-amber-500/40 text-amber-200":"border-border-subtle text-text-secondary hover:bg-amber-500/[0.06]"}`,title:T.active===F?o("machine.sourcesPanel.active"):o("machine.sourcesPanel.switchActiveTo",{name:F}),children:[T.active===F?"● ":"",F]},F))})]},T.type))})]}),x&&n.jsxs("div",{className:"mt-3 rounded border border-sky-500/30 bg-sky-500/[0.06] px-3 py-3",children:[n.jsx("div",{className:"text-2xs font-semibold text-sky-300 mb-2",children:o("machine.sourcesPanel.addTitle")}),n.jsxs("div",{className:"grid md:grid-cols-3 gap-2",children:[n.jsxs("label",{className:"flex flex-col gap-1 text-3xs text-text-secondary md:col-span-3",children:[n.jsx("span",{children:o("machine.sourcesPanel.gitUrl")}),n.jsx("input",{type:"text",value:k,onChange:T=>j(T.target.value),placeholder:"https://github.com/vendor/extra-providers",className:"machine-input text-2xs font-mono"})]}),n.jsxs("label",{className:"flex flex-col gap-1 text-3xs text-text-secondary",children:[n.jsx("span",{children:o("machine.sourcesPanel.ref")}),n.jsx("input",{type:"text",value:v,onChange:T=>_(T.target.value),placeholder:"main",className:"machine-input text-2xs"})]}),n.jsxs("label",{className:"flex flex-col gap-1 text-3xs text-text-secondary md:col-span-2",children:[n.jsx("span",{children:o("machine.sourcesPanel.name")}),n.jsx("input",{type:"text",value:y,onChange:T=>w(T.target.value),placeholder:"@vendor-extra-providers",className:"machine-input text-2xs font-mono"})]})]}),n.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>b(!1),className:"machine-btn text-3xs",children:o("machine.sourcesPanel.cancel")}),n.jsx("button",{type:"button",onClick:()=>void N(),disabled:S||!k.trim(),className:"machine-btn text-3xs bg-sky-500/[0.10] border-sky-500/30 text-sky-200 hover:bg-sky-500/[0.18]",children:o(S?"machine.sourcesPanel.cloning":"machine.sourcesPanel.cloneAndRegister")})]})]}),i]})}function Vh(e){var o;const t=vd(e);if(!t)return{ok:!1,error:"empty response"};if(t.success===!1)return{ok:!1,error:typeof t.error=="string"&&t.error.trim()?t.error:"sync failed"};const s=t.channelSync;if(s&&typeof s=="object"&&s.status==="error"){const a=Array.isArray(s.errors)?(o=s.errors[0])==null?void 0:o.message:void 0;return{ok:!1,error:typeof a=="string"&&a.trim()?a:"channel sync failed"}}return{ok:!0,activatedCount:Array.isArray(t.activated)?t.activated.length:0}}const Yh=new Set(["codex-cli"]),ya=new Set(fy);function xR({machineId:e,providers:t,sendDaemonCommand:s,quota:r,onChannelStaleness:o}){var oe,Ie;const{t:a}=ve("common"),[i,c]=l.useState(null),[d,u]=l.useState(void 0),[m,h]=l.useState({}),[p,g]=l.useState({}),[f,x]=l.useState([]),[b,k]=l.useState([]),[j,v]=l.useState(null),[_,y]=l.useState({}),[w,S]=l.useState(!1),[C,A]=l.useState({}),[O,L]=l.useState(!1),[M,$]=l.useState(null),[N,I]=l.useState(null),[B,T]=l.useState("cli"),[F,q]=l.useState(null),[Q,K]=l.useState(!1),[R,D]=l.useState(0),[P,H]=l.useState(null),[W,U]=l.useState("normal"),[ae,be]=l.useState(""),[V,we]=l.useState(!1),ce=l.useCallback(async()=>{if(e)try{const Z=await s(e,"get_provider_source_config",{}),se=Bh(Z);se&&(H(se),U(se.sourceMode),be(se.explicitProviderDir||""))}catch(Z){$(a("machine.providers.loadFailed",{error:(Z==null?void 0:Z.message)||String(Z)}))}},[e,s,a]),de=l.useCallback(async Z=>{if(e){Z!=null&&Z.explicit&&L(!0);try{const se=await s(e,"get_provider_settings",{}),ye=mx(se);ye&&(c(ye),$(null))}catch(se){$(a("machine.providers.loadFailed",{error:(se==null?void 0:se.message)||String(se)}))}finally{Z!=null&&Z.explicit&&L(!1)}}},[e,s,a]),ne=l.useMemo(()=>{if(!i)return[];const Z=hx(i,t,{filterSchema:se=>se.filter(ye=>ye.key!=="enabled")});return Z.sort((se,ye)=>se.category.localeCompare(ye.category)||se.displayName.localeCompare(ye.displayName)),Z},[i,t]),ee=l.useCallback((Z,se,ye)=>{c($e=>$e&&{...$e,values:{...$e.values,[Z]:{...$e.values[Z]||{},[se]:ye}}})},[]),ue=l.useCallback(async()=>{if(e)try{const Z=await s(e,"get_quota_account_label",{}),se=Z&&typeof Z=="object"&&"result"in Z?Z.result:Z;typeof(se==null?void 0:se.enabled)=="boolean"&&u(se.enabled)}catch{}},[e,s]),je=l.useCallback(async Z=>{if(e){u(Z);try{const se=await s(e,"set_quota_account_label",{enabled:Z}),ye=se&&typeof se=="object"&&"result"in se?se.result:se;(ye==null?void 0:ye.success)===!1&&await ue()}catch{await ue()}}},[e,s,ue]),X=l.useCallback(async Z=>{if(e)try{const se=await s(e,"get_quota_provider_enabled",{providerType:Z}),ye=se&&typeof se=="object"&&"result"in se?se.result:se;typeof(ye==null?void 0:ye.enabled)=="boolean"&&h($e=>({...$e,[Z]:ye.enabled}))}catch{}},[e,s]),G=l.useCallback(async()=>{await Promise.all([...ya].map(Z=>X(Z)))},[X]),z=l.useCallback(async(Z,se)=>{if(e){h(ye=>({...ye,[Z]:se}));try{const ye=await s(e,"set_quota_provider_enabled",{providerType:Z,enabled:se}),$e=ye&&typeof ye=="object"&&"result"in ye?ye.result:ye;($e==null?void 0:$e.success)===!1&&($(a("machine.providers.quotaToggleFailed",{provider:Z,error:typeof $e.error=="string"?$e.error:"unknown error"})),await X(Z))}catch(ye){$(a("machine.providers.quotaToggleFailed",{provider:Z,error:(ye==null?void 0:ye.message)||String(ye)})),await X(Z)}}},[e,s,X,a]),ie=l.useCallback(async()=>{var Z,se;if(e)try{const ye=await s(e,"check_provider_updates",{}),$e=ye&&typeof ye=="object"&&"result"in ye?ye.result:ye,Me={};for(const Te of($e==null?void 0:$e.providers)??[])typeof(Te==null?void 0:Te.type)=="string"&&(Me[Te.type]={activeVersion:Te.activeVersion??null,latestVersion:Te.latestVersion??null,stale:Te.stale===!0,digest:Te.digest??null,activatedAt:Te.activatedAt??null,previousVersion:Te.previousVersion??null});g(Me),x(Array.isArray((Z=$e==null?void 0:$e.channelStaleness)==null?void 0:Z.newTypes)?$e.channelStaleness.newTypes:[]);const De=$e==null?void 0:$e.channelStaleness;o&&De&&!De.error&&o({staleTypes:Array.isArray(De.staleTypes)?De.staleTypes:[],newTypes:Array.isArray(De.newTypes)?De.newTypes:[]}),k(Array.isArray((se=$e==null?void 0:$e.modelStaleness)==null?void 0:se.staleTypes)?$e.modelStaleness.staleTypes:[])}catch{}},[e,s,o]),Ne=l.useCallback(async Z=>{if(e){v(Z),A(se=>{if(!(Z in se))return se;const ye={...se};return delete ye[Z],ye});try{const se=await s(e,"activate_provider_updates",{types:[Z]}),ye=Gh(se);ye.length>0&&A($e=>({...$e,[Z]:ye}))}catch(se){A(ye=>({...ye,[Z]:[{code:"COMMAND_FAILED",message:se instanceof Error?se.message:String(se)}]}))}finally{v(null),await ie(),de()}}},[e,s,ie,de]),Be=l.useCallback(async()=>{if(e){S(!0);try{const Z=await s(e,"activate_provider_updates",{}),se=Vh(Z);"error"in se?ct.showErrorToast(a("machine.detail.providerSyncFailed"),se.error):ct.showToast(se.activatedCount>0?a("machine.detail.providerSyncSuccess",{count:se.activatedCount}):a("machine.detail.providerSyncAlreadyCurrent"),"success")}catch(Z){ct.showErrorToast(a("machine.detail.providerSyncFailed"),Z)}finally{S(!1),await ie(),de()}}},[e,s,ie,de,a]),Le=l.useCallback(async Z=>{if(e)try{await s(e,"rollback_provider_update",{providerType:Z})}finally{await ie(),de()}},[e,s,ie,de]),Je=l.useCallback(async Z=>{if(e){y(se=>({...se,[Z]:!0}));try{const se=await s(e,"activate_provider_updates",{types:[Z],only:!0}),ye=Vh(se),$e=Gh(se);if("error"in ye||$e.length>0){const Me="error"in ye?ye.error:$e.map(De=>De.message||De.code).join("; ");ct.showErrorToast(a("machine.detail.providerSyncFailed"),Me)}else ct.showToast(ye.activatedCount>0?a("machine.detail.providerSyncSuccess",{count:ye.activatedCount}):a("machine.detail.providerSyncAlreadyCurrent"),"success")}catch(se){ct.showErrorToast(a("machine.detail.providerSyncFailed"),se)}finally{y(se=>{const ye={...se};return delete ye[Z],ye}),await ie(),de()}}},[e,s,ie,de,a]);l.useEffect(()=>{i||de({explicit:!0}),P||ce(),d===void 0&&ue(),G(),ie()},[]);const Se=async(Z,se,ye)=>{I(`${Z}.${se}`),ee(Z,se,ye);try{const $e=await s(e,"set_provider_setting",{providerType:Z,key:se,value:ye});$e!=null&&$e.success||de()}catch{de()}I(null)},he=async(Z,se)=>{if(se){q(Z);return}await Se(Z,"enabled",!1)},pe=l.useCallback(async(Z,se)=>{q(null),I(`${Z}.enabled`);try{se.quotaEnabled!==void 0&&await s(e,"set_quota_provider_enabled",{providerType:Z,enabled:se.quotaEnabled});const ye=await s(e,"set_provider_setting",{providerType:Z,key:"autoApprove",value:se.autoApprove}),$e=await s(e,"set_provider_setting",{providerType:Z,key:"enabled",value:!0});if((ye==null?void 0:ye.success)===!1||($e==null?void 0:$e.success)===!1)throw new Error("set_provider_setting refused");ee(Z,"autoApprove",se.autoApprove),ee(Z,"enabled",!0),se.quotaEnabled!==void 0&&h(Me=>({...Me,[Z]:se.quotaEnabled}))}catch{de(),X(Z)}finally{I(null)}},[e,s,de,X,ee]),Ee=async Z=>{I(`${Z}.detect`);try{const se=await s(e,"detect_provider",{providerType:Z}),ye=se&&typeof se=="object"&&"result"in se?se.result:se;(ye==null?void 0:ye.success)===!1&&$(a("machine.providers.loadFailed",{error:typeof ye.error=="string"?ye.error:"detect failed"}))}catch(se){$(a("machine.providers.loadFailed",{error:(se==null?void 0:se.message)||String(se)}))}finally{I(null)}},Y=async Z=>{await Se(Z,"executablePath",""),await Se(Z,"executableArgs","")},me=async()=>{we(!0);try{const Z=await s(e,"set_provider_source_config",{providerSourceMode:W,providerDir:tR(ae)}),se=Bh(Z);se?(H(se),U(se.sourceMode),be(se.explicitProviderDir||"")):await ce(),de()}catch{await ce()}we(!1)},fe=ne.filter(Z=>B==="all"||Z.category===B),E=Object.values(p).filter(Z=>Z.stale).length;return n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[n.jsxs("div",{className:"flex gap-1 items-center",children:[n.jsx("span",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mr-2",children:a("machine.providers.filter")}),["cli","ide","acp","extension","all"].map(Z=>n.jsx("button",{onClick:()=>T(Z),className:`machine-btn text-3xs px-2 py-0.5 ${B===Z?"bg-accent-primary/15 border-accent-primary/40 text-accent-primary":""}`,children:Z.toUpperCase()},Z))]}),n.jsxs("div",{className:"flex gap-1.5 items-center",children:[E>=2&&n.jsxs("button",{onClick:()=>{Be()},disabled:w,className:"machine-btn text-3xs text-amber-400 border-amber-500/25",children:[w?n.jsx(Mr,{size:11}):null," ",a("machine.providers.updateAll")]}),n.jsx(Wi,{onClick:()=>{de({explicit:!0}),ie(),Q&&(ce(),D(Z=>Z+1))},refreshing:O,label:a("machine.providers.refresh"),size:12,className:"h-7 w-7"}),n.jsx("button",{onClick:()=>K(Z=>!Z),"aria-expanded":Q,className:`machine-btn text-3xs ${Q?"bg-accent-primary/10 border-accent-primary/30 text-accent-primary":""}`,title:a("machine.providers.advancedHint"),children:a("machine.providers.advanced")})]})]}),M&&n.jsx(zt,{variant:"error",onDismiss:()=>$(null),children:M}),f.length>0&&n.jsxs(wn,{padding:"none",className:"px-4.5 py-3.5",children:[n.jsxs("div",{className:"mb-2.5 flex items-center gap-1 text-2xs font-semibold uppercase tracking-wider text-accent-primary",children:[a("machine.providers.newChannelTypesTitle"),n.jsx(dt,{content:a("machine.providers.newChannelTypesDesc"),size:12})]}),n.jsx("div",{className:"flex flex-col gap-1.5",children:f.map(Z=>{const se=C[Z]??[];return n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 text-xxs",children:[n.jsx("span",{className:"font-mono text-text-primary",children:Z}),n.jsx("button",{onClick:()=>{Ne(Z)},disabled:j!==null,className:"px-2.5 py-1 rounded-md text-xs font-medium bg-accent-primary/15 text-accent-primary hover:bg-accent-primary/25 disabled:opacity-50",children:j===Z?n.jsx(Mr,{size:11}):a("machine.providers.installNewType")})]}),se.length>0&&n.jsxs("div",{className:"rounded-md border border-red-500/30 bg-red-500/[0.07] px-2.5 py-1.5",children:[n.jsx("div",{className:"text-3xs font-semibold text-red-300",children:gR(se)?a("machine.providers.installFailedDigestMismatch"):a("machine.providers.installFailedTitle")}),n.jsx(Od,{summary:a("toast.details"),className:"mt-1",children:n.jsx("ul",{className:"flex flex-col gap-0.5",children:se.map((ye,$e)=>n.jsxs("li",{className:"text-3xs text-text-muted font-mono break-all",children:[n.jsx("span",{className:"text-red-300/90",children:ye.code}),ye.providerType?` [${ye.providerType}]`:"",ye.message?`: ${ye.message}`:""]},`${ye.code}-${$e}`))})})]})]},Z)})})]}),b.length>0&&n.jsxs(wn,{padding:"none",className:"px-4.5 py-3.5",children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1 text-2xs font-semibold uppercase tracking-wider text-text-secondary",children:[a("machine.providers.modelListTitle"),n.jsx(dt,{content:a("machine.providers.modelListStaleDesc"),size:12})]}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:b.map(Z=>n.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-amber-500/30 bg-amber-500/[0.07] px-2 py-0.5",children:[n.jsx("span",{className:"font-mono text-xxs text-text-primary",children:Z}),n.jsx("span",{className:"text-3xs uppercase tracking-wider text-amber-300/90",children:a("machine.providers.modelListStaleBadge")})]},Z))})]}),Q&&n.jsx(bR,{machineId:e,sendDaemonCommand:s,onChange:()=>{de()},reloadToken:R}),Q&&n.jsxs(wn,{padding:"none",className:"px-4.5 py-3.5",children:[n.jsx("div",{className:"flex items-center justify-between gap-3 mb-3",children:n.jsxs("div",{className:"flex items-center gap-1 text-2xs font-semibold uppercase tracking-wider text-accent-primary",children:[a("machine.providers.sourceConfigTitle"),n.jsx(dt,{content:a("machine.providers.sourceConfigDesc"),size:12})]})}),n.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[n.jsxs("label",{className:"flex flex-col gap-1 text-2xs text-text-secondary",children:[n.jsx("span",{className:"font-medium text-text-primary",children:a("machine.providers.sourceMode")}),n.jsxs("select",{value:W,onChange:Z=>U(Z.target.value),className:"machine-input text-2xs",children:[n.jsx("option",{value:"normal",children:"normal"}),n.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),n.jsxs("label",{className:"flex flex-col gap-1 text-2xs text-text-secondary",children:[n.jsx("span",{className:"font-medium text-text-primary",children:a("machine.providers.explicitProviderDir")}),n.jsx("input",{type:"text",value:ae,onChange:Z=>be(Z.target.value),placeholder:a("machine.providers.providerDirPlaceholder"),className:"machine-input text-2xs"})]}),n.jsx("button",{onClick:()=>void me(),disabled:V,className:"machine-btn text-3xs bg-accent-primary/[0.08] border-accent-primary/20 text-accent-primary hover:bg-accent-primary/[0.14]",children:a(V?"machine.providers.applying":"machine.providers.applyReload")})]}),n.jsx("div",{className:"mt-3 flex flex-col gap-1.5","data-testid":"provider-source-paths",children:[{label:a("machine.providers.userRoot"),value:P==null?void 0:P.userDir},{label:a("machine.providers.upstreamRoot"),value:P==null?void 0:P.upstreamDir},{label:a("machine.providers.providerRoots"),value:(oe=P==null?void 0:P.providerRoots)==null?void 0:oe.join(" → ")}].map(Z=>n.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 text-3xs",children:[n.jsx("span",{className:"shrink-0 font-medium text-text-secondary",children:Z.label}),n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx("span",{className:"min-w-0 truncate font-mono text-text-muted",title:Z.value||void 0,children:Z.value||"—"}),Z.value&&n.jsx(zg,{value:Z.value,label:a("common.copy")})]})]},Z.label))})]}),O&&ne.length===0?n.jsx("div",{className:"p-10 text-center text-text-muted",children:a("machine.providers.loadingSettings")}):fe.length===0?n.jsx(wn,{padding:"none",className:"px-4.5 py-8 text-center",children:n.jsx("div",{className:"text-xs text-text-muted",children:B==="all"?a("machine.providers.noProviders"):a("machine.providers.noFilteredProviders",{filter:B.toUpperCase()})})}):n.jsx("div",{className:"flex flex-col gap-1.5",children:fe.map(Z=>n.jsx(pR,{quota:r==null?void 0:r[Z.type],prov:Z,providerInfo:t.find(se=>se.type===Z.type),savingKey:N,onSetSetting:Se,onEnableToggle:he,onDetect:Ee,onResetCommand:Y,quotaAccountLabelEnabled:Yh.has(Z.type)?d:void 0,onQuotaAccountLabelToggle:Yh.has(Z.type)?je:void 0,quotaEnabled:ya.has(Z.type)?m[Z.type]??!0:void 0,onQuotaToggle:ya.has(Z.type)?z:void 0,pin:p[Z.type],onUpdate:()=>Je(Z.type),updating:_[Z.type]===!0,onRollbackUpdate:()=>Le(Z.type),showAdvanced:Q},Z.type))}),F&&n.jsx(nR,{providerType:F,displayName:((Ie=ne.find(Z=>Z.type===F))==null?void 0:Ie.displayName)||F,supportsQuota:ya.has(F),quotaInstallsClaudeStatusline:F==="claude-cli",onCancel:()=>q(null),onConfirm:Z=>{pe(F,Z)}})]})}const yR=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function vR({count:e,since:t,category:s}){return{count:e,since:t,...s==="all"?{}:{category:s}}}function wR(e,t){return t==="all"?e:e.filter(s=>s.category===t)}function SR(e){return e.trim().toLowerCase()}function zi(e,t){const s=SR(t);return s?e.some(r=>String(r??"").toLowerCase().includes(s)):!0}function cu(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Er(e,t=220){const s=cu(e);return s?s.length>t?`${s.slice(0,t)}…`:s:""}function kR(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.map(s=>{const r=s;return{timestamp:Number(r.ts)||0,level:r.level||"info",message:`[${String(r.category||"daemon")}] ${String(r.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const s=t.trim();return{kind:s?"text":"empty",entries:[],rawText:s}}return{kind:"empty",entries:[],rawText:""}}function jR(e,t){return e.filter(s=>zi([s.level,s.message],t))}function Qh(e){return`${e.timestamp}:${e.level}:${e.message}`}function NR(e,t,s=300){if(t.entries.length>0){const r=new Map;for(const i of e.entries)r.set(Qh(i),i);for(const i of t.entries)r.set(Qh(i),i);const o=Array.from(r.values()).sort((i,c)=>i.timestamp-c.timestamp).slice(-s),a=o.reduce((i,c)=>Math.max(i,Number(c.timestamp||0)),e.lastTs);return{entries:o,kind:"structured",rawText:"",lastTs:a}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function CR(e,t,s=120){if(t.length===0)return e;const r=new Map;for(const o of e)r.set(o.id,o);for(const o of t)r.set(o.id,o);return Array.from(r.values()).sort((o,a)=>o.ts-a.ts).slice(-s)}function _R(e,t){return e.split(`
|
|
79
|
+
`).map(s=>s.trimEnd()).filter(Boolean).filter(s=>zi([s],t))}function AR(e,t){return e.filter(s=>zi([s.level,s.category,s.stage,s.interactionId,cu(s.payload)],t))}function TR(e,t){return e.filter(s=>zi([s.kind,s.topic,s.interactionId,cu(s.payload)],t))}function Jh(e){return e==="warn"||e==="error"}function IR({daemonLogs:e,daemonRawLines:t,trace:s,webEvents:r}){return{all:e.length+t.length+s.length+r.length,info:e.filter(o=>o.level!=="debug").length+s.filter(o=>o.level!=="debug").length+r.length,issues:e.filter(o=>Jh(o.level)).length+s.filter(o=>Jh(o.level)).length}}function MR({daemonLogs:e,daemonRawLines:t,trace:s,webEvents:r}){const o=[];return e.length>0?o.push(["[daemon logs]",...e.map(a=>`${new Date(a.timestamp).toISOString()} ${a.level.toUpperCase()} ${a.message}`)].join(`
|
|
80
|
+
`)):t.length>0&&o.push(["[daemon logs]",...t].join(`
|
|
81
|
+
`)),s.length>0&&o.push(["[trace]",...s.map(a=>`${new Date(a.ts).toISOString()} ${a.level.toUpperCase()} ${a.category}.${a.stage} ${Er(a.payload,500)}`.trim())].join(`
|
|
82
|
+
`)),r.length>0&&o.push(["[browser events]",...r.map(a=>`${new Date(a.ts).toISOString()} ${a.kind}${a.topic?` topic=${a.topic}`:""} ${Er(a.payload,500)}`.trim())].join(`
|
|
83
|
+
`)),o.join(`
|
|
84
|
+
|
|
85
|
+
`)}function RR({machineId:e,sendDaemonCommand:t}){const[s,r]=l.useState([]),[o,a]=l.useState("empty"),[i,c]=l.useState(""),[d,u]=l.useState([]),[m,h]=l.useState([]),[p,g]=l.useState(null),[f,x]=l.useState(!0),[b,k]=l.useState("info"),[j,v]=l.useState("all"),[_,y]=l.useState(!0),[w,S]=l.useState(!0),[C,A]=l.useState(""),[O,L]=l.useState(""),[M,$]=l.useState(0),N=l.useRef(0),I=l.useRef(0),B=l.useRef(0),T=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),F=l.useRef([]),q=l.useCallback(()=>{const W={entries:[],kind:"empty",rawText:"",lastTs:0};T.current=W,I.current=0,r([]),c(""),a("empty"),y(!0)},[]),Q=l.useCallback(()=>{F.current=[],B.current=0,u([]),S(!0)},[]),K=l.useCallback(W=>{W!==b&&(q(),k(W))},[b,q]),R=l.useCallback(W=>{v(U=>U===W?U:W)},[]),D=l.useCallback(()=>{q(),Q(),h([]),g(null),A(""),L(""),Xs.clear()},[q,Q]),P=l.useCallback(()=>{$(W=>W+1)},[]),H=l.useCallback(async()=>{if(!e)return;const W=N.current+1;N.current=W;const U=I.current,ae=B.current,[be,V]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:b,since:U}),t(e,"get_debug_trace",vR({count:120,since:ae,category:j}))]);if(N.current===W){if(be.status==="fulfilled"){const we=be.value,ce=(we==null?void 0:we.result)||we,de=kR(ce),ne=NR(T.current,de,300);T.current=ne,I.current=ne.lastTs,y(!1),A((we==null?void 0:we.success)===!1?String((we==null?void 0:we.error)||"Could not load daemon logs"):""),a(ne.kind),c(ne.rawText),r(ne.entries)}else y(!1),A(be.reason instanceof Error?be.reason.message:"Could not load daemon logs");if(V.status==="fulfilled"){const we=V.value,ce=(we==null?void 0:we.result)||we;if((we==null?void 0:we.success)===!1)L(String((we==null?void 0:we.error)||"Could not load daemon trace"));else if(Array.isArray(ce==null?void 0:ce.trace)){const de=ce.trace,ne=CR(F.current,de,120),ee=de.reduce((ue,je)=>Math.max(ue,Number(je.ts||0)),ae);F.current=ne,ee>ae&&(B.current=ee),L(""),u(ne)}else L("");S(!1)}else S(!1),L(V.reason instanceof Error?V.reason.message:"Could not load daemon trace");h(Xs.list({limit:120})),g(Date.now())}},[b,e,t,j]);return l.useEffect(()=>{Q()},[Q,j]),l.useEffect(()=>{N.current+=1,q(),Q(),h([]),g(null),A(""),L("")},[e,q,Q]),l.useEffect(()=>{if(!e)return;if(H(),!f)return()=>{N.current+=1};const W=setInterval(()=>{H()},3e3);return()=>{N.current+=1,clearInterval(W)}},[f,H,e,M]),{daemonLogs:s,daemonLogKind:o,daemonRawText:i,debugTrace:d,webEvents:m,lastUpdatedAt:p,autoRefresh:f,logLevel:b,traceCategory:j,daemonLoading:_,traceLoading:w,daemonFetchError:C,traceFetchError:O,setAutoRefresh:x,setLogLevel:K,setTraceCategory:R,refresh:P,clear:D}}function PR({daemonLoading:e,traceLoading:t,daemonFetchError:s,traceFetchError:r,daemonLogKind:o,daemonLogsCount:a,daemonRawLineCount:i,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:s?"error":e?"loading":a>0||i>0?"ok":"empty",detail:s||(o==="text"?`${i} raw file-fallback line(s)`:`${a} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:r?"error":t?"loading":c>0?"ok":"empty",detail:r||`${c} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function Xh(e){return e==="warn"||e==="error"}function LR(e){const t=e.toLowerCase();return/\[(err|error)\]/i.test(e)||t.includes(" error ")||t.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||t.includes(" warning ")||t.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function ER(e,t){const s=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(s){const r=Date.parse(s[0]);if(Number.isFinite(r))return r}return Number.MAX_SAFE_INTEGER-1e5+t}function Zh(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function DR(e){const t=Er(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function OR(e){const t=Er(e.payload,320),s=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${s} ${t}`:`${e.kind}${s}`}function $R({daemonLogs:e,daemonRawLines:t,trace:s,webEvents:r}){const o=[];return e.forEach((a,i)=>{o.push({id:`daemon-log-${a.timestamp}-${i}`,source:"daemon_log",ts:Number(a.timestamp||0),severity:a.level,message:a.message,raw:a.message})}),r.forEach(a=>{o.push({id:`browser-event-${a.id}`,source:"browser_event",ts:Number(a.ts||0),severity:"info",message:OR(a),topic:a.topic,interactionId:a.interactionId,payload:a.payload})}),s.forEach(a=>{o.push({id:`daemon-trace-${a.id}`,source:"daemon_trace",ts:Number(a.ts||0),severity:a.level,message:DR(a),category:a.category,stage:a.stage,interactionId:a.interactionId,payload:a.payload})}),t.forEach((a,i)=>{o.push({id:`raw-file-${i}`,source:"raw_file",ts:ER(a,i),severity:LR(a),message:a,raw:a})}),o.sort((a,i)=>a.ts!==i.ts?a.ts-i.ts:Zh(a.source)-Zh(i.source))}function FR(e){return`${e.source}:${e.severity}:${e.message}`}function HR(e){const t=e.filter(r=>Xh(r.severity)).sort((r,o)=>o.ts-r.ts),s=new Map;for(const r of e){if(!Xh(r.severity))continue;const o=FR(r),a=s.get(o);a?(a.count+=1,a.firstTs=Math.min(a.firstTs,r.ts),a.lastTs=Math.max(a.lastTs,r.ts)):s.set(o,{key:o,source:r.source,severity:r.severity,message:r.message,count:1,firstTs:r.ts,lastTs:r.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(s.values()).filter(r=>r.count>1).sort((r,o)=>o.count!==r.count?o.count-r.count:o.lastTs-r.lastTs).slice(0,5)}}function BR(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function ep(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",s=e.interactionId?` ix=${e.interactionId}`:"";return`${BR(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${s} ${e.message}`.trim()}function WR({events:e,summary:t,sources:s,maxTimelineEvents:r=80}){const o=[];o.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
86
|
+
`)),o.push(["[source status]",...s.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
|
|
87
|
+
`)),t.latestIssue&&o.push(["[latest issue]",ep(t.latestIssue)].join(`
|
|
88
|
+
`)),t.repeatedPatterns.length>0&&o.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
|
|
89
|
+
`));const a=e.slice(-r);return o.push(["[timeline]",...a.length>0?a.map(ep):["No diagnostic events captured."]].join(`
|
|
90
|
+
`)),o.join(`
|
|
91
|
+
|
|
92
|
+
`)}function UR(e,t){return t==="issues"?e.filter(s=>s.level==="warn"||s.level==="error"):t==="info"?e.filter(s=>s.level!=="debug"):e}function KR(e,t){return t==="issues"?e.filter(s=>s.level==="warn"||s.level==="error"):t==="info"?e.filter(s=>s.level!=="debug"):e}function qR({daemonLogs:e,daemonRawText:t,daemonLogKind:s,debugTrace:r,webEvents:o,traceCategory:a,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:u,daemonFetchError:m,traceFetchError:h}){const p=wR(r,a),g=jR(e,c),f=_R(t,c),x=AR(p,c),b=TR(o,c),k=UR(g,i),j=i==="all"?f:[],v=KR(x,i),_=i==="issues"?[]:b,y=IR({daemonLogs:g,daemonRawLines:f,trace:x,webEvents:b}),w=$R({daemonLogs:k,daemonRawLines:j,trace:v,webEvents:_}),S=HR(w),C=PR({daemonLoading:d,traceLoading:u,daemonFetchError:m,traceFetchError:h,daemonLogKind:s,daemonLogsCount:g.length,daemonRawLineCount:f.length,traceCount:x.length,webEventCount:b.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:f,filteredTraceEntries:x,filteredWebEvents:b,visibleDaemonLogs:k,visibleDaemonRawLines:j,visibleTraceEntries:v,visibleWebEvents:_,quickFilterCounts:y,diagnosticEvents:w,diagnosticsSummary:S,sourceStates:C}}function zR(e,t){return e?ki(e,{seconds:!0}):t("machine.logsTabSections.notYetLoaded")}function px(e,t){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?t("machine.logsTabSections.rawFile"):ki(e,{seconds:!0})}function zc(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function Hl(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function du(e,t){return t(e==="daemon_log"?"machine.logsTabSections.sourceDaemon":e==="daemon_trace"?"machine.logsTabSections.sourceTrace":e==="browser_event"?"machine.logsTabSections.sourceBrowser":"machine.logsTabSections.rawFile")}function GR({event:e}){const{t}=ve("common");return n.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${zc(e.severity)}`,children:[n.jsxs("div",{className:"flex gap-2 text-3xs text-text-muted flex-wrap",children:[n.jsx("span",{children:px(e.ts,t)}),n.jsx("span",{children:e.severity.toUpperCase()}),n.jsx("span",{children:du(e.source,t)}),e.category&&e.stage&&n.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&n.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&n.jsxs("span",{children:["ix=",e.interactionId]})]}),n.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function VR({quickFilter:e,quickFilterCounts:t,searchQuery:s,autoRefresh:r,onQuickFilterChange:o,onSearchQueryChange:a,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:u,onClear:m}){const{t:h}=ve("common");return n.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx("span",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mr-1",children:h("machine.logsTabSections.view")}),n.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:h("machine.logsTabSections.filterInfo",{count:t.info})},{id:"issues",label:h("machine.logsTabSections.filterIssues",{count:t.issues})},{id:"all",label:h("machine.logsTabSections.filterAll",{count:t.all})}].map(p=>n.jsx("button",{type:"button",onClick:()=>o(p.id),className:`rounded-md px-2.5 py-1 text-2xs transition-colors ${e===p.id?"bg-accent-primary/15 text-accent-primary border border-accent-primary/30":"text-text-secondary hover:text-text-primary"}`,children:p.label},p.id))}),n.jsx("input",{value:s,onChange:p=>a(p.target.value),placeholder:h("machine.logsTabSections.searchPlaceholder"),className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-primary placeholder:text-text-muted"})]}),n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx("button",{onClick:i,className:"machine-btn",children:h("machine.logsTabSections.copyDiagnostics")}),n.jsx("button",{onClick:c,className:"machine-btn",children:h("machine.logsTabSections.copyVisible")}),n.jsx("button",{onClick:d,className:`machine-btn ${r?"text-green-500 border-green-500/30":""}`,children:h(r?"machine.logsTabSections.pause":"machine.logsTabSections.resume")}),n.jsx("button",{onClick:u,className:"machine-btn",children:h("machine.logsTabSections.refresh")}),n.jsx("button",{onClick:m,className:"machine-btn",children:h("machine.logsTabSections.clear")})]})]})}function YR({logLevel:e,traceCategory:t,onLogLevelChange:s,onTraceCategoryChange:r}){const{t:o}=ve("common");return n.jsx(wn,{padding:"sm",children:n.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx("span",{className:"text-3xs uppercase tracking-wider text-text-muted font-semibold",children:o("machine.logsTabSections.advancedSourceScope")}),["debug","info","warn","error"].map(a=>n.jsx("button",{onClick:()=>s(a),className:`machine-btn text-3xs px-2 py-0.5 ${e===a?"bg-accent-primary/15 border-accent-primary/40 text-accent-primary":""}`,children:o("machine.logsTabSections.daemonLevelPlus",{level:a.toUpperCase()})},a))]}),n.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:yR.map(a=>n.jsx("button",{onClick:()=>r(a.value),className:`machine-btn text-3xs px-2 py-0.5 ${t===a.value?"bg-accent-primary/15 border-accent-primary/40 text-accent-primary":""}`,children:a.label},a.value))})]})})}function QR({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:s,searchQuery:r,lastUpdatedAt:o,autoRefresh:a,daemonFetchError:i,traceFetchError:c}){var h,p;const{t:d}=ve("common"),u=((h=e.latestIssue)==null?void 0:h.severity)==="error"?"danger":((p=e.latestIssue)==null?void 0:p.severity)==="warn"?"warning":"good",m=i||c?"danger":a?"good":"neutral";return n.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[n.jsxs("div",{className:`rounded-xl border p-3 ${Hl(e.issueCount>0?"warning":"good")}`,children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted mb-2",children:d("machine.logsTabSections.diagnosticsTimeline")}),n.jsx("div",{className:"text-xxs text-text-primary font-medium",children:d("machine.logsTabSections.visibleEventsIssues",{events:t,issues:e.issueCount})}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:r.trim()?d("machine.logsTabSections.filteredBy",{query:r.trim()}):d("machine.logsTabSections.mergedByTime")})]}),n.jsxs("div",{className:`rounded-xl border p-3 ${Hl(u)}`,children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted mb-2",children:d("machine.logsTabSections.latestIssue")}),e.latestIssue?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"text-xxs text-text-primary font-medium",children:[du(e.latestIssue.source,d)," · ",e.latestIssue.severity.toUpperCase()]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),n.jsx("div",{className:"text-3xs text-text-muted mt-2",children:px(e.latestIssue.ts,d)})]}):n.jsx(n.Fragment,{children:n.jsx("div",{className:"text-xxs text-text-primary font-medium",children:d("machine.logsTabSections.noVisibleIssue")})})]}),n.jsxs("div",{className:`rounded-xl border p-3 ${Hl(m)}`,children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted mb-2",children:d("machine.logsTabSections.sourceStatus")}),n.jsx("div",{className:"text-xxs text-text-primary font-medium",children:d(i||c?"machine.logsTabSections.needsAttention":a?"machine.logsTabSections.livePolling":"machine.logsTabSections.paused")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:d("machine.logsTabSections.lastUpdate",{time:zR(o,d)})}),n.jsx("div",{className:"text-3xs text-text-muted mt-2 space-y-1",children:s.map(g=>n.jsxs("div",{children:[g.label,": ",g.status]},g.id))})]})]})}function JR({patterns:e}){const{t}=ve("common");return e.length===0?null:n.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted mb-2",children:t("machine.logsTabSections.repeatedIssuePatterns")}),n.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(s=>n.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[n.jsxs("div",{className:"text-xs text-text-primary font-medium",children:[s.count,"× ",s.severity.toUpperCase()," · ",du(s.source,t)]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1 line-clamp-2",children:s.message})]},s.key))})]})}function XR({streams:e,sectionsOpen:t,setSectionsOpen:s,diagnosticEvents:r,visibleDaemonLogs:o,visibleDaemonRawLines:a,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:d,searchQuery:u}){const{t:m}=ve("common");return n.jsxs("div",{className:"grid gap-3",children:[n.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(h=>({...h,timeline:!h.timeline})),children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted",children:m("machine.logsTabSections.unifiedTimeline")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:m("machine.logsTabSections.visibleDiagnosticEvents",{count:r.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.timeline?m("machine.logsTabSections.hide"):m("machine.logsTabSections.show")})]}),t.timeline&&n.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-2xs leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.loadingDiagnostics")}),(e.daemonFetchError||e.traceFetchError)&&r.length===0&&n.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&n.jsx("div",{children:m("machine.logsTabSections.daemonLogsError",{error:e.daemonFetchError})}),e.traceFetchError&&n.jsx("div",{children:m("machine.logsTabSections.daemonTraceError",{error:e.traceFetchError})})]}),!e.daemonLoading&&!e.traceLoading&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.noDiagnosticsMatch")}),r.map(h=>n.jsx(GR,{event:h},h.id))]})]}),n.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(h=>({...h,daemon:!h.daemon})),children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted",children:m("machine.logsTabSections.rawSourceDaemonLogs")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:e.daemonLogKind==="text"?m("machine.logsTabSections.visibleRawLinesFallback",{count:a.length}):m("machine.logsTabSections.visibleStructuredLines",{count:o.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.daemon?m("machine.logsTabSections.hide"):m("machine.logsTabSections.show")})]}),t.daemon&&n.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-2xs leading-relaxed",children:[e.daemonLoading&&o.length===0&&a.length===0&&!e.daemonFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.loadingDaemonLogs")}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&n.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.noDaemonLogsYet")}),e.daemonLogKind==="text"&&a.length===0&&e.daemonRawText&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m(d==="all"?"machine.logsTabSections.noRawLinesMatchSearch":"machine.logsTabSections.rawFallbackOnlyInAll")}),e.daemonLogKind==="structured"&&o.length===0&&e.daemonLogs.length>0&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.noStructuredLogsMatch")}),e.daemonLogKind==="text"&&a.map((h,p)=>n.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:h},`raw-${p}`)),e.daemonLogKind!=="text"&&o.map((h,p)=>n.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${zc(h.level)}`,children:[n.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(h.timestamp).toLocaleTimeString()}),n.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-4xs",children:h.level==="error"?"ERR":h.level==="warn"?"WRN":h.level==="debug"?"DBG":"INF"}),n.jsx("span",{className:"break-words",children:h.message})]},`log-${p}`))]})]}),n.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(h=>({...h,trace:!h.trace})),children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-3xs uppercase tracking-wider text-text-muted",children:[m("machine.logsTabSections.rawSourceDaemonTrace"),e.traceCategory==="session_host"?` · ${m("machine.logsTabSections.sessionHostOnly")}`:""]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:m("machine.logsTabSections.visibleTraceEvents",{count:i.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.trace?m("machine.logsTabSections.hide"):m("machine.logsTabSections.show")})]}),t.trace&&n.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-2xs leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.loadingDaemonTrace")}),!e.traceLoading&&e.traceFetchError&&i.length===0&&n.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:u.trim()?m("machine.logsTabSections.noTraceEntriesMatchSearch"):e.traceCategory==="session_host"?m("machine.logsTabSections.noSessionHostTraceYet"):m("machine.logsTabSections.noTraceEntriesYet")}),i.map(h=>n.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${zc(h.level)}`,children:[n.jsxs("div",{className:"flex gap-2 text-3xs text-text-muted flex-wrap",children:[n.jsx("span",{children:new Date(h.ts).toLocaleTimeString()}),n.jsx("span",{children:h.level.toUpperCase()}),n.jsxs("span",{children:[h.category,".",h.stage]}),h.interactionId&&n.jsxs("span",{children:["ix=",h.interactionId]})]}),n.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Er(h.payload,360)||m("machine.logsTabSections.noPayload")})]},h.id))]})]}),n.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(h=>({...h,web:!h.web})),children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted",children:m("machine.logsTabSections.rawSourceBrowserEvents")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:m("machine.logsTabSections.visibleBrowserEvents",{count:c.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.web?m("machine.logsTabSections.hide"):m("machine.logsTabSections.show")})]}),t.web&&n.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-2xs leading-relaxed",children:[c.length===0&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:u.trim()?m("machine.logsTabSections.noBrowserEventsMatchSearch"):m("machine.logsTabSections.noBrowserEventsYet")}),c.map(h=>n.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[n.jsxs("div",{className:"flex gap-2 text-3xs text-text-muted flex-wrap",children:[n.jsx("span",{children:new Date(h.ts).toLocaleTimeString()}),n.jsx("span",{children:h.kind}),h.topic&&n.jsxs("span",{children:["topic=",h.topic]}),h.interactionId&&n.jsxs("span",{children:["ix=",h.interactionId]})]}),n.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Er(h.payload,360)||m("machine.logsTabSections.noPayload")})]},h.id))]})]})]})}function ZR({machineId:e,sendDaemonCommand:t}){const s=RR({machineId:e,sendDaemonCommand:t}),[r,o]=l.useState("info"),[a,i]=l.useState(""),[c,d]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),u=l.useRef(null),m=l.useRef(!1),h=l.useMemo(()=>qR({daemonLogs:s.daemonLogs,daemonRawText:s.daemonRawText,daemonLogKind:s.daemonLogKind,debugTrace:s.debugTrace,webEvents:s.webEvents,traceCategory:s.traceCategory,quickFilter:r,searchQuery:a,daemonLoading:s.daemonLoading,traceLoading:s.traceLoading,daemonFetchError:s.daemonFetchError,traceFetchError:s.traceFetchError}),[r,a,s.daemonFetchError,s.daemonLoading,s.daemonLogKind,s.daemonLogs,s.daemonRawText,s.debugTrace,s.traceCategory,s.traceFetchError,s.traceLoading,s.webEvents]);l.useEffect(()=>{if(s.autoRefresh&&h.diagnosticEvents.length>0){const f=m.current?"smooth":"instant";setTimeout(()=>{var x;(x=u.current)==null||x.scrollIntoView({behavior:f}),m.current=!0},50)}},[h.diagnosticEvents.length,s.autoRefresh]);const p=l.useCallback(async()=>{var x;const f=MR({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!f.trim()){ct.showToast("No visible logs to copy.","info");return}try{await((x=navigator.clipboard)==null?void 0:x.writeText(f)),ct.showToast("Copied visible logs to clipboard.","success")}catch(b){ct.showToast(b instanceof Error?b.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),g=l.useCallback(async()=>{var x;const f=WR({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((x=navigator.clipboard)==null?void 0:x.writeText(f)),ct.showToast("Copied diagnostic bundle to clipboard.","success")}catch(b){ct.showToast(b instanceof Error?b.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return n.jsxs("div",{className:"space-y-4",children:[n.jsx(VR,{quickFilter:r,quickFilterCounts:h.quickFilterCounts,searchQuery:a,autoRefresh:s.autoRefresh,onQuickFilterChange:o,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{p()},onToggleAutoRefresh:()=>s.setAutoRefresh(f=>!f),onRefresh:s.refresh,onClear:s.clear}),n.jsx(YR,{logLevel:s.logLevel,traceCategory:s.traceCategory,onLogLevelChange:s.setLogLevel,onTraceCategoryChange:s.setTraceCategory}),n.jsx(QR,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:a,lastUpdatedAt:s.lastUpdatedAt,autoRefresh:s.autoRefresh,daemonFetchError:s.daemonFetchError,traceFetchError:s.traceFetchError}),n.jsx(JR,{patterns:h.diagnosticsSummary.repeatedPatterns}),n.jsx(XR,{streams:s,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:r,searchQuery:a}),n.jsx("div",{ref:u})]})}function eP(e){const{t}=e;return e.diagnostics?{label:t?t("sessionHostSurface.managed"):"Managed",toneClass:"bg-green-500/[0.08] text-green-500"}:e.loading||e.refreshing?{label:t?t("sessionHostSurface.checking"):"Checking…",toneClass:"bg-sky-500/[0.08] text-sky-400"}:e.error?{label:t?t("sessionHostSurface.diagnosticsIssue"):"Diagnostics issue",toneClass:"bg-amber-500/[0.08] text-amber-400"}:{label:t?t("sessionHostSurface.unavailable"):"Unavailable",toneClass:"bg-red-500/[0.08] text-red-400"}}function fx(e,t){const s=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return s?s==="auto_resumed"?t?t("sessionHostSurface.restoredAfterRestart"):"restored after restart":s==="resume_failed"?t?t("sessionHostSurface.restoreFailed"):"restore failed":s==="host_restart_interrupted"?t?t("sessionHostSurface.hostRestartInterrupted"):"host restart interrupted":s==="orphan_snapshot"?t?t("sessionHostSurface.snapshotRecovered"):"snapshot recovered":s.replace(/_/g," "):null}function tP(e){var o;const t=[],s=[],r=[];for(const a of e||[]){const i=String((a==null?void 0:a.lifecycle)||"").trim(),c=fx((a==null?void 0:a.meta)||void 0),d=((o=a==null?void 0:a.meta)==null?void 0:o.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(a):(i==="stopped"||i==="failed")&&(d||c)?s.push(a):r.push(a)}return{liveRuntimes:t,recoverySnapshots:s,inactiveRecords:r}}function nP(e,t){return e==="live"?t?t("sessionHostSurface.attach"):"Attach":e==="recovery"?t?t("sessionHostSurface.recover"):"Recover":t?t("sessionHostSurface.restart"):"Restart"}function Bl(e,t){return e==="live"?t?t("sessionHostSurface.hintLive"):"These runtimes are live now and are the only attachable targets.":e==="recovery"?t?t("sessionHostSurface.hintRecovery"):"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":t?t("sessionHostSurface.hintInactive"):"These inactive records are shown for reference and usually need restart before they are useful again."}const sP={starting:"sessionHostSurface.lifecycleStarting",running:"sessionHostSurface.lifecycleRunning",stopping:"sessionHostSurface.lifecycleStopping",stopped:"sessionHostSurface.lifecycleStopped",failed:"sessionHostSurface.lifecycleFailed",interrupted:"sessionHostSurface.lifecycleInterrupted"},rP={starting:"Starting",running:"Running",stopping:"Stopping",stopped:"Stopped",failed:"Failed",interrupted:"Interrupted"};function tp(e,t){const s=sP[e];return s?t?t(s):rP[e]??e:e}function Wl(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Ul(e){return ki(e,{seconds:!0})||"—"}function np(e){return Ka(e)||"—"}function oP(e,t){const s=String(e||"").replace(/^session_host_/,"").replace(/_session$/,"");return["resume","restart","stop","start","attach","detach","recover"].includes(s)?t(`sessionHost.transition.${s}`):s.replace(/_/g," ")}function aP(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function iP(e){switch(e){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-bg-glass text-text-muted"}}function lP(e){var s;const t=new Map;for(const r of e){if(!["starting","running","stopping","interrupted"].includes(r.lifecycle))continue;const o=typeof((s=r.meta)==null?void 0:s.providerSessionId)=="string"?String(r.meta.providerSessionId).trim():"";if(!o)continue;const a=`${r.providerType}::${r.workspace}::${o}`;t.set(a,(t.get(a)||0)+1)}return Array.from(t.values()).filter(r=>r>1).length}function cP({machineId:e,cliSessions:t,sendDaemonCommand:s}){const{t:r}=ve("common"),[o,a]=l.useState(""),[i,c]=l.useState(null),{confirm:d,confirmDialog:u}=Fr(),[m,h]=l.useState(!1),p=DT(e,{enabled:!!e,includeSessions:!0,limit:xm,intervalMs:hC}),g=p.diagnostics,f=p.loading,x=p.applyDiagnostics,b=l.useMemo(()=>eP({diagnostics:g,loading:f,refreshing:m,error:o,t:r}),[g,f,m,o,r]),k=l.useMemo(()=>new Map(t.map(N=>[N.sessionId||N.id,N])),[t]),j=l.useCallback(async()=>{if(e){h(!0);try{const N=await s(e,"session_host_get_diagnostics",{includeSessions:!0,limit:xm}),I=Wl(N);if(!(I!=null&&I.success))throw new Error((I==null?void 0:I.error)||r("sessionHost.diagnosticsFailed"));x(I.diagnostics||I.result||null),a("")}catch(N){const I=N instanceof Error?N.message:r("sessionHost.diagnosticsFailed");a(I)}finally{h(!1)}}},[x,e,s,r]);l.useEffect(()=>{!e||g||f||m||j()},[g,f,e,j,m]);const v=l.useCallback(async(N,I)=>{const B=`${N}:${I.sessionId}`;if(!(N==="session_host_stop_session"&&!await d({title:r("sessionHost.stopConfirmTitle",{name:I.displayName}),description:r("sessionHost.stopConfirmDescription"),confirmLabel:r("sessionHost.stop"),tone:"danger"}))){c(B);try{const T=await s(e,N,{sessionId:I.sessionId}),F=Wl(T);if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.error)||r("sessionHost.actionFailed"));const q=N==="session_host_resume_session"?"sessionHost.toastResumed":N==="session_host_restart_session"?"sessionHost.toastRestarted":"sessionHost.toastStopped";ct.showToast(r(q,{name:I.displayName}),"success"),await j()}catch(T){const F=T instanceof Error?T.message:r("sessionHost.actionFailed");ct.showToast(F,"warning"),a(F)}finally{c(T=>T===B?null:T)}}},[d,e,j,s,r]),_=l.useCallback(async()=>{if(await d({title:r("sessionHost.pruneConfirmTitle"),description:r("sessionHost.pruneConfirmDescription"),confirmLabel:r("sessionHost.prune"),tone:"danger"})){c("session_host_prune_duplicate_sessions");try{const I=await s(e,"session_host_prune_duplicate_sessions",{}),B=Wl(I);if(!(B!=null&&B.success))throw new Error((B==null?void 0:B.error)||r("sessionHost.pruneFailed"));const T=B.result||{},F=Array.isArray(T.prunedSessionIds)?T.prunedSessionIds.length:0,q=typeof T.duplicateGroupCount=="number"?T.duplicateGroupCount:0;ct.showToast(r("sessionHost.toastPruned",{pruned:F,groups:q}),"success"),await j()}catch(I){const B=I instanceof Error?I.message:r("sessionHost.pruneFailed");ct.showToast(B,"warning"),a(B)}finally{c(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[d,e,j,s,r]),y=l.useMemo(()=>[...(g==null?void 0:g.sessions)||[]].sort((N,I)=>(I.lastActivityAt||0)-(N.lastActivityAt||0)),[g==null?void 0:g.sessions]),w=l.useMemo(()=>g!=null&&g.liveRuntimes||g!=null&&g.recoverySnapshots||g!=null&&g.inactiveRecords?{liveRuntimes:(g==null?void 0:g.liveRuntimes)||[],recoverySnapshots:(g==null?void 0:g.recoverySnapshots)||[],inactiveRecords:(g==null?void 0:g.inactiveRecords)||[]}:tP(y),[g==null?void 0:g.inactiveRecords,g==null?void 0:g.liveRuntimes,g==null?void 0:g.recoverySnapshots,y]),S=w.liveRuntimes,C=w.recoverySnapshots,A=w.inactiveRecords,O=l.useMemo(()=>lP(S),[S]),L=l.useMemo(()=>[...(g==null?void 0:g.recentTransitions)||[]].slice(-6).reverse(),[g==null?void 0:g.recentTransitions]),M=l.useMemo(()=>[...(g==null?void 0:g.recentLogs)||[]].reverse().find(N=>N.level==="warn"||N.level==="error")||null,[g==null?void 0:g.recentLogs]),$=(N,I)=>{var W;const B=i===`session_host_resume_session:${N.sessionId}`,T=i===`session_host_restart_session:${N.sessionId}`,F=i===`session_host_stop_session:${N.sessionId}`,q=fx(N.meta,r),Q=k.get(N.sessionId),K=r("sessionHost.clientsCount",{count:N.attachedClients.length}),R=r(I==="recovery"?"sessionHost.recover":"sessionHost.resume"),D=r(I==="recovery"?"sessionHost.recovering":"sessionHost.resuming"),P=nP(I,r),H=tp(N.lifecycle,r);return n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("div",{className:"font-medium text-xxs text-text-primary",children:N.displayName||(Q==null?void 0:Q.cliName)||N.providerType}),n.jsx("span",{className:`px-2 py-0.5 rounded-md text-3xs font-semibold ${iP(N.lifecycle)}`,children:H}),q&&n.jsx("span",{className:"px-2 py-0.5 rounded-md text-3xs font-semibold bg-sky-500/[0.08] text-sky-300",children:q})]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1 flex flex-wrap gap-2",children:n.jsx(tn,{content:[N.runtimeKey,N.osPid?`pid ${N.osPid}`:""].filter(Boolean).join(" · "),children:n.jsx("span",{className:"text-text-primary/90",children:N.workspaceLabel||(Q==null?void 0:Q.runtimeWorkspaceLabel)||N.workspace||r("sessionHost.noWorkspace")})})}),n.jsxs("div",{className:"text-3xs text-text-secondary mt-1 flex flex-wrap gap-2",children:[n.jsx("span",{className:((W=N.writeOwner)==null?void 0:W.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:aP(N.writeOwner)}),n.jsx("span",{className:"text-text-muted",children:"·"}),n.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[n.jsx(cw,{size:11})," ",K]}),n.jsx("span",{className:"text-text-muted",children:"·"}),n.jsx("span",{className:"text-text-primary/85",children:r("sessionHost.activeAgo",{time:np(N.lastActivityAt)})}),n.jsx("span",{className:"text-text-muted",children:"·"}),n.jsx("span",{className:"text-sky-200",children:r("sessionHost.nextAction",{action:P})})]})]}),n.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[I==="recovery"&&(N.lifecycle==="interrupted"||N.lifecycle==="failed"||N.lifecycle==="stopped")&&n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1",disabled:!!i,onClick:()=>{v("session_host_resume_session",N)},children:B?D:R}),n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1",disabled:!!i,onClick:()=>{v("session_host_restart_session",N)},children:r(T?"sessionHost.restarting":"sessionHost.restart")}),I==="live"&&(N.lifecycle==="running"||N.lifecycle==="starting"||N.lifecycle==="interrupted")&&n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{v("session_host_stop_session",N)},children:r(F?"sessionHost.stopping":"sessionHost.stop")})]})]})},N.sessionId)};return n.jsxs(wn,{padding:"lg",className:"mb-5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[n.jsx(Tr,{size:14})," ",r("sessionHost.title")]}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:gA()})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[O>0&&n.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{_()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?r("sessionHost.pruning"):r("sessionHost.pruneDuplicatesCount",{count:O})}),n.jsx("span",{className:`px-2 py-1 rounded-md text-3xs font-semibold ${b.toneClass}`,children:b.label}),n.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{j()},disabled:f||m,children:[n.jsx($r,{size:13}),r(f||m?"sessionHost.refreshing":"sessionHost.refresh")]})]})]}),o&&!g&&n.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-xs text-amber-200 mb-3",children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(an,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),n.jsxs("div",{children:[n.jsx("div",{className:"font-medium text-amber-100",children:r("sessionHost.diagnosticsAttention")}),n.jsx("div",{className:"text-amber-200/90 mt-1",children:o})]})]})}),g&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-secondary",children:r("sessionHost.statLive")}),n.jsx("div",{className:"text-lg font-semibold text-text-primary mt-1",children:g.runtimeCount})]}),n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-secondary",children:r("sessionHost.statRecovery")}),n.jsx("div",{className:"text-lg font-semibold text-text-primary mt-1",children:C.length})]}),n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-secondary",children:r("sessionHost.statRequests")}),n.jsx("div",{className:"text-lg font-semibold text-text-primary mt-1",children:g.recentRequests.length})]}),n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-secondary",children:r("sessionHost.statStarted")}),n.jsx("div",{className:"text-xs font-medium text-text-primary mt-1",children:np(g.hostStartedAt)}),n.jsx("div",{className:"text-3xs text-text-secondary mt-0.5",children:Ul(g.hostStartedAt)})]})]}),M&&n.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-2xs text-text-secondary mb-4",children:[n.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[n.jsx(an,{size:13})," ",r("sessionHost.latestWarning")]}),n.jsx("div",{className:"text-text-primary leading-relaxed",children:M.message}),n.jsxs("div",{className:"text-3xs text-text-secondary mt-1",children:[Ul(M.timestamp),M.sessionId?` · ${M.sessionId}`:""]})]}),n.jsxs("div",{className:"mb-4 space-y-4",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[n.jsx(pd,{size:14})," ",r("sessionHost.liveTitle")]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2.5",children:Bl("live",r)}),S.length===0?n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-xs text-text-secondary",children:r("sessionHost.liveEmpty")}):n.jsx("div",{className:"space-y-2",children:S.map(N=>$(N,"live"))})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[n.jsx(Tr,{size:14})," ",r("sessionHost.recoveryTitle")]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2.5",children:Bl("recovery",r)}),C.length===0?n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-xs text-text-secondary",children:r("sessionHost.recoveryEmpty")}):n.jsx("div",{className:"space-y-2",children:C.map(N=>$(N,"recovery"))})]}),A.length>0&&n.jsxs("div",{children:[n.jsx("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:r("sessionHost.inactiveTitle")}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2.5",children:Bl("inactive",r)}),n.jsx("div",{className:"space-y-2 opacity-85",children:A.map(N=>$(N,"inactive"))})]})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:r("sessionHost.recentActivity")}),L.length===0?n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-xs text-text-secondary",children:r("sessionHost.transitionsEmpty")}):n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:L.map(N=>{var B;const I=y.find(T=>T.sessionId===N.sessionId);return n.jsxs("div",{className:"px-3.5 py-2.5 text-2xs flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-text-primary font-medium",children:(I==null?void 0:I.displayName)||((B=k.get(N.sessionId))==null?void 0:B.cliName)||N.sessionId}),n.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[oP(N.action,r),N.lifecycle?` · ${tp(N.lifecycle,r)}`:"",(N.detail||N.error)&&n.jsx(dt,{content:[N.detail,N.error].filter(Boolean).join(`
|
|
93
|
+
`),size:11,className:"ml-1"})]})]}),n.jsx("div",{className:`shrink-0 text-3xs ${N.success===!1?"text-red-300":"text-text-secondary"}`,children:Ul(N.timestamp)})]},`${N.sessionId}:${N.timestamp}:${N.action}`)})})]}),n.jsx(Od,{className:"mt-3",rows:[{label:r("sessionHost.endpointLabel"),value:g.endpoint||null},{label:r("sessionHost.lastErrorLabel"),value:o||null,copyable:!1}]})]}),u]})}function dP({machine:e,launchPick:t,actions:s}){const{t:r}=ve("common"),{runLaunchCliCore:o,setLaunchPick:a}=s;return l.useEffect(()=>{const i=c=>{c.key==="Escape"&&a(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[a]),n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",onClick:()=>a(null),children:n.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",onClick:i=>i.stopPropagation(),children:[n.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:r("machine.launchPick.title")}),n.jsx("p",{className:"text-2xs text-text-muted m-0 mb-4",children:r("machine.launchPick.description")}),n.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?n.jsx("span",{className:"text-2xs text-text-muted",children:r("machine.launchPick.empty")}):(e.workspaces||[]).map(i=>n.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-accent-primary/10 transition-colors",onClick:()=>{a(null),o({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[n.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),n.jsx("span",{className:"text-3xs text-text-muted font-mono truncate block",children:i.path})]},i.id))}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsx("button",{type:"button",className:"machine-btn text-2xs flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),o({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.defaultWorkspace")}),n.jsx("button",{type:"button",className:"machine-btn text-2xs flex-1 min-w-[120px]",onClick:()=>{a(null),o({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.homeDirectory")}),n.jsx("button",{type:"button",className:"machine-btn text-2xs flex-1 min-w-[80px]",onClick:()=>a(null),children:r("common.cancel")})]})]})})})}function uP(e,t){const s=S2(e),r=Bs(e,t),o=tu(e,r),a=Ea(e,r),i=Pb(e,{targetVersion:r,required:a,fallback:"Update daemon"});return o?{visible:!0,showButton:!0,title:a?"Daemon update required":"Version mismatch detected",titleKey:a?"machine.daemonUpdate.requiredTitle":"machine.daemonUpdate.mismatchTitle",descriptionKey:a?"machine.daemonUpdate.requiredDescription":s==="preview"?"machine.daemonUpdate.previewUpgradeDescription":"machine.daemonUpdate.mismatchDescription",description:a?"This machine is on an incompatible daemon version. Update it before starting more sessions.":s==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:r,channel:s,required:a,tone:"warn"}:s==="preview"?{visible:!0,showButton:!1,title:r?"Preview daemon is up to date":"Preview update status unknown",titleKey:r?"machine.daemonUpdate.previewUpToDateTitle":"machine.daemonUpdate.previewUnknownTitle",descriptionKey:r?"machine.daemonUpdate.previewUpToDateDescription":"machine.daemonUpdate.previewUnknownDescription",description:r?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:r,channel:s,required:!1,tone:r?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",titleKey:"",descriptionKey:"",buttonLabel:i,targetVersion:r,channel:s,required:!1,tone:"info"}}function Kl({icon:e,children:t}){return n.jsxs("div",{className:"flex items-center gap-2 text-2xs font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,n.jsx("span",{children:t})]})}function ql({children:e,className:t=""}){return n.jsx("div",{className:`rounded-2xl border border-border-subtle bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function mP({machineEntry:e,providers:t,recentLaunches:s,currentConversations:r,onUpgradeDaemon:o,onOpenRecent:a,onOpenConversation:i}){const{t:c}=ve("common"),d=r.slice(0,6),u=s.slice(0,4),h=uP(e,"1.0.59"),p=h.visible?[c(h.descriptionKey),h.targetVersion?h.channel?c("machine.commandCenter.updateTargetWithChannel",{version:h.targetVersion,channel:c(`machine.commandCenter.updateChannel.${h.channel}`)}):c("machine.commandCenter.updateTarget",{version:h.targetVersion}):""].filter(Boolean).join(`
|
|
94
|
+
`):"";return n.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(Kl,{icon:n.jsx(Jn,{size:13}),children:c("machine.commandCenter.currentChats")}),n.jsx(ql,{children:n.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(g=>{const f=Bc(g);return n.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(g),children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[n.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[n.jsx(_s,{conversation:g,size:12}),n.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:Rt(g)})]}),f>0&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:Si(f)})]}),n.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[n.jsx(Wr,{conversation:g,separator:!0}),Ho(g)]})]},g.tabKey)})})})]}),u.length>0&&n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(Kl,{icon:n.jsx(hd,{size:13}),children:c("machine.commandCenter.recentLaunches")}),n.jsx(ql,{children:n.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(g=>{const{metaText:f,updatedLabel:x}=Kb(g,c);return n.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>a(g),children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:g.label}),x&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:x})]}),n.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:f})]},g.id)})})})]}),h.visible&&h.showButton&&n.jsxs("div",{className:"flex flex-col gap-2","data-testid":"daemon-update-card",children:[n.jsx(Kl,{icon:n.jsx(an,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),n.jsx(ql,{className:"border-amber-500/20 bg-amber-500/5",children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsxs("div",{className:"flex items-center gap-1 text-sm font-semibold text-text-primary",children:[c(h.titleKey),n.jsx(dt,{content:p})]}),n.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:o,children:[n.jsx($r,{size:13}),n.jsx("span",{className:"text-sm font-medium",children:h.targetVersion?c("machine.commandCenter.updateToVersion",{version:h.targetVersion}):c("machine.commandCenter.updateDaemon")})]})]})})]}),h.visible&&!h.showButton&&n.jsx("div",{"data-testid":"daemon-update-chip",children:n.jsx(tn,{content:p,children:n.jsx("span",{className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-2xs font-medium ${h.tone==="good"?"border-emerald-500/20 bg-emerald-500/5 text-emerald-400":"border-border-subtle bg-bg-glass text-text-secondary"}`,children:h.tone==="good"?c("machine.commandCenter.upToDate"):c("machine.commandCenter.updateStatusUnknown")})})})]})}function Gc(e){return e.trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function hP(e,t){return t.has(Gc(e))}function pP({displayLabel:e,path:t,busy:s,onSave:r}){const{t:o}=ve("common"),[a,i]=l.useState(!1),[c,d]=l.useState(e),[u,m]=l.useState(!1),h=l.useRef(null);l.useEffect(()=>{var x,b;a&&((x=h.current)==null||x.focus(),(b=h.current)==null||b.select())},[a]);const p=()=>{d(e),i(!0)},g=()=>{i(!1),d(e)},f=async()=>{m(!0);try{await r(t,c)&&i(!1)}finally{m(!1)}};return a?n.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[n.jsx("input",{ref:h,autoFocus:!0,value:c,maxLength:64,disabled:s||u,onChange:x=>d(x.target.value),onKeyDown:x=>{x.key==="Enter"&&f(),x.key==="Escape"&&g()},placeholder:o("machine.managedWorkspaces.renamePlaceholder"),"aria-label":o("machine.managedWorkspaces.rename"),className:"min-w-0 flex-1 px-1.5 py-0.5 rounded border border-accent/30 bg-bg-secondary text-text-primary text-2xs font-medium"}),n.jsx("button",{type:"button",title:o("machine.managedWorkspaces.saveName"),"aria-label":o("machine.managedWorkspaces.saveName"),className:"shrink-0 p-0.5 rounded text-green-400 hover:bg-green-500/15 transition-colors",disabled:s||u,onClick:()=>{f()},children:n.jsx(Dr,{size:12})}),n.jsx("button",{type:"button",title:o("machine.managedWorkspaces.cancelRename"),"aria-label":o("machine.managedWorkspaces.cancelRename"),className:"shrink-0 p-0.5 rounded text-text-muted/60 hover:text-text-primary hover:bg-bg-glass-hover transition-colors",disabled:u,onClick:g,children:n.jsx(Bt,{size:12})})]}):n.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[n.jsx("div",{className:"font-medium text-text-primary truncate",children:e}),n.jsx("button",{type:"button",title:o("machine.managedWorkspaces.rename"),"aria-label":o("machine.managedWorkspaces.rename"),className:"shrink-0 p-0.5 rounded text-text-muted/60 hover:text-text-primary hover:bg-bg-glass-hover transition-colors",disabled:s,onClick:p,children:n.jsx(mw,{size:12})})]})}function fP({machineId:e,machine:t,ideSessions:s,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:u,handleWorkspaceSetDefault:m,handleWorkspaceSetLabel:h}=a,{t:p}=ve("common"),g=rr(),f=$d(),[x,b]=l.useState(!1),[k,j]=l.useState(()=>new Set),[v,_]=l.useState(null);l.useEffect(()=>{let T=!1;return(async()=>{try{let F=[];if(f!=null&&f.listMeshes)F=(await f.listMeshes(e)).map(q=>q.workspace);else{const q=await i(e,"list_meshes",{}),Q=(q==null?void 0:q.result)??q;F=(Array.isArray(Q==null?void 0:Q.meshes)?Q.meshes:[]).map(R=>{var D;return Array.isArray(R==null?void 0:R.nodes)&&R.nodes.length>0?String(((D=R.nodes[0])==null?void 0:D.workspace)||""):null})}if(T)return;j(new Set(F.filter(q=>!!q).map(Gc)))}catch{}})(),()=>{T=!0}},[e,f,i]);const y=l.useCallback(T=>{g("/dashboard",{state:{openNewSession:{machineId:e,workspaceId:T}}})},[e,g]),w=l.useCallback((T,F)=>{g("/dashboard",{state:{openNewSession:{machineId:e,workspaceId:T,mode:"mesh",meshWorkspacePath:F}}})},[e,g]),[S,C]=l.useState(""),[A,O]=l.useState([]),[L,M]=l.useState(!1),[$,N]=l.useState(""),I=l.useCallback(async T=>{M(!0),N("");try{const F=await ru(i,e,T);C(F.path),O(F.directories)}catch(F){N(F instanceof Error?F.message:"Could not load folder")}finally{M(!1)}},[e,i]),B=l.useCallback(()=>{b(!0);const T=[...s.map(q=>q.workspace),...r.map(q=>q.workspace),...o.map(q=>q.workspace)],F=su(t.platform,nu(T,t.defaultWorkspacePath,(t.workspaces||[]).map(q=>q.path)));I(F)},[o,r,s,I,t.defaultWorkspacePath,t.platform,t.workspaces]);return n.jsxs(n.Fragment,{children:[n.jsxs(wn,{padding:"lg",className:"mb-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[n.jsxs("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[n.jsx(Zs,{size:14})," ",p("machine.managedWorkspaces.title")]}),n.jsxs("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:B,children:["+ ",p("machine.managedWorkspaces.addWorkspace")]})]}),(t.workspaces||[]).length===0?n.jsx("div",{className:"text-2xs text-text-muted py-4 text-center",children:p("machine.managedWorkspaces.empty",{button:p("machine.managedWorkspaces.addWorkspace")})}):n.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(T=>{const F=T.id===t.defaultWorkspaceId;return n.jsxs("li",{className:`flex items-start gap-2 text-2xs rounded-lg border px-2.5 py-2 transition-colors ${F?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[n.jsx("button",{type:"button",title:p(F?"machine.managedWorkspaces.unsetDefaultHint":"machine.managedWorkspaces.setDefaultHint"),disabled:c,onClick:()=>void m(F?null:T.id),className:`text-base leading-none shrink-0 transition-colors ${F?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[hP(T.path,k)?n.jsx(pP,{displayLabel:_a(T.path,T.label),path:T.path,busy:c,onSave:h}):n.jsx("div",{className:"font-medium text-text-primary truncate",children:_a(T.path,T.label)}),n.jsx("div",{className:"font-mono text-text-muted truncate text-3xs",title:T.path,children:T.path})]}),n.jsxs("button",{type:"button",title:p("machine.managedWorkspaces.newSession"),className:"btn shrink-0 flex items-center gap-1 bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-2 py-1 rounded transition-colors text-3xs",disabled:c,onClick:()=>y(T.id),children:[n.jsx(_o,{size:11}),p("machine.managedWorkspaces.newSessionShort")]}),k.has(Gc(T.path))&&n.jsxs("button",{type:"button",title:p("machine.managedWorkspaces.newMeshSession"),className:"btn shrink-0 flex items-center gap-1 bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-2 py-1 rounded transition-colors text-3xs",disabled:c,onClick:()=>w(T.id,T.path),children:[n.jsx(_o,{size:11}),p("machine.managedWorkspaces.newMeshSessionShort")]}),n.jsx("button",{type:"button",title:p("machine.managedWorkspaces.remove"),"aria-label":p("machine.managedWorkspaces.remove"),className:"shrink-0 p-1 rounded text-text-muted/60 hover:text-red-400 hover:bg-red-500/10 transition-colors",disabled:c,onClick:()=>_({id:T.id,label:_a(T.path,T.label)}),children:n.jsx(bw,{size:13})})]},T.id)})})]}),x&&n.jsx(au,{title:p("machine.managedWorkspaces.addWorkspace"),description:p("machine.managedWorkspaces.addDialogDescription"),currentPath:S,directories:A,busy:L,error:$,confirmLabel:p("machine.managedWorkspaces.addWorkspace"),onClose:()=>b(!1),onNavigate:T=>{I(T)},onConfirm:T=>{(async()=>{if(!T)return;await d(T)&&b(!1)})()}}),v&&n.jsx(gf,{title:p("machine.managedWorkspaces.removeConfirmTitle"),description:p("machine.managedWorkspaces.removeConfirmDescription",{label:v.label}),confirmLabel:p("machine.managedWorkspaces.remove"),tone:"danger",busy:c,onCancel:()=>_(null),onConfirm:()=>{const T=v;_(null),T&&u(T.id)}})]})}function gP({machine:e,machineId:t,ideSessions:s,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i}){const{t:c}=ve("common");return n.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[n.jsx("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:n.jsx("div",{className:"text-lg font-semibold text-text-primary",children:c("machine.managedWorkspaces.title")})}),i&&n.jsx(fP,{machineId:t,machine:e,ideSessions:s,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i})]})}function bP({onNicknameSynced:e}={}){var Ne,Be,Le,Je,Se,he,pe,Ee,Y,me,fe;const{t}=ve("common"),{id:s}=ey(),r=rr(),o=fi(),{sendCommand:a}=_t(),i=Br(),c=kb(),d=Ad(),u=d.ides||[],m=d.initialLoaded??!0,h=u.find(E=>E.id===s&&E.type==="adhdev-daemon"),p=u.some(E=>E.type==="adhdev-daemon"),g=s?(Ne=d.connectionRetryStatuses)==null?void 0:Ne[s]:void 0,f=!!(g!=null&&g.blocked),[x,b]=l.useState("workspace"),[k,j]=l.useState(null),[v,_]=l.useState(null),[,y]=l.useState("ide"),w=l.useRef(null),[S,C]=l.useState(null),A=l.useRef("__home__"),[O,L]=l.useState("__home__"),[M,$]=l.useState(!1),N=l.useRef(null);l.useEffect(()=>{!s||!h||!(!h.workspaces||!h.availableProviders||!h.detectedIdes||!h.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,h,s]);const I=l.useCallback(E=>{const oe=vd(E),Ie=oe==null?void 0:oe.providerChannelStaleness;Ie&&!Ie.error&&j({staleTypes:Array.isArray(Ie.staleTypes)?Ie.staleTypes:[],newTypes:Array.isArray(Ie.newTypes)?Ie.newTypes:[]})},[]);l.useEffect(()=>{if(!s||!h)return;let E=!1;return(async()=>{try{const oe=await a(s,"get_status_metadata");E||I(oe)}catch{}})(),()=>{E=!0}},[I,s,h==null?void 0:h.id,a]),l.useEffect(()=>{if(!s||!h||x!=="overview"&&x!=="providers")return;const E=h.machine;(typeof(E==null?void 0:E.cpus)!="number"||typeof(E==null?void 0:E.totalMem)!="number"||typeof(E==null?void 0:E.arch)!="string"||typeof(E==null?void 0:E.release)!="string"||!(E!=null&&E.quota))&&c(s,{minFreshMs:3e4}).catch(()=>{})},[x,c,h,s]),ET(s&&x==="overview"?[s]:[],{enabled:x==="overview",intervalMs:dC});const B=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},T=JM({machineId:s,registeredMachineId:(h==null?void 0:h.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:N});l.useEffect(()=>ct.onToast(oe=>{d.setToasts(Z=>{if(Z.some($e=>$e.message===oe.message&&oe.timestamp-$e.timestamp<3e3))return Z;const ye={id:oe.id,message:oe.message,type:oe.type,timestamp:oe.timestamp,targetKey:oe.targetKey,actions:oe.actions,details:oe.details};return[...Z.slice(-4),ye]});const Ie=oe.duration||5e3;setTimeout(()=>d.setToasts(Z=>Z.filter(se=>se.id!==oe.id||se.pinned)),Ie)}),[d]);const F=(h==null?void 0:h.availableProviders)||[],q={};for(const E of F)q[E.type]=E.icon;const Q=h?{id:h.id,hostname:jd(h,{fallbackId:h.id}),platform:((Be=h.machine)==null?void 0:Be.platform)||"unknown",arch:((Le=h.machine)==null?void 0:Le.arch)||"",cpus:((Je=h.machine)==null?void 0:Je.cpus)||0,totalMem:((Se=h.machine)==null?void 0:Se.totalMem)||0,freeMem:(he=h.machine)==null?void 0:he.freeMem,availableMem:(pe=h.machine)==null?void 0:pe.availableMem,loadavg:(Ee=h.machine)==null?void 0:Ee.loadavg,uptime:(Y=h.machine)==null?void 0:Y.uptime,release:((me=h.machine)==null?void 0:me.release)||"",cdpConnected:!!h.cdpConnected,machineNickname:h.machineNickname||null,...(fe=h.machine)!=null&&fe.quota?{quota:h.machine.quota}:{},p2p:h.p2p?{screenshotActive:!1,...h.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:h.detectedIdes||[],workspaces:h.workspaces||[],defaultWorkspaceId:h.defaultWorkspaceId??h.activeWorkspaceId??null,defaultWorkspacePath:h.defaultWorkspacePath??h.activeWorkspacePath??null}:null,K=u.filter(E=>E.daemonId===s&&E.type!=="adhdev-daemon").filter(E=>!To(E)&&!Nr(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,version:E.version||"",instanceId:E.instanceId||"",status:E.status,workspace:E.workspace||null,terminals:E.terminals||0,aiAgents:pj(E.aiAgents||(E.agents||[]).map(oe=>({id:oe.name,name:oe.name,status:oe.status,version:oe.version}))),activeChat:E.activeChat||null,chats:E.chats||[],childSessions:E.childSessions||[],cdpConnected:E.cdpConnected||!1,daemonId:s,lastMessageAt:E.lastMessageAt})),R=u.filter(E=>E.daemonId===s&&To(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,cliName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,mode:E.mode,runtimeKey:E.runtimeKey,runtimeDisplayName:E.runtimeDisplayName,runtimeWorkspaceLabel:E.runtimeWorkspaceLabel,runtimeWriteOwner:E.runtimeWriteOwner||null,runtimeAttachedClients:E.runtimeAttachedClients||[],daemonId:s,lastMessageAt:E.lastMessageAt})),D=u.filter(E=>E.daemonId===s&&Nr(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,acpName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,daemonId:s,lastMessageAt:E.lastMessageAt})),P=h?Tn(h,{fallbackId:s}):"",H="workspace",W=o.state,U=W==null?void 0:W.initialMachineTab,ae=W==null?void 0:W.initialWorkspaceCategory;W==null||W.initialWorkspaceId,W==null||W.initialWorkspacePath;const be=U==="session-host"?"hosted-runtimes":U==="logs"?"logs":null,V=U==="ides"||U==="clis"||U==="acps"?"workspace":be?"overview":U||H,we=U==="ides"?"ide":U==="clis"?"cli":U==="acps"?"acp":ae,ce=[...K.map(E=>{var oe;return{id:`ide:${E.type}:${E.workspace||""}`,label:((oe=E.activeChat)==null?void 0:oe.title)||E.type,kind:"ide",providerType:E.type,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:E.lastMessageAt||0}}),...R.map(E=>{var oe;return{id:`cli:${E.type}:${E.workspace||""}`,label:((oe=E.activeChat)==null?void 0:oe.title)||E.cliName,kind:"cli",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:E.lastMessageAt||0}}),...D.map(E=>{var oe;return{id:`acp:${E.type}:${E.workspace||""}`,label:((oe=E.activeChat)==null?void 0:oe.title)||E.acpName,kind:"acp",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:tr(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:E.lastMessageAt||0}})].sort((E,oe)=>(oe.lastLaunchedAt||0)-(E.lastLaunchedAt||0)),de=((h==null?void 0:h.recentLaunches)||[]).length>0?((h==null?void 0:h.recentLaunches)||[]).map(E=>({id:E.id,label:E.title||E.providerName||E.providerType,kind:E.kind,providerType:E.providerType,providerSessionId:E.providerSessionId,subtitle:tr(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace,summaryMetadata:E.summaryMetadata,lastLaunchedAt:E.lastLaunchedAt})):ce,ne=l.useMemo(()=>{var oe;const E=((oe=d.connectionStates)==null?void 0:oe[s||""])||void 0;return u.filter(Ie=>Ie.daemonId===s&&Ie.type!=="adhdev-daemon").flatMap(Ie=>Gd(Ie,{connectionStates:s&&E?{[s]:E}:void 0,defaultConnectionState:E})).filter(Ie=>!(Ie.transport==="pty"&&Ie.mode==="terminal")).sort((Ie,Z)=>Bc(Z)-Bc(Ie))},[u,d.connectionStates,s]),ee=l.useCallback(E=>{const oe=Ob(E);oe&&r(Io(oe))},[r]),ue=l.useCallback(()=>{w.current&&($(!0),w.current().finally(()=>{w.current=null,$(!1),C(null)}))},[]),je=l.useCallback(E=>{if(!Q)return;const{options:oe,selectedKey:Ie}=Ub({machine:Q,currentWorkspacePath:E.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),Z=async()=>{y(E.kind),b("workspace")};if(w.current=async()=>{const se=oe.find(Me=>Me.key===A.current),ye=(se==null?void 0:se.workspacePath)??null,$e=(se==null?void 0:se.workspaceId)??null;if(E.kind==="ide"&&E.providerType){await T.handleLaunchIde(E.providerType,ye?{workspace:ye}:void 0);return}if((E.kind==="cli"||E.kind==="acp")&&E.providerType){await T.runLaunchCliCore({cliType:E.providerType,dir:$e?void 0:ye||"",workspaceId:$e||void 0,model:E.kind==="acp"&&Ff(E.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:E.providerSessionId});return}await Z()},A.current=Ie,oe.length<=1){const se=w.current;w.current=null,se==null||se().catch(ye=>ct.showErrorToast(t("machine.detail.relaunchFailed"),ye));return}L(Ie),C({title:E.kind==="ide"?ti(t,"restart-ide",E.label):E.providerSessionId?ob(t,E.label):ti(t,"start-fresh",E.label),description:E.kind==="ide"?ni(t,"restart-ide"):E.providerSessionId?ab(t):ni(t,"start-fresh"),confirmLabel:E.kind==="ide"?si(t,"restart-ide"):E.providerSessionId?Lc(t,!0):si(t,"start-fresh"),busyLabel:E.kind==="ide"?ri(t,"restart-ide"):E.providerSessionId?sb(t,!0):ri(t,"start-fresh"),workspaceOptions:oe,details:[{label:t("machine.detail.launchType"),value:E.kind.toUpperCase()},...E.providerType?[{label:t("machine.detail.launchProvider"),value:(()=>{const se=F.find($e=>$e.type===E.providerType),ye=(se==null?void 0:se.displayName)||E.providerType;return n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Hi,{type:E.providerType,label:ye,size:14}),ye]})})()}]:[]]})},[T,Q,F,t]);if(l.useEffect(()=>{b(V)},[H,V,s]),l.useEffect(()=>{we&&y(we)},[we,s]),!Q)return m?n.jsxs("div",{className:"p-10 text-center text-text-muted",children:[n.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),n.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),n.jsx("button",{onClick:B,className:"machine-btn-back",children:t("machine.detail.back")})]}):n.jsx("div",{className:"p-10 text-center text-text-muted",children:n.jsx("p",{children:t("machine.detail.loading")})});const X=!!k&&k.staleTypes.length+k.newTypes.length>0,G=K.length+R.length+D.length,z=[{key:"workspace",icon:n.jsx(Xn,{size:14}),label:t("machine.detail.tabSessions"),trailing:G>0?n.jsx("span",{className:`px-1.5 py-px rounded-full text-3xs ${x==="workspace"?"bg-accent-primary/20 text-accent-primary":"bg-bg-glass-hover text-text-muted"}`,children:G}):void 0},{key:"providers",icon:n.jsx(Or,{size:14}),label:t("machine.detail.tabProviders"),trailing:X?n.jsx("span",{title:t("machine.detail.providerUpdatesAvailable"),"aria-label":t("machine.detail.providerUpdatesAvailable"),"data-testid":"providers-update-dot",className:"w-1.5 h-1.5 rounded-full bg-amber-400 ml-0.5 shrink-0"}):void 0},{key:"overview",icon:n.jsx(fw,{size:14}),label:t("machine.detail.tabSystem")}],ie=Hf[Q.platform]||Q.platform;return n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-border-subtle",children:[n.jsx("div",{className:"flex items-center justify-between w-full",children:n.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[n.jsx("button",{onClick:B,className:"flex items-center justify-center w-8 h-8 rounded-full bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),n.jsxs("div",{className:"flex flex-col min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[T.editingNickname?n.jsxs("div",{className:"flex gap-1.5 items-center",children:[n.jsx("input",{autoFocus:!0,value:T.nicknameInput,onChange:E=>T.setNicknameInput(E.target.value),onKeyDown:E=>{E.key==="Enter"&&T.handleSaveNickname(),E.key==="Escape"&&T.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-accent/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),n.jsx("button",{onClick:T.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:t("machine.detail.save")}),n.jsx("button",{onClick:()=>T.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-bg-glass text-text-muted hover:bg-bg-glass-hover hover:text-text-primary text-sm font-medium transition-colors",children:t("machine.detail.cancel")})]}):n.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{T.setEditingNickname(!0),T.setNicknameInput(Q.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:P}),f?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),d.retryConnection&&s&&n.jsx("button",{onClick:()=>d.retryConnection(s),className:"px-2.5 py-0.5 rounded text-2xs font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):null]}),n.jsx("div",{className:"mt-1 text-xs text-text-secondary","data-testid":"machine-detail-subtitle",children:[t(f?"machine.card.status.failed":"machine.card.status.online"),ie].filter(Boolean).join(" · ")})]})]})}),n.jsx(Vd,{variant:"underline",tabs:z,activeKey:x,onSelect:E=>b(E),ariaLabel:t("machine.detail.tabsAriaLabel"),className:"mt-4 -mx-1 border-b-0 px-0 md:px-0",tabIdPrefix:"machine-tab"})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:n.jsx("div",{className:"max-w-7xl mx-auto h-full",children:n.jsxs("div",{className:"h-full",children:[x==="workspace"&&n.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[n.jsx(mP,{machineEntry:h,providers:F,recentLaunches:de,currentConversations:ne,onUpgradeDaemon:async()=>{const E=eu(h);if(E)try{await a(s,"daemon_upgrade",E)}catch{}},onOpenRecent:je,onOpenConversation:ee}),n.jsx(gP,{machine:Q,machineId:s,ideSessions:K,cliSessions:R,acpSessions:D,actions:T,sendDaemonCommand:a})]}),x==="providers"&&n.jsx(xR,{machineId:s,providers:F,sendDaemonCommand:a,quota:Q.quota,onChannelStaleness:j}),x==="overview"&&n.jsx(eR,{machine:Q,ideSessions:K,cliSessions:R,acpSessions:D,daemonVersion:h==null?void 0:h.version,initialDiagnostics:be,renderHostedRuntimes:()=>n.jsx(cP,{machineId:s,cliSessions:R,sendDaemonCommand:a}),renderLogs:()=>n.jsx(ZR,{machineId:s,sendDaemonCommand:a})})]})})}),T.launchPick&&Q&&n.jsx(dP,{machine:Q,launchPick:T.launchPick,actions:T}),S&&n.jsx(Ui,{title:S.title,description:S.description,details:S.details,workspaceOptions:S.workspaceOptions,selectedWorkspaceKey:O,onWorkspaceChange:E=>{A.current=E,L(E)},confirmLabel:S.confirmLabel,busyLabel:S.busyLabel,busy:M,onConfirm:ue,onCancel:()=>{w.current=null,C(null)}}),v&&n.jsx(ux,{daemonId:v.daemonId,workspace:v.workspace,onClose:()=>_(null)}),T.confirmDialog,n.jsx(ib,{toasts:d.toasts||[],onDismiss:E=>d.setToasts(oe=>oe.filter(Ie=>Ie.id!==E)),onClickToast:E=>{E.targetKey&&r(Io(E.targetKey))}}),n.jsx("style",{children:`
|
|
95
|
+
@keyframes toast-in {
|
|
96
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
97
|
+
to { opacity: 1; transform: translateX(0); }
|
|
98
|
+
}
|
|
99
|
+
`})]})}const xP=new Set(["approvalAlert","noProgressAlert","noProgressThresholdSec","longGeneratingAlert","longGeneratingThresholdSec"]),yP=[{id:"approval",keys:["approvalAlert"]},{id:"noProgress",keys:["noProgressAlert","longGeneratingAlert"]}];function vP(e){return e.filter(t=>xP.has(t.key))}function wP({machineId:e,children:t}){return n.jsx(Sp,{to:`/machines/${e}`,state:{initialMachineTab:"providers"},className:"text-accent-primary hover:underline",children:t})}function SP({machineId:e,children:t}){return ty()?n.jsx(wP,{machineId:e,children:t}):n.jsx("a",{href:`/machines/${e}`,className:"text-accent-primary hover:underline",children:t})}function kP({machines:e,onBrowserPrefChange:t,renderPushSection:s,initialLoaded:r=!0}){const{t:o}=ve("common"),[a,i]=kj(),{sendCommand:c}=_t(),[d,u]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission),[m,h]=l.useState({}),[p,g]=l.useState(!1),f=l.useMemo(()=>e.filter(y=>y.status==="online"),[e]);l.useEffect(()=>{const y=()=>{if(typeof window>"u"||!("Notification"in window)){u("unsupported");return}u(Notification.permission)};return y(),window.addEventListener("focus",y),document.addEventListener("visibilitychange",y),()=>{window.removeEventListener("focus",y),document.removeEventListener("visibilitychange",y)}},[]);const x=l.useCallback(async()=>{g(!0);const y={};for(const w of f)try{const S=await c(w.id,"get_provider_settings",{}),C=mx(S);if(C){const A=hx(C,w.providers||[],{filterSchema:vP});A.length>0&&(y[w.id]=A)}}catch(S){console.warn("[Notifications] Failed to fetch settings from",w.id,S)}h(y),g(!1)},[f,c]);l.useEffect(()=>{f.length>0&&x()},[f.length]);const b=l.useMemo(()=>{const y=[];for(const[w,S]of Object.entries(m)){const C=f.find(O=>O.id===w),A=C?Tn(C,{fallbackId:w}):w.slice(0,8);for(const O of S)y.push({...O,machineId:w,machineLabel:A})}return y},[m,f]),k=l.useCallback(async(y,w,S,C)=>{h(A=>{const O={...A};return O[y]=(O[y]||[]).map(L=>L.type===w?{...L,values:{...L.values,[S]:C}}:L),O});try{await c(y,"set_provider_setting",{providerType:w,key:S,value:C})}catch{}},[c]),j=l.useMemo(()=>yP.map(y=>{const w=b.map(C=>({entry:C,key:y.keys.find(A=>C.schema.some(O=>O.key===A))})).filter(C=>!!C.key),S=w.filter(({entry:C,key:A})=>{var O;return!!(C.values[A]??((O=C.schema.find(L=>L.key===A))==null?void 0:O.default))}).length;return{id:y.id,targets:w,total:w.length,onCount:S}}).filter(y=>y.total>0),[b]),v=l.useCallback(async(y,w)=>{const S=j.find(C=>C.id===y);if(S)for(const{entry:C,key:A}of S.targets)await k(C.machineId,C.type,A,w)},[j,k]),_=(y,w)=>{i({[y]:w}),t==null||t(y,w)};return n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsx(pb,{icon:n.jsx(js,{className:"text-text-primary"}),title:o("notifications.title"),subtitle:o("notifications.subtitle")}),n.jsxs("div",{className:"page-content",children:[n.jsx(Nt,{title:o("notifications.sectionBrowserAlerts"),className:"mb-4",children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(js,{size:15})," ",o("notifications.masterToggleLabel")]}),description:o("notifications.masterToggleDesc"),checked:a.globalEnabled,onChange:y=>_("globalEnabled",y)}),a.globalEnabled&&n.jsx("div",{className:"border-t border-border-subtle my-0.5"}),a.globalEnabled&&n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Xn,{size:15})," ",o("notifications.browserNotificationsLabel")]}),description:o("notifications.browserNotificationsDesc"),checked:a.browserNotifications,onChange:y=>_("browserNotifications",y)}),a.globalEnabled&&n.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-wrap items-center gap-2","data-testid":"browser-permission-row",children:[d==="granted"&&n.jsx("span",{className:"inline-flex items-center rounded-full border border-emerald-500/25 bg-emerald-500/10 px-2 py-0.5 text-3xs font-semibold text-emerald-400",children:o("notifications.permissionAllowedChip")}),d==="default"&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"inline-flex items-center rounded-full border border-amber-500/25 bg-amber-500/10 px-2 py-0.5 text-3xs font-semibold text-amber-400",children:o("notifications.permissionNeededChip")}),n.jsx("button",{onClick:()=>{Wf().then(u)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-2xs text-text-secondary hover:text-text-primary transition-colors",children:o("notifications.allowNotifications")})]}),d==="denied"&&n.jsx("span",{className:"inline-flex items-center rounded-full border border-amber-500/25 bg-amber-500/10 px-2 py-0.5 text-3xs font-semibold text-amber-400",children:o("notifications.permissionBlockedChip")}),d==="unsupported"&&n.jsx("span",{className:"inline-flex items-center rounded-full border border-border-subtle bg-bg-glass px-2 py-0.5 text-3xs font-semibold text-text-muted",children:o("notifications.permissionUnsupportedChip")}),n.jsx(dt,{content:[o(s?"notifications.browserBackgroundInfoWithPush":"notifications.browserBackgroundInfo"),d==="default"?o("notifications.permissionDefault"):d==="denied"?o("notifications.permissionDenied"):d==="unsupported"?o("notifications.permissionUnsupported"):""].filter(Boolean).join(`
|
|
100
|
+
|
|
101
|
+
`)})]}),a.globalEnabled&&a.browserNotifications&&n.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(vi,{size:15})," ",o("notifications.completionAlertsLabel")]}),description:o("notifications.completionAlertsDesc"),checked:a.completionAlert,onChange:y=>_("completionAlert",y)}),n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Iu,{size:15})," ",o("notifications.approvalAlertsLabel")]}),description:o("notifications.approvalAlertsDesc"),checked:a.approvalAlert,onChange:y=>_("approvalAlert",y)}),n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Ir,{size:15})," ",o("notifications.connectionAlertsLabel")]}),description:o("notifications.connectionAlertsDesc"),checked:a.disconnectAlert,onChange:y=>_("disconnectAlert",y)})]}),a.globalEnabled&&(s==null?void 0:s()),a.globalEnabled&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"border-t border-border-subtle my-0.5"}),n.jsx(jP,{})]}),!a.globalEnabled&&n.jsx("p",{className:"text-2xs text-text-muted italic",children:o("notifications.allDisabled")})]})}),n.jsx(Nt,{title:o("notifications.sectionProviderAlerts"),description:o("notifications.agentAlertsDesc"),action:n.jsx(Wi,{onClick:()=>{x()},refreshing:p,label:o("notifications.refresh")}),className:"mb-4",children:r?f.length===0?n.jsx("p",{className:"text-sm text-text-muted py-6 text-center",children:o("notifications.noOnlineMachines")}):p&&b.length===0?n.jsx("p",{className:"text-sm text-text-muted py-6 text-center",children:o("notifications.loadingProviderSettings")}):n.jsxs("div",{className:"flex flex-col gap-3","data-testid":"agent-alert-toggles",children:[j.map(({id:y,total:w,onCount:S})=>n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[y==="approval"?n.jsx(Iu,{size:15}):n.jsx(hd,{size:15}),n.jsx("span",{children:o(`notifications.agentAlert.${y}`)}),S>0&&S<w&&n.jsx("span",{className:"text-3xs text-text-muted",children:o("notifications.mixed")})]}),description:o(`notifications.agentAlert.${y}Desc`),checked:S===w,onChange:C=>void v(y,C)},y)),n.jsxs("div",{className:"border-t border-border-subtle pt-3 text-2xs text-text-muted","data-testid":"per-provider-link",children:[o("notifications.perProviderIntro")," ",f.map((y,w)=>n.jsxs("span",{children:[w>0?", ":"",n.jsx(SP,{machineId:y.id,children:f.length>1?Tn(y,{fallbackId:y.id}):o("notifications.machineProviders")})]},y.id))]})]}):n.jsx("p",{className:"text-sm text-text-muted py-6 text-center",children:o("notifications.loading")})})]})]})}function jP(){const{t:e}=ve("common"),[t,s]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),r=o=>{s(o);try{localStorage.setItem("adhdev_sound",o?"1":"0")}catch{}};return n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(ww,{size:15})," ",e("notifications.soundEffectsLabel")]}),description:e("notifications.soundEffectsDesc"),checked:t,onChange:r})}const zl=[];function Ut(e){return typeof e=="string"?e.trim():""}function Vc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function gx(...e){const t=new Set;for(const s of e){const r=Ut(s);r&&t.add(r)}return[...t]}function NP(e,t){var h,p;const s=Vc(e==null?void 0:e.settings),r=Ut((h=e==null?void 0:e.coordinator)==null?void 0:h.meshId)||Ut(s.meshCoordinatorFor),o=Ut(s.meshNodeFor),a=!!r||!!o,i=r===t||o===t;if(a&&!i)return null;const c=Vc(e==null?void 0:e.activeChat),d=gx(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),u=d[0]||"";if(!u)return null;const m=r===t?Ut((p=e==null?void 0:e.coordinator)==null?void 0:p.role)||"coordinator":o===t?Ut(s.meshNodeRole)||"worker":Ut(e==null?void 0:e.role)||Ut(s.meshNodeRole)||void 0;return{sessionId:u,aliases:d,meshId:t,nodeId:i&&Ut(s.meshNodeId)||null,providerType:Ut(e==null?void 0:e.providerType)||void 0,state:gi(e==null?void 0:e.status)??void 0,chatStatus:Ut(c.status)||void 0,lifecycle:Ut(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:Ut(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:Ut(e==null?void 0:e.runtimeRecoveryState)||void 0,...m?{role:m}:{},...i?{isSelfCoordinator:r===t}:{},workspace:Ut(e==null?void 0:e.workspace)||null}}function bx(e,t){var r;return t?(Array.isArray((r=e.status)==null?void 0:r.sessions)?e.status.sessions:[]).map(o=>NP(o,t)).filter(o=>o!==null):[]}function di(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function CP(e,t){const s=new Set(di(t));return di(e).some(r=>s.has(r))}function _P(e,t){const s=t.filter(o=>!!o);return s.length===0?e:[...e.filter(o=>!s.some(a=>CP(o,a))),...s]}function AP(e,t){const s=e.nodes??[],r=s.filter(c=>{var d;return((d=c.connection)==null?void 0:d.state)==="self"}),o=r.length>0?r:t?s.filter(c=>on(String(c.daemonId||""),t)):[];if(o.length===1)return o[0].nodeId;const a=o.filter(c=>c.role==="host");if(a.length===1)return a[0].nodeId;const i=o.filter(c=>!c.isLocalWorktree);return i.length===1?i[0].nodeId:null}function TP(e,t,s){if(t.length===0)return e;const r=t.some(d=>d.isSelfCoordinator&&!d.nodeId)?AP(e,s):null,o=new Map;for(const d of t)for(const u of di(d))o.set(u,d);let a=!1;const c=(e.nodes??[]).map(d=>{const u=Array.isArray(d.activeSessionDetails)?d.activeSessionDetails:Array.isArray(d.sessions)?d.sessions:[],m=new Map;for(const p of u){const g=gx(p==null?void 0:p.sessionId,p==null?void 0:p.session_id,p==null?void 0:p.id,p==null?void 0:p.providerSessionId,p==null?void 0:p.provider_session_id),f=g[0]||"";if(!f)continue;const x=g.map(b=>o.get(b)).find(Boolean);x&&(a=!0),m.set(f,x?{...p,sessionId:f,providerType:x.providerType||p.providerType,state:x.state||p.state,chatStatus:x.chatStatus||p.chatStatus,lifecycle:x.lifecycle||p.lifecycle,surfaceKind:x.surfaceKind||p.surfaceKind,recoveryState:x.recoveryState||p.recoveryState,role:x.role||p.role,isSelfCoordinator:x.isSelfCoordinator??p.isSelfCoordinator,workspace:x.workspace||p.workspace}:{...p,sessionId:f})}for(const p of d.activeSessions??[])m.has(p)||m.set(p,{sessionId:p,workspace:d.workspace,isCached:!0});for(const p of t){if(di(p).some(b=>m.has(b)))continue;const f=p.nodeId!=null&&p.nodeId===d.nodeId,x=p.isSelfCoordinator&&!p.nodeId&&r!==null&&r===d.nodeId;!f&&!x||(a=!0,m.set(p.sessionId,{sessionId:p.sessionId,providerType:p.providerType,state:p.state,chatStatus:p.chatStatus,lifecycle:p.lifecycle,surfaceKind:p.surfaceKind,recoveryState:p.recoveryState,role:p.role,isSelfCoordinator:p.isSelfCoordinator,workspace:p.workspace||d.workspace}))}const h=[...m.values()];return h.length===0?d:{...d,activeSessionDetails:h,activeSessions:h.map(p=>p.sessionId)}});return a?{...e,nodes:c}:e}function IP(e,t){const r=bx(e,t).map(o=>{var d;const a=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(u=>Ut(u==null?void 0:u.id)===o.sessionId),i=Vc(a==null?void 0:a.activeInteractivePrompt),c=a!=null&&a.meshQueueStats&&typeof a.meshQueueStats=="object"?JSON.stringify(a.meshQueueStats):"";return[o.sessionId,o.providerType??"",o.state??"",o.chatStatus??"",o.lifecycle??"",o.surfaceKind??"",o.recoveryState??"",Ut(i.status)||Ut(i.kind)||Ut(i.type),o.nodeId??"",o.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(o=>!!o).sort();return r.length>0?r.join(`
|
|
102
|
+
`):null}function MP({status:e,daemonId:t,meshId:s,sendData:r,extraLiveSessions:o=zl}){const[a,i]=l.useState(zl),c=l.useRef(null);l.useEffect(()=>{c.current=null,i(zl)},[t,s]),l.useEffect(()=>{if(!s||!r||!t)return;const u=_n.subscribe({sendData:r},t,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${t}`,params:{includeSessions:!0}},m=>{if(m.topic!=="daemon.metadata")return;const h=IP(m,s);h!==c.current&&(c.current=h,i(bx(m,s)))});return()=>{u()}},[t,s,r]);const d=l.useMemo(()=>_P(a,o),[o,a]);return l.useMemo(()=>e?TP(e,d,t):null,[d,e,t])}function xx({daemonIds:e,meshId:t,sendData:s,onRevisionAdvance:r,onRevisionObserved:o}){const a=l.useRef(new Map),i=l.useRef(r);i.current=r;const c=l.useRef(o);c.current=o;const d=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{a.current=new Map},[d,t]),l.useEffect(()=>{if(!t||!s)return;const u=[...new Set(e.filter(Boolean))];if(u.length===0)return;const m=u.map(h=>_n.subscribe({sendData:s},h,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${h}`,params:{includeSessions:!0}},p=>{var b;if(p.topic!=="daemon.metadata")return;const g=p.meshStateRevisions;if(!g)return;const f=g[t]??g["*"];if(typeof f!="number")return;const x=a.current.get(h);a.current.set(h,f),(b=c.current)==null||b.call(c),x!==void 0&&f>x&&i.current()}));return()=>{for(const h of m)h()}},[d,t,s])}const yx={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},vx=l.createContext(null);function RP(){const e=l.useContext(vx);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function uu(e){var r,o;const t=((r=e==null?void 0:e.error)==null?void 0:r.trim())||"Git discovery failed",s=(o=e==null?void 0:e.action)==null?void 0:o.trim();return s?`${t} ${s}`:t}const ui="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function Yc({workspaces:e,value:t,onChange:s,autoFocus:r}){const{t:o}=ve("common"),[a,i]=l.useState(!1),c=new Set(e.map(u=>u.path)),d=a?"__custom":c.has(t)?t:"";return e.length===0||a?n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("input",{type:"text",className:ui,value:t,autoFocus:r,placeholder:o("setupWizard.machines.workspacePlaceholder"),onChange:u=>s(u.target.value)}),e.length>0&&n.jsx("button",{type:"button",className:"self-start text-3xs text-accent-primary hover:underline",onClick:()=>i(!1),children:o("setupWizard.machines.pickFromKnown")})]}):n.jsxs("select",{className:ui,value:d,onChange:u=>{u.target.value==="__custom"?(i(!0),s("")):s(u.target.value)},children:[n.jsx("option",{value:"",children:o("setupWizard.machines.workspaceSelectPlaceholder")}),e.map(u=>n.jsx("option",{value:u.path,children:u.label||u.path},u.path)),n.jsx("option",{value:"__custom",children:o("setupWizard.machines.workspaceCustom")})]})}function mi(e){var t;return!!(e!=null&&e.success)&&((t=e==null?void 0:e.plan)==null?void 0:t.kind)!==void 0&&e.plan.kind!=="create_mesh_and_onboard"}function wx(e,t){const[s,r]=l.useState(!1),o=l.useRef(null);return l.useEffect(()=>(e?o.current=setTimeout(()=>r(!0),t):r(!1),()=>{o.current&&clearTimeout(o.current)}),[e,t]),e&&s}function Sx({plan:e,loading:t}){var i,c,d;const{t:s}=ve("common"),r=wx(t,250);let o=null,a="text-2xs text-text-muted";return r?o=s("setupWizard.machines.planChecking"):(e==null?void 0:e.success)===!1?(a="text-2xs text-red-400",o=n.jsxs(n.Fragment,{children:[e.error,e.action?` ${e.action}`:""]})):mi(e)?(a="text-2xs text-amber-400",o=((i=e.plan)==null?void 0:i.summary)||s("setupWizard.machines.planExists")):e&&(a="text-2xs text-emerald-400",o=s("setupWizard.machines.planOk",{identity:((c=e.discovery)==null?void 0:c.repoIdentity)||((d=e.discovery)==null?void 0:d.repoRoot)||""})),n.jsx("p",{className:`${a} min-h-[1.4em]`,children:o})}function PP(e){var t;return e.creating||e.planLoading||!e.name.trim()||e.showDaemonPicker&&!e.daemonId||((t=e.plan)==null?void 0:t.success)===!1||mi(e.plan)?!0:e.workspace.trim()?!1:!e.repoRemoteUrl.trim()&&!e.repoIdentity.trim()}function kx(e){var N,I;const{variant:t="page",showDaemonPicker:s,daemons:r,daemonLabel:o,name:a,onNameChange:i,daemonId:c,onDaemonIdChange:d,workspace:u,onWorkspaceChange:m,workspaces:h,plan:p,planLoading:g,repoRemoteUrl:f,onRepoRemoteUrlChange:x,repoIdentity:b,onRepoIdentityChange:k,manualOpen:j,onManualOpenChange:v,creating:_,warning:y,onCreate:w,onCancel:S}=e,{t:C}=ve("common"),A=PP({creating:_,planLoading:g,plan:p,name:a,workspace:u,showDaemonPicker:s,daemonId:c,repoRemoteUrl:f,repoIdentity:b}),O=wx(g,250),L=j||!!f.trim()||!!b.trim(),M=s&&r.length>0&&n.jsxs("select",{className:t==="wizard"?ui:"input w-full",value:c,onChange:B=>d(B.target.value),children:[n.jsx("option",{value:"",children:C("setupWizard.machines.machineSelectPlaceholder")}),r.map(B=>n.jsx("option",{value:B.id,children:o(B)},B.id))]}),$=L?n.jsxs(n.Fragment,{children:[n.jsx(qt,{label:C("mesh.list.remoteUrl"),hint:C("mesh.list.remoteUrlHint"),children:n.jsx(Dn,{value:f,onChange:B=>x(B.target.value),placeholder:"https://github.com/user/repo"})}),n.jsx(qt,{label:C("mesh.list.repoIdentity"),hint:C("mesh.list.repoIdentityHint"),children:n.jsx(Dn,{value:b,onChange:B=>k(B.target.value),placeholder:"github.com/user/repo"})})]}):n.jsx("button",{type:"button",className:"self-start text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-3 bg-transparent border-none cursor-pointer p-0",onClick:()=>v(!0),children:C("mesh.list.advancedIdentityToggle")});return t==="wizard"?n.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:C("setupWizard.machines.meshName")}),n.jsx("input",{type:"text",className:ui,value:a,onChange:B=>i(B.target.value)})]}),s&&r.length>1&&n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:C("setupWizard.machines.machine")}),M]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:C("setupWizard.machines.workspace")}),n.jsx(Yc,{workspaces:h,value:u,onChange:m})]}),n.jsx(Sx,{plan:p,loading:g}),y&&n.jsx("p",{className:"text-2xs text-amber-400",children:y}),n.jsx("div",{className:"flex justify-end",children:n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:w,disabled:A,children:C(_?"setupWizard.machines.creating":"setupWizard.machines.create")})})]}):n.jsxs(n.Fragment,{children:[n.jsx("h3",{className:"text-base font-bold mb-4",children:C("mesh.list.createTitle")}),s&&n.jsx(qt,{label:C("mesh.list.createOnMachine"),children:r.length===0?n.jsx("select",{className:"input w-full",disabled:!0,children:n.jsx("option",{value:"",children:C("mesh.list.noConnectedDaemon")})}):M}),n.jsx(qt,{label:C("mesh.list.workspace"),hint:C("mesh.list.workspaceHint"),children:n.jsx(Yc,{workspaces:h,value:u,onChange:m})}),(O||p)&&n.jsx(zt,{variant:(p==null?void 0:p.success)===!1?"error":mi(p)?"warning":"info",className:"mb-4",children:O?C("setupWizard.machines.planChecking"):(p==null?void 0:p.success)===!1?uu(p):mi(p)?((N=p.plan)==null?void 0:N.summary)||C("setupWizard.machines.planExists"):`${((I=p.plan)==null?void 0:I.summary)||"Git repository detected."} No changes will be made until you click Create.`}),n.jsx(qt,{label:C("mesh.list.name"),children:n.jsx(Dn,{value:a,onChange:B=>i(B.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),n.jsx("div",{className:"flex flex-col",children:$}),n.jsxs("div",{className:"flex gap-2 mt-3",children:[n.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:A,children:C(_?"mesh.list.creating":"mesh.list.create")}),S&&n.jsx("button",{className:"btn btn-secondary btn-sm",onClick:S,disabled:_,children:C("mesh.list.cancel")})]})]})}function LP({size:e=14}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),n.jsx("circle",{cx:"18",cy:"6",r:"3"}),n.jsx("circle",{cx:"6",cy:"18",r:"3"}),n.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function EP({size:e=14}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function DP({size:e=14}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}const OP={online:"#22c55e",dirty:"#f59e0b",offline:"#6b7280",degraded:"#ef4444",enabled:"#22c55e",pending:"#a855f7",assigned:"#3b82f6",completed:"#22c55e",failed:"#ef4444",unknown:"#6b7280"};function $P({status:e}){const{t}=ve("common"),s=OP[e]??"#6b7280",r=e==="degraded"?t("mesh.nodeHealth.degradedHint"):void 0,o=n.jsxs("span",{className:"inline-flex items-center gap-1 text-3xs font-semibold px-2 py-0.5 rounded-md",style:{background:s+"15",color:s,border:`1px solid ${s}25`},children:[n.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:s}}),iT(e,t)]});return r?n.jsx(tn,{content:r,children:o}):o}function jx(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function Qc(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function FP(e,t,s,r,o){if(!e.length)return"";const a=String(o||"");if(a){const d=e.find(u=>on(u.id,a));return d?d.id:a}const i=t.find(d=>d.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const d=e.find(u=>on(u.id,c));if(d)return d.id}return""}function Gi(e,t){var c;if(t.length===1&&((c=t[0])!=null&&c.id))return t[0].id;if(!e)return"";const s=Qc(e.meshHost),r=Array.isArray(e.nodes)?e.nodes:[],o=(s.hostNodeId?r.find(d=>String(d.id)===s.hostNodeId):void 0)??r.find(d=>d.role==="host"),a=s.hostDaemonId||String((o==null?void 0:o.daemon_id)||(o==null?void 0:o.daemonId)||"");if(!a)return"";const i=t.find(d=>on(d.id,a));return i?i.id:a}function HP(e){const t=new Map;for(const s of e)s!=null&&s.id&&t.set(s.id,Zn(s.availableProviders||[]));return t}function BP(e,t){const s=String(e.daemon_id||e.daemonId||"");return s&&t.has(s)?t.get(s):!s&&t.size===1?[...t.values()][0]:[]}function bs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Nx(e){if(!e)return null;const t=bs(e.nodeFacts).availableProviders;if(Array.isArray(t)&&t.length>0)return t;const s=bs(e.heldRuntime).availableProviders;return Array.isArray(s)&&s.length>0?s:null}function WP(e){if(!e)return[];const t=bs(e.nodeFacts),s=Object.keys(bs(e.providerVersions)).length>0?bs(e.providerVersions):bs(t.providerVersions),r=bs(t.providerEnablement);return Object.keys(s).map(o=>o.trim()).filter(o=>o&&bs(r[o]).enabled!==!1)}function UP(e,t,s){const r=Nx(s);if(r)return Zn(r);const o=BP(e,t),a=WP(s);if(a.length===0)return o;if(o.length>0){const i=new Set(a);return o.filter(c=>i.has(c.type))}return Zn(a.map(i=>({type:i,category:"cli",installed:!0})))}function KP(e,t,s){const r=new Map;for(const d of t)d!=null&&d.id&&r.set(d.id,Array.isArray(d.availableProviders)?d.availableProviders:[]);const o=new Set,a=[];let i=0,c=0;for(const d of Array.isArray(e)?e:[]){const u=String((d==null?void 0:d.daemon_id)||(d==null?void 0:d.daemonId)||""),m=mu(d,s),h=Nx(m)??(u?r.get(u):r.size===1?[...r.values()][0]:void 0);if(!h||h.length===0){c++;continue}i++;for(const p of h){const g=String((p==null?void 0:p.type)||(p==null?void 0:p.id)||"").trim();!g||o.has(g)||(o.add(g),a.push(p))}}return a.sort((d,u)=>String((d==null?void 0:d.type)||(d==null?void 0:d.id)||"").localeCompare(String((u==null?void 0:u.type)||(u==null?void 0:u.id)||""))),{providers:a,reportedNodeCount:i,unreportedNodeCount:c}}function mu(e,t){const s=String((e==null?void 0:e.id)||(e==null?void 0:e.nodeId)||"").trim();if(!(!s||!Array.isArray(t)))return t.find(r=>(r==null?void 0:r.nodeId)===s)}function qP(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},s=new Set,r=[],o=a=>{const i=typeof a=="string"?a.trim():"";!i||s.has(i)||(s.add(i),r.push(i))};for(const a of _p(t.slots))o(a.provider);if(Array.isArray(t.providerPriority))for(const a of t.providerPriority)o(a);return r}function zP(e){var d,u;const t=e,s=[],r=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of r){const h=typeof m=="string"?m.trim():"";h&&s.push({tag:h,custom:!0})}const o=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),a=(((u=t.userOverrides)==null?void 0:u.arch)||t.reportedArch||"").toString().trim();o&&s.push({tag:`os=${o}`,custom:!1}),a&&s.push({tag:`arch=${a}`,custom:!1});for(const m of qP(t.policy))s.push({tag:`provider=${m}`,custom:!1});const i=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";t.isLocalWorktree===!0&&i&&s.push({tag:`worktree=${i}`,custom:!1});const c=new Set;return s.filter(m=>c.has(m.tag)?!1:(c.add(m.tag),!0))}function GP(e){return(Array.isArray(e==null?void 0:e.activeSessionDetails)?e.activeSessionDetails:[]).filter(s=>!!(s!=null&&s.sessionId)).map(s=>({id:s.sessionId,provider:s.providerType||"unknown",status:s.chatStatus||s.state||"unknown"}))}function Cx(e){var r,o;if(!e)return null;const t=typeof e.machineStatus=="string"?e.machineStatus.trim():"";if(t)return t;const s=(r=e.connection)==null?void 0:r.state;return s==="self"||s==="connected"?"online":typeof((o=e.gitObservation)==null?void 0:o.unreachableSince)=="number"||s==="failed"||s==="closed"||s==="disconnected"?"offline":null}function VP(e){const t=e==null?void 0:e.nodeFacts,s=typeof(t==null?void 0:t.machineNickname)=="string"&&t.machineNickname.trim()?t.machineNickname.trim():void 0,r=typeof(t==null?void 0:t.platform)=="string"&&t.platform.trim()?t.platform.trim():void 0;return{...s?{machineNickname:s}:{},...r?{platform:r}:{}}}const YP=["","low","medium","high"],QP={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function sp(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function rp(e){const t=e.provider.trim();if(!t)return null;const s=e.model.trim(),r=e.thinkingLevel.trim()||void 0,o=Number(e.maxParallel),a=Number.isFinite(o)&&o>0?Math.floor(o):void 0;return{provider:t,...s?{model:s}:{},...r?{thinkingLevel:r}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...a!==void 0?{maxParallel:a}:{}}}function JP(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const Os="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function XP({slots:e,availableProviders:t,saving:s,onSave:r}){const{t:o}=ve("common"),[a,i]=l.useState(()=>e.map(sp)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(sp))},[c]);const d=l.useMemo(()=>[...new Set(t.map(j=>j.type).filter(Boolean))],[t]),u=l.useMemo(()=>mb(t),[t]),m=l.useMemo(()=>{const j=a.map(rp).filter(Boolean);return JSON.stringify(j)!==JSON.stringify(e)},[a,e]),h=(j,v)=>i(_=>_.map((y,w)=>w===j?{...y,...v}:y)),p=(j,v)=>i(_=>_.map((y,w)=>{var A;if(w!==j)return y;const S=((A=u.get(v))==null?void 0:A.models)??[],C=!y.model||S.length===0||S.includes(y.model);return{...y,provider:v,...C?{}:{model:""}}})),g=j=>i(v=>v.filter((_,y)=>y!==j)),f=()=>i(j=>[...j,JP()]),x=(j,v)=>i(_=>{const y=j+v;if(y<0||y>=_.length)return _;const w=[..._];return[w[j],w[y]]=[w[y],w[j]],w}),b=(j,v)=>i(_=>_.map((y,w)=>{if(w!==j)return y;const S=y.difficulty.includes(v);return{...y,difficulty:S?y.difficulty.filter(C=>C!==v):[...y.difficulty,v]}})),k=()=>r(a.map(rp).filter(Boolean));return n.jsxs("div",{className:"flex flex-col gap-2",onClick:j=>j.stopPropagation(),children:[a.length===0&&n.jsxs("div",{className:"flex items-center gap-1 text-xs text-text-muted",children:[n.jsx("span",{children:o("mesh.slotEditor.empty")}),n.jsx(dt,{content:o("mesh.slotEditor.emptyHint"),size:12})]}),a.map((j,v)=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[n.jsxs("span",{className:"text-2xs font-semibold text-text-muted",children:["#",v+1]}),n.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[n.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:v===0,onClick:()=>x(v,-1),title:o("mesh.slotEditor.moveUp"),children:"↑"}),n.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:v===a.length-1,onClick:()=>x(v,1),title:o("mesh.slotEditor.moveDown"),children:"↓"}),n.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>g(v),"aria-label":o("mesh.slotEditor.removeSlot"),children:n.jsx(Bt,{size:12})})]})]}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.provider")}),d.length>0?n.jsxs("select",{className:Os,value:j.provider,onChange:_=>p(v,_.target.value),children:[n.jsx("option",{value:"",children:o("mesh.slotEditor.select")}),d.map(_=>n.jsx("option",{value:_,children:_},_)),j.provider&&!d.includes(j.provider)&&n.jsx("option",{value:j.provider,children:j.provider})]}):n.jsx("input",{className:Os,value:j.provider,placeholder:"claude-cli",onChange:_=>h(v,{provider:_.target.value})})]}),(()=>{var C;const _=u.get(j.provider),y=(_==null?void 0:_.models)??[],w=(C=_==null?void 0:_.thinking)!=null&&C.length?["",..._.thinking]:YP,S=!!j.model&&y.length>0&&!y.includes(j.model);return n.jsxs(n.Fragment,{children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.model")}),y.length>0&&!S?n.jsxs("select",{className:Os,value:y.includes(j.model)?j.model:"",onChange:A=>h(v,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[n.jsx("option",{value:"",children:o("mesh.slotEditor.providerDefault")}),y.map(A=>n.jsx("option",{value:A,children:A},A)),n.jsx("option",{value:"__custom__",children:o("mesh.slotEditor.custom")})]}):n.jsxs(n.Fragment,{children:[n.jsx("input",{className:Os,value:j.model.trim(),placeholder:j.provider?`${j.provider} model`:o("mesh.slotEditor.modelPlaceholder"),onChange:A=>h(v,{model:A.target.value})}),y.length>0&&n.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-3xs text-text-muted hover:underline",onClick:()=>h(v,{model:""}),children:o("mesh.slotEditor.backToModelList")})]})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.thinking")}),n.jsx("select",{className:Os,value:j.thinkingLevel,onChange:A=>h(v,{thinkingLevel:A.target.value}),children:w.map(A=>n.jsx("option",{value:A,children:A||o("mesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),n.jsxs("div",{className:"mt-2",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.difficulty")}),n.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:Cp.map(_=>{const y=j.difficulty.includes(_);return n.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-2xs font-medium transition-colors ${y?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>b(v,_),children:QP[_]},_)})})]}),n.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.capabilityTags")}),n.jsx("input",{className:Os,value:j.capability.join(", "),placeholder:"worktree, os=darwin",onChange:_=>h(v,{capability:_.target.value.split(",").map(y=>y.trim()).filter(Boolean)})})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.maxParallel")}),n.jsx("input",{type:"number",inputMode:"numeric",min:1,className:Os,value:j.maxParallel,placeholder:o("mesh.slotEditor.maxParallelPlaceholder"),onChange:_=>h(v,{maxParallel:_.target.value})})]})]})]},v)),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:f,children:[n.jsx(_o,{size:13})," ",o("mesh.slotEditor.addSlot")]}),n.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:k,disabled:!!s||!m,children:o(s?"mesh.slotEditor.saving":"mesh.slotEditor.saveSlots")})]})]})}function ZP(e){const t=e.capabilities;return Array.isArray(t)?t.map(s=>typeof s=="string"?s.trim():"").filter(Boolean):[]}const eL=["os=","arch=","provider=","worktree=","converge="];function tL({node:e,saving:t,onSave:s}){const{t:r}=ve("common"),o=l.useMemo(()=>zP(e).filter(x=>!x.custom),[e]),a=l.useMemo(()=>ZP(e),[e]),[i,c]=l.useState(a),[d,u]=l.useState(""),m=JSON.stringify(i)!==JSON.stringify(a),p=(x=>{const b=x.trim();return b?/\s/.test(b)?r("mesh.tagEditor.noSpaces"):eL.some(k=>b.toLowerCase().startsWith(k))?r("mesh.tagEditor.reservedPrefix"):i.includes(b)?r("mesh.tagEditor.alreadyAdded"):null:null})(d);function g(){const x=d.trim();!x||p||(c(b=>[...b,x]),u(""))}function f(x){c(b=>b.filter(k=>k!==x))}return n.jsxs("div",{className:"mt-2",onClick:x=>x.stopPropagation(),children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[n.jsx("span",{className:"text-3xs uppercase tracking-wide text-text-muted mr-1",children:r("mesh.tagEditor.routingTags")}),o.map(x=>n.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-3xs text-text-muted",title:r("mesh.tagEditor.autoDerivedTitle"),children:x.tag},x.tag)),i.map(x=>n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-3xs text-accent-primary",title:r("mesh.tagEditor.customTagTitle"),children:[x,n.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>f(x),disabled:t,"aria-label":r("mesh.tagEditor.remove",{tag:x}),children:"×"})]},x))]}),n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[n.jsx("input",{type:"text",value:d,onChange:x=>u(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),g())},placeholder:r("mesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-xs text-text-primary"}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:g,disabled:t||!d.trim()||!!p,children:r("mesh.tagEditor.add")}),m&&n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>s(i),disabled:t,children:r(t?"mesh.tagEditor.saving":"mesh.tagEditor.saveTags")})]}),p&&n.jsx("div",{className:"mt-1 text-2xs text-amber-400",children:p}),i.length===0&&o.length===0&&n.jsxs("div",{className:"mt-1 flex items-center gap-1 text-2xs text-text-muted",children:[n.jsx("span",{children:r("mesh.tagEditor.empty")}),n.jsx(dt,{content:r("mesh.tagEditor.emptyHint"),size:12})]})]})}function nL(e,t){var s;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((s=e==null?void 0:e.user)==null?void 0:s.name)||t||"You"}function op({nodes:e,statusNodes:t,meshQueue:s,daemons:r,userName:o,features:a,providersByDaemonId:i,savingNodeSlotsId:c,onUpdateNodeSlots:d,savingNodeCapabilitiesId:u,onUpdateNodeCapabilities:m,nodeSystemPromptDrafts:h,onNodeSystemPromptDraftChange:p,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:f,selectedNodeId:x,onSelectNode:b,onRemoveNode:k}){const{t:j}=ve("common"),[v,_]=l.useState(()=>new Set),y=w=>_(S=>{const C=new Set(S);return C.has(w)?C.delete(w):C.add(w),C});return e.length===0?n.jsx(Bi,{variant:"compact",icon:n.jsx(Zs,{size:14}),title:j("mesh.nodeList.emptyTitle"),description:j("mesh.nodeList.emptyDescription")}):n.jsx("div",{className:"flex flex-col gap-2",children:e.map(w=>{var T;const S=aL(w),C=sL(w,s),A=mu(w,t),O=GP(A),L=x===w.id,M=v.has(w.id),$=Cx(A)||w.status||(C.length>0||O.length>0?"active":"enabled"),N=a.addNodeDaemonPicker?w.machine_label||w.machine_nickname||w.hostname||w.workspace:w.workspace.split("/").pop()||w.workspace,I=S.configured?S.label.split(" → "):[],B=a.addNodeDaemonPicker?j("mesh.nodeList.ownerMachine",{owner:nL(r.find(F=>F.id===String(w.daemon_id||"")),o),machine:w.machine_label||w.daemon_id||w.workspace}):null;return n.jsxs("div",{className:`rounded-xl border bg-bg-glass px-4 py-3 transition-colors ${a.addNodeDaemonPicker?"border-border-subtle":`cursor-pointer ${L?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:a.addNodeDaemonPicker?void 0:"button",tabIndex:a.addNodeDaemonPicker?void 0:0,onClick:a.addNodeDaemonPicker?void 0:()=>b(L?null:w.id),onKeyDown:a.addNodeDaemonPicker?void 0:F=>{F.target===F.currentTarget&&(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),b(L?null:w.id))},children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[n.jsx("span",{className:"truncate text-sm font-semibold text-text-primary",title:w.workspace,children:N}),a.addNodeDaemonPicker&&n.jsx($P,{status:$}),!S.configured&&n.jsx(tn,{content:j("mesh.nodeList.launchBlocked"),children:n.jsx("span",{className:"rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-3xs font-medium text-amber-400",children:j("mesh.nodeList.launchBlockedChip")})})]}),n.jsxs("div",{className:"mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 text-2xs text-text-muted",children:[I.length>0&&n.jsx("span",{className:"truncate",children:j("mesh.nodeList.usesTools",{tools:I.join(", ")})}),a.addNodeDaemonPicker&&n.jsx("span",{className:"truncate font-mono text-3xs",title:w.workspace,children:w.workspace.split("/").filter(Boolean).pop()||w.workspace})]})]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0","aria-expanded":M,onClick:F=>{F.stopPropagation(),y(w.id)},children:j(M?"common.done":"common.edit")}),n.jsx("button",{type:"button",className:"shrink-0 bg-transparent border-none cursor-pointer text-text-muted transition-colors hover:text-red-400",onClick:F=>{F.stopPropagation(),k(w.id)},"aria-label":j("mesh.nodeList.removeNode"),title:j("mesh.nodeList.removeNode"),children:n.jsx(EP,{size:14})})]}),M&&n.jsxs("div",{className:"mt-3 max-w-2xl cursor-default",onClick:F=>F.stopPropagation(),children:[n.jsx(qt,{label:j("mesh.nodeList.slotsLabel"),hint:j("mesh.nodeList.slotsHint"),children:n.jsx(XP,{slots:Array.isArray((T=w.policy)==null?void 0:T.slots)?w.policy.slots:[],availableProviders:UP(w,i,A),saving:c===w.id,onSave:F=>d(w,F)})}),n.jsxs("details",{className:"group",children:[n.jsxs("summary",{className:"cursor-pointer select-none text-xs text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[n.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",j("mesh.nodeList.advanced")]}),n.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[n.jsx(tL,{node:w,saving:u===w.id,onSave:F=>m(w,F)}),a.nodeInstruction&&n.jsxs(qt,{label:j("mesh.nodeList.nodeInstruction"),hint:j("mesh.nodeList.nodeInstructionHint"),className:"mb-0",children:[n.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:h[w.id]??"",onChange:F=>{const q=F.target.value;p(w.id,q)},disabled:g===w.id,placeholder:j("mesh.nodeList.nodeInstructionPlaceholder")}),n.jsx("div",{className:"mt-2 flex items-center gap-2",children:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>f(w),disabled:g===w.id,children:g===w.id?j("mesh.nodeList.saving"):j("mesh.nodeList.saveInstruction")})})]}),n.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-xs text-text-muted",children:[B&&n.jsx("div",{className:"mb-2",children:B}),n.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary",children:j("mesh.nodeList.repoRoot")})," ",n.jsx("span",{className:"font-mono break-all",children:w.repoRoot||w.workspace})]}),n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary",children:j("mesh.nodeList.activeSessionsLabel")})," ",O.length]}),a.addNodeDaemonPicker&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary",children:j("mesh.nodeList.added")})," ",gd(w.created_at||w.createdAt)||"—"]})]}),n.jsxs("div",{className:"mt-3",children:[n.jsx("div",{className:"text-text-secondary mb-1",children:j("mesh.nodeList.activeQueueAssignments")}),C.length===0?n.jsx("div",{children:j("mesh.nodeList.noActiveAssignment")}):n.jsx("ul",{className:"m-0 pl-4",children:C.map(F=>n.jsx("li",{className:"font-mono",children:rL(F)},F.id))})]}),O.length>0&&n.jsxs("div",{className:"mt-3",children:[n.jsx("div",{className:"text-text-secondary mb-1",children:j("mesh.nodeList.activeSessions")}),n.jsx("ul",{className:"m-0 pl-4",children:O.map(F=>n.jsxs("li",{className:"font-mono",children:[F.provider," / ",F.status]},F.id))})]}),n.jsx(Od,{className:"mt-3",rows:[{label:j("mesh.nodeList.nodeId"),value:w.id},...O.map(F=>({label:j("mesh.nodeList.activeSessions"),value:F.id}))]})]})]})]})]})]},w.id)})})}function sL(e,t){return t.filter(s=>s.status!=="assigned"?!1:(s.assignedNodeId||s.nodeId)===e.id)}function rL(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",s=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${s}`}function oL(e){var o,a;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((o=e.policy)==null?void 0:o.providerPriority)?e.policy.providerPriority:[],s=new Set,r=t.map(i=>typeof i=="string"?i.trim():"").filter(Boolean).filter(i=>s.has(i)?!1:(s.add(i),!0));return r.length?r:wy((a=e.policy)==null?void 0:a.slots)}function aL(e){const t=oL(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider configured on this node — task launch is blocked until a capability slot or provider priority is set."}}function Jc(e){return e.isLocalWorktree===!0}function hi(e){return e&&(e.machineNickname||e.nickname||e.hostname||(e.id?yb(e.id):void 0))||"Unknown"}function iL(e){return String(e.daemon_id||e.daemonId||"")}function _x(e,t,s){const r=new Map(t.map(i=>[i.id,i])),o=[],a=new Map;for(const i of e){const c=iL(i);a.has(c)||(a.set(c,[]),o.push(c)),a.get(c).push(i)}return o.map(i=>{const c=a.get(i),d=i?r.get(i):void 0,u=c[0],m=c.map(b=>mu(b,s)).filter(b=>!!b),h=m.map(b=>VP(b).machineNickname).find(Boolean),p=i?h||(d?hi(d):(u==null?void 0:u.machine_label)||(u==null?void 0:u.machine_nickname)||(u==null?void 0:u.hostname)||i):hi(d),g=m.map(b=>Cx(b)).filter(b=>!!b),f=g.length>0?g.includes("online"):(d==null?void 0:d.status)==="online",x=c.reduce((b,k)=>{var j;return b+(Array.isArray((j=k.policy)==null?void 0:j.slots)?k.policy.slots.length:0)},0);return{key:i,label:p,online:f,nodes:c,slotCount:x}})}function lL({groups:e,activeKey:t,onChange:s}){const{t:r}=ve("common");return n.jsx(Vd,{variant:"underline",ariaLabel:r("mesh.nodeList.machineTabsLabel"),activeKey:t,onSelect:s,className:"mb-4 px-1 md:px-1",tabs:e.map(o=>({key:o.key,icon:n.jsx("span",{"aria-hidden":!0,className:`w-1.5 h-1.5 rounded-full shrink-0 ${o.online?"bg-green-400":"bg-neutral-500"}`}),label:n.jsx("span",{className:"truncate max-w-[160px]",children:o.label}),trailing:n.jsx("span",{className:"text-2xs text-text-muted font-normal",children:r("mesh.nodeList.machineTabCounts",{nodes:o.nodes.length,slots:o.slotCount})})}))})}function cL({nodes:e,statusNodes:t,meshQueue:s,activeDaemon:r,daemons:o,selectedMeshId:a,userName:i,features:c,coordinatorDaemonId:d,availableCliProviders:u,savingNodeSlotsId:m,onUpdateNodeSlots:h,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:g,nodeSystemPromptDrafts:f,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:b,onSaveNodeSystemPrompt:k,selectedNodeId:j,onSelectNode:v,showAddNode:_,onShowAddNode:y,onCancelAddNode:w,nodeWorkspace:S,onNodeWorkspaceChange:C,nodeProviderPriority:A,onNodeProviderPriorityChange:O,nodeDaemonId:L,onNodeDaemonIdChange:M,nodeCustomPath:$,onNodeCustomPathChange:N,nodePickerWorkspaces:I,nodePickerProviders:B,nodeOnboardingPlan:T,nodePlanLoading:F,attachableDaemons:q,onAddNode:Q,onRemoveNode:K}){var be,V,we;const{t:R}=ve("common"),D=l.useMemo(()=>HP(o),[o]),P=l.useMemo(()=>e.filter(ce=>!Jc(ce)),[e]),H=l.useMemo(()=>c.addNodeDaemonPicker?_x(P,o,t):[],[c.addNodeDaemonPicker,P,o,t]),[W,U]=l.useState(null),ae=H.some(ce=>ce.key===W)?W:((be=H[0])==null?void 0:be.key)??"";return n.jsxs(Nt,{title:c.addNodeDaemonPicker?R("mesh.nodeList.title",{count:P.length}):R("mesh.nodeList.titleNoCount"),description:c.addNodeDaemonPicker?R("mesh.nodeList.descriptionCloud"):R("mesh.nodeList.descriptionStandalone"),children:[c.addNodeDaemonPicker&&n.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[n.jsx("div",{className:"min-w-0 text-sm font-semibold text-text-primary",children:R("mesh.nodeList.daemonCandidates")}),n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:R("mesh.nodeList.available",{count:q.length})})]}),o.length===0?n.jsx("div",{className:"text-xs text-text-muted",children:R("mesh.nodeList.noDaemonsAvailable")}):q.length===0?n.jsx("div",{className:"text-xs text-text-muted",children:R("mesh.nodeList.allDaemonsAttached")}):n.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:q.map(ce=>n.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors min-w-0 ${ce.id===d?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{M(ce.id),C(""),N(!1),O(nr(Zn(ce.availableProviders||[]))),y()},children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-sm font-medium truncate min-w-0",children:hi(ce)}),ce.id===d&&n.jsx("span",{className:"text-3xs text-accent-primary shrink-0",children:R("mesh.nodeList.selectedHost")})]}),n.jsx("div",{className:"mt-1 text-2xs text-text-muted",children:R("mesh.nodeList.workspacesDetected",{count:(ce.workspaces||[]).length})})]},ce.id))})]}),!_&&n.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:y,children:[n.jsx(DP,{size:13})," ",c.addNodeDaemonPicker?R("mesh.nodeList.attachMachine"):R("mesh.nodeList.addNode")]}),_&&n.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[n.jsxs("div",{className:"flex justify-between items-center mb-3",children:[n.jsx("h4",{className:"text-sm font-bold",children:c.addNodeDaemonPicker?R("mesh.nodeList.attachMachineTitle"):R("mesh.nodeList.addNodeTitle")}),n.jsx("button",{onClick:()=>{w(),M(""),N(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:n.jsx(Bt,{size:16})})]}),c.addNodeDaemonPicker&&n.jsx(qt,{label:R("mesh.nodeList.machine"),children:n.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:L,onChange:ce=>{var de;M(ce.target.value),C(""),N(!1),O(nr(Zn(((de=o.find(ne=>ne.id===ce.target.value))==null?void 0:de.availableProviders)||[])))},children:[n.jsx("option",{value:"",children:R("mesh.nodeList.selectMachine")}),o.map(ce=>n.jsx("option",{value:ce.id,children:hi(ce)},ce.id))]})}),(c.addNodeDaemonPicker?L:!0)&&n.jsx(qt,{label:R("mesh.nodeList.workspacePath"),children:c.addNodeDaemonPicker&&!$&&I.length>0?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:I.map(ce=>n.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${S===ce.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>C(ce.path),children:[n.jsx("span",{className:"font-medium block truncate",children:ce.label||ce.path.split("/").pop()}),n.jsx("span",{className:"text-3xs text-text-muted font-mono truncate block",children:ce.path})]},ce.id||ce.path))}),n.jsx("button",{type:"button",className:"text-2xs text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{N(!0),C("")},children:R("mesh.nodeList.enterCustomPath")})]}):n.jsx(n.Fragment,{children:c.addNodeDaemonPicker?n.jsxs(n.Fragment,{children:[n.jsx(Dn,{value:S,onChange:ce=>C(ce.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:ce=>{ce.key==="Enter"&&Q()}}),I.length>0&&n.jsx("button",{type:"button",className:"text-2xs text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{N(!1),C("")},children:R("mesh.nodeList.pickFromSaved")})]}):(()=>{var ne;const ce=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],de=`mesh-add-node-workspaces-${a||"new"}`;return n.jsxs(n.Fragment,{children:[n.jsx(Dn,{value:S,onChange:ee=>C(ee.target.value),placeholder:((ne=ce[0])==null?void 0:ne.path)||"/Users/dev/projects/myapp",list:ce.length>0?de:void 0,autoFocus:!0}),ce.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("datalist",{id:de,children:ce.map(ee=>n.jsx("option",{value:ee.path,children:ee.label||ee.path},ee.id||ee.path))}),n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ce.slice(0,6).map(ee=>n.jsx("button",{type:"button",onClick:()=>C(ee.path),className:"text-2xs px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:ee.path,children:ee.label||ee.path.split("/").filter(Boolean).pop()||ee.path},ee.id||ee.path))})]})]})})()})}),(F||T)&&n.jsx(zt,{variant:(T==null?void 0:T.success)===!1?"error":"info",className:"mb-4",children:F?R("mesh.nodeList.inspectingRepo"):T!=null&&T.success?`${((V=T.plan)==null?void 0:V.summary)||R("mesh.nodeList.compatibleWorkspace")} ${R("mesh.nodeList.addingIsExplicit")}`:uu(T)}),n.jsx(qt,{label:R("mesh.nodeList.preferredTools"),hint:R("mesh.nodeList.preferredToolsHint"),children:n.jsx(DA,{value:A,availableProviders:c.addNodeDaemonPicker?B:u,onChange:O})}),n.jsxs("div",{className:"flex gap-2 mt-3",children:[n.jsx("button",{onClick:Q,disabled:F||(T==null?void 0:T.success)===!1||!S.trim()||c.addNodeDaemonPicker&&!L,className:"btn btn-primary btn-sm",children:R("mesh.nodeList.add")}),n.jsx("button",{onClick:()=>{w(),M(""),N(!1)},className:"btn btn-secondary btn-sm",children:R("mesh.nodeList.cancel")})]})]}),P.length===0?n.jsx(Bi,{icon:n.jsx(Zs,{}),title:R("mesh.nodeList.emptyTitle"),description:R("mesh.nodeList.emptyDescription")}):c.addNodeDaemonPicker?n.jsxs(n.Fragment,{children:[H.length>1&&n.jsx(lL,{groups:H,activeKey:ae,onChange:U}),n.jsx(op,{nodes:((we=H.find(ce=>ce.key===ae))==null?void 0:we.nodes)||P,statusNodes:t,meshQueue:s,daemons:o,userName:i,features:c,providersByDaemonId:D,savingNodeSlotsId:m,onUpdateNodeSlots:h,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:g,nodeSystemPromptDrafts:f,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:b,onSaveNodeSystemPrompt:k,selectedNodeId:j,onSelectNode:v,onRemoveNode:K})]}):n.jsx(op,{nodes:P,statusNodes:t,meshQueue:s,daemons:o,userName:i,features:c,providersByDaemonId:D,savingNodeSlotsId:m,onUpdateNodeSlots:h,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:g,nodeSystemPromptDrafts:f,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:b,onSaveNodeSystemPrompt:k,selectedNodeId:j,onSelectNode:v,onRemoveNode:K})]})}function dL(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function uL({meshes:e,loading:t,error:s,onDismissError:r,daemons:o,features:a,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:u,createRepoIdentity:m,onCreateRepoIdentityChange:h,createRepoRemoteUrl:p,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:f,onNewMeshDaemonIdChange:x,newMeshWorkspace:b,onNewMeshWorkspaceChange:k,createPickerWorkspaces:j,createOnboardingPlan:v,createPlanLoading:_,creating:y,createWarning:w,onDismissCreateWarning:S,onSelectMesh:C,onCreate:A,onCancelCreate:O,sendCommand:L}){const{t:M}=ve("common"),[$,N]=l.useState(!1),[I,B]=l.useState(null);return n.jsxs(Wo,{icon:n.jsx(On,{}),title:M("mesh.list.title"),subtitle:M("mesh.list.count",{count:e.length}),subtitleInline:!0,widthClassName:"max-w-5xl",actions:n.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,children:M("mesh.list.createMesh")}),children:[s&&n.jsx(zt,{variant:"error",onDismiss:r,className:"mb-4",children:s}),w&&n.jsx(zt,{variant:"warning",onDismiss:S,className:"mb-4",children:w}),i&&n.jsx(Nt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:n.jsx(kx,{variant:"page",showDaemonPicker:a.createDaemonPicker,daemons:o,daemonLabel:dL,name:d,onNameChange:u,daemonId:f,onDaemonIdChange:x,workspace:b,onWorkspaceChange:k,workspaces:j,plan:v,planLoading:_,repoRemoteUrl:p,onRepoRemoteUrlChange:g,repoIdentity:m,onRepoIdentityChange:h,manualOpen:$,onManualOpenChange:N,creating:y,onCreate:A,onCancel:O})}),t?n.jsx("div",{className:"text-sm text-text-muted p-4",children:M("mesh.list.loading")}):e.length===0?n.jsx(Bi,{icon:n.jsx(On,{}),title:M("mesh.list.emptyTitle"),description:o.length>0?M("mesh.list.emptyWithDaemons"):M("mesh.list.emptyNoDaemons"),action:n.jsx("button",{className:"btn btn-primary btn-sm",disabled:!o.length,onClick:c,children:M("mesh.list.createFirst")})}):n.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(T=>{const F=Array.isArray(T.nodes)?T.nodes:[],q=_x(F.filter(H=>H.isLocalWorktree!==!0),o).filter(H=>H.key),Q=q.filter(H=>H.online).length,K=Gi(T,o),R=!!K&&o.some(H=>on(H.id,K)&&(H.status===void 0||H.status==="online")),D=T.createdAt||T.created_at,P=q.length===0?"bg-neutral-500":Q===q.length?"bg-green-400":Q===0?"bg-red-400":"bg-amber-400";return n.jsxs("div",{className:"flex w-full flex-col gap-3 rounded-xl border border-border-subtle bg-bg-glass px-4 py-3.5 transition-colors hover:border-border-default sm:flex-row sm:items-center",children:[n.jsxs("button",{type:"button",onClick:()=>C(T.id),className:"min-w-0 flex-1 cursor-pointer border-none bg-transparent p-0 text-left",children:[n.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[n.jsx(On,{size:16}),n.jsx("span",{className:"truncate text-sm font-bold text-text-primary",children:T.name})]}),n.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs text-text-muted",children:[n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx("span",{"aria-hidden":!0,className:`h-1.5 w-1.5 rounded-full ${P}`}),q.length>0?M("mesh.list.machinesOnline",{online:Q,total:q.length}):M("mesh.list.nodeCount",{count:F.length||T.nodeCount||0})]}),n.jsx("span",{className:"truncate font-mono",children:T.repoIdentity||T.repo_identity||M("mesh.list.noRepoIdentity")}),(T.defaultBranch||T.default_branch)&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(LP,{size:11}),T.defaultBranch||T.default_branch]}),D&&n.jsx(tn,{content:Do(D),children:n.jsx("span",{children:gd(D)})})]})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>C(T.id),children:M("mesh.list.settings")}),L&&n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",disabled:!R,title:R?void 0:M("mesh.detail.observabilityDisabledTitle"),onClick:()=>B({meshId:T.id,daemonId:K,meshName:T.name}),children:M("mesh.list.open")})]})]},T.id)})}),I&&L&&n.jsx(Kd,{activeConv:jx(I),sendDaemonCommand:L,onClose:()=>B(null)})]})}const mL={default:"border-white/10 bg-white/[0.04] text-slate-200",good:"border-emerald-400/20 bg-emerald-500/10 text-emerald-200",warn:"border-amber-400/20 bg-amber-500/10 text-amber-100",danger:"border-rose-400/20 bg-rose-500/10 text-rose-100",info:"border-sky-400/20 bg-sky-500/10 text-sky-100"},hL={default:"border-slate-300 bg-white/95 text-slate-700",good:"border-emerald-300 bg-emerald-50 text-emerald-700",warn:"border-amber-300 bg-amber-50 text-amber-700",danger:"border-rose-300 bg-rose-50 text-rose-700",info:"border-sky-300 bg-sky-50 text-sky-700"},pL={default:"border-white/10 bg-white/[0.04] text-slate-200 hover:bg-white/[0.08]",info:"border-sky-400/25 bg-sky-500/10 text-sky-100 hover:bg-sky-500/16",success:"border-emerald-400/25 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/16"},fL={default:"border-slate-300 bg-white text-slate-700 hover:bg-slate-50",info:"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"};function hu(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-3xs text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",blueprintShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-sky-200 bg-[radial-gradient(circle_at_top,_rgba(14,116,233,0.10),_rgba(240,247,255,0.98)_46%,_rgba(248,251,255,1))]",blueprintGridFineColor:"rgba(59, 130, 246, 0.10)",blueprintGridAccentColor:"rgba(59, 130, 246, 0.20)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center bg-[rgba(15,23,42,0.82)] px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",dialogShellClass:"flex shrink-0 h-[calc(100dvh-32px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-2rem)] w-full flex-col overflow-hidden rounded-[20px] border border-slate-200 bg-white shadow-[0_18px_60px_rgba(15,23,42,0.35)] md:h-[calc(100dvh-32px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-2 border-b border-slate-200 bg-white/96 px-4 pb-0 pt-4 backdrop-blur md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-2xs uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-500",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-slate-200/80 py-0.5 text-2xs",panelFieldLabelClass:"shrink-0 text-slate-500",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-3xs text-sky-700",badge:t=>hL[t],actionButton:t=>fL[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-3xs text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",blueprintShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-sky-400/15 bg-[radial-gradient(circle_at_top,_rgba(30,84,164,0.22),_rgba(6,17,38,0.99)_46%,_rgba(3,10,26,1))]",blueprintGridFineColor:"rgba(96, 165, 250, 0.10)",blueprintGridAccentColor:"rgba(96, 165, 250, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center bg-[#030617]/[0.92] px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",dialogShellClass:"flex shrink-0 h-[calc(100dvh-32px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-2rem)] w-full flex-col overflow-hidden rounded-[20px] border border-white/10 bg-slate-950 shadow-[0_18px_60px_rgba(2,6,23,0.6)] md:h-[calc(100dvh-32px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-2 border-b border-white/10 bg-slate-950/92 px-4 pb-0 pt-4 backdrop-blur md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-2xs uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-400",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-white/6 py-0.5 text-2xs",panelFieldLabelClass:"shrink-0 text-slate-400",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-3xs text-blue-300",badge:t=>mL[t],actionButton:t=>pL[t]}}const gL=["claude-cli","codex-cli","hermes-cli","antigravity-cli"],bL=[{kind:"rca",labelKey:"mesh.magiKind.kindRca",hint:"rca"},{kind:"design",labelKey:"mesh.magiKind.kindDesign",hint:"design"},{kind:"claim_audit",labelKey:"mesh.magiKind.kindClaimAudit",hint:"claim_audit"},{kind:"freeform",labelKey:"mesh.magiKind.kindFreeform",hint:"freeform"}];function xL(){return{nodeId:"",provider:"",model:"",n:""}}function ap(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function yL(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function vL(e){const t=[];for(let s=0;s<e.length;s++){const r=e[s],o=r.provider.trim();if(!o)return{error:{code:"provider_required",slot:s+1}};const a=r.nodeId.trim(),i=r.model.trim(),c=r.n.trim();let d;if(c){const u=Number(c);if(!Number.isFinite(u)||u<1)return{error:{code:"replica_min",slot:s+1}};d=Math.floor(u)}t.push({provider:o,...a?{nodeId:a}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function wL({status:e,daemonId:t,sendDaemonCommand:s,availableProviders:r,meshId:o}){const{t:a}=ve(),{theme:i}=Uo(),c=l.useMemo(()=>hu(i),[i]),d=l.useMemo(()=>mb(r),[r]),[u,m]=l.useState({}),[h,p]=l.useState(!1),[g,f]=l.useState(null),[x,b]=l.useState({}),[k,j]=l.useState(null),v=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(P=>({nodeId:P.nodeId,machineLabel:P.machineLabel,providers:P.providers,providerPriority:P.providerPriority,isLocalWorktree:P.isLocalWorktree,worktreeBranch:P.worktreeBranch})),[e==null?void 0:e.nodes]),_=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(P=>P.nodeId),[e==null?void 0:e.nodes]),y=l.useMemo(()=>new Set(v.filter(Jc).map(P=>P.nodeId)),[v]),w=l.useMemo(()=>Object.fromEntries(v.filter(Jc).map(P=>[P.nodeId,P.worktreeBranch])),[v]),S=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(P=>[P.nodeId,uT(P)||P.nodeId])),[e==null?void 0:e.nodes]),C=l.useMemo(()=>{const P={};for(const H of v)P[H.nodeId]=ap(H);return P},[v]),A=l.useMemo(()=>{const P=[...new Set(v.flatMap(ap).filter(Boolean))];return[...new Set([...P,...gL])].sort()},[v]),O=!!t&&!!s,L=P=>P&&typeof P=="object"&&"result"in P?P.result:P,M=o??(e==null?void 0:e.meshId),$=l.useCallback(async()=>{if(!(!t||!s)){p(!0),f(null);try{const P=await s(t,"magi_kind_panel_list",{...M?{meshId:M}:{}}),H=L(P);if((H==null?void 0:H.success)===!1)throw new Error(H.error||a("mesh.magiKind.errorLoad"));m(H!=null&&H.kindPanels&&typeof H.kindPanels=="object"?H.kindPanels:{}),b({})}catch(P){f((P==null?void 0:P.message)||a("mesh.magiKind.errorLoad"))}finally{p(!1)}}},[t,s,M,a]);l.useEffect(()=>{$()},[$]);const N=l.useCallback(P=>{if(x[P])return x[P];const H=u[P];return H?H.map(yL):[]},[x,u]),I=(P,H)=>{b(W=>({...W,[P]:H}))},B=(P,H,W)=>{const U=N(P);I(P,U.map((ae,be)=>be===H?{...ae,...W}:ae))},T=P=>{I(P,[...N(P),xL()])},F=(P,H)=>{I(P,N(P).filter((W,U)=>U!==H))},q=l.useCallback(async P=>{if(!t||!s)return;const H=vL(N(P));if("error"in H){const W=H.error,U=W.code==="provider_required"?a("mesh.magiKind.errorSlotProvider",{slot:W.slot}):W.code==="replica_min"?a("mesh.magiKind.errorSlotReplica",{slot:W.slot}):a("mesh.magiKind.errorNoSlot");f(`${P}: ${U}`);return}j(P),f(null);try{const W=await s(t,"magi_kind_panel_set",{kind:P,slots:H.slots,...M?{meshId:M}:{}}),U=L(W);if((U==null?void 0:U.success)===!1)throw new Error(U.error||a("mesh.magiKind.errorSave"));await $()}catch(W){f((W==null?void 0:W.message)||a("mesh.magiKind.errorSave"))}finally{j(null)}},[t,s,N,$,M,a]),Q=l.useCallback(async P=>{if(!(!t||!s)&&confirm(a("mesh.magiKind.removeConfirm",{kind:P}))){j(P),f(null);try{const H=await s(t,"magi_kind_panel_remove",{kind:P,...M?{meshId:M}:{}}),W=L(H);if((W==null?void 0:W.success)===!1)throw new Error(W.error||a("mesh.magiKind.errorRemove"));await $()}catch(H){f((H==null?void 0:H.message)||a("mesh.magiKind.errorRemove"))}finally{j(null)}}},[t,s,$,M,a]),K=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${c.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,R="btn btn-primary btn-sm",D="btn btn-secondary btn-sm";return n.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[n.jsx("div",{className:"flex flex-wrap items-center gap-2",children:n.jsx("div",{className:"ml-auto flex items-center gap-2",children:n.jsx("button",{type:"button",className:D,onClick:()=>void $(),disabled:h||!O,children:a(h?"mesh.magiKind.loading":"mesh.magiKind.refresh")})})}),!O&&n.jsx("div",{className:`rounded-xl border p-3 text-xs ${c.textSecondary} ${c.isDark?"border-white/10":"border-slate-200"}`,children:a("mesh.magiKind.connectPrompt")}),g&&n.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-xs text-rose-300",children:g}),n.jsx("div",{className:"flex flex-col gap-3",children:bL.map(({kind:P,labelKey:H,hint:W})=>{const U=N(P),ae=!!u[P],be=k===P;return n.jsxs("div",{className:`${c.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:`text-xxs font-semibold ${c.textPrimary}`,children:a(H)}),n.jsx("span",{className:`font-mono text-3xs ${c.textMuted}`,children:W}),n.jsx("span",{className:`rounded-full border px-2 py-0.5 text-3xs uppercase tracking-[0.14em] ${ae?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:ae?a("mesh.magiKind.agentCount",{count:u[P].length}):a("mesh.magiKind.off")})]}),n.jsxs("div",{className:"flex flex-col gap-2",children:[U.length===0&&n.jsx("div",{className:`rounded-xl border p-2.5 text-2xs ${c.textSecondary} ${c.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:a("mesh.magiKind.noAgents")}),U.map((V,we)=>{const ce=V.nodeId?C[V.nodeId]??[]:[],de=V.nodeId&&ce.length?ce:A;return n.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${c.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:`text-4xs uppercase tracking-wide ${c.textSecondary}`,children:a("mesh.magiKind.machine")}),n.jsxs("select",{className:K,value:V.nodeId,onChange:ne=>B(P,we,{nodeId:ne.target.value}),title:a("mesh.magiKind.machineTitle"),children:[n.jsx("option",{value:"",children:a("mesh.magiKind.anyMachine")}),_.map(ne=>{const ee=y.has(ne),ue=ee?a("mesh.magiKind.worktreeSuffix",{label:S[ne]??ne,branch:w[ne]||a("mesh.magiKind.worktreeUnknownBranch")}):S[ne]??ne;return n.jsx("option",{value:ne,disabled:ee,title:ee?a("mesh.magiKind.worktreeDisabledTitle"):void 0,children:ue},ne)}),V.nodeId&&!_.includes(V.nodeId)&&n.jsx("option",{value:V.nodeId,children:a("mesh.magiKind.offlineSuffix",{label:S[V.nodeId]??V.nodeId})})]})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsxs("span",{className:`text-4xs uppercase tracking-wide ${c.textSecondary}`,children:[a("mesh.magiKind.provider")," *"]}),n.jsxs("select",{className:K,value:V.provider,onChange:ne=>B(P,we,{provider:ne.target.value}),title:a("mesh.magiKind.providerTitle"),children:[n.jsx("option",{value:"",children:a("mesh.magiKind.selectProvider")}),de.map(ne=>n.jsx("option",{value:ne,children:ne},ne)),V.provider&&!de.includes(V.provider)&&n.jsx("option",{value:V.provider,children:V.provider})]})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:`text-4xs uppercase tracking-wide ${c.textSecondary}`,children:a("mesh.magiKind.model")}),(()=>{var ue;const ne=(V.provider?(ue=d.get(V.provider))==null?void 0:ue.models:void 0)??[],ee=!!V.model&&ne.length>0&&!ne.includes(V.model);return ne.length>0&&!ee?n.jsxs("select",{className:K,value:ne.includes(V.model)?V.model:"",title:a("mesh.magiKind.modelTitle"),onChange:je=>B(P,we,{model:je.target.value==="__custom__"?" ":je.target.value}),children:[n.jsx("option",{value:"",children:a("mesh.magiKind.modelDefault")}),ne.map(je=>n.jsx("option",{value:je,children:je},je)),n.jsx("option",{value:"__custom__",children:a("mesh.magiKind.modelCustom")})]}):n.jsxs(n.Fragment,{children:[n.jsx("input",{className:K,value:V.model.trim(),placeholder:a("mesh.magiKind.modelDefault"),title:a("mesh.magiKind.modelTitle"),onChange:je=>B(P,we,{model:je.target.value})}),ne.length>0&&n.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-3xs ${c.textSecondary} hover:underline`,onClick:()=>B(P,we,{model:""}),children:a("mesh.magiKind.backToModelList")})]})})()]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:`text-4xs uppercase tracking-wide ${c.textSecondary}`,children:a("mesh.magiKind.copies")}),n.jsx("input",{className:`${K} sm:w-16`,value:V.n,placeholder:"1",inputMode:"numeric",title:a("mesh.magiKind.copiesTitle"),onChange:ne=>B(P,we,{n:ne.target.value})})]}),n.jsx("button",{type:"button",className:`${D} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>F(P,we),"aria-label":a("mesh.magiKind.removeAgent"),title:a("mesh.magiKind.removeAgent"),children:"✕"})]},we)}),n.jsx("div",{children:n.jsx("button",{type:"button",className:D,onClick:()=>T(P),disabled:!O,children:a("mesh.magiKind.addAgent")})})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",className:R,onClick:()=>void q(P),disabled:be||!O,children:a(be?"mesh.magiKind.saving":"mesh.magiKind.save")}),n.jsx("button",{type:"button",className:D,onClick:()=>void Q(P),disabled:be||!O||!ae,title:a(ae?"mesh.magiKind.removeBindingTitle":"mesh.magiKind.removeBindingDisabledTitle"),children:a("mesh.magiKind.removeBinding")})]})]},P)})})]})}const Vi=l.createContext(hu("dark"));function oo({label:e,tone:t="default",className:s,title:r}){const o=l.useContext(Vi),a=n.jsx("span",{className:`rounded-full border pl-2 pr-[calc(0.5rem-0.16em)] py-0.5 text-[10px] leading-none align-middle uppercase tracking-[0.16em] ${o.badge(t)}${s?` ${s}`:""}`,children:e});return r?n.jsx(tn,{content:r,children:a}):a}function h3({label:e,value:t}){const s=l.useContext(Vi);return n.jsxs("div",{className:s.rowClass,children:[n.jsx("span",{className:s.rowLabelClass,children:e}),n.jsx("span",{className:s.rowValueClass,children:t})]})}const SL="You are one independent member of a multi-agent cross-verification quorum";function kL(e){var r,o;const t=(e??"").trim();if(!t)return"";if(!t.startsWith(SL))return t;const s=(o=(r=t.match(/\n## Question\n([\s\S]*?)(?:\n## |$)/))==null?void 0:r[1])==null?void 0:o.trim().replace(/\s+/g," ");return s?`MAGI cross-verify — ${s}`:"MAGI cross-verification task"}function Ax(e){let t=e??"";return t?(t=t.replace(/^```[^\n]*\n?/gm,""),t=t.replace(/^#{1,6}\s+/gm,""),t=t.replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm,""),t=t.replace(/^>\s?/gm,""),t=t.replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"$2"),t=t.replace(/(^|\W)[*_](?=\S)([^*_\n]*\S)[*_](?=\W|$)/g,"$1$2"),t=t.replace(/`([^`\n]*)`/g,"$1"),t=t.replace(/[ \t]{2,}/g," "),t=t.replace(/\n{3,}/g,`
|
|
103
|
+
|
|
104
|
+
`),t.trim()):""}function p3(e){return Ax(kL(e))}const va=["provider_quirk","pattern_to_avoid","recovery_lesson"],ip=240,jL={provider_quirk:"warn",pattern_to_avoid:"danger",recovery_lesson:"good"};function Gl(e,t){return e(t==="provider_quirk"?"mesh.notes.categoryProviderQuirk":t==="pattern_to_avoid"?"mesh.notes.categoryPatternToAvoid":t==="recovery_lesson"?"mesh.notes.categoryRecoveryLesson":"mesh.notes.categoryUncategorized")}function wa(e){return Do(e)}function NL({meshId:e,daemonId:t,sendDaemonCommand:s}){const{t:r}=ve("common"),o=l.useContext(Vi),[a,i]=l.useState([]),[c,d]=l.useState(!1),[u,m]=l.useState(null),[h,p]=l.useState(!1),[g,f]=l.useState(!1),[x,b]=l.useState(""),[k,j]=l.useState(""),[v,_]=l.useState(new Set),[y,w]=l.useState(null),[S,C]=l.useState(""),[A,O]=l.useState(""),L=!!(s&&t&&e),M=l.useCallback(async()=>{if(!(!s||!t||!e)){d(!0),m(null);try{const K=await s(t,"list_mesh_notes",{meshId:e,tail:100}),R=(K==null?void 0:K.result)??K;if(R&&R.success===!1){m(typeof R.error=="string"?R.error:r("mesh.notes.loadFailed")),i([]);return}const D=Array.isArray(R==null?void 0:R.notes)?R.notes:[];i([...D].reverse())}catch(K){m(K instanceof Error?K.message:r("mesh.notes.loadFailed")),i([])}finally{d(!1)}}},[s,t,e,r]);l.useEffect(()=>{M()},[M]);const $=l.useCallback(async()=>{if(!s||!t||!e)return;const K=x.trim();if(!(!K||h)){p(!0),m(null);try{const R=await s(t,"record_mesh_note",{meshId:e,text:K,...k?{category:k}:{}}),D=(R==null?void 0:R.result)??R;if(D&&D.success===!1){m(typeof D.error=="string"?D.error:r("mesh.notes.saveFailed"));return}b(""),j(""),f(!1),await M()}catch(R){m(R instanceof Error?R.message:r("mesh.notes.saveFailed"))}finally{p(!1)}}},[s,t,e,x,k,h,M,r]),N=l.useCallback(async K=>{if(!(!s||!t||!e||h)){p(!0),m(null);try{const R=await s(t,"forget_mesh_note",{meshId:e,noteId:K}),D=(R==null?void 0:R.result)??R;if(D&&D.success===!1){m(typeof D.error=="string"?D.error:r("mesh.notes.deleteFailed"));return}await M()}catch(R){m(R instanceof Error?R.message:r("mesh.notes.deleteFailed"))}finally{p(!1)}}},[s,t,e,h,M,r]),I=l.useCallback(K=>{w(K.id),C(K.text),O(va.includes(K.category)?K.category:"")},[]),B=l.useCallback(()=>{w(null),C(""),O("")},[]),T=l.useCallback(async K=>{if(!s||!t||!e||h)return;const R=S.trim();if(R){p(!0),m(null);try{const D=await s(t,"forget_mesh_note",{meshId:e,noteId:K}),P=(D==null?void 0:D.result)??D;if(P&&P.success===!1){m(typeof P.error=="string"?P.error:r("mesh.notes.editFailed"));return}const H=await s(t,"record_mesh_note",{meshId:e,text:R,...A?{category:A}:{}}),W=(H==null?void 0:H.result)??H;if(W&&W.success===!1){m(typeof W.error=="string"?W.error:r("mesh.notes.editFailed"));return}B(),await M()}catch(D){m(D instanceof Error?D.message:r("mesh.notes.editFailed"))}finally{p(!1)}}},[s,t,e,S,A,h,B,M,r]),F=o.isDark?"rounded-lg border border-white/10 bg-slate-950/40 px-2.5 py-1.5 text-xs text-slate-200":"rounded-lg border border-slate-300 bg-white px-2.5 py-1.5 text-xs text-slate-700",q=o.isDark?"w-full rounded-lg border border-white/10 bg-slate-950/40 px-3 py-2 text-sm text-slate-100 placeholder:text-slate-500":"w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-slate-800 placeholder:text-slate-400",Q=K=>`rounded-lg border px-2.5 py-1 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-45 ${o.actionButton(K)}`;return L?n.jsxs("div",{className:"flex flex-col gap-3",children:[g?n.jsxs("div",{className:`${o.cardClass} rounded-2xl p-4`,children:[n.jsx("div",{className:`mb-2 text-sm font-semibold ${o.textPrimary}`,children:r("mesh.notes.addTitle")}),n.jsx("textarea",{value:x,onChange:K=>b(K.target.value),rows:2,placeholder:r("mesh.notes.textPlaceholder"),className:q,autoFocus:!0}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[n.jsxs("select",{value:k,onChange:K=>j(K.target.value),className:F,"aria-label":r("mesh.notes.categoryLabel"),children:[n.jsx("option",{value:"",children:r("mesh.notes.categoryUncategorized")}),va.map(K=>n.jsx("option",{value:K,children:Gl(r,K)},K))]}),n.jsx("button",{type:"button",onClick:()=>{$()},disabled:h||!x.trim(),className:Q("success"),children:r("mesh.notes.add")}),n.jsx("button",{type:"button",onClick:()=>f(!1),disabled:h,className:Q("default"),children:r("mesh.notes.cancel")})]})]}):n.jsx("div",{children:n.jsxs("button",{type:"button",onClick:()=>f(!0),className:Q("info"),children:["+ ",r("mesh.notes.addTitle")]})}),u&&n.jsx("div",{className:o.isDark?"rounded-xl border border-rose-400/20 bg-rose-500/10 px-3 py-2 text-xs text-rose-100":"rounded-xl border border-rose-300 bg-rose-50 px-3 py-2 text-xs text-rose-700",children:u}),n.jsxs("div",{className:`${o.cardClass} rounded-2xl p-4`,children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[n.jsx("div",{className:`text-sm font-semibold ${o.textPrimary}`,children:r("mesh.notes.listTitle")}),n.jsx(Wi,{onClick:()=>{M()},refreshing:c,disabled:h,label:r("mesh.notes.refresh"),size:13,className:"h-7 w-7"})]}),c?n.jsx("div",{className:`py-6 text-center text-sm ${o.textMuted}`,children:r("mesh.notes.loading")}):a.length===0?n.jsx("div",{className:`py-6 text-center text-sm ${o.textMuted}`,children:r("mesh.notes.empty")}):n.jsx("div",{className:"flex flex-col gap-2",children:a.map(K=>n.jsx("div",{className:`rounded-xl border px-3 py-2.5 ${o.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:y===K.id?n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("textarea",{value:S,onChange:R=>C(R.target.value),rows:2,className:q}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsxs("select",{value:A,onChange:R=>O(R.target.value),className:F,"aria-label":r("mesh.notes.categoryLabel"),children:[n.jsx("option",{value:"",children:r("mesh.notes.categoryUncategorized")}),va.map(R=>n.jsx("option",{value:R,children:Gl(r,R)},R))]}),n.jsx("button",{type:"button",onClick:()=>{T(K.id)},disabled:h||!S.trim(),className:Q("success"),children:r("mesh.notes.save")}),n.jsx("button",{type:"button",onClick:B,disabled:h,className:Q("default"),children:r("mesh.notes.cancel")})]})]}):n.jsxs(n.Fragment,{children:[(()=>{const R=Ax(K.text),D=v.has(K.id),P=R.length>ip,H=!P||D?R:`${R.slice(0,ip).trimEnd()}…`;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`whitespace-pre-wrap break-words text-sm ${o.textPrimary}`,children:H}),P&&n.jsx("button",{type:"button",onClick:()=>_(W=>{const U=new Set(W);return U.has(K.id)?U.delete(K.id):U.add(K.id),U}),className:`mt-1 text-2xs font-medium ${o.isDark?"text-sky-300 hover:text-sky-200":"text-sky-600 hover:text-sky-700"}`,children:r(D?"mesh.notes.showLess":"mesh.notes.showMore")})]})})(),n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[n.jsx(oo,{label:Gl(r,K.category),tone:va.includes(K.category)?jL[K.category]:"default"}),K.pinned&&n.jsx(oo,{label:r("mesh.notes.pinned"),tone:"info"}),K.expired?n.jsx(oo,{label:r("mesh.notes.expired"),tone:"danger"}):K.pinned?n.jsx(oo,{label:r("mesh.notes.neverExpires"),tone:"default"}):wa(K.effectiveExpiresAt)?n.jsx("span",{className:`text-2xs ${o.textMuted}`,title:K.effectiveExpiresAt,children:r("mesh.notes.expiresIn",{when:wa(K.effectiveExpiresAt)})}):n.jsx(oo,{label:r("mesh.notes.durable"),tone:"default"}),wa(K.createdAt)&&n.jsx("span",{className:`text-2xs ${o.textMuted}`,children:wa(K.createdAt)}),n.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>I(K),disabled:h,className:Q("info"),children:r("mesh.notes.edit")}),n.jsx("button",{type:"button",onClick:()=>{N(K.id)},disabled:h,className:Q("default"),children:r("mesh.notes.delete")})]})]})]})},K.id))})]})]}):n.jsx("div",{className:`${o.cardClass} rounded-2xl p-4 text-xs ${o.textSecondary}`,children:r("mesh.notes.unavailable")})}const fr={sessionMinRemainingPercent:10,weeklyMinRemainingPercent:15,sessionResetImminentMinutes:5,staleAfterMinutes:30,spreadBonusMax:30,sessionAxisWeeklyHeadroomPercent:40},Xc=60*1e3;function lp(e){return e===void 0||!Number.isFinite(e)?"":String(e/Xc)}function Fa(e){const t=e??{};return{sessionMinRemainingPercent:t.sessionMinRemainingPercent!==void 0?String(t.sessionMinRemainingPercent):"",weeklyMinRemainingPercent:t.weeklyMinRemainingPercent!==void 0?String(t.weeklyMinRemainingPercent):"",sessionResetImminentMinutes:lp(t.sessionResetImminentMs),staleAfterMinutes:lp(t.staleAfterMs),spreadBonusMax:t.spreadBonusMax!==void 0?String(t.spreadBonusMax):"",sessionAxisWeeklyHeadroomPercent:t.sessionAxisWeeklyHeadroomPercent!==void 0?String(t.sessionAxisWeeklyHeadroomPercent):""}}function CL(e,t){const s=t.trim();if(!s)return null;const r=Number(s);if(!Number.isFinite(r))return"notANumber";const o=e==="sessionMinRemainingPercent"||e==="weeklyMinRemainingPercent"||e==="sessionAxisWeeklyHeadroomPercent";return o&&(r<0||r>100)?"percentRange":!o&&r<0?"negative":null}function Zc(e){const t={},s=u=>{const m=u.trim();if(!m)return;const h=Number(m);return Number.isFinite(h)?h:void 0},r=s(e.sessionMinRemainingPercent);r!==void 0&&(t.sessionMinRemainingPercent=r);const o=s(e.weeklyMinRemainingPercent);o!==void 0&&(t.weeklyMinRemainingPercent=o);const a=s(e.sessionResetImminentMinutes);a!==void 0&&(t.sessionResetImminentMs=a*Xc);const i=s(e.staleAfterMinutes);i!==void 0&&(t.staleAfterMs=i*Xc);const c=s(e.spreadBonusMax);c!==void 0&&(t.spreadBonusMax=c);const d=s(e.sessionAxisWeeklyHeadroomPercent);return d!==void 0&&(t.sessionAxisWeeklyHeadroomPercent=d),t}const _L="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs",AL="w-full rounded-lg border border-red-500/60 bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function TL({quotaRouting:e,saving:t,error:s,onSave:r,hideHeader:o=!1}){const{t:a}=ve("common"),[i,c]=l.useState(()=>Fa(e)),d=l.useCallback((k,j)=>{c(v=>({...v,[k]:j}))},[]),u=l.useMemo(()=>{const k={};for(const j of Object.keys(i)){const v=CL(j,i[j]);v&&(k[j]=v)}return k},[i]),m=Object.keys(u).length>0,h=l.useMemo(()=>JSON.stringify(Zc(i))!==JSON.stringify(cp(e)),[i,e]),p=l.useRef(!1),g=JSON.stringify(cp(e));l.useEffect(()=>{p.current||c(Fa(e))},[g]);const f=l.useCallback(()=>{p.current=!1,!(m||!h)&&r(Zc(i))},[h,i,m,r]),x=l.useCallback(()=>{c(Fa(null)),r({})},[r]),b=[{key:"sessionMinRemainingPercent",label:a("setupWizard.quotaPolicy.sessionMin"),hint:a("setupWizard.quotaPolicy.sessionMinHint"),placeholder:fr.sessionMinRemainingPercent,unit:"%"},{key:"weeklyMinRemainingPercent",label:a("setupWizard.quotaPolicy.weeklyMin"),hint:a("setupWizard.quotaPolicy.weeklyMinHint"),placeholder:fr.weeklyMinRemainingPercent,unit:"%"},{key:"sessionResetImminentMinutes",label:a("setupWizard.quotaPolicy.resetImminent"),hint:a("setupWizard.quotaPolicy.resetImminentHint"),placeholder:fr.sessionResetImminentMinutes,unit:a("setupWizard.quotaPolicy.minutes")},{key:"staleAfterMinutes",label:a("setupWizard.quotaPolicy.staleAfter"),hint:a("setupWizard.quotaPolicy.staleAfterHint"),placeholder:fr.staleAfterMinutes,unit:a("setupWizard.quotaPolicy.minutes")},{key:"spreadBonusMax",label:a("setupWizard.quotaPolicy.spreadBonus"),hint:a("setupWizard.quotaPolicy.spreadBonusHint"),placeholder:fr.spreadBonusMax,unit:""},{key:"sessionAxisWeeklyHeadroomPercent",label:a("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroom"),hint:a("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroomHint"),placeholder:fr.sessionAxisWeeklyHeadroomPercent,unit:"%"}];return n.jsxs("div",{className:"flex flex-col gap-3",children:[!o&&n.jsxs("h3",{className:"flex items-center gap-1 text-sm font-semibold text-text-primary",children:[a("setupWizard.quotaPolicy.title"),n.jsx(dt,{content:a("setupWizard.quotaPolicy.description")})]}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-2",children:b.map(k=>{const j=u[k.key],v=`quota-policy-${k.key}`;return n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsxs("span",{className:"flex items-center gap-1 text-2xs text-text-muted",children:[n.jsxs("label",{htmlFor:v,children:[k.label,k.unit?` (${k.unit})`:""]}),n.jsx(dt,{content:k.hint,size:12})]}),n.jsx("input",{id:v,type:"number",inputMode:"decimal",className:j?AL:_L,value:i[k.key],placeholder:String(k.placeholder),"aria-invalid":j?!0:void 0,onChange:_=>{p.current=!0,d(k.key,_.target.value)},onBlur:f,onKeyDown:_=>{_.key==="Enter"&&f()}}),j&&n.jsx("span",{className:"text-3xs leading-snug text-red-400",children:a(`setupWizard.quotaPolicy.errors.${j}`)})]},k.key)})}),s?n.jsx("p",{className:"text-2xs text-red-400",children:s}):null,n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:x,disabled:!!t,children:a("setupWizard.quotaPolicy.useDefaults")}),n.jsxs("span",{className:"flex items-center gap-1 text-3xs text-text-muted",children:[a(t?"setupWizard.quotaPolicy.saving":"setupWizard.quotaPolicy.blankMeansDefaultShort"),!t&&n.jsx(dt,{content:a("setupWizard.quotaPolicy.blankMeansDefault"),size:12})]})]})]})}function cp(e){return Zc(Fa(e))}function IL(e,t,s,r){const{t:o}=ve(),[a,i]=l.useState(!1),[c,d]=l.useState(null),[u,m]=l.useState(null),[h,p]=l.useState(null),g=l.useCallback(async()=>{if(!e||!t){d(o("mesh.promptPreview.connectPrompt"));return}i(!0),d(null);try{const f=await r(e,"coordinator_prompt_preview",{meshId:t,cliType:s}),x=f!=null&&f.result&&typeof f.result=="object"?f.result:f;if(!(x!=null&&x.success))return d((x==null?void 0:x.error)||o("mesh.promptPreview.errorRender")),null;const b=typeof x.prompt=="string"?x.prompt:"";return m(b),p(typeof x.bytes=="number"?x.bytes:null),b}catch(f){return d((f==null?void 0:f.message)||String(f)),null}finally{i(!1)}},[e,t,s,r,o]);return{loading:a,error:c,prompt:u,bytes:h,load:g}}function ML({daemonId:e,meshId:t,cliType:s,sendCommand:r,defaultOpen:o=!1}){const{t:a}=ve(),[i,c]=l.useState(o),{loading:d,error:u,prompt:m,bytes:h,load:p}=IL(e,t,s,r),g=l.useRef(!1);l.useEffect(()=>{i&&!g.current&&(g.current=!0,p())},[i,p]);const f=l.useCallback(()=>{c(x=>!x)},[]);return n.jsxs("div",{className:"mt-2",children:[n.jsxs("button",{type:"button",onClick:f,className:"inline-flex items-center gap-1 text-xs text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[n.jsx("span",{className:`transition-transform ${i?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),a(i?"mesh.promptPreview.hide":"mesh.promptPreview.view"),n.jsxs("span",{className:"text-text-muted",children:["(",s,")"]})]}),i&&n.jsxs("div",{className:"mt-2",children:[d&&n.jsx("div",{className:"text-xs text-text-muted",children:a("mesh.promptPreview.rendering")}),u&&n.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-300",children:[u,n.jsx("button",{type:"button",onClick:()=>void p(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:a("mesh.promptPreview.retry")})]}),!d&&!u&&m!==null&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between text-2xs text-text-muted",children:[n.jsx(dt,{content:`${a("mesh.promptPreview.info")}
|
|
105
|
+
${a("mesh.promptPreview.launchScopeNote")}`,size:12}),h!==null&&n.jsxs("span",{children:[(h/1024).toFixed(1)," KB"]})]}),n.jsx("textarea",{readOnly:!0,value:m,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-xs text-text-secondary font-mono",onFocus:x=>x.currentTarget.select()})]})]})]})}function RL(e){var i;const t=e!=null&&e.result&&typeof e.result=="object"?e.result:e;if(!t||typeof t!="object"||t.success===!1)return null;if((t.sourceType==="repo_file"||t.sourceType==="invalid"?t.sourceType:"unavailable")==="invalid")return{append:"",override:"",path:typeof t.path=="string"?t.path:"",sourceType:"invalid",error:typeof t.error=="string"?t.error:""};const r=(i=t==null?void 0:t.config)==null?void 0:i.coordinator,o=typeof(r==null?void 0:r.systemPromptAppend)=="string"?r.systemPromptAppend:"",a=typeof(r==null?void 0:r.systemPromptOverride)=="string"?r.systemPromptOverride:"";return!o.trim()&&!a.trim()?null:{append:o,override:a,path:typeof t.path=="string"?t.path:"",sourceType:"repo_file",error:""}}function PL({daemonId:e,workspace:t,sendCommand:s}){const{t:r}=ve(),[o,a]=l.useState(null),i=l.useCallback(async()=>{if(!e||!t){a(null);return}try{const c=await s(e,"read_mesh_json_config",{workspace:t});a(RL(c))}catch{a(null)}},[e,t,s]);return l.useEffect(()=>{i()},[i]),o?o.sourceType==="invalid"?n.jsxs("div",{className:"mt-3 rounded-lg border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-300",children:[r("mesh.detail.repoMeshJsonInvalid"),o.error&&n.jsx("span",{className:"ml-1 font-mono text-2xs opacity-80",children:o.error})]}):n.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[n.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-1",children:[n.jsx("span",{className:"text-[13px] leading-tight font-semibold",children:r("mesh.detail.repoMeshJsonTitle")}),n.jsx(dt,{content:`${r("mesh.detail.repoMeshJsonHint")}${o.path?`
|
|
106
|
+
${o.path}`:""}`,size:12})]}),o.override.trim()&&n.jsxs("div",{className:"mb-2",children:[n.jsx("label",{className:"mb-1 block text-2xs uppercase tracking-wide text-text-muted",children:r("mesh.detail.repoMeshJsonOverrideLabel")}),n.jsx("textarea",{readOnly:!0,value:o.override,rows:4,className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 font-mono text-xs text-text-secondary",onFocus:c=>c.currentTarget.select()})]}),o.append.trim()&&n.jsxs("div",{children:[n.jsx("label",{className:"mb-1 block text-2xs uppercase tracking-wide text-text-muted",children:r("mesh.detail.repoMeshJsonAppendLabel")}),n.jsx("textarea",{readOnly:!0,value:o.append,rows:4,className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 font-mono text-xs text-text-secondary",onFocus:c=>c.currentTarget.select()})]})]}):null}const LL=[{token:"meshName",description:"This mesh's display name.",example:"my-app"},{token:"repo",description:"Repo identity (owner/repo or workspace path).",example:"vilmire/adhdev"},{token:"defaultBranch",description:"The mesh's default branch.",example:"main"},{token:"cliType",description:"The coordinator CLI type this prompt is being rendered for.",example:"claude-cli"},{token:"nodes",description:"Live node status table, or the configured node list if no live status is available.",example:"(rendered node table)"},{token:"mission",description:"Current mission section, when a mission is active. Empty otherwise.",example:"(mission summary or empty)"},{token:"recentActivity",description:"Recent mesh activity summary. Empty when none.",example:"(recent activity or empty)"},{token:"operatingNotes",description:"Accumulated operating notes for this mesh. Empty when none.",example:"(operating notes or empty)"},{token:"policy",description:"The mesh's effective policy section (safety, scheduling, etc.).",example:"(rendered policy section)"},{token:"tools",description:"The canonical MCP tools reference table.",example:"(tools table)"},{token:"workflow",description:"The standard coordinator workflow guidance section.",example:"(workflow section)"},{token:"quota",description:"The quota-awareness section.",example:"(quota section)"},{token:"onboarding",description:"Onboarding/reinit guidance section.",example:"(onboarding section)"},{token:"rules",description:"CLI-type-specific and policy-derived rules section.",example:"(rules section)"},{token:"toolExposurePreflight",description:"Preflight guidance for verifying tool exposure before relying on it.",example:"(preflight section)"}];function dp(e,t){if(t)return e.modes.find(s=>s.id===t)}function EL(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&Yn(t)!=="dangerous")}function DL({config:e,requestedModeId:t,machineAutoApproveEnabled:s,machineDangerousAllowed:r}){const o=dp(e,e.default),a=o==null?void 0:o.id,i=(t==null?void 0:t.trim())||void 0;if(!s)return{status:"disabled",requestedModeId:i,providerDefaultModeId:a,requestedModeUnknown:!1,downgraded:!1};const c=dp(e,i),d=!!i&&!c,u=c??o;if(!u||u.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:a,requestedModeUnknown:d,downgraded:!1};if(Yn(u)==="dangerous"&&!r){const m=EL(e);return{status:m?"downgraded":"none",requestedModeId:i,providerDefaultModeId:a,effectiveMode:m,requestedModeUnknown:d,downgraded:!0}}return{status:d?"invalid_fallback":"requested",requestedModeId:i,providerDefaultModeId:a,effectiveMode:u,requestedModeUnknown:d,downgraded:!1}}function OL(e){const t=[];for(const s of e||[]){if(!s||s.category!=="cli")continue;const r=s.autoApproveModes;if(!r||!Array.isArray(r.modes)||r.modes.length===0)continue;const o=String(s.type||s.id||"").trim();o&&t.push({type:o,label:String(s.displayName||s.name||o),autoApproveModes:r})}return t}function $L({hostDaemonId:e,hostOnline:t,hostWorkspace:s,meshProviders:r,unreportedNodeCount:o=0,machineAutoApproveEnabled:a,machineDangerousAllowed:i,onUpdatePolicy:c,savingPolicy:d,sendCommand:u}){const{t:m}=ve("common"),h=l.useMemo(()=>OL(r),[r]),[p,g]=l.useState({}),[f,x]=l.useState(!1),[b,k]=l.useState(null),[j,v]=l.useState(!1),[_,y]=l.useState(null),[w,S]=l.useState(!1),[C,A]=l.useState(null),[O,L]=l.useState(!1),M=!!e&&t&&!!s,$=!!c&&!d,N=l.useCallback(async()=>{var K,R,D;if(M){x(!0),k(null);try{const P=await u(e,"read_mesh_json_config",{workspace:s}),H=(P==null?void 0:P.result)??P,W=((K=H==null?void 0:H.providerDefaults)==null?void 0:K.autoApproveModes)||((D=(R=H==null?void 0:H.config)==null?void 0:R.providerDefaults)==null?void 0:D.autoApproveModes),U={};if(W&&typeof W=="object")for(const[ae,be]of Object.entries(W))typeof be=="string"&&be.trim()&&(U[ae]=be.trim());g(U)}catch(P){k((P==null?void 0:P.message)||m("mesh.providerAutoApprove.loadError"))}finally{x(!1)}}},[M,e,s,u,m]);l.useEffect(()=>{N()},[N]);const I=l.useRef(null),B=l.useRef(p);B.current=p;const T=l.useCallback((K,R)=>{var P;S(!1);const D={...B.current};R&&R.trim()?D[K]=R.trim():delete D[K],B.current=D,g(D),(P=I.current)==null||P.call(I,D)},[]),F=l.useCallback((K,R)=>{if(Yn(R)==="dangerous"){A({type:K,mode:R});return}T(K,R.id)},[T]),q=l.useCallback(()=>{C&&T(C.type,C.mode.id),A(null)},[T,C]),Q=l.useCallback(async K=>{if(M){v(!0),y(null),S(!1);try{const R=await u(e,"set_mesh_provider_defaults",{workspace:s,autoApproveModes:K,merge:!1,write:!0}),D=(R==null?void 0:R.result)??R;if((D==null?void 0:D.success)===!1)throw new Error((D==null?void 0:D.error)||m("mesh.providerAutoApprove.saveError"));S(!0),ct.showToast(m("common.saved"),"success"),await N()}catch(R){y((R==null?void 0:R.message)||m("mesh.providerAutoApprove.saveError"))}finally{v(!1)}}},[M,e,s,N,u,m]);return I.current=Q,n.jsxs(Nt,{title:m("mesh.providerAutoApprove.title"),collapsible:!0,defaultOpen:!1,children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-3.5",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary",children:m("mesh.providerAutoApprove.machineSection.title")}),n.jsx(tn,{content:m("mesh.providerAutoApprove.machineSection.hint"),children:n.jsx("span",{className:"rounded-full border border-border-subtle bg-surface-secondary/40 px-2 py-0.5 text-3xs font-medium text-text-muted",children:m("mesh.providerAutoApprove.machineSection.chip")})})]}),n.jsxs("div",{className:"mt-3 space-y-2",children:[n.jsx(up,{label:m("mesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:m("mesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:a,disabled:!$,onChange:K=>c==null?void 0:c({delegatedWorkerAutoApprove:K})}),n.jsx(up,{label:m("mesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:m(a?"mesh.providerAutoApprove.machineSection.dangerousToggleHint":"mesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:i,disabled:!$||!a,onChange:K=>{K?L(!0):c==null||c({delegatedWorkerDangerousModeAllow:!1})}})]})]}),M?f?n.jsx("div",{className:"text-xxs text-text-muted",children:m("mesh.providerAutoApprove.loading")}):h.length===0?n.jsx("div",{className:"text-xxs text-text-muted",children:o>0?m("mesh.providerAutoApprove.awaitingNodes",{count:o}):m("mesh.providerAutoApprove.noProviders")}):n.jsxs("div",{className:"space-y-6",children:[b&&n.jsx(zt,{variant:"error",onDismiss:()=>k(null),children:b}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary",children:m("mesh.providerAutoApprove.repoSection.title")}),n.jsx(tn,{content:m("mesh.providerAutoApprove.repoSection.hint"),children:n.jsx("span",{className:"rounded-full border border-border-subtle bg-surface-secondary/40 px-2 py-0.5 text-3xs font-medium text-text-muted",children:m("mesh.providerAutoApprove.repoSection.chip")})}),o>0&&n.jsx(tn,{content:m("mesh.providerAutoApprove.partialInventory",{count:o}),children:n.jsx("span",{className:"rounded-full border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 text-3xs font-medium text-amber-400",children:m("mesh.providerAutoApprove.partialInventoryChip",{count:o})})}),j&&n.jsx("span",{className:"text-3xs text-text-muted",children:m("mesh.providerAutoApprove.saving")})]}),n.jsx("div",{className:"space-y-5",children:h.map(K=>{const R=p[K.type],D=DL({config:K.autoApproveModes,requestedModeId:R,machineAutoApproveEnabled:a,machineDangerousAllowed:i});return n.jsxs("div",{className:"rounded-xl border border-border-subtle p-3.5",children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary",children:K.label}),n.jsx("button",{type:"button",className:"text-2xs text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>T(K.type,void 0),disabled:!R||j,children:m("mesh.providerAutoApprove.repoSection.clear")})]}),n.jsx(lx,{config:K.autoApproveModes,selectedModeId:R||"",disabled:j,onSelectMode:P=>F(K.type,P)}),!R&&n.jsx("div",{className:"mt-1.5 text-2xs text-text-muted",children:m("mesh.providerAutoApprove.repoSection.usesProviderDefault")}),n.jsx(FL,{effective:D,config:K.autoApproveModes})]},K.type)})}),_&&n.jsx(zt,{variant:"error",onDismiss:()=>y(null),children:_}),w&&n.jsx("span",{className:"sr-only",role:"status",children:m("mesh.providerAutoApprove.saved")})]}):n.jsx("div",{className:"text-xxs text-text-muted",children:m("mesh.providerAutoApprove.noHostDaemon")}),O&&n.jsx(Ui,{title:m("mesh.providerAutoApprove.machineSection.confirmTitle"),description:m("mesh.providerAutoApprove.machineSection.confirmDescription"),details:[{label:m("mesh.providerAutoApprove.machineSection.confirmScopeLabel"),value:m("mesh.providerAutoApprove.machineSection.confirmScopeValue")},{label:m("mesh.providerAutoApprove.machineSection.confirmEffectLabel"),value:m("mesh.providerAutoApprove.machineSection.confirmEffectValue")}],confirmLabel:m("mesh.providerAutoApprove.machineSection.confirmConfirm"),onConfirm:()=>{L(!1),c==null||c({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>L(!1)}),C&&n.jsx(cx,{mode:C.mode,onConfirm:q,onCancel:()=>A(null)}),C&&n.jsx("div",{className:"fixed inset-x-0 bottom-6 z-[60] mx-auto max-w-lg px-4",children:n.jsxs("div",{className:"rounded-xl border border-status-error/40 bg-bg-primary p-3.5 shadow-lg",children:[n.jsxs("div",{className:"flex items-center gap-1 text-sm font-semibold text-status-error",children:[m("mesh.providerAutoApprove.dangerous.sharedWarningTitle"),n.jsx(dt,{content:m("mesh.providerAutoApprove.dangerous.sharedWarningDetail")})]}),n.jsx("div",{className:"mt-1 text-xs text-text-muted",children:m("mesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function FL({effective:e,config:t}){var d,u,m,h;const{t:s}=ve("common"),r=p=>{var g;return(p?(g=t.modes.find(f=>f.id===p))==null?void 0:g.label:void 0)||p||""};let o,a=null,i="ok";switch(e.status){case"requested":o=s("mesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((d=e.effectiveMode)==null?void 0:d.label)||""});break;case"invalid_fallback":o=s("mesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((u=e.effectiveMode)==null?void 0:u.label)||""}),i="warn";break;case"downgraded":o=s("mesh.providerAutoApprove.effectiveSection.statusDowngraded",{mode:((m=e.effectiveMode)==null?void 0:m.label)||""}),a=s("mesh.providerAutoApprove.effectiveSection.statusDowngradedHint",{requested:r(e.requestedModeId)||r(e.providerDefaultModeId),mode:((h=e.effectiveMode)==null?void 0:h.label)||""}),i="warn";break;case"disabled":o=s("mesh.providerAutoApprove.effectiveSection.statusDisabled"),i="muted";break;default:o=s("mesh.providerAutoApprove.effectiveSection.statusNone"),i="muted"}const c=i==="ok"?"border-status-online/25 bg-status-online/5 text-text-secondary":i==="warn"?"border-status-warning/30 bg-status-warning/5 text-status-warning":"border-border-subtle bg-surface-secondary/30 text-text-muted";return n.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-lg border px-3 py-2 text-xs ${c}`,children:[e.effectiveMode&&n.jsx(ix,{risk:Yn(e.effectiveMode)}),n.jsx("span",{className:"min-w-0",children:o}),a&&n.jsx(dt,{content:a,size:12})]})}function up({label:e,hint:t,checked:s,disabled:r=!1,onChange:o}){const a=l.useId();return n.jsxs("div",{className:`flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-primary/60 px-3.5 py-2.5 ${r?"opacity-60":""}`,children:[n.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[n.jsx("span",{id:a,className:"text-xxs font-semibold text-text-primary",children:e}),n.jsx(dt,{content:t,size:12})]}),n.jsx(Ur,{checked:s,disabled:r,onChange:o,"aria-labelledby":a})]})}function Sa(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function HL({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:s,isHostNodeAttached:r,selectedHostNode:o,hostPinned:a,hostLabel:i,hostOnline:c,hostRebindDaemonId:d,onHostRebindDaemonIdChange:u,settingMeshHost:m,onSetMeshHost:h}){const{t:p}=ve("common");if(a)return n.jsxs(Nt,{title:p("mesh.host.title"),description:p("mesh.host.descriptionSet"),children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xxs text-text-primary ${c?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[n.jsx("span",{className:"text-text-muted",children:p("mesh.host.hostLabel")}),n.jsx("span",{className:"font-medium",children:i||p("mesh.host.unknown")}),n.jsxs("span",{className:c?"text-text-muted":"text-amber-400",children:["· ",p(c?"mesh.host.online":"mesh.host.offline")]})]}),(o==null?void 0:o.workspace)&&n.jsxs("span",{className:"text-xs text-text-muted",children:[p("mesh.host.hostNode")," ",n.jsx("span",{className:"font-mono text-text-secondary",children:o.workspace})]})]}),!c&&n.jsxs("div",{className:"mt-4",children:[n.jsx(zt,{variant:"warning",className:"mb-3",children:n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("strong",{children:p("mesh.host.hostOffline")}),n.jsx(dt,{content:p("mesh.host.hostOfflineText")})]})}),e.length>0?n.jsx(qt,{label:p("mesh.host.reconnectToCommand"),hint:p("mesh.host.reconnectToCommandHint"),children:n.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:d,onChange:x=>u(x.target.value),children:[n.jsx("option",{value:"",children:p("mesh.host.waitForHost")}),e.map(x=>n.jsx("option",{value:x.id,children:Sa(x)},x.id))]})}):n.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-muted",children:p("mesh.host.noDaemonsToRoute")})]})]});const g=e.find(x=>x.id===t),f=h&&t?n.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>h(t),disabled:!!m,children:p(m?"mesh.host.settingHost":"mesh.host.setHostAction")}):null;return n.jsxs(Nt,{title:p("mesh.host.title"),description:p("mesh.host.descriptionUnset"),children:[n.jsx(zt,{variant:"info",className:"mb-4",children:n.jsx("strong",{children:p("mesh.host.setHostBanner")})}),e.length>0?n.jsxs(n.Fragment,{children:[t?n.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-muted",children:r?n.jsxs(n.Fragment,{children:[p("mesh.host.willHostOn")," ",n.jsx("span",{className:"font-medium text-text-primary",children:Sa(g)}),o!=null&&o.workspace?n.jsxs(n.Fragment,{children:[" · ",p("mesh.host.setupNode")," ",n.jsx("span",{className:"font-mono text-text-secondary",children:o.workspace})]}):null,". ",p("mesh.host.confirmSetsHost")]}):n.jsxs(n.Fragment,{children:[p("mesh.host.willHostOn")," ",n.jsx("span",{className:"font-medium text-text-primary",children:Sa(g)}),". ",p("mesh.host.attachNodeThenSetHost")]})}):n.jsx(qt,{label:p("mesh.host.hostDaemon"),hint:p("mesh.host.hostDaemonHint"),children:n.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:x=>s(x.target.value),children:[n.jsx("option",{value:"",children:p("mesh.host.resolvingHost")}),e.map(x=>n.jsx("option",{value:x.id,children:Sa(x)},x.id))]})}),f&&n.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:f})]}):n.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-muted",children:p("mesh.host.noDaemonsToHost")})]})}function BL({meshId:e,availableCliAgents:t}){const{t:s}=ve(),r=t.find(a=>{const i=a.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||a.name.toLowerCase().includes("hermes")}),o=Db(r==null?void 0:r.meshCoordinator,{meshId:e});return o?n.jsx(Nt,{title:s("mesh.hermesMcp.title"),description:s("mesh.hermesMcp.description"),children:n.jsx(ax,{setup:o,providerName:(r==null?void 0:r.name)||s("mesh.hermesMcp.fallbackProvider")})}):null}const Vl=[{value:"preserve",labelKey:"mesh.sessionCleanup.preserve",descriptionKey:"mesh.sessionCleanup.preserveHint"},{value:"stop",labelKey:"mesh.sessionCleanup.stop",descriptionKey:"mesh.sessionCleanup.stopHint"},{value:"delete_stopped",labelKey:"mesh.sessionCleanup.deleteStopped",descriptionKey:"mesh.sessionCleanup.deleteStoppedHint"},{value:"stop_and_delete",labelKey:"mesh.sessionCleanup.stopAndDelete",descriptionKey:"mesh.sessionCleanup.stopAndDeleteHint"}],WL=[{value:"smart",labelKey:"mesh.detail.distributionSmart",summaryKey:"mesh.detail.distributionSmartSummary",descriptionKey:"mesh.detail.distributionSmartDescription"},{value:"in_order",labelKey:"mesh.detail.distributionInOrder",summaryKey:"mesh.detail.distributionInOrderSummary",descriptionKey:"mesh.detail.distributionInOrderDescription"}];function UL(e){return e==="smart"?"fitness":"first_eligible"}function KL(e,t){const s=e||"first_eligible";return s==="fitness"||s==="least_loaded"||s==="round_robin"||s==="priority_only"&&t!=null&&t.priorityConfigured?"smart":"in_order"}const qL={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function ed(e){return{...qL,...(e==null?void 0:e.policy)||{}}}function zL({selectedMesh:e,error:t,onDismissError:s,onBack:r,onDelete:o,displayedMeshStatus:a,graphError:i,onRefreshGraph:c,savingPolicy:d,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:h,savingCoordinatorPrompt:p,onSaveCoordinatorPrompt:g,daemons:f,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:b,coordinatorCliType:k,isHostNodeAttached:j,selectedHostNode:v,hostPinned:_,hostLabel:y,hostOnline:w,hostRebindDaemonId:S,onHostRebindDaemonIdChange:C,settingMeshHost:A,onSetMeshHost:O,activeDaemon:L,activeDaemonId:M,meshQueue:$,userName:N,availableCliProviders:I,savingNodeSlotsId:B,onUpdateNodeSlots:T,savingNodeCapabilitiesId:F,onUpdateNodeCapabilities:q,nodeSystemPromptDrafts:Q,onNodeSystemPromptDraftChange:K,savingNodeSystemPromptId:R,onSaveNodeSystemPrompt:D,selectedNodeId:P,onSelectNode:H,showAddNode:W,onShowAddNode:U,onCancelAddNode:ae,nodeWorkspace:be,onNodeWorkspaceChange:V,nodeProviderPriority:we,onNodeProviderPriorityChange:ce,nodeDaemonId:de,onNodeDaemonIdChange:ne,nodeCustomPath:ee,onNodeCustomPathChange:ue,nodePickerWorkspaces:je,nodePickerProviders:X,nodeOnboardingPlan:G,nodePlanLoading:z,attachableDaemons:ie,onAddNode:Ne,onRemoveNode:Be,availableCliAgents:Le,features:Je,sendCommand:Se}){const{t:he}=ve("common"),pe=ed(e),Ee=e.nodes||[],Y=(a==null?void 0:a.nodes)??null,me=l.useMemo(()=>KP(Ee,f,Y),[Ee,f,Y]),fe=Ee.some(ke=>{var et;const Ze=Number((et=ke.policy)==null?void 0:et.schedulingPriority);return Number.isFinite(Ze)&&Ze!==0}),E=!pe.schedulingStrategy,oe=l.useMemo(()=>Ee.some(ke=>{var Ze;return Array.isArray((Ze=ke.policy)==null?void 0:Ze.slots)&&ke.policy.slots.length>0}),[Ee]),Ie=E&&(oe||Ee.length>=2)?"smart":null,[Z,se]=l.useState(!1),ye=!!M&&!!e.id,{theme:$e}=Uo(),Me=l.useMemo(()=>hu($e),[$e]),De="w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",Te=pe.quotaRouting&&typeof pe.quotaRouting=="object"?pe.quotaRouting:{},He=Te.quotaBusyFallback!==!1,tt=KL(pe.schedulingStrategy,{priorityConfigured:fe}),Ct=n.jsxs(n.Fragment,{children:[Je.meshHostDaemonSection&&n.jsx(HL,{daemons:f,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:b,isHostNodeAttached:j,selectedHostNode:v,hostPinned:_,hostLabel:y,hostOnline:w,hostRebindDaemonId:S,onHostRebindDaemonIdChange:ke=>{C(ke),c()},settingMeshHost:A,onSetMeshHost:O}),n.jsx(cL,{nodes:Ee,statusNodes:Y,meshQueue:$,activeDaemon:L,daemons:f,selectedMeshId:e.id,userName:N,features:{addNodeDaemonPicker:Je.addNodeDaemonPicker,nodeInstruction:Je.nodeInstruction},coordinatorDaemonId:x,availableCliProviders:I,savingNodeSlotsId:B,onUpdateNodeSlots:T,savingNodeCapabilitiesId:F,onUpdateNodeCapabilities:q,nodeSystemPromptDrafts:Q,onNodeSystemPromptDraftChange:K,savingNodeSystemPromptId:R,onSaveNodeSystemPrompt:D,selectedNodeId:P,onSelectNode:H,showAddNode:W,onShowAddNode:U,onCancelAddNode:ae,nodeWorkspace:be,onNodeWorkspaceChange:V,nodeProviderPriority:we,onNodeProviderPriorityChange:ce,nodeDaemonId:de,onNodeDaemonIdChange:ne,nodeCustomPath:ee,onNodeCustomPathChange:ue,nodePickerWorkspaces:je,nodePickerProviders:X,nodeOnboardingPlan:G,nodePlanLoading:z,attachableDaemons:ie,onAddNode:Ne,onRemoveNode:Be}),n.jsx(Nt,{title:he("mesh.detail.distribution"),children:n.jsxs("fieldset",{className:"border-none p-0 m-0",children:[n.jsx("legend",{className:"sr-only",children:he("mesh.detail.distribution")}),n.jsx("div",{className:"flex flex-col gap-2",children:WL.map(ke=>{const Ze=tt===ke.value;return n.jsxs("label",{className:`flex items-center gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Ze?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[n.jsx("input",{type:"radio",name:"mesh-distribution",className:"accent-[var(--accent-primary)]",value:ke.value,checked:Ze,disabled:d,onChange:()=>u({schedulingStrategy:UL(ke.value)})}),n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[he(ke.labelKey),Ie===ke.value&&n.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-3xs font-medium text-accent-primary",children:he("mesh.detail.recommended")})]}),n.jsx("span",{className:"block truncate text-xs text-text-muted",children:he(ke.summaryKey)})]}),n.jsx(dt,{content:he(ke.descriptionKey)})]},ke.value)})})]})}),n.jsx(Nt,{title:he("mesh.detail.visibilityTitle"),description:he("mesh.detail.visibilityHint"),children:n.jsxs("select",{className:De,"aria-label":he("mesh.detail.visibilityLabel"),value:pe.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:ke=>u({spawnedSessionVisibility:ke.target.value==="visible"?"visible":"hidden"}),disabled:d,children:[n.jsx("option",{value:"hidden",children:he("mesh.detail.visibilityHidden")}),n.jsx("option",{value:"visible",children:he("mesh.detail.visibilityVisible")})]})}),n.jsx($L,{hostDaemonId:x,hostOnline:w,hostWorkspace:(v==null?void 0:v.workspace)||"",meshProviders:me.providers,unreportedNodeCount:me.unreportedNodeCount,machineAutoApproveEnabled:pe.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:pe.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:u,savingPolicy:d,sendCommand:Se})]}),J=pe.autoFastForward&&typeof pe.autoFastForward=="object"?pe.autoFastForward:{},re=J.enabled!==!1,le=J.remoteNodes===!0,xe=J.mode==="continuous"?"continuous":"idle",Ce=ke=>u({autoFastForward:{...J,...ke}}),Re=Vl.find(ke=>ke.value===pe.sessionCleanupOnNodeRemove)??Vl[0],Ue=n.jsxs(n.Fragment,{children:[n.jsxs(Nt,{title:he("setupWizard.quotaPolicy.title"),description:he("setupWizard.quotaPolicy.description"),collapsible:!0,defaultOpen:!1,children:[n.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[n.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-sm text-text-primary",children:[n.jsx("span",{id:"mesh-quota-busy-fallback-label",children:he("mesh.detail.quotaBusyFallback")}),n.jsx(dt,{content:he("mesh.detail.quotaBusyFallbackHint")})]}),n.jsx(Ur,{checked:He,disabled:d,"aria-labelledby":"mesh-quota-busy-fallback-label",onChange:ke=>u({quotaRouting:{...Te,quotaBusyFallback:ke}})})]}),n.jsx(TL,{quotaRouting:pe.quotaRouting??null,saving:d,error:t,hideHeader:!0,onSave:ke=>u({quotaRouting:{...ke,...Te.quotaBusyFallback!==void 0?{quotaBusyFallback:Te.quotaBusyFallback}:{}}})})]}),n.jsx(Nt,{title:he("mesh.detail.magiTitle"),collapsible:!0,defaultOpen:!1,description:he("mesh.detail.magiDescription"),children:n.jsx(wL,{status:a,daemonId:M,meshId:e.id,sendDaemonCommand:Se,availableProviders:I})}),n.jsxs(Nt,{title:he("mesh.detail.safetyTitle"),collapsible:!0,defaultOpen:!1,description:he("mesh.detail.safetyDescription"),children:[n.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:he("mesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no",he("mesh.detail.optionNo")],["yes",he("mesh.detail.optionYes")]],val:ke=>ke?"yes":"no",parse:ke=>ke==="yes"},{label:he("mesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes",he("mesh.detail.optionYes")],["no",he("mesh.detail.optionNo")]],val:ke=>ke?"yes":"no",parse:ke=>ke==="yes"},{label:he("mesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",he("mesh.detail.requireApprovalBeforePush")],["not_required",he("mesh.detail.doNotRequireApproval")]],val:ke=>ke?"required":"not_required",parse:ke=>ke==="required"},{label:he("mesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",he("mesh.detail.warnAndContinue")],["block",he("mesh.detail.blockTask")],["checkpoint_then_continue",he("mesh.detail.checkpointThenContinue")]],val:ke=>ke||"warn",parse:ke=>ke},{label:he("mesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",he("mesh.detail.requireExplicitApproval")],["enabled",he("mesh.detail.allowRefineryPublish")]],val:ke=>ke?"enabled":"disabled",parse:ke=>ke==="enabled"}].map(({label:ke,key:Ze,opts:et,val:Ve,parse:st})=>n.jsx(qt,{label:ke,children:n.jsx("select",{className:De,value:Ve(pe[Ze]),onChange:lt=>u({[Ze]:st(lt.target.value)}),disabled:d,children:et.map(([lt,Qe])=>n.jsx("option",{value:lt,children:Qe},lt))})},Ze))}),n.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[n.jsx(qt,{label:he("mesh.detail.autoFastForward"),children:n.jsxs("select",{className:De,value:re?"enabled":"disabled",onChange:ke=>Ce({enabled:ke.target.value==="enabled"}),disabled:d,children:[n.jsx("option",{value:"enabled",children:he("mesh.detail.ffEnabled")}),n.jsx("option",{value:"disabled",children:he("mesh.detail.ffDisabled")})]})}),n.jsx(qt,{label:he("mesh.detail.includeRemoteNodes"),hint:he("mesh.detail.includeRemoteNodesHint"),children:n.jsxs("select",{className:De,value:le?"yes":"no",onChange:ke=>Ce({remoteNodes:ke.target.value==="yes"}),disabled:d||!re,children:[n.jsx("option",{value:"no",children:he("mesh.detail.remoteNo")}),n.jsx("option",{value:"yes",children:he("mesh.detail.remoteYes")})]})}),n.jsx(qt,{label:he("mesh.detail.detectionMode"),hint:he("mesh.detail.detectionModeHint"),children:n.jsxs("select",{className:De,value:xe,onChange:ke=>Ce({mode:ke.target.value==="continuous"?"continuous":"idle"}),disabled:d||!re||!le,children:[n.jsx("option",{value:"idle",children:he("mesh.detail.idleEdgeOnly")}),n.jsx("option",{value:"continuous",children:he("mesh.detail.continuousScan")})]})}),n.jsx(qt,{label:he("mesh.detail.sessionCleanupLabel"),hint:`${he("mesh.detail.sessionCleanupHint")}
|
|
107
|
+
${he(Re.descriptionKey)}`,children:n.jsx("select",{className:De,value:pe.sessionCleanupOnNodeRemove||"preserve",onChange:ke=>u({sessionCleanupOnNodeRemove:ke.target.value}),disabled:d,children:Vl.map(ke=>n.jsx("option",{value:ke.value,children:he(ke.labelKey)},ke.value))})})]})]}),Je.coordinatorPrompt&&n.jsxs(Nt,{title:he("mesh.detail.coordinatorPromptTitle"),collapsible:!0,defaultOpen:!1,description:he("mesh.detail.thisMeshHint",{name:e.name}),children:[n.jsx(ML,{daemonId:M,meshId:e.id,cliType:k,sendCommand:Se,defaultOpen:!0}),n.jsx(qt,{label:he("mesh.detail.overrideLabel"),hint:he("mesh.detail.overrideHint"),className:"mt-3",children:n.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:ke=>h({...m,override:ke.target.value}),disabled:p,placeholder:he("mesh.detail.overridePlaceholder")})}),n.jsx(qt,{label:he("mesh.detail.appendLabel"),hint:he("mesh.detail.appendHint"),children:n.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:ke=>h({...m,append:ke.target.value}),disabled:p,placeholder:he("mesh.detail.appendPlaceholder")})}),n.jsx(PL,{daemonId:x,workspace:(v==null?void 0:v.workspace)||"",sendCommand:Se}),n.jsxs("details",{className:"mt-2 text-xs text-text-muted",children:[n.jsxs("summary",{className:"cursor-pointer select-none inline-flex items-center gap-1",children:[he("mesh.detail.availablePlaceholders"),n.jsx(dt,{content:he("mesh.detail.placeholdersIntro"),size:12})]}),n.jsx("div",{className:"mt-2 overflow-x-auto",children:n.jsx("table",{className:"w-full text-left border-collapse",children:n.jsx("tbody",{children:LL.map(ke=>n.jsxs("tr",{className:"border-t border-border-subtle/60 align-top",children:[n.jsx("td",{className:"py-1 pr-3 font-mono whitespace-nowrap text-text-secondary",children:`{{${ke.token}}}`}),n.jsx("td",{className:"py-1 pr-3",children:ke.description}),n.jsx("td",{className:"py-1 font-mono text-text-muted/80",children:ke.example})]},ke.token))})})})]}),n.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:g,disabled:p,children:he(p?"mesh.detail.saving":"mesh.detail.saveCoordinatorPrompt")}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h({override:"",append:""}),disabled:p,title:he("mesh.detail.clearTitle"),children:he("mesh.detail.clear")})]})]}),n.jsx(Nt,{title:he("mesh.notes.tab"),collapsible:!0,defaultOpen:!1,description:he("mesh.notes.sectionHint"),children:n.jsx(Vi.Provider,{value:Me,children:n.jsx(NL,{meshId:e.id,daemonId:M,sendDaemonCommand:Se})})}),Je.hermesMcpConfig&&n.jsx(BL,{meshId:e.id,availableCliAgents:Le}),Je.meshHostDaemonSection&&n.jsx(Nt,{title:he("mesh.detail.useFromCli"),collapsible:!0,defaultOpen:!1,description:he("mesh.detail.mcpDescription"),children:n.jsxs("code",{className:"block overflow-x-auto rounded-lg bg-bg-secondary px-3 py-2 text-xs",children:["adhdev mcp --repo-mesh ",e.id]})})]}),Fe=[{key:"general",icon:n.jsx(Or,{size:14}),label:he("mesh.detail.tabGeneral"),content:Ct},{key:"advanced",icon:n.jsx(Jp,{size:14}),label:he("mesh.detail.tabAdvanced"),content:Ue}];return n.jsxs(Wo,{icon:n.jsx(On,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",subtitleInline:!0,widthClassName:"max-w-5xl",contentClassName:"gap-4",actions:n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{className:"btn btn-secondary btn-sm",onClick:r,children:he("mesh.detail.back")}),n.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>se(!0),disabled:!ye,title:he(ye?"mesh.detail.observabilityOpenTitle":"mesh.detail.observabilityDisabledTitle"),children:[n.jsx(On,{size:14}),he("mesh.detail.observabilityOpen")]}),n.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>o(e.id),children:he("mesh.detail.delete")})]}),children:[t&&n.jsx(zt,{variant:"error",onDismiss:s,children:t}),i&&n.jsx(zt,{variant:"warning",children:i}),n.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-subtle bg-bg-card/30",children:n.jsx(gb,{variant:"underline",tabs:Fe,tabIdPrefix:"mesh-settings-tab",ariaLabel:he("mesh.detail.tabsAriaLabel"),panelClassName:"p-4 md:p-6"})}),Z&&ye&&n.jsx(Kd,{activeConv:jx({meshId:e.id,daemonId:M,meshName:e.name}),sendDaemonCommand:Se,onClose:()=>se(!1)})]})}function GL(e,t){const s=[],r=new Map;for(const o of e)for(const a of o.meshes)a!=null&&a.id&&(r.has(a.id)||(r.set(a.id,[]),s.push(a.id)),r.get(a.id).push({daemonId:o.daemonId,mesh:a}));return s.map(o=>{const a=r.get(o),i=a.map(d=>Gi(d.mesh,t)).find(Boolean)||"";return((i?a.find(d=>on(d.daemonId,i)):void 0)??a[0]).mesh})}async function VL(e,t,s){const r=new Array(e.length);let o=0;const a=()=>GL(r.filter(i=>!!i),e);return await Promise.all(e.map(async(i,c)=>{try{r[c]=await t(i)}catch{}o+=1,s==null||s({merged:a(),settled:o,total:e.length})})),a()}function YL(e,t){const s=new Map(t.map(a=>[a.id,a])),r=new Set,o=e.map(a=>(r.add(a.id),s.get(a.id)??a));for(const a of t)r.has(a.id)||o.push(a);return o}const ao=new Map;async function Tx(e){var o,a,i,c,d,u,m,h,p,g,f;const{sendCommand:t,unwrapResult:s}=e,r={meshCreated:!1,meshId:"",error:null,warning:null,plan:null};try{const x=e.reusablePlan??s(await t(e.targetDaemonId,"plan_mesh_onboarding",{workspace:e.workspace||void 0,operation:"auto",meshInventory:e.meshInventory}));if(r.plan=x,(x==null?void 0:x.success)===!1)return{...r,error:`${x.code||"onboarding_blocked"}: ${x.error}${x.action?` ${x.action}`:""}`};if(((o=x==null?void 0:x.plan)==null?void 0:o.kind)!=="create_mesh_and_onboard")return{...r,error:((a=x==null?void 0:x.plan)==null?void 0:a.summary)||"A compatible mesh already exists; add this workspace to it instead of creating a duplicate mesh."};const b={name:e.name.trim()};(e.repoRemoteUrl||(d=(c=(i=x==null?void 0:x.discovery)==null?void 0:i.origin)==null?void 0:c.urls)!=null&&d[0])&&(b.repoRemoteUrl=e.repoRemoteUrl||x.discovery.origin.urls[0]),(e.repoIdentity||(u=x==null?void 0:x.discovery)!=null&&u.repoIdentity)&&(b.repoIdentity=e.repoIdentity||x.discovery.repoIdentity),(m=x==null?void 0:x.discovery)!=null&&m.defaultBranch&&(b.defaultBranch=x.discovery.defaultBranch);const k=await t(e.targetDaemonId,"create_mesh",b),j=s(k);if((j==null?void 0:j.success)===!1)return{...r,error:j.error||"Create failed"};const v=typeof((h=j==null?void 0:j.mesh)==null?void 0:h.id)=="string"?j.mesh.id:"",_={...r,meshCreated:!0,meshId:v};if(!v||!e.attachWorkspace||!e.workspace)return _;try{const y=await t(e.targetDaemonId,"add_mesh_node",{meshId:v,daemonId:e.targetDaemonId,machineId:e.machineId,workspace:((p=x==null?void 0:x.discovery)==null?void 0:p.repoRoot)||e.workspace,repoRoot:(g=x==null?void 0:x.discovery)==null?void 0:g.repoRoot,isLocalWorktree:((f=x==null?void 0:x.discovery)==null?void 0:f.isLinkedWorktree)===!0,role:"host",providerPriority:e.providerPriority}),w=s(y);return(w==null?void 0:w.success)===!1?{..._,warning:mp(w.error||"add_mesh_node failed")}:_}catch(y){return{..._,warning:mp((y==null?void 0:y.message)||"add_mesh_node failed")}}}catch(x){return{...r,error:(x==null?void 0:x.message)||"Create failed"}}}function mp(e){return`Mesh created, but attaching the workspace failed: ${e}. Add the workspace from the mesh's node list.`}function Yl(e,t){return e===t?!0:e.length!==t.length?!1:JSON.stringify(e)===JSON.stringify(t)}function Ix({daemons:e,primaryDaemonId:t,sendCommand:s,unwrapResult:r,normalizeMesh:o,features:a,loadDaemonMetadata:i,confirmAction:c}){const d=e.map(we=>we.id).filter(Boolean).sort().join(","),[u,m]=l.useState(()=>ao.get(d)??[]);l.useEffect(()=>{Ja(u)},[u]);const[h,p]=l.useState(null),[g,f]=l.useState(()=>!ao.has(d)),[x,b]=l.useState(null),[k,j]=l.useState(!1),[v,_]=l.useState(!1),[y,w]=l.useState(null),[S,C]=l.useState(""),[A,O]=l.useState(""),[L,M]=l.useState(""),[$,N]=l.useState(""),[I,B]=l.useState(""),[T,F]=l.useState(null),[q,Q]=l.useState(!1),K=a.createDaemonPicker?$:t,R=l.useMemo(()=>e.find(we=>we.id===K),[e,K]),D=(R==null?void 0:R.workspaces)||[],P=l.useMemo(()=>Zn((R==null?void 0:R.availableProviders)||[]),[R]);l.useEffect(()=>{!i||!K||!R||!(!R.workspaces||!R.availableProviders)||Promise.resolve(i(K,{minFreshMs:3e4})).catch(()=>{})},[i,K,R]),l.useEffect(()=>{if(!k||!K||!I){F(null),Q(!1);return}let we=!1;return Q(!0),s(K,"plan_mesh_onboarding",{workspace:I,operation:"auto",meshInventory:u}).then(ce=>{if(we)return;const de=r(ce);F(de),de!=null&&de.success&&(O(ne=>{var ee;return ne||((ee=de.discovery)==null?void 0:ee.repoIdentity)||""}),M(ne=>{var ee,ue,je,X,G,z;return ne||((je=(ue=(ee=de.discovery)==null?void 0:ee.origin)==null?void 0:ue.urls)==null?void 0:je[0])||((z=(G=(X=de.discovery)==null?void 0:X.upstream)==null?void 0:G.urls)==null?void 0:z[0])||""}),C(ne=>{var ee,ue;return ne||`${String(((ee=de.discovery)==null?void 0:ee.repoIdentity)||((ue=de.discovery)==null?void 0:ue.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(ce=>{we||F({success:!1,error:(ce==null?void 0:ce.message)||"Git discovery failed"})}).finally(()=>{we||Q(!1)}),()=>{we=!0}},[k,K,I,u,s,r]);const H=l.useMemo(()=>e.map(we=>we.id).filter(Boolean).sort().join(","),[e]),W=l.useRef(0),U=l.useCallback(async(we=!1)=>{const ce=++W.current,de=()=>W.current===ce,ne=we||ao.has(H);f(ee=>ne?ee:!0);try{if(a.createDaemonPicker){const ee=await VL(e,async ue=>{if(!ue.id)return{daemonId:"",meshes:[]};const je=await s(ue.id,"list_meshes",{}),X=r(je);if((X==null?void 0:X.success)===!1)throw new Error(X.error||"Failed to load meshes");const G=(Array.isArray(X==null?void 0:X.meshes)?X.meshes:[]).map(z=>o(z,ue.id)).filter(z=>z.id);return{daemonId:ue.id,meshes:G}},({merged:ue,settled:je,total:X})=>{!de()||je>=X||ue.length!==0&&(m(G=>{const z=ne?YL(G,ue):ue;return Yl(G,z)?G:z}),f(!1))});if(!de())return;m(ue=>Yl(ue,ee)?ue:ee),ao.set(H,ee),b(null)}else{if(!t)return;const ee=await s(t,"list_meshes");if(!de())return;if(ee!=null&&ee.success){const ue=(ee.meshes||[]).map(je=>o(je,t));m(je=>Yl(je,ue)?je:ue),ao.set(H,ue),b(null)}else b((ee==null?void 0:ee.error)||"Failed to load meshes")}}catch(ee){de()&&b((ee==null?void 0:ee.message)||"Failed to load meshes")}finally{de()&&f(!1)}},[H,t,s,r,o,a.createDaemonPicker]);async function ae(){const we=a.createDaemonPicker?$:t;if(!we||!S.trim())return;const ce=L.trim(),de=A.trim(),ne=I.trim();if(!(!ne&&!ce&&!de)&&!v){_(!0),w(null);try{const ee=await Tx({targetDaemonId:we,name:S,repoRemoteUrl:ce,repoIdentity:de,workspace:ne,attachWorkspace:!!ne,machineId:R==null?void 0:R.machineId,providerPriority:nr(P),meshInventory:u,sendCommand:s,unwrapResult:r,reusablePlan:!q&&T?T:void 0});if(ee.plan!==null&&F(ee.plan),ee.warning&&w(ee.warning),!ee.meshCreated){b(ee.error||"Create failed");return}j(!1),C(""),O(""),M(""),B(""),await U(),ee.meshId&&p(ee.meshId)}finally{_(!1)}}}async function be(we){var ee;const ce=((ee=u.find(ue=>ue.id===we))==null?void 0:ee.name)||we;if(!(c?await c({title:"Delete this mesh?",description:`"${ce}" will be removed from this daemon. This cannot be undone.`,confirmLabel:"Delete",tone:"danger"}):confirm("Delete this mesh? This cannot be undone.")))return;const ne=Gi(u.find(ue=>ue.id===we),e)||(a.createDaemonPicker?"":t);if(!ne){b(at.t("mesh.host.noCommandTarget"));return}try{const ue=await s(ne,"delete_mesh",{meshId:we}),je=r(ue);if((je==null?void 0:je.success)===!1)throw new Error(je.error||"Failed to delete");h===we&&p(null),await U()}catch(ue){b((ue==null?void 0:ue.message)||"Delete failed")}}function V(){j(!1),C(""),O(""),M(""),B(""),F(null),w(null)}return{meshes:u,setMeshes:m,selectedMeshId:h,setSelectedMeshId:p,loading:g,error:x,setError:b,showCreate:k,setShowCreate:j,creating:v,createWarning:y,setCreateWarning:w,createName:S,setCreateName:C,createRepoIdentity:A,setCreateRepoIdentity:O,createRepoRemoteUrl:L,setCreateRepoRemoteUrl:M,newMeshDaemonId:$,setNewMeshDaemonId:N,newMeshWorkspace:I,setNewMeshWorkspace:B,createPickerWorkspaces:D,createPickerProviders:P,createOnboardingPlan:T,createPlanLoading:q,loadMeshes:U,handleCreate:ae,handleDelete:be,cancelCreate:V}}function QL({selectedMesh:e,selectedMeshId:t,activeDaemonId:s,daemons:r,sendCommand:o,unwrapResult:a,loadLiveMesh:i,resolveCommandTarget:c,launchCoordinator:d,features:u,loadMeshes:m,reloadMeshStatus:h,setError:p,confirmAction:g}){const f=s;function x(){return f||(p(at.t("mesh.host.noCommandTarget")),null)}const[b,k]=l.useState(null),[j,v]=l.useState(!1),[_,y]=l.useState(""),[w,S]=l.useState([]),[C,A]=l.useState(""),[O,L]=l.useState(!1),[M,$]=l.useState(null),[N,I]=l.useState(!1),[B,T]=l.useState(""),[F,q]=l.useState(!1),[Q,K]=l.useState(!1),[R,D]=l.useState(null),[P,H]=l.useState(!1),[W,U]=l.useState({override:"",append:""}),[ae,be]=l.useState(!1),[V,we]=l.useState({}),[ce,de]=l.useState(null),ne=l.useMemo(()=>r.find(Y=>Y.id===C),[r,C]),ee=(ne==null?void 0:ne.workspaces)||[],ue=l.useMemo(()=>Zn((ne==null?void 0:ne.availableProviders)||[]),[ne]);l.useEffect(()=>{if(!j||!t||!_.trim()){$(null);return}const Y=u.addNodeDaemonPicker?C:f;if(!Y)return;let me=!1;return I(!0),o(Y,"plan_mesh_onboarding",{workspace:_.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(fe=>{me||$(a(fe))}).catch(fe=>{me||$({success:!1,error:(fe==null?void 0:fe.message)||"Git discovery failed"})}).finally(()=>{me||I(!1)}),()=>{me=!0}},[j,t,e,_,C,f,u.addNodeDaemonPicker,o,a]);async function je(){var fe,E,oe;if(!t)return;const Y=_.trim();if(!Y)return;const me=x();if(me)try{const Ie=u.addNodeDaemonPicker?C:me,Z=await o(Ie,"plan_mesh_onboarding",{workspace:Y,meshId:t,inlineMesh:e,operation:"add_existing"}),se=a(Z);if($(se),(se==null?void 0:se.success)===!1)throw new Error(uu(se));const ye={meshId:t,workspace:((fe=se==null?void 0:se.discovery)==null?void 0:fe.repoRoot)||Y,repoRoot:(E=se==null?void 0:se.discovery)==null?void 0:E.repoRoot,isLocalWorktree:((oe=se==null?void 0:se.discovery)==null?void 0:oe.isLinkedWorktree)===!0};u.addNodeDaemonPicker&&C&&(ye.daemonId=C,ye.machineId=ne==null?void 0:ne.machineId),ye.providerPriority=Bo(w);const $e=await o(me,"add_mesh_node",ye),Me=a($e);if((Me==null?void 0:Me.success)===!1)throw new Error(Me.error||"Add node failed");v(!1),y(""),S([]),A(""),L(!1),await m(),await h()}catch(Ie){p((Ie==null?void 0:Ie.message)||"Add node failed")}}async function X(Y){var Ie;if(!e)return;const me=ed(e),fe=((Ie=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(Z=>Z.value===me.sessionCleanupOnNodeRemove))==null?void 0:Ie.label)||"Preserve history and runtimes";if(!(g?await g({title:"Remove this node?",description:`Node removal cleanup policy: ${fe}`,confirmLabel:"Remove",tone:"danger"}):confirm(`Remove this node?
|
|
108
|
+
|
|
109
|
+
Node removal cleanup policy: ${fe}`)))return;const oe=x();if(oe)try{const Z=await o(oe,"remove_mesh_node",{meshId:e.id,nodeId:Y}),se=a(Z);if((se==null?void 0:se.success)===!1)throw new Error(se.error||"Remove failed");b===Y&&k(null),await m(),await h()}catch(Z){p((Z==null?void 0:Z.message)||"Remove node failed")}}async function G(Y){if(!e)return;const me={...ed(e),...Y},fe=x();if(fe)try{H(!0),p(null);const E=await o(fe,"update_mesh",{meshId:e.id,policy:me}),oe=a(E);if((oe==null?void 0:oe.success)===!1)throw new Error(oe.error||"Policy update failed");ct.showToast(at.t("common.saved"),"success"),await m()}catch(E){p((E==null?void 0:E.message)||"Policy update failed")}finally{H(!1)}}const[z,ie]=l.useState(null);async function Ne(Y,me){if(!t)return;const fe=x();if(fe)try{ie(Y.id),p(null);const E=await o(fe,"update_mesh_node",{meshId:t,nodeId:Y.id,policy:{slots:me}}),oe=a(E);if((oe==null?void 0:oe.success)===!1){p(oe.error||"Node slots update failed");return}ct.showToast(at.t("common.saved"),"success"),await m()}catch(E){p((E==null?void 0:E.message)||"Node slots update failed")}finally{ie(null)}}const[Be,Le]=l.useState(null);async function Je(Y,me){if(!t)return;const fe=x();if(!fe)return;const E=me.map(oe=>oe.trim()).filter(Boolean);try{Le(Y.id),p(null);const oe=await o(fe,"update_mesh_node",{meshId:t,nodeId:Y.id,capabilities:E}),Ie=a(oe);if((Ie==null?void 0:Ie.success)===!1){p(Ie.error||"Node tag update failed");return}ct.showToast(at.t("common.saved"),"success"),await m()}catch(oe){p((oe==null?void 0:oe.message)||"Node tag update failed")}finally{Le(null)}}async function Se(){if(!t)return;const Y=x();if(!Y)return;const fe={...(e==null?void 0:e.coordinator)||{}};W.override.trim()?fe.systemPromptOverride=W.override:delete fe.systemPromptOverride,W.append.trim()?fe.systemPromptAppend=W.append:delete fe.systemPromptAppend,delete fe.systemPromptSuffix;try{be(!0),p(null);const E=await o(Y,"update_mesh",{meshId:t,coordinator:fe}),oe=a(E);if((oe==null?void 0:oe.success)===!1){p(oe.error||"Coordinator prompt save failed");return}ct.showToast(at.t("common.saved"),"success"),await m()}catch(E){p((E==null?void 0:E.message)||"Coordinator prompt save failed")}finally{be(!1)}}async function he(Y){if(!t)return;const me=x();if(!me)return;const fe=(V[Y.id]||"").trim();try{de(Y.id),p(null);const E=await o(me,"update_mesh_node",{meshId:t,nodeId:Y.id,systemPrompt:fe}),oe=a(E);if((oe==null?void 0:oe.success)===!1){p(oe.error||"Node instruction save failed");return}ct.showToast(at.t("common.saved"),"success"),await m()}catch(E){p((E==null?void 0:E.message)||"Node instruction save failed")}finally{de(null)}}async function pe(Y){if(!(!e||!Y)){if(g){const me=r.find(oe=>oe.id===Y),fe=(me==null?void 0:me.machineNickname)||(me==null?void 0:me.nickname)||(me==null?void 0:me.hostname)||Y;if(!await g({title:at.t("mesh.host.setHostConfirmTitle",{name:fe}),description:at.t("mesh.host.setHostActionHint"),confirmLabel:at.t("mesh.host.setHostAction")}))return}p(null),D(null);try{K(!0);const me=(e.nodes||[]).find(oe=>on(String(oe.daemon_id||oe.daemonId||""),Y)),fe=await o(Y,"set_mesh_host",{meshId:e.id,hostDaemonId:Y,...me!=null&&me.id?{hostNodeId:me.id}:{}}),E=a(fe);if((E==null?void 0:E.success)===!1){p(E.error||"Setting the mesh host failed");return}await m()}catch(me){p((me==null?void 0:me.message)||"Setting the mesh host failed")}finally{K(!1)}}}async function Ee(){if(e){p(null),D(null);try{q(!0);const Y=i?await i(s,e.id,e):null,me=c(s,e.id,e,e.nodes||[],Y);if("error"in me)throw new Error(me.error);const fe=await d(me.targetDaemonId,{meshId:e.id,inlineMesh:me.inlineMesh,coordinatorNodeId:me.coordinatorNodeId,cliType:B.trim()||void 0});D(fe.message)}catch(Y){p((Y==null?void 0:Y.message)||"Coordinator launch failed")}finally{q(!1)}}}return{selectedNodeId:b,setSelectedNodeId:k,showAddNode:j,setShowAddNode:v,nodeWorkspace:_,setNodeWorkspace:y,nodeProviderPriority:w,setNodeProviderPriority:S,nodeDaemonId:C,setNodeDaemonId:A,nodeCustomPath:O,setNodeCustomPath:L,nodePickerWorkspaces:ee,nodePickerProviders:ue,nodeOnboardingPlan:M,nodePlanLoading:N,coordinatorCliType:B,setCoordinatorCliType:T,launchingCoordinator:F,launchResult:R,settingMeshHost:Q,savingPolicy:P,coordinatorPromptDraft:W,setCoordinatorPromptDraft:U,savingCoordinatorPrompt:ae,nodeSystemPromptDrafts:V,setNodeSystemPromptDrafts:we,savingNodeSystemPromptId:ce,savingNodeSlotsId:z,savingNodeCapabilitiesId:Be,handleAddNode:je,handleRemoveNode:X,handleUpdatePolicy:G,handleUpdateNodeSlots:Ne,handleUpdateNodeCapabilities:Je,handleSaveCoordinatorPrompt:Se,handleSaveNodeSystemPrompt:he,handleLaunchCoordinator:Ee,handleSetMeshHost:pe}}const JL=[];function XL(e){const t=e==null?void 0:e.queue,s=t&&typeof t=="object"&&!Array.isArray(t)?t.tasks:t;return Array.isArray(s)?s.filter(r=>!!r&&typeof r=="object"&&typeof r.id=="string"):JL}function ZL({status:e}){return{meshQueue:l.useMemo(()=>XL(e),[e])}}const eE=()=>()=>{};function Mx(e){const t=l.useCallback(r=>e?O1(e,r):eE(),[e]),s=l.useCallback(()=>So(e),[e]);return l.useSyncExternalStore(t,s,s)}const tE=6e4;function f3({meshId:e,daemonId:t,load:s,extract:r,sendData:o,backstopMs:a=tE}){const i=Mx(e),c=l.useRef(s);c.current=s;const d=l.useRef(r);d.current=r;const u=l.useCallback(p=>{const g=c.current;return!e||!t||!g?Promise.resolve(null):$i({meshId:e,daemonId:t,refresh:p,load:g,extract:d.current})},[e,t]);l.useEffect(()=>{u(!1)},[u]),xx({daemonIds:l.useMemo(()=>t?[t]:[],[t]),meshId:e,sendData:o,onRevisionAdvance:()=>{typeof document<"u"&&document.hidden||u(!1)}}),l.useEffect(()=>{if(!e||!t||a<=0)return;const p=setInterval(()=>{typeof document<"u"&&document.hidden||u(!1)},a);return()=>clearInterval(p)},[e,t,a,u]);const m=l.useCallback(()=>u(!0),[u]),h=l.useCallback(()=>u(!1),[u]);return{status:(i==null?void 0:i.status)??null,loading:(i==null?void 0:i.loading)??!1,refreshing:(i==null?void 0:i.refreshing)??!1,error:(i==null?void 0:i.error)??null,loadedAt:(i==null?void 0:i.loadedAt)??null,refresh:m,reload:h}}function nE(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}function sE({selectedMeshId:e,loadMeshStatus:t,extractStatus:s,normalizeNode:r}){const o=Mx(e),[a,i]=l.useState(null),[c,d]=l.useState("idle"),u=(o==null?void 0:o.status)??null,m=l.useMemo(()=>!u||!r?u:{...u,nodes:(u.nodes??[]).map(g=>r(g,u.meshId??e??"",""))},[u,r,e]);function h(g){e&&$1(e,g,(o==null?void 0:o.daemonId)??null)}async function p(g,f=e,x=!1){var k;if(!g||!f)return;i(null),d(x?"settling":"first_paint"),await $i({meshId:f,daemonId:g,refresh:x,load:(j,v,_)=>t(j,v,{refresh:_.refresh}),extract:j=>s(j)})?d("settled"):(i(((k=So(f))==null?void 0:k.error)||"Failed to load mesh graph"),d("idle"))}return{meshGraphStatus:m,setMeshGraphStatus:h,graphLoading:!!(o!=null&&o.loading)&&!u,graphError:a??(u?null:(o==null?void 0:o.error)??null),setGraphError:i,graphProvenance:c,graphBootstrapFallback:nE(o==null?void 0:o.response),loadGraph:p}}function rE(e){var o;if(!e)return"null";const t=[...e.nodes??[]].map(a=>{var i,c,d,u,m,h;return[a.nodeId,a.health,((i=a.git)==null?void 0:i.branch)??"",((c=a.git)==null?void 0:c.headCommit)??"",(d=a.git)!=null&&d.dirty?"1":"0",((u=a.git)==null?void 0:u.ahead)??0,((m=a.git)==null?void 0:m.behind)??0,(h=a.git)!=null&&h.hasConflicts?"1":"0",[...a.activeSessions??[]].sort().join(",")].join("|")}).sort().join(";"),s=(o=e.queue)==null?void 0:o.summary,r=s?[s.pending,s.assigned,s.completed,s.failed,s.cancelled].join(","):"";return`${t}::${r}`}const oE=4,aE=3e4;function iE(){return{lastFingerprint:null,stableTicks:0,backedOff:!1}}function td(e){e.stableTicks=0,e.backedOff=!1}function lE(e,t){const s=rE(t);return e.lastFingerprint===null?(e.lastFingerprint=s,e.backedOff):s!==e.lastFingerprint?(e.lastFingerprint=s,td(e),!1):(e.stableTicks+=1,e.stableTicks>=oE&&(e.backedOff=!0),e.backedOff)}function cE(e,t){return e.backedOff?Math.max(t,aE):t}const dE=7e3,uE=45e3,hp=5*60*1e3;function mE(){const e=RP(),{t}=ve("common"),{confirm:s,confirmDialog:r}=Fr(),{sendCommand:o,sendData:a,daemons:i,userName:c,loadMeshStatus:d,launchCoordinator:u,loadLiveMesh:m,extractStatus:h,unwrapResult:p,normalizeMesh:g,normalizeNode:f,resolveCommandTarget:x,features:b}=e,k=Br(),j=i[0],v=(j==null?void 0:j.id)||"",_=l.useMemo(()=>((j==null?void 0:j.availableProviders)||[]).filter(mt=>mt.category==="cli").map(mt=>({id:mt.type||mt.id,name:mt.displayName||mt.name||mt.type,meshCoordinator:mt.meshCoordinator})),[j]),y=l.useMemo(()=>Zn((j==null?void 0:j.availableProviders)||[]),[j]),{meshes:w,selectedMeshId:S,setSelectedMeshId:C,loading:A,error:O,setError:L,showCreate:M,setShowCreate:$,createName:N,setCreateName:I,createRepoIdentity:B,setCreateRepoIdentity:T,createRepoRemoteUrl:F,setCreateRepoRemoteUrl:q,newMeshDaemonId:Q,setNewMeshDaemonId:K,newMeshWorkspace:R,setNewMeshWorkspace:D,createPickerWorkspaces:P,createOnboardingPlan:H,createPlanLoading:W,creating:U,createWarning:ae,setCreateWarning:be,loadMeshes:V,handleCreate:we,handleDelete:ce,cancelCreate:de}=Ix({confirmAction:s,daemons:i,primaryDaemonId:v,sendCommand:o,unwrapResult:p,normalizeMesh:g,features:b,loadDaemonMetadata:k}),ne=w.find(Ye=>Ye.id===S)||null,{meshGraphStatus:ee,graphLoading:ue,graphError:je,setGraphError:X,loadGraph:G}=sE({selectedMeshId:S,loadMeshStatus:d,extractStatus:h,normalizeNode:f}),[z,ie]=l.useState(""),[Ne,Be]=l.useState(""),Le=b.meshHostDaemonSection?z:v,{meshQueue:Je}=ZL({status:ee}),Se=async()=>{!S||!Le||await G(Le,S,!1)},{selectedNodeId:he,setSelectedNodeId:pe,showAddNode:Ee,setShowAddNode:Y,nodeWorkspace:me,setNodeWorkspace:fe,nodeProviderPriority:E,setNodeProviderPriority:oe,nodeDaemonId:Ie,setNodeDaemonId:Z,nodeCustomPath:se,setNodeCustomPath:ye,nodePickerWorkspaces:$e,nodePickerProviders:Me,nodeOnboardingPlan:De,nodePlanLoading:Te,coordinatorCliType:He,savingPolicy:tt,coordinatorPromptDraft:Ct,setCoordinatorPromptDraft:J,savingCoordinatorPrompt:re,nodeSystemPromptDrafts:le,setNodeSystemPromptDrafts:xe,savingNodeSystemPromptId:Ce,savingNodeSlotsId:Re,savingNodeCapabilitiesId:Ue,handleAddNode:Fe,handleRemoveNode:ke,handleUpdatePolicy:Ze,handleUpdateNodeSlots:et,handleUpdateNodeCapabilities:Ve,handleSaveCoordinatorPrompt:st,handleSaveNodeSystemPrompt:lt,settingMeshHost:Qe,handleSetMeshHost:ge}=QL({confirmAction:s,selectedMesh:ne,selectedMeshId:S,activeDaemonId:Le,daemons:i,availableCliProviders:y,sendCommand:o,unwrapResult:p,loadLiveMesh:m,resolveCommandTarget:x,launchCoordinator:u,features:{addNodeDaemonPicker:b.addNodeDaemonPicker},loadMeshes:V,reloadMeshStatus:Se,setError:L}),_e=l.useMemo(()=>i.find(Ye=>Ye.id===Le)||j,[i,Le,j]),Pe=l.useMemo(()=>new Set(((ne==null?void 0:ne.nodes)||[]).map(Ye=>String(Ye.daemon_id||Ye.daemonId||""))),[ne]),nt=l.useMemo(()=>i.filter(Ye=>Ye.id&&!Pe.has(Ye.id)&&!Np(Ye)),[i,Pe]),ze=(ne==null?void 0:ne.nodes)||[],ut=l.useMemo(()=>ze.find(Ye=>on(String(Ye.daemon_id||Ye.daemonId||""),z)),[ze,z]),Ge=b.meshHostDaemonSection?!!ut:!0,bt=l.useMemo(()=>{if(!b.meshHostDaemonSection||!ne)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Ye=ne.meshHost,mt=ee!=null&&ee.meshId&&String(ee.meshId)===String(ne.id??"")?ee.meshHost:void 0,Zt=mt!=null&&mt.hostDaemonId?mt:Ye??mt,Sn=Qc(Zt),sn=Sn.hostDaemonId,rn=ze.find(kn=>kn.role==="host"),In=Sn.hostNodeId||String((rn==null?void 0:rn.id)||""),jt=In?ze.find(kn=>String(kn.id)===In):void 0,en=String((jt==null?void 0:jt.daemon_id)||(jt==null?void 0:jt.daemonId)||""),gn=sn||en;if(!gn)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Wt=i.find(kn=>sn&&on(kn.id,sn))||(en?i.find(kn=>on(kn.id,en)):void 0);if(Wt)return{pinned:!0,daemonId:Wt.id,label:hE(Wt),online:!0,hostNode:jt};const Rs=String((jt==null?void 0:jt.machineLabel)||"")||String((jt==null?void 0:jt.workspace)||"")||gn;return{pinned:!0,daemonId:gn,label:Rs,online:!1,hostNode:jt}},[ne,ze,i,ee,b.meshHostDaemonSection]),Mt=bt.daemonId,Pt=bt.online,mn=bt.pinned?bt.hostNode:ut,nn=l.useMemo(()=>!b.meshHostDaemonSection||!bt.pinned?"":!Pt&&Ne&&i.some(Ye=>Ye.id===Ne)?Ne:Mt,[b.meshHostDaemonSection,bt.pinned,Pt,Ne,i,Mt]),Jt=MP({status:ee,daemonId:Le||null,meshId:S,sendData:a});l.useEffect(()=>{const Ye=(ne==null?void 0:ne.coordinator)||{};J({override:typeof Ye.systemPromptOverride=="string"?Ye.systemPromptOverride:"",append:typeof Ye.systemPromptAppend=="string"?Ye.systemPromptAppend:typeof Ye.systemPromptSuffix=="string"?Ye.systemPromptSuffix:""}),xe(Object.fromEntries(((ne==null?void 0:ne.nodes)||[]).map(mt=>[mt.id,typeof mt.systemPrompt=="string"?mt.systemPrompt:""])))},[ne]),l.useEffect(()=>{const Ye=b.addNodeDaemonPicker?nr(Me):nr(y);Ee&&E.length===0&&Ye.length>0&&oe(Ye)},[Ee,y,Me,E.length,b.addNodeDaemonPicker]),l.useEffect(()=>{const Ye=new Set(((ne==null?void 0:ne.nodes)||[]).map(mt=>mt.id));he&&!Ye.has(he)&&pe(null)},[ne,he]);const Dt=l.useMemo(()=>{if(!(!(ee!=null&&ee.meshId)||String(ee.meshId)!==String((ne==null?void 0:ne.id)??"")))return Qc(ee.meshHost).hostDaemonId||void 0},[ee,ne]),hn=l.useMemo(()=>FP(i,ze,Le,v,Dt),[i,ze,Le,v,Dt]);l.useEffect(()=>{if(!b.meshHostDaemonSection)return;if(!i.length&&!bt.pinned){ie("");return}const Ye=bt.pinned?nn:hn;Ye&&!on(Ye,z)&&ie(Ye)},[i,z,bt.pinned,nn,hn,b.meshHostDaemonSection]),l.useEffect(()=>{Ne&&(Pt||!i.some(Ye=>Ye.id===Ne))&&Be("")},[Pt,Ne,i]),l.useEffect(()=>{if(b.createDaemonPicker){if(!i.length){K("");return}(!Q||!i.some(Ye=>Ye.id===Q))&&K(i[0].id)}},[i,Q,b.createDaemonPicker]),l.useEffect(()=>{var Ye;if(b.createDaemonPicker){if(!Q){D("");return}if(!P.length){D("");return}P.some(mt=>mt.path===R)||D(((Ye=P[0])==null?void 0:Ye.path)||"")}},[Q,R,P,b.createDaemonPicker]);const Wn=l.useRef(null),Tt=l.useRef(iE()),Vt=b.meshStatePushRefresh?uE:dE,[pn,Oe]=l.useState(Vt);l.useEffect(()=>{if(!S)return;const Ye=Wn.current!==S;Wn.current=S,Ye&&(td(Tt.current),Oe(Vt)),X(null),G(Le,S,!1)},[S,Le]);const rt=l.useRef(G);rt.current=G;const pt=l.useRef(!1),xt=l.useRef(()=>{});xt.current=()=>{pt.current||!S||!Le||(pt.current=!0,Promise.resolve(rt.current(Le,S,!1)).finally(()=>{pt.current=!1}))},l.useEffect(()=>{lE(Tt.current,ee),Oe(cE(Tt.current,Vt))},[ee,Vt]);const yt=l.useRef(null);l.useEffect(()=>{yt.current=null},[S,Le]),xx({daemonIds:l.useMemo(()=>[Le].filter(Boolean),[Le]),meshId:S,sendData:a,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||xt.current()},onRevisionObserved:()=>{yt.current=Date.now()}}),l.useEffect(()=>{if(!S||!Le||typeof document>"u")return;if(b.meshStatePushRefresh){const rn=S,In=setInterval(()=>{if(document.visibilityState!=="visible")return;const jt=yt.current,en=jt===null?1/0:Date.now()-jt;en<hp||(console.warn(`[repo-mesh] mesh_state push backstop firing for mesh ${rn}: no revision push observed in ${Math.round(en/1e3)}s — refreshing via poll fallback`),xt.current())},hp);return()=>clearInterval(In)}let Ye=null;const mt=()=>{document.visibilityState==="visible"&&xt.current()},Zt=()=>{Ye===null&&(Ye=setInterval(mt,pn))},Sn=()=>{Ye!==null&&(clearInterval(Ye),Ye=null)},sn=()=>{document.visibilityState==="visible"?Zt():Sn()};return document.visibilityState==="visible"&&Zt(),document.addEventListener("visibilitychange",sn),()=>{Sn(),document.removeEventListener("visibilitychange",sn)}},[S,Le,pn,b.meshStatePushRefresh]);const kt=l.useMemo(()=>i.map(Ye=>Ye.id).filter(Boolean).sort().join(","),[i]),fn=l.useRef(!1);return l.useEffect(()=>{V(fn.current),fn.current=!0},[kt]),v?ne?n.jsxs(n.Fragment,{children:[r,n.jsx(zL,{selectedMesh:ne,error:O,onDismissError:()=>L(null),onBack:()=>{C(null)},onDelete:ce,displayedMeshStatus:Jt,graphLoading:ue,graphError:je,onRefreshGraph:()=>{td(Tt.current),G(Le,S,!0)},savingPolicy:tt,onUpdatePolicy:Ze,coordinatorPromptDraft:Ct,onCoordinatorPromptDraftChange:J,savingCoordinatorPrompt:re,onSaveCoordinatorPrompt:st,daemons:i,coordinatorDaemonId:z,onCoordinatorDaemonIdChange:ie,coordinatorCliType:He,isHostNodeAttached:Ge,selectedHostNode:mn,hostPinned:bt.pinned,hostLabel:bt.label,hostOnline:Pt,hostRebindDaemonId:Ne,onHostRebindDaemonIdChange:Ye=>Be(Ye),settingMeshHost:Qe,onSetMeshHost:ge,activeDaemon:_e,activeDaemonId:Le,meshQueue:Je,userName:c,availableCliProviders:y,savingNodeSlotsId:Re,onUpdateNodeSlots:et,savingNodeCapabilitiesId:Ue,onUpdateNodeCapabilities:Ve,nodeSystemPromptDrafts:le,onNodeSystemPromptDraftChange:(Ye,mt)=>xe(Zt=>({...Zt,[Ye]:mt})),savingNodeSystemPromptId:Ce,onSaveNodeSystemPrompt:lt,selectedNodeId:he,onSelectNode:pe,showAddNode:Ee,onShowAddNode:()=>Y(!0),onCancelAddNode:()=>Y(!1),nodeWorkspace:me,onNodeWorkspaceChange:fe,nodeProviderPriority:E,onNodeProviderPriorityChange:oe,nodeDaemonId:Ie,onNodeDaemonIdChange:Z,nodeCustomPath:se,onNodeCustomPathChange:ye,nodePickerWorkspaces:$e,nodePickerProviders:Me,nodeOnboardingPlan:De,nodePlanLoading:Te,attachableDaemons:nt,onAddNode:Fe,onRemoveNode:ke,availableCliAgents:_,features:{coordinatorPrompt:b.coordinatorPrompt,meshHostDaemonSection:b.meshHostDaemonSection,hermesMcpConfig:b.hermesMcpConfig,addNodeDaemonPicker:b.addNodeDaemonPicker,nodeInstruction:b.nodeInstruction},sendCommand:o})]}):n.jsxs(n.Fragment,{children:[r,n.jsx(uL,{meshes:w,loading:A,error:O,onDismissError:()=>L(null),daemons:i,features:{createDaemonPicker:b.createDaemonPicker},showCreate:M,onToggleCreate:()=>$(!M),createName:N,onCreateNameChange:I,createRepoIdentity:B,onCreateRepoIdentityChange:T,createRepoRemoteUrl:F,onCreateRepoRemoteUrlChange:q,newMeshDaemonId:Q,onNewMeshDaemonIdChange:K,newMeshWorkspace:R,onNewMeshWorkspaceChange:D,createPickerWorkspaces:P,createOnboardingPlan:H,createPlanLoading:W,creating:U,createWarning:ae,onDismissCreateWarning:()=>be(null),onSelectMesh:C,onCreate:we,onCancelCreate:de,sendCommand:o})]}):n.jsx(Wo,{icon:n.jsx(On,{}),title:"Repo Mesh",subtitle:t("mesh.page.subtitle"),children:n.jsx("div",{className:"text-sm text-text-muted p-4",children:t("mesh.page.waitingForDaemon")})})}function hE(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function pE({children:e}){const{sendCommand:t,sendData:s}=_t(),{ides:r}=An(),o=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),a=l.useMemo(()=>({sendCommand:t,sendData:s,daemons:o,userName:void 0,loadMeshStatus:async(i,c,d)=>t(i,"mesh_status",(d==null?void 0:d.refresh)===!0?{meshId:c,refresh:!0}:{meshId:c}),launchCoordinator:async(i,c)=>{var p;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const u=await t(i,"launch_mesh_coordinator",d),m=(u==null?void 0:u.result)??u;if((m==null?void 0:m.success)===!1)throw new Error(m.error||"Coordinator launch failed");const h=(m==null?void 0:m.sessionId)||((p=m==null?void 0:m.session)==null?void 0:p.id)||(m==null?void 0:m.targetSessionId);return{sessionId:h,message:h?`Coordinator launched (${h})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Fd,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:yx}),[t,s,o]);return n.jsx(vx.Provider,{value:a,children:e})}function fE(e){const{daemons:t,features:s,meshes:r,meshesLoading:o,selectedMeshId:a,onSelectMesh:i,createMode:c,onCreateModeChange:d,createName:u,onCreateNameChange:m,createDaemonId:h,onCreateDaemonIdChange:p,createWorkspace:g,onCreateWorkspaceChange:f,createPickerWorkspaces:x,createPlan:b,createPlanLoading:k,creating:j,createWarning:v,onCreate:_,createRepoRemoteUrl:y,onCreateRepoRemoteUrlChange:w,createRepoIdentity:S,onCreateRepoIdentityChange:C,createManualOpen:A,onCreateManualOpenChange:O,nodes:L,attachableDaemons:M,attachDaemonId:$,onAttachDaemonIdChange:N,attachWorkspace:I,onAttachWorkspaceChange:B,attachPickerWorkspaces:T,attachPlan:F,attachPlanLoading:q,attaching:Q,onAttach:K,renderInstallOnboarding:R,nodeLabel:D,daemonLabel:P}=e,{t:H}=ve("common");if(t.length===0)return n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:H("setupWizard.machines.title")}),n.jsx("p",{className:"mt-1 text-2xs leading-relaxed text-text-muted",children:H("setupWizard.machines.noMachinesDescription")})]}),R?R():n.jsx("p",{className:"text-2xs text-text-muted",children:H("setupWizard.machines.noMachinesFallback")})]});const W=Q||q||(F==null?void 0:F.success)===!1||!I.trim()||s.addNodeDaemonPicker&&!$;return n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:H("setupWizard.machines.title")}),n.jsx("p",{className:"mt-1 text-2xs leading-relaxed text-text-muted",children:H("setupWizard.machines.description")})]}),n.jsxs("div",{className:"flex flex-col gap-2",children:[r.map(U=>{const ae=!c&&a===U.id;return n.jsx("button",{type:"button",onClick:()=>{d(!1),i(U.id)},className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${ae?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:n.jsxs("span",{className:"min-w-0",children:[n.jsx("span",{className:"block truncate text-sm text-text-primary",children:U.name}),n.jsxs("span",{className:"block truncate text-2xs text-text-muted",children:[U.repoIdentity||U.repoRemoteUrl||""," · ",H("setupWizard.machines.nodeCount",{count:(U.nodes||[]).length})]})]})},U.id)}),n.jsx("button",{type:"button",onClick:()=>d(!0),className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${c?"border-accent-primary/60 bg-accent-primary/10":"border-dashed border-border-subtle bg-bg-secondary/40 hover:border-border-default"}`,children:n.jsxs("span",{className:"text-sm text-text-primary",children:["+ ",H("setupWizard.machines.createNew")]})}),o&&r.length===0&&n.jsx("p",{className:"text-2xs text-text-muted",children:H("setupWizard.machines.loadingMeshes")})]}),c&&n.jsx(kx,{variant:"wizard",showDaemonPicker:s.createDaemonPicker,daemons:t,daemonLabel:P,name:u,onNameChange:m,daemonId:h,onDaemonIdChange:p,workspace:g,onWorkspaceChange:f,workspaces:x,plan:b,planLoading:k,repoRemoteUrl:y,onRepoRemoteUrlChange:w,repoIdentity:S,onRepoIdentityChange:C,manualOpen:A,onManualOpenChange:O,creating:j,warning:v,onCreate:_}),!c&&a&&n.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[L.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1.5",children:L.map(U=>n.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-3xs text-text-secondary",children:D(U)},U.id))}),n.jsx("span",{className:"text-2xs font-medium text-text-secondary",children:H("setupWizard.machines.attachTitle")}),s.addNodeDaemonPicker&&(M.length>0?n.jsx("div",{className:"flex flex-wrap gap-1.5",children:M.map(U=>{const ae=$===U.id;return n.jsx("button",{type:"button",onClick:()=>N(U.id),className:`rounded-full border px-2.5 py-1 text-2xs transition-colors ${ae?"border-accent-primary/60 bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-secondary text-text-secondary hover:border-border-default"}`,children:P(U)},U.id)})}):n.jsx("p",{className:"text-2xs text-text-muted",children:H("setupWizard.machines.allMachinesAttached")})),(!s.addNodeDaemonPicker||$)&&n.jsxs(n.Fragment,{children:[n.jsx(Yc,{workspaces:T,value:I,onChange:B}),n.jsx(Sx,{plan:F,loading:q}),n.jsx("div",{className:"flex justify-end",children:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:K,disabled:W,children:H(Q?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function gE(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function bE(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function xE({daemons:e,features:t,sendCommand:s,unwrapResult:r,normalizeMesh:o,loadDaemonMetadata:a,initialMeshId:i,onClose:c,renderInstallOnboarding:d}){var Y,me;const{t:u}=ve("common"),m=((Y=e[0])==null?void 0:Y.id)||"",{meshes:h,loading:p,error:g,setError:f,loadMeshes:x,selectedMeshId:b,setSelectedMeshId:k}=Ix({daemons:e,primaryDaemonId:m,sendCommand:s,unwrapResult:r,normalizeMesh:o,features:{createDaemonPicker:t.createDaemonPicker,addNodeDaemonPicker:t.addNodeDaemonPicker},loadDaemonMetadata:a});l.useEffect(()=>{x()},[x]);const j=l.useRef(h);j.current=h;const v=l.useMemo(()=>h.map(fe=>fe.id).sort().join(","),[h]),_=l.useRef(s);_.current=s;const y=l.useRef(r);y.current=r,l.useEffect(()=>{b||h.length===0||(i&&h.some(fe=>fe.id===i)?k(i):h.length===1&&k(h[0].id))},[h,b,i,k]);const w=l.useMemo(()=>h.find(fe=>fe.id===b)??null,[h,b]),S=l.useMemo(()=>(w==null?void 0:w.nodes)||[],[w]),C=l.useCallback(fe=>Gi(fe,e),[e]),[A,O]=l.useState(!1),[L,M]=l.useState(""),[$,N]=l.useState(""),[I,B]=l.useState(""),[T,F]=l.useState(null),[q,Q]=l.useState(!1),[K,R]=l.useState(!1),[D,P]=l.useState(null),[H,W]=l.useState(""),[U,ae]=l.useState(""),[be,V]=l.useState(!1),we=t.createDaemonPicker&&$||m,ce=l.useMemo(()=>e.find(fe=>fe.id===we),[e,we]),de=(ce==null?void 0:ce.workspaces)||[];l.useEffect(()=>{if(!A||!we||!I.trim()){F(null),Q(!1);return}let fe=!1;const E=setTimeout(()=>{fe||(Q(!0),_.current(we,"plan_mesh_onboarding",{workspace:I.trim(),operation:"auto",meshInventory:j.current}).then(oe=>{if(fe)return;const Ie=y.current(oe);F(Ie),Ie!=null&&Ie.success&&(M(Z=>{var se,ye;return Z||`${String(((se=Ie.discovery)==null?void 0:se.repoIdentity)||((ye=Ie.discovery)==null?void 0:ye.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),ae(Z=>{var se;return Z||((se=Ie.discovery)==null?void 0:se.repoIdentity)||""}),W(Z=>{var se,ye,$e,Me,De,Te;return Z||(($e=(ye=(se=Ie.discovery)==null?void 0:se.origin)==null?void 0:ye.urls)==null?void 0:$e[0])||((Te=(De=(Me=Ie.discovery)==null?void 0:Me.upstream)==null?void 0:De.urls)==null?void 0:Te[0])||""}))}).catch(oe=>{fe||F({success:!1,error:(oe==null?void 0:oe.message)||"Git discovery failed"})}).finally(()=>{fe||Q(!1)}))},300);return()=>{fe=!0,clearTimeout(E)}},[A,we,I,v]);const ne=l.useCallback(async()=>{const fe=we,E=I.trim(),oe=H.trim(),Ie=U.trim();if(!(!fe||!L.trim()||K)&&!(!E&&!oe&&!Ie)){R(!0),P(null),f(null);try{const Z=await Tx({targetDaemonId:fe,name:L,repoRemoteUrl:oe,repoIdentity:Ie,workspace:E,attachWorkspace:!!E,machineId:ce==null?void 0:ce.machineId,providerPriority:nr(Zn((ce==null?void 0:ce.availableProviders)||[])),meshInventory:h,sendCommand:s,unwrapResult:r});if(Z.warning&&P(Z.warning),!Z.meshCreated){f(Z.error||u("setupWizard.machines.createFailed"));return}await x(!0),Z.meshId&&k(Z.meshId),O(!1)}finally{R(!1)}}},[we,L,I,H,U,K,ce,h,s,r,x,k,f,u]),[ee,ue]=l.useState(""),[je,X]=l.useState(""),[G,z]=l.useState(null),[ie,Ne]=l.useState(!1),[Be,Le]=l.useState(!1),Je=l.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const fe=new Set(S.map(E=>String(E.daemon_id||E.daemonId||"")));return e.filter(E=>E.id&&!fe.has(E.id)&&!Np(E))},[t.addNodeDaemonPicker,S,e]),Se=l.useMemo(()=>e.find(fe=>fe.id===ee),[e,ee]),he=t.addNodeDaemonPicker?(Se==null?void 0:Se.workspaces)||[]:((me=e.find(fe=>fe.id===m))==null?void 0:me.workspaces)||[];l.useEffect(()=>{if(A||!b||!je.trim()){z(null);return}const fe=t.addNodeDaemonPicker?ee:C(w);if(!fe)return;let E=!1;return Ne(!0),s(fe,"plan_mesh_onboarding",{workspace:je.trim(),meshId:b,inlineMesh:w,operation:"add_existing"}).then(oe=>{E||z(r(oe))}).catch(oe=>{E||z({success:!1,error:(oe==null?void 0:oe.message)||"Git discovery failed"})}).finally(()=>{E||Ne(!1)}),()=>{E=!0}},[A,b,w,je,ee,t.addNodeDaemonPicker,C,s,r]);const pe=l.useCallback(async()=>{var oe,Ie,Z,se;const fe=C(w);if(!b||Be)return;if(!fe){f(u("mesh.host.noCommandTarget"));return}const E=je.trim();if(E){Le(!0),f(null);try{const ye=t.addNodeDaemonPicker?ee:fe,$e=await s(ye,"plan_mesh_onboarding",{workspace:E,meshId:b,inlineMesh:w,operation:"add_existing"}),Me=r($e);if(z(Me),(Me==null?void 0:Me.success)===!1)throw new Error(`${Me.code||"onboarding_blocked"}: ${Me.error}${Me.action?` ${Me.action}`:""}`);const De={meshId:b,workspace:((oe=Me==null?void 0:Me.discovery)==null?void 0:oe.repoRoot)||E,repoRoot:(Ie=Me==null?void 0:Me.discovery)==null?void 0:Ie.repoRoot,isLocalWorktree:((Z=Me==null?void 0:Me.discovery)==null?void 0:Z.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&ee&&(De.daemonId=ee,De.machineId=Se==null?void 0:Se.machineId),De.providerPriority=nr(Zn(((se=t.addNodeDaemonPicker?Se:e[0])==null?void 0:se.availableProviders)||[]));const Te=await s(fe,"add_mesh_node",De),He=r(Te);if((He==null?void 0:He.success)===!1)throw new Error(He.error||"Add node failed");X(""),z(null),await x(!0)}catch(ye){f((ye==null?void 0:ye.message)||"Add node failed")}finally{Le(!1)}}},[w,b,je,ee,Se,Be,t.addNodeDaemonPicker,C,e,s,r,x,f,u]),Ee=!A&&!!w&&S.length>0;return n.jsxs("div",{className:"mx-auto flex w-full max-w-2xl flex-col gap-4 p-4",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-base font-semibold text-text-primary",children:u("setupWizard.title")}),n.jsx("p",{className:"mt-1.5 text-2xs text-text-muted",children:u("setupWizard.machines.description")})]}),g&&n.jsx("p",{className:"text-2xs text-red-400",children:g}),n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary p-4",children:n.jsx(fE,{daemons:e,features:t,meshes:h,meshesLoading:p,selectedMeshId:b,onSelectMesh:fe=>{k(fe),X(""),ue("")},createMode:A,onCreateModeChange:O,createName:L,onCreateNameChange:M,createDaemonId:$,onCreateDaemonIdChange:N,createWorkspace:I,onCreateWorkspaceChange:B,createPickerWorkspaces:de,createPlan:T,createPlanLoading:q,creating:K,createWarning:D,onCreate:ne,createRepoRemoteUrl:H,onCreateRepoRemoteUrlChange:W,createRepoIdentity:U,onCreateRepoIdentityChange:ae,createManualOpen:be,onCreateManualOpenChange:V,nodes:S,attachableDaemons:Je,attachDaemonId:ee,onAttachDaemonIdChange:fe=>{ue(fe),X("")},attachWorkspace:je,onAttachWorkspaceChange:X,attachPickerWorkspaces:he,attachPlan:G,attachPlanLoading:ie,attaching:Be,onAttach:pe,renderInstallOnboarding:d,nodeLabel:bE,daemonLabel:gE})}),n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("div",{className:"ml-auto flex items-center gap-2",children:n.jsx("button",{type:"button",className:Ee?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:c,children:u(Ee?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function Yi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function yE(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),s=Yi();return s&&!t.searchParams.has("token")&&t.searchParams.set("token",s),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function zn(e,t){return await fetch(yE(e),{credentials:"same-origin",...t})}function Rx(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class vE{constructor(){qe(this,"adapters",new Map);qe(this,"states",new Map);qe(this,"runtimeListeners",new Map);qe(this,"screenshotCallbacks",new Map);qe(this,"statusCallbacks",new Set);qe(this,"stateChangeCallbacks",new Set);qe(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const s of this.adapters.keys())if(s.startsWith("standalone"))return s}return null}register(t,s){this.adapters.set(t,s),this.states.set(t,s.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,s){this.states.set(t,s);const r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(o=>o(r,s))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const s=this.resolveDaemonId(t);return s?this.adapters.get(s):void 0}getState(t){const s=this.resolveDaemonId(t);return s&&this.states.get(s)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,s){return!1}sendPtyInput(t,s,r){return this.ptyInputSender?this.ptyInputSender(t,s,r):!1}onScreenshot(t,s){return this.screenshotCallbacks.set(t,s),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,s){this.screenshotCallbacks.forEach(r=>r(t,s))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,s){this.statusCallbacks.forEach(r=>r(t,s))}emitRuntimeSnapshot(t,s,r=0,o=!1,a,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:s,truncated:o,cols:a,rows:i})}emitSessionOutput(t,s,r){!t||typeof s!="string"||!s||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:s})}onRuntimeEvent(t,s){const r=this.runtimeListeners.get(t)||new Set;return r.add(s),this.runtimeListeners.set(t,r),()=>{const o=this.runtimeListeners.get(t);o&&(o.delete(s),o.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,s,r){if(!s)return{success:!1,error:"sessionId is required"};const o=new URL(`/api/v1/runtime/${encodeURIComponent(s)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&o.searchParams.set("sinceSeq",String(r.sinceSeq));const a=await zn(`${o.pathname}${o.search}`);if(!a.ok){let c=`Runtime snapshot unavailable (${a.status})`;try{const d=await a.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await a.json();return this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,s){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(o=>o(s))}}const qn=new vE;function wE(e,t,s,r){if(!e||typeof e!="object"||e.type!=="status_event")return!1;const o=e.payload;if(!o||typeof o!="object"||typeof o.event!="string")return!0;const a=t||"standalone",i=o.targetSessionId;return r&&typeof i=="string"&&i&&r(a,i,o.event),s.handleRawEvent({...o,daemonId:a},"ws"),!0}const SE="/ws/seqscribe",kE="standalone_dashboard",pp=3e3,jE=3e4,NE=3e4,fp=3e3,CE=6e4;function _E(e){const t=e==null?void 0:e.VITE_ADHDEV_TRANSCRIPT_WORKER;return!(typeof t=="string"&&t.trim().toLowerCase()==="off")}function AE(e,t){const r=`${e.protocol==="https:"?"wss":"ws"}://${e.host}${SE}`;return t?`${r}?token=${encodeURIComponent(t)}`:r}function TE(e){if(!e||typeof e!="object")return!1;const t=e;return t.type==="subscribe"||t.type==="unsubscribe"?!0:t.type==="command"&&t.commandType==="report_transcript_transport"}class IE{constructor(t){qe(this,"socket",null);qe(this,"host",null);qe(this,"openedAt",null);qe(this,"reconnectTimer",null);qe(this,"reconnectDelay",pp);qe(this,"unsubscribeInterest",null);qe(this,"sessionDaemons",new Map);qe(this,"activeSessions",[]);qe(this,"delivered",new Set);qe(this,"subRetryTimer",null);qe(this,"subRetryDelay",fp);qe(this,"started",!1);qe(this,"stopped",!1);this.deps=t}start(){this.started||this.stopped||(this.started=!0,this.unsubscribeInterest=this.deps.subscribeInterest(()=>this.syncInterest()),this.syncInterest(),this.connect())}stop(){var s;if(this.stopped)return;this.stopped=!0,(s=this.unsubscribeInterest)==null||s.call(this),this.unsubscribeInterest=null,this.reconnectTimer!==null&&this.deps.clearTimer(this.reconnectTimer),this.reconnectTimer=null;const t=this.socket;this.socket=null,this.stopHost(!1);try{t==null||t.close()}catch{}}isHostRunning(){return this.host!==null}currentReconnectDelay(){return this.reconnectDelay}connect(){var s,r;if(this.stopped)return;let t;try{t=this.deps.createSocket()}catch(o){(r=(s=this.deps).log)==null||r.call(s,`[Transcript] standalone lane socket failed: ${o instanceof Error?o.message:String(o)}`),this.scheduleReconnect();return}this.socket=t,t.addEventListener("open",()=>this.handleOpen(t)),t.addEventListener("close",()=>this.handleClose(t))}handleOpen(t){var r,o;if(this.stopped||t!==this.socket)return;this.openedAt=this.deps.now(),this.stopHost(!1);const s=this.deps.startHost(t,a=>this.deliver(a));if(!s){(o=(r=this.deps).log)==null||o.call(r,"[Transcript] standalone lane: transcript worker unavailable — staying on legacy chat-tail"),this.stopped=!0,this.socket=null;try{t.close()}catch{}return}this.host=s,this.activeSessions.length>0&&s.activateSessions(this.activeSessions),this.armSubRetry(!0)}handleClose(t){if(t!==this.socket)return;this.socket=null;const s=this.openedAt===null?0:this.deps.now()-this.openedAt;this.openedAt=null,s>=NE&&(this.reconnectDelay=pp),this.stopHost(!0),this.scheduleReconnect()}scheduleReconnect(){if(this.stopped||this.reconnectTimer!==null)return;const t=this.reconnectDelay;this.reconnectDelay=Math.min(Math.round(this.reconnectDelay*1.5),jE),this.reconnectTimer=this.deps.setTimer(()=>{this.reconnectTimer=null,this.connect()},t,"reconnect")}stopHost(t){const s=this.host;if(s&&(this.host=null,this.delivered.clear(),this.subRetryTimer!==null&&this.deps.clearTimer(this.subRetryTimer),this.subRetryTimer=null,s.stop(),!!t))for(const[r,o]of this.sessionDaemons)for(const a of o)console.warn(`[Transcript] standalone replica fallback — session=${r} reason=no_node`),this.deps.reportFallback(a,r,"no_node")}syncInterest(){var r;const t=new Map;for(const[o,a]of this.deps.collectInterest())for(const i of a){const c=t.get(i);c?c.includes(o)||c.push(o):t.set(i,[o])}this.sessionDaemons=t;const s=[...t.keys()].sort();if(!(s.length===this.activeSessions.length&&s.every((o,a)=>o===this.activeSessions[a]))){this.activeSessions=s;for(const o of[...this.delivered])t.has(o)||this.delivered.delete(o);(r=this.host)==null||r.activateSessions(s),this.armSubRetry(!0)}}armSubRetry(t){if(t&&(this.subRetryDelay=fp),!this.host||this.subRetryTimer!==null||!this.activeSessions.some(r=>!this.delivered.has(r)))return;const s=this.subRetryDelay;this.subRetryTimer=this.deps.setTimer(()=>{this.subRetryTimer=null,this.rearmUndelivered()},s,"sub-retry")}rearmUndelivered(){const t=this.host;!t||this.stopped||this.activeSessions.filter(r=>!this.delivered.has(r)).length===0||(t.activateSessions(this.activeSessions.filter(r=>this.delivered.has(r))),t.activateSessions(this.activeSessions),this.subRetryDelay=Math.min(this.subRetryDelay*2,CE),this.armSubRetry(!1))}deliver(t){const s=this.sessionDaemons.get(t.sessionId);if(s){this.delivered.add(t.sessionId);for(const r of s)this.deps.applySnapshot(r,t.sessionId,t.snapshot,{omittedBefore:t.omittedBefore})}}}function Ql(e){return{kind:"transcript-bridge-control",event:e}}function ME(e){return typeof e=="object"&&e!==null&&e.kind==="transcript-bridge-snapshot"}function RE(e,t){return{kind:"transcript-session-activation",sessionIds:[...e],...t?{ownerWriterId:t}:{}}}var PE=Object.create,Px=Object.defineProperty,LE=Object.getOwnPropertyDescriptor,Lx=Object.getOwnPropertyNames,EE=Object.getPrototypeOf,DE=Object.prototype.hasOwnProperty,OE=(e,t)=>function(){return t||(0,e[Lx(e)[0]])((t={exports:{}}).exports,t),t.exports},$E=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Lx(t))!DE.call(e,o)&&o!==s&&Px(e,o,{get:()=>t[o],enumerable:!(r=LE(t,o))||r.enumerable});return e},FE=(e,t,s)=>(s=e!=null?PE(EE(e)):{},$E(Px(s,"default",{value:e,enumerable:!0}),e)),HE=OE({"../../node_modules/canonicalize/lib/canonicalize.js"(e,t){t.exports=function s(r){if(typeof r=="number"&&isNaN(r))throw new Error("NaN is not allowed");if(typeof r=="number"&&!isFinite(r))throw new Error("Infinity is not allowed");return r===null||typeof r!="object"?JSON.stringify(r):r.toJSON instanceof Function?s(r.toJSON()):Array.isArray(r)?`[${r.reduce((i,c,d)=>`${i}${d===0?"":","}${s(c===void 0||typeof c=="symbol"?null:c)}`,"")}]`:`{${Object.keys(r).sort().reduce((a,i)=>{if(r[i]===void 0||typeof r[i]=="symbol")return a;const c=a.length===0?"":",";return`${a}${c}${s(i)}:${s(r[i])}`},"")}}`}}});function un(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var Ex=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress","monitor:long_generating"];un(Ex);var BE=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];un(BE);var WE=["p2p_offer","p2p_ice"];un(WE);var UE=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];un(UE);var KE=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","beacon_vectors","daemon_mesh_command","p2p_offer","p2p_ice"];un(KE);var qE=["auth_ok","auth_error","machine_evicted","force_disconnect","token_revoked","version_mismatch","force_update_required","command","agent_command","resolve_action","beacon_vectors_result","daemon_mesh_result","p2p_ready","p2p_offer","p2p_answer","p2p_ice","mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];un(qE);var zE=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],GE=[...Ex,...zE];un(GE);var VE=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];un(VE);var YE=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];un(YE);var QE=["p2p_ready","p2p_answer","p2p_ice"];un(QE);var JE=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];un(JE);var XE=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];un(XE);var Dx=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];un(Dx);var Ox=["ping","pong","p2p_evicted","status_report","status_event","topic_update","topic_update_chunk","session_output","session_output_chunk","session_io_error","command_result","command_result_chunk","response"];un(Ox);[...new Set([...Dx,...Ox])];var $x=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"];new Set($x);var ZE=["pending","assigned","completed","failed","cancelled"],eD=["completed","failed","cancelled"],tD=["code_change","validation","live_debug_readonly","launch_app","convergence"],nD=["low","normal","high"],sD=["low","medium","high"],rD=["when_idle","interrupt"],oD=["preserve","stop","delete_stopped","stop_and_delete"],Fx=["completed","blocked","failed"],Hx=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function ds(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}ds(ZE);ds(eD);ds(tD);ds(nD);ds(sD);ds(rD);ds(oD);ds(Fx);ds(Hx);var aD=["not_ready","send_in_flight","not_generating","not_supported","platform_unsupported","modal_parked","interrupt_not_implemented","interrupt_refused","idle_timeout","session_exited","unsupported_input","no_target","bootstrap_pending","duplicate_dispatch","internal_error"],iD=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(iD);var lD=["fsm_edge","short_gen_inline","completion_flush_genuine","completion_flush_weak","monitor_final_summary","pre_cleanup_transcript","stall_transcript","startup_grace_collapse","acp_prompt_response","cdp_state","approval_gate","modal_button","mesh_stall_watchdog","status_monitor","pty_exit","provider_error","coordinator_probe","mcp_probe","worker_tool","dispatch","input_service","operator","intentional_cleanup","scheduler","git_probe","session_registry"],cD=["mesh_queue","mesh_direct","plain"],dD=["delivered","queued"],uD=["local","p2p"],mD=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],hD=["default","native_source"],pD=["restart","live_holder"],fD=["approval","choice"],gD=["approved","rejected","answered"],bD=["modal_button","auto_approve","prompt_answer"],xD=["genuine","weak"],yD=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],vD=["completed","aborted"],wD=["alive","unknown","read_failed","dead"],SD=["auth_failed","billing_failed"],kD=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],jD=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],ND=["completed","failed"],CD=["operator_update","refine_terminal","validation_terminal"],_D=["delivered","queued","duplicate"],AD=[...$x,"unknown"],Bx=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],TD=["completed","failed","cancelled"],ID=["genuine","weak","tool_report","operator"],MD=["turn_end","weak_end_confirmed","transcript_final","worker_reported","finalization_timeout_no_response","session_error","provider_auth_failed","provider_billing_failed","operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded","operator_update","refine_terminal","validation_terminal","hard_ceiling","reclaim_budget_exhausted","hollow_max_retries","migration_orphan","dispatch_refused_session_exited","dispatch_refused_no_target","dispatch_refused_unsupported_input","dispatch_failed","session_exit","session_exit_before_turn","session_dead","hollow_completion","assigned_stranded_dispatch_unconfirmed","delivered_not_consumed_redrive","delivered_no_turn_deadline"],Wx=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],gr={t:"id"},br={t:"id",optional:!0},gs={t:"bool"},ka={t:"bool",optional:!0},gp={t:"ms"},RD={t:"ms",optional:!0},ja={t:"int",optional:!0},Ht=e=>({t:"enum",values:e}),io=e=>({t:"enum",values:e,optional:!0}),PD={dispatch_accepted:{scope:Ht(cD),messageId:gr,meshId:br,nodeId:br,providerType:br,attemptNo:ja,dispatchNonce:ja,consumeProfile:io(hD),maxTaskRetries:ja,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:gr,outcome:Ht(dD),via:Ht(uD)},delivery_refused:{messageId:gr,reason:Ht(aD)},dispatch_failed:{workerAbsent:gs,reason:Ht(mD),refusalCode:br},duplicate_dispatch_refusal:{holderSessionId:gr,holderAttemptId:br},session_rebound:{toSessionId:gr,reason:Ht(pD)},turn_started:{retro:gs},suspension:{modal:Ht(fD),modalKey:br},suspension_resolved:{resolution:Ht(gD),via:Ht(bD)},turn_end:{strength:Ht(xD),afterFinalizationTimeout:ka,hollow:ka,summary:{t:"summary_ref",optional:!0},blockReason:io(yD),releasedByHardCap:ka,nativeOutcome:io(vD),live:{t:"live",optional:!0},reportExpected:ka},transcript_final:{selfAttributing:gs,nativeRead:gs,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:RD},transcript_activity:{newestActivityAt:gp},no_progress:{stalledMs:gp,observedStatus:Ht(AD),finalAssistantPresent:gs},liveness:{result:Ht(wD)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:io(SD)},session_error:{reason:Ht(kD)},worker_report:{outcome:Ht(Fx),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:gs,branchState:io(Hx),touchedFileCount:ja},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:gs,commitsSinceDispatch:{t:"int"},attributable:gs},cancel:{reason:Ht(jD)},operator_status:{status:Ht(ND),reason:Ht(CD)},coordinator_ack:{notify:Ht(Wx),outcome:Ht(_D)},hold_expired:{holdId:gr,reason:Ht(Bx)}},LD=Object.keys(PD);function Ms(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Ms(lD);Ms(LD);Ms(MD);Ms(Wx);Ms(Bx);Ms(TD);Ms(ID);var ED=["turn.evidence","turn.committed","turn.notify","mesh.record"];Ms(ED);var DD=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];function Bn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Bn(DD);var OD=["applied","recorded","rejected"];Bn(OD);var $D=["taskId","deliveryId","attemptId","missionId","checkpointId","promptId","providerSessionId","targetNoteId","nodeId","sessionId","providerType","transport","attemptedSessionId","holderSessionId","reason","status","outcome","terminalKind","event","source","intentionalStopReason","retryable","rebound","forced","fallback","membershipRemoved","requestedForce","removedByRemoteDaemon","completedViaReady","intentional","weak","attempt","attemptCount","count"];new Set($D);var FD=["completed","failed"];Bn(FD);var HD=["operator_update","refine_terminal","validation_terminal"];Bn(HD);var BD=["own","fleet"];Bn(BD);var WD=["active","paused","completed","abandoned"];Bn(WD);var UD=["magi","coordinator"];Bn(UD);var KD=["provider_quirk","pattern_to_avoid","recovery_lesson"];Bn(KD);var qD=["coordinator","unknown"];Bn(qD);var zD=["gate_claimed","gate_released","gate_abandoned","node_patched"];Bn(zD);var GD=["turn_observe","mesh_record","turn_cancel","operator_status","turn_query","mesh_index_query","mission_upsert","mission_query","note_upsert","note_forget","tool_call_record","ledger_query","mission_list_query","record_local","queue_query","queue_enqueue","queue_enqueue_graph","queue_cancel","queue_requeue","direct_dispatch_record","graph_audit_record","active_work_query","recovery_context_query","graph_gate_claim","graph_gate_release","graph_gate_abandon","graph_node_patch","graph_view_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];Bn(GD);var VD=FE(HE());VD.default;new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;var YD="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";new Map([...YD].map((e,t)=>[e,t]));new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;new globalThis.TextDecoder;new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1});/*! Bundled license information:
|
|
110
|
+
|
|
111
|
+
@noble/hashes/esm/utils.js:
|
|
112
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
113
|
+
*/const QD=4096;function JD(e){return typeof e.isOpen=="function"?e.isOpen():e.readyState===1||e.readyState==="open"}function XD(e,t,s={}){const r=s.preOpenQueueCap??QD,o=[];let a=!1;const i=()=>{for(const d of o.splice(0))e.send(d)},c=()=>{var d;o.length=0,a=!0,t.onmessage=null,(d=s.onOverflow)==null||d.call(s,"pre_open_queue_full"),t.postMessage(Ql("queue_overflow"))};return t.onmessage=d=>{if(a)return;const u=d.data;typeof u=="string"&&(JD(e)?(o.length>0&&i(),e.send(u)):o.length<r?o.push(u):c())},e.addEventListener("message",d=>{if(a)return;const u=d.data;typeof u=="string"&&t.postMessage(u)}),e.addEventListener("open",()=>{a||(i(),t.postMessage(Ql("transport_open")))}),e.addEventListener("close",()=>{a||(a=!0,o.length=0,t.postMessage(Ql("transport_closed")))}),{pendingCount(){return o.length},close(){a||(a=!0,o.length=0,t.onmessage=null)}}}function ZD(e,t){var d,u,m,h;const s=t.createChannel??(()=>new MessageChannel),r=s(),o=s(),a=t.createWorker();a.postMessage({sessionKey:t.sessionKey,writerId:t.writerId},[r.port2,o.port2]),(u=(d=r.port1).start)==null||u.call(d),(h=(m=o.port1).start)==null||h.call(m),o.port1.onmessage=p=>{var g;ME(p.data)&&((g=t.onSnapshot)==null||g.call(t,p.data))};let i=XD(e,r.port1,{...t.preOpenQueueCap!==void 0?{preOpenQueueCap:t.preOpenQueueCap}:{},onOverflow:()=>{var p;return(p=t.onOverflow)==null?void 0:p.call(t)}}),c=!1;return{pendingCount:()=>(i==null?void 0:i.pendingCount())??0,running:()=>!c,activateSessions(p,g){c||o.port1.postMessage(RE(p,g))},stop(){var p;if(!c){c=!0,i==null||i.close(),i=null,o.port1.onmessage=null;for(const g of[r.port1,o.port1])try{(p=g.close)==null||p.call(g)}catch{}a.terminate()}}}}new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;const e5="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";new Map([...e5].map((e,t)=>[e,t]));new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;new globalThis.TextDecoder;const t5={};function n5(){if(typeof window>"u"||typeof Worker>"u"||typeof WebSocket>"u")return()=>{};if(!_E(t5))return()=>{};const e=AE(window.location,Yi()),t=new IE({createSocket:()=>new WebSocket(e),startHost:(s,r)=>ZD(s,{writerId:kE,sessionKey:"transcript",onSnapshot:r,createWorker:()=>new Worker(new URL("/assets/transcript-worker-entry-Dazh6WtK.js",import.meta.url),{type:"module"}),onOverflow:()=>console.warn("[Transcript] standalone lane pre-open queue overflow — channel reset")}),collectInterest:YC,subscribeInterest:QC,applySnapshot:zC,reportFallback:VC,setTimer:(s,r)=>setTimeout(s,r),clearTimer:s=>clearTimeout(s),now:()=>Date.now(),log:s=>console.warn(s)});return t.start(),()=>t.stop()}function s5(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,s=Yi();return s?`${t}?token=${encodeURIComponent(s)}`:t}const Na=s5(),bp=3e3,r5=3e4;let Ln=null,o5=0;const pi=new Map;let $s=null,No=null,xp=null;function yp(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function lo(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function a5(e){return e==="connected"?"connected":e}async function Co(e,t,s){const r=hb(e,s||{}),o=Ln;if(o&&o.readyState===WebSocket.OPEN){const a=`req_${++o5}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{pi.delete(a),c(new Error(`WS command timeout: ${t}`))},3e4);pi.set(a,{resolve:u=>{clearTimeout(d),i(u)},reject:u=>{clearTimeout(d),c(u)}}),o.send(JSON.stringify({type:"command",requestId:a,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function nd(e,t){const s=Ln;if(!s||s.readyState!==WebSocket.OPEN||!TE(t))return!1;try{return s.send(JSON.stringify(t)),!0}catch{return!1}}function Ux(e,t,s){const r=Ln;if(!r||r.readyState!==WebSocket.OPEN)return!1;const o=hb(e,{sessionId:t,targetSessionId:t,data:s});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:o.payload}})),!0}catch{return!1}}qn.registerPtyInputSender(Ux);class i5{constructor(t){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Ln==null?void 0:Ln.readyState)===WebSocket.OPEN}get connectionState(){return(Ln==null?void 0:Ln.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,s){return Co(this.daemonId,t,s)}async sendInput(t,s){return Co(this.daemonId,"cdp_remote_action",{action:t,params:s,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,$s&&(clearInterval($s),$s=null);const s=async()=>{if(this.hasCommandChannel)try{const r=await Co(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(r!=null&&r.success&&(r!=null&&r.base64)){const o=await fetch(`data:image/jpeg;base64,${r.base64}`).then(a=>a.blob());qn.emitScreenshot(this.daemonId,o)}}catch{}};s(),$s=setInterval(s,2e3)}stopScreenshots(t){$s&&(clearInterval($s),$s=null)}}let Nn=null;function l5(e){return(!Nn||Nn.daemonId!==e)&&(Nn=new i5(e)),Nn}function c5({children:e}){const t=l.useRef(Ar()),s=Ar();t.current=s;const{setUserName:r}=tw(),o=l.useRef(r);o.current=r;const a=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((x,b)=>{c(x),No==null||No(x,b)},[]),u=l.useRef(null),m=l.useRef(),h=l.useRef(bp),p=l.useRef(!0),g=l.useRef(!1),f=l.useRef("initial_connect");return l.useEffect(()=>{p.current=!0,g.current=!1;function x(){var v,_;if(!p.current||((v=u.current)==null?void 0:v.readyState)===WebSocket.OPEN||((_=u.current)==null?void 0:_.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Na}...`),lo("connect_attempt",{url:Na,reason:f.current,delayMs:h.current});let j;try{j=new WebSocket(Na)}catch(y){console.error("[Standalone WS] Failed to create WebSocket:",y),b();return}u.current=j,j.onopen=()=>{if(!p.current){j.close();return}d("connected"),h.current=bp,lo("open",{url:Na,reason:f.current}),_n.resubscribeAll({sendData:nd}),console.log("[Standalone WS] Connected")},Ln=j,j.onmessage=y=>{var w,S;try{const C=JSON.parse(y.data);if((C.type==="command_result"||C.type==="error")&&C.requestId){const A=pi.get(C.requestId);A&&(pi.delete(C.requestId),C.type==="error"?A.reject(new Error(((w=C.data)==null?void 0:w.message)||"Command failed")):A.resolve(C.data));return}if(C.type==="session_output"){const A=C.sessionId||C.cliId||C.cliType;A&&qn.emitSessionOutput(A,typeof C.data=="string"?C.data:"",typeof C.seq=="number"?C.seq:void 0);return}if(C.type==="runtime_snapshot"){qn.emitRuntimeSnapshot(C.sessionId,typeof C.text=="string"?C.text:"",typeof C.seq=="number"?C.seq:0,!!C.truncated,typeof C.cols=="number"?C.cols:void 0,typeof C.rows=="number"?C.rows:void 0);return}if(wE(C,xp,ct,GC))return;if(C.type==="topic_update"){const A=C.update;A&&_n.publish(A);return}if(C.type==="status"||C.type==="initial_state"){const A=C.data;if(!A)return;const{injectEntries:O,markLoaded:L,getIdes:M}=t.current,$=A.instanceId||"standalone";xp=$;const N=M().find(T=>T.id===$),I=l5($);qn.register($,I),qn.setState($,"connected"),d("connected",$),qn.emitStatus($,A);const B=Va(A,{daemonId:$,existingDaemon:N,existingEntries:M()});yp("ws_status",{type:C.type,daemonId:$,sessions:(A.sessions||[]).map(T=>({id:T.id,parentId:T.parentId,providerType:T.providerType,kind:T.kind,transport:T.transport,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,title:T.title})),recentLaunches:(A.recentLaunches||[]).map(T=>({id:T.id,providerType:T.providerType,kind:T.kind,workspace:T.workspace,lastLaunchedAt:T.lastLaunchedAt}))}),yp("entries",{daemonId:$,entries:B.filter(T=>T.type!=="adhdev-daemon").map(T=>({id:T.id,type:T.type,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,sessionId:T.sessionId}))}),B.length>0&&O(B,{authoritativeDaemonIds:[$]}),L(),i.current!==$&&((S=a.current)==null||S.call(a),i.current=$,a.current=_n.subscribe({sendData:nd},$,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${$}`,params:{includeSessions:!0}},T=>{if(T.topic!=="daemon.metadata")return;const F=t.current.getIdes(),q=F.find(K=>K.id===$),Q=Va(T.status,{daemonId:$,existingDaemon:q,existingEntries:F,timestamp:T.timestamp});Q.length>0&&t.current.injectEntries(Q,{authoritativeDaemonIds:[$]}),T.userName&&o.current&&o.current(T.userName)}))}}catch(C){console.error("[Standalone WS] Parse error:",C)}},j.onclose=y=>{p.current&&(Nn==null||Nn.stopScreenshots(),Nn&&qn.setState(Nn.daemonId,"disconnected"),d("disconnected"),u.current=null,f.current=`close:${y.code}${y.wasClean?":clean":":unclean"}`,lo("close",{code:y.code,reason:y.reason||"",wasClean:y.wasClean}),b())},j.onerror=y=>{g.current||!p.current||(f.current="error",lo("error",{message:y instanceof Event?"event":String(y),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",y))}}function b(){if(!p.current)return;clearTimeout(m.current);const j=h.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),lo("schedule_reconnect",{reason:f.current,delayMs:j}),m.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,r5),x()},j)}x();const k=n5();return()=>{var j;k(),p.current=!1,g.current=!0,(j=a.current)==null||j.call(a),a.current=null,i.current=null,clearTimeout(m.current),u.current&&(u.current.onerror=null,u.current.onclose=null,u.current.close(),u.current=null,Ln=null),Nn&&(Nn.stopScreenshots(),qn.unregister(Nn.daemonId))}},[]),n.jsx(n.Fragment,{children:e})}function d5({children:e}){const[t,s]=l.useState("disconnected"),[r,o]=l.useState(null);l.useEffect(()=>(No=(i,c)=>{s(i),c&&o(c)},()=>{No=null}),[]);const a=l.useMemo(()=>{const i=t==="connected",c=a5(t),d={};return r&&(d[r]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d,usesP2P:!1}},[t,r]);return n.jsx(ew,{connectionOverrides:a,children:n.jsx(c5,{children:e})})}const Kx="adhdev_standalone_font_preferences",Js={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Qi=[{id:"default",label:"Default",labelKey:"standalone.fonts.presets.default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",labelKey:null,family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",labelKey:null,family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",labelKey:null,family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",labelKey:null,family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",labelKey:"standalone.fonts.presets.serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",labelKey:"standalone.fonts.presets.custom",family:"",description:"Enter any CSS font-family stack"}],Ro=[{id:"default",label:"Default mono",labelKey:"standalone.fonts.presets.defaultMono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",labelKey:null,family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",labelKey:null,family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",labelKey:null,family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",labelKey:null,family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",labelKey:"standalone.fonts.presets.custom",family:"",description:"Enter any CSS monospace stack"}],u5=new Set(Qi.map(e=>e.id)),m5=new Set(Ro.map(e=>e.id));function Gn(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Ha("chat",t.chat),code:Ha("code",t.code),terminal:Ha("terminal",t.terminal)}}function Ha(e,t){const s=Js[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},o=typeof r.preset=="string"?r.preset.trim():"",a=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?u5:m5).has(o)?o==="custom"?a?{preset:"custom",customFamily:a}:s:{preset:o}:s}function Ba(e,t){var o;const s=Ha(e,t);if(s.preset==="custom"&&s.customFamily)return s.customFamily;const r=e==="chat"?Qi:Ro;return((o=r.find(a=>a.id===s.preset))==null?void 0:o.family)||r[0].family}function h5(e){const t=Gn(e),s=Ba("chat",t.chat),r=Ba("code",t.code),o=Ba("terminal",t.terminal);return{"--chat-font-family":s,"--chat-code-font-family":r,"--chat-terminal-font-family":o,"--chat-tool-font-family":o}}function Ws(e,t=document.documentElement){const s=Gn(e),r=h5(s);t.setAttribute("data-standalone-fonts","custom");for(const[o,a]of Object.entries(r))t.style.setProperty(o,a);return s}function sd(e){const t=Gn(e);try{localStorage.setItem(Kx,JSON.stringify(t))}catch{}return t}function p5(){try{const e=localStorage.getItem(Kx);if(e)return Gn(JSON.parse(e))}catch{}return Js}function f5(){return Ws(p5())}function co(e,t,s){const r=e==="chat"?Qi:Ro,o=r.find(a=>a.id===t)||r[0];return o.labelKey&&s?s(o.labelKey,o.label):o.label}function g5({children:e}){const t=rr(),s=fi(),{t:r}=ve("common"),o=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:n.jsx(zp,{}),label:r("nav.dashboard"),active:s.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:n.jsx(Tr,{}),label:r("nav.machines"),active:s.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:n.jsx(On,{}),label:r("nav.mesh"),active:s.pathname.startsWith("/mesh")||s.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"notifications",path:"/notifications",icon:n.jsx(js,{}),label:r("nav.notifications"),active:s.pathname.startsWith("/notifications"),onSelect:()=>t("/notifications")},{id:"settings",path:"/settings",icon:n.jsx(Or,{}),label:r("nav.settings"),active:s.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[s.pathname,t,r]),a=l.useMemo(()=>[{id:"docs",label:n.jsxs(n.Fragment,{children:[n.jsx("span",{children:r("nav.docs")}),n.jsx("span",{className:"ml-auto text-4xs text-text-muted",children:"↗"})]}),icon:n.jsx(Gp,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("nav.docs")},{id:"about",label:r("nav.about"),icon:n.jsx(Po,{}),active:s.pathname==="/about",onSelect:()=>t("/about"),title:r("nav.about")}],[s.pathname,t,r]);return n.jsx(ZA,{brand:({collapsed:i})=>n.jsxs(n.Fragment,{children:[n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&n.jsx("span",{children:"ADHDev"})]}),navItems:o,footerItems:a,footerInfo:({collapsed:i})=>i?null:n.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.59"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>n.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:r(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[n.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&n.jsx("span",{className:"text-xs",children:r("standalone.layout.collapse")})]}),children:e})}function b5(){const e=rr(),{sendCommand:t}=_t(),{ides:s}=An(),r=l.useMemo(()=>s.filter(o=>o.daemonMode||o.type==="adhdev-daemon").map(o=>o),[s]);return n.jsx(xE,{daemons:r,features:yx,sendCommand:t,unwrapResult:o=>o,normalizeMesh:o=>o,onClose:()=>e("/mesh")})}const x5=[{icon:n.jsx(Tr,{size:16}),key:"localFirst"},{icon:n.jsx(Jn,{size:16}),key:"chatRelay"},{icon:n.jsx(md,{size:16}),key:"screenshots"},{icon:n.jsx(Xn,{size:16}),key:"remoteControl"},{icon:n.jsx(Ir,{size:16}),key:"multiIde"},{icon:n.jsx(Gp,{size:16}),key:"cliAcp"}],y5=[{icon:n.jsx(yi,{size:16}),key:"anywhere"},{icon:n.jsx(zp,{size:16}),key:"p2pStream"},{icon:n.jsx(js,{size:16}),key:"mobileNotifications"},{icon:n.jsx(uw,{size:16}),key:"restApi"},{icon:n.jsx(hw,{size:16}),key:"enterpriseControls"}],v5=[{key:"chatRelay",selfhost:!0,cloud:!0},{key:"screenshots",selfhost:!0,cloud:!0},{key:"remoteControl",selfhost:!0,cloud:!0},{key:"multiIde",selfhost:!0,cloud:!0},{key:"extensionCli",selfhost:!0,cloud:!0},{key:"anyNetwork",selfhost:!1,cloud:!0},{key:"webrtc",selfhost:!1,cloud:!0},{key:"mobilePush",selfhost:!1,cloud:!0},{key:"restApi",selfhost:!1,cloud:!0},{key:"multiMachineDashboards",selfhost:!1,cloud:!0},{key:"ssoRbacAuditLogs",selfhost:!1,cloud:!0}];function w5(){const{t:e}=ve("common");return n.jsxs(Wo,{icon:n.jsx(Po,{className:"text-text-primary"}),title:e("standalone.about.title"),subtitle:e("standalone.about.subtitle"),widthClassName:"max-w-5xl",actions:n.jsxs("div",{className:"px-3 py-1 text-2xs font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","1.0.59"]}),children:[n.jsx(Nt,{children:n.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[n.jsxs("div",{className:"max-w-2xl",children:[n.jsx("div",{className:"text-2xs font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),n.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),n.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),n.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[n.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),n.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),n.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),n.jsx(Nt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:n.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:x5.map(t=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[n.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[n.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),e("standalone.about.features."+t.key+".title")]}),n.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.features."+t.key+".desc")})]},t.key))})}),n.jsx(Nt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:n.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:$A.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:HA.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:FA.map(t=>`${t.icon} ${t.name}`)}].map(t=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[n.jsx("div",{className:"text-2xs font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),n.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(s=>n.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-xs text-text-secondary",children:s},s))})]},t.label))})}),n.jsx(Nt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:n.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:y5.map(t=>n.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[n.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[n.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),e("standalone.about.extras."+t.key+".title")]}),n.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.extras."+t.key+".desc")})]},t.key))})}),n.jsx(Nt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:n.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:n.jsxs("table",{className:"w-full text-xxs",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"bg-bg-secondary",children:[n.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-2xs uppercase tracking-wider",children:e("standalone.about.featureHeader")}),n.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-2xs uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),n.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-2xs uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),n.jsx("tbody",{children:v5.map((t,s)=>n.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[n.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e("standalone.about.comparison."+t.key)}),n.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?n.jsx("span",{className:"text-emerald-500",children:"✓"}):n.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),n.jsx("td",{className:"px-4 py-2.5 text-center",children:n.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.key))})]})})}),n.jsx(Bi,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:n.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[n.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),n.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[n.jsx(Sw,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Jl(e,t,s){return{...e,[t]:s}}function Xl({surface:e,title:t,description:s,value:r,options:o,onChange:a}){const{t:i}=ve("common");return n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[n.jsxs("div",{className:"flex items-center gap-1 text-sm font-medium text-text-primary",children:[t,n.jsx(dt,{content:s,size:12})]}),n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(sT,{value:r.preset,onChange:c=>{const d=c.target.value;a(d==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:d})},children:o.map(c=>n.jsx("option",{value:c.id,children:c.labelKey?i(c.labelKey,c.label):c.label},c.id))}),r.preset==="custom"&&n.jsx(Dn,{type:"text",className:"font-mono",placeholder:i("standalone.fonts.customFamilyPlaceholder"),value:r.customFamily||"",onChange:c=>a({preset:"custom",customFamily:c.target.value})}),n.jsxs("div",{className:"text-2xs text-text-muted",children:[n.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",n.jsx("span",{className:"font-mono break-all",children:Ba(e,r)})]})]})]})}function S5({value:e,savedValue:t,saving:s=!1,error:r,notice:o,onChange:a,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:u}=ve("common"),m=JSON.stringify(e)!==JSON.stringify(t);return n.jsxs("div",{className:"flex flex-col gap-4",children:[r&&n.jsx(zt,{variant:"error",children:r}),o&&n.jsx(zt,{variant:"success",children:o}),n.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[n.jsx(Xl,{surface:"chat",title:u("standalone.fonts.chat"),description:u("standalone.fonts.chatDescription"),value:e.chat,options:Qi,onChange:h=>a(Jl(e,"chat",h))}),n.jsx(Xl,{surface:"code",title:u("standalone.fonts.code"),description:u("standalone.fonts.codeDescription"),value:e.code,options:Ro,onChange:h=>a(Jl(e,"code",h))}),n.jsx(Xl,{surface:"terminal",title:u("standalone.fonts.terminal"),description:u("standalone.fonts.terminalDescription"),value:e.terminal,options:Ro,onChange:h=>a(Jl(e,"terminal",h))})]}),n.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[n.jsx("div",{className:"flex items-center justify-between gap-3",children:n.jsxs("div",{className:"flex items-center gap-1 text-sm font-medium text-text-primary",children:[u("standalone.fonts.livePreview"),n.jsx(dt,{size:12,content:[u("standalone.fonts.previewSummary",{chat:co("chat",e.chat.preset,u),code:co("code",e.code.preset,u),terminal:co("terminal",e.terminal.preset,u)}),u("standalone.fonts.defaultsSummary",{chat:co("chat",Js.chat.preset,u),code:co("code",Js.code.preset,u)}),u("standalone.fonts.fontOverridesNotice")].join(`
|
|
114
|
+
|
|
115
|
+
`)})]})}),n.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:n.jsxs("div",{className:"chat-container-content",children:[n.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:n.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[n.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[n.jsx("span",{className:"chat-sender",children:"Hermes"}),n.jsx("span",{className:"chat-time",children:u("standalone.fonts.previewNow")})]}),n.jsxs("div",{className:"chat-markdown",children:[n.jsx("p",{children:n.jsx(Wa,{i18nKey:"standalone.fonts.previewProse",ns:"common",components:{strong:n.jsx("strong",{}),code:n.jsx("code",{})}})}),n.jsx("pre",{children:n.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),n.jsxs("div",{className:"chat-msg-tool",children:[n.jsx("span",{className:"tool-icon",children:"▸"}),n.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),n.jsxs("div",{className:"chat-msg-terminal",children:[n.jsx("div",{className:"chat-msg-header",children:u("standalone.fonts.terminal")}),n.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx(os,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:s||!m,children:u(s?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),n.jsx(os,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:s||!m,children:u("standalone.fonts.revertToSaved")}),n.jsx(os,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:s,children:u("standalone.fonts.resetToDefaults")})]})]})}function k5(){const{t:e}=ve("common"),{ides:t}=An(),s=t.find(W=>W.type==="adhdev-daemon"),{sendCommand:r}=_t(),{userName:o}=An(),[a,i]=l.useState(o||""),[c,d]=l.useState(null),[u,m]=l.useState(null),[h,p]=l.useState(Js),[g,f]=l.useState(!1),[x,b]=l.useState(""),[k,j]=l.useState(""),[v,_]=l.useState("127.0.0.1"),[y,w]=l.useState(""),[S,C]=l.useState(""),[A,O]=l.useState(""),[L,M]=l.useState(""),[$,N]=l.useState(""),[I,B]=l.useState(!1),T=async()=>{const U=await(await zn("/auth/session")).json();d(U)},F=async()=>{const U=await(await zn("/api/v1/standalone/preferences")).json();m(U),_(U.standaloneBindHost);const ae=Gn(U.standaloneFontPreferences);p(ae),Ws(ae),sd(ae)};l.useEffect(()=>{o!==void 0&&i(o)},[o]),l.useEffect(()=>{Promise.all([T(),F()]).catch(W=>{M(W instanceof Error?W.message:String(W))})},[]),l.useEffect(()=>{Ws(h)},[h]);const q=W=>{const U=W.target.value.trim();s!=null&&s.id&&U!==o&&r(s.id,"set_user_name",{userName:U}).catch(console.error)},Q=async()=>{b(""),j(""),f(!0);try{const W=Gn(h),U=await zn("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:W})}),ae=await U.json();if(!U.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to save standalone font preferences");const be=Gn(ae.standaloneFontPreferences);m(ae),p(be),Ws(be),sd(be),j(e("standalone.settings.fontsSaved"))}catch(W){b(W instanceof Error?W.message:String(W))}finally{f(!1)}},K=()=>{const W=Gn(u==null?void 0:u.standaloneFontPreferences);b(""),j(""),p(W),Ws(W)},R=()=>{b(""),j(""),p(Js),Ws(Js)},D=async()=>{M(""),N(""),B(!0);try{const W=await zn("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:v})}),U=await W.json();if(!W.ok)throw new Error((U==null?void 0:U.error)||"Failed to save standalone network preference");m(U),_(U.standaloneBindHost),N(U.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(W){M(W instanceof Error?W.message:String(W))}finally{B(!1)}},P=async()=>{if(M(""),N(""),S.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(S!==A){M(e("standalone.settings.passwordMismatch"));return}B(!0);try{const W=await zn("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:S})}),U=await W.json();if(!W.ok)throw new Error((U==null?void 0:U.error)||"Failed to save password");d(U),await F(),w(""),C(""),O(""),N(c!=null&&c.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),Rx()}catch(W){M(W instanceof Error?W.message:String(W))}finally{B(!1)}},H=async()=>{M(""),N(""),B(!0);try{const W=await zn("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),U=await W.json();if(!W.ok)throw new Error((U==null?void 0:U.error)||"Failed to clear password");d(U),await F(),w(""),C(""),O(""),N(e("standalone.settings.passwordDisabled"))}catch(W){M(W instanceof Error?W.message:String(W))}finally{B(!1)}};return n.jsxs(Wo,{icon:n.jsx(Or,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[(c==null?void 0:c.publicHostWarning)&&n.jsx(zt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),n.jsx(Nt,{title:e("standalone.settings.daemonSection"),children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[n.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.versionLabel")}),n.jsxs("span",{className:"font-mono text-xs text-text-primary",children:["v","1.0.59"]})]}),n.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[n.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.statusLabel")}),n.jsx("span",{className:`text-xs font-medium ${s?"text-green-400":"text-yellow-400"}`,children:e(s?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")})]}),n.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[n.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.authLabel")}),n.jsx("span",{className:"text-xs text-text-primary",children:c!=null&&c.hasPasswordAuth?e("standalone.settings.authPassword"):c!=null&&c.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]}),(s==null?void 0:s.id)&&n.jsxs("div",{className:"px-1 pt-1 text-xs text-text-muted","data-testid":"standalone-providers-link",children:[e("standalone.settings.providersIntro")," ",n.jsx(Sp,{to:`/machines/${s.id}`,state:{initialMachineTab:"providers"},className:"text-accent-primary hover:underline",children:e("standalone.settings.providersLink")})]})]})}),n.jsx(Nt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkHint"),children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsx("div",{className:"grid gap-3 md:grid-cols-2",role:"radiogroup","aria-label":e("standalone.settings.networkSection"),children:[{host:"127.0.0.1",label:e("standalone.settings.localhostLabel"),hint:e("standalone.settings.localhostHint")},{host:"0.0.0.0",label:e("standalone.settings.allInterfacesLabel"),hint:e("standalone.settings.allInterfacesHint")}].map(W=>n.jsxs("label",{className:`rounded-xl border px-4 py-3 text-sm flex gap-3 items-center cursor-pointer ${v===W.host?"border-accent-primary/40 bg-accent-primary/5":"border-border-subtle bg-bg-glass"}`,children:[n.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v===W.host,onChange:()=>_(W.host)}),n.jsx("span",{className:"font-medium text-text-primary",children:W.label}),n.jsx(dt,{content:W.hint})]},W.host))}),n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx(os,{type:"button",variant:"primary",size:"sm",onClick:()=>{D()},disabled:I,children:e(I?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),(u==null?void 0:u.standaloneBindHost)&&(u.currentBindHost||(c==null?void 0:c.boundHost))&&u.standaloneBindHost!==(u.currentBindHost||(c==null?void 0:c.boundHost))&&n.jsx(tn,{content:e("standalone.settings.networkRestartHint",{host:u.currentBindHost||(c==null?void 0:c.boundHost)||"127.0.0.1"}),children:n.jsx("span",{className:"inline-flex items-center rounded-full border border-amber-500/25 bg-amber-500/10 px-2 py-0.5 text-3xs font-semibold text-amber-400","data-testid":"standalone-restart-chip",children:e("standalone.settings.restartToApply")})})]})]})}),n.jsx(Nt,{title:e("standalone.settings.securitySection"),children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:c!=null&&c.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),L&&n.jsx(zt,{variant:"error",children:L}),$&&n.jsx(zt,{variant:"success",children:$}),n.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[n.jsx(Dn,{type:"password",placeholder:c!=null&&c.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:y,onChange:W=>w(W.target.value)}),n.jsx(Dn,{type:"password",placeholder:c!=null&&c.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:S,onChange:W=>C(W.target.value)}),n.jsx(Dn,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:A,onChange:W=>O(W.target.value)})]}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsx(os,{type:"button",variant:"primary",size:"sm",onClick:()=>{P()},disabled:I,children:I?e("standalone.settings.saving"):c!=null&&c.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(c==null?void 0:c.hasPasswordAuth)&&n.jsx(os,{type:"button",variant:"danger",size:"sm",onClick:()=>{H()},disabled:I,children:e("standalone.settings.disablePassword")})]})]})}),n.jsx(Nt,{title:e("standalone.settings.appearanceSection"),children:n.jsx(IT,{fontsSlot:n.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[n.jsxs("div",{className:"text-xs text-text-muted mb-2 font-medium flex items-center gap-1",children:[e("standalone.settings.fontsLabel"),n.jsx(dt,{content:e("standalone.settings.fontsDescription"),size:12})]}),n.jsx(S5,{value:h,savedValue:Gn(u==null?void 0:u.standaloneFontPreferences),saving:g,error:x,notice:k,onChange:p,onSave:()=>{Q()},onResetToSaved:K,onResetToDefaults:R})]})})}),n.jsx(Nt,{title:e("standalone.settings.profileSection"),children:n.jsx("div",{className:"flex flex-col gap-3",children:n.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[n.jsx("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:n.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[n.jsx(dw,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel"),n.jsx(dt,{content:e("standalone.settings.displayNameHint")})]})}),n.jsx(Dn,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:a,onChange:W=>i(W.target.value),onBlur:q,onKeyDown:W=>{W.key==="Enter"&&W.currentTarget.blur()}})]})})}),n.jsxs(Nt,{title:e("settings.advancedTitle"),collapsible:!0,defaultOpen:!1,children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1 text-xs font-medium text-text-secondary",children:[e("settings.coordinatorPrompts.sectionTitle"),n.jsx(dt,{content:e("settings.coordinatorPrompts.sectionDescription"),size:12})]}),n.jsx(fT,{daemonId:s==null?void 0:s.id,embedded:!0})]})]})}const j5=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],bo="adhdev_onboarding_done",N5=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],C5={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function _5({onDone:e}){const{t}=ve("common"),[s,r]=l.useState([]),[o,a]=l.useState(new Set(j5)),[i,c]=l.useState(!0),[d,u]=l.useState(null),[m,h]=l.useState(!1),[p,g]=l.useState(null),[f,x]=l.useState("all");l.useEffect(()=>{let w=!1;return fetch("/api/v1/providers/catalog?sort=popular&limit=100").then(async S=>{if(!S.ok)throw new Error(`HTTP ${S.status}`);const C=await S.text();try{return JSON.parse(C)}catch{throw new Error(`unexpected non-JSON response (${S.headers.get("content-type")??"unknown content type"})`)}}).then(S=>{w||r(S.providers??[])}).catch(S=>{w||u(S instanceof Error?S.message:String(S))}).finally(()=>{w||c(!1)}),()=>{w=!0}},[]);const b=s.filter(w=>f==="all"||w.category===f),k=["cli","ide","extension","acp"].map(w=>({category:w,items:b.filter(S=>S.category===w)})).filter(w=>w.items.length>0),j=l.useCallback(w=>{a(S=>{const C=new Set(S);return C.has(w)?C.delete(w):C.add(w),C})},[]),v=l.useCallback(async()=>{if(o.size===0){localStorage.setItem(bo,"1"),e();return}h(!0);const w=[];for(const S of o)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:S})})).json().catch(()=>({}));w.push({type:S,ok:!!A.success,error:A.error})}catch(C){w.push({type:S,ok:!1,error:C instanceof Error?C.message:String(C)})}g(w),h(!1),w.every(S=>S.ok)&&localStorage.setItem(bo,"1")},[o,e]),_=l.useCallback(()=>{localStorage.setItem(bo,"1"),e()},[e]),y=l.useCallback(()=>{p&&p.every(w=>w.ok)?e():m||_()},[p,m,e,_]);return n.jsx(Zg,{open:!0,onClose:y,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:n.jsxs("div",{className:"flex w-full items-center gap-2",children:[n.jsx("div",{className:"text-2xs text-text-muted",children:t(o.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:o.size})}),n.jsxs("div",{className:"ml-auto flex gap-2",children:[n.jsx(os,{variant:"secondary",size:"sm",onClick:_,disabled:m,children:t("standalone.onboarding.skip")}),n.jsx(os,{variant:"primary",size:"sm",onClick:()=>{p?(localStorage.setItem(bo,"1"),e()):v()},disabled:m||!p&&o.size===0,children:m?t("standalone.onboarding.installing"):p?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:o.size})})]})]}),children:n.jsxs("div",{className:"flex flex-col gap-5",children:[n.jsx("div",{className:"text-xs text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&s.length>0&&n.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:N5.map(w=>{const S=w.key==="all"?s.length:s.filter(C=>C.category===w.key).length;return S===0&&w.key!=="all"?null:n.jsxs("button",{onClick:()=>x(w.key),className:`machine-btn text-3xs px-2 py-0.5 ${f===w.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[w.label," ",n.jsxs("span",{className:"opacity-60",children:["(",S,")"]})]},w.key)})}),i&&n.jsx("div",{className:"text-text-muted text-xs py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&n.jsx(zt,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&b.length===0&&n.jsx("div",{className:"text-text-muted text-xs py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&b.length>0&&n.jsx("div",{className:"flex flex-col gap-4",children:k.map(w=>n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:C5[w.category]??w.category}),n.jsx("div",{className:"grid gap-1.5",children:w.items.map(S=>{var L;const C=o.has(S.type),A=p==null?void 0:p.find(M=>M.type===S.type),O=((L=S.manifest)==null?void 0:L.details)??"";return n.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${C?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[n.jsx("input",{type:"checkbox",checked:C,onChange:()=>j(S.type),disabled:m,className:"shrink-0"}),n.jsx(Hi,{type:S.type,label:S.displayName??S.type,size:18,className:"shrink-0"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-xxs font-medium text-text-primary truncate",children:S.displayName}),O&&n.jsx("div",{className:"text-3xs text-text-muted truncate",children:O})]}),A&&n.jsx("span",{className:`text-3xs font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},S.type)})})]},w.category))})]})})}function A5(){try{return localStorage.getItem(bo)==="1"}catch{return!1}}const T5="/dashboard";function I5(e,t){const s=typeof t=="string"?t.trim():"";return{suppressed:e.startsWith(T5),sessionId:s||null}}WA();kT();Pf();f5();const M5=Rw({baseUrl:"",getToken:Yi});function R5({children:e}){const{t}=ve("common"),[s,r]=l.useState(null),[o,a]=l.useState(!0),[i,c]=l.useState(""),[d,u]=l.useState(""),[m,h]=l.useState(!1),p=async()=>{a(!0),u("");try{const x=await(await zn("/auth/session")).json();r(x)}catch(f){u(f instanceof Error?f.message:String(f))}finally{a(!1)}};l.useEffect(()=>{p()},[]),l.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let f=!1;return(async()=>{try{const x=await zn("/api/v1/standalone/preferences");if(!x.ok)return;const b=await x.json();if(f)return;const k=Gn(b.standaloneFontPreferences);Ws(k),sd(k)}catch{}})(),()=>{f=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const g=async f=>{f.preventDefault(),h(!0),u("");try{const x=await zn("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),b=await x.json();if(!x.ok)throw new Error((b==null?void 0:b.error)||"Login failed");r(b),c(""),Rx()}catch(x){u(x instanceof Error?x.message:String(x))}finally{h(!1)}};return o?n.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):s?!s.required||s.authenticated?n.jsx(n.Fragment,{children:e}):n.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:n.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),n.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),s.hasPasswordAuth?n.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[n.jsx(Dn,{type:"password",value:i,onChange:f=>c(f.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),n.jsx(os,{type:"submit",variant:"primary",disabled:m||!i,className:"justify-center",children:t(m?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):n.jsx(zt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&n.jsx(zt,{variant:"error",children:d})]})}):n.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function P5(){const{ides:e,initialLoaded:t}=An(),s=e.filter(r=>r.type==="adhdev-daemon").map(r=>({id:r.id,machineId:r.machineId||r.id,nickname:Of(r)||void 0,hostname:jd(r,{fallbackId:r.id}),status:r.status,providers:(r.availableProviders||[]).map(o=>({type:o.type,displayName:o.displayName,icon:o.icon,category:o.category}))}));return n.jsx(kP,{machines:s,initialLoaded:t??!0})}function vp(){const{t:e}=ve("common"),{ides:t,initialLoaded:s}=An();if(!s)return n.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(o=>o.daemonMode||o.type==="adhdev-daemon");return r?n.jsx(tc,{to:`/machines/${r.id}`,replace:!0}):n.jsx(tc,{to:"/dashboard",replace:!0})}function L5(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let s=!1;if(!A5())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{s||(r.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{s=!0}},[]),e?n.jsx(_5,{onDone:()=>t(!1)}):null}function E5(){const{t:e}=ve("common"),t=fi(),[s]=wp(),{suppressed:r,sessionId:o}=I5(t.pathname,s.get("activeTab")),{promptSession:a,hasActivePrompt:i,responseError:c,isSubmitting:d,submit:u,cancel:m,reopen:h}=_i(o);return r||!i?null:n.jsxs("div",{className:"relative",children:[!a&&n.jsx("button",{type:"button",onClick:h,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),n.jsx(wd,{promptSession:a,isSubmitting:d,error:c,onSubmit:u,onCancel:m})]})}function D5(){const e=l.useMemo(()=>({sendCommand:Co,sendData:nd,sendPtyInput:Ux}),[]);return n.jsx(ny,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:n.jsx(rw,{client:M5,children:n.jsx(R5,{children:n.jsx(d5,{children:n.jsx(aw,{value:e,children:n.jsxs(Mw,{sendDaemonCommand:Co,children:[n.jsx(E5,{}),n.jsxs(g5,{children:[n.jsx(L5,{}),n.jsxs(sy,{children:[n.jsx(Kn,{path:"/dashboard",element:n.jsx(QM,{})}),n.jsx(Kn,{path:"/machine",element:n.jsx(vp,{})}),n.jsx(Kn,{path:"/machines/:id",element:n.jsx(bP,{})}),n.jsx(Kn,{path:"/machines",element:n.jsx(vp,{})}),n.jsx(Kn,{path:"/notifications",element:n.jsx(P5,{})}),n.jsx(Kn,{path:"/about",element:n.jsx(w5,{})}),n.jsx(Kn,{path:"/settings",element:n.jsx(k5,{})}),n.jsx(Kn,{path:"/mesh",element:n.jsx(pE,{children:n.jsx(mE,{})})}),n.jsx(Kn,{path:"/setup",element:n.jsx(b5,{})}),n.jsx(Kn,{path:"*",element:n.jsx(tc,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}pN({connectionManager:qn});function O5(){return n.jsx(MT,{fallback:n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",background:"var(--bg-primary)"},children:n.jsx(ln,{})}),children:n.jsx(D5,{})})}ry(document.getElementById("root")).render(n.jsx(rT,{children:n.jsx(O5,{})}));export{a3 as $,ah as A,oo as B,e3 as C,p3 as D,Fr as E,vd as F,iT as G,M0 as H,an as I,es as J,Ka as K,Ax as L,Vi as M,Od as N,mT as O,$r as P,Bt as Q,H5 as R,n3 as S,tn as T,m3 as U,u3 as V,G5 as W,r3 as X,d3 as Y,K5 as Z,l3 as _,Mr as a,ct as a0,i3 as a1,Jp as a2,W5 as a3,c3 as a4,o3 as a5,h3 as a6,Y5 as a7,Vd as a8,zp as a9,pw as aa,On as ab,$d as ac,_t as ad,f3 as ae,MP as af,Do as ag,Pr as ah,Rt as ai,gi as aj,gx as ak,bx as al,IP as am,TP as an,cc as b,U5 as c,X5 as d,Z5 as e,H1 as f,hu as g,B5 as h,Si as i,Q5 as j,ki as k,z5 as l,dt as m,uT as n,q5 as o,nc as p,Lr as q,Vg as r,J5 as s,V5 as t,Uo as u,Wd as v,t3 as w,xb as x,s3 as y,Bd as z};
|