@adhdev/daemon-standalone 1.0.72 → 1.0.73

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,4 +1,4 @@
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-BKOLRm3R.js","assets/mesh-graph-7mv6fb91.js","assets/DashboardMeshGraphDialog-B6V-kTJw.css"])))=>i.map(i=>d[i]);
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-Iml8kna4.js","assets/mesh-graph-7mv6fb91.js","assets/DashboardMeshGraphDialog-B6V-kTJw.css"])))=>i.map(i=>d[i]);
2
2
  var Nx=Object.defineProperty;var Cx=(e,t,s)=>t in e?Nx(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var ze=(e,t,s)=>Cx(e,typeof t!="symbol"?t+"":t,s);import{r as c,j as n,u as pe,i as Ge,M as Xl,b as _x,d as Ax,e as Tx,t as Ix,f as Mx,a as Wn,h as Rx,R as vt,T as Ma,k as qs,l as Yc,m as Qc,D as Px,n as ai,o as sp,p as Ex,q as Dx,L as rp,B as Lx,v as Ox,w as Rn,N as Jc,x as $x}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 Fx(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 ho=Fx();function du(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 Hx(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function uu(e){return Array.isArray(e)?[...e]:[]}function op(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?uu(e.messages):i?[]:t.messages,activeModal:r?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...s?{messages:uu(e.messages)}:{},...r?{activeModal:e.activeModal??null}:{}}}function ha(e,t){const s=Hx(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:op(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 ap(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?ha(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 Xe(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 Lt(...e){return je(...e)??""}function ln(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function qt(...e){for(const t of e)if(typeof t=="boolean")return t}function Yi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Bx(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 Zl(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 Wx(e,t){if(!Array.isArray(e))return;const s=e.map(r=>{const o=Xe(r),a=je(o.path),i=je(o.commit),l=je(o.repoPath,o.repo_root)??Bx(t,a);if(!a||!i)return null;const d={path:a,commit:i,dirty:qt(o.dirty)??!1,outOfSync:qt(o.outOfSync,o.out_of_sync)??!1},m=ln(o.lastCheckedAt,o.last_checked_at);m!==void 0&&(d.lastCheckedAt=m),l&&(d.repoPath=l);const u=je(o.error);return u&&(d.error=u),d}).filter(r=>r!==null);return s.length>0?s:void 0}function Ux(e){return qt(e.isGitRepo)!==void 0||!!je(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!je(e.repoRoot,e.repo_root,e.workspace)||ln(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 pa(e,t,s){const r=qt(e.isGitRepo);if(!Object.keys(e).length||!Ux(e))return;const o=r??!0,a=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(k=>typeof k=="string"):[],i=ln(e.conflicts)??a.length,l=qt(e.hasConflicts)??i>0,d=je(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=Wx(e.submodules,d),u=je(e.upstreamStatus,e.upstream_status),h=ln(e.upstreamFetchedAt,e.upstream_fetched_at),p=je(e.upstreamFetchError,e.upstream_fetch_error),b=je(e.error),f=ln(e.staged)??0,x=ln(e.modified)??0,g=ln(e.untracked)??0,S=ln(e.deleted)??0,w=ln(e.renamed)??0,_=ln(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:u??"unchecked",...h!==void 0?{upstreamFetchedAt:h}:{},...p?{upstreamFetchError:p}:{},ahead:ln(e.ahead)??0,behind:ln(e.behind)??0,staged:f,modified:x,untracked:g,deleted:S,renamed:w,dirty:qt(e.dirty,e.isDirty,e.is_dirty)??(f+x+g+S+w>0||l),hasConflicts:l,conflictFiles:a,stashCount:ln(e.stashCount,e.stash_count)??0,..._!==void 0?{lastCheckedAt:_}:{},...m?{submodules:m}:{},...e.daemonBuildBehind&&typeof e.daemonBuildBehind=="object"?{daemonBuildBehind:e.daemonBuildBehind}:{},...b?{error:b}:{}}}function Kx(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+=Zl(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 qx(e,t){const s=Xe(e.lastGit??e.last_git),r=Xe(s.result),o=Xe(s.status),a=Xe(r.status),i=Xe(e.lastProbe??e.last_probe),l=Xe(i.git),d=Xe(l.result),m=Xe(l.status),u=Xe(d.status);let h=null;for(const p of[o,a,m,u]){const b=pa(p,e);if(!b)continue;const f=Kx(b);(!h||f>h.score)&&(h={git:b,score:f})}return h==null?void 0:h.git}function zx(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 Ra(e){const t=Xe(e),s=je(t.sessionId,t.session_id,t.id)??zx(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)}:{},...qt(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:qt(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)}:{},...qt(t.isCached,t.is_cached)!==void 0?{isCached:qt(t.isCached,t.is_cached)}:{}}:null}function Vx(e){const t=e&&typeof e=="object"?e:{};return je(t.id,t.nodeId,t.node_id)}function Gx(e,t){if(!t)return!1;const s=t.trim();return s?Vx(e)===s:!1}var Yx=["antigravity-cli","claude-cli","codex-cli","cursor-cli","grok-cli","kimi","opencode"];function Xc(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 Qx=["daemon_","standalone_"];function Jx(e){const t=je(e);return!!t&&/^[0-9a-f]{64}$/i.test(t)}function ip(e){var s,r;return!e||!Jx(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 Zc(e){const t=je(e);if(t){for(const s of Qx)if(t.startsWith(s))return t.slice(s.length).trim()||void 0;return t}}function Xx(e){const t=Zc(e);if(t)return t.startsWith("mach_")?`daemon_${t}`:t}function un(e,t){const s=Zc(e),r=Zc(t);return!s||!r?!1:s===r}var cp=["easy","medium","difficult","freeform"];function Zx(e){return typeof e=="string"&&cp.includes(e)}function ey(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(Zx):[],i=Array.isArray(t.capability)?t.capability.filter(m=>typeof m=="string"&&!!m.trim()).map(m=>m.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 lp(e){if(!Array.isArray(e))return[];const t=[];for(const s of e){const r=ey(s);r&&t.push(r)}return t}function ty(e){const t=new Set,s=[];for(const r of lp(e))t.has(r.provider)||(t.add(r.provider),s.push(r.provider));return s}function en(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var dp=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress"];en(dp);var ny=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];en(ny);var sy=["p2p_offer","p2p_ice"];en(sy);var ry=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];en(ry);var oy=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","daemon_mesh_command","p2p_offer","p2p_ice"];en(oy);var ay=["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"];en(ay);var iy=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],cy=[...dp,...iy];en(cy);var ly=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];en(ly);var dy=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];en(dy);var uy=["p2p_ready","p2p_answer","p2p_ice"];en(uy);var my=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];en(my);var hy=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];en(hy);var up=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];en(up);var mp=["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"];en(mp);[...new Set([...up,...mp])];var hp=2;function py(e,t){const s=typeof t=="number"&&Number.isFinite(t)?t:1;return s===e?"ok":s>e?"reload_required":"daemon_update_required"}var fy="Claude TUI review page is not focused",by="Claude TUI answer delivered but not confirmed",ed=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"],pp={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"},fp={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"},gy=new Set(ed);function ii(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return gy.has(t)?t:fp[t]??null}function td(e){const t=ii(e);return t?pp[t]:"unknown"}function ci(e){return td(e)==="working"}function xy(e){return td(e)==="dead"}function yy(e){const t=td(e);return t==="working"||t==="blocked"}function mu(e){return ed.filter(t=>pp[t]===e)}var vy=["pending","assigned","completed","failed","cancelled"],wy=["completed","failed","cancelled"],Sy=["code_change","validation","live_debug_readonly","launch_app","convergence"],ky=["low","normal","high"],jy=["when_idle","interrupt"],bp=["completed","blocked","failed"],Ny=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function gr(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}gr(vy);var T5=gr(wy);gr(Sy);gr(ky);gr(jy);gr(bp);var Cy=["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"],_y=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(_y);var Ay=["mesh_queue","mesh_direct","plain"],Ty=["delivered","queued"],Iy=["local","p2p"],My=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],Ry=["default","native_source"],Py=["restart","live_holder"],Ey=["approval","choice"],Dy=["approved","rejected","answered"],Ly=["modal_button","auto_approve","prompt_answer"],Oy=["genuine","weak"],$y=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],Fy=["completed","aborted"],Hy=["alive","unknown","read_failed","dead"],By=["auth_failed","billing_failed"],Wy=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],Uy=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],Ky=["completed","failed"],qy=["operator_update","refine_terminal","validation_terminal"],zy=["delivered","queued","duplicate"],Vy=[...ed,"unknown"],Gy=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],Yy=["completed","failed","cancelled"],Qy=["genuine","weak","tool_report","operator"],Jy=["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"],gp=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],zs={t:"id"},Vs={t:"id",optional:!0},rs={t:"bool"},Ho={t:"bool",optional:!0},hu={t:"ms"},Xy={t:"ms",optional:!0},Bo={t:"int",optional:!0},It=e=>({t:"enum",values:e}),Rr=e=>({t:"enum",values:e,optional:!0}),Zy={dispatch_accepted:{scope:It(Ay),messageId:zs,meshId:Vs,nodeId:Vs,providerType:Vs,attemptNo:Bo,dispatchNonce:Bo,consumeProfile:Rr(Ry),maxTaskRetries:Bo,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:zs,outcome:It(Ty),via:It(Iy)},delivery_refused:{messageId:zs,reason:It(Cy)},dispatch_failed:{workerAbsent:rs,reason:It(My),refusalCode:Vs},duplicate_dispatch_refusal:{holderSessionId:zs,holderAttemptId:Vs},session_rebound:{toSessionId:zs,reason:It(Py)},turn_started:{retro:rs},suspension:{modal:It(Ey),modalKey:Vs},suspension_resolved:{resolution:It(Dy),via:It(Ly)},turn_end:{strength:It(Oy),afterFinalizationTimeout:Ho,hollow:Ho,summary:{t:"summary_ref",optional:!0},blockReason:Rr($y),releasedByHardCap:Ho,nativeOutcome:Rr(Fy),live:{t:"live",optional:!0},reportExpected:Ho},transcript_final:{selfAttributing:rs,nativeRead:rs,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:Xy},transcript_activity:{newestActivityAt:hu},no_progress:{stalledMs:hu,observedStatus:It(Vy),finalAssistantPresent:rs},liveness:{result:It(Hy)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:Rr(By)},session_error:{reason:It(Wy)},worker_report:{outcome:It(bp),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:rs,branchState:Rr(Ny),touchedFileCount:Bo},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:rs,commitsSinceDispatch:{t:"int"},attributable:rs},cancel:{reason:It(Uy)},operator_status:{status:It(Ky),reason:It(qy)},coordinator_ack:{notify:It(gp),outcome:It(zy)},hold_expired:{holdId:zs,reason:It(Gy)}},ev=Object.keys(Zy);function wo(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}wo(ev);wo(Jy);wo(gp);wo(Yy);wo(Qy);var tv=["user","remembered","mesh_slot","task_override","provider_default","unspecified"];function nd(e){return typeof e=="string"&&tv.includes(e)}var nv=["dashboard","mesh","cli","api","restore"];function sv(e){return typeof e=="string"&&nv.includes(e)}function rv(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??xp(e)}function xp(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 ov(e){const t=rv(e);if(!e||!t)return;const s=xp(e);return{value:t,...s&&s!==t?{changedFrom:s}:{},source:nd(e.source)?e.source:"unspecified"}}function el(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function pu(e){if(!e||typeof e!="object")return;const t=e,s=[];if(Array.isArray(t.history))for(const m of t.history){if(!m||typeof m!="object")continue;const u=m,h=je(u.value),p=el(u.at),b=u.via==="launch"||u.via==="change_model"||u.via==="observed"?u.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=el(t.observedAt);return{source:nd(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 av(e){if(!e||typeof e!="object")return;const t=e,s=je(t.sessionId),r=je(t.providerType),o=el(t.launchedAt),a=pu(t.model),i=pu(t.thinkingLevel);if(!s||!r||o===void 0||!a||!i)return;const l=je(t.providerVersion),d=je(t.workspace),m=je(t.autoApproveModeId);return{sessionId:s,providerType:r,...l?{providerVersion:l}:{},...t.providerChannel==="stable"||t.providerChannel==="preview"?{providerChannel:t.providerChannel}:{},launchedBy:sv(t.launchedBy)?t.launchedBy:"api",launchedAt:o,...d?{workspace:d}:{},model:a,thinkingLevel:i,...m?{autoApproveModeId:m}:{}}}function Zn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var iv=["applied","recorded","rejected"];Zn(iv);var cv=["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(cv);var lv=["completed","failed"];Zn(lv);var dv=["operator_update","refine_terminal","validation_terminal"];Zn(dv);var uv=["own","fleet"];Zn(uv);var mv=["active","paused","completed","abandoned"];Zn(mv);var hv=["provider_quirk","pattern_to_avoid","recovery_lesson"];Zn(hv);var pv=["coordinator","unknown"];Zn(pv);var fv=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];Zn(fv);var bv=["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"];Zn(bv);function bs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function gv(e,t){const[s,r]=Pa(t);if(!r)return e[s];const o=e[s];return bs(o)?o[r]:void 0}function Pa(e){const t=e.indexOf(".");return t<0?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function xv(e,t){const s={...e};for(const r of Object.keys(t.collections)){const[o,a]=Pa(r);if(!a){delete s[o];continue}const i=s[o];if(!bs(i)||!(a in i))continue;const l={...i};delete l[a],s[o]=l}return s}function yv(e,t,s){const r=new Map,o=[];for(const d of Array.isArray(e)?e:[])!bs(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 m=d[s];if(typeof m!="string")continue;const u=r.get(m);r.set(m,u?{...u,...d}:{...d})}for(const[d,m]of Object.entries(t.unsetFields??{})){const u=r.get(d);if(!u)continue;const h={...u};for(const p of m)delete h[p];r.set(d,h)}const a=t.order??o,i=[],l=new Set;for(const d of a){const m=r.get(d);!m||l.has(d)||(i.push(m),l.add(d))}for(const[d,m]of r)l.has(d)||i.push(m);return i}function vv(e,t,s){var a;const r=new Map;for(const i of Object.keys(s.collections))r.set(i,gv(e,i));const o=xv(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=bs(o[i])?{...o[i]}:{};for(const m of l.unset??[])delete d[m];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],m=r.get(i);if(d!=null&&d.absent){const[f,x]=Pa(i);x||delete o[f];continue}if(!d&&m===void 0)continue;const u=d?yv(m,d,l):m,[h,p]=Pa(i);if(!p){o[h]=u;continue}const b=bs(o[h])?{...o[h]}:{};b[p]=u,o[h]=b}return o}var wv={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}},Sv={collections:{nodes:"nodeId","queue.tasks":"id",missions:"id"},volatileTopLevel:["refreshedAt","sourceOfTruth","turnPresentationCounters","meshProtocolV2Counters","pendingRetentionCounters","meshProtocolMetrics"],stableRow:(e,t)=>e==="nodes"?kv(t):t};function Pr(e,t){if(!bs(e))return e;const s={...e};for(const r of t)delete s[r];return s}function kv(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=Pr(t.dataFreshness,["ageMs","lastProbeAt","staleness"])),"connection"in t&&(t.connection=Pr(t.connection,["lastStateChangeAt"])),"git"in t){const r=Pr(t.git,["lastCheckedAt"]);bs(r)&&Array.isArray(r.submodules)&&r.submodules.length===0&&delete r.submodules,t.git=r}"nodeFacts"in t&&(t.nodeFacts=Pr(t.nodeFacts,["reportedAt"]));const s=t.gitObservation;return bs(s)&&(s.source==="self"||s.source==="local")&&(t.gitObservation=Pr(s,["observedAt"])),t}const jv=new Set(["no_progress","long_generating"]);function Nv(e){return!e||jv.has(e)?e:ii(e)??e}function fu(e){return!!e&&typeof e=="object"&&"text"in e}function sd(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:fu(a)?String(a.text||""):"").join(s):fu(e)?o=String(e.text||""):o=String(e||""),r?o.replace(/\s+/g," ").trim():o}function cr(e){return sd(e,{normalizeWhitespace:!0})}function Cv(e){let t="";for(let s=0;s<e.length;s++){const r=e[s],o=e.charCodeAt(s);if(!(o<=31&&r!==`
3
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
4
  `||a===" "||a===" ")continue}t+=r}}return t}function bu(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 yp(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 _v(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 Qi(e){if(!e||typeof e!="object")return"";const t=e,s=_v(cr(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 Av(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=Qi(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:Qi(e[0]),last:Qi(e[e.length-1])}}function tl(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function nl(e,t,s){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(tl(e)&&tl(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)nl(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"&&nl(r[i],o[i],s)}function so(e,t){return Array.isArray(e)?e.map(s=>so(s,t)):!e||typeof e!="object"?e:tl(e)?Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>[r,r==="messages"?Av(o,t):so(o,t)])):Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,so(r,t)]))}function Tv(e,t){try{const s=new WeakSet;return nl(e,t,s),JSON.stringify(so(e,s))===JSON.stringify(so(t,s))}catch{return!1}}function sl(e,t,s){return Tv(e,t)?(e._lastUpdate=s,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function vp(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Iv(e,t,s){t[s]!==void 0&&(e[s]=t[s])}function gu(e,t,s,r){var d;const o=(d=t.chats)!=null&&d.length?t.chats:e.chats,a=ap(e.childSessions,t.childSessions,{preserveMissing:r}),i=op(t.activeChat,e.activeChat),l=t.workspace||e.workspace;return yp(e,t,{...e,...t,chats:o,childSessions:a,activeChat:i,workspace:l,_lastUpdate:s})}function Mv(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=ap(e.childSessions,t.childSessions,{preserveMissing:s})),(o=t.chats)!=null&&o.length&&!((a=e.chats)!=null&&a.length)&&(r.chats=t.chats),t.workspace&&(r.workspace=t.workspace);for(const i of["title","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","muted","model","modelSource","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])Iv(r,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(r.machineNickname=t.machineNickname),t.versionMismatch===!0&&(r.versionMismatch=!0),r}function Rv(e,t,s,r){const o=Mv(e,t,r),a=Object.keys(o).length>0?yp(e,t,{...e,...o,_lastUpdate:s}):{...e,_lastUpdate:s};return sl(e,a,s)}function Pv(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=vp(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 Ev(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 Dv(e,t,s,r,o){return e.transport?s.has(t)&&!r.has(t)?!0:o.has(t):!1}function Lv(e,t,s){var u,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:m}=Pv(e);for(const p of e){const b=a.get(p.id);if(!b){a.set(p.id,{...p,_lastUpdate:r});continue}const f=bu(p),x=bu(b),g=vp(p),S=!o.has(g);if(f>x){const y=gu(b,p,r,S);a.set(p.id,sl(b,y,r));continue}if(f<x){a.set(p.id,Rv(b,p,r,S));continue}const w=y=>typeof y=="number"&&Number.isFinite(y),_=w(p.timestamp)&&w(b.timestamp),k=_?p.timestamp:p.timestamp||r,v=_?b.timestamp:b._lastUpdate||b.timestamp||0;if(k>=v){const y=gu(b,p,r,S);a.set(p.id,sl(b,y,r));continue}(u=p.chats)!=null&&u.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)&&m.has(f)&&!i.has(p)){a.delete(p);continue}const x=r-(b._lastUpdate||b.timestamp||0);Ev(b,f,x,i,o,d)&&a.delete(p)}for(const[p,b]of a){const f=b.daemonId||p.split(":")[0];if(Dv(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 Ov(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 $v(e,t){return e.id===t||e.sessionId===t||e.instanceId===t}function Fv(e,t,s){const r=t.trim();if(!r)return e;let o=!1;const a=e.map(i=>{if(!$v(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 wp=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}),Sp=c.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[],hydrateInteractivePrompt:()=>{}}),kp=c.createContext({userName:void 0,setUserName:()=>{},userRole:void 0,usesP2P:!0});function Hv({children:e,connectionOverrides:t}){const[s,r]=c.useState([]),[o,a]=c.useState(!1),[i,l]=c.useState([]),[d,m]=c.useState(void 0),u=c.useRef(s);c.useEffect(()=>{u.current=s},[s]);const h=c.useCallback((_,k)=>{r(v=>{let y=!1;const j=v.map(N=>N.id!==_||N.chats===k?N:(y=!0,{...N,chats:k}));return y?j:v})},[]),p=c.useCallback((_,k)=>{r(v=>{const y=v.length===0?_:Lv(_,v,k),j=!Ov(v,y);return j&&ho.record({kind:"dashboard.entries_applied",payload:{incoming:du(_),next:du(y)}}),j?y:v})},[]),b=c.useCallback(()=>a(!0),[]),f=c.useCallback((_,k)=>{r(v=>Fv(v,_,k))},[]),x=c.useMemo(()=>({injectEntries:p,markLoaded:b,getIdes:()=>u.current,hydrateInteractivePrompt:f}),[p,b,f]),g=t,S=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:m}),[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]),w=c.useMemo(()=>({userName:d,setUserName:m,userRole:g==null?void 0:g.userRole,usesP2P:(g==null?void 0:g.usesP2P)??!0}),[d,m,g==null?void 0:g.userRole,g==null?void 0:g.usesP2P]);return n.jsx(Sp.Provider,{value:x,children:n.jsx(kp.Provider,{value:w,children:n.jsx(wp.Provider,{value:S,children:e})})})}function xn(){return c.useContext(wp)}function Bv(){return c.useContext(kp)}function lr(){return c.useContext(Sp)}const Wv=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={...}>.`)}}}),Uv=c.createContext(Wv);function Kv({client:e,children:t}){return n.jsx(Uv.Provider,{value:e,children:t})}const qv={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},jp=c.createContext(qv);function zv({value:e,children:t}){return n.jsx(jp.Provider,{value:e,children:t})}function xt(){return c.useContext(jp)}function Np(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function Vv(e){const t=Np(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 Gv(e){const[t,s]=c.useState(null),r=c.useCallback(async(i,l)=>{const d=h=>e(i,"launch_cli",{...l,...h}),m=await d({}),u=Vv(m);return u?new Promise(h=>{s({providerType:u.providerType||String(l.cliType??"?"),sourceName:u.sourceName,description:u.description,retry:()=>d({confirmExternalUntrusted:!0}),resolve:p=>{p.cancelled?h({success:!1,error:"user_cancelled_untrusted_launch"}):h(p.response)}})}):m},[e]),o=c.useCallback(async()=>{const i=t;if(i){s(null);try{const l=await i.retry(),d=Np(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 Ke={size:18};function Cp({size:e=Ke.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 rd({size:e=Ke.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 dr({size:e=Ke.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 Yv({size:e=Ke.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 Qv({size:e=Ke.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 Jv({size:e=Ke.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 _p({size:e=Ke.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 od({size:e=Ke.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 xr({size:e=Ke.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 Xv({size:e=Ke.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 yr({size:e=Ke.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 So({size:e=Ke.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 I5({size:e=Ke.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 Zv({size:e=Ke.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=Ke.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 Hn({size:e=Ke.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 Ap({size:e=Ke.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 Hs({size:e=Ke.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 vr({size:e=Ke.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 Xt({size:e=Ke.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 ur({size:e=Ke.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 Ln({size:e=Ke.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 ew({size:e=Ke.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 ad({size:e=Ke.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 li({size:e=Ke.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 id({size:e=Ke.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 tw({size:e=Ke.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 cd({size:e=Ke.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=Ke.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 Tp({size:e=Ke.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 po({size:e=Ke.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 sw({size:e=Ke.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 Pt({size:e=Ke.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 Ip({size:e=Ke.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 di({size:e=Ke.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 rw({size:e=Ke.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 Mp({size:e=Ke.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 ow({size:e=Ke.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 gs({size:e=Ke.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 rl({size:e=Ke.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 Rp({size:e=Ke.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 Pp({size:e=Ke.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 Ep({size:e=Ke.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 ui({size:e=Ke.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 xu({size:e=Ke.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 aw({size:e=Ke.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=Ke.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 cw({size:e=Ke.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 lw({size:e=Ke.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 Dp({size:e=Ke.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 dw({size:e=Ke.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 uw({size:e=Ke.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 Lp({size:e=Ke.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),n.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}function mr({size:e=Ke.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 Op({size:e=Ke.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 mw({size:e=Ke.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 hw({size:e=Ke.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 pw({size:e=Ke.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 ol({size:e=Ke.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}=pe("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(Xt,{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 $p=c.createContext(null);function bw({sendDaemonCommand:e,children:t}){const s=Gv(e),r=c.useMemo(()=>({launchCli:s.launchCli}),[s.launchCli]);return n.jsxs($p.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 mi(){const e=c.useContext($p);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function gw(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(),m=o(l),u=l.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!l.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function i(l,d={}){const m={"Content-Type":"application/json",...d.headers||{}},u=s==null?void 0:s();u&&(m.Authorization=`Bearer ${u}`);const h=o(l),p=new AbortController,b=setTimeout(()=>p.abort(),15e3);try{const f=await fetch(h,{...d,headers:m,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,m={})=>i(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),execTerminal:(l,d,m)=>i(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:m})}),sendAgentMessage:(l,d,m)=>i(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:m})}),getAgentStatus:l=>i(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,d,m)=>i(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:m?"approve":"reject"})}),getMuxState:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,d,m={})=>i(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),getMuxEventsUrl:l=>a(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>a(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:i}}function hi(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 m=Math.floor(d/24);return m<7?`${m}d${s}`:new Date(e).toLocaleDateString()}const Fp=e=>hi(e);function ko(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 jo(e){var s,r;if(e)return e;const t=((s=Ge)==null?void 0:s.resolvedLanguage)||((r=Ge)==null?void 0:r.language);return t&&t!=="cimode"?t:void 0}function Ea(e,t={}){const s=ko(e);if(s===null)return"";const r=jo(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"):dd(s,{locale:r})}function ld(e,t){try{return new Intl.DateTimeFormat(e,t)}catch{return new Intl.DateTimeFormat(void 0,t)}}function No(e,t={}){const s=ko(e);return s===null?"":ld(jo(t.locale),{dateStyle:"medium",timeStyle:t.seconds?"medium":"short"}).format(s)}function dd(e,t={}){const s=ko(e);return s===null?"":ld(jo(t.locale),{dateStyle:"medium"}).format(s)}function pi(e,t={}){const s=ko(e);return s===null?"":ld(jo(t.locale),{timeStyle:t.seconds?"medium":"short"}).format(s)}function M5(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 os(e,t,s){try{return new Intl.NumberFormat(s,{style:"unit",unit:t,unitDisplay:"short"}).format(e)}catch{return`${e}${t[0]}`}}function xw(e,t={}){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";const s=jo(t.locale),r=Math.round(e/1e3);if(r<60)return os(r,"second",s);const o=Math.floor(r/60);if(o<60)return os(o,"minute",s);const a=Math.floor(o/60);if(a<48){const d=o%60;return d?`${os(a,"hour",s)} ${os(d,"minute",s)}`:os(a,"hour",s)}const i=Math.floor(a/24),l=a%24;return l?`${os(i,"day",s)} ${os(l,"hour",s)}`:os(i,"day",s)}function al(e){return e?pi(e):""}function yw(e,t,s){return Number(e.receivedAt||s[fi(e)]||0)||0}function Hp(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function vw(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}const ww=new Set(["https:","http:","mailto:","file:"]);function yu(e){if(e)try{const t=new URL(e);return ww.has(t.protocol)?e:void 0}catch{return}}function Er(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 Ji(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 vu(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 Sw(e){const t=Bp(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 Bp(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 fi(e,t){const s=e;if(typeof s.messageId=="string"&&s.messageId)return`mid:${s.messageId}`;const r=sd(e.content,{joiner:`
@@ -47,7 +47,7 @@ ${JSON.stringify(t,null,2)}
47
47
  `):"");try{await navigator.clipboard.writeText(Q.join(`
48
48
  `)),f("Copied!"),setTimeout(()=>f("Snapshot"),1500)}catch(ve){console.error("[SpecDebugPanel] clipboard write failed",ve)}},ae=G=>{p(B=>{const Q=new Set(B);return Q.has(G)?Q.delete(G):Q.add(G),Q})};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:G=>G.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"}),J&&n.jsx("span",{className:"text-2xs text-text-secondary font-mono bg-surface-secondary px-1.5 py-0.5 rounded truncate",children:J.spec_id})]}),n.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(J==null?void 0:J.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):q()},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:()=>{ye()},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:()=>{$()},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 ${_?"text-text-secondary hover:bg-bg-glass-hover":"bg-accent-primary/20 text-accent-primary"}`,onClick:()=>{if(_)try{const G=JSON.parse(v);w(G),H(G)}catch{return}k(!1)},disabled:!S&&_,children:"Form"}),n.jsx("button",{type:"button",className:`px-2 py-0.5 ${_?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>{S&&y(JSON.stringify(S,null,2)),k(!0)},children:"JSON"})]}),n.jsx("span",{className:"text-3xs text-text-muted font-mono truncate flex-1",title:J==null?void 0:J.specPath,children:((J==null?void 0:J.specPath)??"").split("/").slice(-3).join("/")}),j&&n.jsx("span",{className:"text-status-warning text-3xs",children:"unsaved"}),!_&&E.length>0&&n.jsxs("span",{className:"text-status-error text-3xs",children:[E.length," error",E.length>1?"s":""]}),n.jsx("button",{type:"button",className:`text-2xs px-2.5 py-1 rounded border transition-colors ${A==="saving"||!_&&E.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:()=>{ke()},disabled:A==="saving"||!_&&E.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}),!_&&E.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:E.map((G,B)=>n.jsx("div",{className:"font-mono",children:G},B))}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:_||!S?n.jsx("textarea",{value:v,onChange:G=>{y(G.target.value),N(!0),R("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(h_,{model:S,onChange:U,onPreview:K,preview:I,onTestSections:oe,sectionPreview:D})}),n.jsx("div",{className:"text-3xs text-text-muted shrink-0",children:_?"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",")."]}),J&&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:[J.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:[J.name," ",n.jsxs("span",{className:"text-text-muted",children:["(",J.cliType,")"]})]})]}),J.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:J.workingDir,children:J.workingDir})]}),J.spawnedAtMs?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-text-muted",children:"Spawned"}),n.jsx("span",{className:"text-text-secondary",children:Ur(J.spawnedAtMs)})]}):null,J.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:J.providerSessionId,children:J.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 ${J.current_state?fc(J.current_state.id):"text-text-muted"}`,children:J.current_state?J.current_state.id:"none"}),((ne=J.current_state)==null?void 0:ne.label)&&J.current_state.label!==J.current_state.id&&n.jsx("span",{className:"text-text-secondary text-2xs",children:J.current_state.label}),J.status&&J.status!==((ie=J.current_state)==null?void 0:ie.id)&&n.jsxs("span",{className:"text-text-muted text-2xs",children:["engine: ",n.jsx("span",{className:`font-mono ${fc(J.status)} px-1 py-0.5 rounded text-3xs`,children:J.status})]}),J.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"}),J.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"}),J.cursorPosition!=null&&n.jsxs("span",{className:"text-text-muted text-2xs font-mono",children:["cursor: ",n.jsxs("span",{className:"text-text-secondary",children:[J.cursorPosition.row,",",J.cursorPosition.col]})]}),J.lastBusyAt>0&&n.jsxs("span",{className:"text-text-muted text-2xs ml-auto",children:["last busy: ",n.jsx("span",{className:"text-text-secondary",children:Ur(J.lastBusyAt)})]})]}),((_e=J.completionIdleDebounce)==null?void 0:_e.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:[J.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:[J.completionIdleDebounce.holdMs,"ms"]})]}),n.jsxs("span",{className:"text-text-secondary",children:["force: ",n.jsxs("span",{className:"text-text-secondary",children:[J.completionIdleDebounce.forceAfterMs,"ms"]})]}),n.jsx("span",{className:"text-text-muted ml-auto",children:J.completionIdleDebounce.ageMs<J.completionIdleDebounce.holdMs?n.jsxs("span",{className:"text-status-warning",children:["hold remaining: ",J.completionIdleDebounce.holdMs-J.completionIdleDebounce.ageMs,"ms"]}):J.completionIdleDebounce.ageMs<J.completionIdleDebounce.forceAfterMs?n.jsxs("span",{className:"text-orange-300",children:["force in: ",J.completionIdleDebounce.forceAfterMs-J.completionIdleDebounce.ageMs,"ms"]}):n.jsx("span",{className:"text-status-error",children:"overdue"})})]}),J.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:J.current_modal.title||""}),J.current_modal.buttons.length>0&&n.jsxs("span",{className:"text-text-secondary ml-2",children:["[",J.current_modal.buttons.map(G=>G.label).join(" / "),"]"]})]}),J.fsm&&n.jsxs(n.Fragment,{children:[n.jsx(Qo,{}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsxs(Yo,{children:["FSM — outgoing from ",n.jsx("span",{className:"text-accent-primary font-mono normal-case",children:J.fsm.currentState})," (held ",Sm(J.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:z,onChange:G=>Z(G.target.checked),className:"accent-[var(--accent-primary)]"}),"live"]})]}),n.jsxs("div",{className:"space-y-1",children:[J.fsm.transitions.length===0&&n.jsx("div",{className:"text-text-muted text-2xs italic px-1",children:"no outgoing transitions (terminal state)"}),J.fsm.transitions.map((G,B)=>n.jsx(y_,{t:G},B))]})]})]}),n.jsx(Qo,{}),J.sections&&Object.keys(J.sections).length>0&&n.jsxs("div",{children:[n.jsx(Yo,{children:"Sections"}),n.jsx("div",{className:"space-y-1",children:Object.entries(J.sections).map(([G,B])=>{var Le;const Q=h.has(G),ue=B.split(`
49
49
  `),Re=((Le=ue[0])==null?void 0:Le.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:()=>ae(G),children:[n.jsx("span",{className:"text-3xs text-text-muted w-3",children:Q?"▾":"▸"}),n.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-2xs",children:G}),!Q&&n.jsx("span",{className:"text-text-secondary truncate font-mono text-2xs",children:Re}),n.jsxs("span",{className:"ml-auto text-text-muted text-3xs shrink-0",children:[ue.length,"L"]})]}),Q&&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:B||"(empty)"})]},G)})})]}),n.jsx(Qo,{}),J.stateHistory&&J.stateHistory.length>0&&n.jsxs("div",{children:[n.jsxs(Yo,{children:["State History (",J.stateHistory.length,")"]}),n.jsx("div",{className:"space-y-px",children:[...J.stateHistory].reverse().slice(0,20).map((G,B)=>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 ${fc(G.stateId)}`,children:G.stateId}),n.jsx("span",{className:"text-text-secondary text-2xs shrink-0 tabular-nums",children:Ur(G.at)}),G.durationMs>0&&n.jsxs("span",{className:"text-text-muted text-2xs",children:["held ",n.jsx("span",{className:"text-text-secondary",children:Sm(G.durationMs)})]}),G.reason&&n.jsx("span",{className:`text-3xs px-1.5 py-0.5 rounded font-mono shrink-0 ${g_[String(G.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(G.reason)}),G.debounceKind&&String(G.debounceKind)!=="none"&&n.jsxs("span",{className:"text-text-muted text-3xs font-mono",children:["debounce:",String(G.debounceKind)]}),G.matchedStateId&&String(G.matchedStateId)!==G.stateId&&n.jsxs("span",{className:"text-text-muted text-3xs font-mono",children:["eval→",n.jsx("span",{className:"text-text-secondary",children:String(G.matchedStateId)})]})]}),G.matchedRules&&G.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:[G.matchedRules.slice(0,3).map((Q,ue)=>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 Q=="string"?Q:JSON.stringify(Q)},ue)),G.matchedRules.length>3&&n.jsxs("span",{className:"text-3xs text-text-muted",children:["+",G.matchedRules.length-3," more"]})]})]},B))})]}),n.jsx(Qo,{}),(()=>{const G=J.messages??J.committedMessages??[];if(G.length===0)return null;const B=G.filter(Re=>Re.role==="user").length,Q=G.filter(Re=>Re.role==="assistant").length,ue=[...G].reverse().find(Re=>Re.role==="assistant");return n.jsxs("div",{children:[n.jsxs(Yo,{children:["Transcript (",G.length," — ",B,"u / ",Q,"a)"]}),ue&&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 ",ue.receivedAt?Ur(ue.receivedAt):""]}),n.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[ue.content.slice(0,400),ue.content.length>400?"…":""]})]})]})})(),J.specPath&&n.jsx("div",{className:"text-3xs text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:J.specPath,children:J.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:()=>u(G=>!G),children:[n.jsx("span",{className:"text-text-muted",children:m?"▾":"▸"}),n.jsxs("span",{children:["Raw screen (",J.screen?J.screen.split(`
50
- `).length:0," lines)"]})]}),m&&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:J.screen||"(empty)"})]})]})]})]})})})}function Sb(e,t){if(typeof window>"u")return!1;try{return window[e]===!0||window.localStorage.getItem(t)==="1"}catch{return window[e]===!0}}function w_(){return Sb("__ADHDEV_DEBUG_SPEC__","adhdev_debug_spec")}function S_(){return Sb("__ADHDEV_DEBUG_MOBILE_BUNDLE__","adhdev_debug_mobile_bundle")}function k_({activeConv:e,clearToken:t=0,terminalRef:s,handleSendChat:r,isSendingChat:o=!1,sendFeedbackMessage:a=null,isVisible:i=!0,isInputActive:l=!0}){var Vt;const{t:d}=pe("common");xn();const{sendPtyInput:m}=xt(),[u,h]=c.useState(!1),p=c.useRef(!1);p.current=u;const[b,f]=c.useState("Runtime terminal unavailable"),[x,g]=c.useState(!1),[S,w]=c.useState(null),[_,k]=c.useState(!1),[v,y]=c.useState(!1),[j,N]=c.useState(1),[A,R]=c.useState(!1),[P,M]=c.useState(!1),[E,C]=c.useState(!1),[I,O]=c.useState(!1),[D,F]=c.useState(!1),z=w_(),[Z,W]=c.useState({width:0,height:0}),[T,$]=c.useState({width:0,height:0}),[H,q]=c.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[U,K]=c.useState(null),oe=c.useRef(null),ke=c.useRef(null),J=c.useRef(!1),ye=c.useRef(!1),ae=c.useRef(i),re=c.useRef(0),de=c.useRef(!1),ne=c.useRef(""),ie=c.useRef(null),_e=c.useRef(!1),G=c.useRef(!1),B=c.useRef(null),Q=c.useRef(null),ue=c.useRef(null),Re=32*1024,Le=()=>{var xe,Ie,De,Ve;return((Ie=(xe=oe.current)==null?void 0:xe.ownerDocument)==null?void 0:Ie.defaultView)||((Ve=(De=ke.current)==null?void 0:De.ownerDocument)==null?void 0:Ve.defaultView)||window},Pe=xe=>{const Ie=Le();return{ownerWindow:Ie,frameId:Ie.requestAnimationFrame(xe)}},Fe=()=>{const xe=B.current;if(xe){try{xe.ownerWindow.cancelAnimationFrame(xe.frameId)}catch{}B.current=null}},X=()=>{const xe=Q.current;if(xe){try{xe.ownerWindow.clearTimeout(xe.timeoutId)}catch{}Q.current=null}},ve=()=>{const xe=ue.current;if(xe){try{xe.ownerWindow.clearTimeout(xe.timeoutId)}catch{}ue.current=null}},Se=()=>{i&&B.current===null&&(B.current=Pe(()=>{Ct()}))},Ce=e.tabKey,L=e.sessionId||"",Y=e.daemonId||((Vt=e.routeId)==null?void 0:Vt.split(":")[0])||e.routeId||"",ce=Ni(e),te=u?Kf(e)||a:b,fe=u&&a||null,V=YC,se=QC,he=.05,Me=()=>{const xe=T.width,Ie=T.height;if(!Number.isFinite(Z.width)||Z.width<=0||!Number.isFinite(Z.height)||Z.height<=0||!Number.isFinite(xe)||xe<=0||!Number.isFinite(Ie)||Ie<=0)return 1;const De=Z.width/xe,Ve=Z.height/Ie;return Number(Math.min(se,Math.max(V,Math.min(De,Ve))).toFixed(2))},Ee=Me(),Te=J.current&&j>Ee,Ne=Number.isFinite(T.width)&&T.width>0?Math.max(Z.width,Math.round(T.width*j)):Z.width,Ue=Number.isFinite(T.height)&&T.height>0?Math.max(Z.height,Math.round(T.height*j)):Z.height,$e=()=>{Pe(()=>{const xe=ke.current;xe&&(xe.scrollLeft=0,xe.scrollTop=xe.scrollHeight-xe.clientHeight)})},ot=()=>{var xe,Ie;re.current=0,de.current=!1,ne.current="",ie.current=null,_e.current=!1,G.current=!1,J.current||(ye.current=!1,N(1)),B.current!==null&&Fe(),h(!1),f("Runtime terminal unavailable"),ve(),X(),w(null),K(null),R(!1),g(!1),k(!1),y(!1),(Ie=(xe=s.current)==null?void 0:xe.reset)==null||Ie.call(xe)},at=()=>{var xe,Ie;re.current=0,de.current=!1,ne.current="",ie.current=null,_e.current=!1,G.current=!1,B.current!==null&&Fe(),h(!0),f(""),ve(),X(),w(null),K(null),R(!1),g(!1),k(!1),y(!1),(Ie=(xe=s.current)==null?void 0:xe.reset)==null||Ie.call(xe)},pt=()=>{G.current&&(G.current=!1,Pe(()=>{var xe,Ie;(Ie=(xe=s.current)==null?void 0:xe.scrollToTop)==null||Ie.call(xe)}))},Ct=()=>{if(B.current=null,!i)return;const xe=ne.current;if(!xe)return;const Ie=xe.slice(0,Re);ne.current=xe.slice(Ie.length);const De=s.current;if(!De){ne.current=Ie+ne.current,Se();return}De.write(Ie,()=>{if(ne.current.length>0){Se();return}pt()})},_t=xe=>{xe&&(ne.current+=xe,Se())},ee=(xe,Ie=0,De,Ve,Ye={})=>{var et,kt,bt,Ht;const ut=!!Ye.force;!ut&&Ie>0&&re.current>=Ie||!ut&&Ie===0&&de.current||(re.current=Ie,Ie>0&&k(!0),h(!0),f(""),typeof De=="number"&&typeof Ve=="number"&&De>0&&Ve>0&&((kt=(et=s.current)==null?void 0:et.resize)==null||kt.call(et,De,Ve)),ne.current="",(Ht=(bt=s.current)==null?void 0:bt.reset)==null||Ht.call(bt),xe?_t(xe):pt())};c.useEffect(()=>{ot()},[L]),c.useEffect(()=>{var Ie;if(!L)return;const xe=((Ie=Dt.onRuntimeEvent)==null?void 0:Ie.call(Dt,L,De=>{if(!(!De||De.sessionId!==L)){if(De.type==="runtime_snapshot"){if(!i){ie.current={text:De.text||"",seq:De.seq||0,cols:De.cols,rows:De.rows,force:!!De.force};return}ee(De.text||"",De.seq||0,De.cols,De.rows,{force:!!De.force});return}if(De.type==="session_output"){de.current=!0,typeof De.seq=="number"&&(re.current=Math.max(re.current,De.seq),De.seq>0&&k(!0)),p.current||h(!0),p.current||f(""),typeof De.data=="string"&&_t(De.data);return}if(De.type==="session_cleared"){if(!i){_e.current=!0,ne.current="",ie.current=null;return}at();return}if(De.type==="session_io_error"){const Ve=typeof De.error=="string"&&De.error?De.error:typeof De.reason=="string"&&De.reason?De.reason:"unknown error";h(!1),f(`Runtime input failed: ${Ve}`);return}}},Y))||(()=>{});return()=>{xe()}},[Y,L,s,i]);const le=async(xe={})=>{var Ie;if(!Y||!L)return{success:!1,error:"daemonId and sessionId are required"};xe.preserveStatus||f(xe.loadingMessage||"Loading runtime terminal...");try{const De=await((Ie=Dt.requestRuntimeSnapshot)==null?void 0:Ie.call(Dt,Y,L,{sinceSeq:xe.sinceSeq,force:xe.force}));return De&&De.success===!1?(xe.preserveStatus||(h(!1),f(`Runtime terminal unavailable: ${De.error}`)),De):De||{success:!0}}catch(De){const Ve=(De==null?void 0:De.message)||String(De);return xe.preserveStatus||(h(!1),f(`Runtime terminal unavailable: ${Ve}`)),{success:!1,error:Ve}}},be=async xe=>{var ut,et;const Ie=((ut=oe.current)==null?void 0:ut.ownerDocument)||document,De=Ie.defaultView||window,Ve=(et=De.navigator)==null?void 0:et.clipboard;if(Ve!=null&&Ve.writeText&&De.isSecureContext)try{return await Ve.writeText(xe),!0}catch{}let Ye=null;try{return Ye=Ie.createElement("textarea"),Ye.value=xe,Ye.setAttribute("readonly","true"),Ye.style.position="fixed",Ye.style.left="-9999px",Ye.style.top="0",Ie.body.appendChild(Ye),Ye.focus(),Ye.select(),Ie.execCommand("copy")}catch{return!1}finally{Ye==null||Ye.remove()}},Ae=xe=>{X(),K(xe);const Ie=Le();Q.current={ownerWindow:Ie,timeoutId:Ie.setTimeout(()=>{Q.current=null,K(De=>De===xe?null:De)},2200)}},me=xe=>{ve(),w(xe);const Ie=Le();ue.current={ownerWindow:Ie,timeoutId:Ie.setTimeout(()=>{ue.current=null,w(De=>De===xe?null:De)},2200)}},Be=async()=>{var Ye,ut,et,kt;const xe=((ut=(Ye=s.current)==null?void 0:Ye.getSelection)==null?void 0:ut.call(Ye))||"",Ie=((kt=(et=s.current)==null?void 0:et.getVisibleText)==null?void 0:kt.call(et))||"",De=xe.trimEnd()||Ie.trimEnd();if(!De){Ae("Nothing to copy");return}if(!await be(De)){Ae("Copy failed");return}Ae(xe.trimEnd()?"Copied selection":"Copied visible terminal")},nt=xe=>{if(!u||!i)return;((m==null?void 0:m(Y,L,xe))??!1)||Ae("Terminal input failed")},qe=xe=>{nt(XC({ctrl:P,alt:E,shift:I},xe)),M(!1),C(!1),O(!1)},lt=async()=>{if(x)return;g(!0),w("Loading older terminal output..."),G.current=!0;const xe=await le({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:u});if(g(!1),(xe==null?void 0:xe.success)===!1){G.current=!1,w(`Older terminal output unavailable: ${xe.error}`);return}y(!0),me("Older terminal output loaded"),Pe(()=>{var Ie;(Ie=s.current)==null||Ie.bumpResize()})};c.useEffect(()=>{var Ie,De;if(!L)return;Y&&((Ie=Dt.getState)==null?void 0:Ie.call(Dt,Y))==="connected"&&le();const xe=(De=Dt.onStateChange)==null?void 0:De.call(Dt,(Ve,Ye)=>{Ve!==Y||Ye!=="connected"||le()});return()=>{xe==null||xe()}},[Y,L,s]),c.useEffect(()=>{t&&ot()},[t,Ce,s]),c.useEffect(()=>{var Ve,Ye;const xe=oe.current,Ie=(Ye=(Ve=xe==null?void 0:xe.ownerDocument)==null?void 0:Ve.defaultView)==null?void 0:Ye.ResizeObserver;if(!xe||!Ie)return;const De=new Ie(ut=>{const et=ut[0];if(!et)return;const{width:kt,height:bt}=et.contentRect;W(Ht=>{const Yt=Math.round(kt),sn=Math.round(bt);return Ht.width===Yt&&Ht.height===sn?Ht:{width:Yt,height:sn}})});return De.observe(xe),()=>De.disconnect()},[]),c.useEffect(()=>{if(J.current)return;const xe=Me();!Number.isFinite(xe)||xe<=0||N(Ie=>ye.current?xe<Ie-he?xe:Ie:(ye.current=!0,xe))},[T.height,T.width,Z.height,Z.width]),c.useEffect(()=>{Te&&$e()},[Te,Ue,Ne]),c.useEffect(()=>{var De;const xe=ae.current;if(ae.current=i,!i)return;xe||y(!1),_e.current&&(_e.current=!1,at());const Ie=ie.current;Ie&&(ie.current=null,ee(Ie.text,Ie.seq,Ie.cols,Ie.rows,{force:!!Ie.force})),Y&&L&&((De=Dt.getState)==null?void 0:De.call(Dt,Y))==="connected"&&le(),ne.current&&B.current===null&&Se(),Pe(()=>{var Ve;(Ve=s.current)==null||Ve.bumpResize()})},[Y,i,L]),c.useEffect(()=>()=>{B.current!==null&&Fe(),X(),ve()},[]),c.useEffect(()=>{const xe=Ve=>{var ut;const Ye=Ve.detail;Ye!=null&&Ye.sessionId&&Ye.sessionId!==L||u&&((ut=s.current)==null||ut.bumpResize())},Ie=Le(),De=Ie===window?[window]:[window,Ie];for(const Ve of De)Ve.addEventListener("adhdev:fit-cli-terminal",xe);return()=>{for(const Ve of De)Ve.removeEventListener("adhdev:fit-cli-terminal",xe)}},[u,L,s]);const ft=u&&_&&!v&&(H.atTop||!H.canScroll)||x||!!S;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{ref:oe,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[ft&&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:()=>{lt()},disabled:!L||x,title:d("terminal.replayScrollbackHint"),children:d(x?"terminal.loadingOlder":"terminal.loadOlderOutput")}),S&&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:S})]}),n.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[U&&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:U}),z&&n.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-2xs font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>F(xe=>!xe),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:()=>{Be()},disabled:!u,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:()=>R(xe=>!xe),disabled:!u,"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:()=>R(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),n.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",P,M],["Alt",E,C],["Shift",I,O]].map(([xe,Ie,De])=>n.jsx("button",{type:"button","aria-pressed":Ie,className:`h-9 rounded-lg border text-xs font-semibold transition-colors ${Ie?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>De(Ve=>!Ve),children:xe},xe))}),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:()=>qe("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:()=>qe("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:()=>qe("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:()=>qe("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:()=>qe("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:()=>qe("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:()=>qe("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:()=>nt(""),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:()=>qe("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:()=>qe("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:()=>{J.current=!0,N(xe=>{const Ie=Math.max(Ee,Number((xe-.1).toFixed(2)));return Ie>Ee&&$e(),Ie})},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:()=>{J.current=!0,N(xe=>{const Ie=Math.min(se,Number((xe+.1).toFixed(2)));return Ie>Ee&&$e(),Ie})},title:d("terminal.growViewport"),children:"+"})]}),n.jsx("div",{ref:ke,className:Te?"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:Ue>0?`${Ue}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:n.jsx("div",{style:{width:T.width>0?`${T.width}px`:"100%",height:T.height>0?`${T.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:j},children:n.jsx(Qp,{ref:s,readOnly:!u||!i,sizingMode:"measured",onViewportMetrics:$,onScrollMetrics:q,onInput:xe=>{!u||(m==null||m(Y,L,xe))}})})})}),!u&&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(Af,{contextKey:e.tabKey,panelLabel:wt(e),isSending:o,isBusy:!!ce,statusMessage:te,inlineStatusMessage:fe,onSend:async xe=>ce?!1:r(xe),isActive:l&&i,showControlsToggle:!1,animateVisibility:!1}),D&&n.jsx(v_,{activeConv:e,onClose:()=>F(!1)})]})}const j_=5e3,N_=12e3,C_=15e3;function __(e){return e==="disconnected"||e==="reconnecting"}function A_({wsStatus:e,showReconnected:t,loginUrl:s,onReconnect:r,reconnectDelayMs:o=j_,reconnectActionDelayMs:a=N_}){const{t:i}=pe(),l=__(e),[d,m]=c.useState(()=>!l||o<=0),[u,h]=c.useState(()=>!l||a<=0),p=c.useRef(!1),[b,f]=c.useState(!1);c.useEffect(()=>{if(!l){m(!1);return}if(p.current=!1,o<=0){p.current=!0,m(!0);return}m(!1);const A=setTimeout(()=>{p.current=!0,m(!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),C_);return()=>clearTimeout(A)},[b]);const x=()=>{f(!0),r==null||r()},g=l?d:e==="offline"||e==="auth_failed",S=!!(r&&e!=="auth_failed"&&(!l||u)),w=c.useMemo(()=>!t||e!=="connected"?!1:o<=0||p.current,[o,t,e]),_=e==="auth_failed"?"red":e==="offline"?"orange":"accent",k={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)"},j="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",N={transform:"translateX(-50%)"};return n.jsxs(n.Fragment,{children:[g&&n.jsx("div",{className:j,style:N,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:k[_],border:v[_],color:y[_]},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"))]}),S&&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(Zt,{size:11,thickness:2,color:"muted"}),i(b?"connection.reconnecting":"connection.reconnectNow")]})]})}),w&&n.jsx("div",{className:j,style:N,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 T_(){const e=c.useSyncExternalStore(GN,sm,sm),{t}=pe("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 kb({mode:e,onChange:t,compact:s=!1}){const{t:r}=pe("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(cd,{size:o}):n.jsx(Cn,{size:o})})}function I_(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 M_(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 R_(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 Nd({git:e,className:t="",compact:s=!1}){const r=I_(e),o=M_(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 ${R_(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 Ns=8,km=6;function P_(e,t,s){const r=Math.max(Ns,s.width-t.width-Ns),o=e.left+e.width/2-t.width/2,a=Math.min(Math.max(Ns,o),r),i=e.bottom+km,l=i+t.height<=s.height-Ns,d=e.top-km-t.height;return!l&&d>=Ns?{top:d,left:a,placement:"above"}:{top:Math.max(Ns,Math.min(i,s.height-t.height-Ns)),left:a,placement:"below"}}function Cd(){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}),[]),m=c.useCallback(h=>r(p=>p.peeking===h?p:{...p,peeking:h}),[]),u=c.useCallback(()=>{const h=e.current,p=t.current;if(!h||!p||typeof window>"u")return;const b=h.getBoundingClientRect(),f=p.getBoundingClientRect();a(P_({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}u()},[i,u]),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,S;const x=f.target;x&&((g=e.current)!=null&&g.contains(x)||(S=t.current)!=null&&S.contains(x)||l())},b=()=>u();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,u]),{anchorRef:e,popoverRef:t,open:i,pinned:s.pinned,position:o,close:l,togglePinned:d,setPeeking:m}}function _d({id:e,popoverRef:t,position:s,children:r,className:o,role:a="tooltip",ariaLabel:i}){return typeof document>"u"?null:Wn.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 jb(e){return e==null||e===!1||e===""}function tt({content:e,label:t,size:s=13,className:r,popoverClassName:o}){const{t:a}=pe("common"),i=c.useId(),l=`${i}-pop`,d=`${i}-desc`,{anchorRef:m,popoverRef:u,open:h,position:p,togglePinned:b,setPeeking:f}=Cd();return jb(e)?null:n.jsxs("span",{className:"inline-flex items-center align-middle",children:[n.jsx("button",{ref:x=>{m.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(So,{size:s})}),n.jsx("span",{id:d,className:"sr-only",children:e}),h&&n.jsx(_d,{id:l,popoverRef:u,position:p,className:o,children:e})]})}function Gt({content:e,children:t,className:s,popoverClassName:r}){const o=c.useId(),a=`${o}-pop`,i=`${o}-desc`,{anchorRef:l,popoverRef:d,open:m,position:u,togglePinned:h,setPeeking:p}=Cd();if(jb(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}),m&&n.jsx(_d,{id:a,popoverRef:d,position:u,className:r,children:e})]})}function R5({children:e,content:t,label:s,className:r,popoverClassName:o}){const i=`${c.useId()}-pop`,{anchorRef:l,popoverRef:d,open:m,position:u,togglePinned:h}=Cd();return n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:p=>{l.current=p},type:"button","aria-label":s,"aria-expanded":m,"aria-haspopup":"dialog","aria-controls":m?i:void 0,onClick:p=>{p.preventDefault(),p.stopPropagation(),h()},className:r,children:e}),m&&n.jsx(_d,{id:i,popoverRef:d,position:u,role:"dialog",ariaLabel:s,className:ct("whitespace-normal",o),children:t})]})}function Nb({value:e,live:t=!0,fallback:s="",className:r}){const{i18n:o}=pe("common"),[,a]=c.useState(0),i=ko(e);if(c.useEffect(()=>{if(!t||i===null||typeof window>"u")return;const d=window.setInterval(()=>a(m=>m+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(Gt,{content:No(i,{locale:l,seconds:!0}),children:n.jsx("time",{dateTime:new Date(i).toISOString(),className:r,children:Ea(i,{locale:l})})})}async function Cb(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 _b({value:e,label:t,className:s}){const{t:r}=pe("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 Cb(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 Ad({rows:e=[],children:t,summary:s,className:r,summaryClassName:o}){const{t:a}=pe("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(_b,{value:l.value})]})]},l.label)),t]})]})}function Ab(e){const t=e.replace(/[\\/]+$/,""),s=t.split(/[\\/]/);return s[s.length-1]||t||e}const E_=c.createContext(null);function Td(){return c.useContext(E_)}function D_(e){const t=e.replace(/^(daemon_|standalone_)/,"");return t.length<=20?t:`${t.slice(0,17)}…`}function L_(e){return qx(e)}function O_(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 $_(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 Ba(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=O_(e);return t.outOfSync?"degraded":t.dirty||$_(e)?"dirty":"online"}function F_(e,t){const s=t?Ba(t):void 0;return!e||e==="unknown"?s:e}function H_(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(Ra).filter(i=>i!==null);if(a.length>0)return a}const s=Xe(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=Ra(r);return o?[o]:void 0}function B_(e){const t=Xe(e.connection);return Object.keys(t).length>0?t:void 0}function W_(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 Tb(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 jm(e){var r,o,a,i,l,d;let t=0;const s=e.git;return Tb(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+=Zl(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 U_(e,t){var f,x,g,S;const s=jm(e),o=jm(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,m=(((g=o.activeSessionDetails)==null?void 0:g.length)??0)>0?o.activeSessionDetails:a.activeSessionDetails,u=(((S=o.providerPriority)==null?void 0:S.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")?Ba(i):o.health,providers:l??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...h?{connection:h}:{},...i?{git:i}:{}},b=Xe(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 K_=new Set(["self","local","member_push","coordinator_probe","none"]);function Cl(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Nm(e){const t=Xe(e),s=je(t.source);if(!s||!K_.has(s))return null;const r=je(t.lastRefreshError);return{source:s,observedAt:Cl(t.observedAt),refreshing:t.refreshing===!0,unreachableSince:Cl(t.unreachableSince),...r?{lastRefreshError:r}:{}}}function Ib(e){const t=Xe(e),s=je(t.nodeId,t.id);if(!s)return null;const r=Xe(t.cachedStatus),o=L_(t),a=o?void 0:pa(Xe(t.git),t)??pa(t,t),i=o??a,l=i?void 0:pa(Xe(r.git),t),d=i??l,m=je(t.machineStatus,t.machine_status,r.machineStatus,r.machine_status),u=je(t.health),h=o?Ba(d):F_(u,i)||(d?Ba(d):void 0)||je(r.health)||m||je(t.status)||"unknown",b=(o?void 0:je(t.error))??(i?void 0:je(r.error)),f=H_(t),x=Yi(t.activeSessions),g=(f==null?void 0:f.map(N=>N.sessionId))??[],S=Yi(t.providerPriority),w=qt(t.gitProbePending,t.git_probe_pending),_=i?void 0:w,k=B_(t),v=Xe(t.branchConvergence??t.branch_convergence),y=k==null?void 0:k.state,j=o&&(!(k!=null&&k.reported)||y==="unknown")?W_(k):k;return{nodeId:s,machineLabel:je(t.machineLabel,t.machine_label,t.hostname)||D_(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)}:{},...m?{machineStatus:m}:{},...qt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:qt(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}:{},..._!==void 0?{gitProbePending:_}:{},providers:Yi(t.providers),activeSessions:x.length>0?x:g,...f&&f.length>0?{activeSessionDetails:f}:{},...S.length>0?{providerPriority:S}:{},...qt(t.launchReady)!==void 0?{launchReady:qt(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)}:{},...j?{connection:j}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...t.scheduling&&typeof t.scheduling=="object"?{scheduling:t.scheduling}:{},...qt(t.autoFastForwardEligible,t.auto_fast_forward_eligible)===!0?{autoFastForwardEligible:!0}:{},...t.worktreeBootstrap&&typeof t.worktreeBootstrap=="object"?{worktreeBootstrap:t.worktreeBootstrap}:{},...t.staleDaemonBuild&&typeof t.staleDaemonBuild=="object"?{staleDaemonBuild:t.staleDaemonBuild}:{},...t.providerVersions&&typeof t.providerVersions=="object"&&!Array.isArray(t.providerVersions)?{providerVersions:t.providerVersions}:{},...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}:{},...Nm(t.gitObservation)?{gitObservation:Nm(t.gitObservation)}:{},...Cm(t.heldRuntime??t.held_runtime)?{heldRuntime:Cm(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 q_=new Set(["member_push","coordinator_probe","none"]);function Cm(e){const t=Xe(e);if(Object.keys(t).length===0)return null;const s=je(t.source)||"none";if(!q_.has(s))return null;const r=Array.isArray(t.sessions)?t.sessions.filter(o=>Object.keys(Xe(o)).length>0):[];return{...t,source:s,observedAt:Cl(t.observedAt),refreshing:t.refreshing===!0,sessions:r}}function z_(e,t,s){const r=Xe(e),o=Xe(r.settings),a=Xe(r.activeChat),i=je(Xe(r.coordinator).meshId,o.meshCoordinatorFor),l=t&&i===t?"coordinator":t&&je(o.meshNodeFor)===t?"worker":void 0,d=Ra({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 V_(e,t,s,r){const o=Xe(e),a=Xe(o.settings),i=je(a.meshNodeId);return i?i===s.nodeId:!r||!t?!1:je(Xe(o.coordinator).meshId,a.meshCoordinatorFor)===t||je(a.meshNodeFor)===t}function Mb(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=>V_(d,e,r,a)).map(d=>z_(d,e,r.workspace||void 0)).filter(d=>d!==null);if(i.length===0)return r;const l=Wa([...r.activeSessionDetails??[],...i]);return{...r,activeSessionDetails:l,activeSessions:Wa([...l,...(r.activeSessions??[]).map(d=>({sessionId:d}))]).map(d=>d.sessionId)}})}function Wa(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 Rb(e,t){const s=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],r=s.map(Ra).filter(o=>o!==null);return r.length===0?t:t.map(o=>{const a=r.filter(l=>{const d=Xe(s.find(p=>{const b=Xe(p);return je(b.sessionId,b.session_id,b.id)===l.sessionId})),m=je(d.nodeId,d.node_id),u=je(d.daemonId,d.daemon_id),h=je(d.workspace);return m&&m===o.nodeId?!0:un(u,o.daemonId)?!h||!o.workspace||h===o.workspace:!!(h&&o.workspace&&h===o.workspace)});if(a.length===0)return o;const i=Wa([...o.activeSessionDetails??[],...a]);return{...o,activeSessionDetails:i,activeSessions:Wa([...o.activeSessionDetails??[],...a,...(o.activeSessions??[]).map(l=>({sessionId:l}))]).map(l=>l.sessionId)}})}function G_(e){const t=Xe(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||qt(t.is_local_worktree)!==void 0}function Pb(e){const t=new Map,s=[];for(const r of e){const o=G_(r)?Ib(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=U_(a,o);t.set(o.nodeId,i);const l=s.findIndex(d=>d.nodeId===o.nodeId);l>=0&&(s[l]=i)}return s}function P5(e){const t=e??{},s=Pb(t.nodes??[]);return{...t,nodes:Mb(je(t.meshId)||"",Rb(t,s))}}function E5(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:Tb(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 Y_(e){const t=je(e.meshId,e.mesh_id,e.id),s=e.nodes,r=Array.isArray(s)?s.map(d=>Ib(d)).filter(d=>d!==null):null;if(!t||!r)return null;const o=Mb(t,Rb(e,Pb(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 Q_(e){var a;let t=0;const s=Xe(e.sourceOfTruth),r=Xe(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+=Zl(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 J_(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 X_=20;function _m(e){let t=null;for(const s of e){const r=Y_(Xe(s));if(!r)continue;const o=Q_(r),a=J_(r);if(!t){t={status:r,score:o,refreshedAt:a};continue}(Math.abs(o-t.score)<=X_?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 _i(e){const s=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,r=_m([s==null?void 0:s.status,s]);return r||_m([e==null?void 0:e.status,e])}function Z_(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 e1(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 t1(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 n1(e,t){var o,a;if(!t)return null;const s=_i(e),r=(o=s==null?void 0:s.nodes)==null?void 0:o.find(i=>Gx(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 s1={sm:"max-w-md",md:"max-w-lg",lg:"max-w-3xl"},Am={center:"items-center justify-center",sheet:"items-end justify-center sm:items-center",stretch:"items-stretch justify-center md:items-center"};function pr({open:e=!0,onClose:t,align:s="center",size:r="md",chrome:o=!0,closeOnBackdrop:a=!0,closeOnEsc:i=!0,ariaLabel:l,ariaLabelledBy:d,overlayClassName:m,surfaceClassName:u,children:h}){c.useEffect(()=>{if(!e||!i)return;const g=S=>{S.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",Am[s],"bg-black/60 px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",m):ct("fixed inset-0 flex",Am[s],m),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",s1[r],u):ct(u),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:Wn.createPortal(x,document.body)}function Eb({open:e,onClose:t,size:s="md",title:r,footer:o,children:a,showClose:i=!0,closeOnBackdrop:l=!0,closeOnEsc:d=!0,ariaLabel:m,className:u,contentClassName:h}){const p=r!=null||i;return n.jsxs(pr,{open:e,onClose:t,size:s,closeOnBackdrop:l,closeOnEsc:d,ariaLabel:r==null?m:void 0,overlayClassName:u,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":Ge.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(Pt,{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 r1(e){return{meshId:e,daemonId:null,status:null,response:null,loadedAt:null,loading:!1,refreshing:!1,error:null}}function Ai(e){let t=_l.get(e);return t||(t={snapshot:r1(e),inFlight:null,queuedRefresh:null,listeners:new Set},_l.set(e,t)),t}function ls(e,t){var r;const s=Ai(e);(r=t.status)!=null&&r.meshName&&t_(e,t.status.meshName),s.snapshot={...s.snapshot,...t};for(const o of[...s.listeners])try{o()}catch{}}function io(e){var t;return e?((t=_l.get(e))==null?void 0:t.snapshot)??null:null}function o1(e,t){const s=Ai(e);return s.listeners.add(t),()=>{s.listeners.delete(t)}}function a1(e,t,s=null){ls(e,{status:t,daemonId:s,loadedAt:t?Date.now():null,error:null})}function i1(e,t,s){ls(e,{status:t,daemonId:s,loadedAt:Date.now(),error:null,loading:!1})}function c1(e){Ai(e).snapshot.status||ls(e,{loading:!0,error:null})}function l1(e){return e instanceof Error?e.message:typeof e=="string"?e:"Failed to load mesh status"}function Ti(e){const{meshId:t,daemonId:s,load:r}=e,o=e.refresh===!0,a=e.extract??(u=>_i(u));if(!t||!s)return Promise.resolve(null);const i=Ai(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,Ti(e)))),i.queuedRefresh);const d=i.snapshot.status!==null;ls(t,{loading:!d,refreshing:d,error:null});const m=(async()=>{var u;await null;try{const h=await r(s,t,{refresh:o}),p=a(h);return p?(ls(t,{status:p,response:h,daemonId:s,loadedAt:Date.now(),error:null}),p):(ls(t,{error:"mesh_status returned an unexpected payload."}),null)}catch(h){return ls(t,{error:l1(h)}),null}finally{((u=i.inFlight)==null?void 0:u.promise)===m&&(i.inFlight=null),ls(t,{loading:!1,refreshing:!1})}})();return i.inFlight={daemonId:s,refresh:o,promise:m},m}const Ua=new Set;function d1(e){if(Ua.size===0)return!1;for(const t of[...Ua])try{t(e)}catch{}return!0}function u1(e){return Ua.add(e),()=>Ua.delete(e)}const Ss={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`},m1=new Set(["missing-credentials","expired-token","unauthorized","quota-exhausted","rate-limited","network","server","parse","cli-unavailable","unsupported","setup-required","no-data","unknown"]);function Id(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)=>m1.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 h1={"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 p1(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 f1(e,t=Ss){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(p1((o??0)+(a??0)))),typeof s.sessions=="number"&&r.push(t.usageSessions(s.sessions)),r.length===0?null:`${s.days}d ${r.join(" · ")}`}function fr(e){return h1[e]??e}function Tm(e){return Number.isFinite(e)?e>=90?"danger":e>=70?"warn":"good":"default"}function b1(e,t=Date.now(),s=Ss){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 wa(e,t=Date.now()){const s=e==null?void 0:e.resetsAt;return typeof s=="number"&&Number.isFinite(s)&&s>0&&s<=t}Ss.windowReset();function Im(e){return!!e&&typeof e.usedPercent=="number"&&Number.isFinite(e.usedPercent)}function g1(e){var s;const t=(s=e.metadata)==null?void 0:s.failureKind;return!(t==="no-data"||t==="expired-token"&&e.provider==="antigravity-cli")}function x1(e){return Im(e.session)||Im(e.weekly)?!0:Array.isArray(e.buckets)&&e.buckets.some(t=>!!t&&typeof t.usedPercent=="number"&&Number.isFinite(t.usedPercent))}function y1(e){var t;if(!g1(e)&&x1(e))return"stale";if(((t=e.metadata)==null?void 0:t.lastGoodWindows)===!0)return"refreshing"}function Mm(e,t=Date.now(),s=!1,r=Ss){if(!e||typeof e.usedPercent!="number"||!Number.isFinite(e.usedPercent))return null;if(wa(e,t))return r.windowReset();const o=r.used(e.usedPercent.toFixed(1)),a=b1(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 v1(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 w1(e,t=Ss){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 m=(o=(typeof a.name=="string"?a.name:"").split("·")[0])==null?void 0:o.trim().replace(/\s+(Models?|Bundled Models?)$/i,"").trim();r.push({label:`${m||t.pool()} ${v1(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 S1(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 k1(e,t=Ss){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 j1(e,t=Date.now(),s=Ss){const r=y1(e),o=(b,f,x)=>{const g=Mm(b,t,r,s);if(!g)return null;const S=b.usedPercent,w=wa(b,t);return{key:f,label:`${x} ${g}`,usedPercent:w?null:S,hint:f,tone:w?"default":Tm(S)}},a=o(e.session,"session","5h"),i=o(e.weekly,"weekly","7d"),l=o(e.monthly,"monthly","30d"),d=w1(e,s).map(b=>({key:b.label,label:`${b.label} ${Mm(b.window,t,r,s)}`,usedPercent:wa(b.window,t)?null:b.usedPercent,hint:"bucket",tone:wa(b.window,t)?"default":Tm(b.usedPercent)})),m=d.length>0?d:[a,i,l].filter(b=>b!==null),u=f1(e,s),h=u?{key:"usage",label:u,usedPercent:null,hint:"usage",tone:"info"}:null,p=a??i??h;return m.length>0?{kind:"chips",cue:r,chips:m,usageLabel:null,message:null,compactChip:p}:h?{kind:"usage",cue:r,chips:[],usageLabel:u,message:null,compactChip:p}:e.status==="ok"?{kind:"okNoWindows",cue:r,chips:[],usageLabel:null,message:S1(e),compactChip:null}:{kind:"failure",cue:r,chips:[],usageLabel:null,message:k1(e,s),compactChip:null}}function Md(e){return(t,s=Date.now())=>j1(t,s,e)}function D5(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 Db(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)=>fr(s.provider).localeCompare(fr(r.provider)))}function L5(e,t=Date.now(),s=Ss){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 Rm(e){return No(e,{seconds:!0})||"—"}function N1({sessionId:e,daemonId:t,conv:s,onClose:r}){var D;const{t:o}=pe("common"),a=Md(Id(o)),{sendCommand:i}=xt(),l=Td(),[d,m]=c.useState(!0),[u,h]=c.useState(null),[p,b]=c.useState(null),[f,x]=c.useState(null),[g,S]=c.useState(null),w=c.useMemo(()=>e1(s),[s]),_=c.useMemo(()=>t1(s),[s]),k=c.useCallback(async()=>{m(!0),b(null);try{const F=await i(t,"get_session_info",{targetSessionId:e}),z=F&&typeof F=="object"?F:{},Z=z.result&&typeof z.result=="object"?z.result:z;Z!=null&&Z.success?h(Z):(b((Z==null?void 0:Z.error)||o("sessionInfo.failedToLoad")),h(null))}catch(F){b((F==null?void 0:F.message)||String(F)),h(null)}finally{m(!1)}},[i,t,e,o]);c.useEffect(()=>{k()},[k]);const v=c.useMemo(()=>{var F,z;return Z_({conv:s,sessionDaemonId:t,heldCoordinatorDaemonId:w?(F=io(w))==null?void 0:F.daemonId:null,reportedCoordinatorDaemonId:(z=u==null?void 0:u.meshWorker)==null?void 0:z.coordinatorDaemonId})},[s,t,w,(D=u==null?void 0:u.meshWorker)==null?void 0:D.coordinatorDaemonId]),y=c.useCallback(async()=>{var W,T;if(x(null),S(null),!w||!_||!v)return;const z=((W=io(w))==null?void 0:W.status)??null??await Ti({meshId:w,daemonId:v,refresh:!1,load:($,H,q)=>l!=null&&l.loadMeshStatus?l.loadMeshStatus($,H,{refresh:q.refresh}):i($,"mesh_status",{meshId:H})});if(!z){S(((T=io(w))==null?void 0:T.error)||o("sessionInfo.meshNodeUnavailable"));return}const Z=n1(z,_);if(!Z){S(o("sessionInfo.stampedToNode"));return}x(Z)},[l,i,v,w,_,o]);c.useEffect(()=>{y()},[y]);const[j,N]=c.useState(!1),A=c.useCallback(async()=>{await Cb(C1({sessionId:e,daemonId:t,conv:s,data:u,meshNode:f,meshNodeError:g}))&&(N(!0),setTimeout(()=>N(!1),1500))},[s,t,u,f,g,e]),R=n.jsxs(n.Fragment,{children:[(u||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(j?"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=F=>o(F?"common.yes":"common.no"),M=u==null?void 0:u.session,E=(M==null?void 0:M.workspace)||(s==null?void 0:s.workspacePath)||"",C=(s==null?void 0:s.machineName)||(u==null?void 0:u.machineNickname)||"",I=u==null?void 0:u.meshWorker,O=Db((f==null?void 0:f.quota)??(u==null?void 0:u.quota));return n.jsx(Eb,{open:!0,onClose:r,title:o("sessionInfo.title"),size:"lg",footer:R,children:n.jsxs("div",{className:"text-sm space-y-4",children:[d&&n.jsx("div",{className:"text-text-secondary",children:o("sessionInfo.loading")}),p&&n.jsx("div",{className:"text-red-500",children:o("sessionInfo.failedToLoad")}),M&&n.jsxs("div",{className:"space-y-1.5","data-testid":"session-info-summary",children:[n.jsx(Qe,{k:o("sessionInfo.rowProvider"),v:M.providerName||M.providerType}),E&&n.jsx(Qe,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(Gt,{content:E,children:n.jsx("span",{className:"truncate",children:Ab(E)})})}),C&&n.jsx(Qe,{k:o("sessionInfo.rowMachine"),v:C}),M.spawnedAtMs?n.jsx(Qe,{k:o("sessionInfo.rowStarted"),v:n.jsx(Nb,{value:M.spawnedAtMs})}):null,(s==null?void 0:s.git)&&n.jsx(Qe,{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")}`]})}),(u==null?void 0:u.coordinator)&&n.jsx(Qe,{k:o("sessionInfo.rowRole"),v:o("sessionInfo.roleCoordinator")}),O.map(({provider:F,quota:z})=>{const Z=a(z);return n.jsx(Qe,{k:[fr(F),Xc(z)].filter(Boolean).join(" · "),v:Z.kind==="chips"?n.jsx("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:Z.chips.map(W=>n.jsx(Pm,{label:W.label,tone:W.tone},W.key))}):Z.kind==="usage"?n.jsx(Pm,{label:Z.usageLabel,tone:"info"}):Z.kind==="okNoWindows"?n.jsx("span",{className:"text-text-secondary",children:Z.message??o("sessionInfo.quotaOkNoWindows")}):n.jsx("span",{className:"text-text-secondary",children:Z.message})},F)}),(I==null?void 0:I.coordinatorSessionId)&&n.jsx(Qe,{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:()=>{d1({sessionId:I.coordinatorSessionId,source:"session-info-dialog"}),r()},children:o("sessionNav.openCoordinatorChat")})]})})]}),(M||f||(u==null?void 0:u.coordinator)||g&&(w||_))&&n.jsxs("details",{className:"group rounded-lg border border-border-subtle px-3 py-2","data-testid":"session-info-technical-details",children:[n.jsxs("summary",{className:"cursor-pointer select-none list-none text-xs font-medium text-text-secondary [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"mr-1 inline-block transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),o("common.technicalDetails")]}),n.jsxs("div",{className:"mt-3 space-y-4",children:[M&&n.jsxs(Ts,{title:o("sessionInfo.sectionSession"),children:[n.jsx(Qe,{k:o("sessionInfo.rowSessionId"),v:n.jsx(Nt,{children:M.sessionId})}),n.jsx(Qe,{k:o("sessionInfo.rowProviderType"),v:n.jsx(Nt,{children:M.providerType})}),M.transport&&n.jsx(Qe,{k:o("sessionInfo.rowTransport"),v:M.transport}),E&&n.jsx(Qe,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(Nt,{children:E})}),M.spawnedAtMs?n.jsx(Qe,{k:o("sessionInfo.rowSpawnedAt"),v:Rm(M.spawnedAtMs)}):null,M.providerSessionId&&n.jsx(Qe,{k:o("sessionInfo.rowProviderSessionId"),v:n.jsx(Nt,{children:M.providerSessionId})}),(s==null?void 0:s.connectionState)&&n.jsx(Qe,{k:o("sessionInfo.rowConnection"),v:s.connectionState})]}),I&&(I.meshId||I.taskId||I.coordinatorSessionId)&&n.jsxs(Ts,{title:o("sessionInfo.sectionMeshWorker"),children:[I.meshId&&n.jsx(Qe,{k:o("sessionInfo.rowMeshId"),v:n.jsx(Nt,{children:I.meshId})}),I.taskId&&n.jsx(Qe,{k:o("sessionInfo.rowTaskId"),v:n.jsx(Nt,{children:I.taskId})}),I.coordinatorSessionId&&n.jsx(Qe,{k:o("sessionInfo.rowCoordinator"),v:n.jsx(Nt,{children:I.coordinatorSessionId})})]}),(M==null?void 0:M.launch)&&n.jsxs(Ts,{title:o("sessionInfo.sectionLaunch"),children:[M.launch.command&&n.jsx(Qe,{k:o("sessionInfo.rowCommand"),v:n.jsx(Nt,{children:M.launch.command})}),M.launch.cwd&&n.jsx(Qe,{k:o("sessionInfo.rowWorkingDirectory"),v:n.jsx(Nt,{children:M.launch.cwd})}),Array.isArray(M.launch.args)&&M.launch.args.length>0&&n.jsx(Qe,{k:o("sessionInfo.rowArgs"),v:n.jsx(Nt,{children:M.launch.args.join(" ")})}),Array.isArray(M.launch.extraArgs)&&M.launch.extraArgs.length>0&&n.jsx(Qe,{k:o("sessionInfo.rowExtraArgs"),v:n.jsx(Nt,{children:M.launch.extraArgs.join(" ")})}),Array.isArray(M.launch.extraEnvKeys)&&M.launch.extraEnvKeys.length>0&&n.jsx(Qe,{k:o("sessionInfo.rowExtraEnv"),v:n.jsx(Nt,{children:M.launch.extraEnvKeys.join(", ")})})]}),f&&n.jsxs(Ts,{title:o("sessionInfo.sectionMeshNode"),children:[f.nodeId&&n.jsx(Qe,{k:o("sessionInfo.rowNodeId"),v:n.jsx(Nt,{children:f.nodeId})}),f.workspace&&n.jsx(Qe,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(Nt,{children:f.workspace})}),f.repoRoot&&f.repoRoot!==f.workspace&&n.jsx(Qe,{k:o("sessionInfo.rowRepoRoot"),v:n.jsx(Nt,{children:f.repoRoot})}),f.daemonId&&n.jsx(Qe,{k:o("sessionInfo.rowDaemonId"),v:n.jsx(Nt,{children:f.daemonId})}),f.role&&n.jsx(Qe,{k:o("sessionInfo.rowRole"),v:f.role}),f.machineStatus&&n.jsx(Qe,{k:o("sessionInfo.rowMachineStatus"),v:f.machineStatus}),f.health&&n.jsx(Qe,{k:o("sessionInfo.rowHealth"),v:f.health}),f.isLocalWorktree&&n.jsx(Qe,{k:o("sessionInfo.rowWorktree"),v:f.worktreeBranch?n.jsx(Nt,{children:f.worktreeBranch}):o("common.yes")}),typeof f.launchReady=="boolean"&&n.jsx(Qe,{k:o("sessionInfo.rowLaunchReady"),v:P(f.launchReady)}),f.git&&n.jsx(Qe,{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(Qe,{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(Qe,{k:o("sessionInfo.rowProviders"),v:n.jsx(Nt,{children:f.providers.join(", ")})}),Array.isArray(f.providerPriority)&&f.providerPriority.length>0&&n.jsx(Qe,{k:o("sessionInfo.rowProviderPriority"),v:n.jsx(Nt,{children:f.providerPriority.join(" › ")})})]}),!f&&g&&(w||_)&&n.jsx(Ts,{title:o("sessionInfo.sectionMeshNode"),children:n.jsx("div",{className:"text-text-secondary italic",children:g})}),(u==null?void 0:u.coordinator)&&n.jsxs(Ts,{title:o("sessionInfo.sectionMeshCoordinator"),children:[n.jsx(Qe,{k:o("sessionInfo.rowMeshId"),v:n.jsx(Nt,{children:u.coordinator.meshId})}),u.coordinator.cliType&&n.jsx(Qe,{k:o("sessionInfo.rowCoordinatorCli"),v:u.coordinator.cliType}),u.coordinator.startedAt?n.jsx(Qe,{k:o("sessionInfo.rowStartedAt"),v:Rm(u.coordinator.startedAt)}):null,u.coordinator.injection&&n.jsx(Qe,{k:o("sessionInfo.rowPromptInjection"),v:`${u.coordinator.injection.mode}${u.coordinator.injection.target?` → ${u.coordinator.injection.target}`:""}`}),u.coordinator.mcpConfigPath&&n.jsx(Qe,{k:o("sessionInfo.rowMcpConfig"),v:n.jsx(Nt,{children:u.coordinator.mcpConfigPath})}),u.coordinator.extraSystemPrompt&&n.jsx(Al,{title:o("sessionInfo.blockExtraPrompt"),body:u.coordinator.extraSystemPrompt}),u.coordinator.systemPrompt&&n.jsx(Al,{title:o("sessionInfo.blockFinalPrompt"),body:u.coordinator.systemPrompt})]}),(M==null?void 0:M.runtimeMetadata)!=null&&n.jsx(_1,{meta:M.runtimeMetadata}),p&&n.jsx("div",{className:"font-mono text-xs text-text-secondary break-all",children:p})]})]})]})})}function C1(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 Ts({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 Qe({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 Nt({children:e}){return n.jsx("code",{className:"font-mono text-xs",children:e})}function Pm({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 _1({meta:e}){const{t}=pe("common");if(!e||typeof e!="object")return null;const s=e,r=m=>typeof m=="string"&&m.trim()?m: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(Ts,{title:t("sessionInfo.sectionRuntime"),children:[o&&n.jsx(Qe,{k:t("sessionInfo.rowRuntimeId"),v:n.jsx(Nt,{children:o})}),a&&n.jsx(Qe,{k:t("sessionInfo.rowLifecycle"),v:a}),i&&n.jsx(Qe,{k:t("sessionInfo.rowSurface"),v:i}),l&&n.jsx(Qe,{k:t("sessionInfo.rowRecoveryState"),v:l}),typeof s.restoredFromStorage=="boolean"&&n.jsx(Qe,{k:t("sessionInfo.rowRestoredFromStorage"),v:s.restoredFromStorage?t("common.yes"):t("common.no")}),d!=null&&n.jsx(Qe,{k:t("sessionInfo.rowAttachedClients"),v:String(d)}),n.jsx(Al,{title:t("sessionInfo.blockRawMetadata"),body:A1(e)})]})}function A1(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Al({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 T1=8e3;function I1({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,m=c.useCallback(()=>{if(!e||!t)return;const u=!l;a(u),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(null),T1),r(t,"set_conversation_prefs",{sessionId:e,muted:u}).catch(h=>{console.warn("[conversation-prefs] toggle mute failed",h),a(null)})},[t,l,r,e]);return{available:d,muted:l,toggle:m}}const Jo=220;function Lb({conversation:e,onOpenHistory:t,onOpenRemote:s,onOpenGit:r,className:o,iconSize:a=16}){const{t:i}=pe("common"),{ides:l}=xn(),{sendCommand:d}=xt(),[m,u]=c.useState(!1),[h,p]=c.useState(!1),[b,f]=c.useState(null),x=c.useRef(null),g=c.useRef(null),S=ht(e),w=c.useMemo(()=>{const j=l.find(N=>N.id===e.routeId);return Uf(e,j)},[e,l]),_=I1({sessionId:e.sessionId,daemonId:e.daemonId,muted:!!(w!=null&&w.muted),sendDaemonCommand:d}),k=[];if(t&&k.push({key:"history",label:i("dashboard.header.chatHistory"),icon:n.jsx(Ap,{size:15}),onSelect:()=>t(e)}),s&&!S&&k.push({key:"remote",label:i("dashboard.header.remoteControl"),icon:n.jsx(Hn,{size:15}),onSelect:()=>s(e)}),r&&e.git&&e.daemonId&&e.workspacePath){const j=e.daemonId,N=e.workspacePath;k.push({key:"git",label:i("dashboard.header.openGitStatus"),icon:n.jsx(ol,{size:15}),onSelect:()=>r(j,N)})}_.available&&k.push({key:"mute",label:_.muted?i("conversation.unmuteThis"):i("conversation.muteThis"),icon:_.muted?n.jsx(rl,{size:15}):n.jsx(gs,{size:15}),onSelect:_.toggle,pressed:_.muted}),e.sessionId&&e.daemonId&&k.push({key:"info",label:i("sessionInfo.title"),icon:n.jsx(So,{size:15}),onSelect:()=>p(!0)});const v=c.useCallback((j=!1)=>{var N;u(!1),j&&((N=x.current)==null||N.focus())},[]);if(c.useLayoutEffect(()=>{var A;if(!m||typeof window>"u"){f(null);return}const j=(A=x.current)==null?void 0:A.getBoundingClientRect();if(!j)return;const N=Math.min(Math.max(8,j.right-Jo),window.innerWidth-Jo-8);f({top:j.bottom+6,left:N})},[m]),c.useEffect(()=>{if(!m||typeof window>"u")return;const j=R=>{R.key==="Escape"&&(R.stopPropagation(),v(!0))},N=R=>{var M,E;const P=R.target;P&&((M=x.current)!=null&&M.contains(P)||(E=g.current)!=null&&E.contains(P)||v())},A=()=>v();return window.addEventListener("keydown",j,!0),document.addEventListener("mousedown",N,!0),window.addEventListener("resize",A),()=>{window.removeEventListener("keydown",j,!0),document.removeEventListener("mousedown",N,!0),window.removeEventListener("resize",A)}},[v,m]),c.useEffect(()=>{var j,N;m&&((N=(j=g.current)==null?void 0:j.querySelector('[role="menuitem"]'))==null||N.focus())},[m,b]),k.length===0)return null;const y=j=>{var P;if(j.key!=="ArrowDown"&&j.key!=="ArrowUp")return;j.preventDefault();const N=Array.from(((P=g.current)==null?void 0:P.querySelectorAll('[role="menuitem"]'))??[]),A=N.indexOf(document.activeElement),R=N[(A+(j.key==="ArrowDown"?1:-1)+N.length)%N.length];R==null||R.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":m,onClick:()=>u(j=>!j),className:o??"btn btn-secondary btn-sm",style:{pointerEvents:"auto"},children:n.jsx(Ip,{size:a})}),m&&typeof document<"u"&&Wn.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:Jo}:{top:-9999,left:-9999,width:Jo,visibility:"hidden"},children:k.map(j=>n.jsxs("button",{type:"button",role:"menuitem","data-menu-item":j.key,"aria-pressed":j.pressed,onClick:()=>{v(),j.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",j.pressed&&"text-amber-500"),children:[n.jsx("span",{className:"flex w-4 shrink-0 justify-center","aria-hidden":!0,children:j.icon}),n.jsx("span",{className:"min-w-0 truncate",children:j.label})]},j.key))}),document.body),h&&e.sessionId&&e.daemonId&&n.jsx(N1,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e,onClose:()=>p(!1)})]})}function Ob(e){const{t}=pe("common");if(!e.role)return null;const s=r_(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 Rd(e){var s;const t=bb(e);return((s=Ob(t))==null?void 0:s.full)??null}function vs({conversation:e,className:t,size:s=12}){const r=bb(e),o=Ob(r);return!pb(e)||!o?null:n.jsx("span",{role:"img","aria-label":o.full,title:o.full,"data-mesh-role":r.role,className:ct("mesh-role-icon",`is-${r.role}`,t),children:n.jsx(Ln,{size:s})})}function Tl(){return or(()=>import("./DashboardMeshGraphDialog-BKOLRm3R.js"),__vite__mapDeps([3,1,4,5]))}const M1=c.lazy(Tl);function R1({onClose:e}){const{t}=pe(),s=t("connection.loadingShort");return n.jsx(pr,{onClose:e,size:"sm",ariaLabel:s,children:n.jsx("div",{className:"flex items-center justify-center p-8","data-testid":"mesh-graph-dialog-loading",children:n.jsx(Zt,{label:s})})})}function Pd(e){return n.jsx(c.Suspense,{fallback:n.jsx(R1,{onClose:e.onClose}),children:n.jsx(M1,{...e})})}function $b({conversation:e,onOpenMeshGraph:t,showLabel:s=!1,iconSize:r=14,className:o}){const{t:a}=pe("common"),i=Rd(e);if(!t||!fb(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:()=>{Tl()},onFocus:()=>{Tl()},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(Ln,{size:r}),s&&n.jsx("span",{className:"hidden lg:inline",children:a("dashboard.header.meshGraph")})]})}function P1({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 Em({value:e}){return e?n.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Dm({notification:e,shortcutIndex:t,onOpen:s,onMarkRead:r,onMarkUnread:o,onDelete:a}){const{t:i}=pe(),l=hi(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:m=>{m.stopPropagation(),r()},children:i("notification.markRead")}):n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:m=>{m.stopPropagation(),o()},children:i("notification.markUnread")}),n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:m=>{m.stopPropagation(),a()},children:i("notification.delete")})]})]})}function E1({activeConv:e,wsStatus:t,isConnected:s,conversations:r,onOpenHistory:o,onOpenRemote:a,onStopCli:i,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:h,onShowAllHidden:p,onResetPanelsToMain:b,inboxOpen:f,onInboxOpenChange:x,hiddenOpen:g,onHiddenOpenChange:S,onOpenNewSession:w,onOpenDashboardGuide:_,guideNudgeVisible:k=!1,actionShortcuts:v,notifications:y,notificationUnreadCount:j,onOpenNotification:N,onMarkNotificationRead:A,onMarkNotificationUnread:R,onDeleteNotification:P,onOpenGitDialog:M,onOpenMeshGraph:E}){const{t:C}=pe(),{ides:I,p2pStates:O={},usesP2P:D=!0}=xn(),F=!!e&&ht(e),z=l||(e?Of(e)?"terminal":"chat":null),[Z,W]=c.useState(!1),[T,$]=c.useState(!1),H=c.useRef(null),q=c.useRef(null),U=c.useRef(null),K=I.filter(B=>B.type==="adhdev-daemon"),oe=P1({wsStatus:t,isConnected:s,daemonCount:K.length,p2pStates:O,usesP2P:D}),ke=C(oe.titleKey),J=oe.subtitleKey?C(oe.subtitleKey,oe.subtitleParams):null,ye=oe.tone==="connected"?"#22c55e":oe.tone==="limited"?"#eab308":"#ef4444",ae=oe.tone==="connected"?"0 0 4px #22c55e80":oe.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",re=c.useMemo(()=>y.filter(B=>!B.readAt),[y]),de=c.useMemo(()=>y.filter(B=>!!B.readAt),[y]),ne=c.useMemo(()=>re.slice(0,9),[re]),ie=j;c.useEffect(()=>{if(!f)return;const B=Q=>{var ue;(ue=q.current)!=null&&ue.contains(Q.target)||x(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[f,x]),c.useEffect(()=>{if(!g)return;const B=Q=>{var ue;(ue=U.current)!=null&&ue.contains(Q.target)||S(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[g,S]),c.useEffect(()=>{if(!g&&!f)return;const B=Q=>{if(!Q.altKey)return;const ue=Q.code.match(/^Digit([1-9])$/);if(!ue)return;const Re=Number(ue[1])-1,Le=g?u[Re]:void 0,Pe=f?ne[Re]:void 0;if(!(!Le&&!Pe)){if(Q.preventDefault(),Q.stopPropagation(),Le){h==null||h(Le),S(!1);return}Pe&&(N(Pe),x(!1))}};return window.addEventListener("keydown",B,!0),()=>window.removeEventListener("keydown",B,!0)},[u,g,f,ne,S,x,N,h]),c.useEffect(()=>{const B=u.length;if(H.current===null){H.current=B;return}B>H.current&&$(!0),H.current=B},[u.length]);const _e=()=>$(!1),G=B=>{if(!B)return;const Q=r.find(ue=>ue.tabKey===B);Q&&(m==null||m(Q))};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:C("dashboard.header.title")}),e&&n.jsx(vs,{conversation:e,size:14,className:"header-title-mobile-role"}),n.jsx("span",{className:"header-title-mobile",children:e?wt(e):C("dashboard.header.title")}),n.jsx(Gt,{content:J?`${ke} · ${J}`:ke,className:"ml-0.5",children:n.jsx("span",{role:"img","aria-label":ke,"data-connection-tone":oe.tone,className:"header-title-status-dot",style:{background:ye,boxShadow:ae}})})]}),n.jsx("div",{className:"header-subtitle flex items-center",children:w&&n.jsx("button",{type:"button",onClick:w,className:"btn btn-secondary btn-sm ml-2",title:`${C("paneGroup.newSession")}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":C("paneGroup.newSession"),children:n.jsx(po,{size:14})})})]})})}),n.jsxs("div",{className:"flex gap-2 items-center",children:[_&&n.jsxs("button",{type:"button",onClick:_,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:C("dashboard.header.guide"),"aria-label":C("dashboard.header.guideOpen"),children:[n.jsx("span",{className:"font-semibold leading-none",children:"?"}),k&&n.jsx("span",{children:C("dashboard.header.guideShort")})]}),e&&n.jsxs("div",{className:"dashboard-header-actions-group","data-testid":"dashboard-pane-toolbar",children:[n.jsx(Nd,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),F&&d&&z&&n.jsx(kb,{mode:z,onChange:d,compact:!0}),F&&i&&n.jsx("button",{type:"button",onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:C("dashboard.header.stopCliProcess"),"aria-label":C("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(Pt,{size:14})}),n.jsx($b,{conversation:e,onOpenMeshGraph:E,showLabel:!0}),n.jsx(Lb,{conversation:e,onOpenHistory:o,onOpenRemote:a?()=>a():void 0,onOpenGit:M,iconSize:14})]}),n.jsxs("div",{className:"dashboard-header-inbox",ref:q,children:[n.jsxs("div",{className:`dashboard-header-hidden${Z?" is-drop-target":""}${T?" hidden-spawn-flash":""}${(u??[]).some(Bs)?" hidden-generating-spin":""}`,onAnimationEnd:_e,ref:U,onDragEnter:B=>{B.dataTransfer.types.includes("text/tab-key")&&(B.preventDefault(),W(!0))},onDragOver:B=>{B.dataTransfer.types.includes("text/tab-key")&&(B.preventDefault(),B.dataTransfer.dropEffect="move",W(!0))},onDragLeave:B=>{B.currentTarget.contains(B.relatedTarget)||W(!1)},onDrop:B=>{const Q=B.dataTransfer.getData("text/tab-key");B.preventDefault(),W(!1),G(Q)},children:[n.jsxs("button",{type:"button",onClick:()=>S(!g),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${C("dashboard.hidden.title")}${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. ${C("dashboard.hidden.dragHint")}`,children:[n.jsx(li,{size:16}),u.length>0&&n.jsx("span",{className:`dashboard-header-hidden-badge${T?" hidden-badge-pop":""}`,children:u.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:C("dashboard.hidden.title")}),n.jsx(Em,{value:v==null?void 0:v.toggleHiddenTabs})]}),n.jsxs("div",{className:"dashboard-header-hidden-actions",children:[b&&n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:b,children:C("dashboard.hidden.resetPanels")}),u.length>0&&p&&n.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{p(),S(!1)},children:C("dashboard.hidden.restoreAll")})]})]}),e&&m&&n.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[n.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[n.jsx("span",{className:"dashboard-header-hidden-current-label",children:C("dashboard.hidden.hideCurrentTab")}),n.jsx(Em,{value:v==null?void 0:v.hideCurrentTab})]}),n.jsx("span",{className:"dashboard-header-hidden-current-title",children:wt(e)})]}),u.length>0?n.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(B=>n.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(B),S(!1)},children:[n.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[Bs(B)&&n.jsx(Zt,{size:12,thickness:2,color:"success",label:C("dashboard.header.generating")}),n.jsx(vs,{conversation:B,size:12}),wt(B)]}),n.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(B)<9?n.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(B)+1]}):null,To(B)]})]},B.tabKey))}):n.jsx("div",{className:"dashboard-header-inbox-empty",children:C("dashboard.hidden.empty")})]})]}),n.jsxs("button",{type:"button",onClick:()=>x(!f),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:C("dashboard.header.activityInbox"),children:[n.jsx(gs,{size:16}),ie>0&&n.jsx("span",{className:"dashboard-header-inbox-badge",children:ie})]}),f&&n.jsxs("div",{className:"dashboard-header-inbox-popover",children:[re.length>0&&n.jsxs("div",{className:"dashboard-header-inbox-section",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title",children:C("dashboard.inbox.unread")}),re.map(B=>n.jsx(Dm,{notification:B,shortcutIndex:ne.indexOf(B)>=0?ne.indexOf(B)+1:void 0,onOpen:()=>N(B),onMarkRead:()=>A(B.id),onMarkUnread:()=>R(B.id),onDelete:()=>P(B.id)},B.id))]}),de.length>0&&n.jsxs("div",{className:"dashboard-header-inbox-section",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title",children:C("dashboard.inbox.read")}),de.map(B=>n.jsx(Dm,{notification:B,onOpen:()=>N(B),onMarkRead:()=>A(B.id),onMarkUnread:()=>R(B.id),onDelete:()=>P(B.id)},B.id))]}),y.length===0&&n.jsx("div",{className:"dashboard-header-inbox-empty",children:C("dashboard.inbox.empty")})]})]})]})]})}function dn(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function D1(e,t){return String(e||"")!==String(t||"")}function L1(e,t={}){const s=String(t.textQuery||"").trim().toLowerCase(),r=String(t.workspaceQuery||"").trim().toLowerCase(),o=String(t.modelQuery||"").trim().toLowerCase(),a=!!t.resumableOnly;return!s&&!r&&!o&&!a?e:e.filter(i=>!(a&&!i.canResume||s&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
50
+ `).length:0," lines)"]})]}),m&&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:J.screen||"(empty)"})]})]})]})]})})})}function Sb(e,t){if(typeof window>"u")return!1;try{return window[e]===!0||window.localStorage.getItem(t)==="1"}catch{return window[e]===!0}}function w_(){return Sb("__ADHDEV_DEBUG_SPEC__","adhdev_debug_spec")}function S_(){return Sb("__ADHDEV_DEBUG_MOBILE_BUNDLE__","adhdev_debug_mobile_bundle")}function k_({activeConv:e,clearToken:t=0,terminalRef:s,handleSendChat:r,isSendingChat:o=!1,sendFeedbackMessage:a=null,isVisible:i=!0,isInputActive:l=!0}){var Vt;const{t:d}=pe("common");xn();const{sendPtyInput:m}=xt(),[u,h]=c.useState(!1),p=c.useRef(!1);p.current=u;const[b,f]=c.useState("Runtime terminal unavailable"),[x,g]=c.useState(!1),[S,w]=c.useState(null),[_,k]=c.useState(!1),[v,y]=c.useState(!1),[j,N]=c.useState(1),[A,R]=c.useState(!1),[P,M]=c.useState(!1),[E,C]=c.useState(!1),[I,O]=c.useState(!1),[D,F]=c.useState(!1),z=w_(),[Z,W]=c.useState({width:0,height:0}),[T,$]=c.useState({width:0,height:0}),[H,q]=c.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[U,K]=c.useState(null),oe=c.useRef(null),ke=c.useRef(null),J=c.useRef(!1),ye=c.useRef(!1),ae=c.useRef(i),re=c.useRef(0),de=c.useRef(!1),ne=c.useRef(""),ie=c.useRef(null),_e=c.useRef(!1),G=c.useRef(!1),B=c.useRef(null),Q=c.useRef(null),ue=c.useRef(null),Re=32*1024,Le=()=>{var xe,Ie,De,Ve;return((Ie=(xe=oe.current)==null?void 0:xe.ownerDocument)==null?void 0:Ie.defaultView)||((Ve=(De=ke.current)==null?void 0:De.ownerDocument)==null?void 0:Ve.defaultView)||window},Pe=xe=>{const Ie=Le();return{ownerWindow:Ie,frameId:Ie.requestAnimationFrame(xe)}},Fe=()=>{const xe=B.current;if(xe){try{xe.ownerWindow.cancelAnimationFrame(xe.frameId)}catch{}B.current=null}},X=()=>{const xe=Q.current;if(xe){try{xe.ownerWindow.clearTimeout(xe.timeoutId)}catch{}Q.current=null}},ve=()=>{const xe=ue.current;if(xe){try{xe.ownerWindow.clearTimeout(xe.timeoutId)}catch{}ue.current=null}},Se=()=>{i&&B.current===null&&(B.current=Pe(()=>{Ct()}))},Ce=e.tabKey,L=e.sessionId||"",Y=e.daemonId||((Vt=e.routeId)==null?void 0:Vt.split(":")[0])||e.routeId||"",ce=Ni(e),te=u?Kf(e)||a:b,fe=u&&a||null,V=YC,se=QC,he=.05,Me=()=>{const xe=T.width,Ie=T.height;if(!Number.isFinite(Z.width)||Z.width<=0||!Number.isFinite(Z.height)||Z.height<=0||!Number.isFinite(xe)||xe<=0||!Number.isFinite(Ie)||Ie<=0)return 1;const De=Z.width/xe,Ve=Z.height/Ie;return Number(Math.min(se,Math.max(V,Math.min(De,Ve))).toFixed(2))},Ee=Me(),Te=J.current&&j>Ee,Ne=Number.isFinite(T.width)&&T.width>0?Math.max(Z.width,Math.round(T.width*j)):Z.width,Ue=Number.isFinite(T.height)&&T.height>0?Math.max(Z.height,Math.round(T.height*j)):Z.height,$e=()=>{Pe(()=>{const xe=ke.current;xe&&(xe.scrollLeft=0,xe.scrollTop=xe.scrollHeight-xe.clientHeight)})},ot=()=>{var xe,Ie;re.current=0,de.current=!1,ne.current="",ie.current=null,_e.current=!1,G.current=!1,J.current||(ye.current=!1,N(1)),B.current!==null&&Fe(),h(!1),f("Runtime terminal unavailable"),ve(),X(),w(null),K(null),R(!1),g(!1),k(!1),y(!1),(Ie=(xe=s.current)==null?void 0:xe.reset)==null||Ie.call(xe)},at=()=>{var xe,Ie;re.current=0,de.current=!1,ne.current="",ie.current=null,_e.current=!1,G.current=!1,B.current!==null&&Fe(),h(!0),f(""),ve(),X(),w(null),K(null),R(!1),g(!1),k(!1),y(!1),(Ie=(xe=s.current)==null?void 0:xe.reset)==null||Ie.call(xe)},pt=()=>{G.current&&(G.current=!1,Pe(()=>{var xe,Ie;(Ie=(xe=s.current)==null?void 0:xe.scrollToTop)==null||Ie.call(xe)}))},Ct=()=>{if(B.current=null,!i)return;const xe=ne.current;if(!xe)return;const Ie=xe.slice(0,Re);ne.current=xe.slice(Ie.length);const De=s.current;if(!De){ne.current=Ie+ne.current,Se();return}De.write(Ie,()=>{if(ne.current.length>0){Se();return}pt()})},_t=xe=>{xe&&(ne.current+=xe,Se())},ee=(xe,Ie=0,De,Ve,Ye={})=>{var et,kt,bt,Ht;const ut=!!Ye.force;!ut&&Ie>0&&re.current>=Ie||!ut&&Ie===0&&de.current||(re.current=Ie,Ie>0&&k(!0),h(!0),f(""),typeof De=="number"&&typeof Ve=="number"&&De>0&&Ve>0&&((kt=(et=s.current)==null?void 0:et.resize)==null||kt.call(et,De,Ve)),ne.current="",(Ht=(bt=s.current)==null?void 0:bt.reset)==null||Ht.call(bt),xe?_t(xe):pt())};c.useEffect(()=>{ot()},[L]),c.useEffect(()=>{var Ie;if(!L)return;const xe=((Ie=Dt.onRuntimeEvent)==null?void 0:Ie.call(Dt,L,De=>{if(!(!De||De.sessionId!==L)){if(De.type==="runtime_snapshot"){if(!i){ie.current={text:De.text||"",seq:De.seq||0,cols:De.cols,rows:De.rows,force:!!De.force};return}ee(De.text||"",De.seq||0,De.cols,De.rows,{force:!!De.force});return}if(De.type==="session_output"){de.current=!0,typeof De.seq=="number"&&(re.current=Math.max(re.current,De.seq),De.seq>0&&k(!0)),p.current||h(!0),p.current||f(""),typeof De.data=="string"&&_t(De.data);return}if(De.type==="session_cleared"){if(!i){_e.current=!0,ne.current="",ie.current=null;return}at();return}if(De.type==="session_io_error"){const Ve=typeof De.error=="string"&&De.error?De.error:typeof De.reason=="string"&&De.reason?De.reason:"unknown error";h(!1),f(`Runtime input failed: ${Ve}`);return}}},Y))||(()=>{});return()=>{xe()}},[Y,L,s,i]);const le=async(xe={})=>{var Ie;if(!Y||!L)return{success:!1,error:"daemonId and sessionId are required"};xe.preserveStatus||f(xe.loadingMessage||"Loading runtime terminal...");try{const De=await((Ie=Dt.requestRuntimeSnapshot)==null?void 0:Ie.call(Dt,Y,L,{sinceSeq:xe.sinceSeq,force:xe.force}));return De&&De.success===!1?(xe.preserveStatus||(h(!1),f(`Runtime terminal unavailable: ${De.error}`)),De):De||{success:!0}}catch(De){const Ve=(De==null?void 0:De.message)||String(De);return xe.preserveStatus||(h(!1),f(`Runtime terminal unavailable: ${Ve}`)),{success:!1,error:Ve}}},be=async xe=>{var ut,et;const Ie=((ut=oe.current)==null?void 0:ut.ownerDocument)||document,De=Ie.defaultView||window,Ve=(et=De.navigator)==null?void 0:et.clipboard;if(Ve!=null&&Ve.writeText&&De.isSecureContext)try{return await Ve.writeText(xe),!0}catch{}let Ye=null;try{return Ye=Ie.createElement("textarea"),Ye.value=xe,Ye.setAttribute("readonly","true"),Ye.style.position="fixed",Ye.style.left="-9999px",Ye.style.top="0",Ie.body.appendChild(Ye),Ye.focus(),Ye.select(),Ie.execCommand("copy")}catch{return!1}finally{Ye==null||Ye.remove()}},Ae=xe=>{X(),K(xe);const Ie=Le();Q.current={ownerWindow:Ie,timeoutId:Ie.setTimeout(()=>{Q.current=null,K(De=>De===xe?null:De)},2200)}},me=xe=>{ve(),w(xe);const Ie=Le();ue.current={ownerWindow:Ie,timeoutId:Ie.setTimeout(()=>{ue.current=null,w(De=>De===xe?null:De)},2200)}},Be=async()=>{var Ye,ut,et,kt;const xe=((ut=(Ye=s.current)==null?void 0:Ye.getSelection)==null?void 0:ut.call(Ye))||"",Ie=((kt=(et=s.current)==null?void 0:et.getVisibleText)==null?void 0:kt.call(et))||"",De=xe.trimEnd()||Ie.trimEnd();if(!De){Ae("Nothing to copy");return}if(!await be(De)){Ae("Copy failed");return}Ae(xe.trimEnd()?"Copied selection":"Copied visible terminal")},nt=xe=>{if(!u||!i)return;((m==null?void 0:m(Y,L,xe))??!1)||Ae("Terminal input failed")},qe=xe=>{nt(XC({ctrl:P,alt:E,shift:I},xe)),M(!1),C(!1),O(!1)},lt=async()=>{if(x)return;g(!0),w("Loading older terminal output..."),G.current=!0;const xe=await le({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:u});if(g(!1),(xe==null?void 0:xe.success)===!1){G.current=!1,w(`Older terminal output unavailable: ${xe.error}`);return}y(!0),me("Older terminal output loaded"),Pe(()=>{var Ie;(Ie=s.current)==null||Ie.bumpResize()})};c.useEffect(()=>{var Ie,De;if(!L)return;Y&&((Ie=Dt.getState)==null?void 0:Ie.call(Dt,Y))==="connected"&&le();const xe=(De=Dt.onStateChange)==null?void 0:De.call(Dt,(Ve,Ye)=>{Ve!==Y||Ye!=="connected"||le()});return()=>{xe==null||xe()}},[Y,L,s]),c.useEffect(()=>{t&&ot()},[t,Ce,s]),c.useEffect(()=>{var Ve,Ye;const xe=oe.current,Ie=(Ye=(Ve=xe==null?void 0:xe.ownerDocument)==null?void 0:Ve.defaultView)==null?void 0:Ye.ResizeObserver;if(!xe||!Ie)return;const De=new Ie(ut=>{const et=ut[0];if(!et)return;const{width:kt,height:bt}=et.contentRect;W(Ht=>{const Yt=Math.round(kt),sn=Math.round(bt);return Ht.width===Yt&&Ht.height===sn?Ht:{width:Yt,height:sn}})});return De.observe(xe),()=>De.disconnect()},[]),c.useEffect(()=>{if(J.current)return;const xe=Me();!Number.isFinite(xe)||xe<=0||N(Ie=>ye.current?xe<Ie-he?xe:Ie:(ye.current=!0,xe))},[T.height,T.width,Z.height,Z.width]),c.useEffect(()=>{Te&&$e()},[Te,Ue,Ne]),c.useEffect(()=>{var De;const xe=ae.current;if(ae.current=i,!i)return;xe||y(!1),_e.current&&(_e.current=!1,at());const Ie=ie.current;Ie&&(ie.current=null,ee(Ie.text,Ie.seq,Ie.cols,Ie.rows,{force:!!Ie.force})),Y&&L&&((De=Dt.getState)==null?void 0:De.call(Dt,Y))==="connected"&&le(),ne.current&&B.current===null&&Se(),Pe(()=>{var Ve;(Ve=s.current)==null||Ve.bumpResize()})},[Y,i,L]),c.useEffect(()=>()=>{B.current!==null&&Fe(),X(),ve()},[]),c.useEffect(()=>{const xe=Ve=>{var ut;const Ye=Ve.detail;Ye!=null&&Ye.sessionId&&Ye.sessionId!==L||u&&((ut=s.current)==null||ut.bumpResize())},Ie=Le(),De=Ie===window?[window]:[window,Ie];for(const Ve of De)Ve.addEventListener("adhdev:fit-cli-terminal",xe);return()=>{for(const Ve of De)Ve.removeEventListener("adhdev:fit-cli-terminal",xe)}},[u,L,s]);const ft=u&&_&&!v&&(H.atTop||!H.canScroll)||x||!!S;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{ref:oe,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[ft&&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:()=>{lt()},disabled:!L||x,title:d("terminal.replayScrollbackHint"),children:d(x?"terminal.loadingOlder":"terminal.loadOlderOutput")}),S&&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:S})]}),n.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[U&&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:U}),z&&n.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-2xs font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>F(xe=>!xe),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:()=>{Be()},disabled:!u,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:()=>R(xe=>!xe),disabled:!u,"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:()=>R(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),n.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",P,M],["Alt",E,C],["Shift",I,O]].map(([xe,Ie,De])=>n.jsx("button",{type:"button","aria-pressed":Ie,className:`h-9 rounded-lg border text-xs font-semibold transition-colors ${Ie?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>De(Ve=>!Ve),children:xe},xe))}),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:()=>qe("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:()=>qe("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:()=>qe("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:()=>qe("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:()=>qe("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:()=>qe("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:()=>qe("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:()=>nt(""),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:()=>qe("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:()=>qe("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:()=>{J.current=!0,N(xe=>{const Ie=Math.max(Ee,Number((xe-.1).toFixed(2)));return Ie>Ee&&$e(),Ie})},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:()=>{J.current=!0,N(xe=>{const Ie=Math.min(se,Number((xe+.1).toFixed(2)));return Ie>Ee&&$e(),Ie})},title:d("terminal.growViewport"),children:"+"})]}),n.jsx("div",{ref:ke,className:Te?"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:Ue>0?`${Ue}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:n.jsx("div",{style:{width:T.width>0?`${T.width}px`:"100%",height:T.height>0?`${T.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:j},children:n.jsx(Qp,{ref:s,readOnly:!u||!i,sizingMode:"measured",onViewportMetrics:$,onScrollMetrics:q,onInput:xe=>{!u||(m==null||m(Y,L,xe))}})})})}),!u&&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(Af,{contextKey:e.tabKey,panelLabel:wt(e),isSending:o,isBusy:!!ce,statusMessage:te,inlineStatusMessage:fe,onSend:async xe=>ce?!1:r(xe),isActive:l&&i,showControlsToggle:!1,animateVisibility:!1}),D&&n.jsx(v_,{activeConv:e,onClose:()=>F(!1)})]})}const j_=5e3,N_=12e3,C_=15e3;function __(e){return e==="disconnected"||e==="reconnecting"}function A_({wsStatus:e,showReconnected:t,loginUrl:s,onReconnect:r,reconnectDelayMs:o=j_,reconnectActionDelayMs:a=N_}){const{t:i}=pe(),l=__(e),[d,m]=c.useState(()=>!l||o<=0),[u,h]=c.useState(()=>!l||a<=0),p=c.useRef(!1),[b,f]=c.useState(!1);c.useEffect(()=>{if(!l){m(!1);return}if(p.current=!1,o<=0){p.current=!0,m(!0);return}m(!1);const A=setTimeout(()=>{p.current=!0,m(!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),C_);return()=>clearTimeout(A)},[b]);const x=()=>{f(!0),r==null||r()},g=l?d:e==="offline"||e==="auth_failed",S=!!(r&&e!=="auth_failed"&&(!l||u)),w=c.useMemo(()=>!t||e!=="connected"?!1:o<=0||p.current,[o,t,e]),_=e==="auth_failed"?"red":e==="offline"?"orange":"accent",k={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)"},j="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",N={transform:"translateX(-50%)"};return n.jsxs(n.Fragment,{children:[g&&n.jsx("div",{className:j,style:N,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:k[_],border:v[_],color:y[_]},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"))]}),S&&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(Zt,{size:11,thickness:2,color:"muted"}),i(b?"connection.reconnecting":"connection.reconnectNow")]})]})}),w&&n.jsx("div",{className:j,style:N,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 T_(){const e=c.useSyncExternalStore(GN,sm,sm),{t}=pe("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 kb({mode:e,onChange:t,compact:s=!1}){const{t:r}=pe("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(cd,{size:o}):n.jsx(Cn,{size:o})})}function I_(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 M_(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 R_(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 Nd({git:e,className:t="",compact:s=!1}){const r=I_(e),o=M_(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 ${R_(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 Ns=8,km=6;function P_(e,t,s){const r=Math.max(Ns,s.width-t.width-Ns),o=e.left+e.width/2-t.width/2,a=Math.min(Math.max(Ns,o),r),i=e.bottom+km,l=i+t.height<=s.height-Ns,d=e.top-km-t.height;return!l&&d>=Ns?{top:d,left:a,placement:"above"}:{top:Math.max(Ns,Math.min(i,s.height-t.height-Ns)),left:a,placement:"below"}}function Cd(){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}),[]),m=c.useCallback(h=>r(p=>p.peeking===h?p:{...p,peeking:h}),[]),u=c.useCallback(()=>{const h=e.current,p=t.current;if(!h||!p||typeof window>"u")return;const b=h.getBoundingClientRect(),f=p.getBoundingClientRect();a(P_({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}u()},[i,u]),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,S;const x=f.target;x&&((g=e.current)!=null&&g.contains(x)||(S=t.current)!=null&&S.contains(x)||l())},b=()=>u();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,u]),{anchorRef:e,popoverRef:t,open:i,pinned:s.pinned,position:o,close:l,togglePinned:d,setPeeking:m}}function _d({id:e,popoverRef:t,position:s,children:r,className:o,role:a="tooltip",ariaLabel:i}){return typeof document>"u"?null:Wn.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 jb(e){return e==null||e===!1||e===""}function tt({content:e,label:t,size:s=13,className:r,popoverClassName:o}){const{t:a}=pe("common"),i=c.useId(),l=`${i}-pop`,d=`${i}-desc`,{anchorRef:m,popoverRef:u,open:h,position:p,togglePinned:b,setPeeking:f}=Cd();return jb(e)?null:n.jsxs("span",{className:"inline-flex items-center align-middle",children:[n.jsx("button",{ref:x=>{m.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(So,{size:s})}),n.jsx("span",{id:d,className:"sr-only",children:e}),h&&n.jsx(_d,{id:l,popoverRef:u,position:p,className:o,children:e})]})}function Gt({content:e,children:t,className:s,popoverClassName:r}){const o=c.useId(),a=`${o}-pop`,i=`${o}-desc`,{anchorRef:l,popoverRef:d,open:m,position:u,togglePinned:h,setPeeking:p}=Cd();if(jb(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}),m&&n.jsx(_d,{id:a,popoverRef:d,position:u,className:r,children:e})]})}function R5({children:e,content:t,label:s,className:r,popoverClassName:o}){const i=`${c.useId()}-pop`,{anchorRef:l,popoverRef:d,open:m,position:u,togglePinned:h}=Cd();return n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:p=>{l.current=p},type:"button","aria-label":s,"aria-expanded":m,"aria-haspopup":"dialog","aria-controls":m?i:void 0,onClick:p=>{p.preventDefault(),p.stopPropagation(),h()},className:r,children:e}),m&&n.jsx(_d,{id:i,popoverRef:d,position:u,role:"dialog",ariaLabel:s,className:ct("whitespace-normal",o),children:t})]})}function Nb({value:e,live:t=!0,fallback:s="",className:r}){const{i18n:o}=pe("common"),[,a]=c.useState(0),i=ko(e);if(c.useEffect(()=>{if(!t||i===null||typeof window>"u")return;const d=window.setInterval(()=>a(m=>m+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(Gt,{content:No(i,{locale:l,seconds:!0}),children:n.jsx("time",{dateTime:new Date(i).toISOString(),className:r,children:Ea(i,{locale:l})})})}async function Cb(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 _b({value:e,label:t,className:s}){const{t:r}=pe("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 Cb(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 Ad({rows:e=[],children:t,summary:s,className:r,summaryClassName:o}){const{t:a}=pe("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(_b,{value:l.value})]})]},l.label)),t]})]})}function Ab(e){const t=e.replace(/[\\/]+$/,""),s=t.split(/[\\/]/);return s[s.length-1]||t||e}const E_=c.createContext(null);function Td(){return c.useContext(E_)}function D_(e){const t=e.replace(/^(daemon_|standalone_)/,"");return t.length<=20?t:`${t.slice(0,17)}…`}function L_(e){return qx(e)}function O_(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 $_(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 Ba(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=O_(e);return t.outOfSync?"degraded":t.dirty||$_(e)?"dirty":"online"}function F_(e,t){const s=t?Ba(t):void 0;return!e||e==="unknown"?s:e}function H_(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(Ra).filter(i=>i!==null);if(a.length>0)return a}const s=Xe(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=Ra(r);return o?[o]:void 0}function B_(e){const t=Xe(e.connection);return Object.keys(t).length>0?t:void 0}function W_(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 Tb(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 jm(e){var r,o,a,i,l,d;let t=0;const s=e.git;return Tb(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+=Zl(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 U_(e,t){var f,x,g,S;const s=jm(e),o=jm(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,m=(((g=o.activeSessionDetails)==null?void 0:g.length)??0)>0?o.activeSessionDetails:a.activeSessionDetails,u=(((S=o.providerPriority)==null?void 0:S.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")?Ba(i):o.health,providers:l??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...h?{connection:h}:{},...i?{git:i}:{}},b=Xe(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 K_=new Set(["self","local","member_push","coordinator_probe","none"]);function Cl(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Nm(e){const t=Xe(e),s=je(t.source);if(!s||!K_.has(s))return null;const r=je(t.lastRefreshError);return{source:s,observedAt:Cl(t.observedAt),refreshing:t.refreshing===!0,unreachableSince:Cl(t.unreachableSince),...r?{lastRefreshError:r}:{}}}function Ib(e){const t=Xe(e),s=je(t.nodeId,t.id);if(!s)return null;const r=Xe(t.cachedStatus),o=L_(t),a=o?void 0:pa(Xe(t.git),t)??pa(t,t),i=o??a,l=i?void 0:pa(Xe(r.git),t),d=i??l,m=je(t.machineStatus,t.machine_status,r.machineStatus,r.machine_status),u=je(t.health),h=o?Ba(d):F_(u,i)||(d?Ba(d):void 0)||je(r.health)||m||je(t.status)||"unknown",b=(o?void 0:je(t.error))??(i?void 0:je(r.error)),f=H_(t),x=Yi(t.activeSessions),g=(f==null?void 0:f.map(N=>N.sessionId))??[],S=Yi(t.providerPriority),w=qt(t.gitProbePending,t.git_probe_pending),_=i?void 0:w,k=B_(t),v=Xe(t.branchConvergence??t.branch_convergence),y=k==null?void 0:k.state,j=o&&(!(k!=null&&k.reported)||y==="unknown")?W_(k):k;return{nodeId:s,machineLabel:je(t.machineLabel,t.machine_label,t.hostname)||D_(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)}:{},...m?{machineStatus:m}:{},...qt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:qt(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}:{},..._!==void 0?{gitProbePending:_}:{},providers:Yi(t.providers),activeSessions:x.length>0?x:g,...f&&f.length>0?{activeSessionDetails:f}:{},...S.length>0?{providerPriority:S}:{},...qt(t.launchReady)!==void 0?{launchReady:qt(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)}:{},...j?{connection:j}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...t.scheduling&&typeof t.scheduling=="object"?{scheduling:t.scheduling}:{},...qt(t.autoFastForwardEligible,t.auto_fast_forward_eligible)===!0?{autoFastForwardEligible:!0}:{},...t.worktreeBootstrap&&typeof t.worktreeBootstrap=="object"?{worktreeBootstrap:t.worktreeBootstrap}:{},...t.staleDaemonBuild&&typeof t.staleDaemonBuild=="object"?{staleDaemonBuild:t.staleDaemonBuild}:{},...t.providerVersions&&typeof t.providerVersions=="object"&&!Array.isArray(t.providerVersions)?{providerVersions:t.providerVersions}:{},...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}:{},...Nm(t.gitObservation)?{gitObservation:Nm(t.gitObservation)}:{},...Cm(t.heldRuntime??t.held_runtime)?{heldRuntime:Cm(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 q_=new Set(["member_push","coordinator_probe","none"]);function Cm(e){const t=Xe(e);if(Object.keys(t).length===0)return null;const s=je(t.source)||"none";if(!q_.has(s))return null;const r=Array.isArray(t.sessions)?t.sessions.filter(o=>Object.keys(Xe(o)).length>0):[];return{...t,source:s,observedAt:Cl(t.observedAt),refreshing:t.refreshing===!0,sessions:r}}function z_(e,t,s){const r=Xe(e),o=Xe(r.settings),a=Xe(r.activeChat),i=je(Xe(r.coordinator).meshId,o.meshCoordinatorFor),l=t&&i===t?"coordinator":t&&je(o.meshNodeFor)===t?"worker":void 0,d=Ra({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 V_(e,t,s,r){const o=Xe(e),a=Xe(o.settings),i=je(a.meshNodeId);return i?i===s.nodeId:!r||!t?!1:je(Xe(o.coordinator).meshId,a.meshCoordinatorFor)===t||je(a.meshNodeFor)===t}function Mb(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=>V_(d,e,r,a)).map(d=>z_(d,e,r.workspace||void 0)).filter(d=>d!==null);if(i.length===0)return r;const l=Wa([...r.activeSessionDetails??[],...i]);return{...r,activeSessionDetails:l,activeSessions:Wa([...l,...(r.activeSessions??[]).map(d=>({sessionId:d}))]).map(d=>d.sessionId)}})}function Wa(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 Rb(e,t){const s=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],r=s.map(Ra).filter(o=>o!==null);return r.length===0?t:t.map(o=>{const a=r.filter(l=>{const d=Xe(s.find(p=>{const b=Xe(p);return je(b.sessionId,b.session_id,b.id)===l.sessionId})),m=je(d.nodeId,d.node_id),u=je(d.daemonId,d.daemon_id),h=je(d.workspace);return m&&m===o.nodeId?!0:un(u,o.daemonId)?!h||!o.workspace||h===o.workspace:!!(h&&o.workspace&&h===o.workspace)});if(a.length===0)return o;const i=Wa([...o.activeSessionDetails??[],...a]);return{...o,activeSessionDetails:i,activeSessions:Wa([...o.activeSessionDetails??[],...a,...(o.activeSessions??[]).map(l=>({sessionId:l}))]).map(l=>l.sessionId)}})}function G_(e){const t=Xe(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||qt(t.is_local_worktree)!==void 0}function Pb(e){const t=new Map,s=[];for(const r of e){const o=G_(r)?Ib(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=U_(a,o);t.set(o.nodeId,i);const l=s.findIndex(d=>d.nodeId===o.nodeId);l>=0&&(s[l]=i)}return s}function P5(e){const t=e??{},s=Pb(t.nodes??[]);return{...t,nodes:Mb(je(t.meshId)||"",Rb(t,s))}}function E5(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:Tb(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 Y_(e){const t=je(e.meshId,e.mesh_id,e.id),s=e.nodes,r=Array.isArray(s)?s.map(d=>Ib(d)).filter(d=>d!==null):null;if(!t||!r)return null;const o=Mb(t,Rb(e,Pb(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 Q_(e){var a;let t=0;const s=Xe(e.sourceOfTruth),r=Xe(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+=Zl(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 J_(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 X_=20;function _m(e){let t=null;for(const s of e){const r=Y_(Xe(s));if(!r)continue;const o=Q_(r),a=J_(r);if(!t){t={status:r,score:o,refreshedAt:a};continue}(Math.abs(o-t.score)<=X_?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 _i(e){const s=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,r=_m([s==null?void 0:s.status,s]);return r||_m([e==null?void 0:e.status,e])}function Z_(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 e1(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 t1(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 n1(e,t){var o,a;if(!t)return null;const s=_i(e),r=(o=s==null?void 0:s.nodes)==null?void 0:o.find(i=>Gx(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 s1={sm:"max-w-md",md:"max-w-lg",lg:"max-w-3xl"},Am={center:"items-center justify-center",sheet:"items-end justify-center sm:items-center",stretch:"items-stretch justify-center md:items-center"};function pr({open:e=!0,onClose:t,align:s="center",size:r="md",chrome:o=!0,closeOnBackdrop:a=!0,closeOnEsc:i=!0,ariaLabel:l,ariaLabelledBy:d,overlayClassName:m,surfaceClassName:u,children:h}){c.useEffect(()=>{if(!e||!i)return;const g=S=>{S.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",Am[s],"bg-black/60 px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",m):ct("fixed inset-0 flex",Am[s],m),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",s1[r],u):ct(u),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:Wn.createPortal(x,document.body)}function Eb({open:e,onClose:t,size:s="md",title:r,footer:o,children:a,showClose:i=!0,closeOnBackdrop:l=!0,closeOnEsc:d=!0,ariaLabel:m,className:u,contentClassName:h}){const p=r!=null||i;return n.jsxs(pr,{open:e,onClose:t,size:s,closeOnBackdrop:l,closeOnEsc:d,ariaLabel:r==null?m:void 0,overlayClassName:u,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":Ge.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(Pt,{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 r1(e){return{meshId:e,daemonId:null,status:null,response:null,loadedAt:null,loading:!1,refreshing:!1,error:null}}function Ai(e){let t=_l.get(e);return t||(t={snapshot:r1(e),inFlight:null,queuedRefresh:null,listeners:new Set},_l.set(e,t)),t}function ls(e,t){var r;const s=Ai(e);(r=t.status)!=null&&r.meshName&&t_(e,t.status.meshName),s.snapshot={...s.snapshot,...t};for(const o of[...s.listeners])try{o()}catch{}}function io(e){var t;return e?((t=_l.get(e))==null?void 0:t.snapshot)??null:null}function o1(e,t){const s=Ai(e);return s.listeners.add(t),()=>{s.listeners.delete(t)}}function a1(e,t,s=null){ls(e,{status:t,daemonId:s,loadedAt:t?Date.now():null,error:null})}function i1(e,t,s){ls(e,{status:t,daemonId:s,loadedAt:Date.now(),error:null,loading:!1})}function c1(e){Ai(e).snapshot.status||ls(e,{loading:!0,error:null})}function l1(e){return e instanceof Error?e.message:typeof e=="string"?e:"Failed to load mesh status"}function Ti(e){const{meshId:t,daemonId:s,load:r}=e,o=e.refresh===!0,a=e.extract??(u=>_i(u));if(!t||!s)return Promise.resolve(null);const i=Ai(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,Ti(e)))),i.queuedRefresh);const d=i.snapshot.status!==null;ls(t,{loading:!d,refreshing:d,error:null});const m=(async()=>{var u;await null;try{const h=await r(s,t,{refresh:o}),p=a(h);return p?(ls(t,{status:p,response:h,daemonId:s,loadedAt:Date.now(),error:null}),p):(ls(t,{error:"mesh_status returned an unexpected payload."}),null)}catch(h){return ls(t,{error:l1(h)}),null}finally{((u=i.inFlight)==null?void 0:u.promise)===m&&(i.inFlight=null),ls(t,{loading:!1,refreshing:!1})}})();return i.inFlight={daemonId:s,refresh:o,promise:m},m}const Ua=new Set;function d1(e){if(Ua.size===0)return!1;for(const t of[...Ua])try{t(e)}catch{}return!0}function u1(e){return Ua.add(e),()=>Ua.delete(e)}const Ss={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`},m1=new Set(["missing-credentials","expired-token","unauthorized","quota-exhausted","rate-limited","network","server","parse","cli-unavailable","unsupported","setup-required","no-data","unknown"]);function Id(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)=>m1.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 h1={"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 p1(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 f1(e,t=Ss){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(p1((o??0)+(a??0)))),typeof s.sessions=="number"&&r.push(t.usageSessions(s.sessions)),r.length===0?null:`${s.days}d ${r.join(" · ")}`}function fr(e){return h1[e]??e}function Tm(e){return Number.isFinite(e)?e>=90?"danger":e>=70?"warn":"good":"default"}function b1(e,t=Date.now(),s=Ss){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 wa(e,t=Date.now()){const s=e==null?void 0:e.resetsAt;return typeof s=="number"&&Number.isFinite(s)&&s>0&&s<=t}Ss.windowReset();function Im(e){return!!e&&typeof e.usedPercent=="number"&&Number.isFinite(e.usedPercent)}function g1(e){var s;const t=(s=e.metadata)==null?void 0:s.failureKind;return!(t==="no-data"||t==="expired-token"&&e.provider==="antigravity-cli")}function x1(e){return Im(e.session)||Im(e.weekly)?!0:Array.isArray(e.buckets)&&e.buckets.some(t=>!!t&&typeof t.usedPercent=="number"&&Number.isFinite(t.usedPercent))}function y1(e){var t;if(!g1(e)&&x1(e))return"stale";if(((t=e.metadata)==null?void 0:t.lastGoodWindows)===!0)return"refreshing"}function Mm(e,t=Date.now(),s=!1,r=Ss){if(!e||typeof e.usedPercent!="number"||!Number.isFinite(e.usedPercent))return null;if(wa(e,t))return r.windowReset();const o=r.used(e.usedPercent.toFixed(1)),a=b1(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 v1(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 w1(e,t=Ss){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 m=(o=(typeof a.name=="string"?a.name:"").split("·")[0])==null?void 0:o.trim().replace(/\s+(Models?|Bundled Models?)$/i,"").trim();r.push({label:`${m||t.pool()} ${v1(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 S1(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 k1(e,t=Ss){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 j1(e,t=Date.now(),s=Ss){const r=y1(e),o=(b,f,x)=>{const g=Mm(b,t,r,s);if(!g)return null;const S=b.usedPercent,w=wa(b,t);return{key:f,label:`${x} ${g}`,usedPercent:w?null:S,hint:f,tone:w?"default":Tm(S)}},a=o(e.session,"session","5h"),i=o(e.weekly,"weekly","7d"),l=o(e.monthly,"monthly","30d"),d=w1(e,s).map(b=>({key:b.label,label:`${b.label} ${Mm(b.window,t,r,s)}`,usedPercent:wa(b.window,t)?null:b.usedPercent,hint:"bucket",tone:wa(b.window,t)?"default":Tm(b.usedPercent)})),m=d.length>0?d:[a,i,l].filter(b=>b!==null),u=f1(e,s),h=u?{key:"usage",label:u,usedPercent:null,hint:"usage",tone:"info"}:null,p=a??i??h;return m.length>0?{kind:"chips",cue:r,chips:m,usageLabel:null,message:null,compactChip:p}:h?{kind:"usage",cue:r,chips:[],usageLabel:u,message:null,compactChip:p}:e.status==="ok"?{kind:"okNoWindows",cue:r,chips:[],usageLabel:null,message:S1(e),compactChip:null}:{kind:"failure",cue:r,chips:[],usageLabel:null,message:k1(e,s),compactChip:null}}function Md(e){return(t,s=Date.now())=>j1(t,s,e)}function D5(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 Db(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)=>fr(s.provider).localeCompare(fr(r.provider)))}function L5(e,t=Date.now(),s=Ss){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 Rm(e){return No(e,{seconds:!0})||"—"}function N1({sessionId:e,daemonId:t,conv:s,onClose:r}){var D;const{t:o}=pe("common"),a=Md(Id(o)),{sendCommand:i}=xt(),l=Td(),[d,m]=c.useState(!0),[u,h]=c.useState(null),[p,b]=c.useState(null),[f,x]=c.useState(null),[g,S]=c.useState(null),w=c.useMemo(()=>e1(s),[s]),_=c.useMemo(()=>t1(s),[s]),k=c.useCallback(async()=>{m(!0),b(null);try{const F=await i(t,"get_session_info",{targetSessionId:e}),z=F&&typeof F=="object"?F:{},Z=z.result&&typeof z.result=="object"?z.result:z;Z!=null&&Z.success?h(Z):(b((Z==null?void 0:Z.error)||o("sessionInfo.failedToLoad")),h(null))}catch(F){b((F==null?void 0:F.message)||String(F)),h(null)}finally{m(!1)}},[i,t,e,o]);c.useEffect(()=>{k()},[k]);const v=c.useMemo(()=>{var F,z;return Z_({conv:s,sessionDaemonId:t,heldCoordinatorDaemonId:w?(F=io(w))==null?void 0:F.daemonId:null,reportedCoordinatorDaemonId:(z=u==null?void 0:u.meshWorker)==null?void 0:z.coordinatorDaemonId})},[s,t,w,(D=u==null?void 0:u.meshWorker)==null?void 0:D.coordinatorDaemonId]),y=c.useCallback(async()=>{var W,T;if(x(null),S(null),!w||!_||!v)return;const z=((W=io(w))==null?void 0:W.status)??null??await Ti({meshId:w,daemonId:v,refresh:!1,load:($,H,q)=>l!=null&&l.loadMeshStatus?l.loadMeshStatus($,H,{refresh:q.refresh}):i($,"mesh_status",{meshId:H})});if(!z){S(((T=io(w))==null?void 0:T.error)||o("sessionInfo.meshNodeUnavailable"));return}const Z=n1(z,_);if(!Z){S(o("sessionInfo.stampedToNode"));return}x(Z)},[l,i,v,w,_,o]);c.useEffect(()=>{y()},[y]);const[j,N]=c.useState(!1),A=c.useCallback(async()=>{await Cb(C1({sessionId:e,daemonId:t,conv:s,data:u,meshNode:f,meshNodeError:g}))&&(N(!0),setTimeout(()=>N(!1),1500))},[s,t,u,f,g,e]),R=n.jsxs(n.Fragment,{children:[(u||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(j?"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=F=>o(F?"common.yes":"common.no"),M=u==null?void 0:u.session,E=(M==null?void 0:M.workspace)||(s==null?void 0:s.workspacePath)||"",C=(s==null?void 0:s.machineName)||(u==null?void 0:u.machineNickname)||"",I=u==null?void 0:u.meshWorker,O=Db((f==null?void 0:f.quota)??(u==null?void 0:u.quota));return n.jsx(Eb,{open:!0,onClose:r,title:o("sessionInfo.title"),size:"lg",footer:R,children:n.jsxs("div",{className:"text-sm space-y-4",children:[d&&n.jsx("div",{className:"text-text-secondary",children:o("sessionInfo.loading")}),p&&n.jsx("div",{className:"text-red-500",children:o("sessionInfo.failedToLoad")}),M&&n.jsxs("div",{className:"space-y-1.5","data-testid":"session-info-summary",children:[n.jsx(Qe,{k:o("sessionInfo.rowProvider"),v:M.providerName||M.providerType}),E&&n.jsx(Qe,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(Gt,{content:E,children:n.jsx("span",{className:"truncate",children:Ab(E)})})}),C&&n.jsx(Qe,{k:o("sessionInfo.rowMachine"),v:C}),M.spawnedAtMs?n.jsx(Qe,{k:o("sessionInfo.rowStarted"),v:n.jsx(Nb,{value:M.spawnedAtMs})}):null,(s==null?void 0:s.git)&&n.jsx(Qe,{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")}`]})}),(u==null?void 0:u.coordinator)&&n.jsx(Qe,{k:o("sessionInfo.rowRole"),v:o("sessionInfo.roleCoordinator")}),O.map(({provider:F,quota:z})=>{const Z=a(z);return n.jsx(Qe,{k:[fr(F),Xc(z)].filter(Boolean).join(" · "),v:Z.kind==="chips"?n.jsx("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:Z.chips.map(W=>n.jsx(Pm,{label:W.label,tone:W.tone},W.key))}):Z.kind==="usage"?n.jsx(Pm,{label:Z.usageLabel,tone:"info"}):Z.kind==="okNoWindows"?n.jsx("span",{className:"text-text-secondary",children:Z.message??o("sessionInfo.quotaOkNoWindows")}):n.jsx("span",{className:"text-text-secondary",children:Z.message})},F)}),(I==null?void 0:I.coordinatorSessionId)&&n.jsx(Qe,{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:()=>{d1({sessionId:I.coordinatorSessionId,source:"session-info-dialog"}),r()},children:o("sessionNav.openCoordinatorChat")})]})})]}),(M||f||(u==null?void 0:u.coordinator)||g&&(w||_))&&n.jsxs("details",{className:"group rounded-lg border border-border-subtle px-3 py-2","data-testid":"session-info-technical-details",children:[n.jsxs("summary",{className:"cursor-pointer select-none list-none text-xs font-medium text-text-secondary [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"mr-1 inline-block transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),o("common.technicalDetails")]}),n.jsxs("div",{className:"mt-3 space-y-4",children:[M&&n.jsxs(Ts,{title:o("sessionInfo.sectionSession"),children:[n.jsx(Qe,{k:o("sessionInfo.rowSessionId"),v:n.jsx(Nt,{children:M.sessionId})}),n.jsx(Qe,{k:o("sessionInfo.rowProviderType"),v:n.jsx(Nt,{children:M.providerType})}),M.transport&&n.jsx(Qe,{k:o("sessionInfo.rowTransport"),v:M.transport}),E&&n.jsx(Qe,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(Nt,{children:E})}),M.spawnedAtMs?n.jsx(Qe,{k:o("sessionInfo.rowSpawnedAt"),v:Rm(M.spawnedAtMs)}):null,M.providerSessionId&&n.jsx(Qe,{k:o("sessionInfo.rowProviderSessionId"),v:n.jsx(Nt,{children:M.providerSessionId})}),(s==null?void 0:s.connectionState)&&n.jsx(Qe,{k:o("sessionInfo.rowConnection"),v:s.connectionState})]}),I&&(I.meshId||I.taskId||I.coordinatorSessionId)&&n.jsxs(Ts,{title:o("sessionInfo.sectionMeshWorker"),children:[I.meshId&&n.jsx(Qe,{k:o("sessionInfo.rowMeshId"),v:n.jsx(Nt,{children:I.meshId})}),I.taskId&&n.jsx(Qe,{k:o("sessionInfo.rowTaskId"),v:n.jsx(Nt,{children:I.taskId})}),I.coordinatorSessionId&&n.jsx(Qe,{k:o("sessionInfo.rowCoordinator"),v:n.jsx(Nt,{children:I.coordinatorSessionId})})]}),(M==null?void 0:M.launch)&&n.jsxs(Ts,{title:o("sessionInfo.sectionLaunch"),children:[M.launch.command&&n.jsx(Qe,{k:o("sessionInfo.rowCommand"),v:n.jsx(Nt,{children:M.launch.command})}),M.launch.cwd&&n.jsx(Qe,{k:o("sessionInfo.rowWorkingDirectory"),v:n.jsx(Nt,{children:M.launch.cwd})}),Array.isArray(M.launch.args)&&M.launch.args.length>0&&n.jsx(Qe,{k:o("sessionInfo.rowArgs"),v:n.jsx(Nt,{children:M.launch.args.join(" ")})}),Array.isArray(M.launch.extraArgs)&&M.launch.extraArgs.length>0&&n.jsx(Qe,{k:o("sessionInfo.rowExtraArgs"),v:n.jsx(Nt,{children:M.launch.extraArgs.join(" ")})}),Array.isArray(M.launch.extraEnvKeys)&&M.launch.extraEnvKeys.length>0&&n.jsx(Qe,{k:o("sessionInfo.rowExtraEnv"),v:n.jsx(Nt,{children:M.launch.extraEnvKeys.join(", ")})})]}),f&&n.jsxs(Ts,{title:o("sessionInfo.sectionMeshNode"),children:[f.nodeId&&n.jsx(Qe,{k:o("sessionInfo.rowNodeId"),v:n.jsx(Nt,{children:f.nodeId})}),f.workspace&&n.jsx(Qe,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(Nt,{children:f.workspace})}),f.repoRoot&&f.repoRoot!==f.workspace&&n.jsx(Qe,{k:o("sessionInfo.rowRepoRoot"),v:n.jsx(Nt,{children:f.repoRoot})}),f.daemonId&&n.jsx(Qe,{k:o("sessionInfo.rowDaemonId"),v:n.jsx(Nt,{children:f.daemonId})}),f.role&&n.jsx(Qe,{k:o("sessionInfo.rowRole"),v:f.role}),f.machineStatus&&n.jsx(Qe,{k:o("sessionInfo.rowMachineStatus"),v:f.machineStatus}),f.health&&n.jsx(Qe,{k:o("sessionInfo.rowHealth"),v:f.health}),f.isLocalWorktree&&n.jsx(Qe,{k:o("sessionInfo.rowWorktree"),v:f.worktreeBranch?n.jsx(Nt,{children:f.worktreeBranch}):o("common.yes")}),typeof f.launchReady=="boolean"&&n.jsx(Qe,{k:o("sessionInfo.rowLaunchReady"),v:P(f.launchReady)}),f.git&&n.jsx(Qe,{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(Qe,{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(Qe,{k:o("sessionInfo.rowProviders"),v:n.jsx(Nt,{children:f.providers.join(", ")})}),Array.isArray(f.providerPriority)&&f.providerPriority.length>0&&n.jsx(Qe,{k:o("sessionInfo.rowProviderPriority"),v:n.jsx(Nt,{children:f.providerPriority.join(" › ")})})]}),!f&&g&&(w||_)&&n.jsx(Ts,{title:o("sessionInfo.sectionMeshNode"),children:n.jsx("div",{className:"text-text-secondary italic",children:g})}),(u==null?void 0:u.coordinator)&&n.jsxs(Ts,{title:o("sessionInfo.sectionMeshCoordinator"),children:[n.jsx(Qe,{k:o("sessionInfo.rowMeshId"),v:n.jsx(Nt,{children:u.coordinator.meshId})}),u.coordinator.cliType&&n.jsx(Qe,{k:o("sessionInfo.rowCoordinatorCli"),v:u.coordinator.cliType}),u.coordinator.startedAt?n.jsx(Qe,{k:o("sessionInfo.rowStartedAt"),v:Rm(u.coordinator.startedAt)}):null,u.coordinator.injection&&n.jsx(Qe,{k:o("sessionInfo.rowPromptInjection"),v:`${u.coordinator.injection.mode}${u.coordinator.injection.target?` → ${u.coordinator.injection.target}`:""}`}),u.coordinator.mcpConfigPath&&n.jsx(Qe,{k:o("sessionInfo.rowMcpConfig"),v:n.jsx(Nt,{children:u.coordinator.mcpConfigPath})}),u.coordinator.extraSystemPrompt&&n.jsx(Al,{title:o("sessionInfo.blockExtraPrompt"),body:u.coordinator.extraSystemPrompt}),u.coordinator.systemPrompt&&n.jsx(Al,{title:o("sessionInfo.blockFinalPrompt"),body:u.coordinator.systemPrompt})]}),(M==null?void 0:M.runtimeMetadata)!=null&&n.jsx(_1,{meta:M.runtimeMetadata}),p&&n.jsx("div",{className:"font-mono text-xs text-text-secondary break-all",children:p})]})]})]})})}function C1(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 Ts({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 Qe({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 Nt({children:e}){return n.jsx("code",{className:"font-mono text-xs",children:e})}function Pm({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 _1({meta:e}){const{t}=pe("common");if(!e||typeof e!="object")return null;const s=e,r=m=>typeof m=="string"&&m.trim()?m: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(Ts,{title:t("sessionInfo.sectionRuntime"),children:[o&&n.jsx(Qe,{k:t("sessionInfo.rowRuntimeId"),v:n.jsx(Nt,{children:o})}),a&&n.jsx(Qe,{k:t("sessionInfo.rowLifecycle"),v:a}),i&&n.jsx(Qe,{k:t("sessionInfo.rowSurface"),v:i}),l&&n.jsx(Qe,{k:t("sessionInfo.rowRecoveryState"),v:l}),typeof s.restoredFromStorage=="boolean"&&n.jsx(Qe,{k:t("sessionInfo.rowRestoredFromStorage"),v:s.restoredFromStorage?t("common.yes"):t("common.no")}),d!=null&&n.jsx(Qe,{k:t("sessionInfo.rowAttachedClients"),v:String(d)}),n.jsx(Al,{title:t("sessionInfo.blockRawMetadata"),body:A1(e)})]})}function A1(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Al({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 T1=8e3;function I1({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,m=c.useCallback(()=>{if(!e||!t)return;const u=!l;a(u),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(null),T1),r(t,"set_conversation_prefs",{sessionId:e,muted:u}).catch(h=>{console.warn("[conversation-prefs] toggle mute failed",h),a(null)})},[t,l,r,e]);return{available:d,muted:l,toggle:m}}const Jo=220;function Lb({conversation:e,onOpenHistory:t,onOpenRemote:s,onOpenGit:r,className:o,iconSize:a=16}){const{t:i}=pe("common"),{ides:l}=xn(),{sendCommand:d}=xt(),[m,u]=c.useState(!1),[h,p]=c.useState(!1),[b,f]=c.useState(null),x=c.useRef(null),g=c.useRef(null),S=ht(e),w=c.useMemo(()=>{const j=l.find(N=>N.id===e.routeId);return Uf(e,j)},[e,l]),_=I1({sessionId:e.sessionId,daemonId:e.daemonId,muted:!!(w!=null&&w.muted),sendDaemonCommand:d}),k=[];if(t&&k.push({key:"history",label:i("dashboard.header.chatHistory"),icon:n.jsx(Ap,{size:15}),onSelect:()=>t(e)}),s&&!S&&k.push({key:"remote",label:i("dashboard.header.remoteControl"),icon:n.jsx(Hn,{size:15}),onSelect:()=>s(e)}),r&&e.git&&e.daemonId&&e.workspacePath){const j=e.daemonId,N=e.workspacePath;k.push({key:"git",label:i("dashboard.header.openGitStatus"),icon:n.jsx(ol,{size:15}),onSelect:()=>r(j,N)})}_.available&&k.push({key:"mute",label:_.muted?i("conversation.unmuteThis"):i("conversation.muteThis"),icon:_.muted?n.jsx(rl,{size:15}):n.jsx(gs,{size:15}),onSelect:_.toggle,pressed:_.muted}),e.sessionId&&e.daemonId&&k.push({key:"info",label:i("sessionInfo.title"),icon:n.jsx(So,{size:15}),onSelect:()=>p(!0)});const v=c.useCallback((j=!1)=>{var N;u(!1),j&&((N=x.current)==null||N.focus())},[]);if(c.useLayoutEffect(()=>{var A;if(!m||typeof window>"u"){f(null);return}const j=(A=x.current)==null?void 0:A.getBoundingClientRect();if(!j)return;const N=Math.min(Math.max(8,j.right-Jo),window.innerWidth-Jo-8);f({top:j.bottom+6,left:N})},[m]),c.useEffect(()=>{if(!m||typeof window>"u")return;const j=R=>{R.key==="Escape"&&(R.stopPropagation(),v(!0))},N=R=>{var M,E;const P=R.target;P&&((M=x.current)!=null&&M.contains(P)||(E=g.current)!=null&&E.contains(P)||v())},A=()=>v();return window.addEventListener("keydown",j,!0),document.addEventListener("mousedown",N,!0),window.addEventListener("resize",A),()=>{window.removeEventListener("keydown",j,!0),document.removeEventListener("mousedown",N,!0),window.removeEventListener("resize",A)}},[v,m]),c.useEffect(()=>{var j,N;m&&((N=(j=g.current)==null?void 0:j.querySelector('[role="menuitem"]'))==null||N.focus())},[m,b]),k.length===0)return null;const y=j=>{var P;if(j.key!=="ArrowDown"&&j.key!=="ArrowUp")return;j.preventDefault();const N=Array.from(((P=g.current)==null?void 0:P.querySelectorAll('[role="menuitem"]'))??[]),A=N.indexOf(document.activeElement),R=N[(A+(j.key==="ArrowDown"?1:-1)+N.length)%N.length];R==null||R.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":m,onClick:()=>u(j=>!j),className:o??"btn btn-secondary btn-sm",style:{pointerEvents:"auto"},children:n.jsx(Ip,{size:a})}),m&&typeof document<"u"&&Wn.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:Jo}:{top:-9999,left:-9999,width:Jo,visibility:"hidden"},children:k.map(j=>n.jsxs("button",{type:"button",role:"menuitem","data-menu-item":j.key,"aria-pressed":j.pressed,onClick:()=>{v(),j.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",j.pressed&&"text-amber-500"),children:[n.jsx("span",{className:"flex w-4 shrink-0 justify-center","aria-hidden":!0,children:j.icon}),n.jsx("span",{className:"min-w-0 truncate",children:j.label})]},j.key))}),document.body),h&&e.sessionId&&e.daemonId&&n.jsx(N1,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e,onClose:()=>p(!1)})]})}function Ob(e){const{t}=pe("common");if(!e.role)return null;const s=r_(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 Rd(e){var s;const t=bb(e);return((s=Ob(t))==null?void 0:s.full)??null}function vs({conversation:e,className:t,size:s=12}){const r=bb(e),o=Ob(r);return!pb(e)||!o?null:n.jsx("span",{role:"img","aria-label":o.full,title:o.full,"data-mesh-role":r.role,className:ct("mesh-role-icon",`is-${r.role}`,t),children:n.jsx(Ln,{size:s})})}function Tl(){return or(()=>import("./DashboardMeshGraphDialog-Iml8kna4.js"),__vite__mapDeps([3,1,4,5]))}const M1=c.lazy(Tl);function R1({onClose:e}){const{t}=pe(),s=t("connection.loadingShort");return n.jsx(pr,{onClose:e,size:"sm",ariaLabel:s,children:n.jsx("div",{className:"flex items-center justify-center p-8","data-testid":"mesh-graph-dialog-loading",children:n.jsx(Zt,{label:s})})})}function Pd(e){return n.jsx(c.Suspense,{fallback:n.jsx(R1,{onClose:e.onClose}),children:n.jsx(M1,{...e})})}function $b({conversation:e,onOpenMeshGraph:t,showLabel:s=!1,iconSize:r=14,className:o}){const{t:a}=pe("common"),i=Rd(e);if(!t||!fb(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:()=>{Tl()},onFocus:()=>{Tl()},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(Ln,{size:r}),s&&n.jsx("span",{className:"hidden lg:inline",children:a("dashboard.header.meshGraph")})]})}function P1({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 Em({value:e}){return e?n.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Dm({notification:e,shortcutIndex:t,onOpen:s,onMarkRead:r,onMarkUnread:o,onDelete:a}){const{t:i}=pe(),l=hi(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:m=>{m.stopPropagation(),r()},children:i("notification.markRead")}):n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:m=>{m.stopPropagation(),o()},children:i("notification.markUnread")}),n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:m=>{m.stopPropagation(),a()},children:i("notification.delete")})]})]})}function E1({activeConv:e,wsStatus:t,isConnected:s,conversations:r,onOpenHistory:o,onOpenRemote:a,onStopCli:i,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:h,onShowAllHidden:p,onResetPanelsToMain:b,inboxOpen:f,onInboxOpenChange:x,hiddenOpen:g,onHiddenOpenChange:S,onOpenNewSession:w,onOpenDashboardGuide:_,guideNudgeVisible:k=!1,actionShortcuts:v,notifications:y,notificationUnreadCount:j,onOpenNotification:N,onMarkNotificationRead:A,onMarkNotificationUnread:R,onDeleteNotification:P,onOpenGitDialog:M,onOpenMeshGraph:E}){const{t:C}=pe(),{ides:I,p2pStates:O={},usesP2P:D=!0}=xn(),F=!!e&&ht(e),z=l||(e?Of(e)?"terminal":"chat":null),[Z,W]=c.useState(!1),[T,$]=c.useState(!1),H=c.useRef(null),q=c.useRef(null),U=c.useRef(null),K=I.filter(B=>B.type==="adhdev-daemon"),oe=P1({wsStatus:t,isConnected:s,daemonCount:K.length,p2pStates:O,usesP2P:D}),ke=C(oe.titleKey),J=oe.subtitleKey?C(oe.subtitleKey,oe.subtitleParams):null,ye=oe.tone==="connected"?"#22c55e":oe.tone==="limited"?"#eab308":"#ef4444",ae=oe.tone==="connected"?"0 0 4px #22c55e80":oe.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",re=c.useMemo(()=>y.filter(B=>!B.readAt),[y]),de=c.useMemo(()=>y.filter(B=>!!B.readAt),[y]),ne=c.useMemo(()=>re.slice(0,9),[re]),ie=j;c.useEffect(()=>{if(!f)return;const B=Q=>{var ue;(ue=q.current)!=null&&ue.contains(Q.target)||x(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[f,x]),c.useEffect(()=>{if(!g)return;const B=Q=>{var ue;(ue=U.current)!=null&&ue.contains(Q.target)||S(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[g,S]),c.useEffect(()=>{if(!g&&!f)return;const B=Q=>{if(!Q.altKey)return;const ue=Q.code.match(/^Digit([1-9])$/);if(!ue)return;const Re=Number(ue[1])-1,Le=g?u[Re]:void 0,Pe=f?ne[Re]:void 0;if(!(!Le&&!Pe)){if(Q.preventDefault(),Q.stopPropagation(),Le){h==null||h(Le),S(!1);return}Pe&&(N(Pe),x(!1))}};return window.addEventListener("keydown",B,!0),()=>window.removeEventListener("keydown",B,!0)},[u,g,f,ne,S,x,N,h]),c.useEffect(()=>{const B=u.length;if(H.current===null){H.current=B;return}B>H.current&&$(!0),H.current=B},[u.length]);const _e=()=>$(!1),G=B=>{if(!B)return;const Q=r.find(ue=>ue.tabKey===B);Q&&(m==null||m(Q))};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:C("dashboard.header.title")}),e&&n.jsx(vs,{conversation:e,size:14,className:"header-title-mobile-role"}),n.jsx("span",{className:"header-title-mobile",children:e?wt(e):C("dashboard.header.title")}),n.jsx(Gt,{content:J?`${ke} · ${J}`:ke,className:"ml-0.5",children:n.jsx("span",{role:"img","aria-label":ke,"data-connection-tone":oe.tone,className:"header-title-status-dot",style:{background:ye,boxShadow:ae}})})]}),n.jsx("div",{className:"header-subtitle flex items-center",children:w&&n.jsx("button",{type:"button",onClick:w,className:"btn btn-secondary btn-sm ml-2",title:`${C("paneGroup.newSession")}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":C("paneGroup.newSession"),children:n.jsx(po,{size:14})})})]})})}),n.jsxs("div",{className:"flex gap-2 items-center",children:[_&&n.jsxs("button",{type:"button",onClick:_,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:C("dashboard.header.guide"),"aria-label":C("dashboard.header.guideOpen"),children:[n.jsx("span",{className:"font-semibold leading-none",children:"?"}),k&&n.jsx("span",{children:C("dashboard.header.guideShort")})]}),e&&n.jsxs("div",{className:"dashboard-header-actions-group","data-testid":"dashboard-pane-toolbar",children:[n.jsx(Nd,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),F&&d&&z&&n.jsx(kb,{mode:z,onChange:d,compact:!0}),F&&i&&n.jsx("button",{type:"button",onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:C("dashboard.header.stopCliProcess"),"aria-label":C("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(Pt,{size:14})}),n.jsx($b,{conversation:e,onOpenMeshGraph:E,showLabel:!0}),n.jsx(Lb,{conversation:e,onOpenHistory:o,onOpenRemote:a?()=>a():void 0,onOpenGit:M,iconSize:14})]}),n.jsxs("div",{className:"dashboard-header-inbox",ref:q,children:[n.jsxs("div",{className:`dashboard-header-hidden${Z?" is-drop-target":""}${T?" hidden-spawn-flash":""}${(u??[]).some(Bs)?" hidden-generating-spin":""}`,onAnimationEnd:_e,ref:U,onDragEnter:B=>{B.dataTransfer.types.includes("text/tab-key")&&(B.preventDefault(),W(!0))},onDragOver:B=>{B.dataTransfer.types.includes("text/tab-key")&&(B.preventDefault(),B.dataTransfer.dropEffect="move",W(!0))},onDragLeave:B=>{B.currentTarget.contains(B.relatedTarget)||W(!1)},onDrop:B=>{const Q=B.dataTransfer.getData("text/tab-key");B.preventDefault(),W(!1),G(Q)},children:[n.jsxs("button",{type:"button",onClick:()=>S(!g),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${C("dashboard.hidden.title")}${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. ${C("dashboard.hidden.dragHint")}`,children:[n.jsx(li,{size:16}),u.length>0&&n.jsx("span",{className:`dashboard-header-hidden-badge${T?" hidden-badge-pop":""}`,children:u.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:C("dashboard.hidden.title")}),n.jsx(Em,{value:v==null?void 0:v.toggleHiddenTabs})]}),n.jsxs("div",{className:"dashboard-header-hidden-actions",children:[b&&n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:b,children:C("dashboard.hidden.resetPanels")}),u.length>0&&p&&n.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{p(),S(!1)},children:C("dashboard.hidden.restoreAll")})]})]}),e&&m&&n.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[n.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[n.jsx("span",{className:"dashboard-header-hidden-current-label",children:C("dashboard.hidden.hideCurrentTab")}),n.jsx(Em,{value:v==null?void 0:v.hideCurrentTab})]}),n.jsx("span",{className:"dashboard-header-hidden-current-title",children:wt(e)})]}),u.length>0?n.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(B=>n.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(B),S(!1)},children:[n.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[Bs(B)&&n.jsx(Zt,{size:12,thickness:2,color:"success",label:C("dashboard.header.generating")}),n.jsx(vs,{conversation:B,size:12}),wt(B)]}),n.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(B)<9?n.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(B)+1]}):null,To(B)]})]},B.tabKey))}):n.jsx("div",{className:"dashboard-header-inbox-empty",children:C("dashboard.hidden.empty")})]})]}),n.jsxs("button",{type:"button",onClick:()=>x(!f),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:C("dashboard.header.activityInbox"),children:[n.jsx(gs,{size:16}),ie>0&&n.jsx("span",{className:"dashboard-header-inbox-badge",children:ie})]}),f&&n.jsxs("div",{className:"dashboard-header-inbox-popover",children:[re.length>0&&n.jsxs("div",{className:"dashboard-header-inbox-section",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title",children:C("dashboard.inbox.unread")}),re.map(B=>n.jsx(Dm,{notification:B,shortcutIndex:ne.indexOf(B)>=0?ne.indexOf(B)+1:void 0,onOpen:()=>N(B),onMarkRead:()=>A(B.id),onMarkUnread:()=>R(B.id),onDelete:()=>P(B.id)},B.id))]}),de.length>0&&n.jsxs("div",{className:"dashboard-header-inbox-section",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title",children:C("dashboard.inbox.read")}),de.map(B=>n.jsx(Dm,{notification:B,onOpen:()=>N(B),onMarkRead:()=>A(B.id),onMarkUnread:()=>R(B.id),onDelete:()=>P(B.id)},B.id))]}),y.length===0&&n.jsx("div",{className:"dashboard-header-inbox-empty",children:C("dashboard.inbox.empty")})]})]})]})]})}function dn(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function D1(e,t){return String(e||"")!==String(t||"")}function L1(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(`
51
51
  `).includes(s)||r&&!String(i.workspace||"").toLowerCase().includes(r)||o&&!yf(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
52
52
  `).includes(o)))}function O1(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 Ed(e,t={}){return O1(L1(e,t),t.sortMode||"recent")}function Il(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function Fb(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function $1(e){return e?e("launch.startFresh"):"Start fresh"}function F1(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function H1(e){return e?e("launch.openSavedHistory"):"Open saved history"}function Ml(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function Dd(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function Hb(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function B1(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function W1(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function Ka(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 qa(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 za(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Va(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function Bb(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function Wb(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function Lm(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 U1({activeConv:e,ides:t,isCreatingChat:s,isRefreshingHistory:r,savedSessions:o=[],isSavedSessionsLoading:a=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:h,onSwitchSession:p,onRefreshHistory:b,onResumeSavedSession:f}){var E;const{t:x}=pe("common"),g=t.find(C=>C.id===e.routeId),S=(g==null?void 0:g.chats)||[],w=(E=g==null?void 0:g.activeChat)==null?void 0:E.id,_=ht(e),[k,v]=c.useState(()=>dn()),[y,j]=c.useState(null),N=l||k,A=String(d||"").trim(),R=C=>{if(m){m(C);return}v(C)},P=c.useMemo(()=>o.map(C=>{const I=String(C.workspace||"").trim();return C.canResume||I||!A?C:{...C,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,o]),M=c.useMemo(()=>Ed(P,{textQuery:N.textQuery,workspaceQuery:N.workspaceQuery,modelQuery:N.modelQuery,resumableOnly:N.resumableOnly,sortMode:N.sortMode}),[P,N.modelQuery,N.resumableOnly,N.sortMode,N.textQuery,N.workspaceQuery]);return n.jsxs(n.Fragment,{children:[n.jsxs(pr,{chrome:!1,onClose:u,closeOnEsc:!y,ariaLabel:_?Ml(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:_?Ml(x):x("historyModal.chatHistory")}),n.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:i_(e)}),_&&n.jsx("div",{className:"text-2xs text-text-muted mt-1",children:Dd(x)})]}),n.jsx("button",{onClick:u,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(Pt,{size:16})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!_&&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")}),_?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:N.textQuery,onChange:C=>R({...N,textQuery:C.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:N.workspaceQuery,onChange:C=>R({...N,workspaceQuery:C.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:N.modelQuery,onChange:C=>R({...N,modelQuery:C.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:N.sortMode,onChange:C=>R({...N,sortMode:C.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:N.resumableOnly,onChange:C=>R({...N,resumableOnly:C.target.checked})}),x("historyModal.resumeReadyOnly")]})]}),M.map(C=>{const I=e.providerSessionId===C.providerSessionId,O=I||!C.canResume||!!i,D=C.workspaceFallbackSource==="selected-workspace";return n.jsxs("button",{type:"button",onClick:()=>{O||!f||j({kind:"saved",session:C})},disabled:O,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"} ${O?"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:C.title||x("historyModal.untitledSession")}),n.jsx("div",{className:"text-2xs text-text-muted font-mono truncate",children:C.providerSessionId})]}),n.jsx("div",{className:"text-2xs text-text-muted shrink-0",children:Lm(C.lastMessageAt)})]}),n.jsx("div",{className:"mt-2 text-xs text-text-muted line-clamp-2",children:C.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:[C.workspace||x("historyModal.workspaceUnknown"),D?x("historyModal.selectedWorkspaceSuffix"):"",go(C.summaryMetadata)?` · ${go(C.summaryMetadata)}`:"",C.messageCount>0?` · ${x("historyModal.msgCount",{count:C.messageCount})}`:""]}),n.jsx("div",{className:"shrink-0",children:I?x("historyModal.statusActive"):C.canResume?D?x("historyModal.statusResumeSelectedWorkspace"):i===C.providerSessionId?x("historyModal.statusResuming"):x("historyModal.statusResume"):x("historyModal.statusMissingWorkspace")})]})]},C.id)})]}):S.map(C=>n.jsxs("div",{onClick:()=>{C.id!==w&&j({kind:"chat",id:C.id,title:C.title||x("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${w===C.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 ${w===C.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:C.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:[C.id.substring(0,12),"..."]}),w===C.id&&n.jsx("span",{className:"text-3xs bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:x("historyModal.statusActive")})]})]},C.id)),(_&&!a&&M.length===0||!_&&S.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(ow,{size:32})}),n.jsx("div",{className:"text-xxs",children:_?o.length>0?x("historyModal.noMatchingHistory"):Hb(x):x("historyModal.noRecentChats")})]}),_&&a&&n.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:n.jsx("div",{className:"text-xxs",children:W1(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(vr,{size:13})," ",_?B1(x):x("historyModal.refreshHistory")]})})})]}),y&&n.jsxs(pr,{chrome:!1,onClose:()=>j(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?` · ${Lm(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 C=y;j(null),C.kind==="chat"?(p(e.routeId,C.id),u()):f&&f(C.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:x("historyModal.confirmSwitchAction")}),n.jsx("button",{onClick:()=>j(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:x("common.cancel")})]})]})]})}const Om={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 K1({toast:e}){const{t}=pe(),{setToasts:s}=xn(),[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 Ub({toasts:e,onDismiss:t,onClickToast:s}){const{t:r}=pe();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=Om[o.type]||Om.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(Pt,{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(K1,{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 q1=e=>e.transport==="pty"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function z1(e){const t=e.workspace||"";if(!t)return"";const s=t.split(/[/\\]/).filter(Boolean);return s.length>0?s[s.length-1]:t}function V1(e,t){return Kb(e)||t}function Kb(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 G1(e){return Kb(e)||void 0}function Y1(e){return e.sessionId||e.instanceId||e.agentType}function qb(e=[]){const t={};for(const s of e)s.type==="adhdev-daemon"&&(t[s.id]=yn(s,{fallbackId:s.id}));return t}function zb(e,t={}){var r;const s=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:Uk(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[s]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Ld(e,t={}){return Q1(e,zb(e,t))}function Q1(e,t={}){var p,b,f,x,g,S,w,_,k;const s=[],r=t.machineName,o=t.connectionState,a=z1(e),i=e.workspace||"",l=wf(e.type,{agentName:e.cliName}),d=ht(e)?l:Ot(e.type),m=V1(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var y,j,N;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||Ot(v.providerType),model:G1(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((j=v.activeChat)==null?void 0:j.messages)||[],activeModal:((N=v.activeChat)==null?void 0:N.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=q1(e);if(h){const v=e.sessionId||e.instanceId,y=(p=e.settings)==null?void 0:p.meshCoordinatorFor,j=((b=e.settings)==null?void 0:b.meshNodeFor)||!((f=e.settings)!=null&&f.meshCoordinatorFor)&&((x=e.settings)==null?void 0:x.launchedByCoordinator),N=y?" (Coordinator)":j?" (Mesh Node)":"",A=l+N,R=(g=e.activeChat)==null?void 0:g.activeModal,P=R&&Array.isArray(R.buttons)&&R.buttons.length>0,M=Qk(e.activeChat,[{status:e.status,activeModal:(S=e.activeChat)==null?void 0:S.activeModal}],e.agents||[]),E=e.activeChat||{title:"",messages:[]};let C=E.title&&String(E.title).trim()?String(E.title).trim():"";const I=(w=e.activeChat)==null?void 0:w.id,O=e.chats;if(I&&Array.isArray(O)&&O.length>0){const H=O.find(q=>q.id===I||q.id&&String(q.id)===String(I));H!=null&&H.title&&String(H.title).trim()&&(C=String(H.title).trim())}const D=(ht(e),e.type),F=ht(e)&&qu(C,A,D)?"":C,z=E.messages||[],Z=typeof I=="string"?I.trim():"",W=ht(e)&&Z===String(e.type||"").trim(),T=Z&&!W?Z:e.providerSessionId,$=e.coordinator||(typeof((_=e.settings)==null?void 0:_.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);s.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:T,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ht(e)&&e.mode||"chat",agentName:A,agentType:D,status:M,title:F,messages:z,resume:e.resume,hostIdeType:ht(e)?void 0:e.type,workspaceName:a,workspacePath:i,git:e.git,displayPrimary:a||F||(ht(e)?e.mode==="chat"?A:`Terminal${N}`:A),displaySecondary:m,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:P?R.buttons:void 0,modalMessage:P?R.message:void 0,streamSource:"native",tabKey:oc(v,e.id),machineName:r,connectionState:o,settings:e.settings,coordinator:$,messageInput:e.messageInput})}if(h&&ht(e))return s;for(const v of u){const y=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,j=Jk(v),N=Y1(v),A=`${e.id}:${N}`,R=v.title&&String(v.title).trim()||"",P=qu(R,v.agentName,v.agentType)?"":R,M=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||M.length>0||y||!!P||!["idle","panel_hidden","disconnected","not_monitored"].includes(j)))continue;const C=v.coordinator||(typeof((k=v.settings)==null?void 0:k.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:j,title:P,messages:M,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:oc(v.sessionId||v.instanceId,A),machineName:r,connectionState:o,settings:v.settings,coordinator:C,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:m,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:oc(e.sessionId||e.instanceId,e.id),connectionState:o,settings:e.settings,messageInput:e.messageInput}),s}const Rl="https://adhf.dev",J1="https://dev.adhf.dev";function X1(e){return e==="adhf.dev"||e==="adhdev-web.pages.dev"||e==="localhost"||e==="127.0.0.1"?Rl:J1}function Z1(){return typeof window>"u"?Rl:X1(window.location.hostname)}function eA(){const e=Z1();return{unix:{cmd:`curl -fsSL ${e}/install | sh`,shell:"Terminal",prompt:"$ "},powershell:{cmd:`irm ${e}/install.ps1 | iex`,shell:"PowerShell",prompt:"PS> "},cmd:{cmd:`curl -fsSL ${e}/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd`,shell:"CMD",prompt:"> "}}}function Vb(e){return String(e.type||e.id||"").trim()}function Ga(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function tA(e,t){const s=(t||"").trim();if(!s)return[];const r=(e||[]).find(o=>o.type===s);return Ga(r==null?void 0:r.modelOptions)}function nA(e,t){const s=(t||"").trim();if(!s)return[];const r=(e||[]).find(o=>o.type===s);return Ga(r==null?void 0:r.thinkingLevelOptions)}function sA(e){const t=new Map;for(const s of e||[])s!=null&&s.type&&t.set(s.type,{models:Ga(s.modelOptions),thinking:Ga(s.thinkingLevelOptions)});return t}function rA(e){var t;return e.category!=="cli"||!Vb(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 Bn(e){var r;const t=new Set,s=[];for(const o of e||[]){if(!rA(o))continue;const a=Vb(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 Io(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 Ws(e){return e.map(t=>t.type)}function oA(e,t){const s=Io(e),r=t.trim();return!r||s.includes(r)?s:[...s,r]}function aA(e,t){return Io(e).filter(s=>s!==t)}function $m(e,t,s){const r=Io(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 iA={"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"}},Fm=["#0EA5E9","#8B5CF6","#10B981","#F59E0B","#EF4444","#14B8A6","#6366F1","#EC4899","#84CC16","#F97316","#06B6D4","#A855F7"];function cA(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 lA(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 Ii({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(hw,{size:s,className:r});const i=iA[o],l=(i==null?void 0:i.monogram)??lA((t==null?void 0:t.trim())||o.replace(/-cli$/,"")),d=(i==null?void 0:i.hue)??Fm[cA(o||a)%Fm.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 Hm({direction:e}){return n.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?n.jsx("polyline",{points:"18 15 12 9 6 15"}):n.jsx("polyline",{points:"6 9 12 15 18 9"})})}function dA({value:e,availableProviders:t,onChange:s,disabled:r=!1,saveButton:o}){const{t:a}=pe("common"),[i,l]=c.useState(""),d=c.useMemo(()=>new Map(t.map(b=>[b.type,b])),[t]),m=c.useMemo(()=>Io(e),[e]),u=m.filter(b=>!d.has(b)).length,h=t.filter(b=>!m.includes(b.type)),p=()=>{i&&(s(oA(m,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:m.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")}):m.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(Ii,{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(Gt,{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($m(m,b,"up")),children:n.jsx(Hm,{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===m.length-1,title:a("settings.providerPriority.moveDown"),onClick:()=>s($m(m,b,"down")),children:n.jsx(Hm,{direction:"down"})}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>s(aA(m,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(tt,{content:[a("settings.providerPriority.orderHint"),u>0?a("settings.providerPriority.undetectedHint",{count:u}):""].filter(Boolean).join(`
53
53
 
@@ -58,8 +58,8 @@ ${JSON.stringify(t,null,2)}
58
58
  `,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:()=>w(!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}),m&&n.jsx("div",{className:"text-xs text-text-muted",children:r("settings.coordinatorPrompts.loading")}),P.length>0&&n.jsx(Jb,{activeKey:E,onTabChange:v,ariaLabel:r("settings.coordinatorPrompts.tabsAriaLabel"),tabIdPrefix:"coordinator-prompt-tab",tabs:P.map(C=>{const I=a[C],O=N(C,"override")||N(C,"append");return{key:C,label:n.jsxs("span",{className:"flex items-center gap-1.5 font-mono text-xs",children:[C,R(C)&&n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-accent-primary",title:r("settings.coordinatorPrompts.customizedBadge")}),O&&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:D=>i(F=>({...F,[C]:{...F[C],override:D.target.value}})),placeholder:r("settings.coordinatorPrompts.overridePlaceholder"),disabled:h===`${C}: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:D=>i(F=>({...F,[C]:{...F[C],append:D.target.value}})),placeholder:r("settings.coordinatorPrompts.appendPlaceholder"),disabled:h===`${C}: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(C),disabled:!!(h!=null&&h.startsWith(`${C}:`))||!O,children:h!=null&&h.startsWith(`${C}:`)?r("settings.coordinatorPrompts.saving"):r(O?"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:m?n.jsx("span",{children:r("settings.coordinatorPrompts.loading")}):M.length===0?n.jsx("span",{children:r("settings.coordinatorPrompts.collapsedNone")}):n.jsxs(n.Fragment,{children:[n.jsxs("span",{children:[r("settings.coordinatorPrompts.customizedBadge"),":"]}),M.map(C=>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}),C]},C))]})}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>w(!0),children:r("settings.coordinatorPrompts.expandLabel")})]})]}):n.jsx("div",{className:"text-xs text-text-muted",children:r("settings.coordinatorPrompts.connectDaemon")})}const UA=[{id:"dark",labelKey:"settings.appearance.modeDark",icon:Pp},{id:"light",labelKey:"settings.appearance.modeLight",icon:Rp},{id:"system",labelKey:"settings.appearance.modeSystem",icon:Ep}];function KA(){const{preference:e,setPreference:t}=Mi(),{t:s}=pe("common");return n.jsx("div",{className:"flex gap-2",children:UA.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 qA(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 zA(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function gc(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function qm(e){const{r:t,g:s,b:r}=zA(e);return .2126*gc(t)+.7152*gc(s)+.0722*gc(r)}function zm(e,t){const s=qm(e),r=qm(t),o=Math.max(s,r),a=Math.min(s,r);return(o+.05)/(a+.05)}function tg(e){const t=qA(e);if(!t)return"#111827";const s="#111827",r="#ffffff";return zm(t,s)>=zm(t,r)?s:r}const Dl={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},Ll={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},VA=[{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"}}}],ng="adhdev-chat-theme",sg="adhdev-chat-theme-custom";function ka(){if(typeof window>"u")return"ember";try{return localStorage.getItem(ng)||"ember"}catch{return"ember"}}function jn(e){try{const t=localStorage.getItem(sg);if(t){const s=JSON.parse(t);return{...e==="dark"?Dl:Ll,...s[e]}}}catch{}return e==="dark"?Dl:Ll}function Xo(e,t){try{localStorage.setItem(sg,JSON.stringify({dark:e,light:t}))}catch{}}function fn(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 Ya(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 GA={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function co(e,t){var o;const s=(o=GA[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",Ya(s,24)),r.style.setProperty("--accent-on-primary",tg(s)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${s}, ${Ya(s,18)})`),r.style.setProperty("--border-accent",fn(s,.35)),r.style.setProperty("--nav-active-bg",fn(s,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${s}, 0 0 12px ${fn(s,.06)}`)}function Ls(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",fn(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",fn(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",fn(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",fn(e.borderSubtle,.5)),t.style.setProperty("--border-default",fn(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Ya(e.accentColor,30)),t.style.setProperty("--accent-on-primary",tg(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Ya(e.accentColor,40)})`),t.style.setProperty("--border-accent",fn(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",fn(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${fn(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 ${fn(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 $d(){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 YA(e){try{localStorage.setItem(ng,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Os()?"dark":"light";Ls(jn(t))}else $d(),co(e,Os()?"dark":"light")}function QA(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=ka();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Os()?"dark":"light";Ls(jn(t))}else $d(),co(e,Os()?"dark":"light")}function Os(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function zt({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 Kr({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 JA({dark:e,onColorsChange:t}){const{t:s}=pe("common"),r=e?"dark":"light",[o,a]=c.useState(()=>jn(r));c.useEffect(()=>{a(jn(r))},[r]);const i=c.useCallback((l,d)=>{a(m=>{const u={...m,[l]:d},p=jn(r==="dark"?"light":"dark");return r==="dark"?Xo(u,p):Xo(p,u),Ls(u),t(u),u})},[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(Kr,{title:s("settings.theme.sectionAppBackground"),children:[n.jsx(zt,{label:s("settings.theme.colorBackground"),value:o.bgPrimary,onChange:l=>i("bgPrimary",l)}),n.jsx(zt,{label:s("settings.theme.colorSurface"),value:o.bgSecondary,onChange:l=>i("bgSecondary",l)}),n.jsx(zt,{label:s("settings.theme.colorCard"),value:o.surfacePrimary,onChange:l=>i("surfacePrimary",l)})]}),n.jsxs(Kr,{title:s("settings.theme.sectionAppText"),children:[n.jsx(zt,{label:s("settings.theme.colorPrimary"),value:o.textPrimary,onChange:l=>i("textPrimary",l)}),n.jsx(zt,{label:s("settings.theme.colorSecondary"),value:o.textSecondary,onChange:l=>i("textSecondary",l)}),n.jsx(zt,{label:s("settings.theme.colorMuted"),value:o.textMuted,onChange:l=>i("textMuted",l)})]}),n.jsxs(Kr,{title:s("settings.theme.sectionBordersAccent"),children:[n.jsx(zt,{label:s("settings.theme.colorBorderSubtle"),value:o.borderSubtle,onChange:l=>i("borderSubtle",l)}),n.jsx(zt,{label:s("settings.theme.colorBorderDefault"),value:o.borderDefault,onChange:l=>i("borderDefault",l)}),n.jsx(zt,{label:s("settings.theme.colorAccent"),value:o.accentColor,onChange:l=>i("accentColor",l)})]})]}),n.jsxs("div",{children:[n.jsxs(Kr,{title:s("settings.theme.sectionChatBubbles"),children:[n.jsx(zt,{label:s("settings.theme.colorUserBubble"),value:o.userBubble,onChange:l=>i("userBubble",l)}),n.jsx(zt,{label:s("settings.theme.colorUserText"),value:o.userText,onChange:l=>i("userText",l)}),n.jsx(zt,{label:s("settings.theme.colorAgentBubble"),value:o.assistantBubble,onChange:l=>i("assistantBubble",l)}),n.jsx(zt,{label:s("settings.theme.colorAgentText"),value:o.assistantText,onChange:l=>i("assistantText",l)})]}),n.jsxs(Kr,{title:s("settings.theme.sectionChatLayout"),children:[n.jsx(zt,{label:s("settings.theme.colorChatBg"),value:o.containerBg,onChange:l=>i("containerBg",l)}),n.jsx(zt,{label:s("settings.theme.colorSendButton"),value:o.sendButton,onChange:l=>i("sendButton",l)}),n.jsx(zt,{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?Dl:Ll,m=jn(e?"light":"dark");e?Xo(l,m):Xo(m,l),a(l),Ls(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 XA(){const{t:e}=pe("common"),[t,s]=c.useState(ka),[r,o]=c.useState(!0),[a,i]=c.useState(()=>jn("dark"));c.useEffect(()=>{o(Os());const m=new MutationObserver(()=>{const p=Os();o(p);const b=ka();b==="custom"?Ls(jn(p?"dark":"light")):co(b,p?"dark":"light")});m.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),h=()=>{const p=Os();o(p);const b=ka();b==="custom"?Ls(jn(p?"dark":"light")):co(b,p?"dark":"light")};return u.addEventListener("change",h),()=>{m.disconnect(),u.removeEventListener("change",h)}},[]),c.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Ls(jn(r?"dark":"light")):($d(),co(t,r?"dark":"light"))},[t,r]),c.useEffect(()=>{i(jn(r?"dark":"light"))},[r]);const l=m=>{s(m),YA(m)},d=[...VA,{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(m=>{const u=t===m.id,h=r?m.preview.dark:m.preview.light,p=m.id==="honey"||m.id==="ember"?"#1a1a1a":m.id==="custom"?a.userText:"#fff";return n.jsxs("button",{onClick:()=>l(m.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?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:[u&&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:m.id==="custom"?e("settings.theme.customLabel"):m.name}),n.jsx("div",{className:"text-3xs text-text-muted",children:m.id==="custom"?m.description:e(`settings.theme.preset.${m.id}`,{defaultValue:m.description})})]})]})]},m.id)})}),t==="custom"&&n.jsx(JA,{dark:r,onColorsChange:m=>i(m)})]})}const Fd="adhdev_mobileDashboardMode_v1",Ol="adhdev:mobile-dashboard-mode-change";function Hd(){try{return localStorage.getItem(Fd)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ZA(e){if(typeof window>"u")return()=>{};const t=o=>{e(o??Hd())},s=o=>{const a=o.detail;t(a)},r=o=>{o.key&&o.key!==Fd||t()};return window.addEventListener(Ol,s),window.addEventListener("storage",r),()=>{window.removeEventListener(Ol,s),window.removeEventListener("storage",r)}}function eT(e){try{localStorage.setItem(Fd,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ol,{detail:e}))}function tT(){const{t:e}=pe("common"),[t,s]=c.useState(!0);return c.useEffect(()=>{s(Hd()==="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),eT(r?"chat":"workspace")},extra:n.jsx("span",{className:"text-2xs text-text-muted",children:e(t?"settings.mobileMode.chatMode":"settings.mobileMode.workspaceMode")})})}function nT(){const{t:e}=pe("common"),[t,s]=c.useState(()=>fo());return c.useEffect(()=>zp(s),[]),n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Mp,{size:15})," ",e("settings.chatActivity.rowLabel")]}),description:e(t?"settings.chatActivity.descriptionOn":"settings.chatActivity.descriptionOff"),checked:t,onChange:r=>{s(r),qp(r)}})}function sT({fontsSlot:e}){const{t}=pe("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(KA,{})]}),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(XA,{})]}),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(nT,{})]}),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(tT,{})]})]})}function rT({children:e,fallback:t=null}){const[s,r]=c.useState($k);return c.useEffect(()=>{if(s)return;let o=!0;return Fk().then(()=>{o&&r(!0)}),()=>{o=!1}},[s]),n.jsx(n.Fragment,{children:s?e:t})}const oT=15e3,aT=15e3,Vm=12,iT=8e3,cT=4e3,xc=new Map,Gm=new Map;function lT(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 dT(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 rg(){const{sendCommand:e}=xt(),{injectEntries:t,getIdes:s}=lr();return c.useCallback(async(r,o)=>{if(!r)return;const a=(o==null?void 0:o.minFreshMs)??aT,i=Gm.get(r)||0;if(!(o!=null&&o.force)&&i>0&&Date.now()-i<a)return;const l=xc.get(r);if(l)return l;const d=(async()=>{const m=await e(r,"get_machine_runtime_stats"),u=lT(m);if(!u)return;const h=s().find(b=>b.id===r),p=dT(h,r,u.machine,u.timestamp||Date.now());t([p]),Gm.set(r,Date.now())})().finally(()=>{xc.delete(r)});return xc.set(r,d),d},[s,t,e])}function uT(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 mT(e,t){const{sendData:s}=xt(),{injectEntries:r,getIdes:o}=lr(),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=>$n.subscribe({sendData:s},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const h=o().find(b=>b.id===d),p=uT(h,d,u);r([p])}));return()=>{l.forEach(d=>d())}},[a,o,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,s])}function hT(e,t){const{sendData:s}=xt(),[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=$n.subscribe({sendData:s},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{l&&(clearTimeout(l),l=null),o(m.diagnostics),i(!1)});return d.initialSendAccepted?l=setTimeout(()=>{i(!1)},cT):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 pT=[{icon:di,key:"welcome",visual:Lp},{icon:Cn,key:"realtimeChat",visual:pw},{icon:ad,key:"watchAndSteer",visual:Op},{icon:ol,key:"orchestrate",visual:ol}],fT={icon:di,key:"getStartedCloud",code:"curl -fsSL https://adhf.dev/install | sh"},bT={icon:di,key:"allSetStandalone",visual:ui},$l="adhdev:first-run-dialog";function gT({onClose:e,standalone:t=!1}){const[s,r]=c.useState(0),{t:o}=pe("common"),a=[...pT,t?bT:fT],i=a[s],l=s===a.length-1;return c.useEffect(()=>{const d=m=>{m.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(Pt,{size:20})}),n.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:a.map((d,m)=>n.jsx("div",{style:{width:m===s?24:8,height:8,borderRadius:4,background:m===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},m))}),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:`
59
59
  @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
60
60
  @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
61
- `})]})})}function og(e){return e instanceof Error?e.message:String(e||"")}function xT(e){const t=og(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 yT(e){const t=og(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function ag({conversation:e,mode:t,ides:s,sendDaemonCommand:r,setCliViewModeOverrides:o}){if(!e||!ht(e))return;const a=kr(e);if(a===t)return;const i=e.sessionId;i&&o(l=>({...l,[i]:t}));try{await r(Jn(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:On(e),mode:t})}catch(l){const d=yT(l);i&&!d&&o(m=>{const u={...m};return a===wT(s,i)?delete u[i]:u[i]=a,u}),xT(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 Ym(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 vT(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=Ym(o,t),i=Array.isArray(o.childSessions)?o.childSessions.map(d=>Ym(d,t)):o.childSessions,l=i!==o.childSessions;return a!==o||l?(s=!0,{...a,...l?{childSessions:i}:{}}):o});return s?r:e}function wT(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 ST({visibleConversations:e,clearedTabs:t,setClearedTabs:s,setActionLogs:r,isConversationMuted:o}){c.useEffect(()=>{kf()},[]);const a=c.useMemo(()=>e.map(i=>({id:i.tabKey,name:yb(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 hj(a),c.useEffect(()=>{if(Object.keys(t).length===0)return;const l=setTimeout(()=>{s(d=>{const m=Date.now(),u={};for(const[h,p]of Object.entries(d))m-p<5e3&&(u[h]=p);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(l)},[t,s]),c.useEffect(()=>{const i=setInterval(()=>{const l=Date.now()-3e5;r(d=>{const m=d.filter(u=>u.timestamp>l).slice(-100);return m.length===d.length?d:m})},6e4);return()=>clearInterval(i)},[r]),null}function Qm(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 $s(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=Qm(t==null?void 0:t.receivedAt)||Qm(t==null?void 0:t.timestamp)||0;return Math.max(s,r)}function Fl(e,t=0){return $s(e)||e.lastUpdated||t||0}function ig(e){return $s(e)||e.lastUpdated||0}function cg(e,t,s=ig){const r=s(t)-s(e);if(r!==0)return r;const o=(e.machineName||"").localeCompare(t.machineName||"");if(o!==0)return o;const a=e.displayPrimary.localeCompare(t.displayPrimary);if(a!==0)return a;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function Hl(e){var s;const t=Jt(e.status,{activeModal:(s=e.modalButtons)!=null&&s.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function kT(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Hl(e)&&!e.title.trim()}function jT(e){return e.length===0?null:[...e].sort((t,s)=>{const r=Number(Hl(s))-Number(Hl(t));if(r!==0)return r;const o=s.messages.length-t.messages.length;return o!==0?o:cg(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=jT(o);return r?a&&kT(r)?a:r:a||s[0]||null}function NT(e){const t=e.filter(o=>o.type!=="adhdev-daemon"),s=new Set;for(const o of t){if(!bl(o))continue;const a=gf(o);a&&s.add(a)}const r=new Map;for(const o of t){const a=Wk(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),m=l(o),u=m>d||m===d&&(o.timestamp||0)>(i.timestamp||0)?o:i;r.set(a,CT(u,u===o?i:o))}return Array.from(r.values())}function CT(e,t){const s=bl(t),r=bl(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 yc(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 _T(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 Jm(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],s=t[t.length-1],r=s?_T(cr(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 AT(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||""),Jm(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||""),Jm(s.activeChat)].join(":"))].join("|")}function TT(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 IT(e,t){const s=new Map;for(const r of e){const o=t.get(r.routeId)||r;for(const a of oo({routeId:r.routeId}))s.set(a,o);for(const a of oo({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))s.set(a,r.streamSource==="native"?o:r);for(const a of oo({tabKey:r.tabKey}))s.set(a,r)}return s}function MT(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function RT(e){const t=MT(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=cr(t.content).slice(0,240);return`${e.messages.length}:${s}:${r}`}function PT({ides:e,connectionStates:t,clearedTabs:s}){const r=c.useMemo(()=>NT(e),[e]),o=c.useMemo(()=>cf(e),[e]),a=c.useMemo(()=>qb(e),[e]),i=c.useRef([]),l=c.useRef([]),d=c.useRef([]),m=c.useRef(new Map),u=c.useRef(new Map),h=c.useMemo(()=>{const k=new Map,v=[];for(const A of r){const{connectionState:R="new",machineName:P}=zb(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),M=AT(A),E=m.current.get(A.id);if(E&&E.ide===A&&E.sourceSignature===M&&E.connectionState===R&&E.machineName===P){k.set(A.id,E),v.push(...E.conversations);continue}const C=Ld(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),I={ide:A,sourceSignature:M,connectionState:R,machineName:P,conversations:C};k.set(A.id,I),v.push(...C)}m.current=k;const y=new Map,j=A=>{const R=RT(A),P=u.current.get(A.tabKey);if(P&&P.signature===R)return y.set(A.tabKey,P),P.timestamp;const M={signature:R,timestamp:ig(A)||(P==null?void 0:P.timestamp)||0};return y.set(A.tabKey,M),M.timestamp},N=[...v].sort((A,R)=>cg(A,R,j));return u.current=y,N},[r,t,a]),p=c.useMemo(()=>{const k=TT(h,s);return yc(i.current,k)?i.current:(i.current=k,k)},[h,s]),b=c.useMemo(()=>{const k=new Map,v=Array.from(new Set(p.map(y=>y.routeId)));for(const y of v){const j=_n(p,y);j&&k.set(y,j)}return k},[p]),f=c.useMemo(()=>{const k=new Map;for(const v of p){const y=b.get(v.routeId),j=v.streamSource==="native"&&y?y:v;for(const N of oo({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))k.set(N,j)}return k},[p,b]),x=c.useMemo(()=>IT(p,b),[p,b]),g=c.useCallback(k=>{if(k)return f.get(k)},[f]),S=c.useCallback(k=>{if(k)return x.get(k)},[x]),w=c.useMemo(()=>{const k=p.filter(v=>!xs(v,o).surfaceHidden);return yc(l.current,k)?l.current:(l.current=k,k)},[p,o]),_=c.useMemo(()=>{const k=w.map(v=>v.tabKey);return yc(d.current,k)?d.current:(d.current=k,k)},[w]);return{chatIdes:r,conversations:p,visibleConversations:w,visibleTabKeys:_,resolveConversationBySessionId:g,resolveConversationByTarget:S}}function ET({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 DT({ides:e,sendDaemonCommand:t,setToasts:s,resolveConversationByTarget:r,hydrateInteractivePrompt:o}){c.useEffect(()=>{Ze.setIdes(e)},[e]),c.useEffect(()=>{Ze.setResolveAction((a,i,l)=>{t(a,i,l).catch(()=>{})})},[t]),c.useEffect(()=>{Ze.setHydrateInteractivePrompt(o)},[o]),c.useEffect(()=>{const a=Ze.onToast(i=>{s(d=>d.some(u=>u.message===i.message&&i.timestamp-u.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(m=>m.id!==i.id||m.pinned)),l)});return()=>{a()}},[s]),c.useEffect(()=>{const a=If.on("status_event",i=>{Ze.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 m=d.targetSessionId||d.targetKey||d.daemonId,u=r(m),h=(u==null?void 0:u.routeId)||d.daemonId;if(!h)return;const p=Number(d.buttonIndex),b=d.button||((g=u==null?void 0:u.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},...(u==null?void 0:u.sessionId)&&{targetSessionId:u.sessionId},...d.targetSessionId&&{targetSessionId:d.targetSessionId}}).catch(S=>console.error("[SW Action] approval failed:",S))};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 LT="adhdev_dashboardLayout_v1",OT="adhdev_dashboardDockview_v1",$T="adhdev_dashboardDockviewHiddenRestore_v1",qr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Bd(e,t){try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}}function FT(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function lg(e){return`${LT}:${e}`}function HT(e){const t=lg(e);return Bd(t,null)}function BT(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=lg(e);if(s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function dg(e){return`${OT}:${e}`}function WT(e){const t=dg(e);return Bd(t,null)}function UT(e,t){try{const s=dg(e);if(!t){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function ug(e){return`${$T}:${e}`}function KT(e){const t=ug(e);return Bd(t,{})}function qT(e,t){try{const s=ug(e);if(Object.keys(t).length===0){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function zT(){return{groupAssignments:[...qr.groupAssignments],focusedGroup:qr.focusedGroup,groupActiveTabIds:{...qr.groupActiveTabIds},groupTabOrders:{...qr.groupTabOrders},groupSizes:[...qr.groupSizes]}}function VT(e,t){return e?e.length===t.length&&e.every((s,r)=>s===t[r]):t.length===0}function GT(){const[e]=c.useState(()=>FT(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({}),[m,u]=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=HT(e)??zT();s(new Map(A.groupAssignments)),o(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),f(!0)},[b,e]);c.useEffect(()=>{b&&BT(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:a,groupTabOrders:l,groupSizes:m})},[b,e,t,r,a,l,m]),c.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),R=P=>p(P.matches);return A.addEventListener("change",R),()=>A.removeEventListener("change",R)},[]);const g=c.useCallback(A=>{s(A)},[]),S=c.useCallback(A=>{o(A)},[]),w=c.useCallback(A=>{i(A)},[]),_=c.useCallback(A=>{d(A)},[]),k=c.useCallback(A=>{u(A)},[]),v=c.useCallback(A=>{S(A)},[S]),y=c.useCallback((A,R)=>{i(P=>(P[A]??null)===(R??null)?P:{...P,[A]:R})},[]),j=c.useCallback((A,R)=>{d(P=>{const M=P[A];return VT(M,R)?P:{...P,[A]:R}})},[]),N=c.useCallback((A,R)=>{const P=R.get(A)??0;return y(P,A),v(P),P},[v,y]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:g,focusedGroup:r,updateFocusedGroup:S,focusGroup:v,groupActiveTabIds:a,updateGroupActiveTabIds:w,setGroupActiveTab:y,groupTabOrders:l,updateGroupTabOrders:_,setGroupTabOrder:j,groupSizes:m,updateGroupSizes:k,isMobile:h,hasHydratedStoredLayout:b,hydrateStoredLayout:x,focusConversationTab:N}}function YT(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const s=e[0],r=yi(t);return typeof(s==null?void 0:s.id)=="string"&&r.includes(s.id)}function QT({urlActiveTab:e,conversations:t,resolveConversationBySessionId:s,normalizedGroupAssignments:r,hasHydratedStoredLayout:o,hydrateStoredLayout:a,focusConversationTab:i,setSearchParams:l,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,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 S=s(e);S&&(i(S.tabKey,r),b.current=!0,f.current=!0,x.current!=null&&(window.clearTimeout(x.current),x.current=null),l(w=>{const _=new URLSearchParams(w);return _.delete("activeTab"),_},{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(!m||g.current||u)return;const S=h.find(w=>w.id===m.routeId);S&&(!S.chats||S.chats.length===0||YT(S.chats,m))&&(g.current=!0,p())},[d,m,u,h,p])}function vc(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=yi(t);return typeof(s==null?void 0:s.id)=="string"&&r.includes(s.id)}function mg({sendDaemonCommand:e,activeConv:t,chats:s,updateRouteChats:r,setToasts:o,setClearedTabs:a}){const[i,l]=c.useState(!1),[d,m]=c.useState(!1),u=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)||"",S=await e(g,"switch_chat",{id:x,sessionId:x,...fs(t)}),w=S==null?void 0:S.result;if((S==null?void 0:S.success)===!0||w==="switched"||w==="switched-by-title")return;w===!1||w==="not_found"?nr(o,"⚠️ Session tab not found — try refreshing history"):typeof w=="string"&&w.startsWith("error:")?nr(o,`⚠️ Switch error: ${w}`):nr(o,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),nr(o,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,o]),p=c.useCallback(async()=>{if(!(!t||i)){l(!0);try{const f=ms(t);await e(f,"new_chat",{...fs(t)}),vC(f,t.sessionId,yi(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)){m(!0);try{const g=ms(t),S=async()=>e(g,"list_chats",{forceExpand:!0,...fs(t)});let w=await S(),_=(w==null?void 0:w.chats)||((f=w==null?void 0:w.result)==null?void 0:f.chats);vc(_,t)&&(await new Promise(k=>setTimeout(k,450)),w=await S(),_=(w==null?void 0:w.chats)||((x=w==null?void 0:w.result)==null?void 0:x.chats)),w!=null&&w.success&&Array.isArray(_)&&(r(t.routeId,_),vc(_,t)&&!vc(s,t)&&nr(o,"⚠️ History dialog did not fully open — try once more"))}catch(g){console.error("Refresh history failed",g)}finally{m(!1)}}},[t,s,d,e,r,o]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:h,handleNewChat:p,handleRefreshHistory:b}}function JT(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 XT(e,t){return e.length!==t.length?!1:e.every((s,r)=>s===t[r])}function Xm(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 Zo(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 Zm(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 ZT(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 e2(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 eh(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 th(e){return Array(e).fill(100/e)}function t2({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:s,updateGroupActiveTabIds:r,updateGroupTabOrders:o,groupSizes:a,updateGroupSizes:i,isMobile:l,visibleConversations:d,visibleTabKeys:m}){const u=c.useRef(null),h=c.useMemo(()=>Zo(e,m),[e,m]),p=h.assignments,b=c.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),f=b>1,x=c.useCallback((v,y)=>{t(j=>{const N=new Map(Zo(j,m).assignments);return y===0?N.delete(v):N.set(v,y),N}),r(j=>({...j,[y]:v})),s(y)},[t,m,r,s]),g=c.useCallback(v=>{t(y=>{const j=Zo(y,m).assignments,N=new Map;for(const[A,R]of j)R!==v&&(R>v?N.set(A,R-1):N.set(A,R));return N}),i(y=>{if(y.length<=1)return[];const j=[...y];j.splice(v,1);const N=j.reduce((A,R)=>A+R,0);return N>0?j.map(A=>A/N*100):[]}),s(0)},[t,m,i,s]),S=c.useCallback((v,y)=>{y.preventDefault();const j=u.current;if(!j)return;const N=y.clientX,A=j.offsetWidth,R=a.length===b?[...a]:th(b),P=E=>{const I=(E.clientX-N)/A*100,O=[...R];O[v]=Math.max(15,R[v]+I),O[v+1]=Math.max(15,R[v+1]-I),i(O)},M=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",P),document.addEventListener("mouseup",M)},[a,b,i]),w=c.useCallback((v,y,j)=>{if(b>=4)return;const N=j==="left"?y:y+1;t(A=>{const R=Zo(A,m).assignments,P=new Map;for(const M of d){const E=R.get(M.tabKey)??0,C=E>=N?E+1:E;C>0&&P.set(M.tabKey,C)}return N>0&&P.set(v,N),P}),i(A=>{const R=A.length===b?[...A]:th(b),P=R[y]??100/b,M=Math.max(15,P/2),E=Math.max(15,P/2),C=[...R];C[y]=M,C.splice(N,0,E);const I=C.reduce((O,D)=>O+D,0);return C.map(O=>O/I*100)}),r(A=>{const R=eh(A,N);return R[N]=v,R}),o(A=>{const R=eh(A,N);return R[N]=[v],R}),s(N)},[b,t,m,d,i,r,o,s]);c.useEffect(()=>{JT(e,p)||t(p)},[e,p,t]),c.useEffect(()=>{const{mapping:v,usedGroups:y}=h;r(j=>{const N=Zm(j,v);return Xm(j,N)?j:N}),o(j=>{const N=Zm(j,v);return Xm(j,N)?j:N}),s(j=>{const N=l?0:ZT(j,y,v);return j===N?j:N}),i(j=>{const N=l?[]:e2(j,y,h.groupCount);return XT(j,N)?j:N})},[h,l,r,o,s,i]);const _=c.useMemo(()=>{const v=Array.from({length:b},()=>[]);for(const y of d){const j=p.get(y.tabKey)??0,N=Math.min(j,b-1);v[N].push(y)}return v},[d,p,b]),k=c.useCallback(()=>{t(new Map),s(0)},[t,s]);return{containerRef:u,normalizedGroupAssignments:p,numGroups:b,isSplitMode:f,groupedConvs:_,moveTabToGroup:x,closeGroup:g,handleResizeStart:S,splitTabRelative:w,clearAllSplits:k}}function wc(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 n2(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 to(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Wd(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},s=wc(t.channel)||wc(e.updateChannel)||wc(e.releaseChannel)||void 0,r=n2(t.npmTag)||(s==="preview"?"next":s==="stable"?"latest":void 0),o=to(t.targetVersion)||to(e.serverVersion)||void 0,a=to(t.minVersion)||void 0,i=to(t.updateCommand)||(s?"adhdev update":void 0);return{...s?{channel:s}:{},...r?{npmTag:r}:{},...o?{targetVersion:o}:{},...a?{minVersion:a}:{},...i?{updateCommand:i}:{}}}function Is(e,t=null){return Wd(e).targetVersion||t}function s2(e){return Wd(e).channel||null}function Ud(e){return!e||!Wd(e).channel?null:{}}function hg(e,t={},s){const r=to(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 Qa(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 nh(e){var t;return((t=Qa(e))==null?void 0:t.base)??null}function pg(e,t){const s=Qa(e),r=Qa(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 Kd(e,t){const s=e.version||null;return!s||!t||e.versionMismatch===!0&&!Qa(t)?!1:pg(s,t)}function ja(e,t){if(e.versionUpdateRequired===!0)return!0;const s=e.version||null;if(!s||!t||!pg(s,t))return!1;const r=nh(s),o=nh(t);return!r||!o?!1:r[0]!==o[0]||r[1]!==o[1]}function r2({ides:e,sendDaemonCommand:t}){const s="1.0.72",r=c.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:Kd(h,Is(h,s))).sort((h,p)=>Number(ja(p,Is(p,s)))-Number(ja(h,Is(h,s)))),[s,e]),o=c.useMemo(()=>r.some(h=>ja(h,Is(h,s))),[s,r]),a=c.useMemo(()=>r.map(h=>Is(h,s)).find(h=>typeof h=="string"&&h.trim().length>0)||s,[s,r]),[i,l]=c.useState(!1),[d,m]=c.useState({}),u=c.useCallback(async h=>{var f,x;const p=e.find(g=>g.id===h);if(!p)return;m(g=>({...g,[h]:"upgrading"}));const b=Ud(p);if(!b){m(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?m(S=>({...S,[h]:"done"})):m(S=>({...S,[h]:"error"}))}catch{m(g=>({...g,[h]:"error"}))}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:o,targetVersion:a,versionBannerDismissed:i,setVersionBannerDismissed:l,upgradingDaemons:d,handleBannerUpgrade:u}}const fg=80;function Na(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function o2(e){return{...e,createdAt:Na(e.createdAt),updatedAt:Na(e.updatedAt,e.createdAt),lastEventAt:Na(e.lastEventAt,e.updatedAt||e.createdAt)}}function a2(e){const t=bf(e);return t==="unknown:"?e.id:t}function i2(e){return[e.type,ff(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function c2(e,t=fg){const s=new Map;for(const r of e){if(r.deletedAt)continue;const o=a2(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 l2(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=gi(o,t),l=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!l)continue;const d=Na(o.lastMessageAt||(a==null?void 0:a.lastUpdated)||o.lastUpdated,s),m=i2({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(o2({id:m,dedupKey:m,type:l,routeId:o.routeId,machineId:o.daemonId||o.routeId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,tabKey:o.tabKey,title:Ff(o),preview:SN(o),createdAt:d,updatedAt:d,lastEventAt:d}))}return c2(r)}function d2(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function u2(e){const{conversations:t,liveSessionInboxState:s,maxItems:r=fg}=e,o=c.useMemo(()=>l2(t,s).slice(0,Math.max(0,r)),[t,s,r]),a=c.useMemo(()=>d2(o),[o]);return{notifications:o,unreadCount:a}}function m2({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 qd(...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 h2(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 zd(e,t=[]){if(e==="win32"){for(const s of t){if(typeof s!="string")continue;const r=h2(s);if(r)return r}return"C:\\"}for(const s of t){const r=typeof s=="string"?s.trim():"";if(r)return r}return"~"}function p2(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const s=t.includes("\\")?"\\":"/",r=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(r[0]||"")?r.length<=2?`${r[0]}\\`:r.slice(0,-1).join("\\"):r.length<=2?s:r.slice(0,-1).join(s)||s}function f2(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Vd(e,t,s){const r=await e(t,"file_list_browse",{path:s}),o=f2(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=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${i}${u}`:`${m.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(o==null?void 0:o.files)?o.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:l(a,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:a,directories:d}}function sh(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 b2(e,t={}){const s=e==null?void 0:e.mcpConfig;if((s==null?void 0:s.mode)!=="manual")return null;const o=sh(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"}).trim();return!o.includes(`
62
- `)&&!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:sh(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"})}}function g2(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 yo(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function bg(e){return vi(e)||e.tabKey||e.routeId||null}function gg(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 ds(e){return String(e||"").trim()}function xg(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Ja(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function x2(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function y2(e,t){const s=ds(e.providerSessionId),r=ds(e.targetSessionId),o=t.find(a=>{const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey,a.routeId].map(ds).filter(Boolean);return!!(s&&i.includes(s)||r&&i.includes(r))});return o?o.tabKey:r||s||null}function v2(e,t,s){if(t.event!=="agent:generating_completed")return null;const r=xg(t.daemonId);if(r&&r!==e.machineId)return null;const o=ds(t.providerType);if(e.providerType&&o!==e.providerType)return null;const a=ds(e.resumeSessionId),i=ds(e.launchedSessionId),l=ds(t.providerSessionId),d=ds(t.targetSessionId);if(a&&a!==l&&a!==d||i&&i!==l&&i!==d)return null;const m=Ja(e.workspacePath);if(m){const u=Ja(t.workspaceName);if(u&&!x2(u,m))return null}return y2(t,s)}function rh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function w2({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=Ja(r.workspacePath),m=e.find(h=>{var g,S,w,_;if(!h||h.type==="adhdev-daemon"||xg(h.daemonId||h.id)!==r.machineId||(xo(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 k=String(r.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(y=>String(y||"")).filter(Boolean).includes(k)}if(d){const k=Ja(h.workspace||h.runtimeWorkspaceLabel);return k?k===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((_=(w=(S=(g=h.activeChat)==null?void 0:g.messages)==null?void 0:S.at)==null?void 0:w.call(S,-1))==null?void 0:_.timestamp)||0)>=r.startedAt-5e3});if(!m)return;const u=gg({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(i(),s(u))},[i,t,e,s,r]),c.useEffect(()=>Ze.onStatusEvent(d=>{const m=a.current;if(!m)return;const u=v2(m,d,t);u&&(i(),s(u))}),[i,t,s]),c.useEffect(()=>{if(!r)return;const d=window.setTimeout(()=>{o(m=>!m||m.startedAt!==r.startedAt?m:(a.current=null,null))},45e3);return()=>window.clearTimeout(d)},[r]),{trackPendingLaunch:l}}function S2(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 k2(e,t,s){var i,l,d,m;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((m=s==null?void 0:s.settings)==null?void 0:m.autoApprove)=="boolean"&&(r.autoApprove=s.settings.autoApprove),r}function j2({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:s,activeConv:r,ides:o,setCliViewModeOverrides:a}){const i=Td(),{launchCli:l}=mi(),d=c.useCallback(async(g,S)=>Vd(e,g,S),[e]),m=c.useCallback(async(g,S)=>{if(!S.trim())return{ok:!1,error:"Choose a workspace path first."};try{const w=await e(g,"workspace_add",{path:S.trim()});return w!=null&&w.success?{ok:!0}:{ok:!1,error:(w==null?void 0:w.error)||"Could not save workspace"}}catch(w){return{ok:!1,error:w instanceof Error?w.message:"Could not save workspace"}}},[e]),u=c.useCallback(async(g,S,w)=>{var _;try{const k={ideType:S,enableCdp:!0};(_=w==null?void 0:w.workspacePath)!=null&&_.trim()&&(k.workspace=w.workspacePath.trim());const v=await e(g,"launch_ide",k);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:S,workspacePath:(w==null?void 0:w.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(k){return{ok:!1,error:k instanceof Error?k.message:"Could not launch IDE"}}},[e,t]),h=c.useCallback(async(g,S,w,_)=>{const k=Date.now();try{const v=S2(w,_),y=await l(g,v),j=(y==null?void 0:y.result)||y,N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return y!=null&&y.success&&N?(t({machineId:g,kind:S,providerType:w,workspacePath:(_==null?void 0:_.workspacePath)||null,resumeSessionId:(_==null?void 0:_.resumeSessionId)||null,launchedSessionId:N,startedAt:k}),{ok:!0}):y!=null&&y.success?(t({machineId:g,kind:S,providerType:w,workspacePath:(_==null?void 0:_.workspacePath)||null,resumeSessionId:(_==null?void 0:_.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(j==null?void 0:j.error)||`Could not launch ${S.toUpperCase()} session`,code:(y==null?void 0:y.code)||(j==null?void 0:j.code)||void 0}}catch(v){return rh(v)?(t({machineId:g,kind:S,providerType:w,workspacePath:(_==null?void 0:_.workspacePath)||null,resumeSessionId:(_==null?void 0:_.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${S.toUpperCase()} session`}}},[l,e,t]),p=c.useCallback(async g=>{var S;if(i!=null&&i.listMeshes){const w=await i.listMeshes(g);return Ha(w),w}if(!g)return[];try{const w=await e(g,"list_meshes",{}),_=(w==null?void 0:w.result)??w;if((_==null?void 0:_.success)===!1)throw new Error((_==null?void 0:_.error)||"Could not load meshes");const v=(Array.isArray(_==null?void 0:_.meshes)?_.meshes:Array.isArray((S=_==null?void 0:_.result)==null?void 0:S.meshes)?_.result.meshes:[]).map(y=>{var j;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(((j=y.nodes[0])==null?void 0:j.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 Ha(v),v}catch(w){throw console.error("List meshes failed",w),w}},[i,e]),b=c.useCallback(async(g,S,w,_)=>{if(!S.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(g,S,w,_);const k=Date.now();try{const v=k2(S,w,_),y=await e(g,"launch_mesh_coordinator",v),j=(y==null?void 0:y.result)??y;if((j==null?void 0:j.success)===!1||(y==null?void 0:y.success)===!1){const A=String((j==null?void 0:j.code)||(y==null?void 0:y.code)||""),R=g2((j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(j==null?void 0:j.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:R}}const N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return N?s(N):t({machineId:g,kind:"cli",providerType:(j==null?void 0:j.cliType)||w.trim()||void 0,workspacePath:(j==null?void 0:j.workspace)||null,startedAt:k}),{ok:!0}}catch(v){return rh(v)?(t({machineId:g,kind:"cli",providerType:w.trim()||void 0,startedAt:k}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,s,e,t]),f=c.useCallback(async(g,S)=>{if(!g||!S)return[];try{const w=await e(g,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),_=(w==null?void 0:w.result)??w;return Array.isArray(_==null?void 0:_.sessions)?_.sessions:[]}catch(w){return console.error("List saved sessions failed",w),[]}},[e]),x=c.useCallback(async g=>{await ag({conversation:r,mode:g,ides:o,sendDaemonCommand:e,setCliViewModeOverrides:a})},[r,o,e,a]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:m,handleLaunchMachineIde:u,handleLaunchMachineProvider:h,handleListMachineMeshes:p,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:f,setActiveCliViewMode:x}}function N2(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 C2(e,t,s=Date.now()){return!e||!N2(t)?null:{tabKey:e,nonce:s}}function _2({isMobile:e,conversations:t,visibleConversations:s,groupActiveTabIds:r,focusedGroup:o,groupedConvs:a,setSearchParams:i}){const[l,d]=c.useState(null),[m,u]=c.useState(null),h=c.useMemo(()=>{var g,S;if(!e){if(l){const w=t.find(_=>_.tabKey===l);if(w)return w}return s[0]}const x=r[o];if(x){const w=t.find(_=>_.tabKey===x);if(w)return w}return((g=a[o])==null?void 0:g[0])||((S=a[0])==null?void 0:S[0])},[t,l,o,r,a,e,s]),p=c.useCallback(x=>{d(x)},[]),b=c.useCallback(x=>{d(x.tabKey),i(g=>{const S=new URLSearchParams(g),w=jN(x);return w?S.set("activeTab",w):S.delete("activeTab"),S},{replace:!0})},[i]),f=c.useCallback((x,g)=>{const S=C2(x,g);S&&u(S)},[]);return{activeConv:h,openDesktopConversation:b,requestScrollToBottom:f,scrollToBottomRequest:m,setDesktopActiveTab:p}}function A2(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 T2(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 I2({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 m=()=>{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){m(),o.current=null;return}if(!(e!=null&&e.sessionId)){m(),o.current=null;return}const u=xs(e,s),h=T2({tabKey:e.tabKey,historySessionId:vi(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:$s(e),liveState:u}),p=h.autoReadKey,b=A2({autoReadKey:p,shouldMarkSeen:h.shouldMarkSeen,completedKey:o.current,pendingKey:a.current});if(!h.shouldMarkSeen){b.shouldCancelPending&&m(),o.current=p;return}if(!b.shouldSchedule)return;b.shouldCancelPending&&m();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 Sc(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 M2({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:s,ides:r,sendDaemonCommand:o,updateRouteChats:a,setToasts:i,setClearedTabs:l,setSearchParams:d}){var F;const{launchCli:m}=mi(),[u,h]=c.useState(!1),[p,b]=c.useState([]),[f,x]=c.useState(()=>dn()),[g,S]=c.useState(!1),[w,_]=c.useState(null),k=c.useRef(null),v=c.useMemo(()=>s||t||e,[e,s,t]),y=!!v&&ht(v),j=c.useMemo(()=>{if(!v||!y)return null;const z=v.daemonId||v.routeId||"",Z=On(v),W=Sc(v);return`${z}:${Z}:${v.providerSessionId||""}:${W}`},[v,y]),N=c.useMemo(()=>!v||!y?"":Sc(v),[v,y]),{isCreatingChat:A,isRefreshingHistory:R,handleSwitchSession:P,handleNewChat:M,handleRefreshHistory:E}=mg({sendDaemonCommand:o,activeConv:v,chats:(F=r.find(z=>z.id===(v==null?void 0:v.routeId)))==null?void 0:F.chats,updateRouteChats:a,setToasts:i,setClearedTabs:l}),C=c.useCallback(()=>{h(!0)},[]),I=c.useCallback(()=>{h(!1)},[]),O=c.useCallback(async()=>{if(!(!v||!y||g)){S(!0);try{const z=v.daemonId||v.routeId,Z=On(v),W=Sc(v),T=await o(z,"list_saved_sessions",{agentType:Z,providerType:Z,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...W?{workspace:W}:{}}),$=(T==null?void 0:T.result)??T;b(Array.isArray($==null?void 0:$.sessions)?$.sessions:[])}catch(z){console.error("Refresh saved sessions failed",z),b([])}finally{S(!1)}}},[v,g,y,o]);c.useEffect(()=>{if(!u){k.current=null;return}if(!y){k.current=null,b([]),S(!1);return}!j||g||k.current!==j&&(k.current=j,O())},[O,u,g,y,j]);const D=c.useCallback(async z=>{if(!v||!y||!z.providerSessionId||!z.workspace)return;const Z=v.daemonId||v.routeId,W=On(v);try{_(z.providerSessionId);const T=Yk(z.summaryMetadata,"model",{preferShortValue:!0})||void 0,$=await m(Z,{cliType:W,dir:z.workspace,resumeSessionId:z.providerSessionId,initialModel:T,...T?{modelSource:"remembered"}:{}}),H=($==null?void 0:$.result)??$,q=typeof(H==null?void 0:H.sessionId)=="string"?H.sessionId:typeof(H==null?void 0:H.id)=="string"?H.id:"";q&&d(U=>{const K=new URLSearchParams(U);return K.set("activeTab",q),K},{replace:!0}),I()}catch(T){console.error("Resume saved session failed",T)}finally{_(null)}},[I,v,y,o,d]);return{historyModalOpen:u,openHistoryModal:C,closeHistoryModal:I,historyTargetConv:v,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:A,isHistoryRefreshingHistory:R,handleHistorySwitchSession:P,handleHistoryNewChat:M,handleHistoryRefresh:E,savedHistorySessions:p,savedHistoryFilters:f,setSavedHistoryFilters:x,missingWorkspaceResumePath:N,isSavedHistoryLoading:g,resumingSavedHistorySessionId:w,handleRefreshSavedHistory:O,handleResumeSavedHistorySession:D}}function R2({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:l}){const[d,m]=c.useState(null),[u,h]=c.useState(null),p=c.useMemo(()=>{if(e||!r)return null;const S=l(r);return S&&!ht(S)?S:null},[e,r,l]),b=c.useMemo(()=>{const S=d==null?void 0:d.routeId;if(!S)return null;const w=d!=null&&d.tabKey?a.find(_=>_.tabKey===d.tabKey):o?a.find(_=>_.tabKey===o):null;return(w==null?void 0:w.routeId)===S?w:_n(a,S)},[a,d,o]),f=c.useMemo(()=>{if(b)return i.find(S=>S.id===b.routeId)},[i,b]);c.useEffect(()=>{p&&(m({routeId:p.routeId,tabKey:Ju(p)}),h(p),s({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,s,p]);const x=c.useCallback(S=>{S&&(m({routeId:S.routeId,tabKey:Ju(S)}),h(S))},[]),g=c.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:b,remoteDialogIdeEntry:f,remoteDialogActiveConv:u,setRemoteDialogActiveConv:h,openRemoteDialog:x,closeRemoteDialog:g}}function P2({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:p,setRemoteDialogActiveConv:b,openRemoteDialog:f,closeRemoteDialog:x}=R2({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:l}),[g,S]=c.useState(!1),[w,_]=c.useState(null),k=c.useCallback(async j=>{const N=j||d;!N||!ht(N)||(_(N),S(!0))},[d]),v=c.useCallback(()=>{S(!1),_(null)},[]),y=c.useCallback(async j=>{const N=w||d;if(!N||!ht(N)){v();return}S(!1);try{const A=On(N),R=N.routeId||N.daemonId||"";await m(R,"stop_cli",{cliType:A,targetSessionId:N.sessionId,mode:j,...ji(N)})}catch(A){console.error("Stop CLI failed:",A)}finally{_(null)}},[d,v,w,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:p,setRemoteDialogActiveConv:b,openRemoteDialog:f,closeRemoteDialog:x,cliStopDialogOpen:g,cliStopTargetConv:w,requestCliStop:k,cancelCliStop:v,confirmCliStop:y}}function kc(e,t=!0){return(e??!0)&&t}const Gd=c.memo(function({activeConv:t,clearToken:s,isCliTerminal:r,ideEntry:o,terminalRef:a,commands:i,actionLogs:l,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:h=!0}){const{handleModalButton:p,handleRelaunch:b,handleSendChat:f,handleSendNowQueued:x,handleCancelQueued:g,isSendingChat:S,sendFeedbackMessage:w,pendingLocalMessage:_,pendingLocalMessages:k,retireEchoedPendingMessages:v,handleFocusAgent:y,isFocusingAgent:j}=i,N=r,A=!r,R=kc(h,N),P=kc(h,A),M=kc(h),{t:E}=pe("common"),C=I=>n.jsx(db,{activeConv:t,ideEntry:o,handleSendChat:f,handleSendNowQueued:x,handleCancelQueued:g,isSendingChat:S,sendFeedbackMessage:w,pendingLocalMessage:_,pendingLocalMessages:k,retireEchoedPendingMessages:v,handleFocusAgent:y,isFocusingAgent:j,actionLogs:l,userName:d,scrollToBottomRequestNonce:m,isInputActive:u&&I,isVisible:I});return n.jsxs(n.Fragment,{children:[n.jsx(df,{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(Xt,{size:14})}),n.jsxs("span",{className:"flex flex-1 items-center gap-1",children:[n.jsx("span",{className:"font-semibold",children:E("paneGroup.cdpDisconnectedShort")}),n.jsx(tt,{content:E("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:E("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:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:n.jsx(k_,{activeConv:t,clearToken:s,terminalRef:a,handleSendChat:f,isSendingChat:S,sendFeedbackMessage:w,isVisible:R,isInputActive:u&&R})}),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:C(P)})]}):C(M)]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.commands===t.commands&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function E2({conversation:e,className:t="",onOpenNativeConversation:s,onOpenMachine:r,interactive:o=!0,meshOnly:a=!1}){const{t:i}=pe("common"),l=qs(),d=Jn(e),m=a?null:$f(e),u=!a&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),h=!a&&e.streamSource==="agent-stream"&&!!e.agentName,p=!a&&!h&&e.transport==="pty",b=hr(e),f=kN(e),x=kd(e).role,g=e.meshQueueStats,S=x==="coordinator",w=c.useCallback(()=>{if(r){r();return}d&&l("/dashboard",{state:{openMachineId:d}})},[d,l,r]),_=c.useCallback(()=>{if(s){s();return}const k=bg(e);k&&l(yo(k))},[e,l,s]);return!u&&!h&&!p&&!m&&!x&&!g?null:n.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(o?n.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:_,title:f,children:[n.jsx(Hn,{size:12}),n.jsx("span",{children:f})]}):n.jsxs("span",{className:"conversation-meta-chip",title:f,children:[n.jsx(Hn,{size:12}),n.jsx("span",{children:f})]})),h&&n.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[n.jsx(ur,{size:12}),n.jsx("span",{children:b})]}),p&&n.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[n.jsx(ur,{size:12}),n.jsx("span",{children:b})]}),m&&(o?n.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:m,children:[n.jsx(dr,{size:12}),n.jsx("span",{children:m})]}):n.jsxs("span",{className:"conversation-meta-chip",title:m,children:[n.jsx(dr,{size:12}),n.jsx("span",{children:m})]})),S&&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(ew,{size:12}),n.jsx("span",{children:i("dashboard.metaChips.queuePending",{count:g.pending})})]})]})}function D2({selectedConversation:e,isStandalone:t,selectedIdeEntry:s,actionLogs:r,userName:o,commands:a,onBack:i,onOpenNativeConversation:l,onOpenMachine:d,onOpenHistory:m,onOpenRemote:u,onOpenMeshGraph:h,onStopCli:p,cliViewMode:b,onSetCliViewMode:f}){const{t:x}=pe("common"),g=c.useRef(null),S=xi(lf(e)),w=ht(e),_=w&&b==="terminal",k=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 ${k} 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(rd,{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(vs,{conversation:e,size:15}),n.jsx("span",{className:"min-w-0 truncate",children:wt(e)})]}),n.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:n.jsx(E2,{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:[w&&b&&n.jsx(kb,{mode:b,onChange:f,compact:!0}),w&&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(Pt,{size:14})}),n.jsx($b,{conversation:e,onOpenMeshGraph:h}),n.jsx(Lb,{conversation:e,onOpenHistory:m,onOpenRemote:u,iconSize:14})]})]}),n.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:n.jsx(Gd,{activeConv:e,clearToken:0,isCliTerminal:_,ideEntry:s,terminalRef:g,commands:a,actionLogs:r,userName:o})}),n.jsx(hd,{promptSession:S.promptSession,isSubmitting:S.isSubmitting,error:S.responseError,onSubmit:S.submit,onCancel:S.cancel})]})}function L2(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function yg({isStandalone:e=!1}={}){const{t}=pe("common"),[s,r]=c.useState("unix"),[o,a]=c.useState("powershell"),[i,l]=c.useState(!1),d=s==="unix"?"unix":o,m=c.useMemo(()=>eA(),[]);c.useEffect(()=>{r(L2())},[]);const u=c.useCallback(()=>{navigator.clipboard.writeText(m[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:u,title:t("app.installCommand.clickToCopy"),children:[n.jsx("span",{className:"text-text-muted select-none",children:m[d].prompt}),n.jsx("span",{className:"flex-1 break-all",children:m[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(xr,{size:12}):n.jsx(od,{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 vg({section:e,onSectionChange:t}){const{t:s}=pe("common"),r=[{key:"machines",label:s("nav.machines"),icon:Hn},{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 ea({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 Qs({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 Cs({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 O2({title:e,isMuted:t,onToggleMute:s,onHide:r,onStop:o}){const{t:a}=pe(),[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 m="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",u=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(rl,{size:13}):n.jsx(Ip,{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 ${m}`,onClick:u(s),children:[t?n.jsx(gs,{size:15}):n.jsx(rl,{size:15}),a(t?"conversation.unmuteThis":"conversation.muteThis")]}),r&&n.jsxs("button",{type:"button",role:"menuitem",className:`mobile-inbox-hide-button ${m}`,onClick:u(r),children:[n.jsx(li,{size:15}),a("mobileInbox.hide")]}),o&&n.jsxs("button",{type:"button",role:"menuitem",className:`mobile-inbox-stop-button ${m} !text-status-error`,onClick:u(o),children:[n.jsx(Pt,{size:15}),a("mobileInbox.stopSessionTitle")]})]})]})}function ta({item:e,type:t,getAvatarText:s,onOpenConversation:r,onRequestHideConversation:o,onRequestStopCli:a,onOpenMeshGraph:i,onCollectChatDebugBundle:l,isMuted:d,onToggleMute:m}){const{t:u}=pe(),h=t==="needs_attention"||t==="task_complete",p=t==="working",b=t==="earlier",f=t==="task_complete",{isReconnecting:x,isConnecting:g,isErrored:S}=ws(e.conversation),w=wt(e.conversation),_=To(e.conversation),k=xb(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",j=b?"text-text-secondary":"text-text-primary",N=b?"text-text-muted":"text-text-secondary",A=b?"text-text-secondary opacity-80":"text-text-muted",R=b?"text-text-muted opacity-80":"text-text-muted",P=!p&&!f,M=fb(e.conversation),E="text-[color:var(--status-warning)]",C=I=>{if(!l||!S_())return;I.preventDefault(),I.stopPropagation();const O=l==null?void 0:l(e.conversation);Promise.resolve(O).catch(D=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",D)})};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(w)}),M&&i&&n.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-[color:color-mix(in_srgb,var(--mesh-coordinator)_34%,transparent)] bg-bg-primary/70 text-[color:var(--mesh-coordinator)] transition-colors hover:bg-[color:color-mix(in_srgb,var(--mesh-coordinator)_10%,transparent)]",onClick:I=>{I.preventDefault(),I.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:w}),title:u("mobileInbox.openLiveMeshGraph"),children:n.jsx(Ln,{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:C,type:"button",children:[n.jsxs("div",{className:"flex items-center gap-1.5 pr-[92px]",children:[n.jsx(vs,{conversation:e.conversation,size:13}),n.jsx("span",{className:`text-[15px] leading-[22px] font-bold truncate tracking-tight ${j}`,children:w})]}),n.jsxs("div",{className:`text-xs font-medium truncate flex items-center ${N}`,children:[n.jsx("span",{className:"truncate",children:_}),n.jsx(Nd,{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:`${E} animate-pulse`,children:u("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:u("mobileInbox.connectingItem")})]}):k==="Action needed"?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:E,children:u("mobileInbox.actionNeeded")})]}):S&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:"text-[color:var(--status-error)]",children:u("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 ${R}`,children:Fp(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:u("mobileInbox.done")}),n.jsx(O2,{title:w,isMuted:d,onToggleMute:m,onHide:o,onStop:a})]})]})},e.conversation.tabKey)}function oh({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 $2({section:e,attentionItems:t,unreadItems:s,workingItems:r,completedItems:o,hiddenConversations:a,machineCards:i,getAvatarText:l,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:h,onHideConversation:p,onShowHiddenConversation:b,onOpenMeshGraph:f,onStopCli:x,onOpenNewSession:g,onOpenMachine:S,onOpenSettings:w,onSectionChange:_,wsStatus:k="connected",initialDataLoaded:v=!0,conversationsLoaded:y,isStandalone:j=!1,onCollectChatDebugBundle:N,isConversationMuted:A,onToggleMuteConversation:R}){const{t:P}=pe(),M=k==="disconnected"||k==="reconnecting"||k==="offline"||k==="auth_failed",E=!M&&!v,C=!M&&!(y??v),I=i.length>0,O=t.length>0||s.length>0||r.length>0||o.length>0,D=P(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),F=j?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",z=j?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",Z=c.useCallback(async $=>{const H=ms($);if(!H)return;const q=Array.isArray($.messages)?$.messages:[],U=zf({activeConv:$,visibleMessages:q,actionLogs:d,visibleBarControlCount:0,chatState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:q.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),K=await m(H,"get_chat_debug_bundle",{...fs($),delivery:"daemon_file",frontendSnapshot:U}),oe=Ps(K),ke=Yf(oe),J=await Gf(ke);J==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),Ze.showToast(Vf(oe,{locatorCopyStatus:J}),J==="failed"?"warning":"success")},[d,m]),W=N||Z,T=c.useCallback($=>{p&&(p($),Ze.showToast(P("mobileInbox.hiddenToast",{title:wt($)}),"info",{duration:6e3,actions:[{label:P("mobileInbox.undo"),variant:"primary",onClick:()=>{b?b($):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 ${F}`,children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:D}),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(gs,{size:13}),n.jsx("span",{children:t.length+s.length})]}),n.jsx("button",{onClick:w,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(yr,{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] ${z}`,children:[e==="machines"&&n.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?n.jsx(Cs,{icon:n.jsx(Zt,{size:32}),title:P(k==="offline"?"mobileInbox.networkOffline":k==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:P(k==="offline"?"mobileInbox.waitingForNetwork":k==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):E?n.jsx(Cs,{icon:n.jsx(Zt,{size:32}),title:P("mobileInbox.loading"),subtitle:P("mobileInbox.loadingSubtitle")}):i.length===0?n.jsx(Cs,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:P(j?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:P(j?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!j&&n.jsx("div",{className:"w-full max-w-[360px] mt-4",children:n.jsx(yg,{})})}):n.jsx(Qs,{children:i.map(($,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:()=>S($.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($.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:$.label}),n.jsxs("span",{className:"flex items-center gap-2 text-2xs font-medium text-text-muted shrink-0",children:[n.jsx(oh,{count:$.generatingCount,label:P("mobileInbox.generatingCount",{count:$.generatingCount})}),$.unread>0?n.jsx("span",{className:"text-accent-primary",children:P("mobileInbox.newCount",{count:$.unread})}):$.total>0?P("mobileInbox.chatCount",{count:$.total}):P("mobileInbox.idle")]})]}),n.jsx("div",{className:"text-xs font-medium text-text-secondary truncate",children:$.subtitle}),$.total>0?n.jsxs("div",{className:"text-xxs text-text-muted mt-0.5",children:[P("mobileInbox.chatCount",{count:$.total}),$.unread>0?P("mobileInbox.unreadSuffix",{count:$.unread}):"",$.generatingCount>0?P("mobileInbox.collapsedGeneratingSuffix",{count:$.generatingCount}):""]}):$.generatingCount>0?n.jsx("div",{className:"text-xxs text-accent-primary mt-0.5 font-medium",children:P("mobileInbox.generatingCount",{count:$.generatingCount})}):n.jsx("div",{className:"text-xxs text-text-muted mt-0.5 italic opacity-70",children:P("mobileInbox.noActiveChats")})]})]},$.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(ea,{title:P("mobileInbox.needsAttention"),className:"mb-0"}),n.jsx(Qs,{children:t.map(($,H)=>n.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:n.jsx(ta,{item:$,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:p?()=>T($.conversation):void 0,onRequestStopCli:x?()=>x($.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:W,isMuted:A==null?void 0:A($.conversation),onToggleMute:R?()=>R($.conversation):void 0})},$.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(ea,{title:P("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),n.jsx(Qs,{children:s.map(($,H)=>n.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:n.jsx(ta,{item:$,type:"task_complete",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:p?()=>T($.conversation):void 0,onRequestStopCli:x?()=>x($.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:W,isMuted:A==null?void 0:A($.conversation),onToggleMute:R?()=>R($.conversation):void 0})},$.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(ea,{title:P("mobileInbox.workingNow"),className:"mb-0 mt-2"}),n.jsx(Qs,{children:r.map(($,H)=>n.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:n.jsx(ta,{item:$,type:"working",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:p?()=>T($.conversation):void 0,onRequestStopCli:x?()=>x($.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:W,isMuted:A==null?void 0:A($.conversation),onToggleMute:R?()=>R($.conversation):void 0})},$.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(ea,{title:P("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?n.jsx(Qs,{children:o.map(($,H)=>n.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:n.jsx(ta,{item:$,type:"earlier",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:p?()=>T($.conversation):void 0,onRequestStopCli:x?()=>x($.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:W,isMuted:A==null?void 0:A($.conversation),onToggleMute:R?()=>R($.conversation):void 0})},$.conversation.tabKey))}):O?n.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:P("mobileInbox.allCaughtUp")}):M?n.jsx(Cs,{icon:n.jsx(Zt,{size:28}),title:P("mobileInbox.connecting"),subtitle:P("mobileInbox.connectingSubtitle")}):C?n.jsx(Cs,{icon:n.jsx(Zt,{size:28}),title:P("mobileInbox.loading"),subtitle:P("mobileInbox.loadingSubtitle")}):I?n.jsx(Cs,{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(Cs,{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 $=I0(a);return n.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:n.jsx(Qs,{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(oh,{count:$,label:P("mobileInbox.generatingCount",{count:$})})]}),n.jsxs("div",{className:"mt-0.5 text-xxs text-text-muted",children:[P("mobileInbox.collapsedCount",{count:a.length}),$>0?P("mobileInbox.collapsedGeneratingSuffix",{count:$}):""]})]}),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&&O&&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(vg,{section:e,onSectionChange:_})]})}function F2(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=go(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(t?t("launch.messageCountShort",{count:e.messageCount}):`${e.messageCount} msgs`);const o=F2(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 Yd({title:e,description:t,currentPath:s,directories:r,busy:o=!1,error:a="",confirmLabel:i,inline:l=!1,onClose:d,onNavigate:m,onConfirm:u}){const[h,p]=c.useState(s),{t:b}=pe("common"),f=i??b("machine.workspaceBrowse.useThisFolder");c.useEffect(()=>{p(s)},[s]);const x=p2(s),g=h.trim(),S=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(Pt,{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||m(x)},disabled:!x||o,children:[n.jsx(rd,{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:w=>p(w.target.value),onKeyDown:w=>{w.key!=="Enter"||!g||o||(w.preventDefault(),m(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||m(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(w=>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:()=>m(w.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(Hs,{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:w.name}),n.jsx("span",{className:"block text-2xs text-text-muted truncate",children:w.path})]})]},w.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:()=>u(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:S}):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:S})})})}function Ei({title:e,description:t,details:s,workspaceOptions:r,selectedWorkspaceKey:o,onWorkspaceChange:a,confirmLabel:i,busyLabel:l,busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:h,showModelInput:p,modelValue:b,onModelChange:f,historyProviderNode:x,onConfirm:g,onCancel:S}){const{t:w}=pe("common"),_=i??w("machine.launchConfirm.launch"),k=l??w("machine.launchConfirm.launching"),v=r==null?void 0:r.find(j=>j.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:S,"aria-label":w("machine.launchConfirm.closeAria"),children:n.jsx(Pt,{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:w("machine.launchConfirm.workspace")}),n.jsx("select",{value:o||"",onChange:j=>a(j.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(j=>n.jsx("option",{value:j.key,children:j.label},j.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((j,N)=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),n.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${N}`)),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:w("machine.launchConfirm.languageModel")}),n.jsx("input",{type:"text",value:b||"",onChange:j=>f(j.target.value),placeholder:w("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})]}),m&&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:w("machine.launchConfirm.cliArgs")}),n.jsx("input",{type:"text",value:u||"",onChange:j=>h(j.target.value),placeholder:w("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:S,disabled:d,children:w("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(Tp,{size:14}),d?k:_]})]})]})});return typeof document>"u"?y:Wn.createPortal(y,document.body)}function ah(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Sg(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 u of t.workspaces||[])l.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${ah(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const d=(s==null?void 0:s.trim())||"",m=d?(t.workspaces||[]).find(u=>u.path===d):null;if(d&&!m&&l.push({key:`custom:${d}`,label:ah(d),description:d,workspaceId:null,workspacePath:d}),r){const u=`saved:${r}`;if(l.some(h=>h.key===u))return{options:l,selectedKey:u}}return m?{options:l,selectedKey:`saved:${m.id}`}:d?{options:l,selectedKey:`custom:${d}`}:{options:l,selectedKey:"__home__"}}function H2(e){return e==="ide"?"IDE":"CLI"}function B2(e,t){return[H2(e.kind),e.subtitle||"",e.providerSessionId?t?t("launch.savedHistoryBadge"):"Saved history":""].filter(Boolean).join(" · ")}function W2(e){return e.lastLaunchedAt?hi(e.lastLaunchedAt):""}function kg(e,t){return{metaText:B2(e,t),updatedLabel:W2(e)}}function jc(e,t){return e?"ide":t>0?"cli":null}function U2({selectedMachineEntry:e,cliProviders:t,machineAction:s,onBrowseDirectory:r,onListSavedSessions:o}){var he,Me,Ee,Te;const a=jr(),[i,l]=c.useState(!1),d=(((he=e.detectedIdes)==null?void 0:he.length)||0)>0,m=c.useMemo(()=>(e.workspaces||[]).map(Ne=>({id:Ne.id,path:Ne.path,label:Ne.label})),[e]),u=e.defaultWorkspaceId||null,[h,p]=c.useState(u||((Me=m[0])==null?void 0:Me.id)||""),[b,f]=c.useState(""),[x,g]=c.useState(""),[S,w]=c.useState([]),[_,k]=c.useState(!1),[v,y]=c.useState(""),[j,N]=c.useState(!1),[A,R]=c.useState(jc(d,t.length)),P=c.useRef(null),[M,E]=c.useState(null),C=c.useRef("__home__"),[I,O]=c.useState("__home__"),[D,F]=c.useState(""),[z,Z]=c.useState(""),[W,T]=c.useState(""),[$,H]=c.useState([]),[q,U]=c.useState(()=>dn().textQuery),[K,oe]=c.useState(()=>dn().workspaceQuery),[ke,J]=c.useState(()=>dn().modelQuery),[ye,ae]=c.useState(()=>dn().resumableOnly),[re,de]=c.useState(()=>dn().sortMode),[ne,ie]=c.useState(!1),[_e,G]=c.useState(!1),B=c.useRef(0),Q=c.useRef(0),ue=c.useRef(null),Re=c.useRef(null);c.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&a(e.id,{minFreshMs:3e4}).catch(()=>{})},[a,e]);const Le=h==="__custom__"?b.trim():((Ee=m.find(Ne=>Ne.id===h))==null?void 0:Ee.path)||"",Pe=h==="__custom__"&&!!Le&&s.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(s.message),Fe=h!=="__custom__"&&((Te=m.find(Ne=>Ne.id===h))==null?void 0:Te.path)||"",X=c.useMemo(()=>(e.recentLaunches||[]).map(Ne=>Ne.workspace),[e]),ve=c.useCallback(async Ne=>{const Ue=B.current+1;B.current=Ue,k(!0),y("");try{const $e=await r(Ne);if(B.current!==Ue)return;g($e.path),f($e.path),w($e.directories)}catch($e){if(B.current!==Ue)return;y($e instanceof Error?$e.message:"Could not load folder")}finally{B.current===Ue&&k(!1)}},[r]),Se=c.useCallback(()=>{var Ue;p("__custom__"),N(!0);const Ne=zd(e.platform,qd(b.trim(),Fe,X,e.defaultWorkspacePath,(Ue=m.find($e=>$e.id===u))==null?void 0:Ue.path,m.map($e=>$e.path)));ve(Ne)},[b,u,ve,X,Fe,e.platform,m]),Ce=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("")},[]),L=c.useCallback(Ne=>{if(p(Ne),Ne==="__custom__"){Se();return}f("")},[Se]),Y=c.useCallback(Ne=>{p("__custom__"),f(Ne)},[]),ce=c.useCallback((Ne,Ue)=>{const $e=Q.current+1;Q.current=$e,P.current=Ue,C.current=Ne.selectedWorkspaceKey||"__home__",O(Ne.selectedWorkspaceKey||"__home__"),F(Ne.initialArgs||""),Z(Ne.initialModel||""),T(""),H([]);const ot=Ne.providerType?`${e.id}:${Ne.providerType}`:null;if(D1(Re.current,ot)){const at=dn();U(at.textQuery),oe(at.workspaceQuery),J(at.modelQuery),ae(at.resumableOnly),de(at.sortMode)}Re.current=ot,E(Ne),Ne.providerType&&o?(ie(!0),o(Ne.providerType).then(at=>{Q.current===$e&&H(at||[])}).catch(at=>{Q.current===$e&&console.warn("Failed to load saved sessions",at)}).finally(()=>{Q.current===$e&&ie(!1)})):ie(!1)},[o,e.id]),te=c.useMemo(()=>Ed($,{textQuery:q,workspaceQuery:K,modelQuery:ke,resumableOnly:ye,sortMode:re}),[ke,ye,$,re,q,K]);c.useEffect(()=>{W&&(te.some(Ne=>Ne.providerSessionId===W)||T(""))},[te,W]);const fe=c.useCallback(()=>{P.current&&(G(!0),P.current().finally(()=>{P.current=null,G(!1),E(null)}))},[]),V=c.useCallback(()=>{Q.current+=1,P.current=null,ie(!1),E(null)},[]),se=c.useCallback(Ne=>{C.current=Ne,O(Ne)},[]);return c.useEffect(()=>{var Ne;ue.current!==e.id&&(B.current+=1,Q.current+=1,ue.current=e.id,p(u||((Ne=m[0])==null?void 0:Ne.id)||"__custom__"),f(""),g(""),w([]),k(!1),y(""),N(!1),P.current=null,E(null),H([]),ie(!1),G(!1),U(dn().textQuery),oe(dn().workspaceQuery),J(dn().modelQuery),ae(dn().resumableOnly),de(dn().sortMode),Re.current=null,R(jc(d,t.length)))},[t.length,u,d,e.id,m]),c.useEffect(()=>{var Ne;h!=="__custom__"&&(h&&m.some(Ue=>Ue.id===h)||p(u||((Ne=m[0])==null?void 0:Ne.id)||"__custom__"))},[u,h,m]),c.useEffect(()=>{A==="ide"&&d||A==="cli"&&t.length>0||R(jc(d,t.length))},[A,t.length,d]),{showAllRecent:i,setShowAllRecent:l,hasIdeOptions:d,workspaceRows:m,defaultWorkspaceId:u,workspaceChoice:h,customWorkspacePath:b,browseCurrentPath:x,browseDirectories:S,browseBusy:_,browseError:v,browseDialogOpen:j,activeLauncherKind:A,launchConfirm:M,launchConfirmWorkspaceKeyRef:C,launchConfirmWorkspaceKey:I,launchConfirmArgs:D,launchConfirmModel:z,launchConfirmResumeId:W,launchConfirmSavedSessions:$,launchConfirmTextFilter:q,launchConfirmWorkspaceFilter:K,launchConfirmModelFilter:ke,launchConfirmResumableOnly:ye,launchConfirmSortMode:re,filteredLaunchConfirmSavedSessions:te,launchConfirmSessionsLoading:ne,launchConfirmBusy:_e,resolvedWorkspacePath:Le,canCreateMissingWorkspace:Pe,openBrowseDialog:Se,loadBrowsePath:ve,handleWorkspaceChoiceChange:L,chooseCustomWorkspacePath:Y,setCustomWorkspacePath:f,setBrowseDialogOpen:N,setActiveLauncherKind:R,openLaunchConfirm:ce,handleConfirmLaunch:fe,closeLaunchConfirm:V,setWorkspaceSelectionFromOption:Ce,setLaunchConfirmWorkspaceKeyAndSync:se,setLaunchConfirmArgs:F,setLaunchConfirmModel:Z,setLaunchConfirmResumeId:T,setLaunchConfirmTextFilter:U,setLaunchConfirmWorkspaceFilter:oe,setLaunchConfirmModelFilter:J,setLaunchConfirmResumableOnly:ae,setLaunchConfirmSortMode:de}}function K2({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:s,cliProviders:r,selectedMachineNeedsUpgrade:o,appVersion:a,machineAction:i,isStandalone:l,section:d,showBottomNav:m,onBack:u,onSectionChange:h,onOpenConversation:p,onOpenRecent:b,onOpenMachineDetails:f,onMachineUpgrade:x,onBrowseDirectory:g,onListSavedSessions:S}){const{t:w}=pe("common"),_=E=>E==="ide"?"IDE":"CLI",k=s.slice(0,4),v=t.slice(0,3),y=U2({selectedMachineEntry:e,cliProviders:r,machineAction:i,onBrowseDirectory:g,onListSavedSessions:S}),j=c.useMemo(()=>k.map(E=>{const{metaText:C,updatedLabel:I}=kg(E,w);return{key:`recent-launch:${E.id}`,primary:E.label,secondary:C,updatedLabel:I,onClick:()=>{const{options:O,selectedKey:D}=Sg({machine:{workspaces:y.workspaceRows,defaultWorkspaceId:y.defaultWorkspaceId},currentWorkspacePath:E.workspace,homeLabel:w("newSession.homeDirectory"),homeDescription:w("newSession.launchWithoutWorkspace")});y.openLaunchConfirm({title:E.kind==="ide"?Ka(w,"restart-ide",E.label):E.providerSessionId?Bb(w,E.label):Ka(w,"start-fresh",E.label),description:E.kind==="ide"?qa(w,"restart-ide"):E.providerSessionId?Wb(w):qa(w,"start-fresh"),confirmLabel:E.kind==="ide"?za(w,"restart-ide"):E.providerSessionId?Il(w,!0):za(w,"start-fresh"),busyLabel:E.kind==="ide"?Va(w,"restart-ide"):E.providerSessionId?Fb(w,!0):Va(w,"start-fresh"),workspaceOptions:O,selectedWorkspaceKey:D,details:[{label:"Mode",value:_(E.kind)},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]},async()=>{const F=O.find(z=>z.key===y.launchConfirmWorkspaceKeyRef.current);y.setWorkspaceSelectionFromOption(F),await b({...E,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[y,b,k,w]),N=c.useMemo(()=>v.map(E=>({key:`recent-chat:${E.conversation.tabKey}`,conversation:E.conversation,primary:wt(E.conversation),secondary:o_(E.conversation,{timestampLabel:E.timestamp?Fp(E.timestamp):null}),unread:E.unread,onClick:()=>p(E.conversation)})),[p,v]),A=y.showAllRecent?j:j.slice(0,4),R=j.length>0,P=N.length>0,M=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 ${M} 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:u,type:"button","aria-label":w("common.back"),children:n.jsx(rd,{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:yn(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||w("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:w("machine.mobile.currentChats")}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:N.map(E=>n.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${E.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:E.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(vs,{conversation:E.conversation,size:13}),n.jsx("span",{className:"min-w-0 truncate",children:E.primary})]}),n.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:E.secondary})]},E.key))})]}),R&&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:w("machine.mobile.recentLaunches")}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(E=>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:E.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:E.primary}),E.updatedLabel&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:E.updatedLabel})]}),n.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:E.secondary})]},E.key))}),j.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(E=>!E),children:y.showAllRecent?w("machine.mobile.showFewer"):w("machine.mobile.showMore",{count:j.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:w("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:w("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:w("machine.mobile.machineDetails")})})]})]})]}),y.browseDialogOpen&&n.jsx(Yd,{title:w("machine.mobile.browseTitle"),description:w("machine.mobile.browseDescription"),currentPath:y.browseCurrentPath,directories:y.browseDirectories,busy:y.browseBusy,error:y.browseError,confirmLabel:w("machine.mobile.useThisFolder"),onClose:()=>y.setBrowseDialogOpen(!1),onNavigate:E=>{y.loadBrowsePath(E)},onConfirm:E=>{y.chooseCustomWorkspacePath(E),y.setBrowseDialogOpen(!1)}}),y.launchConfirm&&n.jsx(Ei,{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?Il(w,!!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:w("launch.resumeSavedHistory")}),y.launchConfirmSessionsLoading&&n.jsx("div",{className:"text-3xs text-text-secondary font-medium",children:w("launch.loadingShort")})]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2",children:Dd(w)}),n.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[n.jsx("input",{type:"text",value:y.launchConfirmTextFilter,onChange:E=>y.setLaunchConfirmTextFilter(E.target.value),placeholder:w("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:E=>y.setLaunchConfirmWorkspaceFilter(E.target.value),placeholder:w("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:E=>y.setLaunchConfirmModelFilter(E.target.value),placeholder:w("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:E=>y.setLaunchConfirmSortMode(E.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:w("machine.mobile.sortRecent")}),n.jsx("option",{value:"oldest",children:w("machine.mobile.sortOldest")}),n.jsx("option",{value:"messages",children:w("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:E=>y.setLaunchConfirmResumableOnly(E.target.checked),disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),w("machine.mobile.resumableOnly")]}),n.jsxs("select",{value:y.launchConfirmResumeId,onChange:E=>y.setLaunchConfirmResumeId(E.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:$1(w)}),y.filteredLaunchConfirmSavedSessions.map(E=>n.jsxs("option",{value:E.providerSessionId,disabled:!E.canResume,children:[E.title||E.providerSessionId," ",E.canResume?"":w("machine.mobile.workspaceMissing")]},E.providerSessionId))]}),!y.launchConfirmSessionsLoading&&y.launchConfirmSavedSessions.length>0&&y.filteredLaunchConfirmSavedSessions.length===0&&n.jsx("div",{className:"mt-2 text-2xs text-text-muted",children:w("machine.mobile.noHistoryMatches")}),y.launchConfirmResumeId&&(()=>{const E=y.filteredLaunchConfirmSavedSessions.find(I=>I.providerSessionId===y.launchConfirmResumeId);if(!E)return null;const C=wg(E,w);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:C.title}),n.jsx("div",{className:"font-mono break-all mt-0.5",children:C.providerSessionId}),n.jsx("div",{className:"mt-1",children:C.metaLine}),C.updatedLabel&&n.jsx("div",{className:"mt-1 text-text-secondary",children:C.updatedLabel}),C.preview&&n.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:C.preview})]})})()]}),onConfirm:y.handleConfirmLaunch,onCancel:y.closeLaunchConfirm}),m&&n.jsx(vg,{section:d,onSectionChange:h})]})}const ih=8e3;function q2(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 jg(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,S]of b){const w=e.get(g),_=S.muted===void 0||(w?w.muted===S.muted:!1),k=S.hidden===void 0||(w?w.surfaceHidden===S.hidden:!1),v=f-S.at>ih;(_&&k||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[S,w]of f)x-w.at>ih&&(f.delete(S),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:xs(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:xs(b,e).surfaceHidden??!1},[e]),m=c.useCallback((b,f)=>{const x=Jn(b),g=b.sessionId;!x||!g||(i(g,f),t(x,"set_conversation_prefs",{sessionId:g,...f,...ji(b)}).then(S=>{const w=q2(S);w.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",w.reason),r.current.delete(g),a(),s==null||s(`Couldn't update conversation — ${w.reason}`))}).catch(S=>{console.warn("[conversation-prefs] set_conversation_prefs failed",S),r.current.delete(g),a();const w=S instanceof Error?S.message:String(S??"the daemon is unreachable");s==null||s(`Couldn't update conversation — ${w}`)}))},[t,i,a,s]),u=c.useCallback(b=>{m(b,{muted:!l(b)})},[m,l]),h=c.useCallback((b,f)=>{m(b,{hidden:f})},[m]),p=c.useCallback(b=>{m(b,{hidden:!d(b)})},[m,d]);return{isMuted:l,isHidden:d,toggleMute:u,setHidden:h,toggleHidden:p}}function Ca(e){return[...e].sort((t,s)=>{const r=s.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(s.conversation.tabKey)})}function z2(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:Ca(e)}function V2(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:Ca(s),unreadItems:Ca(r),workingItems:z2(o,t),completedItems:Ca(a)}}function Di(e,t){if(!t)return!1;const s=e.filter(r=>r.type==="adhdev-daemon"&&Ng(r)==="Connected");return s.length===0?!0:s.every(r=>r._sessionListAuthoritative===!0)}function Ng(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 G2(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:go(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=xo(r)?"cli":"ide";return{id:`${o}:${r.type}:${r.workspace||""}`,label:((a=r.activeChat)==null?void 0:a.title)||xo(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 Y2(e,t,s=[]){const r=new Map;for(const a of t){const i=Jn(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=Jn(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,m=(d==null?void 0:d.conversation)||null,u=gl(a),h=i.filter(x=>x.unread||x.requiresAction).length,p=i.filter(x=>Bs(x.conversation)).length+l.filter(Bs).length,b=Ng(a),f=[a.platform||"machine",b].filter(Boolean);return{id:a.id,label:yn(a,{fallbackId:a.id}),subtitle:f.join(" · "),unread:h,total:i.length,generatingCount:p,latestConversation:m,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:m?a_(m,ib(m)):"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 Q2(e){return e==="chat"}function na(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 J2({conversations:e,machineEntries:t,items:s,selectedConversation:r,selectedTabKey:o,screen:a,liveSessionInboxState:i,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:b,setSelectedTabKey:f,setScreen:x,setSelectedMachineId:g,setSection:S,setMachineBackTarget:w,resetMachineAction:_}){const k=c.useRef(null),v=c.useCallback(y=>{if(!(y!=null&&y.sessionId))return;const j=xs(y,i),N=Math.max(Date.now(),$s(y),j.lastUpdated||0);na("mark_read:start",{tabKey:y.tabKey,sessionId:y.sessionId,displayPrimary:wt(y),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:$s(y),readAt:N}),l(Jn(y)||y.routeId,"mark_session_seen",{sessionId:y.sessionId,providerSessionId:y.providerSessionId,seenAt:N,completionMarker:j.completionMarker}).then(A=>{na("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:A})}).catch(A=>{na("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,l]);return c.useEffect(()=>{var j;if(!r){Q2(a)&&x("inbox"),f(((j=e[0])==null?void 0:j.tabKey)||null),k.current=null;return}if(a!=="chat"){k.current=null;return}const y=`${r.tabKey}:${r.sessionId||""}`;k.current!==y&&(k.current=y,v(r))},[e,v,a,r,x,f]),c.useEffect(()=>{if(!d)return;const y=e.find(j=>j.tabKey===d);y&&(f(y.tabKey),x("chat"),m==null||m())},[e,m,d,x,f]),c.useEffect(()=>{if(!u)return;const y=t.find(j=>j.id===u);y&&(g(y.id),_(),S("machines"),w("inbox"),x("machine"),h==null||h())},[t,h,u,_,w,x,S,g]),c.useEffect(()=>{p&&(S(p),x("inbox"),b==null||b())},[b,p,x,S]),c.useEffect(()=>{const y=s.filter(j=>j.inboxBucket==="task_complete"||j.unread);y.length!==0&&na("inbox_state",{screen:a,selectedTabKey:o,items:y.map(j=>{const N=xs(j.conversation,i);return{liveState:N,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:wt(j.conversation),serverBucket:N.inboxBucket,computedBucket:j.inboxBucket,serverUnread:N.unread,computedUnread:j.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:$s(j.conversation)}})})},[s,i,a,o]),{markConversationRead:v}}const X2="Cannot update: node update policy unavailable; refresh and try again";async function Z2(e,t,s){var o,a,i,l,d,m;const r=Ud(s);if(!r)return{state:"error",message:X2};try{const u=await e(t,"daemon_upgrade",r);return(o=u==null?void 0:u.result)!=null&&o.alreadyLatest?{state:"done",message:`Already on v${((a=u==null?void 0:u.result)==null?void 0:a.version)||"latest"}.`}:(i=u==null?void 0:u.result)!=null&&i.upgraded||(l=u==null?void 0:u.result)!=null&&l.success?{state:"done",message:`Upgrade to v${((d=u==null?void 0:u.result)==null?void 0:d.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((m=u==null?void 0:u.result)==null?void 0:m.error)||"Upgrade failed"}}catch(u){return{state:"error",message:u instanceof Error?u.message:"Upgrade failed"}}}function eI(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ch(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function tI(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function nI({sendDaemonCommand:e,navigate:t,ides:s,conversations:r}){const{launchCli:o}=mi(),[a,i]=c.useState("idle"),[l,d]=c.useState(""),[m,u]=c.useState(null),h=c.useCallback(()=>{i("idle"),d(""),u(null)},[]),p=c.useCallback(async(_,k,v)=>{var y;try{i("loading"),d(`Launching ${k}…`);const j={ideType:k,enableCdp:!0};(y=v==null?void 0:v.workspacePath)!=null&&y.trim()&&(j.workspace=v.workspacePath.trim()),await e(_,"launch_ide",j),i("done"),d(`${k} launch requested`)}catch(j){i("error"),d(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),b=c.useCallback(async(_,k,v)=>{if(k.trim())try{i("loading"),d(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(_,"workspace_add",{path:k.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 _=>{i("loading"),d("Starting daemon upgrade…");const k=s.find(y=>y.id===_||y.daemonId===_),v=await Z2(e,_,k);i(v.state),d(v.message)},[s,e]),x=c.useCallback(async(_,k,v,y)=>{var A,R,P;const j=Date.now(),N={machineId:_,kind:k,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:j};try{i("loading"),d(`Launching ${v}…`),u(N);const M={cliType:v};(A=y==null?void 0:y.workspacePath)!=null&&A.trim()?M.dir=y.workspacePath.trim():y!=null&&y.workspaceId?M.workspaceId=y.workspaceId:y!=null&&y.useHome&&(M.useHome=!0),y!=null&&y.resumeSessionId&&(M.resumeSessionId=y.resumeSessionId),(R=y==null?void 0:y.args)!=null&&R.trim()&&(M.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(P=y==null?void 0:y.model)!=null&&P.trim()&&(M.initialModel=y.model.trim());const E=await o(_,M),C=(E==null?void 0:E.result)||E,I=(C==null?void 0:C.sessionId)||(C==null?void 0:C.id);if(E!=null&&E.success&&I){u(null),i("done"),d(`${v} launched`),t(yo(I));return}if(E!=null&&E.success){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d((E==null?void 0:E.error)||(C==null?void 0:C.error)||`Could not launch ${k.toUpperCase()} workspace`)}catch(M){if(tI(M)){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d(M instanceof Error?M.message:`Could not launch ${k.toUpperCase()} workspace`)}},[t,e]),g=c.useCallback(async(_,k)=>{try{const v=await e(_,"list_saved_sessions",{providerType:k,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]),S=c.useCallback(async(_,k)=>Vd(e,_,k),[e]);c.useEffect(()=>{if(!m)return;const _=ch(m.workspacePath),k=s.find(y=>{var M,E,C,I;if(!y||y.type==="adhdev-daemon"||eI(y.daemonId||y.id)!==m.machineId||(y.transport==="pty"?"cli":null)!==m.kind||String(y.agentType||y.type||"")!==m.providerType)return!1;const R=String(y.providerSessionId||"");if(m.resumeSessionId&&R)return R===m.resumeSessionId;if(_){const O=ch(y.workspace||y.runtimeWorkspaceLabel);return O?O===_:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((I=(C=(E=(M=y.activeChat)==null?void 0:M.messages)==null?void 0:E.at)==null?void 0:C.call(E,-1))==null?void 0:I.timestamp)||0)>=m.startedAt-5e3});if(!k)return;const v=gg({entrySessionId:k.sessionId,entryInstanceId:k.instanceId,entryRouteId:k.id,conversations:r});v&&(u(null),i("done"),d(`${m.providerType} launched`),t(yo(v)))},[r,s,t,m]),c.useEffect(()=>{if(!m)return;const _=window.setTimeout(()=>{u(k=>!k||k.startedAt!==m.startedAt?k:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(_)},[m]);const w=c.useCallback(async(_,k)=>{var v;if(k.kind==="ide"&&k.providerType){await p(_,k.providerType,{workspacePath:k.workspace||null});return}if(k.kind==="cli"&&k.providerType){const y=((v=k.workspace)==null?void 0:v.trim())||"";await x(_,k.kind,k.providerType,{workspacePath:y||null,useHome:!y,resumeSessionId:k.providerSessionId||null})}},[p,x]);return{machineAction:{state:a,message:l},resetMachineAction:h,handleLaunchDetectedIde:p,handleAddWorkspace:b,handleMachineUpgrade:f,handleLaunchWorkspaceProvider:x,handleListSavedSessions:g,handleBrowseDirectory:S,handleOpenRecent:w}}function sI({conversations:e,selectedConversation:t,machineBackTarget:s,markConversationRead:r,resetMachineAction:o,setSelectedTabKey:a,setScreen:i,setSelectedMachineId:l,setSection:d,setMachineBackTarget:m}){const u=c.useCallback(S=>{a(S.tabKey),i("chat"),r(S)},[r,i,a]),h=c.useCallback(S=>{const w=e.find(_=>_.routeId===S.routeId&&_.streamSource==="native");w&&(a(w.tabKey),i("chat"),r(w))},[e,r,i,a]),p=c.useCallback(()=>{r(t),i("inbox")},[r,t,i]),b=c.useCallback((S,w="inbox")=>{l(S),o(),d("machines"),m(w),i("machine")},[o,m,i,d,l]),f=c.useCallback(S=>{const w=Jn(S);w&&b(w,"chat")},[b]),x=c.useCallback(()=>{o(),i(s)},[s,o,i]),g=c.useCallback(S=>{d(S),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:h,backFromConversation:p,openMachine:b,openConversationMachine:f,backFromMachine:x,changeMachineSection:g}}function Qd(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function rI(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function oI({conversations:e,hiddenConversations:t,ides:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:b,onOpenHistory:f,onOpenRemote:x,onStopCli:g,wsStatus:S,isConnected:w,initialDataLoaded:_=!0,onShowAllHiddenConversations:k,onHideConversation:v,onShowHiddenConversation:y,onOpenMeshGraph:j,onOpenNewSession:N,liveSessionInboxState:A,setCliViewModeOverrides:R}){const[P,M]=c.useState(()=>{var Ce;return((Ce=e[0])==null?void 0:Ce.tabKey)||null}),[E,C]=c.useState(()=>e[0]?"chat":"inbox"),[I,O]=c.useState("chats"),[D,F]=c.useState(null),[z,Z]=c.useState("inbox"),W=c.useRef([]),T=qs(),$="1.0.72",H=c.useMemo(()=>e.find(Ce=>Ce.tabKey===P)||e[0]||null,[e,P]),q=c.useMemo(()=>H?s.find(Ce=>Ce.id===H.routeId):void 0,[s,H]),U=c.useMemo(()=>!H||!ht(H)?null:kr(H),[H]),K=c.useMemo(()=>s.filter(Ce=>Ce.type==="adhdev-daemon").sort(La),[s]),oe=c.useMemo(()=>K.find(Ce=>Ce.id===D)||null,[K,D]),ke=Ci({sendDaemonCommand:o,activeConv:H||void 0,setActionLogs:a,isStandalone:i}),J=nI({sendDaemonCommand:o,navigate:T,ides:s,conversations:e}),ye=pC(e),ae=c.useMemo(()=>e.map(Ce=>{const L=E==="chat"&&(H==null?void 0:H.tabKey)===Ce.tabKey,Y=gi(Ce,A,{hideOpenTaskCompleteUnread:!0,isOpenConversation:L}),ce=$s(Ce),te=ib(Ce),fe=gb(Ce,te);return{conversation:Ce,timestamp:ce,preview:fe,unread:Y.unread,requiresAction:Y.requiresAction,isWorking:Y.isWorking,inboxBucket:Y.inboxBucket}}),[e,A,E,H,ye]),{markConversationRead:re}=J2({conversations:e,machineEntries:K,items:ae,selectedConversation:H,selectedTabKey:P,screen:E,liveSessionInboxState:A,sendDaemonCommand:o,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:b,setSelectedTabKey:M,setScreen:C,setSelectedMachineId:F,setSection:O,setMachineBackTarget:Z,resetMachineAction:J.resetMachineAction}),de=sI({conversations:e,selectedConversation:H,machineBackTarget:z,markConversationRead:re,resetMachineAction:J.resetMachineAction,setSelectedTabKey:M,setScreen:C,setSelectedMachineId:F,setSection:O,setMachineBackTarget:Z}),{isMuted:ne,toggleMute:ie}=jg(A,o),{attentionItems:_e,unreadItems:G,workingItems:B,completedItems:Q}=c.useMemo(()=>V2(ae,W.current),[ae]);c.useEffect(()=>{W.current=B.map(Ce=>Ce.conversation.tabKey)},[B]);const ue=c.useMemo(()=>oe?ae.filter(Ce=>Jn(Ce.conversation)===oe.id):[],[ae,oe]),Re=c.useMemo(()=>G2(oe,s),[s,oe]),Le=!!oe&&Kd(oe,Is(oe,$)),Pe=c.useMemo(()=>(oe==null?void 0:oe.availableProviders)||[],[oe]),Fe=c.useMemo(()=>Pe.filter(Ce=>Qd(Ce,"cli")).map(Ce=>({type:Ce.type,displayName:Ce.displayName||Ce.type,icon:Ce.icon})),[Pe]),X=c.useMemo(()=>Y2(K,ae,t),[ae,K,t]),ve=c.useMemo(()=>Di(s,_),[s,_]),Se=c.useCallback(async Ce=>{oe&&await J.handleOpenRecent(oe.id,Ce)},[J,oe]);return n.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:E==="chat"&&H?n.jsx(D2,{selectedConversation:H,isStandalone:i,selectedIdeEntry:q,actionLogs:r,userName:l,commands:ke,onBack:de.backFromConversation,onOpenNativeConversation:de.openNativeConversation,onOpenMachine:de.openConversationMachine,onOpenHistory:f,onOpenRemote:x,onOpenMeshGraph:j,onStopCli:g,cliViewMode:U,onSetCliViewMode:async Ce=>{await ag({conversation:H,mode:Ce,ides:s,sendDaemonCommand:o,setCliViewModeOverrides:R})}}):E==="machine"&&oe?n.jsx(K2,{selectedMachineEntry:oe,selectedMachineConversations:ue,selectedMachineRecentLaunches:Re,cliProviders:Fe,selectedMachineNeedsUpgrade:Le,appVersion:$,machineAction:J.machineAction,isStandalone:i,section:I,showBottomNav:z==="inbox",onBack:de.backFromMachine,onSectionChange:de.changeMachineSection,onOpenConversation:de.openConversation,onOpenRecent:Se,onOpenMachineDetails:()=>T(`/machines/${oe.id}`),onMachineUpgrade:()=>J.handleMachineUpgrade(oe.id),onBrowseDirectory:Ce=>J.handleBrowseDirectory(oe.id,Ce),onListSavedSessions:Ce=>J.handleListSavedSessions(oe.id,Ce)}):n.jsx($2,{section:I,attentionItems:_e,unreadItems:G,workingItems:B,completedItems:Q,hiddenConversations:t,machineCards:X,getAvatarText:rI,actionLogs:r,sendDaemonCommand:o,onOpenConversation:de.openConversation,onShowAllHidden:k,onHideConversation:v,onShowHiddenConversation:y,onOpenMeshGraph:j,onStopCli:g,onOpenNewSession:N,onOpenMachine:de.openMachine,onOpenSettings:()=>T("/settings"),onSectionChange:O,wsStatus:S,isConnected:w,initialDataLoaded:_,conversationsLoaded:ve,isStandalone:i,isConversationMuted:ne,onToggleMuteConversation:ie})})}function Nc(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function aI({conversations:e,numGroups:t,onMoveTab:s,onReceiveTab:r,onOwnTabDrop:o,onClearPreviewOrder:a}){const i=c.useRef(0),[l,d]=c.useState(!1),[m,u]=c.useState(null),h=c.useCallback(()=>{i.current=0,d(!1),u(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(),!Nc(t,s)){u("merge");return}const S=g.currentTarget.getBoundingClientRect(),w=g.clientX-S.left,_=S.width/3;w<_?u("split-left"):w>_*2?u("split-right"):u("merge")},[t,s]),f=c.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),x=c.useCallback(g=>{i.current=0,d(!1);const S=g.dataTransfer.getData("text/tab-key"),w=S?e.some(k=>k.tabKey===S):!1,_=m;if(u(null),a(),!!S){if(g.preventDefault(),_==="split-left"&&Nc(t,s)){s==null||s(S,"split-left");return}if(_==="split-right"&&Nc(t,s)){s==null||s(S,"split-right");return}if(w){o(S);return}r==null||r(S)}},[e,m,t,s,r,o,a]);return{dragOver:l,dropAction:m,resetDragState:h,handleDragEnter:p,handleDragOver:b,handleDragLeave:f,handleDrop:x}}function iI(e,t){const s=new Set(t.map(a=>a.tabKey)),r=e.filter(a=>s.has(a)),o=t.filter(a=>!e.includes(a.tabKey)).map(a=>a.tabKey);return[...r,...o]}function cI({conversations:e,initialActiveTabId:t,initialTabOrder:s,onActiveTabChange:r,onTabOrderChange:o}){const[a,i]=c.useState(t??null),[l,d]=c.useState(s??[]),[m,u]=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(j=>{const N=iI(j,e);return N.length===j.length&&N.every((A,R)=>A===j[R])?j:N})},[e]);const x=c.useMemo(()=>{const j=m??l;if(j.length===0)return e;const N=new Map(j.map((A,R)=>[A,R]));return[...e].sort((A,R)=>{const P=N.get(A.tabKey)??999,M=N.get(R.tabKey)??999;return P-M})},[e,m,l]);c.useEffect(()=>{var N,A;if(x.length===0){a!==null&&(i(null),(N=b.current)==null||N.call(b,null));return}if(a&&x.some(R=>R.tabKey===a))return;const j=x[0].tabKey;j!==a&&(i(j),(A=b.current)==null||A.call(b,j))},[x,a]);const g=c.useMemo(()=>x.find(j=>j.tabKey===a),[x,a]),S=c.useCallback(j=>{var N;i(j),(N=b.current)==null||N.call(b,j)},[]),w=c.useCallback((j,N,A)=>{d(R=>{var C;const P=R.filter(I=>I!==j),M=P.indexOf(N);if(M<0)return R;const E=A==="left"?M:M+1;return P.splice(E,0,j),(C=f.current)==null||C.call(f,P),P}),u(null)},[]),_=c.useCallback((j,N,A)=>{const P=(l.length>0?l:e.map(C=>C.tabKey)).filter(C=>C!==j),M=P.indexOf(N);if(M<0)return;const E=A==="left"?M:M+1;P.splice(E,0,j),h.current=P,u(P)},[l,e]),k=c.useCallback(()=>{var N;const j=h.current;j&&(d(j),(N=f.current)==null||N.call(f,j))},[]),v=c.useCallback(()=>{h.current=null,u(null)},[]),y=c.useCallback(j=>{d(N=>{var R;const A=N.filter(P=>P!==j);return A.push(j),(R=f.current)==null||R.call(f,A),A})},[]);return{activeTabId:a,activeConv:g,sortedConversations:x,previewOrderRef:h,draggingTabRef:p,selectTab:S,handleTabReorder:w,updatePreviewOrder:_,commitPreviewOrder:k,clearPreviewOrder:v,moveTabToEnd:y,setDraggingTabKey:j=>{p.current=j}}}function lI({dropAction:e,canSplit:t}){const{t:s}=pe("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 Jd({conversationsCount:e,isSplitMode:t,isStandalone:s,hasRegisteredMachines:r=!1,suppressGuide:o=!1,onOpenNewSession:a,isLoading:i=!1}){const{t:l}=pe("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(Zt,{}),n.jsx("p",{className:"text-sm",children:l("paneGroup.loadingSessions")})]});const d=!s&&!r,m=r&&!!a,u=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:u}),n.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:h}),m&&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(po,{size:14}),n.jsx("span",{children:l("paneGroup.newSession")})]})}),d&&n.jsx(yg,{}),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 Cg="adhdev-tab-shortcuts";function _g(){try{return JSON.parse(localStorage.getItem(Cg)||"{}")}catch{return{}}}function Ag({enabled:e=!0,sortedTabKeys:t,onFocus:s,onSelectTab:r}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[a,i]=c.useState(()=>_g()),[l,d]=c.useState(null),m=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]),u=c.useCallback(h=>{i(h);try{localStorage.setItem(Cg,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=m(p);if(!b)return;const f={...a};for(const[x,g]of Object.entries(f))g===b&&delete f[x];f[l]=b,u(f),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,a,u,m]),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)&&m(p)===f){p.preventDefault(),s(),r(b);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,a,t,s,r,m]),{isMac:o,tabShortcuts:a,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Cc=e=>{e.preventDefault()},dI=c.memo(function({conv:t,isActive:s,isDraggedTab:r,isTaskCompleteUnread:o,shortcut:a,conversationKeys:i,draggingTabRef:l,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:h,onReorderTab:p,onCommitPreviewOrder:b,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:g,onReceiveTab:S,onOpenContextMenu:w,longPressTimer:_,isGroupActive:k}){const v=ws(t),y=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",j=v.isReconnecting,N=Rd(t),A=c.useCallback(F=>{l.current=t.tabKey,g(t.tabKey),F.dataTransfer.setData("text/tab-key",t.tabKey),F.dataTransfer.effectAllowed="move"},[t.tabKey,l,g]),R=c.useCallback(()=>{l.current=null,g(null),b(),f(),x()},[l,g,b,f,x]),P=c.useCallback(F=>{const z=l.current;if(!(!z||z===t.tabKey)&&F.dataTransfer.types.includes("text/tab-key")){F.preventDefault(),F.stopPropagation();const Z=F.currentTarget.getBoundingClientRect(),W=F.clientX<Z.left+Z.width/2?"left":"right";h(z,t.tabKey,W)}},[t.tabKey,l,h]),M=c.useCallback(F=>{F.preventDefault(),F.stopPropagation();const z=F.dataTransfer.getData("text/tab-key");if(z&&z!==t.tabKey){const Z=F.currentTarget.getBoundingClientRect(),W=F.clientX<Z.left+Z.width/2?"left":"right";i.includes(z)?p(z,t.tabKey,W):S&&S(z)}f()},[t.tabKey,i,p,S,f]),E=c.useCallback(F=>{F.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),C=c.useCallback(F=>{F.preventDefault(),w(F.clientX,F.clientY,t.tabKey)},[t.tabKey,w]),I=c.useCallback(F=>{const z=F.touches[0];_.current=setTimeout(()=>{w(z.clientX,z.clientY,t.tabKey)},600)},[t.tabKey,_,w]),O=c.useCallback(()=>{_.current&&clearTimeout(_.current)},[_]),D=["adhdev-dockview-tab",y,s&&"is-active",k&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return n.jsxs("div",{"data-tabkey":t.tabKey,className:D,draggable:!0,onDragStart:A,onDragEnd:R,onDragOver:P,onDrop:M,onClick:E,onContextMenu:C,onTouchStart:I,onTouchEnd:O,onTouchMove:O,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(Zt,{size:12,thickness:2,color:"success"}):v.isWaiting?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?n.jsx(Zt,{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(vs,{conversation:t,size:12}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("span",{className:"adhdev-dockview-tab-primary",title:N?`${wt(t)} · ${N}`:wt(t),children:wt(t)}),n.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[j?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Ds(t)}):v.isConnecting?n.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Ds(t),n.jsx("span",{className:"connecting-dots"})]}):n.jsx("span",{className:"truncate",children:Ds(t)}),n.jsx(Nd,{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 uI({conversations:e,activeTabId:t,groupIndex:s,unreadTabKeys:r,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:b,onReceiveTab:f,onHideTab:x,isGroupActive:g,allowTabShortcuts:S=!0}){const{t:w}=pe("common"),[_,k]=c.useState(null),v=c.useRef(null),y=c.useRef(null),j=c.useMemo(()=>e.map(C=>C.tabKey),[e]);Co("PaneGroupTabBar",{groupIndex:s,activeTabId:t,tabCount:e.length,ctxMenuTab:(_==null?void 0:_.tabKey)||null});const{isMac:N,tabShortcuts:A,shortcutListening:R,setShortcutListening:P,saveShortcuts:M}=Ag({enabled:S,sortedTabKeys:e.map(C=>C.tabKey),onFocus:a,onSelectTab:i});c.useEffect(()=>{if(!_)return;const C=I=>{const O=document.querySelector("[data-pane-context-menu]");O&&O.contains(I.target)||k(null)};return window.addEventListener("mousedown",C,!0),()=>window.removeEventListener("mousedown",C,!0)},[_]),c.useEffect(()=>{const C=y.current;if(!C)return;const I=O=>{Math.abs(O.deltaY)<=Math.abs(O.deltaX)||(O.preventDefault(),C.scrollLeft+=O.deltaY)};return C.addEventListener("wheel",I,{passive:!1}),()=>C.removeEventListener("wheel",I)},[]);const E=c.useCallback((C,I,O)=>{k({x:C,y:I,tabKey:O})},[]);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(C=>n.jsx(dI,{conv:C,isActive:t===C.tabKey,isDraggedTab:o.current===C.tabKey,isTaskCompleteUnread:r.has(C.tabKey),shortcut:S?A[C.tabKey]:void 0,conversationKeys:j,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:b,onReceiveTab:f,onOpenContextMenu:E,longPressTimer:v,isGroupActive:g},C.tabKey)),e.length===0&&n.jsx("div",{className:"p-2 text-xs opacity-40",children:w("paneGroup.noTabsInGroup")})]})}),_&&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:_.x,top:_.y},children:[S&&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:Cc,onClick:C=>{C.stopPropagation(),P(_.tabKey),k(null)},children:["⌨ ",A[_.tabKey]?w("paneGroup.changeShortcut",{shortcut:A[_.tabKey]}):w("paneGroup.shortcutSetTitle")]}),A[_.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:Cc,onClick:()=>{const C={...A};delete C[_.tabKey],M(C),k(null)},children:["✕ ",w("paneGroup.removeShortcut")]})]}),x&&n.jsxs(n.Fragment,{children:[S&&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:Cc,onClick:()=>{x(_.tabKey),k(null)},children:n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(li,{size:12}),w("paneGroup.hideFromDashboard")]})})]})]}),S&&R&&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:C=>C.stopPropagation(),children:[n.jsxs("div",{className:"text-sm font-bold text-text-primary mb-2",children:["⌨ ",w("paneGroup.shortcutSetTitle")]}),n.jsx("div",{className:"text-xs text-text-secondary mb-4",children:w("paneGroup.shortcutPressCombo",{example1:N?"⌘+1":"Ctrl+1",example2:N?"⌥+A":"Alt+A"})}),n.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:w("paneGroup.shortcutListening")}),n.jsx("div",{className:"text-3xs text-text-muted mt-3",children:w("paneGroup.pressEscToCancel")})]})})})]})}function mI({conversations:e,ides:t,clearedTabs:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:l,initialDataLoaded:d=!0,userName:m,groupIndex:u,onFocus:h,isSplitMode:p,numGroups:b,onMoveTab:f,onReceiveTab:x,style:g,onActiveTabChange:S,initialActiveTabId:w,initialTabOrder:_,onTabOrderChange:k,onHideTab:v,isFocused:y,allowTabShortcuts:j=!0,onOpenNewSession:N,liveSessionInboxState:A}){const{sendCommand:R}=xt(),P=c.useRef(null),{activeTabId:M,activeConv:E,sortedConversations:C,draggingTabRef:I,selectTab:O,handleTabReorder:D,updatePreviewOrder:F,commitPreviewOrder:z,clearPreviewOrder:Z,moveTabToEnd:W,setDraggingTabKey:T}=cI({conversations:e,initialActiveTabId:w,initialTabOrder:_,onActiveTabChange:S,onTabOrderChange:k}),$=Ci({sendDaemonCommand:o,activeConv:E,setActionLogs:a,isStandalone:i}),{dragOver:H,dropAction:q,resetDragState:U,handleDragEnter:K,handleDragOver:oe,handleDragLeave:ke,handleDrop:J}=aI({conversations:e,numGroups:b,onMoveTab:f,onReceiveTab:x,onOwnTabDrop:W,onClearPreviewOrder:Z}),ye=E&&kr(E)==="terminal",ae=c.useMemo(()=>E?t.find(ie=>ie.id===E.routeId):void 0,[t,E]),re=c.useMemo(()=>E?r.filter(ie=>ie.routeId===E.tabKey):[],[r,E]),de=c.useMemo(()=>new Set(C.filter(ie=>R0(ie,A,{isOpenConversation:ie.tabKey===M})).map(ie=>ie.tabKey)),[M,A,C]);Co("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:M,dragOver:H});const ne=c.useCallback(ie=>{ie.streamSource==="agent-stream"&&ie.agentType&&R(ie.routeId,qf(),{agentType:ie.agentType,...ie.sessionId&&{targetSessionId:ie.sessionId}}).catch(()=>{})},[R]);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(uI,{conversations:C,activeTabId:M,groupIndex:u,numGroups:b,unreadTabKeys:de,draggingTabRef:I,onFocus:h,onSelectTab:O,onConversationActivated:ne,onPreviewReorder:F,onReorderTab:D,onCommitPreviewOrder:z,onClearPreviewOrder:Z,onDragStateReset:U,onDragTabKeyChange:T,onMoveTab:f,onReceiveTab:x,onHideTab:v,isGroupActive:y??!1,allowTabShortcuts:j}),n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:K,onDragOver:oe,onDragLeave:ke,onDrop:J,children:[H&&n.jsx(lI,{dropAction:q,canSplit:!!(b<4&&f)}),E?n.jsx(Gd,{activeConv:E,clearToken:s[E.tabKey]||0,isCliTerminal:!!ye,ideEntry:ae,terminalRef:P,commands:$,actionLogs:re,userName:m,isInputActive:!p||!!y}):n.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:n.jsx(Jd,{conversationsCount:e.length,isSplitMode:p,isStandalone:i,hasRegisteredMachines:l,onOpenNewSession:N,isLoading:!Di(t,d)})})]})]})}function hI({containerRef:e,isSplitMode:t,numGroups:s,groupSizes:r,groupedConvs:o,clearedTabs:a,ides:i,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,initialDataLoaded:p,userName:b,focusedGroup:f,focusGroup:x,moveTabToGroup:g,splitTabRelative:S,closeGroup:w,handleResizeStart:_,groupActiveTabIds:k,setGroupActiveTab:v,groupTabOrders:y,setGroupTabOrder:j,toggleHiddenTab:N,onOpenNewSession:A,allowTabShortcuts:R=!0,liveSessionInboxState:P}){const{t:M}=pe("common");return n.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:o.map((E,C)=>{const I=t&&r.length===s?`${r[C]}%`:void 0;return n.jsxs(vt.Fragment,{children:[t&&C>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:O=>_(C-1,O),onDoubleClick:()=>w(C),title:M("paneGroup.resizeHandleHint"),children:n.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),n.jsx(mI,{style:t?{flexBasis:I??`${100/s}%`,flexGrow:I?0:1,flexShrink:I?0:1}:void 0,conversations:E,clearedTabs:a,ides:i,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,initialDataLoaded:p,userName:b,groupIndex:C,isFocused:t&&f===C,onFocus:()=>x(C),isSplitMode:t,numGroups:s,onMoveTab:(O,D)=>{D==="left"&&C>0?g(O,C-1):D==="right"&&C<s-1?g(O,C+1):D==="split-left"&&s<4?S(O,C,"left"):D==="split-right"&&s<4&&S(O,C,"right")},onReceiveTab:O=>g(O,C),onActiveTabChange:O=>v(C,O),initialActiveTabId:k[C],initialTabOrder:y[C],onTabOrderChange:O=>j(C,O),onHideTab:N,onOpenNewSession:A,allowTabShortcuts:R,liveSessionInboxState:P})]},C)})})}const Tg="adhdev-dashboard-action-shortcuts",pI=1200,fI=[["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 bI(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function mt(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 Ig(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:mt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:mt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:mt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:mt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:mt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:mt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:mt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:mt("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:mt("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:mt("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:mt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:mt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:mt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:mt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:mt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:mt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:mt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:mt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:mt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:mt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:mt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:mt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:mt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:mt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:mt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:mt("toggleCliView",e)}]}function Xd(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Xa(e){const t=Object.fromEntries(Ig(e).map(s=>[s.id,s.defaultShortcut]));try{const s=JSON.parse(localStorage.getItem(Tg)||"{}"),r={...t,...s};for(const[o,a]of fI)r[o]===a&&(r[o]=t[o]);return r}catch{return t}}function Mg(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function gI({enabled:e=!0,onTrigger:t}){const s=bI(),[r,o]=c.useState(()=>Xa(s)),[a,i]=c.useState(null),[l,d]=c.useState([]),m=c.useRef({parts:[],timer:null}),u=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(Mg(x.key)),g.join("+"))},[s]),h=c.useCallback(x=>{o(x);try{localStorage.setItem(Tg,JSON.stringify(x))}catch{}},[]);c.useEffect(()=>{const x=Xa(s),g=Object.entries(r),S=Object.entries(x);g.length===S.length&&g.every(([w,_])=>x[w]===_)||h(x)},[r,s,h]);const p=c.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),b=c.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},pI))},[]);c.useEffect(()=>{if(!a)return;const x=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){i(null),d([]);return}const S=u(g);if(!S)return;const _=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(S);if(l.length===0&&_){d([S]);return}const v=[...l,S].slice(0,2).join(" "),y={...r};for(const[j,N]of Object.entries(y))N===v&&delete y[j];y[a]=v,h(y),i(null),d([])};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[r,u,h,a,l]),c.useEffect(()=>{if(!e||a)return;const x=g=>{if(g.defaultPrevented)return;const S=u(g);if(!S)return;const w=g.metaKey||g.ctrlKey||g.altKey;if(Xd(g.target))return;const _=m.current.parts,k=w?[S]:[..._.slice(-1),S].slice(-2),v=k.join(" "),y=k[k.length-1],j=Object.entries(r).filter(([,M])=>!!M),N=j.find(([,M])=>M===v);if(N){g.preventDefault(),p(),t(N[0]);return}if(j.some(([,M])=>M.startsWith(`${v} `))){g.preventDefault(),m.current.parts=k,b();return}const R=j.find(([,M])=>M===y);if(R){g.preventDefault(),p(),t(R[0]);return}if(j.some(([,M])=>M.startsWith(`${y} `))){g.preventDefault(),m.current.parts=[y],b();return}p()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[r,b,e,u,t,p,a]),c.useEffect(()=>()=>p(),[p]);const f=c.useMemo(()=>Ig(s),[s]);return{isMac:s,actionDefinitions:f,actionShortcuts:r,shortcutListening:a,shortcutListeningDraft:l,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:h}}function xI({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 Rg(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function lh({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:s,ides:r}){return!e||s>0?!1:t?!Rg(r):!0}function yI({previousVisibleConversationCount:e,visibleConversationCount:t,ides:s}){return t>0||e<=0?!1:Rg(s)}const Pg=2e4;function vI(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+Pg}:null}function wI(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 Eg=1e3,SI=4;function dh(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function uh(e,t,s){return Math.abs(t.clientX-e.clientX)>s||Math.abs(t.clientY-e.clientY)>s}function kI({detachDelayMs:e=Eg,stillnessThresholdPx:t=SI,onDetach:s,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:o=globalThis.clearTimeout.bind(globalThis)}){let a=null,i=null,l=null,d=null,m=null,u=!1;const h=()=>{m!=null&&(o(m),m=null)},p=()=>{h(),l=null},b=()=>{h(),a=null,i=null,l=null,d=null,u=!1},f=()=>{!a||!l||!d||u||m!=null||(m=r(()=>{m=null,!(!a||!l||!d||u)&&dh(d,i)&&(uh(l,d,t)||(u=!0,s({panelId:a,clientX:d.clientX,clientY:d.clientY})))},e))},x=S=>{if(!(!a||u)){if(!dh(S,i)){d={clientX:S.clientX,clientY:S.clientY},p();return}(!l||uh(l,S,t))&&(h(),l={clientX:S.clientX,clientY:S.clientY}),d={clientX:S.clientX,clientY:S.clientY},f()}},g=S=>{!a||u||(S&&(d={clientX:S.clientX,clientY:S.clientY}),p())};return{startDrag:S=>{h(),a=S.panelId,i=S.selfPanelBounds??null,l=null,d={clientX:S.clientX,clientY:S.clientY},u=!1},markSelfPanel:x,markNonSelfPanel:g,markNoDropTarget:g,markDockTarget:g,endDrag:b,isDragging:()=>a!=null,hasDetached:()=>u,dispose:b}}function jI(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function NI(e,t,s){const r=u=>({clientX:u.clientX,clientY:u.clientY}),o=u=>{const h=u==null?void 0:u.getBoundingClientRect();return h?{left:h.left,right:h.right,top:h.top,bottom:h.bottom}:null},a=u=>{var p;const h=(p=t())==null?void 0:p.getBoundingClientRect();return h?u.clientX<h.left||u.clientX>h.right||u.clientY<h.top||u.clientY>h.bottom:!1},i=kI({detachDelayMs:Eg,onDetach:({panelId:u,clientX:h,clientY:p})=>{var w,_;const b=e.getPanel(u);if(!b)return;try{if(b.group.model.location.type!=="grid")return}catch{return}const f=(w=t())==null?void 0:w.getBoundingClientRect(),x=(_=b.group.element)==null?void 0:_.getBoundingClientRect(),g=Math.round(Math.min(Math.max((x==null?void 0:x.width)??600,360),720)),S=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:S}),b.api.setActive(),s()}}),l=[e.onWillDragPanel(u=>{if(!(u.nativeEvent.defaultPrevented||u.nativeEvent.shiftKey)){try{if(u.panel.group.model.location.type!=="grid")return}catch{return}i.startDrag({panelId:u.panel.id,selfPanelBounds:o(u.panel.group.element),...r(u.nativeEvent)})}}),e.onWillShowOverlay(u=>{if(i.hasDetached()){u.preventDefault();return}i.markDockTarget(r(u.nativeEvent))}),e.onWillDrop(u=>{if(i.hasDetached()){u.preventDefault(),i.endDrag();return}i.markDockTarget(r(u.nativeEvent))}),e.onDidDrop(()=>i.endDrag()),e.onUnhandledDragOverEvent(u=>{i.isDragging()&&i.markSelfPanel(r(u.nativeEvent))})],d=u=>{if(!i.isDragging())return;const h=r(u);a(h)&&i.markNonSelfPanel(h)},m=()=>i.endDrag();return window.addEventListener("dragover",d,!0),window.addEventListener("drop",m,!0),window.addEventListener("dragend",m,!0),()=>{i.dispose();for(const u of l)u.dispose();window.removeEventListener("dragover",d,!0),window.removeEventListener("drop",m,!0),window.removeEventListener("dragend",m,!0)}}function _a(e){return wt(e)||e.tabKey}function CI(e){return`remote:${e}`}function bn(e){return e.startsWith("remote:")}function mh(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function _c(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 Zd(e,t){e.classList.remove(Yc.className,Qc.className),e.classList.add(t==="light"?Yc.className:Qc.className)}function hh(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 _I(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)),m=b=>{const f=b.element.getBoundingClientRect(),x=f.left+f.width/2,g=f.top+f.height/2;let S=0,w=0,_=0,k=!1;if(t==="left"?(k=x<i,S=Math.max(0,a.left-f.right),w=Math.abs(g-l),_=d(a.top,a.bottom,f.top,f.bottom)):t==="right"?(k=x>i,S=Math.max(0,f.left-a.right),w=Math.abs(g-l),_=d(a.top,a.bottom,f.top,f.bottom)):t==="above"?(k=g<l,S=Math.max(0,a.top-f.bottom),w=Math.abs(x-i),_=d(a.left,a.right,f.left,f.right)):(k=g>l,S=Math.max(0,f.top-a.bottom),w=Math.abs(x-i),_=d(a.left,a.right,f.left,f.right)),!k)return Number.POSITIVE_INFINITY;const v=_>0?0:120;return S*3+w+v};let u=null,h=Number.POSITIVE_INFINITY;for(const b of r){if(b.id===o.id)continue;const f=m(b);Number.isFinite(f)&&(f>=h||(h=f,u=b))}return u||void 0}function AI(e,t,s){var i;const r=[t];let o;for(const l of r){let d;for(const m of l){const u=e.addPanel({id:m.tabKey,component:"conversation",title:_a(m),params:{kind:"conversation",tabKey:m.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});d||(d=u.id)}o=d??o}return s??((i=t[0])==null?void 0:i.tabKey)??null}function Ac(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])bn(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!==_a(a)&&i.api.setTitle(_a(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:_a(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 ph(e,t,s){var d,m;const r=s?CI(s):null;for(const u of[...e.panels])bn(u.id)&&(!r||u.id!==r)&&e.removePanel(u);if(!s||!r)return;const o=_n(t,s);if(!o&&e.totalPanels===0)return;const a=e.getPanel(r),i=vb(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)??((m=e.panels.find(u=>!bn(u.id)))==null?void 0:m.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:s},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function TI(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 Dg({doId:e,targetSessionId:t,connState:s,viewMode:r}){var m;const[o,a]=c.useState(null),{ides:i}=ki(),l=((m=i.find(u=>u.id===e&&u.type==="adhdev-daemon"))==null?void 0:m.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 u=e?Dt.get(e):null;if(!(!u||s!=="connected"))return r!=="chat"&&t?u.startScreenshots(t):u.stopScreenshots(t),()=>{u.stopScreenshots(t)}},[r,s,t,e]);const d=c.useCallback(async(u,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(u,h,t)},[e,s,t]);return{connScreenshot:o,screenshotUsage:l,handleRemoteAction:d}}const Lg=c.createContext(null);function Li(){const e=c.useContext(Lg);if(!e)throw new Error("DashboardDockviewContext missing");return e}function II(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 MI({params:e}){var m;const t=Li(),{t:s}=pe("common"),r=c.useMemo(()=>_n([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),o=c.useMemo(()=>t.ides.find(u=>u.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((m=r==null?void 0:r.routeId)==null?void 0:m.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:l,handleRemoteAction:d}=Dg({doId:a,targetSessionId:r?Wf(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(Zp,{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 RI(){const e=Li();return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:n.jsx(Jd,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!Di(e.ides,e.initialDataLoaded)})})}function PI(e){var k,v;II(e);const t=Li(),{t:s}=pe("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=>EC(y),[]),l=c.useCallback(()=>PC(a),[a]),d=c.useSyncExternalStore(i,l,l),m=Rd(o);if(e.params.kind==="remote"){const y=_n([...t.conversationsByTabKey.values()],e.params.routeId),j=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,N=e.api.isGroupActive;return n.jsxs("div",{className:`adhdev-dockview-tab${j?" is-active":""}${N?" 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 u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)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=gi(u,t.liveSessionInboxState,{isOpenConversation:h}),f=b.isReconnecting,x=b.isConnecting,g=b.isGenerating||d,S=b.isWaiting,w=b.unread,_=t.tabShortcuts[u.tabKey];return n.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${p?" is-group-active":""}${f?" is-reconnecting":""}`,title:m?`${wt(u)} · ${m}`:wt(u),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:y=>{var j;y.preventDefault(),r(y),t.openTabContextMenu({x:y.clientX,y:y.clientY,tabKey:u.tabKey,sourceDocument:((j=y.target)==null?void 0:j.ownerDocument)??document})},children:[w&&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(Zt,{size:12,thickness:2,color:"success"}):S?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(Zt,{size:12,thickness:2}):u.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(vs,{conversation:u,size:12}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("div",{className:"adhdev-dockview-tab-primary",children:wt(u)}),n.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Ds(u)}):x?n.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Ds(u)}):n.jsx("span",{children:Ds(u)})})]}),_&&n.jsx("span",{className:"text-4xs opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:_,children:_})]})}function EI(e,t){const{encodeShortcut:s,isMac:r,isShortcutListening:o,isVisibleTab:a,selectTabByShortcut:i,triggerAction:l}=t;let d=[],m=null;const u=()=>{m!=null&&e.clearTimeout(m),m=null,d=[]},h=()=>{m!=null&&e.clearTimeout(m),m=e.setTimeout(()=>{m=null,d=[]},1200)},p=f=>{if(!f.ctrlKey&&!f.metaKey&&!f.altKey)return;const x=s(f);if(!x)return;const g=_g();for(const[S,w]of Object.entries(g))if(a(S)&&w===x){f.preventDefault(),i(S);return}},b=f=>{if(f.defaultPrevented||o())return;const x=s(f);if(!x)return;const g=f.metaKey||f.ctrlKey||f.altKey;if(Xd(f.target))return;const S=Xa(r),w=Object.entries(S).filter(([R,P])=>!!P&&(R==="splitActiveTabRight"||R==="splitActiveTabDown"||R==="floatActiveTab"||R==="popoutActiveTab"||R==="dockActiveTab"||R==="focusLeftPane"||R==="focusRightPane"||R==="focusUpPane"||R==="focusDownPane"||R==="moveActiveTabToLeftPane"||R==="moveActiveTabToRightPane"||R==="moveActiveTabToUpPane"||R==="moveActiveTabToDownPane"||R==="selectPreviousGroupTab"||R==="selectNextGroupTab"||R==="setActiveTabShortcut"||R==="hideCurrentTab")),_=g?[x]:[...d.slice(-1),x].slice(-2),k=_.join(" "),v=_[_.length-1],y=w.find(([,R])=>R===k);if(y){f.preventDefault(),u(),l(y[0]);return}if(w.some(([,R])=>R.startsWith(`${k} `))){f.preventDefault(),d=_,h();return}const N=w.find(([,R])=>R===v);if(N){f.preventDefault(),u(),l(N[0]);return}if(w.some(([,R])=>R.startsWith(`${v} `))){f.preventDefault(),d=[v],h();return}u()};return e.addEventListener("keydown",p),e.addEventListener("keydown",b),()=>{u(),e.removeEventListener("keydown",p),e.removeEventListener("keydown",b)}}function DI(e){e.preventDefault()}function LI(e){switch(e){case"dockInWindow":case"dockBackToGrid":return n.jsx(uw,{size:13,className:"shrink-0 opacity-70"});case"moveBackToMain":return n.jsx(lw,{size:13,className:"shrink-0 opacity-70"});case"floatAsPanel":return n.jsx(dw,{size:13,className:"shrink-0 opacity-70"});case"openInNewWindow":return n.jsx(cw,{size:13,className:"shrink-0 opacity-70"});case"removeShortcut":return n.jsx(Pt,{size:13,className:"shrink-0 opacity-70"});case"hideTab":return n.jsx(li,{size:13,className:"shrink-0 opacity-70"});default:return n.jsx(Dp,{size:13,className:"shrink-0 opacity-70"})}}function OI({x:e,y:t,sourceDocument:s,items:r,onSelect:o}){return Wn.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:DI,onClick:i=>o(a.id,i),children:[LI(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 $I(e,t){const s=document,r=e.document;for(const d of s.querySelectorAll('link[rel="stylesheet"]')){const m=r.createElement("link");m.rel="stylesheet",m.href=d.href,d.crossOrigin&&(m.crossOrigin=d.crossOrigin),r.head.appendChild(m)}for(const d of s.querySelectorAll("style")){const m=r.createElement("style");m.textContent=d.textContent,r.head.appendChild(m)}const o=[];for(const d of s.styleSheets)try{for(const m of d.cssRules)m instanceof CSSStyleRule&&(m.selectorText===":root"||m.selectorText==="html")&&o.push(m.cssText)}catch{}if(o.length>0){const d=r.createElement("style");d.textContent=o.join(`
61
+ `})]})})}function og(e){return e instanceof Error?e.message:String(e||"")}function xT(e){const t=og(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 yT(e){const t=og(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function ag({conversation:e,mode:t,ides:s,sendDaemonCommand:r,setCliViewModeOverrides:o}){if(!e||!ht(e))return;const a=kr(e);if(a===t)return;const i=e.sessionId;i&&o(l=>({...l,[i]:t}));try{await r(Jn(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:On(e),mode:t})}catch(l){const d=yT(l);i&&!d&&o(m=>{const u={...m};return a===wT(s,i)?delete u[i]:u[i]=a,u}),xT(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 Ym(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 vT(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=Ym(o,t),i=Array.isArray(o.childSessions)?o.childSessions.map(d=>Ym(d,t)):o.childSessions,l=i!==o.childSessions;return a!==o||l?(s=!0,{...a,...l?{childSessions:i}:{}}):o});return s?r:e}function wT(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 ST({visibleConversations:e,clearedTabs:t,setClearedTabs:s,setActionLogs:r,isConversationMuted:o}){c.useEffect(()=>{kf()},[]);const a=c.useMemo(()=>e.map(i=>({id:i.tabKey,name:yb(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 hj(a),c.useEffect(()=>{if(Object.keys(t).length===0)return;const l=setTimeout(()=>{s(d=>{const m=Date.now(),u={};for(const[h,p]of Object.entries(d))m-p<5e3&&(u[h]=p);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(l)},[t,s]),c.useEffect(()=>{const i=setInterval(()=>{const l=Date.now()-3e5;r(d=>{const m=d.filter(u=>u.timestamp>l).slice(-100);return m.length===d.length?d:m})},6e4);return()=>clearInterval(i)},[r]),null}function Qm(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 $s(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=Qm(t==null?void 0:t.receivedAt)||Qm(t==null?void 0:t.timestamp)||0;return Math.max(s,r)}function Fl(e,t=0){return $s(e)||e.lastUpdated||t||0}function ig(e){return $s(e)||e.lastUpdated||0}function cg(e,t,s=ig){const r=s(t)-s(e);if(r!==0)return r;const o=(e.machineName||"").localeCompare(t.machineName||"");if(o!==0)return o;const a=e.displayPrimary.localeCompare(t.displayPrimary);if(a!==0)return a;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function Hl(e){var s;const t=Jt(e.status,{activeModal:(s=e.modalButtons)!=null&&s.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function kT(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Hl(e)&&!e.title.trim()}function jT(e){return e.length===0?null:[...e].sort((t,s)=>{const r=Number(Hl(s))-Number(Hl(t));if(r!==0)return r;const o=s.messages.length-t.messages.length;return o!==0?o:cg(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=jT(o);return r?a&&kT(r)?a:r:a||s[0]||null}function NT(e){const t=e.filter(o=>o.type!=="adhdev-daemon"),s=new Set;for(const o of t){if(!bl(o))continue;const a=gf(o);a&&s.add(a)}const r=new Map;for(const o of t){const a=Wk(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),m=l(o),u=m>d||m===d&&(o.timestamp||0)>(i.timestamp||0)?o:i;r.set(a,CT(u,u===o?i:o))}return Array.from(r.values())}function CT(e,t){const s=bl(t),r=bl(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 yc(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 _T(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 Jm(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],s=t[t.length-1],r=s?_T(cr(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 AT(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||""),Jm(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||""),Jm(s.activeChat)].join(":"))].join("|")}function TT(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 IT(e,t){const s=new Map;for(const r of e){const o=t.get(r.routeId)||r;for(const a of oo({routeId:r.routeId}))s.set(a,o);for(const a of oo({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))s.set(a,r.streamSource==="native"?o:r);for(const a of oo({tabKey:r.tabKey}))s.set(a,r)}return s}function MT(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function RT(e){const t=MT(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=cr(t.content).slice(0,240);return`${e.messages.length}:${s}:${r}`}function PT({ides:e,connectionStates:t,clearedTabs:s}){const r=c.useMemo(()=>NT(e),[e]),o=c.useMemo(()=>cf(e),[e]),a=c.useMemo(()=>qb(e),[e]),i=c.useRef([]),l=c.useRef([]),d=c.useRef([]),m=c.useRef(new Map),u=c.useRef(new Map),h=c.useMemo(()=>{const k=new Map,v=[];for(const A of r){const{connectionState:R="new",machineName:P}=zb(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),M=AT(A),E=m.current.get(A.id);if(E&&E.ide===A&&E.sourceSignature===M&&E.connectionState===R&&E.machineName===P){k.set(A.id,E),v.push(...E.conversations);continue}const C=Ld(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),I={ide:A,sourceSignature:M,connectionState:R,machineName:P,conversations:C};k.set(A.id,I),v.push(...C)}m.current=k;const y=new Map,j=A=>{const R=RT(A),P=u.current.get(A.tabKey);if(P&&P.signature===R)return y.set(A.tabKey,P),P.timestamp;const M={signature:R,timestamp:ig(A)||(P==null?void 0:P.timestamp)||0};return y.set(A.tabKey,M),M.timestamp},N=[...v].sort((A,R)=>cg(A,R,j));return u.current=y,N},[r,t,a]),p=c.useMemo(()=>{const k=TT(h,s);return yc(i.current,k)?i.current:(i.current=k,k)},[h,s]),b=c.useMemo(()=>{const k=new Map,v=Array.from(new Set(p.map(y=>y.routeId)));for(const y of v){const j=_n(p,y);j&&k.set(y,j)}return k},[p]),f=c.useMemo(()=>{const k=new Map;for(const v of p){const y=b.get(v.routeId),j=v.streamSource==="native"&&y?y:v;for(const N of oo({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))k.set(N,j)}return k},[p,b]),x=c.useMemo(()=>IT(p,b),[p,b]),g=c.useCallback(k=>{if(k)return f.get(k)},[f]),S=c.useCallback(k=>{if(k)return x.get(k)},[x]),w=c.useMemo(()=>{const k=p.filter(v=>!xs(v,o).surfaceHidden);return yc(l.current,k)?l.current:(l.current=k,k)},[p,o]),_=c.useMemo(()=>{const k=w.map(v=>v.tabKey);return yc(d.current,k)?d.current:(d.current=k,k)},[w]);return{chatIdes:r,conversations:p,visibleConversations:w,visibleTabKeys:_,resolveConversationBySessionId:g,resolveConversationByTarget:S}}function ET({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 DT({ides:e,sendDaemonCommand:t,setToasts:s,resolveConversationByTarget:r,hydrateInteractivePrompt:o}){c.useEffect(()=>{Ze.setIdes(e)},[e]),c.useEffect(()=>{Ze.setResolveAction((a,i,l)=>{t(a,i,l).catch(()=>{})})},[t]),c.useEffect(()=>{Ze.setHydrateInteractivePrompt(o)},[o]),c.useEffect(()=>{const a=Ze.onToast(i=>{s(d=>d.some(u=>u.message===i.message&&i.timestamp-u.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(m=>m.id!==i.id||m.pinned)),l)});return()=>{a()}},[s]),c.useEffect(()=>{const a=If.on("status_event",i=>{Ze.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 m=d.targetSessionId||d.targetKey||d.daemonId,u=r(m),h=(u==null?void 0:u.routeId)||d.daemonId;if(!h)return;const p=Number(d.buttonIndex),b=d.button||((g=u==null?void 0:u.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},...(u==null?void 0:u.sessionId)&&{targetSessionId:u.sessionId},...d.targetSessionId&&{targetSessionId:d.targetSessionId}}).catch(S=>console.error("[SW Action] approval failed:",S))};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 LT="adhdev_dashboardLayout_v1",OT="adhdev_dashboardDockview_v1",$T="adhdev_dashboardDockviewHiddenRestore_v1",qr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Bd(e,t){try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}}function FT(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function lg(e){return`${LT}:${e}`}function HT(e){const t=lg(e);return Bd(t,null)}function BT(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=lg(e);if(s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function dg(e){return`${OT}:${e}`}function WT(e){const t=dg(e);return Bd(t,null)}function UT(e,t){try{const s=dg(e);if(!t){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function ug(e){return`${$T}:${e}`}function KT(e){const t=ug(e);return Bd(t,{})}function qT(e,t){try{const s=ug(e);if(Object.keys(t).length===0){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function zT(){return{groupAssignments:[...qr.groupAssignments],focusedGroup:qr.focusedGroup,groupActiveTabIds:{...qr.groupActiveTabIds},groupTabOrders:{...qr.groupTabOrders},groupSizes:[...qr.groupSizes]}}function VT(e,t){return e?e.length===t.length&&e.every((s,r)=>s===t[r]):t.length===0}function GT(){const[e]=c.useState(()=>FT(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({}),[m,u]=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=HT(e)??zT();s(new Map(A.groupAssignments)),o(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),f(!0)},[b,e]);c.useEffect(()=>{b&&BT(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:a,groupTabOrders:l,groupSizes:m})},[b,e,t,r,a,l,m]),c.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),R=P=>p(P.matches);return A.addEventListener("change",R),()=>A.removeEventListener("change",R)},[]);const g=c.useCallback(A=>{s(A)},[]),S=c.useCallback(A=>{o(A)},[]),w=c.useCallback(A=>{i(A)},[]),_=c.useCallback(A=>{d(A)},[]),k=c.useCallback(A=>{u(A)},[]),v=c.useCallback(A=>{S(A)},[S]),y=c.useCallback((A,R)=>{i(P=>(P[A]??null)===(R??null)?P:{...P,[A]:R})},[]),j=c.useCallback((A,R)=>{d(P=>{const M=P[A];return VT(M,R)?P:{...P,[A]:R}})},[]),N=c.useCallback((A,R)=>{const P=R.get(A)??0;return y(P,A),v(P),P},[v,y]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:g,focusedGroup:r,updateFocusedGroup:S,focusGroup:v,groupActiveTabIds:a,updateGroupActiveTabIds:w,setGroupActiveTab:y,groupTabOrders:l,updateGroupTabOrders:_,setGroupTabOrder:j,groupSizes:m,updateGroupSizes:k,isMobile:h,hasHydratedStoredLayout:b,hydrateStoredLayout:x,focusConversationTab:N}}function YT(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const s=e[0],r=yi(t);return typeof(s==null?void 0:s.id)=="string"&&r.includes(s.id)}function QT({urlActiveTab:e,conversations:t,resolveConversationBySessionId:s,normalizedGroupAssignments:r,hasHydratedStoredLayout:o,hydrateStoredLayout:a,focusConversationTab:i,setSearchParams:l,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,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 S=s(e);S&&(i(S.tabKey,r),b.current=!0,f.current=!0,x.current!=null&&(window.clearTimeout(x.current),x.current=null),l(w=>{const _=new URLSearchParams(w);return _.delete("activeTab"),_},{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(!m||g.current||u)return;const S=h.find(w=>w.id===m.routeId);S&&(!S.chats||S.chats.length===0||YT(S.chats,m))&&(g.current=!0,p())},[d,m,u,h,p])}function vc(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=yi(t);return typeof(s==null?void 0:s.id)=="string"&&r.includes(s.id)}function mg({sendDaemonCommand:e,activeConv:t,chats:s,updateRouteChats:r,setToasts:o,setClearedTabs:a}){const[i,l]=c.useState(!1),[d,m]=c.useState(!1),u=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)||"",S=await e(g,"switch_chat",{id:x,sessionId:x,...fs(t)}),w=S==null?void 0:S.result;if((S==null?void 0:S.success)===!0||w==="switched"||w==="switched-by-title")return;w===!1||w==="not_found"?nr(o,"⚠️ Session tab not found — try refreshing history"):typeof w=="string"&&w.startsWith("error:")?nr(o,`⚠️ Switch error: ${w}`):nr(o,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),nr(o,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,o]),p=c.useCallback(async()=>{if(!(!t||i)){l(!0);try{const f=ms(t);await e(f,"new_chat",{...fs(t)}),vC(f,t.sessionId,yi(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)){m(!0);try{const g=ms(t),S=async()=>e(g,"list_chats",{forceExpand:!0,...fs(t)});let w=await S(),_=(w==null?void 0:w.chats)||((f=w==null?void 0:w.result)==null?void 0:f.chats);vc(_,t)&&(await new Promise(k=>setTimeout(k,450)),w=await S(),_=(w==null?void 0:w.chats)||((x=w==null?void 0:w.result)==null?void 0:x.chats)),w!=null&&w.success&&Array.isArray(_)&&(r(t.routeId,_),vc(_,t)&&!vc(s,t)&&nr(o,"⚠️ History dialog did not fully open — try once more"))}catch(g){console.error("Refresh history failed",g)}finally{m(!1)}}},[t,s,d,e,r,o]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:h,handleNewChat:p,handleRefreshHistory:b}}function JT(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 XT(e,t){return e.length!==t.length?!1:e.every((s,r)=>s===t[r])}function Xm(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 Zo(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 Zm(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 ZT(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 e2(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 eh(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 th(e){return Array(e).fill(100/e)}function t2({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:s,updateGroupActiveTabIds:r,updateGroupTabOrders:o,groupSizes:a,updateGroupSizes:i,isMobile:l,visibleConversations:d,visibleTabKeys:m}){const u=c.useRef(null),h=c.useMemo(()=>Zo(e,m),[e,m]),p=h.assignments,b=c.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),f=b>1,x=c.useCallback((v,y)=>{t(j=>{const N=new Map(Zo(j,m).assignments);return y===0?N.delete(v):N.set(v,y),N}),r(j=>({...j,[y]:v})),s(y)},[t,m,r,s]),g=c.useCallback(v=>{t(y=>{const j=Zo(y,m).assignments,N=new Map;for(const[A,R]of j)R!==v&&(R>v?N.set(A,R-1):N.set(A,R));return N}),i(y=>{if(y.length<=1)return[];const j=[...y];j.splice(v,1);const N=j.reduce((A,R)=>A+R,0);return N>0?j.map(A=>A/N*100):[]}),s(0)},[t,m,i,s]),S=c.useCallback((v,y)=>{y.preventDefault();const j=u.current;if(!j)return;const N=y.clientX,A=j.offsetWidth,R=a.length===b?[...a]:th(b),P=E=>{const I=(E.clientX-N)/A*100,O=[...R];O[v]=Math.max(15,R[v]+I),O[v+1]=Math.max(15,R[v+1]-I),i(O)},M=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",P),document.addEventListener("mouseup",M)},[a,b,i]),w=c.useCallback((v,y,j)=>{if(b>=4)return;const N=j==="left"?y:y+1;t(A=>{const R=Zo(A,m).assignments,P=new Map;for(const M of d){const E=R.get(M.tabKey)??0,C=E>=N?E+1:E;C>0&&P.set(M.tabKey,C)}return N>0&&P.set(v,N),P}),i(A=>{const R=A.length===b?[...A]:th(b),P=R[y]??100/b,M=Math.max(15,P/2),E=Math.max(15,P/2),C=[...R];C[y]=M,C.splice(N,0,E);const I=C.reduce((O,D)=>O+D,0);return C.map(O=>O/I*100)}),r(A=>{const R=eh(A,N);return R[N]=v,R}),o(A=>{const R=eh(A,N);return R[N]=[v],R}),s(N)},[b,t,m,d,i,r,o,s]);c.useEffect(()=>{JT(e,p)||t(p)},[e,p,t]),c.useEffect(()=>{const{mapping:v,usedGroups:y}=h;r(j=>{const N=Zm(j,v);return Xm(j,N)?j:N}),o(j=>{const N=Zm(j,v);return Xm(j,N)?j:N}),s(j=>{const N=l?0:ZT(j,y,v);return j===N?j:N}),i(j=>{const N=l?[]:e2(j,y,h.groupCount);return XT(j,N)?j:N})},[h,l,r,o,s,i]);const _=c.useMemo(()=>{const v=Array.from({length:b},()=>[]);for(const y of d){const j=p.get(y.tabKey)??0,N=Math.min(j,b-1);v[N].push(y)}return v},[d,p,b]),k=c.useCallback(()=>{t(new Map),s(0)},[t,s]);return{containerRef:u,normalizedGroupAssignments:p,numGroups:b,isSplitMode:f,groupedConvs:_,moveTabToGroup:x,closeGroup:g,handleResizeStart:S,splitTabRelative:w,clearAllSplits:k}}function wc(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 n2(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 to(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Wd(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},s=wc(t.channel)||wc(e.updateChannel)||wc(e.releaseChannel)||void 0,r=n2(t.npmTag)||(s==="preview"?"next":s==="stable"?"latest":void 0),o=to(t.targetVersion)||to(e.serverVersion)||void 0,a=to(t.minVersion)||void 0,i=to(t.updateCommand)||(s?"adhdev update":void 0);return{...s?{channel:s}:{},...r?{npmTag:r}:{},...o?{targetVersion:o}:{},...a?{minVersion:a}:{},...i?{updateCommand:i}:{}}}function Is(e,t=null){return Wd(e).targetVersion||t}function s2(e){return Wd(e).channel||null}function Ud(e){return!e||!Wd(e).channel?null:{}}function hg(e,t={},s){const r=to(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 Qa(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 nh(e){var t;return((t=Qa(e))==null?void 0:t.base)??null}function pg(e,t){const s=Qa(e),r=Qa(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 Kd(e,t){const s=e.version||null;return!s||!t||e.versionMismatch===!0&&!Qa(t)?!1:pg(s,t)}function ja(e,t){if(e.versionUpdateRequired===!0)return!0;const s=e.version||null;if(!s||!t||!pg(s,t))return!1;const r=nh(s),o=nh(t);return!r||!o?!1:r[0]!==o[0]||r[1]!==o[1]}function r2({ides:e,sendDaemonCommand:t}){const s="1.0.73",r=c.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:Kd(h,Is(h,s))).sort((h,p)=>Number(ja(p,Is(p,s)))-Number(ja(h,Is(h,s)))),[s,e]),o=c.useMemo(()=>r.some(h=>ja(h,Is(h,s))),[s,r]),a=c.useMemo(()=>r.map(h=>Is(h,s)).find(h=>typeof h=="string"&&h.trim().length>0)||s,[s,r]),[i,l]=c.useState(!1),[d,m]=c.useState({}),u=c.useCallback(async h=>{var f,x;const p=e.find(g=>g.id===h);if(!p)return;m(g=>({...g,[h]:"upgrading"}));const b=Ud(p);if(!b){m(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?m(S=>({...S,[h]:"done"})):m(S=>({...S,[h]:"error"}))}catch{m(g=>({...g,[h]:"error"}))}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:o,targetVersion:a,versionBannerDismissed:i,setVersionBannerDismissed:l,upgradingDaemons:d,handleBannerUpgrade:u}}const fg=80;function Na(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function o2(e){return{...e,createdAt:Na(e.createdAt),updatedAt:Na(e.updatedAt,e.createdAt),lastEventAt:Na(e.lastEventAt,e.updatedAt||e.createdAt)}}function a2(e){const t=bf(e);return t==="unknown:"?e.id:t}function i2(e){return[e.type,ff(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function c2(e,t=fg){const s=new Map;for(const r of e){if(r.deletedAt)continue;const o=a2(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 l2(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=gi(o,t),l=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!l)continue;const d=Na(o.lastMessageAt||(a==null?void 0:a.lastUpdated)||o.lastUpdated,s),m=i2({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(o2({id:m,dedupKey:m,type:l,routeId:o.routeId,machineId:o.daemonId||o.routeId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,tabKey:o.tabKey,title:Ff(o),preview:SN(o),createdAt:d,updatedAt:d,lastEventAt:d}))}return c2(r)}function d2(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function u2(e){const{conversations:t,liveSessionInboxState:s,maxItems:r=fg}=e,o=c.useMemo(()=>l2(t,s).slice(0,Math.max(0,r)),[t,s,r]),a=c.useMemo(()=>d2(o),[o]);return{notifications:o,unreadCount:a}}function m2({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 qd(...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 h2(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 zd(e,t=[]){if(e==="win32"){for(const s of t){if(typeof s!="string")continue;const r=h2(s);if(r)return r}return"C:\\"}for(const s of t){const r=typeof s=="string"?s.trim():"";if(r)return r}return"~"}function p2(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const s=t.includes("\\")?"\\":"/",r=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(r[0]||"")?r.length<=2?`${r[0]}\\`:r.slice(0,-1).join("\\"):r.length<=2?s:r.slice(0,-1).join(s)||s}function f2(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Vd(e,t,s){const r=await e(t,"file_list_browse",{path:s}),o=f2(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=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${i}${u}`:`${m.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(o==null?void 0:o.files)?o.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:l(a,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:a,directories:d}}function sh(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 b2(e,t={}){const s=e==null?void 0:e.mcpConfig;if((s==null?void 0:s.mode)!=="manual")return null;const o=sh(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"}).trim();return!o.includes(`
62
+ `)&&!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:sh(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"})}}function g2(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 yo(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function bg(e){return vi(e)||e.tabKey||e.routeId||null}function gg(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 ds(e){return String(e||"").trim()}function xg(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Ja(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function x2(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function y2(e,t){const s=ds(e.providerSessionId),r=ds(e.targetSessionId),o=t.find(a=>{const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey,a.routeId].map(ds).filter(Boolean);return!!(s&&i.includes(s)||r&&i.includes(r))});return o?o.tabKey:r||s||null}function v2(e,t,s){if(t.event!=="agent:generating_completed")return null;const r=xg(t.daemonId);if(r&&r!==e.machineId)return null;const o=ds(t.providerType);if(e.providerType&&o!==e.providerType)return null;const a=ds(e.resumeSessionId),i=ds(e.launchedSessionId),l=ds(t.providerSessionId),d=ds(t.targetSessionId);if(a&&a!==l&&a!==d||i&&i!==l&&i!==d)return null;const m=Ja(e.workspacePath);if(m){const u=Ja(t.workspaceName);if(u&&!x2(u,m))return null}return y2(t,s)}function rh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function w2({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=Ja(r.workspacePath),m=e.find(h=>{var g,S,w,_;if(!h||h.type==="adhdev-daemon"||xg(h.daemonId||h.id)!==r.machineId||(xo(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 k=String(r.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(y=>String(y||"")).filter(Boolean).includes(k)}if(d){const k=Ja(h.workspace||h.runtimeWorkspaceLabel);return k?k===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((_=(w=(S=(g=h.activeChat)==null?void 0:g.messages)==null?void 0:S.at)==null?void 0:w.call(S,-1))==null?void 0:_.timestamp)||0)>=r.startedAt-5e3});if(!m)return;const u=gg({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(i(),s(u))},[i,t,e,s,r]),c.useEffect(()=>Ze.onStatusEvent(d=>{const m=a.current;if(!m)return;const u=v2(m,d,t);u&&(i(),s(u))}),[i,t,s]),c.useEffect(()=>{if(!r)return;const d=window.setTimeout(()=>{o(m=>!m||m.startedAt!==r.startedAt?m:(a.current=null,null))},45e3);return()=>window.clearTimeout(d)},[r]),{trackPendingLaunch:l}}function S2(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 k2(e,t,s){var i,l,d,m;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((m=s==null?void 0:s.settings)==null?void 0:m.autoApprove)=="boolean"&&(r.autoApprove=s.settings.autoApprove),r}function j2({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:s,activeConv:r,ides:o,setCliViewModeOverrides:a}){const i=Td(),{launchCli:l}=mi(),d=c.useCallback(async(g,S)=>Vd(e,g,S),[e]),m=c.useCallback(async(g,S)=>{if(!S.trim())return{ok:!1,error:"Choose a workspace path first."};try{const w=await e(g,"workspace_add",{path:S.trim()});return w!=null&&w.success?{ok:!0}:{ok:!1,error:(w==null?void 0:w.error)||"Could not save workspace"}}catch(w){return{ok:!1,error:w instanceof Error?w.message:"Could not save workspace"}}},[e]),u=c.useCallback(async(g,S,w)=>{var _;try{const k={ideType:S,enableCdp:!0};(_=w==null?void 0:w.workspacePath)!=null&&_.trim()&&(k.workspace=w.workspacePath.trim());const v=await e(g,"launch_ide",k);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:S,workspacePath:(w==null?void 0:w.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(k){return{ok:!1,error:k instanceof Error?k.message:"Could not launch IDE"}}},[e,t]),h=c.useCallback(async(g,S,w,_)=>{const k=Date.now();try{const v=S2(w,_),y=await l(g,v),j=(y==null?void 0:y.result)||y,N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return y!=null&&y.success&&N?(t({machineId:g,kind:S,providerType:w,workspacePath:(_==null?void 0:_.workspacePath)||null,resumeSessionId:(_==null?void 0:_.resumeSessionId)||null,launchedSessionId:N,startedAt:k}),{ok:!0}):y!=null&&y.success?(t({machineId:g,kind:S,providerType:w,workspacePath:(_==null?void 0:_.workspacePath)||null,resumeSessionId:(_==null?void 0:_.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(j==null?void 0:j.error)||`Could not launch ${S.toUpperCase()} session`,code:(y==null?void 0:y.code)||(j==null?void 0:j.code)||void 0}}catch(v){return rh(v)?(t({machineId:g,kind:S,providerType:w,workspacePath:(_==null?void 0:_.workspacePath)||null,resumeSessionId:(_==null?void 0:_.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${S.toUpperCase()} session`}}},[l,e,t]),p=c.useCallback(async g=>{var S;if(i!=null&&i.listMeshes){const w=await i.listMeshes(g);return Ha(w),w}if(!g)return[];try{const w=await e(g,"list_meshes",{}),_=(w==null?void 0:w.result)??w;if((_==null?void 0:_.success)===!1)throw new Error((_==null?void 0:_.error)||"Could not load meshes");const v=(Array.isArray(_==null?void 0:_.meshes)?_.meshes:Array.isArray((S=_==null?void 0:_.result)==null?void 0:S.meshes)?_.result.meshes:[]).map(y=>{var j;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(((j=y.nodes[0])==null?void 0:j.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 Ha(v),v}catch(w){throw console.error("List meshes failed",w),w}},[i,e]),b=c.useCallback(async(g,S,w,_)=>{if(!S.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(g,S,w,_);const k=Date.now();try{const v=k2(S,w,_),y=await e(g,"launch_mesh_coordinator",v),j=(y==null?void 0:y.result)??y;if((j==null?void 0:j.success)===!1||(y==null?void 0:y.success)===!1){const A=String((j==null?void 0:j.code)||(y==null?void 0:y.code)||""),R=g2((j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(j==null?void 0:j.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:R}}const N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return N?s(N):t({machineId:g,kind:"cli",providerType:(j==null?void 0:j.cliType)||w.trim()||void 0,workspacePath:(j==null?void 0:j.workspace)||null,startedAt:k}),{ok:!0}}catch(v){return rh(v)?(t({machineId:g,kind:"cli",providerType:w.trim()||void 0,startedAt:k}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,s,e,t]),f=c.useCallback(async(g,S)=>{if(!g||!S)return[];try{const w=await e(g,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),_=(w==null?void 0:w.result)??w;return Array.isArray(_==null?void 0:_.sessions)?_.sessions:[]}catch(w){return console.error("List saved sessions failed",w),[]}},[e]),x=c.useCallback(async g=>{await ag({conversation:r,mode:g,ides:o,sendDaemonCommand:e,setCliViewModeOverrides:a})},[r,o,e,a]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:m,handleLaunchMachineIde:u,handleLaunchMachineProvider:h,handleListMachineMeshes:p,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:f,setActiveCliViewMode:x}}function N2(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 C2(e,t,s=Date.now()){return!e||!N2(t)?null:{tabKey:e,nonce:s}}function _2({isMobile:e,conversations:t,visibleConversations:s,groupActiveTabIds:r,focusedGroup:o,groupedConvs:a,setSearchParams:i}){const[l,d]=c.useState(null),[m,u]=c.useState(null),h=c.useMemo(()=>{var g,S;if(!e){if(l){const w=t.find(_=>_.tabKey===l);if(w)return w}return s[0]}const x=r[o];if(x){const w=t.find(_=>_.tabKey===x);if(w)return w}return((g=a[o])==null?void 0:g[0])||((S=a[0])==null?void 0:S[0])},[t,l,o,r,a,e,s]),p=c.useCallback(x=>{d(x)},[]),b=c.useCallback(x=>{d(x.tabKey),i(g=>{const S=new URLSearchParams(g),w=jN(x);return w?S.set("activeTab",w):S.delete("activeTab"),S},{replace:!0})},[i]),f=c.useCallback((x,g)=>{const S=C2(x,g);S&&u(S)},[]);return{activeConv:h,openDesktopConversation:b,requestScrollToBottom:f,scrollToBottomRequest:m,setDesktopActiveTab:p}}function A2(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 T2(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 I2({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 m=()=>{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){m(),o.current=null;return}if(!(e!=null&&e.sessionId)){m(),o.current=null;return}const u=xs(e,s),h=T2({tabKey:e.tabKey,historySessionId:vi(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:$s(e),liveState:u}),p=h.autoReadKey,b=A2({autoReadKey:p,shouldMarkSeen:h.shouldMarkSeen,completedKey:o.current,pendingKey:a.current});if(!h.shouldMarkSeen){b.shouldCancelPending&&m(),o.current=p;return}if(!b.shouldSchedule)return;b.shouldCancelPending&&m();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 Sc(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 M2({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:s,ides:r,sendDaemonCommand:o,updateRouteChats:a,setToasts:i,setClearedTabs:l,setSearchParams:d}){var F;const{launchCli:m}=mi(),[u,h]=c.useState(!1),[p,b]=c.useState([]),[f,x]=c.useState(()=>dn()),[g,S]=c.useState(!1),[w,_]=c.useState(null),k=c.useRef(null),v=c.useMemo(()=>s||t||e,[e,s,t]),y=!!v&&ht(v),j=c.useMemo(()=>{if(!v||!y)return null;const z=v.daemonId||v.routeId||"",Z=On(v),W=Sc(v);return`${z}:${Z}:${v.providerSessionId||""}:${W}`},[v,y]),N=c.useMemo(()=>!v||!y?"":Sc(v),[v,y]),{isCreatingChat:A,isRefreshingHistory:R,handleSwitchSession:P,handleNewChat:M,handleRefreshHistory:E}=mg({sendDaemonCommand:o,activeConv:v,chats:(F=r.find(z=>z.id===(v==null?void 0:v.routeId)))==null?void 0:F.chats,updateRouteChats:a,setToasts:i,setClearedTabs:l}),C=c.useCallback(()=>{h(!0)},[]),I=c.useCallback(()=>{h(!1)},[]),O=c.useCallback(async()=>{if(!(!v||!y||g)){S(!0);try{const z=v.daemonId||v.routeId,Z=On(v),W=Sc(v),T=await o(z,"list_saved_sessions",{agentType:Z,providerType:Z,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...W?{workspace:W}:{}}),$=(T==null?void 0:T.result)??T;b(Array.isArray($==null?void 0:$.sessions)?$.sessions:[])}catch(z){console.error("Refresh saved sessions failed",z),b([])}finally{S(!1)}}},[v,g,y,o]);c.useEffect(()=>{if(!u){k.current=null;return}if(!y){k.current=null,b([]),S(!1);return}!j||g||k.current!==j&&(k.current=j,O())},[O,u,g,y,j]);const D=c.useCallback(async z=>{if(!v||!y||!z.providerSessionId||!z.workspace)return;const Z=v.daemonId||v.routeId,W=On(v);try{_(z.providerSessionId);const T=Yk(z.summaryMetadata,"model",{preferShortValue:!0})||void 0,$=await m(Z,{cliType:W,dir:z.workspace,resumeSessionId:z.providerSessionId,initialModel:T,...T?{modelSource:"remembered"}:{}}),H=($==null?void 0:$.result)??$,q=typeof(H==null?void 0:H.sessionId)=="string"?H.sessionId:typeof(H==null?void 0:H.id)=="string"?H.id:"";q&&d(U=>{const K=new URLSearchParams(U);return K.set("activeTab",q),K},{replace:!0}),I()}catch(T){console.error("Resume saved session failed",T)}finally{_(null)}},[I,v,y,o,d]);return{historyModalOpen:u,openHistoryModal:C,closeHistoryModal:I,historyTargetConv:v,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:A,isHistoryRefreshingHistory:R,handleHistorySwitchSession:P,handleHistoryNewChat:M,handleHistoryRefresh:E,savedHistorySessions:p,savedHistoryFilters:f,setSavedHistoryFilters:x,missingWorkspaceResumePath:N,isSavedHistoryLoading:g,resumingSavedHistorySessionId:w,handleRefreshSavedHistory:O,handleResumeSavedHistorySession:D}}function R2({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:l}){const[d,m]=c.useState(null),[u,h]=c.useState(null),p=c.useMemo(()=>{if(e||!r)return null;const S=l(r);return S&&!ht(S)?S:null},[e,r,l]),b=c.useMemo(()=>{const S=d==null?void 0:d.routeId;if(!S)return null;const w=d!=null&&d.tabKey?a.find(_=>_.tabKey===d.tabKey):o?a.find(_=>_.tabKey===o):null;return(w==null?void 0:w.routeId)===S?w:_n(a,S)},[a,d,o]),f=c.useMemo(()=>{if(b)return i.find(S=>S.id===b.routeId)},[i,b]);c.useEffect(()=>{p&&(m({routeId:p.routeId,tabKey:Ju(p)}),h(p),s({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,s,p]);const x=c.useCallback(S=>{S&&(m({routeId:S.routeId,tabKey:Ju(S)}),h(S))},[]),g=c.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:b,remoteDialogIdeEntry:f,remoteDialogActiveConv:u,setRemoteDialogActiveConv:h,openRemoteDialog:x,closeRemoteDialog:g}}function P2({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:p,setRemoteDialogActiveConv:b,openRemoteDialog:f,closeRemoteDialog:x}=R2({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:l}),[g,S]=c.useState(!1),[w,_]=c.useState(null),k=c.useCallback(async j=>{const N=j||d;!N||!ht(N)||(_(N),S(!0))},[d]),v=c.useCallback(()=>{S(!1),_(null)},[]),y=c.useCallback(async j=>{const N=w||d;if(!N||!ht(N)){v();return}S(!1);try{const A=On(N),R=N.routeId||N.daemonId||"";await m(R,"stop_cli",{cliType:A,targetSessionId:N.sessionId,mode:j,...ji(N)})}catch(A){console.error("Stop CLI failed:",A)}finally{_(null)}},[d,v,w,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:p,setRemoteDialogActiveConv:b,openRemoteDialog:f,closeRemoteDialog:x,cliStopDialogOpen:g,cliStopTargetConv:w,requestCliStop:k,cancelCliStop:v,confirmCliStop:y}}function kc(e,t=!0){return(e??!0)&&t}const Gd=c.memo(function({activeConv:t,clearToken:s,isCliTerminal:r,ideEntry:o,terminalRef:a,commands:i,actionLogs:l,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:h=!0}){const{handleModalButton:p,handleRelaunch:b,handleSendChat:f,handleSendNowQueued:x,handleCancelQueued:g,isSendingChat:S,sendFeedbackMessage:w,pendingLocalMessage:_,pendingLocalMessages:k,retireEchoedPendingMessages:v,handleFocusAgent:y,isFocusingAgent:j}=i,N=r,A=!r,R=kc(h,N),P=kc(h,A),M=kc(h),{t:E}=pe("common"),C=I=>n.jsx(db,{activeConv:t,ideEntry:o,handleSendChat:f,handleSendNowQueued:x,handleCancelQueued:g,isSendingChat:S,sendFeedbackMessage:w,pendingLocalMessage:_,pendingLocalMessages:k,retireEchoedPendingMessages:v,handleFocusAgent:y,isFocusingAgent:j,actionLogs:l,userName:d,scrollToBottomRequestNonce:m,isInputActive:u&&I,isVisible:I});return n.jsxs(n.Fragment,{children:[n.jsx(df,{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(Xt,{size:14})}),n.jsxs("span",{className:"flex flex-1 items-center gap-1",children:[n.jsx("span",{className:"font-semibold",children:E("paneGroup.cdpDisconnectedShort")}),n.jsx(tt,{content:E("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:E("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:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:n.jsx(k_,{activeConv:t,clearToken:s,terminalRef:a,handleSendChat:f,isSendingChat:S,sendFeedbackMessage:w,isVisible:R,isInputActive:u&&R})}),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:C(P)})]}):C(M)]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.commands===t.commands&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function E2({conversation:e,className:t="",onOpenNativeConversation:s,onOpenMachine:r,interactive:o=!0,meshOnly:a=!1}){const{t:i}=pe("common"),l=qs(),d=Jn(e),m=a?null:$f(e),u=!a&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),h=!a&&e.streamSource==="agent-stream"&&!!e.agentName,p=!a&&!h&&e.transport==="pty",b=hr(e),f=kN(e),x=kd(e).role,g=e.meshQueueStats,S=x==="coordinator",w=c.useCallback(()=>{if(r){r();return}d&&l("/dashboard",{state:{openMachineId:d}})},[d,l,r]),_=c.useCallback(()=>{if(s){s();return}const k=bg(e);k&&l(yo(k))},[e,l,s]);return!u&&!h&&!p&&!m&&!x&&!g?null:n.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(o?n.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:_,title:f,children:[n.jsx(Hn,{size:12}),n.jsx("span",{children:f})]}):n.jsxs("span",{className:"conversation-meta-chip",title:f,children:[n.jsx(Hn,{size:12}),n.jsx("span",{children:f})]})),h&&n.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[n.jsx(ur,{size:12}),n.jsx("span",{children:b})]}),p&&n.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[n.jsx(ur,{size:12}),n.jsx("span",{children:b})]}),m&&(o?n.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:m,children:[n.jsx(dr,{size:12}),n.jsx("span",{children:m})]}):n.jsxs("span",{className:"conversation-meta-chip",title:m,children:[n.jsx(dr,{size:12}),n.jsx("span",{children:m})]})),S&&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(ew,{size:12}),n.jsx("span",{children:i("dashboard.metaChips.queuePending",{count:g.pending})})]})]})}function D2({selectedConversation:e,isStandalone:t,selectedIdeEntry:s,actionLogs:r,userName:o,commands:a,onBack:i,onOpenNativeConversation:l,onOpenMachine:d,onOpenHistory:m,onOpenRemote:u,onOpenMeshGraph:h,onStopCli:p,cliViewMode:b,onSetCliViewMode:f}){const{t:x}=pe("common"),g=c.useRef(null),S=xi(lf(e)),w=ht(e),_=w&&b==="terminal",k=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 ${k} 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(rd,{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(vs,{conversation:e,size:15}),n.jsx("span",{className:"min-w-0 truncate",children:wt(e)})]}),n.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:n.jsx(E2,{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:[w&&b&&n.jsx(kb,{mode:b,onChange:f,compact:!0}),w&&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(Pt,{size:14})}),n.jsx($b,{conversation:e,onOpenMeshGraph:h}),n.jsx(Lb,{conversation:e,onOpenHistory:m,onOpenRemote:u,iconSize:14})]})]}),n.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:n.jsx(Gd,{activeConv:e,clearToken:0,isCliTerminal:_,ideEntry:s,terminalRef:g,commands:a,actionLogs:r,userName:o})}),n.jsx(hd,{promptSession:S.promptSession,isSubmitting:S.isSubmitting,error:S.responseError,onSubmit:S.submit,onCancel:S.cancel})]})}function L2(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function yg({isStandalone:e=!1}={}){const{t}=pe("common"),[s,r]=c.useState("unix"),[o,a]=c.useState("powershell"),[i,l]=c.useState(!1),d=s==="unix"?"unix":o,m=c.useMemo(()=>eA(),[]);c.useEffect(()=>{r(L2())},[]);const u=c.useCallback(()=>{navigator.clipboard.writeText(m[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:u,title:t("app.installCommand.clickToCopy"),children:[n.jsx("span",{className:"text-text-muted select-none",children:m[d].prompt}),n.jsx("span",{className:"flex-1 break-all",children:m[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(xr,{size:12}):n.jsx(od,{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 vg({section:e,onSectionChange:t}){const{t:s}=pe("common"),r=[{key:"machines",label:s("nav.machines"),icon:Hn},{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 ea({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 Qs({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 Cs({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 O2({title:e,isMuted:t,onToggleMute:s,onHide:r,onStop:o}){const{t:a}=pe(),[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 m="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",u=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(rl,{size:13}):n.jsx(Ip,{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 ${m}`,onClick:u(s),children:[t?n.jsx(gs,{size:15}):n.jsx(rl,{size:15}),a(t?"conversation.unmuteThis":"conversation.muteThis")]}),r&&n.jsxs("button",{type:"button",role:"menuitem",className:`mobile-inbox-hide-button ${m}`,onClick:u(r),children:[n.jsx(li,{size:15}),a("mobileInbox.hide")]}),o&&n.jsxs("button",{type:"button",role:"menuitem",className:`mobile-inbox-stop-button ${m} !text-status-error`,onClick:u(o),children:[n.jsx(Pt,{size:15}),a("mobileInbox.stopSessionTitle")]})]})]})}function ta({item:e,type:t,getAvatarText:s,onOpenConversation:r,onRequestHideConversation:o,onRequestStopCli:a,onOpenMeshGraph:i,onCollectChatDebugBundle:l,isMuted:d,onToggleMute:m}){const{t:u}=pe(),h=t==="needs_attention"||t==="task_complete",p=t==="working",b=t==="earlier",f=t==="task_complete",{isReconnecting:x,isConnecting:g,isErrored:S}=ws(e.conversation),w=wt(e.conversation),_=To(e.conversation),k=xb(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",j=b?"text-text-secondary":"text-text-primary",N=b?"text-text-muted":"text-text-secondary",A=b?"text-text-secondary opacity-80":"text-text-muted",R=b?"text-text-muted opacity-80":"text-text-muted",P=!p&&!f,M=fb(e.conversation),E="text-[color:var(--status-warning)]",C=I=>{if(!l||!S_())return;I.preventDefault(),I.stopPropagation();const O=l==null?void 0:l(e.conversation);Promise.resolve(O).catch(D=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",D)})};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(w)}),M&&i&&n.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-[color:color-mix(in_srgb,var(--mesh-coordinator)_34%,transparent)] bg-bg-primary/70 text-[color:var(--mesh-coordinator)] transition-colors hover:bg-[color:color-mix(in_srgb,var(--mesh-coordinator)_10%,transparent)]",onClick:I=>{I.preventDefault(),I.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:w}),title:u("mobileInbox.openLiveMeshGraph"),children:n.jsx(Ln,{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:C,type:"button",children:[n.jsxs("div",{className:"flex items-center gap-1.5 pr-[92px]",children:[n.jsx(vs,{conversation:e.conversation,size:13}),n.jsx("span",{className:`text-[15px] leading-[22px] font-bold truncate tracking-tight ${j}`,children:w})]}),n.jsxs("div",{className:`text-xs font-medium truncate flex items-center ${N}`,children:[n.jsx("span",{className:"truncate",children:_}),n.jsx(Nd,{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:`${E} animate-pulse`,children:u("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:u("mobileInbox.connectingItem")})]}):k==="Action needed"?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:E,children:u("mobileInbox.actionNeeded")})]}):S&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:"text-[color:var(--status-error)]",children:u("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 ${R}`,children:Fp(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:u("mobileInbox.done")}),n.jsx(O2,{title:w,isMuted:d,onToggleMute:m,onHide:o,onStop:a})]})]})},e.conversation.tabKey)}function oh({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 $2({section:e,attentionItems:t,unreadItems:s,workingItems:r,completedItems:o,hiddenConversations:a,machineCards:i,getAvatarText:l,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:h,onHideConversation:p,onShowHiddenConversation:b,onOpenMeshGraph:f,onStopCli:x,onOpenNewSession:g,onOpenMachine:S,onOpenSettings:w,onSectionChange:_,wsStatus:k="connected",initialDataLoaded:v=!0,conversationsLoaded:y,isStandalone:j=!1,onCollectChatDebugBundle:N,isConversationMuted:A,onToggleMuteConversation:R}){const{t:P}=pe(),M=k==="disconnected"||k==="reconnecting"||k==="offline"||k==="auth_failed",E=!M&&!v,C=!M&&!(y??v),I=i.length>0,O=t.length>0||s.length>0||r.length>0||o.length>0,D=P(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),F=j?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",z=j?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",Z=c.useCallback(async $=>{const H=ms($);if(!H)return;const q=Array.isArray($.messages)?$.messages:[],U=zf({activeConv:$,visibleMessages:q,actionLogs:d,visibleBarControlCount:0,chatState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:q.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),K=await m(H,"get_chat_debug_bundle",{...fs($),delivery:"daemon_file",frontendSnapshot:U}),oe=Ps(K),ke=Yf(oe),J=await Gf(ke);J==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),Ze.showToast(Vf(oe,{locatorCopyStatus:J}),J==="failed"?"warning":"success")},[d,m]),W=N||Z,T=c.useCallback($=>{p&&(p($),Ze.showToast(P("mobileInbox.hiddenToast",{title:wt($)}),"info",{duration:6e3,actions:[{label:P("mobileInbox.undo"),variant:"primary",onClick:()=>{b?b($):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 ${F}`,children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:D}),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(gs,{size:13}),n.jsx("span",{children:t.length+s.length})]}),n.jsx("button",{onClick:w,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(yr,{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] ${z}`,children:[e==="machines"&&n.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?n.jsx(Cs,{icon:n.jsx(Zt,{size:32}),title:P(k==="offline"?"mobileInbox.networkOffline":k==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:P(k==="offline"?"mobileInbox.waitingForNetwork":k==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):E?n.jsx(Cs,{icon:n.jsx(Zt,{size:32}),title:P("mobileInbox.loading"),subtitle:P("mobileInbox.loadingSubtitle")}):i.length===0?n.jsx(Cs,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:P(j?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:P(j?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!j&&n.jsx("div",{className:"w-full max-w-[360px] mt-4",children:n.jsx(yg,{})})}):n.jsx(Qs,{children:i.map(($,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:()=>S($.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($.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:$.label}),n.jsxs("span",{className:"flex items-center gap-2 text-2xs font-medium text-text-muted shrink-0",children:[n.jsx(oh,{count:$.generatingCount,label:P("mobileInbox.generatingCount",{count:$.generatingCount})}),$.unread>0?n.jsx("span",{className:"text-accent-primary",children:P("mobileInbox.newCount",{count:$.unread})}):$.total>0?P("mobileInbox.chatCount",{count:$.total}):P("mobileInbox.idle")]})]}),n.jsx("div",{className:"text-xs font-medium text-text-secondary truncate",children:$.subtitle}),$.total>0?n.jsxs("div",{className:"text-xxs text-text-muted mt-0.5",children:[P("mobileInbox.chatCount",{count:$.total}),$.unread>0?P("mobileInbox.unreadSuffix",{count:$.unread}):"",$.generatingCount>0?P("mobileInbox.collapsedGeneratingSuffix",{count:$.generatingCount}):""]}):$.generatingCount>0?n.jsx("div",{className:"text-xxs text-accent-primary mt-0.5 font-medium",children:P("mobileInbox.generatingCount",{count:$.generatingCount})}):n.jsx("div",{className:"text-xxs text-text-muted mt-0.5 italic opacity-70",children:P("mobileInbox.noActiveChats")})]})]},$.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(ea,{title:P("mobileInbox.needsAttention"),className:"mb-0"}),n.jsx(Qs,{children:t.map(($,H)=>n.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:n.jsx(ta,{item:$,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:p?()=>T($.conversation):void 0,onRequestStopCli:x?()=>x($.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:W,isMuted:A==null?void 0:A($.conversation),onToggleMute:R?()=>R($.conversation):void 0})},$.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(ea,{title:P("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),n.jsx(Qs,{children:s.map(($,H)=>n.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:n.jsx(ta,{item:$,type:"task_complete",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:p?()=>T($.conversation):void 0,onRequestStopCli:x?()=>x($.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:W,isMuted:A==null?void 0:A($.conversation),onToggleMute:R?()=>R($.conversation):void 0})},$.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(ea,{title:P("mobileInbox.workingNow"),className:"mb-0 mt-2"}),n.jsx(Qs,{children:r.map(($,H)=>n.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:n.jsx(ta,{item:$,type:"working",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:p?()=>T($.conversation):void 0,onRequestStopCli:x?()=>x($.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:W,isMuted:A==null?void 0:A($.conversation),onToggleMute:R?()=>R($.conversation):void 0})},$.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(ea,{title:P("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?n.jsx(Qs,{children:o.map(($,H)=>n.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:n.jsx(ta,{item:$,type:"earlier",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:p?()=>T($.conversation):void 0,onRequestStopCli:x?()=>x($.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:W,isMuted:A==null?void 0:A($.conversation),onToggleMute:R?()=>R($.conversation):void 0})},$.conversation.tabKey))}):O?n.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:P("mobileInbox.allCaughtUp")}):M?n.jsx(Cs,{icon:n.jsx(Zt,{size:28}),title:P("mobileInbox.connecting"),subtitle:P("mobileInbox.connectingSubtitle")}):C?n.jsx(Cs,{icon:n.jsx(Zt,{size:28}),title:P("mobileInbox.loading"),subtitle:P("mobileInbox.loadingSubtitle")}):I?n.jsx(Cs,{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(Cs,{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 $=I0(a);return n.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:n.jsx(Qs,{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(oh,{count:$,label:P("mobileInbox.generatingCount",{count:$})})]}),n.jsxs("div",{className:"mt-0.5 text-xxs text-text-muted",children:[P("mobileInbox.collapsedCount",{count:a.length}),$>0?P("mobileInbox.collapsedGeneratingSuffix",{count:$}):""]})]}),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&&O&&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(vg,{section:e,onSectionChange:_})]})}function F2(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=go(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(t?t("launch.messageCountShort",{count:e.messageCount}):`${e.messageCount} msgs`);const o=F2(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 Yd({title:e,description:t,currentPath:s,directories:r,busy:o=!1,error:a="",confirmLabel:i,inline:l=!1,onClose:d,onNavigate:m,onConfirm:u}){const[h,p]=c.useState(s),{t:b}=pe("common"),f=i??b("machine.workspaceBrowse.useThisFolder");c.useEffect(()=>{p(s)},[s]);const x=p2(s),g=h.trim(),S=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(Pt,{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||m(x)},disabled:!x||o,children:[n.jsx(rd,{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:w=>p(w.target.value),onKeyDown:w=>{w.key!=="Enter"||!g||o||(w.preventDefault(),m(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||m(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(w=>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:()=>m(w.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(Hs,{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:w.name}),n.jsx("span",{className:"block text-2xs text-text-muted truncate",children:w.path})]})]},w.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:()=>u(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:S}):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:S})})})}function Ei({title:e,description:t,details:s,workspaceOptions:r,selectedWorkspaceKey:o,onWorkspaceChange:a,confirmLabel:i,busyLabel:l,busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:h,showModelInput:p,modelValue:b,onModelChange:f,historyProviderNode:x,onConfirm:g,onCancel:S}){const{t:w}=pe("common"),_=i??w("machine.launchConfirm.launch"),k=l??w("machine.launchConfirm.launching"),v=r==null?void 0:r.find(j=>j.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:S,"aria-label":w("machine.launchConfirm.closeAria"),children:n.jsx(Pt,{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:w("machine.launchConfirm.workspace")}),n.jsx("select",{value:o||"",onChange:j=>a(j.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(j=>n.jsx("option",{value:j.key,children:j.label},j.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((j,N)=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),n.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${N}`)),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:w("machine.launchConfirm.languageModel")}),n.jsx("input",{type:"text",value:b||"",onChange:j=>f(j.target.value),placeholder:w("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})]}),m&&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:w("machine.launchConfirm.cliArgs")}),n.jsx("input",{type:"text",value:u||"",onChange:j=>h(j.target.value),placeholder:w("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:S,disabled:d,children:w("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(Tp,{size:14}),d?k:_]})]})]})});return typeof document>"u"?y:Wn.createPortal(y,document.body)}function ah(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Sg(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 u of t.workspaces||[])l.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${ah(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const d=(s==null?void 0:s.trim())||"",m=d?(t.workspaces||[]).find(u=>u.path===d):null;if(d&&!m&&l.push({key:`custom:${d}`,label:ah(d),description:d,workspaceId:null,workspacePath:d}),r){const u=`saved:${r}`;if(l.some(h=>h.key===u))return{options:l,selectedKey:u}}return m?{options:l,selectedKey:`saved:${m.id}`}:d?{options:l,selectedKey:`custom:${d}`}:{options:l,selectedKey:"__home__"}}function H2(e){return e==="ide"?"IDE":"CLI"}function B2(e,t){return[H2(e.kind),e.subtitle||"",e.providerSessionId?t?t("launch.savedHistoryBadge"):"Saved history":""].filter(Boolean).join(" · ")}function W2(e){return e.lastLaunchedAt?hi(e.lastLaunchedAt):""}function kg(e,t){return{metaText:B2(e,t),updatedLabel:W2(e)}}function jc(e,t){return e?"ide":t>0?"cli":null}function U2({selectedMachineEntry:e,cliProviders:t,machineAction:s,onBrowseDirectory:r,onListSavedSessions:o}){var he,Me,Ee,Te;const a=jr(),[i,l]=c.useState(!1),d=(((he=e.detectedIdes)==null?void 0:he.length)||0)>0,m=c.useMemo(()=>(e.workspaces||[]).map(Ne=>({id:Ne.id,path:Ne.path,label:Ne.label})),[e]),u=e.defaultWorkspaceId||null,[h,p]=c.useState(u||((Me=m[0])==null?void 0:Me.id)||""),[b,f]=c.useState(""),[x,g]=c.useState(""),[S,w]=c.useState([]),[_,k]=c.useState(!1),[v,y]=c.useState(""),[j,N]=c.useState(!1),[A,R]=c.useState(jc(d,t.length)),P=c.useRef(null),[M,E]=c.useState(null),C=c.useRef("__home__"),[I,O]=c.useState("__home__"),[D,F]=c.useState(""),[z,Z]=c.useState(""),[W,T]=c.useState(""),[$,H]=c.useState([]),[q,U]=c.useState(()=>dn().textQuery),[K,oe]=c.useState(()=>dn().workspaceQuery),[ke,J]=c.useState(()=>dn().modelQuery),[ye,ae]=c.useState(()=>dn().resumableOnly),[re,de]=c.useState(()=>dn().sortMode),[ne,ie]=c.useState(!1),[_e,G]=c.useState(!1),B=c.useRef(0),Q=c.useRef(0),ue=c.useRef(null),Re=c.useRef(null);c.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&a(e.id,{minFreshMs:3e4}).catch(()=>{})},[a,e]);const Le=h==="__custom__"?b.trim():((Ee=m.find(Ne=>Ne.id===h))==null?void 0:Ee.path)||"",Pe=h==="__custom__"&&!!Le&&s.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(s.message),Fe=h!=="__custom__"&&((Te=m.find(Ne=>Ne.id===h))==null?void 0:Te.path)||"",X=c.useMemo(()=>(e.recentLaunches||[]).map(Ne=>Ne.workspace),[e]),ve=c.useCallback(async Ne=>{const Ue=B.current+1;B.current=Ue,k(!0),y("");try{const $e=await r(Ne);if(B.current!==Ue)return;g($e.path),f($e.path),w($e.directories)}catch($e){if(B.current!==Ue)return;y($e instanceof Error?$e.message:"Could not load folder")}finally{B.current===Ue&&k(!1)}},[r]),Se=c.useCallback(()=>{var Ue;p("__custom__"),N(!0);const Ne=zd(e.platform,qd(b.trim(),Fe,X,e.defaultWorkspacePath,(Ue=m.find($e=>$e.id===u))==null?void 0:Ue.path,m.map($e=>$e.path)));ve(Ne)},[b,u,ve,X,Fe,e.platform,m]),Ce=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("")},[]),L=c.useCallback(Ne=>{if(p(Ne),Ne==="__custom__"){Se();return}f("")},[Se]),Y=c.useCallback(Ne=>{p("__custom__"),f(Ne)},[]),ce=c.useCallback((Ne,Ue)=>{const $e=Q.current+1;Q.current=$e,P.current=Ue,C.current=Ne.selectedWorkspaceKey||"__home__",O(Ne.selectedWorkspaceKey||"__home__"),F(Ne.initialArgs||""),Z(Ne.initialModel||""),T(""),H([]);const ot=Ne.providerType?`${e.id}:${Ne.providerType}`:null;if(D1(Re.current,ot)){const at=dn();U(at.textQuery),oe(at.workspaceQuery),J(at.modelQuery),ae(at.resumableOnly),de(at.sortMode)}Re.current=ot,E(Ne),Ne.providerType&&o?(ie(!0),o(Ne.providerType).then(at=>{Q.current===$e&&H(at||[])}).catch(at=>{Q.current===$e&&console.warn("Failed to load saved sessions",at)}).finally(()=>{Q.current===$e&&ie(!1)})):ie(!1)},[o,e.id]),te=c.useMemo(()=>Ed($,{textQuery:q,workspaceQuery:K,modelQuery:ke,resumableOnly:ye,sortMode:re}),[ke,ye,$,re,q,K]);c.useEffect(()=>{W&&(te.some(Ne=>Ne.providerSessionId===W)||T(""))},[te,W]);const fe=c.useCallback(()=>{P.current&&(G(!0),P.current().finally(()=>{P.current=null,G(!1),E(null)}))},[]),V=c.useCallback(()=>{Q.current+=1,P.current=null,ie(!1),E(null)},[]),se=c.useCallback(Ne=>{C.current=Ne,O(Ne)},[]);return c.useEffect(()=>{var Ne;ue.current!==e.id&&(B.current+=1,Q.current+=1,ue.current=e.id,p(u||((Ne=m[0])==null?void 0:Ne.id)||"__custom__"),f(""),g(""),w([]),k(!1),y(""),N(!1),P.current=null,E(null),H([]),ie(!1),G(!1),U(dn().textQuery),oe(dn().workspaceQuery),J(dn().modelQuery),ae(dn().resumableOnly),de(dn().sortMode),Re.current=null,R(jc(d,t.length)))},[t.length,u,d,e.id,m]),c.useEffect(()=>{var Ne;h!=="__custom__"&&(h&&m.some(Ue=>Ue.id===h)||p(u||((Ne=m[0])==null?void 0:Ne.id)||"__custom__"))},[u,h,m]),c.useEffect(()=>{A==="ide"&&d||A==="cli"&&t.length>0||R(jc(d,t.length))},[A,t.length,d]),{showAllRecent:i,setShowAllRecent:l,hasIdeOptions:d,workspaceRows:m,defaultWorkspaceId:u,workspaceChoice:h,customWorkspacePath:b,browseCurrentPath:x,browseDirectories:S,browseBusy:_,browseError:v,browseDialogOpen:j,activeLauncherKind:A,launchConfirm:M,launchConfirmWorkspaceKeyRef:C,launchConfirmWorkspaceKey:I,launchConfirmArgs:D,launchConfirmModel:z,launchConfirmResumeId:W,launchConfirmSavedSessions:$,launchConfirmTextFilter:q,launchConfirmWorkspaceFilter:K,launchConfirmModelFilter:ke,launchConfirmResumableOnly:ye,launchConfirmSortMode:re,filteredLaunchConfirmSavedSessions:te,launchConfirmSessionsLoading:ne,launchConfirmBusy:_e,resolvedWorkspacePath:Le,canCreateMissingWorkspace:Pe,openBrowseDialog:Se,loadBrowsePath:ve,handleWorkspaceChoiceChange:L,chooseCustomWorkspacePath:Y,setCustomWorkspacePath:f,setBrowseDialogOpen:N,setActiveLauncherKind:R,openLaunchConfirm:ce,handleConfirmLaunch:fe,closeLaunchConfirm:V,setWorkspaceSelectionFromOption:Ce,setLaunchConfirmWorkspaceKeyAndSync:se,setLaunchConfirmArgs:F,setLaunchConfirmModel:Z,setLaunchConfirmResumeId:T,setLaunchConfirmTextFilter:U,setLaunchConfirmWorkspaceFilter:oe,setLaunchConfirmModelFilter:J,setLaunchConfirmResumableOnly:ae,setLaunchConfirmSortMode:de}}function K2({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:s,cliProviders:r,selectedMachineNeedsUpgrade:o,appVersion:a,machineAction:i,isStandalone:l,section:d,showBottomNav:m,onBack:u,onSectionChange:h,onOpenConversation:p,onOpenRecent:b,onOpenMachineDetails:f,onMachineUpgrade:x,onBrowseDirectory:g,onListSavedSessions:S}){const{t:w}=pe("common"),_=E=>E==="ide"?"IDE":"CLI",k=s.slice(0,4),v=t.slice(0,3),y=U2({selectedMachineEntry:e,cliProviders:r,machineAction:i,onBrowseDirectory:g,onListSavedSessions:S}),j=c.useMemo(()=>k.map(E=>{const{metaText:C,updatedLabel:I}=kg(E,w);return{key:`recent-launch:${E.id}`,primary:E.label,secondary:C,updatedLabel:I,onClick:()=>{const{options:O,selectedKey:D}=Sg({machine:{workspaces:y.workspaceRows,defaultWorkspaceId:y.defaultWorkspaceId},currentWorkspacePath:E.workspace,homeLabel:w("newSession.homeDirectory"),homeDescription:w("newSession.launchWithoutWorkspace")});y.openLaunchConfirm({title:E.kind==="ide"?Ka(w,"restart-ide",E.label):E.providerSessionId?Bb(w,E.label):Ka(w,"start-fresh",E.label),description:E.kind==="ide"?qa(w,"restart-ide"):E.providerSessionId?Wb(w):qa(w,"start-fresh"),confirmLabel:E.kind==="ide"?za(w,"restart-ide"):E.providerSessionId?Il(w,!0):za(w,"start-fresh"),busyLabel:E.kind==="ide"?Va(w,"restart-ide"):E.providerSessionId?Fb(w,!0):Va(w,"start-fresh"),workspaceOptions:O,selectedWorkspaceKey:D,details:[{label:"Mode",value:_(E.kind)},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]},async()=>{const F=O.find(z=>z.key===y.launchConfirmWorkspaceKeyRef.current);y.setWorkspaceSelectionFromOption(F),await b({...E,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[y,b,k,w]),N=c.useMemo(()=>v.map(E=>({key:`recent-chat:${E.conversation.tabKey}`,conversation:E.conversation,primary:wt(E.conversation),secondary:o_(E.conversation,{timestampLabel:E.timestamp?Fp(E.timestamp):null}),unread:E.unread,onClick:()=>p(E.conversation)})),[p,v]),A=y.showAllRecent?j:j.slice(0,4),R=j.length>0,P=N.length>0,M=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 ${M} 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:u,type:"button","aria-label":w("common.back"),children:n.jsx(rd,{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:yn(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||w("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:w("machine.mobile.currentChats")}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:N.map(E=>n.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${E.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:E.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(vs,{conversation:E.conversation,size:13}),n.jsx("span",{className:"min-w-0 truncate",children:E.primary})]}),n.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:E.secondary})]},E.key))})]}),R&&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:w("machine.mobile.recentLaunches")}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(E=>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:E.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:E.primary}),E.updatedLabel&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:E.updatedLabel})]}),n.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:E.secondary})]},E.key))}),j.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(E=>!E),children:y.showAllRecent?w("machine.mobile.showFewer"):w("machine.mobile.showMore",{count:j.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:w("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:w("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:w("machine.mobile.machineDetails")})})]})]})]}),y.browseDialogOpen&&n.jsx(Yd,{title:w("machine.mobile.browseTitle"),description:w("machine.mobile.browseDescription"),currentPath:y.browseCurrentPath,directories:y.browseDirectories,busy:y.browseBusy,error:y.browseError,confirmLabel:w("machine.mobile.useThisFolder"),onClose:()=>y.setBrowseDialogOpen(!1),onNavigate:E=>{y.loadBrowsePath(E)},onConfirm:E=>{y.chooseCustomWorkspacePath(E),y.setBrowseDialogOpen(!1)}}),y.launchConfirm&&n.jsx(Ei,{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?Il(w,!!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:w("launch.resumeSavedHistory")}),y.launchConfirmSessionsLoading&&n.jsx("div",{className:"text-3xs text-text-secondary font-medium",children:w("launch.loadingShort")})]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2",children:Dd(w)}),n.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[n.jsx("input",{type:"text",value:y.launchConfirmTextFilter,onChange:E=>y.setLaunchConfirmTextFilter(E.target.value),placeholder:w("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:E=>y.setLaunchConfirmWorkspaceFilter(E.target.value),placeholder:w("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:E=>y.setLaunchConfirmModelFilter(E.target.value),placeholder:w("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:E=>y.setLaunchConfirmSortMode(E.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:w("machine.mobile.sortRecent")}),n.jsx("option",{value:"oldest",children:w("machine.mobile.sortOldest")}),n.jsx("option",{value:"messages",children:w("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:E=>y.setLaunchConfirmResumableOnly(E.target.checked),disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),w("machine.mobile.resumableOnly")]}),n.jsxs("select",{value:y.launchConfirmResumeId,onChange:E=>y.setLaunchConfirmResumeId(E.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:$1(w)}),y.filteredLaunchConfirmSavedSessions.map(E=>n.jsxs("option",{value:E.providerSessionId,disabled:!E.canResume,children:[E.title||E.providerSessionId," ",E.canResume?"":w("machine.mobile.workspaceMissing")]},E.providerSessionId))]}),!y.launchConfirmSessionsLoading&&y.launchConfirmSavedSessions.length>0&&y.filteredLaunchConfirmSavedSessions.length===0&&n.jsx("div",{className:"mt-2 text-2xs text-text-muted",children:w("machine.mobile.noHistoryMatches")}),y.launchConfirmResumeId&&(()=>{const E=y.filteredLaunchConfirmSavedSessions.find(I=>I.providerSessionId===y.launchConfirmResumeId);if(!E)return null;const C=wg(E,w);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:C.title}),n.jsx("div",{className:"font-mono break-all mt-0.5",children:C.providerSessionId}),n.jsx("div",{className:"mt-1",children:C.metaLine}),C.updatedLabel&&n.jsx("div",{className:"mt-1 text-text-secondary",children:C.updatedLabel}),C.preview&&n.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:C.preview})]})})()]}),onConfirm:y.handleConfirmLaunch,onCancel:y.closeLaunchConfirm}),m&&n.jsx(vg,{section:d,onSectionChange:h})]})}const ih=8e3;function q2(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 jg(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,S]of b){const w=e.get(g),_=S.muted===void 0||(w?w.muted===S.muted:!1),k=S.hidden===void 0||(w?w.surfaceHidden===S.hidden:!1),v=f-S.at>ih;(_&&k||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[S,w]of f)x-w.at>ih&&(f.delete(S),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:xs(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:xs(b,e).surfaceHidden??!1},[e]),m=c.useCallback((b,f)=>{const x=Jn(b),g=b.sessionId;!x||!g||(i(g,f),t(x,"set_conversation_prefs",{sessionId:g,...f,...ji(b)}).then(S=>{const w=q2(S);w.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",w.reason),r.current.delete(g),a(),s==null||s(`Couldn't update conversation — ${w.reason}`))}).catch(S=>{console.warn("[conversation-prefs] set_conversation_prefs failed",S),r.current.delete(g),a();const w=S instanceof Error?S.message:String(S??"the daemon is unreachable");s==null||s(`Couldn't update conversation — ${w}`)}))},[t,i,a,s]),u=c.useCallback(b=>{m(b,{muted:!l(b)})},[m,l]),h=c.useCallback((b,f)=>{m(b,{hidden:f})},[m]),p=c.useCallback(b=>{m(b,{hidden:!d(b)})},[m,d]);return{isMuted:l,isHidden:d,toggleMute:u,setHidden:h,toggleHidden:p}}function Ca(e){return[...e].sort((t,s)=>{const r=s.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(s.conversation.tabKey)})}function z2(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:Ca(e)}function V2(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:Ca(s),unreadItems:Ca(r),workingItems:z2(o,t),completedItems:Ca(a)}}function Di(e,t){if(!t)return!1;const s=e.filter(r=>r.type==="adhdev-daemon"&&Ng(r)==="Connected");return s.length===0?!0:s.every(r=>r._sessionListAuthoritative===!0)}function Ng(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 G2(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:go(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=xo(r)?"cli":"ide";return{id:`${o}:${r.type}:${r.workspace||""}`,label:((a=r.activeChat)==null?void 0:a.title)||xo(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 Y2(e,t,s=[]){const r=new Map;for(const a of t){const i=Jn(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=Jn(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,m=(d==null?void 0:d.conversation)||null,u=gl(a),h=i.filter(x=>x.unread||x.requiresAction).length,p=i.filter(x=>Bs(x.conversation)).length+l.filter(Bs).length,b=Ng(a),f=[a.platform||"machine",b].filter(Boolean);return{id:a.id,label:yn(a,{fallbackId:a.id}),subtitle:f.join(" · "),unread:h,total:i.length,generatingCount:p,latestConversation:m,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:m?a_(m,ib(m)):"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 Q2(e){return e==="chat"}function na(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 J2({conversations:e,machineEntries:t,items:s,selectedConversation:r,selectedTabKey:o,screen:a,liveSessionInboxState:i,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:b,setSelectedTabKey:f,setScreen:x,setSelectedMachineId:g,setSection:S,setMachineBackTarget:w,resetMachineAction:_}){const k=c.useRef(null),v=c.useCallback(y=>{if(!(y!=null&&y.sessionId))return;const j=xs(y,i),N=Math.max(Date.now(),$s(y),j.lastUpdated||0);na("mark_read:start",{tabKey:y.tabKey,sessionId:y.sessionId,displayPrimary:wt(y),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:$s(y),readAt:N}),l(Jn(y)||y.routeId,"mark_session_seen",{sessionId:y.sessionId,providerSessionId:y.providerSessionId,seenAt:N,completionMarker:j.completionMarker}).then(A=>{na("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:A})}).catch(A=>{na("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,l]);return c.useEffect(()=>{var j;if(!r){Q2(a)&&x("inbox"),f(((j=e[0])==null?void 0:j.tabKey)||null),k.current=null;return}if(a!=="chat"){k.current=null;return}const y=`${r.tabKey}:${r.sessionId||""}`;k.current!==y&&(k.current=y,v(r))},[e,v,a,r,x,f]),c.useEffect(()=>{if(!d)return;const y=e.find(j=>j.tabKey===d);y&&(f(y.tabKey),x("chat"),m==null||m())},[e,m,d,x,f]),c.useEffect(()=>{if(!u)return;const y=t.find(j=>j.id===u);y&&(g(y.id),_(),S("machines"),w("inbox"),x("machine"),h==null||h())},[t,h,u,_,w,x,S,g]),c.useEffect(()=>{p&&(S(p),x("inbox"),b==null||b())},[b,p,x,S]),c.useEffect(()=>{const y=s.filter(j=>j.inboxBucket==="task_complete"||j.unread);y.length!==0&&na("inbox_state",{screen:a,selectedTabKey:o,items:y.map(j=>{const N=xs(j.conversation,i);return{liveState:N,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:wt(j.conversation),serverBucket:N.inboxBucket,computedBucket:j.inboxBucket,serverUnread:N.unread,computedUnread:j.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:$s(j.conversation)}})})},[s,i,a,o]),{markConversationRead:v}}const X2="Cannot update: node update policy unavailable; refresh and try again";async function Z2(e,t,s){var o,a,i,l,d,m;const r=Ud(s);if(!r)return{state:"error",message:X2};try{const u=await e(t,"daemon_upgrade",r);return(o=u==null?void 0:u.result)!=null&&o.alreadyLatest?{state:"done",message:`Already on v${((a=u==null?void 0:u.result)==null?void 0:a.version)||"latest"}.`}:(i=u==null?void 0:u.result)!=null&&i.upgraded||(l=u==null?void 0:u.result)!=null&&l.success?{state:"done",message:`Upgrade to v${((d=u==null?void 0:u.result)==null?void 0:d.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((m=u==null?void 0:u.result)==null?void 0:m.error)||"Upgrade failed"}}catch(u){return{state:"error",message:u instanceof Error?u.message:"Upgrade failed"}}}function eI(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ch(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function tI(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function nI({sendDaemonCommand:e,navigate:t,ides:s,conversations:r}){const{launchCli:o}=mi(),[a,i]=c.useState("idle"),[l,d]=c.useState(""),[m,u]=c.useState(null),h=c.useCallback(()=>{i("idle"),d(""),u(null)},[]),p=c.useCallback(async(_,k,v)=>{var y;try{i("loading"),d(`Launching ${k}…`);const j={ideType:k,enableCdp:!0};(y=v==null?void 0:v.workspacePath)!=null&&y.trim()&&(j.workspace=v.workspacePath.trim()),await e(_,"launch_ide",j),i("done"),d(`${k} launch requested`)}catch(j){i("error"),d(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),b=c.useCallback(async(_,k,v)=>{if(k.trim())try{i("loading"),d(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(_,"workspace_add",{path:k.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 _=>{i("loading"),d("Starting daemon upgrade…");const k=s.find(y=>y.id===_||y.daemonId===_),v=await Z2(e,_,k);i(v.state),d(v.message)},[s,e]),x=c.useCallback(async(_,k,v,y)=>{var A,R,P;const j=Date.now(),N={machineId:_,kind:k,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:j};try{i("loading"),d(`Launching ${v}…`),u(N);const M={cliType:v};(A=y==null?void 0:y.workspacePath)!=null&&A.trim()?M.dir=y.workspacePath.trim():y!=null&&y.workspaceId?M.workspaceId=y.workspaceId:y!=null&&y.useHome&&(M.useHome=!0),y!=null&&y.resumeSessionId&&(M.resumeSessionId=y.resumeSessionId),(R=y==null?void 0:y.args)!=null&&R.trim()&&(M.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(P=y==null?void 0:y.model)!=null&&P.trim()&&(M.initialModel=y.model.trim());const E=await o(_,M),C=(E==null?void 0:E.result)||E,I=(C==null?void 0:C.sessionId)||(C==null?void 0:C.id);if(E!=null&&E.success&&I){u(null),i("done"),d(`${v} launched`),t(yo(I));return}if(E!=null&&E.success){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d((E==null?void 0:E.error)||(C==null?void 0:C.error)||`Could not launch ${k.toUpperCase()} workspace`)}catch(M){if(tI(M)){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d(M instanceof Error?M.message:`Could not launch ${k.toUpperCase()} workspace`)}},[t,e]),g=c.useCallback(async(_,k)=>{try{const v=await e(_,"list_saved_sessions",{providerType:k,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]),S=c.useCallback(async(_,k)=>Vd(e,_,k),[e]);c.useEffect(()=>{if(!m)return;const _=ch(m.workspacePath),k=s.find(y=>{var M,E,C,I;if(!y||y.type==="adhdev-daemon"||eI(y.daemonId||y.id)!==m.machineId||(y.transport==="pty"?"cli":null)!==m.kind||String(y.agentType||y.type||"")!==m.providerType)return!1;const R=String(y.providerSessionId||"");if(m.resumeSessionId&&R)return R===m.resumeSessionId;if(_){const O=ch(y.workspace||y.runtimeWorkspaceLabel);return O?O===_:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((I=(C=(E=(M=y.activeChat)==null?void 0:M.messages)==null?void 0:E.at)==null?void 0:C.call(E,-1))==null?void 0:I.timestamp)||0)>=m.startedAt-5e3});if(!k)return;const v=gg({entrySessionId:k.sessionId,entryInstanceId:k.instanceId,entryRouteId:k.id,conversations:r});v&&(u(null),i("done"),d(`${m.providerType} launched`),t(yo(v)))},[r,s,t,m]),c.useEffect(()=>{if(!m)return;const _=window.setTimeout(()=>{u(k=>!k||k.startedAt!==m.startedAt?k:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(_)},[m]);const w=c.useCallback(async(_,k)=>{var v;if(k.kind==="ide"&&k.providerType){await p(_,k.providerType,{workspacePath:k.workspace||null});return}if(k.kind==="cli"&&k.providerType){const y=((v=k.workspace)==null?void 0:v.trim())||"";await x(_,k.kind,k.providerType,{workspacePath:y||null,useHome:!y,resumeSessionId:k.providerSessionId||null})}},[p,x]);return{machineAction:{state:a,message:l},resetMachineAction:h,handleLaunchDetectedIde:p,handleAddWorkspace:b,handleMachineUpgrade:f,handleLaunchWorkspaceProvider:x,handleListSavedSessions:g,handleBrowseDirectory:S,handleOpenRecent:w}}function sI({conversations:e,selectedConversation:t,machineBackTarget:s,markConversationRead:r,resetMachineAction:o,setSelectedTabKey:a,setScreen:i,setSelectedMachineId:l,setSection:d,setMachineBackTarget:m}){const u=c.useCallback(S=>{a(S.tabKey),i("chat"),r(S)},[r,i,a]),h=c.useCallback(S=>{const w=e.find(_=>_.routeId===S.routeId&&_.streamSource==="native");w&&(a(w.tabKey),i("chat"),r(w))},[e,r,i,a]),p=c.useCallback(()=>{r(t),i("inbox")},[r,t,i]),b=c.useCallback((S,w="inbox")=>{l(S),o(),d("machines"),m(w),i("machine")},[o,m,i,d,l]),f=c.useCallback(S=>{const w=Jn(S);w&&b(w,"chat")},[b]),x=c.useCallback(()=>{o(),i(s)},[s,o,i]),g=c.useCallback(S=>{d(S),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:h,backFromConversation:p,openMachine:b,openConversationMachine:f,backFromMachine:x,changeMachineSection:g}}function Qd(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function rI(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function oI({conversations:e,hiddenConversations:t,ides:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:b,onOpenHistory:f,onOpenRemote:x,onStopCli:g,wsStatus:S,isConnected:w,initialDataLoaded:_=!0,onShowAllHiddenConversations:k,onHideConversation:v,onShowHiddenConversation:y,onOpenMeshGraph:j,onOpenNewSession:N,liveSessionInboxState:A,setCliViewModeOverrides:R}){const[P,M]=c.useState(()=>{var Ce;return((Ce=e[0])==null?void 0:Ce.tabKey)||null}),[E,C]=c.useState(()=>e[0]?"chat":"inbox"),[I,O]=c.useState("chats"),[D,F]=c.useState(null),[z,Z]=c.useState("inbox"),W=c.useRef([]),T=qs(),$="1.0.73",H=c.useMemo(()=>e.find(Ce=>Ce.tabKey===P)||e[0]||null,[e,P]),q=c.useMemo(()=>H?s.find(Ce=>Ce.id===H.routeId):void 0,[s,H]),U=c.useMemo(()=>!H||!ht(H)?null:kr(H),[H]),K=c.useMemo(()=>s.filter(Ce=>Ce.type==="adhdev-daemon").sort(La),[s]),oe=c.useMemo(()=>K.find(Ce=>Ce.id===D)||null,[K,D]),ke=Ci({sendDaemonCommand:o,activeConv:H||void 0,setActionLogs:a,isStandalone:i}),J=nI({sendDaemonCommand:o,navigate:T,ides:s,conversations:e}),ye=pC(e),ae=c.useMemo(()=>e.map(Ce=>{const L=E==="chat"&&(H==null?void 0:H.tabKey)===Ce.tabKey,Y=gi(Ce,A,{hideOpenTaskCompleteUnread:!0,isOpenConversation:L}),ce=$s(Ce),te=ib(Ce),fe=gb(Ce,te);return{conversation:Ce,timestamp:ce,preview:fe,unread:Y.unread,requiresAction:Y.requiresAction,isWorking:Y.isWorking,inboxBucket:Y.inboxBucket}}),[e,A,E,H,ye]),{markConversationRead:re}=J2({conversations:e,machineEntries:K,items:ae,selectedConversation:H,selectedTabKey:P,screen:E,liveSessionInboxState:A,sendDaemonCommand:o,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:b,setSelectedTabKey:M,setScreen:C,setSelectedMachineId:F,setSection:O,setMachineBackTarget:Z,resetMachineAction:J.resetMachineAction}),de=sI({conversations:e,selectedConversation:H,machineBackTarget:z,markConversationRead:re,resetMachineAction:J.resetMachineAction,setSelectedTabKey:M,setScreen:C,setSelectedMachineId:F,setSection:O,setMachineBackTarget:Z}),{isMuted:ne,toggleMute:ie}=jg(A,o),{attentionItems:_e,unreadItems:G,workingItems:B,completedItems:Q}=c.useMemo(()=>V2(ae,W.current),[ae]);c.useEffect(()=>{W.current=B.map(Ce=>Ce.conversation.tabKey)},[B]);const ue=c.useMemo(()=>oe?ae.filter(Ce=>Jn(Ce.conversation)===oe.id):[],[ae,oe]),Re=c.useMemo(()=>G2(oe,s),[s,oe]),Le=!!oe&&Kd(oe,Is(oe,$)),Pe=c.useMemo(()=>(oe==null?void 0:oe.availableProviders)||[],[oe]),Fe=c.useMemo(()=>Pe.filter(Ce=>Qd(Ce,"cli")).map(Ce=>({type:Ce.type,displayName:Ce.displayName||Ce.type,icon:Ce.icon})),[Pe]),X=c.useMemo(()=>Y2(K,ae,t),[ae,K,t]),ve=c.useMemo(()=>Di(s,_),[s,_]),Se=c.useCallback(async Ce=>{oe&&await J.handleOpenRecent(oe.id,Ce)},[J,oe]);return n.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:E==="chat"&&H?n.jsx(D2,{selectedConversation:H,isStandalone:i,selectedIdeEntry:q,actionLogs:r,userName:l,commands:ke,onBack:de.backFromConversation,onOpenNativeConversation:de.openNativeConversation,onOpenMachine:de.openConversationMachine,onOpenHistory:f,onOpenRemote:x,onOpenMeshGraph:j,onStopCli:g,cliViewMode:U,onSetCliViewMode:async Ce=>{await ag({conversation:H,mode:Ce,ides:s,sendDaemonCommand:o,setCliViewModeOverrides:R})}}):E==="machine"&&oe?n.jsx(K2,{selectedMachineEntry:oe,selectedMachineConversations:ue,selectedMachineRecentLaunches:Re,cliProviders:Fe,selectedMachineNeedsUpgrade:Le,appVersion:$,machineAction:J.machineAction,isStandalone:i,section:I,showBottomNav:z==="inbox",onBack:de.backFromMachine,onSectionChange:de.changeMachineSection,onOpenConversation:de.openConversation,onOpenRecent:Se,onOpenMachineDetails:()=>T(`/machines/${oe.id}`),onMachineUpgrade:()=>J.handleMachineUpgrade(oe.id),onBrowseDirectory:Ce=>J.handleBrowseDirectory(oe.id,Ce),onListSavedSessions:Ce=>J.handleListSavedSessions(oe.id,Ce)}):n.jsx($2,{section:I,attentionItems:_e,unreadItems:G,workingItems:B,completedItems:Q,hiddenConversations:t,machineCards:X,getAvatarText:rI,actionLogs:r,sendDaemonCommand:o,onOpenConversation:de.openConversation,onShowAllHidden:k,onHideConversation:v,onShowHiddenConversation:y,onOpenMeshGraph:j,onStopCli:g,onOpenNewSession:N,onOpenMachine:de.openMachine,onOpenSettings:()=>T("/settings"),onSectionChange:O,wsStatus:S,isConnected:w,initialDataLoaded:_,conversationsLoaded:ve,isStandalone:i,isConversationMuted:ne,onToggleMuteConversation:ie})})}function Nc(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function aI({conversations:e,numGroups:t,onMoveTab:s,onReceiveTab:r,onOwnTabDrop:o,onClearPreviewOrder:a}){const i=c.useRef(0),[l,d]=c.useState(!1),[m,u]=c.useState(null),h=c.useCallback(()=>{i.current=0,d(!1),u(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(),!Nc(t,s)){u("merge");return}const S=g.currentTarget.getBoundingClientRect(),w=g.clientX-S.left,_=S.width/3;w<_?u("split-left"):w>_*2?u("split-right"):u("merge")},[t,s]),f=c.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),x=c.useCallback(g=>{i.current=0,d(!1);const S=g.dataTransfer.getData("text/tab-key"),w=S?e.some(k=>k.tabKey===S):!1,_=m;if(u(null),a(),!!S){if(g.preventDefault(),_==="split-left"&&Nc(t,s)){s==null||s(S,"split-left");return}if(_==="split-right"&&Nc(t,s)){s==null||s(S,"split-right");return}if(w){o(S);return}r==null||r(S)}},[e,m,t,s,r,o,a]);return{dragOver:l,dropAction:m,resetDragState:h,handleDragEnter:p,handleDragOver:b,handleDragLeave:f,handleDrop:x}}function iI(e,t){const s=new Set(t.map(a=>a.tabKey)),r=e.filter(a=>s.has(a)),o=t.filter(a=>!e.includes(a.tabKey)).map(a=>a.tabKey);return[...r,...o]}function cI({conversations:e,initialActiveTabId:t,initialTabOrder:s,onActiveTabChange:r,onTabOrderChange:o}){const[a,i]=c.useState(t??null),[l,d]=c.useState(s??[]),[m,u]=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(j=>{const N=iI(j,e);return N.length===j.length&&N.every((A,R)=>A===j[R])?j:N})},[e]);const x=c.useMemo(()=>{const j=m??l;if(j.length===0)return e;const N=new Map(j.map((A,R)=>[A,R]));return[...e].sort((A,R)=>{const P=N.get(A.tabKey)??999,M=N.get(R.tabKey)??999;return P-M})},[e,m,l]);c.useEffect(()=>{var N,A;if(x.length===0){a!==null&&(i(null),(N=b.current)==null||N.call(b,null));return}if(a&&x.some(R=>R.tabKey===a))return;const j=x[0].tabKey;j!==a&&(i(j),(A=b.current)==null||A.call(b,j))},[x,a]);const g=c.useMemo(()=>x.find(j=>j.tabKey===a),[x,a]),S=c.useCallback(j=>{var N;i(j),(N=b.current)==null||N.call(b,j)},[]),w=c.useCallback((j,N,A)=>{d(R=>{var C;const P=R.filter(I=>I!==j),M=P.indexOf(N);if(M<0)return R;const E=A==="left"?M:M+1;return P.splice(E,0,j),(C=f.current)==null||C.call(f,P),P}),u(null)},[]),_=c.useCallback((j,N,A)=>{const P=(l.length>0?l:e.map(C=>C.tabKey)).filter(C=>C!==j),M=P.indexOf(N);if(M<0)return;const E=A==="left"?M:M+1;P.splice(E,0,j),h.current=P,u(P)},[l,e]),k=c.useCallback(()=>{var N;const j=h.current;j&&(d(j),(N=f.current)==null||N.call(f,j))},[]),v=c.useCallback(()=>{h.current=null,u(null)},[]),y=c.useCallback(j=>{d(N=>{var R;const A=N.filter(P=>P!==j);return A.push(j),(R=f.current)==null||R.call(f,A),A})},[]);return{activeTabId:a,activeConv:g,sortedConversations:x,previewOrderRef:h,draggingTabRef:p,selectTab:S,handleTabReorder:w,updatePreviewOrder:_,commitPreviewOrder:k,clearPreviewOrder:v,moveTabToEnd:y,setDraggingTabKey:j=>{p.current=j}}}function lI({dropAction:e,canSplit:t}){const{t:s}=pe("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 Jd({conversationsCount:e,isSplitMode:t,isStandalone:s,hasRegisteredMachines:r=!1,suppressGuide:o=!1,onOpenNewSession:a,isLoading:i=!1}){const{t:l}=pe("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(Zt,{}),n.jsx("p",{className:"text-sm",children:l("paneGroup.loadingSessions")})]});const d=!s&&!r,m=r&&!!a,u=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:u}),n.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:h}),m&&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(po,{size:14}),n.jsx("span",{children:l("paneGroup.newSession")})]})}),d&&n.jsx(yg,{}),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 Cg="adhdev-tab-shortcuts";function _g(){try{return JSON.parse(localStorage.getItem(Cg)||"{}")}catch{return{}}}function Ag({enabled:e=!0,sortedTabKeys:t,onFocus:s,onSelectTab:r}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[a,i]=c.useState(()=>_g()),[l,d]=c.useState(null),m=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]),u=c.useCallback(h=>{i(h);try{localStorage.setItem(Cg,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=m(p);if(!b)return;const f={...a};for(const[x,g]of Object.entries(f))g===b&&delete f[x];f[l]=b,u(f),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,a,u,m]),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)&&m(p)===f){p.preventDefault(),s(),r(b);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,a,t,s,r,m]),{isMac:o,tabShortcuts:a,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Cc=e=>{e.preventDefault()},dI=c.memo(function({conv:t,isActive:s,isDraggedTab:r,isTaskCompleteUnread:o,shortcut:a,conversationKeys:i,draggingTabRef:l,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:h,onReorderTab:p,onCommitPreviewOrder:b,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:g,onReceiveTab:S,onOpenContextMenu:w,longPressTimer:_,isGroupActive:k}){const v=ws(t),y=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",j=v.isReconnecting,N=Rd(t),A=c.useCallback(F=>{l.current=t.tabKey,g(t.tabKey),F.dataTransfer.setData("text/tab-key",t.tabKey),F.dataTransfer.effectAllowed="move"},[t.tabKey,l,g]),R=c.useCallback(()=>{l.current=null,g(null),b(),f(),x()},[l,g,b,f,x]),P=c.useCallback(F=>{const z=l.current;if(!(!z||z===t.tabKey)&&F.dataTransfer.types.includes("text/tab-key")){F.preventDefault(),F.stopPropagation();const Z=F.currentTarget.getBoundingClientRect(),W=F.clientX<Z.left+Z.width/2?"left":"right";h(z,t.tabKey,W)}},[t.tabKey,l,h]),M=c.useCallback(F=>{F.preventDefault(),F.stopPropagation();const z=F.dataTransfer.getData("text/tab-key");if(z&&z!==t.tabKey){const Z=F.currentTarget.getBoundingClientRect(),W=F.clientX<Z.left+Z.width/2?"left":"right";i.includes(z)?p(z,t.tabKey,W):S&&S(z)}f()},[t.tabKey,i,p,S,f]),E=c.useCallback(F=>{F.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),C=c.useCallback(F=>{F.preventDefault(),w(F.clientX,F.clientY,t.tabKey)},[t.tabKey,w]),I=c.useCallback(F=>{const z=F.touches[0];_.current=setTimeout(()=>{w(z.clientX,z.clientY,t.tabKey)},600)},[t.tabKey,_,w]),O=c.useCallback(()=>{_.current&&clearTimeout(_.current)},[_]),D=["adhdev-dockview-tab",y,s&&"is-active",k&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return n.jsxs("div",{"data-tabkey":t.tabKey,className:D,draggable:!0,onDragStart:A,onDragEnd:R,onDragOver:P,onDrop:M,onClick:E,onContextMenu:C,onTouchStart:I,onTouchEnd:O,onTouchMove:O,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(Zt,{size:12,thickness:2,color:"success"}):v.isWaiting?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?n.jsx(Zt,{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(vs,{conversation:t,size:12}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("span",{className:"adhdev-dockview-tab-primary",title:N?`${wt(t)} · ${N}`:wt(t),children:wt(t)}),n.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[j?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Ds(t)}):v.isConnecting?n.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Ds(t),n.jsx("span",{className:"connecting-dots"})]}):n.jsx("span",{className:"truncate",children:Ds(t)}),n.jsx(Nd,{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 uI({conversations:e,activeTabId:t,groupIndex:s,unreadTabKeys:r,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:b,onReceiveTab:f,onHideTab:x,isGroupActive:g,allowTabShortcuts:S=!0}){const{t:w}=pe("common"),[_,k]=c.useState(null),v=c.useRef(null),y=c.useRef(null),j=c.useMemo(()=>e.map(C=>C.tabKey),[e]);Co("PaneGroupTabBar",{groupIndex:s,activeTabId:t,tabCount:e.length,ctxMenuTab:(_==null?void 0:_.tabKey)||null});const{isMac:N,tabShortcuts:A,shortcutListening:R,setShortcutListening:P,saveShortcuts:M}=Ag({enabled:S,sortedTabKeys:e.map(C=>C.tabKey),onFocus:a,onSelectTab:i});c.useEffect(()=>{if(!_)return;const C=I=>{const O=document.querySelector("[data-pane-context-menu]");O&&O.contains(I.target)||k(null)};return window.addEventListener("mousedown",C,!0),()=>window.removeEventListener("mousedown",C,!0)},[_]),c.useEffect(()=>{const C=y.current;if(!C)return;const I=O=>{Math.abs(O.deltaY)<=Math.abs(O.deltaX)||(O.preventDefault(),C.scrollLeft+=O.deltaY)};return C.addEventListener("wheel",I,{passive:!1}),()=>C.removeEventListener("wheel",I)},[]);const E=c.useCallback((C,I,O)=>{k({x:C,y:I,tabKey:O})},[]);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(C=>n.jsx(dI,{conv:C,isActive:t===C.tabKey,isDraggedTab:o.current===C.tabKey,isTaskCompleteUnread:r.has(C.tabKey),shortcut:S?A[C.tabKey]:void 0,conversationKeys:j,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:b,onReceiveTab:f,onOpenContextMenu:E,longPressTimer:v,isGroupActive:g},C.tabKey)),e.length===0&&n.jsx("div",{className:"p-2 text-xs opacity-40",children:w("paneGroup.noTabsInGroup")})]})}),_&&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:_.x,top:_.y},children:[S&&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:Cc,onClick:C=>{C.stopPropagation(),P(_.tabKey),k(null)},children:["⌨ ",A[_.tabKey]?w("paneGroup.changeShortcut",{shortcut:A[_.tabKey]}):w("paneGroup.shortcutSetTitle")]}),A[_.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:Cc,onClick:()=>{const C={...A};delete C[_.tabKey],M(C),k(null)},children:["✕ ",w("paneGroup.removeShortcut")]})]}),x&&n.jsxs(n.Fragment,{children:[S&&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:Cc,onClick:()=>{x(_.tabKey),k(null)},children:n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(li,{size:12}),w("paneGroup.hideFromDashboard")]})})]})]}),S&&R&&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:C=>C.stopPropagation(),children:[n.jsxs("div",{className:"text-sm font-bold text-text-primary mb-2",children:["⌨ ",w("paneGroup.shortcutSetTitle")]}),n.jsx("div",{className:"text-xs text-text-secondary mb-4",children:w("paneGroup.shortcutPressCombo",{example1:N?"⌘+1":"Ctrl+1",example2:N?"⌥+A":"Alt+A"})}),n.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:w("paneGroup.shortcutListening")}),n.jsx("div",{className:"text-3xs text-text-muted mt-3",children:w("paneGroup.pressEscToCancel")})]})})})]})}function mI({conversations:e,ides:t,clearedTabs:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:l,initialDataLoaded:d=!0,userName:m,groupIndex:u,onFocus:h,isSplitMode:p,numGroups:b,onMoveTab:f,onReceiveTab:x,style:g,onActiveTabChange:S,initialActiveTabId:w,initialTabOrder:_,onTabOrderChange:k,onHideTab:v,isFocused:y,allowTabShortcuts:j=!0,onOpenNewSession:N,liveSessionInboxState:A}){const{sendCommand:R}=xt(),P=c.useRef(null),{activeTabId:M,activeConv:E,sortedConversations:C,draggingTabRef:I,selectTab:O,handleTabReorder:D,updatePreviewOrder:F,commitPreviewOrder:z,clearPreviewOrder:Z,moveTabToEnd:W,setDraggingTabKey:T}=cI({conversations:e,initialActiveTabId:w,initialTabOrder:_,onActiveTabChange:S,onTabOrderChange:k}),$=Ci({sendDaemonCommand:o,activeConv:E,setActionLogs:a,isStandalone:i}),{dragOver:H,dropAction:q,resetDragState:U,handleDragEnter:K,handleDragOver:oe,handleDragLeave:ke,handleDrop:J}=aI({conversations:e,numGroups:b,onMoveTab:f,onReceiveTab:x,onOwnTabDrop:W,onClearPreviewOrder:Z}),ye=E&&kr(E)==="terminal",ae=c.useMemo(()=>E?t.find(ie=>ie.id===E.routeId):void 0,[t,E]),re=c.useMemo(()=>E?r.filter(ie=>ie.routeId===E.tabKey):[],[r,E]),de=c.useMemo(()=>new Set(C.filter(ie=>R0(ie,A,{isOpenConversation:ie.tabKey===M})).map(ie=>ie.tabKey)),[M,A,C]);Co("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:M,dragOver:H});const ne=c.useCallback(ie=>{ie.streamSource==="agent-stream"&&ie.agentType&&R(ie.routeId,qf(),{agentType:ie.agentType,...ie.sessionId&&{targetSessionId:ie.sessionId}}).catch(()=>{})},[R]);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(uI,{conversations:C,activeTabId:M,groupIndex:u,numGroups:b,unreadTabKeys:de,draggingTabRef:I,onFocus:h,onSelectTab:O,onConversationActivated:ne,onPreviewReorder:F,onReorderTab:D,onCommitPreviewOrder:z,onClearPreviewOrder:Z,onDragStateReset:U,onDragTabKeyChange:T,onMoveTab:f,onReceiveTab:x,onHideTab:v,isGroupActive:y??!1,allowTabShortcuts:j}),n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:K,onDragOver:oe,onDragLeave:ke,onDrop:J,children:[H&&n.jsx(lI,{dropAction:q,canSplit:!!(b<4&&f)}),E?n.jsx(Gd,{activeConv:E,clearToken:s[E.tabKey]||0,isCliTerminal:!!ye,ideEntry:ae,terminalRef:P,commands:$,actionLogs:re,userName:m,isInputActive:!p||!!y}):n.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:n.jsx(Jd,{conversationsCount:e.length,isSplitMode:p,isStandalone:i,hasRegisteredMachines:l,onOpenNewSession:N,isLoading:!Di(t,d)})})]})]})}function hI({containerRef:e,isSplitMode:t,numGroups:s,groupSizes:r,groupedConvs:o,clearedTabs:a,ides:i,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,initialDataLoaded:p,userName:b,focusedGroup:f,focusGroup:x,moveTabToGroup:g,splitTabRelative:S,closeGroup:w,handleResizeStart:_,groupActiveTabIds:k,setGroupActiveTab:v,groupTabOrders:y,setGroupTabOrder:j,toggleHiddenTab:N,onOpenNewSession:A,allowTabShortcuts:R=!0,liveSessionInboxState:P}){const{t:M}=pe("common");return n.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:o.map((E,C)=>{const I=t&&r.length===s?`${r[C]}%`:void 0;return n.jsxs(vt.Fragment,{children:[t&&C>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:O=>_(C-1,O),onDoubleClick:()=>w(C),title:M("paneGroup.resizeHandleHint"),children:n.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),n.jsx(mI,{style:t?{flexBasis:I??`${100/s}%`,flexGrow:I?0:1,flexShrink:I?0:1}:void 0,conversations:E,clearedTabs:a,ides:i,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,initialDataLoaded:p,userName:b,groupIndex:C,isFocused:t&&f===C,onFocus:()=>x(C),isSplitMode:t,numGroups:s,onMoveTab:(O,D)=>{D==="left"&&C>0?g(O,C-1):D==="right"&&C<s-1?g(O,C+1):D==="split-left"&&s<4?S(O,C,"left"):D==="split-right"&&s<4&&S(O,C,"right")},onReceiveTab:O=>g(O,C),onActiveTabChange:O=>v(C,O),initialActiveTabId:k[C],initialTabOrder:y[C],onTabOrderChange:O=>j(C,O),onHideTab:N,onOpenNewSession:A,allowTabShortcuts:R,liveSessionInboxState:P})]},C)})})}const Tg="adhdev-dashboard-action-shortcuts",pI=1200,fI=[["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 bI(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function mt(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 Ig(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:mt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:mt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:mt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:mt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:mt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:mt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:mt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:mt("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:mt("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:mt("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:mt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:mt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:mt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:mt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:mt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:mt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:mt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:mt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:mt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:mt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:mt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:mt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:mt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:mt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:mt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:mt("toggleCliView",e)}]}function Xd(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Xa(e){const t=Object.fromEntries(Ig(e).map(s=>[s.id,s.defaultShortcut]));try{const s=JSON.parse(localStorage.getItem(Tg)||"{}"),r={...t,...s};for(const[o,a]of fI)r[o]===a&&(r[o]=t[o]);return r}catch{return t}}function Mg(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function gI({enabled:e=!0,onTrigger:t}){const s=bI(),[r,o]=c.useState(()=>Xa(s)),[a,i]=c.useState(null),[l,d]=c.useState([]),m=c.useRef({parts:[],timer:null}),u=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(Mg(x.key)),g.join("+"))},[s]),h=c.useCallback(x=>{o(x);try{localStorage.setItem(Tg,JSON.stringify(x))}catch{}},[]);c.useEffect(()=>{const x=Xa(s),g=Object.entries(r),S=Object.entries(x);g.length===S.length&&g.every(([w,_])=>x[w]===_)||h(x)},[r,s,h]);const p=c.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),b=c.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},pI))},[]);c.useEffect(()=>{if(!a)return;const x=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){i(null),d([]);return}const S=u(g);if(!S)return;const _=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(S);if(l.length===0&&_){d([S]);return}const v=[...l,S].slice(0,2).join(" "),y={...r};for(const[j,N]of Object.entries(y))N===v&&delete y[j];y[a]=v,h(y),i(null),d([])};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[r,u,h,a,l]),c.useEffect(()=>{if(!e||a)return;const x=g=>{if(g.defaultPrevented)return;const S=u(g);if(!S)return;const w=g.metaKey||g.ctrlKey||g.altKey;if(Xd(g.target))return;const _=m.current.parts,k=w?[S]:[..._.slice(-1),S].slice(-2),v=k.join(" "),y=k[k.length-1],j=Object.entries(r).filter(([,M])=>!!M),N=j.find(([,M])=>M===v);if(N){g.preventDefault(),p(),t(N[0]);return}if(j.some(([,M])=>M.startsWith(`${v} `))){g.preventDefault(),m.current.parts=k,b();return}const R=j.find(([,M])=>M===y);if(R){g.preventDefault(),p(),t(R[0]);return}if(j.some(([,M])=>M.startsWith(`${y} `))){g.preventDefault(),m.current.parts=[y],b();return}p()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[r,b,e,u,t,p,a]),c.useEffect(()=>()=>p(),[p]);const f=c.useMemo(()=>Ig(s),[s]);return{isMac:s,actionDefinitions:f,actionShortcuts:r,shortcutListening:a,shortcutListeningDraft:l,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:h}}function xI({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 Rg(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function lh({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:s,ides:r}){return!e||s>0?!1:t?!Rg(r):!0}function yI({previousVisibleConversationCount:e,visibleConversationCount:t,ides:s}){return t>0||e<=0?!1:Rg(s)}const Pg=2e4;function vI(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+Pg}:null}function wI(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 Eg=1e3,SI=4;function dh(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function uh(e,t,s){return Math.abs(t.clientX-e.clientX)>s||Math.abs(t.clientY-e.clientY)>s}function kI({detachDelayMs:e=Eg,stillnessThresholdPx:t=SI,onDetach:s,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:o=globalThis.clearTimeout.bind(globalThis)}){let a=null,i=null,l=null,d=null,m=null,u=!1;const h=()=>{m!=null&&(o(m),m=null)},p=()=>{h(),l=null},b=()=>{h(),a=null,i=null,l=null,d=null,u=!1},f=()=>{!a||!l||!d||u||m!=null||(m=r(()=>{m=null,!(!a||!l||!d||u)&&dh(d,i)&&(uh(l,d,t)||(u=!0,s({panelId:a,clientX:d.clientX,clientY:d.clientY})))},e))},x=S=>{if(!(!a||u)){if(!dh(S,i)){d={clientX:S.clientX,clientY:S.clientY},p();return}(!l||uh(l,S,t))&&(h(),l={clientX:S.clientX,clientY:S.clientY}),d={clientX:S.clientX,clientY:S.clientY},f()}},g=S=>{!a||u||(S&&(d={clientX:S.clientX,clientY:S.clientY}),p())};return{startDrag:S=>{h(),a=S.panelId,i=S.selfPanelBounds??null,l=null,d={clientX:S.clientX,clientY:S.clientY},u=!1},markSelfPanel:x,markNonSelfPanel:g,markNoDropTarget:g,markDockTarget:g,endDrag:b,isDragging:()=>a!=null,hasDetached:()=>u,dispose:b}}function jI(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function NI(e,t,s){const r=u=>({clientX:u.clientX,clientY:u.clientY}),o=u=>{const h=u==null?void 0:u.getBoundingClientRect();return h?{left:h.left,right:h.right,top:h.top,bottom:h.bottom}:null},a=u=>{var p;const h=(p=t())==null?void 0:p.getBoundingClientRect();return h?u.clientX<h.left||u.clientX>h.right||u.clientY<h.top||u.clientY>h.bottom:!1},i=kI({detachDelayMs:Eg,onDetach:({panelId:u,clientX:h,clientY:p})=>{var w,_;const b=e.getPanel(u);if(!b)return;try{if(b.group.model.location.type!=="grid")return}catch{return}const f=(w=t())==null?void 0:w.getBoundingClientRect(),x=(_=b.group.element)==null?void 0:_.getBoundingClientRect(),g=Math.round(Math.min(Math.max((x==null?void 0:x.width)??600,360),720)),S=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:S}),b.api.setActive(),s()}}),l=[e.onWillDragPanel(u=>{if(!(u.nativeEvent.defaultPrevented||u.nativeEvent.shiftKey)){try{if(u.panel.group.model.location.type!=="grid")return}catch{return}i.startDrag({panelId:u.panel.id,selfPanelBounds:o(u.panel.group.element),...r(u.nativeEvent)})}}),e.onWillShowOverlay(u=>{if(i.hasDetached()){u.preventDefault();return}i.markDockTarget(r(u.nativeEvent))}),e.onWillDrop(u=>{if(i.hasDetached()){u.preventDefault(),i.endDrag();return}i.markDockTarget(r(u.nativeEvent))}),e.onDidDrop(()=>i.endDrag()),e.onUnhandledDragOverEvent(u=>{i.isDragging()&&i.markSelfPanel(r(u.nativeEvent))})],d=u=>{if(!i.isDragging())return;const h=r(u);a(h)&&i.markNonSelfPanel(h)},m=()=>i.endDrag();return window.addEventListener("dragover",d,!0),window.addEventListener("drop",m,!0),window.addEventListener("dragend",m,!0),()=>{i.dispose();for(const u of l)u.dispose();window.removeEventListener("dragover",d,!0),window.removeEventListener("drop",m,!0),window.removeEventListener("dragend",m,!0)}}function _a(e){return wt(e)||e.tabKey}function CI(e){return`remote:${e}`}function bn(e){return e.startsWith("remote:")}function mh(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function _c(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 Zd(e,t){e.classList.remove(Yc.className,Qc.className),e.classList.add(t==="light"?Yc.className:Qc.className)}function hh(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 _I(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)),m=b=>{const f=b.element.getBoundingClientRect(),x=f.left+f.width/2,g=f.top+f.height/2;let S=0,w=0,_=0,k=!1;if(t==="left"?(k=x<i,S=Math.max(0,a.left-f.right),w=Math.abs(g-l),_=d(a.top,a.bottom,f.top,f.bottom)):t==="right"?(k=x>i,S=Math.max(0,f.left-a.right),w=Math.abs(g-l),_=d(a.top,a.bottom,f.top,f.bottom)):t==="above"?(k=g<l,S=Math.max(0,a.top-f.bottom),w=Math.abs(x-i),_=d(a.left,a.right,f.left,f.right)):(k=g>l,S=Math.max(0,f.top-a.bottom),w=Math.abs(x-i),_=d(a.left,a.right,f.left,f.right)),!k)return Number.POSITIVE_INFINITY;const v=_>0?0:120;return S*3+w+v};let u=null,h=Number.POSITIVE_INFINITY;for(const b of r){if(b.id===o.id)continue;const f=m(b);Number.isFinite(f)&&(f>=h||(h=f,u=b))}return u||void 0}function AI(e,t,s){var i;const r=[t];let o;for(const l of r){let d;for(const m of l){const u=e.addPanel({id:m.tabKey,component:"conversation",title:_a(m),params:{kind:"conversation",tabKey:m.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});d||(d=u.id)}o=d??o}return s??((i=t[0])==null?void 0:i.tabKey)??null}function Ac(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])bn(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!==_a(a)&&i.api.setTitle(_a(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:_a(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 ph(e,t,s){var d,m;const r=s?CI(s):null;for(const u of[...e.panels])bn(u.id)&&(!r||u.id!==r)&&e.removePanel(u);if(!s||!r)return;const o=_n(t,s);if(!o&&e.totalPanels===0)return;const a=e.getPanel(r),i=vb(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)??((m=e.panels.find(u=>!bn(u.id)))==null?void 0:m.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:s},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function TI(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 Dg({doId:e,targetSessionId:t,connState:s,viewMode:r}){var m;const[o,a]=c.useState(null),{ides:i}=ki(),l=((m=i.find(u=>u.id===e&&u.type==="adhdev-daemon"))==null?void 0:m.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 u=e?Dt.get(e):null;if(!(!u||s!=="connected"))return r!=="chat"&&t?u.startScreenshots(t):u.stopScreenshots(t),()=>{u.stopScreenshots(t)}},[r,s,t,e]);const d=c.useCallback(async(u,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(u,h,t)},[e,s,t]);return{connScreenshot:o,screenshotUsage:l,handleRemoteAction:d}}const Lg=c.createContext(null);function Li(){const e=c.useContext(Lg);if(!e)throw new Error("DashboardDockviewContext missing");return e}function II(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 MI({params:e}){var m;const t=Li(),{t:s}=pe("common"),r=c.useMemo(()=>_n([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),o=c.useMemo(()=>t.ides.find(u=>u.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((m=r==null?void 0:r.routeId)==null?void 0:m.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:l,handleRemoteAction:d}=Dg({doId:a,targetSessionId:r?Wf(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(Zp,{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 RI(){const e=Li();return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:n.jsx(Jd,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!Di(e.ides,e.initialDataLoaded)})})}function PI(e){var k,v;II(e);const t=Li(),{t:s}=pe("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=>EC(y),[]),l=c.useCallback(()=>PC(a),[a]),d=c.useSyncExternalStore(i,l,l),m=Rd(o);if(e.params.kind==="remote"){const y=_n([...t.conversationsByTabKey.values()],e.params.routeId),j=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,N=e.api.isGroupActive;return n.jsxs("div",{className:`adhdev-dockview-tab${j?" is-active":""}${N?" 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 u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)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=gi(u,t.liveSessionInboxState,{isOpenConversation:h}),f=b.isReconnecting,x=b.isConnecting,g=b.isGenerating||d,S=b.isWaiting,w=b.unread,_=t.tabShortcuts[u.tabKey];return n.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${p?" is-group-active":""}${f?" is-reconnecting":""}`,title:m?`${wt(u)} · ${m}`:wt(u),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:y=>{var j;y.preventDefault(),r(y),t.openTabContextMenu({x:y.clientX,y:y.clientY,tabKey:u.tabKey,sourceDocument:((j=y.target)==null?void 0:j.ownerDocument)??document})},children:[w&&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(Zt,{size:12,thickness:2,color:"success"}):S?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(Zt,{size:12,thickness:2}):u.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(vs,{conversation:u,size:12}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("div",{className:"adhdev-dockview-tab-primary",children:wt(u)}),n.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Ds(u)}):x?n.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Ds(u)}):n.jsx("span",{children:Ds(u)})})]}),_&&n.jsx("span",{className:"text-4xs opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:_,children:_})]})}function EI(e,t){const{encodeShortcut:s,isMac:r,isShortcutListening:o,isVisibleTab:a,selectTabByShortcut:i,triggerAction:l}=t;let d=[],m=null;const u=()=>{m!=null&&e.clearTimeout(m),m=null,d=[]},h=()=>{m!=null&&e.clearTimeout(m),m=e.setTimeout(()=>{m=null,d=[]},1200)},p=f=>{if(!f.ctrlKey&&!f.metaKey&&!f.altKey)return;const x=s(f);if(!x)return;const g=_g();for(const[S,w]of Object.entries(g))if(a(S)&&w===x){f.preventDefault(),i(S);return}},b=f=>{if(f.defaultPrevented||o())return;const x=s(f);if(!x)return;const g=f.metaKey||f.ctrlKey||f.altKey;if(Xd(f.target))return;const S=Xa(r),w=Object.entries(S).filter(([R,P])=>!!P&&(R==="splitActiveTabRight"||R==="splitActiveTabDown"||R==="floatActiveTab"||R==="popoutActiveTab"||R==="dockActiveTab"||R==="focusLeftPane"||R==="focusRightPane"||R==="focusUpPane"||R==="focusDownPane"||R==="moveActiveTabToLeftPane"||R==="moveActiveTabToRightPane"||R==="moveActiveTabToUpPane"||R==="moveActiveTabToDownPane"||R==="selectPreviousGroupTab"||R==="selectNextGroupTab"||R==="setActiveTabShortcut"||R==="hideCurrentTab")),_=g?[x]:[...d.slice(-1),x].slice(-2),k=_.join(" "),v=_[_.length-1],y=w.find(([,R])=>R===k);if(y){f.preventDefault(),u(),l(y[0]);return}if(w.some(([,R])=>R.startsWith(`${k} `))){f.preventDefault(),d=_,h();return}const N=w.find(([,R])=>R===v);if(N){f.preventDefault(),u(),l(N[0]);return}if(w.some(([,R])=>R.startsWith(`${v} `))){f.preventDefault(),d=[v],h();return}u()};return e.addEventListener("keydown",p),e.addEventListener("keydown",b),()=>{u(),e.removeEventListener("keydown",p),e.removeEventListener("keydown",b)}}function DI(e){e.preventDefault()}function LI(e){switch(e){case"dockInWindow":case"dockBackToGrid":return n.jsx(uw,{size:13,className:"shrink-0 opacity-70"});case"moveBackToMain":return n.jsx(lw,{size:13,className:"shrink-0 opacity-70"});case"floatAsPanel":return n.jsx(dw,{size:13,className:"shrink-0 opacity-70"});case"openInNewWindow":return n.jsx(cw,{size:13,className:"shrink-0 opacity-70"});case"removeShortcut":return n.jsx(Pt,{size:13,className:"shrink-0 opacity-70"});case"hideTab":return n.jsx(li,{size:13,className:"shrink-0 opacity-70"});default:return n.jsx(Dp,{size:13,className:"shrink-0 opacity-70"})}}function OI({x:e,y:t,sourceDocument:s,items:r,onSelect:o}){return Wn.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:DI,onClick:i=>o(a.id,i),children:[LI(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 $I(e,t){const s=document,r=e.document;for(const d of s.querySelectorAll('link[rel="stylesheet"]')){const m=r.createElement("link");m.rel="stylesheet",m.href=d.href,d.crossOrigin&&(m.crossOrigin=d.crossOrigin),r.head.appendChild(m)}for(const d of s.querySelectorAll("style")){const m=r.createElement("style");m.textContent=d.textContent,r.head.appendChild(m)}const o=[];for(const d of s.styleSheets)try{for(const m of d.cssRules)m instanceof CSSStyleRule&&(m.selectorText===":root"||m.selectorText==="html")&&o.push(m.cssText)}catch{}if(o.length>0){const d=r.createElement("style");d.textContent=o.join(`
63
63
  `),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"),Zd(l,t))}function FI(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"),Zd(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 HI(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,m=i.title||"ADHDev",u="Popout workspace";const h=a.activePanel;if(h)if(d=h.id,bn(h.id)){const g=((o=h.params)==null?void 0:o.routeId)||h.id.slice(7),S=_n([...t.values()],g);m=vb(S),u=S!=null&&S.machineName?`Remote view · ${S.machineName}`:"Remote view"}else{const g=t.get(h.id);m=g?wt(g):h.title||h.id,u=g?Ds(g):"Dockview panel"}i.title=`${m} — 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=`
64
64
  <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
65
65
  <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
@@ -91,7 +91,7 @@ ${JSON.stringify(t,null,2)}
91
91
  `)),o.join(`
92
92
 
93
93
  `)}function HR(e,t){return t==="issues"?e.filter(s=>s.level==="warn"||s.level==="error"):t==="info"?e.filter(s=>s.level!=="debug"):e}function BR(e,t){return t==="issues"?e.filter(s=>s.level==="warn"||s.level==="error"):t==="info"?e.filter(s=>s.level!=="debug"):e}function WR({daemonLogs:e,daemonRawText:t,daemonLogKind:s,debugTrace:r,webEvents:o,traceCategory:a,quickFilter:i,searchQuery:l,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h}){const p=xR(r,a),b=wR(e,l),f=jR(t,l),x=NR(p,l),g=CR(o,l),S=HR(b,i),w=i==="all"?f:[],_=BR(x,i),k=i==="issues"?[]:g,v=_R({daemonLogs:b,daemonRawLines:f,trace:x,webEvents:g}),y=DR({daemonLogs:S,daemonRawLines:w,trace:_,webEvents:k}),j=OR(y),N=IR({daemonLoading:d,traceLoading:m,daemonFetchError:u,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:S,visibleDaemonRawLines:w,visibleTraceEntries:_,visibleWebEvents:k,quickFilterCounts:v,diagnosticEvents:y,diagnosticsSummary:j,sourceStates:N}}function UR(e,t){return e?pi(e,{seconds:!0}):t("machine.logsTabSections.notYetLoaded")}function Vg(e,t){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?t("machine.logsTabSections.rawFile"):pi(e,{seconds:!0})}function Ul(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 Dc(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 nu(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 KR({event:e}){const{t}=pe("common");return n.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ul(e.severity)}`,children:[n.jsxs("div",{className:"flex gap-2 text-3xs text-text-muted flex-wrap",children:[n.jsx("span",{children:Vg(e.ts,t)}),n.jsx("span",{children:e.severity.toUpperCase()}),n.jsx("span",{children:nu(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 qR({quickFilter:e,quickFilterCounts:t,searchQuery:s,autoRefresh:r,onQuickFilterChange:o,onSearchQueryChange:a,onCopyDiagnostics:i,onCopyVisible:l,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){const{t:h}=pe("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:m,className:"machine-btn",children:h("machine.logsTabSections.refresh")}),n.jsx("button",{onClick:u,className:"machine-btn",children:h("machine.logsTabSections.clear")})]})]})}function zR({logLevel:e,traceCategory:t,onLogLevelChange:s,onTraceCategoryChange:r}){const{t:o}=pe("common");return n.jsx(mn,{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:bR.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 VR({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:s,searchQuery:r,lastUpdatedAt:o,autoRefresh:a,daemonFetchError:i,traceFetchError:l}){var h,p;const{t:d}=pe("common"),m=((h=e.latestIssue)==null?void 0:h.severity)==="error"?"danger":((p=e.latestIssue)==null?void 0:p.severity)==="warn"?"warning":"good",u=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 ${Dc(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 ${Dc(m)}`,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:[nu(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:Vg(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 ${Dc(u)}`,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:UR(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 GR({patterns:e}){const{t}=pe("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()," · ",nu(s.source,t)]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1 line-clamp-2",children:s.message})]},s.key))})]})}function YR({streams:e,sectionsOpen:t,setSectionsOpen:s,diagnosticEvents:r,visibleDaemonLogs:o,visibleDaemonRawLines:a,visibleTraceEntries:i,visibleWebEvents:l,quickFilter:d,searchQuery:m}){const{t:u}=pe("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:u("machine.logsTabSections.unifiedTimeline")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:u("machine.logsTabSections.visibleDiagnosticEvents",{count:r.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.timeline?u("machine.logsTabSections.hide"):u("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:u("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:u("machine.logsTabSections.daemonLogsError",{error:e.daemonFetchError})}),e.traceFetchError&&n.jsx("div",{children:u("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:u("machine.logsTabSections.noDiagnosticsMatch")}),r.map(h=>n.jsx(KR,{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:u("machine.logsTabSections.rawSourceDaemonLogs")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:e.daemonLogKind==="text"?u("machine.logsTabSections.visibleRawLinesFallback",{count:a.length}):u("machine.logsTabSections.visibleStructuredLines",{count:o.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.daemon?u("machine.logsTabSections.hide"):u("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:u("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:u("machine.logsTabSections.noDaemonLogsYet")}),e.daemonLogKind==="text"&&a.length===0&&e.daemonRawText&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:u(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:u("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 ${Ul(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:[u("machine.logsTabSections.rawSourceDaemonTrace"),e.traceCategory==="session_host"?` · ${u("machine.logsTabSections.sessionHostOnly")}`:""]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:u("machine.logsTabSections.visibleTraceEvents",{count:i.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.trace?u("machine.logsTabSections.hide"):u("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:u("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:m.trim()?u("machine.logsTabSections.noTraceEntriesMatchSearch"):e.traceCategory==="session_host"?u("machine.logsTabSections.noSessionHostTraceYet"):u("machine.logsTabSections.noTraceEntriesYet")}),i.map(h=>n.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ul(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:br(h.payload,360)||u("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:u("machine.logsTabSections.rawSourceBrowserEvents")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:u("machine.logsTabSections.visibleBrowserEvents",{count:l.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.web?u("machine.logsTabSections.hide"):u("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:m.trim()?u("machine.logsTabSections.noBrowserEventsMatchSearch"):u("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:br(h.payload,360)||u("machine.logsTabSections.noPayload")})]},h.id))]})]})]})}function QR({machineId:e,sendDaemonCommand:t}){const s=TR({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}),m=c.useRef(null),u=c.useRef(!1),h=c.useMemo(()=>WR({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=u.current?"smooth":"instant";setTimeout(()=>{var x;(x=m.current)==null||x.scrollIntoView({behavior:f}),u.current=!0},50)}},[h.diagnosticEvents.length,s.autoRefresh]);const p=c.useCallback(async()=>{var x;const f=AR({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!f.trim()){Ze.showToast("No visible logs to copy.","info");return}try{await((x=navigator.clipboard)==null?void 0:x.writeText(f)),Ze.showToast("Copied visible logs to clipboard.","success")}catch(g){Ze.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=FR({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((x=navigator.clipboard)==null?void 0:x.writeText(f)),Ze.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){Ze.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(qR,{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(zR,{logLevel:s.logLevel,traceCategory:s.traceCategory,onLogLevelChange:s.setLogLevel,onTraceCategoryChange:s.setTraceCategory}),n.jsx(VR,{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(GR,{patterns:h.diagnosticsSummary.repeatedPatterns}),n.jsx(YR,{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:m})]})}function JR(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 Gg(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 XR(e){var o;const t=[],s=[],r=[];for(const a of e||[]){const i=String((a==null?void 0:a.lifecycle)||"").trim(),l=Gg((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 ZR(e,t){return e==="live"?t?t("sessionHostSurface.attach"):"Attach":e==="recovery"?t?t("sessionHostSurface.recover"):"Recover":t?t("sessionHostSurface.restart"):"Restart"}function Lc(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 eP={starting:"sessionHostSurface.lifecycleStarting",running:"sessionHostSurface.lifecycleRunning",stopping:"sessionHostSurface.lifecycleStopping",stopped:"sessionHostSurface.lifecycleStopped",failed:"sessionHostSurface.lifecycleFailed",interrupted:"sessionHostSurface.lifecycleInterrupted"},tP={starting:"Starting",running:"Running",stopping:"Stopping",stopped:"Stopped",failed:"Failed",interrupted:"Interrupted"};function $h(e,t){const s=eP[e];return s?t?t(s):tP[e]??e:e}function Oc(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function $c(e){return pi(e,{seconds:!0})||"—"}function Fh(e){return Ea(e)||"—"}function nP(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 sP(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function rP(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 oP(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 aP({machineId:e,cliSessions:t,sendDaemonCommand:s}){const{t:r}=pe("common"),[o,a]=c.useState(""),[i,l]=c.useState(null),{confirm:d,confirmDialog:m}=wr(),[u,h]=c.useState(!1),p=hT(e,{enabled:!!e,includeSessions:!0,limit:Vm,intervalMs:iT}),b=p.diagnostics,f=p.loading,x=p.applyDiagnostics,g=c.useMemo(()=>JR({diagnostics:b,loading:f,refreshing:u,error:o,t:r}),[b,f,u,o,r]),S=c.useMemo(()=>new Map(t.map(C=>[C.sessionId||C.id,C])),[t]),w=c.useCallback(async()=>{if(e){h(!0);try{const C=await s(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Vm}),I=Oc(C);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(C){const I=C instanceof Error?C.message:r("sessionHost.diagnosticsFailed");a(I)}finally{h(!1)}}},[x,e,s,r]);c.useEffect(()=>{!e||b||f||u||w()},[b,f,e,w,u]);const _=c.useCallback(async(C,I)=>{const O=`${C}:${I.sessionId}`;if(!(C==="session_host_stop_session"&&!await d({title:r("sessionHost.stopConfirmTitle",{name:I.displayName}),description:r("sessionHost.stopConfirmDescription"),confirmLabel:r("sessionHost.stop"),tone:"danger"}))){l(O);try{const D=await s(e,C,{sessionId:I.sessionId}),F=Oc(D);if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.error)||r("sessionHost.actionFailed"));const z=C==="session_host_resume_session"?"sessionHost.toastResumed":C==="session_host_restart_session"?"sessionHost.toastRestarted":"sessionHost.toastStopped";Ze.showToast(r(z,{name:I.displayName}),"success"),await w()}catch(D){const F=D instanceof Error?D.message:r("sessionHost.actionFailed");Ze.showToast(F,"warning"),a(F)}finally{l(D=>D===O?null:D)}}},[d,e,w,s,r]),k=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",{}),O=Oc(I);if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||r("sessionHost.pruneFailed"));const D=O.result||{},F=Array.isArray(D.prunedSessionIds)?D.prunedSessionIds.length:0,z=typeof D.duplicateGroupCount=="number"?D.duplicateGroupCount:0;Ze.showToast(r("sessionHost.toastPruned",{pruned:F,groups:z}),"success"),await w()}catch(I){const O=I instanceof Error?I.message:r("sessionHost.pruneFailed");Ze.showToast(O,"warning"),a(O)}finally{l(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[d,e,w,s,r]),v=c.useMemo(()=>[...(b==null?void 0:b.sessions)||[]].sort((C,I)=>(I.lastActivityAt||0)-(C.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)||[]}:XR(v),[b==null?void 0:b.inactiveRecords,b==null?void 0:b.liveRuntimes,b==null?void 0:b.recoverySnapshots,v]),j=y.liveRuntimes,N=y.recoverySnapshots,A=y.inactiveRecords,R=c.useMemo(()=>oP(j),[j]),P=c.useMemo(()=>[...(b==null?void 0:b.recentTransitions)||[]].slice(-6).reverse(),[b==null?void 0:b.recentTransitions]),M=c.useMemo(()=>[...(b==null?void 0:b.recentLogs)||[]].reverse().find(C=>C.level==="warn"||C.level==="error")||null,[b==null?void 0:b.recentLogs]),E=(C,I)=>{var U;const O=i===`session_host_resume_session:${C.sessionId}`,D=i===`session_host_restart_session:${C.sessionId}`,F=i===`session_host_stop_session:${C.sessionId}`,z=Gg(C.meta,r),Z=S.get(C.sessionId),W=r("sessionHost.clientsCount",{count:C.attachedClients.length}),T=r(I==="recovery"?"sessionHost.recover":"sessionHost.resume"),$=r(I==="recovery"?"sessionHost.recovering":"sessionHost.resuming"),H=ZR(I,r),q=$h(C.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:C.displayName||(Z==null?void 0:Z.cliName)||C.providerType}),n.jsx("span",{className:`px-2 py-0.5 rounded-md text-3xs font-semibold ${rP(C.lifecycle)}`,children:q}),z&&n.jsx("span",{className:"px-2 py-0.5 rounded-md text-3xs font-semibold bg-sky-500/[0.08] text-sky-300",children:z})]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1 flex flex-wrap gap-2",children:n.jsx(Gt,{content:[C.runtimeKey,C.osPid?`pid ${C.osPid}`:""].filter(Boolean).join(" · "),children:n.jsx("span",{className:"text-text-primary/90",children:C.workspaceLabel||(Z==null?void 0:Z.runtimeWorkspaceLabel)||C.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:((U=C.writeOwner)==null?void 0:U.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:sP(C.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(Yv,{size:11})," ",W]}),n.jsx("span",{className:"text-text-muted",children:"·"}),n.jsx("span",{className:"text-text-primary/85",children:r("sessionHost.activeAgo",{time:Fh(C.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"&&(C.lifecycle==="interrupted"||C.lifecycle==="failed"||C.lifecycle==="stopped")&&n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1",disabled:!!i,onClick:()=>{_("session_host_resume_session",C)},children:O?$:T}),n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1",disabled:!!i,onClick:()=>{_("session_host_restart_session",C)},children:r(D?"sessionHost.restarting":"sessionHost.restart")}),I==="live"&&(C.lifecycle==="running"||C.lifecycle==="starting"||C.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:()=>{_("session_host_stop_session",C)},children:r(F?"sessionHost.stopping":"sessionHost.stop")})]})]})},C.sessionId)};return n.jsxs(mn,{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(dr,{size:14})," ",r("sessionHost.title")]}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:F1()})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[R>0&&n.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{k()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?r("sessionHost.pruning"):r("sessionHost.pruneDuplicatesCount",{count:R})}),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:()=>{w()},disabled:f||u,children:[n.jsx(vr,{size:13}),r(f||u?"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(Xt,{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:N.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:Fh(b.hostStartedAt)}),n.jsx("div",{className:"text-3xs text-text-secondary mt-0.5",children:$c(b.hostStartedAt)})]})]}),M&&n.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-2xs text-text-secondary mb-4",children:[n.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[n.jsx(Xt,{size:13})," ",r("sessionHost.latestWarning")]}),n.jsx("div",{className:"text-text-primary leading-relaxed",children:M.message}),n.jsxs("div",{className:"text-3xs text-text-secondary mt-1",children:[$c(M.timestamp),M.sessionId?` · ${M.sessionId}`:""]})]}),n.jsxs("div",{className:"mb-4 space-y-4",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[n.jsx(cd,{size:14})," ",r("sessionHost.liveTitle")]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2.5",children:Lc("live",r)}),j.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:j.map(C=>E(C,"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(dr,{size:14})," ",r("sessionHost.recoveryTitle")]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2.5",children:Lc("recovery",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.recoveryEmpty")}):n.jsx("div",{className:"space-y-2",children:N.map(C=>E(C,"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:Lc("inactive",r)}),n.jsx("div",{className:"space-y-2 opacity-85",children:A.map(C=>E(C,"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(C=>{var O;const I=v.find(D=>D.sessionId===C.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)||((O=S.get(C.sessionId))==null?void 0:O.cliName)||C.sessionId}),n.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[nP(C.action,r),C.lifecycle?` · ${$h(C.lifecycle,r)}`:"",(C.detail||C.error)&&n.jsx(tt,{content:[C.detail,C.error].filter(Boolean).join(`
94
- `),size:11,className:"ml-1"})]})]}),n.jsx("div",{className:`shrink-0 text-3xs ${C.success===!1?"text-red-300":"text-text-secondary"}`,children:$c(C.timestamp)})]},`${C.sessionId}:${C.timestamp}:${C.action}`)})})]}),n.jsx(Ad,{className:"mt-3",rows:[{label:r("sessionHost.endpointLabel"),value:b.endpoint||null},{label:r("sessionHost.lastErrorLabel"),value:o||null,copyable:!1}]})]}),m]})}function iP({machine:e,launchPick:t,actions:s}){const{t:r}=pe("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 cP(e,t){const s=s2(e),r=Is(e,t),o=Kd(e,r),a=ja(e,r),i=hg(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 Fc({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 Hc({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 lP({machineEntry:e,providers:t,recentLaunches:s,currentConversations:r,onUpgradeDaemon:o,onOpenRecent:a,onOpenConversation:i}){const{t:l}=pe("common"),d=r.slice(0,6),m=s.slice(0,4),h=cP(e,"1.0.72"),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(`
94
+ `),size:11,className:"ml-1"})]})]}),n.jsx("div",{className:`shrink-0 text-3xs ${C.success===!1?"text-red-300":"text-text-secondary"}`,children:$c(C.timestamp)})]},`${C.sessionId}:${C.timestamp}:${C.action}`)})})]}),n.jsx(Ad,{className:"mt-3",rows:[{label:r("sessionHost.endpointLabel"),value:b.endpoint||null},{label:r("sessionHost.lastErrorLabel"),value:o||null,copyable:!1}]})]}),m]})}function iP({machine:e,launchPick:t,actions:s}){const{t:r}=pe("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 cP(e,t){const s=s2(e),r=Is(e,t),o=Kd(e,r),a=ja(e,r),i=hg(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 Fc({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 Hc({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 lP({machineEntry:e,providers:t,recentLaunches:s,currentConversations:r,onUpgradeDaemon:o,onOpenRecent:a,onOpenConversation:i}){const{t:l}=pe("common"),d=r.slice(0,6),m=s.slice(0,4),h=cP(e,"1.0.73"),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(`
95
95
  `):"";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(Fc,{icon:n.jsx(Cn,{size:13}),children:l("machine.commandCenter.currentChats")}),n.jsx(Hc,{children:n.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(b=>{const f=Fl(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(vs,{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:wt(b)})]}),f>0&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:hi(f)})]}),n.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:To(b)})]},b.tabKey)})})})]}),m.length>0&&n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(Fc,{icon:n.jsx(id,{size:13}),children:l("machine.commandCenter.recentLaunches")}),n.jsx(Hc,{children:n.jsx("div",{className:"flex flex-col gap-1.5",children:m.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(Fc,{icon:n.jsx(Xt,{size:13}),children:l("machine.commandCenter.daemonUpdate")}),n.jsx(Hc,{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(tt,{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(vr,{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(Gt,{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 Kl(e){return e.trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function dP(e,t){return t.has(Kl(e))}function uP({displayLabel:e,path:t,busy:s,onSave:r}){const{t:o}=pe("common"),[a,i]=c.useState(!1),[l,d]=c.useState(e),[m,u]=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()=>{u(!0);try{await r(t,l)&&i(!1)}finally{u(!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||m,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||m,onClick:()=>{f()},children:n.jsx(xr,{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:m,onClick:b,children:n.jsx(Pt,{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(Xv,{size:12})})]})}function mP({machineId:e,machine:t,ideSessions:s,cliSessions:r,actions:o,sendDaemonCommand:a}){const{workspaceBusy:i,handleWorkspaceAdd:l,handleWorkspaceRemove:d,handleWorkspaceSetDefault:m,handleWorkspaceSetLabel:u}=o,{t:h}=pe("common"),p=qs(),b=Td(),[f,x]=c.useState(!1),[g,S]=c.useState(()=>new Set),[w,_]=c.useState(null);c.useEffect(()=>{let O=!1;return(async()=>{try{let D=[];if(b!=null&&b.listMeshes)D=(await b.listMeshes(e)).map(F=>F.workspace);else{const F=await a(e,"list_meshes",{}),z=(F==null?void 0:F.result)??F;D=(Array.isArray(z==null?void 0:z.meshes)?z.meshes:[]).map(W=>{var T;return Array.isArray(W==null?void 0:W.nodes)&&W.nodes.length>0?String(((T=W.nodes[0])==null?void 0:T.workspace)||""):null})}if(O)return;S(new Set(D.filter(F=>!!F).map(Kl)))}catch{}})(),()=>{O=!0}},[e,b,a]);const k=c.useCallback(O=>{p("/dashboard",{state:{openNewSession:{machineId:e,workspaceId:O}}})},[e,p]),v=c.useCallback((O,D)=>{p("/dashboard",{state:{openNewSession:{machineId:e,workspaceId:O,mode:"mesh",meshWorkspacePath:D}}})},[e,p]),[y,j]=c.useState(""),[N,A]=c.useState([]),[R,P]=c.useState(!1),[M,E]=c.useState(""),C=c.useCallback(async O=>{P(!0),E("");try{const D=await Vd(a,e,O);j(D.path),A(D.directories)}catch(D){E(D instanceof Error?D.message:"Could not load folder")}finally{P(!1)}},[e,a]),I=c.useCallback(()=>{x(!0);const O=[...s.map(F=>F.workspace),...r.map(F=>F.workspace)],D=zd(t.platform,qd(O,t.defaultWorkspacePath,(t.workspaces||[]).map(F=>F.path)));C(D)},[r,s,C,t.defaultWorkspacePath,t.platform,t.workspaces]);return n.jsxs(n.Fragment,{children:[n.jsxs(mn,{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(Hs,{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(O=>{const D=O.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 ${D?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[n.jsx("button",{type:"button",title:h(D?"machine.managedWorkspaces.unsetDefaultHint":"machine.managedWorkspaces.setDefaultHint"),disabled:i,onClick:()=>void m(D?null:O.id),className:`text-base leading-none shrink-0 transition-colors ${D?"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:[dP(O.path,g)?n.jsx(uP,{displayLabel:fa(O.path,O.label),path:O.path,busy:i,onSave:u}):n.jsx("div",{className:"font-medium text-text-primary truncate",children:fa(O.path,O.label)}),n.jsx("div",{className:"font-mono text-text-muted truncate text-3xs",title:O.path,children:O.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:()=>k(O.id),children:[n.jsx(po,{size:11}),h("machine.managedWorkspaces.newSessionShort")]}),g.has(Kl(O.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(O.id,O.path),children:[n.jsx(po,{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:()=>_({id:O.id,label:fa(O.path,O.label)}),children:n.jsx(sw,{size:13})})]},O.id)})})]}),f&&n.jsx(Yd,{title:h("machine.managedWorkspaces.addWorkspace"),description:h("machine.managedWorkspaces.addDialogDescription"),currentPath:y,directories:N,busy:R,error:M,confirmLabel:h("machine.managedWorkspaces.addWorkspace"),onClose:()=>x(!1),onNavigate:O=>{C(O)},onConfirm:O=>{(async()=>{if(!O)return;await l(O)&&x(!1)})()}}),w&&n.jsx(Jp,{title:h("machine.managedWorkspaces.removeConfirmTitle"),description:h("machine.managedWorkspaces.removeConfirmDescription",{label:w.label}),confirmLabel:h("machine.managedWorkspaces.remove"),tone:"danger",busy:i,onCancel:()=>_(null),onConfirm:()=>{const O=w;_(null),O&&d(O.id)}})]})}function hP({machine:e,machineId:t,ideSessions:s,cliSessions:r,actions:o,sendDaemonCommand:a}){const{t:i}=pe("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(mP,{machineId:t,machine:e,ideSessions:s,cliSessions:r,actions:o,sendDaemonCommand:a})]})}function pP({onNicknameSynced:e}={}){var B,Q,ue,Re,Le,Pe,Fe,X,ve,Se,Ce;const{t}=pe("common"),{id:s}=Ex(),r=qs(),o=ai(),{sendCommand:a}=xt(),i=jr(),l=rg(),d=ki(),m=d.ides||[],u=d.initialLoaded??!0,h=m.find(L=>L.id===s&&L.type==="adhdev-daemon"),p=m.some(L=>L.type==="adhdev-daemon"),b=s?(B=d.connectionRetryStatuses)==null?void 0:B[s]:void 0,f=!!(b!=null&&b.blocked),[x,g]=c.useState("workspace"),[S,w]=c.useState(null),[,_]=c.useState("ide"),k=c.useRef(null),[v,y]=c.useState(null),j=c.useRef("__home__"),[N,A]=c.useState("__home__"),[R,P]=c.useState(!1),M=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 L=h.machine;(typeof(L==null?void 0:L.cpus)!="number"||typeof(L==null?void 0:L.totalMem)!="number"||typeof(L==null?void 0:L.arch)!="string"||typeof(L==null?void 0:L.release)!="string"||!(L!=null&&L.quota))&&l(s,{minFreshMs:3e4}).catch(()=>{})},[x,l,h,s]),mT(s&&x==="overview"?[s]:[],{enabled:x==="overview",intervalMs:oT});const E=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},C=GM({machineId:s,registeredMachineId:(h==null?void 0:h.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:M});c.useEffect(()=>Ze.onToast(Y=>{d.setToasts(te=>{if(te.some(se=>se.message===Y.message&&Y.timestamp-se.timestamp<3e3))return te;const V={id:Y.id,message:Y.message,type:Y.type,timestamp:Y.timestamp,targetKey:Y.targetKey,actions:Y.actions,details:Y.details};return[...te.slice(-4),V]});const ce=Y.duration||5e3;setTimeout(()=>d.setToasts(te=>te.filter(fe=>fe.id!==Y.id||fe.pinned)),ce)}),[d]);const I=(h==null?void 0:h.availableProviders)||[],O={};for(const L of I)O[L.type]=L.icon;const D=h?{id:h.id,hostname:bd(h,{fallbackId:h.id}),platform:((Q=h.machine)==null?void 0:Q.platform)||"unknown",arch:((ue=h.machine)==null?void 0:ue.arch)||"",cpus:((Re=h.machine)==null?void 0:Re.cpus)||0,totalMem:((Le=h.machine)==null?void 0:Le.totalMem)||0,freeMem:(Pe=h.machine)==null?void 0:Pe.freeMem,availableMem:(Fe=h.machine)==null?void 0:Fe.availableMem,loadavg:(X=h.machine)==null?void 0:X.loadavg,uptime:(ve=h.machine)==null?void 0:ve.uptime,release:((Se=h.machine)==null?void 0:Se.release)||"",cdpConnected:!!h.cdpConnected,machineNickname:h.machineNickname||null,...(Ce=h.machine)!=null&&Ce.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,F=m.filter(L=>L.daemonId===s&&L.type!=="adhdev-daemon").filter(L=>!xo(L)).map(L=>({id:L.id,sessionId:L.sessionId,type:L.type,version:L.version||"",instanceId:L.instanceId||"",status:L.status,workspace:L.workspace||null,terminals:L.terminals||0,aiAgents:Xk(L.aiAgents||(L.agents||[]).map(Y=>({id:Y.name,name:Y.name,status:Y.status,version:Y.version}))),activeChat:L.activeChat||null,chats:L.chats||[],childSessions:L.childSessions||[],cdpConnected:L.cdpConnected||!1,daemonId:s,lastMessageAt:L.lastMessageAt})),z=m.filter(L=>L.daemonId===s&&xo(L)).map(L=>({id:L.id,sessionId:L.sessionId,type:L.type,cliName:L.cliName||L.type,status:L.status,workspace:L.workspace||"",activeChat:L.activeChat||null,providerSessionId:L.providerSessionId,mode:L.mode,runtimeKey:L.runtimeKey,runtimeDisplayName:L.runtimeDisplayName,runtimeWorkspaceLabel:L.runtimeWorkspaceLabel,runtimeWriteOwner:L.runtimeWriteOwner||null,runtimeAttachedClients:L.runtimeAttachedClients||[],daemonId:s,lastMessageAt:L.lastMessageAt})),Z=h?yn(h,{fallbackId:s}):"",W="workspace",T=o.state,$=T==null?void 0:T.initialMachineTab,H=T==null?void 0:T.initialWorkspaceCategory;T==null||T.initialWorkspaceId,T==null||T.initialWorkspacePath;const q=$==="session-host"?"hosted-runtimes":$==="logs"?"logs":null,U=$==="ides"||$==="clis"?"workspace":q?"overview":$||W,K=$==="ides"?"ide":$==="clis"?"cli":H,oe=[...F.map(L=>{var Y;return{id:`ide:${L.type}:${L.workspace||""}`,label:((Y=L.activeChat)==null?void 0:Y.title)||L.type,kind:"ide",providerType:L.type,subtitle:L.workspace||void 0,workspace:L.workspace||void 0,lastLaunchedAt:L.lastMessageAt||0}}),...z.map(L=>{var Y;return{id:`cli:${L.type}:${L.workspace||""}`,label:((Y=L.activeChat)==null?void 0:Y.title)||L.cliName,kind:"cli",providerType:L.type,providerSessionId:L.providerSessionId,subtitle:L.workspace||void 0,workspace:L.workspace||void 0,lastLaunchedAt:L.lastMessageAt||0}})].sort((L,Y)=>(Y.lastLaunchedAt||0)-(L.lastLaunchedAt||0)),ke=((h==null?void 0:h.recentLaunches)||[]).length>0?((h==null?void 0:h.recentLaunches)||[]).map(L=>({id:L.id,label:L.title||L.providerName||L.providerType,kind:L.kind,providerType:L.providerType,providerSessionId:L.providerSessionId,subtitle:go(L.summaryMetadata)||L.workspace||void 0,workspace:L.workspace,summaryMetadata:L.summaryMetadata,lastLaunchedAt:L.lastLaunchedAt})):oe,J=c.useMemo(()=>{var Y;const L=((Y=d.connectionStates)==null?void 0:Y[s||""])||void 0;return m.filter(ce=>ce.daemonId===s&&ce.type!=="adhdev-daemon").flatMap(ce=>Ld(ce,{connectionStates:s&&L?{[s]:L}:void 0,defaultConnectionState:L})).filter(ce=>!(ce.transport==="pty"&&ce.mode==="terminal")).sort((ce,te)=>Fl(te)-Fl(ce))},[m,d.connectionStates,s]),ye=c.useCallback(L=>{const Y=bg(L);Y&&r(yo(Y))},[r]),ae=c.useCallback(()=>{k.current&&(P(!0),k.current().finally(()=>{k.current=null,P(!1),y(null)}))},[]),re=c.useCallback(L=>{if(!D)return;const{options:Y,selectedKey:ce}=Sg({machine:D,currentWorkspacePath:L.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),te=async()=>{_(L.kind),g("workspace")};if(k.current=async()=>{const fe=Y.find(he=>he.key===j.current),V=(fe==null?void 0:fe.workspacePath)??null,se=(fe==null?void 0:fe.workspaceId)??null;if(L.kind==="ide"&&L.providerType){await C.handleLaunchIde(L.providerType,V?{workspace:V}:void 0);return}if(L.kind==="cli"&&L.providerType){await C.runLaunchCliCore({cliType:L.providerType,dir:se?void 0:V||"",workspaceId:se||void 0,resumeSessionId:L.providerSessionId});return}await te()},j.current=ce,Y.length<=1){const fe=k.current;k.current=null,fe==null||fe().catch(V=>Ze.showErrorToast(t("machine.detail.relaunchFailed"),V));return}A(ce),y({title:L.kind==="ide"?Ka(t,"restart-ide",L.label):L.providerSessionId?Bb(t,L.label):Ka(t,"start-fresh",L.label),description:L.kind==="ide"?qa(t,"restart-ide"):L.providerSessionId?Wb(t):qa(t,"start-fresh"),confirmLabel:L.kind==="ide"?za(t,"restart-ide"):L.providerSessionId?Il(t,!0):za(t,"start-fresh"),busyLabel:L.kind==="ide"?Va(t,"restart-ide"):L.providerSessionId?Fb(t,!0):Va(t,"start-fresh"),workspaceOptions:Y,details:[{label:t("machine.detail.launchType"),value:L.kind.toUpperCase()},...L.providerType?[{label:t("machine.detail.launchProvider"),value:(()=>{const fe=I.find(se=>se.type===L.providerType),V=(fe==null?void 0:fe.displayName)||L.providerType;return n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Ii,{type:L.providerType,label:V,size:14}),V]})})()}]:[]]})},[C,D,I,t]);if(c.useEffect(()=>{g(U)},[W,U,s]),c.useEffect(()=>{K&&_(K)},[K,s]),!D)return u?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:E,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 de=(h==null?void 0:h.providerChannelStaleness)??null,ne=!!de&&de.staleTypes.length+de.newTypes.length>0,ie=F.length+z.length,_e=[{key:"workspace",icon:n.jsx(Hn,{size:14}),label:t("machine.detail.tabSessions"),trailing:ie>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:ie}):void 0},{key:"providers",icon:n.jsx(yr,{size:14}),label:t("machine.detail.tabProviders"),trailing:ne?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(tw,{size:14}),label:t("machine.detail.tabSystem")}],G=vf[D.platform]||D.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:E,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:[C.editingNickname?n.jsxs("div",{className:"flex gap-1.5 items-center",children:[n.jsx("input",{autoFocus:!0,value:C.nicknameInput,onChange:L=>C.setNicknameInput(L.target.value),onKeyDown:L=>{L.key==="Enter"&&C.handleSaveNickname(),L.key==="Escape"&&C.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:C.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:()=>C.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:()=>{C.setEditingNickname(!0),C.setNicknameInput(D.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:Z}),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"),G].filter(Boolean).join(" · ")})]})]})}),n.jsx(Od,{variant:"underline",tabs:_e,activeKey:x,onSelect:L=>g(L),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(lP,{machineEntry:h,providers:I,recentLaunches:ke,currentConversations:J,onUpgradeDaemon:async()=>{const L=Ud(h);if(L)try{await a(s,"daemon_upgrade",L)}catch{}},onOpenRecent:re,onOpenConversation:ye}),n.jsx(hP,{machine:D,machineId:s,ideSessions:F,cliSessions:z,actions:C,sendDaemonCommand:a})]}),x==="providers"&&n.jsx(fR,{machineId:s,providers:I,sendDaemonCommand:a,quota:D.quota}),x==="overview"&&n.jsx(JM,{machine:D,ideSessions:F,cliSessions:z,daemonVersion:h==null?void 0:h.version,initialDiagnostics:q,renderHostedRuntimes:()=>n.jsx(aP,{machineId:s,cliSessions:z,sendDaemonCommand:a}),renderLogs:()=>n.jsx(QR,{machineId:s,sendDaemonCommand:a})})]})})}),C.launchPick&&D&&n.jsx(iP,{machine:D,launchPick:C.launchPick,actions:C}),v&&n.jsx(Ei,{title:v.title,description:v.description,details:v.details,workspaceOptions:v.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:L=>{j.current=L,A(L)},confirmLabel:v.confirmLabel,busyLabel:v.busyLabel,busy:R,onConfirm:ae,onCancel:()=>{k.current=null,y(null)}}),S&&n.jsx(Kg,{daemonId:S.daemonId,workspace:S.workspace,onClose:()=>w(null)}),C.confirmDialog,n.jsx(Ub,{toasts:d.toasts||[],onDismiss:L=>d.setToasts(Y=>Y.filter(ce=>ce.id!==L)),onClickToast:L=>{L.targetKey&&r(yo(L.targetKey))}}),n.jsx("style",{children:`
96
96
  @keyframes toast-in {
97
97
  from { opacity: 0; transform: translateX(40px); }
@@ -111,6 +111,6 @@ Node removal cleanup policy: ${ce}`)))return;const fe=x();if(fe)try{const se=awa
111
111
 
112
112
  @noble/hashes/esm/utils.js:
113
113
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
114
- */const TL=/[^a-z0-9_-]+/g;function IL(e,t){const s=e.toLowerCase().replace(TL,"_").replace(/^_+|_+$/g,"");return s.length>0?s.slice(0,64):t}function ML(e){return IL(e,"unknown_session")}function RL(e){return`session.${ML(e)}.chat`}function Xh(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 Zh(e){const t=new Map;return e.forEach((s,r)=>t.set(s.messageId,r)),t}function zc(e){const t=e.ordered.length;return{...e.meta,coverage:{...e.meta.coverage,totalMessageCount:t,returnedMessageCount:t},messages:e.ordered}}class PL{constructor(){ze(this,"sessions",new Map)}apply(t){if(t.reset){if(!t.meta)return null;const o=[...t.upserts].sort(Xh),a={meta:t.meta,byId:new Map(o.map(i=>[i.messageId,i])),ordered:o,indexOf:Zh(o)};return this.sessions.set(t.sessionId,a),{sessionId:t.sessionId,view:zc(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(Xh),s.indexOf=Zh(s.ordered)}return{sessionId:t.sessionId,view:zc(s),reset:!1}}view(t){const s=this.sessions.get(t);return s?zc(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 EL="transcript_topics_available",DL=256;function LL(e){if(!e||typeof e!="object")return null;const t=e;if(t.type!==EL||!Array.isArray(t.topics)||t.topics.length>DL)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 OL(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(RL(o)))}const $L=4096;function FL(e){return typeof e.isOpen=="function"?e.isOpen():e.readyState===1||e.readyState==="open"}function HL(e,t,s={}){const r=s.preOpenQueueCap??$L,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(qc("queue_overflow"))};return t.onmessage=d=>{if(a)return;const m=d.data;typeof m=="string"&&(FL(e)?(o.length>0&&i(),e.send(m)):o.length<r?o.push(m):l())},e.addEventListener("message",d=>{if(a)return;const m=d.data;typeof m=="string"&&t.postMessage(m)}),e.addEventListener("open",()=>{a||(i(),t.postMessage(qc("transport_open")))}),e.addEventListener("close",()=>{a||(a=!0,o.length=0,t.postMessage(qc("transport_closed")))}),{pendingCount(){return o.length},close(){a||(a=!0,o.length=0,t.onmessage=null)}}}function BL(e,t){var m,u,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]),(u=(m=r.port1).start)==null||u.call(m),(p=(h=o.port1).start)==null||p.call(h);const i=new PL;o.port1.onmessage=b=>{var f,x;if(hD(b.data)){const g=i.apply(b.data);g&&((f=t.onView)==null||f.call(t,g));return}pD(b.data)&&((x=t.onBaseRequest)==null||x.call(t,b.data.sessionId))};let l=HL(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(fD(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 Sx="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Uint8Array.from(Sx,e=>e.charCodeAt(0));const WL=new Uint8Array(256);for(let e=0;e<64;e++)WL[Sx.charCodeAt(e)]=e;new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;new globalThis.TextDecoder;function UL(){if(typeof window>"u"||typeof Worker>"u"||typeof WebSocket>"u")return()=>{};const e=iD(window.location,Hi()),t=new mD({createSocket:()=>new WebSocket(e),startHost:(s,r,o)=>BL(s,{writerId:nD,sessionKey:"transcript",onView:r,onBaseRequest:o,createWorker:()=>new Worker(new URL("/assets/transcript-worker-entry-BYUOYOUE.js",import.meta.url),{type:"module"}),onOverflow:()=>console.warn("[Transcript] standalone lane pre-open queue overflow — channel reset")}),collectInterest:jC,subscribeInterest:NC,applyView:(s,r,o)=>wC(s,r,o),requestBase:SC,subscribeTopicsAvailable:uD,selectResubscribe:OL,setTimer:(s,r)=>setTimeout(s,r),clearTimer:s=>clearTimeout(s),now:()=>Date.now(),log:s=>console.warn(s)});return t.start(),()=>t.stop()}function KL(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,s=Hi();return s?`${t}?token=${encodeURIComponent(s)}`:t}const ma=KL(),ep=3e3,qL=3e4;let kn=null,zL=0;const ri=new Map;let As=null,uo=null,tp=null;const VL="standalone_hello";function GL(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Qr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function YL(e){return e==="connected"?"connected":e}async function mo(e,t,s){const r=Gb(e,s||{}),o=kn;if(o&&o.readyState===WebSocket.OPEN){const a=`req_${++zL}_${Date.now()}`;return new Promise((i,l)=>{const d=setTimeout(()=>{ri.delete(a),l(new Error(`WS command timeout: ${t}`))},3e4);ri.set(a,{resolve:m=>{clearTimeout(d),i(m)},reject:m=>{clearTimeout(d),l(m)}}),o.send(JSON.stringify({type:"command",requestId:a,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function oi(e,t){const s=kn;if(!s||s.readyState!==WebSocket.OPEN||!lD(t))return!1;try{return s.send(JSON.stringify(t)),!0}catch{return!1}}function kx(e,t,s){const r=kn;if(!r||r.readyState!==WebSocket.OPEN)return!1;const o=Gb(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}}En.registerPtyInputSender(kx);En.registerDataSender((e,t)=>oi(e,t));class QL{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 mo(this.daemonId,t,s)}async sendInput(t,s){return mo(this.daemonId,"cdp_remote_action",{action:t,params:s,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,As&&(clearInterval(As),As=null);const s=async()=>{if(this.hasCommandChannel)try{const r=await mo(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());En.emitScreenshot(this.daemonId,o)}}catch{}};s(),As=setInterval(s,2e3)}stopScreenshots(t){As&&(clearInterval(As),As=null)}}let gn=null;function JL(e){return(!gn||gn.daemonId!==e)&&(gn=new QL(e)),gn}function XL({children:e}){const t=c.useRef(lr()),s=lr();t.current=s;const{setUserName:r}=Bv(),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),uo==null||uo(x,g)},[]),m=c.useRef(null),u=c.useRef(),h=c.useRef(ep),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 _,k;if(!p.current||((_=m.current)==null?void 0:_.readyState)===WebSocket.OPEN||((k=m.current)==null?void 0:k.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${ma}...`),Qr("connect_attempt",{url:ma,reason:f.current,delayMs:h.current});let w;try{w=new WebSocket(ma)}catch(v){console.error("[Standalone WS] Failed to create WebSocket:",v),g();return}m.current=w,w.onopen=()=>{if(!p.current){w.close();return}d("connected"),h.current=ep,Qr("open",{url:ma,reason:f.current}),$n.resubscribeAll({sendData:oi}),console.log("[Standalone WS] Connected")},kn=w,w.onmessage=v=>{var y,j;try{const N=JSON.parse(v.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const R=ri.get(N.requestId);R&&(ri.delete(N.requestId),N.type==="error"?R.reject(new Error(((y=N.data)==null?void 0:y.message)||"Command failed")):R.resolve(N.data));return}if(N.type==="session_output"){const R=N.sessionId||N.cliId||N.cliType;R&&En.emitSessionOutput(R,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){En.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}const A=LL(N);if(A){dD(A);return}if(eD(N,tp,Ze,kC))return;if(N.type==="topic_update"){const R=N.update;R&&$n.publish(R);return}if(N.type===VL&&typeof N.daemonId=="string"&&N.daemonId){const R=N.daemonId;tp=R,wl(R,typeof N.wireVersion=="number"?N.wireVersion:null);const P=JL(R);En.register(R,P),En.setState(R,"connected"),d("connected",R),i.current!==R&&((j=a.current)==null||j.call(a),i.current=R,a.current=$n.subscribe({sendData:oi},R,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${R}`,params:{includeSessions:!0}},M=>{const E=t.current.getIdes(),C=E.find(O=>O.id===R),I=Jf(M.status,{daemonId:R,existingDaemon:C,existingEntries:E,timestamp:M.timestamp});GL("metadata",{daemonId:R,seq:M.seq,sessions:(M.status.sessions||[]).map(O=>({id:O.id,providerType:O.providerType,status:O.status,unread:O.unread,inboxBucket:O.inboxBucket}))}),I.length>0&&t.current.injectEntries(I,{authoritativeDaemonIds:[R]}),t.current.markLoaded(),M.userName&&o.current&&o.current(M.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},w.onclose=v=>{p.current&&(gn==null||gn.stopScreenshots(),gn&&En.setState(gn.daemonId,"disconnected"),d("disconnected"),m.current=null,f.current=`close:${v.code}${v.wasClean?":clean":":unclean"}`,Qr("close",{code:v.code,reason:v.reason||"",wasClean:v.wasClean}),g())},w.onerror=v=>{b.current||!p.current||(f.current="error",Qr("error",{message:v instanceof Event?"event":String(v),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",v))}}function g(){if(!p.current)return;clearTimeout(u.current);const w=h.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),Qr("schedule_reconnect",{reason:f.current,delayMs:w}),u.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,qL),x()},w)}x();const S=UL();return()=>{var w;S(),p.current=!1,b.current=!0,(w=a.current)==null||w.call(a),a.current=null,i.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,kn=null),gn&&(gn.stopScreenshots(),En.unregister(gn.daemonId))}},[]),n.jsx(n.Fragment,{children:e})}function ZL({children:e}){const[t,s]=c.useState("disconnected"),[r,o]=c.useState(null);c.useEffect(()=>(uo=(i,l)=>{s(i),l&&o(l)},()=>{uo=null}),[]);const a=c.useMemo(()=>{const i=t==="connected",l=YL(t),d={};return r&&(d[r]=l),d.standalone=l,{wsStatus:t,isConnected:i,connectionStates:d,usesP2P:!1}},[t,r]);return n.jsx(Hv,{connectionOverrides:a,children:n.jsx(XL,{children:e})})}const jx="adhdev_standalone_font_preferences",Fs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Bi=[{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"}],vo=[{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"}],e5=new Set(Bi.map(e=>e.id)),t5=new Set(vo.map(e=>e.id));function Dn(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Ta("chat",t.chat),code:Ta("code",t.code),terminal:Ta("terminal",t.terminal)}}function Ta(e,t){const s=Fs[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"?e5:t5).has(o)?o==="custom"?a?{preset:"custom",customFamily:a}:s:{preset:o}:s}function Ia(e,t){var o;const s=Ta(e,t);if(s.preset==="custom"&&s.customFamily)return s.customFamily;const r=e==="chat"?Bi:vo;return((o=r.find(a=>a.id===s.preset))==null?void 0:o.family)||r[0].family}function n5(e){const t=Dn(e),s=Ia("chat",t.chat),r=Ia("code",t.code),o=Ia("terminal",t.terminal);return{"--chat-font-family":s,"--chat-code-font-family":r,"--chat-terminal-font-family":o,"--chat-tool-font-family":o}}function Ms(e,t=document.documentElement){const s=Dn(e),r=n5(s);t.setAttribute("data-standalone-fonts","custom");for(const[o,a]of Object.entries(r))t.style.setProperty(o,a);return s}function Jl(e){const t=Dn(e);try{localStorage.setItem(jx,JSON.stringify(t))}catch{}return t}function s5(){try{const e=localStorage.getItem(jx);if(e)return Dn(JSON.parse(e))}catch{}return Fs}function r5(){return Ms(s5())}function Jr(e,t,s){const r=e==="chat"?Bi:vo,o=r.find(a=>a.id===t)||r[0];return o.labelKey&&s?s(o.labelKey,o.label):o.label}function o5({children:e}){const t=qs(),s=ai(),{t:r}=pe("common"),o=c.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:n.jsx(Cp,{}),label:r("nav.dashboard"),active:s.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:n.jsx(dr,{}),label:r("nav.machines"),active:s.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:n.jsx(Ln,{}),label:r("nav.mesh"),active:s.pathname.startsWith("/mesh")||s.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"notifications",path:"/notifications",icon:n.jsx(gs,{}),label:r("nav.notifications"),active:s.pathname.startsWith("/notifications"),onSelect:()=>t("/notifications")},{id:"settings",path:"/settings",icon:n.jsx(yr,{}),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(_p,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("nav.docs")},{id:"about",label:r("nav.about"),icon:n.jsx(So,{}),active:s.pathname==="/about",onSelect:()=>t("/about"),title:r("nav.about")}],[s.pathname,t,r]);return n.jsx(_A,{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.72"]}),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 a5(){const e=qs(),{sendCommand:t}=xt(),{ides:s}=xn(),r=c.useMemo(()=>s.filter(o=>o.daemonMode||o.type==="adhdev-daemon").map(o=>o),[s]);return n.jsx(JE,{daemons:r,features:Xg,sendCommand:t,unwrapResult:o=>o,normalizeMesh:o=>o,onClose:()=>e("/mesh")})}const i5=[{icon:n.jsx(dr,{size:16}),key:"localFirst"},{icon:n.jsx(Cn,{size:16}),key:"chatRelay"},{icon:n.jsx(ad,{size:16}),key:"screenshots"},{icon:n.jsx(Hn,{size:16}),key:"remoteControl"},{icon:n.jsx(ur,{size:16}),key:"multiIde"},{icon:n.jsx(_p,{size:16}),key:"cli"}],c5=[{icon:n.jsx(di,{size:16}),key:"anywhere"},{icon:n.jsx(Cp,{size:16}),key:"p2pStream"},{icon:n.jsx(gs,{size:16}),key:"mobileNotifications"},{icon:n.jsx(Jv,{size:16}),key:"restApi"},{icon:n.jsx(Zv,{size:16}),key:"enterpriseControls"}],l5=[{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 d5(){const{t:e}=pe("common");return n.jsxs(Mo,{icon:n.jsx(So,{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.72"]}),children:[n.jsx(gt,{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(gt,{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:i5.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(gt,{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:mA.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:pA.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:hA.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(gt,{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:c5.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(gt,{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:l5.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(Ri,{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 Vc(e,t,s){return{...e,[t]:s}}function Gc({surface:e,title:t,description:s,value:r,options:o,onChange:a}){const{t:i}=pe("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(tt,{content:s,size:12})]}),n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(MA,{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:Ia(e,r)})]})]})]})}function u5({value:e,savedValue:t,saving:s=!1,error:r,notice:o,onChange:a,onSave:i,onResetToSaved:l,onResetToDefaults:d}){const{t:m}=pe("common"),u=JSON.stringify(e)!==JSON.stringify(t);return n.jsxs("div",{className:"flex flex-col gap-4",children:[r&&n.jsx(Ft,{variant:"error",children:r}),o&&n.jsx(Ft,{variant:"success",children:o}),n.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[n.jsx(Gc,{surface:"chat",title:m("standalone.fonts.chat"),description:m("standalone.fonts.chatDescription"),value:e.chat,options:Bi,onChange:h=>a(Vc(e,"chat",h))}),n.jsx(Gc,{surface:"code",title:m("standalone.fonts.code"),description:m("standalone.fonts.codeDescription"),value:e.code,options:vo,onChange:h=>a(Vc(e,"code",h))}),n.jsx(Gc,{surface:"terminal",title:m("standalone.fonts.terminal"),description:m("standalone.fonts.terminalDescription"),value:e.terminal,options:vo,onChange:h=>a(Vc(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:[m("standalone.fonts.livePreview"),n.jsx(tt,{size:12,content:[m("standalone.fonts.previewSummary",{chat:Jr("chat",e.chat.preset,m),code:Jr("code",e.code.preset,m),terminal:Jr("terminal",e.terminal.preset,m)}),m("standalone.fonts.defaultsSummary",{chat:Jr("chat",Fs.chat.preset,m),code:Jr("code",Fs.code.preset,m)}),m("standalone.fonts.fontOverridesNotice")].join(`
114
+ */const TL=/[^a-z0-9_-]+/g;function IL(e,t){const s=e.toLowerCase().replace(TL,"_").replace(/^_+|_+$/g,"");return s.length>0?s.slice(0,64):t}function ML(e){return IL(e,"unknown_session")}function RL(e){return`session.${ML(e)}.chat`}function Xh(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 Zh(e){const t=new Map;return e.forEach((s,r)=>t.set(s.messageId,r)),t}function zc(e){const t=e.ordered.length;return{...e.meta,coverage:{...e.meta.coverage,totalMessageCount:t,returnedMessageCount:t},messages:e.ordered}}class PL{constructor(){ze(this,"sessions",new Map)}apply(t){if(t.reset){if(!t.meta)return null;const o=[...t.upserts].sort(Xh),a={meta:t.meta,byId:new Map(o.map(i=>[i.messageId,i])),ordered:o,indexOf:Zh(o)};return this.sessions.set(t.sessionId,a),{sessionId:t.sessionId,view:zc(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(Xh),s.indexOf=Zh(s.ordered)}return{sessionId:t.sessionId,view:zc(s),reset:!1}}view(t){const s=this.sessions.get(t);return s?zc(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 EL="transcript_topics_available",DL=256;function LL(e){if(!e||typeof e!="object")return null;const t=e;if(t.type!==EL||!Array.isArray(t.topics)||t.topics.length>DL)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 OL(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(RL(o)))}const $L=4096;function FL(e){return typeof e.isOpen=="function"?e.isOpen():e.readyState===1||e.readyState==="open"}function HL(e,t,s={}){const r=s.preOpenQueueCap??$L,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(qc("queue_overflow"))};return t.onmessage=d=>{if(a)return;const m=d.data;typeof m=="string"&&(FL(e)?(o.length>0&&i(),e.send(m)):o.length<r?o.push(m):l())},e.addEventListener("message",d=>{if(a)return;const m=d.data;typeof m=="string"&&t.postMessage(m)}),e.addEventListener("open",()=>{a||(i(),t.postMessage(qc("transport_open")))}),e.addEventListener("close",()=>{a||(a=!0,o.length=0,t.postMessage(qc("transport_closed")))}),{pendingCount(){return o.length},close(){a||(a=!0,o.length=0,t.onmessage=null)}}}function BL(e,t){var m,u,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]),(u=(m=r.port1).start)==null||u.call(m),(p=(h=o.port1).start)==null||p.call(h);const i=new PL;o.port1.onmessage=b=>{var f,x;if(hD(b.data)){const g=i.apply(b.data);g&&((f=t.onView)==null||f.call(t,g));return}pD(b.data)&&((x=t.onBaseRequest)==null||x.call(t,b.data.sessionId))};let l=HL(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(fD(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 Sx="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Uint8Array.from(Sx,e=>e.charCodeAt(0));const WL=new Uint8Array(256);for(let e=0;e<64;e++)WL[Sx.charCodeAt(e)]=e;new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;new globalThis.TextDecoder;function UL(){if(typeof window>"u"||typeof Worker>"u"||typeof WebSocket>"u")return()=>{};const e=iD(window.location,Hi()),t=new mD({createSocket:()=>new WebSocket(e),startHost:(s,r,o)=>BL(s,{writerId:nD,sessionKey:"transcript",onView:r,onBaseRequest:o,createWorker:()=>new Worker(new URL("/assets/transcript-worker-entry-BYUOYOUE.js",import.meta.url),{type:"module"}),onOverflow:()=>console.warn("[Transcript] standalone lane pre-open queue overflow — channel reset")}),collectInterest:jC,subscribeInterest:NC,applyView:(s,r,o)=>wC(s,r,o),requestBase:SC,subscribeTopicsAvailable:uD,selectResubscribe:OL,setTimer:(s,r)=>setTimeout(s,r),clearTimer:s=>clearTimeout(s),now:()=>Date.now(),log:s=>console.warn(s)});return t.start(),()=>t.stop()}function KL(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,s=Hi();return s?`${t}?token=${encodeURIComponent(s)}`:t}const ma=KL(),ep=3e3,qL=3e4;let kn=null,zL=0;const ri=new Map;let As=null,uo=null,tp=null;const VL="standalone_hello";function GL(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Qr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function YL(e){return e==="connected"?"connected":e}async function mo(e,t,s){const r=Gb(e,s||{}),o=kn;if(o&&o.readyState===WebSocket.OPEN){const a=`req_${++zL}_${Date.now()}`;return new Promise((i,l)=>{const d=setTimeout(()=>{ri.delete(a),l(new Error(`WS command timeout: ${t}`))},3e4);ri.set(a,{resolve:m=>{clearTimeout(d),i(m)},reject:m=>{clearTimeout(d),l(m)}}),o.send(JSON.stringify({type:"command",requestId:a,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function oi(e,t){const s=kn;if(!s||s.readyState!==WebSocket.OPEN||!lD(t))return!1;try{return s.send(JSON.stringify(t)),!0}catch{return!1}}function kx(e,t,s){const r=kn;if(!r||r.readyState!==WebSocket.OPEN)return!1;const o=Gb(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}}En.registerPtyInputSender(kx);En.registerDataSender((e,t)=>oi(e,t));class QL{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 mo(this.daemonId,t,s)}async sendInput(t,s){return mo(this.daemonId,"cdp_remote_action",{action:t,params:s,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,As&&(clearInterval(As),As=null);const s=async()=>{if(this.hasCommandChannel)try{const r=await mo(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());En.emitScreenshot(this.daemonId,o)}}catch{}};s(),As=setInterval(s,2e3)}stopScreenshots(t){As&&(clearInterval(As),As=null)}}let gn=null;function JL(e){return(!gn||gn.daemonId!==e)&&(gn=new QL(e)),gn}function XL({children:e}){const t=c.useRef(lr()),s=lr();t.current=s;const{setUserName:r}=Bv(),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),uo==null||uo(x,g)},[]),m=c.useRef(null),u=c.useRef(),h=c.useRef(ep),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 _,k;if(!p.current||((_=m.current)==null?void 0:_.readyState)===WebSocket.OPEN||((k=m.current)==null?void 0:k.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${ma}...`),Qr("connect_attempt",{url:ma,reason:f.current,delayMs:h.current});let w;try{w=new WebSocket(ma)}catch(v){console.error("[Standalone WS] Failed to create WebSocket:",v),g();return}m.current=w,w.onopen=()=>{if(!p.current){w.close();return}d("connected"),h.current=ep,Qr("open",{url:ma,reason:f.current}),$n.resubscribeAll({sendData:oi}),console.log("[Standalone WS] Connected")},kn=w,w.onmessage=v=>{var y,j;try{const N=JSON.parse(v.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const R=ri.get(N.requestId);R&&(ri.delete(N.requestId),N.type==="error"?R.reject(new Error(((y=N.data)==null?void 0:y.message)||"Command failed")):R.resolve(N.data));return}if(N.type==="session_output"){const R=N.sessionId||N.cliId||N.cliType;R&&En.emitSessionOutput(R,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){En.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}const A=LL(N);if(A){dD(A);return}if(eD(N,tp,Ze,kC))return;if(N.type==="topic_update"){const R=N.update;R&&$n.publish(R);return}if(N.type===VL&&typeof N.daemonId=="string"&&N.daemonId){const R=N.daemonId;tp=R,wl(R,typeof N.wireVersion=="number"?N.wireVersion:null);const P=JL(R);En.register(R,P),En.setState(R,"connected"),d("connected",R),i.current!==R&&((j=a.current)==null||j.call(a),i.current=R,a.current=$n.subscribe({sendData:oi},R,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${R}`,params:{includeSessions:!0}},M=>{const E=t.current.getIdes(),C=E.find(O=>O.id===R),I=Jf(M.status,{daemonId:R,existingDaemon:C,existingEntries:E,timestamp:M.timestamp});GL("metadata",{daemonId:R,seq:M.seq,sessions:(M.status.sessions||[]).map(O=>({id:O.id,providerType:O.providerType,status:O.status,unread:O.unread,inboxBucket:O.inboxBucket}))}),I.length>0&&t.current.injectEntries(I,{authoritativeDaemonIds:[R]}),t.current.markLoaded(),M.userName&&o.current&&o.current(M.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},w.onclose=v=>{p.current&&(gn==null||gn.stopScreenshots(),gn&&En.setState(gn.daemonId,"disconnected"),d("disconnected"),m.current=null,f.current=`close:${v.code}${v.wasClean?":clean":":unclean"}`,Qr("close",{code:v.code,reason:v.reason||"",wasClean:v.wasClean}),g())},w.onerror=v=>{b.current||!p.current||(f.current="error",Qr("error",{message:v instanceof Event?"event":String(v),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",v))}}function g(){if(!p.current)return;clearTimeout(u.current);const w=h.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),Qr("schedule_reconnect",{reason:f.current,delayMs:w}),u.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,qL),x()},w)}x();const S=UL();return()=>{var w;S(),p.current=!1,b.current=!0,(w=a.current)==null||w.call(a),a.current=null,i.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,kn=null),gn&&(gn.stopScreenshots(),En.unregister(gn.daemonId))}},[]),n.jsx(n.Fragment,{children:e})}function ZL({children:e}){const[t,s]=c.useState("disconnected"),[r,o]=c.useState(null);c.useEffect(()=>(uo=(i,l)=>{s(i),l&&o(l)},()=>{uo=null}),[]);const a=c.useMemo(()=>{const i=t==="connected",l=YL(t),d={};return r&&(d[r]=l),d.standalone=l,{wsStatus:t,isConnected:i,connectionStates:d,usesP2P:!1}},[t,r]);return n.jsx(Hv,{connectionOverrides:a,children:n.jsx(XL,{children:e})})}const jx="adhdev_standalone_font_preferences",Fs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Bi=[{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"}],vo=[{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"}],e5=new Set(Bi.map(e=>e.id)),t5=new Set(vo.map(e=>e.id));function Dn(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Ta("chat",t.chat),code:Ta("code",t.code),terminal:Ta("terminal",t.terminal)}}function Ta(e,t){const s=Fs[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"?e5:t5).has(o)?o==="custom"?a?{preset:"custom",customFamily:a}:s:{preset:o}:s}function Ia(e,t){var o;const s=Ta(e,t);if(s.preset==="custom"&&s.customFamily)return s.customFamily;const r=e==="chat"?Bi:vo;return((o=r.find(a=>a.id===s.preset))==null?void 0:o.family)||r[0].family}function n5(e){const t=Dn(e),s=Ia("chat",t.chat),r=Ia("code",t.code),o=Ia("terminal",t.terminal);return{"--chat-font-family":s,"--chat-code-font-family":r,"--chat-terminal-font-family":o,"--chat-tool-font-family":o}}function Ms(e,t=document.documentElement){const s=Dn(e),r=n5(s);t.setAttribute("data-standalone-fonts","custom");for(const[o,a]of Object.entries(r))t.style.setProperty(o,a);return s}function Jl(e){const t=Dn(e);try{localStorage.setItem(jx,JSON.stringify(t))}catch{}return t}function s5(){try{const e=localStorage.getItem(jx);if(e)return Dn(JSON.parse(e))}catch{}return Fs}function r5(){return Ms(s5())}function Jr(e,t,s){const r=e==="chat"?Bi:vo,o=r.find(a=>a.id===t)||r[0];return o.labelKey&&s?s(o.labelKey,o.label):o.label}function o5({children:e}){const t=qs(),s=ai(),{t:r}=pe("common"),o=c.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:n.jsx(Cp,{}),label:r("nav.dashboard"),active:s.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:n.jsx(dr,{}),label:r("nav.machines"),active:s.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:n.jsx(Ln,{}),label:r("nav.mesh"),active:s.pathname.startsWith("/mesh")||s.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"notifications",path:"/notifications",icon:n.jsx(gs,{}),label:r("nav.notifications"),active:s.pathname.startsWith("/notifications"),onSelect:()=>t("/notifications")},{id:"settings",path:"/settings",icon:n.jsx(yr,{}),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(_p,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("nav.docs")},{id:"about",label:r("nav.about"),icon:n.jsx(So,{}),active:s.pathname==="/about",onSelect:()=>t("/about"),title:r("nav.about")}],[s.pathname,t,r]);return n.jsx(_A,{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.73"]}),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 a5(){const e=qs(),{sendCommand:t}=xt(),{ides:s}=xn(),r=c.useMemo(()=>s.filter(o=>o.daemonMode||o.type==="adhdev-daemon").map(o=>o),[s]);return n.jsx(JE,{daemons:r,features:Xg,sendCommand:t,unwrapResult:o=>o,normalizeMesh:o=>o,onClose:()=>e("/mesh")})}const i5=[{icon:n.jsx(dr,{size:16}),key:"localFirst"},{icon:n.jsx(Cn,{size:16}),key:"chatRelay"},{icon:n.jsx(ad,{size:16}),key:"screenshots"},{icon:n.jsx(Hn,{size:16}),key:"remoteControl"},{icon:n.jsx(ur,{size:16}),key:"multiIde"},{icon:n.jsx(_p,{size:16}),key:"cli"}],c5=[{icon:n.jsx(di,{size:16}),key:"anywhere"},{icon:n.jsx(Cp,{size:16}),key:"p2pStream"},{icon:n.jsx(gs,{size:16}),key:"mobileNotifications"},{icon:n.jsx(Jv,{size:16}),key:"restApi"},{icon:n.jsx(Zv,{size:16}),key:"enterpriseControls"}],l5=[{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 d5(){const{t:e}=pe("common");return n.jsxs(Mo,{icon:n.jsx(So,{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.73"]}),children:[n.jsx(gt,{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(gt,{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:i5.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(gt,{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:mA.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:pA.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:hA.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(gt,{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:c5.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(gt,{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:l5.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(Ri,{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 Vc(e,t,s){return{...e,[t]:s}}function Gc({surface:e,title:t,description:s,value:r,options:o,onChange:a}){const{t:i}=pe("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(tt,{content:s,size:12})]}),n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(MA,{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:Ia(e,r)})]})]})]})}function u5({value:e,savedValue:t,saving:s=!1,error:r,notice:o,onChange:a,onSave:i,onResetToSaved:l,onResetToDefaults:d}){const{t:m}=pe("common"),u=JSON.stringify(e)!==JSON.stringify(t);return n.jsxs("div",{className:"flex flex-col gap-4",children:[r&&n.jsx(Ft,{variant:"error",children:r}),o&&n.jsx(Ft,{variant:"success",children:o}),n.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[n.jsx(Gc,{surface:"chat",title:m("standalone.fonts.chat"),description:m("standalone.fonts.chatDescription"),value:e.chat,options:Bi,onChange:h=>a(Vc(e,"chat",h))}),n.jsx(Gc,{surface:"code",title:m("standalone.fonts.code"),description:m("standalone.fonts.codeDescription"),value:e.code,options:vo,onChange:h=>a(Vc(e,"code",h))}),n.jsx(Gc,{surface:"terminal",title:m("standalone.fonts.terminal"),description:m("standalone.fonts.terminalDescription"),value:e.terminal,options:vo,onChange:h=>a(Vc(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:[m("standalone.fonts.livePreview"),n.jsx(tt,{size:12,content:[m("standalone.fonts.previewSummary",{chat:Jr("chat",e.chat.preset,m),code:Jr("code",e.code.preset,m),terminal:Jr("terminal",e.terminal.preset,m)}),m("standalone.fonts.defaultsSummary",{chat:Jr("chat",Fs.chat.preset,m),code:Jr("code",Fs.code.preset,m)}),m("standalone.fonts.fontOverridesNotice")].join(`
115
115
 
116
- `)})]})}),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:m("standalone.fonts.previewNow")})]}),n.jsxs("div",{className:"chat-markdown",children:[n.jsx("p",{children:n.jsx(Ma,{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:m("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||!u,children:m(s?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),n.jsx(Qn,{type:"button",variant:"secondary",size:"sm",onClick:l,disabled:s||!u,children:m("standalone.fonts.revertToSaved")}),n.jsx(Qn,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:s,children:m("standalone.fonts.resetToDefaults")})]})]})}function m5(){const{t:e}=pe("common"),{ides:t}=xn(),s=t.find(U=>U.type==="adhdev-daemon"),{sendCommand:r}=xt(),{userName:o}=xn(),[a,i]=c.useState(o||""),[l,d]=c.useState(null),[m,u]=c.useState(null),[h,p]=c.useState(Fs),[b,f]=c.useState(!1),[x,g]=c.useState(""),[S,w]=c.useState(""),[_,k]=c.useState("127.0.0.1"),[v,y]=c.useState(""),[j,N]=c.useState(""),[A,R]=c.useState(""),[P,M]=c.useState(""),[E,C]=c.useState(""),[I,O]=c.useState(!1),D=async()=>{const K=await(await Pn("/auth/session")).json();d(K)},F=async()=>{const K=await(await Pn("/api/v1/standalone/preferences")).json();u(K),k(K.standaloneBindHost);const oe=Dn(K.standaloneFontPreferences);p(oe),Ms(oe),Jl(oe)};c.useEffect(()=>{o!==void 0&&i(o)},[o]),c.useEffect(()=>{Promise.all([D(),F()]).catch(U=>{M(U instanceof Error?U.message:String(U))})},[]),c.useEffect(()=>{Ms(h)},[h]);const z=U=>{const K=U.target.value.trim();s!=null&&s.id&&K!==o&&r(s.id,"set_user_name",{userName:K}).catch(console.error)},Z=async()=>{g(""),w(""),f(!0);try{const U=Dn(h),K=await Pn("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:U})}),oe=await K.json();if(!K.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save standalone font preferences");const ke=Dn(oe.standaloneFontPreferences);u(oe),p(ke),Ms(ke),Jl(ke),w(e("standalone.settings.fontsSaved"))}catch(U){g(U instanceof Error?U.message:String(U))}finally{f(!1)}},W=()=>{const U=Dn(m==null?void 0:m.standaloneFontPreferences);g(""),w(""),p(U),Ms(U)},T=()=>{g(""),w(""),p(Fs),Ms(Fs)},$=async()=>{M(""),C(""),O(!0);try{const U=await Pn("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:_})}),K=await U.json();if(!U.ok)throw new Error((K==null?void 0:K.error)||"Failed to save standalone network preference");u(K),k(K.standaloneBindHost),C(K.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(U){M(U instanceof Error?U.message:String(U))}finally{O(!1)}},H=async()=>{if(M(""),C(""),j.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(j!==A){M(e("standalone.settings.passwordMismatch"));return}O(!0);try{const U=await Pn("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:j})}),K=await U.json();if(!U.ok)throw new Error((K==null?void 0:K.error)||"Failed to save password");d(K),await F(),y(""),N(""),R(""),C(l!=null&&l.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),mx()}catch(U){M(U instanceof Error?U.message:String(U))}finally{O(!1)}},q=async()=>{M(""),C(""),O(!0);try{const U=await Pn("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),K=await U.json();if(!U.ok)throw new Error((K==null?void 0:K.error)||"Failed to clear password");d(K),await F(),y(""),N(""),R(""),C(e("standalone.settings.passwordDisabled"))}catch(U){M(U instanceof Error?U.message:String(U))}finally{O(!1)}};return n.jsxs(Mo,{icon:n.jsx(yr,{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(Ft,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),n.jsx(gt,{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.72"]})]}),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(rp,{to:`/machines/${s.id}`,state:{initialMachineTab:"providers"},className:"text-accent-primary hover:underline",children:e("standalone.settings.providersLink")})]})]})}),n.jsx(gt,{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(U=>n.jsxs("label",{className:`rounded-xl border px-4 py-3 text-sm flex gap-3 items-center cursor-pointer ${_===U.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:_===U.host,onChange:()=>k(U.host)}),n.jsx("span",{className:"font-medium text-text-primary",children:U.label}),n.jsx(tt,{content:U.hint})]},U.host))}),n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx(Qn,{type:"button",variant:"primary",size:"sm",onClick:()=>{$()},disabled:I,children:e(I?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),(m==null?void 0:m.standaloneBindHost)&&(m.currentBindHost||(l==null?void 0:l.boundHost))&&m.standaloneBindHost!==(m.currentBindHost||(l==null?void 0:l.boundHost))&&n.jsx(Gt,{content:e("standalone.settings.networkRestartHint",{host:m.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(gt,{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(Ft,{variant:"error",children:P}),E&&n.jsx(Ft,{variant:"success",children:E}),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:U=>y(U.target.value)}),n.jsx(Nn,{type:"password",placeholder:l!=null&&l.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:j,onChange:U=>N(U.target.value)}),n.jsx(Nn,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:A,onChange:U=>R(U.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:()=>{q()},disabled:I,children:e("standalone.settings.disablePassword")})]})]})}),n.jsx(gt,{title:e("standalone.settings.appearanceSection"),children:n.jsx(sT,{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(tt,{content:e("standalone.settings.fontsDescription"),size:12})]}),n.jsx(u5,{value:h,savedValue:Dn(m==null?void 0:m.standaloneFontPreferences),saving:b,error:x,notice:S,onChange:p,onSave:()=>{Z()},onResetToSaved:W,onResetToDefaults:T})]})})}),n.jsx(gt,{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(Qv,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel"),n.jsx(tt,{content:e("standalone.settings.displayNameHint")})]})}),n.jsx(Nn,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:a,onChange:U=>i(U.target.value),onBlur:z,onKeyDown:U=>{U.key==="Enter"&&U.currentTarget.blur()}})]})})}),n.jsxs(gt,{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(tt,{content:e("settings.coordinatorPrompts.sectionDescription"),size:12})]}),n.jsx(WA,{daemonId:s==null?void 0:s.id,embedded:!0})]})]})}const h5=["claude-cli","codex-cli","antigravity-cli"],no="adhdev_onboarding_done",p5=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"}],f5={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions"};function b5({onDone:e}){const{t}=pe("common"),[s,r]=c.useState([]),[o,a]=c.useState(new Set(h5)),[i,l]=c.useState(!0),[d,m]=c.useState(null),[u,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 j=>{if(!j.ok)throw new Error(`HTTP ${j.status}`);const N=await j.text();try{return JSON.parse(N)}catch{throw new Error(`unexpected non-JSON response (${j.headers.get("content-type")??"unknown content type"})`)}}).then(j=>{y||r(j.providers??[])}).catch(j=>{y||m(j instanceof Error?j.message:String(j))}).finally(()=>{y||l(!1)}),()=>{y=!0}},[]);const g=s.filter(y=>f==="all"||y.category===f),S=["cli","ide","extension"].map(y=>({category:y,items:g.filter(j=>j.category===y)})).filter(y=>y.items.length>0),w=c.useCallback(y=>{a(j=>{const N=new Set(j);return N.has(y)?N.delete(y):N.add(y),N})},[]),_=c.useCallback(async()=>{if(o.size===0){localStorage.setItem(no,"1"),e();return}h(!0);const y=[];for(const j of o)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:j})})).json().catch(()=>({}));y.push({type:j,ok:!!A.success,error:A.error})}catch(N){y.push({type:j,ok:!1,error:N instanceof Error?N.message:String(N)})}b(y),h(!1),y.every(j=>j.ok)&&localStorage.setItem(no,"1")},[o,e]),k=c.useCallback(()=>{localStorage.setItem(no,"1"),e()},[e]),v=c.useCallback(()=>{p&&p.every(y=>y.ok)?e():u||k()},[p,u,e,k]);return n.jsx(Eb,{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:k,disabled:u,children:t("standalone.onboarding.skip")}),n.jsx(Qn,{variant:"primary",size:"sm",onClick:()=>{p?(localStorage.setItem(no,"1"),e()):_()},disabled:u||!p&&o.size===0,children:u?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:p5.map(y=>{const j=y.key==="all"?s.length:s.filter(N=>N.category===y.key).length;return j===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:["(",j,")"]})]},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(Ft,{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:S.map(y=>n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:f5[y.category]??y.category}),n.jsx("div",{className:"grid gap-1.5",children:y.items.map(j=>{var P;const N=o.has(j.type),A=p==null?void 0:p.find(M=>M.type===j.type),R=((P=j.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 ${N?"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:N,onChange:()=>w(j.type),disabled:u,className:"shrink-0"}),n.jsx(Ii,{type:j.type,label:j.displayName??j.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:j.displayName}),R&&n.jsx("div",{className:"text-3xs text-text-muted truncate",children:R})]}),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"})})]},j.type)})})]},y.category))})]})})}function g5(){try{return localStorage.getItem(no)==="1"}catch{return!1}}const x5="/dashboard";function y5(e,t){const s=typeof t=="string"?t.trim():"";return{suppressed:e.startsWith(x5),sessionId:s||null}}bA();QA();pf();r5();const v5=gw({baseUrl:"",getToken:Hi});function w5({children:e}){const{t}=pe("common"),[s,r]=c.useState(null),[o,a]=c.useState(!0),[i,l]=c.useState(""),[d,m]=c.useState(""),[u,h]=c.useState(!1),p=async()=>{a(!0),m("");try{const x=await(await Pn("/auth/session")).json();r(x)}catch(f){m(f instanceof Error?f.message:String(f))}finally{a(!1)}};c.useEffect(()=>{p()},[]),c.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let f=!1;return(async()=>{try{const x=await Pn("/api/v1/standalone/preferences");if(!x.ok)return;const g=await x.json();if(f)return;const S=Dn(g.standaloneFontPreferences);Ms(S),Jl(S)}catch{}})(),()=>{f=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const b=async f=>{f.preventDefault(),h(!0),m("");try{const x=await Pn("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),g=await x.json();if(!x.ok)throw new Error((g==null?void 0:g.error)||"Login failed");r(g),l(""),mx()}catch(x){m(x instanceof Error?x.message:String(x))}finally{h(!1)}};return o?n.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):s?!s.required||s.authenticated?n.jsx(n.Fragment,{children:e}):n.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:n.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),n.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),s.hasPasswordAuth?n.jsxs("form",{className:"flex flex-col gap-3",onSubmit:b,children:[n.jsx(Nn,{type:"password",value:i,onChange:f=>l(f.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),n.jsx(Qn,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):n.jsx(Ft,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&n.jsx(Ft,{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 S5(){const{ides:e,initialLoaded:t}=xn(),s=e.filter(r=>r.type==="adhdev-daemon").map(r=>({id:r.id,machineId:r.machineId||r.id,nickname:xf(r)||void 0,hostname:bd(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(vP,{machines:s,initialLoaded:t??!0})}function np(){const{t:e}=pe("common"),{ides:t,initialLoaded:s}=xn();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(Jc,{to:`/machines/${r.id}`,replace:!0}):n.jsx(Jc,{to:"/dashboard",replace:!0})}function k5(){const[e,t]=c.useState(!1);return c.useEffect(()=>{let s=!1;if(!g5())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{s||(r.providers??[]).length===0&&(window.dispatchEvent(new Event($l)),t(!0))}).catch(()=>{}),()=>{s=!0}},[]),e?n.jsx(b5,{onDone:()=>t(!1)}):null}function j5(){const{t:e}=pe("common"),t=ai(),[s]=sp(),{suppressed:r,sessionId:o}=y5(t.pathname,s.get("activeTab")),{promptSession:a,hasActivePrompt:i,responseError:l,isSubmitting:d,submit:m,cancel:u,reopen:h}=xi(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(hd,{promptSession:a,isSubmitting:d,error:l,onSubmit:m,onCancel:u})]})}function N5(){const e=c.useMemo(()=>({sendCommand:mo,sendData:oi,sendPtyInput:kx}),[]);return n.jsx(Lx,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:n.jsx(Kv,{client:v5,children:n.jsx(w5,{children:n.jsx(ZL,{children:n.jsx(zv,{value:e,children:n.jsxs(bw,{sendDaemonCommand:mo,children:[n.jsx(j5,{}),n.jsx(T_,{}),n.jsxs(o5,{children:[n.jsx(k5,{}),n.jsxs(Ox,{children:[n.jsx(Rn,{path:"/dashboard",element:n.jsx(qM,{})}),n.jsx(Rn,{path:"/machine",element:n.jsx(np,{})}),n.jsx(Rn,{path:"/machines/:id",element:n.jsx(pP,{})}),n.jsx(Rn,{path:"/machines",element:n.jsx(np,{})}),n.jsx(Rn,{path:"/notifications",element:n.jsx(S5,{})}),n.jsx(Rn,{path:"/about",element:n.jsx(d5,{})}),n.jsx(Rn,{path:"/settings",element:n.jsx(m5,{})}),n.jsx(Rn,{path:"/mesh",element:n.jsx(VE,{children:n.jsx(qE,{})})}),n.jsx(Rn,{path:"/setup",element:n.jsx(a5,{})}),n.jsx(Rn,{path:"*",element:n.jsx(Jc,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Xj({connectionManager:En});function C5(){return n.jsx(rT,{fallback:n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",background:"var(--bg-primary)"},children:n.jsx(Zt,{})}),children:n.jsx(N5,{})})}$x(document.getElementById("root")).render(n.jsx(RA,{children:n.jsx(C5,{})}));export{nO as $,Md as A,Vr as B,q5 as C,Zb as D,G5 as E,Id as F,Km as G,K5 as H,Xt as I,lO as J,oO as K,T5 as L,rO as M,Ea as N,gS as O,Un as P,cx as Q,Ad as R,V5 as S,Gt as T,DA as U,FA as V,Xp as W,vr as X,Pt as Y,I5 as Z,sO as _,mr as a,O5 as a0,Y5 as a1,tO as a2,E5 as a3,Z5 as a4,J5 as a5,Ze as a6,X5 as a7,Mp as a8,R5 as a9,eO as aa,Q5 as ab,cO as ac,F5 as ad,Od as ae,Cp as af,ew as ag,Ln as ah,Td as ai,xt as aj,dO as ak,AP as al,No as am,pr as an,wt as ao,ii as ap,Yg as aq,Qg as ar,_P as as,CP as at,Bu as b,P5 as c,ol as d,W5 as e,U5 as f,ix as g,d1 as h,dl as i,M5 as j,hi as k,H5 as l,aO as m,z5 as n,iO as o,pi as p,Fi as q,Tb as r,B5 as s,L5 as t,Mi as u,tt as v,D5 as w,fr as x,Xc as y,$5 as z};
116
+ `)})]})}),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:m("standalone.fonts.previewNow")})]}),n.jsxs("div",{className:"chat-markdown",children:[n.jsx("p",{children:n.jsx(Ma,{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:m("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||!u,children:m(s?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),n.jsx(Qn,{type:"button",variant:"secondary",size:"sm",onClick:l,disabled:s||!u,children:m("standalone.fonts.revertToSaved")}),n.jsx(Qn,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:s,children:m("standalone.fonts.resetToDefaults")})]})]})}function m5(){const{t:e}=pe("common"),{ides:t}=xn(),s=t.find(U=>U.type==="adhdev-daemon"),{sendCommand:r}=xt(),{userName:o}=xn(),[a,i]=c.useState(o||""),[l,d]=c.useState(null),[m,u]=c.useState(null),[h,p]=c.useState(Fs),[b,f]=c.useState(!1),[x,g]=c.useState(""),[S,w]=c.useState(""),[_,k]=c.useState("127.0.0.1"),[v,y]=c.useState(""),[j,N]=c.useState(""),[A,R]=c.useState(""),[P,M]=c.useState(""),[E,C]=c.useState(""),[I,O]=c.useState(!1),D=async()=>{const K=await(await Pn("/auth/session")).json();d(K)},F=async()=>{const K=await(await Pn("/api/v1/standalone/preferences")).json();u(K),k(K.standaloneBindHost);const oe=Dn(K.standaloneFontPreferences);p(oe),Ms(oe),Jl(oe)};c.useEffect(()=>{o!==void 0&&i(o)},[o]),c.useEffect(()=>{Promise.all([D(),F()]).catch(U=>{M(U instanceof Error?U.message:String(U))})},[]),c.useEffect(()=>{Ms(h)},[h]);const z=U=>{const K=U.target.value.trim();s!=null&&s.id&&K!==o&&r(s.id,"set_user_name",{userName:K}).catch(console.error)},Z=async()=>{g(""),w(""),f(!0);try{const U=Dn(h),K=await Pn("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:U})}),oe=await K.json();if(!K.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save standalone font preferences");const ke=Dn(oe.standaloneFontPreferences);u(oe),p(ke),Ms(ke),Jl(ke),w(e("standalone.settings.fontsSaved"))}catch(U){g(U instanceof Error?U.message:String(U))}finally{f(!1)}},W=()=>{const U=Dn(m==null?void 0:m.standaloneFontPreferences);g(""),w(""),p(U),Ms(U)},T=()=>{g(""),w(""),p(Fs),Ms(Fs)},$=async()=>{M(""),C(""),O(!0);try{const U=await Pn("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:_})}),K=await U.json();if(!U.ok)throw new Error((K==null?void 0:K.error)||"Failed to save standalone network preference");u(K),k(K.standaloneBindHost),C(K.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(U){M(U instanceof Error?U.message:String(U))}finally{O(!1)}},H=async()=>{if(M(""),C(""),j.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(j!==A){M(e("standalone.settings.passwordMismatch"));return}O(!0);try{const U=await Pn("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:j})}),K=await U.json();if(!U.ok)throw new Error((K==null?void 0:K.error)||"Failed to save password");d(K),await F(),y(""),N(""),R(""),C(l!=null&&l.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),mx()}catch(U){M(U instanceof Error?U.message:String(U))}finally{O(!1)}},q=async()=>{M(""),C(""),O(!0);try{const U=await Pn("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),K=await U.json();if(!U.ok)throw new Error((K==null?void 0:K.error)||"Failed to clear password");d(K),await F(),y(""),N(""),R(""),C(e("standalone.settings.passwordDisabled"))}catch(U){M(U instanceof Error?U.message:String(U))}finally{O(!1)}};return n.jsxs(Mo,{icon:n.jsx(yr,{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(Ft,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),n.jsx(gt,{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.73"]})]}),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(rp,{to:`/machines/${s.id}`,state:{initialMachineTab:"providers"},className:"text-accent-primary hover:underline",children:e("standalone.settings.providersLink")})]})]})}),n.jsx(gt,{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(U=>n.jsxs("label",{className:`rounded-xl border px-4 py-3 text-sm flex gap-3 items-center cursor-pointer ${_===U.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:_===U.host,onChange:()=>k(U.host)}),n.jsx("span",{className:"font-medium text-text-primary",children:U.label}),n.jsx(tt,{content:U.hint})]},U.host))}),n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx(Qn,{type:"button",variant:"primary",size:"sm",onClick:()=>{$()},disabled:I,children:e(I?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),(m==null?void 0:m.standaloneBindHost)&&(m.currentBindHost||(l==null?void 0:l.boundHost))&&m.standaloneBindHost!==(m.currentBindHost||(l==null?void 0:l.boundHost))&&n.jsx(Gt,{content:e("standalone.settings.networkRestartHint",{host:m.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(gt,{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(Ft,{variant:"error",children:P}),E&&n.jsx(Ft,{variant:"success",children:E}),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:U=>y(U.target.value)}),n.jsx(Nn,{type:"password",placeholder:l!=null&&l.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:j,onChange:U=>N(U.target.value)}),n.jsx(Nn,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:A,onChange:U=>R(U.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:()=>{q()},disabled:I,children:e("standalone.settings.disablePassword")})]})]})}),n.jsx(gt,{title:e("standalone.settings.appearanceSection"),children:n.jsx(sT,{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(tt,{content:e("standalone.settings.fontsDescription"),size:12})]}),n.jsx(u5,{value:h,savedValue:Dn(m==null?void 0:m.standaloneFontPreferences),saving:b,error:x,notice:S,onChange:p,onSave:()=>{Z()},onResetToSaved:W,onResetToDefaults:T})]})})}),n.jsx(gt,{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(Qv,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel"),n.jsx(tt,{content:e("standalone.settings.displayNameHint")})]})}),n.jsx(Nn,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:a,onChange:U=>i(U.target.value),onBlur:z,onKeyDown:U=>{U.key==="Enter"&&U.currentTarget.blur()}})]})})}),n.jsxs(gt,{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(tt,{content:e("settings.coordinatorPrompts.sectionDescription"),size:12})]}),n.jsx(WA,{daemonId:s==null?void 0:s.id,embedded:!0})]})]})}const h5=["claude-cli","codex-cli","antigravity-cli"],no="adhdev_onboarding_done",p5=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"}],f5={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions"};function b5({onDone:e}){const{t}=pe("common"),[s,r]=c.useState([]),[o,a]=c.useState(new Set(h5)),[i,l]=c.useState(!0),[d,m]=c.useState(null),[u,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 j=>{if(!j.ok)throw new Error(`HTTP ${j.status}`);const N=await j.text();try{return JSON.parse(N)}catch{throw new Error(`unexpected non-JSON response (${j.headers.get("content-type")??"unknown content type"})`)}}).then(j=>{y||r(j.providers??[])}).catch(j=>{y||m(j instanceof Error?j.message:String(j))}).finally(()=>{y||l(!1)}),()=>{y=!0}},[]);const g=s.filter(y=>f==="all"||y.category===f),S=["cli","ide","extension"].map(y=>({category:y,items:g.filter(j=>j.category===y)})).filter(y=>y.items.length>0),w=c.useCallback(y=>{a(j=>{const N=new Set(j);return N.has(y)?N.delete(y):N.add(y),N})},[]),_=c.useCallback(async()=>{if(o.size===0){localStorage.setItem(no,"1"),e();return}h(!0);const y=[];for(const j of o)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:j})})).json().catch(()=>({}));y.push({type:j,ok:!!A.success,error:A.error})}catch(N){y.push({type:j,ok:!1,error:N instanceof Error?N.message:String(N)})}b(y),h(!1),y.every(j=>j.ok)&&localStorage.setItem(no,"1")},[o,e]),k=c.useCallback(()=>{localStorage.setItem(no,"1"),e()},[e]),v=c.useCallback(()=>{p&&p.every(y=>y.ok)?e():u||k()},[p,u,e,k]);return n.jsx(Eb,{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:k,disabled:u,children:t("standalone.onboarding.skip")}),n.jsx(Qn,{variant:"primary",size:"sm",onClick:()=>{p?(localStorage.setItem(no,"1"),e()):_()},disabled:u||!p&&o.size===0,children:u?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:p5.map(y=>{const j=y.key==="all"?s.length:s.filter(N=>N.category===y.key).length;return j===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:["(",j,")"]})]},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(Ft,{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:S.map(y=>n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:f5[y.category]??y.category}),n.jsx("div",{className:"grid gap-1.5",children:y.items.map(j=>{var P;const N=o.has(j.type),A=p==null?void 0:p.find(M=>M.type===j.type),R=((P=j.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 ${N?"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:N,onChange:()=>w(j.type),disabled:u,className:"shrink-0"}),n.jsx(Ii,{type:j.type,label:j.displayName??j.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:j.displayName}),R&&n.jsx("div",{className:"text-3xs text-text-muted truncate",children:R})]}),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"})})]},j.type)})})]},y.category))})]})})}function g5(){try{return localStorage.getItem(no)==="1"}catch{return!1}}const x5="/dashboard";function y5(e,t){const s=typeof t=="string"?t.trim():"";return{suppressed:e.startsWith(x5),sessionId:s||null}}bA();QA();pf();r5();const v5=gw({baseUrl:"",getToken:Hi});function w5({children:e}){const{t}=pe("common"),[s,r]=c.useState(null),[o,a]=c.useState(!0),[i,l]=c.useState(""),[d,m]=c.useState(""),[u,h]=c.useState(!1),p=async()=>{a(!0),m("");try{const x=await(await Pn("/auth/session")).json();r(x)}catch(f){m(f instanceof Error?f.message:String(f))}finally{a(!1)}};c.useEffect(()=>{p()},[]),c.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let f=!1;return(async()=>{try{const x=await Pn("/api/v1/standalone/preferences");if(!x.ok)return;const g=await x.json();if(f)return;const S=Dn(g.standaloneFontPreferences);Ms(S),Jl(S)}catch{}})(),()=>{f=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const b=async f=>{f.preventDefault(),h(!0),m("");try{const x=await Pn("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),g=await x.json();if(!x.ok)throw new Error((g==null?void 0:g.error)||"Login failed");r(g),l(""),mx()}catch(x){m(x instanceof Error?x.message:String(x))}finally{h(!1)}};return o?n.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):s?!s.required||s.authenticated?n.jsx(n.Fragment,{children:e}):n.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:n.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),n.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),s.hasPasswordAuth?n.jsxs("form",{className:"flex flex-col gap-3",onSubmit:b,children:[n.jsx(Nn,{type:"password",value:i,onChange:f=>l(f.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),n.jsx(Qn,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):n.jsx(Ft,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&n.jsx(Ft,{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 S5(){const{ides:e,initialLoaded:t}=xn(),s=e.filter(r=>r.type==="adhdev-daemon").map(r=>({id:r.id,machineId:r.machineId||r.id,nickname:xf(r)||void 0,hostname:bd(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(vP,{machines:s,initialLoaded:t??!0})}function np(){const{t:e}=pe("common"),{ides:t,initialLoaded:s}=xn();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(Jc,{to:`/machines/${r.id}`,replace:!0}):n.jsx(Jc,{to:"/dashboard",replace:!0})}function k5(){const[e,t]=c.useState(!1);return c.useEffect(()=>{let s=!1;if(!g5())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{s||(r.providers??[]).length===0&&(window.dispatchEvent(new Event($l)),t(!0))}).catch(()=>{}),()=>{s=!0}},[]),e?n.jsx(b5,{onDone:()=>t(!1)}):null}function j5(){const{t:e}=pe("common"),t=ai(),[s]=sp(),{suppressed:r,sessionId:o}=y5(t.pathname,s.get("activeTab")),{promptSession:a,hasActivePrompt:i,responseError:l,isSubmitting:d,submit:m,cancel:u,reopen:h}=xi(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(hd,{promptSession:a,isSubmitting:d,error:l,onSubmit:m,onCancel:u})]})}function N5(){const e=c.useMemo(()=>({sendCommand:mo,sendData:oi,sendPtyInput:kx}),[]);return n.jsx(Lx,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:n.jsx(Kv,{client:v5,children:n.jsx(w5,{children:n.jsx(ZL,{children:n.jsx(zv,{value:e,children:n.jsxs(bw,{sendDaemonCommand:mo,children:[n.jsx(j5,{}),n.jsx(T_,{}),n.jsxs(o5,{children:[n.jsx(k5,{}),n.jsxs(Ox,{children:[n.jsx(Rn,{path:"/dashboard",element:n.jsx(qM,{})}),n.jsx(Rn,{path:"/machine",element:n.jsx(np,{})}),n.jsx(Rn,{path:"/machines/:id",element:n.jsx(pP,{})}),n.jsx(Rn,{path:"/machines",element:n.jsx(np,{})}),n.jsx(Rn,{path:"/notifications",element:n.jsx(S5,{})}),n.jsx(Rn,{path:"/about",element:n.jsx(d5,{})}),n.jsx(Rn,{path:"/settings",element:n.jsx(m5,{})}),n.jsx(Rn,{path:"/mesh",element:n.jsx(VE,{children:n.jsx(qE,{})})}),n.jsx(Rn,{path:"/setup",element:n.jsx(a5,{})}),n.jsx(Rn,{path:"*",element:n.jsx(Jc,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Xj({connectionManager:En});function C5(){return n.jsx(rT,{fallback:n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",background:"var(--bg-primary)"},children:n.jsx(Zt,{})}),children:n.jsx(N5,{})})}$x(document.getElementById("root")).render(n.jsx(RA,{children:n.jsx(C5,{})}));export{nO as $,Md as A,Vr as B,q5 as C,Zb as D,G5 as E,Id as F,Km as G,K5 as H,Xt as I,lO as J,oO as K,T5 as L,rO as M,Ea as N,gS as O,Un as P,cx as Q,Ad as R,V5 as S,Gt as T,DA as U,FA as V,Xp as W,vr as X,Pt as Y,I5 as Z,sO as _,mr as a,O5 as a0,Y5 as a1,tO as a2,E5 as a3,Z5 as a4,J5 as a5,Ze as a6,X5 as a7,Mp as a8,R5 as a9,eO as aa,Q5 as ab,cO as ac,F5 as ad,Od as ae,Cp as af,ew as ag,Ln as ah,Td as ai,xt as aj,dO as ak,AP as al,No as am,pr as an,wt as ao,ii as ap,Yg as aq,Qg as ar,_P as as,CP as at,Bu as b,P5 as c,ol as d,W5 as e,U5 as f,ix as g,d1 as h,dl as i,M5 as j,hi as k,H5 as l,aO as m,z5 as n,iO as o,pi as p,Fi as q,Tb as r,B5 as s,L5 as t,Mi as u,tt as v,D5 as w,fr as x,Xc as y,$5 as z};