@adhdev/daemon-standalone 1.0.76-rc.4 → 1.0.76-rc.5

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.
@@ -1,122 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-dI1yRint.js","assets/vendor-CgFxQ3Rd.js","assets/terminal-6GBZ9nXN.css","assets/DashboardMeshGraphDialog-BoHsr8ue.js","assets/mesh-graph-7mv6fb91.js","assets/DashboardMeshGraphDialog-B6V-kTJw.css"])))=>i.map(i=>d[i]);
2
- var Vx=Object.defineProperty;var Gx=(e,t,s)=>t in e?Vx(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var ze=(e,t,s)=>Gx(e,typeof t!="symbol"?t+"":t,s);import{r as c,j as n,u as he,i as Ye,M as Yx,b as Qx,d as Jx,e as Xx,t as Zx,f as ey,a as An,h as ty,R as yt,T as La,k as Gs,l as ol,m as al,D as ny,n as hi,o as bp,p as sy,q as ry,L as gp,B as oy,v as ay,w as Pn,N as il,x as iy}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 cy(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 bo=cy();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 ly(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Su(e){return Array.isArray(e)?[...e]:[]}function xp(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 ga(e,t){const s=ly(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:xp(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 yp(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?ga(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 Ze(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function je(...e){for(const t of e){if(typeof t!="string")continue;const s=t.trim();if(s)return s}}function Ot(...e){return je(...e)??""}function dn(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Vt(...e){for(const t of e)if(typeof t=="boolean")return t}function sc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function dy(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 cd(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 uy(e,t){if(!Array.isArray(e))return;const s=e.map(r=>{const o=Ze(r),a=je(o.path),i=je(o.commit),l=je(o.repoPath,o.repo_root)??dy(t,a);if(!a||!i)return null;const d={path:a,commit:i,dirty:Vt(o.dirty)??!1,outOfSync:Vt(o.outOfSync,o.out_of_sync)??!1},u=dn(o.lastCheckedAt,o.last_checked_at);u!==void 0&&(d.lastCheckedAt=u),l&&(d.repoPath=l);const m=je(o.error);return m&&(d.error=m),d}).filter(r=>r!==null);return s.length>0?s:void 0}function my(e){return Vt(e.isGitRepo)!==void 0||!!je(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!je(e.repoRoot,e.repo_root,e.workspace)||dn(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 xa(e,t,s){const r=Vt(e.isGitRepo);if(!Object.keys(e).length||!my(e))return;const o=r??!0,a=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(j=>typeof j=="string"):[],i=dn(e.conflicts)??a.length,l=Vt(e.hasConflicts)??i>0,d=je(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,u=uy(e.submodules,d),m=je(e.upstreamStatus,e.upstream_status),h=dn(e.upstreamFetchedAt,e.upstream_fetched_at),p=je(e.upstreamFetchError,e.upstream_fetch_error),b=je(e.error),f=dn(e.staged)??0,x=dn(e.modified)??0,g=dn(e.untracked)??0,w=dn(e.deleted)??0,S=dn(e.renamed)??0,C=dn(e.lastCheckedAt,e.last_checked_at);return{workspace:je(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:o,branch:je(e.branch)??null,headCommit:je(e.headCommit)??null,headMessage:je(e.headMessage)??null,upstream:je(e.upstream)??null,upstreamStatus:m??"unchecked",...h!==void 0?{upstreamFetchedAt:h}:{},...p?{upstreamFetchError:p}:{},ahead:dn(e.ahead)??0,behind:dn(e.behind)??0,staged:f,modified:x,untracked:g,deleted:w,renamed:S,dirty:Vt(e.dirty,e.isDirty,e.is_dirty)??(f+x+g+w+S>0||l),hasConflicts:l,conflictFiles:a,stashCount:dn(e.stashCount,e.stash_count)??0,...C!==void 0?{lastCheckedAt:C}:{},...u?{submodules:u}:{},...e.daemonBuildBehind&&typeof e.daemonBuildBehind=="object"?{daemonBuildBehind:e.daemonBuildBehind}:{},...b?{error:b}:{}}}function hy(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+=cd(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 py(e,t){const s=Ze(e.lastGit??e.last_git),r=Ze(s.result),o=Ze(s.status),a=Ze(r.status),i=Ze(e.lastProbe??e.last_probe),l=Ze(i.git),d=Ze(l.result),u=Ze(l.status),m=Ze(d.status);let h=null;for(const p of[o,a,u,m]){const b=xa(p,e);if(!b)continue;const f=hy(b);(!h||f>h.score)&&(h={git:b,score:f})}return h==null?void 0:h.git}function fy(e){const t=[je(e.workspace),je(e.providerType,e.provider),je(e.role),je(e.state,e.status),je(e.title),je(e.createdAt,e.created_at),je(e.startedAt,e.started_at)].filter(s=>!!s);if(t.length!==0)return`synthetic:${t.join("|")}`}function Da(e){const t=Ze(e),s=je(t.sessionId,t.session_id,t.id)??fy(t);return s?{sessionId:s,...je(t.providerType,t.provider)?{providerType:je(t.providerType,t.provider)}:{},...je(t.state,t.status)?{state:je(t.state,t.status)}:{},...je(t.chatStatus,t.chat_status)?{chatStatus:je(t.chatStatus,t.chat_status)}:{},...je(t.lifecycle)?{lifecycle:je(t.lifecycle)}:{},...je(t.surfaceKind,t.surface_kind)?{surfaceKind:je(t.surfaceKind,t.surface_kind)}:{},...je(t.recoveryState,t.recovery_state)?{recoveryState:je(t.recoveryState,t.recovery_state)}:{},...je(t.workspace)?{workspace:je(t.workspace)}:{},...je(t.title)?{title:je(t.title)}:{},...je(t.role)?{role:je(t.role)}:{},...Vt(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:Vt(t.isSelfCoordinator,t.is_self_coordinator)}:{},...je(t.statusNote,t.status_note)?{statusNote:je(t.statusNote,t.status_note)}:{},...je(t.createdAt,t.created_at)?{createdAt:je(t.createdAt,t.created_at)}:{},...je(t.startedAt,t.started_at)?{startedAt:je(t.startedAt,t.started_at)}:{},...je(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:je(t.lastActivityAt,t.last_activity_at)}:{},...Vt(t.isCached,t.is_cached)!==void 0?{isCached:Vt(t.isCached,t.is_cached)}:{}}:null}function by(e){const t=e&&typeof e=="object"?e:{};return je(t.id,t.nodeId,t.node_id)}function gy(e,t){if(!t)return!1;const s=t.trim();return s?by(e)===s:!1}var xy=["antigravity-cli","claude-cli","codex-cli","cursor-cli","grok-cli","kimi","opencode"];function cl(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 yy=["daemon_","standalone_"];function vy(e){const t=je(e);return!!t&&/^[0-9a-f]{64}$/i.test(t)}function vp(e){var s,r;return!e||!vy(e.id)?!1:!!!(je(e.machineNickname)||je(e.nickname)||je(e.hostname)||je(e.platform)||je((s=e.machine)==null?void 0:s.hostname)||je((r=e.machine)==null?void 0:r.platform)||je(e.machineId)||Array.isArray(e.sessions)&&e.sessions.length>0)}function ll(e){const t=je(e);if(t){for(const s of yy)if(t.startsWith(s))return t.slice(s.length).trim()||void 0;return t}}function wy(e){const t=ll(e);if(t)return t.startsWith("mach_")?`daemon_${t}`:t}function mn(e,t){const s=ll(e),r=ll(t);return!s||!r?!1:s===r}var wp=["easy","medium","difficult","freeform"];function Sy(e){return typeof e=="string"&&wp.includes(e)}function ky(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(Sy):[],i=Array.isArray(t.capability)?t.capability.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[],l=Number(t.maxParallel),d=Number.isFinite(l)&&l>0?Math.floor(l):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 Sp(e){if(!Array.isArray(e))return[];const t=[];for(const s of e){const r=ky(s);r&&t.push(r)}return t}function jy(e){const t=new Set,s=[];for(const r of Sp(e))t.has(r.provider)||(t.add(r.provider),s.push(r.provider));return s}function nn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var kp=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress"];nn(kp);var Ny=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];nn(Ny);var Cy=["p2p_offer","p2p_ice"];nn(Cy);var _y=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];nn(_y);var Ay=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","daemon_mesh_command","p2p_offer","p2p_ice"];nn(Ay);var Ty=["auth_ok","auth_error","machine_evicted","force_disconnect","token_revoked","version_mismatch","force_update_required","command","agent_command","resolve_action","daemon_mesh_result","p2p_ready","p2p_offer","p2p_answer","p2p_ice","mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];nn(Ty);var Iy=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],My=[...kp,...Iy];nn(My);var Ry=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];nn(Ry);var Py=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];nn(Py);var Ey=["p2p_ready","p2p_answer","p2p_ice"];nn(Ey);var Ly=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];nn(Ly);var Dy=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];nn(Dy);var jp=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];nn(jp);var Np=["ping","pong","p2p_evicted","status_event","topic_update","topic_update_chunk","session_output","session_output_chunk","session_io_error","command_result","command_result_chunk","response","transcript_topics_available"];nn(Np);[...new Set([...jp,...Np])];var Cp=2;function Oy(e,t){const s=typeof t=="number"&&Number.isFinite(t)?t:1;return s===e?"ok":s>e?"reload_required":"daemon_update_required"}var $y="Claude TUI review page is not focused",Fy="Claude TUI answer delivered but not confirmed",ld=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"],_p={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"},Ap={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"},Hy=new Set(ld);function pi(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return Hy.has(t)?t:Ap[t]??null}function dd(e){const t=pi(e);return t?_p[t]:"unknown"}function fi(e){return dd(e)==="working"}function By(e){return dd(e)==="dead"}function Wy(e){const t=dd(e);return t==="working"||t==="blocked"}function ku(e){return ld.filter(t=>_p[t]===e)}var Uy=["pending","assigned","completed","failed","cancelled"],Ky=["completed","failed","cancelled"],qy=["code_change","validation","live_debug_readonly","launch_app","convergence"],zy=["low","normal","high"],Vy=["when_idle","interrupt"],Tp=["completed","blocked","failed"],Gy=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function Nr(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Nr(Uy);var KO=Nr(Ky);Nr(qy);Nr(zy);Nr(Vy);Nr(Tp);var Yy=["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"],Qy=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(Qy);var Jy=["projects","project_status","project_send","project_read","project_add","discover_repos","memory","skill_view","skill_manage","project_note"];new Set(Jy);var Xy=["mesh_queue","mesh_direct","plain"],Zy=["delivered","queued"],ev=["local","p2p"],tv=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],nv=["default","native_source"],sv=["restart","live_holder"],rv=["approval","choice"],ov=["approved","rejected","answered"],av=["modal_button","auto_approve","prompt_answer"],iv=["genuine","weak"],cv=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],lv=["completed","aborted"],dv=["alive","unknown","read_failed","dead"],ju=["auth_failed","billing_failed"],uv=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],mv=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],hv=["completed","failed"],pv=["operator_update","refine_terminal","validation_terminal"],fv=["delivered","queued","duplicate"],bv=[...ld,"unknown"],gv=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],xv=["completed","failed","cancelled"],yv=["genuine","weak","tool_report","operator"],vv=["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"],Ip=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],Ys={t:"id"},Qs={t:"id",optional:!0},as={t:"bool"},Uo={t:"bool",optional:!0},Nu={t:"ms"},wv={t:"ms",optional:!0},Ko={t:"int",optional:!0},Mt=e=>({t:"enum",values:e}),Js=e=>({t:"enum",values:e,optional:!0}),Sv={dispatch_accepted:{scope:Mt(Xy),messageId:Ys,meshId:Qs,nodeId:Qs,providerType:Qs,attemptNo:Ko,dispatchNonce:Ko,consumeProfile:Js(nv),maxTaskRetries:Ko,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:Ys,outcome:Mt(Zy),via:Mt(ev)},delivery_refused:{messageId:Ys,reason:Mt(Yy)},dispatch_failed:{workerAbsent:as,reason:Mt(tv),refusalCode:Qs},duplicate_dispatch_refusal:{holderSessionId:Ys,holderAttemptId:Qs},session_rebound:{toSessionId:Ys,reason:Mt(sv)},turn_started:{retro:as},suspension:{modal:Mt(rv),modalKey:Qs},suspension_resolved:{resolution:Mt(ov),via:Mt(av)},turn_end:{strength:Mt(iv),afterFinalizationTimeout:Uo,hollow:Uo,summary:{t:"summary_ref",optional:!0},blockReason:Js(cv),releasedByHardCap:Uo,nativeOutcome:Js(lv),live:{t:"live",optional:!0},reportExpected:Uo,providerFailure:Js(ju)},transcript_final:{selfAttributing:as,nativeRead:as,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:wv},transcript_activity:{newestActivityAt:Nu},no_progress:{stalledMs:Nu,observedStatus:Mt(bv),finalAssistantPresent:as},liveness:{result:Mt(dv)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:Js(ju)},session_error:{reason:Mt(uv)},worker_report:{outcome:Mt(Tp),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:as,branchState:Js(Gy),touchedFileCount:Ko},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:as,commitsSinceDispatch:{t:"int"},attributable:as},cancel:{reason:Mt(mv)},operator_status:{status:Mt(hv),reason:Mt(pv)},coordinator_ack:{notify:Mt(Ip),outcome:Mt(fv)},hold_expired:{holdId:Ys,reason:Mt(gv)}},kv=Object.keys(Sv);function No(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}No(kv);No(vv);No(Ip);No(xv);No(yv);var jv=["user","remembered","mesh_slot","task_override","provider_default","unspecified"];function ud(e){return typeof e=="string"&&jv.includes(e)}var Nv=["dashboard","mesh","cli","api","restore","assistant"];function Cv(e){return typeof e=="string"&&Nv.includes(e)}function _v(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??Mp(e)}function Mp(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 Av(e){const t=_v(e);if(!e||!t)return;const s=Mp(e);return{value:t,...s&&s!==t?{changedFrom:s}:{},source:ud(e.source)?e.source:"unspecified"}}function dl(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Cu(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=je(m.value),p=dl(m.at),b=m.via==="launch"||m.via==="change_model"||m.via==="observed"?m.via:void 0;h&&p!==void 0&&b&&s.push({at:p,value:h,via:b})}const r=je(t.requested),o=je(t.launchValue),a=je(t.resolvedDefault),i=je(t.current),l=je(t.observed),d=dl(t.observedAt);return{source:ud(t.source)?t.source:"unspecified",...r?{requested:r}:{},...o?{launchValue:o}:{},...a?{resolvedDefault:a}:{},...i?{current:i}:{},...l?{observed:l}:{},...d!==void 0?{observedAt:d}:{},history:s.slice(-20)}}function Tv(e){if(!e||typeof e!="object")return;const t=e,s=je(t.sessionId),r=je(t.providerType),o=dl(t.launchedAt),a=Cu(t.model),i=Cu(t.thinkingLevel);if(!s||!r||o===void 0||!a||!i)return;const l=je(t.providerVersion),d=je(t.workspace),u=je(t.autoApproveModeId);return{sessionId:s,providerType:r,...l?{providerVersion:l}:{},...t.providerChannel==="stable"||t.providerChannel==="preview"?{providerChannel:t.providerChannel}:{},launchedBy:Cv(t.launchedBy)?t.launchedBy:"api",launchedAt:o,...d?{workspace:d}:{},model:a,thinkingLevel:i,...u?{autoApproveModeId:u}:{}}}function es(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var Iv=["applied","recorded","rejected"];es(Iv);var Mv=["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(Mv);var Rv=["completed","failed"];es(Rv);var Pv=["operator_update","refine_terminal","validation_terminal"];es(Pv);var Ev=["own","fleet"];es(Ev);var Lv=["active","paused","completed","abandoned"];es(Lv);var Dv=["provider_quirk","pattern_to_avoid","recovery_lesson"];es(Dv);var Ov=["coordinator","unknown"];es(Ov);var $v=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];es($v);var Fv=["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_batch","queue_cancel","queue_requeue","direct_dispatch_record","active_work_query","recovery_context_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];es(Fv);function xs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Hv(e,t){const[s,r]=Oa(t);if(!r)return e[s];const o=e[s];return xs(o)?o[r]:void 0}function Oa(e){const t=e.indexOf(".");return t<0?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function Bv(e,t){const s={...e};for(const r of Object.keys(t.collections)){const[o,a]=Oa(r);if(!a){delete s[o];continue}const i=s[o];if(!xs(i)||!(a in i))continue;const l={...i};delete l[a],s[o]=l}return s}function Wv(e,t,s){const r=new Map,o=[];for(const d of Array.isArray(e)?e:[])!xs(d)||typeof d[s]!="string"||(r.set(d[s],d),o.push(d[s]));for(const d of t.removed??[])r.delete(d);for(const d of t.upsert??[]){const u=d[s];if(typeof u!="string")continue;const m=r.get(u);r.set(u,m?{...m,...d}:{...d})}for(const[d,u]of Object.entries(t.unsetFields??{})){const m=r.get(d);if(!m)continue;const h={...m};for(const p of u)delete h[p];r.set(d,h)}const a=t.order??o,i=[],l=new Set;for(const d of a){const u=r.get(d);!u||l.has(d)||(i.push(u),l.add(d))}for(const[d,u]of r)l.has(d)||i.push(u);return i}function Uv(e,t,s){var a;const r=new Map;for(const i of Object.keys(s.collections))r.set(i,Hv(e,i));const o=Bv(e,s);for(const i of t.unset??[])delete o[i];Object.assign(o,t.set??{});for(const[i,l]of Object.entries(t.objects??{})){const d=xs(o[i])?{...o[i]}:{};for(const u of l.unset??[])delete d[u];Object.assign(d,l.set??{}),o[i]=d}for(const[i,l]of Object.entries(s.collections)){const d=(a=t.collections)==null?void 0:a[i],u=r.get(i);if(d!=null&&d.absent){const[f,x]=Oa(i);x||delete o[f];continue}if(!d&&u===void 0)continue;const m=d?Wv(u,d,l):u,[h,p]=Oa(i);if(!p){o[h]=m;continue}const b=xs(o[h])?{...o[h]}:{};b[p]=m,o[h]=b}return o}var Kv={collections:{"status.sessions":"id"},splitObjects:["status"],ignore:["daemonId","status.timestamp"],stableRow:(e,t)=>{if(!("lastUpdated"in t))return t;const{lastUpdated:s,...r}=t;return r}},qv={collections:{nodes:"nodeId","queue.tasks":"id",missions:"id"},volatileTopLevel:["refreshedAt","sourceOfTruth","turnPresentationCounters","meshProtocolV2Counters","pendingRetentionCounters","meshProtocolMetrics"],stableRow:(e,t)=>e==="nodes"?zv(t):t};function Fr(e,t){if(!xs(e))return e;const s={...e};for(const r of t)delete s[r];return s}function zv(e){const t={...e};if(delete t.lastSeenAt,delete t.updatedAt,delete t.last_seen_at,delete t.updated_at,"dataFreshness"in t&&(t.dataFreshness=Fr(t.dataFreshness,["ageMs","lastProbeAt","staleness"])),"connection"in t&&(t.connection=Fr(t.connection,["lastStateChangeAt"])),"git"in t){const r=Fr(t.git,["lastCheckedAt"]);xs(r)&&Array.isArray(r.submodules)&&r.submodules.length===0&&delete r.submodules,t.git=r}"nodeFacts"in t&&(t.nodeFacts=Fr(t.nodeFacts,["reportedAt"]));const s=t.gitObservation;return xs(s)&&(s.source==="self"||s.source==="local")&&(t.gitObservation=Fr(s,["observedAt"])),t}const Vv=new Set(["no_progress","long_generating"]);function Gv(e){return!e||Vv.has(e)?e:pi(e)??e}function _u(e){return!!e&&typeof e=="object"&&"text"in e}function md(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 br(e){return md(e,{normalizeWhitespace:!0})}function Yv(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 Rp(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,l=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),l&&(r.versionUpdateRequired=!0),r)}function Qv(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 rc(e){if(!e||typeof e!="object")return"";const t=e,s=Qv(br(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 Jv(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=rc(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:rc(e[0]),last:rc(e[e.length-1])}}function ul(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function ml(e,t,s){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ul(e)&&ul(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 l=0;l<i;l+=1)ml(e[l],t[l],s);return}const r=e,o=t,a=new Set([...Object.keys(r),...Object.keys(o)]);for(const i of a)i!=="messages"&&ml(r[i],o[i],s)}function ao(e,t){return Array.isArray(e)?e.map(s=>ao(s,t)):!e||typeof e!="object"?e:ul(e)?Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>[r,r==="messages"?Jv(o,t):ao(o,t)])):Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,ao(r,t)]))}function Xv(e,t){try{const s=new WeakSet;return ml(e,t,s),JSON.stringify(ao(e,s))===JSON.stringify(ao(t,s))}catch{return!1}}function hl(e,t,s){return Xv(e,t)?(e._lastUpdate=s,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Pp(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Zv(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=yp(e.childSessions,t.childSessions,{preserveMissing:r}),i=xp(t.activeChat,e.activeChat),l=t.workspace||e.workspace;return Rp(e,t,{...e,...t,chats:o,childSessions:a,activeChat:i,workspace:l,_lastUpdate:s})}function ew(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=yp(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","assistant","managedByAssistant","model","modelSource","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])Zv(r,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(r.machineNickname=t.machineNickname),t.versionMismatch===!0&&(r.versionMismatch=!0),r}function tw(e,t,s,r){const o=ew(e,t,r),a=Object.keys(o).length>0?Rp(e,t,{...e,...o,_lastUpdate:s}):{...e,_lastUpdate:s};return hl(e,a,s)}function nw(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=Pp(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 sw(e,t,s,r,o,a){return!o.has(t)||!a.has(t)||r.has(e.id)?!1:e.transport==="pty"?s>1e4:e.transport==="cdp-page"?s>3e4:!1}function rw(e,t,s,r,o){return e.transport?s.has(t)&&!r.has(t)?!0:o.has(t):!1}function ow(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:l,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:u}=nw(e);for(const p of e){const b=a.get(p.id);if(!b){a.set(p.id,{...p,_lastUpdate:r});continue}const f=Au(p),x=Au(b),g=Pp(p),w=!o.has(g);if(f>x){const y=Tu(b,p,r,w);a.set(p.id,hl(b,y,r));continue}if(f<x){a.set(p.id,tw(b,p,r,w));continue}const S=y=>typeof y=="number"&&Number.isFinite(y),C=S(p.timestamp)&&S(b.timestamp),j=C?p.timestamp:p.timestamp||r,v=C?b.timestamp:b._lastUpdate||b.timestamp||0;if(j>=v){const y=Tu(b,p,r,w);a.set(p.id,hl(b,y,r));continue}(m=p.chats)!=null&&m.length&&!((h=b.chats)!=null&&h.length)&&a.set(p.id,{...b,chats:p.chats})}for(const[p,b]of a){const f=b.daemonId||p.split(":")[0];if(!l.has(f))continue;if(o.has(f)&&u.has(f)&&!i.has(p)){a.delete(p);continue}const x=r-(b._lastUpdate||b.timestamp||0);sw(b,f,x,i,o,d)&&a.delete(p)}for(const[p,b]of a){const f=b.daemonId||p.split(":")[0];if(rw(b,f,l,d,a))continue;r-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&a.delete(p)}return Array.from(a.values())}function aw(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 iw(e,t){return e.id===t||e.sessionId===t||e.instanceId===t}function cw(e,t,s){const r=t.trim();if(!r)return e;let o=!1;const a=e.map(i=>{if(!iw(i,r))return i;const l=i.activeInteractivePrompt;return l&&l.promptId===s.promptId?i:(o=!0,{...i,activeInteractivePrompt:s})});return o?a:e}const Ep=c.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}),Lp=c.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[],hydrateInteractivePrompt:()=>{}}),Dp=c.createContext({userName:void 0,setUserName:()=>{},userRole:void 0,usesP2P:!0});function lw({children:e,connectionOverrides:t}){const[s,r]=c.useState([]),[o,a]=c.useState(!1),[i,l]=c.useState([]),[d,u]=c.useState(void 0),m=c.useRef(s);c.useEffect(()=>{m.current=s},[s]);const h=c.useCallback((C,j)=>{r(v=>{let y=!1;const N=v.map(k=>k.id!==C||k.chats===j?k:(y=!0,{...k,chats:j}));return y?N:v})},[]),p=c.useCallback((C,j)=>{r(v=>{const y=v.length===0?C:ow(C,v,j),N=!aw(v,y);return N&&bo.record({kind:"dashboard.entries_applied",payload:{incoming:wu(C),next:wu(y)}}),N?y:v})},[]),b=c.useCallback(()=>a(!0),[]),f=c.useCallback((C,j)=>{r(v=>cw(v,C,j))},[]),x=c.useMemo(()=>({injectEntries:p,markLoaded:b,getIdes:()=>m.current,hydrateInteractivePrompt:f}),[p,b,f]),g=t,w=c.useMemo(()=>({ides:s,updateRouteChats:h,initialLoaded:o,toasts:i,setToasts:l,wsStatus:(g==null?void 0:g.wsStatus)??"connected",isConnected:(g==null?void 0:g.isConnected)??!0,connectionStates:(g==null?void 0:g.connectionStates)??{},connectionTransports:(g==null?void 0:g.connectionTransports)??{},showReconnected:(g==null?void 0:g.showReconnected)??!1,retryConnection:g==null?void 0:g.retryConnection,retryServerConnection:g==null?void 0:g.retryServerConnection,connectionLoginUrl:g==null?void 0:g.connectionLoginUrl,isP2PActive:(g==null?void 0:g.isP2PActive)??!1,p2pStates:(g==null?void 0:g.p2pStates)??{},usesP2P:(g==null?void 0:g.usesP2P)??!0,userRole:g==null?void 0:g.userRole,connectionRetryStatuses:g==null?void 0:g.connectionRetryStatuses,userName:d,setUserName:u}),[s,h,o,i,g==null?void 0:g.wsStatus,g==null?void 0:g.isConnected,g==null?void 0:g.connectionStates,g==null?void 0:g.connectionTransports,g==null?void 0:g.showReconnected,g==null?void 0:g.retryConnection,g==null?void 0:g.retryServerConnection,g==null?void 0:g.connectionLoginUrl,g==null?void 0:g.isP2PActive,g==null?void 0:g.p2pStates,g==null?void 0:g.usesP2P,g==null?void 0:g.userRole,g==null?void 0:g.connectionRetryStatuses,d]),S=c.useMemo(()=>({userName:d,setUserName:u,userRole:g==null?void 0:g.userRole,usesP2P:(g==null?void 0:g.usesP2P)??!0}),[d,u,g==null?void 0:g.userRole,g==null?void 0:g.usesP2P]);return n.jsx(Lp.Provider,{value:x,children:n.jsx(Dp.Provider,{value:S,children:n.jsx(Ep.Provider,{value:w,children:e})})})}function yn(){return c.useContext(Ep)}function dw(){return c.useContext(Dp)}function gr(){return c.useContext(Lp)}const uw=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={...}>.`)}}}),mw=c.createContext(uw);function hw({client:e,children:t}){return n.jsx(mw.Provider,{value:e,children:t})}const pw={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Op=c.createContext(pw);function fw({value:e,children:t}){return n.jsx(Op.Provider,{value:e,children:t})}function wt(){return c.useContext(Op)}function $p(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function bw(e){const t=$p(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 gw(e){const[t,s]=c.useState(null),r=c.useCallback(async(i,l)=>{const d=h=>e(i,"launch_cli",{...l,...h}),u=await d({}),m=bw(u);return m?new Promise(h=>{s({providerType:m.providerType||String(l.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=c.useCallback(async()=>{const i=t;if(i){s(null);try{const l=await i.retry(),d=$p(l);d!=null&&d.success?i.resolve({ok:!0,response:l}):i.resolve({ok:!1,error:(d==null?void 0:d.error)||"launch failed after confirm",response:l})}catch(l){i.resolve({ok:!1,error:(l==null?void 0:l.message)||String(l)})}}},[t]),a=c.useCallback(()=>{const i=t;i&&(s(null),i.resolve({ok:!1,cancelled:!0}))},[t]);return{launchCli:r,pending:t,confirm:o,cancel:a}}const Ue={size:18};function Fp({size:e=Ue.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 bi({size:e=Ue.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 xr({size:e=Ue.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 xw({size:e=Ue.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 yw({size:e=Ue.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 vw({size:e=Ue.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 hd({size:e=Ue.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 Hp({size:e=Ue.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 Cr({size:e=Ue.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 ww({size:e=Ue.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 _r({size:e=Ue.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 Co({size:e=Ue.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 qO({size:e=Ue.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 Sw({size:e=Ue.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 Cn({size:e=Ue.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 Bn({size:e=Ue.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 Bp({size:e=Ue.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 Ws({size:e=Ue.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 Ar({size:e=Ue.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 en({size:e=Ue.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 yr({size:e=Ue.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=Ue.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 pl({size:e=Ue.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 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"}),n.jsx("path",{d:"M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"})]})}function kw({size:e=Ue.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 pd({size:e=Ue.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 gi({size:e=Ue.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 fd({size:e=Ue.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 jw({size:e=Ue.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 bd({size:e=Ue.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 Nw({size:e=Ue.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 Wp({size:e=Ue.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 go({size:e=Ue.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 Cw({size:e=Ue.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 Et({size:e=Ue.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 Up({size:e=Ue.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 xi({size:e=Ue.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 _w({size:e=Ue.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 Kp({size:e=Ue.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 Aw({size:e=Ue.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 Jn({size:e=Ue.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 fl({size:e=Ue.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 qp({size:e=Ue.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=Ue.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 Vp({size:e=Ue.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 yi({size:e=Ue.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=Ue.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 Tw({size:e=Ue.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 Iw({size:e=Ue.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 Mw({size:e=Ue.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 Rw({size:e=Ue.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 Gp({size:e=Ue.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 Pw({size:e=Ue.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 Ew({size:e=Ue.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 Yp({size:e=Ue.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 vr({size:e=Ue.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 Lw({size:e=Ue.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:"16 3 21 3 21 8"}),n.jsx("line",{x1:"4",y1:"20",x2:"21",y2:"3"}),n.jsx("polyline",{points:"21 16 21 21 16 21"}),n.jsx("line",{x1:"15",y1:"15",x2:"21",y2:"21"}),n.jsx("line",{x1:"4",y1:"4",x2:"9",y2:"9"})]})}function Qp({size:e=Ue.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 Dw({size:e=Ue.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 Ow({size:e=Ue.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 $w({size:e=Ue.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 $a({size:e=Ue.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 Fw({providerType:e,sourceName:t,description:s,onConfirm:r,onCancel:o}){const{t:a}=he("common"),i=c.useRef(null);return c.useEffect(()=>{var l;(l=i.current)==null||l.focus()},[]),c.useEffect(()=>{const l=d=>{d.key==="Escape"&&o()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[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:l=>l.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(en,{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 Jp=c.createContext(null);function Hw({sendDaemonCommand:e,children:t}){const s=gw(e),r=c.useMemo(()=>({launchCli:s.launchCli}),[s.launchCli]);return n.jsxs(Jp.Provider,{value:r,children:[t,s.pending&&n.jsx(Fw,{providerType:s.pending.providerType,sourceName:s.pending.sourceName,description:s.pending.description,onConfirm:s.confirm,onCancel:s.cancel})]})}function vi(){const e=c.useContext(Jp);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function Bw(e){const{baseUrl:t,getToken:s,onUnauthorized:r}=e;function o(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function a(l){const d=s==null?void 0:s(),u=o(l),m=l.startsWith("http")?new URL(u):new URL(u,typeof window<"u"?window.location.origin:"http://localhost");return d&&m.searchParams.set("token",d),!l.startsWith("http")&&!t?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function i(l,d={}){const u={"Content-Type":"application/json",...d.headers||{}},m=s==null?void 0:s();m&&(u.Authorization=`Bearer ${m}`);const h=o(l),p=new AbortController,b=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(b)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:l=>i(`/api/v1/daemons/${l}/status`),sendCommand:(l,d,u={})=>i(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:d,payload:u})}),execTerminal:(l,d,u)=>i(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:u})}),sendAgentMessage:(l,d,u)=>i(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:u})}),getAgentStatus:l=>i(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,d,u)=>i(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:u?"approve":"reject"})}),getMuxState:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,d,u={})=>i(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:u})}),getMuxEventsUrl:l=>a(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>a(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:i}}function wi(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 l=Math.floor(i/60);if(l<60)return`${l}m${s}`;const d=Math.floor(l/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 Xp=e=>wi(e);function _o(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 Ao(e){var s,r;if(e)return e;const t=((s=Ye)==null?void 0:s.resolvedLanguage)||((r=Ye)==null?void 0:r.language);return t&&t!=="cimode"?t:void 0}function Fa(e,t={}){const s=_o(e);if(s===null)return"";const r=Ao(t.locale),o=t.now??Date.now(),a=Math.round((s-o)/1e3),i=Math.abs(a);let l;try{l=new Intl.RelativeTimeFormat(r,{numeric:"auto",style:"short"})}catch{l=new Intl.RelativeTimeFormat(void 0,{numeric:"auto",style:"short"})}return i<45?l.format(0,"second"):i<3600?l.format(Math.round(a/60),"minute"):i<86400?l.format(Math.round(a/3600),"hour"):i<7*86400?l.format(Math.round(a/86400),"day"):xd(s,{locale:r})}function gd(e,t){try{return new Intl.DateTimeFormat(e,t)}catch{return new Intl.DateTimeFormat(void 0,t)}}function To(e,t={}){const s=_o(e);return s===null?"":gd(Ao(t.locale),{dateStyle:"medium",timeStyle:t.seconds?"medium":"short"}).format(s)}function xd(e,t={}){const s=_o(e);return s===null?"":gd(Ao(t.locale),{dateStyle:"medium"}).format(s)}function Si(e,t={}){const s=_o(e);return s===null?"":gd(Ao(t.locale),{timeStyle:t.seconds?"medium":"short"}).format(s)}function zO(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 is(e,t,s){try{return new Intl.NumberFormat(s,{style:"unit",unit:t,unitDisplay:"short"}).format(e)}catch{return`${e}${t[0]}`}}function Ww(e,t={}){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";const s=Ao(t.locale),r=Math.round(e/1e3);if(r<60)return is(r,"second",s);const o=Math.floor(r/60);if(o<60)return is(o,"minute",s);const a=Math.floor(o/60);if(a<48){const d=o%60;return d?`${is(a,"hour",s)} ${is(d,"minute",s)}`:is(a,"hour",s)}const i=Math.floor(a/24),l=a%24;return l?`${is(i,"day",s)} ${is(l,"hour",s)}`:is(i,"day",s)}function Zp(e){return e?Si(e):""}function yd(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Uw(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}const Kw=new Set(["https:","http:","mailto:","file:"]);function Mu(e){if(e)try{const t=new URL(e);return Kw.has(t.protocol)?e:void 0}catch{return}}function Hr(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 oc(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 qw(e){const t=ef(e);if(t&&"messageId"in t)return`toolmsg:${t.messageId}`;const s=e.toolBlockRef;if(!s||typeof s!="object")return null;const{recordIndex:r,blockIndex:o}=s;return!Number.isInteger(r)||!Number.isInteger(o)?null:`toolblock:${r}:${o}`}function ef(e){const t=e.toolBlockRef;if(t&&typeof t=="object")return{toolBlockRef:t};const s=e;return s._expandable===!0&&typeof s.messageId=="string"&&s.messageId?{messageId:s.messageId}:null}function vd(e,t){const s=e;if(typeof s.messageId=="string"&&s.messageId)return`mid:${s.messageId}`;const r=md(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 zw(e){const t=e.map((o,a)=>vd(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 tf(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 Vw(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function nf(e){return e?tf([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Vw(e.content)]):""}const wd=200,Gw=80,Pu=650,Br=new Map;function Ha(e,t){if(!e)return!1;const s=String(e.messageFingerprint||"");return s?s===String(t||""):!0}function Yw(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}:${nf(r)}`}function Qw(e,t,s,r){return e||!t?!1:Ha(s,r)}function Jw({scrollTop:e,scrollHeight:t,clientHeight:s,topThresholdPx:r=Gw,bottomThresholdPx:o=wd}){const a=Math.max(0,Number(e)||0),i=Math.max(0,Number(t)||0),l=Math.max(0,Number(s)||0);return Math.max(0,i-l)<=0?{showTop:!1,showBottom:!1}:{showTop:a>r,showBottom:Math.max(0,i-a-l)>o}}function Xw(e){return Jw({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function to(e,t=wd){return!!e&&e.fromBottom>=t}function Zw(e,t){return Ha(e,t)?!to(e):!0}function eS({hasSelection:e,userScrolledUp:t,hasChatContentChanged:s=!0}){return!(e||t||!s)}function tS({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:s}){return e?!1:s||!t}function ac(e,t){const s=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(s)?s:t.top}function sf({text:e,size:t="sm"}){const{t:s}=he("common"),[r,o]=c.useState(!1),a=c.useCallback(u=>{u.preventDefault(),u.stopPropagation(),navigator.clipboard.writeText(e).then(()=>{o(!0),setTimeout(()=>o(!1),1500)}).catch(()=>{})},[e]),i=t==="code",l=s(i?"chat.copyCode":"chat.copyMessage"),d=i?12:11;return n.jsx("button",{type:"button",onClick:a,"aria-label":l,title:i?l:void 0,className:i?"chat-code-copy-btn":"chat-copy-btn",children:r?n.jsx(Cr,{size:d}):n.jsx(Hp,{size:d})})}function bl(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(bl).join("");if(c.isValidElement(e)){const s=(t=e.props)==null?void 0:t.children;return bl(s)}return""}function nS(e){const t=bl(e.children);return n.jsxs("pre",{...e,children:[e.children,n.jsx(sf,{text:t,size:"code"})]})}const sS={pre:nS},rS=[Qx,{singleTilde:!1}],oS=[rS,Jx,Xx],ki=c.memo(function({content:t,renderAsPreformatted:s,renderAsMarkdown:r}){return s?n.jsx("pre",{className:"chat-preformatted",children:t}):r?n.jsx(Yx,{remarkPlugins:oS,components:sS,children:t}):n.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function Eu({text:e,preformatted:t}){return e?n.jsx(ki,{content:e,renderAsPreformatted:t,renderAsMarkdown:!t&&yd(e)}):null}function qo({kind:e,label:t,detail: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 aS({part:e,preformatted:t}){if(e.type==="text")return n.jsx("div",{children:n.jsx(Eu,{text:String(e.text||""),preformatted:t})});if(e.type==="image"){const s=oc(e),r=e.alt||e.description||Hr(e.uri,"image");return s?n.jsx("img",{src:s,alt:r,className:"max-w-full rounded-md border border-border-subtle"}):n.jsx("div",{children:n.jsx(qo,{kind:"Image",label:r,detail:e.mimeType})})}if(e.type==="audio"){const s=oc(e);return s?n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("audio",{controls:!0,src:s,className:"max-w-full"}),e.transcript?n.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:e.transcript}):null]}):n.jsx("div",{children:n.jsx(qo,{kind:"Audio",label:Hr(e.uri,"audio"),detail:e.transcript||e.mimeType})})}if(e.type==="video"){const s=oc(e),r=e.title||e.name||e.alt||Hr(e.uri,"video"),o=[e.transcript,e.description,e.mimeType].filter(Boolean).join(`
6
- `);return n.jsxs("div",{className:"flex flex-col gap-1",children:[s?n.jsx("video",{controls:!0,src:s,poster:e.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):n.jsx(qo,{kind:"Video",label:r,detail:o}),s&&o?n.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]})}if(e.type==="resource_link"){const s=e.title||e.name||Hr(e.uri,"resource"),r=[e.description,e.mimeType].filter(Boolean).join(`
7
- `),o=Mu(e.uri);return n.jsxs("div",{className:"flex flex-col gap-1",children:[o?n.jsx("a",{href:o,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:s}):n.jsx(qo,{kind:"Resource",label:s,detail:r}),o&&r?n.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r}):null]})}if(e.type==="resource"&&e.resource){const s=Hr(e.resource.uri,"resource");if(e.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:s}),n.jsx(Eu,{text:e.resource.text,preformatted:!0})]});const r=Mu(e.resource.uri);if(r)return n.jsx("a",{href:r,target:"_blank",rel:"noreferrer",className:"underline break-all",children:s})}return null}function iS({parts:e,renderAsPreformatted:t}){return n.jsx("div",{className:"flex flex-col gap-2",children:e.map((s,r)=>n.jsx(aS,{part:s,preformatted:t},`${s.type}-${r}`))})}function cS({body:e,className:t,text:s,asPre:r}){if(e.type==="parts"){const a=n.jsx(iS,{parts:e.parts,renderAsPreformatted:e.preformatted});return t===null?a:n.jsx("div",{className:t,children:a})}const o=s??e.text;return t===null?n.jsx(n.Fragment,{children:o}):r&&e.type==="pre"?n.jsx("pre",{className:t,children:o}):e.type==="plain"?n.jsx("div",{className:t,style:{whiteSpace:"pre-wrap"},children:o}):n.jsx("div",{className:t,children:n.jsx(ki,{content:o,renderAsPreformatted:e.type==="pre",renderAsMarkdown:e.type==="markdown"})})}const Lu="chat-bubble-header",lS={user:{outer:"chat-message-row chat-message-row-user self-end",root:"chat-bubble chat-bubble-user",header:Lu,label:"chat-sender",meta:"chat-bubble-header-end",body:"chat-markdown",expand:"chat-bubble-expand",showLabel:!0},assistant:{outer:"chat-message-row chat-message-row-assistant self-start",root:"chat-bubble chat-bubble-assistant",header:Lu,label:"chat-sender",meta:"chat-bubble-header-end",body:"chat-markdown",expand:"chat-bubble-expand",showLabel:!0},tool:{root:"self-start chat-msg-tool",header:"chat-msg-tool-meta",headerAria:"chat.toolMessageAria",label:"tool-label",meta:"chat-bubble-header-end chat-msg-tool-header-end",body:"tool-text w-full",expand:"chat-msg-tool-expand",showLabel:!0},thought:{root:"self-start chat-msg-thought",header:"chat-msg-header",label:"chat-row-label",meta:"chat-bubble-header-end",body:"chat-msg-body",expand:"chat-msg-thought-expand",showLabel:!0},terminal:{root:"self-start chat-msg-terminal",header:"chat-msg-header",label:"chat-row-label",meta:"chat-bubble-header-end",body:"chat-msg-body",bodyPre:!0,expand:"chat-msg-terminal-expand",showLabel:!0},activity:{root:"self-start chat-msg-activity",header:"chat-msg-activity-meta",headerAria:"chat.activityMessageAria",label:"chat-row-label",meta:"chat-bubble-header-end",body:"chat-msg-activity-body",expand:"chat-msg-activity-expand",showLabel:!0},system:{root:"self-center chat-msg-system",header:"chat-msg-system-meta",label:"chat-row-label",meta:"chat-bubble-header-end",body:null,expand:"chat-msg-system-expand",headerLast:!0}};function dS(e){const{t}=he("common");return"text"in e?e.text:t(e.i18nKey)}function uS({icon:e}){switch(e){case"thought":return n.jsx(_w,{size:13});case"tool-dot":return n.jsx("span",{className:"tool-icon","aria-hidden":"true"});case"activity-dot":return n.jsx("span",{className:"activity-dot"});case"running":return n.jsx("span",{children:n.jsx(vr,{size:12})});case"done":return n.jsx("span",{children:n.jsx(Cr,{size:12})});case"git":return n.jsx("span",{className:"chat-row-icon","aria-hidden":"true",children:n.jsx($a,{size:11})});default:return null}}function Sd({className:e,copyText:t,timestamp:s}){return t===null&&s===null?null:n.jsxs("span",{className:`chat-row-meta ${e}`,children:[t!==null&&n.jsx(sf,{text:t}),s!==null&&n.jsx("span",{className:"chat-time",children:Zp(s)})]})}function rf({collapse:e,className:t,expanded:s,onToggle:r,remoteState:o,onExpandRemote:a,onCollapseRemote:i}){const{t:l}=he("common"),d=`chat-row-expand ${t}`;if(e.mode==="none")return null;if(e.mode==="remote"){if(!a)return null;if((o==null?void 0:o.status)==="loading")return n.jsx("div",{className:d,"aria-live":"polite",children:l("chat.toolExpandLoading")});if((o==null?void 0:o.status)==="error"){const m=o.error==="source_changed";return n.jsx("div",{className:`${d} chat-row-expand-error ${t}-error`,role:"status","data-expand-error-reason":o.error??"unknown",children:l(m?"chat.toolExpandStale":"chat.toolExpandUnavailable")})}const u=(o==null?void 0:o.status)==="expanded";return n.jsx("button",{type:"button",className:d,"aria-expanded":u,onClick:u?i:()=>a(e.address),children:l(u?"chat.toolCollapse":"chat.toolExpand")})}return r?n.jsx("button",{type:"button",className:d,"aria-expanded":s,onClick:r,children:l(s?"chat.toolCollapse":"chat.toolExpand")}):null}function mS(e,t,s){if(e.body.type==="parts")return;const r=(s==null?void 0:s.status)==="expanded"&&s.text!==void 0?s.text:e.body.text,o=e.collapse;return o.mode==="local"&&!t&&r.length>o.threshold?`${r.slice(0,o.previewChars)}…`:r}function hS({model:e,expanded:t,onToggle:s,remoteState:r,onExpandRemote:o,onCollapseRemote:a,children:i}){const{t:l}=he("common"),d=e.kind==="injected"?"system":e.kind,u=lS[d],m=dS(e.label),h=e.surface==="activity",p=!!u.outer,b=e.body.type==="parts"||e.body.text.length>0,f=t||(r==null?void 0:r.status)==="expanded",x=mS(e,f,r);if(p&&!b&&e.kind!=="user")return n.jsx("div",{className:u.outer});const g=u.headerLast?"span":"div",w=n.jsxs(g,{className:`chat-row-header ${u.header}${p?b?" mb-1.5":" mb-0":""}`,"aria-label":u.headerAria?l(u.headerAria):void 0,children:[n.jsx(uS,{icon:e.icon}),u.showLabel&&n.jsx("span",{className:u.label,children:m}),n.jsx(Sd,{className:u.meta,copyText:b?e.copyText:null,timestamp:e.timestamp})]}),S=b?n.jsx(cS,{body:e.body,className:u.body,text:x,asPre:u.bodyPre}):null,C=n.jsx(rf,{collapse:e.collapse,className:u.expand,expanded:f,onToggle:s,remoteState:r,onExpandRemote:o,onCollapseRemote:a}),j=n.jsxs("div",{className:`chat-row chat-row-${e.kind} ${u.root}`,"data-chat-row-kind":e.kind,"data-chat-activity-row":h?"true":void 0,title:d==="system"&&e.body.type!=="parts"?e.body.text:void 0,children:[!u.headerLast&&w,S,C,u.headerLast&&w,i]});return u.outer?n.jsx("div",{className:u.outer,children:j}):j}const pS={mode:"local",threshold:0,previewChars:0};function fS({segment:e,timestamp:t,open:s,onToggle:r}){const{t:o}=he("common"),a=e.outcome||"",i=o("chat.relayLabel",{project:e.project||"",outcome:o(`chat.relayOutcome.${a}`,{defaultValue:a})});return n.jsxs("div",{className:"chat-relay-card","data-relay-outcome":a,"data-expanded":s?"true":"false",children:[n.jsxs("div",{className:"chat-row-header chat-relay-header",children:[n.jsx("span",{className:"chat-row-icon","aria-hidden":"true",children:n.jsx(Lw,{size:12})}),n.jsx("span",{className:"chat-relay-label",children:i}),e.idle&&n.jsx("span",{className:"chat-relay-badge",children:o("chat.relayIdle")}),n.jsx(Sd,{className:"chat-bubble-header-end",copyText:e.body||null,timestamp:t})]}),s?n.jsx("div",{className:"chat-relay-body chat-markdown",children:n.jsx(ki,{content:e.body,renderAsPreformatted:!1,renderAsMarkdown:yd(e.body)})}):e.preview?n.jsx("div",{className:"chat-relay-preview",children:e.preview}):null,e.body&&n.jsx(rf,{collapse:pS,className:"chat-relay-expand",expanded:s,onToggle:r})]})}function bS({segment:e,timestamp:t}){const{t:s}=he("common"),r=e.source==="signal"?e.project||"":e.source==="review"?s("chat.reviewLabel"):s("chat.daemonNoticeLabel"),o=e.source==="review"?hd:Jn;return n.jsxs("div",{className:"chat-notice-chip","data-injected-source":e.source,title:e.body,children:[n.jsx("span",{className:"chat-row-icon","aria-hidden":"true",children:n.jsx(o,{size:11})}),n.jsx("span",{className:"chat-notice-chip-label",children:r}),n.jsx("span",{className:"chat-notice-chip-text",children:e.preview}),n.jsx(Sd,{className:"chat-bubble-header-end",copyText:e.body||null,timestamp:t})]})}function gS({model:e,openSegments:t,onToggleSegment:s}){var a,i;const r=((a=e.injected)==null?void 0:a.segments)??[],o=new Set(t?t.split(","):[]);return n.jsx("div",{className:"chat-row chat-row-injected self-stretch chat-msg-injected","data-chat-row-kind":"injected","data-injected-source":(i=e.injected)==null?void 0:i.source,children:r.map((l,d)=>l.source==="relay"?n.jsx(fS,{segment:l,timestamp:e.timestamp,open:o.has(String(d)),onToggle:s?()=>s(d):void 0},`relay-${d}`):l.source==="text"?n.jsx("div",{className:"chat-injected-text",style:{whiteSpace:"pre-wrap"},children:l.body},`text-${d}`):n.jsx(bS,{segment:l,timestamp:e.timestamp},`${l.source}-${d}`))})}const kd="adhdev_chat_activity_visible",Du=new Set(["hidden","debug","internal"]),Ou=new Set(["visible","user","chat"]),xS=new Set(["debug","trace","internal"]),yS=new Set(["tool_call","terminal_command","runtime_activity"]),vS=new Set(["runtime_status","provider_chrome","control"]),wS=new Set(["thought","tool","terminal"]);function of(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function cr(e){return typeof e=="string"?e.trim().toLowerCase():""}function ic(e,t,s){return e[s]??(t==null?void 0:t[s])}function $u(e,t,s){const r=e;return s.some(o=>r[o]===!0||(t==null?void 0:t[o])===!0)}function SS(e,t){const s=cr(e.kind);return s||(t==="tool"?"tool":"standard")}const lr={terminal:{text:"Terminal",key:"chat.activityTerminal"},tool:{text:"Tool",key:"chat.tool"},thought:{text:"Thought",key:"chat.thought"},runtime:{text:"Runtime",key:"chat.activityRuntime"},activity:{text:"Activity",key:"chat.activityFallback"}};function af(e,t){return e==="terminal"||t==="terminal_command"?lr.terminal:e==="tool"||t==="tool_call"?lr.tool:e==="thought"?lr.thought:t==="runtime_activity"?lr.runtime:lr.activity}function cc(e,t,s){const r=of(e),o=typeof(r==null?void 0:r.label)=="string"?r.label.trim():"";return o||af(t,s).text}function kS(e){const t=e.content;return Array.isArray(t)&&t.some(s=>!!s&&typeof s=="object"&&s.type!=="text")}function jd(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal",labelKey:lr.activity.key};const t=of(e),s=cr(e.role),r=SS(e,s),o=cr(ic(e,t,"visibility")),a=cr(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??o),i=cr(ic(e,t,"audience")),l=cr(ic(e,t,"source")),d=Du.has(o)||Du.has(a)||xS.has(i)||$u(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),u=Ou.has(o)||Ou.has(a)||i==="chat"||$u(e,t,["userFacing"]),m=wS.has(r)||yS.has(l),h=af(r,l).key;if(d)return{surface:m?"activity":"internal",isUserFacing:!1,isActivityFacing:m,isInternal:!m,role:s,kind:r,label:cc(e,r,l),labelKey:h};if(u)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:s,kind:r,label:cc(e,r,l),labelKey:h};if((s==="system"||r==="system")&&kS(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:s,kind:r,label:"Chat",labelKey:h};if(vS.has(l)||s==="system"||r==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:s,kind:r,label:"Internal",labelKey:h};if(m)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:s,kind:r,label:cc(e,r,l),labelKey:h};const p=(s==="user"||s==="human"||s==="assistant")&&(r==="standard"||r==="");return{surface:p?"chat":"internal",isUserFacing:p,isActivityFacing:!1,isInternal:!p,role:s,kind:r,label:p?"Chat":"Internal",labelKey:h}}function jS(e){return(Array.isArray(e)?e:[]).filter(t=>jd(t).isActivityFacing)}const Fu=new WeakMap;function cf(e){const t=Fu.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 Fu.set(e,r),r}function NS(e){return`${String(e.role||"")}::${cf(e)}`}function CS(e){if(e.length<2)return e;const t=[];let s="";for(const r of e){const o=NS(r);cf(r).trim().length>0&&o===s||(t.push(r),s=o)}return t}function _S(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 l=Number(r.index??0)||0,d=Number(o.index??0)||0;return l-d})}function xo(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(kd))!=="0"}catch{return!0}}function AS(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(kd,e?"1":"0")}catch{}}const gl="adhdev:chat-activity-visibility-change";function lf(e){AS(e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(gl,{detail:e}))}function df(e){if(typeof window>"u")return()=>{};const t=r=>{const o=r.detail;e(typeof o=="boolean"?o:xo())},s=r=>{r.key&&r.key!==kd||e(xo())};return window.addEventListener(gl,t),window.addEventListener("storage",s),()=>{window.removeEventListener(gl,t),window.removeEventListener("storage",s)}}const uf="adhdev_assistant_activity_visible";function TS(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(uf))==="1"}catch{return!1}}function IS(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(uf,e?"1":"0")}catch{}}const MS=/^\s*\[System\]\s/,RS=/^\s*\[ADHDev relay · project (\S+) · (\w+)\]\s*$/,PS=/^\s*\[\/relay\]\s*$/,ES=/^Untrusted agent output from the \S+ project follows\./,LS=/^\s*\[idle\]\s*$/,DS=[{source:"relay",re:RS},{source:"signal",re:/^\s*\[project ([^\]\s]+)\]\s+(.*)$/},{source:"review",re:/^\s*\[ADHDev review\]\s+(.*)$/},{source:"notice",re:/^\s*\[ADHDev (?:restart|first run)\]\s+(.*)$/}],Hu=160;function xl(e){for(const t of DS){const s=t.re.exec(e);if(s)return{rule:t,match:s}}return null}function yo(e){for(const t of e.split(`
8
- `))if(t.trim())return t;return""}function Ba(e){const t=e.trim();return t.length>Hu?`${t.slice(0,Hu-1)}…`:t}function mf(e){let t=0,s=e.length;for(;t<s&&!e[t].trim();)t++;for(;s>t&&!e[s-1].trim();)s--;return e.slice(t,s)}function OS(e,t,s){let r=!1;const o=s.filter(i=>ES.test(i.trim())?!1:LS.test(i)?(r=!0,!1):!0),a=mf(o).join(`
9
- `);return{source:"relay",project:e,outcome:t,idle:r,preview:Ba(yo(a)),body:a}}function $S(e){const t=e.replace(/\r\n?/g,`
10
- `).split(`
11
- `),s=[];let r=[];const o=()=>{const i=mf(r);if(r=[],!i.length)return;const l=i.join(`
12
- `);s.push({source:"text",preview:Ba(yo(l)),body:l})};let a=0;for(;a<t.length;){const i=xl(t[a]);if(!i){r.push(t[a]),a++;continue}if(o(),i.rule.source==="relay"){const u=[];for(a++;a<t.length&&!PS.test(t[a]);)u.push(t[a++]);a++,s.push(OS(i.match[1],i.match[2],u));continue}const l=[i.match[i.rule.source==="signal"?2:1]??""];for(a++;a<t.length&&t[a].trim()&&!xl(t[a]);)l.push(t[a++]);const d=l.join(`
13
- `).trim();s.push({source:i.rule.source,...i.rule.source==="signal"?{project:i.match[1]}:{},preview:Ba(yo(d)),body:d})}return o(),s}function FS(e){if(!e)return null;if(MS.test(e))return{source:"system",segments:[{source:"system",preview:Ba(yo(e)),body:e}]};const t=xl(yo(e));return t?{source:t.rule.source,segments:$S(e)}:null}const Bu={mode:"local",threshold:100,previewChars:100},Wu={mode:"local",threshold:600,previewChars:599},HS=new Set(["thought","tool","terminal"]);function BS(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function zo(e){return typeof e.label=="string"?e.label:""}function Xs(e,t){return e?{text:e}:{i18nKey:t}}function WS(e,t,s,r){if(r)return r.source==="system"?"system":"injected";const o=e.kind||(t==="tool"?"tool":"standard");return s&&!HS.has(o)?"activity":o==="thought"||o==="tool"||o==="terminal"||o==="system"?o:t==="system"?"system":t==="user"||t==="human"?"user":"assistant"}function US(e,t,s,r,o){switch(e){case"user":return Xs(r.userName||"","chat.you");case"assistant":return Xs(t.senderName||r.agentName||"","chat.agent");case"tool":return Xs(zo(s)||(typeof t.toolName=="string"?t.toolName:""),"chat.tool");case"thought":return Xs(zo(s),"chat.thought");case"terminal":return Xs(zo(s),"chat.ranCommand");case"activity":return Xs(zo(s).trim(),o);case"system":return{i18nKey:"chat.system"};case"injected":return{i18nKey:"chat.injected"}}}function KS(e,t){switch(e){case"thought":return"thought";case"tool":return"tool-dot";case"activity":return"activity-dot";case"terminal":return t.isRunning?"running":"done";case"system":return t.source==="git-system-bubble"?"git":null;default:return null}}function qS(e,t,s,r){const a=(typeof r.renderMode=="string"?r.renderMode.trim():"")==="preformatted";if(s)return{type:"parts",parts:s,preformatted:e==="terminal"||(e==="user"||e==="assistant")&&a};if(e==="terminal")return{type:"pre",text:t};if(e==="assistant"){if(a)return{type:"pre",text:t};if(yd(t))return{type:"markdown",text:t}}return e==="user"&&a?{type:"pre",text:t}:{type:"plain",text:t}}function zS(e,t,s,r){if(r)return{mode:"none"};if(e==="tool"){const o=ef(t);return o?{mode:"remote",address:o}:s.length>Wu.threshold?Wu:{mode:"none"}}return e==="system"?s.length>Bu.threshold?Bu:{mode:"none"}:{mode:"none"}}function VS(e){if(!(e.pendingLocal!==!0||e.queued!==!0))return{queued:{pendingId:typeof e.pendingId=="string"?e.pendingId:""}}}function GS(e){return"text"in e?`t:${e.text}`:`k:${e.i18nKey}`}function YS(e){if(e.mode==="local")return`local:${e.threshold}:${e.previewChars}`;if(e.mode==="remote"){const t=e.address;return"messageId"in t?`remote:mid:${t.messageId}`:`remote:ref:${t.toolBlockRef.recordIndex}:${t.toolBlockRef.blockIndex}:${t.toolBlockRef.sourceMtimeMs}`}return"none"}function QS(e,t){var r;const s=t.body;return tf([nf(e),t.key,t.expandKey??"",t.kind,t.surface,GS(t.label),t.icon??"",String(t.timestamp??""),t.copyText===null?"":"copy",s.type==="parts"?`parts:${s.preformatted}`:s.type,YS(t.collapse),(r=t.status)!=null&&r.queued?`queued:${t.status.queued.pendingId}`:"",t.injected?t.injected.segments.map(o=>`${o.source}:${o.project??""}:${o.outcome??""}:${o.idle?1:0}`).join(","):""])}const Uu=new WeakMap;function JS(e,t){var f;const s=jd(e),r=BS(e),o=(e.role||"").toLowerCase(),a=Uw(e.content)?e.content:null,i=a!=null&&a.some(x=>x.type!=="text")?a:null,l=md(e.content,{joiner:`
14
- `}),d=(o==="user"||o==="human")&&!i&&r.pendingLocal!==!0?FS(l):null,u=d?{source:d.source,segments:d.segments}:void 0,m=WS(e,o,s.isActivityFacing,u),h=vd(e),p=t.receivedAt!==void 0?t.receivedAt:Number(e.receivedAt||((f=t.receivedAtMap)==null?void 0:f[h])||0)||null,b={key:h,expandKey:qw(e),kind:m,surface:s.surface,label:US(m,e,r,t,s.labelKey),icon:KS(m,r),timestamp:p||null,copyText:l||null,body:qS(m,l,i,r),collapse:zS(m,e,l,!!i),...u?{injected:u}:{},...m==="user"?{status:VS(r)}:{}};return b.status===void 0&&delete b.status,{...b,signature:QS(e,b)}}function yl(e,t={}){const s=Uu.get(e);if(s&&s.agentName===t.agentName&&s.userName===t.userName&&s.receivedAt===t.receivedAt&&s.receivedAtMap===t.receivedAtMap)return s.model;const r=JS(e,t);return Uu.set(e,{agentName:t.agentName,userName:t.userName,receivedAt:t.receivedAt,receivedAtMap:t.receivedAtMap,model:r}),r}const XS=c.memo(function({log:t}){return n.jsxs("div",{className:"self-center chat-msg-action",children:[n.jsx(ki,{content:t.text,renderAsPreformatted:!1,renderAsMarkdown:!0}),n.jsx("span",{className:"action-time",children:Zp(t.timestamp)})]})},(e,t)=>e.log===t.log);function lc(e){return e.row??yl(e.message,{agentName:e.agentName,userName:e.userName,receivedAt:e.receivedAt??null})}function ZS({pendingId:e,onSendNow:t,isSendingNow:s,onCancelQueued:r}){const{t:o}=he("common");return n.jsxs("div",{className:"chat-bubble-queued","data-chat-queued-row":"true",children:[n.jsx("span",{className:"chat-bubble-queued-label","aria-label":o("chat.waitingToSendAria"),children:o("chat.waitingToSend")}),t&&n.jsx("button",{type:"button",onClick:()=>t(e||void 0),disabled:s,className:"chat-bubble-send-now","aria-label":o("chat.sendNowAria"),title:o("chat.sendNowTitle"),children:o(s?"chat.sending":"chat.sendNow")}),r&&e&&n.jsx("button",{type:"button",onClick:()=>r(e),disabled:s,className:"chat-bubble-cancel-queued","aria-label":o("chat.cancelQueuedAria"),title:o("chat.cancelQueuedTitle"),children:o("chat.cancelQueued")})]})}const e0=c.memo(function(t){var p;const s=lc(t),{isTextExpanded:r,onToggleTextExpanded:o,onSendNow:a,isSendingNow:i,onCancelQueued:l,onExpandToolBlock:d,onCollapseToolBlock:u,toolExpand:m}=t;if(s.kind==="injected")return n.jsx(gS,{model:s,openSegments:t.openSegments??"",onToggleSegment:t.onToggleSegment});const h=(p=s.status)==null?void 0:p.queued;return n.jsx(hS,{model:s,expanded:r,onToggle:o,remoteState:m,onExpandRemote:d,onCollapseRemote:u,children:h&&n.jsx(ZS,{pendingId:h.pendingId,onSendNow:a,isSendingNow:i,onCancelQueued:l})})},(e,t)=>(e.message===t.message&&e.row===t.row||lc(e).signature===lc(t).signature)&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded&&e.openSegments===t.openSegments&&e.isSendingNow===t.isSendingNow&&e.onSendNow===t.onSendNow&&e.onCancelQueued===t.onCancelQueued&&e.toolExpand===t.toolExpand),t0="";function n0(e,t){const[s,r]=c.useState({}),o=c.useCallback(d=>{r(u=>{var p;const m=u[d],h={...u};return m!=null&&m.open||((p=m==null?void 0:m.remote)==null?void 0:p.status)==="expanded"?delete h[d]:h[d]={open:!0},h})},[]),a=c.useCallback(d=>{r(u=>{if(!u[d])return u;const m={...u};return delete m[d],m})},[]),i=c.useCallback((d,u)=>{t&&(r(m=>({...m,[d]:{remote:{status:"loading"}}})),t(u).catch(()=>({status:"error"})).then(m=>r(h=>({...h,[d]:{remote:m}}))))},[t]);return c.useCallback(d=>{var b;const u=`${e}${t0}${d}`,m=s[u],h=`${u}#`,p=[];for(const f of Object.keys(s))f.startsWith(h)&&((b=s[f])!=null&&b.open)&&p.push(Number(f.slice(h.length)));return{isTextExpanded:(m==null?void 0:m.open)===!0,onToggleTextExpanded:()=>o(u),toolExpand:m==null?void 0:m.remote,onExpandToolBlock:t?f=>i(u,f):void 0,onCollapseToolBlock:t?()=>a(u):void 0,openSegments:p.sort((f,x)=>f-x).join(","),onToggleSegment:f=>o(`${h}${f}`)}},[a,e,s,i,t,o])}const s0=c.forwardRef(function({messages:t,actionLogs:s,agentName:r="Agent",userName:o,isCliMode:a=!1,isWorking:i=!1,contextKey:l="",receivedAtMap:d={},lastMessageHash:u,showActivityMessages:m=!1,emptyState:h,onLoadMore:p,isLoadingMore:b,hasMoreHistory:f,hiddenLiveCount:x=0,loadError:g,scrollToBottomRequestNonce:w,isVisible:S=!0,onSendNow:C,isSendingNow:j,onCancelQueued:v,fetchToolBlock:y},N){const{t:k}=he("common"),A=c.useRef(null),E=c.useRef(null),P=c.useRef(null),T=c.useRef(0),M=c.useRef(""),_=c.useRef(""),I=c.useRef(!1),D=c.useRef(null),L=c.useRef(!1),$=c.useRef(null),U=c.useRef(!1),J=n0(l,y),[K,R]=c.useState({showTop:!1,showBottom:!1}),O=c.useRef(!1),H=c.useRef(!1),B=c.useRef(S),q=c.useRef(S),W=c.useRef(null);q.current=S;const ce=()=>{const Z=A.current;return Z?Z.scrollHeight-Z.scrollTop-Z.clientHeight<wd:!0},ye=c.useCallback(()=>{const Z=A.current,ie=Z?Xw(Z):{showTop:!1,showBottom:!1};R(F=>F.showTop===ie.showTop&&F.showBottom===ie.showBottom?F:ie)},[]),G=c.useCallback((Z="auto")=>{var F;const ie=A.current;ie&&(ie.scrollTo({top:ie.scrollHeight,behavior:Z}),(F=ie.ownerDocument.defaultView)==null||F.requestAnimationFrame(()=>ye()))},[ye]),Se=c.useCallback((Z="auto")=>{var F;const ie=A.current;ie&&(ie.scrollTo({top:0,behavior:Z}),(F=ie.ownerDocument.defaultView)==null||F.requestAnimationFrame(()=>ye()))},[ye]),ue=c.useCallback(()=>{var me;const Z=A.current,ie=(me=window.getSelection)==null?void 0:me.call(window);if(!Z||!ie||ie.rangeCount===0||ie.isCollapsed){U.current=!1;return}const F=ie.anchorNode,se=ie.focusNode;U.current=!!(F&&se&&Z.contains(F)&&Z.contains(se))},[]),{visibleMessages:ne,rowByMessage:ae}=c.useMemo(()=>{const Z=new Map,ie=[],F=[];for(const se of Array.isArray(t)?t:[]){const me=yl(se,{agentName:r,userName:o,receivedAtMap:d});Z.set(se,me),me.surface==="chat"?ie.push(se):me.surface==="activity"&&F.push(se)}return{visibleMessages:CS(_S(ie,F,m)),rowByMessage:Z}},[t,m,r,o,d]),ee=ne.length===t.length?u:void 0,oe=Yw(ne,ee),Ce=c.useCallback(()=>{const Z=A.current;if(!Z||!l||!q.current)return;const ie={top:Z.scrollTop,fromBottom:Math.max(0,Z.scrollHeight-Z.scrollTop-Z.clientHeight),messageFingerprint:oe};W.current={contextKey:l,snapshot:ie},Br.set(l,ie)},[l,oe]),Q=c.useCallback((Z="auto")=>{D.current!=null&&cancelAnimationFrame(D.current),D.current=requestAnimationFrame(()=>{D.current=null,G(Z)})},[G]),z=c.useCallback(()=>{O.current=!1,L.current=!0,H.current=!0,$.current!=null&&window.clearTimeout($.current),$.current=window.setTimeout(()=>{L.current=!1,$.current=null},Pu)},[]);c.useEffect(()=>{const Z=!I.current,ie=_.current!==l;if(_.current=l,Z||ie){I.current=!0;const se=l?Br.get(l):null,me=!!se&&Ha(se,oe);O.current=me?to(se):!1,L.current=Zw(se,oe),U.current||(me?requestAnimationFrame(()=>{const re=A.current;re&&(ac(re,se),O.current=to(se),ye(),H.current=!0)}):Q("auto")),T.current=ne.length,M.current=oe;return}ne.length>T.current;const F=oe!==M.current;eS({hasSelection:U.current,userScrolledUp:O.current,hasChatContentChanged:F})&&Q("auto"),T.current=ne.length,M.current=oe},[oe,l,ne.length,Q,ye]),c.useEffect(()=>{w&&(z(),U.current||Q("auto"))},[z,Q,w]),c.useEffect(()=>{const Z=B.current;Z&&!S&&Ce(),q.current=S,B.current=S;const ie=l?Br.get(l):null;if(Qw(Z,S,ie,oe)){if(!ie)return;O.current=to(ie),L.current=!1,U.current||requestAnimationFrame(()=>{const F=A.current;F&&(ac(F,ie),ye())});return}},[S,l,oe,z,Ce,Q,ye]),c.useEffect(()=>()=>{const Z=W.current;Z&&Br.set(Z.contextKey,Z.snapshot),D.current!=null&&cancelAnimationFrame(D.current),$.current!=null&&window.clearTimeout($.current)},[]),c.useEffect(()=>{const Z=E.current,ie=A.current;if(!Z||!ie)return;const F=()=>{$.current!=null&&window.clearTimeout($.current),$.current=window.setTimeout(()=>{L.current=!1,$.current=null},Pu)},se=new ResizeObserver(()=>{ye();const me=L.current;tS({hasSelection:U.current,userScrolledUp:O.current,contextAutoScrollActive:me})&&(Q("auto"),me&&F())});return se.observe(Z),ie!==Z&&se.observe(ie),()=>{se.disconnect(),$.current!=null&&(window.clearTimeout($.current),$.current=null)}},[Q,l,ye]),c.useImperativeHandle(N,()=>({scrollToBottom:(Z="smooth")=>{G(Z)}}),[G]),c.useEffect(()=>{const Z=A.current;if(!Z)return;let ie;const F=()=>{Ce(),clearTimeout(ie),ie=setTimeout(()=>{O.current=!ce(),ye()},50)};return Z.addEventListener("scroll",F,{passive:!0}),()=>{Z.removeEventListener("scroll",F),clearTimeout(ie)}},[Ce,ye]),c.useEffect(()=>(document.addEventListener("selectionchange",ue),()=>document.removeEventListener("selectionchange",ue)),[ue]);const X=c.useRef(0),pe=c.useRef(!1);c.useEffect(()=>{const Z=A.current;if(!Z||!pe.current||X.current===0)return;const ie=Z.scrollHeight-X.current;ie>0&&(Z.scrollTop=ie),ye(),Ce(),X.current=0,pe.current=!1},[ne.length,Ce,ye]),c.useEffect(()=>{if(H.current||!l)return;const Z=Br.get(l),ie=A.current;if(!(!Z||!ie)){if(!Ha(Z,oe)){G("auto"),H.current=!0;return}ac(ie,Z),O.current=to(Z),ye(),H.current=!0}},[l,oe,ne.length,G,ye]);const Pe=()=>{const Z=A.current;Z&&(X.current=Z.scrollHeight),pe.current=!0,p==null||p()},Oe=()=>{O.current=!0,Se("smooth"),Ce()},Le=()=>{z(),G("smooth"),Ce()},ke=c.useMemo(()=>{const Z=zw(ne),ie=ne.map((re,we)=>{const V=ae.get(re)??yl(re,{agentName:r,userName:o,receivedAtMap:d});return{type:"message",data:re,row:V,index:we,ts:V.timestamp??0,stableKey:Z[we]}});if(!s||s.length===0)return ie;const F=[...s].sort((re,we)=>re.timestamp-we.timestamp).map((re,we)=>({type:"action",data:re,index:we,ts:re.timestamp})),se=[];let me=0;for(const re of ie){for(;me<F.length&&re.ts>0&&F[me].ts<re.ts;)se.push(F[me++]);se.push(re)}for(;me<F.length;)se.push(F[me++]);return se},[ne,ae,s,r,o,d]),Y=x>0||!!f,ve=x>0?x>80?k("chatList.showEarlierMessagesHidden",{count:Math.min(x,80),total:x}):k("chatList.showEarlierMessages",{count:Math.min(x,80)}):g?k("chatList.loadErrorRetry",{error:g}):k("chatList.loadOlderMessages");return n.jsxs("div",{className:"chat-scroll-frame",children:[n.jsx("div",{ref:A,"data-chat-scroll":!0,className:"chat-container",children:n.jsxs("div",{ref:E,className:"chat-container-content",children:[b&&n.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:k("chatList.loadingOlderMessages")}),Y&&!b&&n.jsx("div",{className:"text-center py-2",children:n.jsx("button",{type:"button",onClick:Pe,className:`text-2xs rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${g&&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:ve})}),ke.length===0&&!Y&&(h||n.jsx("div",{className:"text-center mt-16 opacity-20 text-xxs",children:k("chatList.waitingForMessages")})),ke.map(Z=>{if(Z.type==="action"){const re=Z.data;return n.jsx(XS,{log:re},`action-${Z.index}`)}const ie=Z.data,F=Z.row,se=Z.stableKey,me=J(F.expandKey??se);return n.jsx(e0,{message:ie,row:F,receivedAt:F.timestamp??void 0,agentName:r,userName:o,isCliMode:a,onSendNow:C,isSendingNow:j,onCancelQueued:v,...me},`msg-${se}`)}),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:k("chatList.agentGenerating")})]})}),n.jsx("div",{className:"min-h-10",ref:P})]})}),(K.showTop||K.showBottom)&&n.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":k("chatList.jumpToTop"),children:[K.showTop&&n.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:Oe,"aria-label":k("chatList.jumpToOldestMessages"),title:k("chatList.jumpToTop"),children:k("chatList.top")}),K.showBottom&&n.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:Le,"aria-label":k("chatList.jumpToLatestMessages"),title:k("chatList.jumpToBottom"),children:k("chatList.latest")})]})]})}),r0=c.memo(s0,(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.fetchToolBlock===t.fetchToolBlock),o0="modulepreload",a0=function(e){return"/"+e},Ku={},hr=function(t,s,r){let o=Promise.resolve();if(s&&s.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),l=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));o=Promise.allSettled(s.map(d=>{if(d=a0(d),d in Ku)return;Ku[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":o0,u||(h.as="script"),h.crossOrigin="",h.href=d,l&&h.setAttribute("nonce",l),document.head.appendChild(h),u)return new Promise((p,b)=>{h.addEventListener("load",p),h.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${d}`)))})}))}function a(i){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=i,window.dispatchEvent(l),!l.defaultPrevented)throw i}return o.then(i=>{for(const l of i||[])l.status==="rejected"&&a(l.reason);return t().catch(a)})};let qu=!1;const hf=c.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:s,fontSize:r=13,readOnly:o=!1,sizingMode:a="measured"},i)=>{const l=c.useRef(null),[d,u]=c.useState(null),m=c.useRef([]),h=c.useRef(!1),p=c.useRef(!1),b=c.useRef(!1),f=c.useRef(!1),x=()=>{const g=l.current;if(g){h.current&&(g.clear(),h.current=!1);for(const w of m.current)g.write(w.data,w.onProcessed);m.current=[],p.current&&(g.fit(),p.current=!1),b.current&&(g.bumpResize(),b.current=!1),f.current&&(g.scrollToTop(),f.current=!1)}};return c.useImperativeHandle(i,()=>({write:(g,w)=>{l.current?l.current.write(g,w):m.current.push({data:g,onProcessed:w})},clear:()=>{l.current?l.current.clear():(m.current=[],h.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(m.current=[],h.current=!0)},resize:(g,w)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(g,w)},fit:()=>{l.current?l.current.fit():p.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():b.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():f.current=!0},getSelection:()=>{var g,w;return((w=(g=l.current)==null?void 0:g.getSelection)==null?void 0:w.call(g))||""},getVisibleText:()=>{var g,w;return((w=(g=l.current)==null?void 0:g.getVisibleText)==null?void 0:w.call(g))||""}}),[]),c.useEffect(()=>{d&&x()},[d]),c.useEffect(()=>{let g=!1;return hr(()=>import("./terminal-dI1yRint.js"),__vite__mapDeps([0,1,2])).then(w=>{qu||(qu=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),g||u(()=>w.GhosttyTerminalView)}).catch(w=>{console.error("[CliTerminal] failed to load terminal renderer",w)}),()=>{g=!0}},[]),d?n.jsx(d,{ref:l,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"}})});hf.displayName="CliTerminal";function ct(...e){return Zx(ey(e))}const i0={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},c0={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},hn=c.forwardRef(function({radius:t="xl",padding:s="md",className:r,...o},a){return n.jsx("div",{ref:a,className:ct("border border-border-subtle bg-bg-secondary",i0[t],c0[s],r),...o})});function dc({label:e,value:t,sub:s,icon:r}){return n.jsxs(hn,{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 pf({title:e,description:t,confirmLabel:s,cancelLabel:r,tone:o="default",busy:a=!1,onConfirm:i,onCancel:l}){const{t:d}=he("common");c.useEffect(()=>{const m=h=>{h.key==="Escape"&&l()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[l]);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&&l()},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:l,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 An.createPortal(u,document.body)}function ff(e){if(!e||typeof e!="object")return;const t=e;return"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Tr(){const[e,t]=c.useState(null),s=c.useRef(null),r=c.useCallback(i=>{t(null);const l=s.current;s.current=null,l==null||l(i)},[]),o=c.useCallback(i=>new Promise(l=>{var d;(d=s.current)==null||d.call(s,!1),s.current=l,t(i)}),[]);c.useEffect(()=>()=>{var i;(i=s.current)==null||i.call(s,!1)},[]);const a=e?n.jsx(pf,{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 zu({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,l=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:l}})})]}):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, ${l}, ${l}cc)`}})}),o&&n.jsx("div",{className:"text-3xs text-text-muted mt-0.5",children:o})]})}function l0({cursorPos:e,viewportRef:t,imgRef:s}){var S;if(!e||!s.current)return null;const r=s.current,o=r.getBoundingClientRect(),a=(S=t.current)==null?void 0:S.getBoundingClientRect();if(!a)return null;const i=r.naturalWidth||o.width,l=r.naturalHeight||o.height,d=i/l,u=o.width/o.height;let m,h,p,b;d>u?(m=o.width,h=o.width/d,p=0,b=(o.height-h)/2):(h=o.height,m=o.height*d,p=(o.width-m)/2,b=0);const f=o.left-a.left+p+m*e.nx,x=o.top-a.top+b+h*e.ny,g=Math.max(8,Math.min(a.width-8,f)),w=Math.max(8,Math.min(a.height-8,x));return n.jsxs("div",{style:{position:"absolute",left:g-8,top:w-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 uc(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function d0({inputMode:e,onToggleInputMode:t,isImeOpen:s,setIsImeOpen:r,isMenuOpen:o,setIsMenuOpen:a,imeText:i,setImeText:l,handleImeSubmit:d,isConnActive:u,zoom:m,isMobile:h,mobileFillZoom:p,onZoomOut:b,onZoomReset:f,onZoomIn:x,transportType:g,screenshotUsage:w,lastActionStatus:S}){const{t:C}=he("common");return n.jsxs(n.Fragment,{children:[n.jsxs("div",{onTouchStart:j=>j.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:uc(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(Qp,{size:14}):n.jsx(Dw,{size:14})}),n.jsx("span",{className:`text-3xs font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:C(e==="mouse"?"remote.mouse":"remote.touch")})]}),n.jsxs("div",{className:"relative",children:[n.jsx("div",{role:"button",tabIndex:0,onClick:()=>{r(j=>!j),a(!1)},onKeyDown:uc(()=>{r(j=>!j),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(Gp,{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:C("remote.typeAndEnter"),value:i,autoFocus:!0,onTouchStart:j=>j.stopPropagation(),onChange:j=>l(j.target.value),onKeyDown:j=>{d(j)},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(j=>!j),r(!1)},onKeyDown:uc(()=>{a(j=>!j),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(_r,{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:C(u?"remote.connected":"remote.ws")})]}),m>1&&n.jsxs("span",{className:"text-5xs font-bold text-indigo-400",children:[Math.round(m*100),"%"]}),g==="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:C("remote.directP2PTitle"),children:C("remote.direct")}),g==="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:C("remote.turnRelayTitle"),children:C("remote.relay")}),w&&w.dailyBudgetMinutes>0&&n.jsx("span",{className:"text-5xs font-bold px-1 py-0.5 rounded",style:{color:w.budgetExhausted?"#ef4444":"#c4b5fd",background:w.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:C("remote.dailyTurnTitle"),children:w.budgetExhausted?C("remote.turnBlocked"):C("remote.turnUsage",{used:w.dailyUsedMinutes,budget:w.dailyBudgetMinutes})}),S&&n.jsx("span",{className:"text-5xs text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:S})]})]}),o&&n.jsxs("div",{onTouchStart:j=>j.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:C("remote.settings")}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[n.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:[C("remote.zoom")," ",m<=(h?p:1)+.01?C(h?"remote.fill":"remote.fit"):`${Math.round(m*100)}%`]}),n.jsxs("div",{style:{display:"flex",gap:4},children:[n.jsx("button",{onClick:j=>{j.stopPropagation(),b()},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:j=>{j.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:C(h?"remote.fill":"remote.fit")}),n.jsx("button",{onClick:j=>{j.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 u0({waitingLabel:e,waitingHint:t,transportType:s}){const{t:r}=he("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 m0({connState:e,onRetry:t}){const{t:s}=he("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(en,{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(Ar,{size:13}),s("remote.error.retry")]})]})}function h0(){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 Io(e,t){const s=c.useRef(null),r=c.useRef(0);c.useEffect(()=>{if(!h0())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,l])=>[i,Vu(l)]))}),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 p0({containerRef:e,viewportRef:t,imgRef:s,inputMode:r,setInputMode:o,minZoom:a,zoomRef:i,panXRef:l,panYRef:d,setPanX:u,setPanY:m,setZoom:h,lastWheelTimeRef:p,onAction:b,setLastActionStatus:f,spawnRippleFromNormalized:x,clampPan:g,isMobile:w,mobileFillZoom:S}){const[C,j]=c.useState(null),v=c.useRef(null),y=c.useRef(null),N=c.useRef(null),k=c.useRef(!1),A=c.useRef(null),E=c.useRef(0),P=c.useRef(null),T=c.useRef(1),M=c.useRef({x:0,y:0}),_=c.useRef(!1),I=c.useRef(r),D=c.useRef(b),L=30,$=550,U=18,J=60,K=400,R=12,O=()=>{if(v.current)return;const q={nx:.5,ny:.5};v.current=q,j(q)};return c.useEffect(()=>{I.current=r,r==="mouse"&&O()},[r]),c.useEffect(()=>{D.current=b},[b]),c.useEffect(()=>{const q=e.current;if(!q)return;const W=ne=>{if(!s.current)return null;const ae=s.current.getBoundingClientRect();return!ae.width||!ae.height?null:{nx:Math.max(0,Math.min(1,(ne.clientX-ae.left)/ae.width)),ny:Math.max(0,Math.min(1,(ne.clientY-ae.top)/ae.height))}},ce=(ne,ae)=>{if(!s.current)return{dnx:0,dny:0};const ee=s.current,oe=ee.getBoundingClientRect(),Ce=ee.naturalWidth||oe.width,Q=ee.naturalHeight||oe.height,z=Ce/Q,X=oe.width/oe.height;let pe,Pe;return z>X?(pe=oe.width,Pe=oe.width/z):(Pe=oe.height,pe=oe.height*z),{dnx:ne/pe,dny:ae/Pe}},ye=(ne,ae,ee)=>{if(ee<=1.05)return;const oe=-(ne-.5)*100,Ce=-(ae-.5)*100,Q=g(oe,Ce,ee);(Math.abs(Q.x-l.current)>.1||Math.abs(Q.y-d.current)>.1)&&(u(Q.x),m(Q.y),l.current=Q.x,d.current=Q.y)},G=ne=>{const ae=t.current;if(ae&&ne.target instanceof Node&&ae.contains(ne.target))ne.preventDefault();else return;if(ne.touches.length===1){const ee=ne.touches[0];y.current={x:ee.clientX,y:ee.clientY,time:Date.now()},N.current={x:ee.clientX,y:ee.clientY},_.current||(k.current=!1),A.current=setTimeout(()=>{if(!k.current&&!_.current)if(k.current=!0,I.current==="mouse"){const oe=v.current||{nx:.5,ny:.5};f("Right Click"),x(oe.nx,oe.ny,"right"),D.current("input_click",{...oe,button:"right"}).catch(()=>{})}else{const oe=W(ee);oe&&(f("Right Click"),x(oe.nx,oe.ny,"right"),D.current("input_click",{...oe,button:"right"}).catch(()=>{}))}},500);return}if(ne.touches.length===2){A.current&&clearTimeout(A.current),k.current=!0,_.current=!0;const ee=ne.touches[1].clientX-ne.touches[0].clientX,oe=ne.touches[1].clientY-ne.touches[0].clientY;P.current=Math.sqrt(ee*ee+oe*oe),T.current=i.current,M.current={x:(ne.touches[0].clientX+ne.touches[1].clientX)/2,y:(ne.touches[0].clientY+ne.touches[1].clientY)/2}}},Se=ne=>{const ae=t.current;if(ae&&ne.target instanceof Node&&ae.contains(ne.target)&&ne.preventDefault(),ne.touches.length===1&&N.current){const ee=ne.touches[0],oe=ee.clientX-N.current.x,Ce=ee.clientY-N.current.y;if(!k.current&&y.current){const Q=ee.clientX-y.current.x,z=ee.clientY-y.current.y;Math.sqrt(Q*Q+z*z)>8&&(k.current=!0,A.current&&clearTimeout(A.current))}if(k.current)if(I.current==="mouse"){const Q=ce(oe,Ce),z=v.current||{nx:.5,ny:.5},X=Math.max(0,Math.min(1,z.nx+Q.dnx)),pe=Math.max(0,Math.min(1,z.ny+Q.dny));v.current={nx:X,ny:pe},j({nx:X,ny:pe}),f(`Cursor: ${Math.round(X*100)}%, ${Math.round(pe*100)}%`),ye(X,pe,i.current);const Pe=Date.now();Pe-p.current>=30&&(p.current=Pe,D.current("input_mouseMoved",{nx:X,ny:pe}).catch(()=>{}))}else if(i.current>1){const Q=t.current;if(Q){const z=Q.clientWidth,X=Q.clientHeight,pe=l.current+oe/z*100,Pe=d.current+Ce/X*100,Oe=g(pe,Pe,i.current);u(Oe.x),m(Oe.y),l.current=Oe.x,d.current=Oe.y}}else{const Q=W(ee);if(Q){const z=Date.now();z-p.current>=40&&(p.current=z,f("Scroll"),D.current("input_wheel",{nx:Q.nx,ny:Q.ny,deltaX:Math.round(-oe*2.5),deltaY:Math.round(-Ce*2.5)}).catch(()=>{}))}}N.current={x:ee.clientX,y:ee.clientY};return}if(ne.touches.length===2&&P.current!==null){const ee=ne.touches[1].clientX-ne.touches[0].clientX,oe=ne.touches[1].clientY-ne.touches[0].clientY,Q=Math.sqrt(ee*ee+oe*oe)/P.current,z=(ne.touches[0].clientX+ne.touches[1].clientX)/2,X=(ne.touches[0].clientY+ne.touches[1].clientY)/2,pe=z-M.current.x,Pe=X-M.current.y,Oe=Math.abs(Q-1)>.03;if(I.current==="mouse"){if(Oe){const Le=Math.max(a,Math.min(5,T.current*Q));h(Le),i.current=Le}else if(Math.abs(pe)>2||Math.abs(Pe)>2){const Le=v.current||{nx:.5,ny:.5},ke=Date.now();ke-p.current>=30&&(p.current=ke,f("Scroll"),D.current("input_wheel",{nx:Le.nx,ny:Le.ny,deltaX:Math.round(-pe*3),deltaY:Math.round(-Pe*3)}).catch(()=>{}))}}else{const Le=Math.max(a,Math.min(5,T.current*Q));h(Le),i.current=Le;const ke=t.current;if(ke&&Le>1){const Y=ke.clientWidth,ve=ke.clientHeight,Z=l.current+pe/Y*100,ie=d.current+Pe/ve*100,F=g(Z,ie,Le);u(F.x),m(F.y),l.current=F.x,d.current=F.y}}M.current={x:z,y:X}}},ue=ne=>{var ae;if(A.current&&clearTimeout(A.current),P.current=null,ne.touches.length===1&&_.current){const ee=ne.touches[0];y.current={x:ee.clientX,y:ee.clientY,time:Date.now()},N.current={x:ee.clientX,y:ee.clientY},k.current=!0;return}if(ne.touches.length===0){if(_.current){_.current=!1,k.current=!1;return}if(ne.changedTouches.length===1){const ee=ne.changedTouches[0],oe=Date.now(),Ce=oe-(((ae=y.current)==null?void 0:ae.time)||0),Q=y.current?ee.clientX-y.current.x:0,z=y.current?ee.clientY-y.current.y:0,X=Math.sqrt(Q*Q+z*z);if(I.current==="mouse"){if(Ce<L||Ce>$||X>U){k.current=!1;return}const pe=v.current||W(ee);pe&&(f(`Click: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),x(pe.nx,pe.ny,"left"),D.current("input_click",{...pe}).catch(()=>{}))}else{if(k.current){k.current=!1;return}if(Ce<J||Ce>K||X>R){k.current=!1;return}const pe=W(ee);if(!pe)return;oe-E.current<300?(f("Double tap"),x(pe.nx,pe.ny,"double"),D.current("input_click",{...pe,clickCount:2}).catch(()=>{}),E.current=0):(f(`Tap: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),x(pe.nx,pe.ny,"left"),D.current("input_click",{...pe}).catch(()=>{}),E.current=oe)}}k.current=!1}};return q.addEventListener("touchstart",G,{passive:!1}),q.addEventListener("touchmove",Se,{passive:!1}),q.addEventListener("touchend",ue,{passive:!1}),()=>{q.removeEventListener("touchstart",G),q.removeEventListener("touchmove",Se),q.removeEventListener("touchend",ue),A.current&&clearTimeout(A.current)}},[e,t,s,a,i,l,d,u,m,h,p,f,x,g]),{cursorPos:C,cursorPosRef:v,handleToggleInputMode:()=>{o(q=>{const W=q==="touch"?"mouse":"touch";return W==="mouse"&&O(),W})},handleZoomReset:()=>{const q=w?S:1;h(q),i.current=q,u(0),m(0),l.current=0,d.current=0}}}const f0=15e3;function bf({onAction:e,addLog:t,connState:s,connScreenshot:r,screenshotUsage:o,transportType:a,onRetry:i}){const{t:l}=he("common"),d=c.useRef(null),u=c.useRef(null),m=c.useRef(null),[h,p]=c.useState(null),[b,f]=c.useState(""),[,x]=c.useState(!1),[g,w]=c.useState(!1),[S,C]=c.useState(!1),[j,v]=c.useState([]),y=c.useRef(0),N=c.useRef(new Set),[k,A]=c.useState(!1),[E,P]=c.useState(!1),T=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[M,_]=c.useState(T?"mouse":"touch"),[I,D]=c.useState(1),L=c.useRef(!1),[$,U]=c.useState(1),[J,K]=c.useState(0),[R,O]=c.useState(0);Io("RemoteView",{connState:s,hasScreenshot:!!r,inputMode:M,zoom:$,panX:J,panY:R,isMenuOpen:k,isImeOpen:E});const H=c.useRef(0),B=c.useRef($),q=c.useRef(J),W=c.useRef(R);c.useEffect(()=>{B.current=$},[$]),c.useEffect(()=>{q.current=J},[J]),c.useEffect(()=>{W.current=R},[R]),c.useEffect(()=>{var Y;(Y=d.current)==null||Y.focus()},[]),c.useEffect(()=>{s!=="connected"&&w(!1)},[s]),c.useEffect(()=>{if(s==="connected"){C(!1);return}C(!1);const Y=setTimeout(()=>C(!0),f0);return()=>clearTimeout(Y)},[s]);const ce=s==="connected",ye=r,G=s==="failed"||s==="disconnected"&&S,Se=l(ce?"remote.waiting.connectedLabel":s==="connecting"?"remote.waiting.connectingLabel":"remote.waiting.reconnectingLabel"),ue=l(ce?"remote.waiting.connectedHint":"remote.waiting.reconnectingHint");c.useEffect(()=>{if(!T||L.current||!ye)return;const Y=m.current,ve=u.current;if(!Y||!ve)return;const Z=()=>{const ie=ve.clientWidth,F=ve.clientHeight,se=Y.naturalWidth,me=Y.naturalHeight;if(!se||!me||!ie||!F)return;const re=Math.min(ie/se,F/me),V=Math.max(ie/se,F/me)/re;V>1.01&&(D(V),U(V),B.current=V),L.current=!0};if(Y.complete&&Y.naturalWidth){Z();return}return Y.addEventListener("load",Z,{once:!0}),()=>Y.removeEventListener("load",Z)},[ye,T]);const ne=.5;c.useEffect(()=>{$<=ne&&(K(0),O(0))},[$,ne]);const ae=(Y,ve,Z)=>{if(Z<=ne)return{x:0,y:0};const ie=(Z-1)/(2*Z)*100,F=(Z-1)/(2*Z)*100;return{x:Math.max(-ie,Math.min(ie,Y)),y:Math.max(-F,Math.min(F,ve))}},ee=(Y,ve)=>{if(!m.current)return null;const Z=m.current.getBoundingClientRect();return!Z.width||!Z.height?null:{nx:Math.max(0,Math.min(1,(Y-Z.left)/Z.width)),ny:Math.max(0,Math.min(1,(ve-Z.top)/Z.height))}},oe=Y=>{const ve=setTimeout(()=>{N.current.delete(ve),v(Z=>Z.filter(ie=>ie.id!==Y))},600);N.current.add(ve)};c.useEffect(()=>{const Y=N.current;return()=>{for(const ve of Y)clearTimeout(ve);Y.clear()}},[]);const Ce=(Y,ve,Z)=>{const ie=u.current;if(!ie)return;const F=ie.getBoundingClientRect(),se=++y.current;v(me=>[...me,{id:se,x:Y-F.left,y:ve-F.top,type:Z}]),oe(se)},Q=(Y,ve,Z)=>{const ie=m.current,F=u.current;if(!ie||!F)return;const se=ie.getBoundingClientRect(),me=F.getBoundingClientRect(),re=ie.naturalWidth||se.width,we=ie.naturalHeight||se.height,V=re/we,de=se.width/se.height;let ge,Ie,Ke,Ae;V>de?(ge=se.width,Ie=se.width/V,Ke=0,Ae=(se.height-Ie)/2):(Ie=se.height,ge=se.height*V,Ke=(se.width-ge)/2,Ae=0);const Ne=se.left-me.left+Ke+ge*Y,He=se.top-me.top+Ae+Ie*ve,Fe=++y.current;v(it=>[...it,{id:Fe,x:Ne,y:He,type:Z}]),oe(Fe)},z=async Y=>{var Z;const ve=ee(Y.clientX,Y.clientY);if(ve){p(`Click: ${Math.round(ve.nx*100)}%, ${Math.round(ve.ny*100)}%`),(Z=d.current)==null||Z.focus(),w(!0);try{const ie=await e("input_click",{nx:ve.nx,ny:ve.ny});if(!(ie!=null&&ie.success)){t(`❌ Click failed: ${ie==null?void 0:ie.error}`);return}Ce(Y.clientX,Y.clientY,"left")}catch(ie){t(`❌ Click error: ${ie.message||ie}`)}}},X=async(Y,ve,Z,ie=0)=>{try{await e("input_key",{type:Z?"char":"keyDown",key:Y,code:ve,text:Z?Y:void 0,unmodifiedText:Z?Y:void 0,modifiers:ie})}catch(F){t(`❌ Key error: ${F.message||F}`)}},pe=async Y=>{if(Y.target.tagName==="INPUT"||!g||Y.key==="Escape")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter"].includes(Y.key)&&Y.preventDefault();let Z=0;Y.altKey&&(Z|=1),Y.ctrlKey&&(Z|=2),Y.metaKey&&(Z|=4),Y.shiftKey&&(Z|=8),p(`Key: ${Y.key}`),await X(Y.key,Y.code,Y.key.length===1,Z)},Pe=async Y=>{if(Y.key==="Enter"){if(Y.nativeEvent.isComposing)return;if(b){const ve=b;f(""),p(`IME Sent: ${ve}`);try{const Z=await e("input_type",{text:ve});Z!=null&&Z.success||t(`❌ IME error: ${Z==null?void 0:Z.error}`)}catch(Z){t(`❌ IME error: ${Z.message}`)}}else p("Key: Enter"),await X("Enter","Enter",!1)}};c.useEffect(()=>{const Y=d.current;if(!Y)return;const ve=Z=>{var ie;if((ie=m.current)!=null&&ie.contains(Z.target)){Z.preventDefault();const F=Date.now();if(F-H.current<40)return;H.current=F;const se=ee(Z.clientX,Z.clientY);if(!se)return;p(`Scroll: ${Math.round(Z.deltaY)}`),e("input_wheel",{nx:se.nx,ny:se.ny,deltaX:Math.round(Z.deltaX),deltaY:Math.round(Z.deltaY)}).catch(()=>{})}};return Y.addEventListener("wheel",ve,{passive:!1}),()=>Y.removeEventListener("wheel",ve)},[e]);const{cursorPos:Oe,handleToggleInputMode:Le,handleZoomReset:ke}=p0({containerRef:d,viewportRef:u,imgRef:m,inputMode:M,setInputMode:_,minZoom:ne,zoomRef:B,panXRef:q,panYRef:W,setPanX:K,setPanY:O,setZoom:U,lastWheelTimeRef:H,onAction:e,setLastActionStatus:p,spawnRippleFromNormalized:Q,clampPan:ae,isMobile:T,mobileFillZoom:I});return n.jsxs("div",{ref:d,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:pe,onContextMenu:Y=>Y.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:[G?n.jsx(m0,{connState:s,onRetry:i}):ye?n.jsx("img",{ref:m,src:ye,alt:l("remote.screenshotAlt"),style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${$}) translate(${J}%, ${R}%)`,transformOrigin:"center center",cursor:M==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:z,onContextMenu:Y=>Y.preventDefault(),onDragStart:Y=>Y.preventDefault()}):n.jsx(u0,{waitingLabel:Se,waitingHint:ue,transportType:a}),M==="mouse"&&!G&&ye&&n.jsx(l0,{cursorPos:Oe,viewportRef:u,imgRef:m}),j.map(Y=>{const Z={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[Y.type];return n.jsxs("div",{style:{position:"absolute",left:Y.x,top:Y.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${Z}, 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(${Z}, 0.9)`,boxShadow:`0 0 12px rgba(${Z}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},Y.id)})]}),n.jsx(d0,{inputMode:M,onToggleInputMode:Le,isImeOpen:E,setIsImeOpen:P,isMenuOpen:k,setIsMenuOpen:A,imeText:b,setImeText:f,handleImeSubmit:Pe,isConnActive:ce,zoom:$,isMobile:T,mobileFillZoom:I,onZoomOut:()=>U(Y=>Math.max(.5,Y-.25)),onZoomReset:ke,onZoomIn:()=>U(Y=>Math.min(5,Y+.25)),transportType:a,screenshotUsage:o,lastActionStatus:h}),n.jsx("style",{children:`
15
- @keyframes slideUp {
16
- from { opacity: 0; transform: translateY(6px); }
17
- to { opacity: 1; transform: translateY(0); }
18
- }
19
- @keyframes slideUpSidebar {
20
- from { opacity: 0; transform: translateY(6px); }
21
- to { opacity: 1; transform: translateY(0); }
22
- }
23
- @keyframes click-ripple-ring {
24
- 0% { transform: scale(0.3); opacity: 1; }
25
- 100% { transform: scale(2.2); opacity: 0; }
26
- }
27
- @keyframes click-ripple-dot {
28
- 0% { transform: scale(1); opacity: 0.9; }
29
- 50% { transform: scale(1.8); opacity: 0.6; }
30
- 100% { transform: scale(0.5); opacity: 0; }
31
- }
32
- @keyframes remote-float {
33
- 0% { transform: translateY(0px); }
34
- 50% { transform: translateY(-7px); }
35
- 100% { transform: translateY(0px); }
36
- }
37
- `})]})}function vl(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 b0(e){var t;return vl(e.activeInteractivePrompt)||vl((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function g0(e){return e.sessionId||e.instanceId||e.id}function x0(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=b0(a);if(!i)continue;const l=g0(a);if(r&&r!==l&&r!==a.id||!o&&a.surfaceHidden===!0)continue;return{daemonId:a.daemonId||a.id.split(":")[0]||a.id,sessionId:l,routeId:a.id,providerType:a.type,title:a.title||a.cliName||a.type,prompt:i}}return null}function gf(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))),l=(r=a.freeformText)==null?void 0:r.trim();s[o.questionId]={selectedLabels:i,...l?{freeformText:l}:{}}}return{promptId:e.promptId,answers:s}}function Un({children:e}){return typeof document>"u"?n.jsx(n.Fragment,{children:e}):An.createPortal(e,document.body)}function y0(e,t){const s=r=>{r.key==="Escape"&&(r.stopPropagation(),t())};return e.addEventListener("keydown",s,!0),()=>e.removeEventListener("keydown",s,!0)}const Gu='a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',v0=200;function Yu(e){const t={};for(const s of(e==null?void 0:e.prompt.questions)||[])t[s.questionId]={selectedLabels:[],freeformText:""};return t}function Qu(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 w0({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(yi,{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 Nd({promptSession:e,isSubmitting:t=!1,error:s,onSubmit:r,onCancel:o}){const{t:a}=he("common"),[i,l]=c.useState(()=>Yu(e)),[d,u]=c.useState(!1),m=c.useRef(!1),h=c.useRef(null),p="interactive-prompt-title";c.useEffect(()=>{if(l(Yu(e)),u(!1),m.current=!1,!(e==null?void 0:e.prompt.promptId))return;const A=setTimeout(()=>{m.current=!0,u(!0)},v0);return()=>clearTimeout(A)},[e==null?void 0:e.prompt.promptId]),c.useEffect(()=>{if(e)return y0(window,o)},[e,o]);const b=e==null?void 0:e.prompt.promptId,f=e==null?void 0:e.sessionId,x=e==null?void 0:e.daemonId;c.useEffect(()=>{if(!b)return;const k=h.current;if(!k)return;const A=()=>Array.from(k.querySelectorAll(Gu)),E=P=>{if(P.key!=="Tab")return;const T=A();if(T.length===0)return;const M=T[0],_=T[T.length-1],I=document.activeElement;P.shiftKey?(I===M||!k.contains(I))&&(P.preventDefault(),_.focus()):(I===_||!k.contains(I))&&(P.preventDefault(),M.focus())};return k.addEventListener("keydown",E),()=>k.removeEventListener("keydown",E)},[b,f,x]),c.useEffect(()=>{if(!b)return;const k=h.current;if(!k)return;const A=document.activeElement;if(A instanceof Node&&k.contains(A))return;(Array.from(k.querySelectorAll(Gu))[0]||k).focus()},[b,f,x]);const g=(e==null?void 0:e.prompt.questions)||[],w=g.length===1,S=c.useMemo(()=>e?e.prompt.questions.every(k=>Qu(k,i[k.questionId])):!1,[e,i]),C=c.useMemo(()=>g.filter(k=>!Qu(k,i[k.questionId])).length,[g,i]);if(!e)return null;const j=(k,A)=>{l(E=>{const P=E[k.questionId]||{selectedLabels:[]},T=P.selectedLabels||[],M=k.multiSelect?T.includes(A)?T.filter(_=>_!==A):[...T,A]:[A];return{...E,[k.questionId]:{...P,selectedLabels:M}}})},v=(k,A)=>{l(E=>({...E,[k]:{...E[k]||{selectedLabels:[]},freeformText:A}}))},y=()=>{!S||t||!m.current||r(i)},N=gf(e.prompt,i);return n.jsx(Un,{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(en,{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(Et,{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:[g.map((k,A)=>{var T,M;const E=((T=N.answers[k.questionId])==null?void 0:T.selectedLabels)||[],P=k.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:[k.header&&n.jsx("span",{className:"text-xs font-semibold uppercase tracking-normal text-text-muted",children:k.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:P})]}),n.jsxs("div",{className:"mt-1 text-sm font-semibold text-text-primary",children:[w?"":`${A+1}. `,k.question]}),k.multiSelect&&k.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:k.multiSelect?"group":"radiogroup","aria-label":k.question,children:k.options.map(_=>n.jsx(w0,{label:_.label,description:_.description||_.preview,selected:E.includes(_.label),multiSelect:k.multiSelect,disabled:t,onClick:()=>j(k,_.label)},_.label))}),k.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:((M=i[k.questionId])==null?void 0:M.freeformText)||"",disabled:t,onChange:_=>v(k.questionId,_.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"})]})]},k.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:[!S&&C>0&&n.jsx("span",{className:"mr-auto text-xs text-text-muted",children:a("interactivePrompt.answersRequired",{count:C})}),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:y,disabled:!S||t||!d,children:a(t?"interactivePrompt.submitting":"interactivePrompt.submit")})]})]})})})}function sn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var xf=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress"];sn(xf);var S0=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];sn(S0);var k0=["p2p_offer","p2p_ice"];sn(k0);var j0=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];sn(j0);var N0=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","daemon_mesh_command","p2p_offer","p2p_ice"];sn(N0);var C0=["auth_ok","auth_error","machine_evicted","force_disconnect","token_revoked","version_mismatch","force_update_required","command","agent_command","resolve_action","daemon_mesh_result","p2p_ready","p2p_offer","p2p_answer","p2p_ice","mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];sn(C0);var _0=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],A0=[...xf,..._0];sn(A0);var T0=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];sn(T0);var I0=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];sn(I0);var M0=["p2p_ready","p2p_answer","p2p_ice"];sn(M0);var R0=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];sn(R0);var P0=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];sn(P0);var yf=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];sn(yf);var vf=["ping","pong","p2p_evicted","status_event","topic_update","topic_update_chunk","session_output","session_output_chunk","session_io_error","command_result","command_result_chunk","response","transcript_topics_available"];sn(vf);[...new Set([...yf,...vf])];var wf=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"],E0={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"},L0=new Set(wf);function D0(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return L0.has(t)?t:E0[t]??null}var O0=["pending","assigned","completed","failed","cancelled"],$0=["completed","failed","cancelled"],F0=["code_change","validation","live_debug_readonly","launch_app","convergence"],H0=["low","normal","high"],B0=["when_idle","interrupt"],Sf=["completed","blocked","failed"],W0=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function Ir(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Ir(O0);Ir($0);Ir(F0);Ir(H0);Ir(B0);Ir(Sf);var U0=["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"],K0=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(K0);var q0=["projects","project_status","project_send","project_read","project_add","discover_repos","memory","skill_view","skill_manage","project_note"];new Set(q0);var z0=["mesh_queue","mesh_direct","plain"],V0=["delivered","queued"],G0=["local","p2p"],Y0=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],Q0=["default","native_source"],J0=["restart","live_holder"],X0=["approval","choice"],Z0=["approved","rejected","answered"],ek=["modal_button","auto_approve","prompt_answer"],tk=["genuine","weak"],nk=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],sk=["completed","aborted"],rk=["alive","unknown","read_failed","dead"],Ju=["auth_failed","billing_failed"],ok=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],ak=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],ik=["completed","failed"],ck=["operator_update","refine_terminal","validation_terminal"],lk=["delivered","queued","duplicate"],dk=[...wf,"unknown"],uk=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],mk=["completed","failed","cancelled"],hk=["genuine","weak","tool_report","operator"],pk=["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"],kf=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],Zs={t:"id"},er={t:"id",optional:!0},cs={t:"bool"},Vo={t:"bool",optional:!0},Xu={t:"ms"},fk={t:"ms",optional:!0},Go={t:"int",optional:!0},Rt=e=>({t:"enum",values:e}),tr=e=>({t:"enum",values:e,optional:!0}),bk={dispatch_accepted:{scope:Rt(z0),messageId:Zs,meshId:er,nodeId:er,providerType:er,attemptNo:Go,dispatchNonce:Go,consumeProfile:tr(Q0),maxTaskRetries:Go,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:Zs,outcome:Rt(V0),via:Rt(G0)},delivery_refused:{messageId:Zs,reason:Rt(U0)},dispatch_failed:{workerAbsent:cs,reason:Rt(Y0),refusalCode:er},duplicate_dispatch_refusal:{holderSessionId:Zs,holderAttemptId:er},session_rebound:{toSessionId:Zs,reason:Rt(J0)},turn_started:{retro:cs},suspension:{modal:Rt(X0),modalKey:er},suspension_resolved:{resolution:Rt(Z0),via:Rt(ek)},turn_end:{strength:Rt(tk),afterFinalizationTimeout:Vo,hollow:Vo,summary:{t:"summary_ref",optional:!0},blockReason:tr(nk),releasedByHardCap:Vo,nativeOutcome:tr(sk),live:{t:"live",optional:!0},reportExpected:Vo,providerFailure:tr(Ju)},transcript_final:{selfAttributing:cs,nativeRead:cs,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:fk},transcript_activity:{newestActivityAt:Xu},no_progress:{stalledMs:Xu,observedStatus:Rt(dk),finalAssistantPresent:cs},liveness:{result:Rt(rk)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:tr(Ju)},session_error:{reason:Rt(ok)},worker_report:{outcome:Rt(Sf),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:cs,branchState:tr(W0),touchedFileCount:Go},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:cs,commitsSinceDispatch:{t:"int"},attributable:cs},cancel:{reason:Rt(ak)},operator_status:{status:Rt(ik),reason:Rt(ck)},coordinator_ack:{notify:Rt(kf),outcome:Rt(lk)},hold_expired:{holdId:Zs,reason:Rt(uk)}},gk=Object.keys(bk);function Mo(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Mo(gk);Mo(pk);Mo(kf);Mo(mk);Mo(hk);function ts(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var xk=["applied","recorded","rejected"];ts(xk);var yk=["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(yk);var vk=["completed","failed"];ts(vk);var wk=["operator_update","refine_terminal","validation_terminal"];ts(wk);var Sk=["own","fleet"];ts(Sk);var kk=["active","paused","completed","abandoned"];ts(kk);var jk=["provider_quirk","pattern_to_avoid","recovery_lesson"];ts(jk);var Nk=["coordinator","unknown"];ts(Nk);var Ck=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];ts(Ck);var _k=["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_batch","queue_cancel","queue_requeue","direct_dispatch_record","active_work_query","recovery_context_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];ts(_k);function Ak(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Zt(e,t){return Ak(t==null?void 0:t.activeModal)?"waiting_approval":D0(e)??"idle"}function wl(e){return Zt(e)==="generating"}function Zu(e,t){return Zt(e,t)==="waiting_approval"}function Tk(e){return(e==null?void 0:e.surfaceHidden)===!0}function Ik(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 Ss(e){const t=e.connectionState==="failed"||e.connectionState==="closed",s=e.connectionState==="connecting"||e.connectionState==="new",r=fi(e.status),o=Zt(e.status),a=o==="waiting_approval",i=o==="waiting_choice",l=By(o);return{isReconnecting:t,isConnecting:s,isGenerating:r,isWaiting:a,isWaitingChoice:i,isErrored:l}}function Mk(e){const t=!e.hasLiveSnapshot&&e.visibleMessageCount===0,{isGenerating:s}=Ss(e),r=s&&(!t||Zt(e.status)==="generating");return{awaitingFirstView:t,showWorkingIndicator:r}}function Us(e){return Ss(e).isGenerating}function Rk(e){let t=0;for(const s of e)Us(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 Pk(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 jf(e){const t=new Map,s=new Map,r=(o,a)=>{if(!o)return;const i=s.get(o),l=t.get(o),d=(a.lastUpdated||0)>((i==null?void 0:i.lastUpdated)||0),u=tm(l==null?void 0:l.surfaceHidden,typeof a.surfaceHidden=="boolean"?a.surfaceHidden:void 0,d),m=tm(l==null?void 0:l.muted,typeof a.muted=="boolean"?a.muted:void 0,d);if(i&&!Pk(i,a)){l&&t.set(o,{...l,surfaceHidden:u,muted:m});return}s.set(o,a),t.set(o,{sessionId:o,...Ik(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 ys(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 ji(e,t,s){const r=ys(e,t),o=Ss(e),a=o.isReconnecting,i=o.isConnecting,l=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"||l,b=!!(r.inboxBucket==="task_complete"&&r.unread&&!(s!=null&&s.hideOpenTaskCompleteUnread&&(s!=null&&s.isOpenConversation)));return{unread:b,requiresAction:m,isWorking:h,isReconnecting:a,isConnecting:i,isGenerating:l,isWaiting:d,inboxBucket:m?"needs_attention":h?"working":b?"task_complete":"idle"}}function Ek(e,t,s){return ji(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:s==null?void 0:s.isOpenConversation}).unread}function Lk(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Dk(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 Ok(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 $k({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(!Lk(a))throw new Error(Dk(a));return}await Ok(e.sessionId,t,o)}let Sl=null;const kl=new Set;function Fk(e){return kl.add(e),()=>{kl.delete(e)}}function nm(){return Sl}function Yo(e){if(Sl!==e){Sl=e;for(const t of kl)t()}}function Ni(e,t){const{t:s}=he("common"),{ides:r,isP2PActive:o,p2pStates:a}=yn(),{sendCommand:i}=wt(),l=c.useSyncExternalStore(Fk,nm,nm),[d,u]=c.useState(!1),[m,h]=c.useState(null),p=c.useRef(!1),b=(t==null?void 0:t.includeHidden)===!0,f=c.useMemo(()=>x0(r,{sessionId:e,includeHidden:b}),[r,e,b]),x=!!f,g=c.useMemo(()=>f?f.prompt.promptId===l?null:f:null,[l,f]),w=(f==null?void 0:f.prompt.promptId)??null;c.useEffect(()=>{h(null)},[w]);const S=c.useCallback(async v=>{if(!g||p.current)return;p.current=!0;const y=gf(g.prompt,v);u(!0),h(null);try{const N=(a==null?void 0:a[g.daemonId])==="connected"||o===!0;await $k({promptSession:g,response:y,useP2PCommand:N,sendCommand:i}),Yo(g.prompt.promptId)}catch(N){let k=N instanceof Error?N.message:String(N);throw k.includes(Fy)?(Yo(g.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."})),N):(k.includes($y)&&(k=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(k),N)}finally{u(!1),p.current=!1}},[o,a,g,i]),C=c.useCallback(()=>{g&&Yo(g.prompt.promptId)},[g]),j=c.useCallback(()=>{if(Yo(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:g,hasActivePrompt:x,responseError:m,isSubmitting:d,submit:S,cancel:C,reopen:j}}function Nf(e){return e.sessionId??e.routeId}const mc=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(),Hk=12e3;function Bk(e){return/^always\b|\balways allow\b|\bdon'?t ask again\b|\ballow all\b|^yes,? and allow\b/.test(e)?"always":/^(run|approve|accept|yes|allow)/.test(e)?"primary":/^(reject|deny|delete|remove|abort|no)\b/.test(e)?"danger":"neutral"}function Cf({activeConv:e,onModalButton:t}){const{t:s}=he(),[r,o]=c.useState(null),{hasActivePrompt:a,promptSession:i,reopen:l}=Ni(Nf(e));c.useEffect(()=>{o(null)},[e.modalMessage,e.status,e.connectionState]),c.useEffect(()=>{if(!r)return;const h=setTimeout(()=>o(null),Hk);return()=>clearTimeout(h)},[r]);const d=Ss(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(en,{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(en,{size:14})," ",s("approval.questionPending",{defaultValue:"Question waiting"})]}),n.jsx("button",{onClick:l,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-4 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(en,{size:14})," ",s(r?"approval.processing":"approval.actionRequired")]}),n.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((h,p)=>{const b=mc(h).toLowerCase(),f=Bk(b),x=f==="always",g=f==="primary",w=f==="danger",S=r===h,C=r!==null;return n.jsx("button",{onClick:()=>u(h),disabled:C,title:x?s("approval.alwaysAllowWarning"):void 0,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${g?"font-extrabold":w?"bg-red-500/30 text-white font-semibold":x?"text-white/90 font-semibold":"text-white font-semibold"} ${C&&!S?"opacity-40":"opacity-100"} ${C?"cursor-not-allowed":"cursor-pointer"}`,style:g?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:x?{background:"transparent",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 55%, transparent)"}:w?void 0:{background:"color-mix(in srgb, black 18%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 35%, transparent)"},children:S?n.jsx(vr,{size:12}):x?n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(en,{size:11}),mc(h)]}):mc(h)},p)})})]})]})}const Cd="adhdev_controls_bar_visible",jl="adhdev:controlsbarvisibilitychange";function hc(e){if(!e)return!1;try{return e.getItem(Cd)==="1"}catch{return!1}}function Wk(e,t){if(t)try{t.setItem(Cd,e?"1":"0")}catch{}}function Uk(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(jl,{detail:{visible:e}}))}function _d(){const[e,t]=c.useState(()=>typeof window>"u"?!1:hc(window.localStorage)),s=c.useRef(e),r=c.useCallback((i,l=!0)=>{s.current=i,t(i),typeof window<"u"&&Wk(i,window.localStorage),l&&Uk(i)},[]);c.useEffect(()=>{const i=d=>{const u=d.detail,m=typeof(u==null?void 0:u.visible)=="boolean"?u.visible:hc(window.localStorage);s.current=m,t(m)},l=d=>{if(d.key!==Cd)return;const u=hc(window.localStorage);s.current=u,t(u)};return window.addEventListener(jl,i),window.addEventListener("storage",l),()=>{window.removeEventListener(jl,i),window.removeEventListener("storage",l)}},[]);const o=c.useCallback(i=>{r(i)},[r]),a=c.useCallback(()=>{r(!s.current)},[r]);return{isVisible:e,setVisibility:o,toggleVisibility:a}}const _f=["en","ko","ja","zh-CN","es"],Ds="en",Ns=[{code:"en",label:"English"},{code:"ko",label:"한국어"},{code:"ja",label:"日本語"},{code:"zh-CN",label:"中文(简体)"},{code:"es",label:"Español"}];function Es(e){return typeof e=="string"&&_f.includes(e)}function Kk(e){if(!e)return Ds;const t=e.trim().toLowerCase();if(!t)return Ds;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":Ds}const qk={runFailed:"Couldn't run {{label}}",updateFailed:"Couldn't update {{label}}",loadOptionsFailed:"Couldn't load {{label}} options"},zk={unknown:"Unknown",starting:"Starting",stopped:"Stopped",failed:"Failed",idle:"Idle",generating:"Working",awaitingApproval:"Needs approval"},Vk={label:"Language",select:"Select language"},Gk={copy:"Copy",no:"No",yes:"Yes",diagnostics:"Diagnostics",done:"Done",edit:"Edit",copied:"Copied",copyId:"Copy ID",technicalDetails:"Technical details",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?"},Yk={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"},Qk={details:"Details",label:{success:"Done",warning:"Attention",info:"Update"},dismiss:"Dismiss"},Jk={actionNeeded:"Action needed",taskComplete:"Task complete",markRead:"Mark read",markUnread:"Mark unread",delete:"Delete"},Xk={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"},Zk={header:{moreActions:"More actions",title:"Dashboard",guide:"Dashboard guide",guideOpen:"Open dashboard guide",guideShort:"Guide",openGitStatus:"Open git status",meshGraph:"Mesh graph",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"},assistant:{label:"Assistant",start:"Start assistant",starting:"Starting…",startHint:"Start your personal assistant — a chat that manages your projects and coordinators",startFailed:"Could not start the assistant: {{error}}"},assistantLaunch:{chooseCli:"Choose the assistant's CLI",startWith:"Starts with {{cli}}",noToolLock:"no tool lock",noToolLockHint:"Only the assistant's instructions limit this CLI's tools — it keeps its own shell and file tools",unavailable:"Unavailable: {{reason}}",unsupported:"This CLI can't host the assistant",model:"Model",thinking:"Thinking",defaultOption:"Default",start:"Start assistant"},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 and CLI 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 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 or CLI 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."}}},ej={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"},tj={processing:"PROCESSING...",actionRequired:"ACTION REQUIRED",alwaysAllowWarning:"Grants this permission permanently — future runs will not ask again",questionPending:"QUESTION WAITING",answerQuestion:"Answer the question"},nj={loading:"Loading…",launchModelChanged:"{{from}} → {{to}} (changed)",launchModelSource:{user:"chosen",remembered:"remembered",mesh_slot:"mesh slot",task_override:"task override",provider_default:"default"}},sj={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…",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"},rj={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)"},oj={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",showKey:"Show key events only",showAll:"Show all activity",nodeChanged:"Machine joined or left",worktreeCreated:"Worktree created",nodeJoined:"Node joined",nodeRemoved:"Node removed",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."]},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."]},blueprint:{term:"Blueprint",summary:"The plan view: live queue work and its task dependencies 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 dependency chains fold away so live work stays in view."]},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:{easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"},panel:{outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusCoordinator:"coordinator",statusWorker:"worker",upstreamUnverified:"unverified",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",working:"working",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"},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"},empty:"No tasks yet",waitsOn_one:"waits on {{count}}",waitsOn_other:"waits on {{count}}",missingDeps_one:"{{count}} unknown dep",missingDeps_other:"{{count}} unknown deps",legend:{satisfied:"done",waiting:"waiting",failed:"failed"},predictedSlotPinned:"Pinned to a target node — predicted slot on that node"},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",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",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."},health:{statFailed:"Failed",statPending:"Waiting"},blueprint:{schedPrediction:"Prediction",readonlyBadge:"read-only",schedObservedAt:"as of {{time}}",schedNoNodes:"No routable nodes.",schedQuotaButton:"Quota",schedQuotaButtonTitle:"Per-machine plan quota at a glance",schedNoWinner:"no eligible slot",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",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",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",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}}",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",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}}",tooltipTask:"Task: {{id}}",tooltipMission:"Mission: {{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",legendRunning:"running",legendDead:"can never start",heldUntil:"until {{time}}",tone:{pending:"pending",running:"running",completed:"completed",failed:"failed",cancelled:"cancelled",dead:"stuck",plan:"planned",held:"held"}}},page:{title:"Repo Mesh",subtitle:"Multi-workspace orchestration",waitingForDaemon:"Waiting for daemon connection..."},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.",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"},detail:{useFromCli:"Use from CLI",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",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:"Approval gates and git safety behavior for coordinator-driven tasks. Uncommitted changes follow a fixed rule: a dirty base node never takes write tasks; a dirty worktree takes only follow-ups on its own branch; Refinery refuses to merge a branch worktree with uncommitted changes.",policyDefaultBadge:"Default",policyResetToDefault:"Reset to default",pushApproval:"Push approval",requireApprovalBeforePush:"Require approval before push",doNotRequireApproval:"Do not require approval",destructiveGitApproval:"Destructive git approval",requireApproval:"Require approval",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",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.",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)",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.",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."},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."},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."},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",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",detailLabelMissionId:"Mission id",detailLabelCreated:"Created",detailLabelUpdated:"Updated",detailLabelElapsed:"Elapsed",detailLabelFullInstruction:"Show full instruction",detailLabelLastActivity:"Last task activity",detailLabelIncompleteEvidence:"Incomplete evidence",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",sessionTasksHeading:"Tasks in this session",showOnCanvas:"Show on canvas"}},aj={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.",agent:"Agent",tool:"Tool",ranCommand:"Ran command",activityTerminal:"Terminal",activityRuntime:"Runtime",system:"System",injected:"Injected input",relayLabel:"Relay · {{project}} · {{outcome}}",relayOutcome:{completed:"completed",failed:"failed",cancelled:"cancelled"},relayIdle:"Nothing left running",reviewLabel:"Memory review",daemonNoticeLabel:"Notice"},ij={debugBundleFailed:"Couldn't collect debug info",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...",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"},cj={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"},lj={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"},dj={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"},uj={muteThis:"Mute this chat",unmuteThis:"Unmute this chat"},mj={switchToTerminal:"Switch to Terminal view",switchToChat:"Switch to Chat view"},hj={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…",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."},pj={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",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",selectedCount_one:"{{count}} selected",selectedCount_other:"{{count}} selected",intro:"Pick the providers you want to use. Defaults to the three officially supported CLI providers; you can install IDE 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."},cli:{title:"CLI coverage",desc:"Track standalone CLI agents 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"}}},fj={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",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 →"}},bj={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."},dashboardWire:{reloadTitle:"Reload required",reloadBody:"This page is older than the daemon it talks to, so it cannot read the daemon's state. Reload to get the current dashboard.",reload:"Reload",daemonUpdateTitle:"Daemon update required",daemonUpdateBody:"{{count}} machine(s) run an older daemon this dashboard cannot read. Update them with `adhdev update` (or the machine page's update action)."},openMenu:"Open menu",closeMenu:"Close menu"},gj={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}}"},xj={zoomOut:"Zoom Out",zoomIn:"Zoom In",resetZoom:"Reset Zoom",toggleFullscreen:"Toggle Fullscreen"},yj={screenshotAlt:"Remote View",mouse:"Mouse",touch:"Touch",connected:"Connected",ws:"Reconnecting",direct:"Direct",relay:"Relay",turnBlocked:"Daily view limit reached",turnUsage:"View {{used}}/{{budget}}m",typeAndEnter:"Type & Enter...",settings:"SETTINGS",zoom:"ZOOM:",fill:"FILL",fit:"FIT",directP2PTitle:"Direct P2P connection",turnRelayTitle:"TURN relay in use",dailyTurnTitle:"Remote view minutes used today (plan limit)",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}}"}},vj={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"},wj={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"},Sj={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",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?"},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…",online:"Online"},slowLink:"Slow link",coresCount_other:"{{count}} cores",coresCount_one:"{{count}} core",onMachine:"on {{machine}}",sectionIDEs:"IDEs",sectionCLIs:"CLIs",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",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"},fleetQuota:{title:"Plan quota across machines",subtitle:"How much of each subscription's 5-hour and weekly window is left on every machine. The task queue skips plans that are nearly out and spends quota that would expire unused first.",machine:"Machine",unreadable:"unreadable"},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",nicknameTimeout:"The machine didn't answer — check its connection and try again",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 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."}},kj={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",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}}"},jj={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"},Nj={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."}},Cj={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"},_j={gallery:{next:"Next view",previous:"Previous view",slides:{overview:"Missions & activity — from a phone",tasks:"Task queue across workers",map:"Live map of nodes and branches",desktop:"The same mesh, desktop view"}},theme:{system:"System theme",light:"Light theme",dark:"Dark theme"},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:"Claude Code, Codex, Cursor & more — on all your machines",title:"The control plane for your coding agents.",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:"Every agent on every machine in one view, one shared task queue, and only work that passes your tests reaches main.",axes:{os:["Mac","Windows","Linux"],place:["the subway","a cafe","your parents' place","bed","the couch","the garden","the passenger seat","the ferry","the gym","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:"One question, several independent agents",crossDesc:"Have the coordinator ask the same read-only question to several machines and models at once, then compare where they agree and disagree — 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:"Local CLIs spawn subagents; desktop orchestrators fan work across worktrees with a native UI. Both stop at the branch — reviewing and merging is left to you. Here's how they compare, including where each of them is the better fit.",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 rebases + merges onto main only if it hasn't moved — 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 audit trail",rowCrossCheck:"Cross-check the answer",rowCrossCheckLocalCli:"One agent's take, no second opinion",rowCrossCheckDesktop:"Parallel work, single verdict",rowCrossCheckAdhdev:"The coordinator sends the same read-only question to agents on different machines and providers and compares 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 — all in the same mesh, driven from the same dashboard. 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, Kimi, and OpenCode — launched 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).",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 — your code never routes through the server. The cloud handles sign-in, connection setup and session status. The one exception: approval push notifications include up to 80 characters of what you're approving."},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, and {{extensions}} IDE-resident extension 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."},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:"Prices in USD, excluding applicable taxes. Prefer to self-host? The daemon and dashboard are open source.",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 and IDE agents",push:"Push notifications for approvals & completions",share:"One shared session link"}},pro:{period:"/mo",tagline:"Two machines, so Repo Mesh can run agents across both — plus more concurrent sessions.",cta:"Start 7-day Pro trial",features:{machines:"2 machines — run agents on both",p2p:"More concurrent P2P sessions",push:"Unlimited push notifications",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 Linux use the Unix script; Windows uses the PowerShell one. All three are in daily use.",arrow:"→",steps:{step1:{title:"Install the daemon",desc:"One 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, 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:"Put every agent and every machine behind one queue.",subtitle:"One command, one daemon, every agent you already use. Queue the work, and only what passes your tests lands on main.",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 showing an ADHDev approval push with the Bash command Claude Code wants to run",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:"The right model for each task, on the subscription that still has room.",sectionSubtitle:"Tag a task easy, medium, or difficult and the mesh applies a matching preset — provider, model, and thinking budget. Every machine also reads how much of each subscription's 5-hour and weekly window is left: a plan that is nearly out gets skipped, and quota that would expire unused at the next reset is spent first.",point1:"Difficulty-based presets: easy / medium / difficult",point2:"Each preset picks provider, model, and thinking level",point3:"Routes around plans that are nearly out of quota"},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, Windows and Linux machines are all in daily use."}},Aj={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."},Tj={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"}},Ij={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"},Mj={pageTitle:"Approvals",pageSubtitle:"Sessions waiting on your decision.",pending:"Pending",loading:"Loading approvals…",emptyHint:"Approvals from any connected machine will appear here automatically."},Rj={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"},Pj={dashboard:"Dashboard",machines:"Machines",notifications:"Notifications",mesh:"Mesh",marketplace:"Marketplace",api:"API",webhooks:"Webhooks",account:"Account",settings:"Settings",docs:"Docs",about:"About",chats:"Chats"},Ej={controls:qk,sessionStatus:zk,language:Vk,common:Gk,connection:Yk,toast:Qk,notification:Jk,event:Xk,dashboard:Zk,cliStop:ej,approval:tj,chatControls:nj,newSession:sj,mobileInbox:rj,mesh:oj,chat:aj,chatPane:ij,chatInput:cj,paneGroup:lj,terminal:dj,conversation:uj,cliView:mj,launch:hj,standalone:pj,cloud:fj,app:bj,chatList:gj,screenshot:xj,remote:yj,sessionNav:vj,sessionInfo:wj,machine:Sj,sessionHost:kj,sessionHostSurface:jj,settings:Nj,historyModal:Cj,landing:_j,interactivePrompt:Aj,git:Tj,notifications:Ij,approvals:Mj,setupWizard:Rj,nav:Pj},Nl="lang",io="common",Lj={ko:()=>hr(()=>import("./common-B-bcABBd.js"),[]),ja:()=>hr(()=>import("./common-D___Aqd4.js"),[]),"zh-CN":()=>hr(()=>import("./common-BRmyrjB5.js"),[]),es:()=>hr(()=>import("./common-V_b-iyjQ.js"),[])};async function Dj(e){return!Es(e)||e===Ds?null:(await Lj[e]()).default}const Oj={type:"backend",init(){},read(e,t,s){if(t!==io){s(null,{});return}Dj(e).then(r=>s(null,r??{}),r=>s(r instanceof Error?r:new Error(String(r)),!1))}};function $j(e){return{resources:{[Ds]:{[io]:Ej}},partialBundledLanguages:!0,lng:e,fallbackLng:Ds,supportedLngs:_f,ns:[io],defaultNS:io,interpolation:{escapeValue:!1},returnEmptyString:!1,react:{transKeepBasicHtmlNodesFor:["br","strong","i","p","em"]}}}function Fj(){try{const e=localStorage.getItem(Nl);if(Es(e))return e}catch{}return null}function Af(){const e=Fj();return e||(typeof navigator<"u"?Kk(navigator.language):Ds)}function Cl(e){typeof document>"u"||document.documentElement.setAttribute("lang",e)}let vo=null,Tf=!1;function If(){if(vo)return Ye;const e=Af();return vo=Ye.use(Oj).use(ty).init($j(e)).then(()=>{},()=>{}).finally(()=>{Tf=!0}),Cl(e),Ye}function Hj(){return Tf?!0:!!vo&&Ye.isInitialized&&Ye.hasLoadedNamespace(io)}function Bj(){return vo||If(),vo}function Ut(e){return(typeof e=="string"?e.trim():"")||void 0}function Yn(e,t){const s=Ut(t);return s?`${e}:${s}`:void 0}function hs(e,t,s){const r=Yn(t,s),o=Ut(s);r&&e.push(r),o&&e.push(o)}function pr(e){const t=[],s=new Set;for(const r of e)!r||s.has(r)||(s.add(r),t.push(r));return t}function Mf(e){return Ut(e.providerSessionId)||Ut(e.sessionId)||Ut(e.tabKey)||Ut(e.routeId)}function Ci(e){return pr([Ut(e.historySessionId),Ut(e.providerSessionId),Ut(e.sessionId)])}function co(e){const t=[];return hs(t,"provider",e.providerSessionId),hs(t,"session",e.sessionId),hs(t,"tab",e.tabKey),hs(t,"route",e.routeId),pr(t)}function Wj(e){const t=[];return Ut(e.providerSessionId)?(hs(t,"provider",e.providerSessionId),pr(t)):Ut(e.sessionId)?(hs(t,"session",e.sessionId),pr(t)):Ut(e.tabKey)?(hs(t,"tab",e.tabKey),pr(t)):Ut(e.routeId)?(hs(t,"route",e.routeId),pr(t)):[]}function Rf(e){return Yn("provider",e.providerSessionId)||Yn("session",e.sessionId)||Yn("tab",e.tabKey)||Yn("route",e.routeId)||"unknown:"}function _i(e){return Ci(e)[0]}function Ai(e){const t=Ut(e.sessionId),s=_i(e);if(s&&!(t&&s===t))return s}function Uj(e){const t=Ut(e.providerSessionId),s=Ut(e.sessionId),r=Ut(e.tabKey),o=Ut(e.routeId),a=[Yn("provider",t),Yn("session",s),Yn("tab",r),Yn("route",o)].filter(d=>typeof d=="string"),i=co({providerSessionId:t,sessionId:s,tabKey:r,routeId:o}),l=Rf({providerSessionId:t,sessionId:s,tabKey:r,routeId:o});return{providerSessionId:t,sessionId:s,tabKey:r,routeId:o,canonicalKey:l,targetKey:l,targetValue:Mf({providerSessionId:t,sessionId:s,tabKey:r,routeId:o}),historySessionId:_i({providerSessionId:t,sessionId:s}),runtimeSessionId:s,allKeys:a,lookupKeys:i}}function no(e,t){const s=Uj(e);return Wj(t).some(r=>s.lookupKeys.includes(r))}function Pf(e){const t=String(e.daemonId||"").trim(),s=String(e.id||"").trim();return t&&s.startsWith(`${t}:`)?s.slice(t.length+1):s}function _l(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 Kj(e,t){const s=String(e.daemonId||"").trim(),r=String(e.id||"").trim(),o=Pf(e);if(o&&t.has(o))return`mesh:${o}`;const a=String(e.ownerDaemonId||"").trim()||s;return a?o?`${a}:${o}`:a:r}function pc(e,t){return t||e||"unknown"}function qj(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 zj={vscode:"VS Code",pearai:"PearAI"};function $t(e){return e?e.split("-").map(t=>zj[t.toLowerCase()]||t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Vj(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 fc(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function ya(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 Gj(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 Yj(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Qj(e){return Gj(e.trim().replace(/\.local$/i,""))}function Ef(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Ad(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&&!Yj(i));if(s&&s!=="Unknown")return Qj(s);const r=t.fallbackId||e.id;return r?`Machine-${r.substring(0,8)}`:t.fallbackLabel||"Machine"}function pn(e,t={}){return Ef(e)||Ad(e,t)}function Lf(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 Jj(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 wo(e,t){return Lf(e).join(" · ")}function So(e){return e.transport==="pty"}const Df={darwin:"macOS",linux:"Linux",win32:"Windows"};function Of(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:$t(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=$t(s||"").trim().toLowerCase();return r===o||r===a||r===i}function Xj(e,t=[],s=[]){var d,u,m,h;const r=Zt(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})||wl(p.status));if(o)return Zt(o.status,{activeModal:o.activeModal});const a=s.find(p=>Zu(p.status,{activeModal:p.activeModal})||wl(p.status));if(a)return Zt(a.status,{activeModal:a.activeModal});if(r&&r!=="idle")return r;const i=Zt((d=t[0])==null?void 0:d.status,{activeModal:(u=t[0])==null?void 0:u.activeModal});if(i!=="idle")return i;const l=Zt((m=s[0])==null?void 0:m.status,{activeModal:(h=s[0])==null?void 0:h.activeModal});return l!=="idle"?l:"idle"}function Zj(e){return Zt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function eN(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=Zt(r.status);if(!a){t.set(o,{...r,status:i});continue}const l=s.indexOf(a.status||"idle"),d=s.indexOf(i||"idle");d>=0&&(l<0||d<l)&&t.set(o,{...r,status:i})}return Array.from(t.values())}function tN(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 nN(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&&tN(t.receivedAt)||0}function sN(e){return(e.recentLaunches||[]).reduce((s,r)=>Math.max(s,r.lastLaunchedAt||0),0)}function Al(e){return Math.max(sN(e),nN(e.activeChat))}function rN(e,t,s,r,o,a){const i=t-e;if(i!==0)return i;const l=s.localeCompare(r);return l!==0?l:o.localeCompare(a)}function Wa(e,t){return rN(Al(e),Al(t),pn(e,{fallbackId:e.id}),pn(t,{fallbackId:t.id}),e.id,t.id)}const $f="adhdev_notification_prefs",rm={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function oN(){try{const e=localStorage.getItem($f);if(e){const t=JSON.parse(e);return{...rm,...t}}}catch{}return{...rm}}function aN(e){try{localStorage.setItem($f,JSON.stringify(e))}catch{}}let Gn=oN(),va=[];function iN(){va.forEach(e=>e())}function cN(e){Gn={...Gn,...e},aN(Gn),iN()}function lN(){const[,e]=c.useState(0);c.useEffect(()=>{const s=()=>e(r=>r+1);return va.push(s),()=>{va=va.filter(r=>r!==s)}},[]);const t=c.useCallback(s=>{cN(s)},[]);return[{...Gn},t]}function lo(e){if(!Gn.globalEnabled)return!1;switch(e){case"disconnect":return Gn.disconnectAlert;case"completion":return Gn.completionAlert;case"approval":return Gn.approvalAlert;case"browser":return Gn.browserNotifications;default:return!0}}const dN={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ff(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Hf(){return"Notification"in window&&Notification.permission==="granted"}function uN(e,t,s){return e?!(s==="waiting_choice"&&t!=="waiting_choice"):!1}let Cs=null;function mN(e){return e!==!1}async function hN(){if(Cs!==null)return Cs;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Cs=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Cs=!!await e.pushManager.getSubscription(),Cs):(Cs=!1,!1)}catch{return Cs=!1,!1}}function Tl(e,t,s){if(Hf())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 pN(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?Ye.t("event.browser.questionWithMessage",{message:a}):Ye.t("event.browser.question")}:e.onApproval&&r==="waiting_approval"&&s!=="waiting_approval"?{kind:"approval",title:t,body:a?Ye.t("event.browser.approvalWithMessage",{message:a}):Ye.t("event.browser.approval")}:e.onComplete&&wl(s)&&r==="idle"?{kind:"complete",title:t,body:Ye.t("event.browser.finished")}:e.onError&&r==="error"&&s!=="error"?{kind:"error",title:t,body:Ye.t("event.browser.error")}:null}function fN(e,t={}){const s={...dN,...t},r=c.useRef(new Map),o=c.useRef(0),[a,i]=c.useState(null);c.useEffect(()=>{let d=!1;return hN().then(u=>{d||i(u)}),()=>{d=!0}},[]);const l=c.useCallback((d,u,m)=>{const h=Date.now();h-o.current<s.throttleMs||(o.current=h,Tl(d,u,m))},[s.throttleMs]);c.useEffect(()=>{var d;if(!(!s.enabled||!Hf())&&lo("browser")&&!mN(a)){if(document.hasFocus()){for(const u of e)r.current.set(u.id,Zt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const m=r.current.get(u.id),h=Zt(u.status,{activeModal:u.activeModal}),p=u.name||u.id,b=h==="waiting_choice"&&m!=="waiting_choice";if(uN(u.muted,m,h)){r.current.set(u.id,h);continue}const f=pN({name:p,prev:m,curr:h,modalMessage:(d=u.activeModal)==null?void 0:d.message,questionEntered:b,onApproval:s.onApproval&&lo("approval"),onComplete:s.onComplete&&lo("completion"),onError:s.onError});f&&l(f.title,f.body,`${f.kind}-${u.id}`),r.current.set(u.id,h)}}},[e,s.enabled,s.onApproval,s.onComplete,s.onError,a,l])}const bN=/^(run|approve|accept|yes|allow|always)/,gN=/^(run|approve|accept|yes|allow|always|proceed|save)/,xN=/^(reject|deny|delete|remove|abort|cancel|no)/;function Td(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").replace(/\s*\(\s*\)/g,"").trim()}function yN(e){const t=Td(e).toLowerCase();return bN.test(t)?"primary":xN.test(t)?"danger":"default"}function vN(e){return gN.test(Td(e).toLowerCase())?"approve":"reject"}function wN(e){return e.map((t,s)=>({label:Td(t),variant:yN(t),action:vN(t),button:t,buttonIndex:s}))}function SN(e,t,s){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:s}function kN(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 Id(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 Id(s);try{return JSON.stringify(e)}catch{return}}return String(e)}}class jN{constructor(){ze(this,"dedupMap",new Map);ze(this,"DEDUP_WINDOW_MS",5e3);ze(this,"DEDUP_MAX_SIZE",50);ze(this,"DEDUP_CLEANUP_AGE_MS",1e4);ze(this,"toastCallbacks",[]);ze(this,"statusEventCallbacks",[]);ze(this,"resolveActionFn",null);ze(this,"viewRequestRespondFn",null);ze(this,"hydrateInteractivePromptFn",null);ze(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=vl(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=Id(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),l=`${a}:${t.event}:${i}`;if(t.event==="agent:waiting_choice"&&this.hydrateInteractivePromptFromEvent(t),this.isDuplicate(l))return;for(const g of this.statusEventCallbacks)g(t);const d=this.isConversationEventMuted(t),u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let h=m&&m!=="adhdev-daemon"?Of(m,{agentName:u==null?void 0:u.cliName}):$t(m);const p=this.resolveOwningDaemon(t);if(p){const g=pn(p,{fallbackId:p.id});g&&(h=!m||m==="adhdev-daemon"?g:`${g}/${h}`)}let b="",f="info";if(t.event==="agent:generating_completed"){if(b=t.duration?`✅ ${Ye.t("event.taskCompletedWithDuration",{label:h,duration:Ww(Number(t.duration)*1e3)})}`:`✅ ${Ye.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(b=`⚡ ${Ye.t("event.approvalNeeded",{label:h})}`,f="warning",d)b="";else if((x=t.modalButtons)!=null&&x.length&&this.resolveActionFn){const g=this.resolveActionRouteTarget(t);if(!g)return;const w=this.resolveActionFn,S=wN(t.modalButtons).map(v=>({label:v.label,variant:v.variant,onClick:()=>{w(g,"resolve_action",{action:v.action,button:v.button,buttonIndex:v.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),C=SN(h,t.modalMessage,b),j=Date.now();this.emitToast({id:j,message:C,type:f,timestamp:j,targetKey:r||g,actions:S,duration:15e3}),b=""}}else if(t.event==="agent:waiting_choice"){b=`❓ ${Ye.t("event.questionNeeded",{label:h})}`,f="warning";const g=typeof t.modalMessage=="string"&&t.modalMessage.trim()?t.modalMessage.replace(/[\n\r]+/g," ").slice(0,120):"";g&&(b=`${b} — ${g}`);const w=Date.now();this.emitToast({id:w,message:b,type:f,timestamp:w,targetKey:r||t.daemonId,duration:1e4}),b=""}else if(t.event==="monitor:no_progress"){const g=t.elapsedSec?Math.round(t.elapsedSec/60):0;b=g?`⚠️ ${Ye.t("event.noProgressWithDuration",{label:h,minutes:g})}`:`⚠️ ${Ye.t("event.noProgress",{label:h})}`,f="warning",!d&&lo("browser")&&!document.hasFocus()&&Tl(`⚠️ ${Ye.t("event.noProgressTitle",{label:h})}`,Ye.t("event.noProgressBody",{duration:g?`${g}m`:""}),`no-progress-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const g=t.requesterName||Ye.t("event.someoneRequester"),w=t.requestId,S=t.orgId;if(b=`${Ye.t("event.viewRequest",{requester:g})}`,f="warning",w&&S&&this.viewRequestRespondFn){const C=Date.now(),j=kN(S,w,this.viewRequestRespondFn,(v,y)=>console.error(`[EventManager] ${v} view request failed:`,y));this.emitToast({id:C,message:b,type:f,timestamp:C,actions:j,duration:3e4}),b=""}lo("browser")&&!document.hasFocus()&&Tl(`${Ye.t("event.viewRequestTitle")}`,Ye.t("event.viewRequest",{requester:g}),`view-request-${w}`)}else if(t.event==="team:view_request_approved")b=`✅ ${Ye.t("event.viewRequestApproved")}`,f="success";else if(t.event==="team:view_request_rejected"){const g=t.targetName||Ye.t("event.someoneTarget");b=`❌ ${Ye.t("event.viewRequestDeclined",{target:g})}`,f="warning"}}if(b&&!d){const g=Date.now();this.emitToast({id:g,message:b,type:f,timestamp:g,targetKey:r||t.daemonId,duration:5e3})}}}const et=new jN,om=new Map;function Bf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function fr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ti(e){return ff(e)??null}function NN(e){const t=Ti(e);return!t||!Bf(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Qo(e){const t=Ti(e);return!t||!Bf(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Wr(e){const t=Ti(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Jo(e){const t=Ti(e);return!!t&&t.success===!1}function CN(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";et.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";et.showToast(r.notification.body,o)}}}function _N(e,t){return e&&fr(e.currentValue)?e.currentValue:t}function AN(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 TN(e,t){return fr(t)?fr(e)?typeof e=="string"&&e.trim()==="":!0:!1}function IN(e,t){var a,i;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(fr(l))return l}const r=(a=t.controlValues)==null?void 0:a[e];if(fr(r))return r;const o=(i=t.defaultValues)==null?void 0:i[e];return fr(o)?o:void 0}function wa(e,t){return e.options||t[e.id]||[]}const MN={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 RN(e,t,s){var r;return((r=MN[t])==null?void 0:r.has(s.id))===!0}function PN(e){if(e){if(fi(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 EN(e,t){const s=e.visibleWhenState;if(!s||s.length===0)return!0;const r=PN(t);return r?r.some(o=>s.includes(o)):!0}function Md(e,t){return(e||[]).filter(s=>s.placement==="bar"&&s.hidden!==!0&&!RN(t.hostIdeType,t.providerType,s)&&EN(s,t.currentStatus)).sort((s,r)=>(s.order??50)-(r.order??50))}function bc(e,t){return{value:t}}function LN(e,t,s){var o;return s?((o=wa(e,t).find(a=>a.value===s))==null?void 0:o.label)||s:""}const DN={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function ON({routeId:e,sessionId:t,hostIdeType:s,providerType:r,displayLabel:o,controls:a,controlValues:i,currentStatus:l,coordinatorHint:d}){const{t:u}=he("common"),{sendCommand:m}=wt(),{confirm:h,confirmDialog:p}=Tr(),b=`${e}:${t||r}`,f=DN[r]||"#94a3b8",[x,g]=c.useState({}),w=c.useRef({}),S=c.useRef(i);w.current=x,S.current=i;const C=c.useRef(0),j={};for(const R of a||[])R.defaultValue!==void 0&&(j[R.id]=R.defaultValue);const v={...j,...i||{},...Date.now()<C.current?x:{}};c.useEffect(()=>{i&&Date.now()>C.current&&g(R=>AN(R,i))},[i]);const[y,N]=c.useState(om.get(b)||{}),[k,A]=c.useState(null),[E,P]=c.useState(null),T=c.useCallback(async(R,O={})=>{const H={...O,...t&&{targetSessionId:t},...d??{}};return await m(e,R,H)},[e,t,m,d]),M=c.useCallback(async(R,O={})=>{const H=t?{targetSessionId:t}:{agentType:r,...s?{ideType:s}:{}};return await T("invoke_provider_script",{...H,scriptName:R,...O})},[T,r,s,t]),_=c.useCallback((R,O,H)=>{const B=_N(H,O);g(q=>({...q,[R.id]:B})),CN(H==null?void 0:H.effects)},[]),I=c.useCallback((R,O)=>{g(H=>{const B={...H};return O===void 0?delete B[R.id]:B[R.id]=O,B}),C.current=0},[]);if(!a||a.length===0)return null;const D=Md(a,{hostIdeType:s,providerType:r,currentStatus:l});if(D.length===0)return null;const L=async R=>{if(k===R.id){A(null);return}if(wa(R,y).length>0){A(R.id);return}if(R.dynamic&&R.listScript){P(R.id);try{const H=await M(R.listScript,{}),B=NN(H);if(!B){const ce=Wr(H);ce&&et.showErrorToast(u("controls.loadOptionsFailed",{label:R.label}),ce);return}const q=B.options;N(ce=>{const ye={...ce,[R.id]:q};return om.set(b,ye),ye});const W=IN(R.id,{localOverrideUntil:C.current,localValues:w.current,controlValues:S.current,defaultValues:j});if(TN(W,B.currentValue)){const ce=B.currentValue;g(ye=>({...ye,[R.id]:ce}))}A(R.id)}catch(H){et.showErrorToast(u("controls.loadOptionsFailed",{label:R.label}),H)}finally{P(null)}}},$=async(R,O)=>{A(null);const H=(i==null?void 0:i[R.id])??j[R.id];g(B=>({...B,[R.id]:O})),C.current=Date.now()+5e3;try{if(!R.setScript)return;const B=await M(R.setScript,bc(R,O)),q=Qo(B);if(q&&!q.ok||Jo(B))throw new Error((q==null?void 0:q.error)||Wr(B)||`Could not update ${R.label}`);_(R,O,q)}catch(B){I(R,H),et.showErrorToast(u("controls.updateFailed",{label:R.label}),B)}},U=async R=>{const O=wa(R,y).map(ye=>ye.value);if(O.length===0)return;const H=String(v[R.id]||""),q=(O.indexOf(H)+1)%O.length,W=O[q];if(typeof W!="string")return;const ce=(i==null?void 0:i[R.id])??j[R.id];g(ye=>({...ye,[R.id]:W})),C.current=Date.now()+5e3;try{if(!R.setScript)return;const ye=await M(R.setScript,bc(R,W)),G=Qo(ye);if(G&&!G.ok||Jo(ye))throw new Error((G==null?void 0:G.error)||Wr(ye)||`Could not update ${R.label}`);_(R,W,G)}catch(ye){I(R,ce),et.showErrorToast(u("controls.updateFailed",{label:R.label}),ye)}},J=async R=>{const H=!v[R.id],B=(i==null?void 0:i[R.id])??j[R.id];g(q=>({...q,[R.id]:H})),C.current=Date.now()+5e3;try{if(!R.setScript)return;const q=await M(R.setScript,bc(R,H)),W=Qo(q);if(W&&!W.ok||Jo(q))throw new Error((W==null?void 0:W.error)||Wr(q)||`Could not update ${R.label}`);_(R,H,W)}catch(q){I(R,B),et.showErrorToast(u("controls.updateFailed",{label:R.label}),q)}},K=async R=>{var H,B,q;if(!R.invokeScript||R.confirmMessage&&!await h({title:((H=R.confirmTitle)==null?void 0:H.trim())||R.confirmMessage,description:(B=R.confirmTitle)!=null&&B.trim()?R.confirmMessage:void 0,confirmLabel:((q=R.confirmLabel)==null?void 0:q.trim())||u("common.confirm")}))return;const O=(i==null?void 0:i[R.id])??j[R.id];try{const W=await M(R.invokeScript),ce=Qo(W);if(ce&&!ce.ok||Jo(W))throw new Error((ce==null?void 0:ce.error)||Wr(W)||`Could not run ${R.label}`);ce&&_(R,O??!0,ce)}catch(W){I(R,O),et.showErrorToast(u("controls.runFailed",{label:R.label}),W)}};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}),D.map(R=>{const O=String(v[R.id]||""),H=LN(R,y,O),B=k===R.id,q=E===R.id,W=wa(R,y),ce="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:`${ce} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:B?`${f}55`:"var(--border-default)",background:B?`${f}10`:"var(--surface-tertiary)",color:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void L(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:q?u("chatControls.loading"):H||R.label}),n.jsx("span",{className:"text-4xs opacity-55",children:"▼"})]}),B&&W.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}),W.map(ye=>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:ye.value===O?`${f}14`:"transparent",color:ye.value===O?"var(--text-primary)":"var(--text-secondary)",borderLeft:ye.value===O?`2px solid ${f}`:"2px solid transparent"},title:ye.description||ye.label,onMouseEnter:G=>{G.currentTarget.style.background=`${f}10`},onMouseLeave:G=>{G.currentTarget.style.background=ye.value===O?`${f}14`:"transparent"},onClick:()=>void $(R,ye.value),children:[n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ye.label}),ye.value===O&&n.jsx("span",{className:"shrink-0 text-2xs font-semibold",style:{color:f},children:"✓"})]},ye.value))]})]})]},R.id);case"cycle":return n.jsxs("button",{type:"button",className:`${ce} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void U(R),title:`Click to cycle: ${W.map(ye=>ye.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:H||R.label}),n.jsx("span",{className:"text-3xs opacity-55",children:"⟳"})]},R.id);case"toggle":return n.jsxs("button",{type:"button",className:`${ce} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:O?`${f}44`:"var(--border-default)",background:O?`${f}14`:"var(--surface-tertiary)",color:O?f:"var(--text-muted)"},onClick:()=>void J(R),"aria-pressed":!!O,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:`${ce} 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"&&O?`${R.label}: ${O}`: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:O?"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:O?`${R.label}: ${O}`:R.label})]},R.id);default:return null}})]}),p]})}function $N(e){if(!e||typeof e!="object")return{};const t=e,s=Tv(t.launch);return{...s?{launch:s}:{},...typeof t.model=="string"&&t.model.trim()?{model:t.model.trim()}:{},...ud(t.modelSource)?{modelSource:t.modelSource}:{}}}const am={user:"chosen",remembered:"remembered",mesh_slot:"mesh slot",task_override:"task",provider_default:"default",unspecified:""};function FN(e,t){return String(t.defaultValue??"").replace(/\{\{(\w+)\}\}/g,(s,r)=>String(t[r]??""))}function Wf(e,t=FN){const s=e.launch?Av(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 HN({surface:e}){const{t}=he("common"),s=Wf(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 BN({isActive:e=!0,isCliTerminal:t=!1,routeId:s,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:l,controlValues:d,currentStatus:u,coordinatorHint:m,launchSurface:h}){const{isVisible:p}=_d(),b=Md(l,{hostIdeType:o,providerType:a,currentStatus:u}),f=b.length>0&&p,x=!!h&&!!Wf(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(HN,{surface:h})}),f&&n.jsx(ON,{routeId:s,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:b,controlValues:d,currentStatus:u,coordinatorHint:m})]})}const Ur=5,Uf=10*1024*1024;function WN({hasDraft:e,isBusy:t=!1}){return!e||t}function UN(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 KN(e){if(e.size>Uf)return null;const t=await UN(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 qN(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}function zN(e){return/[\u1100-\u11FF\u3130-\u318F\uAC00-\uD7A3]/.test(e)}const Kf=c.memo(function({contextKey:t,panelLabel:s,isSending:r,isBusy:o=!1,statusMessage:a=null,inlineStatusMessage:i=null,onSend:l,isActive:d=!0,showControlsToggle:u=!1,animateVisibility:m=!0,onControlsToggle:h,messageInput:p}){const{t:b}=he("common"),f=c.useRef(null),x=c.useRef(null),[g,w]=c.useState(""),[S,C]=c.useState([]),[j,v]=c.useState(null),[y,N]=c.useState(!1),k=c.useRef(!1),A=c.useRef(0),E=50,P=c.useRef(""),T=c.useRef(!1),M=c.useRef(null),_=30,{isVisible:I,toggleVisibility:D}=_d(),L=qN(p),$=!!g.trim()||S.length>0;c.useEffect(()=>{w(""),C([]),v(null)},[t]),c.useEffect(()=>{var W;d&&((W=f.current)==null||W.focus({preventScroll:!0}))},[t,d]),c.useEffect(()=>{const W=f.current;W&&(W.style.height="auto",g&&(W.style.height=`${Math.min(W.scrollHeight,160)}px`))},[g]);const U=c.useCallback(async W=>{v(null);const ce=Array.from(W).filter(ae=>ae.type.startsWith("image/"));if(ce.length===0)return;const ye=Ur-S.length;if(ye<=0){v(`Max ${Ur} images`);return}const G=ce.slice(0,ye);if(G.filter(ae=>ae.size>Uf).length>0){v("Image too large (max 10 MB)");return}const ne=(await Promise.all(G.map(KN))).filter(ae=>ae!==null);C(ae=>[...ae,...ne])},[S.length]),J=c.useCallback(W=>{C(ce=>ce.filter((ye,G)=>G!==W))},[]),K=c.useCallback(async()=>{const W=g.trim();if(!W&&S.length===0||o||k.current)return;k.current=!0;const ce=S.length>0?[...S]:void 0;try{await l(W,ce)!==!1&&(w(""),C([]),v(null))}finally{k.current=!1}},[g,S,o,l]),R=c.useRef(K);R.current=K;const O=c.useCallback(()=>{T.current&&(T.current=!1,M.current&&(clearTimeout(M.current),M.current=null),setTimeout(()=>{R.current()},0))},[]);c.useEffect(()=>()=>{M.current&&clearTimeout(M.current)},[]);const H=c.useCallback(W=>{L&&(W.preventDefault(),N(!0))},[L]),B=c.useCallback(()=>N(!1),[]),q=c.useCallback(W=>{L&&(W.preventDefault(),N(!1),W.dataTransfer.files.length>0&&U(W.dataTransfer.files))},[L,U]);return n.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",y?"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:H,onDragLeave:B,onDrop:q,children:[S.length>0&&n.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:S.map((W,ce)=>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:W.previewUrl,alt:W.name,className:"w-full h-full object-cover"}),n.jsx("button",{type:"button",onClick:()=>J(ce),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 ${W.name}`,children:"✕"})]},ce))}),n.jsxs("div",{className:"flex gap-2 items-center",title:d?b("chatInput.sendTo",{panel:s}):void 0,children:[u&&n.jsx("button",{type:"button",onClick:()=>{D(),h==null||h()},"aria-label":b(I?"chatInput.hideControls":"chatInput.showControls"),"aria-pressed":I,title:b(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"})]})}),L&&n.jsxs(n.Fragment,{children:[n.jsx("input",{ref:x,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:W=>{W.target.files&&U(W.target.files),W.target.value=""}}),n.jsx("button",{type:"button",onClick:()=>{var W;return(W=x.current)==null?void 0:W.click()},disabled:S.length>=Ur,title:S.length>=Ur?`Max ${Ur} images`:b("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":b("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||(L&&S.length>0?b("chatInput.addMessageOptional"):b("chatInput.placeholder",{panel:s})),value:g,onChange:W=>w(W.target.value),onPaste:W=>{if(L&&W.clipboardData.files.length>0&&Array.from(W.clipboardData.files).some(oe=>oe.type.startsWith("image/"))){W.preventDefault(),U(W.clipboardData.files);return}const ce=W.clipboardData.getData("text/plain"),ye=Yv(ce);if(ye===ce)return;W.preventDefault();const G=f.current,Se=(G==null?void 0:G.selectionStart)??g.length,ue=(G==null?void 0:G.selectionEnd)??g.length,ne=g.slice(0,Se)+ye+g.slice(ue);w(ne);const ae=Se+ye.length;requestAnimationFrame(()=>{G==null||G.setSelectionRange(ae,ae)})},onCompositionUpdate:W=>{P.current=W.data||""},onCompositionEnd:W=>{A.current=Date.now(),W.data&&(P.current=W.data),O()},onKeyDown:W=>{if(W.key!=="Enter"||W.shiftKey)return;if(W.nativeEvent.isComposing||W.keyCode===229||Date.now()-A.current<E){W.preventDefault(),zN(P.current)&&!T.current&&(T.current=!0,M.current=setTimeout(O,_));return}W.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:WN({hasDraft:$,isBusy:o}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${$&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:$&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":b("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:$?"text-white":"text-text-muted",children:n.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(j||L&&y)&&n.jsx("div",{className:`pt-1.5 px-1 text-2xs ${j?"text-red-400":"text-[var(--accent-primary)]"}`,children:j||b("chatInput.dropImage")}),i&&!j&&n.jsx("div",{className:"pt-2 px-1 text-2xs text-text-muted opacity-80",children:i})]})});function VN({entries:e,onSendNow:t,onCancelQueued:s,isSendingNow:r}){const{t:o}=he(),a=e.filter(d=>d.queued===!0&&!!d.id);if(a.length===0)return null;const i=a.some(d=>d.stale!==!0),l=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":l,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 GN=c.memo(VN,(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})),YN={accent:{track:"--accent-primary",head:"--accent-primary-light"},success:{track:"--status-online",head:"--status-online"},muted:{track:"--text-muted",head:"--text-muted"}};function tn({size:e=28,thickness:t=2.5,color:s="accent",className:r,label:o}){const a=YN[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:ct("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 QN=1e4;function JN({machineId:e,blocked:t,retryConnection:s}){const{t:r}=he("common"),[o,a]=c.useState(!1),i=c.useRef(null);if(c.useEffect(()=>{t||a(!1)},[t]),c.useEffect(()=>{if(!o)return;const d=setTimeout(()=>a(!1),QN);return()=>clearTimeout(d)},[o]),c.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),!e||!t||!s)return null;const l=()=>{o||(a(!0),s(e))};return n.jsxs("button",{type:"button","data-testid":"chat-machine-reconnect",onClick:l,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(tn,{size:11,thickness:2,color:"muted"}):n.jsx(yr,{size:12}),n.jsx("span",{children:r(o?"chatPane.reconnectingMachine":"chatPane.reconnectMachine")})]})}let qf=yn;function Ii(){return qf()}class XN{constructor(){ze(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 zf=new XN;class ZN{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 Dt=new ZN;function eC(e){e.dashboardWS&&(zf=e.dashboardWS),e.connectionManager&&(Dt=e.connectionManager),e.useDaemonsHook&&(qf=e.useDaemonsHook)}function Sa(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Vf="adhdev-pending-queued-messages-v1",tC=256*1024,nC=24*60*60*1e3,Gf=10*60*1e3;function Yf(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Vf)||"{}");return{byKey:e.byKey&&typeof e.byKey=="object"?e.byKey:{}}}catch{return{byKey:{}}}}function sC(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Vf,JSON.stringify(e))}catch{}}function rC(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(l=>typeof l=="string"):[]),a=[];for(const l of s.parts){if(!l||typeof l!="object")continue;const d=l,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<=tC){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 Qf(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,l=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(!l.trim()||!d||!u||t-d>nC||s.has(u))continue;s.add(u);const m=i.stale===!0||t-d>Gf,h=rC(i.input,l);r.push({entry:{id:u,content:l,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 oC(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 aC(e,t=Date.now()){const s=String(e||"").trim();return s?Qf(Yf().byKey[s],t):[]}function iC(e,t,s=Date.now()){const r=String(e||"").trim();if(!r)return;const o=Yf(),a=Qf(t,s);a.length>0?o.byKey[r]=a:delete o.byKey[r],sC(o)}function Jf(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}const cC=12e4;function lC(e){if(typeof e=="string")return e.trim();if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}const dC=/^(?:\s*(?:\[Image #\d+\]|\[image: [^\]\n]{1,100}\]))+\s*/;function uC(e,t){const s=lC(e);if(s===t)return!0;const r=s.replace(dC,"").trim();return r!==s&&r.length>0&&r===t}function mC(e,t){if(!t)return!1;const s=e.meta;return typeof(s==null?void 0:s.sourceMessageId)=="string"&&s.sourceMessageId===t}function cm(e){const t=e.meta;return typeof(t==null?void 0:t.sourceMessageId)=="string"&&t.sourceMessageId.length>0}function Xf(e,t){if(!t)return 0;let s=0;for(const r of e)String(r.role||"").toLowerCase()==="user"&&uC(r.content,t)&&(s+=1);return s}function hC(e,t,s=Date.now(),r=Gf){if(!e||e.length===0)return{entries:[],changed:!1,retiredByEcho:0,markedStale:0};const o=new Map,a=[];let i=0,l=0,d=!1;const u=t.some(m=>cm(m))?t.filter(m=>!cm(m)):t;for(const m of e){const h=m.content.trim();if(!h){d=!0;continue}if(t.some(f=>mC(f,m.id))){i+=1,d=!0;continue}o.has(h)||o.set(h,Xf(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){l+=1,d=!0,a.push({...m,stale:!0});continue}a.push(m)}return d?{entries:a,changed:!0,retiredByEcho:i,markedStale:l}:{entries:e,changed:!1,retiredByEcho:0,markedStale:0}}function pC(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 fC(e,t,s=Date.now(),r={}){if(!t||t.length===0)return e;const o=new Map,a=[];for(const i of t){const l=i.content.trim();if(!l||s-i.sentAt>cC)continue;o.has(l)||o.set(l,Xf(e,l));const d=o.get(l)||0;if(d>0){o.set(l,d-1);continue}r.excludeQueued&&i.queued===!0&&i.id||a.push(pC(i))}return a.length===0?e:[...e,...a]}function bC(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 gc(e){return bC(e)?String(e.role||"").toLowerCase():""}const gC=4;function xC(e,t){if(e.length===0)return[];for(let a=t.length-1;a>=0;a-=1)if(gc(t[a])==="assistant")return[];const s=t.some(a=>gc(a)==="user"),r=[];let o=!1;for(let a=e.length-1;a>=0&&r.length<gC;a-=1){const i=e[a],l=gc(i);if(l){if(!o&&l==="assistant"){r.unshift(i),o=!0;continue}if(o&&l==="user"){s||r.unshift(i);break}}}return r}function yC(e){let t=!0;for(let s=1;s<e.length;s+=1)if(Sa(e[s-1])>Sa(e[s])){t=!1;break}return t?e:e.map((s,r)=>({message:s,index:r,ts:Sa(s)})).sort((s,r)=>s.ts-r.ts||s.index-r.index).map(s=>s.message)}function vC(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,l=xC(a,i),d=l.length>0?[...l,...i]:i,u=t.length===0?d:[...t,...d];return yC(u)}const ft=e=>e.transport==="pty",Mr=(e,t)=>ft(e)&&e.mode||"chat",Zf=(e,t)=>ft(e)&&Mr(e)==="terminal",wC=180;function bs(e){return e.streamSource!=="agent-stream"}function Xn(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Mi(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 eb(e){return e.machineName||""}function vs(e){return Xn(e)}function $n(e){return e.agentType||""}function Ua(e){return e.hostIdeType||""}function Rd(e){return e.displayPrimary||e.agentName||"Agent"}function tb(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function SC(e,t){const s=Jf(e,t),r=[...s].reverse();return r.find(o=>!(o!=null&&o._localId)&&jd(o).isUserFacing)||r.find(o=>!(o!=null&&o._localId))||s[s.length-1]}function nb(e,t){const s=SC(e,t),r=br(s==null?void 0:s.content),o=br(e.lastMessagePreview);return o&&e.lastMessageRole==="assistant"&&(s==null?void 0:s.role)==="user"?o:r||o||""}function kC(e,t=wC){const s=br(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 jC(e){return kC(nb(e)||e.displaySecondary||"")}function sb(e){return[e.displaySecondary,eb(e)].filter(Boolean)}function wr(e){return e.agentName||$t($n(e))}function NC(e){var t,s;if(!bs(e)){const r=(s=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:s.trim();if(r)return r}return $t(Ua(e)||$n(e))}function rb(e){return bs(e)?e.sessionId:e.nativeSessionId}function lm(e){return bs(e)?"native":e.tabKey}function CC(e){return e.sessionId}function ob(e,t){if(t)return bs(e)||!t.childSessions?t:t.childSessions.find(s=>s.id===e.sessionId||s.providerType===e.agentType)||t}function _C(e,t){const s=$n(e),r=bs(e),o=ft(e),a=r?o?wr(e)||(t==null?void 0:t.cliName)||$t(Ua(e)||s):t!=null&&t.type?$t(t.type):$t(Ua(e)||s):wr(e);return{isNativeConversation:r,isCli:ft(e),isCliTerminal:Zf(e),providerType:s,displayLabel:a,targetEntry:ob(e,t)}}function gs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:ft(e)?{agentType:$n(e)}:e.streamSource==="agent-stream"?{agentType:$n(e)}:t}function ps(e){return e?vs(e):""}function dr(e,t){e(s=>[...s,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}const AC="Waiting for approval…",TC="Waiting for your answer…";function Ri(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 ab(e){return Ri(e)?(e==null?void 0:e.status)==="waiting_choice"?TC:AC:null}function Xo(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 ib(){return"select_session"}function IC(){return"open_panel"}function MC({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function RC(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 Ls(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}const so="Waiting to send — the agent is still working.",PC="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 EC({feedbackMessage:e,lastSendQueued:t,isGenerating:s}){return!t||e!==so?!1:!s}function Pd(e){return e instanceof Error?e.message:String(e||"")}function mm(e){const t=Pd(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function hm(e,t){const s=Pd(t);return s?s.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${s}`:`⚠️ **${e}** unavailable`}const LC=5e3;function DC(e,t,s=LC){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 OC(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,...gs(r)}}function Pi({sendDaemonCommand:e,activeConv:t,setActionLogs:s,isStandalone:r}){const[o,a]=c.useState(!1),[i,l]=c.useState(!1),[d,u]=c.useState(null),[m,h]=c.useState(!1),[p,b]=c.useState([]),f=c.useRef(!1),x=c.useRef(null),g=c.useRef([]);g.current=p;const w=c.useRef(new Map),S=(t==null?void 0:t.tabKey)||"",C=c.useRef(S);C.current=S;const j=c.useCallback(_=>{b(I=>{const D=_(I);return D===I?I:(iC(C.current,D),D)})},[]),v=c.useCallback(_=>{j(I=>{const D=hC(I,_);return D.changed?D.entries:I})},[j]);c.useEffect(()=>{u(null),h(!1),b(S?aC(S):[])},[t==null?void 0:t.tabKey,S]);const y=t?Us(t):!1;c.useEffect(()=>{u(_=>EC({feedbackMessage:_,lastSendQueued:m,isGenerating:y})?null:_),!y&&m&&h(!1)},[y,m]);const N=c.useCallback(async(_,I)=>{if(!t||f.current)return!1;const D=_.trim(),L=Ri(t);if(MC({hasMessage:!!D,blockedMessage:L,sendInFlight:f.current}))return L&&u(L),!1;const $=Date.now(),U={tabKey:t.tabKey,message:D,timestamp:$};if(RC(x.current,U))return u(null),!0;f.current=!0,l(!0),u(null),h(!1),x.current=U;const J=oC($),K=OC(D,I);let R=()=>{};w.current.set(J,new Promise(H=>{R=H}));let O="not-parked";j(H=>[...H,{id:J,content:D,sentAt:$,...K?{input:K}:{}}].slice(-20));try{const H=ps(t);if(!H)return x.current=dm(x.current,U),j(W=>W.filter(ce=>ce.id!==J)),u("Unable to send message right now."),!1;const B=await e(H,"send_chat",pm(J,D,K,t)),q=Ls(B);if(q!=null&&q.deduplicated)return u(null),!0;if(um(q))return O="parked",h(!0),j(W=>W.map(ce=>ce.id===J?{...ce,queued:!0}:ce)),u(so),!0;if((q==null?void 0:q.sent)===!1)throw new Error((q==null?void 0:q.error)||"Send failed");if((q==null?void 0:q.success)===!1)throw new Error((q==null?void 0:q.error)||"Send failed");return h(!1),u(null),!0}catch(H){const B=Pd(H);return B.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",B):console.warn("Send blocked/failed",H),x.current=dm(x.current,U),j(q=>q.filter(W=>W.id!==J)),u(Xo(H)),!1}finally{w.current.delete(J),R(O),j(H=>H.map(B=>B.id===J?{...B,settled:!0}:B)),f.current=!1,l(!1)}},[t,e,j]),k=c.useCallback(async _=>{if(!t||f.current)return!1;const I=g.current,D=_?I.find(U=>U.id===_):I.find(U=>U.queued===!0);if(!D||!D.queued)return!1;const L=D.content.trim();if(!L)return!1;const $=D.id;f.current=!0,l(!0),u(null);try{const U=ps(t);if(!U)return u("Unable to send message right now."),!1;const J=await e(U,"send_chat",pm($,L,D.input,t,{mode:"send_now"})),K=Ls(J);return(K==null?void 0:K.success)===!1?(u(Xo(new Error((K==null?void 0:K.error)||"Send now failed"))),!1):(K==null?void 0:K.queuedWithAgent)===!0?(h(!1),j(R=>R.map(O=>O.id===$?{...O,queued:!1}:O)),u(null),!0):um(K)?(h(!0),j(R=>R.map(O=>O.id===$?{...O,queued:!0}:O)),u(so),!0):(h(!1),j(R=>R.map(O=>O.id===$?{...O,queued:!1}:O)),u(null),!0)}catch(U){return console.warn("Send now blocked/failed",U),u(Xo(U)),!1}finally{f.current=!1,l(!1)}},[t,e,j]),A=c.useCallback(async _=>{if(!t||!_)return!1;const I=g.current.find(L=>L.id===_);if(!I)return!1;const D=I.content.trim();if(I.settled&&!I.queued)return j(L=>L.filter($=>$.id!==_)),!0;if(!I.settled&&await DC(w.current,_)==="not-parked")return j($=>$.filter(U=>U.id!==_)),!0;try{const L=ps(t);if(!L)return u("Unable to cancel this message right now."),!1;const $=await e(L,"cancel_queued_chat",{messageId:_,message:D,...gs(t)}),U=Ls($),J=typeof(U==null?void 0:U.cancelled)=="number"&&U.cancelled===0;return J&&I.stale===!0?(j(K=>K.filter(R=>R.id!==_)),u(K=>K===so?null:K),!0):(U==null?void 0:U.success)===!1||J?(u(PC),!1):(j(K=>K.filter(R=>R.id!==_)),u(K=>K===so?null:K),!0)}catch(L){return console.warn("Cancel queued send failed",L),u(Xo(L)),!1}},[t,e,j]),E=c.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(_){console.error("Relaunch failed",_)}},[t,e]),P=c.useCallback(async _=>{if(t)try{const D=(t.modalButtons||[]).indexOf(_),L=_.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),$=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(L),U=ps(t);if(!U)return;const J=await e(U,"resolve_action",{button:_,action:$?"approve":"reject",...D>=0&&{buttonIndex:D},...gs(t),...Mi(t)}),K=Ls(J);K.success||s(R=>[...R,{routeId:t.tabKey,text:hm(_,K==null?void 0:K.error),timestamp:Date.now()}])}catch(I){mm(I)||console.error("[ModalButton] Error:",I),s(D=>[...D,{routeId:t.tabKey,text:mm(I)?hm(_,I):`❌ **${_}** error`,timestamp:Date.now()}])}},[t,e,s]),T=c.useCallback(async()=>{if(!(!t||o)){a(!0);try{await e(t.routeId,IC(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(_){console.error("Focus agent failed",_)}finally{a(!1)}}},[t,o,e]),M=p.length>0?p[p.length-1]:null;return c.useMemo(()=>({isSendingChat:i,sendFeedbackMessage:d,lastSendQueued:m,pendingLocalMessage:M,pendingLocalMessages:p,isFocusingAgent:o,handleSendChat:N,handleSendNowQueued:k,handleCancelQueued:A,retireEchoedPendingMessages:v,handleRelaunch:E,handleModalButton:P,handleFocusAgent:T}),[i,d,m,M,p,o,N,k,A,v,E,P,T])}const $C=10,FC=8e3,HC=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function BC(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 Il(e,t="",s=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(HC.test(t)&&e.trim())return"[REDACTED:secret-field]";const r=BC(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=>Il(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,Il(o,r,s+1)]))}function Kr(e,t){return Array.isArray(e)?e.slice(-t):[]}function WC(e,t=Date.now()){const s=e&&t-e.firstAt<=FC,r=s?e.count+1:1;return r>=$C?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:r,firstAt:s?e.firstAt:t},shouldCollect:!1}}function cb(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.chatState.liveMessages)==null?void 0:r.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((o=e.chatState.historyMessages)==null?void 0:o.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Kr(e.chatState.liveMessages??t.messages,10),activeConversationMessagesTail:Kr(t.messages,10),visibleMessagesTail:Kr(e.visibleMessages,5),historyMessagesTail:Kr(e.chatState.historyMessages,5),actionLogsTail:Kr(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chat:{hasLiveSnapshot:!!e.chatState.hasLiveSnapshot,hasMoreHistory:!!e.chatState.hasMoreHistory,historyError:e.chatState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return Il(s)}function lb(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 db(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 ub(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(`
38
- `)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
39
-
40
- \`\`\`json
41
- ${JSON.stringify(t.bundle,null,2)}
42
- \`\`\``:`# ADHDev Chat Debug Bundle
43
-
44
- \`\`\`json
45
- ${JSON.stringify(t,null,2)}
46
- \`\`\``}function mb(e,t,s){if(s.mode!=="delta")return{...s,mode:"snapshot"};const r=t?e.docOf(t):void 0;return!t||!r||typeof t.seq=="number"&&s.seq!==t.seq+1?null:e.snapshotOf(Uv(r,e.deltaOf(s),e.spec),s,t)}const UC=["topic","key","mode","seq","timestamp","wireVersion"],KC={spec:Kv,docOf:e=>{if(e.status===void 0)return;const t={...e};for(const s of UC)delete t[s];return t},deltaOf:e=>e.delta,snapshotOf:(e,t,s)=>{const r=e;return{...r,topic:"daemon.metadata",key:t.key,mode:"snapshot",daemonId:t.daemonId||s.daemonId,status:{...r.status,timestamp:t.timestamp},seq:t.seq,timestamp:t.timestamp}}},qC={spec:qv,docOf:e=>e.status||void 0,deltaOf:e=>e.delta,snapshotOf:(e,t,s)=>({topic:"mesh.status",key:t.key,mode:"snapshot",meshId:t.meshId||s.meshId,status:e,seq:t.seq,timestamp:t.timestamp})};function zC(e,t){return mb(KC,e,t)}function VC(e,t){return mb(qC,e,t)}const Ka=new Map,Ml=new Set;let ka={reloadRequired:!1,daemonUpdateRequired:[]};function GC(){const e=[];let t=!1;for(const[s,r]of Ka)r==="reload_required"?t=!0:r==="daemon_update_required"&&e.push(s);if(e.sort(),!(t===ka.reloadRequired&&e.join(`
47
- `)===ka.daemonUpdateRequired.join(`
48
- `))){ka={reloadRequired:t,daemonUpdateRequired:e};for(const s of Ml)s()}}function Rl(e,t){const s=Oy(Cp,t);return s==="ok"?Ka.delete(e):Ka.set(e,s),GC(),s}function YC(e){return Ka.get(e)??"ok"}function fm(){return ka}function QC(e){return Ml.add(e),()=>{Ml.delete(e)}}function xc(e,t){return`${e}:${t}`}const JC=new Set(["intervalMs"]);function bm(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]=JC.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 xm(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function XC(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function ls(e,t){XC()&&console.debug(`[subscription-manager] ${e}`,t)}class ZC{constructor(){ze(this,"active",new Map);ze(this,"retryTimers",new Map)}subscribe(t,s,r,o,a){var h,p;r={...r,wireVersion:Cp};const i=xc(r.topic,r.key),l=this.active.get(i);let d=!0;if(l){l.transport=t,l.handlers.add(o),l.handlerParams.set(o,gm(r));const b={...r,params:bm(l.handlerParams.values())};(!xm(l.request,b)||l.daemonId!==s)&&(l.daemonId=s,l.request=b,d=((h=t.sendData)==null?void 0:h.call(t,s,b))??!1,!d&&(a!=null&&a.retryIntervalMs)?this.scheduleRetry(i,t,a.retryIntervalMs):d&&this.clearRetry(i),ls("subscribe_update",{daemonId:s,topic:r.topic,key:r.key,accepted:d})),l.lastUpdate&&o(l.lastUpdate)}else{const b={daemonId:s,request:r,handlers:new Set([o]),handlerParams:new Map([[o,gm(r)]]),transport:t};this.active.set(i,b),ls("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 g,w;if(u)return;u=!0,this.clearRetry(i);const b=this.active.get(i);if(!b)return;if(b.handlers.delete(o),b.handlerParams.delete(o),b.handlers.size>0){const S={...b.request,params:bm(b.handlerParams.values())};xm(b.request,S)||(b.request=S,(g=t.sendData)==null||g.call(t,b.daemonId,S));return}this.active.delete(i);const f=b.daemonId,x={type:"unsubscribe",topic:r.topic,key:r.key};ls("unsubscribe",{daemonId:f,topic:r.topic,key:r.key}),(w=t.sendData)==null||w.call(t,f,x)};return m.initialSendAccepted=d,m}publish(t){var l,d,u,m;const s=t,r=xc(s.topic,s.key),o=this.active.get(r);if(!o)return;this.clearRetry(r);const a=s.mode;if(a==="protocol_mismatch"){Rl(o.daemonId,t.daemonWireVersion);return}if((s.topic==="daemon.metadata"||s.topic==="mesh.status")&&a!=="delta"){if(Rl(o.daemonId,s.wireVersion)!=="ok")return}else if(YC(o.daemonId)!=="ok")return;let i=s;if(s.topic==="daemon.metadata"){const h=zC(o.lastUpdate,s);if(!h){ls("metadata_resync",{daemonId:o.daemonId,key:s.key,seq:s.seq}),o.lastUpdate=void 0,(d=(l=o.transport)==null?void 0:l.sendData)==null||d.call(l,o.daemonId,o.request);return}i=h}else if(s.topic==="mesh.status"){const h=VC(o.lastUpdate,s);if(!h){ls("mesh_status_resync",{daemonId:o.daemonId,key:s.key,seq:s.seq}),o.lastUpdate=void 0,(m=(u=o.transport)==null?void 0:u.sendData)==null||m.call(u,o.daemonId,o.request);return}i=h}o.lastUpdate=i,bo.record({interactionId:typeof i.interactionId=="string"?i.interactionId:void 0,kind:"subscription.publish",topic:i.topic,payload:{key:i.key}}),o.handlers.forEach(h=>{h(i),bo.record({interactionId:typeof i.interactionId=="string"?i.interactionId:void 0,kind:"subscription.handler_invoked",topic:i.topic,payload:{key:i.key}})})}updateParams(t,s,r){const o=xc(t,s),a=this.active.get(o);if(a){a.request={...a.request,params:{...a.request.params,...r}};for(const[i,l]of a.handlerParams)a.handlerParams.set(i,{...l,...r})}}resubscribeAll(t){var s;ls("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())r.transport=t,(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);ls("resubscribe_daemon",{daemonId:t,count:r.length,subscriptions:r.map(a=>({topic:a.request.topic,key:a.request.key}))});for(const a of r)a.transport=s,(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 l;this.retryTimers.delete(t);const a=this.active.get(t);if(!a)return;const i=((l=s.sendData)==null?void 0:l.call(s,a.daemonId,a.request))??!1;ls("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 Fn=new ZC,ym=["lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash"],vm=["controlValues","providerControls","summaryMetadata","settings","messageInput"];function e_(e){const t=e;return{...t.assistant===!0?{assistant:!0}:{},...t.managedByAssistant===!0?{managedByAssistant:!0}:{}}}const t_=["runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients"];function qr(e,t){const s={};for(const r of t)e[r]!==void 0&&(s[r]=e[r]);return s}function n_(e){const{ownerDaemonId:t,ownerMachineName:s}=e;return{...t&&{ownerDaemonId:t},...s&&{ownerMachineName:s}}}function s_(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 r_(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 wm(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function o_(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function a_(e){o_()&&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 hb(e,t){const s=[],{daemonId:r,existingDaemon:o,existingEntries:a,timestamp:i}=t,l=i||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:u,childrenByParent:m}=r_(d),h=s_(a,r),p=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,b=u.filter(x=>x.kind==="workspace"&&x.transport==="cdp-page"),f=u.filter(x=>x.kind==="agent"&&x.transport==="pty");s.push({...o||{},id:r,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...p&&{machine:p,platform:p.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.screenshotUsage!==void 0&&{screenshotUsage:e.screenshotUsage},...e.providerChannelStaleness&&{providerChannelStaleness:e.providerChannelStaleness},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:b.some(x=>!!x.cdpConnected)});for(const x of b){const g=h.get(x.id),w=ga(x,g),S=(m.get(x.id)||[]).map(C=>ga(C,h.get(C.id)));s.push({id:`${r}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(g==null?void 0:g.providerSessionId),parentSessionId:w.parentId,sessionKind:w.kind,transport:w.transport,sessionCapabilities:w.capabilities,type:w.providerType,status:w.cdpConnected?"online":"detected",daemonId:r,instanceId:wm(r,x.id),workspace:w.workspace,terminals:0,childSessions:S,agents:S.map(C=>({id:C.id,name:C.providerName||C.providerType,type:C.providerType,status:C.status})),activeChat:w.activeChat,...w.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:w.activeInteractivePrompt},chats:[],cdpConnected:w.cdpConnected,...qr(w,ym),lastUpdated:w.lastUpdated,unread:w.unread,lastSeenAt:w.lastSeenAt,inboxBucket:w.inboxBucket,completionMarker:w.completionMarker,seenCompletionMarker:w.seenCompletionMarker,surfaceHidden:w.surfaceHidden,muted:w.muted,...qr(w,vm),timestamp:l})}for(const x of f){const g=h.get(x.id),w=ga(x,g);s.push({id:`${r}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(g==null?void 0:g.providerSessionId),parentSessionId:w.parentId,sessionKind:w.kind,transport:w.transport,sessionCapabilities:w.capabilities,type:w.providerType,agentType:w.providerType,status:Gv(w.status)||"generating",daemonId:r,instanceId:wm(r,x.id),cliName:w.providerName||w.providerType,mode:w.mode||(g==null?void 0:g.mode)||"terminal",workspace:w.workspace||"",...n_(x),activeChat:w.activeChat,...w.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:w.activeInteractivePrompt},...w.resume!==void 0&&{resume:w.resume},...qr(w,t_),...qr(w,ym),lastUpdated:w.lastUpdated,unread:w.unread,lastSeenAt:w.lastSeenAt,inboxBucket:w.inboxBucket,completionMarker:w.completionMarker,seenCompletionMarker:w.seenCompletionMarker,surfaceHidden:w.surfaceHidden,muted:w.muted,...qr(w,vm),...e_(w),timestamp:l,_isCli:!0})}return a_(s),s}const yc=new Set;function Rr(){const{sendData:e}=wt(),{injectEntries:t,getIdes:s}=gr(),r=c.useRef(new Map);return c.useEffect(()=>{const o=r.current;return()=>{for(const[a,i]of o)i(),yc.delete(a);o.clear()}},[]),c.useCallback(async(o,a)=>{var l;if(!o||!e||yc.has(o))return;const i=Fn.subscribe({sendData:e},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},d=>{const u=s(),m=u.find(p=>p.id===o),h=hb(d.status,{daemonId:o,existingDaemon:m,existingEntries:u,timestamp:d.timestamp});h.length>0&&t(h,{authoritativeDaemonIds:[o]})});(l=r.current.get(o))==null||l(),r.current.set(o,i),yc.add(o)},[s,t,e])}const i_=60,c_=50;function l_(e={}){return e.isCliLike?c_:i_}const pb=new Map;function Sm(e,t){if(!e)return t;const s=pb.get(e);return typeof s=="number"&&s>t?s:t}function d_(e,t){e&&pb.set(e,t)}function u_(e){return e.omittedBefore?{"data-transcript-omitted-before":"true"}:{}}function fb(e){const t={role:e.role,kind:e.kind,content:e.content,id:e.messageId,messageId:e.messageId,_ord:e.ord,_rev:e.rev};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.expandable&&(t._expandable=!0),e.turnKey!==null&&(t._turnKey=e.turnKey),t}class bb{constructor(){ze(this,"entries",new Map)}map(t){const s=new Map,r=t.map(o=>{const a=this.entries.get(o.messageId);let i=a;return!a||a.source!==o&&(a.source.rev!==o.rev||a.source.ord!==o.ord||a.source.content!==o.content)?i={source:o,mapped:fb(o)}:a.source!==o&&(i={source:o,mapped:a.mapped}),s.set(o.messageId,i),i.mapped});return this.entries=s,r}}function gb(e){if(!e||typeof e!="object")return!1;const t=e;if(t.schemaVersion!==2||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 xb(e,t={}){var s;return{messages:t.cache?t.cache.map(e.messages):e.messages.map(fb),status:e.status,omittedBefore:((s=e.coverage)==null?void 0:s.omittedBefore)===!0}}const m_=new Set([...ku("working"),...ku("blocked"),...Object.keys(Ap).filter(e=>Wy(e))]);function h_(e){return fi(e)}const p_=new Set(["agent:generating_completed","agent:stopped","agent:waiting_approval","agent:waiting_choice"]);function yb(e){return typeof e=="string"&&p_.has(e)}function f_(e,t){const{sendData:s,sendCommand:r}=wt(),o=(t==null?void 0:t.enabled)!==!1,a=vs(e),i=e.sessionId||"",l=Ai(e),d=e.messages.length,u=c.useMemo(()=>!o||!a||!i?null:Sb({daemonId:a,sessionId:i,historySessionId:l,sendData:s,fallbackRecentCount:d}),[a,o,l,s,i]);c.useEffect(()=>{u==null||u.updateOptions({fallbackRecentCount:d})},[u,d]);const[m,h]=c.useState(()=>(u==null?void 0:u.getSnapshot())||qa());c.useEffect(()=>{if(!u){h(qa());return}u.retain(),h(u.getSnapshot());const b=u.subscribe(f=>{h(f)});return()=>{b(),u.release()}},[u]);const p=c.useCallback(async()=>{!u||!a||!i||await u.loadHistoryPage(async({offset:b,excludeRecentCount:f,excludeFromIdentity:x})=>{const g=await r(a,"chat_history",{agentType:e.agentType,offset:b,limit:30,targetSessionId:i,historySessionId:l,excludeRecentCount:f,...x?{excludeFromIdentity:x}:{},...xo()?{includeActivity:!0}:{}}),w=g&&typeof g=="object"&&"result"in g?g.result||{}:g||{};return{messages:Array.isArray(w.messages)?w.messages:[],hasMore:w.hasMore===!0}})},[e.agentType,u,a,l,r,i]);return c.useMemo(()=>T_(m,p),[p,m])}function b_(e,t){const{sendData:s}=wt(),r=(t==null?void 0:t.enabled)!==!1,o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Ed)),a=R_(o),[i,l]=c.useState(0);c.useEffect(()=>{if(!r||e.length===0)return;const u=setInterval(()=>{l(m=>m+1)},a);return()=>{clearInterval(u)}},[e.length,r,a]);const d=c.useMemo(()=>P_(e,{recentActivityMs:o}),[e,o,i]);c.useEffect(()=>{if(!r||d.descriptors.length===0)return;const u=d.descriptors.map(m=>Sb({...m,...s?{sendData:s}:{}}));return u.forEach(m=>m.retain()),()=>{u.forEach(m=>m.release())}},[d.signature,r,s])}function g_(e){const[t,s]=c.useState(0),r=c.useMemo(()=>{const i=[];for(const l of e){const d=vs(l),u=l.sessionId||"";if(!d||!u)continue;const m=Ai(l);i.push(Ro(d,u,m||u))}return i},[e]),o=r.join("|"),a=c.useSyncExternalStore(wb,jm,jm);return c.useEffect(()=>{if(r.length===0)return;const i=[];for(const l of r){const d=Zn.get(l);if(!d)continue;let u=!1;i.push(d.subscribe(()=>{if(!u){u=!0;return}s(m=>m+1)}))}return()=>{for(const l of i)l()}},[o,a]),t}function x_(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 km=500,y_=15e3,Ed=12e4,Zn=new Map;let vb=0;const Pl=new Set;function El(){vb+=1;for(const e of Pl)e()}let vc=!1;function v_(){vc||(vc=!0,queueMicrotask(()=>{vc=!1,El()}))}function wb(e){return Pl.add(e),()=>{Pl.delete(e)}}function jm(){return vb}function Ro(e,t,s){return`${e}::${t}::${s||t}`}function qa(){return{liveMessages:[],hasLiveSnapshot:!1,historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null,omittedBefore:!1}}function w_(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}class S_{constructor(t){ze(this,"sendData");ze(this,"daemonId");ze(this,"sessionId");ze(this,"fallbackRecentCount");ze(this,"now");ze(this,"snapshot",qa());ze(this,"listeners",new Set);ze(this,"retainCount",0);ze(this,"loadHistoryPromise",null);ze(this,"bubbleCache",new bb);ze(this,"lastViewStatus",null);ze(this,"lastTerminalBaseRequestAt",0);this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.now=t.now??(()=>Date.now())}updateOptions(t){t.sendData&&(this.sendData=t.sendData),t.now&&(this.now=t.now),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount))}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...qa(),hasLiveSnapshot:!0},this.emit()}applyTranscriptView(t,s={}){if(!gb(t))return;const r=s.mapped??xb(t,{cache:this.bubbleCache});this.lastViewStatus=r.status;const o=this.snapshot,a=o.historyOffset>0?o.hasMoreHistory:r.omittedBefore;o.hasLiveSnapshot&&w_(o.liveMessages,r.messages)&&o.omittedBefore===r.omittedBefore&&o.hasMoreHistory===a||(this.snapshot={...o,liveMessages:r.messages,hasLiveSnapshot:!0,omittedBefore:r.omittedBefore,hasMoreHistory:a},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.retainCount+=1,this.retainCount===1&&El()}release(){const t=this.retainCount>0;this.retainCount=Math.max(0,this.retainCount-1),t&&this.retainCount===0&&El()}isRetained(){return this.retainCount>0}getIdentity(){return{daemonId:this.daemonId,sessionId:this.sessionId}}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const s=(async()=>{try{const o=this.snapshot.hasLiveSnapshot?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),a=await t({offset:this.snapshot.historyOffset,excludeRecentCount:o,excludeFromIdentity:x_(this.snapshot.liveMessages[0])}),i=Array.isArray(a.messages)?a.messages:[],l=[...i,...this.snapshot.historyMessages],d=l.length>km?l.slice(l.length-km):l;this.snapshot={...this.snapshot,historyMessages:d,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory: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}requestTranscriptBase(){if(!this.sendData||!this.daemonId||!this.sessionId)return!1;try{return this.sendData(this.daemonId,{type:"command",commandType:"request_transcript_base",data:{rawSessionId:this.sessionId}})===!0}catch{return!1}}noteTerminalStatusEvent(t){if(!yb(t)||!this.isRetained()||!h_(this.lastViewStatus))return!1;const s=this.now();return this.lastTerminalBaseRequestAt>0&&s-this.lastTerminalBaseRequestAt<y_?!1:(this.lastTerminalBaseRequestAt=s,this.requestTranscriptBase())}dispose(){this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null,this.lastViewStatus=null,this.lastTerminalBaseRequestAt=0}emit(){this.listeners.forEach(t=>t(this.snapshot))}}function Sb(e){const t=Ro(e.daemonId,e.sessionId,e.historySessionId),s=Zn.get(t);if(s)return s.updateOptions(e),s;const r=new S_(e);return Zn.set(t,r),v_(),r}function k_(e,t,s){if(!e||!t)return;const r=`${e}::${t}::`,o=Ro(e,t,s);for(const[a,i]of Zn.entries())(a===o||a.startsWith(r))&&i.clearLiveSnapshot()}function kb(e){const t=vs(e),s=e.sessionId||"";if(!t||!s)return;const r=Ai(e),o=Ro(t,s,r||s),a=Zn.get(o);if(!a)return;const i=a.getSnapshot();return i.hasLiveSnapshot?i:void 0}const wc=new Map;function j_(e,t,s){if(!e||!t)return 0;const r=`${e}::${t}::`;let o,a=0;for(const[i,l]of Zn.entries())if(i.startsWith(r)){if(!o&&gb(s)){let d=wc.get(r);d||(d=new bb,wc.set(r,d)),o=xb(s,{cache:d})}l.applyTranscriptView(s,o?{mapped:o}:{}),a+=1}return a===0&&wc.delete(r),a}function N_(e,t){if(!e||!t)return!1;const s=`${e}::${t}::`;for(const[r,o]of Zn.entries())if(r.startsWith(s)&&o.requestTranscriptBase())return!0;return!1}function C_(e,t,s){if(!e||!t||!yb(s))return!1;const r=`${e}::${t}::`;for(const[o,a]of Zn.entries())if(o.startsWith(r)&&a.noteTerminalStatusEvent(s))return!0;return!1}function __(){const e=new Map;for(const s of Zn.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 A_(e){return wb(e)}function T_(e,t){return{...e,loadHistoryPage:t}}function I_(e,t){return e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function M_(e,t={}){const s=String(e.status||"").trim().toLowerCase();if(m_.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??Ed)),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 R_(e=Ed){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function P_(e,t={}){const s=new Set,r=[];for(const o of e){if(!M_(o,t))continue;const a=vs(o),i=o.sessionId||"";if(!a||!i)continue;const l=Ai(o),d=Ro(a,i,l||i);s.has(d)||(s.add(d),r.push({daemonId:a,sessionId:i,historySessionId:l}))}return r.sort(I_),{descriptors:r,signature:r.map(o=>`${o.daemonId}|${o.sessionId}|${o.historySessionId}`).join("||")}}function E_(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function L_(e){return E_(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const ja=new Map,Ll=new Set;function Nm(e,t){!e||ja.get(e)===t||(t?ja.set(e,!0):ja.delete(e),Ll.forEach(r=>r(e,t)))}function D_(e){return e?ja.get(e)===!0:!1}function O_(e){return Ll.add(e),()=>{Ll.delete(e)}}function $_(e,t,s=`${t}s`){return`${e} ${e===1?t:s}`}function F_(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 jb(e){return fi(e.status)||e.inboxBucket==="working"}function Nb(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 B_(e){return jb(e)?!1:e.inboxBucket==="task_complete"&&Nb(e).length>0}function Cm(e){return e.branch||"detached HEAD"}function W_(e){if(e.error)return`${Cm(e)} · Git error: ${e.error}`;const t=[Cm(e)];return e.changedFiles>0?t.push($_(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 U_(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${W_(t)}`}function K_(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function q_(e,t={}){if(t.enabled===!1)return[];if(!H_(e))return[];const s=jb(e)?"working":B_(e)?"complete":null;if(!s)return[];const r=s==="complete"?Nb(e):"";return[{id:s==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${F_(r)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",visibility:"visible",content:U_(s,e.git),timestamp:K_(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 z_=60,V_=3e4;function G_(e){return{enabled:!!e.sessionId}}function Y_(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 Q_=["unsupported_source","source_unavailable","source_changed","block_not_found","not_a_tool_block"];function J_(e){return Q_.find(t=>t===e)}function Cb({activeConv:e,ideEntry:t,handleSendChat:s,handleSendNowQueued:r,handleCancelQueued:o,isSendingChat:a=!1,sendFeedbackMessage:i=null,pendingLocalMessage:l=null,pendingLocalMessages:d=null,retireEchoedPendingMessages:u,handleFocusAgent:m,isFocusingAgent:h,actionLogs:p,userName:b,scrollToBottomRequestNonce:f,isInputActive:x=!0,isVisible:g=!0}){var re,we,V,de,ge,Ie,Ke;const{t:w}=he("common"),S=c.useRef(new Map),C=c.useRef(void 0),j=Rr(),{sendCommand:v}=wt(),{isVisible:y}=_d(),N=Ii(),k=vs(e),A=yt.useMemo(()=>{const Ae=N.connectionRetryStatuses;if(!Ae||!k)return;const Ne=Ae[k];if(Ne)return Ne;const He=Object.keys(Ae).find(Fe=>mn(Fe,k));return He?Ae[He]:void 0},[N.connectionRetryStatuses,k]);Io("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:p.length,isSendingChat:a});const E=yt.useMemo(()=>Ss(e),[e.status,e.connectionState]);yt.useEffect(()=>{const Ae=e.sessionId;if(Ae)return Nm(Ae,E.isGenerating),()=>{Nm(Ae,!1)}},[e.sessionId,E.isGenerating]);const P=c.useMemo(()=>_C(e,t),[e,t]),T=c.useMemo(()=>$N(P.targetEntry),[P.targetEntry]),M=c.useMemo(()=>{var Ae;return Md((Ae=P.targetEntry)==null?void 0:Ae.providerControls,{hostIdeType:e.hostIdeType,providerType:P.providerType})},[e.hostIdeType,P.providerType,(re=P.targetEntry)==null?void 0:re.providerControls]),_=l_({isCliLike:P.isCli}),I=f_(e,G_({sessionId:e.sessionId})),[D,L]=c.useState(()=>Sm(e.tabKey,_)),$=e.assistant===!0,[U,J]=c.useState(()=>xo()),[K,R]=c.useState(()=>TS()),O=$?K:U,H=e.tabKey,B=I.historyMessages,q=I.hasMoreHistory,W=I.historyError,ce=Jf(e,I),ye=Mk({status:e.status,connectionState:e.connectionState,hasLiveSnapshot:I.hasLiveSnapshot,visibleMessageCount:ce.length}),G=fC(ce,d??(l?[l]:null),void 0,{excludeQueued:!0}),Se=((d==null?void 0:d.length)??0)>0;c.useEffect(()=>{if(!u||(u(ce),!Se))return;const Ae=setInterval(()=>u(ce),V_);return()=>clearInterval(Ae)},[u,ce,Se]);const ue=c.useMemo(()=>jS(G).length,[G]);c.useEffect(()=>{L(Sm(H,_))},[_,H]);const ne=Math.max(0,G.length-D),ae=Rd(e),ee=vs(e),oe=L_(e),Ce=Ri(e),Q=Y_(e,w),z=i||null,X=ab(e)||i||Q,pe=!!Ce,[Pe,Oe]=c.useState(!1);c.useEffect(()=>{const Ae=P.targetEntry;ee&&(!Ae||Ae.providerControls===void 0||Ae.controlValues===void 0)&&j(ee,{minFreshMs:3e4}).catch(()=>{})},[ee,(we=P.targetEntry)==null?void 0:we.providerControls,(V=P.targetEntry)==null?void 0:V.controlValues,j]);const Le=c.useCallback(async()=>{if(!Pe){if(G.length>D){L(Ae=>{const Ne=Math.min(G.length,Ae+z_);return d_(H,Ne),Ne});return}Oe(!0);try{await I.loadHistoryPage()}finally{Oe(!1)}}},[I,Pe,G.length,H,D]),{allMessages:ke,receivedAtMap:Y}=c.useMemo(()=>{const Ae=vC({historyMessages:B,liveMessages:G,visibleLiveCount:D}),Ne=q_(e),He=Ne.length>0?[...Ae,...Ne]:Ae,Fe={};return He.forEach((it,ut)=>{const dt=vd(it),Tt=`${e.tabKey}:${dt}`;let bt=Sa(it)||S.current.get(Tt)||0;bt||(bt=Date.now(),S.current.set(Tt,bt)),Fe[dt]=bt}),{allMessages:He,receivedAtMap:Fe}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,ne,B,G,D]),ve=c.useMemo(()=>p.filter(Ae=>Ae.routeId===e.tabKey).sort((Ae,Ne)=>Ae.timestamp-Ne.timestamp),[p,e.tabKey]),Z=c.useCallback(async Ae=>{if(!ee)return{status:"error"};try{const Ne=await v(ee,"expand_tool_block",{targetSessionId:e.sessionId,agentType:P.providerType||e.agentType,..."messageId"in Ae?{messageId:Ae.messageId}:{toolBlockRef:Ae.toolBlockRef}}),He=Ls(Ne),Fe=He!=null&&He.success?He.callArgs!==void 0?`${He.toolName?`${He.toolName}: `:""}${He.callArgs}`:He.result:void 0;return Fe!==void 0?{status:"expanded",text:Fe}:{status:"error",error:J_(He==null?void 0:He.reason)}}catch{return{status:"error"}}},[e.agentType,e.sessionId,P.providerType,ee,v]),ie=c.useCallback(async()=>{var ut,dt;if(!ee)return;const Ae=cb({activeConv:e,visibleMessages:ke,actionLogs:p,controls:(ut=P.targetEntry)==null?void 0:ut.providerControls,controlValues:(dt=P.targetEntry)==null?void 0:dt.controlValues,visibleBarControlCount:M.length,chatState:{liveMessages:I.liveMessages,hasLiveSnapshot:I.hasLiveSnapshot,hasMoreHistory:q,historyError:W,historyMessages:B},ui:{controlsVisible:y,visibleLiveCount:D,activityVisible:O,activityCount:ue,hiddenLiveCount:ne,isInputActive:x,isVisible:g}}),Ne=await v(ee,"get_chat_debug_bundle",{agentType:P.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:Ae}),He=Ls(Ne),Fe=ub(He),it=await db(Fe);it==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),et.showToast(lb(He,{locatorCopyStatus:it}),it==="failed"?"warning":"success")},[e,p,ue,ke,y,I.hasLiveSnapshot,I.liveMessages,P.providerType,(de=P.targetEntry)==null?void 0:de.controlValues,(ge=P.targetEntry)==null?void 0:ge.providerControls,ee,q,ne,B,x,g,W,v,O,M.length,D]);c.useEffect(()=>df(J),[]);const F=c.useCallback(()=>{if($){R(Ae=>{const Ne=!Ae;return IS(Ne),Ne});return}J(Ae=>{const Ne=!Ae;return lf(Ne),Ne})},[$]),se=c.useCallback(()=>{const Ae=WC(C.current);C.current=Ae.state,Ae.shouldCollect&&ie().catch(Ne=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",Ne),et.showErrorToast(w("chatPane.debugBundleFailed"),Ne)})},[ie,w]),me=c.useMemo(()=>{if(G.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:[w("chatPane.connectingToMachine"),n.jsx("span",{className:"connecting-dots"})]}),n.jsx("div",{className:"text-2xs opacity-35",children:w("chatPane.establishingP2P")})]})]});if(E.isGenerating&&Oe(!1),e.status==="not_monitored"&&oe)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(yr,{size:28})}),n.jsx("div",{className:"text-xxs opacity-50",children:w("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(vr,{size:12}),w("chatPane.switchingPanel")]}):n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Ws,{size:14})," ",w("chatPane.openPanel",{label:ae})]})}),n.jsx("div",{className:"text-2xs opacity-35 max-w-[280px]",children:w("chatPane.clickToSwitchMonitoring")})]});if(e.status==="panel_hidden"&&oe)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(pd,{size:28})}),n.jsx("div",{className:"text-xxs opacity-50",children:w("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(vr,{size:12}),w("chatPane.openingPanel")]}):n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Ws,{size:14})," ",w("chatPane.openPanel",{label:ae})]})}),n.jsx("div",{className:"text-2xs opacity-35 max-w-[280px]",children:w("chatPane.openPanelHint")})]});if(ye.awaitingFirstView)return n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3","data-chat-pane-state":"awaiting-first-view",children:[n.jsx("div",{className:"opacity-40 animate-pulse",children:n.jsx(Cn,{size:26})}),n.jsx("div",{className:"text-xxs opacity-40",children:w("chatPane.loadingChat")})]});if(e.status==="idle"&&!Pe)return!q&&B.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(Cn,{size:26})}),n.jsx("div",{className:"text-xxs opacity-40",children:w("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(Cn,{size:26})}),n.jsx("div",{className:"text-xxs opacity-40",children:w("chatPane.loadingChat")})]})}},[e.connectionState,e.status,oe,ye.awaitingFirstView,m,q,B.length,h,Pe,G.length,ae,E.isGenerating]);return n.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",...u_(I),children:[n.jsxs("div",{className:"chat-activity-toggle-bar",children:[n.jsxs("button",{type:"button",className:`chat-activity-toggle ${O?"chat-activity-toggle-active":""}`,onClick:F,"aria-pressed":O,title:w("chatPane.activityToggleTitle"),children:[n.jsx("span",{className:"chat-activity-toggle-dot"}),w("chatPane.activityToggleLabel"),ue>0&&n.jsx("span",{className:"chat-activity-toggle-count",children:ue})]}),n.jsx("div",{className:"ml-auto flex items-center gap-1",children:n.jsx(JN,{machineId:k,blocked:!!(A!=null&&A.blocked),retryConnection:N.retryConnection})})]}),n.jsx(r0,{messages:ke,actionLogs:ve,agentName:wr(e)||ae||"Agent",userName:b,isCliMode:P.isCli,isWorking:ye.showWorkingIndicator,contextKey:e.tabKey,receivedAtMap:Y,lastMessageHash:e.lastMessageHash,showActivityMessages:O,onLoadMore:Le,isLoadingMore:Pe,hasMoreHistory:q,hiddenLiveCount:ne,loadError:W??void 0,emptyState:me,scrollToBottomRequestNonce:f,isVisible:g,onSendNow:r,isSendingNow:a,onCancelQueued:o,fetchToolBlock:Z}),n.jsx(GN,{entries:d??(l?[l]:[]),onSendNow:r,onCancelQueued:o,isSendingNow:a}),n.jsx(BN,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:P.providerType,displayLabel:P.displayLabel,controls:(Ie=P.targetEntry)==null?void 0:Ie.providerControls,controlValues:(Ke=P.targetEntry)==null?void 0:Ke.controlValues,currentStatus:e.status,coordinatorHint:Mi(e),isActive:x,isCliTerminal:P.isCliTerminal,launchSurface:T}),!P.isCliTerminal&&n.jsx(Kf,{contextKey:e.tabKey,panelLabel:ae,isSending:a,isBusy:pe,statusMessage:X,inlineStatusMessage:z,onSend:s,isActive:x,showControlsToggle:M.length>0,onControlsToggle:se,messageInput:e.messageInput})]})}const X_=.5,Z_=1.25,Sn="\x1B",_m={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function e1(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function Am(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 t1(e,t){if(t in _m){const r=_m[t],o=e1(e);return o===1?`${Sn}[${r}`:`${Sn}[1;${o}${r}`}switch(t){case"Enter":return e.alt?`${Sn}\r`:"\r";case"Escape":return e.alt?`${Sn}${Sn}`:Sn;case"Backspace":{const r=e.ctrl?"\b":"";return e.alt?`${Sn}${r}`:r}case"Tab":{const r=e.shift?`${Sn}[Z`:" ";return e.alt&&!e.shift?`${Sn} `:r}case"Space":{const r=Am(" ",e);return e.alt?`${Sn}${r}`:r}}const s=Am(t,e);return e.alt?`${Sn}${s}`:s}const _b="adhdev:mesh-names:v1",n1=200;let zr=null,Ab=0;const Dl=new Set;function Tb(){if(zr)return zr;zr=new Map;try{const e=typeof localStorage<"u"?localStorage.getItem(_b):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()&&zr.set(s,r.trim())}catch{}return zr}function s1(e){try{if(typeof localStorage>"u")return;const t=[...e.entries()].slice(-n1);localStorage.setItem(_b,JSON.stringify(Object.fromEntries(t)))}catch{}}function za(e){const t=Tb();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){Ab+=1,s1(t);for(const r of[...Dl])try{r()}catch{}}}function r1(e,t){za([{id:e,name:t}])}function o1(e){return e?Tb().get(e)??null:null}function a1(e){return Dl.add(e),()=>{Dl.delete(e)}}function Tm(){return Ab}const Im=Object.freeze({role:null,meshId:null,meshName:null});function Sc(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ld(e,t=o1){var a;if(!e)return Im;const s=e.settings||{},r=Sc((a=e.coordinator)==null?void 0:a.meshId)||Sc(s.meshCoordinatorFor);if(r)return{role:"coordinator",meshId:r,meshName:t(r)};const o=Sc(s.meshNodeFor);return o?{role:"worker",meshId:o,meshName:t(o)}:s.launchedByCoordinator===!0?{role:"worker",meshId:null,meshName:null}:Im}function Ib(e){return Ld(e).role==="coordinator"}function Mb(e){return!!(e!=null&&e.daemonId)&&Ib(e)}function i1(e){return e.meshName||e.meshId}function Rb(e){return c.useSyncExternalStore(a1,Tm,Tm),Ld(e)}function kt(e){return Rd(e)}function Po(e){return sb(e).join(" · ")}function Pb(e,t){const s=nb(e,t);return s||(e.title?e.title:Po(e)||"No messages yet")}function Eb(e,t){const{isReconnecting:s,isConnecting:r,isErrored:o}=Ss(e);return s?"Reconnecting…":r?"Connecting…":t!=null&&t.requiresAction?"Action needed":o?"Needs attention":null}function c1(e,t){const s=["Chat",...sb(e)];return t!=null&&t.timestampLabel&&s.push(t.timestampLabel),s.filter(Boolean).join(" · ")}function Os(e){return Eb(e)||Po(e)}function l1(e,t){return`${kt(e)} · ${Pb(e,t)}`}function d1(e){const t=Ua(e),s=t?$t(t):wr(e);return`${kt(e)} — ${s||"Agent"}`}function u1(e){return wr(e)||"CLI"}function Lb(e){return tb(e)}function Db(e){return e?`Remote · ${kt(e)||e.workspaceName||"Session"}`:"Remote"}const Mm=[{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:""}})}],m1=[{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 h1(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 Dd({cond:e,path:t,sections:s,onChange:r,onRemove:o,onPreview:a,preview:i}){const l=h1(e),d=i[t],u=m=>{const h=Mm.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:l,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:Mm.map(m=>n.jsx("option",{value:m.kind,children:m.label},m.kind))}),(l==="regex"||l==="stable"||l==="changed"||l==="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:"×"})]}),l==="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"})]}),l==="elapsed"&&n.jsx(fs,{label:"elapsed_ms",value:e.elapsed_ms,onChange:m=>r({elapsed_ms:m})}),l==="stable"&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(fs,{label:"stable_ms",value:e.stable_ms,onChange:m=>r({...e,stable_ms:m})}),n.jsx(fs,{label:"cursor_above",value:e.cursor_above??0,onChange:m=>r({...e,cursor_above:m||void 0})})]}),l==="changed"&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(fs,{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"]})]}),(l==="all"||l==="any")&&n.jsx(p1,{kind:l,cond:e,path:t,sections:s,onChange:r,onPreview:a,preview:i}),l==="not"&&n.jsx("div",{className:"pl-2 border-l border-border-default",children:n.jsx(Dd,{cond:e.not,path:`${t}.not`,sections:s,onChange:m=>r({not:m}),onPreview:a,preview:i})})]})}function p1({kind:e,cond:t,path:s,sections:r,onChange:o,onPreview:a,preview:i}){const l=(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:[l.map((u,m)=>n.jsx(Dd,{cond:u,path:`${s}.${e}[${m}]`,sections:r,onChange:h=>d(l.map((p,b)=>b===m?h:p)),onRemove:()=>d(l.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([...l,{section:r[0],matches:""}]),children:"+ condition"}),m1.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([...l,JSON.parse(JSON.stringify(u.cond))]),title:"insert verified pattern",children:["+ ",u.label]},u.label))]})]})}function fs({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 f1({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])):{},l=(h,p)=>{if(!p||p===h||e[p])return;const b={};for(const[f,x]of Object.entries(e))b[f===h?p:f]=x;s(b)},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],b=p.anchor!=null?"anchor":"positional",f=g=>{g==="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:g=>l(h,g.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 ${b==="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 ${b==="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:"×"})]}),b==="positional"?n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx(fs,{label:"from_top",value:typeof p.from_top=="number"?p.from_top:0,onChange:g=>d(h,{...p,from_top:g,from_bottom:void 0})}),n.jsx(fs,{label:"from_bottom",value:typeof p.from_bottom=="number"?p.from_bottom:0,onChange:g=>d(h,{...p,from_bottom:g||void 0})}),n.jsx(Rm,{def:p,otherIds:t(h),onChange:g=>d(h,g)})]}):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:g=>d(h,{...p,anchor:g.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:g=>d(h,{...p,anchor_last:g.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"last"]})]}),n.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:n.jsx(Rm,{def:p,otherIds:t(h),onChange:g=>d(h,g)})}),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:g=>d(h,{...p,anchor_context:{...p.anchor_context,next:g.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 Rm({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 b1({model:e,onChange:t,onPreview:s,preview:r,onTestSections:o,sectionPreview:a}){const i=e.states.map(h=>h.id),l=Object.keys(e.sections??{}),d=c.useCallback(h=>t({...e,...h}),[e,t]),u=(h,p)=>d({states:e.states.map((b,f)=>f===h?{...b,...p}:b)}),m=(h,p)=>d({transitions:e.transitions.map((b,f)=>f===h?{...b,...p}:b)});return n.jsxs("div",{className:"space-y-3",children:[n.jsx(f1,{sections:e.sections??{},otherSectionIds:h=>l.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:b=>u(p,{id:b.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:b=>u(p,{label:b.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((b,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((b,f)=>({...b,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:b=>u(p,{modal:b.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:b=>u(p,{status:b.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(g1,{value:h.from,states:i,onChange:b=>m(p,{from:b})}),n.jsx("span",{className:"text-3xs text-text-muted",children:"→"}),n.jsx("select",{value:h.to,onChange:b=>m(p,{to:b.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(b=>n.jsx("option",{value:b,children:b},b))}),n.jsx("span",{className:"text-3xs text-text-muted ml-1",children:"label"}),n.jsx("input",{value:h.label??"",onChange:b=>m(p,{label:b.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((b,f)=>f!==p)}),children:"×"})]}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(fs,{label:"min_hold_ms",value:h.min_hold_ms??0,onChange:b=>m(p,{min_hold_ms:b||void 0})}),n.jsx(fs,{label:"priority",value:h.priority??0,onChange:b=>m(p,{priority:b||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:l[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(Dd,{cond:h.when,path:`t${p}`,sections:l,onChange:b=>m(p,{when:b}),onPreview:s,preview:r})]})]},p))})]})]})}function g1({value:e,states:t,onChange:s}){const r=new Set(Array.isArray(e)?e:e==="*"?t:[e]),o=e==="*",a=i=>{const l=new Set(r);l.has(i)?l.delete(i):l.add(i);const d=t.filter(u=>l.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 x1(e){return e&&typeof e=="object"?e:{}}function kc(e){return typeof e=="string"?e:""}function y1(e){const t=x1(e);return!!(typeof t.spec_id=="string"&&t.spec_id.length>0||"current_state"in t||Array.isArray(t.stateHistory))}function Pm(e){if(e==null||typeof e!="object"||!y1(e))return null;const t=e;return{cliType:kc(t.cliType),spec_id:kc(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:kc(t.screen),sections:t.sections??void 0,stateHistory:Array.isArray(t.stateHistory)?t.stateHistory:[],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}}function Vr(e){const t=Date.now()-e;return t<0?Fa(e):t<2e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:Fa(e)}function Em(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const v1={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"},w1={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 jc(e){return w1[e]??"text-text-primary bg-bg-glass border border-border-default"}function Zo({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 ea(){return n.jsx("div",{className:"border-t border-white/8 my-2"})}function Ob({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(Ob,{node:a,depth:t+1},i))]})}function S1({t:e}){const[t,s]=c.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(Ob,{node:e.cond})})]})}function k1({activeConv:e,onClose:t}){var ne,ae,ee,oe,Ce;const{sendCommand:s}=wt(),[r,o]=c.useState(!0),[a,i]=c.useState(null),[l,d]=c.useState(null),[u,m]=c.useState(!1),[h,p]=c.useState(new Set(["footer"])),[b,f]=c.useState("Snapshot"),[x,g]=c.useState(!1),[w,S]=c.useState(null),[C,j]=c.useState(!1),[v,y]=c.useState(""),[N,k]=c.useState(!1),[A,E]=c.useState("idle"),[P,T]=c.useState(null),[M,_]=c.useState([]),[I,D]=c.useState({}),[L,$]=c.useState(null),[U,J]=c.useState(!1),K=e.daemonId||((ne=e.routeId)==null?void 0:ne.split(":")[0])||e.routeId||"",R=e.sessionId||"",O=c.useCallback(async()=>{o(!0),d(null);try{const Q=await s(K,"get_spec_debug",{targetSessionId:R}),z=Q&&typeof Q=="object"?Q:{},X=z.result&&typeof z.result=="object"?z.result:z;X!=null&&X.success?i(X):(d((X==null?void 0:X.error)||"Failed to load spec debug"),i(null))}catch(Q){d((Q==null?void 0:Q.message)||String(Q)),i(null)}finally{o(!1)}},[s,K,R]);c.useEffect(()=>{O()},[O]),c.useEffect(()=>{if(!U)return;const Q=setInterval(()=>{O()},1e3);return()=>clearInterval(Q)},[U,O]),c.useEffect(()=>{const Q=z=>{z.key==="Escape"&&!x&&t()};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[t,x]);const H=c.useCallback(async Q=>{try{const z=await s(K,"validate_spec",{content:JSON.stringify(Q)}),X=z&&typeof z=="object"?z:{},pe=X.result&&typeof X.result=="object"?X.result:X;_(pe!=null&&pe.valid?[]:(pe==null?void 0:pe.errors)??["validation failed"])}catch(z){_([(z==null?void 0:z.message)||String(z)])}},[s,K]),B=c.useCallback(async()=>{T(null),E("idle"),D({});try{const Q=await s(K,"get_spec_source",{targetSessionId:R}),z=Q&&typeof Q=="object"?Q:{},X=z.result&&typeof z.result=="object"?z.result:z;if(!(X!=null&&X.success)||typeof X.content!="string"){T((X==null?void 0:X.error)||"Failed to load spec source");return}y(X.content);let pe=null;try{pe=JSON.parse(X.content)}catch{}pe&&pe.$schema==="adhdev:cli/spec@4"?(S(pe),j(!1),H(pe)):(S(null),j(!0)),k(!1),g(!0)}catch(Q){T((Q==null?void 0:Q.message)||String(Q))}},[s,K,R,H]),q=c.useCallback(Q=>{S(Q),y(JSON.stringify(Q,null,2)),k(!0),E("idle"),H(Q)},[H]),W=c.useCallback(async(Q,z)=>{D(X=>({...X,[Q]:"loading"}));try{const X=await s(K,"eval_condition_preview",{targetSessionId:R,condition:z}),pe=X&&typeof X=="object"?X:{},Pe=pe.result&&typeof pe.result=="object"?pe.result:pe;!(Pe!=null&&Pe.success)||!Pe.result?D(Oe=>({...Oe,[Q]:{result:!1,detail:Pe==null?void 0:Pe.error}})):D(Oe=>({...Oe,[Q]:{result:Pe.result.result,detail:Pe.result.detail}}))}catch(X){D(pe=>({...pe,[Q]:{result:!1,detail:X==null?void 0:X.message}}))}},[s,K,R]),ce=c.useCallback(async Q=>{$("loading");try{const z=await s(K,"resolve_section_preview",{targetSessionId:R,sections:Q}),X=z&&typeof z=="object"?z:{},pe=X.result&&typeof X.result=="object"?X.result:X;!(pe!=null&&pe.success)||!Array.isArray(pe.sections)?$({error:(pe==null?void 0:pe.error)||"resolve failed"}):$({sections:pe.sections,screenLineCount:pe.screenLineCount??0})}catch(z){$({error:(z==null?void 0:z.message)||String(z)})}},[s,K,R]),ye=c.useCallback(async()=>{var X,pe;const Q=(X=a==null?void 0:a.snapshot)==null?void 0:X.specPath;if(!Q){T("No spec path on this session");return}if(!C&&M.length>0){T("Fix validation errors before saving");return}const z=!C&&w?JSON.stringify(w,null,2):v;E("saving"),T(null);try{const Pe=await s(K,"write_spec_source",{specPath:Q,content:z}),Oe=Pe&&typeof Pe=="object"?Pe:{},Le=Oe.result&&typeof Oe.result=="object"?Oe.result:Oe;if(!(Le!=null&&Le.success)){E("error"),T(((pe=Le==null?void 0:Le.validationErrors)==null?void 0:pe.join(`
49
- `))||(Le==null?void 0:Le.error)||"Save failed");return}E("saved"),k(!1),setTimeout(()=>{O()},400),setTimeout(()=>E("idle"),1500)}catch(Pe){E("error"),T((Pe==null?void 0:Pe.message)||String(Pe))}},[s,K,(ae=a==null?void 0:a.snapshot)==null?void 0:ae.specPath,v,w,C,M,O]),G=Pm(a==null?void 0:a.snapshot),Se=async()=>{var Le,ke,Y;let Q=a;Q||(await O(),Q=a);const z=Pm(Q==null?void 0:Q.snapshot),X=[];if(X.push("# Spec Debug Snapshot"),X.push(`Generated: ${new Date().toISOString()}`),X.push(`Session: ${(Q==null?void 0:Q.sessionId)??""} (${(Q==null?void 0:Q.providerType)??""})`),X.push(`Spec: ${(z==null?void 0:z.spec_id)??""} (${(z==null?void 0:z.specPath)??""})`),X.push(`Provider: ${(z==null?void 0:z.name)??""} (${(z==null?void 0:z.cliType)??""})`),X.push(`Working dir: ${(z==null?void 0:z.workingDir)??""}`),X.push(`Spawned: ${z!=null&&z.spawnedAtMs?new Date(z.spawnedAtMs).toISOString():""}`),X.push(""),X.push("## Current State"),X.push(`State: ${((Le=z==null?void 0:z.current_state)==null?void 0:Le.id)??"none"} (${((ke=z==null?void 0:z.current_state)==null?void 0:ke.label)??""})`),X.push(`Status: ${(z==null?void 0:z.status)??""}`),X.push(`Idle hold pending: ${(z==null?void 0:z.idleHoldPending)??!1}`),X.push(`Exited: ${(z==null?void 0:z.exited)??!1}`),X.push(`Last busy: ${z!=null&&z.lastBusyAt?Vr(z.lastBusyAt):""}`),X.push(`Cursor: ${(z==null?void 0:z.cursorPosition)!=null?`(${z.cursorPosition.row},${z.cursorPosition.col})`:"n/a"}`),(Y=z==null?void 0:z.completionIdleDebounce)!=null&&Y.active){const ve=z.completionIdleDebounce;X.push(`completion_idle_after: age=${ve.ageMs}ms hold=${ve.holdMs}ms force=${ve.forceAfterMs}ms remaining=${Math.max(0,ve.holdMs-ve.ageMs)}ms`)}if(X.push(""),X.push("## Modal"),z!=null&&z.current_modal){const ve=z.current_modal.buttons.map(Z=>Z.label).join(" / ");X.push(`${z.current_modal.title??""} [${ve}]`)}else X.push("none");X.push(""),X.push("## State History (last 20)");const pe=z!=null&&z.stateHistory?[...z.stateHistory].reverse().slice(0,20):[];for(const ve of pe){const Z=ve.reason!=null?typeof ve.reason=="string"?ve.reason:JSON.stringify(ve.reason):"",ie=ve.debounceKind!=null?typeof ve.debounceKind=="string"?ve.debounceKind:JSON.stringify(ve.debounceKind):"",F=ve.matchedStateId!=null?String(ve.matchedStateId):"",se=(ve.matchedRules??[]).map(me=>typeof me=="string"?me:JSON.stringify(me)).join(", ");X.push(`- ${ve.stateId} @ ${new Date(ve.at).toISOString()} held ${ve.durationMs}ms | reason: ${Z} | debounce: ${ie} | eval→${F} | rules: ${se}`)}if(X.push(""),X.push("## Sections"),z!=null&&z.sections)for(const[ve,Z]of Object.entries(z.sections)){const ie=Z.split(`
50
- `).slice(0,3).join(`
51
- `);X.push(`${ve}: ${ie}`)}X.push(""),X.push("## Last Assistant Message");const Oe=[...(z==null?void 0:z.messages)??(z==null?void 0:z.committedMessages)??[]].reverse().find(ve=>ve.role==="assistant");X.push(Oe?Oe.content.slice(0,400):""),X.push(""),X.push("## Screen (first 50 lines)"),X.push(z!=null&&z.screen?z.screen.split(`
52
- `).slice(0,50).join(`
53
- `):"");try{await navigator.clipboard.writeText(X.join(`
54
- `)),f("Copied!"),setTimeout(()=>f("Snapshot"),1500)}catch(ve){console.error("[SpecDebugPanel] clipboard write failed",ve)}},ue=Q=>{p(z=>{const X=new Set(z);return X.has(Q)?X.delete(Q):X.add(Q),X})};return n.jsx(Un,{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:Q=>Q.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"}),G&&n.jsx("span",{className:"text-2xs text-text-secondary font-mono bg-surface-secondary px-1.5 py-0.5 rounded truncate",children:G.spec_id})]}),n.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(G==null?void 0:G.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?g(!1):B()},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:()=>{Se()},disabled:r,children:b}),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:()=>{O()},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 ${C?"text-text-secondary hover:bg-bg-glass-hover":"bg-accent-primary/20 text-accent-primary"}`,onClick:()=>{if(C)try{const Q=JSON.parse(v);S(Q),H(Q)}catch{return}j(!1)},disabled:!w&&C,children:"Form"}),n.jsx("button",{type:"button",className:`px-2 py-0.5 ${C?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>{w&&y(JSON.stringify(w,null,2)),j(!0)},children:"JSON"})]}),n.jsx("span",{className:"text-3xs text-text-muted font-mono truncate flex-1",title:G==null?void 0:G.specPath,children:((G==null?void 0:G.specPath)??"").split("/").slice(-3).join("/")}),N&&n.jsx("span",{className:"text-status-warning text-3xs",children:"unsaved"}),!C&&M.length>0&&n.jsxs("span",{className:"text-status-error text-3xs",children:[M.length," error",M.length>1?"s":""]}),n.jsx("button",{type:"button",className:`text-2xs px-2.5 py-1 rounded border transition-colors ${A==="saving"||!C&&M.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:()=>{ye()},disabled:A==="saving"||!C&&M.length>0,children:A==="saving"?"Saving…":A==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),P&&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:P}),!C&&M.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:M.map((Q,z)=>n.jsx("div",{className:"font-mono",children:Q},z))}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:C||!w?n.jsx("textarea",{value:v,onChange:Q=>{y(Q.target.value),k(!0),E("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(b1,{model:w,onChange:q,onPreview:W,preview:I,onTestSections:ce,sectionPreview:L})}),n.jsx("div",{className:"text-3xs text-text-muted shrink-0",children:C?"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:[l&&n.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2",children:l}),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",")."]}),G&&n.jsxs(n.Fragment,{children:[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:[G.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:[G.name," ",n.jsxs("span",{className:"text-text-muted",children:["(",G.cliType,")"]})]})]}),G.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:G.workingDir,children:G.workingDir})]}),G.spawnedAtMs?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-text-muted",children:"Spawned"}),n.jsx("span",{className:"text-text-secondary",children:Vr(G.spawnedAtMs)})]}):null,G.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:G.providerSessionId,children:G.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 ${G.current_state?jc(G.current_state.id):"text-text-muted"}`,children:G.current_state?G.current_state.id:"none"}),((ee=G.current_state)==null?void 0:ee.label)&&G.current_state.label!==G.current_state.id&&n.jsx("span",{className:"text-text-secondary text-2xs",children:G.current_state.label}),G.status&&G.status!==((oe=G.current_state)==null?void 0:oe.id)&&n.jsxs("span",{className:"text-text-muted text-2xs",children:["engine: ",n.jsx("span",{className:`font-mono ${jc(G.status)} px-1 py-0.5 rounded text-3xs`,children:G.status})]}),G.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"}),G.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"}),G.cursorPosition!=null&&n.jsxs("span",{className:"text-text-muted text-2xs font-mono",children:["cursor: ",n.jsxs("span",{className:"text-text-secondary",children:[G.cursorPosition.row,",",G.cursorPosition.col]})]}),G.lastBusyAt>0&&n.jsxs("span",{className:"text-text-muted text-2xs ml-auto",children:["last busy: ",n.jsx("span",{className:"text-text-secondary",children:Vr(G.lastBusyAt)})]})]}),((Ce=G.completionIdleDebounce)==null?void 0:Ce.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:[G.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:[G.completionIdleDebounce.holdMs,"ms"]})]}),n.jsxs("span",{className:"text-text-secondary",children:["force: ",n.jsxs("span",{className:"text-text-secondary",children:[G.completionIdleDebounce.forceAfterMs,"ms"]})]}),n.jsx("span",{className:"text-text-muted ml-auto",children:G.completionIdleDebounce.ageMs<G.completionIdleDebounce.holdMs?n.jsxs("span",{className:"text-status-warning",children:["hold remaining: ",G.completionIdleDebounce.holdMs-G.completionIdleDebounce.ageMs,"ms"]}):G.completionIdleDebounce.ageMs<G.completionIdleDebounce.forceAfterMs?n.jsxs("span",{className:"text-orange-300",children:["force in: ",G.completionIdleDebounce.forceAfterMs-G.completionIdleDebounce.ageMs,"ms"]}):n.jsx("span",{className:"text-status-error",children:"overdue"})})]}),G.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:G.current_modal.title||""}),G.current_modal.buttons.length>0&&n.jsxs("span",{className:"text-text-secondary ml-2",children:["[",G.current_modal.buttons.map(Q=>Q.label).join(" / "),"]"]})]}),G.fsm&&n.jsxs(n.Fragment,{children:[n.jsx(ea,{}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsxs(Zo,{children:["FSM — outgoing from ",n.jsx("span",{className:"text-accent-primary font-mono normal-case",children:G.fsm.currentState})," (held ",Em(G.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:U,onChange:Q=>J(Q.target.checked),className:"accent-[var(--accent-primary)]"}),"live"]})]}),n.jsxs("div",{className:"space-y-1",children:[G.fsm.transitions.length===0&&n.jsx("div",{className:"text-text-muted text-2xs italic px-1",children:"no outgoing transitions (terminal state)"}),G.fsm.transitions.map((Q,z)=>n.jsx(S1,{t:Q},z))]})]})]}),n.jsx(ea,{}),G.sections&&Object.keys(G.sections).length>0&&n.jsxs("div",{children:[n.jsx(Zo,{children:"Sections"}),n.jsx("div",{className:"space-y-1",children:Object.entries(G.sections).map(([Q,z])=>{var Oe;const X=h.has(Q),pe=z.split(`
55
- `),Pe=((Oe=pe[0])==null?void 0:Oe.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:()=>ue(Q),children:[n.jsx("span",{className:"text-3xs text-text-muted w-3",children:X?"▾":"▸"}),n.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-2xs",children:Q}),!X&&n.jsx("span",{className:"text-text-secondary truncate font-mono text-2xs",children:Pe}),n.jsxs("span",{className:"ml-auto text-text-muted text-3xs shrink-0",children:[pe.length,"L"]})]}),X&&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:z||"(empty)"})]},Q)})})]}),n.jsx(ea,{}),G.stateHistory&&G.stateHistory.length>0&&n.jsxs("div",{children:[n.jsxs(Zo,{children:["State History (",G.stateHistory.length,")"]}),n.jsx("div",{className:"space-y-px",children:[...G.stateHistory].reverse().slice(0,20).map((Q,z)=>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 ${jc(Q.stateId)}`,children:Q.stateId}),n.jsx("span",{className:"text-text-secondary text-2xs shrink-0 tabular-nums",children:Vr(Q.at)}),Q.durationMs>0&&n.jsxs("span",{className:"text-text-muted text-2xs",children:["held ",n.jsx("span",{className:"text-text-secondary",children:Em(Q.durationMs)})]}),Q.reason&&n.jsx("span",{className:`text-3xs px-1.5 py-0.5 rounded font-mono shrink-0 ${v1[String(Q.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(Q.reason)}),Q.debounceKind&&String(Q.debounceKind)!=="none"&&n.jsxs("span",{className:"text-text-muted text-3xs font-mono",children:["debounce:",String(Q.debounceKind)]}),Q.matchedStateId&&String(Q.matchedStateId)!==Q.stateId&&n.jsxs("span",{className:"text-text-muted text-3xs font-mono",children:["eval→",n.jsx("span",{className:"text-text-secondary",children:String(Q.matchedStateId)})]})]}),Q.matchedRules&&Q.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:[Q.matchedRules.slice(0,3).map((X,pe)=>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 X=="string"?X:JSON.stringify(X)},pe)),Q.matchedRules.length>3&&n.jsxs("span",{className:"text-3xs text-text-muted",children:["+",Q.matchedRules.length-3," more"]})]})]},z))})]}),n.jsx(ea,{}),(()=>{const Q=G.messages??G.committedMessages??[];if(Q.length===0)return null;const z=Q.filter(Pe=>Pe.role==="user").length,X=Q.filter(Pe=>Pe.role==="assistant").length,pe=[...Q].reverse().find(Pe=>Pe.role==="assistant");return n.jsxs("div",{children:[n.jsxs(Zo,{children:["Transcript (",Q.length," — ",z,"u / ",X,"a)"]}),pe&&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 ",pe.receivedAt?Vr(pe.receivedAt):""]}),n.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[pe.content.slice(0,400),pe.content.length>400?"…":""]})]})]})})(),G.specPath&&n.jsx("div",{className:"text-3xs text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:G.specPath,children:G.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(Q=>!Q),children:[n.jsx("span",{className:"text-text-muted",children:u?"▾":"▸"}),n.jsxs("span",{children:["Raw screen (",G.screen?G.screen.split(`
56
- `).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:G.screen||"(empty)"})]})]})]})]})})})}function $b(e,t){if(typeof window>"u")return!1;try{return window[e]===!0||window.localStorage.getItem(t)==="1"}catch{return window[e]===!0}}function j1(){return $b("__ADHDEV_DEBUG_SPEC__","adhdev_debug_spec")}function N1(){return $b("__ADHDEV_DEBUG_MOBILE_BUNDLE__","adhdev_debug_mobile_bundle")}function C1({activeConv:e,clearToken:t=0,terminalRef:s,handleSendChat:r,isSendingChat:o=!1,sendFeedbackMessage:a=null,isVisible:i=!0,isInputActive:l=!0}){var Kt;const{t:d}=he("common");yn();const{sendPtyInput:u}=wt(),[m,h]=c.useState(!1),p=c.useRef(!1);p.current=m;const[b,f]=c.useState("Runtime terminal unavailable"),[x,g]=c.useState(!1),[w,S]=c.useState(null),[C,j]=c.useState(!1),[v,y]=c.useState(!1),[N,k]=c.useState(1),[A,E]=c.useState(!1),[P,T]=c.useState(!1),[M,_]=c.useState(!1),[I,D]=c.useState(!1),[L,$]=c.useState(!1),U=j1(),[J,K]=c.useState({width:0,height:0}),[R,O]=c.useState({width:0,height:0}),[H,B]=c.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[q,W]=c.useState(null),ce=c.useRef(null),ye=c.useRef(null),G=c.useRef(!1),Se=c.useRef(!1),ue=c.useRef(i),ne=c.useRef(0),ae=c.useRef(!1),ee=c.useRef(""),oe=c.useRef(null),Ce=c.useRef(!1),Q=c.useRef(!1),z=c.useRef(null),X=c.useRef(null),pe=c.useRef(null),Pe=32*1024,Oe=()=>{var fe,Me,Ee,Ve;return((Me=(fe=ce.current)==null?void 0:fe.ownerDocument)==null?void 0:Me.defaultView)||((Ve=(Ee=ye.current)==null?void 0:Ee.ownerDocument)==null?void 0:Ve.defaultView)||window},Le=fe=>{const Me=Oe();return{ownerWindow:Me,frameId:Me.requestAnimationFrame(fe)}},ke=()=>{const fe=z.current;if(fe){try{fe.ownerWindow.cancelAnimationFrame(fe.frameId)}catch{}z.current=null}},Y=()=>{const fe=X.current;if(fe){try{fe.ownerWindow.clearTimeout(fe.timeoutId)}catch{}X.current=null}},ve=()=>{const fe=pe.current;if(fe){try{fe.ownerWindow.clearTimeout(fe.timeoutId)}catch{}pe.current=null}},Z=()=>{i&&z.current===null&&(z.current=Le(()=>{Tt()}))},ie=e.tabKey,F=e.sessionId||"",se=e.daemonId||((Kt=e.routeId)==null?void 0:Kt.split(":")[0])||e.routeId||"",me=Ri(e),re=m?ab(e)||a:b,we=m&&a||null,V=X_,de=Z_,ge=.05,Ie=()=>{const fe=R.width,Me=R.height;if(!Number.isFinite(J.width)||J.width<=0||!Number.isFinite(J.height)||J.height<=0||!Number.isFinite(fe)||fe<=0||!Number.isFinite(Me)||Me<=0)return 1;const Ee=J.width/fe,Ve=J.height/Me;return Number(Math.min(de,Math.max(V,Math.min(Ee,Ve))).toFixed(2))},Ke=Ie(),Ae=G.current&&N>Ke,Ne=Number.isFinite(R.width)&&R.width>0?Math.max(J.width,Math.round(R.width*N)):J.width,He=Number.isFinite(R.height)&&R.height>0?Math.max(J.height,Math.round(R.height*N)):J.height,Fe=()=>{Le(()=>{const fe=ye.current;fe&&(fe.scrollLeft=0,fe.scrollTop=fe.scrollHeight-fe.clientHeight)})},it=()=>{var fe,Me;ne.current=0,ae.current=!1,ee.current="",oe.current=null,Ce.current=!1,Q.current=!1,G.current||(Se.current=!1,k(1)),z.current!==null&&ke(),h(!1),f("Runtime terminal unavailable"),ve(),Y(),S(null),W(null),E(!1),g(!1),j(!1),y(!1),(Me=(fe=s.current)==null?void 0:fe.reset)==null||Me.call(fe)},ut=()=>{var fe,Me;ne.current=0,ae.current=!1,ee.current="",oe.current=null,Ce.current=!1,Q.current=!1,z.current!==null&&ke(),h(!0),f(""),ve(),Y(),S(null),W(null),E(!1),g(!1),j(!1),y(!1),(Me=(fe=s.current)==null?void 0:fe.reset)==null||Me.call(fe)},dt=()=>{Q.current&&(Q.current=!1,Le(()=>{var fe,Me;(Me=(fe=s.current)==null?void 0:fe.scrollToTop)==null||Me.call(fe)}))},Tt=()=>{if(z.current=null,!i)return;const fe=ee.current;if(!fe)return;const Me=fe.slice(0,Pe);ee.current=fe.slice(Me.length);const Ee=s.current;if(!Ee){ee.current=Me+ee.current,Z();return}Ee.write(Me,()=>{if(ee.current.length>0){Z();return}dt()})},bt=fe=>{fe&&(ee.current+=fe,Z())},te=(fe,Me=0,Ee,Ve,Qe={})=>{var tt,Nt,xt,Bt;const ht=!!Qe.force;!ht&&Me>0&&ne.current>=Me||!ht&&Me===0&&ae.current||(ne.current=Me,Me>0&&j(!0),h(!0),f(""),typeof Ee=="number"&&typeof Ve=="number"&&Ee>0&&Ve>0&&((Nt=(tt=s.current)==null?void 0:tt.resize)==null||Nt.call(tt,Ee,Ve)),ee.current="",(Bt=(xt=s.current)==null?void 0:xt.reset)==null||Bt.call(xt),fe?bt(fe):dt())};c.useEffect(()=>{it()},[F]),c.useEffect(()=>{var Me;if(!F)return;const fe=((Me=Dt.onRuntimeEvent)==null?void 0:Me.call(Dt,F,Ee=>{if(!(!Ee||Ee.sessionId!==F)){if(Ee.type==="runtime_snapshot"){if(!i){oe.current={text:Ee.text||"",seq:Ee.seq||0,cols:Ee.cols,rows:Ee.rows,force:!!Ee.force};return}te(Ee.text||"",Ee.seq||0,Ee.cols,Ee.rows,{force:!!Ee.force});return}if(Ee.type==="session_output"){ae.current=!0,typeof Ee.seq=="number"&&(ne.current=Math.max(ne.current,Ee.seq),Ee.seq>0&&j(!0)),p.current||h(!0),p.current||f(""),typeof Ee.data=="string"&&bt(Ee.data);return}if(Ee.type==="session_cleared"){if(!i){Ce.current=!0,ee.current="",oe.current=null;return}ut();return}if(Ee.type==="session_io_error"){const Ve=typeof Ee.error=="string"&&Ee.error?Ee.error:typeof Ee.reason=="string"&&Ee.reason?Ee.reason:"unknown error";h(!1),f(`Runtime input failed: ${Ve}`);return}}},se))||(()=>{});return()=>{fe()}},[se,F,s,i]);const le=async(fe={})=>{var Me;if(!se||!F)return{success:!1,error:"daemonId and sessionId are required"};fe.preserveStatus||f(fe.loadingMessage||"Loading runtime terminal...");try{const Ee=await((Me=Dt.requestRuntimeSnapshot)==null?void 0:Me.call(Dt,se,F,{sinceSeq:fe.sinceSeq,force:fe.force}));return Ee&&Ee.success===!1?(fe.preserveStatus||(h(!1),f(`Runtime terminal unavailable: ${Ee.error}`)),Ee):Ee||{success:!0}}catch(Ee){const Ve=(Ee==null?void 0:Ee.message)||String(Ee);return fe.preserveStatus||(h(!1),f(`Runtime terminal unavailable: ${Ve}`)),{success:!1,error:Ve}}},be=async fe=>{var ht,tt;const Me=((ht=ce.current)==null?void 0:ht.ownerDocument)||document,Ee=Me.defaultView||window,Ve=(tt=Ee.navigator)==null?void 0:tt.clipboard;if(Ve!=null&&Ve.writeText&&Ee.isSecureContext)try{return await Ve.writeText(fe),!0}catch{}let Qe=null;try{return Qe=Me.createElement("textarea"),Qe.value=fe,Qe.setAttribute("readonly","true"),Qe.style.position="fixed",Qe.style.left="-9999px",Qe.style.top="0",Me.body.appendChild(Qe),Qe.focus(),Qe.select(),Me.execCommand("copy")}catch{return!1}finally{Qe==null||Qe.remove()}},Te=fe=>{Y(),W(fe);const Me=Oe();X.current={ownerWindow:Me,timeoutId:Me.setTimeout(()=>{X.current=null,W(Ee=>Ee===fe?null:Ee)},2200)}},De=fe=>{ve(),S(fe);const Me=Oe();pe.current={ownerWindow:Me,timeoutId:Me.setTimeout(()=>{pe.current=null,S(Ee=>Ee===fe?null:Ee)},2200)}},qe=async()=>{var Qe,ht,tt,Nt;const fe=((ht=(Qe=s.current)==null?void 0:Qe.getSelection)==null?void 0:ht.call(Qe))||"",Me=((Nt=(tt=s.current)==null?void 0:tt.getVisibleText)==null?void 0:Nt.call(tt))||"",Ee=fe.trimEnd()||Me.trimEnd();if(!Ee){Te("Nothing to copy");return}if(!await be(Ee)){Te("Copy failed");return}Te(fe.trimEnd()?"Copied selection":"Copied visible terminal")},ot=fe=>{if(!m||!i)return;((u==null?void 0:u(se,F,fe))??!1)||Te("Terminal input failed")},_e=fe=>{ot(t1({ctrl:P,alt:M,shift:I},fe)),T(!1),_(!1),D(!1)},st=async()=>{if(x)return;g(!0),S("Loading older terminal output..."),Q.current=!0;const fe=await le({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(g(!1),(fe==null?void 0:fe.success)===!1){Q.current=!1,S(`Older terminal output unavailable: ${fe.error}`);return}y(!0),De("Older terminal output loaded"),Le(()=>{var Me;(Me=s.current)==null||Me.bumpResize()})};c.useEffect(()=>{var Me,Ee;if(!F)return;se&&((Me=Dt.getState)==null?void 0:Me.call(Dt,se))==="connected"&&le();const fe=(Ee=Dt.onStateChange)==null?void 0:Ee.call(Dt,(Ve,Qe)=>{Ve!==se||Qe!=="connected"||le()});return()=>{fe==null||fe()}},[se,F,s]),c.useEffect(()=>{t&&it()},[t,ie,s]),c.useEffect(()=>{var Ve,Qe;const fe=ce.current,Me=(Qe=(Ve=fe==null?void 0:fe.ownerDocument)==null?void 0:Ve.defaultView)==null?void 0:Qe.ResizeObserver;if(!fe||!Me)return;const Ee=new Me(ht=>{const tt=ht[0];if(!tt)return;const{width:Nt,height:xt}=tt.contentRect;K(Bt=>{const Jt=Math.round(Nt),on=Math.round(xt);return Bt.width===Jt&&Bt.height===on?Bt:{width:Jt,height:on}})});return Ee.observe(fe),()=>Ee.disconnect()},[]),c.useEffect(()=>{if(G.current)return;const fe=Ie();!Number.isFinite(fe)||fe<=0||k(Me=>Se.current?fe<Me-ge?fe:Me:(Se.current=!0,fe))},[R.height,R.width,J.height,J.width]),c.useEffect(()=>{Ae&&Fe()},[Ae,He,Ne]),c.useEffect(()=>{var Ee;const fe=ue.current;if(ue.current=i,!i)return;fe||y(!1),Ce.current&&(Ce.current=!1,ut());const Me=oe.current;Me&&(oe.current=null,te(Me.text,Me.seq,Me.cols,Me.rows,{force:!!Me.force})),se&&F&&((Ee=Dt.getState)==null?void 0:Ee.call(Dt,se))==="connected"&&le(),ee.current&&z.current===null&&Z(),Le(()=>{var Ve;(Ve=s.current)==null||Ve.bumpResize()})},[se,i,F]),c.useEffect(()=>()=>{z.current!==null&&ke(),Y(),ve()},[]),c.useEffect(()=>{const fe=Ve=>{var ht;const Qe=Ve.detail;Qe!=null&&Qe.sessionId&&Qe.sessionId!==F||m&&((ht=s.current)==null||ht.bumpResize())},Me=Oe(),Ee=Me===window?[window]:[window,Me];for(const Ve of Ee)Ve.addEventListener("adhdev:fit-cli-terminal",fe);return()=>{for(const Ve of Ee)Ve.removeEventListener("adhdev:fit-cli-terminal",fe)}},[m,F,s]);const gt=m&&C&&!v&&(H.atTop||!H.canScroll)||x||!!w;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{ref:ce,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[gt&&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:()=>{st()},disabled:!F||x,title:d("terminal.replayScrollbackHint"),children:d(x?"terminal.loadingOlder":"terminal.loadOlderOutput")}),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})]}),n.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[q&&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:q}),U&&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:()=>$(fe=>!fe),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:()=>{qe()},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:()=>E(fe=>!fe),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:()=>E(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),n.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",P,T],["Alt",M,_],["Shift",I,D]].map(([fe,Me,Ee])=>n.jsx("button",{type:"button","aria-pressed":Me,className:`h-9 rounded-lg border text-xs font-semibold transition-colors ${Me?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>Ee(Ve=>!Ve),children:fe},fe))}),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:()=>_e("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:()=>_e("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:()=>_e("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:()=>_e("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:()=>_e("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:()=>_e("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:()=>_e("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:()=>ot(""),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:()=>_e("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:()=>_e("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:()=>{G.current=!0,k(fe=>{const Me=Math.max(Ke,Number((fe-.1).toFixed(2)));return Me>Ke&&Fe(),Me})},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:()=>{G.current=!0,k(fe=>{const Me=Math.min(de,Number((fe+.1).toFixed(2)));return Me>Ke&&Fe(),Me})},title:d("terminal.growViewport"),children:"+"})]}),n.jsx("div",{ref:ye,className:Ae?"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:Ne>0?`${Ne}px`:"100%",height:He>0?`${He}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:N},children:n.jsx(hf,{ref:s,readOnly:!m||!i,sizingMode:"measured",onViewportMetrics:O,onScrollMetrics:B,onInput:fe=>{!m||(u==null||u(se,F,fe))}})})})}),!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:b})]}),n.jsx(Kf,{contextKey:e.tabKey,panelLabel:kt(e),isSending:o,isBusy:!!me,statusMessage:re,inlineStatusMessage:we,onSend:async fe=>me?!1:r(fe),isActive:l&&i,showControlsToggle:!1,animateVisibility:!1}),L&&n.jsx(k1,{activeConv:e,onClose:()=>$(!1)})]})}const _1=5e3,A1=12e3,T1=15e3;function I1(e){return e==="disconnected"||e==="reconnecting"}function M1({wsStatus:e,showReconnected:t,loginUrl:s,onReconnect:r,reconnectDelayMs:o=_1,reconnectActionDelayMs:a=A1}){const{t:i}=he(),l=I1(e),[d,u]=c.useState(()=>!l||o<=0),[m,h]=c.useState(()=>!l||a<=0),p=c.useRef(!1),[b,f]=c.useState(!1);c.useEffect(()=>{if(!l){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,l]),c.useEffect(()=>{if(!l){h(!1);return}if(a<=0){h(!0);return}h(!1);const A=setTimeout(()=>{h(!0)},a);return()=>clearTimeout(A)},[a,l]),c.useEffect(()=>{e!=="reconnecting"&&f(!1)},[e]),c.useEffect(()=>{if(!b)return;const A=setTimeout(()=>f(!1),T1);return()=>clearTimeout(A)},[b]);const x=()=>{f(!0),r==null||r()},g=l?d:e==="offline"||e==="auth_failed",w=!!(r&&e!=="auth_failed"&&(!l||m)),S=c.useMemo(()=>!t||e!=="connected"?!1:o<=0||p.current,[o,t,e]),C=e==="auth_failed"?"red":e==="offline"?"orange":"accent",j={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))"},v={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)"},y={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},N="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",k={transform:"translateX(-50%)"};return n.jsxs(n.Fragment,{children:[g&&n.jsx("div",{className:N,style:k,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:j[C],border:v[C],color:y[C]},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"))]}),w&&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"||b,children:[b&&n.jsx(tn,{size:11,thickness:2,color:"muted"}),i(b?"connection.reconnecting":"connection.reconnectNow")]})]})}),S&&n.jsx("div",{className:N,style:k,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 R1(){const e=c.useSyncExternalStore(QC,fm,fm),{t}=he("common");return e.reloadRequired?n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal,1000)] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4",role:"alertdialog","aria-modal":"true","aria-labelledby":"dashboard-wire-reload-title","data-testid":"dashboard-wire-reload-overlay",children:n.jsxs("div",{className:"max-w-[420px] w-full rounded-2xl border border-border-default bg-bg-primary p-5 shadow-2xl text-text-primary",children:[n.jsx("h2",{id:"dashboard-wire-reload-title",className:"text-base font-semibold mb-2",children:t("app.dashboardWire.reloadTitle")}),n.jsx("p",{className:"text-sm text-text-secondary mb-4",children:t("app.dashboardWire.reloadBody")}),n.jsx("button",{type:"button",className:"w-full rounded-lg px-3 py-2 text-sm font-semibold bg-accent-primary text-white hover:opacity-90",onClick:()=>window.location.reload(),children:t("app.dashboardWire.reload")})]})}):e.daemonUpdateRequired.length===0?null:n.jsxs("div",{className:"fixed left-1/2 top-[calc(env(safe-area-inset-top,0px)+12px)] z-[var(--z-toast)] max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-4 py-2.5 text-[13px] leading-[1.6] shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{transform:"translateX(-50%)",background:"color-mix(in srgb, var(--status-warning, #f59e0b) 14%, var(--bg-primary))",border:"1px solid color-mix(in srgb, var(--status-warning, #f59e0b) 40%, transparent)"},role:"status","data-testid":"dashboard-wire-daemon-update",children:[n.jsx("div",{className:"font-semibold",children:t("app.dashboardWire.daemonUpdateTitle")}),n.jsx("div",{className:"text-text-secondary",children:t("app.dashboardWire.daemonUpdateBody",{count:e.daemonUpdateRequired.length})})]})}function Ei(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Fb(e){return String(e.type||e.id||"").trim()}function Va(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function Hb(e,t){const s=(t||"").trim();if(!s)return[];const r=(e||[]).find(o=>o.type===s);return Va(r==null?void 0:r.modelOptions)}function Bb(e,t){const s=(t||"").trim();if(!s)return[];const r=(e||[]).find(o=>o.type===s);return Va(r==null?void 0:r.thinkingLevelOptions)}function P1(e){const t=new Map;for(const s of e||[])s!=null&&s.type&&t.set(s.type,{models:Va(s.modelOptions),thinking:Va(s.thinkingLevelOptions)});return t}function E1(e){var t;return e.category!=="cli"||!Fb(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 Wn(e){var r;const t=new Set,s=[];for(const o of e||[]){if(!E1(o))continue;const a=Fb(o);if(!a||t.has(a))continue;t.add(a);const i=String(o.displayName||o.name||a),l=o.detectedPath||((r=o.lastDetection)==null?void 0:r.path)||null;s.push({type:a,label:i,icon:o.icon,statusLabel:l?`Detected at ${l}`:"Detected on this machine",detectedPath:l,...Array.isArray(o.modelOptions)&&o.modelOptions.length?{modelOptions:o.modelOptions}:{},...Array.isArray(o.thinkingLevelOptions)&&o.thinkingLevelOptions.length?{thinkingLevelOptions:o.thinkingLevelOptions}:{}})}return s}function Eo(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 Ks(e){return e.map(t=>t.type)}function L1(e,t){const s=Eo(e),r=t.trim();return!r||s.includes(r)?s:[...s,r]}function D1(e,t){return Eo(e).filter(s=>s!==t)}function Lm(e,t,s){const r=Eo(e),o=r.indexOf(t);if(o<0)return r;const a=r.filter(l=>l!==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 O1="Assistant",$1="claude-cli",F1="launch_assistant";function Wb(e){var t;return e?e.assistant===!0||((t=e.settings)==null?void 0:t.assistant)===!0:!1}function qs(e){return Wb(e)}function Ub(e,t){return Number(qs(t))-Number(qs(e))}function H1(e){return e.some(qs)}function B1(e){const t=String(e.status||"").toLowerCase();return t!=="offline"&&t!=="disconnected"}function W1(e){const t=e.assistant;return{cliType:e.type,label:e.displayName||e.name||e.type,supported:t?t.supported===!0:!0,...t&&!t.supported&&t.reason?{reason:t.reason}:{},promptOnly:t?t.toolRestriction==="prompt_only":!1,modelOptions:Hb([e],e.type),thinkingLevelOptions:Bb([e],e.type)}}function Ga(e,t,s){const r=s!=null&&s.model&&t.modelOptions.includes(s.model)?s.model:void 0,o=s!=null&&s.thinkingLevel&&t.thinkingLevelOptions.includes(s.thinkingLevel)?s.thinkingLevel:void 0;return{machineId:e,cliType:t.cliType,...r?{model:r}:{},...o?{thinkingLevel:o}:{}}}function U1(e){return{cliType:e.cliType,...e.model?{model:e.model}:{},...e.thinkingLevel?{thinkingLevel:e.thinkingLevel}:{}}}function K1(e){const t=[];for(const s of e){if(!(s!=null&&s.id)||!B1(s))continue;const r=(s.availableProviders||[]).filter(a=>Ei(a,"cli")).map(W1);if(r.length===0)continue;const o=a=>(a.supported?0:2)+(a.cliType===$1?0:1);r.sort((a,i)=>o(a)-o(i)),t.push({machineId:s.id,label:pn(s,{fallbackId:s.id}),clis:r})}return t}function q1(e,t){const s=K1(e),r=(o,a)=>o.clis.find(i=>i.supported&&(!a||i.cliType===a));if(t!=null&&t.cliType){const o=t.machineId?s.filter(a=>a.machineId===t.machineId):s;for(const a of o){const i=r(a,t.cliType);if(i)return{machines:s,defaultTarget:Ga(a.machineId,i,t)}}}for(const o of s){const a=r(o);if(a)return{machines:s,defaultTarget:Ga(o.machineId,a)}}return{machines:s,defaultTarget:null}}const Kb="adhdev_assistant_launch_choice";function z1(e=typeof localStorage<"u"?localStorage:void 0){try{const t=e==null?void 0:e.getItem(Kb);if(!t)return null;const s=JSON.parse(t);if(!s||typeof s.cliType!="string"||!s.cliType)return null;const r=o=>typeof s[o]=="string"&&s[o]?{[o]:s[o]}:{};return{cliType:s.cliType,...r("machineId"),...r("model"),...r("thinkingLevel")}}catch{return null}}function V1(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(Kb,JSON.stringify({machineId:e.machineId,cliType:e.cliType,...e.model?{model:e.model}:{},...e.thinkingLevel?{thinkingLevel:e.thinkingLevel}:{}}))}catch{}}function G1(e,t){return!!t&&!H1(e)}const Nc=280;function Y1({onStart:e,onStartWith:t,machines:s=[],defaultTarget:r=null,pending:o=!1,error:a=null}){var A,E,P;const{t:i}=he("common"),[l,d]=c.useState(!1),[u,m]=c.useState(null),[h,p]=c.useState(null),b=c.useRef(null),f=c.useRef(null),x=s.length>1,g=!!t&&s.some(T=>T.clis.length>0),w=r?((E=(A=s.find(T=>T.machineId===r.machineId))==null?void 0:A.clis.find(T=>T.cliType===r.cliType))==null?void 0:E.label)||r.cliType:"",S=w&&(r!=null&&r.model)?`${w} · ${r.model}`:w,C=u?(P=s.find(T=>T.machineId===u.machineId))==null?void 0:P.clis.find(T=>T.cliType===u.cliType&&T.supported):void 0,j=()=>{l||m(r),d(!l)},v=(T,M)=>{!u||!C||m(Ga(u.machineId,C,{...u,[T]:M||void 0}))},y=c.useCallback((T=!1)=>{var M;d(!1),T&&((M=b.current)==null||M.focus())},[]);c.useLayoutEffect(()=>{var _;if(!l||typeof window>"u"){p(null);return}const T=(_=b.current)==null?void 0:_.getBoundingClientRect();if(!T)return;const M=Math.min(Math.max(8,T.left),window.innerWidth-Nc-8);p({top:T.bottom+6,left:Math.max(8,M)})},[l]),c.useEffect(()=>{if(!l||typeof window>"u")return;const T=I=>{I.key==="Escape"&&(I.stopPropagation(),y(!0))},M=I=>{var L,$;const D=I.target;D&&((L=b.current)!=null&&L.contains(D)||($=f.current)!=null&&$.contains(D)||y())},_=()=>y();return window.addEventListener("keydown",T,!0),document.addEventListener("mousedown",M,!0),window.addEventListener("resize",_),()=>{window.removeEventListener("keydown",T,!0),document.removeEventListener("mousedown",M,!0),window.removeEventListener("resize",_)}},[y,l]),c.useEffect(()=>{var M;if(!l)return;const T=f.current;(M=(T==null?void 0:T.querySelector('[role="menuitemradio"][aria-checked="true"]:not([disabled])'))??(T==null?void 0:T.querySelector('[role="menuitemradio"]:not([disabled])')))==null||M.focus()},[l,h]);const N=T=>{var D,L,$;if(T.key!=="ArrowDown"&&T.key!=="ArrowUp"||((L=(D=T.target)==null?void 0:D.getAttribute)==null?void 0:L.call(D,"role"))!=="menuitemradio")return;T.preventDefault();const M=Array.from((($=f.current)==null?void 0:$.querySelectorAll('[role="menuitemradio"]:not([disabled])'))??[]);if(M.length===0)return;const _=M.indexOf(document.activeElement),I=M[(_+(T.key==="ArrowDown"?1:-1)+M.length)%M.length];I==null||I.focus()},k=a?i("dashboard.assistant.startFailed",{error:a}):S?`${i("dashboard.assistant.startHint")} · ${i("dashboard.assistantLaunch.startWith",{cli:S})}`:i("dashboard.assistant.startHint");return n.jsxs("span",{className:"ml-2 inline-flex items-stretch","data-testid":"dashboard-start-assistant-group",children:[n.jsxs("button",{type:"button",onClick:e,disabled:o,className:ct("btn btn-secondary btn-sm inline-flex items-center gap-1.5",g&&"rounded-r-none"),title:k,"aria-label":i("dashboard.assistant.start"),"data-testid":"dashboard-start-assistant",children:[n.jsx(pl,{size:14}),n.jsx("span",{children:i(o?"dashboard.assistant.starting":"dashboard.assistant.start")})]}),g&&n.jsx("button",{ref:b,type:"button",onClick:j,disabled:o,className:"btn btn-secondary btn-sm rounded-l-none border-l border-border-default px-1.5 inline-flex items-center",title:i("dashboard.assistantLaunch.chooseCli"),"aria-label":i("dashboard.assistantLaunch.chooseCli"),"aria-haspopup":"menu","aria-expanded":l,"data-testid":"dashboard-start-assistant-menu",children:n.jsx(bi,{size:12,className:"-rotate-90"})}),l&&g&&typeof document<"u"&&An.createPortal(n.jsxs("div",{ref:f,role:"menu","aria-label":i("dashboard.assistantLaunch.chooseCli"),onKeyDown:N,"data-testid":"dashboard-start-assistant-options",className:"fixed z-[var(--z-popover)] flex max-h-[70vh] flex-col rounded-xl border border-border-default bg-bg-card p-1 shadow-xl backdrop-blur-xl",style:h?{top:h.top,left:h.left,width:Nc}:{top:-9999,left:-9999,width:Nc,visibility:"hidden"},children:[n.jsx("div",{className:"flex min-h-0 flex-col overflow-y-auto",children:s.map(T=>n.jsxs("div",{role:"group","aria-label":T.label,className:"flex flex-col",children:[x&&n.jsx("div",{className:"px-2.5 pb-1 pt-2 text-2xs font-semibold uppercase tracking-wide text-text-muted",children:T.label}),T.clis.map(M=>{const _=!!u&&u.machineId===T.machineId&&u.cliType===M.cliType;return n.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":_,disabled:!M.supported,"data-assistant-cli":M.cliType,"data-assistant-machine":T.machineId,title:M.supported?M.promptOnly?i("dashboard.assistantLaunch.noToolLockHint"):void 0:i("dashboard.assistantLaunch.unavailable",{reason:M.reason||i("dashboard.assistantLaunch.unsupported")}),onClick:()=>{if(!M.supported)return;const I=r&&r.machineId===T.machineId&&r.cliType===M.cliType;m(Ga(T.machineId,M,I?r:null))},className:ct("flex w-full items-start 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",M.supported?"hover:bg-bg-secondary hover:text-text-primary focus-visible:bg-bg-secondary focus-visible:text-text-primary focus-visible:outline-none":"cursor-not-allowed opacity-50"),children:[n.jsx("span",{className:"mt-0.5 flex w-4 shrink-0 justify-center","aria-hidden":!0,children:_?n.jsx(Cr,{size:13}):null}),n.jsxs("span",{className:"flex min-w-0 flex-col",children:[n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx("span",{className:"truncate",children:M.label}),M.supported&&M.promptOnly&&n.jsx("span",{className:"shrink-0 rounded border border-border-default px-1 text-2xs text-text-muted","data-testid":"assistant-cli-no-tool-lock",children:i("dashboard.assistantLaunch.noToolLock")})]}),!M.supported&&n.jsx("span",{className:"line-clamp-2 text-2xs font-normal text-text-muted","data-testid":"assistant-cli-unavailable-reason",children:M.reason||i("dashboard.assistantLaunch.unsupported")})]})]},M.cliType)})]},T.machineId))}),u&&C&&n.jsxs("div",{className:"mt-1 flex flex-col gap-1.5 border-t border-border-default px-1.5 pb-1 pt-2","data-testid":"assistant-launch-options",children:[(C.modelOptions.length>0||C.thinkingLevelOptions.length>0)&&n.jsxs("div",{className:"flex gap-1.5",children:[C.modelOptions.length>0&&n.jsxs("label",{className:"flex min-w-0 flex-1 flex-col gap-0.5 text-2xs text-text-muted",children:[i("dashboard.assistantLaunch.model"),n.jsxs("select",{value:u.model??"",onChange:T=>v("model",T.target.value),className:"min-w-0 rounded-md border border-border-default bg-bg-secondary px-1.5 py-1 text-xs text-text-primary","data-testid":"assistant-launch-model",children:[n.jsx("option",{value:"",children:i("dashboard.assistantLaunch.defaultOption")}),C.modelOptions.map(T=>n.jsx("option",{value:T,children:T},T))]})]}),C.thinkingLevelOptions.length>0&&n.jsxs("label",{className:"flex w-[88px] shrink-0 flex-col gap-0.5 text-2xs text-text-muted",children:[i("dashboard.assistantLaunch.thinking"),n.jsxs("select",{value:u.thinkingLevel??"",onChange:T=>v("thinkingLevel",T.target.value),className:"min-w-0 rounded-md border border-border-default bg-bg-secondary px-1.5 py-1 text-xs text-text-primary","data-testid":"assistant-launch-thinking",children:[n.jsx("option",{value:"",children:i("dashboard.assistantLaunch.defaultOption")}),C.thinkingLevelOptions.map(T=>n.jsx("option",{value:T,children:T},T))]})]})]}),n.jsxs("button",{type:"button",onClick:()=>{y(),t==null||t(u)},className:"btn btn-primary btn-sm inline-flex items-center justify-center gap-1.5","data-testid":"assistant-launch-start",children:[n.jsx(pl,{size:13}),n.jsx("span",{children:i("dashboard.assistantLaunch.start")})]})]})]}),document.body)]})}function qb({mode:e,onChange:t,compact:s=!1}){const{t:r}=he("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(bd,{size:o}):n.jsx(Cn,{size:o})})}function Q1(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 J1(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 X1(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 Od({git:e,className:t="",compact:s=!1}){const r=Q1(e),o=J1(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 ${X1(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})]})}const _s=8,Dm=6;function Z1(e,t,s){const r=Math.max(_s,s.width-t.width-_s),o=e.left+e.width/2-t.width/2,a=Math.min(Math.max(_s,o),r),i=e.bottom+Dm,l=i+t.height<=s.height-_s,d=e.top-Dm-t.height;return!l&&d>=_s?{top:d,left:a,placement:"above"}:{top:Math.max(_s,Math.min(i,s.height-t.height-_s)),left:a,placement:"below"}}function $d(){const e=c.useRef(null),t=c.useRef(null),[s,r]=c.useState({pinned:!1,peeking:!1}),[o,a]=c.useState(null),i=s.pinned||s.peeking,l=c.useCallback(()=>r({pinned:!1,peeking:!1}),[]),d=c.useCallback(()=>r(h=>h.pinned?{pinned:!1,peeking:!1}:{pinned:!0,peeking:!1}),[]),u=c.useCallback(h=>r(p=>p.peeking===h?p:{...p,peeking:h}),[]),m=c.useCallback(()=>{const h=e.current,p=t.current;if(!h||!p||typeof window>"u")return;const b=h.getBoundingClientRect(),f=p.getBoundingClientRect();a(Z1({top:b.top,bottom:b.bottom,left:b.left,width:b.width},{width:f.width,height:f.height},{width:window.innerWidth,height:window.innerHeight}))},[]);return c.useLayoutEffect(()=>{if(!i){a(null);return}m()},[i,m]),c.useEffect(()=>{if(!i||typeof window>"u")return;const h=f=>{var x,g;f.key==="Escape"&&(f.stopPropagation(),f.preventDefault(),l(),(g=(x=e.current)==null?void 0:x.focus)==null||g.call(x))},p=f=>{var g,w;const x=f.target;x&&((g=e.current)!=null&&g.contains(x)||(w=t.current)!=null&&w.contains(x)||l())},b=()=>m();return window.addEventListener("keydown",h,!0),document.addEventListener("pointerdown",p,!0),document.addEventListener("mousedown",p,!0),window.addEventListener("resize",b),window.addEventListener("scroll",b,!0),()=>{window.removeEventListener("keydown",h,!0),document.removeEventListener("pointerdown",p,!0),document.removeEventListener("mousedown",p,!0),window.removeEventListener("resize",b),window.removeEventListener("scroll",b,!0)}},[l,i,m]),{anchorRef:e,popoverRef:t,open:i,pinned:s.pinned,position:o,close:l,togglePinned:d,setPeeking:u}}function Fd({id:e,popoverRef:t,position:s,children:r,className:o,role:a="tooltip",ariaLabel:i}){return typeof document>"u"?null:An.createPortal(n.jsx("div",{ref:t,id:e,role:a,"aria-label":i,"data-placement":(s==null?void 0:s.placement)??"below",className:ct("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 zb(e){return e==null||e===!1||e===""}function nt({content:e,label:t,size:s=13,className:r,popoverClassName:o}){const{t:a}=he("common"),i=c.useId(),l=`${i}-pop`,d=`${i}-desc`,{anchorRef:u,popoverRef:m,open:h,position:p,togglePinned:b,setPeeking:f}=$d();return zb(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?l:void 0,"aria-describedby":d,onClick:x=>{x.preventDefault(),x.stopPropagation(),b()},onPointerEnter:x=>{x.pointerType==="mouse"&&f(!0)},onPointerLeave:x=>{x.pointerType==="mouse"&&f(!1)},className:ct("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(Co,{size:s})}),n.jsx("span",{id:d,className:"sr-only",children:e}),h&&n.jsx(Fd,{id:l,popoverRef:m,position:p,className:o,children:e})]})}function Qt({content:e,children:t,className:s,popoverClassName:r}){const o=c.useId(),a=`${o}-pop`,i=`${o}-desc`,{anchorRef:l,popoverRef:d,open:u,position:m,togglePinned:h,setPeeking:p}=$d();if(zb(e))return n.jsx(n.Fragment,{children:t});const b=n.jsx("span",{ref:f=>{l.current=f},"data-tooltip":"",tabIndex:0,"aria-describedby":i,className:ct("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:[b,n.jsx("span",{id:i,className:"sr-only",children:e}),u&&n.jsx(Fd,{id:a,popoverRef:d,position:m,className:r,children:e})]})}function VO({children:e,content:t,label:s,className:r,popoverClassName:o}){const i=`${c.useId()}-pop`,{anchorRef:l,popoverRef:d,open:u,position:m,togglePinned:h}=$d();return n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:p=>{l.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(Fd,{id:i,popoverRef:d,position:m,role:"dialog",ariaLabel:s,className:ct("whitespace-normal",o),children:t})]})}function Vb({value:e,live:t=!0,fallback:s="",className:r}){const{i18n:o}=he("common"),[,a]=c.useState(0),i=_o(e);if(c.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 l=(o==null?void 0:o.resolvedLanguage)||(o==null?void 0:o.language);return n.jsx(Qt,{content:To(i,{locale:l,seconds:!0}),children:n.jsx("time",{dateTime:new Date(i).toISOString(),className:r,children:Fa(i,{locale:l})})})}async function Gb(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 Yb({value:e,label:t,className:s}){const{t:r}=he("common"),[o,a]=c.useState(!1),i=c.useRef(null);return c.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),n.jsx("button",{type:"button",onClick:async l=>{l.stopPropagation(),await Gb(e)&&(a(!0),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500))},title:e,"aria-label":`${t??r("common.copyId")}: ${e}`,className:ct("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 Hd({rows:e=[],children:t,summary:s,className:r,summaryClassName:o}){const{t:a}=he("common"),i=e.filter(l=>typeof l.value=="string"&&l.value);return i.length===0&&!t?null:n.jsxs("details",{className:ct("group text-xs",r),"data-technical-details":"",children:[n.jsxs("summary",{className:ct("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(l=>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:l.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:l.value,children:l.value}),l.copyable!==!1&&n.jsx(Yb,{value:l.value})]})]},l.label)),t]})]})}function Qb(e){const t=e.replace(/[\\/]+$/,""),s=t.split(/[\\/]/);return s[s.length-1]||t||e}const eA=c.createContext(null);function Bd(){return c.useContext(eA)}function tA(e){const t=e.replace(/^(daemon_|standalone_)/,"");return t.length<=20?t:`${t.slice(0,17)}…`}function nA(e){return py(e)}function sA(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 rA(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 Ya(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=sA(e);return t.outOfSync?"degraded":t.dirty||rA(e)?"dirty":"online"}function oA(e,t){const s=t?Ya(t):void 0;return!e||e==="unknown"?s:e}function aA(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(Da).filter(i=>i!==null);if(a.length>0)return a}const s=Ze(e.activeSession??e.active_session),r={...s,sessionId:je(s.sessionId,s.id,s.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id)},o=Da(r);return o?[o]:void 0}function iA(e){const t=Ze(e.connection);return Object.keys(t).length>0?t:void 0}function cA(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 Jb(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 Om(e){var r,o,a,i,l,d;let t=0;const s=e.git;return Jb(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+=cd(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),((l=e.connection)==null?void 0:l.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 lA(e,t){var f,x,g,w;const s=Om(e),o=Om(t)>s?t:e,a=o===t?e:t,i=o.git??a.git,l=(((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=(((g=o.activeSessionDetails)==null?void 0:g.length)??0)>0?o.activeSessionDetails:a.activeSessionDetails,m=(((w=o.providerPriority)==null?void 0:w.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")?Ya(i):o.health,providers:l??[],activeSessions:d??[],...u&&u.length>0?{activeSessionDetails:u}:{},...m&&m.length>0?{providerPriority:m}:{},...h?{connection:h}:{},...i?{git:i}:{}},b=Ze(o.branchConvergence);return Object.keys(b).length>0?Object.assign(p,{branchConvergence:b}):delete p.branchConvergence,i&&(delete p.gitProbePending,delete p.error),p}const dA=new Set(["self","local","member_push","coordinator_probe","none"]);function Ol(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function $m(e){const t=Ze(e),s=je(t.source);if(!s||!dA.has(s))return null;const r=je(t.lastRefreshError);return{source:s,observedAt:Ol(t.observedAt),refreshing:t.refreshing===!0,unreachableSince:Ol(t.unreachableSince),...r?{lastRefreshError:r}:{}}}function Xb(e){const t=Ze(e),s=je(t.nodeId,t.id);if(!s)return null;const r=Ze(t.cachedStatus),o=nA(t),a=o?void 0:xa(Ze(t.git),t)??xa(t,t),i=o??a,l=i?void 0:xa(Ze(r.git),t),d=i??l,u=je(t.machineStatus,t.machine_status,r.machineStatus,r.machine_status),m=je(t.health),h=o?Ya(d):oA(m,i)||(d?Ya(d):void 0)||je(r.health)||u||je(t.status)||"unknown",b=(o?void 0:je(t.error))??(i?void 0:je(r.error)),f=aA(t),x=sc(t.activeSessions),g=(f==null?void 0:f.map(k=>k.sessionId))??[],w=sc(t.providerPriority),S=Vt(t.gitProbePending,t.git_probe_pending),C=i?void 0:S,j=iA(t),v=Ze(t.branchConvergence??t.branch_convergence),y=j==null?void 0:j.state,N=o&&(!(j!=null&&j.reported)||y==="unknown")?cA(j):j;return{nodeId:s,machineLabel:je(t.machineLabel,t.machine_label,t.hostname)||tA(je(t.daemonId,t.daemon_id,t.machineId,t.machine_id,s)||s),workspace:je(t.workspace,d==null?void 0:d.workspace)||"",...je(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:je(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...je(t.daemonId,t.daemon_id)?{daemonId:je(t.daemonId,t.daemon_id)}:{},...je(t.machineId,t.machine_id)?{machineId:je(t.machineId,t.machine_id)}:{},...u?{machineStatus:u}:{},...Vt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Vt(t.isLocalWorktree,t.is_local_worktree)}:{},...je(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:je(t.worktreeBranch,t.worktree_branch)}:{},...je(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:je(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:h,...d?{git:d}:{},...C!==void 0?{gitProbePending:C}:{},providers:sc(t.providers),activeSessions:x.length>0?x:g,...f&&f.length>0?{activeSessionDetails:f}:{},...w.length>0?{providerPriority:w}:{},...Vt(t.launchReady)!==void 0?{launchReady:Vt(t.launchReady)}:o?{launchReady:!0}:{},...je(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)?{lastSeenAt:je(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)}:{},...je(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)?{updatedAt:je(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)}:{},...N?{connection:N}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...t.scheduling&&typeof t.scheduling=="object"?{scheduling:t.scheduling}:{},...Vt(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}:{},...je(t.daemonBuildVersion,t.daemon_build_version)?{daemonBuildVersion:je(t.daemonBuildVersion,t.daemon_build_version)}:{},...t.nodeFacts&&typeof t.nodeFacts=="object"&&!Array.isArray(t.nodeFacts)?{nodeFacts:t.nodeFacts}:{},...$m(t.gitObservation)?{gitObservation:$m(t.gitObservation)}:{},...Fm(t.heldRuntime??t.held_runtime)?{heldRuntime:Fm(t.heldRuntime??t.held_runtime)}:{},...je(t.role)?{role:je(t.role)}:{},...je(t.nodeLabel,t.node_label)?{nodeLabel:je(t.nodeLabel,t.node_label)}:{},...b?{error:b}:{}}}const uA=new Set(["member_push","coordinator_probe","none"]);function Fm(e){const t=Ze(e);if(Object.keys(t).length===0)return null;const s=je(t.source)||"none";if(!uA.has(s))return null;const r=Array.isArray(t.sessions)?t.sessions.filter(o=>Object.keys(Ze(o)).length>0):[];return{...t,source:s,observedAt:Ol(t.observedAt),refreshing:t.refreshing===!0,sessions:r}}function mA(e,t,s){const r=Ze(e),o=Ze(r.settings),a=Ze(r.activeChat),i=je(Ze(r.coordinator).meshId,o.meshCoordinatorFor),l=t&&i===t?"coordinator":t&&je(o.meshNodeFor)===t?"worker":void 0,d=Da({sessionId:je(r.instanceId,r.id,r.sessionId),providerType:je(r.providerType),state:je(r.status),chatStatus:je(a.status),...l?{role:l}:{},...s?{workspace:s}:{}});return d?{...d,isSelfCoordinator:!1}:null}function hA(e,t,s,r){const o=Ze(e),a=Ze(o.settings),i=je(a.meshNodeId);return i?i===s.nodeId:!r||!t?!1:je(Ze(o.coordinator).meshId,a.meshCoordinatorFor)===t||je(a.meshNodeFor)===t}function Zb(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=>hA(d,e,r,a)).map(d=>mA(d,e,r.workspace||void 0)).filter(d=>d!==null);if(i.length===0)return r;const l=Qa([...r.activeSessionDetails??[],...i]);return{...r,activeSessionDetails:l,activeSessions:Qa([...l,...(r.activeSessions??[]).map(d=>({sessionId:d}))]).map(d=>d.sessionId)}})}function Qa(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 eg(e,t){const s=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],r=s.map(Da).filter(o=>o!==null);return r.length===0?t:t.map(o=>{const a=r.filter(l=>{const d=Ze(s.find(p=>{const b=Ze(p);return je(b.sessionId,b.session_id,b.id)===l.sessionId})),u=je(d.nodeId,d.node_id),m=je(d.daemonId,d.daemon_id),h=je(d.workspace);return u&&u===o.nodeId?!0:mn(m,o.daemonId)?!h||!o.workspace||h===o.workspace:!!(h&&o.workspace&&h===o.workspace)});if(a.length===0)return o;const i=Qa([...o.activeSessionDetails??[],...a]);return{...o,activeSessionDetails:i,activeSessions:Qa([...o.activeSessionDetails??[],...a,...(o.activeSessions??[]).map(l=>({sessionId:l}))]).map(l=>l.sessionId)}})}function pA(e){const t=Ze(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||je(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||Vt(t.is_local_worktree)!==void 0}function tg(e){const t=new Map,s=[];for(const r of e){const o=pA(r)?Xb(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=lA(a,o);t.set(o.nodeId,i);const l=s.findIndex(d=>d.nodeId===o.nodeId);l>=0&&(s[l]=i)}return s}function GO(e){const t=e??{},s=tg(t.nodes??[]);return{...t,nodes:Zb(je(t.meshId)||"",eg(t,s))}}function YO(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:Jb(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 fA(e){const t=je(e.meshId,e.mesh_id,e.id),s=e.nodes,r=Array.isArray(s)?s.map(d=>Xb(d)).filter(d=>d!==null):null;if(!t||!r)return null;const o=Zb(t,eg(e,tg(r))),a=je(e.meshName,e.mesh_name,e.name),i=je(e.repoIdentity,e.repo_identity),l=je(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!a||!i||!l?null:{...e,meshId:t,meshName:a,repoIdentity:i,refreshedAt:l,nodes:o}}function bA(e){var a;let t=0;const s=Ze(e.sourceOfTruth),r=Ze(s.directPeerTruth);je(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 l=i.git;if(!l){i.gitProbePending&&(t-=8);continue}t+=10,l.isGitRepo===!0&&(t+=5),l.isGitRepo===!1&&(t+=1),l.branch&&(t+=4),l.upstream&&(t+=3),l.headCommit&&(t+=3),t+=cd(l.upstreamStatus),typeof l.ahead=="number"&&(t+=1),typeof l.behind=="number"&&(t+=1),typeof l.lastCheckedAt=="number"&&(t+=2),t+=(((a=l.submodules)==null?void 0:a.length)??0)*2}return t}function gA(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 xA=20;function Hm(e){let t=null;for(const s of e){const r=fA(Ze(s));if(!r)continue;const o=bA(r),a=gA(r);if(!t){t={status:r,score:o,refreshedAt:a};continue}(Math.abs(o-t.score)<=xA?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 Li(e){const s=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,r=Hm([s==null?void 0:s.status,s]);return r||Hm([e==null?void 0:e.status,e])}function yA(e){var l;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((l=s==null?void 0:s.coordinator)==null?void 0:l.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 vA(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 wA(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 SA(e,t){var o,a;if(!t)return null;const s=Li(e),r=(o=s==null?void 0:s.nodes)==null?void 0:o.find(i=>gy(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 kA={sm:"max-w-md",md:"max-w-lg",lg:"max-w-3xl"},Bm={center:"items-center justify-center",sheet:"items-end justify-center sm:items-center",stretch:"items-stretch justify-center md:items-center"};function Sr({open:e=!0,onClose:t,align:s="center",size:r="md",chrome:o=!0,closeOnBackdrop:a=!0,closeOnEsc:i=!0,ariaLabel:l,ariaLabelledBy:d,overlayClassName:u,surfaceClassName:m,children:h}){c.useEffect(()=>{if(!e||!i)return;const g=w=>{w.key==="Escape"&&t()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[e,i,t]);const p=c.useCallback(g=>{a&&g.target===g.currentTarget&&t()},[a,t]);if(!e)return null;const b=o?ct("fixed inset-0 flex",Bm[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):ct("fixed inset-0 flex",Bm[s],u),f=o?ct("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",kA[r],m):ct(m),x=n.jsx("div",{className:b,style:o?{zIndex:"var(--z-modal-backdrop)"}:void 0,onClick:p,children:n.jsx("div",{role:"dialog","aria-modal":"true","aria-label":l,"aria-labelledby":d,className:f,style:o?{zIndex:"var(--z-modal)"}:void 0,onClick:g=>g.stopPropagation(),children:h})});return typeof document>"u"?x:An.createPortal(x,document.body)}function ng({open:e,onClose:t,size:s="md",title:r,footer:o,children:a,showClose:i=!0,closeOnBackdrop:l=!0,closeOnEsc:d=!0,ariaLabel:u,className:m,contentClassName:h}){const p=r!=null||i;return n.jsxs(Sr,{open:e,onClose:t,size:s,closeOnBackdrop:l,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":Ye.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(Et,{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 $l=new Map;function jA(e){return{meshId:e,daemonId:null,status:null,response:null,loadedAt:null,loading:!1,refreshing:!1,error:null}}function Di(e){let t=$l.get(e);return t||(t={snapshot:jA(e),inFlight:null,queuedRefresh:null,listeners:new Set},$l.set(e,t)),t}function us(e,t){var r;const s=Di(e);(r=t.status)!=null&&r.meshName&&r1(e,t.status.meshName),s.snapshot={...s.snapshot,...t};for(const o of[...s.listeners])try{o()}catch{}}function uo(e){var t;return e?((t=$l.get(e))==null?void 0:t.snapshot)??null:null}function NA(e,t){const s=Di(e);return s.listeners.add(t),()=>{s.listeners.delete(t)}}function CA(e,t,s=null){us(e,{status:t,daemonId:s,loadedAt:t?Date.now():null,error:null})}function _A(e,t,s){us(e,{status:t,daemonId:s,loadedAt:Date.now(),error:null,loading:!1})}function AA(e){Di(e).snapshot.status||us(e,{loading:!0,error:null})}function TA(e){return e instanceof Error?e.message:typeof e=="string"?e:"Failed to load mesh status"}function Oi(e){const{meshId:t,daemonId:s,load:r}=e,o=e.refresh===!0,a=e.extract??(m=>Li(m));if(!t||!s)return Promise.resolve(null);const i=Di(t),l=i.inFlight;if(l&&l.daemonId===s)return!o||l.refresh?l.promise:(i.queuedRefresh||(i.queuedRefresh=l.promise.then(()=>(i.queuedRefresh=null,Oi(e)))),i.queuedRefresh);const d=i.snapshot.status!==null;us(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?(us(t,{status:p,response:h,daemonId:s,loadedAt:Date.now(),error:null}),p):(us(t,{error:"mesh_status returned an unexpected payload."}),null)}catch(h){return us(t,{error:TA(h)}),null}finally{((m=i.inFlight)==null?void 0:m.promise)===u&&(i.inFlight=null),us(t,{loading:!1,refreshing:!1})}})();return i.inFlight={daemonId:s,refresh:o,promise:u},u}const Ja=new Set;function IA(e){if(Ja.size===0)return!1;for(const t of[...Ja])try{t(e)}catch{}return!0}function MA(e){return Ja.add(e),()=>Ja.delete(e)}const ks={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`},RA=new Set(["missing-credentials","expired-token","unauthorized","quota-exhausted","rate-limited","network","server","parse","cli-unavailable","unsupported","setup-required","no-data","unknown"]);function Wd(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)=>RA.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 PA={"antigravity-cli":"Antigravity CLI","claude-cli":"Claude Code","codex-cli":"Codex CLI","cursor-cli":"Cursor CLI","grok-cli":"Grok CLI",kimi:"Kimi Code",opencode:"opencode"};function EA(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 LA(e,t=ks){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(EA((o??0)+(a??0)))),typeof s.sessions=="number"&&r.push(t.usageSessions(s.sessions)),r.length===0?null:`${s.days}d ${r.join(" · ")}`}function kr(e){return PA[e]??e}function Wm(e){return Number.isFinite(e)?e>=90?"danger":e>=70?"warn":"good":"default"}function DA(e,t=Date.now(),s=ks){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 Na(e,t=Date.now()){const s=e==null?void 0:e.resetsAt;return typeof s=="number"&&Number.isFinite(s)&&s>0&&s<=t}ks.windowReset();function Um(e){return!!e&&typeof e.usedPercent=="number"&&Number.isFinite(e.usedPercent)}function OA(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 $A(e){return Um(e.session)||Um(e.weekly)?!0:Array.isArray(e.buckets)&&e.buckets.some(t=>!!t&&typeof t.usedPercent=="number"&&Number.isFinite(t.usedPercent))}function FA(e){var t;if(!OA(e)&&$A(e))return"stale";if(((t=e.metadata)==null?void 0:t.lastGoodWindows)===!0)return"refreshing"}function Km(e,t=Date.now(),s=!1,r=ks){if(!e||typeof e.usedPercent!="number"||!Number.isFinite(e.usedPercent))return null;if(Na(e,t))return r.windowReset();const o=r.used(e.usedPercent.toFixed(1)),a=DA(e.resetsAt,t,r),i=a?`${o} · ${a}`:o,l=s===!0||s==="refreshing"?"refreshing":s==="stale"?"stale":null;return l?`${i} · ${r.cue(l)}`:i}function HA(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 BA(e,t=ks){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),l=Number(a.windowMinutes);if(!Number.isFinite(i)||!Number.isFinite(l)||l<=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()} ${HA(l)}`,usedPercent:i,window:{usedPercent:i,windowMinutes:l,resetsAt:typeof a.resetsAt=="number"?a.resetsAt:null}})}return r.sort((a,i)=>a.label.localeCompare(i.label))}function WA(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 UA(e,t=ks){var l;const s=typeof e.error=="string"?e.error.trim():"",r=(l=e.metadata)==null?void 0:l.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 KA(e,t=Date.now(),s=ks){const r=FA(e),o=(b,f,x)=>{const g=Km(b,t,r,s);if(!g)return null;const w=b.usedPercent,S=Na(b,t);return{key:f,label:`${x} ${g}`,usedPercent:S?null:w,hint:f,tone:S?"default":Wm(w)}},a=o(e.session,"session","5h"),i=o(e.weekly,"weekly","7d"),l=o(e.monthly,"monthly","30d"),d=BA(e,s).map(b=>({key:b.label,label:`${b.label} ${Km(b.window,t,r,s)}`,usedPercent:Na(b.window,t)?null:b.usedPercent,hint:"bucket",tone:Na(b.window,t)?"default":Wm(b.usedPercent)})),u=d.length>0?d:[a,i,l].filter(b=>b!==null),m=LA(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:WA(e),compactChip:null}:{kind:"failure",cue:r,chips:[],usageLabel:null,message:UA(e,s),compactChip:null}}function Ud(e){return(t,s=Date.now())=>KA(t,s,e)}function QO(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 sg(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)=>kr(s.provider).localeCompare(kr(r.provider)))}function JO(e,t=Date.now(),s=ks){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 qm(e){return To(e,{seconds:!0})||"—"}function qA({sessionId:e,daemonId:t,conv:s,onClose:r}){var L;const{t:o}=he("common"),a=Ud(Wd(o)),{sendCommand:i}=wt(),l=Bd(),[d,u]=c.useState(!0),[m,h]=c.useState(null),[p,b]=c.useState(null),[f,x]=c.useState(null),[g,w]=c.useState(null),S=c.useMemo(()=>vA(s),[s]),C=c.useMemo(()=>wA(s),[s]),j=c.useCallback(async()=>{u(!0),b(null);try{const $=await i(t,"get_session_info",{targetSessionId:e}),U=$&&typeof $=="object"?$:{},J=U.result&&typeof U.result=="object"?U.result:U;J!=null&&J.success?h(J):(b((J==null?void 0:J.error)||o("sessionInfo.failedToLoad")),h(null))}catch($){b(($==null?void 0:$.message)||String($)),h(null)}finally{u(!1)}},[i,t,e,o]);c.useEffect(()=>{j()},[j]);const v=c.useMemo(()=>{var $,U;return yA({conv:s,sessionDaemonId:t,heldCoordinatorDaemonId:S?($=uo(S))==null?void 0:$.daemonId:null,reportedCoordinatorDaemonId:(U=m==null?void 0:m.meshWorker)==null?void 0:U.coordinatorDaemonId})},[s,t,S,(L=m==null?void 0:m.meshWorker)==null?void 0:L.coordinatorDaemonId]),y=c.useCallback(async()=>{var K,R;if(x(null),w(null),!S||!C||!v)return;const U=((K=uo(S))==null?void 0:K.status)??null??await Oi({meshId:S,daemonId:v,refresh:!1,load:(O,H,B)=>l!=null&&l.loadMeshStatus?l.loadMeshStatus(O,H,{refresh:B.refresh}):i(O,"mesh_status",{meshId:H})});if(!U){w(((R=uo(S))==null?void 0:R.error)||o("sessionInfo.meshNodeUnavailable"));return}const J=SA(U,C);if(!J){w(o("sessionInfo.stampedToNode"));return}x(J)},[l,i,v,S,C,o]);c.useEffect(()=>{y()},[y]);const[N,k]=c.useState(!1),A=c.useCallback(async()=>{await Gb(zA({sessionId:e,daemonId:t,conv:s,data:m,meshNode:f,meshNodeError:g}))&&(k(!0),setTimeout(()=>k(!1),1500))},[s,t,m,f,g,e]),E=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(N?"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")})]}),P=$=>o($?"common.yes":"common.no"),T=m==null?void 0:m.session,M=(T==null?void 0:T.workspace)||(s==null?void 0:s.workspacePath)||"",_=(s==null?void 0:s.machineName)||(m==null?void 0:m.machineNickname)||"",I=m==null?void 0:m.meshWorker,D=sg((f==null?void 0:f.quota)??(m==null?void 0:m.quota));return n.jsx(ng,{open:!0,onClose:r,title:o("sessionInfo.title"),size:"lg",footer:E,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")}),T&&n.jsxs("div",{className:"space-y-1.5","data-testid":"session-info-summary",children:[n.jsx(Je,{k:o("sessionInfo.rowProvider"),v:T.providerName||T.providerType}),M&&n.jsx(Je,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(Qt,{content:M,children:n.jsx("span",{className:"truncate",children:Qb(M)})})}),_&&n.jsx(Je,{k:o("sessionInfo.rowMachine"),v:_}),T.spawnedAtMs?n.jsx(Je,{k:o("sessionInfo.rowStarted"),v:n.jsx(Vb,{value:T.spawnedAtMs})}):null,(s==null?void 0:s.git)&&n.jsx(Je,{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(Je,{k:o("sessionInfo.rowRole"),v:o("sessionInfo.roleCoordinator")}),D.map(({provider:$,quota:U})=>{const J=a(U);return n.jsx(Je,{k:[kr($),cl(U)].filter(Boolean).join(" · "),v:J.kind==="chips"?n.jsx("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:J.chips.map(K=>n.jsx(zm,{label:K.label,tone:K.tone},K.key))}):J.kind==="usage"?n.jsx(zm,{label:J.usageLabel,tone:"info"}):J.kind==="okNoWindows"?n.jsx("span",{className:"text-text-secondary",children:J.message??o("sessionInfo.quotaOkNoWindows")}):n.jsx("span",{className:"text-text-secondary",children:J.message})},$)}),(I==null?void 0:I.coordinatorSessionId)&&n.jsx(Je,{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:()=>{IA({sessionId:I.coordinatorSessionId,source:"session-info-dialog"}),r()},children:o("sessionNav.openCoordinatorChat")})]})})]}),(T||f||(m==null?void 0:m.coordinator)||g&&(S||C))&&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:[T&&n.jsxs(Ms,{title:o("sessionInfo.sectionSession"),children:[n.jsx(Je,{k:o("sessionInfo.rowSessionId"),v:n.jsx(_t,{children:T.sessionId})}),n.jsx(Je,{k:o("sessionInfo.rowProviderType"),v:n.jsx(_t,{children:T.providerType})}),T.transport&&n.jsx(Je,{k:o("sessionInfo.rowTransport"),v:T.transport}),M&&n.jsx(Je,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(_t,{children:M})}),T.spawnedAtMs?n.jsx(Je,{k:o("sessionInfo.rowSpawnedAt"),v:qm(T.spawnedAtMs)}):null,T.providerSessionId&&n.jsx(Je,{k:o("sessionInfo.rowProviderSessionId"),v:n.jsx(_t,{children:T.providerSessionId})}),(s==null?void 0:s.connectionState)&&n.jsx(Je,{k:o("sessionInfo.rowConnection"),v:s.connectionState})]}),I&&(I.meshId||I.taskId||I.coordinatorSessionId)&&n.jsxs(Ms,{title:o("sessionInfo.sectionMeshWorker"),children:[I.meshId&&n.jsx(Je,{k:o("sessionInfo.rowMeshId"),v:n.jsx(_t,{children:I.meshId})}),I.taskId&&n.jsx(Je,{k:o("sessionInfo.rowTaskId"),v:n.jsx(_t,{children:I.taskId})}),I.coordinatorSessionId&&n.jsx(Je,{k:o("sessionInfo.rowCoordinator"),v:n.jsx(_t,{children:I.coordinatorSessionId})})]}),(T==null?void 0:T.launch)&&n.jsxs(Ms,{title:o("sessionInfo.sectionLaunch"),children:[T.launch.command&&n.jsx(Je,{k:o("sessionInfo.rowCommand"),v:n.jsx(_t,{children:T.launch.command})}),T.launch.cwd&&n.jsx(Je,{k:o("sessionInfo.rowWorkingDirectory"),v:n.jsx(_t,{children:T.launch.cwd})}),Array.isArray(T.launch.args)&&T.launch.args.length>0&&n.jsx(Je,{k:o("sessionInfo.rowArgs"),v:n.jsx(_t,{children:T.launch.args.join(" ")})}),Array.isArray(T.launch.extraArgs)&&T.launch.extraArgs.length>0&&n.jsx(Je,{k:o("sessionInfo.rowExtraArgs"),v:n.jsx(_t,{children:T.launch.extraArgs.join(" ")})}),Array.isArray(T.launch.extraEnvKeys)&&T.launch.extraEnvKeys.length>0&&n.jsx(Je,{k:o("sessionInfo.rowExtraEnv"),v:n.jsx(_t,{children:T.launch.extraEnvKeys.join(", ")})})]}),f&&n.jsxs(Ms,{title:o("sessionInfo.sectionMeshNode"),children:[f.nodeId&&n.jsx(Je,{k:o("sessionInfo.rowNodeId"),v:n.jsx(_t,{children:f.nodeId})}),f.workspace&&n.jsx(Je,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(_t,{children:f.workspace})}),f.repoRoot&&f.repoRoot!==f.workspace&&n.jsx(Je,{k:o("sessionInfo.rowRepoRoot"),v:n.jsx(_t,{children:f.repoRoot})}),f.daemonId&&n.jsx(Je,{k:o("sessionInfo.rowDaemonId"),v:n.jsx(_t,{children:f.daemonId})}),f.role&&n.jsx(Je,{k:o("sessionInfo.rowRole"),v:f.role}),f.machineStatus&&n.jsx(Je,{k:o("sessionInfo.rowMachineStatus"),v:f.machineStatus}),f.health&&n.jsx(Je,{k:o("sessionInfo.rowHealth"),v:f.health}),f.isLocalWorktree&&n.jsx(Je,{k:o("sessionInfo.rowWorktree"),v:f.worktreeBranch?n.jsx(_t,{children:f.worktreeBranch}):o("common.yes")}),typeof f.launchReady=="boolean"&&n.jsx(Je,{k:o("sessionInfo.rowLaunchReady"),v:P(f.launchReady)}),f.git&&n.jsx(Je,{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(Je,{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(Je,{k:o("sessionInfo.rowProviders"),v:n.jsx(_t,{children:f.providers.join(", ")})}),Array.isArray(f.providerPriority)&&f.providerPriority.length>0&&n.jsx(Je,{k:o("sessionInfo.rowProviderPriority"),v:n.jsx(_t,{children:f.providerPriority.join(" › ")})})]}),!f&&g&&(S||C)&&n.jsx(Ms,{title:o("sessionInfo.sectionMeshNode"),children:n.jsx("div",{className:"text-text-secondary italic",children:g})}),(m==null?void 0:m.coordinator)&&n.jsxs(Ms,{title:o("sessionInfo.sectionMeshCoordinator"),children:[n.jsx(Je,{k:o("sessionInfo.rowMeshId"),v:n.jsx(_t,{children:m.coordinator.meshId})}),m.coordinator.cliType&&n.jsx(Je,{k:o("sessionInfo.rowCoordinatorCli"),v:m.coordinator.cliType}),m.coordinator.startedAt?n.jsx(Je,{k:o("sessionInfo.rowStartedAt"),v:qm(m.coordinator.startedAt)}):null,m.coordinator.injection&&n.jsx(Je,{k:o("sessionInfo.rowPromptInjection"),v:`${m.coordinator.injection.mode}${m.coordinator.injection.target?` → ${m.coordinator.injection.target}`:""}`}),m.coordinator.mcpConfigPath&&n.jsx(Je,{k:o("sessionInfo.rowMcpConfig"),v:n.jsx(_t,{children:m.coordinator.mcpConfigPath})}),m.coordinator.extraSystemPrompt&&n.jsx(Fl,{title:o("sessionInfo.blockExtraPrompt"),body:m.coordinator.extraSystemPrompt}),m.coordinator.systemPrompt&&n.jsx(Fl,{title:o("sessionInfo.blockFinalPrompt"),body:m.coordinator.systemPrompt})]}),(T==null?void 0:T.runtimeMetadata)!=null&&n.jsx(VA,{meta:T.runtimeMetadata}),p&&n.jsx("div",{className:"font-mono text-xs text-text-secondary break-all",children:p})]})]})]})})}function zA(e){const{sessionId:t,daemonId:s,conv:r,data:o,meshNode:a,meshNodeError:i}=e,l={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(l,null,2)}catch{return String(l)}}function Ms({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 Je({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 _t({children:e}){return n.jsx("code",{className:"font-mono text-xs",children:e})}function zm({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 VA({meta:e}){const{t}=he("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),l=r(s.recoveryState),d=Array.isArray(s.attachedClients)?s.attachedClients.length:null;return n.jsxs(Ms,{title:t("sessionInfo.sectionRuntime"),children:[o&&n.jsx(Je,{k:t("sessionInfo.rowRuntimeId"),v:n.jsx(_t,{children:o})}),a&&n.jsx(Je,{k:t("sessionInfo.rowLifecycle"),v:a}),i&&n.jsx(Je,{k:t("sessionInfo.rowSurface"),v:i}),l&&n.jsx(Je,{k:t("sessionInfo.rowRecoveryState"),v:l}),typeof s.restoredFromStorage=="boolean"&&n.jsx(Je,{k:t("sessionInfo.rowRestoredFromStorage"),v:s.restoredFromStorage?t("common.yes"):t("common.no")}),d!=null&&n.jsx(Je,{k:t("sessionInfo.rowAttachedClients"),v:String(d)}),n.jsx(Fl,{title:t("sessionInfo.blockRawMetadata"),body:GA(e)})]})}function GA(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Fl({title:e,body:t,defaultOpen:s=!1}){const[r,o]=c.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 YA=8e3;function QA({sessionId:e,daemonId:t,muted:s,sendDaemonCommand:r}){const[o,a]=c.useState(null),i=c.useRef(null);c.useEffect(()=>{o!==null&&s===o&&a(null)},[s,o]),c.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]);const l=o!==null?o:s,d=!!e&&!!t,u=c.useCallback(()=>{if(!e||!t)return;const m=!l;a(m),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(null),YA),r(t,"set_conversation_prefs",{sessionId:e,muted:m}).catch(h=>{console.warn("[conversation-prefs] toggle mute failed",h),a(null)})},[t,l,r,e]);return{available:d,muted:l,toggle:u}}const ta=220;function rg({conversation:e,onOpenHistory:t,onOpenRemote:s,onOpenGit:r,className:o,iconSize:a=16}){const{t:i}=he("common"),{ides:l}=yn(),{sendCommand:d}=wt(),[u,m]=c.useState(!1),[h,p]=c.useState(!1),[b,f]=c.useState(null),x=c.useRef(null),g=c.useRef(null),w=ft(e),S=c.useMemo(()=>{const N=l.find(k=>k.id===e.routeId);return ob(e,N)},[e,l]),C=QA({sessionId:e.sessionId,daemonId:e.daemonId,muted:!!(S!=null&&S.muted),sendDaemonCommand:d}),j=[];if(t&&j.push({key:"history",label:i("dashboard.header.chatHistory"),icon:n.jsx(Bp,{size:15}),onSelect:()=>t(e)}),s&&!w&&j.push({key:"remote",label:i("dashboard.header.remoteControl"),icon:n.jsx(Bn,{size:15}),onSelect:()=>s(e)}),r&&e.git&&e.daemonId&&e.workspacePath){const N=e.daemonId,k=e.workspacePath;j.push({key:"git",label:i("dashboard.header.openGitStatus"),icon:n.jsx($a,{size:15}),onSelect:()=>r(N,k)})}C.available&&j.push({key:"mute",label:C.muted?i("conversation.unmuteThis"):i("conversation.muteThis"),icon:C.muted?n.jsx(fl,{size:15}):n.jsx(Jn,{size:15}),onSelect:C.toggle,pressed:C.muted}),e.sessionId&&e.daemonId&&j.push({key:"info",label:i("sessionInfo.title"),icon:n.jsx(Co,{size:15}),onSelect:()=>p(!0)});const v=c.useCallback((N=!1)=>{var k;m(!1),N&&((k=x.current)==null||k.focus())},[]);if(c.useLayoutEffect(()=>{var A;if(!u||typeof window>"u"){f(null);return}const N=(A=x.current)==null?void 0:A.getBoundingClientRect();if(!N)return;const k=Math.min(Math.max(8,N.right-ta),window.innerWidth-ta-8);f({top:N.bottom+6,left:k})},[u]),c.useEffect(()=>{if(!u||typeof window>"u")return;const N=E=>{E.key==="Escape"&&(E.stopPropagation(),v(!0))},k=E=>{var T,M;const P=E.target;P&&((T=x.current)!=null&&T.contains(P)||(M=g.current)!=null&&M.contains(P)||v())},A=()=>v();return window.addEventListener("keydown",N,!0),document.addEventListener("mousedown",k,!0),window.addEventListener("resize",A),()=>{window.removeEventListener("keydown",N,!0),document.removeEventListener("mousedown",k,!0),window.removeEventListener("resize",A)}},[v,u]),c.useEffect(()=>{var N,k;u&&((k=(N=g.current)==null?void 0:N.querySelector('[role="menuitem"]'))==null||k.focus())},[u,b]),j.length===0)return null;const y=N=>{var P;if(N.key!=="ArrowDown"&&N.key!=="ArrowUp")return;N.preventDefault();const k=Array.from(((P=g.current)==null?void 0:P.querySelectorAll('[role="menuitem"]'))??[]),A=k.indexOf(document.activeElement),E=k[(A+(N.key==="ArrowDown"?1:-1)+k.length)%k.length];E==null||E.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(N=>!N),className:o??"btn btn-secondary btn-sm",style:{pointerEvents:"auto"},children:n.jsx(Up,{size:a})}),u&&typeof document<"u"&&An.createPortal(n.jsx("div",{ref:g,role:"menu","aria-label":i("dashboard.header.moreActions"),onKeyDown:y,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:b?{top:b.top,left:b.left,width:ta}:{top:-9999,left:-9999,width:ta,visibility:"hidden"},children:j.map(N=>n.jsxs("button",{type:"button",role:"menuitem","data-menu-item":N.key,"aria-pressed":N.pressed,onClick:()=>{v(),N.onSelect()},className:ct("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",N.pressed&&"text-amber-500"),children:[n.jsx("span",{className:"flex w-4 shrink-0 justify-center","aria-hidden":!0,children:N.icon}),n.jsx("span",{className:"min-w-0 truncate",children:N.label})]},N.key))}),document.body),h&&e.sessionId&&e.daemonId&&n.jsx(qA,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e,onClose:()=>p(!1)})]})}function og(e){const{t}=he("common");if(!e.role)return null;const s=i1(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 Kd(e){var o;const{t}=he("common"),s=Rb(e),r=((o=og(s))==null?void 0:o.full)??null;return qs(e)?t("dashboard.assistant.label"):r}function ws({conversation:e,className:t,size:s=12}){const{t:r}=he("common"),o=Rb(e),a=og(o);if(qs(e)){const i=r("dashboard.assistant.label");return n.jsx("span",{role:"img","aria-label":i,title:i,"data-assistant-role":"assistant",className:ct("mesh-role-icon","is-assistant",t),children:n.jsx(pl,{size:s})})}return!Ib(e)||!a?null:n.jsx("span",{role:"img","aria-label":a.full,title:a.full,"data-mesh-role":o.role,className:ct("mesh-role-icon",`is-${o.role}`,t),children:n.jsx(On,{size:s})})}function Hl(){return hr(()=>import("./DashboardMeshGraphDialog-BoHsr8ue.js"),__vite__mapDeps([3,1,4,5]))}const JA=c.lazy(Hl);function XA({onClose:e}){const{t}=he(),s=t("connection.loadingShort");return n.jsx(Sr,{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(tn,{label:s})})})}function qd(e){return n.jsx(c.Suspense,{fallback:n.jsx(XA,{onClose:e.onClose}),children:n.jsx(JA,{...e})})}function ag({conversation:e,onOpenMeshGraph:t,showLabel:s=!1,iconSize:r=14,className:o}){const{t:a}=he("common"),i=Kd(e);if(!t||!Mb(e))return null;const l=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:()=>{Hl()},onFocus:()=>{Hl()},className:ct("btn btn-secondary btn-sm dashboard-header-mesh-button inline-flex items-center gap-1.5",o),title:l,"aria-label":l,children:[n.jsx(On,{size:r}),s&&n.jsx("span",{className:"hidden lg:inline",children:a("dashboard.header.meshGraph")})]})}function ZA({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(l=>l==="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 Vm({value:e}){return e?n.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Gm({notification:e,shortcutIndex:t,onOpen:s,onMarkRead:r,onMarkUnread:o,onDelete:a}){const{t:i}=he(),l=wi(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"),l].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 eT({activeConv:e,wsStatus:t,isConnected:s,conversations:r,onOpenHistory:o,onOpenRemote:a,onStopCli:i,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:u,hiddenConversations:m=[],onShowConversation:h,onShowAllHidden:p,onResetPanelsToMain:b,inboxOpen:f,onInboxOpenChange:x,hiddenOpen:g,onHiddenOpenChange:w,onOpenNewSession:S,onStartAssistant:C,startAssistantPending:j=!1,startAssistantError:v=null,onStartAssistantWith:y,startAssistantMachines:N,startAssistantDefault:k=null,onOpenDashboardGuide:A,guideNudgeVisible:E=!1,actionShortcuts:P,notifications:T,notificationUnreadCount:M,onOpenNotification:_,onMarkNotificationRead:I,onMarkNotificationUnread:D,onDeleteNotification:L,onOpenGitDialog:$,onOpenMeshGraph:U}){const{t:J}=he(),{ides:K,p2pStates:R={},usesP2P:O=!0}=yn(),H=!!e&&ft(e),B=l||(e?Zf(e)?"terminal":"chat":null),[q,W]=c.useState(!1),[ce,ye]=c.useState(!1),G=c.useRef(null),Se=c.useRef(null),ue=c.useRef(null),ne=K.filter(ke=>ke.type==="adhdev-daemon"),ae=ZA({wsStatus:t,isConnected:s,daemonCount:ne.length,p2pStates:R,usesP2P:O}),ee=J(ae.titleKey),oe=ae.subtitleKey?J(ae.subtitleKey,ae.subtitleParams):null,Ce=ae.tone==="connected"?"#22c55e":ae.tone==="limited"?"#eab308":"#ef4444",Q=ae.tone==="connected"?"0 0 4px #22c55e80":ae.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",z=c.useMemo(()=>T.filter(ke=>!ke.readAt),[T]),X=c.useMemo(()=>T.filter(ke=>!!ke.readAt),[T]),pe=c.useMemo(()=>z.slice(0,9),[z]),Pe=M;c.useEffect(()=>{if(!f)return;const ke=Y=>{var ve;(ve=Se.current)!=null&&ve.contains(Y.target)||x(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[f,x]),c.useEffect(()=>{if(!g)return;const ke=Y=>{var ve;(ve=ue.current)!=null&&ve.contains(Y.target)||w(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[g,w]),c.useEffect(()=>{if(!g&&!f)return;const ke=Y=>{if(!Y.altKey)return;const ve=Y.code.match(/^Digit([1-9])$/);if(!ve)return;const Z=Number(ve[1])-1,ie=g?m[Z]:void 0,F=f?pe[Z]:void 0;if(!(!ie&&!F)){if(Y.preventDefault(),Y.stopPropagation(),ie){h==null||h(ie),w(!1);return}F&&(_(F),x(!1))}};return window.addEventListener("keydown",ke,!0),()=>window.removeEventListener("keydown",ke,!0)},[m,g,f,pe,w,x,_,h]),c.useEffect(()=>{const ke=m.length;if(G.current===null){G.current=ke;return}ke>G.current&&ye(!0),G.current=ke},[m.length]);const Oe=()=>ye(!1),Le=ke=>{if(!ke)return;const Y=r.find(ve=>ve.tabKey===ke);Y&&(u==null||u(Y))};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(Cn,{size:18}),n.jsx("span",{className:"header-title-desktop",children:J("dashboard.header.title")}),e&&n.jsx(ws,{conversation:e,size:14,className:"header-title-mobile-role"}),n.jsx("span",{className:"header-title-mobile",children:e?kt(e):J("dashboard.header.title")}),n.jsx(Qt,{content:oe?`${ee} · ${oe}`:ee,className:"ml-0.5",children:n.jsx("span",{role:"img","aria-label":ee,"data-connection-tone":ae.tone,className:"header-title-status-dot",style:{background:Ce,boxShadow:Q}})})]}),n.jsxs("div",{className:"header-subtitle flex items-center",children:[S&&n.jsx("button",{type:"button",onClick:S,className:"btn btn-secondary btn-sm ml-2",title:`${J("paneGroup.newSession")}${P!=null&&P.openNewSession?` (${P.openNewSession})`:""}`,"aria-label":J("paneGroup.newSession"),children:n.jsx(go,{size:14})}),C&&n.jsx(Y1,{onStart:C,onStartWith:y,machines:N,defaultTarget:k,pending:j,error:v})]})]})})}),n.jsxs("div",{className:"flex gap-2 items-center",children:[A&&n.jsxs("button",{type:"button",onClick:A,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:J("dashboard.header.guide"),"aria-label":J("dashboard.header.guideOpen"),children:[n.jsx("span",{className:"font-semibold leading-none",children:"?"}),E&&n.jsx("span",{children:J("dashboard.header.guideShort")})]}),e&&n.jsxs("div",{className:"dashboard-header-actions-group","data-testid":"dashboard-pane-toolbar",children:[n.jsx(Od,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),H&&d&&B&&n.jsx(qb,{mode:B,onChange:d,compact:!0}),H&&i&&n.jsx("button",{type:"button",onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:J("dashboard.header.stopCliProcess"),"aria-label":J("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(Et,{size:14})}),n.jsx(ag,{conversation:e,onOpenMeshGraph:U,showLabel:!0}),n.jsx(rg,{conversation:e,onOpenHistory:o,onOpenRemote:a?()=>a():void 0,onOpenGit:$,iconSize:14})]}),n.jsxs("div",{className:"dashboard-header-inbox",ref:Se,children:[n.jsxs("div",{className:`dashboard-header-hidden${q?" is-drop-target":""}${ce?" hidden-spawn-flash":""}${(m??[]).some(Us)?" hidden-generating-spin":""}`,onAnimationEnd:Oe,ref:ue,onDragEnter:ke=>{ke.dataTransfer.types.includes("text/tab-key")&&(ke.preventDefault(),W(!0))},onDragOver:ke=>{ke.dataTransfer.types.includes("text/tab-key")&&(ke.preventDefault(),ke.dataTransfer.dropEffect="move",W(!0))},onDragLeave:ke=>{ke.currentTarget.contains(ke.relatedTarget)||W(!1)},onDrop:ke=>{const Y=ke.dataTransfer.getData("text/tab-key");ke.preventDefault(),W(!1),Le(Y)},children:[n.jsxs("button",{type:"button",onClick:()=>w(!g),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${J("dashboard.hidden.title")}${P!=null&&P.toggleHiddenTabs?` (${P.toggleHiddenTabs})`:""}. ${J("dashboard.hidden.dragHint")}`,children:[n.jsx(gi,{size:16}),m.length>0&&n.jsx("span",{className:`dashboard-header-hidden-badge${ce?" hidden-badge-pop":""}`,children:m.length})]}),g&&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:J("dashboard.hidden.title")}),n.jsx(Vm,{value:P==null?void 0:P.toggleHiddenTabs})]}),n.jsxs("div",{className:"dashboard-header-hidden-actions",children:[b&&n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:b,children:J("dashboard.hidden.resetPanels")}),m.length>0&&p&&n.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{p(),w(!1)},children:J("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:J("dashboard.hidden.hideCurrentTab")}),n.jsx(Vm,{value:P==null?void 0:P.hideCurrentTab})]}),n.jsx("span",{className:"dashboard-header-hidden-current-title",children:kt(e)})]}),m.length>0?n.jsx("div",{className:"dashboard-header-hidden-list",children:m.map(ke=>n.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(ke),w(!1)},children:[n.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[Us(ke)&&n.jsx(tn,{size:12,thickness:2,color:"success",label:J("dashboard.header.generating")}),n.jsx(ws,{conversation:ke,size:12}),kt(ke)]}),n.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[m.indexOf(ke)<9?n.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",m.indexOf(ke)+1]}):null,Po(ke)]})]},ke.tabKey))}):n.jsx("div",{className:"dashboard-header-inbox-empty",children:J("dashboard.hidden.empty")})]})]}),n.jsxs("button",{type:"button",onClick:()=>x(!f),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:J("dashboard.header.activityInbox"),children:[n.jsx(Jn,{size:16}),Pe>0&&n.jsx("span",{className:"dashboard-header-inbox-badge",children:Pe})]}),f&&n.jsxs("div",{className:"dashboard-header-inbox-popover",children:[z.length>0&&n.jsxs("div",{className:"dashboard-header-inbox-section",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title",children:J("dashboard.inbox.unread")}),z.map(ke=>n.jsx(Gm,{notification:ke,shortcutIndex:pe.indexOf(ke)>=0?pe.indexOf(ke)+1:void 0,onOpen:()=>_(ke),onMarkRead:()=>I(ke.id),onMarkUnread:()=>D(ke.id),onDelete:()=>L(ke.id)},ke.id))]}),X.length>0&&n.jsxs("div",{className:"dashboard-header-inbox-section",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title",children:J("dashboard.inbox.read")}),X.map(ke=>n.jsx(Gm,{notification:ke,onOpen:()=>_(ke),onMarkRead:()=>I(ke.id),onMarkUnread:()=>D(ke.id),onDelete:()=>L(ke.id)},ke.id))]}),T.length===0&&n.jsx("div",{className:"dashboard-header-inbox-empty",children:J("dashboard.inbox.empty")})]})]})]})]})}function un(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function tT(e,t){return String(e||"")!==String(t||"")}function nT(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(`
57
- `).includes(s)||r&&!String(i.workspace||"").toLowerCase().includes(r)||o&&!Lf(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
58
- `).includes(o)))}function sT(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 zd(e,t={}){return sT(nT(e,t),t.sortMode||"recent")}function Bl(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function ig(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function rT(e){return e?e("launch.startFresh"):"Start fresh"}function oT(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function aT(e){return e?e("launch.openSavedHistory"):"Open saved history"}function Wl(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function Vd(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function cg(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function iT(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function cT(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function Xa(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 Za(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 ei(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function ti(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function lg(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function dg(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function Ym(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 lT({activeConv:e,ides:t,isCreatingChat:s,isRefreshingHistory:r,savedSessions:o=[],isSavedSessionsLoading:a=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:u,onClose:m,onNewChat:h,onSwitchSession:p,onRefreshHistory:b,onResumeSavedSession:f}){var M;const{t:x}=he("common"),g=t.find(_=>_.id===e.routeId),w=(g==null?void 0:g.chats)||[],S=(M=g==null?void 0:g.activeChat)==null?void 0:M.id,C=ft(e),[j,v]=c.useState(()=>un()),[y,N]=c.useState(null),k=l||j,A=String(d||"").trim(),E=_=>{if(u){u(_);return}v(_)},P=c.useMemo(()=>o.map(_=>{const I=String(_.workspace||"").trim();return _.canResume||I||!A?_:{..._,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,o]),T=c.useMemo(()=>zd(P,{textQuery:k.textQuery,workspaceQuery:k.workspaceQuery,modelQuery:k.modelQuery,resumableOnly:k.resumableOnly,sortMode:k.sortMode}),[P,k.modelQuery,k.resumableOnly,k.sortMode,k.textQuery,k.workspaceQuery]);return n.jsxs(n.Fragment,{children:[n.jsxs(Sr,{chrome:!1,onClose:m,closeOnEsc:!y,ariaLabel:C?Wl(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:C?Wl(x):x("historyModal.chatHistory")}),n.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:d1(e)}),C&&n.jsx("div",{className:"text-2xs text-text-muted mt-1",children:Vd(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(Et,{size:16})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!C&&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")}),C?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:k.textQuery,onChange:_=>E({...k,textQuery:_.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:k.workspaceQuery,onChange:_=>E({...k,workspaceQuery:_.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:k.modelQuery,onChange:_=>E({...k,modelQuery:_.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:k.sortMode,onChange:_=>E({...k,sortMode:_.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:k.resumableOnly,onChange:_=>E({...k,resumableOnly:_.target.checked})}),x("historyModal.resumeReadyOnly")]})]}),T.map(_=>{const I=e.providerSessionId===_.providerSessionId,D=I||!_.canResume||!!i,L=_.workspaceFallbackSource==="selected-workspace";return n.jsxs("button",{type:"button",onClick:()=>{D||!f||N({kind:"saved",session:_})},disabled:D,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"} ${D?"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:_.title||x("historyModal.untitledSession")}),n.jsx("div",{className:"text-2xs text-text-muted font-mono truncate",children:_.providerSessionId})]}),n.jsx("div",{className:"text-2xs text-text-muted shrink-0",children:Ym(_.lastMessageAt)})]}),n.jsx("div",{className:"mt-2 text-xs text-text-muted line-clamp-2",children:_.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:[_.workspace||x("historyModal.workspaceUnknown"),L?x("historyModal.selectedWorkspaceSuffix"):"",wo(_.summaryMetadata)?` · ${wo(_.summaryMetadata)}`:"",_.messageCount>0?` · ${x("historyModal.msgCount",{count:_.messageCount})}`:""]}),n.jsx("div",{className:"shrink-0",children:I?x("historyModal.statusActive"):_.canResume?L?x("historyModal.statusResumeSelectedWorkspace"):i===_.providerSessionId?x("historyModal.statusResuming"):x("historyModal.statusResume"):x("historyModal.statusMissingWorkspace")})]})]},_.id)})]}):w.map(_=>n.jsxs("div",{onClick:()=>{_.id!==S&&N({kind:"chat",id:_.id,title:_.title||x("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${S===_.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 ${S===_.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:_.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:[_.id.substring(0,12),"..."]}),S===_.id&&n.jsx("span",{className:"text-3xs bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:x("historyModal.statusActive")})]})]},_.id)),(C&&!a&&T.length===0||!C&&w.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(Aw,{size:32})}),n.jsx("div",{className:"text-xxs",children:C?o.length>0?x("historyModal.noMatchingHistory"):cg(x):x("historyModal.noRecentChats")})]}),C&&a&&n.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:n.jsx("div",{className:"text-xxs",children:cT(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:b,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(Ar,{size:13})," ",C?iT(x):x("historyModal.refreshHistory")]})})})]}),y&&n.jsxs(Sr,{chrome:!1,onClose:()=>N(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:y.kind==="chat"?y.title:y.session.title||x("historyModal.untitledSession")})}),y.kind==="saved"&&n.jsxs("div",{className:"mt-2 text-2xs text-text-muted font-mono truncate",children:[y.session.workspace||x("historyModal.workspaceUnknown"),y.session.lastMessageAt?` · ${Ym(y.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 _=y;N(null),_.kind==="chat"?(p(e.routeId,_.id),m()):f&&f(_.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:x("historyModal.confirmSwitchAction")}),n.jsx("button",{onClick:()=>N(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:x("common.cancel")})]})]})]})}const Qm={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 dT({toast:e}){const{t}=he(),{setToasts:s}=yn(),[r,o]=c.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(l=>l.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 ug({toasts:e,onDismiss:t,onClickToast:s}){const{t:r}=he();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=Qm[o.type]||Qm.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(Et,{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(dT,{toast:o}),o.actions&&o.actions.length>0&&n.jsx("div",{className:"flex gap-2 mt-3",children:o.actions.map((i,l)=>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},l))})]})]},o.id)})})}const uT=e=>e.transport==="pty"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function mT(e){const t=e.workspace||"";if(!t)return"";const s=t.split(/[/\\]/).filter(Boolean);return s.length>0?s[s.length-1]:t}function hT(e,t){return mg(e)||t}function mg(e){var o,a,i;const t=(a=(o=e.summaryMetadata)==null?void 0:o.items)==null?void 0:a.find(l=>(l==null?void 0:l.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 pT(e){return mg(e)||void 0}function fT(e){return e.sessionId||e.instanceId||e.agentType}function hg(e=[]){const t={};for(const s of e)s.type==="adhdev-daemon"&&(t[s.id]=pn(s,{fallbackId:s.id}));return t}function pg(e,t={}){var r;const s=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:qj(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[s]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Gd(e,t={}){return bT(e,pg(e,t))}function bT(e,t={}){var p,b,f,x,g,w,S,C,j;const s=[],r=t.machineName,o=t.connectionState,a=mT(e),i=e.workspace||"",l=Of(e.type,{agentName:e.cliName}),d=ft(e)?l:$t(e.type),u=hT(e,d),m=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var y,N,k;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,activeChatId:(y=v.activeChat)==null?void 0:y.id,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||$t(v.providerType),model:pT(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((N=v.activeChat)==null?void 0:N.messages)||[],activeModal:((k=v.activeChat)==null?void 0:k.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,git:v.git,settings:v.settings,coordinator:v.coordinator,messageInput:v.messageInput}}):[],h=uT(e);if(h){const v=e.sessionId||e.instanceId,y=(p=e.settings)==null?void 0:p.meshCoordinatorFor,N=((b=e.settings)==null?void 0:b.meshNodeFor)||!((f=e.settings)!=null&&f.meshCoordinatorFor)&&((x=e.settings)==null?void 0:x.launchedByCoordinator),k=Wb(e),A=k?" (Assistant)":y?" (Coordinator)":N?" (Mesh Node)":"",E=l+A,P=(g=e.activeChat)==null?void 0:g.activeModal,T=P&&Array.isArray(P.buttons)&&P.buttons.length>0,M=Xj(e.activeChat,[{status:e.status,activeModal:(w=e.activeChat)==null?void 0:w.activeModal}],e.agents||[]),_=e.activeChat||{title:"",messages:[]};let I=_.title&&String(_.title).trim()?String(_.title).trim():"";const D=(S=e.activeChat)==null?void 0:S.id,L=e.chats;if(D&&Array.isArray(L)&&L.length>0){const B=L.find(q=>q.id===D||q.id&&String(q.id)===String(D));B!=null&&B.title&&String(B.title).trim()&&(I=String(B.title).trim())}const $=(ft(e),e.type),U=ft(e)&&sm(I,E,$)?"":I,J=_.messages||[],K=typeof D=="string"?D.trim():"",R=ft(e)&&K===String(e.type||"").trim(),O=K&&!R?K:e.providerSessionId,H=e.coordinator||(typeof((C=e.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);s.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:O,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ft(e)&&e.mode||"chat",agentName:E,agentType:$,status:M,title:U,messages:J,resume:e.resume,hostIdeType:ft(e)?void 0:e.type,workspaceName:a,workspacePath:i,git:e.git,displayPrimary:(k?O1:"")||a||U||(ft(e)?e.mode==="chat"?E:`Terminal${A}`:E),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:T?P.buttons:void 0,modalMessage:T?P.message:void 0,streamSource:"native",tabKey:pc(v,e.id),machineName:r,connectionState:o,settings:e.settings,coordinator:H,...k?{assistant:!0}:{},messageInput:e.messageInput})}if(h&&ft(e))return s;for(const v of m){const y=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,N=Zj(v),k=fT(v),A=`${e.id}:${k}`,E=v.title&&String(v.title).trim()||"",P=sm(E,v.agentName,v.agentType)?"":E,T=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||T.length>0||y||!!P||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const _=v.coordinator||(typeof((j=v.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&v.settings.meshCoordinatorFor?{meshId:v.settings.meshCoordinatorFor,role:"coordinator"}:void 0);s.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,historySessionId:v.activeChatId||v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:N,title:P,messages:T,hostIdeType:e.type,workspaceName:a,workspacePath:i,git:v.git||e.git,displayPrimary:a||P||v.agentName||d,displaySecondary:v.model&&v.model.trim()?v.model.trim():`${d} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,modalButtons:y?v.activeModal.buttons:void 0,modalMessage:y?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:pc(v.sessionId||v.instanceId,A),machineName:r,connectionState:o,settings:v.settings,coordinator:_,messageInput:v.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:l,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:pc(e.sessionId||e.instanceId,e.id),connectionState:o,settings:e.settings,messageInput:e.messageInput}),s}const Ul="https://adhf.dev",gT="https://dev.adhf.dev";function xT(e){return e==="adhf.dev"||e==="adhdev-web.pages.dev"||e==="localhost"||e==="127.0.0.1"?Ul:gT}function yT(){return typeof window>"u"?Ul:xT(window.location.hostname)}function vT(){const e=yT();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:"> "}}}const wT={"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"},"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"}},Jm=["#0EA5E9","#8B5CF6","#10B981","#F59E0B","#EF4444","#14B8A6","#6366F1","#EC4899","#84CC16","#F97316","#06B6D4","#A855F7"];function ST(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 kT(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 $i({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(Ow,{size:s,className:r});const i=wT[o],l=(i==null?void 0:i.monogram)??kT((t==null?void 0:t.trim())||o.replace(/-cli$/,"")),d=(i==null?void 0:i.hue)??Jm[ST(o||a)%Jm.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:l})}function Xm({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 jT({value:e,availableProviders:t,onChange:s,disabled:r=!1,saveButton:o}){const{t:a}=he("common"),[i,l]=c.useState(""),d=c.useMemo(()=>new Map(t.map(b=>[b.type,b])),[t]),u=c.useMemo(()=>Eo(e),[e]),m=u.filter(b=>!d.has(b)).length,h=t.filter(b=>!u.includes(b.type)),p=()=>{i&&(s(L1(u,i)),l(""))};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((b,f)=>{const x=d.get(b),g=!!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 ${g?"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($i,{type:b,label:x==null?void 0:x.label,size:14}),n.jsx("span",{className:`font-mono text-xs ${g?"text-text-primary":"text-text-muted"}`,children:b}),g?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(Qt,{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(Lm(u,b,"up")),children:n.jsx(Xm,{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(Lm(u,b,"down")),children:n.jsx(Xm,{direction:"down"})}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>s(D1(u,b)),children:a("settings.providerPriority.remove")})]})]},b)})}),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:b=>l(b.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(b=>n.jsxs("option",{value:b.type,children:[b.label," (",b.type,")"]},b.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(nt,{content:[a("settings.providerPriority.orderHint"),m>0?a("settings.providerPriority.undetectedHint",{count:m}):""].filter(Boolean).join(`
59
-
60
- `)})})]})}function NT(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function fg(e,t){const s=NT(e);return{daemonId:s.daemonId,payload:{...t,...s.targetSessionId&&!t.targetSessionId?{targetSessionId:s.targetSessionId}:{}}}}const CT=[{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:"🏄"}],_T=[{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:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],AT=[{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 bg({icon:e,title:t,subtitle:s,subtitleInline:r=!1,badge:o,actions:a,className:i}){return n.jsxs("div",{className:ct("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(nt,{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 Lo({icon:e,title:t,subtitle:s,subtitleInline:r,badge:o,actions:a,widthClassName:i="max-w-6xl",contentClassName:l,children:d}){return n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsx(bg,{icon:e,title:t,subtitle:s,subtitleInline:r,badge:o,actions:a}),n.jsx("div",{className:"page-content",children:n.jsx("div",{className:ct("mx-auto flex w-full flex-col gap-4",i,l),children:d})})]})}const Kl="adhdev:themechange";function TT(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ur(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function mr(e){return e==="system"?TT():e}function gg(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Ca(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Kl,{detail:{preference:e,theme:t}}))}function IT(){const e=ur(),t=mr(e);gg(t),Ca(e,t)}function Fi(){const[e,t]=c.useState(ur),[s,r]=c.useState(()=>mr(ur()));c.useEffect(()=>{gg(s)},[s]),c.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const u=d.matches?"light":"dark";r(u),Ca("system",u)}};return i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[e]),c.useEffect(()=>{const i=d=>{const u=d.detail||{},m=u.preference,h=u.theme;t(m==="dark"||m==="light"||m==="system"?m:ur()),r(h==="dark"||h==="light"?h:mr(ur()))},l=d=>{if(d.key!=="theme")return;const u=ur(),m=mr(u);t(u),r(m)};return window.addEventListener(Kl,i),window.addEventListener("storage",l),()=>{window.removeEventListener(Kl,i),window.removeEventListener("storage",l)}},[]);const o=c.useCallback(i=>{const l=mr(i);t(i),r(l);try{localStorage.setItem("theme",i)}catch{}Ca(i,l)},[]),a=c.useCallback(()=>{t(i=>{const l=i==="dark"?"light":i==="light"?"system":"dark",d=mr(l);r(d);try{localStorage.setItem("theme",l)}catch{}return Ca(l,d),l})},[]);return{theme:s,preference:e,setPreference:o,cycleTheme:a,isDark:s==="dark"}}const Zm={dark:"Dark",light:"Light",system:"System"};function MT({collapsed:e}){const{preference:t,cycleTheme:s}=Fi(),r=t==="dark"?n.jsx(zp,{size:16}):t==="light"?n.jsx(qp,{size:16}):n.jsx(Vp,{size:16});return n.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:s,title:`Theme: ${Zm[t]} (click to cycle)`,children:[n.jsx("span",{className:"nav-icon",children:r}),!e&&n.jsx("span",{className:"text-xs",children:Zm[t]})]})}const ql="adhdev:langchange";function RT(){const e=Ye.language;return Es(e)?e:Af()}function PT(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ql,{detail:{language:e}}))}function ET(){const[e,t]=c.useState(RT);c.useEffect(()=>{const r=i=>{Es(i)&&t(i)},o=i=>{const l=i.detail||{};Es(l.language)&&t(l.language)},a=i=>{if(i.key!==Nl)return;const l=i.newValue;Es(l)&&l!==Ye.language&&(Ye.changeLanguage(l),Cl(l))};return Ye.on("languageChanged",r),window.addEventListener(ql,o),window.addEventListener("storage",a),()=>{Ye.off("languageChanged",r),window.removeEventListener(ql,o),window.removeEventListener("storage",a)}},[]);const s=c.useCallback(r=>{if(Es(r)){t(r);try{localStorage.setItem(Nl,r)}catch{}Ye.changeLanguage(r),Cl(r),PT(r)}},[]);return{language:e,setLanguage:s}}function LT({trigger:e,viewport:t,menu:s,variant:r,gap:o=6,margin:a=8}){const i=e.top-a,l=t.height-e.bottom-a,d=r==="sidebar";let u=d;d&&i<s.height&&l>i&&(u=!1),!d&&l<s.height&&i>l&&(u=!0);const m=u?i:l,h=Math.max(80,Math.min(s.height,m));let p;u?p=e.top-o-h:p=e.bottom+o,p=eh(p,a,Math.max(a,t.height-h-a));const b=eh(e.left,a,Math.max(a,t.width-s.width-a));return{top:p,left:b,maxHeight:h}}function eh(e,t,s){return Math.min(Math.max(e,t),s)}function DT({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 OT({collapsed:e,variant:t="sidebar"}){const{language:s,setLanguage:r}=ET(),{t:o}=he("common"),[a,i]=c.useState(!1),[l,d]=c.useState(0),u=c.useRef(null),m=c.useRef(null),h=c.useRef(null),p=c.useId(),[b,f]=c.useState(null),x=c.useCallback(()=>{const T=m.current;if(!T)return;const M=T.getBoundingClientRect(),_=h.current,I=Math.max((_==null?void 0:_.offsetWidth)??0,168),D=(_==null?void 0:_.scrollHeight)??Ns.length*36+12;f(LT({trigger:{top:M.top,left:M.left,right:M.right,bottom:M.bottom,width:M.width,height:M.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:I,height:D},variant:t}))},[t]),g=Math.max(0,Ns.findIndex(T=>T.code===s)),w=Ns[g]??Ns[0],S=o("language.label",{defaultValue:"Language"}),C=o("language.select",{defaultValue:"Select language"}),j=T=>`${p}-opt-${T}`,v=c.useCallback(()=>{d(g),i(!0)},[g]),y=c.useCallback((T=!0)=>{var M;i(!1),T&&((M=m.current)==null||M.focus())},[]),N=c.useCallback(T=>{const M=Ns[T];M&&r(M.code),y()},[r,y]);c.useEffect(()=>{if(!a)return;const T=I=>{var D,L;return!!((D=u.current)!=null&&D.contains(I)||(L=h.current)!=null&&L.contains(I))},M=I=>{T(I.target)||i(!1)},_=I=>{T(I.target)||i(!1)};return document.addEventListener("pointerdown",M,!0),document.addEventListener("focusin",_,!0),()=>{document.removeEventListener("pointerdown",M,!0),document.removeEventListener("focusin",_,!0)}},[a]),c.useLayoutEffect(()=>{if(!a){f(null);return}x();const T=()=>x();return window.addEventListener("resize",T),window.addEventListener("scroll",T,!0),()=>{window.removeEventListener("resize",T),window.removeEventListener("scroll",T,!0)}},[a,x]),c.useEffect(()=>{var T;a&&b&&((T=h.current)==null||T.focus())},[a,b]);const k=T=>{const M=Ns.length-1;switch(T.key){case"ArrowDown":T.preventDefault(),d(_=>_>=M?0:_+1);break;case"ArrowUp":T.preventDefault(),d(_=>_<=0?M:_-1);break;case"Home":T.preventDefault(),d(0);break;case"End":T.preventDefault(),d(M);break;case"Enter":case" ":T.preventDefault(),N(l);break;case"Escape":T.preventDefault(),y();break;case"Tab":i(!1);break}},A=T=>{a||(T.key==="ArrowDown"||T.key==="ArrowUp"||T.key==="Enter"||T.key===" ")&&(T.preventDefault(),v())},E=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":""}`,P=t==="landing"||!e;return n.jsxs("div",{ref:u,className:"lang-switch",children:[n.jsxs("button",{ref:m,type:"button",className:E,"aria-haspopup":"listbox","aria-expanded":a,"aria-label":`${S}: ${w.label}`,title:`${S}: ${w.label}`,onClick:()=>a?y(!1):v(),onKeyDown:A,children:[n.jsx("span",{className:"nav-icon lang-switch-icon",children:n.jsx(Yp,{size:16})}),P&&n.jsx("span",{className:"lang-switch-label text-xs",children:w.label}),P&&n.jsx(DT,{open:a})]}),a&&typeof document<"u"&&An.createPortal(n.jsx("ul",{ref:h,role:"listbox",tabIndex:-1,"aria-label":C,"aria-activedescendant":j(l),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(b==null?void 0:b.top)??0,left:(b==null?void 0:b.left)??0,maxHeight:b==null?void 0:b.maxHeight,overflowY:"auto",visibility:b?"visible":"hidden"},onKeyDown:k,children:Ns.map((T,M)=>{const _=T.code===w.code,I=M===l;return n.jsxs("li",{id:j(M),role:"option","aria-selected":_,className:`lang-switch-option${I?" is-active":""}${_?" is-selected":""}`,onMouseEnter:()=>d(M),onClick:()=>N(M),children:[n.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:_?n.jsx(Cr,{size:14}):null}),n.jsx("span",{className:"lang-switch-option-label",children:T.label})]},T.code)})}),document.body)]})}const $T=[],FT=[];function Cc(e,t){return e?typeof e=="function"?e(t):e:null}const HT=c.memo(function({renderState:t,brand:s,navItems:r,sidebarSections:o,footerItems:a,footerInfo:i,footerActions:l,closeMobileMenu:d}){const{t:u}=he("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}`:""}`,b=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:Cc(s,t)}),n.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":u("app.closeMenu"),onClick:d,children:n.jsx(Et,{size:16})})]}),n.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),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(b)]},f.key)),n.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),Cc(i,t),n.jsx(MT,{collapsed:m}),n.jsx(OT,{collapsed:m}),Cc(l,t)]})]})});function BT({children:e,brand:t,navItems:s,sidebarSections:r=$T,footerItems:o=FT,footerInfo:a,footerActions:i,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const{t:u}=he("common"),[m,h]=c.useState(!1),[p,b]=c.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),f=c.useCallback(()=>h(!0),[]),x=c.useCallback(()=>h(!1),[]),g=c.useCallback(()=>{b(S=>{const C=!S;try{localStorage.setItem(d,C?"1":"0")}catch{}return C})},[d]),w=c.useMemo(()=>({collapsed:p,mobileMenuOpen:m,openMobileMenu:f,closeMobileMenu:x,toggleCollapsed:g}),[p,m,f,x,g]);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:S=>S.key==="Escape"&&x()}),n.jsx(HT,{renderState:w,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:[l,e]})})]})}function vt({title:e,icon:t,description:s,descriptionInline:r=!1,accentColor:o,className:a,collapsible:i,defaultOpen:l=!0,badge:d,action:u,children:m}){const[h,p]=c.useState(l),b=i?h:!0,f=()=>p(w=>!w),x=n.jsxs(n.Fragment,{children:[t&&n.jsx("span",{children:t}),n.jsx("span",{children:e})]}),g=(e||s||u)&&n.jsxs("div",{className:ct("flex items-start justify-between gap-3",b&&"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:w=>{w.stopPropagation(),f()},"aria-expanded":b,children:x}):x,s&&!r&&n.jsx("span",{onClick:w=>w.stopPropagation(),className:"inline-flex",children:n.jsx(nt,{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:w=>w.stopPropagation(),children:u}),i&&n.jsx("span",{className:ct("mt-0.5 shrink-0 text-text-muted transition-transform select-none",b?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return n.jsxs("div",{className:ct("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:[g,b&&m]})}function Hi({icon:e,title:t,description:s,action:r,className:o,variant:a="default"}){return a==="compact"?n.jsxs("div",{className:ct("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(nt,{content:s}):null,r]}):n.jsxs("div",{className:ct("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 WT={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"},UT={error:en,warning:en,success:yi,info:Co};function Ht({variant:e,children:t,onDismiss:s,className:r}){return n.jsxs("div",{className:ct("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-xxs",WT[e],r),children:[n.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const o=UT[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 Ft({label:e,hint:t,hintInline:s=!1,children:r,className:o}){return n.jsxs("div",{className:ct("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(nt,{content:t})]}),r,t&&s&&n.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function Nn(e){const{className:t,...s}=e;return n.jsx("input",{...s,className:ct("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 KT={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Qn=c.forwardRef(function({variant:t="secondary",size:s="md",type:r,className:o,...a},i){return n.jsx("button",{ref:i,type:r??"button",className:ct("btn",KT[t],s==="sm"&&"btn-sm",o),...a})}),qT=c.forwardRef(function({options:t,children:s,className:r,...o},a){return n.jsx("select",{ref:a,className:ct("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 Yd({tabs:e,activeKey:t,onSelect:s,variant:r="pill",ariaLabel:o,className:a,tabIdPrefix:i,panelIdPrefix:l}){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(g=>g.key===t)),p=m.key==="Home"?0:m.key==="End"?e.length-1:(h+(m.key==="ArrowRight"?1:-1)+e.length)%e.length,b=e[p];if(!b)return;m.preventDefault(),s(b.key),(x=m.currentTarget.querySelectorAll('[role="tab"]')[p])==null||x.focus()};return n.jsx("div",{className:ct(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":l?`${l}-${m.key}`:void 0,tabIndex:h?0:-1,className:ct(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 xg({tabs:e,defaultTabKey:t,activeKey:s,onTabChange:r,variant:o="pill",ariaLabel:a,className:i,tabListClassName:l,panelClassName:d,tabIdPrefix:u,unmountInactivePanels:m=!1}){var g;const[h,p]=c.useState(t??((g=e[0])==null?void 0:g.key)),b=s!==void 0,f=b?s:h,x=w=>{b||p(w),r==null||r(w)};return n.jsxs("div",{className:i,children:[n.jsx(Yd,{tabs:e,activeKey:f,onSelect:x,variant:o,ariaLabel:a,className:l,tabIdPrefix:u}),e.map(w=>{const S=w.key===f;return m&&!S?null:n.jsx("div",{role:"tabpanel","aria-labelledby":u?`${u}-${w.key}`:void 0,className:S?ct("flex flex-col gap-4",d):"hidden",children:w.content},w.key)})]})}class zT extends c.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(en,{size:44,className:"text-status-warning"})}),n.jsx("h2",{style:{margin:"0 0 8px",fontSize:18,fontWeight:600,color:"var(--text-primary, #eee)"},children:Ye.t("app.errorBoundary.title")}),n.jsx("p",{style:{margin:"0 0 20px",fontSize:14,opacity:.7,lineHeight:1.5},children:Ye.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:Ye.t("app.errorBoundary.reload")})]})}):this.props.children}}const VT={sm:"w-[34px] h-[19px]",md:"w-[40px] h-[22px]"},th={sm:{base:"w-[16px] h-[16px]",on:"translate-x-[15px]"},md:{base:"w-[19px] h-[19px]",on:"translate-x-[18px]"}};function Pr({checked:e,onChange:t,disabled:s=!1,busy:r=!1,size:o="md",id:a,title:i,className:l,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:ct("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",l)},b=n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,className:ct("inline-block rounded-full transition-colors duration-200 ease-in-out",VT[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:ct("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",th[o].base,e?th[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:b}):n.jsx("button",{type:"button",...p,disabled:s,onClick:h,children:b})}function Bi({onClick:e,refreshing:t=!1,disabled:s=!1,label:r,size:o=14,showLabel:a=!1,className:i}){const{t:l}=he("common"),d=r??l("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:ct("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(Ar,{size:o,className:t?"animate-spin":void 0}),a&&n.jsx("span",{children:d})]})}const XO={recentFailures:0};function ZO(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 GT={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 YT(e,t){const s=GT[(e||"unknown").toLowerCase()];return s?t(s):String(e)}function e3(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 yg(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return{bucket:"other",normalized:""};const r=pi(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 t3(e){const{bucket:t,normalized:s}=yg(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 n3(e,t){const{bucket:s,normalized:r}=yg(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 s3(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 QT(e){return e.startedAt||e.createdAt||null}function r3(e){const t=QT(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 o3(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),l=(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})),l.length>0&&a.push(s("mesh.drift.submoduleOutOfSync",`${l.length} submodule drift`,{count:l.length})),r.hasConflicts&&a.push(s("mesh.drift.conflicts","conflicts")),a.join(" · ")||s("mesh.drift.clean","Clean")}function JT(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)=>kr(o.provider).localeCompare(kr(a.provider)))}function vg(e){return wy(e.daemonId)||e.machineId||e.nodeId}function a3(e){var s;const t=new Map;for(const r of e.nodes){const o=r.nodeFacts,a=vg(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 l=typeof(o==null?void 0:o.reportedAt)=="number"&&Number.isFinite(o.reportedAt)?o.reportedAt:void 0,d=l!==void 0&&(i.reportedAt===void 0||l>i.reportedAt);d&&(i.reportedAt=l),o&&(i.hasReported=!0);const u=JT(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=ZT(e,r.machineKey);return[...t.values()].sort((r,o)=>r.label.localeCompare(o.label)||r.machineKey.localeCompare(o.machineKey))}function XT(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 i3(e){const t=XT(e),s=typeof e.machineLabel=="string"?e.machineLabel.trim():"";return!s||s===t?t:`${t} · ${s}`}function ZT(e,t){var i,l,d;const s=[],r=[],o=[];for(const u of e.nodes){if(vg(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,b=(p!=null&&p.sameMachine?p.coordinatorHostname:void 0)??((d=(l=p==null?void 0:p.identityEvidence)==null?void 0:l.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 b=="string"&&b.trim()&&r.push(b.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)??wg(t)}function wg(e){const t=e.replace(/^(daemon_|standalone_)/,"");return t.length<=20?t:`${t.slice(0,17)}…`}const c3={first_eligible:"In order",fitness:"Smart",least_loaded:"Smart",round_robin:"Smart (round-robin)",priority_only:"Smart (priority)"};function l3(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 d3(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 u3(e){return e.assignedNodeId||e.targetNodeId||null}function nh(e){return e?e.slice(0,7):null}function e2(e,t){var a,i,l;const s=nh((a=e==null?void 0:e.git)==null?void 0:a.headCommit),r=((l=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:l.trim())||"";if(s||r)return[s,r].filter(Boolean).join(" · ");const o=t[0];return o?[nh(o.commit),o.message].filter(Boolean).join(" · "):null}function m3(e,t){const s=e2(e,t);return s||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function h3(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 p3(e){var o,a,i,l,d,u,m;const t=((o=e.selectedSessionEntry)==null?void 0:o.session.workspace)||((a=e.selectedSessionEntry)==null?void 0:a.workspace)||((l=(i=e.selectedNodeStatus)==null?void 0:i.git)==null?void 0:l.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 f3(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 b3(e,t){return t?e.nodes.find(s=>s.id===t)??null:null}function g3(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,l,d,u,m,h,p,b,f,x,g,w,S,C,j,v,y,N,k,A,E,P;return[a.nodeId,a.daemonId??"",a.machineId??"",a.machineLabel,a.machineStatus??"",((i=a.connection)==null?void 0:i.state)??"",((l=a.connection)==null?void 0:l.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)??"",((b=a.git)==null?void 0:b.behind)??"",((f=a.git)==null?void 0:f.headCommit)??"",((x=a.git)==null?void 0:x.staged)??"",((g=a.git)==null?void 0:g.modified)??"",((w=a.git)==null?void 0:w.untracked)??"",((S=a.git)==null?void 0:S.deleted)??"",((C=a.git)==null?void 0:C.renamed)??"",(j=a.git)!=null&&j.hasConflicts?1:0,((v=a.git)==null?void 0:v.lastCheckedAt)??"",((y=a.activeSessions)==null?void 0:y.join(","))??"",((N=a.activeSessionDetails)==null?void 0:N.length)??"",((k=a.activeSessionDetails)==null?void 0:k.map(T=>[T.sessionId,T.providerType??"",T.state??"",T.chatStatus??"",T.lifecycle??"",T.role??"",T.isSelfCoordinator?1:0,T.statusNote??"",T.startedAt??"",T.createdAt??""].join("/")).join(","))??"",((A=a.providers)==null?void 0:A.join(","))??"",((E=a.providerPriority)==null?void 0:E.join(","))??"",a.error??"",(((P=a.git)==null?void 0:P.submodules)??[]).map(T=>[T.path,T.commit,T.dirty?1:0,T.outOfSync?1:0,T.error??""].join("/")).join(",")].join("|")})].join("::")}function x3(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function Vn({label:e,description:t,descriptionInline:s=!1,checked:r,disabled:o,onChange:a,extra:i}){const l=c.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:l,children:e}),t&&!s&&n.jsx(nt,{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(Pr,{checked:r,disabled:o,onChange:a,"aria-labelledby":l})]})]})}const t2=["default","claude-cli","codex-cli","antigravity-cli"];function n2({daemonId:e,knownCliTypes:t=t2,embedded:s=!1}){const{t:r}=he("common"),{sendCommand:o}=wt(),[a,i]=c.useState({}),[l,d]=c.useState({}),[u,m]=c.useState(!0),[h,p]=c.useState(null),[b,f]=c.useState(null),[x,g]=c.useState(""),[w,S]=c.useState(!1),C=s||w,[j,v]=c.useState(null),y=c.useCallback(async()=>{if(e){m(!0),f(null);try{const _=await o(e,"list_coordinator_prompts",{}),I=_!=null&&_.result&&typeof _.result=="object"?_.result:_;if(!(I!=null&&I.success)){f((I==null?void 0:I.error)||r("settings.coordinatorPrompts.loadFailed"));return}const D=I.entries||{};g(I.dir||"");const L={};for(const $ of t)L[$]=D[$]||{override:"",append:""};for(const $ of Object.keys(D))L[$]||(L[$]=D[$]);i(L),d(JSON.parse(JSON.stringify(L)))}catch(_){f((_==null?void 0:_.message)||String(_))}finally{m(!1)}}},[o,e,t,r]);c.useEffect(()=>{y()},[y]);const N=c.useCallback(async(_,I)=>{var D;if(e){p(`${_}:${I}`),f(null);try{const L=((D=a[_])==null?void 0:D[I])||"",$=await o(e,"write_coordinator_prompt",{key:_,kind:I,content:L}),U=$!=null&&$.result&&typeof $.result=="object"?$.result:$;if(!(U!=null&&U.success)){f((U==null?void 0:U.error)||r("settings.coordinatorPrompts.saveFailed"));return}d(J=>({...J,[_]:{...J[_]||{override:"",append:""},[I]:L}}))}catch(L){f((L==null?void 0:L.message)||String(L))}finally{p(null)}}},[o,e,a,r]),k=c.useMemo(()=>(_,I)=>{var D,L;return(((D=a[_])==null?void 0:D[I])||"")!==(((L=l[_])==null?void 0:L[I])||"")},[a,l]),A=c.useCallback(async _=>{k(_,"override")&&await N(_,"override"),k(_,"append")&&await N(_,"append")},[k,N]),E=c.useCallback(_=>{const I=l[_];return!!(I&&((I.override||"").trim()||(I.append||"").trim()))},[l]),P=Object.keys(a),T=P.filter(E),M=j&&a[j]?j:P[0];return e?C?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(nt,{content:n.jsxs("span",{children:[r("settings.coordinatorPrompts.intro")," ",x||"~/.adhdev/coordinator-prompts/",`
61
-
62
- `,n.jsx(La,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:n.jsx("strong",{})}})," ",n.jsx(La,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:n.jsx("strong",{})}}),`
63
-
64
- `,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:()=>S(!1),children:r("settings.coordinatorPrompts.collapseLabel")})]}),b&&n.jsx("div",{className:"text-xs text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:b}),u&&n.jsx("div",{className:"text-xs text-text-muted",children:r("settings.coordinatorPrompts.loading")}),P.length>0&&n.jsx(xg,{activeKey:M,onTabChange:v,ariaLabel:r("settings.coordinatorPrompts.tabsAriaLabel"),tabIdPrefix:"coordinator-prompt-tab",tabs:P.map(_=>{const I=a[_],D=k(_,"override")||k(_,"append");return{key:_,label:n.jsxs("span",{className:"flex items-center gap-1.5 font-mono text-xs",children:[_,E(_)&&n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-accent-primary",title:r("settings.coordinatorPrompts.customizedBadge")}),D&&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:L=>i($=>({...$,[_]:{...$[_],override:L.target.value}})),placeholder:r("settings.coordinatorPrompts.overridePlaceholder"),disabled:h===`${_}: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:L=>i($=>({...$,[_]:{...$[_],append:L.target.value}})),placeholder:r("settings.coordinatorPrompts.appendPlaceholder"),disabled:h===`${_}: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(_),disabled:!!(h!=null&&h.startsWith(`${_}:`))||!D,children:h!=null&&h.startsWith(`${_}:`)?r("settings.coordinatorPrompts.saving"):r(D?"settings.coordinatorPrompts.save":"settings.coordinatorPrompts.saved")})})]})}})})]}):n.jsxs("div",{className:"flex flex-col gap-3",children:[b&&n.jsx("div",{className:"text-xs text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:b}),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")}):T.length===0?n.jsx("span",{children:r("settings.coordinatorPrompts.collapsedNone")}):n.jsxs(n.Fragment,{children:[n.jsxs("span",{children:[r("settings.coordinatorPrompts.customizedBadge"),":"]}),T.map(_=>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.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>S(!0),children:r("settings.coordinatorPrompts.expandLabel")})]})]}):n.jsx("div",{className:"text-xs text-text-muted",children:r("settings.coordinatorPrompts.connectDaemon")})}const s2=[{id:"dark",labelKey:"settings.appearance.modeDark",icon:zp},{id:"light",labelKey:"settings.appearance.modeLight",icon:qp},{id:"system",labelKey:"settings.appearance.modeSystem",icon:Vp}];function r2(){const{preference:e,setPreference:t}=Fi(),{t:s}=he("common");return n.jsx("div",{className:"flex gap-2",children:s2.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 o2(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 a2(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function _c(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function sh(e){const{r:t,g:s,b:r}=a2(e);return .2126*_c(t)+.7152*_c(s)+.0722*_c(r)}function rh(e,t){const s=sh(e),r=sh(t),o=Math.max(s,r),a=Math.min(s,r);return(o+.05)/(a+.05)}function Sg(e){const t=o2(e);if(!t)return"#111827";const s="#111827",r="#ffffff";return rh(t,s)>=rh(t,r)?s:r}const zl={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},Vl={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},i2=[{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"}}}],kg="adhdev-chat-theme",jg="adhdev-chat-theme-custom";function _a(){if(typeof window>"u")return"ember";try{return localStorage.getItem(kg)||"ember"}catch{return"ember"}}function jn(e){try{const t=localStorage.getItem(jg);if(t){const s=JSON.parse(t);return{...e==="dark"?zl:Vl,...s[e]}}}catch{}return e==="dark"?zl:Vl}function na(e,t){try{localStorage.setItem(jg,JSON.stringify({dark:e,light:t}))}catch{}}function bn(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 ni(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 c2={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function mo(e,t){var o;const s=(o=c2[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",ni(s,24)),r.style.setProperty("--accent-on-primary",Sg(s)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${s}, ${ni(s,18)})`),r.style.setProperty("--border-accent",bn(s,.35)),r.style.setProperty("--nav-active-bg",bn(s,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${s}, 0 0 12px ${bn(s,.06)}`)}function $s(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",bn(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",bn(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",bn(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",bn(e.borderSubtle,.5)),t.style.setProperty("--border-default",bn(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",ni(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Sg(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${ni(e.accentColor,40)})`),t.style.setProperty("--border-accent",bn(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",bn(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${bn(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 ${bn(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 Qd(){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 l2(e){try{localStorage.setItem(kg,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Fs()?"dark":"light";$s(jn(t))}else Qd(),mo(e,Fs()?"dark":"light")}function d2(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=_a();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Fs()?"dark":"light";$s(jn(t))}else Qd(),mo(e,Fs()?"dark":"light")}function Fs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Gt({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 Gr({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 u2({dark:e,onColorsChange:t}){const{t:s}=he("common"),r=e?"dark":"light",[o,a]=c.useState(()=>jn(r));c.useEffect(()=>{a(jn(r))},[r]);const i=c.useCallback((l,d)=>{a(u=>{const m={...u,[l]:d},p=jn(r==="dark"?"light":"dark");return r==="dark"?na(m,p):na(p,m),$s(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(Gr,{title:s("settings.theme.sectionAppBackground"),children:[n.jsx(Gt,{label:s("settings.theme.colorBackground"),value:o.bgPrimary,onChange:l=>i("bgPrimary",l)}),n.jsx(Gt,{label:s("settings.theme.colorSurface"),value:o.bgSecondary,onChange:l=>i("bgSecondary",l)}),n.jsx(Gt,{label:s("settings.theme.colorCard"),value:o.surfacePrimary,onChange:l=>i("surfacePrimary",l)})]}),n.jsxs(Gr,{title:s("settings.theme.sectionAppText"),children:[n.jsx(Gt,{label:s("settings.theme.colorPrimary"),value:o.textPrimary,onChange:l=>i("textPrimary",l)}),n.jsx(Gt,{label:s("settings.theme.colorSecondary"),value:o.textSecondary,onChange:l=>i("textSecondary",l)}),n.jsx(Gt,{label:s("settings.theme.colorMuted"),value:o.textMuted,onChange:l=>i("textMuted",l)})]}),n.jsxs(Gr,{title:s("settings.theme.sectionBordersAccent"),children:[n.jsx(Gt,{label:s("settings.theme.colorBorderSubtle"),value:o.borderSubtle,onChange:l=>i("borderSubtle",l)}),n.jsx(Gt,{label:s("settings.theme.colorBorderDefault"),value:o.borderDefault,onChange:l=>i("borderDefault",l)}),n.jsx(Gt,{label:s("settings.theme.colorAccent"),value:o.accentColor,onChange:l=>i("accentColor",l)})]})]}),n.jsxs("div",{children:[n.jsxs(Gr,{title:s("settings.theme.sectionChatBubbles"),children:[n.jsx(Gt,{label:s("settings.theme.colorUserBubble"),value:o.userBubble,onChange:l=>i("userBubble",l)}),n.jsx(Gt,{label:s("settings.theme.colorUserText"),value:o.userText,onChange:l=>i("userText",l)}),n.jsx(Gt,{label:s("settings.theme.colorAgentBubble"),value:o.assistantBubble,onChange:l=>i("assistantBubble",l)}),n.jsx(Gt,{label:s("settings.theme.colorAgentText"),value:o.assistantText,onChange:l=>i("assistantText",l)})]}),n.jsxs(Gr,{title:s("settings.theme.sectionChatLayout"),children:[n.jsx(Gt,{label:s("settings.theme.colorChatBg"),value:o.containerBg,onChange:l=>i("containerBg",l)}),n.jsx(Gt,{label:s("settings.theme.colorSendButton"),value:o.sendButton,onChange:l=>i("sendButton",l)}),n.jsx(Gt,{label:s("settings.theme.colorInputBorder"),value:o.inputBorder,onChange:l=>i("inputBorder",l)}),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:l=>i("bubbleRadius",Number(l.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 l=e?zl:Vl,u=jn(e?"light":"dark");e?na(l,u):na(u,l),a(l),$s(l),t(l)},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 m2(){const{t:e}=he("common"),[t,s]=c.useState(_a),[r,o]=c.useState(!0),[a,i]=c.useState(()=>jn("dark"));c.useEffect(()=>{o(Fs());const u=new MutationObserver(()=>{const p=Fs();o(p);const b=_a();b==="custom"?$s(jn(p?"dark":"light")):mo(b,p?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),h=()=>{const p=Fs();o(p);const b=_a();b==="custom"?$s(jn(p?"dark":"light")):mo(b,p?"dark":"light")};return m.addEventListener("change",h),()=>{u.disconnect(),m.removeEventListener("change",h)}},[]),c.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?$s(jn(r?"dark":"light")):(Qd(),mo(t,r?"dark":"light"))},[t,r]),c.useEffect(()=>{i(jn(r?"dark":"light"))},[r]);const l=u=>{s(u),l2(u)},d=[...i2,{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:()=>l(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(u2,{dark:r,onColorsChange:u=>i(u)})]})}const Jd="adhdev_mobileDashboardMode_v1",Gl="adhdev:mobile-dashboard-mode-change";function Xd(){try{return localStorage.getItem(Jd)==="workspace"?"workspace":"chat"}catch{return"chat"}}function h2(e){if(typeof window>"u")return()=>{};const t=o=>{e(o??Xd())},s=o=>{const a=o.detail;t(a)},r=o=>{o.key&&o.key!==Jd||t()};return window.addEventListener(Gl,s),window.addEventListener("storage",r),()=>{window.removeEventListener(Gl,s),window.removeEventListener("storage",r)}}function p2(e){try{localStorage.setItem(Jd,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Gl,{detail:e}))}function f2(){const{t:e}=he("common"),[t,s]=c.useState(!0);return c.useEffect(()=>{s(Xd()==="chat")},[]),n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Cn,{size:15})," ",e("settings.mobileMode.label")]}),description:e(t?"settings.mobileMode.descriptionChat":"settings.mobileMode.descriptionWorkspace"),checked:t,onChange:r=>{s(r),p2(r?"chat":"workspace")},extra:n.jsx("span",{className:"text-2xs text-text-muted",children:e(t?"settings.mobileMode.chatMode":"settings.mobileMode.workspaceMode")})})}function b2(){const{t:e}=he("common"),[t,s]=c.useState(()=>xo());return c.useEffect(()=>df(s),[]),n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Kp,{size:15})," ",e("settings.chatActivity.rowLabel")]}),description:e(t?"settings.chatActivity.descriptionOn":"settings.chatActivity.descriptionOff"),checked:t,onChange:r=>{s(r),lf(r)}})}function g2({fontsSlot:e}){const{t}=he("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(r2,{})]}),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(m2,{})]}),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(b2,{})]}),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(f2,{})]})]})}function x2({children:e,fallback:t=null}){const[s,r]=c.useState(Hj);return c.useEffect(()=>{if(s)return;let o=!0;return Bj().then(()=>{o&&r(!0)}),()=>{o=!1}},[s]),n.jsx(n.Fragment,{children:s?e:t})}const y2=15e3,v2=15e3,oh=12,w2=8e3,S2=4e3,Ac=new Map,ah=new Map;function k2(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 j2(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 Ng(){const{sendCommand:e}=wt(),{injectEntries:t,getIdes:s}=gr();return c.useCallback(async(r,o)=>{if(!r)return;const a=(o==null?void 0:o.minFreshMs)??v2,i=ah.get(r)||0;if(!(o!=null&&o.force)&&i>0&&Date.now()-i<a)return;const l=Ac.get(r);if(l)return l;const d=(async()=>{const u=await e(r,"get_machine_runtime_stats"),m=k2(u);if(!m)return;const h=s().find(b=>b.id===r),p=j2(h,r,m.machine,m.timestamp||Date.now());t([p]),ah.set(r,Date.now())})().finally(()=>{Ac.delete(r)});return Ac.set(r,d),d},[s,t,e])}function N2(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 C2(e,t){const{sendData:s}=wt(),{injectEntries:r,getIdes:o}=gr(),a=Array.from(new Set(e.filter(Boolean))).join("|");c.useEffect(()=>{if(!(t!=null&&t.enabled)||!s)return;const i=a?a.split("|"):[];if(i.length===0)return;const l=i.map(d=>Fn.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(b=>b.id===d),p=N2(h,d,m);r([p])}));return()=>{l.forEach(d=>d())}},[a,o,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,s])}function _2(e,t){const{sendData:s}=wt(),[r,o]=c.useState(null),[a,i]=c.useState(!1);return c.useEffect(()=>{if(!e){o(null),i(!1);return}if(!(t!=null&&t.enabled)||!s){i(!1);return}o(null),i(!0);let l=null;const d=Fn.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=>{l&&(clearTimeout(l),l=null),o(u.diagnostics),i(!1)});return d.initialSendAccepted?l=setTimeout(()=>{i(!1)},S2):i(!1),()=>{l&&clearTimeout(l),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}}const A2=[{icon:xi,key:"welcome",visual:Yp},{icon:Cn,key:"realtimeChat",visual:$w},{icon:pd,key:"watchAndSteer",visual:Qp},{icon:$a,key:"orchestrate",visual:$a}],T2={icon:xi,key:"getStartedCloud",code:"curl -fsSL https://adhf.dev/install | sh"},I2={icon:xi,key:"allSetStandalone",visual:yi},Yl="adhdev:first-run-dialog";function M2({onClose:e,standalone:t=!1}){const[s,r]=c.useState(0),{t:o}=he("common"),a=[...A2,t?I2:T2],i=a[s],l=s===a.length-1;return c.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]),n.jsx(Un,{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(Et,{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]}),l&&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:()=>l?e():r(d=>d+1),className:"btn btn-primary",children:l?`${o("app.onboardingTour.getStarted")} →`:`${o("app.onboardingTour.next")} →`})})]}),n.jsx("style",{children:`
65
- @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
66
- @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
67
- `})]})})}function Cg(e){return e instanceof Error?e.message:String(e||"")}function R2(e){const t=Cg(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 P2(e){const t=Cg(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function _g({conversation:e,mode:t,ides:s,sendDaemonCommand:r,setCliViewModeOverrides:o}){if(!e||!ft(e))return;const a=Mr(e);if(a===t)return;const i=e.sessionId;i&&o(l=>({...l,[i]:t}));try{await r(Xn(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:$n(e),mode:t})}catch(l){const d=P2(l);i&&!d&&o(u=>{const m={...u};return a===L2(s,i)?delete m[i]:m[i]=a,m}),R2(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function ih(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 E2(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=ih(o,t),i=Array.isArray(o.childSessions)?o.childSessions.map(d=>ih(d,t)):o.childSessions,l=i!==o.childSessions;return a!==o||l?(s=!0,{...a,...l?{childSessions:i}:{}}):o});return s?r:e}function L2(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 D2({visibleConversations:e,clearedTabs:t,setClearedTabs:s,setActionLogs:r,isConversationMuted:o}){c.useEffect(()=>{Ff()},[]);const a=c.useMemo(()=>e.map(i=>({id:i.tabKey,name:Lb(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 fN(a),c.useEffect(()=>{if(Object.keys(t).length===0)return;const l=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(l)},[t,s]),c.useEffect(()=>{const i=setInterval(()=>{const l=Date.now()-3e5;r(d=>{const u=d.filter(m=>m.timestamp>l).slice(-100);return u.length===d.length?d:u})},6e4);return()=>clearInterval(i)},[r]),null}function ch(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 Hs(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=ch(t==null?void 0:t.receivedAt)||ch(t==null?void 0:t.timestamp)||0;return Math.max(s,r)}function Ql(e,t=0){return Hs(e)||e.lastUpdated||t||0}function Ag(e){return Hs(e)||e.lastUpdated||0}function Tg(e,t,s=Ag){const r=Ub(e,t);if(r!==0)return r;const o=s(t)-s(e);if(o!==0)return o;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const l=e.displaySecondary.localeCompare(t.displaySecondary);return l!==0?l:e.tabKey.localeCompare(t.tabKey)}function Jl(e){var s;const t=Zt(e.status,{activeModal:(s=e.modalButtons)!=null&&s.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function O2(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Jl(e)&&!e.title.trim()}function $2(e){return e.length===0?null:[...e].sort((t,s)=>{const r=Number(Jl(s))-Number(Jl(t));if(r!==0)return r;const o=s.messages.length-t.messages.length;return o!==0?o:Tg(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=$2(o);return r?a&&O2(r)?a:r:a||s[0]||null}function F2(e){const t=e.filter(o=>o.type!=="adhdev-daemon"),s=new Set;for(const o of t){if(!_l(o))continue;const a=Pf(o);a&&s.add(a)}const r=new Map;for(const o of t){const a=Kj(o,s),i=r.get(a);if(!i){r.set(a,o);continue}const l=h=>(h.workspace?1:0)+(h.activeChat?1:0)+(h.lastMessagePreview?1:0),d=l(i),u=l(o),m=u>d||u===d&&(o.timestamp||0)>(i.timestamp||0)?o:i;r.set(a,H2(m,m===o?i:o))}return Array.from(r.values())}function H2(e,t){const s=_l(t),r=_l(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,l=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=a==null?void 0:a.settings;return{...e,...i&&{ownerDaemonId:i},...l&&!e.ownerMachineName&&{ownerMachineName:l},...d&&!r&&{settings:{...d,...e.settings??{}}}}}function Tc(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 B2(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 lh(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],s=t[t.length-1],r=s?B2(br(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 W2(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||""),lh(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||""),lh(s.activeChat)].join(":"))].join("|")}function U2(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 K2(e,t){const s=new Map;for(const r of e){const o=t.get(r.routeId)||r;for(const a of co({routeId:r.routeId}))s.set(a,o);for(const a of co({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))s.set(a,r.streamSource==="native"?o:r);for(const a of co({tabKey:r.tabKey}))s.set(a,r)}return s}function q2(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function z2(e){const t=q2(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=br(t.content).slice(0,240);return`${e.messages.length}:${s}:${r}`}function V2({ides:e,connectionStates:t,clearedTabs:s}){const r=c.useMemo(()=>F2(e),[e]),o=c.useMemo(()=>jf(e),[e]),a=c.useMemo(()=>hg(e),[e]),i=c.useRef([]),l=c.useRef([]),d=c.useRef([]),u=c.useRef(new Map),m=c.useRef(new Map),h=c.useMemo(()=>{const j=new Map,v=[];for(const A of r){const{connectionState:E="new",machineName:P}=pg(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),T=W2(A),M=u.current.get(A.id);if(M&&M.ide===A&&M.sourceSignature===T&&M.connectionState===E&&M.machineName===P){j.set(A.id,M),v.push(...M.conversations);continue}const _=Gd(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),I={ide:A,sourceSignature:T,connectionState:E,machineName:P,conversations:_};j.set(A.id,I),v.push(..._)}u.current=j;const y=new Map,N=A=>{const E=z2(A),P=m.current.get(A.tabKey);if(P&&P.signature===E)return y.set(A.tabKey,P),P.timestamp;const T={signature:E,timestamp:Ag(A)||(P==null?void 0:P.timestamp)||0};return y.set(A.tabKey,T),T.timestamp},k=[...v].sort((A,E)=>Tg(A,E,N));return m.current=y,k},[r,t,a]),p=c.useMemo(()=>{const j=U2(h,s);return Tc(i.current,j)?i.current:(i.current=j,j)},[h,s]),b=c.useMemo(()=>{const j=new Map,v=Array.from(new Set(p.map(y=>y.routeId)));for(const y of v){const N=_n(p,y);N&&j.set(y,N)}return j},[p]),f=c.useMemo(()=>{const j=new Map;for(const v of p){const y=b.get(v.routeId),N=v.streamSource==="native"&&y?y:v;for(const k of co({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))j.set(k,N)}return j},[p,b]),x=c.useMemo(()=>K2(p,b),[p,b]),g=c.useCallback(j=>{if(j)return f.get(j)},[f]),w=c.useCallback(j=>{if(j)return x.get(j)},[x]),S=c.useMemo(()=>{const j=p.filter(v=>!ys(v,o).surfaceHidden);return Tc(l.current,j)?l.current:(l.current=j,j)},[p,o]),C=c.useMemo(()=>{const j=S.map(v=>v.tabKey);return Tc(d.current,j)?d.current:(d.current=j,j)},[S]);return{chatIdes:r,conversations:p,visibleConversations:S,visibleTabKeys:C,resolveConversationBySessionId:g,resolveConversationByTarget:w}}function G2({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:s,setSearchParams:r}){const o=c.useMemo(()=>{var l;return e||!t?null:((l=s(t))==null?void 0:l.tabKey)??null},[e,s,t]),a=c.useMemo(()=>{var l;return!e||!t?null:((l=s(t))==null?void 0:l.tabKey)??null},[e,s,t]),i=c.useCallback(()=>{t&&r(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[r,t]);return{requestedDesktopTabKey:o,requestedMobileTabKey:a,consumeRequestedActiveTab:i}}function Y2({ides:e,sendDaemonCommand:t,setToasts:s,resolveConversationByTarget:r,hydrateInteractivePrompt:o}){c.useEffect(()=>{et.setIdes(e)},[e]),c.useEffect(()=>{et.setResolveAction((a,i,l)=>{t(a,i,l).catch(()=>{})})},[t]),c.useEffect(()=>{et.setHydrateInteractivePrompt(o)},[o]),c.useEffect(()=>{const a=et.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 l=i.duration||5e3;setTimeout(()=>s(d=>d.filter(u=>u.id!==i.id||u.pinned)),l)});return()=>{a()}},[s]),c.useEffect(()=>{const a=zf.on("status_event",i=>{et.handleRawEvent(i,"ws")});return()=>{a()}},[]),c.useEffect(()=>{var i;const a=l=>{var g;const d=l.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),b=d.button||((g=m==null?void 0:m.modalButtons)==null?void 0:g[p])||"Approve",f=String(b).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),x=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(f);t(h,"resolve_action",{action:x?"approve":"reject",button:b,...Number.isFinite(p)&&{buttonIndex:p},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...d.targetSessionId&&{targetSessionId:d.targetSessionId}}).catch(w=>console.error("[SW Action] approval failed:",w))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",a)}},[r,t])}const Q2="adhdev_dashboardLayout_v1",J2="adhdev_dashboardDockview_v1",X2="adhdev_dashboardDockviewHiddenRestore_v1",Yr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Zd(e,t){try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}}function Z2(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Ig(e){return`${Q2}:${e}`}function eI(e){const t=Ig(e);return Zd(t,null)}function tI(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=Ig(e);if(s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Mg(e){return`${J2}:${e}`}function nI(e){const t=Mg(e);return Zd(t,null)}function sI(e,t){try{const s=Mg(e);if(!t){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function Rg(e){return`${X2}:${e}`}function rI(e){const t=Rg(e);return Zd(t,{})}function oI(e,t){try{const s=Rg(e);if(Object.keys(t).length===0){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function aI(){return{groupAssignments:[...Yr.groupAssignments],focusedGroup:Yr.focusedGroup,groupActiveTabIds:{...Yr.groupActiveTabIds},groupTabOrders:{...Yr.groupTabOrders},groupSizes:[...Yr.groupSizes]}}function iI(e,t){return e?e.length===t.length&&e.every((s,r)=>s===t[r]):t.length===0}function cI(){const[e]=c.useState(()=>Z2(typeof window<"u"?window.innerWidth:1280)),[t,s]=c.useState(()=>new Map),[r,o]=c.useState(0),[a,i]=c.useState({}),[l,d]=c.useState({}),[u,m]=c.useState([]),[h,p]=c.useState(()=>typeof window<"u"&&window.innerWidth<768),[b,f]=c.useState(!1),x=c.useCallback(()=>{if(b)return;const A=eI(e)??aI();s(new Map(A.groupAssignments)),o(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),m(A.groupSizes),f(!0)},[b,e]);c.useEffect(()=>{b&&tI(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:a,groupTabOrders:l,groupSizes:u})},[b,e,t,r,a,l,u]),c.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),E=P=>p(P.matches);return A.addEventListener("change",E),()=>A.removeEventListener("change",E)},[]);const g=c.useCallback(A=>{s(A)},[]),w=c.useCallback(A=>{o(A)},[]),S=c.useCallback(A=>{i(A)},[]),C=c.useCallback(A=>{d(A)},[]),j=c.useCallback(A=>{m(A)},[]),v=c.useCallback(A=>{w(A)},[w]),y=c.useCallback((A,E)=>{i(P=>(P[A]??null)===(E??null)?P:{...P,[A]:E})},[]),N=c.useCallback((A,E)=>{d(P=>{const T=P[A];return iI(T,E)?P:{...P,[A]:E}})},[]),k=c.useCallback((A,E)=>{const P=E.get(A)??0;return y(P,A),v(P),P},[v,y]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:g,focusedGroup:r,updateFocusedGroup:w,focusGroup:v,groupActiveTabIds:a,updateGroupActiveTabIds:S,setGroupActiveTab:y,groupTabOrders:l,updateGroupTabOrders:C,setGroupTabOrder:N,groupSizes:u,updateGroupSizes:j,isMobile:h,hasHydratedStoredLayout:b,hydrateStoredLayout:x,focusConversationTab:k}}function lI(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const s=e[0],r=Ci(t);return typeof(s==null?void 0:s.id)=="string"&&r.includes(s.id)}function dI({urlActiveTab:e,conversations:t,resolveConversationBySessionId:s,normalizedGroupAssignments:r,hasHydratedStoredLayout:o,hydrateStoredLayout:a,focusConversationTab:i,setSearchParams:l,historyModalOpen:d,activeConv:u,isRefreshingHistory:m,ides:h,handleRefreshHistory:p}){const b=c.useRef(!1),f=c.useRef(!1),x=c.useRef(null),g=c.useRef(!1);c.useEffect(()=>{if(!e||b.current||t.length===0)return;if(!o){a();return}const w=s(e);w&&(i(w.tabKey,r),b.current=!0,f.current=!0,x.current!=null&&(window.clearTimeout(x.current),x.current=null),l(S=>{const C=new URLSearchParams(S);return C.delete("activeTab"),C},{replace:!0}))},[e,t,s,r,o,a,i,l]),c.useEffect(()=>{if(!(f.current||o)&&t.length!==0){if(!e){a(),f.current=!0;return}if(b.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]),c.useEffect(()=>{if(!d){g.current=!1;return}if(!u||g.current||m)return;const w=h.find(S=>S.id===u.routeId);w&&(!w.chats||w.chats.length===0||lI(w.chats,u))&&(g.current=!0,p())},[d,u,m,h,p])}function Ic(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=Ci(t);return typeof(s==null?void 0:s.id)=="string"&&r.includes(s.id)}function Pg({sendDaemonCommand:e,activeConv:t,chats:s,updateRouteChats:r,setToasts:o,setClearedTabs:a}){const[i,l]=c.useState(!1),[d,u]=c.useState(!1),m=c.useCallback(async f=>{try{await e("standalone","launch_ide",{ideType:f,enableCdp:!0})}catch(x){console.error("Launch failed",x)}},[e]),h=c.useCallback(async(f,x)=>{try{const g=f||(t==null?void 0:t.daemonId)||"",w=await e(g,"switch_chat",{id:x,sessionId:x,...gs(t)}),S=w==null?void 0:w.result;if((w==null?void 0:w.success)===!0||S==="switched"||S==="switched-by-title")return;S===!1||S==="not_found"?dr(o,"⚠️ Session tab not found — try refreshing history"):typeof S=="string"&&S.startsWith("error:")?dr(o,`⚠️ Switch error: ${S}`):dr(o,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),dr(o,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,o]),p=c.useCallback(async()=>{if(!(!t||i)){l(!0);try{const f=ps(t);await e(f,"new_chat",{...gs(t)}),k_(f,t.sessionId,Ci(t)[0]),a(x=>({...x,[t.tabKey]:Date.now()}))}catch(f){console.error("New chat failed",f)}finally{l(!1)}}},[t,i,e,a]),b=c.useCallback(async()=>{var f,x;if(!(!t||d)){u(!0);try{const g=ps(t),w=async()=>e(g,"list_chats",{forceExpand:!0,...gs(t)});let S=await w(),C=(S==null?void 0:S.chats)||((f=S==null?void 0:S.result)==null?void 0:f.chats);Ic(C,t)&&(await new Promise(j=>setTimeout(j,450)),S=await w(),C=(S==null?void 0:S.chats)||((x=S==null?void 0:S.result)==null?void 0:x.chats)),S!=null&&S.success&&Array.isArray(C)&&(r(t.routeId,C),Ic(C,t)&&!Ic(s,t)&&dr(o,"⚠️ History dialog did not fully open — try once more"))}catch(g){console.error("Refresh history failed",g)}finally{u(!1)}}},[t,s,d,e,r,o]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:m,handleSwitchSession:h,handleNewChat:p,handleRefreshHistory:b}}function uI(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 mI(e,t){return e.length!==t.length?!1:e.every((s,r)=>s===t[r])}function dh(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 sa(e,t){const s=new Set(t),r=t.length>0?[0]:[];for(const[i,l]of e)!s.has(i)||l<=0||r.includes(l)||r.push(l);r.sort((i,l)=>i-l);const o={};r.forEach((i,l)=>{o[i]=l}),r.length===0&&(o[0]=0);const a=new Map;for(const[i,l]of e){if(!s.has(i)||l<=0)continue;const d=o[l];typeof d=="number"&&d>0&&a.set(i,d)}return{assignments:a,groupCount:Math.max(1,r.length),mapping:o,usedGroups:r}}function uh(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 hI(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 pI(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,l)=>i+l,0);return a>0?o.map(i=>i/a*100):Array(s).fill(100/s)}function mh(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 hh(e){return Array(e).fill(100/e)}function fI({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:s,updateGroupActiveTabIds:r,updateGroupTabOrders:o,groupSizes:a,updateGroupSizes:i,isMobile:l,visibleConversations:d,visibleTabKeys:u}){const m=c.useRef(null),h=c.useMemo(()=>sa(e,u),[e,u]),p=h.assignments,b=c.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),f=b>1,x=c.useCallback((v,y)=>{t(N=>{const k=new Map(sa(N,u).assignments);return y===0?k.delete(v):k.set(v,y),k}),r(N=>({...N,[y]:v})),s(y)},[t,u,r,s]),g=c.useCallback(v=>{t(y=>{const N=sa(y,u).assignments,k=new Map;for(const[A,E]of N)E!==v&&(E>v?k.set(A,E-1):k.set(A,E));return k}),i(y=>{if(y.length<=1)return[];const N=[...y];N.splice(v,1);const k=N.reduce((A,E)=>A+E,0);return k>0?N.map(A=>A/k*100):[]}),s(0)},[t,u,i,s]),w=c.useCallback((v,y)=>{y.preventDefault();const N=m.current;if(!N)return;const k=y.clientX,A=N.offsetWidth,E=a.length===b?[...a]:hh(b),P=M=>{const I=(M.clientX-k)/A*100,D=[...E];D[v]=Math.max(15,E[v]+I),D[v+1]=Math.max(15,E[v+1]-I),i(D)},T=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",P),document.addEventListener("mouseup",T)},[a,b,i]),S=c.useCallback((v,y,N)=>{if(b>=4)return;const k=N==="left"?y:y+1;t(A=>{const E=sa(A,u).assignments,P=new Map;for(const T of d){const M=E.get(T.tabKey)??0,_=M>=k?M+1:M;_>0&&P.set(T.tabKey,_)}return k>0&&P.set(v,k),P}),i(A=>{const E=A.length===b?[...A]:hh(b),P=E[y]??100/b,T=Math.max(15,P/2),M=Math.max(15,P/2),_=[...E];_[y]=T,_.splice(k,0,M);const I=_.reduce((D,L)=>D+L,0);return _.map(D=>D/I*100)}),r(A=>{const E=mh(A,k);return E[k]=v,E}),o(A=>{const E=mh(A,k);return E[k]=[v],E}),s(k)},[b,t,u,d,i,r,o,s]);c.useEffect(()=>{uI(e,p)||t(p)},[e,p,t]),c.useEffect(()=>{const{mapping:v,usedGroups:y}=h;r(N=>{const k=uh(N,v);return dh(N,k)?N:k}),o(N=>{const k=uh(N,v);return dh(N,k)?N:k}),s(N=>{const k=l?0:hI(N,y,v);return N===k?N:k}),i(N=>{const k=l?[]:pI(N,y,h.groupCount);return mI(N,k)?N:k})},[h,l,r,o,s,i]);const C=c.useMemo(()=>{const v=Array.from({length:b},()=>[]);for(const y of d){const N=p.get(y.tabKey)??0,k=Math.min(N,b-1);v[k].push(y)}return v},[d,p,b]),j=c.useCallback(()=>{t(new Map),s(0)},[t,s]);return{containerRef:m,normalizedGroupAssignments:p,numGroups:b,isSplitMode:f,groupedConvs:C,moveTabToGroup:x,closeGroup:g,handleResizeStart:w,splitTabRelative:S,clearAllSplits:j}}function Mc(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 bI(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 ro(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function eu(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},s=Mc(t.channel)||Mc(e.updateChannel)||Mc(e.releaseChannel)||void 0,r=bI(t.npmTag)||(s==="preview"?"next":s==="stable"?"latest":void 0),o=ro(t.targetVersion)||ro(e.serverVersion)||void 0,a=ro(t.minVersion)||void 0,i=ro(t.updateCommand)||(s?"adhdev update":void 0);return{...s?{channel:s}:{},...r?{npmTag:r}:{},...o?{targetVersion:o}:{},...a?{minVersion:a}:{},...i?{updateCommand:i}:{}}}function Rs(e,t=null){return eu(e).targetVersion||t}function gI(e){return eu(e).channel||null}function tu(e){return!e||!eu(e).channel?null:{}}function Eg(e,t={},s){const r=ro(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 si(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 ph(e){var t;return((t=si(e))==null?void 0:t.base)??null}function Lg(e,t){const s=si(e),r=si(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 nu(e,t){const s=e.version||null;return!s||!t||e.versionMismatch===!0&&!si(t)?!1:Lg(s,t)}function Aa(e,t){if(e.versionUpdateRequired===!0)return!0;const s=e.version||null;if(!s||!t||!Lg(s,t))return!1;const r=ph(s),o=ph(t);return!r||!o?!1:r[0]!==o[0]||r[1]!==o[1]}function xI({ides:e,sendDaemonCommand:t}){const s="1.0.75",r=c.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:nu(h,Rs(h,s))).sort((h,p)=>Number(Aa(p,Rs(p,s)))-Number(Aa(h,Rs(h,s)))),[s,e]),o=c.useMemo(()=>r.some(h=>Aa(h,Rs(h,s))),[s,r]),a=c.useMemo(()=>r.map(h=>Rs(h,s)).find(h=>typeof h=="string"&&h.trim().length>0)||s,[s,r]),[i,l]=c.useState(!1),[d,u]=c.useState({}),m=c.useCallback(async h=>{var f,x;const p=e.find(g=>g.id===h);if(!p)return;u(g=>({...g,[h]:"upgrading"}));const b=tu(p);if(!b){u(g=>({...g,[h]:"error"}));return}try{const g=await t(h,"daemon_upgrade",b);(f=g==null?void 0:g.result)!=null&&f.upgraded||(x=g==null?void 0:g.result)!=null&&x.success?u(w=>({...w,[h]:"done"})):u(w=>({...w,[h]:"error"}))}catch{u(g=>({...g,[h]:"error"}))}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:o,targetVersion:a,versionBannerDismissed:i,setVersionBannerDismissed:l,upgradingDaemons:d,handleBannerUpgrade:m}}const Dg=80;function Ta(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function yI(e){return{...e,createdAt:Ta(e.createdAt),updatedAt:Ta(e.updatedAt,e.createdAt),lastEventAt:Ta(e.lastEventAt,e.updatedAt||e.createdAt)}}function vI(e){const t=Rf(e);return t==="unknown:"?e.id:t}function wI(e){return[e.type,Mf(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function SI(e,t=Dg){const s=new Map;for(const r of e){if(r.deletedAt)continue;const o=vI(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 kI(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=ji(o,t),l=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!l)continue;const d=Ta(o.lastMessageAt||(a==null?void 0:a.lastUpdated)||o.lastUpdated,s),u=wI({type:l,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(yI({id:u,dedupKey:u,type:l,routeId:o.routeId,machineId:o.daemonId||o.routeId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,tabKey:o.tabKey,title:tb(o),preview:jC(o),createdAt:d,updatedAt:d,lastEventAt:d}))}return SI(r)}function jI(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function NI(e){const{conversations:t,liveSessionInboxState:s,maxItems:r=Dg}=e,o=c.useMemo(()=>kI(t,s).slice(0,Math.max(0,r)),[t,s,r]),a=c.useMemo(()=>jI(o),[o]);return{notifications:o,unreadCount:a}}function CI({notifications:e,sendDaemonCommand:t}){const s=c.useCallback(a=>{const i=e.find(d=>d.id===a),l=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:l}).catch(()=>{})},[e,t]),r=c.useCallback(a=>{const i=e.find(l=>l.id===a);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),o=c.useCallback(a=>{const i=e.find(l=>l.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 su(...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 _I(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 ru(e,t=[]){if(e==="win32"){for(const s of t){if(typeof s!="string")continue;const r=_I(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 AI(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 TI(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function ou(e,t,s){const r=await e(t,"file_list_browse",{path:s}),o=TI(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("\\")?"\\":"/",l=(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:l(a,u.name)})).sort((u,m)=>u.name.localeCompare(m.name)):[];return{path:a,directories:d}}function fh(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 II(e,t={}){const s=e==null?void 0:e.mcpConfig;if((s==null?void 0:s.mode)!=="manual")return null;const o=fh(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"}).trim();return!o.includes(`
68
- `)&&!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:fh(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"})}}function MI(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 ko(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Og(e){return _i(e)||e.tabKey||e.routeId||null}function $g(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(l=>typeof l=="string"?l.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 ms(e){return String(e||"").trim()}function Fg(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ri(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function RI(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function PI(e,t){const s=ms(e.providerSessionId),r=ms(e.targetSessionId),o=t.find(a=>{const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey,a.routeId].map(ms).filter(Boolean);return!!(s&&i.includes(s)||r&&i.includes(r))});return o?o.tabKey:r||s||null}function EI(e,t,s){if(t.event!=="agent:generating_completed")return null;const r=Fg(t.daemonId);if(r&&r!==e.machineId)return null;const o=ms(t.providerType);if(e.providerType&&o!==e.providerType)return null;const a=ms(e.resumeSessionId),i=ms(e.launchedSessionId),l=ms(t.providerSessionId),d=ms(t.targetSessionId);if(a&&a!==l&&a!==d||i&&i!==l&&i!==d)return null;const u=ri(e.workspacePath);if(u){const m=ri(t.workspaceName);if(m&&!RI(m,u))return null}return PI(t,s)}function bh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function LI({ides:e,conversations:t,onOpenSession:s}){const[r,o]=c.useState(null),a=c.useRef(null),i=c.useCallback(()=>{a.current=null,o(null)},[]),l=c.useCallback(d=>{a.current=d,o(d)},[]);return c.useEffect(()=>{if(!r)return;const d=ri(r.workspacePath),u=e.find(h=>{var g,w,S,C;if(!h||h.type==="adhdev-daemon"||Fg(h.daemonId||h.id)!==r.machineId||(So(h)?"cli":"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 j=String(r.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(y=>String(y||"")).filter(Boolean).includes(j)}if(d){const j=ri(h.workspace||h.runtimeWorkspaceLabel);return j?j===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((C=(S=(w=(g=h.activeChat)==null?void 0:g.messages)==null?void 0:w.at)==null?void 0:S.call(w,-1))==null?void 0:C.timestamp)||0)>=r.startedAt-5e3});if(!u)return;const m=$g({entrySessionId:u.sessionId,entryInstanceId:u.instanceId,entryRouteId:u.id,conversations:t});m&&(i(),s(m))},[i,t,e,s,r]),c.useEffect(()=>et.onStatusEvent(d=>{const u=a.current;if(!u)return;const m=EI(u,d,t);m&&(i(),s(m))}),[i,t,s]),c.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:l}}function DI(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 OI(e,t,s){var i,l,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=(l=s==null?void 0:s.initialThinkingLevel)==null?void 0:l.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 $I({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:s,activeConv:r,ides:o,setCliViewModeOverrides:a}){const i=Bd(),{launchCli:l}=vi(),d=c.useCallback(async(g,w)=>ou(e,g,w),[e]),u=c.useCallback(async(g,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const S=await e(g,"workspace_add",{path:w.trim()});return S!=null&&S.success?{ok:!0}:{ok:!1,error:(S==null?void 0:S.error)||"Could not save workspace"}}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not save workspace"}}},[e]),m=c.useCallback(async(g,w,S)=>{var C;try{const j={ideType:w,enableCdp:!0};(C=S==null?void 0:S.workspacePath)!=null&&C.trim()&&(j.workspace=S.workspacePath.trim());const v=await e(g,"launch_ide",j);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:g,kind:"ide",providerType:w,workspacePath:(S==null?void 0:S.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not launch IDE"}}},[e,t]),h=c.useCallback(async(g,w,S,C)=>{const j=Date.now();try{const v=DI(S,C),y=await l(g,v),N=(y==null?void 0:y.result)||y,k=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);return y!=null&&y.success&&k?(t({machineId:g,kind:w,providerType:S,workspacePath:(C==null?void 0:C.workspacePath)||null,resumeSessionId:(C==null?void 0:C.resumeSessionId)||null,launchedSessionId:k,startedAt:j}),{ok:!0}):y!=null&&y.success?(t({machineId:g,kind:w,providerType:S,workspacePath:(C==null?void 0:C.workspacePath)||null,resumeSessionId:(C==null?void 0:C.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(N==null?void 0:N.error)||`Could not launch ${w.toUpperCase()} session`,code:(y==null?void 0:y.code)||(N==null?void 0:N.code)||void 0}}catch(v){return bh(v)?(t({machineId:g,kind:w,providerType:S,workspacePath:(C==null?void 0:C.workspacePath)||null,resumeSessionId:(C==null?void 0:C.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${w.toUpperCase()} session`}}},[l,e,t]),p=c.useCallback(async g=>{var w;if(i!=null&&i.listMeshes){const S=await i.listMeshes(g);return za(S),S}if(!g)return[];try{const S=await e(g,"list_meshes",{}),C=(S==null?void 0:S.result)??S;if((C==null?void 0:C.success)===!1)throw new Error((C==null?void 0:C.error)||"Could not load meshes");const v=(Array.isArray(C==null?void 0:C.meshes)?C.meshes:Array.isArray((w=C==null?void 0:C.result)==null?void 0:w.meshes)?C.result.meshes:[]).map(y=>{var N;return{id:String((y==null?void 0:y.id)||""),name:String((y==null?void 0:y.name)||(y==null?void 0:y.id)||"Untitled mesh"),repoIdentity:(y==null?void 0:y.repoIdentity)||(y==null?void 0:y.repo_identity)||null,workspace:Array.isArray(y==null?void 0:y.nodes)&&y.nodes.length>0?String(((N=y.nodes[0])==null?void 0:N.workspace)||""):null,nodesCount:Array.isArray(y==null?void 0:y.nodes)?y.nodes.length:void 0,status:(y==null?void 0:y.status)||null}}).filter(y=>y.id);return za(v),v}catch(S){throw console.error("List meshes failed",S),S}},[i,e]),b=c.useCallback(async(g,w,S,C)=>{if(!w.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(g,w,S,C);const j=Date.now();try{const v=OI(w,S,C),y=await e(g,"launch_mesh_coordinator",v),N=(y==null?void 0:y.result)??y;if((N==null?void 0:N.success)===!1||(y==null?void 0:y.success)===!1){const A=String((N==null?void 0:N.code)||(y==null?void 0:y.code)||""),E=MI((N==null?void 0:N.meshCoordinatorSetup)||(N==null?void 0:N.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(N==null?void 0:N.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:E}}const k=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);return k?s(k):t({machineId:g,kind:"cli",providerType:(N==null?void 0:N.cliType)||S.trim()||void 0,workspacePath:(N==null?void 0:N.workspace)||null,startedAt:j}),{ok:!0}}catch(v){return bh(v)?(t({machineId:g,kind:"cli",providerType:S.trim()||void 0,startedAt:j}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,s,e,t]),f=c.useCallback(async(g,w)=>{if(!g||!w)return[];try{const S=await e(g,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),C=(S==null?void 0:S.result)??S;return Array.isArray(C==null?void 0:C.sessions)?C.sessions:[]}catch(S){return console.error("List saved sessions failed",S),[]}},[e]),x=c.useCallback(async g=>{await _g({conversation:r,mode:g,ides:o,sendDaemonCommand:e,setCliViewModeOverrides:a})},[r,o,e,a]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:u,handleLaunchMachineIde:m,handleLaunchMachineProvider:h,handleListMachineMeshes:p,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:f,setActiveCliViewMode:x}}function FI(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 HI(e,t,s=Date.now()){return!e||!FI(t)?null:{tabKey:e,nonce:s}}function BI({isMobile:e,conversations:t,visibleConversations:s,groupActiveTabIds:r,focusedGroup:o,groupedConvs:a,setSearchParams:i}){const[l,d]=c.useState(null),[u,m]=c.useState(null),h=c.useMemo(()=>{var g,w;if(!e){if(l){const S=t.find(C=>C.tabKey===l);if(S)return S}return s[0]}const x=r[o];if(x){const S=t.find(C=>C.tabKey===x);if(S)return S}return((g=a[o])==null?void 0:g[0])||((w=a[0])==null?void 0:w[0])},[t,l,o,r,a,e,s]),p=c.useCallback(x=>{d(x)},[]),b=c.useCallback(x=>{d(x.tabKey),i(g=>{const w=new URLSearchParams(g),S=CC(x);return S?w.set("activeTab",S):w.delete("activeTab"),w},{replace:!0})},[i]),f=c.useCallback((x,g)=>{const w=HI(x,g);w&&m(w)},[]);return{activeConv:h,openDesktopConversation:b,requestScrollToBottom:f,scrollToBottomRequest:u,setDesktopActiveTab:p}}function WI(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 UI(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 KI({activeConv:e,isMobile:t,liveSessionInboxState:s,sendDaemonCommand:r}){const o=c.useRef(null),a=c.useRef(null),i=c.useRef(null),l=c.useRef(null),d=c.useRef(null);c.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),l.current&&(clearTimeout(l.current),l.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=ys(e,s),h=UI({tabKey:e.tabKey,historySessionId:_i(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Hs(e),liveState:m}),p=h.autoReadKey,b=WI({autoReadKey:p,shouldMarkSeen:h.shouldMarkSeen,completedKey:o.current,pendingKey:a.current});if(!h.shouldMarkSeen){b.shouldCancelPending&&u(),o.current=p;return}if(!b.shouldSchedule)return;b.shouldCancelPending&&u();const f=()=>{if(document.visibilityState!=="visible"||o.current===p)return;o.current=p,a.current=null,i.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const g=h.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:g,completionMarker:h.completionMarker}).catch(()=>{})};if(a.current=b.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(f,1500);const g=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=g,document.addEventListener("visibilitychange",g);return}const x=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.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]),c.useEffect(()=>()=>{i.current&&clearTimeout(i.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Rc(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 qI({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:s,ides:r,sendDaemonCommand:o,updateRouteChats:a,setToasts:i,setClearedTabs:l,setSearchParams:d}){var $;const{launchCli:u}=vi(),[m,h]=c.useState(!1),[p,b]=c.useState([]),[f,x]=c.useState(()=>un()),[g,w]=c.useState(!1),[S,C]=c.useState(null),j=c.useRef(null),v=c.useMemo(()=>s||t||e,[e,s,t]),y=!!v&&ft(v),N=c.useMemo(()=>{if(!v||!y)return null;const U=v.daemonId||v.routeId||"",J=$n(v),K=Rc(v);return`${U}:${J}:${v.providerSessionId||""}:${K}`},[v,y]),k=c.useMemo(()=>!v||!y?"":Rc(v),[v,y]),{isCreatingChat:A,isRefreshingHistory:E,handleSwitchSession:P,handleNewChat:T,handleRefreshHistory:M}=Pg({sendDaemonCommand:o,activeConv:v,chats:($=r.find(U=>U.id===(v==null?void 0:v.routeId)))==null?void 0:$.chats,updateRouteChats:a,setToasts:i,setClearedTabs:l}),_=c.useCallback(()=>{h(!0)},[]),I=c.useCallback(()=>{h(!1)},[]),D=c.useCallback(async()=>{if(!(!v||!y||g)){w(!0);try{const U=v.daemonId||v.routeId,J=$n(v),K=Rc(v),R=await o(U,"list_saved_sessions",{agentType:J,providerType:J,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...K?{workspace:K}:{}}),O=(R==null?void 0:R.result)??R;b(Array.isArray(O==null?void 0:O.sessions)?O.sessions:[])}catch(U){console.error("Refresh saved sessions failed",U),b([])}finally{w(!1)}}},[v,g,y,o]);c.useEffect(()=>{if(!m){j.current=null;return}if(!y){j.current=null,b([]),w(!1);return}!N||g||j.current!==N&&(j.current=N,D())},[D,m,g,y,N]);const L=c.useCallback(async U=>{if(!v||!y||!U.providerSessionId||!U.workspace)return;const J=v.daemonId||v.routeId,K=$n(v);try{C(U.providerSessionId);const R=Jj(U.summaryMetadata,"model",{preferShortValue:!0})||void 0,O=await u(J,{cliType:K,dir:U.workspace,resumeSessionId:U.providerSessionId,initialModel:R,...R?{modelSource:"remembered"}:{}}),H=(O==null?void 0:O.result)??O,B=typeof(H==null?void 0:H.sessionId)=="string"?H.sessionId:typeof(H==null?void 0:H.id)=="string"?H.id:"";B&&d(q=>{const W=new URLSearchParams(q);return W.set("activeTab",B),W},{replace:!0}),I()}catch(R){console.error("Resume saved session failed",R)}finally{C(null)}},[I,v,y,o,d]);return{historyModalOpen:m,openHistoryModal:_,closeHistoryModal:I,historyTargetConv:v,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:A,isHistoryRefreshingHistory:E,handleHistorySwitchSession:P,handleHistoryNewChat:T,handleHistoryRefresh:M,savedHistorySessions:p,savedHistoryFilters:f,setSavedHistoryFilters:x,missingWorkspaceResumePath:k,isSavedHistoryLoading:g,resumingSavedHistorySessionId:S,handleRefreshSavedHistory:D,handleResumeSavedHistorySession:L}}function zI({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:l}){const[d,u]=c.useState(null),[m,h]=c.useState(null),p=c.useMemo(()=>{if(e||!r)return null;const w=l(r);return w&&!ft(w)?w:null},[e,r,l]),b=c.useMemo(()=>{const w=d==null?void 0:d.routeId;if(!w)return null;const S=d!=null&&d.tabKey?a.find(C=>C.tabKey===d.tabKey):o?a.find(C=>C.tabKey===o):null;return(S==null?void 0:S.routeId)===w?S:_n(a,w)},[a,d,o]),f=c.useMemo(()=>{if(b)return i.find(w=>w.id===b.routeId)},[i,b]);c.useEffect(()=>{p&&(u({routeId:p.routeId,tabKey:lm(p)}),h(p),s({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,s,p]);const x=c.useCallback(w=>{w&&(u({routeId:w.routeId,tabKey:lm(w)}),h(w))},[]),g=c.useCallback(()=>{u(null),h(null)},[]);return{remoteDialogConv:b,remoteDialogIdeEntry:f,remoteDialogActiveConv:m,setRemoteDialogActiveConv:h,openRemoteDialog:x,closeRemoteDialog:g}}function VI({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:u}){const{remoteDialogConv:m,remoteDialogIdeEntry:h,remoteDialogActiveConv:p,setRemoteDialogActiveConv:b,openRemoteDialog:f,closeRemoteDialog:x}=zI({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:l}),[g,w]=c.useState(!1),[S,C]=c.useState(null),j=c.useCallback(async N=>{const k=N||d;!k||!ft(k)||(C(k),w(!0))},[d]),v=c.useCallback(()=>{w(!1),C(null)},[]),y=c.useCallback(async N=>{const k=S||d;if(!k||!ft(k)){v();return}w(!1);try{const A=$n(k),E=k.routeId||k.daemonId||"";await u(E,"stop_cli",{cliType:A,targetSessionId:k.sessionId,mode:N,...Mi(k)})}catch(A){console.error("Stop CLI failed:",A)}finally{C(null)}},[d,v,S,u]);return{remoteDialogConv:m,remoteDialogIdeEntry:h,remoteDialogActiveConv:p,setRemoteDialogActiveConv:b,openRemoteDialog:f,closeRemoteDialog:x,cliStopDialogOpen:g,cliStopTargetConv:S,requestCliStop:j,cancelCliStop:v,confirmCliStop:y}}function Pc(e,t=!0){return(e??!0)&&t}const au=c.memo(function({activeConv:t,clearToken:s,isCliTerminal:r,ideEntry:o,terminalRef:a,commands:i,actionLogs:l,userName:d,scrollToBottomRequestNonce:u,isInputActive:m=!0,isVisible:h=!0}){const{handleModalButton:p,handleRelaunch:b,handleSendChat:f,handleSendNowQueued:x,handleCancelQueued:g,isSendingChat:w,sendFeedbackMessage:S,pendingLocalMessage:C,pendingLocalMessages:j,retireEchoedPendingMessages:v,handleFocusAgent:y,isFocusingAgent:N}=i,k=r,A=!r,E=Pc(h,k),P=Pc(h,A),T=Pc(h),{t:M}=he("common"),_=I=>n.jsx(Cb,{activeConv:t,ideEntry:o,handleSendChat:f,handleSendNowQueued:x,handleCancelQueued:g,isSendingChat:w,sendFeedbackMessage:S,pendingLocalMessage:C,pendingLocalMessages:j,retireEchoedPendingMessages:v,handleFocusAgent:y,isFocusingAgent:N,actionLogs:l,userName:d,scrollToBottomRequestNonce:u,isInputActive:m&&I,isVisible:I});return n.jsxs(n.Fragment,{children:[n.jsx(Cf,{activeConv:t,onModalButton:p}),t.transport!=="pty"&&t.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(en,{size:14})}),n.jsxs("span",{className:"flex flex-1 items-center gap-1",children:[n.jsx("span",{className:"font-semibold",children:M("paneGroup.cdpDisconnectedShort")}),n.jsx(nt,{content:M("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:b,children:M("paneGroup.relaunchWithCdp")})]})}):null,t.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:k?"visible":"hidden",pointerEvents:k?"auto":"none"},children:n.jsx(C1,{activeConv:t,clearToken:s,terminalRef:a,handleSendChat:f,isSendingChat:w,sendFeedbackMessage:S,isVisible:E,isInputActive:m&&E})}),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:_(P)})]}):_(T)]})},(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 GI({conversation:e,className:t="",onOpenNativeConversation:s,onOpenMachine:r,interactive:o=!0,meshOnly:a=!1}){const{t:i}=he("common"),l=Gs(),d=Xn(e),u=a?null:eb(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",b=wr(e),f=NC(e),x=Ld(e).role,g=e.meshQueueStats,w=x==="coordinator",S=c.useCallback(()=>{if(r){r();return}d&&l("/dashboard",{state:{openMachineId:d}})},[d,l,r]),C=c.useCallback(()=>{if(s){s();return}const j=Og(e);j&&l(ko(j))},[e,l,s]);return!m&&!h&&!p&&!u&&!x&&!g?null:n.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(o?n.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:C,title:f,children:[n.jsx(Bn,{size:12}),n.jsx("span",{children:f})]}):n.jsxs("span",{className:"conversation-meta-chip",title:f,children:[n.jsx(Bn,{size:12}),n.jsx("span",{children:f})]})),h&&n.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[n.jsx(yr,{size:12}),n.jsx("span",{children:b})]}),p&&n.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[n.jsx(yr,{size:12}),n.jsx("span",{children:b})]}),u&&(o?n.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:u,children:[n.jsx(xr,{size:12}),n.jsx("span",{children:u})]}):n.jsxs("span",{className:"conversation-meta-chip",title:u,children:[n.jsx(xr,{size:12}),n.jsx("span",{children:u})]})),w&&g&&n.jsxs("span",{className:`conversation-meta-chip ${g.pending>0?"is-active":""}`,style:g.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:i("dashboard.metaChips.queueTooltip",{pending:g.pending,assigned:g.assigned,completed:g.completed,failed:g.failed}),children:[n.jsx(kw,{size:12}),n.jsx("span",{children:i("dashboard.metaChips.queuePending",{count:g.pending})})]})]})}function YI({selectedConversation:e,isStandalone:t,selectedIdeEntry:s,actionLogs:r,userName:o,commands:a,onBack:i,onOpenNativeConversation:l,onOpenMachine:d,onOpenHistory:u,onOpenRemote:m,onOpenMeshGraph:h,onStopCli:p,cliViewMode:b,onSetCliViewMode:f}){const{t:x}=he("common"),g=c.useRef(null),w=Ni(Nf(e)),S=ft(e),C=S&&b==="terminal",j=t?"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 ${j} 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:i,type:"button","aria-label":x("common.back"),children:n.jsx(bi,{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(ws,{conversation:e,size:15}),n.jsx("span",{className:"min-w-0 truncate",children:kt(e)})]}),n.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:n.jsx(GI,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>l(e),onOpenMachine:()=>d(e)})})]})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&b&&n.jsx(qb,{mode:b,onChange:f,compact:!0}),S&&p&&n.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:x("cliStop.stopProcess"),"aria-label":x("cliStop.stopProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:n.jsx(Et,{size:14})}),n.jsx(ag,{conversation:e,onOpenMeshGraph:h}),n.jsx(rg,{conversation:e,onOpenHistory:u,onOpenRemote:m,iconSize:14})]})]}),n.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:n.jsx(au,{activeConv:e,clearToken:0,isCliTerminal:C,ideEntry:s,terminalRef:g,commands:a,actionLogs:r,userName:o})}),n.jsx(Nd,{promptSession:w.promptSession,isSubmitting:w.isSubmitting,error:w.responseError,onSubmit:w.submit,onCancel:w.cancel})]})}function QI(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Hg({isStandalone:e=!1}={}){const{t}=he("common"),[s,r]=c.useState("unix"),[o,a]=c.useState("powershell"),[i,l]=c.useState(!1),d=s==="unix"?"unix":o,u=c.useMemo(()=>vT(),[]);c.useEffect(()=>{r(QI())},[]);const m=c.useCallback(()=>{navigator.clipboard.writeText(u[d].cmd).catch(()=>{}),l(!0),setTimeout(()=>l(!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(Cr,{size:12}):n.jsx(Hp,{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 Bg({section:e,onSectionChange:t}){const{t:s}=he("common"),r=[{key:"machines",label:s("nav.machines"),icon:Bn},{key:"chats",label:s("nav.chats"),icon:Cn}];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 l=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 ${l?"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:l?{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":l,children:[n.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${l?"text-accent-primary":"bg-transparent text-current"}`,style:l?{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 ra({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 nr({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 As({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 JI({title:e,isMuted:t,onToggleMute:s,onHide:r,onStop:o}){const{t:a}=he(),[i,l]=c.useState(!1),d=c.useRef(null);if(c.useEffect(()=>{if(!i)return;const h=b=>{var f;(f=d.current)!=null&&f.contains(b.target)||l(!1)},p=b=>{b.key==="Escape"&&l(!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(),l(!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(),l(p=>!p)},"aria-haspopup":"menu","aria-expanded":i,"aria-label":a("mobileInbox.moreActionsFor",{title:e}),title:a("dashboard.header.moreActions"),children:t?n.jsx(fl,{size:13}):n.jsx(Up,{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(Jn,{size:15}):n.jsx(fl,{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(gi,{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(Et,{size:15}),a("mobileInbox.stopSessionTitle")]})]})]})}function oa({item:e,type:t,getAvatarText:s,onOpenConversation:r,onRequestHideConversation:o,onRequestStopCli:a,onOpenMeshGraph:i,onCollectChatDebugBundle:l,isMuted:d,onToggleMute:u}){const{t:m}=he(),h=t==="needs_attention"||t==="task_complete",p=t==="working",b=t==="earlier",f=t==="task_complete",{isReconnecting:x,isConnecting:g,isErrored:w}=Ss(e.conversation),S=kt(e.conversation),C=Po(e.conversation),j=Eb(e.conversation,{requiresAction:t==="needs_attention"}),v=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%)]":b?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",y=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":b?"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",N=b?"text-text-secondary":"text-text-primary",k=b?"text-text-muted":"text-text-secondary",A=b?"text-text-secondary opacity-80":"text-text-muted",E=b?"text-text-muted opacity-80":"text-text-muted",P=!p&&!f,T=Mb(e.conversation),M="text-[color:var(--status-warning)]",_=I=>{if(!l||!N1())return;I.preventDefault(),I.stopPropagation();const D=l==null?void 0:l(e.conversation);Promise.resolve(D).catch(L=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",L)})};return n.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${v}`,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 ${y}`,style:h?{color:"var(--accent-on-primary)"}:void 0,children:s(S)}),T&&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:S}),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:_,type:"button",children:[n.jsxs("div",{className:"flex items-center gap-1.5 pr-[92px]",children:[n.jsx(ws,{conversation:e.conversation,size:13}),n.jsx("span",{className:`text-[15px] leading-[22px] font-bold truncate tracking-tight ${N}`,children:S})]}),n.jsxs("div",{className:`text-xs font-medium truncate flex items-center ${k}`,children:[n.jsx("span",{className:"truncate",children:C}),n.jsx(Od,{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:`${M} animate-pulse`,children:m("mobileInbox.reconnectingItem")})]}):g?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")})]}):j==="Action needed"?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:M,children:m("mobileInbox.actionNeeded")})]}):w&&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:[P&&n.jsx("span",{className:`mr-0.5 text-2xs font-medium shrink-0 ${E}`,children:Xp(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(JI,{title:S,isMuted:d,onToggleMute:u,onHide:o,onStop:a})]})]})},e.conversation.tabKey)}function gh({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 XI({section:e,attentionItems:t,unreadItems:s,workingItems:r,completedItems:o,hiddenConversations:a,machineCards:i,getAvatarText:l,actionLogs:d,sendDaemonCommand:u,onOpenConversation:m,onShowAllHidden:h,onHideConversation:p,onShowHiddenConversation:b,onOpenMeshGraph:f,onStopCli:x,onOpenNewSession:g,onOpenMachine:w,onOpenSettings:S,onSectionChange:C,wsStatus:j="connected",initialDataLoaded:v=!0,conversationsLoaded:y,isStandalone:N=!1,onCollectChatDebugBundle:k,isConversationMuted:A,onToggleMuteConversation:E}){const{t:P}=he(),T=j==="disconnected"||j==="reconnecting"||j==="offline"||j==="auth_failed",M=!T&&!v,_=!T&&!(y??v),I=i.length>0,D=t.length>0||s.length>0||r.length>0||o.length>0,L=P(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),$=N?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",U=N?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",J=c.useCallback(async O=>{const H=ps(O);if(!H)return;const B=Array.isArray(O.messages)?O.messages:[],q=cb({activeConv:O,visibleMessages:B,actionLogs:d,visibleBarControlCount:0,chatState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:B.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),W=await u(H,"get_chat_debug_bundle",{...gs(O),delivery:"daemon_file",frontendSnapshot:q}),ce=Ls(W),ye=ub(ce),G=await db(ye);G==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),et.showToast(lb(ce,{locatorCopyStatus:G}),G==="failed"?"warning":"success")},[d,u]),K=k||J,R=c.useCallback(O=>{p&&(p(O),et.showToast(P("mobileInbox.hiddenToast",{title:kt(O)}),"info",{duration:6e3,actions:[{label:P("mobileInbox.undo"),variant:"primary",onClick:()=>{b?b(O):h()}}]}))},[p,h,b,P]);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 ${$}`,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:L}),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(Jn,{size:13}),n.jsx("span",{children:t.length+s.length})]}),n.jsx("button",{onClick:S,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(_r,{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] ${U}`,children:[e==="machines"&&n.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:T?n.jsx(As,{icon:n.jsx(tn,{size:32}),title:P(j==="offline"?"mobileInbox.networkOffline":j==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:P(j==="offline"?"mobileInbox.waitingForNetwork":j==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):M?n.jsx(As,{icon:n.jsx(tn,{size:32}),title:P("mobileInbox.loading"),subtitle:P("mobileInbox.loadingSubtitle")}):i.length===0?n.jsx(As,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:P(N?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:P(N?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!N&&n.jsx("div",{className:"w-full max-w-[360px] mt-4",children:n.jsx(Hg,{})})}):n.jsx(nr,{children:i.map((O,H)=>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] ${H>0?"border-t border-border-subtle/70":""}`,onClick:()=>w(O.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:l(O.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:O.label}),n.jsxs("span",{className:"flex items-center gap-2 text-2xs font-medium text-text-muted shrink-0",children:[n.jsx(gh,{count:O.generatingCount,label:P("mobileInbox.generatingCount",{count:O.generatingCount})}),O.unread>0?n.jsx("span",{className:"text-accent-primary",children:P("mobileInbox.newCount",{count:O.unread})}):O.total>0?P("mobileInbox.chatCount",{count:O.total}):P("mobileInbox.idle")]})]}),n.jsx("div",{className:"text-xs font-medium text-text-secondary truncate",children:O.subtitle}),O.total>0?n.jsxs("div",{className:"text-xxs text-text-muted mt-0.5",children:[P("mobileInbox.chatCount",{count:O.total}),O.unread>0?P("mobileInbox.unreadSuffix",{count:O.unread}):"",O.generatingCount>0?P("mobileInbox.collapsedGeneratingSuffix",{count:O.generatingCount}):""]}):O.generatingCount>0?n.jsx("div",{className:"text-xxs text-accent-primary mt-0.5 font-medium",children:P("mobileInbox.generatingCount",{count:O.generatingCount})}):n.jsx("div",{className:"text-xxs text-text-muted mt-0.5 italic opacity-70",children:P("mobileInbox.noActiveChats")})]})]},O.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(ra,{title:P("mobileInbox.needsAttention"),className:"mb-0"}),n.jsx(nr,{children:t.map((O,H)=>n.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:n.jsx(oa,{item:O,type:"needs_attention",getAvatarText:l,onOpenConversation:m,onRequestHideConversation:p?()=>R(O.conversation):void 0,onRequestStopCli:x?()=>x(O.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:K,isMuted:A==null?void 0:A(O.conversation),onToggleMute:E?()=>E(O.conversation):void 0})},O.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(ra,{title:P("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),n.jsx(nr,{children:s.map((O,H)=>n.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:n.jsx(oa,{item:O,type:"task_complete",getAvatarText:l,onOpenConversation:m,onRequestHideConversation:p?()=>R(O.conversation):void 0,onRequestStopCli:x?()=>x(O.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:K,isMuted:A==null?void 0:A(O.conversation),onToggleMute:E?()=>E(O.conversation):void 0})},O.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(ra,{title:P("mobileInbox.workingNow"),className:"mb-0 mt-2"}),n.jsx(nr,{children:r.map((O,H)=>n.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:n.jsx(oa,{item:O,type:"working",getAvatarText:l,onOpenConversation:m,onRequestHideConversation:p?()=>R(O.conversation):void 0,onRequestStopCli:x?()=>x(O.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:K,isMuted:A==null?void 0:A(O.conversation),onToggleMute:E?()=>E(O.conversation):void 0})},O.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(ra,{title:P("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?n.jsx(nr,{children:o.map((O,H)=>n.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:n.jsx(oa,{item:O,type:"earlier",getAvatarText:l,onOpenConversation:m,onRequestHideConversation:p?()=>R(O.conversation):void 0,onRequestStopCli:x?()=>x(O.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:K,isMuted:A==null?void 0:A(O.conversation),onToggleMute:E?()=>E(O.conversation):void 0})},O.conversation.tabKey))}):D?n.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:P("mobileInbox.allCaughtUp")}):T?n.jsx(As,{icon:n.jsx(tn,{size:28}),title:P("mobileInbox.connecting"),subtitle:P("mobileInbox.connectingSubtitle")}):_?n.jsx(As,{icon:n.jsx(tn,{size:28}),title:P("mobileInbox.loading"),subtitle:P("mobileInbox.loadingSubtitle")}):I?n.jsx(As,{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(Cn,{size:20})}),title:P("mobileInbox.noConversations"),subtitle:P("paneGroup.newSessionDescription"),children:g&&n.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:g,"aria-label":P("paneGroup.newSession"),title:P("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:P("paneGroup.newSession")})]})}):n.jsx(As,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:P("mobileInbox.noMachinesConnected"),subtitle:P("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&a.length>0&&(()=>{const O=Rk(a);return n.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:n.jsx(nr,{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:P("mobileInbox.hiddenTabs")}),n.jsx(gh,{count:O,label:P("mobileInbox.generatingCount",{count:O})})]}),n.jsxs("div",{className:"mt-0.5 text-xxs text-text-muted",children:[P("mobileInbox.collapsedCount",{count:a.length}),O>0?P("mobileInbox.collapsedGeneratingSuffix",{count:O}):""]})]}),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:P("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&g&&D&&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:g,"aria-label":P("paneGroup.newSession"),title:P("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(Bg,{section:e,onSectionChange:C})]})}function ZI(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 Wg(e,t){const s=[e.workspace||(t?t("launch.workspaceUnknown"):"Workspace unknown")],r=wo(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(t?t("launch.messageCountShort",{count:e.messageCount}):`${e.messageCount} msgs`);const o=ZI(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 iu({title:e,description:t,currentPath:s,directories:r,busy:o=!1,error:a="",confirmLabel:i,inline:l=!1,onClose:d,onNavigate:u,onConfirm:m}){const[h,p]=c.useState(s),{t:b}=he("common"),f=i??b("machine.workspaceBrowse.useThisFolder");c.useEffect(()=>{p(s)},[s]);const x=AI(s),g=h.trim(),w=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&&!l&&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":b("common.close"),children:n.jsx(Et,{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(bi,{size:15}),b("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:b("machine.workspaceBrowse.currentFolder")}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"text",value:h,onChange:S=>p(S.target.value),onKeyDown:S=>{S.key!=="Enter"||!g||o||(S.preventDefault(),u(g))},placeholder:b("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:()=>{!g||o||u(g)},disabled:!g||o,children:b("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:b("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:b("machine.workspaceBrowse.noSubfolders")}):n.jsx("div",{className:"p-3",children:r.map(S=>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(S.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(Ws,{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:S.name}),n.jsx("span",{className:"block text-2xs text-text-muted truncate",children:S.path})]})]},S.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:b("common.cancel")}),n.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(g||s),disabled:!g&&!s||o,children:f})]})]});return l?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:w}):n.jsx(Un,{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:w})})})}function Wi({title:e,description:t,details:s,workspaceOptions:r,selectedWorkspaceKey:o,onWorkspaceChange:a,confirmLabel:i,busyLabel:l,busy:d=!1,showArgsInput:u,argsValue:m,onArgsChange:h,showModelInput:p,modelValue:b,onModelChange:f,historyProviderNode:x,onConfirm:g,onCancel:w}){const{t:S}=he("common"),C=i??S("machine.launchConfirm.launch"),j=l??S("machine.launchConfirm.launching"),v=r==null?void 0:r.find(N=>N.key===o),y=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:w,"aria-label":S("machine.launchConfirm.closeAria"),children:n.jsx(Et,{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:S("machine.launchConfirm.workspace")}),n.jsx("select",{value:o||"",onChange:N=>a(N.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(N=>n.jsx("option",{value:N.key,children:N.label},N.key))}),(v==null?void 0:v.description)&&n.jsx("div",{className:"mt-2 text-2xs text-text-muted break-all",children:v.description})]}),x,s.map((N,k)=>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:N.label}),n.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${k}`)),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:S("machine.launchConfirm.languageModel")}),n.jsx("input",{type:"text",value:b||"",onChange:N=>f(N.target.value),placeholder:S("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:S("machine.launchConfirm.cliArgs")}),n.jsx("input",{type:"text",value:m||"",onChange:N=>h(N.target.value),placeholder:S("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:w,disabled:d,children:S("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:g,disabled:d,children:[n.jsx(Wp,{size:14}),d?j:C]})]})]})});return typeof document>"u"?y:An.createPortal(y,document.body)}function xh(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Ug(e){const{machine:t,currentWorkspacePath:s,currentWorkspaceId:r,includeHome:o=!0,homeLabel:a="Home directory",homeDescription:i="Launch without a workspace"}=e,l=[];o&&l.push({key:"__home__",label:a,description:i,workspaceId:null,workspacePath:null});for(const m of t.workspaces||[])l.push({key:`saved:${m.id}`,label:`${m.id===t.defaultWorkspaceId?"⭐ ":""}${xh(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&&l.push({key:`custom:${d}`,label:xh(d),description:d,workspaceId:null,workspacePath:d}),r){const m=`saved:${r}`;if(l.some(h=>h.key===m))return{options:l,selectedKey:m}}return u?{options:l,selectedKey:`saved:${u.id}`}:d?{options:l,selectedKey:`custom:${d}`}:{options:l,selectedKey:"__home__"}}function eM(e){return e==="ide"?"IDE":"CLI"}function tM(e,t){return[eM(e.kind),e.subtitle||"",e.providerSessionId?t?t("launch.savedHistoryBadge"):"Saved history":""].filter(Boolean).join(" · ")}function nM(e){return e.lastLaunchedAt?wi(e.lastLaunchedAt):""}function Kg(e,t){return{metaText:tM(e,t),updatedLabel:nM(e)}}function Ec(e,t){return e?"ide":t>0?"cli":null}function sM({selectedMachineEntry:e,cliProviders:t,machineAction:s,onBrowseDirectory:r,onListSavedSessions:o}){var ge,Ie,Ke,Ae;const a=Rr(),[i,l]=c.useState(!1),d=(((ge=e.detectedIdes)==null?void 0:ge.length)||0)>0,u=c.useMemo(()=>(e.workspaces||[]).map(Ne=>({id:Ne.id,path:Ne.path,label:Ne.label})),[e]),m=e.defaultWorkspaceId||null,[h,p]=c.useState(m||((Ie=u[0])==null?void 0:Ie.id)||""),[b,f]=c.useState(""),[x,g]=c.useState(""),[w,S]=c.useState([]),[C,j]=c.useState(!1),[v,y]=c.useState(""),[N,k]=c.useState(!1),[A,E]=c.useState(Ec(d,t.length)),P=c.useRef(null),[T,M]=c.useState(null),_=c.useRef("__home__"),[I,D]=c.useState("__home__"),[L,$]=c.useState(""),[U,J]=c.useState(""),[K,R]=c.useState(""),[O,H]=c.useState([]),[B,q]=c.useState(()=>un().textQuery),[W,ce]=c.useState(()=>un().workspaceQuery),[ye,G]=c.useState(()=>un().modelQuery),[Se,ue]=c.useState(()=>un().resumableOnly),[ne,ae]=c.useState(()=>un().sortMode),[ee,oe]=c.useState(!1),[Ce,Q]=c.useState(!1),z=c.useRef(0),X=c.useRef(0),pe=c.useRef(null),Pe=c.useRef(null);c.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&a(e.id,{minFreshMs:3e4}).catch(()=>{})},[a,e]);const Oe=h==="__custom__"?b.trim():((Ke=u.find(Ne=>Ne.id===h))==null?void 0:Ke.path)||"",Le=h==="__custom__"&&!!Oe&&s.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(s.message),ke=h!=="__custom__"&&((Ae=u.find(Ne=>Ne.id===h))==null?void 0:Ae.path)||"",Y=c.useMemo(()=>(e.recentLaunches||[]).map(Ne=>Ne.workspace),[e]),ve=c.useCallback(async Ne=>{const He=z.current+1;z.current=He,j(!0),y("");try{const Fe=await r(Ne);if(z.current!==He)return;g(Fe.path),f(Fe.path),S(Fe.directories)}catch(Fe){if(z.current!==He)return;y(Fe instanceof Error?Fe.message:"Could not load folder")}finally{z.current===He&&j(!1)}},[r]),Z=c.useCallback(()=>{var He;p("__custom__"),k(!0);const Ne=ru(e.platform,su(b.trim(),ke,Y,e.defaultWorkspacePath,(He=u.find(Fe=>Fe.id===m))==null?void 0:He.path,u.map(Fe=>Fe.path)));ve(Ne)},[b,m,ve,Y,ke,e.platform,u]),ie=c.useCallback(Ne=>{if(Ne!=null&&Ne.workspaceId){p(Ne.workspaceId),f("");return}if(Ne!=null&&Ne.workspacePath){p("__custom__"),f(Ne.workspacePath);return}p(""),f("")},[]),F=c.useCallback(Ne=>{if(p(Ne),Ne==="__custom__"){Z();return}f("")},[Z]),se=c.useCallback(Ne=>{p("__custom__"),f(Ne)},[]),me=c.useCallback((Ne,He)=>{const Fe=X.current+1;X.current=Fe,P.current=He,_.current=Ne.selectedWorkspaceKey||"__home__",D(Ne.selectedWorkspaceKey||"__home__"),$(Ne.initialArgs||""),J(Ne.initialModel||""),R(""),H([]);const it=Ne.providerType?`${e.id}:${Ne.providerType}`:null;if(tT(Pe.current,it)){const ut=un();q(ut.textQuery),ce(ut.workspaceQuery),G(ut.modelQuery),ue(ut.resumableOnly),ae(ut.sortMode)}Pe.current=it,M(Ne),Ne.providerType&&o?(oe(!0),o(Ne.providerType).then(ut=>{X.current===Fe&&H(ut||[])}).catch(ut=>{X.current===Fe&&console.warn("Failed to load saved sessions",ut)}).finally(()=>{X.current===Fe&&oe(!1)})):oe(!1)},[o,e.id]),re=c.useMemo(()=>zd(O,{textQuery:B,workspaceQuery:W,modelQuery:ye,resumableOnly:Se,sortMode:ne}),[ye,Se,O,ne,B,W]);c.useEffect(()=>{K&&(re.some(Ne=>Ne.providerSessionId===K)||R(""))},[re,K]);const we=c.useCallback(()=>{P.current&&(Q(!0),P.current().finally(()=>{P.current=null,Q(!1),M(null)}))},[]),V=c.useCallback(()=>{X.current+=1,P.current=null,oe(!1),M(null)},[]),de=c.useCallback(Ne=>{_.current=Ne,D(Ne)},[]);return c.useEffect(()=>{var Ne;pe.current!==e.id&&(z.current+=1,X.current+=1,pe.current=e.id,p(m||((Ne=u[0])==null?void 0:Ne.id)||"__custom__"),f(""),g(""),S([]),j(!1),y(""),k(!1),P.current=null,M(null),H([]),oe(!1),Q(!1),q(un().textQuery),ce(un().workspaceQuery),G(un().modelQuery),ue(un().resumableOnly),ae(un().sortMode),Pe.current=null,E(Ec(d,t.length)))},[t.length,m,d,e.id,u]),c.useEffect(()=>{var Ne;h!=="__custom__"&&(h&&u.some(He=>He.id===h)||p(m||((Ne=u[0])==null?void 0:Ne.id)||"__custom__"))},[m,h,u]),c.useEffect(()=>{A==="ide"&&d||A==="cli"&&t.length>0||E(Ec(d,t.length))},[A,t.length,d]),{showAllRecent:i,setShowAllRecent:l,hasIdeOptions:d,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:h,customWorkspacePath:b,browseCurrentPath:x,browseDirectories:w,browseBusy:C,browseError:v,browseDialogOpen:N,activeLauncherKind:A,launchConfirm:T,launchConfirmWorkspaceKeyRef:_,launchConfirmWorkspaceKey:I,launchConfirmArgs:L,launchConfirmModel:U,launchConfirmResumeId:K,launchConfirmSavedSessions:O,launchConfirmTextFilter:B,launchConfirmWorkspaceFilter:W,launchConfirmModelFilter:ye,launchConfirmResumableOnly:Se,launchConfirmSortMode:ne,filteredLaunchConfirmSavedSessions:re,launchConfirmSessionsLoading:ee,launchConfirmBusy:Ce,resolvedWorkspacePath:Oe,canCreateMissingWorkspace:Le,openBrowseDialog:Z,loadBrowsePath:ve,handleWorkspaceChoiceChange:F,chooseCustomWorkspacePath:se,setCustomWorkspacePath:f,setBrowseDialogOpen:k,setActiveLauncherKind:E,openLaunchConfirm:me,handleConfirmLaunch:we,closeLaunchConfirm:V,setWorkspaceSelectionFromOption:ie,setLaunchConfirmWorkspaceKeyAndSync:de,setLaunchConfirmArgs:$,setLaunchConfirmModel:J,setLaunchConfirmResumeId:R,setLaunchConfirmTextFilter:q,setLaunchConfirmWorkspaceFilter:ce,setLaunchConfirmModelFilter:G,setLaunchConfirmResumableOnly:ue,setLaunchConfirmSortMode:ae}}function rM({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:s,cliProviders:r,selectedMachineNeedsUpgrade:o,appVersion:a,machineAction:i,isStandalone:l,section:d,showBottomNav:u,onBack:m,onSectionChange:h,onOpenConversation:p,onOpenRecent:b,onOpenMachineDetails:f,onMachineUpgrade:x,onBrowseDirectory:g,onListSavedSessions:w}){const{t:S}=he("common"),C=M=>M==="ide"?"IDE":"CLI",j=s.slice(0,4),v=t.slice(0,3),y=sM({selectedMachineEntry:e,cliProviders:r,machineAction:i,onBrowseDirectory:g,onListSavedSessions:w}),N=c.useMemo(()=>j.map(M=>{const{metaText:_,updatedLabel:I}=Kg(M,S);return{key:`recent-launch:${M.id}`,primary:M.label,secondary:_,updatedLabel:I,onClick:()=>{const{options:D,selectedKey:L}=Ug({machine:{workspaces:y.workspaceRows,defaultWorkspaceId:y.defaultWorkspaceId},currentWorkspacePath:M.workspace,homeLabel:S("newSession.homeDirectory"),homeDescription:S("newSession.launchWithoutWorkspace")});y.openLaunchConfirm({title:M.kind==="ide"?Xa(S,"restart-ide",M.label):M.providerSessionId?lg(S,M.label):Xa(S,"start-fresh",M.label),description:M.kind==="ide"?Za(S,"restart-ide"):M.providerSessionId?dg(S):Za(S,"start-fresh"),confirmLabel:M.kind==="ide"?ei(S,"restart-ide"):M.providerSessionId?Bl(S,!0):ei(S,"start-fresh"),busyLabel:M.kind==="ide"?ti(S,"restart-ide"):M.providerSessionId?ig(S,!0):ti(S,"start-fresh"),workspaceOptions:D,selectedWorkspaceKey:L,details:[{label:"Mode",value:C(M.kind)},...M.providerType?[{label:"Provider",value:M.providerType}]:[]]},async()=>{const $=D.find(U=>U.key===y.launchConfirmWorkspaceKeyRef.current);y.setWorkspaceSelectionFromOption($),await b({...M,workspace:($==null?void 0:$.workspacePath)??null})})}}}),[y,b,j,S]),k=c.useMemo(()=>v.map(M=>({key:`recent-chat:${M.conversation.tabKey}`,conversation:M.conversation,primary:kt(M.conversation),secondary:c1(M.conversation,{timestampLabel:M.timestamp?Xp(M.timestamp):null}),unread:M.unread,onClick:()=>p(M.conversation)})),[p,v]),A=y.showAllRecent?N:N.slice(0,4),E=N.length>0,P=k.length>0,T=l?"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 ${T} 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:m,type:"button","aria-label":S("common.back"),children:n.jsx(bi,{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:pn(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||S("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:[P&&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:S("machine.mobile.currentChats")}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:k.map(M=>n.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${M.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:M.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(ws,{conversation:M.conversation,size:13}),n.jsx("span",{className:"min-w-0 truncate",children:M.primary})]}),n.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.key))})]}),E&&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:S("machine.mobile.recentLaunches")}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(M=>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:M.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:M.primary}),M.updatedLabel&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:M.updatedLabel})]}),n.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.key))}),N.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:()=>y.setShowAllRecent(M=>!M),children:y.showAllRecent?S("machine.mobile.showFewer"):S("machine.mobile.showMore",{count:N.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:S("machine.mobile.inspect")}),n.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&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:x,children:n.jsx("span",{className:"text-sm font-bold text-text-primary",children:S("machine.commandCenter.updateToVersion",{version:a})})}),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:f,children:n.jsx("span",{className:"text-sm font-bold text-text-primary",children:S("machine.mobile.machineDetails")})})]})]})]}),y.browseDialogOpen&&n.jsx(iu,{title:S("machine.mobile.browseTitle"),description:S("machine.mobile.browseDescription"),currentPath:y.browseCurrentPath,directories:y.browseDirectories,busy:y.browseBusy,error:y.browseError,confirmLabel:S("machine.mobile.useThisFolder"),onClose:()=>y.setBrowseDialogOpen(!1),onNavigate:M=>{y.loadBrowsePath(M)},onConfirm:M=>{y.chooseCustomWorkspacePath(M),y.setBrowseDialogOpen(!1)}}),y.launchConfirm&&n.jsx(Wi,{title:y.launchConfirm.title,description:y.launchConfirm.description,details:y.launchConfirm.details,workspaceOptions:y.launchConfirm.workspaceOptions,selectedWorkspaceKey:y.launchConfirmWorkspaceKey,onWorkspaceChange:y.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:y.launchConfirm.providerType?Bl(S,!!y.launchConfirmResumeId):y.launchConfirm.confirmLabel,busyLabel:y.launchConfirm.providerType?void 0:y.launchConfirm.busyLabel,busy:y.launchConfirmBusy,showArgsInput:y.launchConfirm.showArgsInput,argsValue:y.launchConfirmArgs,onArgsChange:y.setLaunchConfirmArgs,showModelInput:y.launchConfirm.showModelInput,modelValue:y.launchConfirmModel,onModelChange:y.setLaunchConfirmModel,historyProviderNode:y.launchConfirm.providerType&&(y.launchConfirmSessionsLoading||y.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:S("launch.resumeSavedHistory")}),y.launchConfirmSessionsLoading&&n.jsx("div",{className:"text-3xs text-text-secondary font-medium",children:S("launch.loadingShort")})]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2",children:Vd(S)}),n.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[n.jsx("input",{type:"text",value:y.launchConfirmTextFilter,onChange:M=>y.setLaunchConfirmTextFilter(M.target.value),placeholder:S("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:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),n.jsx("input",{type:"text",value:y.launchConfirmWorkspaceFilter,onChange:M=>y.setLaunchConfirmWorkspaceFilter(M.target.value),placeholder:S("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:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),n.jsx("input",{type:"text",value:y.launchConfirmModelFilter,onChange:M=>y.setLaunchConfirmModelFilter(M.target.value),placeholder:S("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:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),n.jsxs("select",{value:y.launchConfirmSortMode,onChange:M=>y.setLaunchConfirmSortMode(M.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading,children:[n.jsx("option",{value:"recent",children:S("machine.mobile.sortRecent")}),n.jsx("option",{value:"oldest",children:S("machine.mobile.sortOldest")}),n.jsx("option",{value:"messages",children:S("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:y.launchConfirmResumableOnly,onChange:M=>y.setLaunchConfirmResumableOnly(M.target.checked),disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),S("machine.mobile.resumableOnly")]}),n.jsxs("select",{value:y.launchConfirmResumeId,onChange:M=>y.setLaunchConfirmResumeId(M.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading,children:[n.jsx("option",{value:"",children:rT(S)}),y.filteredLaunchConfirmSavedSessions.map(M=>n.jsxs("option",{value:M.providerSessionId,disabled:!M.canResume,children:[M.title||M.providerSessionId," ",M.canResume?"":S("machine.mobile.workspaceMissing")]},M.providerSessionId))]}),!y.launchConfirmSessionsLoading&&y.launchConfirmSavedSessions.length>0&&y.filteredLaunchConfirmSavedSessions.length===0&&n.jsx("div",{className:"mt-2 text-2xs text-text-muted",children:S("machine.mobile.noHistoryMatches")}),y.launchConfirmResumeId&&(()=>{const M=y.filteredLaunchConfirmSavedSessions.find(I=>I.providerSessionId===y.launchConfirmResumeId);if(!M)return null;const _=Wg(M,S);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:_.title}),n.jsx("div",{className:"font-mono break-all mt-0.5",children:_.providerSessionId}),n.jsx("div",{className:"mt-1",children:_.metaLine}),_.updatedLabel&&n.jsx("div",{className:"mt-1 text-text-secondary",children:_.updatedLabel}),_.preview&&n.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:_.preview})]})})()]}),onConfirm:y.handleConfirmLaunch,onCancel:y.closeLaunchConfirm}),u&&n.jsx(Bg,{section:d,onSectionChange:h})]})}const yh=8e3;function oM(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 qg(e,t,s){const r=c.useRef(new Map),[,o]=c.useState(0),a=c.useCallback(()=>o(b=>b+1),[]);c.useEffect(()=>{const b=r.current;if(b.size===0)return;const f=Date.now();let x=!1;for(const[g,w]of b){const S=e.get(g),C=w.muted===void 0||(S?S.muted===w.muted:!1),j=w.hidden===void 0||(S?S.surfaceHidden===w.hidden:!1),v=f-w.at>yh;(C&&j||v)&&(b.delete(g),x=!0)}x&&a()},[e,a]),c.useEffect(()=>{if(r.current.size===0)return;const b=setInterval(()=>{const f=r.current,x=Date.now();let g=!1;for(const[w,S]of f)x-S.at>yh&&(f.delete(w),g=!0);g&&a(),f.size===0&&clearInterval(b)},1e3);return()=>clearInterval(b)});const i=c.useCallback((b,f)=>{const x=r.current.get(b);r.current.set(b,{...x,...f,at:Date.now()}),a()},[a]),l=c.useCallback(b=>{const f=b.sessionId,x=f?r.current.get(f):void 0;return(x==null?void 0:x.muted)!==void 0?x.muted:ys(b,e).muted??!1},[e]),d=c.useCallback(b=>{const f=b.sessionId,x=f?r.current.get(f):void 0;return(x==null?void 0:x.hidden)!==void 0?x.hidden:ys(b,e).surfaceHidden??!1},[e]),u=c.useCallback((b,f)=>{const x=Xn(b),g=b.sessionId;!x||!g||(i(g,f),t(x,"set_conversation_prefs",{sessionId:g,...f,...Mi(b)}).then(w=>{const S=oM(w);S.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",S.reason),r.current.delete(g),a(),s==null||s(`Couldn't update conversation — ${S.reason}`))}).catch(w=>{console.warn("[conversation-prefs] set_conversation_prefs failed",w),r.current.delete(g),a();const S=w instanceof Error?w.message:String(w??"the daemon is unreachable");s==null||s(`Couldn't update conversation — ${S}`)}))},[t,i,a,s]),m=c.useCallback(b=>{u(b,{muted:!l(b)})},[u,l]),h=c.useCallback((b,f)=>{u(b,{hidden:f})},[u]),p=c.useCallback(b=>{u(b,{hidden:!d(b)})},[u,d]);return{isMuted:l,isHidden:d,toggleMute:m,setHidden:h,toggleHidden:p}}function Ia(e){return[...e].sort((t,s)=>{const r=Ub(t.conversation,s.conversation);if(r!==0)return r;const o=s.timestamp-t.timestamp;return o!==0?o:t.conversation.tabKey.localeCompare(s.conversation.tabKey)})}function aM(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:Ia(e)}function iM(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:Ia(s),unreadItems:Ia(r),workingItems:aM(o,t),completedItems:Ia(a)}}function Ui(e,t){if(!t)return!1;const s=e.filter(r=>r.type==="adhdev-daemon"&&zg(r)==="Connected");return s.length===0?!0:s.every(r=>r._sessionListAuthoritative===!0)}function zg(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 cM(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:wo(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 a;const o=So(r)?"cli":"ide";return{id:`${o}:${r.type}:${r.workspace||""}`,label:((a=r.activeChat)==null?void 0:a.title)||So(r)&&r.cliName||r.type,kind:o,providerType:r.type,providerSessionId:r.providerSessionId,subtitle: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 lM(e,t,s=[]){const r=new Map;for(const a of t){const i=Xn(a.conversation),l=r.get(i);l?l.push(a):r.set(i,[a])}const o=new Map;for(const a of s){const i=Xn(a),l=o.get(i);l?l.push(a):o.set(i,[a])}return e.map(a=>{const i=r.get(a.id)||[],l=o.get(a.id)||[],d=[...i].sort((x,g)=>g.timestamp-x.timestamp)[0]||null,u=(d==null?void 0:d.conversation)||null,m=Al(a),h=i.filter(x=>x.unread||x.requiresAction).length,p=i.filter(x=>Us(x.conversation)).length+l.filter(Us).length,b=zg(a),f=[a.platform||"machine",b].filter(Boolean);return{id:a.id,label:pn(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?l1(u,kb(u)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE or CLI session."}}).sort((a,i)=>{const l=a.latestTimestamp||a.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==l?d-l:a.label.localeCompare(i.label)})}function dM(e){return e==="chat"}function aa(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 uM({conversations:e,machineEntries:t,items:s,selectedConversation:r,selectedTabKey:o,screen:a,liveSessionInboxState:i,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:b,setSelectedTabKey:f,setScreen:x,setSelectedMachineId:g,setSection:w,setMachineBackTarget:S,resetMachineAction:C}){const j=c.useRef(null),v=c.useCallback(y=>{if(!(y!=null&&y.sessionId))return;const N=ys(y,i),k=Math.max(Date.now(),Hs(y),N.lastUpdated||0);aa("mark_read:start",{tabKey:y.tabKey,sessionId:y.sessionId,displayPrimary:kt(y),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Hs(y),readAt:k}),l(Xn(y)||y.routeId,"mark_session_seen",{sessionId:y.sessionId,providerSessionId:y.providerSessionId,seenAt:k,completionMarker:N.completionMarker}).then(A=>{aa("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:A})}).catch(A=>{aa("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,l]);return c.useEffect(()=>{var N;if(!r){dM(a)&&x("inbox"),f(((N=e[0])==null?void 0:N.tabKey)||null),j.current=null;return}if(a!=="chat"){j.current=null;return}const y=`${r.tabKey}:${r.sessionId||""}`;j.current!==y&&(j.current=y,v(r))},[e,v,a,r,x,f]),c.useEffect(()=>{if(!d)return;const y=e.find(N=>N.tabKey===d);y&&(f(y.tabKey),x("chat"),u==null||u())},[e,u,d,x,f]),c.useEffect(()=>{if(!m)return;const y=t.find(N=>N.id===m);y&&(g(y.id),C(),w("machines"),S("inbox"),x("machine"),h==null||h())},[t,h,m,C,S,x,w,g]),c.useEffect(()=>{p&&(w(p),x("inbox"),b==null||b())},[b,p,x,w]),c.useEffect(()=>{const y=s.filter(N=>N.inboxBucket==="task_complete"||N.unread);y.length!==0&&aa("inbox_state",{screen:a,selectedTabKey:o,items:y.map(N=>{const k=ys(N.conversation,i);return{liveState:k,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:kt(N.conversation),serverBucket:k.inboxBucket,computedBucket:N.inboxBucket,serverUnread:k.unread,computedUnread:N.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:Hs(N.conversation)}})})},[s,i,a,o]),{markConversationRead:v}}const mM="Cannot update: node update policy unavailable; refresh and try again";async function hM(e,t,s){var o,a,i,l,d,u;const r=tu(s);if(!r)return{state:"error",message:mM};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||(l=m==null?void 0:m.result)!=null&&l.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 pM(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function vh(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function fM(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function bM({sendDaemonCommand:e,navigate:t,ides:s,conversations:r}){const{launchCli:o}=vi(),[a,i]=c.useState("idle"),[l,d]=c.useState(""),[u,m]=c.useState(null),h=c.useCallback(()=>{i("idle"),d(""),m(null)},[]),p=c.useCallback(async(C,j,v)=>{var y;try{i("loading"),d(`Launching ${j}…`);const N={ideType:j,enableCdp:!0};(y=v==null?void 0:v.workspacePath)!=null&&y.trim()&&(N.workspace=v.workspacePath.trim()),await e(C,"launch_ide",N),i("done"),d(`${j} launch requested`)}catch(N){i("error"),d(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),b=c.useCallback(async(C,j,v)=>{if(j.trim())try{i("loading"),d(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(C,"workspace_add",{path:j.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(y!=null&&y.success){i("done"),d(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),d(y instanceof Error?y.message:"Could not save workspace")}},[e]),f=c.useCallback(async C=>{i("loading"),d("Starting daemon upgrade…");const j=s.find(y=>y.id===C||y.daemonId===C),v=await hM(e,C,j);i(v.state),d(v.message)},[s,e]),x=c.useCallback(async(C,j,v,y)=>{var A,E,P;const N=Date.now(),k={machineId:C,kind:j,providerType:v,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:N};try{i("loading"),d(`Launching ${v}…`),m(k);const T={cliType:v};(A=y==null?void 0:y.workspacePath)!=null&&A.trim()?T.dir=y.workspacePath.trim():y!=null&&y.workspaceId?T.workspaceId=y.workspaceId:y!=null&&y.useHome&&(T.useHome=!0),y!=null&&y.resumeSessionId&&(T.resumeSessionId=y.resumeSessionId),(E=y==null?void 0:y.args)!=null&&E.trim()&&(T.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(P=y==null?void 0:y.model)!=null&&P.trim()&&(T.initialModel=y.model.trim());const M=await o(C,T),_=(M==null?void 0:M.result)||M,I=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(M!=null&&M.success&&I){m(null),i("done"),d(`${v} launched`),t(ko(I));return}if(M!=null&&M.success){i("loading"),d(`${v} launch requested — waiting for session…`);return}m(null),i("error"),d((M==null?void 0:M.error)||(_==null?void 0:_.error)||`Could not launch ${j.toUpperCase()} workspace`)}catch(T){if(fM(T)){i("loading"),d(`${v} launch requested — waiting for session…`);return}m(null),i("error"),d(T instanceof Error?T.message:`Could not launch ${j.toUpperCase()} workspace`)}},[t,e]),g=c.useCallback(async(C,j)=>{try{const v=await e(C,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),y=(v==null?void 0:v.result)??v;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),w=c.useCallback(async(C,j)=>ou(e,C,j),[e]);c.useEffect(()=>{if(!u)return;const C=vh(u.workspacePath),j=s.find(y=>{var T,M,_,I;if(!y||y.type==="adhdev-daemon"||pM(y.daemonId||y.id)!==u.machineId||(y.transport==="pty"?"cli":null)!==u.kind||String(y.agentType||y.type||"")!==u.providerType)return!1;const E=String(y.providerSessionId||"");if(u.resumeSessionId&&E)return E===u.resumeSessionId;if(C){const D=vh(y.workspace||y.runtimeWorkspaceLabel);return D?D===C:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((I=(_=(M=(T=y.activeChat)==null?void 0:T.messages)==null?void 0:M.at)==null?void 0:_.call(M,-1))==null?void 0:I.timestamp)||0)>=u.startedAt-5e3});if(!j)return;const v=$g({entrySessionId:j.sessionId,entryInstanceId:j.instanceId,entryRouteId:j.id,conversations:r});v&&(m(null),i("done"),d(`${u.providerType} launched`),t(ko(v)))},[r,s,t,u]),c.useEffect(()=>{if(!u)return;const C=window.setTimeout(()=>{m(j=>!j||j.startedAt!==u.startedAt?j:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(C)},[u]);const S=c.useCallback(async(C,j)=>{var v;if(j.kind==="ide"&&j.providerType){await p(C,j.providerType,{workspacePath:j.workspace||null});return}if(j.kind==="cli"&&j.providerType){const y=((v=j.workspace)==null?void 0:v.trim())||"";await x(C,j.kind,j.providerType,{workspacePath:y||null,useHome:!y,resumeSessionId:j.providerSessionId||null})}},[p,x]);return{machineAction:{state:a,message:l},resetMachineAction:h,handleLaunchDetectedIde:p,handleAddWorkspace:b,handleMachineUpgrade:f,handleLaunchWorkspaceProvider:x,handleListSavedSessions:g,handleBrowseDirectory:w,handleOpenRecent:S}}function gM({conversations:e,selectedConversation:t,machineBackTarget:s,markConversationRead:r,resetMachineAction:o,setSelectedTabKey:a,setScreen:i,setSelectedMachineId:l,setSection:d,setMachineBackTarget:u}){const m=c.useCallback(w=>{a(w.tabKey),i("chat"),r(w)},[r,i,a]),h=c.useCallback(w=>{const S=e.find(C=>C.routeId===w.routeId&&C.streamSource==="native");S&&(a(S.tabKey),i("chat"),r(S))},[e,r,i,a]),p=c.useCallback(()=>{r(t),i("inbox")},[r,t,i]),b=c.useCallback((w,S="inbox")=>{l(w),o(),d("machines"),u(S),i("machine")},[o,u,i,d,l]),f=c.useCallback(w=>{const S=Xn(w);S&&b(S,"chat")},[b]),x=c.useCallback(()=>{o(),i(s)},[s,o,i]),g=c.useCallback(w=>{d(w),i("inbox")},[i,d]);return{openConversation:m,openNativeConversation:h,backFromConversation:p,openMachine:b,openConversationMachine:f,backFromMachine:x,changeMachineSection:g}}function xM(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function yM({conversations:e,hiddenConversations:t,ides:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:b,onOpenHistory:f,onOpenRemote:x,onStopCli:g,wsStatus:w,isConnected:S,initialDataLoaded:C=!0,onShowAllHiddenConversations:j,onHideConversation:v,onShowHiddenConversation:y,onOpenMeshGraph:N,onOpenNewSession:k,liveSessionInboxState:A,setCliViewModeOverrides:E}){const[P,T]=c.useState(()=>{var ie;return((ie=e[0])==null?void 0:ie.tabKey)||null}),[M,_]=c.useState(()=>e[0]?"chat":"inbox"),[I,D]=c.useState("chats"),[L,$]=c.useState(null),[U,J]=c.useState("inbox"),K=c.useRef([]),R=Gs(),O="1.0.75",H=c.useMemo(()=>e.find(ie=>ie.tabKey===P)||e[0]||null,[e,P]),B=c.useMemo(()=>H?s.find(ie=>ie.id===H.routeId):void 0,[s,H]),q=c.useMemo(()=>!H||!ft(H)?null:Mr(H),[H]),W=c.useMemo(()=>s.filter(ie=>ie.type==="adhdev-daemon").sort(Wa),[s]),ce=c.useMemo(()=>W.find(ie=>ie.id===L)||null,[W,L]),ye=Pi({sendDaemonCommand:o,activeConv:H||void 0,setActionLogs:a,isStandalone:i}),G=bM({sendDaemonCommand:o,navigate:R,ides:s,conversations:e}),Se=g_(e),ue=c.useMemo(()=>e.map(ie=>{const F=M==="chat"&&(H==null?void 0:H.tabKey)===ie.tabKey,se=ji(ie,A,{hideOpenTaskCompleteUnread:!0,isOpenConversation:F}),me=Hs(ie),re=kb(ie),we=Pb(ie,re);return{conversation:ie,timestamp:me,preview:we,unread:se.unread,requiresAction:se.requiresAction,isWorking:se.isWorking,inboxBucket:se.inboxBucket}}),[e,A,M,H,Se]),{markConversationRead:ne}=uM({conversations:e,machineEntries:W,items:ue,selectedConversation:H,selectedTabKey:P,screen:M,liveSessionInboxState:A,sendDaemonCommand:o,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:b,setSelectedTabKey:T,setScreen:_,setSelectedMachineId:$,setSection:D,setMachineBackTarget:J,resetMachineAction:G.resetMachineAction}),ae=gM({conversations:e,selectedConversation:H,machineBackTarget:U,markConversationRead:ne,resetMachineAction:G.resetMachineAction,setSelectedTabKey:T,setScreen:_,setSelectedMachineId:$,setSection:D,setMachineBackTarget:J}),{isMuted:ee,toggleMute:oe}=qg(A,o),{attentionItems:Ce,unreadItems:Q,workingItems:z,completedItems:X}=c.useMemo(()=>iM(ue,K.current),[ue]);c.useEffect(()=>{K.current=z.map(ie=>ie.conversation.tabKey)},[z]);const pe=c.useMemo(()=>ce?ue.filter(ie=>Xn(ie.conversation)===ce.id):[],[ue,ce]),Pe=c.useMemo(()=>cM(ce,s),[s,ce]),Oe=!!ce&&nu(ce,Rs(ce,O)),Le=c.useMemo(()=>(ce==null?void 0:ce.availableProviders)||[],[ce]),ke=c.useMemo(()=>Le.filter(ie=>Ei(ie,"cli")).map(ie=>({type:ie.type,displayName:ie.displayName||ie.type,icon:ie.icon})),[Le]),Y=c.useMemo(()=>lM(W,ue,t),[ue,W,t]),ve=c.useMemo(()=>Ui(s,C),[s,C]),Z=c.useCallback(async ie=>{ce&&await G.handleOpenRecent(ce.id,ie)},[G,ce]);return n.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&H?n.jsx(YI,{selectedConversation:H,isStandalone:i,selectedIdeEntry:B,actionLogs:r,userName:l,commands:ye,onBack:ae.backFromConversation,onOpenNativeConversation:ae.openNativeConversation,onOpenMachine:ae.openConversationMachine,onOpenHistory:f,onOpenRemote:x,onOpenMeshGraph:N,onStopCli:g,cliViewMode:q,onSetCliViewMode:async ie=>{await _g({conversation:H,mode:ie,ides:s,sendDaemonCommand:o,setCliViewModeOverrides:E})}}):M==="machine"&&ce?n.jsx(rM,{selectedMachineEntry:ce,selectedMachineConversations:pe,selectedMachineRecentLaunches:Pe,cliProviders:ke,selectedMachineNeedsUpgrade:Oe,appVersion:O,machineAction:G.machineAction,isStandalone:i,section:I,showBottomNav:U==="inbox",onBack:ae.backFromMachine,onSectionChange:ae.changeMachineSection,onOpenConversation:ae.openConversation,onOpenRecent:Z,onOpenMachineDetails:()=>R(`/machines/${ce.id}`),onMachineUpgrade:()=>G.handleMachineUpgrade(ce.id),onBrowseDirectory:ie=>G.handleBrowseDirectory(ce.id,ie),onListSavedSessions:ie=>G.handleListSavedSessions(ce.id,ie)}):n.jsx(XI,{section:I,attentionItems:Ce,unreadItems:Q,workingItems:z,completedItems:X,hiddenConversations:t,machineCards:Y,getAvatarText:xM,actionLogs:r,sendDaemonCommand:o,onOpenConversation:ae.openConversation,onShowAllHidden:j,onHideConversation:v,onShowHiddenConversation:y,onOpenMeshGraph:N,onStopCli:g,onOpenNewSession:k,onOpenMachine:ae.openMachine,onOpenSettings:()=>R("/settings"),onSectionChange:D,wsStatus:w,isConnected:S,initialDataLoaded:C,conversationsLoaded:ve,isStandalone:i,isConversationMuted:ee,onToggleMuteConversation:oe})})}function Lc(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function vM({conversations:e,numGroups:t,onMoveTab:s,onReceiveTab:r,onOwnTabDrop:o,onClearPreviewOrder:a}){const i=c.useRef(0),[l,d]=c.useState(!1),[u,m]=c.useState(null),h=c.useCallback(()=>{i.current=0,d(!1),m(null)},[]);c.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const p=c.useCallback(g=>{g.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),b=c.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!Lc(t,s)){m("merge");return}const w=g.currentTarget.getBoundingClientRect(),S=g.clientX-w.left,C=w.width/3;S<C?m("split-left"):S>C*2?m("split-right"):m("merge")},[t,s]),f=c.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),m(null))},[]),x=c.useCallback(g=>{i.current=0,d(!1);const w=g.dataTransfer.getData("text/tab-key"),S=w?e.some(j=>j.tabKey===w):!1,C=u;if(m(null),a(),!!w){if(g.preventDefault(),C==="split-left"&&Lc(t,s)){s==null||s(w,"split-left");return}if(C==="split-right"&&Lc(t,s)){s==null||s(w,"split-right");return}if(S){o(w);return}r==null||r(w)}},[e,u,t,s,r,o,a]);return{dragOver:l,dropAction:u,resetDragState:h,handleDragEnter:p,handleDragOver:b,handleDragLeave:f,handleDrop:x}}function wM(e,t){const s=new Set(t.map(l=>l.tabKey)),r=e.filter(l=>s.has(l)),o=t.filter(l=>!e.includes(l.tabKey)),a=o.filter(qs).map(l=>l.tabKey),i=o.filter(l=>!qs(l)).map(l=>l.tabKey);return[...a,...r,...i]}function SM({conversations:e,initialActiveTabId:t,initialTabOrder:s,onActiveTabChange:r,onTabOrderChange:o}){const[a,i]=c.useState(t??null),[l,d]=c.useState(s??[]),[u,m]=c.useState(null),h=c.useRef(null),p=c.useRef(null),b=c.useRef(r),f=c.useRef(o);c.useEffect(()=>{b.current=r},[r]),c.useEffect(()=>{f.current=o},[o]),c.useEffect(()=>{t&&t!==a&&i(t)},[t,a]),c.useEffect(()=>{d(N=>{const k=wM(N,e);return k.length===N.length&&k.every((A,E)=>A===N[E])?N:k})},[e]);const x=c.useMemo(()=>{const N=u??l;if(N.length===0)return e;const k=new Map(N.map((A,E)=>[A,E]));return[...e].sort((A,E)=>{const P=k.get(A.tabKey)??999,T=k.get(E.tabKey)??999;return P-T})},[e,u,l]);c.useEffect(()=>{var k,A;if(x.length===0){a!==null&&(i(null),(k=b.current)==null||k.call(b,null));return}if(a&&x.some(E=>E.tabKey===a))return;const N=x[0].tabKey;N!==a&&(i(N),(A=b.current)==null||A.call(b,N))},[x,a]);const g=c.useMemo(()=>x.find(N=>N.tabKey===a),[x,a]),w=c.useCallback(N=>{var k;i(N),(k=b.current)==null||k.call(b,N)},[]),S=c.useCallback((N,k,A)=>{d(E=>{var _;const P=E.filter(I=>I!==N),T=P.indexOf(k);if(T<0)return E;const M=A==="left"?T:T+1;return P.splice(M,0,N),(_=f.current)==null||_.call(f,P),P}),m(null)},[]),C=c.useCallback((N,k,A)=>{const P=(l.length>0?l:e.map(_=>_.tabKey)).filter(_=>_!==N),T=P.indexOf(k);if(T<0)return;const M=A==="left"?T:T+1;P.splice(M,0,N),h.current=P,m(P)},[l,e]),j=c.useCallback(()=>{var k;const N=h.current;N&&(d(N),(k=f.current)==null||k.call(f,N))},[]),v=c.useCallback(()=>{h.current=null,m(null)},[]),y=c.useCallback(N=>{d(k=>{var E;const A=k.filter(P=>P!==N);return A.push(N),(E=f.current)==null||E.call(f,A),A})},[]);return{activeTabId:a,activeConv:g,sortedConversations:x,previewOrderRef:h,draggingTabRef:p,selectTab:w,handleTabReorder:S,updatePreviewOrder:C,commitPreviewOrder:j,clearPreviewOrder:v,moveTabToEnd:y,setDraggingTabKey:N=>{p.current=N}}}function kM({dropAction:e,canSplit:t}){const{t:s}=he("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 cu({conversationsCount:e,isSplitMode:t,isStandalone:s,hasRegisteredMachines:r=!1,suppressGuide:o=!1,onOpenNewSession:a,isLoading:i=!1}){const{t:l}=he("common");if(o)return n.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:l("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(tn,{}),n.jsx("p",{className:"text-sm",children:l("paneGroup.loadingSessions")})]});const d=!s&&!r,u=r&&!!a,m=l(r?"paneGroup.noConversations":s?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),h=l(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:l("paneGroup.newSession"),"aria-label":l("paneGroup.newSession"),children:[n.jsx(go,{size:14}),n.jsx("span",{children:l("paneGroup.newSession")})]})}),d&&n.jsx(Hg,{}),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:l("machine.card.emptyDocsLink")})})]})]}):n.jsx("div",{className:"text-sm text-text-muted opacity-50",children:l(t?"paneGroup.moveTabHere":"paneGroup.noActiveAgent")})}const Vg="adhdev-tab-shortcuts";function Gg(){try{return JSON.parse(localStorage.getItem(Vg)||"{}")}catch{return{}}}function Yg({enabled:e=!0,sortedTabKeys:t,onFocus:s,onSelectTab:r}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[a,i]=c.useState(()=>Gg()),[l,d]=c.useState(null),u=c.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=c.useCallback(h=>{i(h);try{localStorage.setItem(Vg,JSON.stringify(h))}catch{}},[]);return c.useEffect(()=>{if(!e||!l)return;const h=p=>{if(p.preventDefault(),p.stopPropagation(),p.key==="Escape"){d(null);return}const b=u(p);if(!b)return;const f={...a};for(const[x,g]of Object.entries(f))g===b&&delete f[x];f[l]=b,m(f),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,a,m,u]),c.useEffect(()=>{if(!e)return;const h=p=>{if(!(!p.ctrlKey&&!p.metaKey&&!p.altKey)){for(const[b,f]of Object.entries(a))if(t.includes(b)&&u(p)===f){p.preventDefault(),s(),r(b);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,a,t,s,r,u]),{isMac:o,tabShortcuts:a,shortcutListening:l,setShortcutListening:d,saveShortcuts:m}}const Dc=e=>{e.preventDefault()},jM=c.memo(function({conv:t,isActive:s,isDraggedTab:r,isTaskCompleteUnread:o,shortcut:a,conversationKeys:i,draggingTabRef:l,onFocus:d,onSelectTab:u,onConversationActivated:m,onPreviewReorder:h,onReorderTab:p,onCommitPreviewOrder:b,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:g,onReceiveTab:w,onOpenContextMenu:S,longPressTimer:C,isGroupActive:j}){const v=Ss(t),y=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",N=v.isReconnecting,k=Kd(t),A=c.useCallback($=>{l.current=t.tabKey,g(t.tabKey),$.dataTransfer.setData("text/tab-key",t.tabKey),$.dataTransfer.effectAllowed="move"},[t.tabKey,l,g]),E=c.useCallback(()=>{l.current=null,g(null),b(),f(),x()},[l,g,b,f,x]),P=c.useCallback($=>{const U=l.current;if(!(!U||U===t.tabKey)&&$.dataTransfer.types.includes("text/tab-key")){$.preventDefault(),$.stopPropagation();const J=$.currentTarget.getBoundingClientRect(),K=$.clientX<J.left+J.width/2?"left":"right";h(U,t.tabKey,K)}},[t.tabKey,l,h]),T=c.useCallback($=>{$.preventDefault(),$.stopPropagation();const U=$.dataTransfer.getData("text/tab-key");if(U&&U!==t.tabKey){const J=$.currentTarget.getBoundingClientRect(),K=$.clientX<J.left+J.width/2?"left":"right";i.includes(U)?p(U,t.tabKey,K):w&&w(U)}f()},[t.tabKey,i,p,w,f]),M=c.useCallback($=>{$.stopPropagation(),d(),u(t.tabKey),m(t)},[t,m,d,u]),_=c.useCallback($=>{$.preventDefault(),S($.clientX,$.clientY,t.tabKey)},[t.tabKey,S]),I=c.useCallback($=>{const U=$.touches[0];C.current=setTimeout(()=>{S(U.clientX,U.clientY,t.tabKey)},600)},[t.tabKey,C,S]),D=c.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),L=["adhdev-dockview-tab",y,s&&"is-active",j&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return n.jsxs("div",{"data-tabkey":t.tabKey,className:L,draggable:!0,onDragStart:A,onDragEnd:E,onDragOver:P,onDrop:T,onClick:M,onContextMenu:_,onTouchStart:I,onTouchEnd:D,onTouchMove:D,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:v.isGenerating?n.jsx(tn,{size:12,thickness:2,color:"success"}):v.isWaiting?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?n.jsx(tn,{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(ws,{conversation:t,size:12}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("span",{className:"adhdev-dockview-tab-primary",title:k?`${kt(t)} · ${k}`:kt(t),children:kt(t)}),n.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Os(t)}):v.isConnecting?n.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Os(t),n.jsx("span",{className:"connecting-dots"})]}):n.jsx("span",{className:"truncate",children:Os(t)}),n.jsx(Od,{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 NM({conversations:e,activeTabId:t,groupIndex:s,unreadTabKeys:r,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:l,onPreviewReorder:d,onReorderTab:u,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:b,onReceiveTab:f,onHideTab:x,isGroupActive:g,allowTabShortcuts:w=!0}){const{t:S}=he("common"),[C,j]=c.useState(null),v=c.useRef(null),y=c.useRef(null),N=c.useMemo(()=>e.map(_=>_.tabKey),[e]);Io("PaneGroupTabBar",{groupIndex:s,activeTabId:t,tabCount:e.length,ctxMenuTab:(C==null?void 0:C.tabKey)||null});const{isMac:k,tabShortcuts:A,shortcutListening:E,setShortcutListening:P,saveShortcuts:T}=Yg({enabled:w,sortedTabKeys:e.map(_=>_.tabKey),onFocus:a,onSelectTab:i});c.useEffect(()=>{if(!C)return;const _=I=>{const D=document.querySelector("[data-pane-context-menu]");D&&D.contains(I.target)||j(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[C]),c.useEffect(()=>{const _=y.current;if(!_)return;const I=D=>{Math.abs(D.deltaY)<=Math.abs(D.deltaX)||(D.preventDefault(),_.scrollLeft+=D.deltaY)};return _.addEventListener("wheel",I,{passive:!1}),()=>_.removeEventListener("wheel",I)},[]);const M=c.useCallback((_,I,D)=>{j({x:_,y:I,tabKey:D})},[]);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:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(_=>n.jsx(jM,{conv:_,isActive:t===_.tabKey,isDraggedTab:o.current===_.tabKey,isTaskCompleteUnread:r.has(_.tabKey),shortcut:w?A[_.tabKey]:void 0,conversationKeys:N,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:l,onPreviewReorder:d,onReorderTab:u,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:b,onReceiveTab:f,onOpenContextMenu:M,longPressTimer:v,isGroupActive:g},_.tabKey)),e.length===0&&n.jsx("div",{className:"p-2 text-xs opacity-40",children:S("paneGroup.noTabsInGroup")})]})}),C&&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:C.x,top:C.y},children:[w&&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:Dc,onClick:_=>{_.stopPropagation(),P(C.tabKey),j(null)},children:["⌨ ",A[C.tabKey]?S("paneGroup.changeShortcut",{shortcut:A[C.tabKey]}):S("paneGroup.shortcutSetTitle")]}),A[C.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:Dc,onClick:()=>{const _={...A};delete _[C.tabKey],T(_),j(null)},children:["✕ ",S("paneGroup.removeShortcut")]})]}),x&&n.jsxs(n.Fragment,{children:[w&&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:Dc,onClick:()=>{x(C.tabKey),j(null)},children:n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(gi,{size:12}),S("paneGroup.hideFromDashboard")]})})]})]}),w&&E&&n.jsx(Un,{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:()=>P(null),children:n.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:_=>_.stopPropagation(),children:[n.jsxs("div",{className:"text-sm font-bold text-text-primary mb-2",children:["⌨ ",S("paneGroup.shortcutSetTitle")]}),n.jsx("div",{className:"text-xs text-text-secondary mb-4",children:S("paneGroup.shortcutPressCombo",{example1:k?"⌘+1":"Ctrl+1",example2:k?"⌥+A":"Alt+A"})}),n.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:S("paneGroup.shortcutListening")}),n.jsx("div",{className:"text-3xs text-text-muted mt-3",children:S("paneGroup.pressEscToCancel")})]})})})]})}function CM({conversations:e,ides:t,clearedTabs:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:l,initialDataLoaded:d=!0,userName:u,groupIndex:m,onFocus:h,isSplitMode:p,numGroups:b,onMoveTab:f,onReceiveTab:x,style:g,onActiveTabChange:w,initialActiveTabId:S,initialTabOrder:C,onTabOrderChange:j,onHideTab:v,isFocused:y,allowTabShortcuts:N=!0,onOpenNewSession:k,liveSessionInboxState:A}){const{sendCommand:E}=wt(),P=c.useRef(null),{activeTabId:T,activeConv:M,sortedConversations:_,draggingTabRef:I,selectTab:D,handleTabReorder:L,updatePreviewOrder:$,commitPreviewOrder:U,clearPreviewOrder:J,moveTabToEnd:K,setDraggingTabKey:R}=SM({conversations:e,initialActiveTabId:S,initialTabOrder:C,onActiveTabChange:w,onTabOrderChange:j}),O=Pi({sendDaemonCommand:o,activeConv:M,setActionLogs:a,isStandalone:i}),{dragOver:H,dropAction:B,resetDragState:q,handleDragEnter:W,handleDragOver:ce,handleDragLeave:ye,handleDrop:G}=vM({conversations:e,numGroups:b,onMoveTab:f,onReceiveTab:x,onOwnTabDrop:K,onClearPreviewOrder:J}),Se=M&&Mr(M)==="terminal",ue=c.useMemo(()=>M?t.find(oe=>oe.id===M.routeId):void 0,[t,M]),ne=c.useMemo(()=>M?r.filter(oe=>oe.routeId===M.tabKey):[],[r,M]),ae=c.useMemo(()=>new Set(_.filter(oe=>Ek(oe,A,{isOpenConversation:oe.tabKey===T})).map(oe=>oe.tabKey)),[T,A,_]);Io("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:T,dragOver:H});const ee=c.useCallback(oe=>{oe.streamSource==="agent-stream"&&oe.agentType&&E(oe.routeId,ib(),{agentType:oe.agentType,...oe.sessionId&&{targetSessionId:oe.sessionId}}).catch(()=>{})},[E]);return n.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...g,outline:H?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[n.jsx(NM,{conversations:_,activeTabId:T,groupIndex:m,numGroups:b,unreadTabKeys:ae,draggingTabRef:I,onFocus:h,onSelectTab:D,onConversationActivated:ee,onPreviewReorder:$,onReorderTab:L,onCommitPreviewOrder:U,onClearPreviewOrder:J,onDragStateReset:q,onDragTabKeyChange:R,onMoveTab:f,onReceiveTab:x,onHideTab:v,isGroupActive:y??!1,allowTabShortcuts:N}),n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:W,onDragOver:ce,onDragLeave:ye,onDrop:G,children:[H&&n.jsx(kM,{dropAction:B,canSplit:!!(b<4&&f)}),M?n.jsx(au,{activeConv:M,clearToken:s[M.tabKey]||0,isCliTerminal:!!Se,ideEntry:ue,terminalRef:P,commands:O,actionLogs:ne,userName:u,isInputActive:!p||!!y}):n.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:n.jsx(cu,{conversationsCount:e.length,isSplitMode:p,isStandalone:i,hasRegisteredMachines:l,onOpenNewSession:k,isLoading:!Ui(t,d)})})]})]})}function _M({containerRef:e,isSplitMode:t,numGroups:s,groupSizes:r,groupedConvs:o,clearedTabs:a,ides:i,actionLogs:l,sendDaemonCommand:d,setActionLogs:u,isStandalone:m,hasRegisteredMachines:h,initialDataLoaded:p,userName:b,focusedGroup:f,focusGroup:x,moveTabToGroup:g,splitTabRelative:w,closeGroup:S,handleResizeStart:C,groupActiveTabIds:j,setGroupActiveTab:v,groupTabOrders:y,setGroupTabOrder:N,toggleHiddenTab:k,onOpenNewSession:A,allowTabShortcuts:E=!0,liveSessionInboxState:P}){const{t:T}=he("common");return n.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:o.map((M,_)=>{const I=t&&r.length===s?`${r[_]}%`:void 0;return n.jsxs(yt.Fragment,{children:[t&&_>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:D=>C(_-1,D),onDoubleClick:()=>S(_),title:T("paneGroup.resizeHandleHint"),children:n.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),n.jsx(CM,{style:t?{flexBasis:I??`${100/s}%`,flexGrow:I?0:1,flexShrink:I?0:1}:void 0,conversations:M,clearedTabs:a,ides:i,actionLogs:l,sendDaemonCommand:d,setActionLogs:u,isStandalone:m,hasRegisteredMachines:h,initialDataLoaded:p,userName:b,groupIndex:_,isFocused:t&&f===_,onFocus:()=>x(_),isSplitMode:t,numGroups:s,onMoveTab:(D,L)=>{L==="left"&&_>0?g(D,_-1):L==="right"&&_<s-1?g(D,_+1):L==="split-left"&&s<4?w(D,_,"left"):L==="split-right"&&s<4&&w(D,_,"right")},onReceiveTab:D=>g(D,_),onActiveTabChange:D=>v(_,D),initialActiveTabId:j[_],initialTabOrder:y[_],onTabOrderChange:D=>N(_,D),onHideTab:k,onOpenNewSession:A,allowTabShortcuts:E,liveSessionInboxState:P})]},_)})})}const Qg="adhdev-dashboard-action-shortcuts",AM=1200,TM=[["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 IM(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function pt(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 Jg(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:pt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:pt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:pt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:pt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:pt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:pt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:pt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:pt("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:pt("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:pt("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:pt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:pt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:pt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:pt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:pt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:pt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:pt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:pt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:pt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:pt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:pt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:pt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:pt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:pt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:pt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:pt("toggleCliView",e)}]}function lu(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function oi(e){const t=Object.fromEntries(Jg(e).map(s=>[s.id,s.defaultShortcut]));try{const s=JSON.parse(localStorage.getItem(Qg)||"{}"),r={...t,...s};for(const[o,a]of TM)r[o]===a&&(r[o]=t[o]);return r}catch{return t}}function Xg(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function MM({enabled:e=!0,onTrigger:t}){const s=IM(),[r,o]=c.useState(()=>oi(s)),[a,i]=c.useState(null),[l,d]=c.useState([]),u=c.useRef({parts:[],timer:null}),m=c.useCallback(x=>{const g=[];return x.metaKey&&g.push(s?"⌘":"Meta"),x.ctrlKey&&g.push("Ctrl"),x.altKey&&g.push(s?"⌥":"Alt"),x.shiftKey&&x.key.length!==1&&g.push(s?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(g.push(Xg(x.key)),g.join("+"))},[s]),h=c.useCallback(x=>{o(x);try{localStorage.setItem(Qg,JSON.stringify(x))}catch{}},[]);c.useEffect(()=>{const x=oi(s),g=Object.entries(r),w=Object.entries(x);g.length===w.length&&g.every(([S,C])=>x[S]===C)||h(x)},[r,s,h]);const p=c.useCallback(()=>{typeof window<"u"&&u.current.timer!=null&&window.clearTimeout(u.current.timer),u.current={parts:[],timer:null}},[]),b=c.useCallback(()=>{typeof window>"u"||(u.current.timer!=null&&window.clearTimeout(u.current.timer),u.current.timer=window.setTimeout(()=>{u.current={parts:[],timer:null}},AM))},[]);c.useEffect(()=>{if(!a)return;const x=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){i(null),d([]);return}const w=m(g);if(!w)return;const C=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(w);if(l.length===0&&C){d([w]);return}const v=[...l,w].slice(0,2).join(" "),y={...r};for(const[N,k]of Object.entries(y))k===v&&delete y[N];y[a]=v,h(y),i(null),d([])};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[r,m,h,a,l]),c.useEffect(()=>{if(!e||a)return;const x=g=>{if(g.defaultPrevented)return;const w=m(g);if(!w)return;const S=g.metaKey||g.ctrlKey||g.altKey;if(lu(g.target))return;const C=u.current.parts,j=S?[w]:[...C.slice(-1),w].slice(-2),v=j.join(" "),y=j[j.length-1],N=Object.entries(r).filter(([,T])=>!!T),k=N.find(([,T])=>T===v);if(k){g.preventDefault(),p(),t(k[0]);return}if(N.some(([,T])=>T.startsWith(`${v} `))){g.preventDefault(),u.current.parts=j,b();return}const E=N.find(([,T])=>T===y);if(E){g.preventDefault(),p(),t(E[0]);return}if(N.some(([,T])=>T.startsWith(`${y} `))){g.preventDefault(),u.current.parts=[y],b();return}p()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[r,b,e,m,t,p,a]),c.useEffect(()=>()=>p(),[p]);const f=c.useMemo(()=>Jg(s),[s]);return{isMac:s,actionDefinitions:f,actionShortcuts:r,shortcutListening:a,shortcutListeningDraft:l,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:h}}function RM({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 Zg(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function wh({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:s,ides:r}){return!e||s>0?!1:t?!Zg(r):!0}function PM({previousVisibleConversationCount:e,visibleConversationCount:t,ides:s}){return t>0||e<=0?!1:Zg(s)}const ex=2e4;function EM(e,t,s,r=Date.now()){const o=new Set(t),a=e.filter(i=>!s(i)&&!o.has(i));return a.length>0?{ids:new Set(a),deadline:r+ex}:null}function LM(e,t,s=Date.now()){const r=e.current;if(!r)return null;for(const o of t)r.ids.delete(o);return r.ids.size===0||s>=r.deadline?(e.current=null,null):r.ids}const tx=1e3,DM=4;function Sh(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function kh(e,t,s){return Math.abs(t.clientX-e.clientX)>s||Math.abs(t.clientY-e.clientY)>s}function OM({detachDelayMs:e=tx,stillnessThresholdPx:t=DM,onDetach:s,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:o=globalThis.clearTimeout.bind(globalThis)}){let a=null,i=null,l=null,d=null,u=null,m=!1;const h=()=>{u!=null&&(o(u),u=null)},p=()=>{h(),l=null},b=()=>{h(),a=null,i=null,l=null,d=null,m=!1},f=()=>{!a||!l||!d||m||u!=null||(u=r(()=>{u=null,!(!a||!l||!d||m)&&Sh(d,i)&&(kh(l,d,t)||(m=!0,s({panelId:a,clientX:d.clientX,clientY:d.clientY})))},e))},x=w=>{if(!(!a||m)){if(!Sh(w,i)){d={clientX:w.clientX,clientY:w.clientY},p();return}(!l||kh(l,w,t))&&(h(),l={clientX:w.clientX,clientY:w.clientY}),d={clientX:w.clientX,clientY:w.clientY},f()}},g=w=>{!a||m||(w&&(d={clientX:w.clientX,clientY:w.clientY}),p())};return{startDrag:w=>{h(),a=w.panelId,i=w.selfPanelBounds??null,l=null,d={clientX:w.clientX,clientY:w.clientY},m=!1},markSelfPanel:x,markNonSelfPanel:g,markNoDropTarget:g,markDockTarget:g,endDrag:b,isDragging:()=>a!=null,hasDetached:()=>m,dispose:b}}function $M(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function FM(e,t,s){const r=m=>({clientX:m.clientX,clientY:m.clientY}),o=m=>{const h=m==null?void 0:m.getBoundingClientRect();return h?{left:h.left,right:h.right,top:h.top,bottom:h.bottom}:null},a=m=>{var p;const h=(p=t())==null?void 0:p.getBoundingClientRect();return h?m.clientX<h.left||m.clientX>h.right||m.clientY<h.top||m.clientY>h.bottom:!1},i=OM({detachDelayMs:tx,onDetach:({panelId:m,clientX:h,clientY:p})=>{var S,C;const b=e.getPanel(m);if(!b)return;try{if(b.group.model.location.type!=="grid")return}catch{return}const f=(S=t())==null?void 0:S.getBoundingClientRect(),x=(C=b.group.element)==null?void 0:C.getBoundingClientRect(),g=Math.round(Math.min(Math.max((x==null?void 0:x.width)??600,360),720)),w=Math.round(Math.min(Math.max((x==null?void 0:x.height)??500,260),640));e.addFloatingGroup(b,{x:f?Math.max(0,h-f.left-32):void 0,y:f?Math.max(0,p-f.top-18):void 0,width:g,height:w}),b.api.setActive(),s()}}),l=[e.onWillDragPanel(m=>{if(!(m.nativeEvent.defaultPrevented||m.nativeEvent.shiftKey)){try{if(m.panel.group.model.location.type!=="grid")return}catch{return}i.startDrag({panelId:m.panel.id,selfPanelBounds:o(m.panel.group.element),...r(m.nativeEvent)})}}),e.onWillShowOverlay(m=>{if(i.hasDetached()){m.preventDefault();return}i.markDockTarget(r(m.nativeEvent))}),e.onWillDrop(m=>{if(i.hasDetached()){m.preventDefault(),i.endDrag();return}i.markDockTarget(r(m.nativeEvent))}),e.onDidDrop(()=>i.endDrag()),e.onUnhandledDragOverEvent(m=>{i.isDragging()&&i.markSelfPanel(r(m.nativeEvent))})],d=m=>{if(!i.isDragging())return;const h=r(m);a(h)&&i.markNonSelfPanel(h)},u=()=>i.endDrag();return window.addEventListener("dragover",d,!0),window.addEventListener("drop",u,!0),window.addEventListener("dragend",u,!0),()=>{i.dispose();for(const m of l)m.dispose();window.removeEventListener("dragover",d,!0),window.removeEventListener("drop",u,!0),window.removeEventListener("dragend",u,!0)}}function Ma(e){return kt(e)||e.tabKey}function HM(e){return`remote:${e}`}function gn(e){return e.startsWith("remote:")}function jh(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Oc(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 du(e,t){e.classList.remove(ol.className,al.className),e.classList.add(t==="light"?ol.className:al.className)}function Nh(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 BM(e,t){var p;const s=e.activeGroup||((p=e.activePanel)==null?void 0:p.group);if(!s)return;const r=e.groups||[],o=r.find(b=>b.id===s.id);if(!o)return;const a=o.element.getBoundingClientRect(),i=a.left+a.width/2,l=a.top+a.height/2,d=(b,f,x,g)=>Math.max(0,Math.min(f,g)-Math.max(b,x)),u=b=>{const f=b.element.getBoundingClientRect(),x=f.left+f.width/2,g=f.top+f.height/2;let w=0,S=0,C=0,j=!1;if(t==="left"?(j=x<i,w=Math.max(0,a.left-f.right),S=Math.abs(g-l),C=d(a.top,a.bottom,f.top,f.bottom)):t==="right"?(j=x>i,w=Math.max(0,f.left-a.right),S=Math.abs(g-l),C=d(a.top,a.bottom,f.top,f.bottom)):t==="above"?(j=g<l,w=Math.max(0,a.top-f.bottom),S=Math.abs(x-i),C=d(a.left,a.right,f.left,f.right)):(j=g>l,w=Math.max(0,f.top-a.bottom),S=Math.abs(x-i),C=d(a.left,a.right,f.left,f.right)),!j)return Number.POSITIVE_INFINITY;const v=C>0?0:120;return w*3+S+v};let m=null,h=Number.POSITIVE_INFINITY;for(const b of r){if(b.id===o.id)continue;const f=u(b);Number.isFinite(f)&&(f>=h||(h=f,m=b))}return m||void 0}function WM(e,t,s){var i;const r=[t];let o;for(const l of r){let d;for(const u of l){const m=e.addPanel({id:u.tabKey,component:"conversation",title:Ma(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 $c(e,t,s){const r=new Set(t.map(a=>a.tabKey)),o=new Map;for(const a of t)o.set(a.tabKey,(o.get(a.tabKey)||0)+1);for(const a of[...e.panels])gn(a.id)||!r.has(a.id)&&!(s!=null&&s.has(a.id))&&e.removePanel(a);for(const a of t){const i=e.getPanel(a.tabKey);if(i){(o.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:i.id}),i.update({params:{tabKey:a.tabKey}}),i.title!==Ma(a)&&i.api.setTitle(Ma(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:Ma(a),params:{kind:"conversation",tabKey:a.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 Ch(e,t,s){var d,u;const r=s?HM(s):null;for(const m of[...e.panels])gn(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=Db(o);if(a){a.title!==i&&a.api.setTitle(i);return}const l=(o==null?void 0:o.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((u=e.panels.find(m=>!gn(m.id)))==null?void 0:u.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:s},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function UM(e,t){var r,o,a,i;const s=e.toJSON();for(const l of s.floatingGroups||[])if((o=(r=l.data)==null?void 0:r.views)!=null&&o.includes(t)&&l.position)return{kind:"floating",position:l.position};for(const l of s.popoutGroups||[])if((i=(a=l.data)==null?void 0:a.views)!=null&&i.includes(t))return{kind:"popout",position:l.position,popoutUrl:l.url};return{kind:"grid"}}function nx({doId:e,targetSessionId:t,connState:s,viewMode:r}){var u;const[o,a]=c.useState(null),{ides:i}=Ii(),l=((u=i.find(m=>m.id===e&&m.type==="adhdev-daemon"))==null?void 0:u.screenshotUsage)??null;c.useEffect(()=>e?Dt.onScreenshot("ide-page",(h,p)=>{if(h!==e)return;const b=new FileReader;b.onload=()=>a(b.result),b.readAsDataURL(p)}):void 0,[e]),c.useEffect(()=>{s!=="connected"&&a(null)},[s]),c.useEffect(()=>{a(null)},[e,t]),c.useEffect(()=>{const m=e?Dt.get(e):null;if(!(!m||s!=="connected"))return r!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[r,s,t,e]);const d=c.useCallback(async(m,h)=>{const p=e?Dt.get(e):null;return!p||s!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):p.sendInput(m,h,t)},[e,s,t]);return{connScreenshot:o,screenshotUsage:l,handleRemoteAction:d}}const sx=c.createContext(null);function Ki(){const e=c.useContext(sx);if(!e)throw new Error("DashboardDockviewContext missing");return e}function KM(e){const[,t]=c.useState(0);c.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 qM({params:e}){var u;const t=Ki(),{t:s}=he("common"),r=c.useMemo(()=>_n([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),o=c.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:l,handleRemoteAction:d}=nx({doId:a,targetSessionId:r?rb(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:l,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 zM(){const e=Ki();return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:n.jsx(cu,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!Ui(e.ides,e.initialDataLoaded)})})}function VM(e){var j,v;KM(e);const t=Ki(),{t:s}=he("common"),r=c.useCallback(y=>{"button"in y&&y.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=c.useCallback(y=>O_(y),[]),l=c.useCallback(()=>D_(a),[a]),d=c.useSyncExternalStore(i,l,l),u=Kd(o);if(e.params.kind==="remote"){const y=_n([...t.conversationsByTabKey.values()],e.params.routeId),N=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,k=e.api.isGroupActive;return n.jsxs("div",{className:`adhdev-dockview-tab${N?" is-active":""}${k?" is-group-active":""}`,title:e.api.title||s("dashboard.remoteDialog.remoteFallback"),"data-tab-key":(y==null?void 0:y.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:y!=null&&y.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:y.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=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,p=e.api.isGroupActive,b=ji(m,t.liveSessionInboxState,{isOpenConversation:h}),f=b.isReconnecting,x=b.isConnecting,g=b.isGenerating||d,w=b.isWaiting,S=b.unread,C=t.tabShortcuts[m.tabKey];return n.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${p?" is-group-active":""}${f?" is-reconnecting":""}`,title:u?`${kt(m)} · ${u}`:kt(m),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:y=>{var N;y.preventDefault(),r(y),t.openTabContextMenu({x:y.clientX,y:y.clientY,tabKey:m.tabKey,sourceDocument:((N=y.target)==null?void 0:N.ownerDocument)??document})},children:[S&&n.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),n.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:g?n.jsx(tn,{size:12,thickness:2,color:"success"}):w?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(tn,{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(ws,{conversation:m,size:12}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("div",{className:"adhdev-dockview-tab-primary",children:kt(m)}),n.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Os(m)}):x?n.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Os(m)}):n.jsx("span",{children:Os(m)})})]}),C&&n.jsx("span",{className:"text-4xs opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:C,children:C})]})}function GM(e,t){const{encodeShortcut:s,isMac:r,isShortcutListening:o,isVisibleTab:a,selectTabByShortcut:i,triggerAction:l}=t;let d=[],u=null;const m=()=>{u!=null&&e.clearTimeout(u),u=null,d=[]},h=()=>{u!=null&&e.clearTimeout(u),u=e.setTimeout(()=>{u=null,d=[]},1200)},p=f=>{if(!f.ctrlKey&&!f.metaKey&&!f.altKey)return;const x=s(f);if(!x)return;const g=Gg();for(const[w,S]of Object.entries(g))if(a(w)&&S===x){f.preventDefault(),i(w);return}},b=f=>{if(f.defaultPrevented||o())return;const x=s(f);if(!x)return;const g=f.metaKey||f.ctrlKey||f.altKey;if(lu(f.target))return;const w=oi(r),S=Object.entries(w).filter(([E,P])=>!!P&&(E==="splitActiveTabRight"||E==="splitActiveTabDown"||E==="floatActiveTab"||E==="popoutActiveTab"||E==="dockActiveTab"||E==="focusLeftPane"||E==="focusRightPane"||E==="focusUpPane"||E==="focusDownPane"||E==="moveActiveTabToLeftPane"||E==="moveActiveTabToRightPane"||E==="moveActiveTabToUpPane"||E==="moveActiveTabToDownPane"||E==="selectPreviousGroupTab"||E==="selectNextGroupTab"||E==="setActiveTabShortcut"||E==="hideCurrentTab")),C=g?[x]:[...d.slice(-1),x].slice(-2),j=C.join(" "),v=C[C.length-1],y=S.find(([,E])=>E===j);if(y){f.preventDefault(),m(),l(y[0]);return}if(S.some(([,E])=>E.startsWith(`${j} `))){f.preventDefault(),d=C,h();return}const k=S.find(([,E])=>E===v);if(k){f.preventDefault(),m(),l(k[0]);return}if(S.some(([,E])=>E.startsWith(`${v} `))){f.preventDefault(),d=[v],h();return}m()};return e.addEventListener("keydown",p),e.addEventListener("keydown",b),()=>{m(),e.removeEventListener("keydown",p),e.removeEventListener("keydown",b)}}function YM(e){e.preventDefault()}function QM(e){switch(e){case"dockInWindow":case"dockBackToGrid":return n.jsx(Ew,{size:13,className:"shrink-0 opacity-70"});case"moveBackToMain":return n.jsx(Rw,{size:13,className:"shrink-0 opacity-70"});case"floatAsPanel":return n.jsx(Pw,{size:13,className:"shrink-0 opacity-70"});case"openInNewWindow":return n.jsx(Mw,{size:13,className:"shrink-0 opacity-70"});case"removeShortcut":return n.jsx(Et,{size:13,className:"shrink-0 opacity-70"});case"hideTab":return n.jsx(gi,{size:13,className:"shrink-0 opacity-70"});default:return n.jsx(Gp,{size:13,className:"shrink-0 opacity-70"})}}function JM({x:e,y:t,sourceDocument:s,items:r,onSelect:o}){return An.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:e,top:t},children:r.map(a=>a.type==="separator"?n.jsx("div",{className:"border-t border-border-subtle my-1"},a.id):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 ${a.tone==="muted"?"text-text-muted":""}`,onMouseDown:YM,onClick:i=>o(a.id,i),children:[QM(a.id),n.jsx("span",{className:"flex-1 min-w-0",children:a.label}),a.shortcut?n.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:a.shortcut}):null]},a.id))}),s.body)}function XM(e,t){const s=document,r=e.document;for(const d of s.querySelectorAll('link[rel="stylesheet"]')){const u=r.createElement("link");u.rel="stylesheet",u.href=d.href,d.crossOrigin&&(u.crossOrigin=d.crossOrigin),r.head.appendChild(u)}for(const d of s.querySelectorAll("style")){const u=r.createElement("style");u.textContent=d.textContent,r.head.appendChild(u)}const o=[];for(const d of s.styleSheets)try{for(const u of d.cssRules)u instanceof CSSStyleRule&&(u.selectorText===":root"||u.selectorText==="html")&&o.push(u.cssText)}catch{}if(o.length>0){const d=r.createElement("style");d.textContent=o.join(`
69
- `),r.head.appendChild(d)}const a=s.documentElement.getAttribute("data-theme");a&&r.documentElement.setAttribute("data-theme",a),r.documentElement.style.colorScheme=a==="light"?"light":"dark",r.body.className=s.body.className;const i=s.documentElement.getAttribute("style");i&&r.documentElement.setAttribute("style",i);const l=r.getElementById("dv-popout-window");l instanceof HTMLElement&&(l.classList.add("adhdev-dockview"),du(l,t))}function ZM(e,t){var s;for(const r of e.groups)try{const o=(s=r.element)==null?void 0:s.ownerDocument;if(!o||o===document)continue;const a=o.getElementById("dv-popout-window");a instanceof HTMLElement&&(a.classList.add("adhdev-dockview"),du(a,t));const i=document.documentElement.getAttribute("data-theme");i&&o.documentElement.setAttribute("data-theme",i),o.documentElement.style.colorScheme=i==="light"?"light":"dark",o.body.className=document.body.className;const l=document.documentElement.getAttribute("style");l?o.documentElement.setAttribute("style",l):o.documentElement.removeAttribute("style")}catch{}}function eR(e,t,s){var r,o;for(const a of e.groups){const i=(r=a.element)==null?void 0:r.ownerDocument;if(!i||i===document)continue;const l=i.getElementById("dv-popout-window");if(!(l instanceof HTMLElement))continue;let d=null,u=i.title||"ADHDev",m="Popout workspace";const h=a.activePanel;if(h)if(d=h.id,gn(h.id)){const g=((o=h.params)==null?void 0:o.routeId)||h.id.slice(7),w=_n([...t.values()],g);u=Db(w),m=w!=null&&w.machineName?`Remote view · ${w.machineName}`:"Remote view"}else{const g=t.get(h.id);u=g?kt(g):h.title||h.id,m=g?Os(g):"Dockview panel"}i.title=`${u} — ADHDev`;const p=Array.from(i.querySelectorAll("#adhdev-popout-header"));for(const g of p)g.remove();const b=i.createElement("div");b.id="adhdev-popout-header",i.body.appendChild(b),b.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(";")),b.innerHTML=`
70
- <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
71
- <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
72
- <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${jh(u)}</div>
73
- <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${jh(m)}</div>
74
- </div>
75
- <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
76
- <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>
77
- <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>
78
- </div>
79
- `,l.style.top="52px",l.style.height="calc(100% - 52px)";const f=b.querySelector("[data-adhdev-popout-focus]");f&&(f.onclick=()=>{window.focus()});const x=b.querySelector("[data-adhdev-popout-dock]");x&&(x.disabled=!d,x.style.opacity=d?"1":"0.5",x.style.cursor=d?"pointer":"default",x.onclick=()=>{var g;d&&s(d),(g=i.defaultView)==null||g.focus()})}}const tR=[];function ia(e){return e.isActive}function _h(e){return e.isVisible}function nR({params:e,api:t}){var f;const s=Ki(),r=c.useRef(null),[o,a]=c.useState(()=>ia(t)),[i,l]=c.useState(()=>_h(t)),d=s.conversationsByTabKey.get(e.tabKey),u=Pi({sendDaemonCommand:s.sendDaemonCommand,activeConv:d,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone});c.useEffect(()=>{a(ia(t)),l(_h(t));const x=[t.onDidActiveChange(g=>a(g.isActive)),t.onDidActiveGroupChange(g=>{if(!ia(t)&&!g.isActive){a(!1);return}a(ia(t))}),t.onDidVisibilityChange(g=>l(g.isVisible))];return()=>{for(const g of x)g.dispose()}},[t]);const m=c.useMemo(()=>d?s.ides.find(x=>x.id===d.routeId):void 0,[s.ides,d]),h=d==null?void 0:d.tabKey,p=c.useMemo(()=>h?s.actionLogs.filter(x=>x.routeId===h):tR,[s.actionLogs,h]);if(!d)return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:n.jsx(cu,{conversationsCount:0,isSplitMode:!1,isStandalone:s.isStandalone,hasRegisteredMachines:s.hasRegisteredMachines,onOpenNewSession:s.onOpenNewSession,suppressGuide:s.hasDetachedConversationPanels,isLoading:!Ui(s.ides,s.initialDataLoaded)})});const b=Mr(d)==="terminal";return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:n.jsx(au,{activeConv:d,clearToken:s.clearedTabs[d.tabKey]||0,isCliTerminal:b,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 sR({visibleConversations:e,clearedTabs:t,ides:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:l,initialDataLoaded:d,userName:u,toggleHiddenTab:m,actionShortcuts:h,registerActionHandlers:p,onActiveTabChange:b,onOpenNewSession:f,onRequestScrollToBottom:x,requestedActiveTabKey:g,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:S,scrollToBottomRequest:C,liveSessionInboxState:j,layoutProfile:v}){var dt,Tt,bt;const{t:y}=he("common"),{theme:N}=Fi(),{sendCommand:k}=wt(),A=c.useRef(null),E=c.useRef(null),P=c.useRef(null),T=c.useRef(!1),M=c.useRef(!1),_=c.useRef(!1),I=c.useRef(null),D=c.useRef([]),L=c.useRef(null),$=c.useRef(e);$.current=e;const[U,J]=c.useState(null),[K,R]=c.useState(0),O=c.useRef(typeof window>"u"?{}:rI(v)),H=c.useMemo(()=>new Map(e.map(te=>[te.tabKey,te])),[e]),B=c.useMemo(()=>{const te=A.current;return te?te.groups.some(le=>{try{const be=le.model.location.type;return be!=="floating"&&be!=="popout"?!1:le.panels.some(Te=>H.has(Te.id))}catch{return!1}}):!1},[H,K,e]),q=c.useCallback(()=>{var te;(te=A.current)==null||te.focus()},[]),W=c.useCallback((te,le)=>{x==null||x(te,le)},[x]),ce=c.useCallback(te=>{XM(te,N)},[N]),ye=c.useCallback(()=>{const te=A.current;te&&ZM(te,N)},[N]),G=c.useCallback(te=>{const le=A.current;if(!le)return;const be=le.getPanel(te);be&&le.addPopoutGroup(be,{popoutUrl:"/popout.html",onDidOpen:({window:Te})=>{ce(Te),z();const De=H.get(te);Te.document.title=De?`${kt(De)} — ADHDev`:"ADHDev — Popout"}})},[H,ce]),Se=c.useCallback(te=>{const le=A.current,be=le==null?void 0:le.getPanel(te);if(!le||!be)return;const Te=le.groups.filter(De=>{var qe;try{return((qe=De.element)==null?void 0:qe.ownerDocument)===document}catch{return!0}});Te.length>0?be.api.moveTo({group:Te[0],position:"center"}):be.api.moveTo({position:"center"}),be.api.setActive()},[]),ue=c.useCallback(te=>{var Te;const le=A.current;if(!le)return!1;const be=le.getPanel(te);if(!be)return!1;try{return((Te=be.group.element)==null?void 0:Te.ownerDocument)!==document}catch{return!1}},[]),ne=c.useCallback(te=>{ue(te)&&Se(te),m(te)},[ue,Se,m]),ae=c.useCallback(te=>{const le=A.current,be=le==null?void 0:le.getPanel(te);!le||!be||le.addFloatingGroup(be,{width:600,height:500})},[]),ee=c.useCallback(te=>{var be;const le=(be=A.current)==null?void 0:be.getPanel(te);if(!le)return!1;try{return le.group.model.location.type==="floating"}catch{return!1}},[]),oe=c.useCallback(()=>{var le,be;const te=(be=(le=A.current)==null?void 0:le.activePanel)==null?void 0:be.id;return!te||gn(te)?null:H.has(te)?te:null},[H]),Ce=c.useCallback(te=>{const le=A.current,be=le==null?void 0:le.getPanel(te);if(!le||!be)return;const Te=le.groups.filter(De=>{try{return De.model.location.type==="grid"}catch{return!0}});Te.length>0?be.api.moveTo({group:Te[0],position:"center"}):be.api.moveTo({position:"center"}),be.api.setActive()},[]),Q=c.useCallback(()=>{var qe;const te=A.current;if(!te)return;const be=te.groups.filter(ot=>{var _e;try{return((_e=ot.element)==null?void 0:_e.ownerDocument)===document&&ot.model.location.type==="grid"}catch{return!1}})[0]||null,Te=[...te.panels];for(const ot of Te){const _e=(qe=ot.group.element)==null?void 0:qe.ownerDocument,st=ot.group.model.location.type;_e===document&&st==="grid"||(be&&be.id!==ot.group.id?ot.api.moveTo({group:be,position:"center"}):ot.api.moveTo({position:"center"}))}const De=te.activePanel;De&&(De.group.model.openPanel(De),De.api.setActive()),Oc(document)},[]),z=c.useCallback(()=>{const te=A.current;te&&eR(te,H,Se)},[H,Se]),X=c.useCallback(te=>{var Te;const le=A.current,be=le==null?void 0:le.getPanel(te);if(!(!le||!be)){be.group.model.openPanel(be),be.api.setActive(),W(te,"dockview-shortcut");try{const De=be.group.model.location;De.type==="popout"?De.getWindow().focus():Oc((Te=be.group.element)==null?void 0:Te.ownerDocument)}catch{}}},[W]),pe=c.useCallback(te=>{const le=A.current,be=le==null?void 0:le.activePanel,Te=(le==null?void 0:le.activeGroup)||(be==null?void 0:be.group);if(!le||!be||!Te)return;const De=Te.panels||[];if(De.length<=1)return;const qe=De.findIndex(st=>st.id===be.id);if(qe<0)return;const ot=(qe+te+De.length)%De.length,_e=De[ot];_e&&(_e.group.model.openPanel(_e),_e.api.setActive(),gn(_e.id)||W(_e.id,"dockview-shortcut"))},[W]),Pe=c.useCallback(te=>{const le=A.current;return le?BM(le,te):void 0},[]),Oe=c.useCallback(te=>{var Te;const le=Pe(te);if(!le)return;const be=le.activePanel||le.panels[0];be&&(le.model.openPanel(be),be.api.setActive(),gn(be.id)||W(be.id,"dockview-focus"),Oc((Te=le.element)==null?void 0:Te.ownerDocument))},[Pe,W]),Le=c.useCallback((te,le)=>{const be=A.current,Te=be==null?void 0:be.activePanel,De=(be==null?void 0:be.activeGroup)||(Te==null?void 0:Te.group);if(!be||!Te||!De)return;let qe=Pe(te);!qe&&(le!=null&&le.createGroupIfMissing)&&(qe=be.addGroup({referenceGroup:De,direction:te})),qe&&(Te.api.moveTo({group:qe,position:"center"}),Te.group.model.openPanel(Te),Te.api.setActive(),gn(Te.id)||W(Te.id,le!=null&&le.createGroupIfMissing?"dockview-split":"dockview-move"))},[Pe,W]),{isMac:ke,tabShortcuts:Y,shortcutListening:ve,setShortcutListening:Z,saveShortcuts:ie}=Yg({sortedTabKeys:e.map(te=>te.tabKey),onFocus:q,onSelectTab:X}),F=c.useCallback(()=>{var be;const te=A.current;if(!te)return;const le=te.activePanel;if(le){if(gn(le.id)){const Te=((be=le.params)==null?void 0:be.routeId)||le.id.slice(7),De=_n(e,Te);De!=null&&De.tabKey&&Z(De.tabKey);return}H.has(le.id)&&Z(le.id)}},[H,X,Z,e]),se=c.useCallback(te=>{const le=[];return te.metaKey&&le.push(ke?"⌘":"Meta"),te.ctrlKey&&le.push("Ctrl"),te.altKey&&le.push(ke?"⌥":"Alt"),te.shiftKey&&te.key.length!==1&&le.push(ke?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(te.key)?null:(le.push(Xg(te.key)),le.join("+"))},[ke]),me=c.useCallback(te=>{var le,be;switch(te){case"splitActiveTabRight":Le("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Le("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const Te=oe();Te&&ae(Te);return}case"popoutActiveTab":{const Te=oe();Te&&G(Te);return}case"dockActiveTab":{const Te=oe();if(!Te)return;ue(Te)?Se(Te):ee(Te)&&Ce(Te);return}case"focusLeftPane":Oe("left");return;case"focusRightPane":Oe("right");return;case"focusUpPane":Oe("above");return;case"focusDownPane":Oe("below");return;case"moveActiveTabToLeftPane":Le("left");return;case"moveActiveTabToRightPane":Le("right");return;case"moveActiveTabToUpPane":Le("above");return;case"moveActiveTabToDownPane":Le("below");return;case"selectPreviousGroupTab":pe(-1);return;case"selectNextGroupTab":pe(1);return;case"setActiveTabShortcut":F();return;case"hideCurrentTab":{const Te=(be=(le=A.current)==null?void 0:le.activePanel)==null?void 0:be.id;Te&&!gn(Te)&&ne(Te);return}default:return}},[pe,Ce,Oe,ae,oe,ne,ee,ue,Se,Le,G,F]);c.useEffect(()=>{if(!U)return;const te=U.sourceDocument,le=te.defaultView??window,be=Te=>{const De=te.querySelector("[data-dockview-tab-context-menu]");De&&De.contains(Te.target)||J(null)};return le.addEventListener("mousedown",be,!0),le!==window&&window.addEventListener("mousedown",()=>J(null),!0),()=>{le.removeEventListener("mousedown",be,!0),le!==window&&window.removeEventListener("mousedown",()=>J(null),!0)}},[U]);const re=c.useMemo(()=>({actionLogs:r,clearedTabs:t,conversationsByTabKey:H,hasDetachedConversationPanels:B,ides:s,isStandalone:i,hasRegisteredMachines:l,initialDataLoaded:d,onOpenNewSession:f,liveSessionInboxState:j,sendDaemonCommand:o,setActionLogs:a,toggleHiddenTab:ne,userName:u,scrollToBottomRequest:C,tabShortcuts:Y,openTabContextMenu:({x:te,y:le,tabKey:be,sourceDocument:Te})=>J({x:te,y:le,tabKey:be,sourceDocument:Te??document}),popoutTab:G,moveTabBackToMain:Se,isTabInPopout:ue,floatTab:ae,isTabFloating:ee}),[r,t,H,B,s,i,l,d,f,j,o,a,ne,u,C,Y,G,Se,ue,ae,ee]),we=U?RM({isTabInPopout:ue(U.tabKey),isTabFloating:ee(U.tabKey),tabShortcut:Y[U.tabKey],actionShortcuts:h}):[],V=c.useCallback(te=>{var Te;const le=A.current;if((((Te=le==null?void 0:le.activePanel)==null?void 0:Te.id)??null)===te.id){te.group.model.openPanel(te);return}te.group.model.openPanel(te),te.api.setActive()},[]),de=c.useCallback((te,le="requested-tab")=>{if(!te)return!1;const be=A.current;if(!be)return!1;const Te=be.getPanel(te);return Te?(V(Te),W(te,le),S==null||S(),!0):!1},[V,S,W]),ge=c.useCallback(()=>{if(_.current)return!1;const te=de(I.current,"stored-layout-restore");return te&&(_.current=!0),te},[de]),Ie=c.useCallback(()=>{var le;const te=A.current;te&&sI(v,{activeTabId:((le=te.activePanel)==null?void 0:le.id)??null,layout:te.toJSON()})},[v]),Ke=c.useCallback(()=>{oI(v,O.current)},[v]),Ae=c.useCallback(te=>{const le=A.current;return le?UM(le,te):{kind:"grid"}},[]),Ne=c.useCallback(te=>{const le=A.current;if(!le)return;const be=le.getPanel(te),Te=O.current[te];if(!be||!Te||Te.kind==="grid")return;if(be.group.model.location.type===Te.kind){delete O.current[te],Ke();return}if(Te.kind==="floating"){le.addFloatingGroup(be,{x:Te.position.left??24,y:Te.position.top??24,width:Te.position.width,height:Te.position.height}),delete O.current[te],Ke();return}delete O.current[te],Ke()},[Ke]);c.useEffect(()=>(p==null||p({setShortcutForActiveTab:F,restoreHiddenTabToSavedLocation:Ne,activateConversationTab:X,resetAllPanelsToMain:Q,activatePreviousTabInGroup:()=>pe(-1),activateNextTabInGroup:()=>pe(1),floatActiveTab:()=>{const te=oe();te&&ae(te)},popoutActiveTab:()=>{const te=oe();te&&G(te)},dockActiveTab:()=>{const te=oe();te&&(ue(te)?Se(te):ee(te)&&Ce(te))},splitActiveTabRight:()=>Le("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Le("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Oe("left"),focusRightPane:()=>Oe("right"),focusUpPane:()=>Oe("above"),focusDownPane:()=>Oe("below"),moveActiveTabToLeftPane:()=>Le("left"),moveActiveTabToRightPane:()=>Le("right"),moveActiveTabToUpPane:()=>Le("above"),moveActiveTabToDownPane:()=>Le("below")}),()=>p==null?void 0:p(null)),[pe,Ce,ae,Oe,oe,ee,ue,Le,Se,G,p,Q,Ne,X,F]),c.useEffect(()=>()=>{var te;(te=P.current)==null||te.call(P),P.current=null},[]);const He=c.useCallback(te=>LM(L,te.map(le=>le.tabKey)),[]),Fe=c.useCallback(te=>{var be,Te;A.current=te.api,(be=P.current)==null||be.call(P),P.current=null;const le=nI(v);if(I.current=(le==null?void 0:le.activeTabId)??null,le!=null&&le.layout&&(te.api.fromJSON(le.layout,{reuseExistingPanels:!1}),L.current=EM(te.api.panels.map(De=>De.id),e.map(De=>De.tabKey),gn),L.current&&window.setTimeout(()=>{const De=A.current;!De||!L.current||(L.current=null,$c(De,$.current))},ex+50)),M.current=wh({hasStoredLayout:!!(le!=null&&le.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:s}),M.current||($c(te.api,e,He(e)),Ch(te.api,e,w)),te.api.totalPanels===0&&e.length>0){const De=WM(te.api,e,g);if(De){const qe=te.api.getPanel(De);qe&&V(qe)}}else!M.current&&!de(g)&&ge();T.current=!0,te.api.onDidActivePanelChange(De=>{var ot;if(I.current=(De==null?void 0:De.id)??null,_.current=!0,z(),De&&gn(De.id)){const _e=((ot=De.params)==null?void 0:ot.routeId)||De.id.slice(7),st=_n(e,_e);b((st==null?void 0:st.tabKey)??null),Ie();return}if(b((De==null?void 0:De.id)??null),Ie(),!De)return;const qe=H.get(De.id);(qe==null?void 0:qe.streamSource)==="agent-stream"&&qe.agentType&&k(qe.routeId,ib(),{agentType:qe.agentType,...qe.sessionId&&{targetSessionId:qe.sessionId}}).catch(()=>{})}),te.api.onDidLayoutChange(()=>{Ie(),z(),R(De=>De+1)}),$M()&&(P.current=FM(te.api,()=>E.current,()=>{Ie(),z(),R(De=>De+1)})),te.api.onDidAddGroup(De=>{requestAnimationFrame(()=>{var qe,ot;try{const _e=(qe=De.element)==null?void 0:qe.ownerDocument;if(!_e||_e===document)return;(ot=_e.getElementById("dv-popout-window"))==null||ot.classList.add("adhdev-dockview");const st=document.documentElement.getAttribute("data-theme");st&&_e.documentElement.setAttribute("data-theme",st),_e.body.className=document.body.className;const jt=document.documentElement.getAttribute("style");jt&&_e.documentElement.setAttribute("style",jt)}catch{}z(),R(_e=>_e+1)})}),b(((Te=te.api.activePanel)==null?void 0:Te.id)??null)},[V,de,H,s,d,v,b,Ie,g,w,He,k,z,e]);c.useLayoutEffect(()=>{const te=A.current;if(!te||!T.current||M.current&&wh({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:s}))return;M.current&&(M.current=!1);const le=D.current,be=new Set(le),Te=e.map(gt=>gt.tabKey),De=new Set(Te),qe=PM({previousVisibleConversationCount:le.length,visibleConversationCount:e.length,ides:s});let ot=!1;for(const gt of le)De.has(gt)||qe||(O.current[gt]=Ae(gt),ot=!0);ot&&Ke(),qe||($c(te,e,He(e)),Ch(te,e,w));const _e=Te.filter(gt=>!be.has(gt));let st=!1;for(const gt of _e){const Kt=te.getPanel(gt),fe=O.current[gt];if(!Kt||!fe||fe.kind==="grid")continue;if(Kt.group.model.location.type===fe.kind){delete O.current[gt],st=!0;continue}if(fe.kind==="floating"){te.addFloatingGroup(Kt,{x:fe.position.left??24,y:fe.position.top??24,width:fe.position.width,height:fe.position.height}),delete O.current[gt],st=!0;continue}}if(st&&Ke(),D.current=Te,g&&de(g))return;!te.activePanel&&te.panels[0]&&V(te.panels[0]),!!(te.activePanel&&te.getPanel(te.activePanel.id))||ge()},[V,de,ge,s,d,Ke,Ae,g,w,He,e]),c.useEffect(()=>{T.current&&de(g)},[de,g]),c.useEffect(()=>{const te=be=>{const Te=be.target;if(!Te)return;const De=Te.querySelector("[data-tab-key]")||Te.closest("[data-tab-key]");if(De){const qe=De.getAttribute("data-tab-key");if(qe&&be.dataTransfer){const ot=Te.closest(".dv-tab")||De.closest(".dv-tab")||De;be.dataTransfer.effectAllowed="move",be.dataTransfer.setData("text/tab-key",qe),ot instanceof HTMLElement&&be.dataTransfer.setDragImage(ot,Math.max(12,Math.round(ot.clientWidth/2)),Math.max(10,Math.round(ot.clientHeight/2)))}}};window.addEventListener("dragstart",te);const le=Nh(A.current);for(const be of le)be.addEventListener("dragstart",te);return()=>{window.removeEventListener("dragstart",te);for(const be of le)be.removeEventListener("dragstart",te)}},[K]),c.useEffect(()=>{var le;const te=(le=E.current)==null?void 0:le.querySelector(".adhdev-dockview");te instanceof HTMLElement&&du(te,N),ye(),z()},[z,ye,N]),c.useEffect(()=>{z()},[z]),c.useEffect(()=>{const te=le=>{if(le.defaultPrevented||ve)return;const be=se(le);if(!be)return;const Te=le.metaKey||le.ctrlKey||le.altKey;lu(le.target)&&!Te||oi(ke).setActiveTabShortcut!==be||(le.preventDefault(),le.stopPropagation(),F())};return window.addEventListener("keydown",te,!0),()=>window.removeEventListener("keydown",te,!0)},[se,ke,ve,F]),c.useEffect(()=>{const te=E.current;if(!te)return;const le=be=>{var _e,st;if(!be.isTrusted)return;const Te=(st=(_e=be.target)==null?void 0:_e.closest)==null?void 0:st.call(_e,".dv-scrollable");if(!Te)return;be.preventDefault(),be.stopPropagation();const De=Math.abs(be.deltaX),qe=Math.abs(be.deltaY),ot=De>qe?be.deltaX:be.deltaY;Te.dispatchEvent(new WheelEvent("wheel",{deltaY:ot,deltaMode:be.deltaMode,bubbles:!1,cancelable:!0}))};return te.addEventListener("wheel",le,{passive:!1,capture:!0}),()=>te.removeEventListener("wheel",le,{capture:!0})},[]),c.useEffect(()=>{const te=Nh(A.current);if(te.length===0)return;const le=te.map(be=>GM(be,{encodeShortcut:se,isMac:ke,isShortcutListening:()=>!!ve,isVisibleTab:Te=>e.some(De=>De.tabKey===Te),selectTabByShortcut:X,triggerAction:me}));return()=>{for(const be of le)be()}},[se,ke,K,X,ve,me,e]);const it=N==="light"?ol:al,ut=((bt=(Tt=(dt=A.current)==null?void 0:dt.activePanel)==null?void 0:Tt.group.element)==null?void 0:bt.ownerDocument)??document;return n.jsxs(sx.Provider,{value:re,children:[n.jsx("div",{ref:E,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:n.jsx(ny,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:nR,remote:qM},defaultTabComponent:VM,watermarkComponent:zM,onReady:Fe,singleTabMode:"default",tabAnimation:"smooth",theme:it,popoutUrl:"/popout.html"})}),U&&n.jsx(JM,{x:U.x,y:U.y,sourceDocument:U.sourceDocument,items:we,onSelect:(te,le)=>{switch(te){case"dockInWindow":case"dockBackToGrid":Ce(U.tabKey);break;case"moveBackToMain":Se(U.tabKey);break;case"floatAsPanel":ae(U.tabKey);break;case"openInNewWindow":G(U.tabKey);break;case"setShortcut":le.stopPropagation(),Z(U.tabKey);break;case"removeShortcut":{const be={...Y};delete be[U.tabKey],ie(be);break}case"hideTab":ne(U.tabKey);break}J(null)}}),ve&&An.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:()=>Z(null),children:n.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:te=>te.stopPropagation(),children:[n.jsxs("div",{className:"text-sm font-bold text-text-primary mb-2",children:["⌨ ",y("paneGroup.shortcutSetTitle")]}),n.jsx("div",{className:"text-xs text-text-secondary mb-4",children:y("paneGroup.shortcutPressCombo",{example1:ke?"⌘+1":"Ctrl+1",example2:ke?"⌥+A":"Alt+A"})}),n.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:y("paneGroup.shortcutListening")}),n.jsx("div",{className:"text-3xs text-text-muted mt-3",children:y("paneGroup.pressEscToCancel")})]})}),ut.body)]})}const rx="adhdev-recent-launch-args-v1",rR=8;function oR(e){return String(e||"").trim().replace(/\s+/g," ")}function ox(e,t){return`${e.trim()}::${t.trim()}`}function ax(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(rx)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function aR(e){if(!(typeof window>"u"))try{window.localStorage.setItem(rx,JSON.stringify(e))}catch{}}function iR(e,t){var a;const s=String(e||"").trim(),r=String(t||"").trim();return!s||!r?[]:((a=ax().byKey[ox(s,r)])==null?void 0:a.items)||[]}function cR(e,t,s){var m;const r=String(e||"").trim(),o=String(t||"").trim(),a=oR(s);if(!r||!o||!a)return;const i=ax(),l=ox(r,o),d=((m=i.byKey[l])==null?void 0:m.items)||[],u=[a,...d.filter(h=>h!==a)].slice(0,rR);i.byKey[l]={items:u},aR(i)}const lR="adhdev.remember.";function Xl(e){return`${lR}${e.trim()}`}function Fc(e){if(typeof window>"u"||!e.trim())return null;try{const t=window.localStorage.getItem(Xl(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 ca(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(Xl(e));return}window.localStorage.setItem(Xl(e),JSON.stringify(s))}catch{}}function dR({sessions:e,loading:t,busy:s=!1,resumingSessionId:r=null,fallbackWorkspacePath:o,onResume:a,onRefresh:i,onClose:l}){const{t:d}=he("common"),[u,m]=c.useState(""),h=String(o||"").trim(),p=c.useMemo(()=>{const b=e.map(f=>f.canResume||String(f.workspace||"").trim()||!h?f:{...f,workspace:h,canResume:!0,workspaceFallbackSource:"selected-workspace"});return zd(b,{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":Wl(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:b=>m(b.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(Bi,{onClick:i,refreshing:t,className:"h-8 w-8"}),n.jsx("button",{type:"button",onClick:l,"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(Et,{size:14})})]}),n.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-2",children:[p.map(b=>{const f=r===b.providerSessionId,x=String(b.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:b.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(Vb,{value:b.lastMessageAt}),x&&n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx(Qt,{content:x,children:n.jsx("span",{className:"truncate",children:Qb(x)})})]}),b.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:b.messageCount})})]})]})]}),b.canResume?n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",disabled:s||!!r,onClick:()=>a(b),children:d(f?"historyModal.statusResuming":"historyModal.statusResume")}):n.jsx("span",{className:"shrink-0 text-2xs text-text-muted",children:d("historyModal.statusMissingWorkspace")})]},b.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"):cg(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 uR(e){return!e.hasLoadedInitialResults&&!e.isLoading}function zs({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(nt,{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 mR(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 hR({busy:e,savedSessionsLoading:t,savedSessionsError:s,savedSessionsLoaded:r,savedSessionsCount:o=0,selectedSession:a,historyOpen:i=!1,onOpenHistory:l,onClearSelection:d}){const{t:u}=he("common"),m=a?Wg(a,u):null,h=mR(u,{savedSessionsLoading:t,savedSessionsLoaded:r,savedSessionsCount:o}),p=!!m||!!h||!!s;return n.jsx(zs,{title:u("launch.savedHistoryBadge"),description:Vd(u),action:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,"aria-expanded":i,onClick:l,children:aT(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 pR({setup:e,providerName:t,className:s=""}){const{t:r}=he("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 fR={cli:"CLI",ide:"IDE"},ho="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm";function bR({machines:e,selectedMachineId:t,useDropdown:s,busy:r,onSelect:o,onPrefetch:a}){const{t:i}=he();return n.jsx(zs,{title:i("newSession.machine"),children:s?n.jsx("select",{"aria-label":i("newSession.machine"),value:t,onChange:l=>o(l.target.value),onFocus:()=>e.forEach(l=>a(l.id)),className:ho,disabled:r,children:e.map(l=>n.jsx("option",{value:l.id,children:pn(l,{fallbackId:l.id})},l.id))}):n.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":i("newSession.machine"),children:e.map(l=>{const d=pn(l,{fallbackId:l.id}),u=t===l.id;return n.jsxs("button",{type:"button","aria-label":i("newSession.selectMachine",{name:d}),"aria-pressed":u,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${u?"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:()=>o(l.id),onMouseEnter:()=>a(l.id),onFocus:()=>a(l.id),disabled:r,title:d,children:[n.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${l.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),n.jsx("span",{className:"truncate",children:d})]},l.id)})})})}function gR({loading:e,error:t,meshes:s,selectedMeshId:r,busy:o,onSelect:a}){const{t:i}=he();return n.jsxs("div",{className:"space-y-3",children:[e&&n.jsx("div",{className:"text-sm text-text-muted",children:i("newSession.loadingMeshes")}),!e&&t&&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:t}),!e&&!t&&s.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:[i("newSession.noMeshesShort"),n.jsx(nt,{content:i("newSession.noMeshes")})]}),s.length>0&&n.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":i("newSession.mesh"),children:s.map(l=>n.jsxs("button",{type:"button",role:"radio","aria-checked":r===l.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${r===l.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>a(l.id),disabled:o,children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:l.name}),n.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[l.repoIdentity||i("newSession.repoMesh"),typeof l.nodesCount=="number"?` · ${i("newSession.nodeCount",{count:l.nodesCount})}`:""]}),l.workspace&&n.jsx("div",{className:"mt-1 text-2xs text-text-muted break-all",children:i("newSession.coordinatorWorkspace",{path:l.workspace})})]},l.id))})]})}function xR({targets:e,activeKind:t,selectedTarget:s,showCategory:r,busy:o,onSelect:a}){const{t:i}=he();return n.jsx(zs,{title:i("newSession.agent"),children:n.jsxs("div",{className:"grid grid-cols-1 gap-1.5",role:"radiogroup","aria-label":i("newSession.agent"),children:[e.map(l=>{const d=t===l.kind&&s===l.id;return n.jsxs("button",{type:"button",role:"radio","aria-checked":d,"data-launch-kind":l.kind,className:`flex w-full items-center justify-between gap-3 rounded-xl border px-3.5 py-2.5 text-left transition-colors ${d?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>a(l),disabled:o,children:[n.jsx("span",{className:"min-w-0 truncate text-sm font-semibold text-text-primary",children:l.label}),n.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[l.meta&&n.jsx("span",{className:"text-2xs text-text-muted",children:l.meta}),r&&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:fR[l.kind]})]})]},`${l.kind}:${l.id}`)}),e.length===0&&n.jsxs("div",{className:"flex items-center gap-1 text-sm text-text-muted",children:[i("newSession.noProvidersShort"),n.jsx(nt,{content:i("newSession.noProviders")})]})]})})}function yR({value:e,recentOptions:t,busy:s,onChange:r}){const{t:o}=he();return n.jsxs(zs,{title:o("newSession.startupArguments"),children:[n.jsx("input",{type:"text",value:e,onChange:a=>r(a.target.value),placeholder:o("newSession.optionalFlags"),className:ho,disabled:s}),t.length>0&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.map(a=>n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>r(a),disabled:s,title:a,children:a},a))})]})}function vR({modelOptions:e,thinkingOptions:t,model:s,thinkingLevel:r,modelIsCustom:o,busy:a,onModelIsCustomChange:i,onModelChange:l,onThinkingChange:d}){const{t:u}=he();return n.jsx(zs,{title:u("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:u("newSession.model")}),e.length>0&&!o?n.jsxs(n.Fragment,{children:[n.jsxs("select",{value:e.includes(s)?s:"",onChange:m=>{m.target.value==="__custom__"?(i(!0),l("")):l(m.target.value)},className:ho,disabled:a,children:[n.jsx("option",{value:"",children:u("newSession.providerDefault")}),e.map(m=>n.jsx("option",{value:m,children:m},m)),n.jsx("option",{value:"__custom__",children:u("newSession.custom")})]}),!s.trim()&&n.jsx("span",{className:"text-2xs text-text-muted","data-testid":"new-session-default-model",children:u("newSession.defaultResolvesTo",{model:e[0],defaultValue:"Default resolves to {{model}}"})})]}):n.jsxs(n.Fragment,{children:[n.jsx("input",{type:"text",value:s,onChange:m=>l(m.target.value),placeholder:u("newSession.typeModelName"),className:ho,disabled:a,autoFocus:o}),e.length>0&&n.jsx("button",{type:"button",className:"self-start text-2xs text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{i(!1),l("")},disabled:a,children:u("newSession.backToModelList")})]})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:u("newSession.thinkingLevel")}),n.jsxs("select",{value:r,onChange:m=>d(m.target.value),className:ho,disabled:a,children:[n.jsx("option",{value:"",children:u("newSession.providerDefault")}),t.map(m=>n.jsx("option",{value:m,children:m},m))]})]})]})})}function ai(e,t){var s;return e?t==="ide"?(((s=e.detectedIdes)==null?void 0:s.length)||0)>0:(e.availableProviders||[]).some(r=>Ei(r,t)):!1}function Hc(e){return e?ai(e,"cli")?"cli":ai(e,"ide")?"ide":null:null}const Bc="new-session-dialog",Ah="new-session-workspace",Th="new-session-mesh",Zl={value:"",source:null};function Ih(e,t){return e?{value:e,source:t}:Zl}function Mh(e,t){return{...e.value.trim()&&e.source?{modelSource:e.source}:{},...t.value.trim()&&t.source?{thinkingLevelSource:t.source}:{}}}function wR(e){return e==="cli"||e==="ide"}function sr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}const SR=new Set(["--dangerously-skip-permissions","--dangerously-bypass-approvals-and-sandbox","bypassPermissions","sandbox_mode=danger-full-access","approval_policy=never"]);function kR(e){const t=e.trim();return SR.has(t)||t.startsWith("--dangerously-skip-permissions=")||t.startsWith("--dangerously-bypass-approvals-and-sandbox=")}function Hn(e){var t;return(t=e.launchArgs)!=null&&t.some(kR)?"dangerous":e.risk}function jR(e){var s,r;if(!e)return"";const t=e.modes.find(o=>o.id===e.default);return t&&Hn(t)!=="dangerous"?t.id:((s=e.modes.find(o=>o.strategy==="pty-parse-default"&&Hn(o)!=="dangerous"))==null?void 0:s.id)||((r=e.modes.find(o=>Hn(o)!=="dangerous"))==null?void 0:r.id)||""}function NR(e,t,s){return e?t?{autoApproveMode:t}:{autoApprove:!1}:{autoApprove:s}}const CR={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}=he();return n.jsx("span",{className:`rounded-full border px-2 py-0.5 text-3xs font-semibold uppercase tracking-wide ${CR[e]}`,children:t(`newSession.autoApproveRisk.${e}`)})}function cx({config:e,selectedModeId:t,disabled:s=!1,onSelectMode:r}){const{t:o}=he();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=Hn(a),l=t===a.id;return n.jsxs("button",{type:"button",role:"radio","aria-checked":l,className:`flex w-full items-center justify-between gap-3 rounded-xl border px-3.5 py-3 text-left transition-colors ${l?"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 _R({checked:e,disabled:t=!1,onChange:s}){const{t:r}=he();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(nt,{content:r("newSession.autoApproveLegacyDescription")})]}),n.jsx(Pr,{checked:e,onChange:s,disabled:t,"aria-labelledby":"legacy-auto-approve-label"})]})}function lx({mode:e,onConfirm:t,onCancel:s}){const{t:r}=he();return n.jsx(Wi,{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 AR({machines:e,ides:t,onClose:s,onBrowseDirectory:r,onSaveWorkspace:o,onLaunchIde:a,onLaunchProvider:i,onListMeshes:l,onLaunchMeshCoordinator:d,onListSavedSessions:u,initialMachineId:m,initialWorkspaceId:h,initialLaunchMode:p,initialMeshWorkspacePath:b}){var Xe,It,wn,$r,bu,gu,xu,yu,vu;const{t:f}=he(),x=Rr(),g=c.useMemo(()=>[...e].sort(Wa),[e]),[w]=c.useState(()=>({dialog:Fc(Bc),workspace:Fc(Ah),mesh:Fc(Th)})),[S,C]=c.useState(()=>{var Be,$e;if(m&&e.some(at=>at.id===m))return m;const xe=(Be=w.dialog)==null?void 0:Be.machineId;return xe&&e.some(at=>at.id===xe)?xe:(($e=[...e].sort(Wa)[0])==null?void 0:$e.id)||""}),j=c.useMemo(()=>g.find(xe=>xe.id===S)||g[0],[S,g]),v=c.useMemo(()=>((j==null?void 0:j.workspaces)||[]).map(xe=>({id:xe.id,path:xe.path,label:xe.label})),[j]),y=(j==null?void 0:j.defaultWorkspaceId)||null,[N,k]=c.useState("workspace"),[A,E]=c.useState(""),[P,T]=c.useState(""),[M,_]=c.useState([]),[I,D]=c.useState(""),[L,$]=c.useState(!1),[U,J]=c.useState(null),[K,R]=c.useState(""),[O,H]=c.useState(Hc(g[0])),[B,q]=c.useState(""),[W,ce]=c.useState(""),[ye,G]=c.useState(!1),[Se,ue]=c.useState(""),[ne,ae]=c.useState(null),[ee,oe]=c.useState(Zl),[Ce,Q]=c.useState(Zl),z=ee.value,X=Ce.value,pe=c.useCallback((xe,Be)=>{oe(Ih(xe,Be))},[]),Pe=c.useCallback((xe,Be)=>{Q(Ih(xe,Be))},[]),[Oe,Le]=c.useState(!1),[ke,Y]=c.useState([]),[ve,Z]=c.useState(""),[ie,F]=c.useState([]),[se,me]=c.useState(!1),[re,we]=c.useState(!1),[V,de]=c.useState(""),[ge,Ie]=c.useState(!1),[Ke,Ae]=c.useState(null),[Ne,He]=c.useState(!1),[Fe,it]=c.useState(""),[ut,dt]=c.useState("error"),[Tt,bt]=c.useState(null),[te,le]=c.useState(!1),[be,Te]=c.useState(""),[De,qe]=c.useState([]),[ot,_e]=c.useState(!1),[st,jt]=c.useState(""),[gt,Kt]=c.useState(!1),fe=c.useRef(null),Me=c.useRef(h||null),Ee=c.useRef(p||(((Xe=w.dialog)==null?void 0:Xe.mode)==="mesh"||((It=w.dialog)==null?void 0:It.mode)==="workspace"?w.dialog.mode:null)),Ve=c.useRef(b||null),Qe=c.useRef(h?null:((wn=w.workspace)==null?void 0:wn.workspaceChoice)||null),ht=($r=w.workspace)==null?void 0:$r.kind,tt=c.useRef(wR(ht)?ht:null),Nt=c.useRef(((bu=w.workspace)==null?void 0:bu.target)||null),xt=c.useRef(((gu=w.mesh)==null?void 0:gu.meshId)||null),Bt=c.useRef(((xu=w.mesh)==null?void 0:xu.cliType)||null),Jt=c.useRef(!0),on=c.useRef(!0),qt=c.useRef(0),At=c.useRef(0),an=c.useRef(0);c.useEffect(()=>{var xe,Be;if(!S&&((xe=g[0])!=null&&xe.id)){const $e=(Be=w.dialog)==null?void 0:Be.machineId,at=m&&g.some(ln=>ln.id===m)?m:$e&&g.some(ln=>ln.id===$e)?$e:g[0].id;C(at)}},[m,w,S,g]),c.useEffect(()=>{!j||!(!j.workspaces||!j.availableProviders||!j.detectedIdes||!j.recentLaunches)||x(j.id,{minFreshMs:3e4}).catch(()=>{})},[x,j]);const Kn=c.useCallback(xe=>{xe&&x(xe,{minFreshMs:3e4}).catch(()=>{})},[x]),Ct=c.useMemo(()=>((j==null?void 0:j.availableProviders)||[]).filter(xe=>Ei(xe,"cli")),[j]),cn=c.useMemo(()=>((j==null?void 0:j.detectedIdes)||[]).map(xe=>({id:xe.type,label:xe.name||xe.type,meta:xe.running?f("newSession.detectedLocally"):f("newSession.availableToOpen")})),[j,f]),fn=c.useMemo(()=>O==="cli"?Ct.map(xe=>({id:xe.type,label:xe.displayName||xe.type,meta:""})):cn,[O,Ct,cn]),Ge=c.useMemo(()=>{const xe=Ct.map($e=>({kind:"cli",id:$e.type,label:$e.displayName||$e.type,meta:""}));if(N==="mesh")return xe;const Be=cn.map($e=>({kind:"ide",...$e}));return[...xe,...Be]},[Ct,cn,N]),lt=c.useMemo(()=>M.find(xe=>xe.id===I)||null,[M,I]),Re=c.useMemo(()=>Ct.find(xe=>xe.type===B)||null,[Ct,B]),We=c.useMemo(()=>Ct.find(xe=>xe.type===B),[Ct,B]),rt=O==="cli"?We==null?void 0:We.autoApproveModes:void 0,St=JSON.stringify(rt||null),zt=jR(rt),mt=c.useMemo(()=>Hb(We?[We]:[],We==null?void 0:We.type),[We]),Yt=c.useMemo(()=>{const xe=Bb(We?[We]:[],We==null?void 0:We.type);return xe.length?xe:["low","medium","high"]},[We]),Tn=c.useMemo(()=>II(Re==null?void 0:Re.meshCoordinator,{meshId:(lt==null?void 0:lt.id)||"",workspace:(lt==null?void 0:lt.workspace)||""}),[Re,lt]),vn=Tt||Tn,In=c.useCallback(async xe=>{const Be=an.current+1;an.current=Be,$(!0),R("");try{const $e=await l(xe);if(an.current!==Be)return;_($e),D(at=>{var ln;return $e.some(os=>os.id===at)?at:((ln=$e[0])==null?void 0:ln.id)||""}),J(xe)}catch($e){if(an.current!==Be)return;_([]),D(""),J(xe),R($e instanceof Error?$e.message:f("newSession.errorLoadMeshes"))}finally{an.current===Be&&$(!1)}},[l,f]);c.useEffect(()=>{var ln,os;if(!j)return;if(fe.current!==j.id){At.current+=1,an.current+=1,fe.current!==null&&(Me.current=null,Ee.current=null,Ve.current=null,Qe.current=null,tt.current=null,Nt.current=null,xt.current=null,Bt.current=null,Jt.current=!1,on.current=!1),fe.current=j.id;const Lt=Ee.current;Ee.current=null,k(Lt||"workspace");const Rn=Me.current,zn=Qe.current;T(""),le(!1),Te(""),qe([]),_e(!1),jt(""),Rn&&v.some(nc=>nc.id===Rn)?(Me.current=null,E(Rn)):zn==="__home__"?(Qe.current=null,E("__home__")):zn==="__custom__"&&((ln=w.workspace)!=null&&ln.customWorkspacePath)?(Qe.current=null,E("__custom__"),T(w.workspace.customWorkspacePath)):zn&&v.some(nc=>nc.id===zn)?(Qe.current=null,E(zn)):E(y||((os=v[0])==null?void 0:os.id)||"__home__"),_([]),D(""),$(!1),J(null),R("");const tc=tt.current;tc&&ai(j,tc)?(tt.current=null,H(tc)):H(Hc(j)),q(""),ce(""),G(!1),ue(""),ae(null),pe("","user"),Pe("","user"),Le(!1),Z(""),F([]),we(!1),de(""),Ie(!1),it(""),bt(null);return}const Be=Me.current,$e=Qe.current;Be&&v.some(Lt=>Lt.id===Be)?(Me.current=null,E(Be)):$e&&v.some(Lt=>Lt.id===$e)?(Qe.current=null,E($e)):E(Lt=>{var Rn;return Lt==="__custom__"||Lt==="__home__"||v.some(zn=>zn.id===Lt)?Lt:y||((Rn=v[0])==null?void 0:Rn.id)||"__home__"});const at=tt.current;at&&ai(j,at)?(tt.current=null,H(at)):H(Lt=>Lt==="ide"&&cn.length>0||Lt==="cli"&&Ct.length>0?Lt:Hc(j))},[Ct.length,y,cn.length,w,j,v]),c.useEffect(()=>{!j||N!=="mesh"||U===j.id||L||In(j.id)},[In,U,L,j,N]),c.useEffect(()=>{if(M.length===0)return;const xe=Ve.current;if(xe){Ve.current=null,xt.current=null;const $e=M.find(at=>sr(at.workspace)===sr(xe));$e&&D($e.id);return}const Be=xt.current;Be&&(xt.current=null,M.some($e=>$e.id===Be)&&D(Be))},[M]),c.useEffect(()=>{N==="mesh"&&O!=="cli"&&Ct.length>0&&H("cli")},[O,Ct.length,N]),c.useEffect(()=>{var $e;if(!O||fn.some(at=>at.id===B))return;let xe=(($e=fn[0])==null?void 0:$e.id)||"";const Be=Nt.current;N!=="mesh"&&Be&&fn.length>0&&O===ht&&(Nt.current=null,fn.some(at=>at.id===Be)&&(xe=Be)),q(xe)},[O,fn,ht,B,N]),c.useEffect(()=>{if(N!=="mesh")return;const xe=Bt.current;!xe||Ct.length===0||(Bt.current=null,Ct.some(Be=>Be.type===xe)&&q(xe))},[Ct,N]),c.useEffect(()=>{bt(null)},[j==null?void 0:j.id,I,B,N]),c.useEffect(()=>{pe("","user"),Pe("","user"),Le(!1)},[B,pe,Pe]),c.useEffect(()=>{ue(zt),G(!1),ae(null)},[St,zt,j==null?void 0:j.id,B]),c.useEffect(()=>{if(!B)return;const xe=N==="mesh",Be=xe?on:Jt;if(!Be.current)return;const $e=xe?w.mesh:w.workspace,at=xe?$e==null?void 0:$e.cliType:$e==null?void 0:$e.target;if(!$e||at!==B)return;Be.current=!1;const ln=$e.model||"";ln&&(mt.length>0&&!mt.includes(ln)&&Le(!0),pe(ln,"remembered"));const os=$e.thinkingLevel||"";os&&Yt.includes(os)&&Pe(os,"remembered");const Lt=$e.autoApproveModeId||"";if(Lt&&rt){const Rn=rt.modes.find(zn=>zn.id===Lt);Rn&&Hn(Rn)!=="dangerous"&&ue(Rn.id)}},[rt,St,mt,w,B,pe,Pe,Yt,N]);const Xt=c.useCallback(xe=>{if(Hn(xe)==="dangerous"){ae(xe);return}ue(xe.id)},[]),Mn=c.useMemo(()=>NR(rt,Se,ye),[rt,ye,Se]),ss=c.useCallback(async(xe,Be)=>{const $e=qt.current+1;return qt.current=$e,me(!0),de(""),u(xe,Be).then(at=>{qt.current===$e&&F(at)}).catch(at=>{qt.current===$e&&(F([]),de(at instanceof Error?at.message:f("newSession.errorLoadSavedSessions")))}).finally(()=>{qt.current===$e&&(me(!1),we(!0))})},[u,f]),qn=c.useCallback((xe,Be)=>{Y(iR(xe,Be))},[]);c.useEffect(()=>{qt.current+=1,Z(""),Ie(!1),!j||!B||O==="ide"?Y([]):qn(j.id,B),we(!1),F([]),de(""),me(!1)},[O,qn,ss,j,B]),c.useEffect(()=>{if(!ve)return;const xe=ie.find(Be=>Be.providerSessionId===ve);xe!=null&&xe.canResume||Z("")},[ie,ve]);const Wt=A==="__custom__"?P.trim():A==="__home__"?"":((yu=v.find(xe=>xe.id===A))==null?void 0:yu.path)||"",js=c.useMemo(()=>j?t.filter(xe=>xe.id!==j.id&&xe.daemonId===j.id).map(xe=>xe.workspace):[],[t,j]),rs=c.useMemo(()=>((j==null?void 0:j.recentLaunches)||[]).map(xe=>xe.workspace),[j]),Oo=c.useCallback(xe=>{const Be=String(xe.workspace||"").trim();if(!Be)return;const $e=v.find(at=>sr(at.path)===sr(Be));if($e){E($e.id),T("");return}E("__custom__"),T(Be)},[v]),$o=c.useCallback(xe=>{const Be=String(xe.workspace||"").trim();if(!Be)return{workspaceId:null,workspacePath:null,useHome:!0};const $e=v.find(at=>sr(at.path)===sr(Be));return $e?{workspaceId:$e.id,workspacePath:null,useHome:!1}:{workspaceId:null,workspacePath:Be,useHome:!1}},[v]),Qi=c.useMemo(()=>ie.find(xe=>xe.providerSessionId===ve)||null,[ie,ve]),Ji=c.useCallback(xe=>{if(!j||!B||Ke||!xe.canResume)return;const Be=$o(xe);Z(xe.providerSessionId),Oo(xe),Ae(xe.providerSessionId),Ie(!1),He(!0),it(""),i(j.id,"cli",B,{workspaceId:Be.workspaceId,workspacePath:Be.workspacePath,useHome:Be.useHome,resumeSessionId:xe.providerSessionId,settings:Mn}).then($e=>{if(!$e.ok){dt("error"),it($e.code==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"?f("newSession.errorWorkspaceContextRequired"):$e.error||f("newSession.errorResumeSession"));return}s()}).finally(()=>{He(!1),Ae($e=>$e===xe.providerSessionId?null:$e)})},[Oo,Mn,s,i,$o,Ke,j,B,f]),Xi=((vu=rt==null?void 0:rt.modes.find(xe=>xe.id===Se))==null?void 0:vu.label)||"",Lr=[W.trim(),z.trim(),X.trim(),O==="cli"||N==="mesh"?rt?Xi:ye?f("newSession.autoApproveLegacy"):"":""].filter(Boolean).join(" · "),Dr=c.useCallback(()=>{var $e;if(!j)return;const xe=At.current+1;At.current=xe,E("__custom__"),le(!0),jt("");const Be=ru(j.platform,su(P.trim(),Wt,js,rs,j.defaultWorkspacePath,($e=v.find(at=>at.id===y))==null?void 0:$e.path,v.map(at=>at.path)));_e(!0),r(j.id,Be).then(at=>{At.current===xe&&(Te(at.path),T(at.path),qe(at.directories))}).catch(at=>{At.current===xe&&jt(at instanceof Error?at.message:f("newSession.errorLoadFolder"))}).finally(()=>{At.current===xe&&_e(!1)})},[P,y,rs,js,r,Wt,j,v]),Zi=c.useCallback(xe=>{if(!j)return;const Be=At.current+1;At.current=Be,_e(!0),jt(""),r(j.id,xe).then($e=>{At.current===Be&&(Te($e.path),T($e.path),qe($e.directories))}).catch($e=>{At.current===Be&&jt($e instanceof Error?$e.message:f("newSession.errorLoadFolder"))}).finally(()=>{At.current===Be&&_e(!1)})},[r,j]),ec=c.useCallback(async()=>{if(!j||!Wt)return;Kt(!0),it("");const xe=await o(j.id,Wt);if(Kt(!1),!xe.ok){dt("error"),it(xe.error||f("newSession.errorSaveWorkspace"));return}dt("info"),it(f("newSession.workspaceSaved"))},[o,Wt,j,f]),Fo=c.useCallback(async()=>{if(!j)return;if(N==="mesh"){if(!I||!B)return;He(!0),it(""),bt(null);const $e=await d(j.id,I,B,{initialModel:z.trim()?z.trim():null,initialThinkingLevel:X.trim()?X.trim():null,...Mh(ee,Ce),settings:Mn});if(He(!1),!$e.ok){if($e.code==="mesh_coordinator_manual_mcp_setup_required"&&$e.manualSetup){bt($e.manualSetup),dt("info"),it(f("newSession.errorManualMcpSetup"));return}dt("error"),it($e.error||f("newSession.errorStartMeshCoordinator"));return}ca(Bc,{machineId:j.id,mode:"mesh"}),ca(Th,{meshId:I,cliType:B,model:z.trim(),thinkingLevel:X.trim(),autoApproveModeId:Se}),s();return}if(!O||!B)return;He(!0),it("");const xe=W.trim()?W.trim().split(/\s+/).filter(Boolean):[],Be=O==="ide"?await a(j.id,B,{workspacePath:Wt||null}):await i(j.id,O,B,{workspaceId:A!=="__home__"&&A!=="__custom__"?A:null,workspacePath:A==="__custom__"&&Wt||null,useHome:A==="__home__",resumeSessionId:O==="cli"&&ve?ve:null,cliArgs:xe,initialModel:z.trim()?z.trim():null,initialThinkingLevel:X.trim()?X.trim():null,...Mh(ee,Ce),settings:Mn});if(He(!1),!Be.ok){dt("error"),it(Be.code==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"?f("newSession.errorWorkspaceContextRequired"):Be.error||f("newSession.errorStartSession"));return}O!=="ide"&&W.trim()&&(cR(j.id,B,W),qn(j.id,B)),ca(Bc,{machineId:j.id,mode:"workspace"}),ca(Ah,{workspaceChoice:A,customWorkspacePath:A==="__custom__"?Wt:"",kind:O,target:B,model:O==="ide"?"":z.trim(),thinkingLevel:O==="ide"?"":X.trim(),autoApproveModeId:O==="cli"?Se:""}),s()},[O,W,z,X,ee,Ce,Mn,qn,s,a,d,i,Wt,Se,j,I,ve,B,A,N,f]),Or=O==="cli"&&!!ve,Ho=f(N==="mesh"?"newSession.startMeshCoordinator":O==="cli"?Or?"newSession.resumeSavedHistory":"newSession.startFresh":O==="ide"?"newSession.startIde":"newSession.start"),Bo=f(N==="mesh"?"newSession.startingCoordinator":O==="cli"?Or?"newSession.resumingSavedHistory":"newSession.startingFresh":O==="ide"?"newSession.startingIde":"newSession.starting"),Wo=g.length>5;return j?n.jsxs(n.Fragment,{children:[n.jsxs(Sr,{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(Et,{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:[g.length>1&&n.jsx(bR,{machines:g,selectedMachineId:j.id,useDropdown:Wo,busy:Ne,onSelect:C,onPrefetch:Kn}),n.jsxs(zs,{title:f("newSession.workspace"),action:N==="workspace"?n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Dr,disabled:Ne,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(xe=>n.jsxs("button",{type:"button",role:"radio","aria-checked":N===xe.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${N===xe.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:()=>{k(xe.id),it(""),xe.id==="mesh"&&j&&U!==j.id&&!L&&In(j.id)},disabled:Ne,children:[n.jsx("div",{className:"text-sm font-semibold",children:xe.label}),n.jsx("div",{className:"mt-0.5 text-2xs opacity-80",children:xe.desc})]},xe.id))}),N==="workspace"?n.jsxs(n.Fragment,{children:[n.jsxs("select",{value:A,onChange:xe=>{const Be=xe.target.value;Qe.current=null,E(Be),Be==="__custom__"?Dr():it("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Ne,children:[n.jsx("option",{value:"__home__",children:f("newSession.homeDirectory")}),v.map(xe=>n.jsxs("option",{value:xe.id,children:[xe.id===y?"★ ":"",ya(xe.path,xe.label)||xe.path]},xe.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")}),te&&n.jsx(iu,{inline:!0,title:f("newSession.selectWorkspaceTitle"),description:"",currentPath:be,directories:De,busy:ot,error:st,onClose:()=>le(!1),onNavigate:Zi,onConfirm:xe=>{T(xe),Te(xe),E("__custom__"),le(!1)}}),!te&&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:Dr,disabled:Ne,children:[n.jsx(Ws,{size:14}),f("newSession.selectFolder")]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ec,disabled:Ne||gt,children:f(gt?"newSession.saving":"newSession.saveWorkspace")})]})]}):n.jsx(gR,{loading:L,error:K,meshes:M,selectedMeshId:I,busy:Ne,onSelect:xe=>{xt.current=null,D(xe)}})]}),n.jsx(xR,{targets:Ge,activeKind:O,selectedTarget:B,showCategory:N!=="mesh",busy:Ne,onSelect:xe=>{tt.current=null,Nt.current=null,Bt.current=null,H(xe.kind),q(xe.id)}}),N==="mesh"&&vn&&n.jsx(pR,{setup:vn,providerName:(Re==null?void 0:Re.displayName)||(Re==null?void 0:Re.name)||B}),(N==="mesh"&&!!B||N!=="mesh"&&O!=="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")}),Lr&&n.jsx("span",{className:"ml-auto min-w-0 truncate text-2xs text-text-secondary","data-testid":"new-session-advanced-summary",children:Lr})]}),n.jsxs("div",{className:"space-y-3 px-3 pb-3",children:[N!=="mesh"&&O!=="ide"&&n.jsx(yR,{value:W,recentOptions:ke,busy:Ne,onChange:ce}),(N==="mesh"&&!!B||N!=="mesh"&&O==="cli")&&n.jsx(zs,{title:f("newSession.autoApproveMode"),description:rt?f("newSession.autoApproveModeDescription"):void 0,children:rt?n.jsx(cx,{config:rt,selectedModeId:Se,disabled:Ne,onSelectMode:Xt}):n.jsx(_R,{checked:ye,disabled:Ne,onChange:G})}),(N==="mesh"&&!!B||N!=="mesh"&&O!=="ide")&&n.jsx(vR,{modelOptions:mt,thinkingOptions:Yt,model:z,thinkingLevel:X,modelIsCustom:Oe,busy:Ne,onModelIsCustomChange:Le,onModelChange:xe=>pe(xe,"user"),onThinkingChange:xe=>Pe(xe,"user")})]})]}),N!=="mesh"&&O==="cli"&&n.jsx(hR,{busy:Ne,savedSessionsLoading:se,savedSessionsError:V,savedSessionsLoaded:re,savedSessionsCount:ie.length,selectedSession:Qi,historyOpen:ge,onOpenHistory:()=>{if(!(!j||!B)){if(ge){Ie(!1);return}Ie(!0),uR({hasLoadedInitialResults:re,isLoading:se})&&ss(j.id,B)}},onClearSelection:()=>Z("")}),N!=="mesh"&&O==="cli"&&ge&&n.jsx(dR,{sessions:ie,loading:se,busy:Ne,resumingSessionId:Ke,fallbackWorkspacePath:Wt||null,onRefresh:()=>{!j||!B||ss(j.id,B)},onClose:()=>Ie(!1),onResume:Ji}),Fe&&n.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ut==="info"?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:Fe})]}),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:Ne,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:Fo,disabled:Ne||(N==="mesh"?!I||!B||O!=="cli"||L:!O||!B||A==="__custom__"&&!Wt),children:[n.jsx(Wp,{size:14}),Ne?Bo:Ho]})]})]}),ne&&n.jsx(lx,{mode:ne,onConfirm:()=>{ue(ne.id),ae(null)},onCancel:()=>ae(null)})]}):null}function TR(e,t){const{sendCommand:s}=wt(),[r,o]=c.useState(null),[a,i]=c.useState(!1),l=c.useRef(0);c.useEffect(()=>{const u=l.current+1;if(l.current=u,o(null),!e||!t){i(!1);return}return i(!0),s(e,"git_remote_url",{workspace:t}).then(m=>{if(l.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(()=>{l.current===u&&o(null)}).finally(()=>{l.current===u&&i(!1)}),()=>{l.current+=1}},[e,t,s]);const d=IR(r);return{remoteUrl:r,githubUrl:d,loading:a}}function IR(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 MR(e,t){return t?`git:${t}:${e}`:`git:${e}`}function RR({workspace:e,daemonId:t,includeDiffSummary:s=!1,intervalMs:r=dx}){return{type:"subscribe",topic:"workspace.git",key:MR(e,t),params:{workspace:e,includeDiffSummary:s,intervalMs:r}}}function uu(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Vs(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 PR(e){const t=uu(e);return(t==null?void 0:t.success)===!1?{status:null,error:Vs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Vs(t,"Git status response did not include status")}}function ER(e){const t=uu(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Vs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Vs(t,"Git diff summary response did not include diffSummary")}}function Wc(e){return e===void 0||typeof e=="boolean"}function LR(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Wc(t.binary)&&Wc(t.truncated)&&Wc(t.staged)}function DR(e){const t=uu(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Vs(t,"Git file diff request failed")}:LR(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Vs(t,"Git file diff response did not include a valid diff object")}}function OR({daemonId:e,workspace:t,enabled:s=!0,includeDiffSummary:r=!1,intervalMs:o=dx}){const{sendCommand:a,sendData:i}=wt(),l=typeof t=="string"?t.trim():"",d=!!(s&&e&&l),[u,m]=c.useState(null),[h,p]=c.useState(null),[b,f]=c.useState(!1),[x,g]=c.useState(null),w=c.useRef(0),S=c.useCallback(async()=>{if(!d||!e||!l)return;const j=w.current+1;w.current=j,f(!0),g(null);try{const v=PR(await a(e,"git_status",{workspace:l}));if(w.current!==j)return;if(v.error){m(null),p(null),g(v.error);return}if(m(v.status),!r){p(null);return}const y=ER(await a(e,"git_diff_summary",{workspace:l}));if(w.current!==j)return;if(y.error){p(null),g(y.error);return}p(y.diffSummary)}catch(v){if(w.current!==j)return;g(Vs(v,"Git status request failed"))}finally{w.current===j&&f(!1)}},[d,e,r,a,l]),C=c.useMemo(()=>l?RR({workspace:l,daemonId:e,includeDiffSummary:r,intervalMs:o}):null,[e,r,o,l]);return c.useEffect(()=>{if(w.current+=1,m(null),p(null),f(!1),g(null),!d||!e||!l||!C)return;const j=i?Fn.subscribe({sendData:i},e,C,v=>{var y,N;v.workspace===l&&(m(v.status),p(v.diffSummary??null),g(((y=v.status)==null?void 0:y.error)||((N=v.diffSummary)==null?void 0:N.error)||null),f(!1))},{retryIntervalMs:1e3}):null;return S(),()=>{w.current+=1,j==null||j()}},[d,e,S,C,i,l]),{status:u,diffSummary:h,loading:b,error:x,refresh:S}}const $R={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},FR={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 Rh(e){return e.split("/").pop()??e}function HR(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function BR({files:e,truncated:t,onFileClick:s,selectedPath:r,className:o=""}){const{t:a}=he("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 l=r===i.path,d=$R[i.status]??"?",u=FR[i.status]??"text-text-muted",m=HR(i.path),h=Rh(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 ${l?"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:["← ",Rh(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(La,{i18nKey:"git.changeList.truncatedNote",ns:"common",components:{code:n.jsx("code",{className:"font-mono"})}})})]})}function WR(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 UR({diff:e,binary:t,truncated:s,loading:r,error:o,className:a=""}){const{t:i}=he("common"),l=c.useRef(null);if(c.useEffect(()=>{l.current&&(l.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(`
80
- `);return n.jsxs("div",{ref:l,className:`overflow-auto ${a}`,children:[n.jsx("div",{className:"py-1",children:d.map((u,m)=>WR(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 KR(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(`
81
- `)}function ux({daemonId:e,workspace:t,onClose:s}){const{t:r}=he("common"),{sendCommand:o}=wt(),{status:a,diffSummary:i,loading:l,error:d,refresh:u}=OR({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,h]=c.useState(null),[p,b]=c.useState(null),[f,x]=c.useState(""),[g,w]=c.useState(!1),[S,C]=c.useState(!1),[j,v]=c.useState(null),[y,N]=c.useState(null),{githubUrl:k}=TR(e,t),A=c.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 D=await o(e,"git_diff_file",{workspace:t,path:I.path,staged:I.staged}),L=DR(D);if(L.error||!L.diff){h({path:I.path,diff:"",binary:!1,truncated:!1,loading:!1,error:L.error??"Failed to load diff"});return}h({path:I.path,diff:L.diff.diff,binary:L.diff.binary??!1,truncated:L.diff.truncated??!1,loading:!1,error:null})}catch(D){const L=D instanceof Error?D.message:"Failed to load diff";h({path:I.path,diff:"",binary:!1,truncated:!1,loading:!1,error:L})}}},[e,o,m,t]),E=c.useCallback(I=>{x(""),w(!1),v(null),N(null),b(I)},[]),P=c.useCallback(()=>{b(null),v(null),C(!1)},[]),T=c.useCallback(async()=>{var I,D,L;if(p){C(!0),v(null);try{let $;p==="checkpoint"?$=await o(e,"git_checkpoint",{workspace:t,message:f,includeUntracked:g}):p==="stash"?$=await o(e,"git_stash_push",{workspace:t,message:f,includeUntracked:g}):p==="stash_pop"?$=await o(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&m&&($=await o(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const U=($==null?void 0:$.result)??$;if((U==null?void 0:U.success)===!1||U!=null&&U.error){v((U==null?void 0:U.error)??"Action failed"),C(!1);return}p==="checkpoint"?N(`Checkpoint created: ${((D=(I=U==null?void 0:U.checkpoint)==null?void 0:I.commit)==null?void 0:D.slice(0,7))??"done"}`):p==="stash"?N(`Stashed as ${((L=U==null?void 0:U.stash)==null?void 0:L.stashRef)??"stash@{0}"}`):p==="stash_pop"?N("Stash restored"):(N("File reverted"),h(null)),b(null),await u()}catch($){v($ instanceof Error?$.message:"Action failed")}finally{C(!1)}}},[p,o,e,t,f,g,m,u]),M=!!(a!=null&&a.hasConflicts);c.useEffect(()=>{const I=D=>{D.key==="Escape"&&(p?P():s())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[p,P,s]);const _=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return n.jsx(Un,{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}),k&&n.jsx("a",{href:`${k}/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:l,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(Et,{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")}),_===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:[l&&!i&&n.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:r("git.statusDialog.loading")}),i&&n.jsx(BR,{files:i.files,truncated:i.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:A}),!l&&!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(UR,{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")})})]}),y&&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:y}),n.jsx("button",{onClick:()=>N(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:()=>E("checkpoint"),disabled:M,title:r(M?"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:()=>E("stash"),disabled:M,title:r(M?"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:()=>E("stash_pop"),disabled:M||!(a!=null&&a.stashCount),title:M?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:()=>E("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=KR((a==null?void 0:a.branch)??null,i);navigator.clipboard.writeText(I),N(r("git.statusDialog.copied")),setTimeout(()=>N(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:g,onChange:I=>w(I.target.checked)}),r("git.statusDialog.includeUntracked")]})]}),j&&n.jsx("p",{className:"text-xs text-status-error",children:j}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{onClick:P,disabled:S,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:T,disabled:S||(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(S?"git.statusDialog.working":"common.confirm")})]})]})})]})})})}function qR({isMobile:e,showMobileChatMode:t,visibleConversationCount:s}){const[r,o]=c.useState(!1),[a,i]=c.useState(!1),[l,d]=c.useState(!1),[u,m]=c.useState(!1),[h,p]=c.useState(!1),[b,f]=c.useState("quickstart"),[x,g]=c.useState("workspace"),w=c.useMemo(()=>!t&&!e,[t,e]),S=c.useCallback(k=>{o(k),k&&i(!1)},[]),C=c.useCallback(k=>{i(k),k&&o(!1)},[]),j=c.useCallback(()=>{f(s===0?"quickstart":"shortcuts"),g("workspace"),d(!0),o(!1),i(!1)},[s]),v=c.useCallback(()=>{d(!1)},[]),y=c.useCallback(()=>{m(!0)},[]),N=c.useCallback(()=>{m(!1)},[]);return c.useEffect(()=>{if(!w){p(!1);return}p(!0);const k=window.setTimeout(()=>{p(!1)},1e4);return()=>window.clearTimeout(k)},[w]),{inboxOpen:r,hiddenOpen:a,shortcutHelpOpen:l,newSessionOpen:u,guideNudgeVisible:h,guideTab:b,shortcutSection:x,isDesktopDashboard:w,setGuideTab:f,setShortcutSection:g,handleInboxOpenChange:S,handleHiddenOpenChange:C,handleOpenShortcutHelp:j,closeShortcutHelp:v,openNewSession:y,closeNewSession:N}}function zR({machineEntries:e,conversations:t,sendDaemonCommand:s}){const[r,o]=c.useState(!1),[a,i]=c.useState(null),[l,d]=c.useState(()=>z1()),u=c.useRef(!1),m=c.useMemo(()=>q1(e,l),[e,l]),h=m.defaultTarget,p=G1(t,h),b=c.useCallback(async f=>{const x=f||h;if(!(!x||u.current)){f&&(V1(f),d({...f})),u.current=!0,o(!0),i(null);try{const g=await s(x.machineId,F1,U1(x)),w=(g==null?void 0:g.result)||g;((g==null?void 0:g.success)===!1||(w==null?void 0:w.success)===!1)&&i(String((w==null?void 0:w.error)||(g==null?void 0:g.error)||(w==null?void 0:w.code)||"launch_assistant failed"))}catch(g){i(g instanceof Error?g.message:String(g))}finally{u.current=!1,o(!1)}}},[s,h]);return{visible:p,pending:r,error:a,defaultTarget:h,machines:m.machines,start:b}}function VR(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 GR(e){return e instanceof Error?e.message:String(e||"")}function YR(e){const t=GR(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function QR({showMobileChatMode:e,isMobile:t,activeConv:s,wsStatus:r,isConnected:o,onOpenHistory:a,onOpenRemote:i,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:u,mobileChatConversations:m,hiddenConversations:h,ides:p,actionLogs:b,sendDaemonCommand:f,setActionLogs:x,setCliViewModeOverrides:g,isStandalone:w,initialDataLoaded:S,userName:C,requestedMobileTabKey:j,onRequestedMobileTabConsumed:v,requestedMachineId:y,onRequestedMachineConsumed:N,requestedNewSessionLaunch:k,onRequestedNewSessionLaunchConsumed:A,requestedMobileSection:E,onRequestedMobileSectionConsumed:P,containerRef:T,isSplitMode:M,numGroups:_,groupSizes:I,groupedConvs:D,clearedTabs:L,focusedGroup:$,focusGroup:U,moveTabToGroup:J,splitTabRelative:K,closeGroup:R,handleResizeStart:O,groupActiveTabIds:H,setGroupActiveTab:B,groupTabOrders:q,setGroupTabOrder:W,toggleHiddenTab:ce,visibleConversations:ye,requestedDesktopTabKey:G,onRequestedDesktopTabConsumed:Se,onDesktopActiveTabChange:ue,onRequestScrollToBottom:ne,onHideConversation:ae,onShowHiddenConversation:ee,onShowAllHiddenConversations:oe,scrollToBottomRequest:Ce,machineEntries:Q,layoutProfile:z,onBrowseMachineDirectory:X,onSaveMachineWorkspace:pe,onLaunchMachineIde:Pe,onLaunchMachineProvider:Oe,onListMachineMeshes:Le,onLaunchMeshCoordinator:ke,onListMachineSavedSessions:Y,notifications:ve,notificationUnreadCount:Z,liveSessionInboxState:ie,onMarkNotificationRead:F,onMarkNotificationUnread:se,onDeleteNotification:me}){const{t:re}=he(),we=yt.useRef(null),{inboxOpen:V,hiddenOpen:de,shortcutHelpOpen:ge,newSessionOpen:Ie,guideNudgeVisible:Ke,guideTab:Ae,shortcutSection:Ne,isDesktopDashboard:He,setGuideTab:Fe,setShortcutSection:it,handleInboxOpenChange:ut,handleHiddenOpenChange:dt,handleOpenShortcutHelp:Tt,closeShortcutHelp:bt,openNewSession:te,closeNewSession:le}=qR({isMobile:t,showMobileChatMode:e,visibleConversationCount:ye.length}),[be,Te]=yt.useState(null);yt.useEffect(()=>{k&&(Te({machineId:k.machineId,workspaceId:k.workspaceId??null,mode:k.mode||"workspace",meshWorkspacePath:k.meshWorkspacePath??null}),te(),A==null||A())},[k,te,A]);const De=yt.useCallback(()=>{Te(null),le()},[le]),{confirm:qe,confirmDialog:ot}=Tr(),[_e,st]=yt.useState(null),[jt,gt]=yt.useState(null),Kt=yt.useCallback((Re,We)=>{st({daemonId:Re,workspace:We})},[]),fe=yt.useCallback(Re=>{gt(Re)},[]),Me=yt.useCallback(Re=>{var We;An.flushSync(()=>{ee(Re)}),(We=we.current)==null||We.restoreHiddenTabToSavedLocation(Re.tabKey)},[ee]),Ee=yt.useCallback(Re=>{var rt;const We=m.find(St=>no(St,Re))||h.find(St=>no(St,Re));We&&(h.some(St=>St.tabKey===We.tabKey)&&Me(We),ue(We.tabKey),(rt=we.current)==null||rt.activateConversationTab(We.tabKey),ne(We.tabKey,"notification-open")),F(Re.id),ut(!1)},[Me,h,m,ue,F,ne]);yt.useEffect(()=>MA(Re=>{var St;const We=[{sessionId:Re.sessionId},...Re.providerSessionId?[{providerSessionId:Re.providerSessionId}]:[]];let rt;for(const zt of We)if(rt=m.find(mt=>no(mt,zt))||h.find(mt=>no(mt,zt)),rt)break;if(!rt){et.showToast(re("sessionNav.chatNotFound"),"info");return}h.some(zt=>zt.tabKey===rt.tabKey)&&Me(rt),gt(null),ue(rt.tabKey),(St=we.current)==null||St.activateConversationTab(rt.tabKey),ne(rt.tabKey,"conversation-open")}),[Me,h,m,ue,ne,re]);const Ve=yt.useCallback(async()=>{var We;await qe({title:re("common.confirmTitle"),description:re("dashboard.hidden.resetPanelsConfirm"),confirmLabel:re("common.confirm")})&&((We=we.current)==null||We.resetAllPanelsToMain(),dt(!1))},[qe,dt,re]),Qe=yt.useCallback(async Re=>{var mt;if(!s)return;const We=(mt=s.modalButtons)==null?void 0:mt[Re];if(!We)return;const rt=ps(s);if(!rt)return;const St=We.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),zt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(St);try{await f(rt,"resolve_action",{button:We,action:zt?"approve":"reject",buttonIndex:Re,...gs(s)})}catch(Yt){YR(Yt)||console.error("[Shortcut approval] Failed:",Yt)}},[s,f]),{isMac:ht,actionDefinitions:tt,actionShortcuts:Nt,shortcutListening:xt,shortcutListeningDraft:Bt,setShortcutListening:Jt,setShortcutListeningDraft:on,saveShortcuts:qt}=MM({enabled:He&&!ge,onTrigger:Re=>{var We,rt,St,zt,mt,Yt,Tn,vn,In,Xt,Mn,ss,qn,Wt,js,rs;if(Re==="openShortcutHelp"){Tt();return}if(Re==="openNewSession"){te();return}if(Re==="hideCurrentTab"){s&&ae(s);return}if(Re==="toggleHiddenTabs"){dt(!de);return}if(Re==="openHistoryForActiveTab"){s&&a(s);return}if(Re==="openRemoteForActiveTab"){s&&!ft(s)&&i(s);return}if(Re==="splitActiveTabRight"){(We=we.current)==null||We.splitActiveTabRight();return}if(Re==="splitActiveTabDown"){(rt=we.current)==null||rt.splitActiveTabDown();return}if(Re==="floatActiveTab"){(St=we.current)==null||St.floatActiveTab();return}if(Re==="popoutActiveTab"){(zt=we.current)==null||zt.popoutActiveTab();return}if(Re==="dockActiveTab"){(mt=we.current)==null||mt.dockActiveTab();return}if(Re==="focusLeftPane"){(Yt=we.current)==null||Yt.focusLeftPane();return}if(Re==="focusRightPane"){(Tn=we.current)==null||Tn.focusRightPane();return}if(Re==="focusUpPane"){(vn=we.current)==null||vn.focusUpPane();return}if(Re==="focusDownPane"){(In=we.current)==null||In.focusDownPane();return}if(Re==="moveActiveTabToLeftPane"){(Xt=we.current)==null||Xt.moveActiveTabToLeftPane();return}if(Re==="moveActiveTabToRightPane"){(Mn=we.current)==null||Mn.moveActiveTabToRightPane();return}if(Re==="moveActiveTabToUpPane"){(ss=we.current)==null||ss.moveActiveTabToUpPane();return}if(Re==="moveActiveTabToDownPane"){(qn=we.current)==null||qn.moveActiveTabToDownPane();return}if(Re==="triggerPrimaryApprovalAction"){Qe(0);return}if(Re==="triggerSecondaryApprovalAction"){Qe(1);return}if(Re==="triggerTertiaryApprovalAction"){Qe(2);return}if(Re==="setActiveTabShortcut"){(Wt=we.current)==null||Wt.setShortcutForActiveTab();return}if(Re==="selectPreviousGroupTab"){(js=we.current)==null||js.activatePreviousTabInGroup();return}if(Re==="selectNextGroupTab"){(rs=we.current)==null||rs.activateNextTabInGroup();return}!s||!ft(s)||Re==="toggleCliView"&&u(d==="chat"?"terminal":"chat")}}),At=yt.useCallback(()=>{bt(),Jt(null),on([])},[bt,Jt,on]),an=yt.useMemo(()=>Ne==="all"?tt:tt.filter(Re=>VR(Re)===Ne),[tt,Ne]),Kn=yt.useMemo(()=>[pt("triggerPrimaryApprovalAction",ht),pt("triggerSecondaryApprovalAction",ht),pt("triggerTertiaryApprovalAction",ht)].filter(Boolean).join(" / "),[ht]),Ct=ht?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",cn=yt.useCallback(()=>{const Re=Object.fromEntries(tt.map(We=>[We.id,""]));qt(Re)},[tt,qt]),fn=yt.useCallback(async()=>{if(!await qe({title:re("common.confirmTitle"),description:re("dashboard.guide.shortcuts.resetConfirm"),confirmLabel:re("common.confirm")}))return;const We=Object.fromEntries(tt.map(rt=>[rt.id,rt.defaultShortcut]));qt(We)},[tt,qe,qt,re]);yt.useEffect(()=>{const Re=We=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?We.metaKey&&We.key.toLowerCase()==="w":We.ctrlKey&&We.key.toLowerCase()==="w")&&(We.preventDefault(),s&&ae&&ae(s))};return window.addEventListener("keydown",Re),()=>window.removeEventListener("keydown",Re)},[s,ae]),yt.useEffect(()=>{if(!ge||xt)return;const Re=We=>{We.key==="Escape"&&(We.preventDefault(),At())};return window.addEventListener("keydown",Re,!0),()=>window.removeEventListener("keydown",Re,!0)},[At,ge,xt]);const Ge=yt.useMemo(()=>[...ye,...h],[ye,h]),lt=zR({machineEntries:Q,conversations:Ge,sendDaemonCommand:f});return n.jsxs(n.Fragment,{children:[!e&&n.jsx(eT,{activeConv:s,wsStatus:r,isConnected:o,conversations:ye,hiddenConversations:h,onOpenHistory:a,onHideConversation:ae,onShowConversation:Me,onShowAllHidden:oe,onResetPanelsToMain:Ve,notifications:ve,notificationUnreadCount:Z,onOpenNotification:Ee,onMarkNotificationRead:F,onMarkNotificationUnread:se,onDeleteNotification:me,inboxOpen:V,onInboxOpenChange:ut,hiddenOpen:de,onHiddenOpenChange:dt,onOpenNewSession:t?void 0:te,onStartAssistant:lt.visible?()=>{lt.start()}:void 0,startAssistantPending:lt.pending,startAssistantError:lt.error,onStartAssistantWith:lt.visible?Re=>{lt.start(Re)}:void 0,startAssistantMachines:lt.machines,startAssistantDefault:lt.defaultTarget,onOpenDashboardGuide:Tt,guideNudgeVisible:Ke,actionShortcuts:Nt,onOpenRemote:()=>{!s||ft(s)||i(s)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:u,onOpenGitDialog:Kt,onOpenMeshGraph:fe}),e?n.jsx(yM,{conversations:m,hiddenConversations:h,ides:p,actionLogs:b,sendDaemonCommand:f,setActionLogs:x,setCliViewModeOverrides:g,isStandalone:w,userName:C,requestedActiveTabKey:j,onRequestedActiveTabConsumed:v,requestedMachineId:y,onRequestedMachineConsumed:N,requestedMobileSection:E,onRequestedMobileSectionConsumed:P,onOpenHistory:a,onOpenRemote:i,onStopCli:l,wsStatus:r,isConnected:o,initialDataLoaded:S,onShowAllHiddenConversations:oe,onHideConversation:ae,onShowHiddenConversation:Me,onOpenMeshGraph:fe,onOpenNewSession:te,liveSessionInboxState:ie}):t?n.jsx(_M,{containerRef:T,isSplitMode:M,numGroups:_,groupSizes:I,groupedConvs:D,clearedTabs:L,ides:p,actionLogs:b,sendDaemonCommand:f,setActionLogs:x,isStandalone:w,hasRegisteredMachines:Q.length>0,initialDataLoaded:S,userName:C,focusedGroup:$,focusGroup:U,moveTabToGroup:J,splitTabRelative:K,closeGroup:R,handleResizeStart:O,groupActiveTabIds:H,setGroupActiveTab:B,groupTabOrders:q,setGroupTabOrder:W,toggleHiddenTab:ce,onOpenNewSession:te,allowTabShortcuts:!1,liveSessionInboxState:ie}):n.jsx(sR,{visibleConversations:ye,clearedTabs:L,ides:p,actionLogs:b,sendDaemonCommand:f,setActionLogs:x,isStandalone:w,hasRegisteredMachines:Q.length>0,initialDataLoaded:S,userName:C,toggleHiddenTab:ce,actionShortcuts:Nt,registerActionHandlers:Re=>{we.current=Re},onActiveTabChange:ue,requestedActiveTabKey:G,onRequestedActiveTabConsumed:Se,onRequestScrollToBottom:ne,scrollToBottomRequest:Ce,onOpenNewSession:te,liveSessionInboxState:ie,layoutProfile:z}),Ie&&n.jsx(AR,{machines:Q,ides:p,initialMachineId:(be==null?void 0:be.machineId)||null,initialWorkspaceId:(be==null?void 0:be.workspaceId)||null,initialLaunchMode:(be==null?void 0:be.mode)||null,initialMeshWorkspacePath:(be==null?void 0:be.meshWorkspacePath)||null,onClose:De,onBrowseDirectory:X,onSaveWorkspace:pe,onLaunchIde:Pe,onLaunchProvider:Oe,onListMeshes:Le,onLaunchMeshCoordinator:ke,onListSavedSessions:Y},be?`${be.machineId}:${be.workspaceId||""}:${be.mode||""}:${be.meshWorkspacePath||""}`:"default"),jt&&n.jsx(qd,{activeConv:jt,sendDaemonCommand:f,onClose:()=>gt(null)}),ot,_e&&n.jsx(ux,{daemonId:_e.daemonId,workspace:_e.workspace,onClose:()=>st(null)}),ge&&n.jsxs(Sr,{chrome:!1,onClose:At,closeOnEsc:!1,ariaLabel:re("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:re("dashboard.guide.title")}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:re("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:At,"aria-label":re("dashboard.guide.close"),children:n.jsx(Et,{size:14})})]}),n.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:re("dashboard.guide.tabs.overview")},{id:"quickstart",label:re("dashboard.guide.tabs.quickstart")},{id:"shortcuts",label:re("dashboard.guide.tabs.shortcuts")}].map(Re=>n.jsx("button",{type:"button",className:`btn btn-sm ${Ae===Re.id?"btn-primary":"btn-secondary"}`,onClick:()=>Fe(Re.id),children:Re.label},Re.id))}),Ae==="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:re("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:re("dashboard.guide.overview.whatLivesWhere.tabsLabel")})," ",re("dashboard.guide.overview.whatLivesWhere.tabsText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.whatLivesWhere.hiddenLabel")})," ",re("dashboard.guide.overview.whatLivesWhere.hiddenText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.whatLivesWhere.inboxLabel")})," ",re("dashboard.guide.overview.whatLivesWhere.inboxText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.whatLivesWhere.cliToggleLabel")})," ",re("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:re("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:re("dashboard.guide.overview.usefulFlows.reviewLabel")})," ",re("dashboard.guide.overview.usefulFlows.reviewText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.clutterLabel")})," ",re("dashboard.guide.overview.usefulFlows.clutterText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.splitLabel")})," ",re("dashboard.guide.overview.usefulFlows.splitText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.detachedLabel")})," ",re("dashboard.guide.overview.usefulFlows.detachedText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.dockingLabel")})," ",re("dashboard.guide.overview.usefulFlows.dockingText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.perTabLabel")})," ",re("dashboard.guide.overview.usefulFlows.perTabText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.approvalLabel")})," ",re("dashboard.guide.overview.usefulFlows.approvalText",{keys:Kn})]})]})]})]}),Ae==="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:re("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."})," ",re("dashboard.guide.quickstart.desktop.step1")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," ",re("dashboard.guide.quickstart.desktop.step2")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," ",re("dashboard.guide.quickstart.desktop.step3")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," ",re("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:re("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."})," ",re("dashboard.guide.quickstart.mobile.step1")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," ",re("dashboard.guide.quickstart.mobile.step2")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," ",re("dashboard.guide.quickstart.mobile.step3")]})]})]})]}),Ae==="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:re("dashboard.guide.shortcuts.sections.all")},{id:"workspace",label:re("dashboard.guide.shortcuts.sections.workspace")},{id:"panes",label:re("dashboard.guide.shortcuts.sections.panes")},{id:"approvals",label:re("dashboard.guide.shortcuts.sections.approvals")}].map(Re=>n.jsx("button",{type:"button",className:`btn btn-sm ${Ne===Re.id?"btn-primary":"btn-secondary"}`,onClick:()=>it(Re.id),children:Re.label},Re.id))}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:cn,children:re("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:fn,children:re("dashboard.guide.shortcuts.resetToDefaults")})]})]}),n.jsx("div",{className:"space-y-2",children:an.map(Re=>n.jsx("div",{className:`rounded-xl border px-4 py-3 ${xt===Re.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:re(`dashboard.shortcutDefs.${Re.id}.label`,Re.label)}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:re(`dashboard.shortcutDefs.${Re.id}.description`,Re.description)}),n.jsxs("div",{className:"text-2xs text-text-muted mt-2",children:[re("dashboard.guide.shortcuts.default")," ",n.jsx("span",{className:"font-mono",children:Re.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:xt===Re.id?Bt.length>0?`${Bt.join(" ")} ...`:re("dashboard.guide.shortcuts.listening"):Nt[Re.id]||re("dashboard.guide.shortcuts.off")}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Jt(Re.id),on([])},children:xt===Re.id?re("dashboard.guide.shortcuts.setListening"):re("dashboard.guide.shortcuts.set")}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const We={...Nt};We[Re.id]="",qt(We)},children:re("dashboard.guide.shortcuts.disable")})]})]})},Re.id))}),n.jsx("div",{className:"text-2xs text-text-muted mt-4",children:re("dashboard.guide.shortcuts.footer",{keys:Ct})})]})]})]})}function JR({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,l=a.status==="waiting_approval",d=Us(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:l?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),a.title,l&&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 XR({ideData:e,allIdes:t,connectionStates:s,ideName:r,preferredTabKey:o}){const[a,i]=c.useState(()=>o||"native"),l=c.useMemo(()=>hg(t),[t]),d=c.useMemo(()=>e?Gd(e,{machineNames:l,connectionStates:s,defaultConnectionState:"new"}):[],[e,l,s]),u=c.useMemo(()=>d.find(x=>x.streamSource==="native"),[d]),m=c.useMemo(()=>d.filter(x=>x.streamSource==="agent-stream"),[d]),h=c.useMemo(()=>e?_n(d,e.id):null,[d,e]);c.useEffect(()=>{o&&i(o)},[o]),c.useEffect(()=>{if(o||!h)return;const x=h.streamSource==="native"?"native":h.tabKey;!x||a===x||a==="native"&&i(x)},[a,h,o]),c.useEffect(()=>{var x;a!=="native"&&(m.some(g=>g.tabKey===a)||i(((x=m[0])==null?void 0:x.tabKey)||"native"))},[a,m]),c.useEffect(()=>{a==="native"&&(u||m[0]&&i(m[0].tabKey))},[a,u,m]);const p=c.useMemo(()=>a==="native"&&u?u:m.find(x=>x.tabKey===a)||h||u||m[0],[a,u,h,m]),b=c.useMemo(()=>m.map(x=>({tabKey:x.tabKey,title:Lb(x)||r,status:x.status})),[m,r]),f=c.useCallback(x=>{if(x)return d.find(g=>no(g,{sessionId:x,routeId:x,tabKey:x,providerSessionId:x}))},[d]);return{activeChatTab:a,setActiveChatTab:i,activeConv:p,conversations:d,extensionTabs:b,hasExtensions:b.length>0,resolveConversationByTarget:f}}function ZR({activeConv:e,ideEntry:t,ides:s,connectionStates:r,actionLogs:o,sendDaemonCommand:a,setActionLogs:i,isStandalone:l,userName:d,onOpenHistory:u,onConversationChange:m,onClose:h,onRetryConnection:p}){const{t:b}=he("common"),[f,x]=c.useState("split"),[g,w]=c.useState(()=>bs(e)?"native":e.tabKey),S=c.useRef(null),C=c.useMemo(()=>t||s.find(K=>K.id===e.routeId),[e.routeId,t,s]),j=c.useMemo(()=>$t((C==null?void 0:C.type)||""),[C==null?void 0:C.type]),{conversations:v,extensionTabs:y,hasExtensions:N}=XR({ideData:C,allIdes:s,connectionStates:r,ideName:j||"IDE",preferredTabKey:bs(e)?void 0:e.tabKey}),k=c.useMemo(()=>C?_n(v,C.id):null,[C,v]);c.useEffect(()=>{const K=S.current,R={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(S.current=R,!(K&&K.routeId===R.routeId&&K.tabKey===R.tabKey&&K.streamSource===R.streamSource)){if(bs(e)){w("native");return}w(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),c.useEffect(()=>{if(g==="native"){if(v.some(K=>K.streamSource==="native"))return;(k==null?void 0:k.streamSource)==="agent-stream"&&w(k.tabKey);return}if(!v.some(K=>K.tabKey===g)){if((k==null?void 0:k.streamSource)==="agent-stream"){w(k.tabKey);return}w("native")}},[v,g,k]);const A=c.useMemo(()=>g==="native"?v.find(K=>K.streamSource==="native")||e:v.find(K=>K.tabKey===g)||e,[e,v,g]),E=vs(A),P=Pi({sendDaemonCommand:a,activeConv:A,setActionLogs:i,isStandalone:l}),{connScreenshot:T,screenshotUsage:M,handleRemoteAction:_}=nx({doId:E,targetSessionId:rb(A),connState:A.connectionState||"new",viewMode:f}),I=c.useMemo(()=>o.filter(K=>K.routeId===A.tabKey),[o,A.tabKey]),D=A.tabKey,L=c.useCallback(K=>{i(R=>[...R,{routeId:D,text:K,timestamp:Date.now()}])},[D,i]),$=C==null?void 0:C.machineId,U=c.useMemo(()=>{if(!(!p||!$))return()=>p($)},[p,$]);c.useEffect(()=>{m==null||m(A)},[A,m]),c.useEffect(()=>{const K=R=>{R.key==="Escape"&&h()};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[h]);const J=c.useCallback(K=>{K.stopPropagation()},[]);return n.jsx(Un,{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:J,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(Bn,{size:16})}),n.jsx("span",{className:"truncate",children:Rd(A)||b("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:b("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(K=>{const R=f===K;return n.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${R?"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(K),title:b(K==="split"?"dashboard.remoteDialog.splitView":"dashboard.remoteDialog.remoteOnly"),children:K==="split"?n.jsx(Nw,{size:15}):n.jsx(Bn,{size:15})},K)})}),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:b("dashboard.remoteDialog.history"),children:[n.jsx(Bp,{size:14,className:"md:mr-1.5"}),n.jsx("span",{className:"hidden md:inline",children:b("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:b("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(JR,{hasExtensions:N,ideName:j||"IDE",activeChatTab:g,extensionTabs:y,onSelectTab:w}),n.jsx(Cf,{activeConv:A,onModalButton:P.handleModalButton}),n.jsx(Cb,{activeConv:A,ideEntry:C,showMetaChips:!1,handleSendChat:P.handleSendChat,handleSendNowQueued:P.handleSendNowQueued,handleCancelQueued:P.handleCancelQueued,isSendingChat:P.isSendingChat,sendFeedbackMessage:P.sendFeedbackMessage,pendingLocalMessage:P.pendingLocalMessage,pendingLocalMessages:P.pendingLocalMessages,retireEchoedPendingMessages:P.retireEchoedPendingMessages,handleFocusAgent:P.handleFocusAgent,isFocusingAgent:P.isFocusingAgent,actionLogs:I,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:L,connState:A.connectionState||"new",connScreenshot:T,screenshotUsage:M,transportType:A.transport,onAction:_,onRetry:U})})]})]})})})}function eP({activeConv:e,canSaveAndStop:t=!1,onCancel:s,onStopNow:r,onSaveAndStop:o}){const{t:a}=he(),i=u1(e);return n.jsx(Un,{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 tP({historyModal:e,remoteDialog:t,cliStopDialog:s,connectionBanner:r,toastOverlay:o,onboarding:a,interactivePrompt:i,suppressInteractivePrompt:l=!1}){var d;return n.jsxs(n.Fragment,{children:[!r.suppress&&n.jsx(M1,{wsStatus:r.wsStatus,showReconnected:r.showReconnected,loginUrl:r.loginUrl,onReconnect:r.onReconnect}),e.open&&e.targetConv&&n.jsx(lT,{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(ZR,{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&&ft(s.targetConv)&&n.jsx(eP,{activeConv:s.targetConv,canSaveAndStop:ft(s.targetConv)&&!!((d=s.targetConv.resume)!=null&&d.supported),onCancel:s.onCancel,onStopNow:s.onStopNow,onSaveAndStop:s.onSaveAndStop}),n.jsx(ug,{toasts:o.toasts,onDismiss:o.onDismiss,onClickToast:o.onClick}),!l&&n.jsx(Nd,{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(M2,{onClose:a.onClose,standalone:a.standalone})]})}function nP({daemons:e,targetVersion:t,required:s=!1,upgradingDaemons:r,onUpgrade:o,onDismiss:a}){const{t:i}=he("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(Ar,{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(l=>{const d=pn(l,{fallbackId:l.id}),u=r[l.id],m=l.version||l.daemonVersion||i("dashboard.versionBanner.unknownVersion"),h=l.versionUpdateRequired===!0,p=Eg(l,{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(l.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(l.id),children:p})]},l.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(Et,{size:16})})]})}function sP(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function rP(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 oP(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>rP(t)).map(t=>t.id)}}function aP({suppressConnectionBanner:e=!1}={}){var Fo,Or,Ho,Bo,Wo;const{sendCommand:t}=wt(),s=Rr(),r=Ng(),o=hi(),a=Gs(),[i,l]=bp(),d=i.get("activeTab"),u=((Fo=o.state)==null?void 0:Fo.openRemoteForTabKey)||null,m=((Or=o.state)==null?void 0:Or.openMachineId)||null,h=((Ho=o.state)==null?void 0:Ho.openNewSession)||null,p=((Bo=o.state)==null?void 0:Bo.mobileSection)||null,b=Ii(),f=b.ides||[],x=b.initialLoaded??!0,{updateRouteChats:g,setToasts:w}=b,{hydrateInteractivePrompt:S}=gr(),[C,j]=c.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}});c.useEffect(()=>{const Xe=()=>j(!1);return window.addEventListener(Yl,Xe),()=>window.removeEventListener(Yl,Xe)},[]);const v=b.toasts||[],y=b.wsStatus||"connected",N=b.isConnected??!0,k=b.connectionStates||{},A=b.showReconnected||!1,{layoutProfile:E,groupAssignments:P,updateGroupAssignments:T,focusedGroup:M,updateFocusedGroup:_,focusGroup:I,groupActiveTabIds:D,updateGroupActiveTabIds:L,setGroupActiveTab:$,groupTabOrders:U,updateGroupTabOrders:J,setGroupTabOrder:K,groupSizes:R,updateGroupSizes:O,isMobile:H,hasHydratedStoredLayout:B,hydrateStoredLayout:q,focusConversationTab:W}=cI(),[ce,ye]=c.useState(()=>Xd());c.useEffect(()=>h2(ye),[]);const G=c.useMemo(()=>sP({isMobile:H,mobileViewMode:ce}),[H,ce]),[Se,ue]=c.useState([]),[ne,ae]=c.useState({}),[ee,oe]=c.useState({});Io("Dashboard",{ideCount:f.length,toastCount:v.length,focusedGroup:M,groupCount:Object.keys(P).length,actionLogCount:Se.length});const Ce=c.useMemo(()=>f.filter(Xe=>Xe.type==="adhdev-daemon").sort(Wa),[f]),z=!!Ce[0];c.useEffect(()=>{const{metadataDaemonIds:Xe,runtimeDaemonIds:It}=oP(Ce);for(const wn of Xe)s(wn,{minFreshMs:3e4}).catch(()=>{});for(const wn of It)r(wn,{minFreshMs:3e4}).catch(()=>{})},[s,r,Ce]);const X=c.useMemo(()=>E2(f,ne),[f,ne]),{conversations:pe,visibleConversations:Pe,visibleTabKeys:Oe,resolveConversationBySessionId:Le,resolveConversationByTarget:ke}=V2({ides:X,connectionStates:k,clearedTabs:ee}),Y=c.useMemo(()=>new Map(pe.map(Xe=>[Xe.tabKey,Xe])),[pe]);b_(Pe,G);const ve=c.useMemo(()=>jf(f),[f]),Z=qg(ve,t,c.useCallback(Xe=>dr(w,Xe),[w])),{notifications:ie,unreadCount:F}=NI({conversations:pe,liveSessionInboxState:ve}),{handleMarkDashboardNotificationRead:se,handleMarkDashboardNotificationUnread:me,handleDeleteDashboardNotification:re}=CI({notifications:ie,sendDaemonCommand:t}),{containerRef:we,normalizedGroupAssignments:V,numGroups:de,isSplitMode:ge,groupedConvs:Ie,moveTabToGroup:Ke,closeGroup:Ae,handleResizeStart:Ne,splitTabRelative:He}=fI({groupAssignments:P,updateGroupAssignments:T,updateFocusedGroup:_,updateGroupActiveTabIds:L,updateGroupTabOrders:J,groupSizes:R,updateGroupSizes:O,isMobile:H,visibleConversations:Pe,visibleTabKeys:Oe}),{activeConv:Fe,openDesktopConversation:it,requestScrollToBottom:ut,scrollToBottomRequest:dt,setDesktopActiveTab:Tt}=BI({isMobile:H,conversations:pe,visibleConversations:Pe,groupActiveTabIds:D,focusedGroup:M,groupedConvs:Ie,setSearchParams:l});KI({activeConv:Fe,isMobile:H,liveSessionInboxState:ve,sendDaemonCommand:t});const{requestedDesktopTabKey:bt,requestedMobileTabKey:te,consumeRequestedActiveTab:le}=G2({isMobile:H,urlActiveTab:d,resolveConversationBySessionId:Le,setSearchParams:l}),{remoteDialogConv:be,remoteDialogIdeEntry:Te,remoteDialogActiveConv:De,setRemoteDialogActiveConv:qe,openRemoteDialog:ot,closeRemoteDialog:_e,cliStopDialogOpen:st,cliStopTargetConv:jt,requestCliStop:gt,cancelCliStop:Kt,confirmCliStop:fe}=VI({isMobile:H,location:o,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:bt,conversations:pe,ides:f,resolveConversationByTarget:ke,activeConv:Fe,sendDaemonCommand:t}),{historyModalOpen:Me,openHistoryModal:Ee,closeHistoryModal:Ve,historyTargetConv:Qe,isSavedSessionHistoryTarget:ht,isHistoryCreatingChat:tt,isHistoryRefreshingHistory:Nt,handleHistorySwitchSession:xt,handleHistoryNewChat:Bt,handleHistoryRefresh:Jt,savedHistorySessions:on,savedHistoryFilters:qt,setSavedHistoryFilters:At,missingWorkspaceResumePath:an,isSavedHistoryLoading:Kn,resumingSavedHistorySessionId:Ct,handleRefreshSavedHistory:cn,handleResumeSavedHistorySession:fn}=qI({activeConv:Fe,remoteDialogConv:be,remoteDialogActiveConv:De,ides:f,sendDaemonCommand:t,updateRouteChats:g,setToasts:w,setClearedTabs:oe,setSearchParams:l}),Ge=c.useMemo(()=>Pe,[Pe]),lt=H&&ce==="chat",Re=c.useMemo(()=>pe.filter(Xe=>Tk(ys(Xe,ve))),[pe,ve]),We=c.useCallback(Xe=>{const It=new URLSearchParams(i);It.set("activeTab",Xe),l(It,{replace:!0})},[i,l]),{trackPendingLaunch:rt}=LI({ides:f,conversations:pe,onOpenSession:We}),{handleBrowseMachineDirectory:St,handleSaveMachineWorkspace:zt,handleLaunchMachineIde:mt,handleLaunchMachineProvider:Yt,handleListMachineMeshes:Tn,handleLaunchMeshCoordinator:vn,handleListMachineSavedSessions:In,setActiveCliViewMode:Xt}=$I({sendDaemonCommand:t,trackPendingLaunch:rt,onOpenSession:We,activeConv:Fe,ides:f,setCliViewModeOverrides:ae});D2({visibleConversations:Pe,clearedTabs:ee,setClearedTabs:oe,setActionLogs:ue,isConversationMuted:Z.isMuted}),Y2({ides:f,sendDaemonCommand:t,setToasts:w,resolveConversationByTarget:ke,hydrateInteractivePrompt:S});const Mn=Ni((Fe==null?void 0:Fe.sessionId)??(Fe==null?void 0:Fe.routeId)??null),{isRefreshingHistory:ss,handleRefreshHistory:qn}=Pg({sendDaemonCommand:t,activeConv:Fe,chats:(Wo=f.find(Xe=>Xe.id===(Fe==null?void 0:Fe.routeId)))==null?void 0:Wo.chats,updateRouteChats:g,setToasts:w,setClearedTabs:oe});dI({urlActiveTab:H&&!lt?d:null,conversations:pe,resolveConversationBySessionId:Le,normalizedGroupAssignments:V,hasHydratedStoredLayout:H&&!lt?B:!0,hydrateStoredLayout:H&&!lt?q:()=>{},focusConversationTab:W,setSearchParams:l,historyModalOpen:Me,activeConv:Fe,isRefreshingHistory:ss,ides:f,handleRefreshHistory:qn});const Wt=c.useMemo(()=>!Fe||!ft(Fe)?null:Mr(Fe),[Fe]),{versionMismatchDaemons:js,hasRequiredVersionDaemons:rs,targetVersion:Oo,versionBannerDismissed:$o,setVersionBannerDismissed:Qi,upgradingDaemons:Ji,handleBannerUpgrade:Xi}=xI({ides:f,sendDaemonCommand:t}),Lr=c.useCallback(Xe=>{Z.setHidden(Xe,!1),it(Xe)},[it,Z]),Dr=c.useCallback(()=>{for(const Xe of Re)Z.setHidden(Xe,!1)},[Re,Z]),Zi=c.useCallback(Xe=>{Z.setHidden(Xe,!0)},[Z]),ec=c.useCallback(Xe=>{Z.toggleHidden(Xe)},[Z]);return n.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!$o||rs)&&n.jsx(nP,{daemons:js,targetVersion:Oo,required:rs,upgradingDaemons:Ji,onUpgrade:Xi,onDismiss:()=>Qi(!0)}),n.jsx(QR,{showMobileChatMode:lt,isMobile:H,activeConv:Fe,wsStatus:y,isConnected:N,onOpenHistory:Xe=>{Xe&&qe(Xe),Ee()},onOpenRemote:ot,onStopCli:gt,activeCliViewMode:Wt,onSetActiveCliViewMode:Xt,mobileChatConversations:Ge,ides:f,actionLogs:Se,sendDaemonCommand:t,setActionLogs:ue,setCliViewModeOverrides:ae,isStandalone:z,initialDataLoaded:x,userName:b.userName,requestedMobileTabKey:te,onRequestedMobileTabConsumed:le,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:we,isSplitMode:ge,numGroups:de,groupSizes:R,groupedConvs:Ie,clearedTabs:ee,focusedGroup:M,focusGroup:I,moveTabToGroup:Ke,splitTabRelative:He,closeGroup:Ae,handleResizeStart:Ne,groupActiveTabIds:D,setGroupActiveTab:$,groupTabOrders:U,setGroupTabOrder:K,toggleHiddenTab:Xe=>{const It=Y.get(Xe);It&&ec(It)},visibleConversations:Pe,hiddenConversations:Re,requestedDesktopTabKey:bt,onRequestedDesktopTabConsumed:le,onDesktopActiveTabChange:Tt,onRequestScrollToBottom:ut,onHideConversation:Zi,onShowHiddenConversation:Lr,onShowAllHiddenConversations:Dr,scrollToBottomRequest:dt,machineEntries:Ce,layoutProfile:E,onBrowseMachineDirectory:St,onSaveMachineWorkspace:zt,onLaunchMachineIde:mt,onLaunchMachineProvider:Yt,onListMachineMeshes:Tn,onLaunchMeshCoordinator:vn,onListMachineSavedSessions:In,notifications:ie,notificationUnreadCount:F,liveSessionInboxState:ve,onMarkNotificationRead:se,onMarkNotificationUnread:me,onDeleteNotification:re}),n.jsx("style",{children:`
82
- body { overflow: hidden; overscroll-behavior: none; }
83
- `}),n.jsx(tP,{historyModal:{open:Me,targetConv:Qe,ides:f,isCreatingChat:tt,isRefreshingHistory:ht?!1:Nt,savedSessions:on,savedHistoryFilters:qt,missingWorkspaceResumePath:an||null,onSavedHistoryFiltersChange:At,isSavedSessionsLoading:Kn,isResumingSavedSessionId:Ct,onClose:Ve,onNewChat:Bt,onSwitchSession:xt,onRefreshHistory:ht?cn:Jt,onResumeSavedSession:fn},remoteDialog:{conversation:be,ideEntry:Te,ides:f,connectionStates:k,actionLogs:Se,sendDaemonCommand:t,setActionLogs:ue,isStandalone:z,userName:b.userName,onOpenHistory:Xe=>{Xe&&qe(Xe),Ee()},onConversationChange:qe,onClose:_e,onRetryConnection:b.retryConnection},cliStopDialog:{open:st,targetConv:jt,onCancel:Kt,onStopNow:async()=>{await fe("hard")},onSaveAndStop:async()=>{await fe("save")}},connectionBanner:{wsStatus:y,showReconnected:A,loginUrl:b.connectionLoginUrl,onReconnect:b.retryServerConnection,suppress:e},toastOverlay:{toasts:v.filter(Xe=>{var It,wn,$r;return!((It=Xe.actions)!=null&&It.length&&Xe.targetKey&&((wn=Fe==null?void 0:Fe.modalButtons)!=null&&wn.length)&&(($r=ke(Xe.targetKey))==null?void 0:$r.tabKey)===Fe.tabKey)}),onDismiss:Xe=>w(It=>It.filter(wn=>wn.id!==Xe)),onClick:Xe=>{if(Xe.targetKey){const It=ke(Xe.targetKey);It&&(W(It.tabKey,V),Lr(It),ut(It.tabKey,"toast-open"))}}},onboarding:{open:C,standalone:z,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}j(!1)}},interactivePrompt:Mn,suppressInteractivePrompt:lt})]})}const iP=15e3;async function cP(e,t){let s;try{const r=await Promise.race([e,new Promise((o,a)=>{s=setTimeout(()=>a(new Error(t.timeoutMessage)),t.timeoutMs)})]);if(r&&r.success===!1)throw new Error(r.error||t.failedMessage)}finally{s&&clearTimeout(s)}}function lP({machineId:e,registeredMachineId:t,sendDaemonCommand:s,onNicknameSynced:r,logsEndRef:o}){const{t:a}=he("common"),{launchCli:i}=vi(),{confirm:l,confirmDialog:d}=Tr(),[u,m]=c.useState([]),[h,p]=c.useState(null),[b,f]=c.useState(null),[x,g]=c.useState(!1),[w,S]=c.useState(null),[C,j]=c.useState(!1),[v,y]=c.useState(""),N=c.useRef(null),k=c.useCallback(H=>{N.current=H},[]),A=c.useCallback((H,B,q=!1,W)=>{const ce=Id(W),ye=ce&&ce!==B?`${B} — ${ce}`:B;m(G=>[...G.slice(-100),{timestamp:Date.now(),level:H,message:ye}]),setTimeout(()=>{var G;return(G=o.current)==null?void 0:G.scrollIntoView({behavior:"smooth"})},100),q&&(H==="error"||H==="warn"?et.showErrorToast(B,W):et.showToast(B,"success"))},[o]),E=c.useCallback(H=>{const B=H instanceof Error?H.message:String(H||"");return B.includes("P2P command timeout")||B.includes("P2P not connected")||B.includes("P2P not available")},[]),P=c.useCallback(async(H,B)=>{var q;if(!e||h)return!1;p(H),A("info",a("machine.actions.launching",{name:$t(H)}));try{const W={ideType:H,enableCdp:!0};(q=B==null?void 0:B.workspace)!=null&&q.trim()?W.workspace=B.workspace.trim():B!=null&&B.useDefaultWorkspace&&(W.useDefaultWorkspace=!0);const ce=await s(e,"launch_ide",W);return ce!=null&&ce.success?A("info",a("machine.actions.launched",{name:$t(H)}),!0):A("error",a("machine.actions.launchFailed",{name:$t(H)}),!0,ce==null?void 0:ce.error),!!(ce!=null&&ce.success)}catch(W){return A("error",a("machine.actions.launchFailed",{name:$t(H)}),!0,W),!1}finally{p(null)}},[e,h,A,s,a]),T=c.useCallback(async H=>{if(!e)return{success:!1};const{cliType:B,dir:q,workspaceId:W,useDefaultWorkspace:ce,useHome:ye,argsStr:G,model:Se,resumeSessionId:ue}=H;if(!B)return A("warn",a("machine.actions.selectProviderFirst"),!0),{success:!1};const ne=G?G.split(/\s+/).filter(Boolean):void 0,ae=(q==null?void 0:q.trim())||(W?"(saved id)":ce?"(default workspace)":ye?"(home)":"");A("info",a("machine.actions.launching",{name:B}),!1,[ae,Se].filter(Boolean).join(" · ")||void 0),f(B);try{const ee={cliType:B,cliArgs:ne,initialModel:Se||void 0};q!=null&&q.trim()?ee.dir=q.trim():W?ee.workspaceId=W:ce?ee.useDefaultWorkspace=!0:ye&&(ee.useHome=!0),ue&&(ee.resumeSessionId=ue);const oe=await i(e,ee),Ce=(oe==null?void 0:oe.result)||oe;return oe!=null&&oe.success?(A("info",a("machine.actions.launched",{name:B}),!0),(Ce==null?void 0:Ce.launchSource)==="home"?A("info",a("machine.actions.runningInHome")):(Ce==null?void 0:Ce.launchSource)==="defaultWorkspace"&&A("info",a("machine.actions.usingDefaultWorkspace")),{success:!0,sessionId:Ce==null?void 0:Ce.sessionId}):(A("error",a("machine.actions.launchFailed",{name:B}),!0,(oe==null?void 0:oe.error)||(Ce==null?void 0:Ce.error)),(oe==null?void 0:oe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&S({cliType:B,argsStr:G,model:Se}),{success:!1,sessionId:Ce==null?void 0:Ce.sessionId})}catch(ee){return E(ee)?(A("warn",a("machine.actions.launchPending",{name:B}),!0),{success:!1,pending:!0}):(A("error",a("machine.actions.launchFailed",{name:B}),!0,ee),{success:!1})}finally{f(null)}},[e,A,E,s,a]),M=c.useCallback(async(H,B,q,W)=>e?H?B.trim()?T({cliType:H,dir:B,argsStr:q,model:W}):(S({cliType:H,argsStr:q,model:W}),{success:!1}):(A("warn",a("machine.actions.selectProvider"),!0),{success:!1}):{success:!1},[e,A,T,a]),_=c.useCallback(async(H,B,q)=>{if(e&&await l({title:a("cliStop.title",{agent:H}),description:a("machine.actions.stopCliConfirmDescription"),confirmLabel:a("cliStop.stop"),tone:"danger"}))try{const W=await s(e,"stop_cli",{cliType:H,dir:B,targetSessionId:q});W!=null&&W.success?A("info",a("machine.actions.stopped",{name:H}),!0):A("error",a("machine.actions.stopFailed"),!0,W==null?void 0:W.error)}catch(W){A("error",a("machine.actions.stopFailed"),!0,W)}},[e,A,l,s,a]),I=c.useCallback(async H=>{try{await s(H.daemonId,"restart_ide",{ideType:H.type}),A("info",a("machine.actions.restartInitiated",{name:$t(H.type)}),!0)}catch(B){A("error",a("machine.actions.restartFailed"),!0,B)}},[A,s,a]),D=c.useCallback(async H=>{if(await l({title:a("cliStop.title",{agent:$t(H.type)}),description:a("machine.actions.stopIdeConfirmDescription"),confirmLabel:a("cliStop.stop"),tone:"danger"}))try{const B=await s(H.daemonId,"stop_ide",{ideType:H.type,killProcess:!0});B!=null&&B.success?A("info",a("machine.actions.stopped",{name:$t(H.type)}),!0):A("error",a("machine.actions.stopFailed"),!0,B==null?void 0:B.error)}catch(B){A("error",a("machine.actions.stopFailed"),!0,B)}},[A,l,s,a]),L=c.useCallback(async()=>{if(e)try{const H=await s(e,"detect_ides",{});A("info",a("machine.actions.idesFound",{count:((H==null?void 0:H.result)||[]).length}),!0)}catch(H){A("error",a("machine.actions.detectFailed"),!0,H)}},[e,A,s,a]),$=c.useCallback(async H=>{if(!e||!H.trim())return!1;g(!0);try{const B=await s(e,"workspace_add",{path:H.trim()});return B!=null&&B.success?(A("info",a("machine.actions.workspaceAdded"),!1,H.trim()),!0):(A("error",a("machine.actions.workspaceActionFailed"),!1,B==null?void 0:B.error),!1)}catch(B){return A("error",a("machine.actions.workspaceActionFailed"),!1,B),!1}finally{g(!1)}},[e,A,s,a]),U=c.useCallback(async H=>{if(e){g(!0);try{const B=await s(e,"workspace_remove",{id:H});B!=null&&B.success?A("info",a("machine.actions.workspaceRemoved"),!0):A("error",a("machine.actions.workspaceActionFailed"),!0,B==null?void 0:B.error)}catch(B){A("error",a("machine.actions.workspaceActionFailed"),!0,B)}finally{g(!1)}}},[e,A,s,a]),J=c.useCallback(async H=>{var B;if(e){g(!0);try{const q=await s(e,"workspace_set_default",H===null?{clear:!0}:{id:H});if(q!=null&&q.success){A("info",a(H?"machine.actions.defaultWorkspaceUpdated":"machine.actions.defaultWorkspaceCleared"),!0);const W=typeof q.defaultWorkspacePath=="string"?q.defaultWorkspacePath:"";W&&((B=N.current)==null||B.call(N,W))}else A("error",a("machine.actions.workspaceActionFailed"),!0,q==null?void 0:q.error)}catch(q){A("error",a("machine.actions.workspaceActionFailed"),!0,q)}finally{g(!1)}}},[e,A,s,a]),K=c.useCallback(async(H,B)=>{if(!e||!H.trim())return!1;g(!0);try{const q=await s(e,"workspace_set_label",{path:H.trim(),label:B});return q!=null&&q.success?(await s(e,"workspace_list",{}),A("info",a("machine.actions.workspaceLabelUpdated"),!0),!0):(A("error",a("machine.managedWorkspaces.renameFailed"),!0,q==null?void 0:q.error),!1)}catch(q){return A("error",a("machine.managedWorkspaces.renameFailed"),!0,q),!1}finally{g(!1)}},[e,A,s,a]),R=c.useCallback(async H=>{var q;if(!e||!H.trim())return;const B=H.trim();g(!0);try{const W=await s(e,"workspace_set_default",{path:B});W!=null&&W.success?(A("info",a("machine.actions.defaultWorkspaceUpdated")),(q=N.current)==null||q.call(N,B)):A("error",a("machine.actions.workspaceActionFailed"),!1,(W==null?void 0:W.error)||a("machine.actions.pathMissing"))}catch(W){A("error",a("machine.actions.workspaceActionFailed"),!1,W)}finally{g(!1)}},[e,A,s,a]),O=c.useCallback(async()=>{if(e)try{if(await cP(s(e,"set_machine_nickname",{nickname:v}),{timeoutMs:iP,timeoutMessage:a("machine.actions.nicknameTimeout"),failedMessage:a("machine.actions.nicknameFailed")}),r)try{await r({machineRuntimeId:e,registeredMachineId:t,nickname:v})}catch(H){A("warn",a("machine.actions.nicknameSyncFailed"),!1,H)}A("info",a("machine.actions.nicknameSaved")),j(!1)}catch(H){A("error",a("machine.actions.nicknameFailed"),!0,H)}},[e,v,t,A,r,s,a]);return{logs:u,launchingIde:h,launchingAgentType:b,workspaceBusy:x,launchPick:w,setLaunchPick:S,editingNickname:C,setEditingNickname:j,nicknameInput:v,setNicknameInput:y,addLog:A,handleLaunchIde:P,runLaunchCliCore:T,handleLaunchCli:M,handleStopCli:_,handleRestartIde:I,handleStopIde:D,handleDetectIdes:L,handleWorkspaceAdd:$,handleWorkspaceRemove:U,handleWorkspaceSetDefault:J,handleWorkspaceSetLabel:K,handleWorkspaceResumePath:R,handleSaveNickname:O,confirmDialog:d,setOnDefaultWorkspaceChanged:k}}const Ph={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"},dP={bucket:"machine.quota.bucketHint",session:"machine.quota.sessionHint",weekly:"machine.quota.weeklyHint",monthly:"machine.quota.monthlyHint",usage:"machine.quota.usageHint"};function Eh({label:e,tone:t,title:s}){return n.jsx("span",{title:s,className:`rounded-full px-2 py-0.5 text-3xs font-medium ${Ph[t]??Ph.default}`,children:e})}function uP({machine:e}){const{t}=he("common"),s=Ud(Wd(t)),r=sg(e.quota);return r.length===0?null:n.jsxs(hn,{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:kr(o)}),cl(a)&&n.jsx("span",{className:"text-3xs text-text-secondary",title:t("machine.quota.accountHint"),children:cl(a)}),i.kind==="chips"&&i.chips.map(l=>n.jsx(Eh,{label:l.label,tone:l.tone,title:t(dP[l.hint])},l.key)),i.kind==="usage"&&n.jsx(Eh,{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 Lh({title:e,defaultOpen:t=!1,testId:s,children:r}){const[o,a]=c.useState(t),[i,l]=c.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&&l(!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 mP({machine:e,ideSessions:t,cliSessions:s,daemonVersion:r,renderHostedRuntimes:o,renderLogs:a,initialDiagnostics:i=null}){var p,b;const{t:l}=he("common"),d=typeof e.uptime=="number"||typeof e.freeMem=="number"||typeof e.availableMem=="number"||Array.isArray(e.loadavg)&&e.loadavg.length>0,u=e.availableMem??e.freeMem??e.totalMem,m=d&&e.totalMem>0?Math.min(100,Math.max(0,Math.round((e.totalMem-u)/e.totalMem*100))):0,h=((p=e.loadavg)==null?void 0:p[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(dc,{icon:n.jsx(fd,{size:16}),label:l("machine.overview.uptime"),value:typeof e.uptime=="number"?Vj(e.uptime):l("machine.overview.waiting")}),n.jsx(dc,{icon:n.jsx(Bn,{size:16}),label:"IDEs",value:`${t.length}`}),n.jsx(dc,{icon:n.jsx(bd,{size:16}),label:"CLIs",value:`${s.length}`})]}),n.jsxs(hn,{padding:"lg",className:"mb-5",children:[n.jsx("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mb-3",children:l("machine.overview.resourceUsage")}),n.jsxs("div",{className:"flex gap-6",children:[n.jsx(zu,{value:d?Math.min(Math.round(h/e.cpus*100),100):0,max:100,label:l("machine.overview.cpuLoad"),color:"#8b5cf6",detail:d?l("machine.overview.cpuDetail",{load:h.toFixed(2),cores:e.cpus}):l("machine.overview.waitingForStats")}),n.jsx(zu,{value:m,max:100,label:l("machine.overview.memory"),color:"#3b82f6",detail:d?`${fc(e.totalMem-u)} / ${fc(e.totalMem)}${e.platform==="darwin"?` ${l("machine.overview.approx")}`:""}`:l("machine.overview.waitingForStatsWithTotal",{total:fc(e.totalMem)})})]})]}),n.jsx(uP,{machine:e}),n.jsxs(hn,{padding:"lg",className:"mb-5",children:[n.jsx("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mb-3",children:l("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(Qr,{label:l("machine.overview.hostname"),value:e.hostname}),n.jsx(Qr,{label:l("machine.overview.platform"),value:[Df[e.platform]||e.platform,e.arch].filter(Boolean).join(" · ")}),e.cpus>0&&n.jsx(Qr,{label:l("machine.overview.cores"),value:String(e.cpus)}),r&&n.jsx(Qr,{label:l("machine.overview.daemonVersion"),value:`v${r}`}),((b=e.p2p)==null?void 0:b.available)&&n.jsx(Qr,{label:l("machine.overview.p2p"),value:e.p2p.state==="connected"?l("machine.detail.p2pConnected"):e.p2p.state})]})]}),(o||a)&&n.jsxs("details",{className:"group mb-5","data-testid":"machine-diagnostics",open:i?!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:"▸"}),l("machine.overview.diagnostics")]}),n.jsxs("div",{className:"flex flex-col gap-3",children:[o&&n.jsx(Lh,{title:l("machine.detail.tabHostedRuntimes"),defaultOpen:i==="hosted-runtimes",testId:"machine-diagnostics-hosted-runtimes",children:o}),a&&n.jsx(Lh,{title:l("machine.detail.tabLogs"),defaultOpen:i==="logs",testId:"machine-diagnostics-logs",children:a})]})]})]})}function Qr({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 l=t.find(d=>d.type===o);r.push({type:o,displayName:(l==null?void 0:l.displayName)||o,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:i,values:e.values[o]||{}})}return r}function Uc(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 Dh(e){if(!e||typeof e!="object")return null;if(Uc(e))return e;const t=e,s=t.result;return Uc(s)?s:Uc(t.sourceConfig)?t.sourceConfig:null}function hP(e){const t=e.trim();return t||null}function pP({providerType:e,displayName:t,supportsQuota:s,quotaInstallsClaudeStatusline:r,onCancel:o,onConfirm:a}){const{t:i}=he("common"),[l,d]=c.useState(!0),[u,m]=c.useState(!0);return n.jsx(Un,{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:l,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(nt,{content:[i("machine.installOptions.quotaHint"),r&&l?i("machine.installOptions.quotaClaudeNote"):""].filter(Boolean).join(`
84
-
85
- `),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?l: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 Oh={"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"},$h={"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"},fP={"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 bP({trust:e,sourceName:t,description:s}){const{t:r}=he("common"),o=Oh[e]?r(Oh[e]):e,a=t&&(e==="external-safe"||e==="external-untrusted")?`${o} · ${t}`:o,i=$h[e]?r($h[e]):s;return n.jsx("span",{className:`text-3xs px-1.5 py-0.5 rounded border whitespace-nowrap ${fP[e]??""}`,title:i,children:a})}const gP={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]"},extension:{badge:"bg-teal-500/10 text-teal-300 border-teal-500/20",accent:"border-teal-500/[0.12]"}},xP=["enabled","autoApprove","executablePath","executableArgs","cliPathOverride","appPathOverride","approvalAlert","longGeneratingAlert","longGeneratingThresholdSec","showThinking","showToolCalls","showTerminal","showCoordinatorSystemPrompt","notifications"],yP=new Set(xP);function vP(e,t,s){if(!yP.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 wP(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 SP(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 Fh={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"},kP={bucket:"machine.quota.bucketHint",session:"machine.quota.sessionHint",weekly:"machine.quota.weeklyHint",monthly:"machine.quota.monthlyHint",usage:"machine.quota.usageHint"},jP={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 Hh(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 Bh={Stable:"machine.providerRow.lifecycleStable",Beta:"machine.providerRow.lifecycleBeta",Experimental:"machine.providerRow.lifecycleExperimental",Deprecated:"machine.providerRow.lifecycleDeprecated"};function NP(e){return e==="cli"}function Kc({checked:e,busy:t,label:s,onToggle:r}){return n.jsx(Pr,{as:"span",size:"sm",checked:e,busy:t,"aria-label":s,onChange:()=>r()})}function CP({prov:e,quota:t,providerInfo:s,savingKey:r,onSetSetting:o,onEnableToggle:a,onDetect:i,onResetCommand:l,quotaAccountLabelEnabled:d,onQuotaAccountLabelToggle:u,quotaEnabled:m,onQuotaToggle:h,pin:p,onUpdate:b,updating:f,onRollbackUpdate:x,showAdvanced:g=!1}){var _;const[w,S]=c.useState(null),[C,j]=c.useState(!1),{t:v}=he("common"),y={detected:v("machine.providerRow.statusDetected"),not_detected:v("machine.providerRow.statusNotDetected"),enabled_unchecked:v("machine.providerRow.statusEnabledUnchecked"),disabled:v("machine.providerRow.statusDisabled")},[N,k]=c.useState(!1),A=(s==null?void 0:s.enabled)===!0||e.values.enabled===!0,E=s==null?void 0:s.machineStatus,P=A&&E==="disabled"?"enabled_unchecked":E||(A?"enabled_unchecked":"disabled"),T=NP(e.category),M=(()=>{if(!t)return null;const D=Ud(Wd(v))(t).compactChip;return D?{label:D.label,tone:jP[D.tone],title:v(kP[D.hint])}:null})();return n.jsxs(hn,{padding:"none",children:[n.jsxs("button",{onClick:()=>k(I=>!I),className:"w-full px-4 py-2.5 flex items-center gap-3 text-left",children:[n.jsx($i,{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 ${((_=gP[e.category])==null?void 0:_.badge)??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(s==null?void 0:s.trust)&&n.jsx(bP,{trust:s.trust,sourceName:s.sourceName??null,description:s.trustDescription}),T&&n.jsx("span",{className:`text-4xs font-semibold px-1.5 py-px rounded border ${Fh[P]??Fh.disabled}`,children:y[P]??P}),n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[b&&(p==null?void 0:p.stale)&&p.latestVersion&&n.jsx("span",{role:"button",tabIndex:0,"aria-disabled":f?!0:void 0,title:v("machine.providerRow.updateInlineHint",{latest:p.latestVersion}),onClick:I=>{I.stopPropagation(),!f&&b()},onKeyDown:I=>{I.key!=="Enter"&&I.key!==" "||(I.preventDefault(),I.stopPropagation(),!f&&b())},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:v(f?"machine.providerRow.specPinUpdating":"machine.providerRow.updateInline")}),M&&n.jsx("span",{className:`text-4xs font-semibold px-1.5 py-px rounded border shrink-0 ${M.tone}`,title:M.title,children:M.label}),T&&n.jsx(Kc,{checked:A,busy:r===`${e.type}.enabled`,label:v(A?"machine.providerRow.disable":"machine.providerRow.enable"),onToggle:()=>{a(e.type,!A)}}),n.jsx("span",{className:"text-text-muted text-xs",children:N?"▾":"▸"})]})]}),N&&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 D=vP(v,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:[D.label,D.description&&n.jsx(nt,{content:D.description,size:11}),r===`${e.type}.${I.key}`&&n.jsx("span",{className:"ml-1.5 text-4xs text-accent-primary",children:v("machine.providerRow.saving")})]})}),n.jsx("div",{className:"shrink-0",children:I.type==="boolean"?n.jsx(Pr,{checked:!!(e.values[I.key]??I.default),busy:r===`${e.type}.${I.key}`,"aria-label":D.label,onChange:L=>void o(e.type,I.key,L)}):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:L=>{const $=parseInt(L.target.value)||0;I.min!==void 0&&$<I.min||I.max!==void 0&&$>I.max||o(e.type,I.key,$)},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:L=>void o(e.type,I.key,L.target.value),className:"machine-input text-2xs",children:I.options.map(L=>n.jsx("option",{value:L,children:wP(v,L)},L))}):n.jsx("input",{type:"text",defaultValue:String(e.values[I.key]??I.default??""),onBlur:L=>void o(e.type,I.key,L.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:[v("machine.providerRow.quotaTracking"),n.jsx(nt,{content:v("machine.providerRow.quotaTrackingHint"),size:11})]}),C?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:v("machine.providerRow.quotaClaudeConfirmTitle")}),n.jsx("div",{className:"text-3xs text-text-muted max-w-[420px] text-right",children:v("machine.providerRow.quotaClaudeConfirmBody")}),n.jsxs("div",{className:"flex gap-1.5",children:[n.jsx("button",{onClick:I=>{I.stopPropagation(),j(!1),h(e.type,!0)},className:"machine-btn text-3xs px-2 py-0.5 text-amber-400 border-amber-500/25",children:v("machine.providerRow.quotaClaudeConfirmOk")}),n.jsx("button",{onClick:I=>{I.stopPropagation(),j(!1)},className:"machine-btn text-3xs px-2 py-0.5",children:v("machine.providerRow.quotaClaudeConfirmCancel")})]})]}):n.jsx(Kc,{checked:m,label:v("machine.providerRow.quotaTracking"),onToggle:()=>{e.type==="claude-cli"&&!m?j(!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:[v("machine.providerRow.quotaAccountLabel"),n.jsx(nt,{content:v("machine.providerRow.quotaAccountLabelHint"),size:11})]}),n.jsx(Kc,{checked:d,label:v("machine.providerRow.quotaAccountLabel"),onToggle:()=>{u(!d)}})]}),g&&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:v("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:v("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:v("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:v("machine.providerRow.specPinStaleHint",{latest:p.latestVersion}),children:v("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:v("machine.providerRow.labelActivatedAt")})," ",To(p.activatedAt)]}),(p==null?void 0:p.previousVersion)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:v("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:v("machine.providerRow.labelDigest")})," ",n.jsx("span",{className:"font-mono",children:p.digest.replace(/^sha256:/,"").slice(0,12)})]}),g&&(s==null?void 0:s.binary)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:v("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:v("machine.providerRow.labelStatus")})," ",Bh[s.status]?v(Bh[s.status]):s.status]}),g&&(s==null?void 0:s.details)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:v("machine.providerRow.labelDetails")})," ",s.details]}),g&&(s==null?void 0:s.sourceLayer)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:v("machine.providerRow.labelSource")})," ",n.jsx("span",{className:"font-mono",children:s.sourceLayer}),s.sourceName?` · ${s.sourceName}`:""]}),g&&(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:v("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 D=Object.entries(I).map(([L,$])=>({k:L,href:SP($)})).filter(L=>L.href!==null);return D.length===0?null:n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:v("machine.providerRow.labelLinks")})," ",D.map(({k:L,href:$})=>n.jsx("a",{href:$,target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary hover:underline mr-2",children:L},L))]})})()]}),T&&(g||(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:[(g||(s==null?void 0:s.lastDetection))&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:v("machine.providerRow.labelDetection")})," ",Hh(v,s==null?void 0:s.lastDetection)]}),(g||(s==null?void 0:s.lastVerification))&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:v("machine.providerRow.labelVerification")})," ",Hh(v,s==null?void 0:s.lastVerification)]})]}),n.jsxs("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:[T&&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:v(A?"machine.providerRow.detectHint":"machine.providerRow.detectDisabledHint"),children:v("machine.providerRow.detect")}),n.jsx("button",{onClick:()=>void l(e.type),className:"machine-btn text-3xs px-2 py-0.5",children:v("machine.providerRow.resetCommand")})]}),x&&(p==null?void 0:p.previousVersion)&&n.jsx("button",{onClick:()=>{S("rollback"),x().finally(()=>S(null))},disabled:w!==null||f===!0,className:"machine-btn text-3xs px-2 py-0.5",title:v("machine.providerRow.specPinRollbackHint",{version:p.previousVersion}),children:v(w==="rollback"?"machine.providerRow.specPinRollingBack":"machine.providerRow.specPinRollback")})]})]})]})}function _P(e){if(!e||typeof e!="object")return null;const t=e,s=t.result;return s&&typeof s=="object"?s:t}function Wh(e){const t=_P(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,l=typeof i.code=="string"?i.code:"UNKNOWN",d=typeof i.message=="string"?i.message:"";s.push({code:l,message:d,...typeof i.providerType=="string"?{providerType:i.providerType}:{}})}return s}function AP(e){return e.some(t=>t.code==="DIGEST_MISMATCH")}function la(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function TP({machineId:e,sendDaemonCommand:t,onChange:s,reloadToken:r=0}){const{t:o}=he("common"),{confirm:a,confirmDialog:i}=Tr(),[l,d]=c.useState([]),[u,m]=c.useState([]),[h,p]=c.useState(!1),[b,f]=c.useState(null),[x,g]=c.useState(!1),[w,S]=c.useState(""),[C,j]=c.useState("main"),[v,y]=c.useState(""),[N,k]=c.useState(!1),[A,E]=c.useState(null),[P,T]=c.useState(null),M=c.useCallback(async()=>{if(e){p(!0),f(null);try{const L=la(await t(e,"list_provider_sources",{}));if(!(L!=null&&L.success)){f((L==null?void 0:L.error)||o("machine.sourcesPanel.loadFailed"));return}d(L.sources||[]),m(L.conflicts||[])}catch(L){f((L==null?void 0:L.message)||o("machine.sourcesPanel.loadFailed"))}finally{p(!1)}}},[e,t,o]);c.useEffect(()=>{M()},[M,r]);const _=async()=>{if(w.trim()){k(!0),f(null);try{const L=la(await t(e,"add_provider_source",{url:w.trim(),ref:C.trim()||"main",...v.trim()?{name:v.trim()}:{}}));L!=null&&L.success?(g(!1),S(""),j("main"),y(""),await M(),s==null||s()):f((L==null?void 0:L.error)||o("machine.sourcesPanel.addFailed"))}catch(L){f((L==null?void 0:L.message)||o("machine.sourcesPanel.addFailed"))}finally{k(!1)}}},I=async L=>{if(await a({title:o("machine.sourcesPanel.removeConfirmTitle",{name:L}),description:o("machine.sourcesPanel.removeConfirmDescription"),confirmLabel:o("machine.sourcesPanel.removeConfirmLabel"),cancelLabel:o("machine.sourcesPanel.cancel"),tone:"danger"})){E(L),f(null);try{const U=la(await t(e,"remove_provider_source",{name:L}));U!=null&&U.success?(await M(),s==null||s()):f((U==null?void 0:U.error)||o("machine.sourcesPanel.removeFailed"))}catch(U){f((U==null?void 0:U.message)||o("machine.sourcesPanel.removeFailed"))}finally{E(null)}}},D=async(L,$)=>{T(`${L}:${$}`),f(null);try{const U=la(await t(e,"set_active_provider_source",{type:L,sourceName:$}));U!=null&&U.success?(await M(),s==null||s()):f((U==null?void 0:U.error)||o("machine.sourcesPanel.setActiveFailed"))}catch(U){f((U==null?void 0:U.message)||o("machine.sourcesPanel.setActiveFailed"))}finally{T(null)}};return n.jsxs(hn,{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(nt,{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:()=>g(!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")})})]}),b&&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:b}),l.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:l.map(L=>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:L.name}),n.jsxs("div",{className:"text-3xs text-text-muted truncate",children:[L.url," ",n.jsxs("span",{className:"opacity-60",children:["@ ",L.ref]})]})]}),n.jsx("button",{type:"button",onClick:()=>void I(L.name),disabled:A===L.name,className:"machine-btn text-3xs text-red-400 hover:bg-red-500/[0.10]",children:A===L.name?o("machine.sourcesPanel.removing"):o("machine.sourcesPanel.remove")})]}),n.jsx("div",{className:"mt-1.5 text-3xs text-text-muted",children:Object.entries(L.providers).map(([$,U])=>n.jsxs("span",{className:"mr-3",children:[n.jsxs("span",{className:"text-text-secondary",children:[$,":"]})," ",U.length]},$))})]},L.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(nt,{content:o("machine.sourcesPanel.conflictsDescription"),size:12})]}),n.jsx("ul",{className:"flex flex-col gap-1.5",children:u.map(L=>n.jsxs("li",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"font-mono text-2xs",children:[L.type," ",n.jsxs("span",{className:"text-text-muted",children:["(",L.category,")"]})]}),n.jsx("div",{className:"flex gap-1.5 flex-wrap",children:L.candidates.map($=>n.jsxs("button",{type:"button",onClick:()=>void D(L.type,$),disabled:P===`${L.type}:${$}`,className:`text-3xs px-2 py-0.5 rounded border ${L.active===$?"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:L.active===$?o("machine.sourcesPanel.active"):o("machine.sourcesPanel.switchActiveTo",{name:$}),children:[L.active===$?"● ":"",$]},$))})]},L.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:w,onChange:L=>S(L.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:C,onChange:L=>j(L.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:v,onChange:L=>y(L.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:()=>g(!1),className:"machine-btn text-3xs",children:o("machine.sourcesPanel.cancel")}),n.jsx("button",{type:"button",onClick:()=>void _(),disabled:N||!w.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(N?"machine.sourcesPanel.cloning":"machine.sourcesPanel.cloneAndRegister")})]})]}),i]})}function Uh(e){var o;const t=ff(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 Kh=new Set(["codex-cli"]),da=new Set(xy);function IP({machineId:e,providers:t,sendDaemonCommand:s,quota:r}){var re,we;const{t:o}=he("common"),[a,i]=c.useState(null),[l,d]=c.useState(void 0),[u,m]=c.useState({}),[h,p]=c.useState({}),[b,f]=c.useState([]),[x,g]=c.useState([]),[w,S]=c.useState(null),[C,j]=c.useState({}),[v,y]=c.useState(!1),[N,k]=c.useState({}),[A,E]=c.useState(!1),[P,T]=c.useState(null),[M,_]=c.useState(null),[I,D]=c.useState("cli"),[L,$]=c.useState(null),[U,J]=c.useState(!1),[K,R]=c.useState(0),[O,H]=c.useState(null),[B,q]=c.useState("normal"),[W,ce]=c.useState(""),[ye,G]=c.useState(!1),Se=c.useCallback(async()=>{if(e)try{const V=await s(e,"get_provider_source_config",{}),de=Dh(V);de&&(H(de),q(de.sourceMode),ce(de.explicitProviderDir||""))}catch(V){T(o("machine.providers.loadFailed",{error:(V==null?void 0:V.message)||String(V)}))}},[e,s,o]),ue=c.useCallback(async V=>{if(e){V!=null&&V.explicit&&E(!0);try{const de=await s(e,"get_provider_settings",{}),ge=mx(de);ge&&(i(ge),T(null))}catch(de){T(o("machine.providers.loadFailed",{error:(de==null?void 0:de.message)||String(de)}))}finally{V!=null&&V.explicit&&E(!1)}}},[e,s,o]),ne=c.useMemo(()=>{if(!a)return[];const V=hx(a,t,{filterSchema:de=>de.filter(ge=>ge.key!=="enabled")});return V.sort((de,ge)=>de.category.localeCompare(ge.category)||de.displayName.localeCompare(ge.displayName)),V},[a,t]),ae=c.useCallback((V,de,ge)=>{i(Ie=>Ie&&{...Ie,values:{...Ie.values,[V]:{...Ie.values[V]||{},[de]:ge}}})},[]),ee=c.useCallback(async()=>{if(e)try{const V=await s(e,"get_quota_account_label",{}),de=V&&typeof V=="object"&&"result"in V?V.result:V;typeof(de==null?void 0:de.enabled)=="boolean"&&d(de.enabled)}catch{}},[e,s]),oe=c.useCallback(async V=>{if(e){d(V);try{const de=await s(e,"set_quota_account_label",{enabled:V}),ge=de&&typeof de=="object"&&"result"in de?de.result:de;(ge==null?void 0:ge.success)===!1&&await ee()}catch{await ee()}}},[e,s,ee]),Ce=c.useCallback(async V=>{if(e)try{const de=await s(e,"get_quota_provider_enabled",{providerType:V}),ge=de&&typeof de=="object"&&"result"in de?de.result:de;typeof(ge==null?void 0:ge.enabled)=="boolean"&&m(Ie=>({...Ie,[V]:ge.enabled}))}catch{}},[e,s]),Q=c.useCallback(async()=>{await Promise.all([...da].map(V=>Ce(V)))},[Ce]),z=c.useCallback(async(V,de)=>{if(e){m(ge=>({...ge,[V]:de}));try{const ge=await s(e,"set_quota_provider_enabled",{providerType:V,enabled:de}),Ie=ge&&typeof ge=="object"&&"result"in ge?ge.result:ge;(Ie==null?void 0:Ie.success)===!1&&(T(o("machine.providers.quotaToggleFailed",{provider:V,error:typeof Ie.error=="string"?Ie.error:"unknown error"})),await Ce(V))}catch(ge){T(o("machine.providers.quotaToggleFailed",{provider:V,error:(ge==null?void 0:ge.message)||String(ge)})),await Ce(V)}}},[e,s,Ce,o]),X=c.useCallback(async()=>{var V,de;if(e)try{const ge=await s(e,"check_provider_updates",{}),Ie=ge&&typeof ge=="object"&&"result"in ge?ge.result:ge,Ke={};for(const Ae of(Ie==null?void 0:Ie.providers)??[])typeof(Ae==null?void 0:Ae.type)=="string"&&(Ke[Ae.type]={activeVersion:Ae.activeVersion??null,latestVersion:Ae.latestVersion??null,stale:Ae.stale===!0,digest:Ae.digest??null,activatedAt:Ae.activatedAt??null,previousVersion:Ae.previousVersion??null});p(Ke),f(Array.isArray((V=Ie==null?void 0:Ie.channelStaleness)==null?void 0:V.newTypes)?Ie.channelStaleness.newTypes:[]),g(Array.isArray((de=Ie==null?void 0:Ie.modelStaleness)==null?void 0:de.staleTypes)?Ie.modelStaleness.staleTypes:[])}catch{}},[e,s]),pe=c.useCallback(async V=>{if(e){S(V),k(de=>{if(!(V in de))return de;const ge={...de};return delete ge[V],ge});try{const de=await s(e,"activate_provider_updates",{types:[V]}),ge=Wh(de);ge.length>0&&k(Ie=>({...Ie,[V]:ge}))}catch(de){k(ge=>({...ge,[V]:[{code:"COMMAND_FAILED",message:de instanceof Error?de.message:String(de)}]}))}finally{S(null),await X(),ue()}}},[e,s,X,ue]),Pe=c.useCallback(async()=>{if(e){y(!0);try{const V=await s(e,"activate_provider_updates",{}),de=Uh(V);"error"in de?et.showErrorToast(o("machine.detail.providerSyncFailed"),de.error):et.showToast(de.activatedCount>0?o("machine.detail.providerSyncSuccess",{count:de.activatedCount}):o("machine.detail.providerSyncAlreadyCurrent"),"success")}catch(V){et.showErrorToast(o("machine.detail.providerSyncFailed"),V)}finally{y(!1),await X(),ue()}}},[e,s,X,ue,o]),Oe=c.useCallback(async V=>{if(e)try{await s(e,"rollback_provider_update",{providerType:V})}finally{await X(),ue()}},[e,s,X,ue]),Le=c.useCallback(async V=>{if(e){j(de=>({...de,[V]:!0}));try{const de=await s(e,"activate_provider_updates",{types:[V],only:!0}),ge=Uh(de),Ie=Wh(de);if("error"in ge||Ie.length>0){const Ke="error"in ge?ge.error:Ie.map(Ae=>Ae.message||Ae.code).join("; ");et.showErrorToast(o("machine.detail.providerSyncFailed"),Ke)}else et.showToast(ge.activatedCount>0?o("machine.detail.providerSyncSuccess",{count:ge.activatedCount}):o("machine.detail.providerSyncAlreadyCurrent"),"success")}catch(de){et.showErrorToast(o("machine.detail.providerSyncFailed"),de)}finally{j(de=>{const ge={...de};return delete ge[V],ge}),await X(),ue()}}},[e,s,X,ue,o]);c.useEffect(()=>{a||ue({explicit:!0}),O||Se(),l===void 0&&ee(),Q(),X()},[]);const ke=async(V,de,ge)=>{_(`${V}.${de}`),ae(V,de,ge);try{const Ie=await s(e,"set_provider_setting",{providerType:V,key:de,value:ge});Ie!=null&&Ie.success||ue()}catch{ue()}_(null)},Y=async(V,de)=>{if(de){$(V);return}await ke(V,"enabled",!1)},ve=c.useCallback(async(V,de)=>{$(null),_(`${V}.enabled`);try{de.quotaEnabled!==void 0&&await s(e,"set_quota_provider_enabled",{providerType:V,enabled:de.quotaEnabled});const ge=await s(e,"set_provider_setting",{providerType:V,key:"autoApprove",value:de.autoApprove}),Ie=await s(e,"set_provider_setting",{providerType:V,key:"enabled",value:!0});if((ge==null?void 0:ge.success)===!1||(Ie==null?void 0:Ie.success)===!1)throw new Error("set_provider_setting refused");ae(V,"autoApprove",de.autoApprove),ae(V,"enabled",!0),de.quotaEnabled!==void 0&&m(Ke=>({...Ke,[V]:de.quotaEnabled}))}catch{ue(),Ce(V)}finally{_(null)}},[e,s,ue,Ce,ae]),Z=async V=>{_(`${V}.detect`);try{const de=await s(e,"detect_provider",{providerType:V}),ge=de&&typeof de=="object"&&"result"in de?de.result:de;(ge==null?void 0:ge.success)===!1&&T(o("machine.providers.loadFailed",{error:typeof ge.error=="string"?ge.error:"detect failed"}))}catch(de){T(o("machine.providers.loadFailed",{error:(de==null?void 0:de.message)||String(de)}))}finally{_(null)}},ie=async V=>{await ke(V,"executablePath",""),await ke(V,"executableArgs","")},F=async()=>{G(!0);try{const V=await s(e,"set_provider_source_config",{providerSourceMode:B,providerDir:hP(W)}),de=Dh(V);de?(H(de),q(de.sourceMode),ce(de.explicitProviderDir||"")):await Se(),ue()}catch{await Se()}G(!1)},se=ne.filter(V=>I==="all"||V.category===I),me=Object.values(h).filter(V=>V.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:o("machine.providers.filter")}),["cli","ide","extension","all"].map(V=>n.jsx("button",{onClick:()=>D(V),className:`machine-btn text-3xs px-2 py-0.5 ${I===V?"bg-accent-primary/15 border-accent-primary/40 text-accent-primary":""}`,children:V.toUpperCase()},V))]}),n.jsxs("div",{className:"flex gap-1.5 items-center",children:[me>=2&&n.jsxs("button",{onClick:()=>{Pe()},disabled:v,className:"machine-btn text-3xs text-amber-400 border-amber-500/25",children:[v?n.jsx(vr,{size:11}):null," ",o("machine.providers.updateAll")]}),n.jsx(Bi,{onClick:()=>{ue({explicit:!0}),X(),U&&(Se(),R(V=>V+1))},refreshing:A,label:o("machine.providers.refresh"),size:12,className:"h-7 w-7"}),n.jsx("button",{onClick:()=>J(V=>!V),"aria-expanded":U,className:`machine-btn text-3xs ${U?"bg-accent-primary/10 border-accent-primary/30 text-accent-primary":""}`,title:o("machine.providers.advancedHint"),children:o("machine.providers.advanced")})]})]}),P&&n.jsx(Ht,{variant:"error",onDismiss:()=>T(null),children:P}),b.length>0&&n.jsxs(hn,{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:[o("machine.providers.newChannelTypesTitle"),n.jsx(nt,{content:o("machine.providers.newChannelTypesDesc"),size:12})]}),n.jsx("div",{className:"flex flex-col gap-1.5",children:b.map(V=>{const de=N[V]??[];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:V}),n.jsx("button",{onClick:()=>{pe(V)},disabled:w!==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:w===V?n.jsx(vr,{size:11}):o("machine.providers.installNewType")})]}),de.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:AP(de)?o("machine.providers.installFailedDigestMismatch"):o("machine.providers.installFailedTitle")}),n.jsx(Hd,{summary:o("toast.details"),className:"mt-1",children:n.jsx("ul",{className:"flex flex-col gap-0.5",children:de.map((ge,Ie)=>n.jsxs("li",{className:"text-3xs text-text-muted font-mono break-all",children:[n.jsx("span",{className:"text-red-300/90",children:ge.code}),ge.providerType?` [${ge.providerType}]`:"",ge.message?`: ${ge.message}`:""]},`${ge.code}-${Ie}`))})})]})]},V)})})]}),x.length>0&&n.jsxs(hn,{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:[o("machine.providers.modelListTitle"),n.jsx(nt,{content:o("machine.providers.modelListStaleDesc"),size:12})]}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:x.map(V=>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:V}),n.jsx("span",{className:"text-3xs uppercase tracking-wider text-amber-300/90",children:o("machine.providers.modelListStaleBadge")})]},V))})]}),U&&n.jsx(TP,{machineId:e,sendDaemonCommand:s,onChange:()=>{ue()},reloadToken:K}),U&&n.jsxs(hn,{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:[o("machine.providers.sourceConfigTitle"),n.jsx(nt,{content:o("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:o("machine.providers.sourceMode")}),n.jsxs("select",{value:B,onChange:V=>q(V.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:o("machine.providers.explicitProviderDir")}),n.jsx("input",{type:"text",value:W,onChange:V=>ce(V.target.value),placeholder:o("machine.providers.providerDirPlaceholder"),className:"machine-input text-2xs"})]}),n.jsx("button",{onClick:()=>void F(),disabled:ye,className:"machine-btn text-3xs bg-accent-primary/[0.08] border-accent-primary/20 text-accent-primary hover:bg-accent-primary/[0.14]",children:o(ye?"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:o("machine.providers.userRoot"),value:O==null?void 0:O.userDir},{label:o("machine.providers.upstreamRoot"),value:O==null?void 0:O.upstreamDir},{label:o("machine.providers.providerRoots"),value:(re=O==null?void 0:O.providerRoots)==null?void 0:re.join(" → ")}].map(V=>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:V.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:V.value||void 0,children:V.value||"—"}),V.value&&n.jsx(Yb,{value:V.value,label:o("common.copy")})]})]},V.label))})]}),A&&ne.length===0?n.jsx("div",{className:"p-10 text-center text-text-muted",children:o("machine.providers.loadingSettings")}):se.length===0?n.jsx(hn,{padding:"none",className:"px-4.5 py-8 text-center",children:n.jsx("div",{className:"text-xs text-text-muted",children:I==="all"?o("machine.providers.noProviders"):o("machine.providers.noFilteredProviders",{filter:I.toUpperCase()})})}):n.jsx("div",{className:"flex flex-col gap-1.5",children:se.map(V=>n.jsx(CP,{quota:r==null?void 0:r[V.type],prov:V,providerInfo:t.find(de=>de.type===V.type),savingKey:M,onSetSetting:ke,onEnableToggle:Y,onDetect:Z,onResetCommand:ie,quotaAccountLabelEnabled:Kh.has(V.type)?l:void 0,onQuotaAccountLabelToggle:Kh.has(V.type)?oe:void 0,quotaEnabled:da.has(V.type)?u[V.type]??!0:void 0,onQuotaToggle:da.has(V.type)?z:void 0,pin:h[V.type],onUpdate:()=>Le(V.type),updating:C[V.type]===!0,onRollbackUpdate:()=>Oe(V.type),showAdvanced:U},V.type))}),L&&n.jsx(pP,{providerType:L,displayName:((we=ne.find(V=>V.type===L))==null?void 0:we.displayName)||L,supportsQuota:da.has(L),quotaInstallsClaudeStatusline:L==="claude-cli",onCancel:()=>$(null),onConfirm:V=>{ve(L,V)}})]})}const MP=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function RP({count:e,since:t,category:s}){return{count:e,since:t,...s==="all"?{}:{category:s}}}function PP(e,t){return t==="all"?e:e.filter(s=>s.category===t)}function EP(e){return e.trim().toLowerCase()}function qi(e,t){const s=EP(t);return s?e.some(r=>String(r??"").toLowerCase().includes(s)):!0}function mu(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function jr(e,t=220){const s=mu(e);return s?s.length>t?`${s.slice(0,t)}…`:s:""}function LP(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 DP(e,t){return e.filter(s=>qi([s.level,s.message],t))}function qh(e){return`${e.timestamp}:${e.level}:${e.message}`}function OP(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,l)=>i.timestamp-l.timestamp).slice(-s),a=o.reduce((i,l)=>Math.max(i,Number(l.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 $P(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 FP(e,t){return e.split(`
86
- `).map(s=>s.trimEnd()).filter(Boolean).filter(s=>qi([s],t))}function HP(e,t){return e.filter(s=>qi([s.level,s.category,s.stage,s.interactionId,mu(s.payload)],t))}function BP(e,t){return e.filter(s=>qi([s.kind,s.topic,s.interactionId,mu(s.payload)],t))}function zh(e){return e==="warn"||e==="error"}function WP({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=>zh(o.level)).length+s.filter(o=>zh(o.level)).length}}function UP({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(`
87
- `)):t.length>0&&o.push(["[daemon logs]",...t].join(`
88
- `)),s.length>0&&o.push(["[trace]",...s.map(a=>`${new Date(a.ts).toISOString()} ${a.level.toUpperCase()} ${a.category}.${a.stage} ${jr(a.payload,500)}`.trim())].join(`
89
- `)),r.length>0&&o.push(["[browser events]",...r.map(a=>`${new Date(a.ts).toISOString()} ${a.kind}${a.topic?` topic=${a.topic}`:""} ${jr(a.payload,500)}`.trim())].join(`
90
- `)),o.join(`
91
-
92
- `)}function KP({machineId:e,sendDaemonCommand:t}){const[s,r]=c.useState([]),[o,a]=c.useState("empty"),[i,l]=c.useState(""),[d,u]=c.useState([]),[m,h]=c.useState([]),[p,b]=c.useState(null),[f,x]=c.useState(!0),[g,w]=c.useState("info"),[S,C]=c.useState("all"),[j,v]=c.useState(!0),[y,N]=c.useState(!0),[k,A]=c.useState(""),[E,P]=c.useState(""),[T,M]=c.useState(0),_=c.useRef(0),I=c.useRef(0),D=c.useRef(0),L=c.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),$=c.useRef([]),U=c.useCallback(()=>{const q={entries:[],kind:"empty",rawText:"",lastTs:0};L.current=q,I.current=0,r([]),l(""),a("empty"),v(!0)},[]),J=c.useCallback(()=>{$.current=[],D.current=0,u([]),N(!0)},[]),K=c.useCallback(q=>{q!==g&&(U(),w(q))},[g,U]),R=c.useCallback(q=>{C(W=>W===q?W:q)},[]),O=c.useCallback(()=>{U(),J(),h([]),b(null),A(""),P(""),bo.clear()},[U,J]),H=c.useCallback(()=>{M(q=>q+1)},[]),B=c.useCallback(async()=>{if(!e)return;const q=_.current+1;_.current=q;const W=I.current,ce=D.current,[ye,G]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:g,since:W}),t(e,"get_debug_trace",RP({count:120,since:ce,category:S}))]);if(_.current===q){if(ye.status==="fulfilled"){const Se=ye.value,ue=(Se==null?void 0:Se.result)||Se,ne=LP(ue),ae=OP(L.current,ne,300);L.current=ae,I.current=ae.lastTs,v(!1),A((Se==null?void 0:Se.success)===!1?String((Se==null?void 0:Se.error)||"Could not load daemon logs"):""),a(ae.kind),l(ae.rawText),r(ae.entries)}else v(!1),A(ye.reason instanceof Error?ye.reason.message:"Could not load daemon logs");if(G.status==="fulfilled"){const Se=G.value,ue=(Se==null?void 0:Se.result)||Se;if((Se==null?void 0:Se.success)===!1)P(String((Se==null?void 0:Se.error)||"Could not load daemon trace"));else if(Array.isArray(ue==null?void 0:ue.trace)){const ne=ue.trace,ae=$P($.current,ne,120),ee=ne.reduce((oe,Ce)=>Math.max(oe,Number(Ce.ts||0)),ce);$.current=ae,ee>ce&&(D.current=ee),P(""),u(ae)}else P("");N(!1)}else N(!1),P(G.reason instanceof Error?G.reason.message:"Could not load daemon trace");h(bo.list({limit:120})),b(Date.now())}},[g,e,t,S]);return c.useEffect(()=>{J()},[J,S]),c.useEffect(()=>{_.current+=1,U(),J(),h([]),b(null),A(""),P("")},[e,U,J]),c.useEffect(()=>{if(!e)return;if(B(),!f)return()=>{_.current+=1};const q=setInterval(()=>{B()},3e3);return()=>{_.current+=1,clearInterval(q)}},[f,B,e,T]),{daemonLogs:s,daemonLogKind:o,daemonRawText:i,debugTrace:d,webEvents:m,lastUpdatedAt:p,autoRefresh:f,logLevel:g,traceCategory:S,daemonLoading:j,traceLoading:y,daemonFetchError:k,traceFetchError:E,setAutoRefresh:x,setLogLevel:K,setTraceCategory:R,refresh:H,clear:O}}function qP({daemonLoading:e,traceLoading:t,daemonFetchError:s,traceFetchError:r,daemonLogKind:o,daemonLogsCount:a,daemonRawLineCount:i,traceCount:l,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":l>0?"ok":"empty",detail:r||`${l} 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 Vh(e){return e==="warn"||e==="error"}function zP(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 VP(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 Gh(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function GP(e){const t=jr(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function YP(e){const t=jr(e.payload,320),s=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${s} ${t}`:`${e.kind}${s}`}function QP({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:YP(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:GP(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:VP(a,i),severity:zP(a),message:a,raw:a})}),o.sort((a,i)=>a.ts!==i.ts?a.ts-i.ts:Gh(a.source)-Gh(i.source))}function JP(e){return`${e.source}:${e.severity}:${e.message}`}function XP(e){const t=e.filter(r=>Vh(r.severity)).sort((r,o)=>o.ts-r.ts),s=new Map;for(const r of e){if(!Vh(r.severity))continue;const o=JP(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 ZP(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Yh(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",s=e.interactionId?` ix=${e.interactionId}`:"";return`${ZP(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${s} ${e.message}`.trim()}function eE({events:e,summary:t,sources:s,maxTimelineEvents:r=80}){const o=[];o.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
93
- `)),o.push(["[source status]",...s.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
94
- `)),t.latestIssue&&o.push(["[latest issue]",Yh(t.latestIssue)].join(`
95
- `)),t.repeatedPatterns.length>0&&o.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
96
- `));const a=e.slice(-r);return o.push(["[timeline]",...a.length>0?a.map(Yh):["No diagnostic events captured."]].join(`
97
- `)),o.join(`
98
-
99
- `)}function tE(e,t){return t==="issues"?e.filter(s=>s.level==="warn"||s.level==="error"):t==="info"?e.filter(s=>s.level!=="debug"):e}function nE(e,t){return t==="issues"?e.filter(s=>s.level==="warn"||s.level==="error"):t==="info"?e.filter(s=>s.level!=="debug"):e}function sE({daemonLogs:e,daemonRawText:t,daemonLogKind:s,debugTrace:r,webEvents:o,traceCategory:a,quickFilter:i,searchQuery:l,daemonLoading:d,traceLoading:u,daemonFetchError:m,traceFetchError:h}){const p=PP(r,a),b=DP(e,l),f=FP(t,l),x=HP(p,l),g=BP(o,l),w=tE(b,i),S=i==="all"?f:[],C=nE(x,i),j=i==="issues"?[]:g,v=WP({daemonLogs:b,daemonRawLines:f,trace:x,webEvents:g}),y=QP({daemonLogs:w,daemonRawLines:S,trace:C,webEvents:j}),N=XP(y),k=qP({daemonLoading:d,traceLoading:u,daemonFetchError:m,traceFetchError:h,daemonLogKind:s,daemonLogsCount:b.length,daemonRawLineCount:f.length,traceCount:x.length,webEventCount:g.length});return{filteredDaemonLogs:b,filteredDaemonRawLines:f,filteredTraceEntries:x,filteredWebEvents:g,visibleDaemonLogs:w,visibleDaemonRawLines:S,visibleTraceEntries:C,visibleWebEvents:j,quickFilterCounts:v,diagnosticEvents:y,diagnosticsSummary:N,sourceStates:k}}function rE(e,t){return e?Si(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"):Si(e,{seconds:!0})}function ed(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 qc(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 hu(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 oE({event:e}){const{t}=he("common");return n.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${ed(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:hu(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 aE({quickFilter:e,quickFilterCounts:t,searchQuery:s,autoRefresh:r,onQuickFilterChange:o,onSearchQueryChange:a,onCopyDiagnostics:i,onCopyVisible:l,onToggleAutoRefresh:d,onRefresh:u,onClear:m}){const{t:h}=he("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:l,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 iE({logLevel:e,traceCategory:t,onLogLevelChange:s,onTraceCategoryChange:r}){const{t:o}=he("common");return n.jsx(hn,{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:MP.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 cE({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:s,searchQuery:r,lastUpdatedAt:o,autoRefresh:a,daemonFetchError:i,traceFetchError:l}){var h,p;const{t:d}=he("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||l?"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 ${qc(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 ${qc(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:[hu(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 ${qc(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||l?"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:rE(o,d)})}),n.jsx("div",{className:"text-3xs text-text-muted mt-2 space-y-1",children:s.map(b=>n.jsxs("div",{children:[b.label,": ",b.status]},b.id))})]})]})}function lE({patterns:e}){const{t}=he("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()," · ",hu(s.source,t)]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1 line-clamp-2",children:s.message})]},s.key))})]})}function dE({streams:e,sectionsOpen:t,setSectionsOpen:s,diagnosticEvents:r,visibleDaemonLogs:o,visibleDaemonRawLines:a,visibleTraceEntries:i,visibleWebEvents:l,quickFilter:d,searchQuery:u}){const{t:m}=he("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(oE,{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 ${ed(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 ${ed(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:jr(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:l.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:[l.length===0&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:u.trim()?m("machine.logsTabSections.noBrowserEventsMatchSearch"):m("machine.logsTabSections.noBrowserEventsYet")}),l.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:jr(h.payload,360)||m("machine.logsTabSections.noPayload")})]},h.id))]})]})]})}function uE({machineId:e,sendDaemonCommand:t}){const s=KP({machineId:e,sendDaemonCommand:t}),[r,o]=c.useState("info"),[a,i]=c.useState(""),[l,d]=c.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),u=c.useRef(null),m=c.useRef(!1),h=c.useMemo(()=>sE({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]);c.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=c.useCallback(async()=>{var x;const f=UP({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!f.trim()){et.showToast("No visible logs to copy.","info");return}try{await((x=navigator.clipboard)==null?void 0:x.writeText(f)),et.showToast("Copied visible logs to clipboard.","success")}catch(g){et.showToast(g instanceof Error?g.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),b=c.useCallback(async()=>{var x;const f=eE({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((x=navigator.clipboard)==null?void 0:x.writeText(f)),et.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){et.showToast(g instanceof Error?g.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return n.jsxs("div",{className:"space-y-4",children:[n.jsx(aE,{quickFilter:r,quickFilterCounts:h.quickFilterCounts,searchQuery:a,autoRefresh:s.autoRefresh,onQuickFilterChange:o,onSearchQueryChange:i,onCopyDiagnostics:()=>{b()},onCopyVisible:()=>{p()},onToggleAutoRefresh:()=>s.setAutoRefresh(f=>!f),onRefresh:s.refresh,onClear:s.clear}),n.jsx(iE,{logLevel:s.logLevel,traceCategory:s.traceCategory,onLogLevelChange:s.setLogLevel,onTraceCategoryChange:s.setTraceCategory}),n.jsx(cE,{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(lE,{patterns:h.diagnosticsSummary.repeatedPatterns}),n.jsx(dE,{streams:s,sectionsOpen:l,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 mE(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 hE(e){var o;const t=[],s=[],r=[];for(const a of e||[]){const i=String((a==null?void 0:a.lifecycle)||"").trim(),l=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||l)?s.push(a):r.push(a)}return{liveRuntimes:t,recoverySnapshots:s,inactiveRecords:r}}function pE(e,t){return e==="live"?t?t("sessionHostSurface.attach"):"Attach":e==="recovery"?t?t("sessionHostSurface.recover"):"Recover":t?t("sessionHostSurface.restart"):"Restart"}function zc(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 fE={starting:"sessionHostSurface.lifecycleStarting",running:"sessionHostSurface.lifecycleRunning",stopping:"sessionHostSurface.lifecycleStopping",stopped:"sessionHostSurface.lifecycleStopped",failed:"sessionHostSurface.lifecycleFailed",interrupted:"sessionHostSurface.lifecycleInterrupted"},bE={starting:"Starting",running:"Running",stopping:"Stopping",stopped:"Stopped",failed:"Failed",interrupted:"Interrupted"};function Qh(e,t){const s=fE[e];return s?t?t(s):bE[e]??e:e}function Vc(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Gc(e){return Si(e,{seconds:!0})||"—"}function Jh(e){return Fa(e)||"—"}function gE(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 xE(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function yE(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 vE(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 wE({machineId:e,cliSessions:t,sendDaemonCommand:s}){const{t:r}=he("common"),[o,a]=c.useState(""),[i,l]=c.useState(null),{confirm:d,confirmDialog:u}=Tr(),[m,h]=c.useState(!1),p=_2(e,{enabled:!!e,includeSessions:!0,limit:oh,intervalMs:w2}),b=p.diagnostics,f=p.loading,x=p.applyDiagnostics,g=c.useMemo(()=>mE({diagnostics:b,loading:f,refreshing:m,error:o,t:r}),[b,f,m,o,r]),w=c.useMemo(()=>new Map(t.map(_=>[_.sessionId||_.id,_])),[t]),S=c.useCallback(async()=>{if(e){h(!0);try{const _=await s(e,"session_host_get_diagnostics",{includeSessions:!0,limit:oh}),I=Vc(_);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(_){const I=_ instanceof Error?_.message:r("sessionHost.diagnosticsFailed");a(I)}finally{h(!1)}}},[x,e,s,r]);c.useEffect(()=>{!e||b||f||m||S()},[b,f,e,S,m]);const C=c.useCallback(async(_,I)=>{const D=`${_}:${I.sessionId}`;if(!(_==="session_host_stop_session"&&!await d({title:r("sessionHost.stopConfirmTitle",{name:I.displayName}),description:r("sessionHost.stopConfirmDescription"),confirmLabel:r("sessionHost.stop"),tone:"danger"}))){l(D);try{const L=await s(e,_,{sessionId:I.sessionId}),$=Vc(L);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||r("sessionHost.actionFailed"));const U=_==="session_host_resume_session"?"sessionHost.toastResumed":_==="session_host_restart_session"?"sessionHost.toastRestarted":"sessionHost.toastStopped";et.showToast(r(U,{name:I.displayName}),"success"),await S()}catch(L){const $=L instanceof Error?L.message:r("sessionHost.actionFailed");et.showToast($,"warning"),a($)}finally{l(L=>L===D?null:L)}}},[d,e,S,s,r]),j=c.useCallback(async()=>{if(await d({title:r("sessionHost.pruneConfirmTitle"),description:r("sessionHost.pruneConfirmDescription"),confirmLabel:r("sessionHost.prune"),tone:"danger"})){l("session_host_prune_duplicate_sessions");try{const I=await s(e,"session_host_prune_duplicate_sessions",{}),D=Vc(I);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||r("sessionHost.pruneFailed"));const L=D.result||{},$=Array.isArray(L.prunedSessionIds)?L.prunedSessionIds.length:0,U=typeof L.duplicateGroupCount=="number"?L.duplicateGroupCount:0;et.showToast(r("sessionHost.toastPruned",{pruned:$,groups:U}),"success"),await S()}catch(I){const D=I instanceof Error?I.message:r("sessionHost.pruneFailed");et.showToast(D,"warning"),a(D)}finally{l(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[d,e,S,s,r]),v=c.useMemo(()=>[...(b==null?void 0:b.sessions)||[]].sort((_,I)=>(I.lastActivityAt||0)-(_.lastActivityAt||0)),[b==null?void 0:b.sessions]),y=c.useMemo(()=>b!=null&&b.liveRuntimes||b!=null&&b.recoverySnapshots||b!=null&&b.inactiveRecords?{liveRuntimes:(b==null?void 0:b.liveRuntimes)||[],recoverySnapshots:(b==null?void 0:b.recoverySnapshots)||[],inactiveRecords:(b==null?void 0:b.inactiveRecords)||[]}:hE(v),[b==null?void 0:b.inactiveRecords,b==null?void 0:b.liveRuntimes,b==null?void 0:b.recoverySnapshots,v]),N=y.liveRuntimes,k=y.recoverySnapshots,A=y.inactiveRecords,E=c.useMemo(()=>vE(N),[N]),P=c.useMemo(()=>[...(b==null?void 0:b.recentTransitions)||[]].slice(-6).reverse(),[b==null?void 0:b.recentTransitions]),T=c.useMemo(()=>[...(b==null?void 0:b.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[b==null?void 0:b.recentLogs]),M=(_,I)=>{var q;const D=i===`session_host_resume_session:${_.sessionId}`,L=i===`session_host_restart_session:${_.sessionId}`,$=i===`session_host_stop_session:${_.sessionId}`,U=fx(_.meta,r),J=w.get(_.sessionId),K=r("sessionHost.clientsCount",{count:_.attachedClients.length}),R=r(I==="recovery"?"sessionHost.recover":"sessionHost.resume"),O=r(I==="recovery"?"sessionHost.recovering":"sessionHost.resuming"),H=pE(I,r),B=Qh(_.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:_.displayName||(J==null?void 0:J.cliName)||_.providerType}),n.jsx("span",{className:`px-2 py-0.5 rounded-md text-3xs font-semibold ${yE(_.lifecycle)}`,children:B}),U&&n.jsx("span",{className:"px-2 py-0.5 rounded-md text-3xs font-semibold bg-sky-500/[0.08] text-sky-300",children:U})]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1 flex flex-wrap gap-2",children:n.jsx(Qt,{content:[_.runtimeKey,_.osPid?`pid ${_.osPid}`:""].filter(Boolean).join(" · "),children:n.jsx("span",{className:"text-text-primary/90",children:_.workspaceLabel||(J==null?void 0:J.runtimeWorkspaceLabel)||_.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:((q=_.writeOwner)==null?void 0:q.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:xE(_.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(xw,{size:11})," ",K]}),n.jsx("span",{className:"text-text-muted",children:"·"}),n.jsx("span",{className:"text-text-primary/85",children:r("sessionHost.activeAgo",{time:Jh(_.lastActivityAt)})}),n.jsx("span",{className:"text-text-muted",children:"·"}),n.jsx("span",{className:"text-sky-200",children:r("sessionHost.nextAction",{action:H})})]})]}),n.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[I==="recovery"&&(_.lifecycle==="interrupted"||_.lifecycle==="failed"||_.lifecycle==="stopped")&&n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1",disabled:!!i,onClick:()=>{C("session_host_resume_session",_)},children:D?O:R}),n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1",disabled:!!i,onClick:()=>{C("session_host_restart_session",_)},children:r(L?"sessionHost.restarting":"sessionHost.restart")}),I==="live"&&(_.lifecycle==="running"||_.lifecycle==="starting"||_.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:()=>{C("session_host_stop_session",_)},children:r($?"sessionHost.stopping":"sessionHost.stop")})]})]})},_.sessionId)};return n.jsxs(hn,{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(xr,{size:14})," ",r("sessionHost.title")]}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:oT()})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[E>0&&n.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{j()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?r("sessionHost.pruning"):r("sessionHost.pruneDuplicatesCount",{count:E})}),n.jsx("span",{className:`px-2 py-1 rounded-md text-3xs font-semibold ${g.toneClass}`,children:g.label}),n.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{S()},disabled:f||m,children:[n.jsx(Ar,{size:13}),r(f||m?"sessionHost.refreshing":"sessionHost.refresh")]})]})]}),o&&!b&&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(en,{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})]})]})}),b&&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:b.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:k.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:b.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:Jh(b.hostStartedAt)}),n.jsx("div",{className:"text-3xs text-text-secondary mt-0.5",children:Gc(b.hostStartedAt)})]})]}),T&&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(en,{size:13})," ",r("sessionHost.latestWarning")]}),n.jsx("div",{className:"text-text-primary leading-relaxed",children:T.message}),n.jsxs("div",{className:"text-3xs text-text-secondary mt-1",children:[Gc(T.timestamp),T.sessionId?` · ${T.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(bd,{size:14})," ",r("sessionHost.liveTitle")]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2.5",children:zc("live",r)}),N.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:N.map(_=>M(_,"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(xr,{size:14})," ",r("sessionHost.recoveryTitle")]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2.5",children:zc("recovery",r)}),k.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:k.map(_=>M(_,"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:zc("inactive",r)}),n.jsx("div",{className:"space-y-2 opacity-85",children:A.map(_=>M(_,"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")}),P.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:P.map(_=>{var D;const I=v.find(L=>L.sessionId===_.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)||((D=w.get(_.sessionId))==null?void 0:D.cliName)||_.sessionId}),n.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[gE(_.action,r),_.lifecycle?` · ${Qh(_.lifecycle,r)}`:"",(_.detail||_.error)&&n.jsx(nt,{content:[_.detail,_.error].filter(Boolean).join(`
100
- `),size:11,className:"ml-1"})]})]}),n.jsx("div",{className:`shrink-0 text-3xs ${_.success===!1?"text-red-300":"text-text-secondary"}`,children:Gc(_.timestamp)})]},`${_.sessionId}:${_.timestamp}:${_.action}`)})})]}),n.jsx(Hd,{className:"mt-3",rows:[{label:r("sessionHost.endpointLabel"),value:b.endpoint||null},{label:r("sessionHost.lastErrorLabel"),value:o||null,copyable:!1}]})]}),u]})}function SE({machine:e,launchPick:t,actions:s}){const{t:r}=he("common"),{runLaunchCliCore:o,setLaunchPick:a}=s;return c.useEffect(()=>{const i=l=>{l.key==="Escape"&&a(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[a]),n.jsx(Un,{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 kE(e,t){const s=gI(e),r=Rs(e,t),o=nu(e,r),a=Aa(e,r),i=Eg(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 Yc({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 Qc({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 jE({machineEntry:e,providers:t,recentLaunches:s,currentConversations:r,onUpgradeDaemon:o,onOpenRecent:a,onOpenConversation:i}){const{t:l}=he("common"),d=r.slice(0,6),u=s.slice(0,4),h=kE(e,"1.0.75"),p=h.visible?[l(h.descriptionKey),h.targetVersion?h.channel?l("machine.commandCenter.updateTargetWithChannel",{version:h.targetVersion,channel:l(`machine.commandCenter.updateChannel.${h.channel}`)}):l("machine.commandCenter.updateTarget",{version:h.targetVersion}):""].filter(Boolean).join(`
101
- `):"";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(Yc,{icon:n.jsx(Cn,{size:13}),children:l("machine.commandCenter.currentChats")}),n.jsx(Qc,{children:n.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(b=>{const f=Ql(b);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(b),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(ws,{conversation:b,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:kt(b)})]}),f>0&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:wi(f)})]}),n.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Po(b)})]},b.tabKey)})})})]}),u.length>0&&n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(Yc,{icon:n.jsx(fd,{size:13}),children:l("machine.commandCenter.recentLaunches")}),n.jsx(Qc,{children:n.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(b=>{const{metaText:f,updatedLabel:x}=Kg(b,l);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(b),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:b.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})]},b.id)})})})]}),h.visible&&h.showButton&&n.jsxs("div",{className:"flex flex-col gap-2","data-testid":"daemon-update-card",children:[n.jsx(Yc,{icon:n.jsx(en,{size:13}),children:l("machine.commandCenter.daemonUpdate")}),n.jsx(Qc,{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:[l(h.titleKey),n.jsx(nt,{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(Ar,{size:13}),n.jsx("span",{className:"text-sm font-medium",children:h.targetVersion?l("machine.commandCenter.updateToVersion",{version:h.targetVersion}):l("machine.commandCenter.updateDaemon")})]})]})})]}),h.visible&&!h.showButton&&n.jsx("div",{"data-testid":"daemon-update-chip",children:n.jsx(Qt,{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"?l("machine.commandCenter.upToDate"):l("machine.commandCenter.updateStatusUnknown")})})})]})}function td(e){return e.trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function NE(e,t){return t.has(td(e))}function CE({displayLabel:e,path:t,busy:s,onSave:r}){const{t:o}=he("common"),[a,i]=c.useState(!1),[l,d]=c.useState(e),[u,m]=c.useState(!1),h=c.useRef(null);c.useEffect(()=>{var x,g;a&&((x=h.current)==null||x.focus(),(g=h.current)==null||g.select())},[a]);const p=()=>{d(e),i(!0)},b=()=>{i(!1),d(e)},f=async()=>{m(!0);try{await r(t,l)&&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:l,maxLength:64,disabled:s||u,onChange:x=>d(x.target.value),onKeyDown:x=>{x.key==="Enter"&&f(),x.key==="Escape"&&b()},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(Cr,{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:b,children:n.jsx(Et,{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(ww,{size:12})})]})}function _E({machineId:e,machine:t,ideSessions:s,cliSessions:r,actions:o,sendDaemonCommand:a}){const{workspaceBusy:i,handleWorkspaceAdd:l,handleWorkspaceRemove:d,handleWorkspaceSetDefault:u,handleWorkspaceSetLabel:m}=o,{t:h}=he("common"),p=Gs(),b=Bd(),[f,x]=c.useState(!1),[g,w]=c.useState(()=>new Set),[S,C]=c.useState(null);c.useEffect(()=>{let D=!1;return(async()=>{try{let L=[];if(b!=null&&b.listMeshes)L=(await b.listMeshes(e)).map($=>$.workspace);else{const $=await a(e,"list_meshes",{}),U=($==null?void 0:$.result)??$;L=(Array.isArray(U==null?void 0:U.meshes)?U.meshes:[]).map(K=>{var R;return Array.isArray(K==null?void 0:K.nodes)&&K.nodes.length>0?String(((R=K.nodes[0])==null?void 0:R.workspace)||""):null})}if(D)return;w(new Set(L.filter($=>!!$).map(td)))}catch{}})(),()=>{D=!0}},[e,b,a]);const j=c.useCallback(D=>{p("/dashboard",{state:{openNewSession:{machineId:e,workspaceId:D}}})},[e,p]),v=c.useCallback((D,L)=>{p("/dashboard",{state:{openNewSession:{machineId:e,workspaceId:D,mode:"mesh",meshWorkspacePath:L}}})},[e,p]),[y,N]=c.useState(""),[k,A]=c.useState([]),[E,P]=c.useState(!1),[T,M]=c.useState(""),_=c.useCallback(async D=>{P(!0),M("");try{const L=await ou(a,e,D);N(L.path),A(L.directories)}catch(L){M(L instanceof Error?L.message:"Could not load folder")}finally{P(!1)}},[e,a]),I=c.useCallback(()=>{x(!0);const D=[...s.map($=>$.workspace),...r.map($=>$.workspace)],L=ru(t.platform,su(D,t.defaultWorkspacePath,(t.workspaces||[]).map($=>$.path)));_(L)},[r,s,_,t.defaultWorkspacePath,t.platform,t.workspaces]);return n.jsxs(n.Fragment,{children:[n.jsxs(hn,{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(Ws,{size:14})," ",h("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:i,onClick:I,children:["+ ",h("machine.managedWorkspaces.addWorkspace")]})]}),(t.workspaces||[]).length===0?n.jsx("div",{className:"text-2xs text-text-muted py-4 text-center",children:h("machine.managedWorkspaces.empty",{button:h("machine.managedWorkspaces.addWorkspace")})}):n.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(D=>{const L=D.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 ${L?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[n.jsx("button",{type:"button",title:h(L?"machine.managedWorkspaces.unsetDefaultHint":"machine.managedWorkspaces.setDefaultHint"),disabled:i,onClick:()=>void u(L?null:D.id),className:`text-base leading-none shrink-0 transition-colors ${L?"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:[NE(D.path,g)?n.jsx(CE,{displayLabel:ya(D.path,D.label),path:D.path,busy:i,onSave:m}):n.jsx("div",{className:"font-medium text-text-primary truncate",children:ya(D.path,D.label)}),n.jsx("div",{className:"font-mono text-text-muted truncate text-3xs",title:D.path,children:D.path})]}),n.jsxs("button",{type:"button",title:h("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:i,onClick:()=>j(D.id),children:[n.jsx(go,{size:11}),h("machine.managedWorkspaces.newSessionShort")]}),g.has(td(D.path))&&n.jsxs("button",{type:"button",title:h("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:i,onClick:()=>v(D.id,D.path),children:[n.jsx(go,{size:11}),h("machine.managedWorkspaces.newMeshSessionShort")]}),n.jsx("button",{type:"button",title:h("machine.managedWorkspaces.remove"),"aria-label":h("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:i,onClick:()=>C({id:D.id,label:ya(D.path,D.label)}),children:n.jsx(Cw,{size:13})})]},D.id)})})]}),f&&n.jsx(iu,{title:h("machine.managedWorkspaces.addWorkspace"),description:h("machine.managedWorkspaces.addDialogDescription"),currentPath:y,directories:k,busy:E,error:T,confirmLabel:h("machine.managedWorkspaces.addWorkspace"),onClose:()=>x(!1),onNavigate:D=>{_(D)},onConfirm:D=>{(async()=>{if(!D)return;await l(D)&&x(!1)})()}}),S&&n.jsx(pf,{title:h("machine.managedWorkspaces.removeConfirmTitle"),description:h("machine.managedWorkspaces.removeConfirmDescription",{label:S.label}),confirmLabel:h("machine.managedWorkspaces.remove"),tone:"danger",busy:i,onCancel:()=>C(null),onConfirm:()=>{const D=S;C(null),D&&d(D.id)}})]})}function AE({machine:e,machineId:t,ideSessions:s,cliSessions:r,actions:o,sendDaemonCommand:a}){const{t:i}=he("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:i("machine.managedWorkspaces.title")})}),a&&n.jsx(_E,{machineId:t,machine:e,ideSessions:s,cliSessions:r,actions:o,sendDaemonCommand:a})]})}function TE({onNicknameSynced:e}={}){var z,X,pe,Pe,Oe,Le,ke,Y,ve,Z,ie;const{t}=he("common"),{id:s}=sy(),r=Gs(),o=hi(),{sendCommand:a}=wt(),i=Rr(),l=Ng(),d=Ii(),u=d.ides||[],m=d.initialLoaded??!0,h=u.find(F=>F.id===s&&F.type==="adhdev-daemon"),p=u.some(F=>F.type==="adhdev-daemon"),b=s?(z=d.connectionRetryStatuses)==null?void 0:z[s]:void 0,f=!!(b!=null&&b.blocked),[x,g]=c.useState("workspace"),[w,S]=c.useState(null),[,C]=c.useState("ide"),j=c.useRef(null),[v,y]=c.useState(null),N=c.useRef("__home__"),[k,A]=c.useState("__home__"),[E,P]=c.useState(!1),T=c.useRef(null);c.useEffect(()=>{!s||!h||!(!h.workspaces||!h.availableProviders||!h.detectedIdes||!h.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,h,s]),c.useEffect(()=>{if(!s||!h||x!=="overview"&&x!=="providers")return;const F=h.machine;(typeof(F==null?void 0:F.cpus)!="number"||typeof(F==null?void 0:F.totalMem)!="number"||typeof(F==null?void 0:F.arch)!="string"||typeof(F==null?void 0:F.release)!="string"||!(F!=null&&F.quota))&&l(s,{minFreshMs:3e4}).catch(()=>{})},[x,l,h,s]),C2(s&&x==="overview"?[s]:[],{enabled:x==="overview",intervalMs:y2});const M=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},_=lP({machineId:s,registeredMachineId:(h==null?void 0:h.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:T});c.useEffect(()=>et.onToast(se=>{d.setToasts(re=>{if(re.some(de=>de.message===se.message&&se.timestamp-de.timestamp<3e3))return re;const V={id:se.id,message:se.message,type:se.type,timestamp:se.timestamp,targetKey:se.targetKey,actions:se.actions,details:se.details};return[...re.slice(-4),V]});const me=se.duration||5e3;setTimeout(()=>d.setToasts(re=>re.filter(we=>we.id!==se.id||we.pinned)),me)}),[d]);const I=(h==null?void 0:h.availableProviders)||[],D={};for(const F of I)D[F.type]=F.icon;const L=h?{id:h.id,hostname:Ad(h,{fallbackId:h.id}),platform:((X=h.machine)==null?void 0:X.platform)||"unknown",arch:((pe=h.machine)==null?void 0:pe.arch)||"",cpus:((Pe=h.machine)==null?void 0:Pe.cpus)||0,totalMem:((Oe=h.machine)==null?void 0:Oe.totalMem)||0,freeMem:(Le=h.machine)==null?void 0:Le.freeMem,availableMem:(ke=h.machine)==null?void 0:ke.availableMem,loadavg:(Y=h.machine)==null?void 0:Y.loadavg,uptime:(ve=h.machine)==null?void 0:ve.uptime,release:((Z=h.machine)==null?void 0:Z.release)||"",cdpConnected:!!h.cdpConnected,machineNickname:h.machineNickname||null,...(ie=h.machine)!=null&&ie.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,$=u.filter(F=>F.daemonId===s&&F.type!=="adhdev-daemon").filter(F=>!So(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,version:F.version||"",instanceId:F.instanceId||"",status:F.status,workspace:F.workspace||null,terminals:F.terminals||0,aiAgents:eN(F.aiAgents||(F.agents||[]).map(se=>({id:se.name,name:se.name,status:se.status,version:se.version}))),activeChat:F.activeChat||null,chats:F.chats||[],childSessions:F.childSessions||[],cdpConnected:F.cdpConnected||!1,daemonId:s,lastMessageAt:F.lastMessageAt})),U=u.filter(F=>F.daemonId===s&&So(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,cliName:F.cliName||F.type,status:F.status,workspace:F.workspace||"",activeChat:F.activeChat||null,providerSessionId:F.providerSessionId,mode:F.mode,runtimeKey:F.runtimeKey,runtimeDisplayName:F.runtimeDisplayName,runtimeWorkspaceLabel:F.runtimeWorkspaceLabel,runtimeWriteOwner:F.runtimeWriteOwner||null,runtimeAttachedClients:F.runtimeAttachedClients||[],daemonId:s,lastMessageAt:F.lastMessageAt})),J=h?pn(h,{fallbackId:s}):"",K="workspace",R=o.state,O=R==null?void 0:R.initialMachineTab,H=R==null?void 0:R.initialWorkspaceCategory;R==null||R.initialWorkspaceId,R==null||R.initialWorkspacePath;const B=O==="session-host"?"hosted-runtimes":O==="logs"?"logs":null,q=O==="ides"||O==="clis"?"workspace":B?"overview":O||K,W=O==="ides"?"ide":O==="clis"?"cli":H,ce=[...$.map(F=>{var se;return{id:`ide:${F.type}:${F.workspace||""}`,label:((se=F.activeChat)==null?void 0:se.title)||F.type,kind:"ide",providerType:F.type,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),...U.map(F=>{var se;return{id:`cli:${F.type}:${F.workspace||""}`,label:((se=F.activeChat)==null?void 0:se.title)||F.cliName,kind:"cli",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}})].sort((F,se)=>(se.lastLaunchedAt||0)-(F.lastLaunchedAt||0)),ye=((h==null?void 0:h.recentLaunches)||[]).length>0?((h==null?void 0:h.recentLaunches)||[]).map(F=>({id:F.id,label:F.title||F.providerName||F.providerType,kind:F.kind,providerType:F.providerType,providerSessionId:F.providerSessionId,subtitle:wo(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace,summaryMetadata:F.summaryMetadata,lastLaunchedAt:F.lastLaunchedAt})):ce,G=c.useMemo(()=>{var se;const F=((se=d.connectionStates)==null?void 0:se[s||""])||void 0;return u.filter(me=>me.daemonId===s&&me.type!=="adhdev-daemon").flatMap(me=>Gd(me,{connectionStates:s&&F?{[s]:F}:void 0,defaultConnectionState:F})).filter(me=>!(me.transport==="pty"&&me.mode==="terminal")).sort((me,re)=>Ql(re)-Ql(me))},[u,d.connectionStates,s]),Se=c.useCallback(F=>{const se=Og(F);se&&r(ko(se))},[r]),ue=c.useCallback(()=>{j.current&&(P(!0),j.current().finally(()=>{j.current=null,P(!1),y(null)}))},[]),ne=c.useCallback(F=>{if(!L)return;const{options:se,selectedKey:me}=Ug({machine:L,currentWorkspacePath:F.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),re=async()=>{C(F.kind),g("workspace")};if(j.current=async()=>{const we=se.find(ge=>ge.key===N.current),V=(we==null?void 0:we.workspacePath)??null,de=(we==null?void 0:we.workspaceId)??null;if(F.kind==="ide"&&F.providerType){await _.handleLaunchIde(F.providerType,V?{workspace:V}:void 0);return}if(F.kind==="cli"&&F.providerType){await _.runLaunchCliCore({cliType:F.providerType,dir:de?void 0:V||"",workspaceId:de||void 0,resumeSessionId:F.providerSessionId});return}await re()},N.current=me,se.length<=1){const we=j.current;j.current=null,we==null||we().catch(V=>et.showErrorToast(t("machine.detail.relaunchFailed"),V));return}A(me),y({title:F.kind==="ide"?Xa(t,"restart-ide",F.label):F.providerSessionId?lg(t,F.label):Xa(t,"start-fresh",F.label),description:F.kind==="ide"?Za(t,"restart-ide"):F.providerSessionId?dg(t):Za(t,"start-fresh"),confirmLabel:F.kind==="ide"?ei(t,"restart-ide"):F.providerSessionId?Bl(t,!0):ei(t,"start-fresh"),busyLabel:F.kind==="ide"?ti(t,"restart-ide"):F.providerSessionId?ig(t,!0):ti(t,"start-fresh"),workspaceOptions:se,details:[{label:t("machine.detail.launchType"),value:F.kind.toUpperCase()},...F.providerType?[{label:t("machine.detail.launchProvider"),value:(()=>{const we=I.find(de=>de.type===F.providerType),V=(we==null?void 0:we.displayName)||F.providerType;return n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx($i,{type:F.providerType,label:V,size:14}),V]})})()}]:[]]})},[_,L,I,t]);if(c.useEffect(()=>{g(q)},[K,q,s]),c.useEffect(()=>{W&&C(W)},[W,s]),!L)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:M,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 ae=(h==null?void 0:h.providerChannelStaleness)??null,ee=!!ae&&ae.staleTypes.length+ae.newTypes.length>0,oe=$.length+U.length,Ce=[{key:"workspace",icon:n.jsx(Bn,{size:14}),label:t("machine.detail.tabSessions"),trailing:oe>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:oe}):void 0},{key:"providers",icon:n.jsx(_r,{size:14}),label:t("machine.detail.tabProviders"),trailing:ee?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(jw,{size:14}),label:t("machine.detail.tabSystem")}],Q=Df[L.platform]||L.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:M,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:[_.editingNickname?n.jsxs("div",{className:"flex gap-1.5 items-center",children:[n.jsx("input",{autoFocus:!0,value:_.nicknameInput,onChange:F=>_.setNicknameInput(F.target.value),onKeyDown:F=>{F.key==="Enter"&&_.handleSaveNickname(),F.key==="Escape"&&_.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:_.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:()=>_.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:()=>{_.setEditingNickname(!0),_.setNicknameInput(L.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:J}),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"),Q].filter(Boolean).join(" · ")})]})]})}),n.jsx(Yd,{variant:"underline",tabs:Ce,activeKey:x,onSelect:F=>g(F),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(jE,{machineEntry:h,providers:I,recentLaunches:ye,currentConversations:G,onUpgradeDaemon:async()=>{const F=tu(h);if(F)try{await a(s,"daemon_upgrade",F)}catch{}},onOpenRecent:ne,onOpenConversation:Se}),n.jsx(AE,{machine:L,machineId:s,ideSessions:$,cliSessions:U,actions:_,sendDaemonCommand:a})]}),x==="providers"&&n.jsx(IP,{machineId:s,providers:I,sendDaemonCommand:a,quota:L.quota}),x==="overview"&&n.jsx(mP,{machine:L,ideSessions:$,cliSessions:U,daemonVersion:h==null?void 0:h.version,initialDiagnostics:B,renderHostedRuntimes:()=>n.jsx(wE,{machineId:s,cliSessions:U,sendDaemonCommand:a}),renderLogs:()=>n.jsx(uE,{machineId:s,sendDaemonCommand:a})})]})})}),_.launchPick&&L&&n.jsx(SE,{machine:L,launchPick:_.launchPick,actions:_}),v&&n.jsx(Wi,{title:v.title,description:v.description,details:v.details,workspaceOptions:v.workspaceOptions,selectedWorkspaceKey:k,onWorkspaceChange:F=>{N.current=F,A(F)},confirmLabel:v.confirmLabel,busyLabel:v.busyLabel,busy:E,onConfirm:ue,onCancel:()=>{j.current=null,y(null)}}),w&&n.jsx(ux,{daemonId:w.daemonId,workspace:w.workspace,onClose:()=>S(null)}),_.confirmDialog,n.jsx(ug,{toasts:d.toasts||[],onDismiss:F=>d.setToasts(se=>se.filter(me=>me.id!==F)),onClickToast:F=>{F.targetKey&&r(ko(F.targetKey))}}),n.jsx("style",{children:`
102
- @keyframes toast-in {
103
- from { opacity: 0; transform: translateX(40px); }
104
- to { opacity: 1; transform: translateX(0); }
105
- }
106
- `})]})}const IE=new Set(["approvalAlert","noProgressAlert","noProgressThresholdSec","longGeneratingAlert","longGeneratingThresholdSec"]),ME=[{id:"approval",keys:["approvalAlert"]},{id:"noProgress",keys:["noProgressAlert","longGeneratingAlert"]}];function RE(e){return e.filter(t=>IE.has(t.key))}function PE({machineId:e,children:t}){return n.jsx(gp,{to:`/machines/${e}`,state:{initialMachineTab:"providers"},className:"text-accent-primary hover:underline",children:t})}function EE({machineId:e,children:t}){return ry()?n.jsx(PE,{machineId:e,children:t}):n.jsx("a",{href:`/machines/${e}`,className:"text-accent-primary hover:underline",children:t})}function LE({machines:e,onBrowserPrefChange:t,renderPushSection:s,initialLoaded:r=!0}){const{t:o}=he("common"),[a,i]=lN(),{sendCommand:l}=wt(),[d,u]=c.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission),[m,h]=c.useState({}),[p,b]=c.useState(!1),f=c.useMemo(()=>e.filter(v=>v.status==="online"),[e]);c.useEffect(()=>{const v=()=>{if(typeof window>"u"||!("Notification"in window)){u("unsupported");return}u(Notification.permission)};return v(),window.addEventListener("focus",v),document.addEventListener("visibilitychange",v),()=>{window.removeEventListener("focus",v),document.removeEventListener("visibilitychange",v)}},[]);const x=c.useCallback(async()=>{b(!0);const v={};for(const y of f)try{const N=await l(y.id,"get_provider_settings",{}),k=mx(N);if(k){const A=hx(k,y.providers||[],{filterSchema:RE});A.length>0&&(v[y.id]=A)}}catch(N){console.warn("[Notifications] Failed to fetch settings from",y.id,N)}h(v),b(!1)},[f,l]);c.useEffect(()=>{f.length>0&&x()},[f.length]);const g=c.useMemo(()=>{const v=[];for(const[y,N]of Object.entries(m)){const k=f.find(E=>E.id===y),A=k?pn(k,{fallbackId:y}):y.slice(0,8);for(const E of N)v.push({...E,machineId:y,machineLabel:A})}return v},[m,f]),w=c.useCallback(async(v,y,N,k)=>{h(A=>{const E={...A};return E[v]=(E[v]||[]).map(P=>P.type===y?{...P,values:{...P.values,[N]:k}}:P),E});try{await l(v,"set_provider_setting",{providerType:y,key:N,value:k})}catch{}},[l]),S=c.useMemo(()=>ME.map(v=>{const y=g.map(k=>({entry:k,key:v.keys.find(A=>k.schema.some(E=>E.key===A))})).filter(k=>!!k.key),N=y.filter(({entry:k,key:A})=>{var E;return!!(k.values[A]??((E=k.schema.find(P=>P.key===A))==null?void 0:E.default))}).length;return{id:v.id,targets:y,total:y.length,onCount:N}}).filter(v=>v.total>0),[g]),C=c.useCallback(async(v,y)=>{const N=S.find(k=>k.id===v);if(N)for(const{entry:k,key:A}of N.targets)await w(k.machineId,k.type,A,y)},[S,w]),j=(v,y)=>{i({[v]:y}),t==null||t(v,y)};return n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsx(bg,{icon:n.jsx(Jn,{className:"text-text-primary"}),title:o("notifications.title"),subtitle:o("notifications.subtitle")}),n.jsxs("div",{className:"page-content",children:[n.jsx(vt,{title:o("notifications.sectionBrowserAlerts"),className:"mb-4",children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Jn,{size:15})," ",o("notifications.masterToggleLabel")]}),description:o("notifications.masterToggleDesc"),checked:a.globalEnabled,onChange:v=>j("globalEnabled",v)}),a.globalEnabled&&n.jsx("div",{className:"border-t border-border-subtle my-0.5"}),a.globalEnabled&&n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Bn,{size:15})," ",o("notifications.browserNotificationsLabel")]}),description:o("notifications.browserNotificationsDesc"),checked:a.browserNotifications,onChange:v=>j("browserNotifications",v)}),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:()=>{Ff().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(nt,{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(`
107
-
108
- `)})]}),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(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(yi,{size:15})," ",o("notifications.completionAlertsLabel")]}),description:o("notifications.completionAlertsDesc"),checked:a.completionAlert,onChange:v=>j("completionAlert",v)}),n.jsx(Vn,{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:v=>j("approvalAlert",v)}),n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(yr,{size:15})," ",o("notifications.connectionAlertsLabel")]}),description:o("notifications.connectionAlertsDesc"),checked:a.disconnectAlert,onChange:v=>j("disconnectAlert",v)})]}),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(DE,{})]}),!a.globalEnabled&&n.jsx("p",{className:"text-2xs text-text-muted italic",children:o("notifications.allDisabled")})]})}),n.jsx(vt,{title:o("notifications.sectionProviderAlerts"),description:o("notifications.agentAlertsDesc"),action:n.jsx(Bi,{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&&g.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:[S.map(({id:v,total:y,onCount:N})=>n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[v==="approval"?n.jsx(Iu,{size:15}):n.jsx(fd,{size:15}),n.jsx("span",{children:o(`notifications.agentAlert.${v}`)}),N>0&&N<y&&n.jsx("span",{className:"text-3xs text-text-muted",children:o("notifications.mixed")})]}),description:o(`notifications.agentAlert.${v}Desc`),checked:N===y,onChange:k=>void C(v,k)},v)),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((v,y)=>n.jsxs("span",{children:[y>0?", ":"",n.jsx(EE,{machineId:v.id,children:f.length>1?pn(v,{fallbackId:v.id}):o("notifications.machineProviders")})]},v.id))]})]}):n.jsx("p",{className:"text-sm text-text-muted py-6 text-center",children:o("notifications.loading")})})]})]})}function DE(){const{t:e}=he("common"),[t,s]=c.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(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Tw,{size:15})," ",e("notifications.soundEffectsLabel")]}),description:e("notifications.soundEffectsDesc"),checked:t,onChange:r})}const Jc=[];function bx(...e){const t=new Set;for(const s of e){const r=Ot(s);r&&t.add(r)}return[...t]}function OE(e,t){var h,p;const s=Ze(e==null?void 0:e.settings),r=Ot((h=e==null?void 0:e.coordinator)==null?void 0:h.meshId)||Ot(s.meshCoordinatorFor),o=Ot(s.meshNodeFor),a=!!r||!!o,i=r===t||o===t;if(a&&!i)return null;const l=Ze(e==null?void 0:e.activeChat),d=bx(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,l.sessionId,l.session_id,l.providerSessionId,l.provider_session_id),u=d[0]||"";if(!u)return null;const m=r===t?Ot((p=e==null?void 0:e.coordinator)==null?void 0:p.role)||"coordinator":o===t?Ot(s.meshNodeRole)||"worker":Ot(e==null?void 0:e.role)||Ot(s.meshNodeRole)||void 0;return{sessionId:u,aliases:d,meshId:t,nodeId:i&&Ot(s.meshNodeId)||null,providerType:Ot(e==null?void 0:e.providerType)||void 0,state:pi(e==null?void 0:e.status)??void 0,chatStatus:Ot(l.status)||void 0,lifecycle:Ot(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:Ot(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:Ot(e==null?void 0:e.runtimeRecoveryState)||void 0,...m?{role:m}:{},...i?{isSelfCoordinator:r===t}:{},workspace:Ot(e==null?void 0:e.workspace)||null}}function gx(e,t){var r;return t?(Array.isArray((r=e.status)==null?void 0:r.sessions)?e.status.sessions:[]).map(o=>OE(o,t)).filter(o=>o!==null):[]}function ii(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function $E(e,t){const s=new Set(ii(t));return ii(e).some(r=>s.has(r))}function FE(e,t){const s=t.filter(o=>!!o);return s.length===0?e:[...e.filter(o=>!s.some(a=>$E(o,a))),...s]}function HE(e,t){const s=e.nodes??[],r=s.filter(l=>{var d;return((d=l.connection)==null?void 0:d.state)==="self"}),o=r.length>0?r:t?s.filter(l=>mn(String(l.daemonId||""),t)):[];if(o.length===1)return o[0].nodeId;const a=o.filter(l=>l.role==="host");if(a.length===1)return a[0].nodeId;const i=o.filter(l=>!l.isLocalWorktree);return i.length===1?i[0].nodeId:null}function BE(e,t,s){if(t.length===0)return e;const r=t.some(d=>d.isSelfCoordinator&&!d.nodeId)?HE(e,s):null,o=new Map;for(const d of t)for(const u of ii(d))o.set(u,d);let a=!1;const l=(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 b=bx(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=b[0]||"";if(!f)continue;const x=b.map(g=>o.get(g)).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(ii(p).some(g=>m.has(g)))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:l}:e}function WE(e,t){const r=gx(e,t).map(o=>{var d;const a=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(u=>Ot(u==null?void 0:u.id)===o.sessionId),i=Ze(a==null?void 0:a.activeInteractivePrompt),l=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??"",Ot(i.status)||Ot(i.kind)||Ot(i.type),o.nodeId??"",o.isSelfCoordinator?"coordinator":"worker",l].join("|")}).filter(o=>!!o).sort();return r.length>0?r.join(`
109
- `):null}function UE({status:e,daemonId:t,meshId:s,sendData:r,extraLiveSessions:o=Jc}){const[a,i]=c.useState(Jc),l=c.useRef(null);c.useEffect(()=>{l.current=null,i(Jc)},[t,s]),c.useEffect(()=>{if(!s||!r||!t)return;const u=Fn.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=WE(m,s);h!==l.current&&(l.current=h,i(gx(m,s)))});return()=>{u()}},[t,s,r]);const d=c.useMemo(()=>FE(a,o),[o,a]);return c.useMemo(()=>e?BE(e,d,t):null,[d,e,t])}function KE(e){return`mesh:status:${e}`}function xx({meshId:e,daemonId:t,sendData:s}){c.useEffect(()=>{if(!(!e||!t||!s))return AA(e),Fn.subscribe({sendData:s},t,{type:"subscribe",topic:"mesh.status",key:KE(e),params:{meshId:e}},r=>{if(r.topic!=="mesh.status"||r.meshId!==e)return;const o=Li(r.status);o&&_A(e,o,t)},{retryIntervalMs:2e3})},[e,t,s])}const yx={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,coordinatorPrompt:!0,nodeInstruction:!0,reviewInbox:!0},vx=c.createContext(null);function qE(){const e=c.useContext(vx);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function pu(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 ci="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function nd({workspaces:e,value:t,onChange:s,autoFocus:r}){const{t:o}=he("common"),[a,i]=c.useState(!1),l=new Set(e.map(u=>u.path)),d=a?"__custom":l.has(t)?t:"";return e.length===0||a?n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("input",{type:"text",className:ci,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:ci,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 li(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]=c.useState(!1),o=c.useRef(null);return c.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,l,d;const{t:s}=he("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}`:""]})):li(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:((l=e.discovery)==null?void 0:l.repoIdentity)||((d=e.discovery)==null?void 0:d.repoRoot)||""})),n.jsx("p",{className:`${a} min-h-[1.4em]`,children:o})}function zE(e){var t;return e.creating||e.planLoading||!e.name.trim()||e.showDaemonPicker&&!e.daemonId||((t=e.plan)==null?void 0:t.success)===!1||li(e.plan)?!0:e.workspace.trim()?!1:!e.repoRemoteUrl.trim()&&!e.repoIdentity.trim()}function kx(e){var _,I;const{variant:t="page",showDaemonPicker:s,daemons:r,daemonLabel:o,name:a,onNameChange:i,daemonId:l,onDaemonIdChange:d,workspace:u,onWorkspaceChange:m,workspaces:h,plan:p,planLoading:b,repoRemoteUrl:f,onRepoRemoteUrlChange:x,repoIdentity:g,onRepoIdentityChange:w,manualOpen:S,onManualOpenChange:C,creating:j,warning:v,onCreate:y,onCancel:N}=e,{t:k}=he("common"),A=zE({creating:j,planLoading:b,plan:p,name:a,workspace:u,showDaemonPicker:s,daemonId:l,repoRemoteUrl:f,repoIdentity:g}),E=wx(b,250),P=S||!!f.trim()||!!g.trim(),T=s&&r.length>0&&n.jsxs("select",{className:t==="wizard"?ci:"input w-full",value:l,onChange:D=>d(D.target.value),children:[n.jsx("option",{value:"",children:k("setupWizard.machines.machineSelectPlaceholder")}),r.map(D=>n.jsx("option",{value:D.id,children:o(D)},D.id))]}),M=P?n.jsxs(n.Fragment,{children:[n.jsx(Ft,{label:k("mesh.list.remoteUrl"),hint:k("mesh.list.remoteUrlHint"),children:n.jsx(Nn,{value:f,onChange:D=>x(D.target.value),placeholder:"https://github.com/user/repo"})}),n.jsx(Ft,{label:k("mesh.list.repoIdentity"),hint:k("mesh.list.repoIdentityHint"),children:n.jsx(Nn,{value:g,onChange:D=>w(D.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:()=>C(!0),children:k("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:k("setupWizard.machines.meshName")}),n.jsx("input",{type:"text",className:ci,value:a,onChange:D=>i(D.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:k("setupWizard.machines.machine")}),T]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:k("setupWizard.machines.workspace")}),n.jsx(nd,{workspaces:h,value:u,onChange:m})]}),n.jsx(Sx,{plan:p,loading:b}),v&&n.jsx("p",{className:"text-2xs text-amber-400",children:v}),n.jsx("div",{className:"flex justify-end",children:n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:y,disabled:A,children:k(j?"setupWizard.machines.creating":"setupWizard.machines.create")})})]}):n.jsxs(n.Fragment,{children:[n.jsx("h3",{className:"text-base font-bold mb-4",children:k("mesh.list.createTitle")}),s&&n.jsx(Ft,{label:k("mesh.list.createOnMachine"),children:r.length===0?n.jsx("select",{className:"input w-full",disabled:!0,children:n.jsx("option",{value:"",children:k("mesh.list.noConnectedDaemon")})}):T}),n.jsx(Ft,{label:k("mesh.list.workspace"),hint:k("mesh.list.workspaceHint"),children:n.jsx(nd,{workspaces:h,value:u,onChange:m})}),(E||p)&&n.jsx(Ht,{variant:(p==null?void 0:p.success)===!1?"error":li(p)?"warning":"info",className:"mb-4",children:E?k("setupWizard.machines.planChecking"):(p==null?void 0:p.success)===!1?pu(p):li(p)?((_=p.plan)==null?void 0:_.summary)||k("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(Ft,{label:k("mesh.list.name"),children:n.jsx(Nn,{value:a,onChange:D=>i(D.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),n.jsx("div",{className:"flex flex-col",children:M}),n.jsxs("div",{className:"flex gap-2 mt-3",children:[n.jsx("button",{className:"btn btn-primary btn-sm",onClick:y,disabled:A,children:k(j?"mesh.list.creating":"mesh.list.create")}),N&&n.jsx("button",{className:"btn btn-secondary btn-sm",onClick:N,disabled:j,children:k("mesh.list.cancel")})]})]})}function VE({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 GE({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 YE({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 QE={online:"#22c55e",dirty:"#f59e0b",offline:"#6b7280",degraded:"#ef4444",enabled:"#22c55e",pending:"#a855f7",assigned:"#3b82f6",completed:"#22c55e",failed:"#ef4444",unknown:"#6b7280"};function JE({status:e}){const{t}=he("common"),s=QE[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}}),YT(e,t)]});return r?n.jsx(Qt,{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 sd(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function XE(e,t,s,r,o){if(!e.length)return"";const a=String(o||"");if(a){const d=e.find(u=>mn(u.id,a));return d?d.id:a}const i=t.find(d=>d.role==="host"),l=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(l){const d=e.find(u=>mn(u.id,l));if(d)return d.id}return""}function zi(e,t){var l;if(t.length===1&&((l=t[0])!=null&&l.id))return t[0].id;if(!e)return"";const s=sd(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=>mn(d.id,a));return i?i.id:a}function ZE(e){const t=new Map;for(const s of e)s!=null&&s.id&&t.set(s.id,Wn(s.availableProviders||[]));return t}function eL(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 Nx(e){if(!e)return null;const t=Ze(e.nodeFacts).availableProviders;if(Array.isArray(t)&&t.length>0)return t;const s=Ze(e.heldRuntime).availableProviders;return Array.isArray(s)&&s.length>0?s:null}function tL(e){if(!e)return[];const t=Ze(e.nodeFacts),s=Object.keys(Ze(e.providerVersions)).length>0?Ze(e.providerVersions):Ze(t.providerVersions),r=Ze(t.providerEnablement);return Object.keys(s).map(o=>o.trim()).filter(o=>o&&Ze(r[o]).enabled!==!1)}function nL(e,t,s){const r=Nx(s);if(r)return Wn(r);const o=eL(e,t),a=tL(s);if(a.length===0)return o;if(o.length>0){const i=new Set(a);return o.filter(l=>i.has(l.type))}return Wn(a.map(i=>({type:i,category:"cli",installed:!0})))}function sL(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,l=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=fu(d,s),h=Nx(m)??(u?r.get(u):r.size===1?[...r.values()][0]:void 0);if(!h||h.length===0){l++;continue}i++;for(const p of h){const b=String((p==null?void 0:p.type)||(p==null?void 0:p.id)||"").trim();!b||o.has(b)||(o.add(b),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:l}}function fu(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 rL(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 Sp(t.slots))o(a.provider);if(Array.isArray(t.providerPriority))for(const a of t.providerPriority)o(a);return r}function oL(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 rL(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 l=new Set;return s.filter(m=>l.has(m.tag)?!1:(l.add(m.tag),!0))}function aL(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 iL(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 cL=["","low","medium","high"],lL={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Xh(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 Zh(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 dL(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const Ts="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function uL({slots:e,availableProviders:t,saving:s,onSave:r}){const{t:o}=he("common"),[a,i]=c.useState(()=>e.map(Xh)),l=c.useMemo(()=>JSON.stringify(e),[e]);c.useEffect(()=>{i(e.map(Xh))},[l]);const d=c.useMemo(()=>[...new Set(t.map(S=>S.type).filter(Boolean))],[t]),u=c.useMemo(()=>P1(t),[t]),m=c.useMemo(()=>{const S=a.map(Zh).filter(Boolean);return JSON.stringify(S)!==JSON.stringify(e)},[a,e]),h=(S,C)=>i(j=>j.map((v,y)=>y===S?{...v,...C}:v)),p=(S,C)=>i(j=>j.map((v,y)=>{var A;if(y!==S)return v;const N=((A=u.get(C))==null?void 0:A.models)??[],k=!v.model||N.length===0||N.includes(v.model);return{...v,provider:C,...k?{}:{model:""}}})),b=S=>i(C=>C.filter((j,v)=>v!==S)),f=()=>i(S=>[...S,dL()]),x=(S,C)=>i(j=>{const v=S+C;if(v<0||v>=j.length)return j;const y=[...j];return[y[S],y[v]]=[y[v],y[S]],y}),g=(S,C)=>i(j=>j.map((v,y)=>{if(y!==S)return v;const N=v.difficulty.includes(C);return{...v,difficulty:N?v.difficulty.filter(k=>k!==C):[...v.difficulty,C]}})),w=()=>r(a.map(Zh).filter(Boolean));return n.jsxs("div",{className:"flex flex-col gap-2",onClick:S=>S.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(nt,{content:o("mesh.slotEditor.emptyHint"),size:12})]}),a.map((S,C)=>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:["#",C+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:C===0,onClick:()=>x(C,-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:C===a.length-1,onClick:()=>x(C,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:()=>b(C),"aria-label":o("mesh.slotEditor.removeSlot"),children:n.jsx(Et,{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:Ts,value:S.provider,onChange:j=>p(C,j.target.value),children:[n.jsx("option",{value:"",children:o("mesh.slotEditor.select")}),d.map(j=>n.jsx("option",{value:j,children:j},j)),S.provider&&!d.includes(S.provider)&&n.jsx("option",{value:S.provider,children:S.provider})]}):n.jsx("input",{className:Ts,value:S.provider,placeholder:"claude-cli",onChange:j=>h(C,{provider:j.target.value})})]}),(()=>{var k;const j=u.get(S.provider),v=(j==null?void 0:j.models)??[],y=(k=j==null?void 0:j.thinking)!=null&&k.length?["",...j.thinking]:cL,N=!!S.model&&v.length>0&&!v.includes(S.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")}),v.length>0&&!N?n.jsxs("select",{className:Ts,value:v.includes(S.model)?S.model:"",onChange:A=>h(C,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[n.jsx("option",{value:"",children:o("mesh.slotEditor.providerDefault")}),v.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:Ts,value:S.model.trim(),placeholder:S.provider?`${S.provider} model`:o("mesh.slotEditor.modelPlaceholder"),onChange:A=>h(C,{model:A.target.value})}),v.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(C,{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:Ts,value:S.thinkingLevel,onChange:A=>h(C,{thinkingLevel:A.target.value}),children:y.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:wp.map(j=>{const v=S.difficulty.includes(j);return n.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-2xs font-medium transition-colors ${v?"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:()=>g(C,j),children:lL[j]},j)})})]}),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:Ts,value:S.capability.join(", "),placeholder:"worktree, os=darwin",onChange:j=>h(C,{capability:j.target.value.split(",").map(v=>v.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:Ts,value:S.maxParallel,placeholder:o("mesh.slotEditor.maxParallelPlaceholder"),onChange:j=>h(C,{maxParallel:j.target.value})})]})]})]},C)),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(go,{size:13})," ",o("mesh.slotEditor.addSlot")]}),n.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:w,disabled:!!s||!m,children:o(s?"mesh.slotEditor.saving":"mesh.slotEditor.saveSlots")})]})]})}function mL(e){const t=e.capabilities;return Array.isArray(t)?t.map(s=>typeof s=="string"?s.trim():"").filter(Boolean):[]}const hL=["os=","arch=","provider=","worktree="];function pL({node:e,saving:t,onSave:s}){const{t:r}=he("common"),o=c.useMemo(()=>oL(e).filter(x=>!x.custom),[e]),a=c.useMemo(()=>mL(e),[e]),[i,l]=c.useState(a),[d,u]=c.useState(""),m=JSON.stringify(i)!==JSON.stringify(a),p=(x=>{const g=x.trim();return g?/\s/.test(g)?r("mesh.tagEditor.noSpaces"):hL.some(w=>g.toLowerCase().startsWith(w))?r("mesh.tagEditor.reservedPrefix"):i.includes(g)?r("mesh.tagEditor.alreadyAdded"):null:null})(d);function b(){const x=d.trim();!x||p||(l(g=>[...g,x]),u(""))}function f(x){l(g=>g.filter(w=>w!==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(),b())},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:b,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(nt,{content:r("mesh.tagEditor.emptyHint"),size:12})]})]})}function fL(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 ep({nodes:e,statusNodes:t,meshQueue:s,daemons:r,userName:o,features:a,providersByDaemonId:i,savingNodeSlotsId:l,onUpdateNodeSlots:d,savingNodeCapabilitiesId:u,onUpdateNodeCapabilities:m,nodeSystemPromptDrafts:h,onNodeSystemPromptDraftChange:p,savingNodeSystemPromptId:b,onSaveNodeSystemPrompt:f,selectedNodeId:x,onSelectNode:g,onRemoveNode:w}){const{t:S}=he("common"),[C,j]=c.useState(()=>new Set),v=y=>j(N=>{const k=new Set(N);return k.has(y)?k.delete(y):k.add(y),k});return e.length===0?n.jsx(Hi,{variant:"compact",icon:n.jsx(Ws,{size:14}),title:S("mesh.nodeList.emptyTitle"),description:S("mesh.nodeList.emptyDescription")}):n.jsx("div",{className:"flex flex-col gap-2",children:e.map(y=>{var L;const N=yL(y),k=bL(y,s),A=fu(y,t),E=aL(A),P=x===y.id,T=C.has(y.id),M=Cx(A)||y.status||(k.length>0||E.length>0?"active":"enabled"),_=a.addNodeDaemonPicker?y.machine_label||y.machine_nickname||y.hostname||y.workspace:y.workspace.split("/").pop()||y.workspace,I=N.configured?N.label.split(" → "):[],D=a.addNodeDaemonPicker?S("mesh.nodeList.ownerMachine",{owner:fL(r.find($=>$.id===String(y.daemon_id||"")),o),machine:y.machine_label||y.daemon_id||y.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 ${P?"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:()=>g(P?null:y.id),onKeyDown:a.addNodeDaemonPicker?void 0:$=>{$.target===$.currentTarget&&($.key==="Enter"||$.key===" ")&&($.preventDefault(),g(P?null:y.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:y.workspace,children:_}),a.addNodeDaemonPicker&&n.jsx(JE,{status:M}),!N.configured&&n.jsx(Qt,{content:S("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:S("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:S("mesh.nodeList.usesTools",{tools:I.join(", ")})}),a.addNodeDaemonPicker&&n.jsx("span",{className:"truncate font-mono text-3xs",title:y.workspace,children:y.workspace.split("/").filter(Boolean).pop()||y.workspace})]})]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0","aria-expanded":T,onClick:$=>{$.stopPropagation(),v(y.id)},children:S(T?"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:$=>{$.stopPropagation(),w(y.id)},"aria-label":S("mesh.nodeList.removeNode"),title:S("mesh.nodeList.removeNode"),children:n.jsx(GE,{size:14})})]}),T&&n.jsxs("div",{className:"mt-3 max-w-2xl cursor-default",onClick:$=>$.stopPropagation(),children:[n.jsx(Ft,{label:S("mesh.nodeList.slotsLabel"),hint:S("mesh.nodeList.slotsHint"),children:n.jsx(uL,{slots:Array.isArray((L=y.policy)==null?void 0:L.slots)?y.policy.slots:[],availableProviders:nL(y,i,A),saving:l===y.id,onSave:$=>d(y,$)})}),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:"▸"})," ",S("mesh.nodeList.advanced")]}),n.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[n.jsx(pL,{node:y,saving:u===y.id,onSave:$=>m(y,$)}),a.nodeInstruction&&n.jsxs(Ft,{label:S("mesh.nodeList.nodeInstruction"),hint:S("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[y.id]??"",onChange:$=>{const U=$.target.value;p(y.id,U)},disabled:b===y.id,placeholder:S("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(y),disabled:b===y.id,children:b===y.id?S("mesh.nodeList.saving"):S("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:[D&&n.jsx("div",{className:"mb-2",children:D}),n.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary",children:S("mesh.nodeList.repoRoot")})," ",n.jsx("span",{className:"font-mono break-all",children:y.repoRoot||y.workspace})]}),n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary",children:S("mesh.nodeList.activeSessionsLabel")})," ",E.length]}),a.addNodeDaemonPicker&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary",children:S("mesh.nodeList.added")})," ",xd(y.created_at||y.createdAt)||"—"]})]}),n.jsxs("div",{className:"mt-3",children:[n.jsx("div",{className:"text-text-secondary mb-1",children:S("mesh.nodeList.activeQueueAssignments")}),k.length===0?n.jsx("div",{children:S("mesh.nodeList.noActiveAssignment")}):n.jsx("ul",{className:"m-0 pl-4",children:k.map($=>n.jsx("li",{className:"font-mono",children:gL($)},$.id))})]}),E.length>0&&n.jsxs("div",{className:"mt-3",children:[n.jsx("div",{className:"text-text-secondary mb-1",children:S("mesh.nodeList.activeSessions")}),n.jsx("ul",{className:"m-0 pl-4",children:E.map($=>n.jsxs("li",{className:"font-mono",children:[$.provider," / ",$.status]},$.id))})]}),n.jsx(Hd,{className:"mt-3",rows:[{label:S("mesh.nodeList.nodeId"),value:y.id},...E.map($=>({label:S("mesh.nodeList.activeSessions"),value:$.id}))]})]})]})]})]})]},y.id)})})}function bL(e,t){return t.filter(s=>s.status!=="assigned"?!1:(s.assignedNodeId||s.nodeId)===e.id)}function gL(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 xL(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:jy((a=e.policy)==null?void 0:a.slots)}function yL(e){const t=xL(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 vL(e){return e.isLocalWorktree===!0}function di(e){return e&&(e.machineNickname||e.nickname||e.hostname||(e.id?wg(e.id):void 0))||"Unknown"}function wL(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 l=wL(i);a.has(l)||(a.set(l,[]),o.push(l)),a.get(l).push(i)}return o.map(i=>{const l=a.get(i),d=i?r.get(i):void 0,u=l[0],m=l.map(g=>fu(g,s)).filter(g=>!!g),h=m.map(g=>iL(g).machineNickname).find(Boolean),p=i?h||(d?di(d):(u==null?void 0:u.machine_label)||(u==null?void 0:u.machine_nickname)||(u==null?void 0:u.hostname)||i):di(d),b=m.map(g=>Cx(g)).filter(g=>!!g),f=b.length>0?b.includes("online"):(d==null?void 0:d.status)==="online",x=l.reduce((g,w)=>{var S;return g+(Array.isArray((S=w.policy)==null?void 0:S.slots)?w.policy.slots.length:0)},0);return{key:i,label:p,online:f,nodes:l,slotCount:x}})}function SL({groups:e,activeKey:t,onChange:s}){const{t:r}=he("common");return n.jsx(Yd,{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 kL({nodes:e,statusNodes:t,meshQueue:s,activeDaemon:r,daemons:o,selectedMeshId:a,userName:i,features:l,coordinatorDaemonId:d,availableCliProviders:u,savingNodeSlotsId:m,onUpdateNodeSlots:h,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:b,nodeSystemPromptDrafts:f,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:w,selectedNodeId:S,onSelectNode:C,showAddNode:j,onShowAddNode:v,onCancelAddNode:y,nodeWorkspace:N,onNodeWorkspaceChange:k,nodeProviderPriority:A,onNodeProviderPriorityChange:E,nodeDaemonId:P,onNodeDaemonIdChange:T,nodeCustomPath:M,onNodeCustomPathChange:_,nodePickerWorkspaces:I,nodePickerProviders:D,nodeOnboardingPlan:L,nodePlanLoading:$,attachableDaemons:U,onAddNode:J,onRemoveNode:K}){var ye,G,Se;const{t:R}=he("common"),O=c.useMemo(()=>ZE(o),[o]),H=c.useMemo(()=>e.filter(ue=>!vL(ue)),[e]),B=c.useMemo(()=>l.addNodeDaemonPicker?_x(H,o,t):[],[l.addNodeDaemonPicker,H,o,t]),[q,W]=c.useState(null),ce=B.some(ue=>ue.key===q)?q:((ye=B[0])==null?void 0:ye.key)??"";return n.jsxs(vt,{title:l.addNodeDaemonPicker?R("mesh.nodeList.title",{count:H.length}):R("mesh.nodeList.titleNoCount"),description:l.addNodeDaemonPicker?R("mesh.nodeList.descriptionCloud"):R("mesh.nodeList.descriptionStandalone"),children:[l.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:U.length})})]}),o.length===0?n.jsx("div",{className:"text-xs text-text-muted",children:R("mesh.nodeList.noDaemonsAvailable")}):U.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:U.map(ue=>n.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors min-w-0 ${ue.id===d?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{T(ue.id),k(""),_(!1),E(Ks(Wn(ue.availableProviders||[]))),v()},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:di(ue)}),ue.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:(ue.workspaces||[]).length})})]},ue.id))})]}),!j&&n.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:v,children:[n.jsx(YE,{size:13})," ",l.addNodeDaemonPicker?R("mesh.nodeList.attachMachine"):R("mesh.nodeList.addNode")]}),j&&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:l.addNodeDaemonPicker?R("mesh.nodeList.attachMachineTitle"):R("mesh.nodeList.addNodeTitle")}),n.jsx("button",{onClick:()=>{y(),T(""),_(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:n.jsx(Et,{size:16})})]}),l.addNodeDaemonPicker&&n.jsx(Ft,{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:P,onChange:ue=>{var ne;T(ue.target.value),k(""),_(!1),E(Ks(Wn(((ne=o.find(ae=>ae.id===ue.target.value))==null?void 0:ne.availableProviders)||[])))},children:[n.jsx("option",{value:"",children:R("mesh.nodeList.selectMachine")}),o.map(ue=>n.jsx("option",{value:ue.id,children:di(ue)},ue.id))]})}),(l.addNodeDaemonPicker?P:!0)&&n.jsx(Ft,{label:R("mesh.nodeList.workspacePath"),children:l.addNodeDaemonPicker&&!M&&I.length>0?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:I.map(ue=>n.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${N===ue.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:()=>k(ue.path),children:[n.jsx("span",{className:"font-medium block truncate",children:ue.label||ue.path.split("/").pop()}),n.jsx("span",{className:"text-3xs text-text-muted font-mono truncate block",children:ue.path})]},ue.id||ue.path))}),n.jsx("button",{type:"button",className:"text-2xs text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{_(!0),k("")},children:R("mesh.nodeList.enterCustomPath")})]}):n.jsx(n.Fragment,{children:l.addNodeDaemonPicker?n.jsxs(n.Fragment,{children:[n.jsx(Nn,{value:N,onChange:ue=>k(ue.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:ue=>{ue.key==="Enter"&&J()}}),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:()=>{_(!1),k("")},children:R("mesh.nodeList.pickFromSaved")})]}):(()=>{var ae;const ue=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],ne=`mesh-add-node-workspaces-${a||"new"}`;return n.jsxs(n.Fragment,{children:[n.jsx(Nn,{value:N,onChange:ee=>k(ee.target.value),placeholder:((ae=ue[0])==null?void 0:ae.path)||"/Users/dev/projects/myapp",list:ue.length>0?ne:void 0,autoFocus:!0}),ue.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("datalist",{id:ne,children:ue.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:ue.slice(0,6).map(ee=>n.jsx("button",{type:"button",onClick:()=>k(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))})]})]})})()})}),($||L)&&n.jsx(Ht,{variant:(L==null?void 0:L.success)===!1?"error":"info",className:"mb-4",children:$?R("mesh.nodeList.inspectingRepo"):L!=null&&L.success?`${((G=L.plan)==null?void 0:G.summary)||R("mesh.nodeList.compatibleWorkspace")} ${R("mesh.nodeList.addingIsExplicit")}`:pu(L)}),n.jsx(Ft,{label:R("mesh.nodeList.preferredTools"),hint:R("mesh.nodeList.preferredToolsHint"),children:n.jsx(jT,{value:A,availableProviders:l.addNodeDaemonPicker?D:u,onChange:E})}),n.jsxs("div",{className:"flex gap-2 mt-3",children:[n.jsx("button",{onClick:J,disabled:$||(L==null?void 0:L.success)===!1||!N.trim()||l.addNodeDaemonPicker&&!P,className:"btn btn-primary btn-sm",children:R("mesh.nodeList.add")}),n.jsx("button",{onClick:()=>{y(),T(""),_(!1)},className:"btn btn-secondary btn-sm",children:R("mesh.nodeList.cancel")})]})]}),H.length===0?n.jsx(Hi,{icon:n.jsx(Ws,{}),title:R("mesh.nodeList.emptyTitle"),description:R("mesh.nodeList.emptyDescription")}):l.addNodeDaemonPicker?n.jsxs(n.Fragment,{children:[B.length>1&&n.jsx(SL,{groups:B,activeKey:ce,onChange:W}),n.jsx(ep,{nodes:((Se=B.find(ue=>ue.key===ce))==null?void 0:Se.nodes)||H,statusNodes:t,meshQueue:s,daemons:o,userName:i,features:l,providersByDaemonId:O,savingNodeSlotsId:m,onUpdateNodeSlots:h,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:b,nodeSystemPromptDrafts:f,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:w,selectedNodeId:S,onSelectNode:C,onRemoveNode:K})]}):n.jsx(ep,{nodes:H,statusNodes:t,meshQueue:s,daemons:o,userName:i,features:l,providersByDaemonId:O,savingNodeSlotsId:m,onUpdateNodeSlots:h,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:b,nodeSystemPromptDrafts:f,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:w,selectedNodeId:S,onSelectNode:C,onRemoveNode:K})]})}function jL(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function NL({meshes:e,loading:t,error:s,onDismissError:r,daemons:o,features:a,showCreate:i,onToggleCreate:l,createName:d,onCreateNameChange:u,createRepoIdentity:m,onCreateRepoIdentityChange:h,createRepoRemoteUrl:p,onCreateRepoRemoteUrlChange:b,newMeshDaemonId:f,onNewMeshDaemonIdChange:x,newMeshWorkspace:g,onNewMeshWorkspaceChange:w,createPickerWorkspaces:S,createOnboardingPlan:C,createPlanLoading:j,creating:v,createWarning:y,onDismissCreateWarning:N,onSelectMesh:k,onCreate:A,onCancelCreate:E,sendCommand:P}){const{t:T}=he("common"),[M,_]=c.useState(!1),[I,D]=c.useState(null);return n.jsxs(Lo,{icon:n.jsx(On,{}),title:T("mesh.list.title"),subtitle:T("mesh.list.count",{count:e.length}),subtitleInline:!0,widthClassName:"max-w-5xl",actions:n.jsx("button",{className:"btn btn-primary btn-sm",onClick:l,children:T("mesh.list.createMesh")}),children:[s&&n.jsx(Ht,{variant:"error",onDismiss:r,className:"mb-4",children:s}),y&&n.jsx(Ht,{variant:"warning",onDismiss:N,className:"mb-4",children:y}),i&&n.jsx(vt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:n.jsx(kx,{variant:"page",showDaemonPicker:a.createDaemonPicker,daemons:o,daemonLabel:jL,name:d,onNameChange:u,daemonId:f,onDaemonIdChange:x,workspace:g,onWorkspaceChange:w,workspaces:S,plan:C,planLoading:j,repoRemoteUrl:p,onRepoRemoteUrlChange:b,repoIdentity:m,onRepoIdentityChange:h,manualOpen:M,onManualOpenChange:_,creating:v,onCreate:A,onCancel:E})}),t?n.jsx("div",{className:"text-sm text-text-muted p-4",children:T("mesh.list.loading")}):e.length===0?n.jsx(Hi,{icon:n.jsx(On,{}),title:T("mesh.list.emptyTitle"),description:o.length>0?T("mesh.list.emptyWithDaemons"):T("mesh.list.emptyNoDaemons"),action:n.jsx("button",{className:"btn btn-primary btn-sm",disabled:!o.length,onClick:l,children:T("mesh.list.createFirst")})}):n.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(L=>{const $=Array.isArray(L.nodes)?L.nodes:[],U=_x($.filter(B=>B.isLocalWorktree!==!0),o).filter(B=>B.key),J=U.filter(B=>B.online).length,K=zi(L,o),R=!!K&&o.some(B=>mn(B.id,K)&&(B.status===void 0||B.status==="online")),O=L.createdAt||L.created_at,H=U.length===0?"bg-neutral-500":J===U.length?"bg-green-400":J===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:()=>k(L.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:L.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 ${H}`}),U.length>0?T("mesh.list.machinesOnline",{online:J,total:U.length}):T("mesh.list.nodeCount",{count:$.length||L.nodeCount||0})]}),n.jsx("span",{className:"truncate font-mono",children:L.repoIdentity||L.repo_identity||T("mesh.list.noRepoIdentity")}),(L.defaultBranch||L.default_branch)&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(VE,{size:11}),L.defaultBranch||L.default_branch]}),O&&n.jsx(Qt,{content:To(O),children:n.jsx("span",{children:xd(O)})})]})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>k(L.id),children:T("mesh.list.settings")}),P&&n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",disabled:!R,title:R?void 0:T("mesh.detail.observabilityDisabledTitle"),onClick:()=>D({meshId:L.id,daemonId:K,meshName:L.name}),children:T("mesh.list.open")})]})]},L.id)})}),I&&P&&n.jsx(qd,{activeConv:jx(I),sendDaemonCommand:P,onClose:()=>D(null)})]})}const y3="inline-flex h-5 min-w-0 max-w-full shrink-0 items-center gap-1 whitespace-nowrap rounded-full border px-2 text-3xs font-medium leading-none";function v3(e){return`inline-flex h-6 shrink-0 items-center gap-1 whitespace-nowrap rounded-full border px-2.5 text-3xs font-medium leading-none transition-colors ${e?"border-accent/50 bg-accent/10 text-accent":"border-border-default bg-transparent text-text-secondary hover:bg-bg-glass-hover hover:text-text-primary"}`}function w3(e){switch(e){case"good":return"border-status-online/30 text-status-online";case"warn":return"border-status-warning/35 text-status-warning";case"danger":return"border-status-error/35 text-status-error";case"neutral":default:return"border-border-default text-text-secondary"}}const S3="rounded-md border border-border-default bg-surface-primary px-1.5 py-0.5 text-3xs font-medium",CL={default:"border-border-default bg-transparent text-text-secondary",good:"border-status-online/30 bg-transparent text-status-online",warn:"border-status-warning/35 bg-transparent text-status-warning",danger:"border-status-error/35 bg-transparent text-status-error",info:"border-border-default bg-transparent text-text-secondary"},_L={default:"border-border-default bg-bg-glass text-text-primary hover:bg-bg-glass-hover",info:"border-accent/40 bg-transparent text-accent hover:bg-accent/10",success:"border-status-online/35 bg-transparent text-status-online hover:bg-status-online/10"},tp={textPrimary:"text-text-primary",textSecondary:"text-text-secondary",textMuted:"text-text-muted",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-xl border border-border-subtle bg-bg-secondary",graphStatChipClass:"rounded-full border border-border-default bg-surface-primary px-3 py-1 text-text-secondary",graphHintChipClass:"rounded-full border border-border-default bg-surface-primary px-3 py-1 text-3xs text-text-muted",graphControlsClass:"!bottom-3 !left-3 !shadow-sm",blueprintShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-xl border border-border-subtle bg-bg-secondary",edgeLabelTextColor:"var(--text-secondary)",edgeLabelBackgroundColor:"var(--surface-primary)",edgeLabelBorderColor:"var(--border-default)",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-2 border-b border-border-subtle bg-bg-primary px-4 pb-0 pt-4 md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-text-primary md:text-xl",dialogKickerClass:"rounded-full border border-border-default px-2.5 py-1 text-2xs text-text-secondary",dialogSubtitleClass:"mt-1 truncate text-sm text-text-muted",dialogRefreshedChipClass:"rounded-full border border-border-default px-3 py-1.5 text-xs text-text-secondary",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-lg border border-border-default bg-bg-glass text-text-secondary transition hover:bg-bg-glass-hover hover:text-text-primary",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-bg-primary px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-xl border border-dashed border-border-default px-6 text-center text-sm text-text-muted",cardClass:"rounded-xl border border-border-subtle bg-bg-card",cardHeaderClass:"border-b border-border-subtle px-4 py-3",cardTitleClass:"text-sm font-semibold text-text-primary",cardSubtitleClass:"mt-1 text-xs text-text-muted",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-border-subtle py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-text-muted",rowValueClass:"min-w-0 flex-1 break-all text-right text-text-primary",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-border-default bg-surface-primary p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-border-subtle bg-surface-primary p-4 text-xs text-text-muted md:w-64",panelTitleClass:"truncate text-xs font-semibold text-text-primary",panelCloseButtonClass:"text-xs text-text-muted hover:text-text-primary",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-border-subtle py-0.5 text-2xs",panelFieldLabelClass:"shrink-0 text-text-muted",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-text-primary",infoCalloutClass:"mt-1 rounded-md border border-border-default bg-bg-glass px-2 py-1.5 text-3xs text-text-secondary",badge:e=>CL[e],actionButton:e=>_L[e]};function Ax(e){return e==="light"?{...tp,theme:e,isDark:!1,flowColorMode:"light",graphBackgroundDotColor:"rgba(15, 23, 42, 0.10)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center bg-[rgba(15,23,42,0.55)] 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-xl border border-border-default bg-bg-primary shadow-lg md:h-[calc(100dvh-32px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-2xl"}:{...tp,theme:e,isDark:!0,flowColorMode:"dark",graphBackgroundDotColor:"rgba(255, 255, 255, 0.06)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center bg-[rgba(0,0,0,0.72)] 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-xl border border-border-default bg-bg-primary shadow-lg md:h-[calc(100dvh-32px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-2xl"}}const Vi=c.createContext(Ax("dark"));function Jr({label:e,tone:t="default",className:s,title:r}){const o=c.useContext(Vi),a=n.jsx("span",{className:`inline-flex h-5 shrink-0 items-center whitespace-nowrap rounded-full border px-2 align-middle text-3xs font-medium leading-none ${o.badge(t)}${s?` ${s}`:""}`,children:e});return r?n.jsx(Qt,{content:r,children:a}):a}function k3({label:e,value:t}){const s=c.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})]})}function Tx(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,`
110
-
111
- `),t.trim()):""}function j3(e){return Tx((e??"").trim())}const ua=["provider_quirk","pattern_to_avoid","recovery_lesson"],np=240,AL={provider_quirk:"warn",pattern_to_avoid:"danger",recovery_lesson:"good"};function Xc(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 ma(e){return To(e)}function TL({meshId:e,daemonId:t,sendDaemonCommand:s}){const{t:r}=he("common"),o=c.useContext(Vi),[a,i]=c.useState([]),[l,d]=c.useState(!1),[u,m]=c.useState(null),[h,p]=c.useState(!1),[b,f]=c.useState(!1),[x,g]=c.useState(""),[w,S]=c.useState(""),[C,j]=c.useState(new Set),[v,y]=c.useState(null),[N,k]=c.useState(""),[A,E]=c.useState(""),P=!!(s&&t&&e),T=c.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 O=Array.isArray(R==null?void 0:R.notes)?R.notes:[];i([...O].reverse())}catch(K){m(K instanceof Error?K.message:r("mesh.notes.loadFailed")),i([])}finally{d(!1)}}},[s,t,e,r]);c.useEffect(()=>{T()},[T]);const M=c.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,...w?{category:w}:{}}),O=(R==null?void 0:R.result)??R;if(O&&O.success===!1){m(typeof O.error=="string"?O.error:r("mesh.notes.saveFailed"));return}g(""),S(""),f(!1),await T()}catch(R){m(R instanceof Error?R.message:r("mesh.notes.saveFailed"))}finally{p(!1)}}},[s,t,e,x,w,h,T,r]),_=c.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}),O=(R==null?void 0:R.result)??R;if(O&&O.success===!1){m(typeof O.error=="string"?O.error:r("mesh.notes.deleteFailed"));return}await T()}catch(R){m(R instanceof Error?R.message:r("mesh.notes.deleteFailed"))}finally{p(!1)}}},[s,t,e,h,T,r]),I=c.useCallback(K=>{y(K.id),k(K.text),E(ua.includes(K.category)?K.category:"")},[]),D=c.useCallback(()=>{y(null),k(""),E("")},[]),L=c.useCallback(async K=>{if(!s||!t||!e||h)return;const R=N.trim();if(R){p(!0),m(null);try{const O=await s(t,"forget_mesh_note",{meshId:e,noteId:K}),H=(O==null?void 0:O.result)??O;if(H&&H.success===!1){m(typeof H.error=="string"?H.error:r("mesh.notes.editFailed"));return}const B=await s(t,"record_mesh_note",{meshId:e,text:R,...A?{category:A}:{}}),q=(B==null?void 0:B.result)??B;if(q&&q.success===!1){m(typeof q.error=="string"?q.error:r("mesh.notes.editFailed"));return}D(),await T()}catch(O){m(O instanceof Error?O.message:r("mesh.notes.editFailed"))}finally{p(!1)}}},[s,t,e,N,A,h,D,T,r]),$=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",U=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",J=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 P?n.jsxs("div",{className:"flex flex-col gap-3",children:[b?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=>g(K.target.value),rows:2,placeholder:r("mesh.notes.textPlaceholder"),className:U,autoFocus:!0}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[n.jsxs("select",{value:w,onChange:K=>S(K.target.value),className:$,"aria-label":r("mesh.notes.categoryLabel"),children:[n.jsx("option",{value:"",children:r("mesh.notes.categoryUncategorized")}),ua.map(K=>n.jsx("option",{value:K,children:Xc(r,K)},K))]}),n.jsx("button",{type:"button",onClick:()=>{M()},disabled:h||!x.trim(),className:J("success"),children:r("mesh.notes.add")}),n.jsx("button",{type:"button",onClick:()=>f(!1),disabled:h,className:J("default"),children:r("mesh.notes.cancel")})]})]}):n.jsx("div",{children:n.jsxs("button",{type:"button",onClick:()=>f(!0),className:J("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(Bi,{onClick:()=>{T()},refreshing:l,disabled:h,label:r("mesh.notes.refresh"),size:13,className:"h-7 w-7"})]}),l?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:v===K.id?n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("textarea",{value:N,onChange:R=>k(R.target.value),rows:2,className:U}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsxs("select",{value:A,onChange:R=>E(R.target.value),className:$,"aria-label":r("mesh.notes.categoryLabel"),children:[n.jsx("option",{value:"",children:r("mesh.notes.categoryUncategorized")}),ua.map(R=>n.jsx("option",{value:R,children:Xc(r,R)},R))]}),n.jsx("button",{type:"button",onClick:()=>{L(K.id)},disabled:h||!N.trim(),className:J("success"),children:r("mesh.notes.save")}),n.jsx("button",{type:"button",onClick:D,disabled:h,className:J("default"),children:r("mesh.notes.cancel")})]})]}):n.jsxs(n.Fragment,{children:[(()=>{const R=Tx(K.text),O=C.has(K.id),H=R.length>np,B=!H||O?R:`${R.slice(0,np).trimEnd()}…`;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`whitespace-pre-wrap break-words text-sm ${o.textPrimary}`,children:B}),H&&n.jsx("button",{type:"button",onClick:()=>j(q=>{const W=new Set(q);return W.has(K.id)?W.delete(K.id):W.add(K.id),W}),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(O?"mesh.notes.showLess":"mesh.notes.showMore")})]})})(),n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[n.jsx(Jr,{label:Xc(r,K.category),tone:ua.includes(K.category)?AL[K.category]:"default"}),K.pinned&&n.jsx(Jr,{label:r("mesh.notes.pinned"),tone:"info"}),K.expired?n.jsx(Jr,{label:r("mesh.notes.expired"),tone:"danger"}):K.pinned?n.jsx(Jr,{label:r("mesh.notes.neverExpires"),tone:"default"}):ma(K.effectiveExpiresAt)?n.jsx("span",{className:`text-2xs ${o.textMuted}`,title:K.effectiveExpiresAt,children:r("mesh.notes.expiresIn",{when:ma(K.effectiveExpiresAt)})}):n.jsx(Jr,{label:r("mesh.notes.durable"),tone:"default"}),ma(K.createdAt)&&n.jsx("span",{className:`text-2xs ${o.textMuted}`,children:ma(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:J("info"),children:r("mesh.notes.edit")}),n.jsx("button",{type:"button",onClick:()=>{_(K.id)},disabled:h,className:J("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 rr={sessionMinRemainingPercent:10,weeklyMinRemainingPercent:15,sessionResetImminentMinutes:5,staleAfterMinutes:30,spreadBonusMax:30,sessionAxisWeeklyHeadroomPercent:40},rd=60*1e3;function sp(e){return e===void 0||!Number.isFinite(e)?"":String(e/rd)}function Ra(e){const t=e??{};return{sessionMinRemainingPercent:t.sessionMinRemainingPercent!==void 0?String(t.sessionMinRemainingPercent):"",weeklyMinRemainingPercent:t.weeklyMinRemainingPercent!==void 0?String(t.weeklyMinRemainingPercent):"",sessionResetImminentMinutes:sp(t.sessionResetImminentMs),staleAfterMinutes:sp(t.staleAfterMs),spreadBonusMax:t.spreadBonusMax!==void 0?String(t.spreadBonusMax):"",sessionAxisWeeklyHeadroomPercent:t.sessionAxisWeeklyHeadroomPercent!==void 0?String(t.sessionAxisWeeklyHeadroomPercent):""}}function IL(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 od(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*rd);const i=s(e.staleAfterMinutes);i!==void 0&&(t.staleAfterMs=i*rd);const l=s(e.spreadBonusMax);l!==void 0&&(t.spreadBonusMax=l);const d=s(e.sessionAxisWeeklyHeadroomPercent);return d!==void 0&&(t.sessionAxisWeeklyHeadroomPercent=d),t}const ML="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs",RL="w-full rounded-lg border border-red-500/60 bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function PL({quotaRouting:e,saving:t,error:s,onSave:r,hideHeader:o=!1}){const{t:a}=he("common"),[i,l]=c.useState(()=>Ra(e)),d=c.useCallback((w,S)=>{l(C=>({...C,[w]:S}))},[]),u=c.useMemo(()=>{const w={};for(const S of Object.keys(i)){const C=IL(S,i[S]);C&&(w[S]=C)}return w},[i]),m=Object.keys(u).length>0,h=c.useMemo(()=>JSON.stringify(od(i))!==JSON.stringify(rp(e)),[i,e]),p=c.useRef(!1),b=JSON.stringify(rp(e));c.useEffect(()=>{p.current||l(Ra(e))},[b]);const f=c.useCallback(()=>{p.current=!1,!(m||!h)&&r(od(i))},[h,i,m,r]),x=c.useCallback(()=>{l(Ra(null)),r({})},[r]),g=[{key:"sessionMinRemainingPercent",label:a("setupWizard.quotaPolicy.sessionMin"),hint:a("setupWizard.quotaPolicy.sessionMinHint"),placeholder:rr.sessionMinRemainingPercent,unit:"%"},{key:"weeklyMinRemainingPercent",label:a("setupWizard.quotaPolicy.weeklyMin"),hint:a("setupWizard.quotaPolicy.weeklyMinHint"),placeholder:rr.weeklyMinRemainingPercent,unit:"%"},{key:"sessionResetImminentMinutes",label:a("setupWizard.quotaPolicy.resetImminent"),hint:a("setupWizard.quotaPolicy.resetImminentHint"),placeholder:rr.sessionResetImminentMinutes,unit:a("setupWizard.quotaPolicy.minutes")},{key:"staleAfterMinutes",label:a("setupWizard.quotaPolicy.staleAfter"),hint:a("setupWizard.quotaPolicy.staleAfterHint"),placeholder:rr.staleAfterMinutes,unit:a("setupWizard.quotaPolicy.minutes")},{key:"spreadBonusMax",label:a("setupWizard.quotaPolicy.spreadBonus"),hint:a("setupWizard.quotaPolicy.spreadBonusHint"),placeholder:rr.spreadBonusMax,unit:""},{key:"sessionAxisWeeklyHeadroomPercent",label:a("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroom"),hint:a("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroomHint"),placeholder:rr.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(nt,{content:a("setupWizard.quotaPolicy.description")})]}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-2",children:g.map(w=>{const S=u[w.key],C=`quota-policy-${w.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:C,children:[w.label,w.unit?` (${w.unit})`:""]}),n.jsx(nt,{content:w.hint,size:12})]}),n.jsx("input",{id:C,type:"number",inputMode:"decimal",className:S?RL:ML,value:i[w.key],placeholder:String(w.placeholder),"aria-invalid":S?!0:void 0,onChange:j=>{p.current=!0,d(w.key,j.target.value)},onBlur:f,onKeyDown:j=>{j.key==="Enter"&&f()}}),S&&n.jsx("span",{className:"text-3xs leading-snug text-red-400",children:a(`setupWizard.quotaPolicy.errors.${S}`)})]},w.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(nt,{content:a("setupWizard.quotaPolicy.blankMeansDefault"),size:12})]})]})]})}function rp(e){return od(Ra(e))}function EL(e,t,s,r){const{t:o}=he(),[a,i]=c.useState(!1),[l,d]=c.useState(null),[u,m]=c.useState(null),[h,p]=c.useState(null),b=c.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 g=typeof x.prompt=="string"?x.prompt:"";return m(g),p(typeof x.bytes=="number"?x.bytes:null),g}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:l,prompt:u,bytes:h,load:b}}function LL({daemonId:e,meshId:t,cliType:s,sendCommand:r,defaultOpen:o=!1}){const{t:a}=he(),[i,l]=c.useState(o),{loading:d,error:u,prompt:m,bytes:h,load:p}=EL(e,t,s,r),b=c.useRef(!1);c.useEffect(()=>{i&&!b.current&&(b.current=!0,p())},[i,p]);const f=c.useCallback(()=>{l(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(nt,{content:`${a("mesh.promptPreview.info")}
112
- ${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 DL(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 OL({daemonId:e,workspace:t,sendCommand:s}){const{t:r}=he(),[o,a]=c.useState(null),i=c.useCallback(async()=>{if(!e||!t){a(null);return}try{const l=await s(e,"read_mesh_json_config",{workspace:t});a(DL(l))}catch{a(null)}},[e,t,s]);return c.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(nt,{content:`${r("mesh.detail.repoMeshJsonHint")}${o.path?`
113
- ${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:l=>l.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:l=>l.currentTarget.select()})]})]}):null}const $L=[{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 op(e,t){if(t)return e.modes.find(s=>s.id===t)}function FL(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&Hn(t)!=="dangerous")}function HL({config:e,requestedModeId:t,machineAutoApproveEnabled:s,machineDangerousAllowed:r}){const o=op(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 l=op(e,i),d=!!i&&!l,u=l??o;if(!u||u.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:a,requestedModeUnknown:d,downgraded:!1};if(Hn(u)==="dangerous"&&!r){const m=FL(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 BL(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 WL({hostDaemonId:e,hostOnline:t,hostWorkspace:s,meshProviders:r,unreportedNodeCount:o=0,machineAutoApproveEnabled:a,machineDangerousAllowed:i,onUpdatePolicy:l,savingPolicy:d,sendCommand:u}){const{t:m}=he("common"),h=c.useMemo(()=>BL(r),[r]),[p,b]=c.useState({}),[f,x]=c.useState(!1),[g,w]=c.useState(null),[S,C]=c.useState(!1),[j,v]=c.useState(null),[y,N]=c.useState(!1),[k,A]=c.useState(null),[E,P]=c.useState(!1),T=!!e&&t&&!!s,M=!!l&&!d,_=c.useCallback(async()=>{var K,R,O;if(T){x(!0),w(null);try{const H=await u(e,"read_mesh_json_config",{workspace:s}),B=(H==null?void 0:H.result)??H,q=((K=B==null?void 0:B.providerDefaults)==null?void 0:K.autoApproveModes)||((O=(R=B==null?void 0:B.config)==null?void 0:R.providerDefaults)==null?void 0:O.autoApproveModes),W={};if(q&&typeof q=="object")for(const[ce,ye]of Object.entries(q))typeof ye=="string"&&ye.trim()&&(W[ce]=ye.trim());b(W)}catch(H){w((H==null?void 0:H.message)||m("mesh.providerAutoApprove.loadError"))}finally{x(!1)}}},[T,e,s,u,m]);c.useEffect(()=>{_()},[_]);const I=c.useRef(null),D=c.useRef(p);D.current=p;const L=c.useCallback((K,R)=>{var H;N(!1);const O={...D.current};R&&R.trim()?O[K]=R.trim():delete O[K],D.current=O,b(O),(H=I.current)==null||H.call(I,O)},[]),$=c.useCallback((K,R)=>{if(Hn(R)==="dangerous"){A({type:K,mode:R});return}L(K,R.id)},[L]),U=c.useCallback(()=>{k&&L(k.type,k.mode.id),A(null)},[L,k]),J=c.useCallback(async K=>{if(T){C(!0),v(null),N(!1);try{const R=await u(e,"set_mesh_provider_defaults",{workspace:s,autoApproveModes:K,merge:!1,write:!0}),O=(R==null?void 0:R.result)??R;if((O==null?void 0:O.success)===!1)throw new Error((O==null?void 0:O.error)||m("mesh.providerAutoApprove.saveError"));N(!0),et.showToast(m("common.saved"),"success"),await _()}catch(R){v((R==null?void 0:R.message)||m("mesh.providerAutoApprove.saveError"))}finally{C(!1)}}},[T,e,s,_,u,m]);return I.current=J,n.jsxs(vt,{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(Qt,{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(ap,{label:m("mesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:m("mesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:a,disabled:!M,onChange:K=>l==null?void 0:l({delegatedWorkerAutoApprove:K})}),n.jsx(ap,{label:m("mesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:m(a?"mesh.providerAutoApprove.machineSection.dangerousToggleHint":"mesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:i,disabled:!M||!a,onChange:K=>{K?P(!0):l==null||l({delegatedWorkerDangerousModeAllow:!1})}})]})]}),T?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:[g&&n.jsx(Ht,{variant:"error",onDismiss:()=>w(null),children:g}),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(Qt,{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(Qt,{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})})}),S&&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],O=HL({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:()=>L(K.type,void 0),disabled:!R||S,children:m("mesh.providerAutoApprove.repoSection.clear")})]}),n.jsx(cx,{config:K.autoApproveModes,selectedModeId:R||"",disabled:S,onSelectMode:H=>$(K.type,H)}),!R&&n.jsx("div",{className:"mt-1.5 text-2xs text-text-muted",children:m("mesh.providerAutoApprove.repoSection.usesProviderDefault")}),n.jsx(UL,{effective:O,config:K.autoApproveModes})]},K.type)})}),j&&n.jsx(Ht,{variant:"error",onDismiss:()=>v(null),children:j}),y&&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")}),E&&n.jsx(Wi,{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:()=>{P(!1),l==null||l({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>P(!1)}),k&&n.jsx(lx,{mode:k.mode,onConfirm:U,onCancel:()=>A(null)}),k&&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(nt,{content:m("mesh.providerAutoApprove.dangerous.sharedWarningDetail")})]}),n.jsx("div",{className:"mt-1 text-xs text-text-muted",children:m("mesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function UL({effective:e,config:t}){var d,u,m,h;const{t:s}=he("common"),r=p=>{var b;return(p?(b=t.modes.find(f=>f.id===p))==null?void 0:b.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 l=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 ${l}`,children:[e.effectiveMode&&n.jsx(ix,{risk:Hn(e.effectiveMode)}),n.jsx("span",{className:"min-w-0",children:o}),a&&n.jsx(nt,{content:a,size:12})]})}function ap({label:e,hint:t,checked:s,disabled:r=!1,onChange:o}){const a=c.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(nt,{content:t,size:12})]}),n.jsx(Pr,{checked:s,disabled:r,onChange:o,"aria-labelledby":a})]})}function ha(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function KL({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:s,isHostNodeAttached:r,selectedHostNode:o,hostPinned:a,hostLabel:i,hostOnline:l,hostRebindDaemonId:d,onHostRebindDaemonIdChange:u,settingMeshHost:m,onSetMeshHost:h}){const{t:p}=he("common");if(a)return n.jsxs(vt,{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 ${l?"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:l?"text-text-muted":"text-amber-400",children:["· ",p(l?"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})]})]}),!l&&n.jsxs("div",{className:"mt-4",children:[n.jsx(Ht,{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(nt,{content:p("mesh.host.hostOfflineText")})]})}),e.length>0?n.jsx(Ft,{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:ha(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 b=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(vt,{title:p("mesh.host.title"),description:p("mesh.host.descriptionUnset"),children:[n.jsx(Ht,{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:ha(b)}),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:ha(b)}),". ",p("mesh.host.attachNodeThenSetHost")]})}):n.jsx(Ft,{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:ha(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")})]})}const Zc=[{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"}],qL=[{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 zL(e){return e==="smart"?"fitness":"first_eligible"}function VL(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"}function Ix(e){return{...(e==null?void 0:e.effectivePolicy)||(e==null?void 0:e.policy)||{}}}function GL(e,t){const s=e==null?void 0:e.policy;return!!s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,t)}function YL({selectedMesh:e,error:t,onDismissError:s,onBack:r,onDelete:o,displayedMeshStatus:a,graphError:i,onRefreshGraph:l,savingPolicy:d,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:h,savingCoordinatorPrompt:p,onSaveCoordinatorPrompt:b,daemons:f,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:g,coordinatorCliType:w,isHostNodeAttached:S,selectedHostNode:C,hostPinned:j,hostLabel:v,hostOnline:y,hostRebindDaemonId:N,onHostRebindDaemonIdChange:k,settingMeshHost:A,onSetMeshHost:E,activeDaemon:P,activeDaemonId:T,meshQueue:M,userName:_,availableCliProviders:I,savingNodeSlotsId:D,onUpdateNodeSlots:L,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:U,nodeSystemPromptDrafts:J,onNodeSystemPromptDraftChange:K,savingNodeSystemPromptId:R,onSaveNodeSystemPrompt:O,selectedNodeId:H,onSelectNode:B,showAddNode:q,onShowAddNode:W,onCancelAddNode:ce,nodeWorkspace:ye,onNodeWorkspaceChange:G,nodeProviderPriority:Se,onNodeProviderPriorityChange:ue,nodeDaemonId:ne,onNodeDaemonIdChange:ae,nodeCustomPath:ee,onNodeCustomPathChange:oe,nodePickerWorkspaces:Ce,nodePickerProviders:Q,nodeOnboardingPlan:z,nodePlanLoading:X,attachableDaemons:pe,onAddNode:Pe,onRemoveNode:Oe,features:Le,sendCommand:ke}){var ot;const{t:Y}=he("common"),ve=Ix(e),Z=e.nodes||[],ie=(a==null?void 0:a.nodes)??null,F=c.useMemo(()=>sL(Z,f,ie),[Z,f,ie]),se=Z.some(_e=>{var jt;const st=Number((jt=_e.policy)==null?void 0:jt.schedulingPriority);return Number.isFinite(st)&&st!==0}),me=!ve.schedulingStrategy,re=c.useMemo(()=>Z.some(_e=>{var st;return Array.isArray((st=_e.policy)==null?void 0:st.slots)&&_e.policy.slots.length>0}),[Z]),we=me&&(re||Z.length>=2)?"smart":null,[V,de]=c.useState(!1),ge=!!T&&!!e.id,{theme:Ie}=Fi(),Ke=c.useMemo(()=>Ax(Ie),[Ie]),Ae="w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",Ne=(ot=e.policy)==null?void 0:ot.quotaRouting,He=Ne&&typeof Ne=="object"?Ne:{},Fe=He.quotaBusyFallback!==!1,it=VL(ve.schedulingStrategy,{priorityConfigured:se}),ut=n.jsxs(n.Fragment,{children:[Le.meshHostDaemonSection&&n.jsx(KL,{daemons:f,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:g,isHostNodeAttached:S,selectedHostNode:C,hostPinned:j,hostLabel:v,hostOnline:y,hostRebindDaemonId:N,onHostRebindDaemonIdChange:_e=>{k(_e),l()},settingMeshHost:A,onSetMeshHost:E}),n.jsx(kL,{nodes:Z,statusNodes:ie,meshQueue:M,activeDaemon:P,daemons:f,selectedMeshId:e.id,userName:_,features:{addNodeDaemonPicker:Le.addNodeDaemonPicker,nodeInstruction:Le.nodeInstruction},coordinatorDaemonId:x,availableCliProviders:I,savingNodeSlotsId:D,onUpdateNodeSlots:L,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:U,nodeSystemPromptDrafts:J,onNodeSystemPromptDraftChange:K,savingNodeSystemPromptId:R,onSaveNodeSystemPrompt:O,selectedNodeId:H,onSelectNode:B,showAddNode:q,onShowAddNode:W,onCancelAddNode:ce,nodeWorkspace:ye,onNodeWorkspaceChange:G,nodeProviderPriority:Se,onNodeProviderPriorityChange:ue,nodeDaemonId:ne,onNodeDaemonIdChange:ae,nodeCustomPath:ee,onNodeCustomPathChange:oe,nodePickerWorkspaces:Ce,nodePickerProviders:Q,nodeOnboardingPlan:z,nodePlanLoading:X,attachableDaemons:pe,onAddNode:Pe,onRemoveNode:Oe}),n.jsx(vt,{title:Y("mesh.detail.distribution"),children:n.jsxs("fieldset",{className:"border-none p-0 m-0",children:[n.jsx("legend",{className:"sr-only",children:Y("mesh.detail.distribution")}),n.jsx("div",{className:"flex flex-col gap-2",children:qL.map(_e=>{const st=it===_e.value;return n.jsxs("label",{className:`flex items-center gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${st?"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:_e.value,checked:st,disabled:d,onChange:()=>u({schedulingStrategy:zL(_e.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:[Y(_e.labelKey),we===_e.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:Y("mesh.detail.recommended")})]}),n.jsx("span",{className:"block truncate text-xs text-text-muted",children:Y(_e.summaryKey)})]}),n.jsx(nt,{content:Y(_e.descriptionKey)})]},_e.value)})})]})}),n.jsx(vt,{title:Y("mesh.detail.visibilityTitle"),description:Y("mesh.detail.visibilityHint"),children:n.jsxs("select",{className:Ae,"aria-label":Y("mesh.detail.visibilityLabel"),value:ve.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:_e=>u({spawnedSessionVisibility:_e.target.value==="visible"?"visible":"hidden"}),disabled:d,children:[n.jsx("option",{value:"hidden",children:Y("mesh.detail.visibilityHidden")}),n.jsx("option",{value:"visible",children:Y("mesh.detail.visibilityVisible")})]})}),n.jsx(WL,{hostDaemonId:x,hostOnline:y,hostWorkspace:(C==null?void 0:C.workspace)||"",meshProviders:F.providers,unreportedNodeCount:F.unreportedNodeCount,machineAutoApproveEnabled:ve.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:ve.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:u,savingPolicy:d,sendCommand:ke})]}),dt=ve.autoFastForward&&typeof ve.autoFastForward=="object"?ve.autoFastForward:{},Tt=dt.enabled!==!1,bt=dt.remoteNodes===!0,te=dt.mode==="continuous"?"continuous":"idle",le=_e=>u({autoFastForward:{...dt,..._e}}),be=Zc.find(_e=>_e.value===ve.sessionCleanupOnNodeRemove)??Zc[0],Te=_e=>GL(e,_e)?n.jsx("button",{type:"button",className:"mt-1.5 text-2xs text-text-muted underline hover:text-text-primary disabled:opacity-50",disabled:d,onClick:()=>u({[_e]:null}),children:Y("mesh.detail.policyResetToDefault")}):n.jsx("span",{className:"mt-1.5 inline-block rounded border border-border-subtle px-1.5 py-0.5 text-2xs uppercase tracking-wider text-text-muted",children:Y("mesh.detail.policyDefaultBadge")}),De=n.jsxs(n.Fragment,{children:[n.jsxs(vt,{title:Y("setupWizard.quotaPolicy.title"),description:Y("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:Y("mesh.detail.quotaBusyFallback")}),n.jsx(nt,{content:Y("mesh.detail.quotaBusyFallbackHint")})]}),n.jsx(Pr,{checked:Fe,disabled:d,"aria-labelledby":"mesh-quota-busy-fallback-label",onChange:_e=>u({quotaRouting:{...He,quotaBusyFallback:_e}})})]}),n.jsx(PL,{quotaRouting:Ne??null,saving:d,error:t,hideHeader:!0,onSave:_e=>u({quotaRouting:{..._e,...He.quotaBusyFallback!==void 0?{quotaBusyFallback:He.quotaBusyFallback}:{}}})})]}),n.jsxs(vt,{title:Y("mesh.detail.safetyTitle"),collapsible:!0,defaultOpen:!1,description:Y("mesh.detail.safetyDescription"),children:[n.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:Y("mesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",Y("mesh.detail.requireApprovalBeforePush")],["not_required",Y("mesh.detail.doNotRequireApproval")]],val:_e=>_e?"required":"not_required",parse:_e=>_e==="required"},{label:Y("mesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",Y("mesh.detail.requireExplicitApproval")],["enabled",Y("mesh.detail.allowRefineryPublish")]],val:_e=>_e?"enabled":"disabled",parse:_e=>_e==="enabled"}].map(({label:_e,key:st,opts:jt,val:gt,parse:Kt})=>n.jsxs(Ft,{label:_e,children:[n.jsx("select",{className:Ae,value:gt(ve[st]),onChange:fe=>u({[st]:Kt(fe.target.value)}),disabled:d,children:jt.map(([fe,Me])=>n.jsx("option",{value:fe,children:Me},fe))}),Te(st)]},st))}),n.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[n.jsxs(Ft,{label:Y("mesh.detail.autoFastForward"),children:[n.jsxs("select",{className:Ae,value:Tt?"enabled":"disabled",onChange:_e=>le({enabled:_e.target.value==="enabled"}),disabled:d,children:[n.jsx("option",{value:"enabled",children:Y("mesh.detail.ffEnabled")}),n.jsx("option",{value:"disabled",children:Y("mesh.detail.ffDisabled")})]}),Te("autoFastForward")]}),n.jsx(Ft,{label:Y("mesh.detail.includeRemoteNodes"),hint:Y("mesh.detail.includeRemoteNodesHint"),children:n.jsxs("select",{className:Ae,value:bt?"yes":"no",onChange:_e=>le({remoteNodes:_e.target.value==="yes"}),disabled:d||!Tt,children:[n.jsx("option",{value:"no",children:Y("mesh.detail.remoteNo")}),n.jsx("option",{value:"yes",children:Y("mesh.detail.remoteYes")})]})}),n.jsx(Ft,{label:Y("mesh.detail.detectionMode"),hint:Y("mesh.detail.detectionModeHint"),children:n.jsxs("select",{className:Ae,value:te,onChange:_e=>le({mode:_e.target.value==="continuous"?"continuous":"idle"}),disabled:d||!Tt||!bt,children:[n.jsx("option",{value:"idle",children:Y("mesh.detail.idleEdgeOnly")}),n.jsx("option",{value:"continuous",children:Y("mesh.detail.continuousScan")})]})}),n.jsxs(Ft,{label:Y("mesh.detail.sessionCleanupLabel"),hint:`${Y("mesh.detail.sessionCleanupHint")}
114
- ${Y(be.descriptionKey)}`,children:[n.jsx("select",{className:Ae,value:ve.sessionCleanupOnNodeRemove||"preserve",onChange:_e=>u({sessionCleanupOnNodeRemove:_e.target.value}),disabled:d,children:Zc.map(_e=>n.jsx("option",{value:_e.value,children:Y(_e.labelKey)},_e.value))}),Te("sessionCleanupOnNodeRemove")]})]})]}),Le.coordinatorPrompt&&n.jsxs(vt,{title:Y("mesh.detail.coordinatorPromptTitle"),collapsible:!0,defaultOpen:!1,description:Y("mesh.detail.thisMeshHint",{name:e.name}),children:[n.jsx(LL,{daemonId:T,meshId:e.id,cliType:w,sendCommand:ke,defaultOpen:!0}),n.jsx(Ft,{label:Y("mesh.detail.overrideLabel"),hint:Y("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:_e=>h({...m,override:_e.target.value}),disabled:p,placeholder:Y("mesh.detail.overridePlaceholder")})}),n.jsx(Ft,{label:Y("mesh.detail.appendLabel"),hint:Y("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:_e=>h({...m,append:_e.target.value}),disabled:p,placeholder:Y("mesh.detail.appendPlaceholder")})}),n.jsx(OL,{daemonId:x,workspace:(C==null?void 0:C.workspace)||"",sendCommand:ke}),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:[Y("mesh.detail.availablePlaceholders"),n.jsx(nt,{content:Y("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:$L.map(_e=>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:`{{${_e.token}}}`}),n.jsx("td",{className:"py-1 pr-3",children:_e.description}),n.jsx("td",{className:"py-1 font-mono text-text-muted/80",children:_e.example})]},_e.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:b,disabled:p,children:Y(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:Y("mesh.detail.clearTitle"),children:Y("mesh.detail.clear")})]})]}),n.jsx(vt,{title:Y("mesh.notes.tab"),collapsible:!0,defaultOpen:!1,description:Y("mesh.notes.sectionHint"),children:n.jsx(Vi.Provider,{value:Ke,children:n.jsx(TL,{meshId:e.id,daemonId:T,sendDaemonCommand:ke})})}),Le.meshHostDaemonSection&&n.jsx(vt,{title:Y("mesh.detail.useFromCli"),collapsible:!0,defaultOpen:!1,description:Y("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]})})]}),qe=[{key:"general",icon:n.jsx(_r,{size:14}),label:Y("mesh.detail.tabGeneral"),content:ut},{key:"advanced",icon:n.jsx(Kp,{size:14}),label:Y("mesh.detail.tabAdvanced"),content:De}];return n.jsxs(Lo,{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:Y("mesh.detail.back")}),n.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>de(!0),disabled:!ge,title:Y(ge?"mesh.detail.observabilityOpenTitle":"mesh.detail.observabilityDisabledTitle"),children:[n.jsx(On,{size:14}),Y("mesh.detail.observabilityOpen")]}),n.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>o(e.id),children:Y("mesh.detail.delete")})]}),children:[t&&n.jsx(Ht,{variant:"error",onDismiss:s,children:t}),i&&n.jsx(Ht,{variant:"warning",children:i}),n.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-subtle bg-bg-card/30",children:n.jsx(xg,{variant:"underline",tabs:qe,tabIdPrefix:"mesh-settings-tab",ariaLabel:Y("mesh.detail.tabsAriaLabel"),panelClassName:"p-4 md:p-6"})}),V&&ge&&n.jsx(qd,{activeConv:jx({meshId:e.id,daemonId:T,meshName:e.name}),sendDaemonCommand:ke,onClose:()=>de(!1)})]})}function QL(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=>zi(d.mesh,t)).find(Boolean)||"";return((i?a.find(d=>mn(d.daemonId,i)):void 0)??a[0]).mesh})}async function JL(e,t,s){const r=new Array(e.length);let o=0;const a=()=>QL(r.filter(i=>!!i),e);return await Promise.all(e.map(async(i,l)=>{try{r[l]=await t(i)}catch{}o+=1,s==null||s({merged:a(),settled:o,total:e.length})})),a()}function XL(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 Xr=new Map;async function Mx(e){var o,a,i,l,d,u,m,h,p,b,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 g={name:e.name.trim()};(e.repoRemoteUrl||(d=(l=(i=x==null?void 0:x.discovery)==null?void 0:i.origin)==null?void 0:l.urls)!=null&&d[0])&&(g.repoRemoteUrl=e.repoRemoteUrl||x.discovery.origin.urls[0]),(e.repoIdentity||(u=x==null?void 0:x.discovery)!=null&&u.repoIdentity)&&(g.repoIdentity=e.repoIdentity||x.discovery.repoIdentity),(m=x==null?void 0:x.discovery)!=null&&m.defaultBranch&&(g.defaultBranch=x.discovery.defaultBranch);const w=await t(e.targetDaemonId,"create_mesh",g),S=s(w);if((S==null?void 0:S.success)===!1)return{...r,error:S.error||"Create failed"};const C=typeof((h=S==null?void 0:S.mesh)==null?void 0:h.id)=="string"?S.mesh.id:"",j={...r,meshCreated:!0,meshId:C};if(!C||!e.attachWorkspace||!e.workspace)return j;try{const v=await t(e.targetDaemonId,"add_mesh_node",{meshId:C,daemonId:e.targetDaemonId,machineId:e.machineId,workspace:((p=x==null?void 0:x.discovery)==null?void 0:p.repoRoot)||e.workspace,repoRoot:(b=x==null?void 0:x.discovery)==null?void 0:b.repoRoot,isLocalWorktree:((f=x==null?void 0:x.discovery)==null?void 0:f.isLinkedWorktree)===!0,role:"host",providerPriority:e.providerPriority}),y=s(v);return(y==null?void 0:y.success)===!1?{...j,warning:ip(y.error||"add_mesh_node failed")}:j}catch(v){return{...j,warning:ip((v==null?void 0:v.message)||"add_mesh_node failed")}}}catch(x){return{...r,error:(x==null?void 0:x.message)||"Create failed"}}}function ip(e){return`Mesh created, but attaching the workspace failed: ${e}. Add the workspace from the mesh's node list.`}function el(e,t){return e===t?!0:e.length!==t.length?!1:JSON.stringify(e)===JSON.stringify(t)}function Rx({daemons:e,primaryDaemonId:t,sendCommand:s,unwrapResult:r,normalizeMesh:o,features:a,loadDaemonMetadata:i,confirmAction:l}){const d=e.map(Se=>Se.id).filter(Boolean).sort().join(","),[u,m]=c.useState(()=>Xr.get(d)??[]);c.useEffect(()=>{za(u)},[u]);const[h,p]=c.useState(null),[b,f]=c.useState(()=>!Xr.has(d)),[x,g]=c.useState(null),[w,S]=c.useState(!1),[C,j]=c.useState(!1),[v,y]=c.useState(null),[N,k]=c.useState(""),[A,E]=c.useState(""),[P,T]=c.useState(""),[M,_]=c.useState(""),[I,D]=c.useState(""),[L,$]=c.useState(null),[U,J]=c.useState(!1),K=a.createDaemonPicker?M:t,R=c.useMemo(()=>e.find(Se=>Se.id===K),[e,K]),O=(R==null?void 0:R.workspaces)||[],H=c.useMemo(()=>Wn((R==null?void 0:R.availableProviders)||[]),[R]);c.useEffect(()=>{!i||!K||!R||!(!R.workspaces||!R.availableProviders)||Promise.resolve(i(K,{minFreshMs:3e4})).catch(()=>{})},[i,K,R]),c.useEffect(()=>{if(!w||!K||!I){$(null),J(!1);return}let Se=!1;return J(!0),s(K,"plan_mesh_onboarding",{workspace:I,operation:"auto",meshInventory:u}).then(ue=>{if(Se)return;const ne=r(ue);$(ne),ne!=null&&ne.success&&(E(ae=>{var ee;return ae||((ee=ne.discovery)==null?void 0:ee.repoIdentity)||""}),T(ae=>{var ee,oe,Ce,Q,z,X;return ae||((Ce=(oe=(ee=ne.discovery)==null?void 0:ee.origin)==null?void 0:oe.urls)==null?void 0:Ce[0])||((X=(z=(Q=ne.discovery)==null?void 0:Q.upstream)==null?void 0:z.urls)==null?void 0:X[0])||""}),k(ae=>{var ee,oe;return ae||`${String(((ee=ne.discovery)==null?void 0:ee.repoIdentity)||((oe=ne.discovery)==null?void 0:oe.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(ue=>{Se||$({success:!1,error:(ue==null?void 0:ue.message)||"Git discovery failed"})}).finally(()=>{Se||J(!1)}),()=>{Se=!0}},[w,K,I,u,s,r]);const B=c.useMemo(()=>e.map(Se=>Se.id).filter(Boolean).sort().join(","),[e]),q=c.useRef(0),W=c.useCallback(async(Se=!1)=>{const ue=++q.current,ne=()=>q.current===ue;if(a.createDaemonPicker?!B:!t){f(!0);return}const ae=Se||Xr.has(B);f(ee=>ae?ee:!0);try{if(a.createDaemonPicker){const ee=await JL(e,async oe=>{if(!oe.id)return{daemonId:"",meshes:[]};const Ce=await s(oe.id,"list_meshes",{}),Q=r(Ce);if((Q==null?void 0:Q.success)===!1)throw new Error(Q.error||"Failed to load meshes");const z=(Array.isArray(Q==null?void 0:Q.meshes)?Q.meshes:[]).map(X=>o(X,oe.id)).filter(X=>X.id);return{daemonId:oe.id,meshes:z}},({merged:oe,settled:Ce,total:Q})=>{!ne()||Ce>=Q||oe.length!==0&&(m(z=>{const X=ae?XL(z,oe):oe;return el(z,X)?z:X}),f(!1))});if(!ne())return;m(oe=>el(oe,ee)?oe:ee),Xr.set(B,ee),g(null)}else{const ee=await s(t,"list_meshes");if(!ne())return;if(ee!=null&&ee.success){const oe=(ee.meshes||[]).map(Ce=>o(Ce,t));m(Ce=>el(Ce,oe)?Ce:oe),Xr.set(B,oe),g(null)}else g((ee==null?void 0:ee.error)||"Failed to load meshes")}}catch(ee){ne()&&g((ee==null?void 0:ee.message)||"Failed to load meshes")}finally{ne()&&f(!1)}},[B,t,s,r,o,a.createDaemonPicker]);async function ce(){const Se=a.createDaemonPicker?M:t;if(!Se||!N.trim())return;const ue=P.trim(),ne=A.trim(),ae=I.trim();if(!(!ae&&!ue&&!ne)&&!C){j(!0),y(null);try{const ee=await Mx({targetDaemonId:Se,name:N,repoRemoteUrl:ue,repoIdentity:ne,workspace:ae,attachWorkspace:!!ae,machineId:R==null?void 0:R.machineId,providerPriority:Ks(H),meshInventory:u,sendCommand:s,unwrapResult:r,reusablePlan:!U&&L?L:void 0});if(ee.plan!==null&&$(ee.plan),ee.warning&&y(ee.warning),!ee.meshCreated){g(ee.error||"Create failed");return}S(!1),k(""),E(""),T(""),D(""),await W(),ee.meshId&&p(ee.meshId)}finally{j(!1)}}}async function ye(Se){var ee;const ue=((ee=u.find(oe=>oe.id===Se))==null?void 0:ee.name)||Se;if(!(l?await l({title:"Delete this mesh?",description:`"${ue}" will be removed from this daemon. This cannot be undone.`,confirmLabel:"Delete",tone:"danger"}):confirm("Delete this mesh? This cannot be undone.")))return;const ae=zi(u.find(oe=>oe.id===Se),e)||(a.createDaemonPicker?"":t);if(!ae){g(Ye.t("mesh.host.noCommandTarget"));return}try{const oe=await s(ae,"delete_mesh",{meshId:Se}),Ce=r(oe);if((Ce==null?void 0:Ce.success)===!1)throw new Error(Ce.error||"Failed to delete");h===Se&&p(null),await W()}catch(oe){g((oe==null?void 0:oe.message)||"Delete failed")}}function G(){S(!1),k(""),E(""),T(""),D(""),$(null),y(null)}return{meshes:u,setMeshes:m,selectedMeshId:h,setSelectedMeshId:p,loading:b,error:x,setError:g,showCreate:w,setShowCreate:S,creating:C,createWarning:v,setCreateWarning:y,createName:N,setCreateName:k,createRepoIdentity:A,setCreateRepoIdentity:E,createRepoRemoteUrl:P,setCreateRepoRemoteUrl:T,newMeshDaemonId:M,setNewMeshDaemonId:_,newMeshWorkspace:I,setNewMeshWorkspace:D,createPickerWorkspaces:O,createPickerProviders:H,createOnboardingPlan:L,createPlanLoading:U,loadMeshes:W,handleCreate:ce,handleDelete:ye,cancelCreate:G}}function ZL({selectedMesh:e,selectedMeshId:t,activeDaemonId:s,daemons:r,sendCommand:o,unwrapResult:a,loadLiveMesh:i,resolveCommandTarget:l,launchCoordinator:d,features:u,loadMeshes:m,reloadMeshStatus:h,setError:p,confirmAction:b}){const f=s;function x(){return f||(p(Ye.t("mesh.host.noCommandTarget")),null)}const[g,w]=c.useState(null),[S,C]=c.useState(!1),[j,v]=c.useState(""),[y,N]=c.useState([]),[k,A]=c.useState(""),[E,P]=c.useState(!1),[T,M]=c.useState(null),[_,I]=c.useState(!1),[D,L]=c.useState(""),[$,U]=c.useState(!1),[J,K]=c.useState(!1),[R,O]=c.useState(null),[H,B]=c.useState(!1),[q,W]=c.useState({override:"",append:""}),[ce,ye]=c.useState(!1),[G,Se]=c.useState({}),[ue,ne]=c.useState(null),ae=c.useMemo(()=>r.find(F=>F.id===k),[r,k]),ee=(ae==null?void 0:ae.workspaces)||[],oe=c.useMemo(()=>Wn((ae==null?void 0:ae.availableProviders)||[]),[ae]);c.useEffect(()=>{if(!S||!t||!j.trim()){M(null);return}const F=u.addNodeDaemonPicker?k:f;if(!F)return;let se=!1;return I(!0),o(F,"plan_mesh_onboarding",{workspace:j.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(me=>{se||M(a(me))}).catch(me=>{se||M({success:!1,error:(me==null?void 0:me.message)||"Git discovery failed"})}).finally(()=>{se||I(!1)}),()=>{se=!0}},[S,t,e,j,k,f,u.addNodeDaemonPicker,o,a]);async function Ce(){var me,re,we;if(!t)return;const F=j.trim();if(!F)return;const se=x();if(se)try{const V=u.addNodeDaemonPicker?k:se,de=await o(V,"plan_mesh_onboarding",{workspace:F,meshId:t,inlineMesh:e,operation:"add_existing"}),ge=a(de);if(M(ge),(ge==null?void 0:ge.success)===!1)throw new Error(pu(ge));const Ie={meshId:t,workspace:((me=ge==null?void 0:ge.discovery)==null?void 0:me.repoRoot)||F,repoRoot:(re=ge==null?void 0:ge.discovery)==null?void 0:re.repoRoot,isLocalWorktree:((we=ge==null?void 0:ge.discovery)==null?void 0:we.isLinkedWorktree)===!0};u.addNodeDaemonPicker&&k&&(Ie.daemonId=k,Ie.machineId=ae==null?void 0:ae.machineId),Ie.providerPriority=Eo(y);const Ke=await o(se,"add_mesh_node",Ie),Ae=a(Ke);if((Ae==null?void 0:Ae.success)===!1)throw new Error(Ae.error||"Add node failed");C(!1),v(""),N([]),A(""),P(!1),await m(),await h()}catch(V){p((V==null?void 0:V.message)||"Add node failed")}}async function Q(F){var ge;if(!e)return;const se=Ix(e),me=(e.nodes||[]).find(Ie=>Ie.id===F),re=se.sessionCleanupOnNodeRemove||((me==null?void 0:me.isLocalWorktree)===!0?"stop_and_delete":"preserve"),we=((ge=[{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(Ie=>Ie.value===re))==null?void 0:ge.label)||"Preserve history and runtimes";if(!(b?await b({title:"Remove this node?",description:`Node removal cleanup policy: ${we}`,confirmLabel:"Remove",tone:"danger"}):confirm(`Remove this node?
115
-
116
- Node removal cleanup policy: ${we}`)))return;const de=x();if(de)try{const Ie=await o(de,"remove_mesh_node",{meshId:e.id,nodeId:F}),Ke=a(Ie);if((Ke==null?void 0:Ke.success)===!1)throw new Error(Ke.error||"Remove failed");g===F&&w(null),await m(),await h()}catch(Ie){p((Ie==null?void 0:Ie.message)||"Remove node failed")}}async function z(F){if(!e)return;const se={...F},me=x();if(me)try{B(!0),p(null);const re=await o(me,"update_mesh",{meshId:e.id,policy:se}),we=a(re);if((we==null?void 0:we.success)===!1)throw new Error(we.error||"Policy update failed");et.showToast(Ye.t("common.saved"),"success"),await m()}catch(re){p((re==null?void 0:re.message)||"Policy update failed")}finally{B(!1)}}const[X,pe]=c.useState(null);async function Pe(F,se){if(!t)return;const me=x();if(me)try{pe(F.id),p(null);const re=await o(me,"update_mesh_node",{meshId:t,nodeId:F.id,policy:{slots:se}}),we=a(re);if((we==null?void 0:we.success)===!1){p(we.error||"Node slots update failed");return}et.showToast(Ye.t("common.saved"),"success"),await m()}catch(re){p((re==null?void 0:re.message)||"Node slots update failed")}finally{pe(null)}}const[Oe,Le]=c.useState(null);async function ke(F,se){if(!t)return;const me=x();if(!me)return;const re=se.map(we=>we.trim()).filter(Boolean);try{Le(F.id),p(null);const we=await o(me,"update_mesh_node",{meshId:t,nodeId:F.id,capabilities:re}),V=a(we);if((V==null?void 0:V.success)===!1){p(V.error||"Node tag update failed");return}et.showToast(Ye.t("common.saved"),"success"),await m()}catch(we){p((we==null?void 0:we.message)||"Node tag update failed")}finally{Le(null)}}async function Y(){if(!t)return;const F=x();if(!F)return;const me={...(e==null?void 0:e.coordinator)||{}};q.override.trim()?me.systemPromptOverride=q.override:delete me.systemPromptOverride,q.append.trim()?me.systemPromptAppend=q.append:delete me.systemPromptAppend,delete me.systemPromptSuffix;try{ye(!0),p(null);const re=await o(F,"update_mesh",{meshId:t,coordinator:me}),we=a(re);if((we==null?void 0:we.success)===!1){p(we.error||"Coordinator prompt save failed");return}et.showToast(Ye.t("common.saved"),"success"),await m()}catch(re){p((re==null?void 0:re.message)||"Coordinator prompt save failed")}finally{ye(!1)}}async function ve(F){if(!t)return;const se=x();if(!se)return;const me=(G[F.id]||"").trim();try{ne(F.id),p(null);const re=await o(se,"update_mesh_node",{meshId:t,nodeId:F.id,systemPrompt:me}),we=a(re);if((we==null?void 0:we.success)===!1){p(we.error||"Node instruction save failed");return}et.showToast(Ye.t("common.saved"),"success"),await m()}catch(re){p((re==null?void 0:re.message)||"Node instruction save failed")}finally{ne(null)}}async function Z(F){if(!(!e||!F)){if(b){const se=r.find(we=>we.id===F),me=(se==null?void 0:se.machineNickname)||(se==null?void 0:se.nickname)||(se==null?void 0:se.hostname)||F;if(!await b({title:Ye.t("mesh.host.setHostConfirmTitle",{name:me}),description:Ye.t("mesh.host.setHostActionHint"),confirmLabel:Ye.t("mesh.host.setHostAction")}))return}p(null),O(null);try{K(!0);const se=(e.nodes||[]).find(we=>mn(String(we.daemon_id||we.daemonId||""),F)),me=await o(F,"set_mesh_host",{meshId:e.id,hostDaemonId:F,...se!=null&&se.id?{hostNodeId:se.id}:{}}),re=a(me);if((re==null?void 0:re.success)===!1){p(re.error||"Setting the mesh host failed");return}await m()}catch(se){p((se==null?void 0:se.message)||"Setting the mesh host failed")}finally{K(!1)}}}async function ie(){if(e){p(null),O(null);try{U(!0);const F=i?await i(s,e.id,e):null,se=l(s,e.id,e,e.nodes||[],F);if("error"in se)throw new Error(se.error);const me=await d(se.targetDaemonId,{meshId:e.id,inlineMesh:se.inlineMesh,coordinatorNodeId:se.coordinatorNodeId,cliType:D.trim()||void 0});O(me.message)}catch(F){p((F==null?void 0:F.message)||"Coordinator launch failed")}finally{U(!1)}}}return{selectedNodeId:g,setSelectedNodeId:w,showAddNode:S,setShowAddNode:C,nodeWorkspace:j,setNodeWorkspace:v,nodeProviderPriority:y,setNodeProviderPriority:N,nodeDaemonId:k,setNodeDaemonId:A,nodeCustomPath:E,setNodeCustomPath:P,nodePickerWorkspaces:ee,nodePickerProviders:oe,nodeOnboardingPlan:T,nodePlanLoading:_,coordinatorCliType:D,setCoordinatorCliType:L,launchingCoordinator:$,launchResult:R,settingMeshHost:J,savingPolicy:H,coordinatorPromptDraft:q,setCoordinatorPromptDraft:W,savingCoordinatorPrompt:ce,nodeSystemPromptDrafts:G,setNodeSystemPromptDrafts:Se,savingNodeSystemPromptId:ue,savingNodeSlotsId:X,savingNodeCapabilitiesId:Oe,handleAddNode:Ce,handleRemoveNode:Q,handleUpdatePolicy:z,handleUpdateNodeSlots:Pe,handleUpdateNodeCapabilities:ke,handleSaveCoordinatorPrompt:Y,handleSaveNodeSystemPrompt:ve,handleLaunchCoordinator:ie,handleSetMeshHost:Z}}const eD=[];function tD(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"):eD}function nD({status:e}){return{meshQueue:c.useMemo(()=>tD(e),[e])}}const sD=()=>()=>{};function Px(e){const t=c.useCallback(r=>e?NA(e,r):sD(),[e]),s=c.useCallback(()=>uo(e),[e]);return c.useSyncExternalStore(t,s,s)}function N3({meshId:e,daemonId:t,load:s,extract:r,sendData:o}){const a=Px(e),i=c.useRef(s);i.current=s;const l=c.useRef(r);l.current=r;const d=c.useCallback(h=>{const p=i.current;return!e||!t||!p?Promise.resolve(null):Oi({meshId:e,daemonId:t,refresh:h,load:p,extract:l.current})},[e,t]);xx({meshId:e,daemonId:t,sendData:o});const u=c.useCallback(()=>d(!0),[d]),m=c.useCallback(()=>d(!1),[d]);return{status:(a==null?void 0:a.status)??null,loading:(a==null?void 0:a.loading)??!1,refreshing:(a==null?void 0:a.refreshing)??!1,error:(a==null?void 0:a.error)??null,loadedAt:(a==null?void 0:a.loadedAt)??null,refresh:u,reload:m}}function rD(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}function oD({selectedMeshId:e,loadMeshStatus:t,extractStatus:s,normalizeNode:r}){const o=Px(e),[a,i]=c.useState(null),[l,d]=c.useState("idle"),u=(o==null?void 0:o.status)??null,m=c.useMemo(()=>!u||!r?u:{...u,nodes:(u.nodes??[]).map(b=>r(b,u.meshId??e??"",""))},[u,r,e]);function h(b){e&&CA(e,b,(o==null?void 0:o.daemonId)??null)}async function p(b,f=e,x=!1){var w;if(!b||!f)return;i(null),d(x?"settling":"first_paint"),await Oi({meshId:f,daemonId:b,refresh:x,load:(S,C,j)=>t(S,C,{refresh:j.refresh}),extract:S=>s(S)})?d("settled"):(i(((w=uo(f))==null?void 0:w.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:l,graphBootstrapFallback:rD(o==null?void 0:o.response),loadGraph:p}}function aD(){var fn;const e=qE(),{t}=he("common"),{confirm:s,confirmDialog:r}=Tr(),{sendCommand:o,sendData:a,daemons:i,userName:l,loadMeshStatus:d,launchCoordinator:u,loadLiveMesh:m,extractStatus:h,unwrapResult:p,normalizeMesh:b,normalizeNode:f,resolveCommandTarget:x,features:g}=e,w=Rr(),S=i[0],C=(S==null?void 0:S.id)||"",j=c.useMemo(()=>Wn((S==null?void 0:S.availableProviders)||[]),[S]),{meshes:v,selectedMeshId:y,setSelectedMeshId:N,loading:k,error:A,setError:E,showCreate:P,setShowCreate:T,createName:M,setCreateName:_,createRepoIdentity:I,setCreateRepoIdentity:D,createRepoRemoteUrl:L,setCreateRepoRemoteUrl:$,newMeshDaemonId:U,setNewMeshDaemonId:J,newMeshWorkspace:K,setNewMeshWorkspace:R,createPickerWorkspaces:O,createOnboardingPlan:H,createPlanLoading:B,creating:q,createWarning:W,setCreateWarning:ce,loadMeshes:ye,handleCreate:G,handleDelete:Se,cancelCreate:ue}=Rx({confirmAction:s,daemons:i,primaryDaemonId:C,sendCommand:o,unwrapResult:p,normalizeMesh:b,features:g,loadDaemonMetadata:w}),ne=v.find(Ge=>Ge.id===y)||null,{meshGraphStatus:ae,graphLoading:ee,graphError:oe,setGraphError:Ce,loadGraph:Q}=oD({selectedMeshId:y,loadMeshStatus:d,extractStatus:h,normalizeNode:f}),[z,X]=c.useState(""),[pe,Pe]=c.useState(""),Oe=g.meshHostDaemonSection?z:C,{meshQueue:Le}=nD({status:ae}),ke=async()=>{!y||!Oe||await Q(Oe,y,!1)},{selectedNodeId:Y,setSelectedNodeId:ve,showAddNode:Z,setShowAddNode:ie,nodeWorkspace:F,setNodeWorkspace:se,nodeProviderPriority:me,setNodeProviderPriority:re,nodeDaemonId:we,setNodeDaemonId:V,nodeCustomPath:de,setNodeCustomPath:ge,nodePickerWorkspaces:Ie,nodePickerProviders:Ke,nodeOnboardingPlan:Ae,nodePlanLoading:Ne,coordinatorCliType:He,savingPolicy:Fe,coordinatorPromptDraft:it,setCoordinatorPromptDraft:ut,savingCoordinatorPrompt:dt,nodeSystemPromptDrafts:Tt,setNodeSystemPromptDrafts:bt,savingNodeSystemPromptId:te,savingNodeSlotsId:le,savingNodeCapabilitiesId:be,handleAddNode:Te,handleRemoveNode:De,handleUpdatePolicy:qe,handleUpdateNodeSlots:ot,handleUpdateNodeCapabilities:_e,handleSaveCoordinatorPrompt:st,handleSaveNodeSystemPrompt:jt,settingMeshHost:gt,handleSetMeshHost:Kt}=ZL({confirmAction:s,selectedMesh:ne,selectedMeshId:y,activeDaemonId:Oe,daemons:i,availableCliProviders:j,sendCommand:o,unwrapResult:p,loadLiveMesh:m,resolveCommandTarget:x,launchCoordinator:u,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:ye,reloadMeshStatus:ke,setError:E}),fe=c.useMemo(()=>i.find(Ge=>Ge.id===Oe)||S,[i,Oe,S]),Me=c.useMemo(()=>new Set(((ne==null?void 0:ne.nodes)||[]).map(Ge=>String(Ge.daemon_id||Ge.daemonId||""))),[ne]),Ee=c.useMemo(()=>i.filter(Ge=>Ge.id&&!Me.has(Ge.id)&&!vp(Ge)),[i,Me]),Ve=(ne==null?void 0:ne.nodes)||[],Qe=c.useMemo(()=>Ve.find(Ge=>mn(String(Ge.daemon_id||Ge.daemonId||""),z)),[Ve,z]),ht=g.meshHostDaemonSection?!!Qe:!0,tt=c.useMemo(()=>{if(!g.meshHostDaemonSection||!ne)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Ge=ne.meshHost,lt=ae!=null&&ae.meshId&&String(ae.meshId)===String(ne.id??"")?ae.meshHost:void 0,Re=lt!=null&&lt.hostDaemonId?lt:Ge??lt,We=sd(Re),rt=We.hostDaemonId,St=Ve.find(Xt=>Xt.role==="host"),zt=We.hostNodeId||String((St==null?void 0:St.id)||""),mt=zt?Ve.find(Xt=>String(Xt.id)===zt):void 0,Yt=String((mt==null?void 0:mt.daemon_id)||(mt==null?void 0:mt.daemonId)||""),Tn=rt||Yt;if(!Tn)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const vn=i.find(Xt=>rt&&mn(Xt.id,rt))||(Yt?i.find(Xt=>mn(Xt.id,Yt)):void 0);if(vn)return{pinned:!0,daemonId:vn.id,label:iD(vn),online:!0,hostNode:mt};const In=String((mt==null?void 0:mt.machineLabel)||"")||String((mt==null?void 0:mt.workspace)||"")||Tn;return{pinned:!0,daemonId:Tn,label:In,online:!1,hostNode:mt}},[ne,Ve,i,ae,g.meshHostDaemonSection]),Nt=tt.daemonId,xt=tt.online,Bt=tt.pinned?tt.hostNode:Qe,Jt=c.useMemo(()=>!g.meshHostDaemonSection||!tt.pinned?"":!xt&&pe&&i.some(Ge=>Ge.id===pe)?pe:Nt,[g.meshHostDaemonSection,tt.pinned,xt,pe,i,Nt]),on=UE({status:ae,daemonId:Oe||null,meshId:y,sendData:a});c.useEffect(()=>{const Ge=(ne==null?void 0:ne.coordinator)||{};ut({override:typeof Ge.systemPromptOverride=="string"?Ge.systemPromptOverride:"",append:typeof Ge.systemPromptAppend=="string"?Ge.systemPromptAppend:typeof Ge.systemPromptSuffix=="string"?Ge.systemPromptSuffix:""}),bt(Object.fromEntries(((ne==null?void 0:ne.nodes)||[]).map(lt=>[lt.id,typeof lt.systemPrompt=="string"?lt.systemPrompt:""])))},[ne]),c.useEffect(()=>{const Ge=g.addNodeDaemonPicker?Ks(Ke):Ks(j);Z&&me.length===0&&Ge.length>0&&re(Ge)},[Z,j,Ke,me.length,g.addNodeDaemonPicker]),c.useEffect(()=>{const Ge=new Set(((ne==null?void 0:ne.nodes)||[]).map(lt=>lt.id));Y&&!Ge.has(Y)&&ve(null)},[ne,Y]);const qt=c.useMemo(()=>{if(!(!(ae!=null&&ae.meshId)||String(ae.meshId)!==String((ne==null?void 0:ne.id)??"")))return sd(ae.meshHost).hostDaemonId||void 0},[ae,ne]),At=c.useMemo(()=>XE(i,Ve,Oe,C,qt),[i,Ve,Oe,C,qt]);c.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!i.length&&!tt.pinned){X("");return}const Ge=tt.pinned?Jt:At;Ge&&!mn(Ge,z)&&X(Ge)},[i,z,tt.pinned,Jt,At,g.meshHostDaemonSection]),c.useEffect(()=>{pe&&(xt||!i.some(Ge=>Ge.id===pe))&&Pe("")},[xt,pe,i]),c.useEffect(()=>{if(g.createDaemonPicker){if(!i.length){J("");return}(!U||!i.some(Ge=>Ge.id===U))&&J(i[0].id)}},[i,U,g.createDaemonPicker]);const an=c.useRef(null),Kn=((fn=O[0])==null?void 0:fn.path)||"";c.useEffect(()=>{g.createDaemonPicker&&(an.current!==U&&(an.current=U,R("")),U&&Kn&&R(Ge=>Ge||Kn))},[U,Kn,g.createDaemonPicker]),c.useEffect(()=>{Ce(null)},[y,Oe]),xx({meshId:y,daemonId:Oe||null,sendData:a});const Ct=c.useMemo(()=>i.map(Ge=>Ge.id).filter(Boolean).sort().join(","),[i]),cn=c.useRef(!1);return c.useEffect(()=>{ye(cn.current),Ct&&(cn.current=!0)},[Ct]),C?ne?n.jsxs(n.Fragment,{children:[r,n.jsx(YL,{selectedMesh:ne,error:A,onDismissError:()=>E(null),onBack:()=>{N(null)},onDelete:Se,displayedMeshStatus:on,graphLoading:ee,graphError:oe,onRefreshGraph:()=>{Q(Oe,y,!0)},savingPolicy:Fe,onUpdatePolicy:qe,coordinatorPromptDraft:it,onCoordinatorPromptDraftChange:ut,savingCoordinatorPrompt:dt,onSaveCoordinatorPrompt:st,daemons:i,coordinatorDaemonId:z,onCoordinatorDaemonIdChange:X,coordinatorCliType:He,isHostNodeAttached:ht,selectedHostNode:Bt,hostPinned:tt.pinned,hostLabel:tt.label,hostOnline:xt,hostRebindDaemonId:pe,onHostRebindDaemonIdChange:Ge=>Pe(Ge),settingMeshHost:gt,onSetMeshHost:Kt,activeDaemon:fe,activeDaemonId:Oe,meshQueue:Le,userName:l,availableCliProviders:j,savingNodeSlotsId:le,onUpdateNodeSlots:ot,savingNodeCapabilitiesId:be,onUpdateNodeCapabilities:_e,nodeSystemPromptDrafts:Tt,onNodeSystemPromptDraftChange:(Ge,lt)=>bt(Re=>({...Re,[Ge]:lt})),savingNodeSystemPromptId:te,onSaveNodeSystemPrompt:jt,selectedNodeId:Y,onSelectNode:ve,showAddNode:Z,onShowAddNode:()=>ie(!0),onCancelAddNode:()=>ie(!1),nodeWorkspace:F,onNodeWorkspaceChange:se,nodeProviderPriority:me,onNodeProviderPriorityChange:re,nodeDaemonId:we,onNodeDaemonIdChange:V,nodeCustomPath:de,onNodeCustomPathChange:ge,nodePickerWorkspaces:Ie,nodePickerProviders:Ke,nodeOnboardingPlan:Ae,nodePlanLoading:Ne,attachableDaemons:Ee,onAddNode:Te,onRemoveNode:De,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:o})]}):n.jsxs(n.Fragment,{children:[r,n.jsx(NL,{meshes:v,loading:k,error:A,onDismissError:()=>E(null),daemons:i,features:{createDaemonPicker:g.createDaemonPicker},showCreate:P,onToggleCreate:()=>T(!P),createName:M,onCreateNameChange:_,createRepoIdentity:I,onCreateRepoIdentityChange:D,createRepoRemoteUrl:L,onCreateRepoRemoteUrlChange:$,newMeshDaemonId:U,onNewMeshDaemonIdChange:J,newMeshWorkspace:K,onNewMeshWorkspaceChange:R,createPickerWorkspaces:O,createOnboardingPlan:H,createPlanLoading:B,creating:q,createWarning:W,onDismissCreateWarning:()=>ce(null),onSelectMesh:N,onCreate:G,onCancelCreate:ue,sendCommand:o})]}):n.jsx(Lo,{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 iD(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function cD({children:e}){const{sendCommand:t,sendData:s}=wt(),{ides:r}=yn(),o=c.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),a=c.useMemo(()=>({sendCommand:t,sendData:s,daemons:o,userName:void 0,loadMeshStatus:async(i,l,d)=>t(i,"mesh_status",(d==null?void 0:d.refresh)===!0?{meshId:l,refresh:!0}:{meshId:l}),launchCoordinator:async(i,l)=>{var p;const d={meshId:l.meshId};l.cliType&&(d.cliType=l.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:Li,unwrapResult:i=>i,normalizeMesh:(i,l)=>i,normalizeNode:(i,l,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:yx}),[t,s,o]);return n.jsx(vx.Provider,{value:a,children:e})}function lD(e){const{daemons:t,features:s,meshes:r,meshesLoading:o,selectedMeshId:a,onSelectMesh:i,createMode:l,onCreateModeChange:d,createName:u,onCreateNameChange:m,createDaemonId:h,onCreateDaemonIdChange:p,createWorkspace:b,onCreateWorkspaceChange:f,createPickerWorkspaces:x,createPlan:g,createPlanLoading:w,creating:S,createWarning:C,onCreate:j,createRepoRemoteUrl:v,onCreateRepoRemoteUrlChange:y,createRepoIdentity:N,onCreateRepoIdentityChange:k,createManualOpen:A,onCreateManualOpenChange:E,nodes:P,attachableDaemons:T,attachDaemonId:M,onAttachDaemonIdChange:_,attachWorkspace:I,onAttachWorkspaceChange:D,attachPickerWorkspaces:L,attachPlan:$,attachPlanLoading:U,attaching:J,onAttach:K,renderInstallOnboarding:R,nodeLabel:O,daemonLabel:H}=e,{t:B}=he("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:B("setupWizard.machines.title")}),n.jsx("p",{className:"mt-1 text-2xs leading-relaxed text-text-muted",children:B("setupWizard.machines.noMachinesDescription")})]}),R?R():n.jsx("p",{className:"text-2xs text-text-muted",children:B("setupWizard.machines.noMachinesFallback")})]});const q=J||U||($==null?void 0:$.success)===!1||!I.trim()||s.addNodeDaemonPicker&&!M;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:B("setupWizard.machines.title")}),n.jsx("p",{className:"mt-1 text-2xs leading-relaxed text-text-muted",children:B("setupWizard.machines.description")})]}),n.jsxs("div",{className:"flex flex-col gap-2",children:[r.map(W=>{const ce=!l&&a===W.id;return n.jsx("button",{type:"button",onClick:()=>{d(!1),i(W.id)},className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${ce?"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:W.name}),n.jsxs("span",{className:"block truncate text-2xs text-text-muted",children:[W.repoIdentity||W.repoRemoteUrl||""," · ",B("setupWizard.machines.nodeCount",{count:(W.nodes||[]).length})]})]})},W.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 ${l?"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:["+ ",B("setupWizard.machines.createNew")]})}),o&&r.length===0&&n.jsx("p",{className:"text-2xs text-text-muted",children:B("setupWizard.machines.loadingMeshes")})]}),l&&n.jsx(kx,{variant:"wizard",showDaemonPicker:s.createDaemonPicker,daemons:t,daemonLabel:H,name:u,onNameChange:m,daemonId:h,onDaemonIdChange:p,workspace:b,onWorkspaceChange:f,workspaces:x,plan:g,planLoading:w,repoRemoteUrl:v,onRepoRemoteUrlChange:y,repoIdentity:N,onRepoIdentityChange:k,manualOpen:A,onManualOpenChange:E,creating:S,warning:C,onCreate:j}),!l&&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:[P.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1.5",children:P.map(W=>n.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-3xs text-text-secondary",children:O(W)},W.id))}),n.jsx("span",{className:"text-2xs font-medium text-text-secondary",children:B("setupWizard.machines.attachTitle")}),s.addNodeDaemonPicker&&(T.length>0?n.jsx("div",{className:"flex flex-wrap gap-1.5",children:T.map(W=>{const ce=M===W.id;return n.jsx("button",{type:"button",onClick:()=>_(W.id),className:`rounded-full border px-2.5 py-1 text-2xs transition-colors ${ce?"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:H(W)},W.id)})}):n.jsx("p",{className:"text-2xs text-text-muted",children:B("setupWizard.machines.allMachinesAttached")})),(!s.addNodeDaemonPicker||M)&&n.jsxs(n.Fragment,{children:[n.jsx(nd,{workspaces:L,value:I,onChange:D}),n.jsx(Sx,{plan:$,loading:U}),n.jsx("div",{className:"flex justify-end",children:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:K,disabled:q,children:B(J?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function dD(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function uD(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function mD({daemons:e,features:t,sendCommand:s,unwrapResult:r,normalizeMesh:o,loadDaemonMetadata:a,initialMeshId:i,onClose:l,renderInstallOnboarding:d}){var F,se;const{t:u}=he("common"),m=((F=e[0])==null?void 0:F.id)||"",{meshes:h,loading:p,error:b,setError:f,loadMeshes:x,selectedMeshId:g,setSelectedMeshId:w}=Rx({daemons:e,primaryDaemonId:m,sendCommand:s,unwrapResult:r,normalizeMesh:o,features:{createDaemonPicker:t.createDaemonPicker,addNodeDaemonPicker:t.addNodeDaemonPicker},loadDaemonMetadata:a});c.useEffect(()=>{x()},[x]);const S=c.useRef(h);S.current=h;const C=c.useMemo(()=>h.map(me=>me.id).sort().join(","),[h]),j=c.useRef(s);j.current=s;const v=c.useRef(r);v.current=r,c.useEffect(()=>{g||h.length===0||(i&&h.some(me=>me.id===i)?w(i):h.length===1&&w(h[0].id))},[h,g,i,w]);const y=c.useMemo(()=>h.find(me=>me.id===g)??null,[h,g]),N=c.useMemo(()=>(y==null?void 0:y.nodes)||[],[y]),k=c.useCallback(me=>zi(me,e),[e]),[A,E]=c.useState(!1),[P,T]=c.useState(""),[M,_]=c.useState(""),[I,D]=c.useState(""),[L,$]=c.useState(null),[U,J]=c.useState(!1),[K,R]=c.useState(!1),[O,H]=c.useState(null),[B,q]=c.useState(""),[W,ce]=c.useState(""),[ye,G]=c.useState(!1),Se=t.createDaemonPicker&&M||m,ue=c.useMemo(()=>e.find(me=>me.id===Se),[e,Se]),ne=(ue==null?void 0:ue.workspaces)||[];c.useEffect(()=>{if(!A||!Se||!I.trim()){$(null),J(!1);return}let me=!1;const re=setTimeout(()=>{me||(J(!0),j.current(Se,"plan_mesh_onboarding",{workspace:I.trim(),operation:"auto",meshInventory:S.current}).then(we=>{if(me)return;const V=v.current(we);$(V),V!=null&&V.success&&(T(de=>{var ge,Ie;return de||`${String(((ge=V.discovery)==null?void 0:ge.repoIdentity)||((Ie=V.discovery)==null?void 0:Ie.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),ce(de=>{var ge;return de||((ge=V.discovery)==null?void 0:ge.repoIdentity)||""}),q(de=>{var ge,Ie,Ke,Ae,Ne,He;return de||((Ke=(Ie=(ge=V.discovery)==null?void 0:ge.origin)==null?void 0:Ie.urls)==null?void 0:Ke[0])||((He=(Ne=(Ae=V.discovery)==null?void 0:Ae.upstream)==null?void 0:Ne.urls)==null?void 0:He[0])||""}))}).catch(we=>{me||$({success:!1,error:(we==null?void 0:we.message)||"Git discovery failed"})}).finally(()=>{me||J(!1)}))},300);return()=>{me=!0,clearTimeout(re)}},[A,Se,I,C]);const ae=c.useCallback(async()=>{const me=Se,re=I.trim(),we=B.trim(),V=W.trim();if(!(!me||!P.trim()||K)&&!(!re&&!we&&!V)){R(!0),H(null),f(null);try{const de=await Mx({targetDaemonId:me,name:P,repoRemoteUrl:we,repoIdentity:V,workspace:re,attachWorkspace:!!re,machineId:ue==null?void 0:ue.machineId,providerPriority:Ks(Wn((ue==null?void 0:ue.availableProviders)||[])),meshInventory:h,sendCommand:s,unwrapResult:r});if(de.warning&&H(de.warning),!de.meshCreated){f(de.error||u("setupWizard.machines.createFailed"));return}await x(!0),de.meshId&&w(de.meshId),E(!1)}finally{R(!1)}}},[Se,P,I,B,W,K,ue,h,s,r,x,w,f,u]),[ee,oe]=c.useState(""),[Ce,Q]=c.useState(""),[z,X]=c.useState(null),[pe,Pe]=c.useState(!1),[Oe,Le]=c.useState(!1),ke=c.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const me=new Set(N.map(re=>String(re.daemon_id||re.daemonId||"")));return e.filter(re=>re.id&&!me.has(re.id)&&!vp(re))},[t.addNodeDaemonPicker,N,e]),Y=c.useMemo(()=>e.find(me=>me.id===ee),[e,ee]),ve=t.addNodeDaemonPicker?(Y==null?void 0:Y.workspaces)||[]:((se=e.find(me=>me.id===m))==null?void 0:se.workspaces)||[];c.useEffect(()=>{if(A||!g||!Ce.trim()){X(null);return}const me=t.addNodeDaemonPicker?ee:k(y);if(!me)return;let re=!1;return Pe(!0),s(me,"plan_mesh_onboarding",{workspace:Ce.trim(),meshId:g,inlineMesh:y,operation:"add_existing"}).then(we=>{re||X(r(we))}).catch(we=>{re||X({success:!1,error:(we==null?void 0:we.message)||"Git discovery failed"})}).finally(()=>{re||Pe(!1)}),()=>{re=!0}},[A,g,y,Ce,ee,t.addNodeDaemonPicker,k,s,r]);const Z=c.useCallback(async()=>{var we,V,de,ge;const me=k(y);if(!g||Oe)return;if(!me){f(u("mesh.host.noCommandTarget"));return}const re=Ce.trim();if(re){Le(!0),f(null);try{const Ie=t.addNodeDaemonPicker?ee:me,Ke=await s(Ie,"plan_mesh_onboarding",{workspace:re,meshId:g,inlineMesh:y,operation:"add_existing"}),Ae=r(Ke);if(X(Ae),(Ae==null?void 0:Ae.success)===!1)throw new Error(`${Ae.code||"onboarding_blocked"}: ${Ae.error}${Ae.action?` ${Ae.action}`:""}`);const Ne={meshId:g,workspace:((we=Ae==null?void 0:Ae.discovery)==null?void 0:we.repoRoot)||re,repoRoot:(V=Ae==null?void 0:Ae.discovery)==null?void 0:V.repoRoot,isLocalWorktree:((de=Ae==null?void 0:Ae.discovery)==null?void 0:de.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&ee&&(Ne.daemonId=ee,Ne.machineId=Y==null?void 0:Y.machineId),Ne.providerPriority=Ks(Wn(((ge=t.addNodeDaemonPicker?Y:e[0])==null?void 0:ge.availableProviders)||[]));const He=await s(me,"add_mesh_node",Ne),Fe=r(He);if((Fe==null?void 0:Fe.success)===!1)throw new Error(Fe.error||"Add node failed");Q(""),X(null),await x(!0)}catch(Ie){f((Ie==null?void 0:Ie.message)||"Add node failed")}finally{Le(!1)}}},[y,g,Ce,ee,Y,Oe,t.addNodeDaemonPicker,k,e,s,r,x,f,u]),ie=!A&&!!y&&N.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")})]}),b&&n.jsx("p",{className:"text-2xs text-red-400",children:b}),n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary p-4",children:n.jsx(lD,{daemons:e,features:t,meshes:h,meshesLoading:p,selectedMeshId:g,onSelectMesh:me=>{w(me),Q(""),oe("")},createMode:A,onCreateModeChange:E,createName:P,onCreateNameChange:T,createDaemonId:M,onCreateDaemonIdChange:_,createWorkspace:I,onCreateWorkspaceChange:D,createPickerWorkspaces:ne,createPlan:L,createPlanLoading:U,creating:K,createWarning:O,onCreate:ae,createRepoRemoteUrl:B,onCreateRepoRemoteUrlChange:q,createRepoIdentity:W,onCreateRepoIdentityChange:ce,createManualOpen:ye,onCreateManualOpenChange:G,nodes:N,attachableDaemons:ke,attachDaemonId:ee,onAttachDaemonIdChange:me=>{oe(me),Q("")},attachWorkspace:Ce,onAttachWorkspaceChange:Q,attachPickerWorkspaces:ve,attachPlan:z,attachPlanLoading:pe,attaching:Oe,onAttach:Z,renderInstallOnboarding:d,nodeLabel:uD,daemonLabel:dD})}),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:ie?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:l,children:u(ie?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function Gi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function hD(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=Gi();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 En(e,t){return await fetch(hD(e),{credentials:"same-origin",...t})}function Ex(){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 pD{constructor(){ze(this,"adapters",new Map);ze(this,"states",new Map);ze(this,"runtimeListeners",new Map);ze(this,"screenshotCallbacks",new Map);ze(this,"stateChangeCallbacks",new Set);ze(this,"ptyInputSender",null);ze(this,"dataSender",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}registerDataSender(t){this.dataSender=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))}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,r){const o=this.runtimeListeners.get(t)||new Set;o.add(s),this.runtimeListeners.set(t,o);const a=this.dataSender,i=a&&t?Fn.subscribe({sendData:(l,d)=>a(l,d)},r||this.resolveDaemonId("standalone")||"standalone",{type:"subscribe",topic:"session.runtime_output",key:`runtime:${t}`,params:{targetSessionId:t}},()=>{}):void 0;return()=>{i==null||i();const l=this.runtimeListeners.get(t);l&&(l.delete(s),l.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 En(`${o.pathname}${o.search}`);if(!a.ok){let l=`Runtime snapshot unavailable (${a.status})`;try{const d=await a.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}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 Ln=new pD;function fD(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 bD="/ws/seqscribe",gD="standalone_dashboard",cp=3e3,xD=3e4,yD=3e4,vD=1e3,wD=6e4;function SD(e,t){const r=`${e.protocol==="https:"?"wss":"ws"}://${e.host}${bD}`;return t?`${r}?token=${encodeURIComponent(t)}`:r}const kD=["request_transcript_base"];function jD(e){if(!e||typeof e!="object")return!1;const t=e;return t.type==="subscribe"||t.type==="unsubscribe"?!0:t.type==="command"&&typeof t.commandType=="string"&&kD.includes(t.commandType)}const ad=new Set;function ND(e){if(e.length!==0)for(const t of[...ad])try{t(e)}catch{}}function CD(e){return ad.add(e),()=>{ad.delete(e)}}class _D{constructor(t){ze(this,"socket",null);ze(this,"host",null);ze(this,"openedAt",null);ze(this,"reconnectTimer",null);ze(this,"reconnectDelay",cp);ze(this,"unsubscribeInterest",null);ze(this,"unsubscribeTopicsAvailable",null);ze(this,"sessionDaemons",new Map);ze(this,"activeSessions",[]);ze(this,"delivered",new Set);ze(this,"subRetryTimer",null);ze(this,"subRetryDelay");ze(this,"subRetryInitialMs");ze(this,"subRetryMaxMs");ze(this,"started",!1);ze(this,"stopped",!1);var s,r;this.deps=t,this.subRetryInitialMs=((s=t.subRetrySchedule)==null?void 0:s.initialMs)??vD,this.subRetryMaxMs=((r=t.subRetrySchedule)==null?void 0:r.maxMs)??wD,this.subRetryDelay=this.subRetryInitialMs}start(){var t,s;this.started||this.stopped||(this.started=!0,this.unsubscribeInterest=this.deps.subscribeInterest(()=>this.syncInterest()),this.unsubscribeTopicsAvailable=((s=(t=this.deps).subscribeTopicsAvailable)==null?void 0:s.call(t,r=>this.handleTopicsAvailable(r)))??null,this.syncInterest(),this.connect())}stop(){var s,r;if(this.stopped)return;this.stopped=!0,(s=this.unsubscribeInterest)==null||s.call(this),this.unsubscribeInterest=null,(r=this.unsubscribeTopicsAvailable)==null||r.call(this),this.unsubscribeTopicsAvailable=null,this.reconnectTimer!==null&&this.deps.clearTimer(this.reconnectTimer),this.reconnectTimer=null;const t=this.socket;this.socket=null,this.stopHost();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();const s=this.deps.startHost(t,a=>this.deliver(a),a=>this.requestBase(a));if(!s){(o=(r=this.deps).log)==null||o.call(r,"[Transcript] standalone lane: transcript worker unavailable — live chat cannot be shown"),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>=yD&&(this.reconnectDelay=cp),this.stopHost(),this.scheduleReconnect()}scheduleReconnect(){if(this.stopped||this.reconnectTimer!==null)return;const t=this.reconnectDelay;this.reconnectDelay=Math.min(Math.round(this.reconnectDelay*1.5),xD),this.reconnectTimer=this.deps.setTimer(()=>{this.reconnectTimer=null,this.connect()},t,"reconnect")}stopHost(){const t=this.host;t&&(this.host=null,this.delivered.clear(),this.subRetryTimer!==null&&this.deps.clearTimer(this.subRetryTimer),this.subRetryTimer=null,t.stop())}syncInterest(){var r;const t=new Map;for(const[o,a]of this.deps.collectInterest())for(const i of a){const l=t.get(i);l?l.includes(o)||l.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=this.subRetryInitialMs),!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")}handleTopicsAvailable(t){const s=this.host;if(!s||this.stopped||!this.deps.selectResubscribe)return;const r=this.deps.selectResubscribe(this.activeSessions,this.delivered,t);if(r.length===0)return;const o=new Set(r);s.activateSessions(this.activeSessions.filter(a=>!o.has(a))),s.activateSessions(this.activeSessions)}rearmUndelivered(){const t=this.host;if(!t||this.stopped)return;const s=this.activeSessions.filter(r=>!this.delivered.has(r));if(s.length!==0){for(const r of s)this.requestBase(r);t.activateSessions(this.activeSessions.filter(r=>this.delivered.has(r))),t.activateSessions(this.activeSessions),this.subRetryDelay=Math.min(this.subRetryDelay*2,this.subRetryMaxMs),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.applyView(r,t.sessionId,t.view)}}requestBase(t){for(const s of this.sessionDaemons.get(t)??[])if(this.deps.requestBase(s,t))return}}function tl(e){return{kind:"transcript-bridge-control",event:e}}function AD(e){return typeof e=="object"&&e!==null&&e.kind==="transcript-bridge-frame"&&Array.isArray(e.upserts)&&Array.isArray(e.deletes)}function TD(e){return typeof e=="object"&&e!==null&&e.kind==="transcript-bridge-base-request"&&typeof e.sessionId=="string"}function ID(e,t){return{kind:"transcript-session-activation",sessionIds:[...e],...t?{ownerDaemonId:t}:{}}}var MD=Object.create,Lx=Object.defineProperty,RD=Object.getOwnPropertyDescriptor,Dx=Object.getOwnPropertyNames,PD=Object.getPrototypeOf,ED=Object.prototype.hasOwnProperty,LD=(e,t)=>function(){return t||(0,e[Dx(e)[0]])((t={exports:{}}).exports,t),t.exports},DD=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Dx(t))!ED.call(e,o)&&o!==s&&Lx(e,o,{get:()=>t[o],enumerable:!(r=RD(t,o))||r.enumerable});return e},OD=(e,t,s)=>(s=e!=null?MD(PD(e)):{},DD(Lx(s,"default",{value:e,enumerable:!0}),e)),$D=LD({"../../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,l,d)=>`${i}${d===0?"":","}${s(l===void 0||typeof l=="symbol"?null:l)}`,"")}]`:`{${Object.keys(r).sort().reduce((a,i)=>{if(r[i]===void 0||typeof r[i]=="symbol")return a;const l=a.length===0?"":",";return`${a}${l}${s(i)}:${s(r[i])}`},"")}}`}}});function rn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var Ox=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress"];rn(Ox);var FD=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];rn(FD);var HD=["p2p_offer","p2p_ice"];rn(HD);var BD=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];rn(BD);var WD=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","daemon_mesh_command","p2p_offer","p2p_ice"];rn(WD);var UD=["auth_ok","auth_error","machine_evicted","force_disconnect","token_revoked","version_mismatch","force_update_required","command","agent_command","resolve_action","daemon_mesh_result","p2p_ready","p2p_offer","p2p_answer","p2p_ice","mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];rn(UD);var KD=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],qD=[...Ox,...KD];rn(qD);var zD=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];rn(zD);var VD=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];rn(VD);var GD=["p2p_ready","p2p_answer","p2p_ice"];rn(GD);var YD=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];rn(YD);var QD=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];rn(QD);var $x=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];rn($x);var Fx=["ping","pong","p2p_evicted","status_event","topic_update","topic_update_chunk","session_output","session_output_chunk","session_io_error","command_result","command_result_chunk","response","transcript_topics_available"];rn(Fx);[...new Set([...$x,...Fx])];var Hx=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"];new Set(Hx);var JD=["pending","assigned","completed","failed","cancelled"],XD=["completed","failed","cancelled"],ZD=["code_change","validation","live_debug_readonly","launch_app","convergence"],e5=["low","normal","high"],t5=["when_idle","interrupt"],Bx=["completed","blocked","failed"],n5=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function Er(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Er(JD);Er(XD);Er(ZD);Er(e5);Er(t5);Er(Bx);var s5=["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"],r5=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(r5);var o5=["projects","project_status","project_send","project_read","project_add","discover_repos","memory","skill_view","skill_manage","project_note"];new Set(o5);var a5=["mesh_queue","mesh_direct","plain"],i5=["delivered","queued"],c5=["local","p2p"],l5=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],d5=["default","native_source"],u5=["restart","live_holder"],m5=["approval","choice"],h5=["approved","rejected","answered"],p5=["modal_button","auto_approve","prompt_answer"],f5=["genuine","weak"],b5=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],g5=["completed","aborted"],x5=["alive","unknown","read_failed","dead"],lp=["auth_failed","billing_failed"],y5=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],v5=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],w5=["completed","failed"],S5=["operator_update","refine_terminal","validation_terminal"],k5=["delivered","queued","duplicate"],j5=[...Hx,"unknown"],N5=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],C5=["completed","failed","cancelled"],_5=["genuine","weak","tool_report","operator"],A5=["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"],or={t:"id"},ar={t:"id",optional:!0},ds={t:"bool"},pa={t:"bool",optional:!0},dp={t:"ms"},T5={t:"ms",optional:!0},fa={t:"int",optional:!0},Pt=e=>({t:"enum",values:e}),ir=e=>({t:"enum",values:e,optional:!0}),I5={dispatch_accepted:{scope:Pt(a5),messageId:or,meshId:ar,nodeId:ar,providerType:ar,attemptNo:fa,dispatchNonce:fa,consumeProfile:ir(d5),maxTaskRetries:fa,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:or,outcome:Pt(i5),via:Pt(c5)},delivery_refused:{messageId:or,reason:Pt(s5)},dispatch_failed:{workerAbsent:ds,reason:Pt(l5),refusalCode:ar},duplicate_dispatch_refusal:{holderSessionId:or,holderAttemptId:ar},session_rebound:{toSessionId:or,reason:Pt(u5)},turn_started:{retro:ds},suspension:{modal:Pt(m5),modalKey:ar},suspension_resolved:{resolution:Pt(h5),via:Pt(p5)},turn_end:{strength:Pt(f5),afterFinalizationTimeout:pa,hollow:pa,summary:{t:"summary_ref",optional:!0},blockReason:ir(b5),releasedByHardCap:pa,nativeOutcome:ir(g5),live:{t:"live",optional:!0},reportExpected:pa,providerFailure:ir(lp)},transcript_final:{selfAttributing:ds,nativeRead:ds,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:T5},transcript_activity:{newestActivityAt:dp},no_progress:{stalledMs:dp,observedStatus:Pt(j5),finalAssistantPresent:ds},liveness:{result:Pt(x5)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:ir(lp)},session_error:{reason:Pt(y5)},worker_report:{outcome:Pt(Bx),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:ds,branchState:ir(n5),touchedFileCount:fa},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:ds,commitsSinceDispatch:{t:"int"},attributable:ds},cancel:{reason:Pt(v5)},operator_status:{status:Pt(w5),reason:Pt(S5)},coordinator_ack:{notify:Pt(Wx),outcome:Pt(k5)},hold_expired:{holdId:or,reason:Pt(N5)}},M5=Object.keys(I5);function Do(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Do(M5);Do(A5);Do(Wx);Do(C5);Do(_5);function ns(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var R5=["applied","recorded","rejected"];ns(R5);var P5=["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(P5);var E5=["completed","failed"];ns(E5);var L5=["operator_update","refine_terminal","validation_terminal"];ns(L5);var D5=["own","fleet"];ns(D5);var O5=["active","paused","completed","abandoned"];ns(O5);var $5=["provider_quirk","pattern_to_avoid","recovery_lesson"];ns($5);var F5=["coordinator","unknown"];ns(F5);var H5=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];ns(H5);var B5=["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_batch","queue_cancel","queue_requeue","direct_dispatch_record","active_work_query","recovery_context_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];ns(B5);var W5=OD($D());W5.default;new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;var Ux="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Uint8Array.from(Ux,e=>e.charCodeAt(0));var U5=new Uint8Array(256);for(let e=0;e<64;e++)U5[Ux.charCodeAt(e)]=e;new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;new globalThis.TextDecoder;/*! Bundled license information:
117
-
118
- @noble/hashes/esm/utils.js:
119
- (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
120
- */const K5=/[^a-z0-9_-]+/g;function q5(e,t){const s=e.toLowerCase().replace(K5,"_").replace(/^_+|_+$/g,"");return s.length>0?s.slice(0,64):t}function z5(e){return q5(e,"unknown_session")}function V5(e){return`session.${z5(e)}.chat`}function up(e,t){return e.ord!==t.ord?e.ord<t.ord?-1:1:e.messageId<t.messageId?-1:e.messageId>t.messageId?1:0}function mp(e){const t=new Map;return e.forEach((s,r)=>t.set(s.messageId,r)),t}function nl(e){const t=e.ordered.length;return{...e.meta,coverage:{...e.meta.coverage,totalMessageCount:t,returnedMessageCount:t},messages:e.ordered}}class G5{constructor(){ze(this,"sessions",new Map)}apply(t){if(t.reset){if(!t.meta)return null;const o=[...t.upserts].sort(up),a={meta:t.meta,byId:new Map(o.map(i=>[i.messageId,i])),ordered:o,indexOf:mp(o)};return this.sessions.set(t.sessionId,a),{sessionId:t.sessionId,view:nl(a),reset:!0}}const s=this.sessions.get(t.sessionId);if(!s)return null;if(s.meta=t.meta??{...s.meta,epoch:t.epoch,frame:t.frame},t.deletes.length===0&&t.upserts.every(o=>{const a=s.byId.get(o.messageId);return a!==void 0&&a.ord===o.ord})){if(t.upserts.length>0){const o=s.ordered.slice();for(const a of t.upserts)s.byId.set(a.messageId,a),o[s.indexOf.get(a.messageId)]=a;s.ordered=o}}else{for(const o of t.deletes)s.byId.delete(o);for(const o of t.upserts)s.byId.set(o.messageId,o);s.ordered=Array.from(s.byId.values()).sort(up),s.indexOf=mp(s.ordered)}return{sessionId:t.sessionId,view:nl(s),reset:!1}}view(t){const s=this.sessions.get(t);return s?nl(s):null}retain(t){const s=new Set(t);for(const r of[...this.sessions.keys()])s.has(r)||this.sessions.delete(r)}clear(){this.sessions.clear()}}const Y5="transcript_topics_available",Q5=256;function J5(e){if(!e||typeof e!="object")return null;const t=e;if(t.type!==Y5||!Array.isArray(t.topics)||t.topics.length>Q5)return null;const s=[];for(const r of t.topics){if(typeof r!="string")return null;r.length>0&&s.push(r)}return s}function X5(e,t,s){if(s.length===0||e.length===0)return[];const r=new Set(s);return e.filter(o=>!(t!=null&&t.has(o))&&r.has(V5(o)))}const Z5=4096;function eO(e){return typeof e.isOpen=="function"?e.isOpen():e.readyState===1||e.readyState==="open"}function tO(e,t,s={}){const r=s.preOpenQueueCap??Z5,o=[];let a=!1;const i=()=>{for(const d of o.splice(0))e.send(d)},l=()=>{var d;o.length=0,a=!0,t.onmessage=null,(d=s.onOverflow)==null||d.call(s,"pre_open_queue_full"),t.postMessage(tl("queue_overflow"))};return t.onmessage=d=>{if(a)return;const u=d.data;typeof u=="string"&&(eO(e)?(o.length>0&&i(),e.send(u)):o.length<r?o.push(u):l())},e.addEventListener("message",d=>{if(a)return;const u=d.data;typeof u=="string"&&t.postMessage(u)}),e.addEventListener("open",()=>{a||(i(),t.postMessage(tl("transport_open")))}),e.addEventListener("close",()=>{a||(a=!0,o.length=0,t.postMessage(tl("transport_closed")))}),{pendingCount(){return o.length},close(){a||(a=!0,o.length=0,t.onmessage=null)}}}function nO(e,t){var u,m,h,p;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]),(m=(u=r.port1).start)==null||m.call(u),(p=(h=o.port1).start)==null||p.call(h);const i=new G5;o.port1.onmessage=b=>{var f,x;if(AD(b.data)){const g=i.apply(b.data);g&&((f=t.onView)==null||f.call(t,g));return}TD(b.data)&&((x=t.onBaseRequest)==null||x.call(t,b.data.sessionId))};let l=tO(e,r.port1,{...t.preOpenQueueCap!==void 0?{preOpenQueueCap:t.preOpenQueueCap}:{},onOverflow:()=>{var b;return(b=t.onOverflow)==null?void 0:b.call(t)}}),d=!1;return{pendingCount:()=>(l==null?void 0:l.pendingCount())??0,running:()=>!d,activateSessions(b,f){d||(i.retain(b),o.port1.postMessage(ID(b,f)))},view:b=>i.view(b),stop(){var b;if(!d){d=!0,l==null||l.close(),l=null,o.port1.onmessage=null,i.clear();for(const f of[r.port1,o.port1])try{(b=f.close)==null||b.call(f)}catch{}a.terminate()}}}}new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;const Kx="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Uint8Array.from(Kx,e=>e.charCodeAt(0));const sO=new Uint8Array(256);for(let e=0;e<64;e++)sO[Kx.charCodeAt(e)]=e;new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;new globalThis.TextDecoder;function rO(){if(typeof window>"u"||typeof Worker>"u"||typeof WebSocket>"u")return()=>{};const e=SD(window.location,Gi()),t=new _D({createSocket:()=>new WebSocket(e),startHost:(s,r,o)=>nO(s,{writerId:gD,sessionKey:"transcript",onView:r,onBaseRequest:o,createWorker:()=>new Worker(new URL("/assets/transcript-worker-entry-DW88VYRp.js",import.meta.url),{type:"module"}),onOverflow:()=>console.warn("[Transcript] standalone lane pre-open queue overflow — channel reset")}),collectInterest:__,subscribeInterest:A_,applyView:(s,r,o)=>j_(s,r,o),requestBase:N_,subscribeTopicsAvailable:CD,selectResubscribe:X5,setTimer:(s,r)=>setTimeout(s,r),clearTimer:s=>clearTimeout(s),now:()=>Date.now(),log:s=>console.warn(s)});return t.start(),()=>t.stop()}function oO(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,s=Gi();return s?`${t}?token=${encodeURIComponent(s)}`:t}const ba=oO(),hp=3e3,aO=3e4;let kn=null,iO=0;const ui=new Map;let Is=null,po=null,pp=null;const cO="standalone_hello";function lO(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Zr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function dO(e){return e==="connected"?"connected":e}async function fo(e,t,s){const r=fg(e,s||{}),o=kn;if(o&&o.readyState===WebSocket.OPEN){const a=`req_${++iO}_${Date.now()}`;return new Promise((i,l)=>{const d=setTimeout(()=>{ui.delete(a),l(new Error(`WS command timeout: ${t}`))},3e4);ui.set(a,{resolve:u=>{clearTimeout(d),i(u)},reject:u=>{clearTimeout(d),l(u)}}),o.send(JSON.stringify({type:"command",requestId:a,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function mi(e,t){const s=kn;if(!s||s.readyState!==WebSocket.OPEN||!jD(t))return!1;try{return s.send(JSON.stringify(t)),!0}catch{return!1}}function qx(e,t,s){const r=kn;if(!r||r.readyState!==WebSocket.OPEN)return!1;const o=fg(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}}Ln.registerPtyInputSender(qx);Ln.registerDataSender((e,t)=>mi(e,t));class uO{constructor(t){ze(this,"daemonId");ze(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(kn==null?void 0:kn.readyState)===WebSocket.OPEN}get connectionState(){return(kn==null?void 0:kn.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,s){return fo(this.daemonId,t,s)}async sendInput(t,s){return fo(this.daemonId,"cdp_remote_action",{action:t,params:s,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Is&&(clearInterval(Is),Is=null);const s=async()=>{if(this.hasCommandChannel)try{const r=await fo(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());Ln.emitScreenshot(this.daemonId,o)}}catch{}};s(),Is=setInterval(s,2e3)}stopScreenshots(t){Is&&(clearInterval(Is),Is=null)}}let xn=null;function mO(e){return(!xn||xn.daemonId!==e)&&(xn=new uO(e)),xn}function hO({children:e}){const t=c.useRef(gr()),s=gr();t.current=s;const{setUserName:r}=dw(),o=c.useRef(r);o.current=r;const a=c.useRef(null),i=c.useRef(null),[,l]=c.useState("disconnected"),d=c.useCallback((x,g)=>{l(x),po==null||po(x,g)},[]),u=c.useRef(null),m=c.useRef(),h=c.useRef(hp),p=c.useRef(!0),b=c.useRef(!1),f=c.useRef("initial_connect");return c.useEffect(()=>{p.current=!0,b.current=!1;function x(){var C,j;if(!p.current||((C=u.current)==null?void 0:C.readyState)===WebSocket.OPEN||((j=u.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${ba}...`),Zr("connect_attempt",{url:ba,reason:f.current,delayMs:h.current});let S;try{S=new WebSocket(ba)}catch(v){console.error("[Standalone WS] Failed to create WebSocket:",v),g();return}u.current=S,S.onopen=()=>{if(!p.current){S.close();return}d("connected"),h.current=hp,Zr("open",{url:ba,reason:f.current}),Fn.resubscribeAll({sendData:mi}),console.log("[Standalone WS] Connected")},kn=S,S.onmessage=v=>{var y,N;try{const k=JSON.parse(v.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const E=ui.get(k.requestId);E&&(ui.delete(k.requestId),k.type==="error"?E.reject(new Error(((y=k.data)==null?void 0:y.message)||"Command failed")):E.resolve(k.data));return}if(k.type==="session_output"){const E=k.sessionId||k.cliId||k.cliType;E&&Ln.emitSessionOutput(E,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Ln.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated,typeof k.cols=="number"?k.cols:void 0,typeof k.rows=="number"?k.rows:void 0);return}const A=J5(k);if(A){ND(A);return}if(fD(k,pp,et,C_))return;if(k.type==="topic_update"){const E=k.update;E&&Fn.publish(E);return}if(k.type===cO&&typeof k.daemonId=="string"&&k.daemonId){const E=k.daemonId;pp=E,Rl(E,typeof k.wireVersion=="number"?k.wireVersion:null);const P=mO(E);Ln.register(E,P),Ln.setState(E,"connected"),d("connected",E),i.current!==E&&((N=a.current)==null||N.call(a),i.current=E,a.current=Fn.subscribe({sendData:mi},E,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${E}`,params:{includeSessions:!0}},T=>{const M=t.current.getIdes(),_=M.find(D=>D.id===E),I=hb(T.status,{daemonId:E,existingDaemon:_,existingEntries:M,timestamp:T.timestamp});lO("metadata",{daemonId:E,seq:T.seq,sessions:(T.status.sessions||[]).map(D=>({id:D.id,providerType:D.providerType,status:D.status,unread:D.unread,inboxBucket:D.inboxBucket}))}),I.length>0&&t.current.injectEntries(I,{authoritativeDaemonIds:[E]}),t.current.markLoaded(),T.userName&&o.current&&o.current(T.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},S.onclose=v=>{p.current&&(xn==null||xn.stopScreenshots(),xn&&Ln.setState(xn.daemonId,"disconnected"),d("disconnected"),u.current=null,f.current=`close:${v.code}${v.wasClean?":clean":":unclean"}`,Zr("close",{code:v.code,reason:v.reason||"",wasClean:v.wasClean}),g())},S.onerror=v=>{b.current||!p.current||(f.current="error",Zr("error",{message:v instanceof Event?"event":String(v),readyState:S.readyState}),console.warn("[Standalone WS] Error, will reconnect:",v))}}function g(){if(!p.current)return;clearTimeout(m.current);const S=h.current;console.log(`[Standalone WS] Reconnecting in ${S}ms...`),Zr("schedule_reconnect",{reason:f.current,delayMs:S}),m.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,aO),x()},S)}x();const w=rO();return()=>{var S;w(),p.current=!1,b.current=!0,(S=a.current)==null||S.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,kn=null),xn&&(xn.stopScreenshots(),Ln.unregister(xn.daemonId))}},[]),n.jsx(n.Fragment,{children:e})}function pO({children:e}){const[t,s]=c.useState("disconnected"),[r,o]=c.useState(null);c.useEffect(()=>(po=(i,l)=>{s(i),l&&o(l)},()=>{po=null}),[]);const a=c.useMemo(()=>{const i=t==="connected",l=dO(t),d={};return r&&(d[r]=l),d.standalone=l,{wsStatus:t,isConnected:i,connectionStates:d,usesP2P:!1}},[t,r]);return n.jsx(lw,{connectionOverrides:a,children:n.jsx(hO,{children:e})})}const zx="adhdev_standalone_font_preferences",Bs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Yi=[{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"}],jo=[{id:"default",label:"Default mono",labelKey:"standalone.fonts.presets.defaultMono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", "D2Coding", "Noto Sans Mono CJK KR", "Apple SD Gothic Neo", "Malgun Gothic", 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"}],fO=new Set(Yi.map(e=>e.id)),bO=new Set(jo.map(e=>e.id));function Dn(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Pa("chat",t.chat),code:Pa("code",t.code),terminal:Pa("terminal",t.terminal)}}function Pa(e,t){const s=Bs[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"?fO:bO).has(o)?o==="custom"?a?{preset:"custom",customFamily:a}:s:{preset:o}:s}function Ea(e,t){var o;const s=Pa(e,t);if(s.preset==="custom"&&s.customFamily)return s.customFamily;const r=e==="chat"?Yi:jo;return((o=r.find(a=>a.id===s.preset))==null?void 0:o.family)||r[0].family}function gO(e){const t=Dn(e),s=Ea("chat",t.chat),r=Ea("code",t.code),o=Ea("terminal",t.terminal);return{"--chat-font-family":s,"--chat-code-font-family":r,"--chat-terminal-font-family":o,"--chat-tool-font-family":o}}function Ps(e,t=document.documentElement){const s=Dn(e),r=gO(s);t.setAttribute("data-standalone-fonts","custom");for(const[o,a]of Object.entries(r))t.style.setProperty(o,a);return s}function id(e){const t=Dn(e);try{localStorage.setItem(zx,JSON.stringify(t))}catch{}return t}function xO(){try{const e=localStorage.getItem(zx);if(e)return Dn(JSON.parse(e))}catch{}return Bs}function yO(){return Ps(xO())}function eo(e,t,s){const r=e==="chat"?Yi:jo,o=r.find(a=>a.id===t)||r[0];return o.labelKey&&s?s(o.labelKey,o.label):o.label}function vO({children:e}){const t=Gs(),s=hi(),{t:r}=he("common"),o=c.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:n.jsx(Fp,{}),label:r("nav.dashboard"),active:s.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:n.jsx(xr,{}),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(Jn,{}),label:r("nav.notifications"),active:s.pathname.startsWith("/notifications"),onSelect:()=>t("/notifications")},{id:"settings",path:"/settings",icon:n.jsx(_r,{}),label:r("nav.settings"),active:s.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[s.pathname,t,r]),a=c.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(hd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("nav.docs")},{id:"about",label:r("nav.about"),icon:n.jsx(Co,{}),active:s.pathname==="/about",onSelect:()=>t("/about"),title:r("nav.about")}],[s.pathname,t,r]);return n.jsx(BT,{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.75"]}),footerActions:({collapsed:i,toggleCollapsed:l})=>n.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:l,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 wO(){const e=Gs(),{sendCommand:t}=wt(),{ides:s}=yn(),r=c.useMemo(()=>s.filter(o=>o.daemonMode||o.type==="adhdev-daemon").map(o=>o),[s]);return n.jsx(mD,{daemons:r,features:yx,sendCommand:t,unwrapResult:o=>o,normalizeMesh:o=>o,onClose:()=>e("/mesh")})}const SO=[{icon:n.jsx(xr,{size:16}),key:"localFirst"},{icon:n.jsx(Cn,{size:16}),key:"chatRelay"},{icon:n.jsx(pd,{size:16}),key:"screenshots"},{icon:n.jsx(Bn,{size:16}),key:"remoteControl"},{icon:n.jsx(yr,{size:16}),key:"multiIde"},{icon:n.jsx(hd,{size:16}),key:"cli"}],kO=[{icon:n.jsx(xi,{size:16}),key:"anywhere"},{icon:n.jsx(Fp,{size:16}),key:"p2pStream"},{icon:n.jsx(Jn,{size:16}),key:"mobileNotifications"},{icon:n.jsx(vw,{size:16}),key:"restApi"},{icon:n.jsx(Sw,{size:16}),key:"enterpriseControls"}],jO=[{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 NO(){const{t:e}=he("common");return n.jsxs(Lo,{icon:n.jsx(Co,{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.75"]}),children:[n.jsx(vt,{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(vt,{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:SO.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(vt,{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:CT.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:AT.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:_T.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(vt,{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:kO.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(vt,{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:jO.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(Hi,{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(Iw,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function sl(e,t,s){return{...e,[t]:s}}function rl({surface:e,title:t,description:s,value:r,options:o,onChange:a}){const{t:i}=he("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(nt,{content:s,size:12})]}),n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(qT,{value:r.preset,onChange:l=>{const d=l.target.value;a(d==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:d})},children:o.map(l=>n.jsx("option",{value:l.id,children:l.labelKey?i(l.labelKey,l.label):l.label},l.id))}),r.preset==="custom"&&n.jsx(Nn,{type:"text",className:"font-mono",placeholder:i("standalone.fonts.customFamilyPlaceholder"),value:r.customFamily||"",onChange:l=>a({preset:"custom",customFamily:l.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:Ea(e,r)})]})]})]})}function CO({value:e,savedValue:t,saving:s=!1,error:r,notice:o,onChange:a,onSave:i,onResetToSaved:l,onResetToDefaults:d}){const{t:u}=he("common"),m=JSON.stringify(e)!==JSON.stringify(t);return n.jsxs("div",{className:"flex flex-col gap-4",children:[r&&n.jsx(Ht,{variant:"error",children:r}),o&&n.jsx(Ht,{variant:"success",children:o}),n.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[n.jsx(rl,{surface:"chat",title:u("standalone.fonts.chat"),description:u("standalone.fonts.chatDescription"),value:e.chat,options:Yi,onChange:h=>a(sl(e,"chat",h))}),n.jsx(rl,{surface:"code",title:u("standalone.fonts.code"),description:u("standalone.fonts.codeDescription"),value:e.code,options:jo,onChange:h=>a(sl(e,"code",h))}),n.jsx(rl,{surface:"terminal",title:u("standalone.fonts.terminal"),description:u("standalone.fonts.terminalDescription"),value:e.terminal,options:jo,onChange:h=>a(sl(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(nt,{size:12,content:[u("standalone.fonts.previewSummary",{chat:eo("chat",e.chat.preset,u),code:eo("code",e.code.preset,u),terminal:eo("terminal",e.terminal.preset,u)}),u("standalone.fonts.defaultsSummary",{chat:eo("chat",Bs.chat.preset,u),code:eo("code",Bs.code.preset,u)}),u("standalone.fonts.fontOverridesNotice")].join(`
121
-
122
- `)})]})}),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:"Claude"}),n.jsx("span",{className:"chat-time",children:u("standalone.fonts.previewNow")})]}),n.jsxs("div",{className:"chat-markdown",children:[n.jsx("p",{children:n.jsx(La,{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(Qn,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:s||!m,children:u(s?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),n.jsx(Qn,{type:"button",variant:"secondary",size:"sm",onClick:l,disabled:s||!m,children:u("standalone.fonts.revertToSaved")}),n.jsx(Qn,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:s,children:u("standalone.fonts.resetToDefaults")})]})]})}function _O(){const{t:e}=he("common"),{ides:t}=yn(),s=t.find(q=>q.type==="adhdev-daemon"),{sendCommand:r}=wt(),{userName:o}=yn(),[a,i]=c.useState(o||""),[l,d]=c.useState(null),[u,m]=c.useState(null),[h,p]=c.useState(Bs),[b,f]=c.useState(!1),[x,g]=c.useState(""),[w,S]=c.useState(""),[C,j]=c.useState("127.0.0.1"),[v,y]=c.useState(""),[N,k]=c.useState(""),[A,E]=c.useState(""),[P,T]=c.useState(""),[M,_]=c.useState(""),[I,D]=c.useState(!1),L=async()=>{const W=await(await En("/auth/session")).json();d(W)},$=async()=>{const W=await(await En("/api/v1/standalone/preferences")).json();m(W),j(W.standaloneBindHost);const ce=Dn(W.standaloneFontPreferences);p(ce),Ps(ce),id(ce)};c.useEffect(()=>{o!==void 0&&i(o)},[o]),c.useEffect(()=>{Promise.all([L(),$()]).catch(q=>{T(q instanceof Error?q.message:String(q))})},[]),c.useEffect(()=>{Ps(h)},[h]);const U=q=>{const W=q.target.value.trim();s!=null&&s.id&&W!==o&&r(s.id,"set_user_name",{userName:W}).catch(console.error)},J=async()=>{g(""),S(""),f(!0);try{const q=Dn(h),W=await En("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:q})}),ce=await W.json();if(!W.ok)throw new Error((ce==null?void 0:ce.error)||"Failed to save standalone font preferences");const ye=Dn(ce.standaloneFontPreferences);m(ce),p(ye),Ps(ye),id(ye),S(e("standalone.settings.fontsSaved"))}catch(q){g(q instanceof Error?q.message:String(q))}finally{f(!1)}},K=()=>{const q=Dn(u==null?void 0:u.standaloneFontPreferences);g(""),S(""),p(q),Ps(q)},R=()=>{g(""),S(""),p(Bs),Ps(Bs)},O=async()=>{T(""),_(""),D(!0);try{const q=await En("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),W=await q.json();if(!q.ok)throw new Error((W==null?void 0:W.error)||"Failed to save standalone network preference");m(W),j(W.standaloneBindHost),_(W.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(q){T(q instanceof Error?q.message:String(q))}finally{D(!1)}},H=async()=>{if(T(""),_(""),N.trim().length<4){T(e("standalone.settings.passwordTooShort"));return}if(N!==A){T(e("standalone.settings.passwordMismatch"));return}D(!0);try{const q=await En("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:N})}),W=await q.json();if(!q.ok)throw new Error((W==null?void 0:W.error)||"Failed to save password");d(W),await $(),y(""),k(""),E(""),_(l!=null&&l.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),Ex()}catch(q){T(q instanceof Error?q.message:String(q))}finally{D(!1)}},B=async()=>{T(""),_(""),D(!0);try{const q=await En("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),W=await q.json();if(!q.ok)throw new Error((W==null?void 0:W.error)||"Failed to clear password");d(W),await $(),y(""),k(""),E(""),_(e("standalone.settings.passwordDisabled"))}catch(q){T(q instanceof Error?q.message:String(q))}finally{D(!1)}};return n.jsxs(Lo,{icon:n.jsx(_r,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[(l==null?void 0:l.publicHostWarning)&&n.jsx(Ht,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),n.jsx(vt,{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.75"]})]}),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:l!=null&&l.hasPasswordAuth?e("standalone.settings.authPassword"):l!=null&&l.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(gp,{to:`/machines/${s.id}`,state:{initialMachineTab:"providers"},className:"text-accent-primary hover:underline",children:e("standalone.settings.providersLink")})]})]})}),n.jsx(vt,{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(q=>n.jsxs("label",{className:`rounded-xl border px-4 py-3 text-sm flex gap-3 items-center cursor-pointer ${C===q.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:C===q.host,onChange:()=>j(q.host)}),n.jsx("span",{className:"font-medium text-text-primary",children:q.label}),n.jsx(nt,{content:q.hint})]},q.host))}),n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx(Qn,{type:"button",variant:"primary",size:"sm",onClick:()=>{O()},disabled:I,children:e(I?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),(u==null?void 0:u.standaloneBindHost)&&(u.currentBindHost||(l==null?void 0:l.boundHost))&&u.standaloneBindHost!==(u.currentBindHost||(l==null?void 0:l.boundHost))&&n.jsx(Qt,{content:e("standalone.settings.networkRestartHint",{host:u.currentBindHost||(l==null?void 0:l.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(vt,{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:l!=null&&l.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),P&&n.jsx(Ht,{variant:"error",children:P}),M&&n.jsx(Ht,{variant:"success",children:M}),n.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[n.jsx(Nn,{type:"password",placeholder:l!=null&&l.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:v,onChange:q=>y(q.target.value)}),n.jsx(Nn,{type:"password",placeholder:l!=null&&l.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:N,onChange:q=>k(q.target.value)}),n.jsx(Nn,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:A,onChange:q=>E(q.target.value)})]}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsx(Qn,{type:"button",variant:"primary",size:"sm",onClick:()=>{H()},disabled:I,children:I?e("standalone.settings.saving"):l!=null&&l.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(l==null?void 0:l.hasPasswordAuth)&&n.jsx(Qn,{type:"button",variant:"danger",size:"sm",onClick:()=>{B()},disabled:I,children:e("standalone.settings.disablePassword")})]})]})}),n.jsx(vt,{title:e("standalone.settings.appearanceSection"),children:n.jsx(g2,{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(nt,{content:e("standalone.settings.fontsDescription"),size:12})]}),n.jsx(CO,{value:h,savedValue:Dn(u==null?void 0:u.standaloneFontPreferences),saving:b,error:x,notice:w,onChange:p,onSave:()=>{J()},onResetToSaved:K,onResetToDefaults:R})]})})}),n.jsx(vt,{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(yw,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel"),n.jsx(nt,{content:e("standalone.settings.displayNameHint")})]})}),n.jsx(Nn,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:a,onChange:q=>i(q.target.value),onBlur:U,onKeyDown:q=>{q.key==="Enter"&&q.currentTarget.blur()}})]})})}),n.jsxs(vt,{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(nt,{content:e("settings.coordinatorPrompts.sectionDescription"),size:12})]}),n.jsx(n2,{daemonId:s==null?void 0:s.id,embedded:!0})]})]})}const AO=["claude-cli","codex-cli","antigravity-cli"],oo="adhdev_onboarding_done",TO=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"}],IO={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions"};function MO({onDone:e}){const{t}=he("common"),[s,r]=c.useState([]),[o,a]=c.useState(new Set(AO)),[i,l]=c.useState(!0),[d,u]=c.useState(null),[m,h]=c.useState(!1),[p,b]=c.useState(null),[f,x]=c.useState("all");c.useEffect(()=>{let y=!1;return fetch("/api/v1/providers/catalog?sort=popular&limit=100").then(async N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);const k=await N.text();try{return JSON.parse(k)}catch{throw new Error(`unexpected non-JSON response (${N.headers.get("content-type")??"unknown content type"})`)}}).then(N=>{y||r(N.providers??[])}).catch(N=>{y||u(N instanceof Error?N.message:String(N))}).finally(()=>{y||l(!1)}),()=>{y=!0}},[]);const g=s.filter(y=>f==="all"||y.category===f),w=["cli","ide","extension"].map(y=>({category:y,items:g.filter(N=>N.category===y)})).filter(y=>y.items.length>0),S=c.useCallback(y=>{a(N=>{const k=new Set(N);return k.has(y)?k.delete(y):k.add(y),k})},[]),C=c.useCallback(async()=>{if(o.size===0){localStorage.setItem(oo,"1"),e();return}h(!0);const y=[];for(const N of o)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:N})})).json().catch(()=>({}));y.push({type:N,ok:!!A.success,error:A.error})}catch(k){y.push({type:N,ok:!1,error:k instanceof Error?k.message:String(k)})}b(y),h(!1),y.every(N=>N.ok)&&localStorage.setItem(oo,"1")},[o,e]),j=c.useCallback(()=>{localStorage.setItem(oo,"1"),e()},[e]),v=c.useCallback(()=>{p&&p.every(y=>y.ok)?e():m||j()},[p,m,e,j]);return n.jsx(ng,{open:!0,onClose:v,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(Qn,{variant:"secondary",size:"sm",onClick:j,disabled:m,children:t("standalone.onboarding.skip")}),n.jsx(Qn,{variant:"primary",size:"sm",onClick:()=>{p?(localStorage.setItem(oo,"1"),e()):C()},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:TO.map(y=>{const N=y.key==="all"?s.length:s.filter(k=>k.category===y.key).length;return N===0&&y.key!=="all"?null:n.jsxs("button",{onClick:()=>x(y.key),className:`machine-btn text-3xs px-2 py-0.5 ${f===y.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[y.label," ",n.jsxs("span",{className:"opacity-60",children:["(",N,")"]})]},y.key)})}),i&&n.jsx("div",{className:"text-text-muted text-xs py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&n.jsx(Ht,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&g.length===0&&n.jsx("div",{className:"text-text-muted text-xs py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&g.length>0&&n.jsx("div",{className:"flex flex-col gap-4",children:w.map(y=>n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:IO[y.category]??y.category}),n.jsx("div",{className:"grid gap-1.5",children:y.items.map(N=>{var P;const k=o.has(N.type),A=p==null?void 0:p.find(T=>T.type===N.type),E=((P=N.manifest)==null?void 0:P.details)??"";return n.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${k?"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:k,onChange:()=>S(N.type),disabled:m,className:"shrink-0"}),n.jsx($i,{type:N.type,label:N.displayName??N.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:N.displayName}),E&&n.jsx("div",{className:"text-3xs text-text-muted truncate",children:E})]}),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"})})]},N.type)})})]},y.category))})]})})}function RO(){try{return localStorage.getItem(oo)==="1"}catch{return!1}}const PO="/dashboard";function EO(e,t){const s=typeof t=="string"?t.trim():"";return{suppressed:e.startsWith(PO),sessionId:s||null}}IT();d2();If();yO();const LO=Bw({baseUrl:"",getToken:Gi});function DO({children:e}){const{t}=he("common"),[s,r]=c.useState(null),[o,a]=c.useState(!0),[i,l]=c.useState(""),[d,u]=c.useState(""),[m,h]=c.useState(!1),p=async()=>{a(!0),u("");try{const g=await En("/auth/session");if(!g.ok)throw new Error(`HTTP ${g.status}`);const w=await g.json();r(w)}catch(g){u(g instanceof Error?g.message:String(g))}finally{a(!1)}},[b,f]=c.useState(0);c.useEffect(()=>{p()},[]),c.useEffect(()=>{if(!d||s)return;const g=Math.min(5e3,500*2**b),w=window.setTimeout(()=>{f(S=>S+1),p()},g);return()=>window.clearTimeout(w)},[d,s,b]),c.useEffect(()=>{s&&f(0)},[s]),c.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let g=!1;return(async()=>{try{const w=await En("/api/v1/standalone/preferences");if(!w.ok)return;const S=await w.json();if(g)return;const C=Dn(S.standaloneFontPreferences);Ps(C),id(C)}catch{}})(),()=>{g=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const x=async g=>{g.preventDefault(),h(!0),u("");try{const w=await En("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),S=await w.json();if(!w.ok)throw new Error((S==null?void 0:S.error)||"Login failed");r(S),l(""),Ex()}catch(w){u(w instanceof Error?w.message:String(w))}finally{h(!1)}};return o||!s&&b<3?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:x,children:[n.jsx(Nn,{type:"password",value:i,onChange:g=>l(g.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),n.jsx(Qn,{type:"submit",variant:"primary",disabled:m||!i,className:"justify-center",children:t(m?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):n.jsx(Ht,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&n.jsx(Ht,{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 OO(){const{ides:e,initialLoaded:t}=yn(),s=e.filter(r=>r.type==="adhdev-daemon").map(r=>({id:r.id,machineId:r.machineId||r.id,nickname:Ef(r)||void 0,hostname:Ad(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(LE,{machines:s,initialLoaded:t??!0})}function fp(){const{t:e}=he("common"),{ides:t,initialLoaded:s}=yn();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(il,{to:`/machines/${r.id}`,replace:!0}):n.jsx(il,{to:"/dashboard",replace:!0})}function $O(){const[e,t]=c.useState(!1);return c.useEffect(()=>{let s=!1;if(!RO())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{s||(r.providers??[]).length===0&&(window.dispatchEvent(new Event(Yl)),t(!0))}).catch(()=>{}),()=>{s=!0}},[]),e?n.jsx(MO,{onDone:()=>t(!1)}):null}function FO(){const{t:e}=he("common"),t=hi(),[s]=bp(),{suppressed:r,sessionId:o}=EO(t.pathname,s.get("activeTab")),{promptSession:a,hasActivePrompt:i,responseError:l,isSubmitting:d,submit:u,cancel:m,reopen:h}=Ni(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(Nd,{promptSession:a,isSubmitting:d,error:l,onSubmit:u,onCancel:m})]})}function HO(){const e=c.useMemo(()=>({sendCommand:fo,sendData:mi,sendPtyInput:qx}),[]);return n.jsx(oy,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:n.jsx(hw,{client:LO,children:n.jsx(DO,{children:n.jsx(pO,{children:n.jsx(fw,{value:e,children:n.jsxs(Hw,{sendDaemonCommand:fo,children:[n.jsx(FO,{}),n.jsx(R1,{}),n.jsxs(vO,{children:[n.jsx($O,{}),n.jsxs(ay,{children:[n.jsx(Pn,{path:"/dashboard",element:n.jsx(aP,{})}),n.jsx(Pn,{path:"/machine",element:n.jsx(fp,{})}),n.jsx(Pn,{path:"/machines/:id",element:n.jsx(TE,{})}),n.jsx(Pn,{path:"/machines",element:n.jsx(fp,{})}),n.jsx(Pn,{path:"/notifications",element:n.jsx(OO,{})}),n.jsx(Pn,{path:"/about",element:n.jsx(NO,{})}),n.jsx(Pn,{path:"/settings",element:n.jsx(_O,{})}),n.jsx(Pn,{path:"/mesh",element:n.jsx(cD,{children:n.jsx(aD,{})})}),n.jsx(Pn,{path:"/setup",element:n.jsx(wO,{})}),n.jsx(Pn,{path:"*",element:n.jsx(il,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}eC({connectionManager:Ln});function BO(){return n.jsx(x2,{fallback:n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",background:"var(--bg-primary)"},children:n.jsx(tn,{})}),children:n.jsx(HO,{})})}iy(document.getElementById("root")).render(n.jsx(zT,{children:n.jsx(BO,{})}));export{ZT as $,Ud as A,Jr as B,a3 as C,vg as D,l3 as E,Wd as F,nh as G,o3 as H,en as I,j3 as J,v3 as K,KO as L,y3 as M,Fa as N,y0 as O,Un as P,Tx as Q,Hd as R,c3 as S,Qt as T,ff as U,Yd as V,Qn as W,Nn as X,wy as Y,dw as Z,YT as _,vr as a,Ar as a0,Et as a1,qO as a2,x3 as a3,g3 as a4,XO as a5,d3 as a6,b3 as a7,YO as a8,p3 as a9,m3 as aa,et as ab,h3 as ac,Kp as ad,VO as ae,f3 as af,u3 as ag,k3 as ah,e3 as ai,Fp as aj,kw as ak,On as al,Bd as am,wt as an,N3 as ao,UE as ap,To as aq,Sr as ar,kt as as,pi as at,bx as au,gx as av,WE as aw,BE as ax,Zu as b,GO as c,$a as d,s3 as e,r3 as f,Ax as g,IA as h,wl as i,zO as j,wi as k,t3 as l,w3 as m,i3 as n,S3 as o,Si as p,Vi as q,Jb as r,n3 as s,JO as t,Fi as u,nt as v,QO as w,kr as x,cl as y,ZO as z};