@adhdev/daemon-standalone 1.0.68 → 1.0.70

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-1-miPo1F.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-Mhmnf_CX.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:`
@@ -28,7 +28,7 @@ var Nx=Object.defineProperty;var Cx=(e,t,s)=>t in e?Nx(e,t,{enumerable:!0,config
28
28
  50% { transform: translateY(-7px); }
29
29
  100% { transform: translateY(0px); }
30
30
  }
31
- `})]})}function ll(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.promptId!="string"||!t.promptId.trim()||typeof t.providerType!="string"||!t.providerType.trim()||!Array.isArray(t.questions)||t.questions.length===0?null:t}function pS(e){var t;return ll(e.activeInteractivePrompt)||ll((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function fS(e){return e.sessionId||e.instanceId||e.id}function bS(e,t){let s;t==null?s={}:typeof t=="string"?s={sessionId:t,includeHidden:!!t.trim()}:s=t;const r=typeof s.sessionId=="string"?s.sessionId.trim():"",o=s.includeHidden===!0;for(const a of e){const i=pS(a);if(!i)continue;const l=fS(a);if(r&&r!==l&&r!==a.id||!o&&a.surfaceHidden===!0)continue;return{daemonId:a.daemonId||a.id.split(":")[0]||a.id,sessionId:l,routeId:a.id,providerType:a.type,title:a.title||a.cliName||a.type,prompt:i}}return null}function ef(e,t){var r;const s={};for(const o of e.questions){const a=t[o.questionId]||{},i=Array.from(new Set((a.selectedLabels||[]).map(d=>d.trim()).filter(Boolean))),l=(r=a.freeformText)==null?void 0:r.trim();s[o.questionId]={selectedLabels:i,...l?{freeformText:l}:{}}}return{promptId:e.promptId,answers:s}}function Un({children:e}){return typeof document>"u"?n.jsx(n.Fragment,{children:e}):Wn.createPortal(e,document.body)}function gS(e,t){const s=r=>{r.key==="Escape"&&(r.stopPropagation(),t())};return e.addEventListener("keydown",s,!0),()=>e.removeEventListener("keydown",s,!0)}const Ou='a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',xS=200;function $u(e){const t={};for(const s of(e==null?void 0:e.prompt.questions)||[])t[s.questionId]={selectedLabels:[],freeformText:""};return t}function Fu(e,t){var s,r;return!!((s=t==null?void 0:t.freeformText)!=null&&s.trim())||(((r=t==null?void 0:t.selectedLabels)==null?void 0:r.length)||0)>0||e.options.length===0&&!!e.allowFreeform}function yS({label:e,description:t,selected:s,multiSelect:r,disabled:o,onClick:a}){return n.jsx("button",{type:"button",disabled:o,role:r?"checkbox":"radio","aria-checked":s,onClick:a,className:`w-full text-left rounded-md border px-3 py-2 transition ${s?"border-accent-primary bg-accent-primary/15 text-text-primary":"border-border-default bg-surface-secondary text-text-secondary hover:bg-surface-secondary hover:text-text-primary"} ${o?"cursor-not-allowed opacity-60":""}`,children:n.jsxs("span",{className:"flex items-start gap-2",children:[n.jsx("span",{className:`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border ${r?"rounded-sm":"rounded-full"} ${s?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-subtle"}`,children:s?r?n.jsx(ui,{size:12}):n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-accent-on-primary"}):null}),n.jsxs("span",{className:"min-w-0",children:[n.jsx("span",{className:"block text-sm font-semibold leading-5",children:e}),t&&n.jsx("span",{className:"mt-0.5 line-clamp-3 block text-xs leading-5 text-text-muted",children:t})]})]})})}function hd({promptSession:e,isSubmitting:t=!1,error:s,onSubmit:r,onCancel:o}){const{t:a}=pe("common"),[i,l]=c.useState(()=>$u(e)),[d,m]=c.useState(!1),u=c.useRef(!1),h=c.useRef(null),p="interactive-prompt-title";c.useEffect(()=>{if(l($u(e)),m(!1),u.current=!1,!(e==null?void 0:e.prompt.promptId))return;const A=setTimeout(()=>{u.current=!0,m(!0)},xS);return()=>clearTimeout(A)},[e==null?void 0:e.prompt.promptId]),c.useEffect(()=>{if(e)return gS(window,o)},[e,o]);const b=e==null?void 0:e.prompt.promptId,f=e==null?void 0:e.sessionId,x=e==null?void 0:e.daemonId;c.useEffect(()=>{if(!b)return;const N=h.current;if(!N)return;const A=()=>Array.from(N.querySelectorAll(Ou)),R=P=>{if(P.key!=="Tab")return;const M=A();if(M.length===0)return;const E=M[0],C=M[M.length-1],I=document.activeElement;P.shiftKey?(I===E||!N.contains(I))&&(P.preventDefault(),C.focus()):(I===C||!N.contains(I))&&(P.preventDefault(),E.focus())};return N.addEventListener("keydown",R),()=>N.removeEventListener("keydown",R)},[b,f,x]),c.useEffect(()=>{if(!b)return;const N=h.current;if(!N)return;const A=document.activeElement;if(A instanceof Node&&N.contains(A))return;(Array.from(N.querySelectorAll(Ou))[0]||N).focus()},[b,f,x]);const g=(e==null?void 0:e.prompt.questions)||[],S=g.length===1,w=c.useMemo(()=>e?e.prompt.questions.every(N=>Fu(N,i[N.questionId])):!1,[e,i]),_=c.useMemo(()=>g.filter(N=>!Fu(N,i[N.questionId])).length,[g,i]);if(!e)return null;const k=(N,A)=>{l(R=>{const P=R[N.questionId]||{selectedLabels:[]},M=P.selectedLabels||[],E=N.multiSelect?M.includes(A)?M.filter(C=>C!==A):[...M,A]:[A];return{...R,[N.questionId]:{...P,selectedLabels:E}}})},v=(N,A)=>{l(R=>({...R,[N]:{...R[N]||{selectedLabels:[]},freeformText:A}}))},y=()=>{!w||t||!u.current||r(i)},j=ef(e.prompt,i);return n.jsx(Un,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50 px-4 pt-[calc(24px+env(safe-area-inset-top,0px))] pb-[calc(24px+env(safe-area-inset-bottom,0px))]",children:n.jsxs("div",{ref:h,role:"dialog","aria-modal":"true","aria-labelledby":p,tabIndex:-1,className:"flex max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-48px)] w-full max-w-2xl flex-col overflow-hidden rounded-lg border border-border-default bg-surface-primary shadow-2xl outline-none",children:[n.jsxs("div",{className:"flex shrink-0 items-start justify-between gap-4 border-b border-border-default px-5 py-4",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-normal text-status-warning",children:[n.jsx(Xt,{size:15})," ",a("interactivePrompt.actionRequired")]}),n.jsx("h2",{id:p,className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("button",{type:"button",onClick:o,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":a("interactivePrompt.cancelAria"),children:n.jsx(Pt,{size:16})})})]}),n.jsxs("div",{className:"interactive-prompt-question-list min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-4",children:[g.map((N,A)=>{var M,E;const R=((M=j.answers[N.questionId])==null?void 0:M.selectedLabels)||[],P=N.multiSelect?a("interactivePrompt.multipleChoice"):a("interactivePrompt.singleChoice");return n.jsxs("section",{className:A>0?"space-y-3 border-t border-border-default pt-5":"space-y-3",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[N.header&&n.jsx("span",{className:"text-xs font-semibold uppercase tracking-normal text-text-muted",children:N.header}),n.jsx("span",{className:"rounded-full border border-border-subtle px-2 py-0.5 text-3xs font-semibold uppercase tracking-normal text-text-muted",children:P})]}),n.jsxs("div",{className:"mt-1 text-sm font-semibold text-text-primary",children:[S?"":`${A+1}. `,N.question]}),N.multiSelect&&N.options.length>0&&n.jsx("div",{className:"mt-0.5 text-xs text-text-muted",children:a("interactivePrompt.selectAllThatApply")})]}),n.jsx("div",{className:"grid gap-2",role:N.multiSelect?"group":"radiogroup","aria-label":N.question,children:N.options.map(C=>n.jsx(yS,{label:C.label,description:C.description||C.preview,selected:R.includes(C.label),multiSelect:N.multiSelect,disabled:t,onClick:()=>k(N,C.label)},C.label))}),N.allowFreeform&&n.jsxs("label",{className:"block",children:[n.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:a("interactivePrompt.other")}),n.jsx("textarea",{value:((E=i[N.questionId])==null?void 0:E.freeformText)||"",disabled:t,onChange:C=>v(N.questionId,C.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-default bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]},N.questionId)}),s&&n.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:s})]}),n.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border-default px-5 pt-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))]",children:[!w&&_>0&&n.jsx("span",{className:"mr-auto text-xs text-text-muted",children:a("interactivePrompt.answersRequired",{count:_})}),n.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:o,disabled:t,children:a("common.cancel")}),n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:y,disabled:!w||t||!d,children:a(t?"interactivePrompt.submitting":"interactivePrompt.submit")})]})]})})})}function tn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var tf=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress"];tn(tf);var vS=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];tn(vS);var wS=["p2p_offer","p2p_ice"];tn(wS);var SS=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];tn(SS);var kS=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","daemon_mesh_command","p2p_offer","p2p_ice"];tn(kS);var jS=["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"];tn(jS);var NS=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],CS=[...tf,...NS];tn(CS);var _S=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];tn(_S);var AS=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];tn(AS);var TS=["p2p_ready","p2p_answer","p2p_ice"];tn(TS);var IS=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];tn(IS);var MS=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];tn(MS);var nf=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];tn(nf);var sf=["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"];tn(sf);[...new Set([...nf,...sf])];var rf=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"],RS={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"},PS=new Set(rf);function ES(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return PS.has(t)?t:RS[t]??null}var DS=["pending","assigned","completed","failed","cancelled"],LS=["completed","failed","cancelled"],OS=["code_change","validation","live_debug_readonly","launch_app","convergence"],$S=["low","normal","high"],FS=["when_idle","interrupt"],of=["completed","blocked","failed"],HS=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function Sr(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Sr(DS);Sr(LS);Sr(OS);Sr($S);Sr(FS);Sr(of);var BS=["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"],WS=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(WS);var US=["mesh_queue","mesh_direct","plain"],KS=["delivered","queued"],qS=["local","p2p"],zS=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],VS=["default","native_source"],GS=["restart","live_holder"],YS=["approval","choice"],QS=["approved","rejected","answered"],JS=["modal_button","auto_approve","prompt_answer"],XS=["genuine","weak"],ZS=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],e0=["completed","aborted"],t0=["alive","unknown","read_failed","dead"],n0=["auth_failed","billing_failed"],s0=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],r0=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],o0=["completed","failed"],a0=["operator_update","refine_terminal","validation_terminal"],i0=["delivered","queued","duplicate"],c0=[...rf,"unknown"],l0=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],d0=["completed","failed","cancelled"],u0=["genuine","weak","tool_report","operator"],m0=["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"],af=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],Gs={t:"id"},Ys={t:"id",optional:!0},as={t:"bool"},Uo={t:"bool",optional:!0},Hu={t:"ms"},h0={t:"ms",optional:!0},Ko={t:"int",optional:!0},Mt=e=>({t:"enum",values:e}),Or=e=>({t:"enum",values:e,optional:!0}),p0={dispatch_accepted:{scope:Mt(US),messageId:Gs,meshId:Ys,nodeId:Ys,providerType:Ys,attemptNo:Ko,dispatchNonce:Ko,consumeProfile:Or(VS),maxTaskRetries:Ko,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:Gs,outcome:Mt(KS),via:Mt(qS)},delivery_refused:{messageId:Gs,reason:Mt(BS)},dispatch_failed:{workerAbsent:as,reason:Mt(zS),refusalCode:Ys},duplicate_dispatch_refusal:{holderSessionId:Gs,holderAttemptId:Ys},session_rebound:{toSessionId:Gs,reason:Mt(GS)},turn_started:{retro:as},suspension:{modal:Mt(YS),modalKey:Ys},suspension_resolved:{resolution:Mt(QS),via:Mt(JS)},turn_end:{strength:Mt(XS),afterFinalizationTimeout:Uo,hollow:Uo,summary:{t:"summary_ref",optional:!0},blockReason:Or(ZS),releasedByHardCap:Uo,nativeOutcome:Or(e0),live:{t:"live",optional:!0},reportExpected:Uo},transcript_final:{selfAttributing:as,nativeRead:as,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:h0},transcript_activity:{newestActivityAt:Hu},no_progress:{stalledMs:Hu,observedStatus:Mt(c0),finalAssistantPresent:as},liveness:{result:Mt(t0)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:Or(n0)},session_error:{reason:Mt(s0)},worker_report:{outcome:Mt(of),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:as,branchState:Or(HS),touchedFileCount:Ko},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:as,commitsSinceDispatch:{t:"int"},attributable:as},cancel:{reason:Mt(r0)},operator_status:{status:Mt(o0),reason:Mt(a0)},coordinator_ack:{notify:Mt(af),outcome:Mt(i0)},hold_expired:{holdId:Gs,reason:Mt(l0)}},f0=Object.keys(p0);function _o(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}_o(f0);_o(m0);_o(af);_o(d0);_o(u0);function es(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var b0=["applied","recorded","rejected"];es(b0);var g0=["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(g0);var x0=["completed","failed"];es(x0);var y0=["operator_update","refine_terminal","validation_terminal"];es(y0);var v0=["own","fleet"];es(v0);var w0=["active","paused","completed","abandoned"];es(w0);var S0=["provider_quirk","pattern_to_avoid","recovery_lesson"];es(S0);var k0=["coordinator","unknown"];es(k0);var j0=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];es(j0);var N0=["turn_observe","mesh_record","turn_cancel","operator_status","turn_query","mesh_index_query","mission_upsert","mission_query","note_upsert","note_forget","tool_call_record","ledger_query","mission_list_query","record_local","queue_query","queue_enqueue","queue_enqueue_batch","queue_cancel","queue_requeue","direct_dispatch_record","active_work_query","recovery_context_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];es(N0);function C0(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Jt(e,t){return C0(t==null?void 0:t.activeModal)?"waiting_approval":ES(e)??"idle"}function dl(e){return Jt(e)==="generating"}function Bu(e,t){return Jt(e,t)==="waiting_approval"}function _0(e){return(e==null?void 0:e.surfaceHidden)===!0}function A0(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function ws(e){const t=e.connectionState==="failed"||e.connectionState==="closed",s=e.connectionState==="connecting"||e.connectionState==="new",r=ci(e.status),o=Jt(e.status),a=o==="waiting_approval",i=o==="waiting_choice",l=xy(o);return{isReconnecting:t,isConnecting:s,isGenerating:r,isWaiting:a,isWaitingChoice:i,isErrored:l}}function T0(e){const t=!e.hasLiveSnapshot&&e.visibleMessageCount===0,{isGenerating:s}=ws(e),r=s&&(!t||Jt(e.status)==="generating");return{awaitingFirstView:t,showWorkingIndicator:r}}function Bs(e){return ws(e).isGenerating}function I0(e){let t=0;for(const s of e)Bs(s)&&t++;return t}function Wu(e){let t=0;return e.unread!==void 0&&(t+=1),e.lastSeenAt!==void 0&&(t+=1),e.lastUpdated!==void 0&&(t+=1),e.inboxBucket!==void 0&&(t+=1),e.surfaceHidden!==void 0&&(t+=1),e.muted!==void 0&&(t+=1),e.completionMarker!==void 0&&(t+=1),e.seenCompletionMarker!==void 0&&(t+=1),t}function M0(e,t){const s=e.lastUpdated||0,r=t.lastUpdated||0;if(r!==s)return r>s;const o=Wu(e),a=Wu(t);return a!==o?a>o:!1}function Uu(e,t,s){return e===void 0?t:t===void 0?e:s?t:e}function cf(e){const t=new Map,s=new Map,r=(o,a)=>{if(!o)return;const i=s.get(o),l=t.get(o),d=(a.lastUpdated||0)>((i==null?void 0:i.lastUpdated)||0),m=Uu(l==null?void 0:l.surfaceHidden,typeof a.surfaceHidden=="boolean"?a.surfaceHidden:void 0,d),u=Uu(l==null?void 0:l.muted,typeof a.muted=="boolean"?a.muted:void 0,d);if(i&&!M0(i,a)){l&&t.set(o,{...l,surfaceHidden:m,muted:u});return}s.set(o,a),t.set(o,{sessionId:o,...A0(a),surfaceHidden:m,muted:u})};for(const o of e)if(o.type!=="adhdev-daemon"){r(o.sessionId,o);for(const a of o.childSessions||[])r(a.id,a)}return t}function xs(e,t){if(e.sessionId){const s=t.get(e.sessionId);if(s)return s}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:void 0,muted:void 0,completionMarker:"",seenCompletionMarker:""}}function gi(e,t,s){const r=xs(e,t),o=ws(e),a=o.isReconnecting,i=o.isConnecting,l=o.isGenerating,d=o.isWaiting,m=o.isWaitingChoice,u=r.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d||m,h=r.inboxBucket==="working"||l,b=!!(r.inboxBucket==="task_complete"&&r.unread&&!(s!=null&&s.hideOpenTaskCompleteUnread&&(s!=null&&s.isOpenConversation)));return{unread:b,requiresAction:u,isWorking:h,isReconnecting:a,isConnecting:i,isGenerating:l,isWaiting:d,inboxBucket:u?"needs_attention":h?"working":b?"task_complete":"idle"}}function R0(e,t,s){return gi(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:s==null?void 0:s.isOpenConversation}).unread}function P0(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function E0(e){const t=(e==null?void 0:e.result)??e;return typeof(t==null?void 0:t.error)=="string"?t.error:"Interactive prompt response failed"}async function D0(e,t,s){const r=await s(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let o=`HTTP ${r.status}`;try{const a=await r.json();typeof(a==null?void 0:a.error)=="string"&&(o=a.error)}catch{}throw new Error(o)}}async function L0({promptSession:e,response:t,useP2PCommand:s,sendCommand:r,fetchImpl:o=fetch}){if(s){const a=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!P0(a))throw new Error(E0(a));return}await D0(e.sessionId,t,o)}let ul=null;const ml=new Set;function O0(e){return ml.add(e),()=>{ml.delete(e)}}function Ku(){return ul}function qo(e){if(ul!==e){ul=e;for(const t of ml)t()}}function xi(e,t){const{t:s}=pe("common"),{ides:r,isP2PActive:o,p2pStates:a}=xn(),{sendCommand:i}=xt(),l=c.useSyncExternalStore(O0,Ku,Ku),[d,m]=c.useState(!1),[u,h]=c.useState(null),p=c.useRef(!1),b=(t==null?void 0:t.includeHidden)===!0,f=c.useMemo(()=>bS(r,{sessionId:e,includeHidden:b}),[r,e,b]),x=!!f,g=c.useMemo(()=>f?f.prompt.promptId===l?null:f:null,[l,f]),S=(f==null?void 0:f.prompt.promptId)??null;c.useEffect(()=>{h(null)},[S]);const w=c.useCallback(async v=>{if(!g||p.current)return;p.current=!0;const y=ef(g.prompt,v);m(!0),h(null);try{const j=(a==null?void 0:a[g.daemonId])==="connected"||o===!0;await L0({promptSession:g,response:y,useP2PCommand:j,sendCommand:i}),qo(g.prompt.promptId)}catch(j){let N=j instanceof Error?j.message:String(j);throw N.includes(by)?(qo(g.prompt.promptId),h(s("interactivePrompt.errorReviewUnconfirmed",{defaultValue:"The answer keys reached the terminal, but the question is still on screen — the answer may not have been submitted. Check the terminal: if it was not submitted, answer there; resending from here could submit it twice."})),j):(N.includes(fy)&&(N=s("interactivePrompt.errorReviewPageNotFocused",{defaultValue:"The terminal is showing a different screen, so the answer was not submitted — check the terminal screen or close this and try again."})),h(N),j)}finally{m(!1),p.current=!1}},[o,a,g,i]),_=c.useCallback(()=>{g&&qo(g.prompt.promptId)},[g]),k=c.useCallback(()=>{if(qo(null),!f){h(s("interactivePrompt.errorUnavailable",{defaultValue:"Could not load the question — answer it in the terminal view instead."}));return}h(null)},[f,s]);return{promptSession:g,hasActivePrompt:x,responseError:u,isSubmitting:d,submit:w,cancel:_,reopen:k}}function lf(e){return e.sessionId??e.routeId}const sc=e=>e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*\(\s*\b(?:Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)\b(?:\s*\+\s*\w+)*\s*\)/gi,"").replace(/\s*\b(?:Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)\b(?:\s*\+\s*\w+)*/gi,"").trim(),$0=12e3;function F0(e){return/^always\b|\balways allow\b|\bdon'?t ask again\b|\ballow all\b|^yes,? and allow\b/.test(e)?"always":/^(run|approve|accept|yes|allow)/.test(e)?"primary":/^(reject|deny|delete|remove|abort|no)\b/.test(e)?"danger":"neutral"}function df({activeConv:e,onModalButton:t}){const{t:s}=pe(),[r,o]=c.useState(null),{hasActivePrompt:a,promptSession:i,reopen:l}=xi(lf(e));c.useEffect(()=>{o(null)},[e.modalMessage,e.status,e.connectionState]),c.useEffect(()=>{if(!r)return;const h=setTimeout(()=>o(null),$0);return()=>clearTimeout(h)},[r]);const d=ws(e);if(!d.isWaiting&&!d.isWaitingChoice||!e.modalButtons)return null;const m=h=>{r||(o(h),t(h))},u=()=>n.jsx("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:n.jsx("div",{className:"flex items-center gap-2",children:n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(Xt,{size:14}),s("approval.questionUnavailable",{defaultValue:"Question waiting — could not load it here. Answer it in the terminal view."})]})})});return a&&!i?u():a?n.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&n.jsx("div",{className:"text-2xs opacity-85 mb-1.5 line-clamp-3 max-w-full whitespace-pre-wrap break-words",title:e.modalMessage,children:e.modalMessage}),n.jsxs("div",{className:"flex justify-between items-center gap-2",children:[n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(Xt,{size:14})," ",s("approval.questionPending",{defaultValue:"Question waiting"})]}),n.jsx("button",{onClick:l,className:"btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold cursor-pointer whitespace-nowrap shrink-0",style:{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"},children:s("approval.answerQuestion",{defaultValue:"Answer the question"})})]})]}):d.isWaitingChoice?u():n.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&n.jsx("div",{className:"text-2xs opacity-85 mb-1.5 line-clamp-4 max-w-full whitespace-pre-wrap break-words",title:e.modalMessage,children:e.modalMessage}),n.jsxs("div",{className:"flex justify-between items-center",children:[n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(Xt,{size:14})," ",s(r?"approval.processing":"approval.actionRequired")]}),n.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((h,p)=>{const b=sc(h).toLowerCase(),f=F0(b),x=f==="always",g=f==="primary",S=f==="danger",w=r===h,_=r!==null;return n.jsx("button",{onClick:()=>m(h),disabled:_,title:x?s("approval.alwaysAllowWarning"):void 0,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${g?"font-extrabold":S?"bg-red-500/30 text-white font-semibold":x?"text-white/90 font-semibold":"text-white font-semibold"} ${_&&!w?"opacity-40":"opacity-100"} ${_?"cursor-not-allowed":"cursor-pointer"}`,style:g?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:x?{background:"transparent",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 55%, transparent)"}:S?void 0:{background:"color-mix(in srgb, black 18%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 35%, transparent)"},children:w?n.jsx(mr,{size:12}):x?n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Xt,{size:11}),sc(h)]}):sc(h)},p)})})]})]})}const pd="adhdev_controls_bar_visible",hl="adhdev:controlsbarvisibilitychange";function rc(e){if(!e)return!1;try{return e.getItem(pd)==="1"}catch{return!1}}function H0(e,t){if(t)try{t.setItem(pd,e?"1":"0")}catch{}}function B0(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(hl,{detail:{visible:e}}))}function fd(){const[e,t]=c.useState(()=>typeof window>"u"?!1:rc(window.localStorage)),s=c.useRef(e),r=c.useCallback((i,l=!0)=>{s.current=i,t(i),typeof window<"u"&&H0(i,window.localStorage),l&&B0(i)},[]);c.useEffect(()=>{const i=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:rc(window.localStorage);s.current=u,t(u)},l=d=>{if(d.key!==pd)return;const m=rc(window.localStorage);s.current=m,t(m)};return window.addEventListener(hl,i),window.addEventListener("storage",l),()=>{window.removeEventListener(hl,i),window.removeEventListener("storage",l)}},[]);const o=c.useCallback(i=>{r(i)},[r]),a=c.useCallback(()=>{r(!s.current)},[r]);return{isVisible:e,setVisibility:o,toggleVisibility:a}}const uf=["en","ko","ja","zh-CN","es"],Es="en",ks=[{code:"en",label:"English"},{code:"ko",label:"한국어"},{code:"ja",label:"日本語"},{code:"zh-CN",label:"中文(简体)"},{code:"es",label:"Español"}];function Rs(e){return typeof e=="string"&&uf.includes(e)}function W0(e){if(!e)return Es;const t=e.trim().toLowerCase();if(!t)return Es;if(t==="zh"||t.startsWith("zh-")||t.startsWith("zh_"))return"zh-CN";const s=t.split(/[-_]/)[0];return s==="en"?"en":s==="ko"?"ko":s==="ja"?"ja":s==="es"?"es":Es}const U0={runFailed:"Couldn't run {{label}}",updateFailed:"Couldn't update {{label}}",loadOptionsFailed:"Couldn't load {{label}} options"},K0={unknown:"Unknown",starting:"Starting",stopped:"Stopped",failed:"Failed",idle:"Idle",generating:"Working",awaitingApproval:"Needs approval"},q0={label:"Language",select:"Select language"},z0={copy:"Copy",no:"No",yes:"Yes",diagnostics:"Diagnostics",done:"Done",edit:"Edit",copied:"Copied",copyId:"Copy ID",technicalDetails:"Technical details",saved:"Saved",refresh:"Refresh",moreInfo:"More info",closeDialog:"Close dialog",noRecords:"No records found.",close:"Close",back:"Back",cancel:"Cancel",confirm:"Confirm",confirmTitle:"Are you sure?"},V0={loadingShort:"Loading…",loadingDashboard:"Loading your dashboard...",machinesConnectedCount:"{{connected}}/{{total}} machines connected",disconnected:"Disconnected",connected:"Connected",connectedToDashboard:"Connected to dashboard",networkOffline:"Network offline",reconnecting:"Reconnecting",sessionExpired:"Session expired.",logInAgain:"Log in again",connectionFailed:"Connection failed — refresh the page or try again shortly.",reconnectNow:"Reconnect now"},G0={details:"Details",label:{success:"Done",warning:"Attention",info:"Update"},dismiss:"Dismiss"},Y0={actionNeeded:"Action needed",taskComplete:"Task complete",markRead:"Mark read",markUnread:"Mark unread",delete:"Delete"},Q0={browser:{error:"Stopped with an error",finished:"Finished",approvalWithMessage:"Needs approval: {{message}}",approval:"Needs approval",questionWithMessage:"Question: {{message}}",question:"Waiting for your answer"},taskCompleted:"{{label}} agent task completed",taskCompletedWithDuration:"{{label}} agent task completed ({{duration}})",approvalNeeded:"{{label}} approval needed",questionNeeded:"{{label}} question needs an answer",noProgress:"{{label}} agent shows no progress",noProgressWithDuration:"{{label}} agent shows no progress ({{minutes}}m)",noProgressTitle:"{{label}} — No Progress",noProgressBody:"Agent has shown no progress for over {{duration}}",viewRequest:"{{requester}} wants to view your session",viewRequestTitle:"View Request",viewRequestApproved:"View request approved",viewRequestDeclined:"{{target}} declined your view request",someoneRequester:"A team member",someoneTarget:"Team member"},J0={header:{moreActions:"More actions",title:"Dashboard",guide:"Dashboard guide",guideOpen:"Open dashboard guide",guideShort:"Guide",openGitStatus:"Open git status",meshGraph:"Mesh graph",stopCliProcess:"Stop CLI process",chatHistory:"Chat History",remoteControl:"Remote Control",generating:"generating",activityInbox:"Notifications"},hidden:{title:"Hidden tabs",dragHint:"Drag a tab here to hide it.",resetPanels:"Reset panels",restoreAll:"Restore all",hideCurrentTab:"Hide current tab",empty:"No hidden tabs.",resetPanelsConfirm:"Move every floating or popout panel back into the main dashboard grid?"},inbox:{unread:"Unread",read:"Read",empty:"No pending activity."},metaChips:{queuePending:"{{count}} waiting",queueTooltip:"Queue: {{pending}} waiting, {{assigned}} assigned, {{completed}} completed, {{failed}} failed"},meshRole:{coordinator:"Coordinator",worker:"Worker",coordinatorFor:"Coordinator for {{mesh}}",workerFor:"Worker for {{mesh}}",coordinatorUnknownMesh:"Mesh coordinator",workerUnknownMesh:"Mesh worker",openMeshGraph:"Open mesh graph"},versionBanner:{restarting:"restarting",upgrading:"updating…",unknownVersion:"unknown",updateAvailable:"Update available",required:"required",retry:"retry"},remoteDialog:{liveRemoteView:"Live remote view",remoteUnavailable:"Remote view unavailable",remoteOnly:"Remote only",splitView:"Split view",remoteFallback:"Remote",history:"History"},guide:{title:"Dashboard guide",subtitle:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune.",close:"Close dashboard guide",tabs:{overview:"Overview",quickstart:"Quick start",shortcuts:"Shortcuts"},overview:{whatLivesWhere:{title:"What lives where",tabsLabel:"Tabs:",tabsText:"active sessions across IDE and CLI agents.",hiddenLabel:"Hidden tabs:",hiddenText:"stash sessions you do not want in the main strip but still want to keep around.",inboxLabel:"Activity inbox:",inboxText:"sessions waiting for approval or finished tasks you have not reviewed yet.",cliToggleLabel:"CLI view toggle:",cliToggleText:"switch a PTY session between terminal and chat rendering without relaunching it."},usefulFlows:{title:"Useful flows",reviewLabel:"Review notifications:",reviewText:"open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane.",clutterLabel:"Reduce clutter:",clutterText:"hide less important sessions instead of closing them, then restore from hidden tabs when needed.",splitLabel:"Split work:",splitText:"keep one pane active for input and let secondary panes stay read-only until you focus them.",detachedLabel:"Detached views:",detachedText:"float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor.",dockingLabel:"Docking:",dockingText:"use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard.",perTabLabel:"Per-tab shortcuts:",perTabText:"right-click a Dockview tab to assign a direct shortcut for that specific session.",approvalLabel:"Approval buttons:",approvalText:"use {{keys}} for the first three visible approval actions on the active session."}},quickstart:{desktop:{title:"Desktop quick start",step1:"Start from the machine or workspace flow first. Pick or save a workspace before launching CLI sessions.",step2:"Keep the main strip focused on active work and push overflow into Hidden tabs.",step3:"Use the inbox for approval-required or completed sessions instead of scanning every tab.",step4:"Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."},mobile:{title:"Mobile quick start",step1:"Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions.",step2:"Start from the machine screen, choose a workspace, then launch IDE or CLI from there.",step3:"Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."}},shortcuts:{sections:{all:"All",workspace:"Workspace",panes:"Panes",approvals:"Approvals"},disableAll:"Disable all",resetToDefaults:"Reset to defaults",default:"Default:",listening:"Listening...",set:"Set",disable:"Disable",off:"Off",footer:"Use modifier shortcuts like {{keys}}, or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs.",resetConfirm:"Reset all dashboard shortcuts back to their default values?",setListening:"Listening"}},shortcutDefs:{openShortcutHelp:{label:"Open shortcuts",description:"Show the keyboard shortcuts panel."},openNewSession:{label:"New session",description:"Open the new session launcher."},hideCurrentTab:{label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs."},toggleHiddenTabs:{label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover."},openHistoryForActiveTab:{label:"Open history",description:"Open history for the active session."},openRemoteForActiveTab:{label:"Open remote",description:"Open remote control for the active session when available."},floatActiveTab:{label:"Float active tab",description:"Move the active tab into a floating panel."},popoutActiveTab:{label:"Open active tab in new window",description:"Move the active tab into a detached popout window."},dockActiveTab:{label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window."},splitActiveTabRight:{label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it."},splitActiveTabDown:{label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it."},focusLeftPane:{label:"Focus left pane",description:"Move focus to the pane on the left."},focusRightPane:{label:"Focus right pane",description:"Move focus to the pane on the right."},focusUpPane:{label:"Focus upper pane",description:"Move focus to the pane above."},focusDownPane:{label:"Focus lower pane",description:"Move focus to the pane below."},moveActiveTabToLeftPane:{label:"Move active tab left",description:"Move the active tab into the pane on the left."},moveActiveTabToRightPane:{label:"Move active tab right",description:"Move the active tab into the pane on the right."},moveActiveTabToUpPane:{label:"Move active tab up",description:"Move the active tab into the pane above."},moveActiveTabToDownPane:{label:"Move active tab down",description:"Move the active tab into the pane below."},triggerPrimaryApprovalAction:{label:"Approval action 1",description:"Press the first approval/action button for the active session."},triggerSecondaryApprovalAction:{label:"Approval action 2",description:"Press the second approval/action button for the active session."},triggerTertiaryApprovalAction:{label:"Approval action 3",description:"Press the third approval/action button for the active session."},setActiveTabShortcut:{label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab."},selectPreviousGroupTab:{label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group."},selectNextGroupTab:{label:"Next tab in group",description:"Move to the next tab inside the active Dockview group."},toggleCliView:{label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view."}}},X0={stopProcess:"Stop CLI process",title:"Stop {{agent}}?",gracefulDescription:"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.",forceOnlyDescription:"This provider does not support graceful stop. Force Stop will end the runtime immediately.",stop:"Stop",forceStop:"Force Stop"},Z0={processing:"PROCESSING...",actionRequired:"ACTION REQUIRED",alwaysAllowWarning:"Grants this permission permanently — future runs will not ask again",questionPending:"QUESTION WAITING",answerQuestion:"Answer the question"},ek={loading:"Loading…",launchModelChanged:"{{from}} → {{to}} (changed)",launchModelSource:{user:"chosen",remembered:"remembered",mesh_slot:"mesh slot",task_override:"task override",provider_default:"default"}},tk={noMeshesShort:"No meshes on this machine",noProvidersShort:"No agents available",advancedOptions:"Advanced options",agent:"Agent",defaultResolvesTo:"Default resolves to {{model}}",title:"Start session",close:"Close new session dialog",detectedLocally:"Detected locally",availableToOpen:"Available to open",machine:"Machine",selectMachine:"Select machine {{name}}",workspace:"Workspace",browse:"Browse…",launchTargetType:"Launch target type",modeWorkspace:"Workspace",modeWorkspaceDesc:"Normal session",modeMesh:"Mesh",modeMeshDesc:"Coordinator session",homeDirectory:"Home directory",customFolder:"Custom folder…",launchWithoutWorkspace:"Launch without a workspace.",selectWorkspaceFolder:"Select a workspace folder.",selectFolder:"Select folder",saving:"Saving…",saveWorkspace:"Save workspace",loadingMeshes:"Loading meshes…",noMeshes:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker.",mesh:"Mesh",repoMesh:"Repo mesh",nodeCount_one:"{{count}} node",nodeCount_other:"{{count}} nodes",coordinatorWorkspace:"Coordinator workspace: {{path}}",noProviders:"Nothing usable on the selected machine. If an agent is installed outside the default location, set its executable path in Machine → Providers.",startupArguments:"Startup arguments",optionalFlags:"Optional flags...",autoApproveMode:"Auto-approve mode",autoApproveModeDescription:"Choose how this session handles approval prompts.",autoApproveLegacy:"Auto approve",autoApproveLegacyDescription:"Automatically accept supported approval prompts for this session.",autoApproveRisk:{safe:"Safe",caution:"Caution",dangerous:"Dangerous"},dangerousModeTitle:"Confirm dangerous auto-approve mode",dangerousModeFallbackWarning:"This mode can bypass approval or sandbox protections. Use it only in a trusted workspace.",dangerousModeRisk:"Risk",dangerousModeLaunchArgs:"Injected launch arguments",dangerousModeConfirm:"Use dangerous mode",modelAndThinking:"Model & thinking (optional)",model:"Model",providerDefault:"(provider default)",custom:"Custom…",typeModelName:"Type a model name",backToModelList:"← Back to model list",thinkingLevel:"Thinking level",selectWorkspaceTitle:"Select workspace",start:"Start",starting:"Starting…",startMeshCoordinator:"Start mesh coordinator",startingCoordinator:"Starting coordinator…",startIde:"Start IDE",startingIde:"Starting IDE…",startFresh:"Start fresh",startingFresh:"Starting fresh…",resumeSavedHistory:"Resume saved history",resumingSavedHistory:"Resuming saved history…",errorLoadMeshes:"Could not load meshes",errorLoadFolder:"Could not load folder",errorLoadSavedSessions:"Could not load saved sessions",errorSaveWorkspace:"Could not save workspace",workspaceSaved:"Workspace saved. It will appear in the list once the machine state refreshes.",errorManualMcpSetup:"Manual MCP setup required before this provider can act as mesh coordinator.",errorStartMeshCoordinator:"Could not start mesh coordinator",errorStartSession:"Could not start session",errorResumeSession:"Could not resume session",errorWorkspaceContextRequired:"Choose a workspace — a directory, a saved/default workspace, or your home directory — before launching.",defaultWorkspace:"Default workspace"},nk={undo:"Undo",hiddenToast:"Hid {{title}}",moreActionsFor:"More actions for {{title}}",loading:"Loading...",loadingSubtitle:"Fetching your machines and sessions.",machines:"Machines",chats:"Chats",networkOffline:"Network offline",sessionExpired:"Session expired",reconnecting:"Reconnecting",waitingForNetwork:"Waiting for network…",pleaseLogInAgain:"Please log in again.",restoringConnection:"Restoring the server connection…",waitingForDaemon:"Waiting for your daemon",connectYourMachines:"Connect your machines",waitingForDaemonSubtitle:"Start the ADHDev daemon to connect.",connectYourMachinesSubtitle:"Install ADHDev on a machine and sign in.",newCount:"{{count}} new",chatCount_one:"{{count}} chat",chatCount_other:"{{count}} chats",idle:"Idle",unreadSuffix:" · {{count}} unread",noActiveChats:"No active chats",needsAttention:"Needs attention",taskComplete:"Task complete",workingNow:"Working now",earlier:"Earlier",connecting:"Connecting…",connectingSubtitle:"Waiting for server connection before loading conversations.",noMachinesConnected:"No machines connected",noMachinesSubtitle:"Connect a machine from the Machines tab.",noConversations:"No conversations yet",allCaughtUp:"All caught up.",hiddenTabs:"Hidden tabs",collapsedCount_one:"{{count}} collapsed conversation",collapsedCount_other:"{{count}} collapsed conversations",generatingCount:"{{count}} generating",collapsedGeneratingSuffix:" · {{count}} generating",restoreAll:"Restore all",hide:"Hide",reconnectingItem:"Reconnecting…",connectingItem:"Connecting…",actionNeeded:"Action needed",done:"Done",openMeshGraphFor:"Open mesh graph for {{title}}",openLiveMeshGraph:"Open live repo mesh graph",stopSessionTitle:"Stop session (terminates the agent)"},sk={hint:{daemon:{followUp:"Needs follow-up",merged:"Merged",notMergeable:"Can't merge yet — changes or conflicts",cleanup:"Merged — worktree can be cleaned up",needsMerge:"Pushed — ready to merge",blockedReview:"Needs review before merging"},anchorEmpty:"No workspace on the default branch",anchorWorkspaces:"{{count}} workspace(s) on {{branch}}",anchorNeedsFollowUp:"{{count}} on {{branch}} need follow-up",submoduleSynced:"{{path}} is in sync",submoduleChanged:"{{path}} has local changes",submoduleOutOfSync:"{{path}} is out of sync with its parent",gitAgeUnknown:"Git status age unknown",staleGit:"Git status is over 5 min old",missingSubmodule:"Submodule not reported: {{paths}}",noGitYet:"No git status received yet",noGitYetOnline:"Online — git status not received yet",waitingForGit:"Waiting for git status…",nodeError:"Node reported an error",upstreamUnverified:"Upstream not verified yet",noUpstream:"Push {{branch}} to set its upstream",mergeConflicts:"Resolve merge conflicts",detachedHead:"Detached HEAD — check out a branch",notGitRepo:"Not a git repository",noGitStatus:"No git status yet"},sessionCleanup:{stopAndDeleteHint:"Stop matching sessions, then remove their chat records.",stopAndDelete:"Stop and delete sessions",deleteStoppedHint:"Clear finished or stopped chats without stopping running sessions.",deleteStopped:"Delete stopped sessions only",stopHint:"Stop running session processes but keep their chat records.",stop:"Stop running sessions only",preserveHint:"Keep finished chat history and leave running sessions alone.",preserve:"Keep history and running sessions"},nodeHealth:{failed:"Failed",completed:"Completed",assigned:"Assigned",pending:"Pending",enabled:"Enabled",unknown:"Connecting…",wrongBranch:"Other branch",degradedHint:"The connection to this machine is down or timed out — often temporary. Wait a moment or reconnect the machine.",degraded:"Unreachable",offline:"Offline",dirty:"Uncommitted changes",online:"Online"},activity:{noKeyEvents:"No recent key events",showKey:"Show key events only",showAll:"Show all activity",nodeChanged:"Machine joined or left",worktreeCreated:"Worktree created",nodeJoined:"Node joined",nodeRemoved:"Node removed",sessionStarted:"Agent started",needsInput:"Needs your input",taskFailed:"Task failed",taskFinished:"Task finished",taskStarted:"Task started"},drift:{clean:"Clean",conflicts:"conflicts",submoduleOutOfSync_other:"{{count}} submodules out of sync",submoduleOutOfSync_one:"{{count}} submodule out of sync",submoduleChanged_other:"{{count}} submodules changed",submoduleChanged_one:"{{count}} submodule changed",changed_other:"{{count}} changed",changed_one:"{{count}} changed",upstreamUnverified:"upstream unverified",noGit:"No git info",probePending:"Checking git…"},graph:{slowLinkChip:"Slow link",observationUnreachableChip:"Unreachable",observationStaleChip:"Stale",remoteBadge:"remote",activeSessionAria:"active session",observationAsOf:"as of {{age}} ago",observationRefreshing:"as of {{age}} ago · refreshing",observationFetching:"fetching state…",observationUnreachable:"unreachable · last known {{age}} ago",observationUnreachableNoState:"unreachable · no state yet"},statusTab:{v2ScopeHint:"Pending events by scope",providerSkewHint:"Providers running different versions on different nodes",providerSkew:"{{count}} provider version mismatch",v2RatioHint:"Share of pending coordinator events in the current message format",daemonBuildHint:"Exact daemon build (version@commit) running on this node",quotaFailedHint:"This machine couldn't read this provider's usage",quotaOkNoWindowHint:"Read successfully — this provider has no percentage limit to show",nodeCountHint:"Mesh nodes (workspaces/worktrees) on this machine — they share one plan quota",nodeCount_other:"{{count}} nodes",nodeCount_one:"{{count}} node",daemonVersionHint:"Daemon version running on this machine",blockedReasonHint:"Why this node can't take a new code-changing task right now",providerCapHint:"Active tasks per provider on this node vs its declared limit",priorityHint:"Scheduling preference (higher is preferred)",priority:"priority {{value}}",loadHint:"Active tasks assigned to this node",load:"load {{count}}",readonlyCapHint:"Active read-only investigation tasks vs their limit (2× the write limit)",readonlyCap:"read-only {{active}}/{{max}}",writeCapHint:"Active tasks that change code vs the mesh-wide parallel limit",writeCap:"write {{active}}/{{max}}"},manualSetup:{restartHint:"Start a fresh CLI session after editing config.",configPath:"Config path:",format:"Format:",server:"Server:",titleFor:"Manual MCP setup required for {{provider}}",title:"Manual MCP setup required"},help:{toggleAria:"Mesh help",toggleTitle:"Mesh concept help",regionAria:"Mesh concept help",kicker:"Help",title:"Mesh concepts at a glance",close:"Close help",sections:{node:{term:"Node",summary:"A workspace participating in the mesh — a repo checkout or an isolated git worktree.",details:["Base node vs worktree clone node — a clone isolates parallel work without conflicts.","Shows health (online/offline) alongside git state (branch · ahead/behind · dirty).","Multiple nodes can share the same daemon."]},p2p:{term:"P2P connection",summary:"How the selected coordinator reaches each remote node over WebRTC.",details:["direct — a direct host/STUN path; lowest latency.","relay — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed — no live P2P link from the coordinator right now.","P2P connectivity is shown as transport and RTT chips on each node card (and in the node detail panel), not as a graph edge."]},session:{term:"Session",summary:"An agent CLI session running on a node.",details:["status = idle / generating / waiting_approval.","Distinguishes coordinator sessions (which dispatch and collect work) from delegated worker sessions (which do the work)."]},task:{term:"Task",summary:"A single unit of work handled by the queue-based pull model.",details:["States: pending → assigned → completed / failed / cancelled.","Idle nodes claim from the queue automatically; direct dispatch targets a specific session."]},mission:{term:"Mission",summary:"A multi-task batch aimed at one goal, and the durable record of that effort.",details:["States: active / paused / completed / abandoned.","Progress is derived from the states of its member tasks."]},refinery:{term:"Refinery (refine)",summary:"The process of safely converging and merging a worktree branch into the base.",details:["Config-driven (.adhdev/refine.*) — guarded by a patch-equivalence preflight and a no-op guard.","ff-only by principle; no force-push.","If a submodule commit is unreachable from origin it must be published → classified as blocked_review."]},completion:{term:"Completion model",summary:"Completion of delegated work is persisted to the queue (pending-events).",details:["The coordinator learns of completion via periodic polling or events.","Because it is persisted to the queue, completion signals are never lost."]},convergence:{term:"Branch convergence states",summary:"After worktree work, each branch is classified into exactly one final state.",details:["merged_to_main — merged into the base.","pushed_feature_branch_needs_merge — pushed, awaiting merge.","blocked_review — held back by review/reachability issues.","cleanup_candidate — ready to clean up.","not_mergeable — cannot be merged."]},blueprint:{term:"Blueprint",summary:"The plan view: live queue work and its task dependencies on one canvas.",details:["One axis — dependency depth, left to right. Root tasks are ordered newest first.","Cards carry their own time, so position never has to encode it.","Finished dependency chains fold away so live work stays in view."]},routingPreview:{term:"Routing preview",summary:"A read-only forecast of where a hypothetical task would land.",details:["Shown per difficulty; a task pinned to a node gets its own pinned preview (📌).","It is a prediction, not the owner — a card that already ran shows its real node below."]},worktree:{term:"Worktree node",summary:"A node backed by a git worktree rather than the main checkout.",details:["Labelled by its branch (⎇). Lets several tasks run on one machine without sharing a branch.","Orphan worktrees are reported as cleanup candidates and are never deleted automatically."]}}},approvals:{title:"PENDING APPROVALS",empty:"No sessions are awaiting an approval decision.",sessionFallback:"session {{id}}",approve:"Approve",reject:"Reject",waitingFor:"Waiting for {{duration}}"},difficulty:{easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"},panel:{outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusCoordinator:"coordinator",statusWorker:"worker",upstreamUnverified:"unverified",needsFollowUp:"needs follow-up",refined:"refined",tooltipLocalChanges:"Local changes",tooltipHasConflicts:"Has conflicts",tooltipOutOfSync:"Out of sync",tooltipNeedsFollowUp:"Needs follow-up",tooltipUpstreamUnverified:"Upstream unverified",tooltipRefineCompleted:"refine completed",tooltipRefinedBranch:"refined {{branch}}",tooltipP2PRelayed:"P2P link relayed through TURN (slower path)",tooltipPrefixStatus:"Status:",tooltipPrefixBranch:"Branch:",tooltipPrefixNote:"Note:",defaultBranch:"default branch",submoduleSynced:"synced",moreChats_one:"+{{count}} more chat",moreChats_other:"+{{count}} more chats",remote:"remote",chats_one:"{{count}} chat",chats_other:"{{count}} chats",generatingCount:"{{count}} generating",coordinatorAttached:"coordinator attached",coordinators:"{{count}} coordinators",workers_one:"{{count}} worker",workers_other:"{{count}} workers",sampledStatus:"sampled status"},legendEdge:{parentBranch:"default branch",cloneLink:"worktree clone",worktreeLink:"same branch",submoduleLink:"submodule",sessionLink:"session",orphanLink:"needs follow-up"},attention:{submoduleDrift:"submodule drift",submoduleDirty:"submodule dirty",conflictsPresent:"conflicts present",dirtyWorkspace:"dirty workspace",upstreamUnverified:"upstream unverified",pushBranch:"push branch",blockedReview:"blocked review",refineFailed:"refine failed",working:"working",refining:"refining…",needsMerge:"needs merge",refineWorktree:"refine worktree",needsFollowUp:"needs follow-up",offline:"offline",ahead:"ahead {{count}}",behind:"behind {{count}}",aheadBehind:"ahead {{ahead}} / behind {{behind}}"},summary:{anchor:"Default branch anchor",parent:"parent {{label}}",localChanges:"local changes",sessions_one:"{{count}} session",sessions_other:"{{count}} sessions",conflicts:"conflicts",clean:"Clean and even with upstream"},taskDag:{plan:{depsFailed_one:"{{count}} upstream failed",depsFailed_other:"{{count}} upstream failed"},time:{now:"just now",minutes_one:"{{count}}m ago",minutes_other:"{{count}}m ago",hours_one:"{{count}}h ago",hours_other:"{{count}}h ago",days_one:"{{count}}d ago",days_other:"{{count}}d ago"},empty:"No tasks yet",waitsOn_one:"waits on {{count}}",waitsOn_other:"waits on {{count}}",missingDeps_one:"{{count}} unknown dep",missingDeps_other:"{{count}} unknown deps",legend:{satisfied:"done",waiting:"waiting",failed:"failed"},predictedSlotPinned:"Pinned to a target node — predicted slot on that node"},obs:{fieldEdgeId:"Link ID",fieldHealthRaw:"Health",fieldNodeId:"Node ID",machineSection:"Machine",behindCount:"{{count}} behind",aheadCount:"{{count}} ahead",healUnavailableHint:"Only a clean checkout that is strictly behind a verified upstream can be updated here.",healHint:"Fast-forward this checkout to its upstream. It has no local changes, so nothing can be lost.",healFailed:"Couldn't update {{label}}: {{reason}}",healDone:"{{label}} is up to date",directionTBShort:"↓",directionLRShort:"→",tabMap:"Map",closeDetailAria:"Close detail panel",layoutDirectionAria:"Graph layout direction",viewAria:"Mesh view",tabOverview:"Overview",tabTasks:"Tasks",panHint:"drag or scroll to pan",headlineFollowUp_one:"{{count}} needs attention",headlineFollowUp_other:"{{count}} need attention",headlineIncomplete:"Some machines not visible",headlineConverged:"All synced",badgeBlocked:"{{count}} blocked",badgeBlockedTitle:"{{count}} blocked review",badgeNotMergeable:"{{count}} not mergeable",badgeNeedMerge_one:"{{count}} needs merge",badgeNeedMerge_other:"{{count}} need merge",badgeCleanupTitle:"{{count}} refine/cleanup",badgeOffline:"{{count}} offline",badgeIncompleteTitle:"{{count}} incomplete peer snapshot",badgeNoGitTitle:"{{count}} no git snapshot",badgeNoSubmodTitle:"{{count}} missing submodule visibility",badgeStaleTitle:"{{count}} stale peer snapshot",badgeActiveQueue:"{{count}} active queue",badgeNodes_one:"{{count}} node",badgeNodes_other:"{{count}} nodes",badgeAttachedChats_one:"{{count}} attached chat",badgeAttachedChats_other:"{{count}} attached chats",legendDirty:"{{count}} dirty",legendOrphan:"{{count}} orphan",legendRecentFailures_one:"{{count}} recent failure",legendRecentFailures_other:"{{count}} recent failures",legendAnchor:"Anchor = default branch",legendPeerLink:"Peer link = same-branch worktree",legendSubmoduleLink:"Submodule link = child checkout",healthRefineFailed:"{{count}} refine failed",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedEdge:"Selected edge",activeSessions:"Active Sessions",queueTasks:"Queue tasks",keyWarning:"Key warning",noResultCode:"No result code returned.",legend:"Legend",checking:"Updating…",heal:"Update",loadingGraph:"Loading graph…",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",connecting:"connecting...",providerUnknown:"provider unknown",directionLRTitle:"Left to right",directionTBTitle:"Top to bottom"},notes:{sectionHint:"Lessons the coordinator keeps between sessions — provider quirks, patterns to avoid, recovery steps.",expired:"expired",neverExpires:"never expires",durable:"durable",expiresIn:"expires {{when}}",tab:"Notes",addTitle:"Add operating note",listTitle:"Operating notes",textPlaceholder:"Record a provider quirk, a pattern to avoid, or a recovery lesson...",categoryLabel:"Category",categoryUncategorized:"Uncategorized",categoryProviderQuirk:"Provider quirk",categoryPatternToAvoid:"Pattern to avoid",categoryRecoveryLesson:"Recovery lesson",add:"Add",edit:"Edit",delete:"Delete",save:"Save",cancel:"Cancel",refresh:"Refresh",loading:"Loading notes...",empty:"No operating notes recorded yet.",unavailable:"Operating notes are unavailable — the coordinator is not reachable over P2P.",loadFailed:"Failed to load operating notes.",saveFailed:"Failed to save the operating note.",deleteFailed:"Failed to delete the operating note.",editFailed:"Failed to update the operating note.",showMore:"Show more",showLess:"Show less",pinned:"pinned"},dialog:{liveUpdatesOn:"Live updates on",liveUpdatesPaused:"Live updates paused — showing the last loaded state",refreshedAt:"Refreshed {{time}}",refreshFailedQuiet:"refresh failed · showing last loaded",refreshTitle:"Refresh live mesh graph",loadingStatus:"Loading live mesh status…",noGraph:"No live mesh graph is available for this coordinator yet. Tap the ? above to learn what a Repo Mesh does.",errorNoMeshId:"This coordinator does not expose a live mesh id."},health:{statFailed:"Failed",statPending:"Waiting"},blueprint:{schedPrediction:"Prediction",readonlyBadge:"read-only",schedObservedAt:"as of {{time}}",schedNoNodes:"No routable nodes.",schedQuotaButton:"Quota",schedQuotaButtonTitle:"Per-machine plan quota at a glance",schedNoWinner:"no eligible slot",schedNext:"Next up",schedWaiting:"Ready",schedFull:"At capacity",schedFloorExcluded:"Below difficulty",schedQuotaGated:"Quota-gated",schedCapFree:"Free",schedColSlot:"Slot",schedColScore:"Score",schedColQuota:"Quota",schedColParallel:"Parallel",schedColStatus:"Status",schedColMachine:"Machine",schedNextTitle:"Dispatch a task of this difficulty now and this slot takes it",schedTargetWorktreeTitle:"The task would run in this worktree checkout",schedUnpinnedTitle:"Hypothetical dispatch with no target pin — tasks pinned to a node show their own forecast on their cards",schedPointInTime:"Point-in-time prediction, not a settled assignment: slot capacity can go stale as soon as a slot is claimed or released",schedulingShort:"Scheduling",list:{barActive:"Active {{count}}",barBlocked:"Blocked {{count}}",barRecent:"Recent {{count}}",barMissions_one:"{{count}} mission",barMissions_other:"{{count}} missions",sectionRunning:"Running",sectionBlocked:"Blocked",sectionRecent:"Recent",sectionHistory:"History",generating:"generating",approvalNeeded:"approval needed",choiceNeeded:"choice needed",planShow:"plan",planHide:"hide",planTitle:"Show this task's dependency plan",noMission:"No mission",loadMore_one:"Show {{count}} more",loadMore_other:"Show {{count}} more",emptyActive:"Nothing running",waitingOn:"waiting on:",waitingOnMore:"+{{count}} more",blockedByDeadDependency:"blocked by failed/cancelled dependency:",chainGroup:"Chain: {{title}}"},graph:{viewSwitchLabel:"Blueprint view",viewList:"List",viewGraph:"Graph",activeOnly:"Active only",activeOnlyTitle:"Hide lanes where everything has finished",hiddenLanes_one:"{{count}} finished lane hidden",hiddenLanes_other:"{{count}} finished lanes hidden",emptyActive:"Nothing running",showFinished:"Show finished lanes",layoutFailed:"Graph layout failed: {{error}}",laneAdhoc:"Independent tasks",laneCollapse:"Collapse",laneExpand:"Expand",foldCompleted:"Fold completed",unfoldCompleted:"Show completed",foldNode_one:"{{count}} completed",foldNode_other:"{{count}} completed",countRunning_one:"{{count}} running",countRunning_other:"{{count}} running",countDead_one:"{{count}} stuck",countDead_other:"{{count}} stuck",countWaiting_one:"{{count}} waiting",countWaiting_other:"{{count}} waiting",countFailed_one:"{{count}} failed",countFailed_other:"{{count}} failed",countDone_one:"{{count}} done",countDone_other:"{{count}} done",timeRunning:"running {{age}}",timeFinished:"ended {{time}}",timeQueued:"queued {{age}}",tooltipTask:"Task: {{id}}",tooltipMission:"Mission: {{id}}",tooltipStatus:"Status: {{status}}",deadDirect:"A dependency failed or was cancelled — this task will not start on its own.",deadTransitive:"Something upstream failed or was cancelled — this task will not start on its own.",legendDepends:"depends on",legendRunning:"running",legendDead:"can never start",heldUntil:"until {{time}}",tone:{pending:"pending",running:"running",completed:"completed",failed:"failed",cancelled:"cancelled",dead:"stuck",plan:"planned",held:"held"}}},page:{title:"Repo Mesh",subtitle:"Multi-workspace orchestration",waitingForDaemon:"Waiting for daemon connection..."},list:{nodeCount_other:"{{count}} nodes",nodeCount_one:"{{count}} node",machinesOnline:"{{online}}/{{total}} machines online",settings:"Settings",open:"Open",title:"Repo Meshes",count_one:"{{count}} mesh",count_other:"{{count}} meshes",createMesh:"+ Create Mesh",createTitle:"Create Repo Mesh",createOnMachine:"Create on machine",noConnectedDaemon:"No connected daemon",workspace:"Workspace",workspaceHint:"Choose from workspaces registered by the selected daemon.",name:"Name",remoteUrl:"Repo remote URL (recommended)",remoteUrlHint:"Paste your repo URL — the identity (github.com/user/repo) is filled in automatically.",repoIdentity:"Repo identity",repoIdentityHint:"For a repo with no remote, or when the URL differs per machine. e.g. github.com/user/repo",advancedIdentityToggle:"Advanced: set identity manually",create:"Create",creating:"Creating…",cancel:"Cancel",loading:"Loading meshes...",emptyTitle:"No Repo Meshes",emptyWithDaemons:"Run several coding agents on one repo across your machines.",emptyNoDaemons:"Connect a machine first.",createFirst:"Create First Mesh",noRepoIdentity:"No repo identity"},detail:{useFromCli:"Use from CLI",optionNo:"No",optionYes:"Yes",distributionInOrderSummary:"First available node, in the order added",distributionSmartSummary:"Best-fit node for each task, spread by load",tabGeneral:"General",back:"← Back",delete:"Delete",observabilityOpenTitle:"Open the live view (overview, tasks, map)",observabilityDisabledTitle:"The host machine must be connected first",observabilityOpen:"Open",tabsAriaLabel:"Mesh settings sections",tabAdvanced:"Advanced",quotaBusyFallback:"Quota fallback when busy",quotaBusyFallbackHint:"When the best provider by quota has no free slot, try the next provider with quota on the same node instead of waiting. Never falls back to a provider that is low on quota, and never moves the task to another node.",distribution:"Distribution",distributionSmart:"Smart",distributionSmartDescription:"Match each task to the node whose capability slot fits it best (difficulty + capability tags), then spread by priority and load. Without slots it still spreads work evenly. Recommended when any node has slots.",distributionInOrder:"In order",distributionInOrderDescription:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading.",recommended:"Recommended",saving:"Saving…",visibilityTitle:"Dashboard visibility",visibilityLabel:"Coordinator-spawned worker sessions",visibilityHint:"Hidden = keep the inbox quiet and mute their notifications; you interact through the coordinator session. Visible = show every spawned worker as its own conversation.",visibilityHidden:"Hidden",visibilityVisible:"Visible",coordinatorPromptTitle:"Coordinator prompt",thisMeshHint:"Applies only to coordinator sessions for {{name}}. Leave empty to keep the daemon default.",overrideLabel:"Override (replaces default)",overrideHint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",overridePlaceholder:"(empty — daemon default applies)",appendLabel:"Append (added after the base)",appendHint:"Always added after whichever base prompt wins.",appendPlaceholder:"(empty — nothing appended)",availablePlaceholders:"Available placeholders",placeholdersIntro:"These tokens are replaced when rendering an override or append prompt:",saveCoordinatorPrompt:"Save coordinator prompt",clear:"Clear",clearTitle:"Clear both fields. Click Save to commit.",safetyTitle:"Safety & Git",safetyDescription:"Checkpointing, approval gates, and git safety behavior for coordinator-driven tasks.",checkpointBefore:"Auto-commit a checkpoint before each task",checkpointAfter:"Auto-commit a checkpoint after each task",pushApproval:"Push approval",requireApprovalBeforePush:"Require approval before push",doNotRequireApproval:"Do not require approval",destructiveGitApproval:"Destructive git approval",requireApproval:"Require approval",uncommittedChanges:"When the workspace has uncommitted changes",warnAndContinue:"Warn and continue",blockTask:"Block task",checkpointThenContinue:"Checkpoint then continue",autoPublishSubmodule:"Auto-publish submodule commits (advanced)",requireExplicitApproval:"Require explicit approval",allowRefineryPublish:"Allow Refinery non-force publish",autoFastForward:"Auto fast-forward idle nodes",ffEnabled:"Enabled (catch up online, clean, behind nodes)",ffDisabled:"Disabled",includeRemoteNodes:"Include remote nodes",includeRemoteNodesHint:"Off = only the coordinator's local workspace is auto fast-forwarded.",remoteNo:"No (local workspace only)",remoteYes:"Yes (delegate to remote owning daemons)",detectionMode:"Detection mode",detectionModeHint:"Idle = on a node's idle edge. Continuous = also scan periodically (base nodes only).",idleEdgeOnly:"Idle edge only",continuousScan:"Continuous (periodic scan)",sessionCleanupLabel:"When removing a node, its sessions…",sessionCleanupHint:"Separate transcript cleanup from runtime/process cleanup.",mcpDescription:"· The mesh MCP server can be used directly from your CLI agent.",repoMeshJsonTitle:"From repo file (read-only)",repoMeshJsonHint:"This repo commits coordinator prompt text that stacks with the fields above. Edit it in the repo file, not here:",repoMeshJsonOverrideLabel:"Repo override",repoMeshJsonAppendLabel:"Repo append",repoMeshJsonInvalid:"This repo's .adhdev/mesh.json could not be parsed, so its prompt layer is ignored."},nodeList:{advanced:"Advanced",launchBlockedChip:"No provider detected",usesTools:"Uses {{tools}}",addingIsExplicit:"Adding it is still up to you.",compatibleWorkspace:"Compatible Git workspace detected.",inspectingRepo:"Inspecting the Git repository (read-only)…",title:"Nodes & Providers ({{count}})",descriptionCloud:"Workspaces in this mesh and their preferred AI tools.",descriptionStandalone:"Workspaces participating in this mesh and their preferred AI tools.",daemonCandidates:"Machine daemon candidates",available:"{{count}} available",noDaemonsAvailable:"No connected machine daemons are currently available.",allDaemonsAttached:"All connected machine daemons are already attached.",selectedHost:"selected host",attachMachine:"Attach machine",addNode:"Add node",attachMachineTitle:"Attach Machine Daemon",addNodeTitle:"Add Node",machine:"Machine",selectMachine:"Select a machine...",workspacePath:"Workspace Path",enterCustomPath:"Or enter a custom path →",preferredTools:"Preferred AI tools (in order)",preferredToolsHint:"Order used when launching without an explicit provider.",add:"Add",cancel:"Cancel",emptyTitle:"No nodes",emptyDescription:"Add a workspace to this mesh.",slotsLabel:"Preferred AI tools (capability slots)",slotsHint:"Each slot = provider + model + thinking + the task difficulty/capability it handles + a per-slot parallel cap. Tasks are matched to the best-fit slot (order = preference). With no slots, this node uses its legacy provider order.",nodeInstruction:"Node instruction (optional)",nodeInstructionHint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",nodeInstructionPlaceholder:"e.g. 'Run only smoke tests here', 'Use opus on this node'",saveInstruction:"Save instruction",saving:"Saving…",removeNode:"Remove node",nodeId:"Node ID:",repoRoot:"Repo root:",activeSessionsLabel:"Active sessions:",added:"Added:",activeQueueAssignments:"Active queue assignments",noActiveAssignment:"No active assigned queue task for this node.",activeSessions:"Active sessions",launchBlocked:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)",titleNoCount:"Nodes & Providers",workspacesDetected:"{{count}} workspace(s) detected",pickFromSaved:"← Pick from saved workspaces",ownerMachine:"Owner: {{owner}} · Machine: {{machine}}",machineTabsLabel:"Machines in this mesh",machineTabCounts:"{{nodes}} node(s) · {{slots}} slot(s)"},host:{setHostConfirmTitle:"Set {{name}} as the host?",setupNode:"setup node",willHostOn:"Will host on",title:"Host machine",descriptionSet:"The machine that runs this mesh's coordinator. It is set once and not changed here.",descriptionUnset:"Choose the machine that will run this mesh's coordinator.",hostLabel:"Host:",hostNode:"Host node:",unknown:"Unknown",hostOffline:"Host offline",hostOfflineText:"Live status won't load until the host reconnects. Meanwhile you can send commands through another connected machine — this doesn't change the host.",reconnectToCommand:"Reconnect to command",reconnectToCommandHint:"Route commands through this connected daemon until the host is back. Does not change the mesh host.",waitForHost:"Wait for host to reconnect",noDaemonsToRoute:"No connected daemons available to route commands through. Bring the host (or another daemon) online.",setHostBanner:"Choose a host machine",hostDaemon:"Host daemon",hostDaemonHint:'Pick the daemon that will host this mesh, then confirm with "Set as host".',resolvingHost:"Resolving host… (or pick a daemon to host)",noDaemonsToHost:"No connected daemons. Bring a daemon online to host this mesh.",online:"online",offline:"offline",noCommandTarget:"No command target available — bring the host or a daemon online.",setHostAction:"Set as host",settingHost:"Setting host…",setHostActionHint:"Pins this daemon as the mesh host. Effectively permanent — it is not reassigned from here afterwards.",confirmSetsHost:"Confirm below to set it as the mesh host.",attachNodeThenSetHost:"Attach one of its workspaces as a node first, then set it as the host."},slotEditor:{emptyHint:"Without slots this node still runs tasks using its provider order. Add a slot to send specific task difficulties or capabilities to a specific tool.",empty:"No slots (optional)",moveUp:"Move up",moveDown:"Move down",removeSlot:"Remove slot",provider:"Provider",select:"(select)",model:"Model",providerDefault:"(provider default)",custom:"Custom…",modelPlaceholder:"model",backToModelList:"← Back to model list",thinking:"Thinking",thinkingDefault:"(default)",difficulty:"Difficulty (blank = freeform tasks only)",capabilityTags:"Capability tags (comma-separated)",maxParallel:"Max parallel (per slot)",maxParallelPlaceholder:"unlimited",addSlot:"Add slot",saving:"Saving…",saveSlots:"Save slots"},tagEditor:{emptyHint:"Tasks can run here without matching any specific tag. Add tags to target this node from a task's required tags.",noSpaces:"Tags cannot contain spaces.",reservedPrefix:"That prefix is auto-derived — pick a different tag.",alreadyAdded:"Already added.",routingTags:"Routing tags",autoDerivedTitle:"Auto-derived — can't be edited",customTagTitle:"Custom tag",remove:"Remove {{tag}}",addPlaceholder:"add a custom tag (e.g. test-runner)",add:"Add",saving:"Saving…",saveTags:"Save tags",empty:"No tags (optional)"},queue:{title:"Queue",description:"Inspect active queue work separately from historical completed, failed, and cancelled task records."},promptPreview:{connectPrompt:"Connect a daemon to preview the default.",errorRender:"Failed to render the default prompt",hide:"Hide the default prompt",view:"View the default prompt",rendering:"Rendering…",retry:"Retry",info:"This is what a coordinator session gets when Override is empty.",launchScopeNote:"Mission, recent activity and operating notes are added at launch and are not shown here."},providerAutoApprove:{partialInventoryChip_other:"{{count}} nodes pending",partialInventoryChip_one:"{{count}} node pending",title:"Provider auto-approve defaults",loading:"Loading provider defaults…",loadError:"Failed to load provider auto-approve defaults.",noProviders:"No CLI providers with auto-approve modes detected on this mesh's machines.",awaitingNodes:"Waiting for {{count}} node(s) to report their installed providers…",partialInventory:"Provider list may be incomplete — {{count}} node(s) have not reported yet.",noHostDaemon:"Connect the mesh host daemon to configure provider auto-approve defaults.",repoSection:{chip:"Shared with team",title:"Repository default",hint:"Committed to .adhdev/mesh.json — shared with the whole team. Sets which mode a delegated worker requests; it does not grant permission to run it.",usesProviderDefault:"Uses provider default",clear:"Use provider default"},machineSection:{chip:"This machine only",title:"This machine authorization",hint:"Local only (meshes.json) — never committed. Controls whether workers on THIS machine auto-approve at all, and whether dangerous modes are allowed.",autoApproveToggleLabel:"Delegated worker auto-approve",autoApproveToggleHint:"When off, workers delegated to this machine stop at every approval prompt.",dangerousToggleLabel:"Allow dangerous modes on this machine",dangerousToggleHint:"Opt-in: workers on this machine may run dangerous modes that execute tools with no approval at all.",dangerousDisabledHint:"No effect while auto-approve above is off.",confirmTitle:"Opt in to dangerous modes",confirmDescription:"This allows delegated workers on this machine to run dangerous provider modes. In a dangerous mode the agent executes tools and commands with no approval prompts at all.",confirmScopeLabel:"Scope",confirmScopeValue:"This machine only (local meshes.json — never committed)",confirmEffectLabel:"Effect",confirmEffectValue:"Repo-requested dangerous modes (e.g. Force, fully autonomous) are no longer downgraded to a safer interactive mode on this machine.",confirmConfirm:"Opt in"},effectiveSection:{statusDowngradedHint:"{{requested}} was requested, but this machine hasn't allowed dangerous modes, so it runs {{mode}}.",statusRequested:"Runs: {{mode}}",statusInvalidFallback:"Requested mode not found → runs provider default: {{mode}}",statusDowngraded:"{{mode}} (downgraded)",statusDisabled:"Auto-approve disabled on this machine — worker will ask for approval.",statusNone:"No usable auto-approve mode — worker will ask for approval."},dangerous:{sharedWarningDetail:"Saved in .adhdev/mesh.json. Each machine runs it only after opting in (delegatedWorkerDangerousModeAllow).",sharedWarningTitle:"This is committed to the repository",sharedWarning:"Committed to the repo and shared with your team. Machines that haven't allowed dangerous modes run a safer mode instead."},saving:"Saving…",saved:"Saved to .adhdev/mesh.json",saveError:"Failed to save provider defaults."},status:{healthErrorChip:"Error",offlineMachinesTitle:"Not reporting: {{machines}}",badgeBootstrap:"Setting up",badgeUpdatePending:"Update pending",quotaClaudeRefreshChip:"Needs refresh",quotaClaudeSetupChip:"Set up",machineNotReportingHint:"We haven't heard from this machine, so its plan quota is unknown.",quotaNotCollectedHint:"A machine reports its plan quota after its first refresh (about 15 minutes) and only while an agent has been active.",schedulingNotReportedHint:"This machine runs an older version that doesn't report scheduling details.",schedulingNotReported:"Update the daemon to see scheduling",schedulingTitle:"Scheduling",distributionTitle:"Distribution decides how work without a target is spread across nodes. Per-node load and limits are listed below.",protocolTitle:"Protocol & provider versions",noNodesReporting:"No nodes reporting runtime yet.",quotaNotCollected:"No quota yet",quotaFreshnessHint:"Last updated",machineNotReporting:"Offline · quota unknown",quotaClaudeSetupHint:"Set up Claude quota with `adhdev quota claude:install`.",quotaClaudeRefreshHint:"Open a Claude Code session once to refresh quota.",quotaAccountHint:"The signed-in account this quota belongs to, as reported by the provider CLI",quotaOkNoWindows:"No limit",healthNotGitRepo:"Not a git repo",healthProbePending:"Checking…",healthPeerConnection:"Connection {{state}}",healthNoLiveReport:"No report yet",badgeWorktree:"worktree",badgeWorktreeTitle:"Local worktree node",badgeWorktreeBranchTitle:"Worktree branch {{branch}}",badgeBootstrapTitle:"Worktree bootstrap is still in progress",badgeConnectionTitle:"Mesh peer connection state",badgeSessions_one:"{{count}} session",badgeSessions_other:"{{count}} sessions",badgeFastForwardReady:"fast-forward ready",badgeFastForwardReadyTitle:"Clean, behind upstream — safe for fast-forward",badgeStaleBuildTitle:"Live daemon was built behind workspace HEAD — merged fixes may not be live",badgeDeployLagTitle:"Running daemon build commit differs from origin/main — deploy + restart pending for this node",machinesNotReporting_one:"{{count}} offline",machinesNotReporting_other:"{{count}} offline",machinesSection:"Machines — plan · nodes",versionSkewTitle:"Version differs from this machine’s consensus (stale report or partial install)",machineVersionsTitle:"Provider CLI versions installed on this machine — shared by all its nodes"},overview:{tasksCount_other:"{{count}} tasks",tasksCount_one:"{{count}} task",sessionCount_other:"{{count}} sessions",sessionCount_one:"{{count}} session",providerUnknown:"provider unknown",truncated:"(truncated)",missionCard:"Missions",ledgerCard:"Activity",queueCard:"Queue",nodesCard:"Nodes",sessionsCard:"Active sessions",refineCard:"Refine jobs",recentActivity:"Recent activity",recentTasks:"Recent tasks",missionTasksHeading:"Mission tasks",showFewer:"Show fewer",showMore:"+{{count}} more",noActiveMissions:"No active missions",missionDataUnavailable:"Update the daemon to see missions",completedHistory:"Completed / abandoned history",noQueueActivity:"No queue activity.",noNodes:"No nodes in this mesh yet.",noActiveSessions:"No active sessions.",noRefineJobs:"No refine jobs.",closeDetail:"Close detail",loadingGoal:"Loading…",showFullGoal:"Show full goal",statCompleted:"Completed",statAssigned:"Assigned",statPending:"Pending",statFailed:"Failed",statBlocked:"Blocked",statCancelled:"Cancelled",statWallClock:"Wall clock",statTotalRuntime:"Total runtime",statRetries:"Retries",statDispatched:"Dispatched",statStalled:"Stalled",statSessions:"Sessions",statCheckpoints:"Checkpoints",statActive:"Active",statPaused:"Paused",statAbandoned:"Abandoned",recentFailures:"{{count}} recent failures",activeCount:"{{count}} active",failedCount:"{{count}} failed",detailKickerMission:"Mission",detailKickerLedger:"Ledger entry",detailKickerQueue:"Queue task",detailKickerSession:"Session",detailLabelMissionId:"Mission id",detailLabelCreated:"Created",detailLabelUpdated:"Updated",detailLabelElapsed:"Elapsed",detailLabelFullInstruction:"Show full instruction",detailLabelLastActivity:"Last task activity",detailLabelIncompleteEvidence:"Incomplete evidence",detailLabelEntryId:"Entry id",detailLabelWhen:"When",detailLabelNode:"Node",detailLabelDependsOn:"Depends on",detailLabelSession:"Session",detailLabelProvider:"Provider",detailLabelPayload:"Show raw payload",detailLabelTaskId:"Task id",detailLabelFinalSummary:"Final summary",detailLabelFullFinalSummary:"Show full report",detailFinalSummaryLoading:"Loading final summary…",detailFinalSummaryUnavailable:"Final summary unavailable",detailLabelAutoLaunch:"Auto launch",detailLabelCancelReason:"Cancel reason",detailLabelRequeueReason:"Requeue reason",detailLabelRequeued:"requeued {{count}}",detailLabelSessionId:"Session id",detailLabelBranch:"Branch",detailLabelRole:"Role",detailLabelStarted:"Started",detailLabelWorkspace:"Workspace",routingHeading:"Routing",routingDevice:"Device",routingDaemon:"Daemon",routingExecution:"Execution",routingVia:"Via",routingDifficulty:"Difficulty",routingFitness:"Fitness",routingReason:"Reason",routingRequiredTags:"Required tags",routingTagsUnsatisfied:"unsatisfied",routingSkipped:"Skipped candidates",routingSkippedMore:"+{{count}} more",pausedMissions:"Paused missions",ledgerAllTime:"all-time totals",sessionTasksHeading:"Tasks in this session",showOnCanvas:"Show on canvas"}},rk={showMoreChars:"Show more ({{count}} characters)",collapse:"Collapse",you:"You",toolMessageAria:"Tool message",activityMessageAria:"Activity message",activityFallback:"Activity",copyMessage:"Copy message",copyCode:"Copy code",showMore:"Show more",showLess:"Show less",thought:"Thought",toolExpand:"Show full output",toolCollapse:"Show less",toolExpandLoading:"Loading…",toolExpandUnavailable:"Full output could not be fetched for this step.",toolExpandStale:"Full output has moved — the transcript changed since this was read. Reload the conversation to fetch it.",waitingToSend:"Waiting to send — the agent is still working.",waitingToSendAria:"Waiting to send",notDelivered:"Not delivered — the agent never received this.",notDeliveredAria:"Not delivered",sendNow:"Send now",sending:"Sending…",sendNowAria:"Send now to the agent's queue, without interrupting its current turn",sendNowTitle:"Send this message to the agent now. It goes into the agent's own queue and is answered next — the turn in progress keeps running.",cancelQueued:"Cancel",cancelQueuedAria:"Cancel this queued message",cancelQueuedTitle:"Remove this message from the queue. It will not be sent to the agent."},ok={debugBundleFailed:"Couldn't collect debug info",connectingToMachine:"Connecting to your machine",establishingP2P:"Establishing P2P connection",agentNotMonitored:"Agent not monitored",clickToSwitchMonitoring:"Click to switch monitoring to this agent",agentPanelHidden:"Agent panel is not visible yet",openPanelHint:"Open the chat in your IDE",noMessagesYet:"No messages yet",loadingChat:"Loading chat...",openPanel:"Open {{label}} Panel",switchingPanel:"Switching...",openingPanel:"Opening...",busyNoProgress:"Agent shows no progress.",busyGenerating:"Agent is generating.",busyWaitingApproval:"Waiting for approval",activityToggleLabel:"Tool steps",activityToggleTitle:"Show tool, terminal and thinking steps",reconnectMachine:"Reconnect",reconnectingMachine:"Reconnecting…",reconnectMachineTitle:"Automatic reconnection gave up on this machine — reconnect now"},ak={addMessageOptional:"Add a message (optional)…",showControls:"Show controls",hideControls:"Hide controls",sendTo:"Send message to {{panel}}",attachImage:"Attach image",placeholder:"Send message to {{panel}}...",sendMessage:"Send message",dropImage:"Drop image here"},ik={cdpDisconnectedShort:"IDE disconnected",hideFromDashboard:"Hide from dashboard",removeShortcut:"Remove shortcut",changeShortcut:"Change shortcut ({{shortcut}})",dropSplitRight:"Split right",dropMoveHere:"Move here",dropSplitLeft:"Split left",relaunchWithCdp:"Relaunch with connection",cdpDisconnected:"Not connected to the IDE — chat history and screenshots are unavailable.",resizeHandleHint:"Drag to resize · Double-click to merge",shortcutListening:"Listening…",shortcutPressCombo:"Press a key combination (e.g. {{example1}}, {{example2}})",shortcutSetTitle:"Set shortcut",loadingSessions:"Loading sessions...",noConversations:"No conversations yet",waitingForDaemon:"Waiting for your daemon",connectYourMachines:"Connect your machines",daemonDescription:"Start the ADHDev daemon to connect.",installDescription:"Install ADHDev on a machine and sign in.",newSession:"New session",newSessionDescription:"Start a session with any installed agent.",noTabsInGroup:"No tabs in this group",pressEscToCancel:"Press Esc to cancel",noActiveAgent:"No active agent",moveTabHere:"Move a tab here to view"},ck={growViewport:"Enlarge terminal view",shrinkViewport:"Shrink terminal view",sendInterrupt:"Send interrupt (Ctrl-C)",arrowRight:"Arrow right",arrowDown:"Arrow down",arrowLeft:"Arrow left",arrowUp:"Arrow up",keysPanelTitle:"Terminal keys",keysButton:"Keys",copyHint:"Copy the selected terminal text, or the visible screen if nothing is selected",specDebugHint:"Spec debug — inspect current state, sections, and transition history",replayScrollbackHint:"Load earlier terminal output so you can scroll farther up",loadOlderOutput:"Load older terminal output",loadingOlder:"Loading older...",debug:"Debug",copy:"Copy",openControlKeys:"Open terminal control keys",closeControlKeys:"Close terminal control keys"},lk={muteThis:"Mute this chat",unmuteThis:"Unmute this chat"},dk={switchToTerminal:"Switch to Terminal view",switchToChat:"Switch to Chat view"},uk={updatedAt:"Updated {{time}}",messageCountShort_other:"{{count}} msgs",messageCountShort_one:"{{count}} msg",workspaceUnknown:"Workspace unknown",clearSelection:"Clear",selectedSavedHistory:"Selected saved history",loadingShort:"Loading…",savedHistoryNoneYet:"No saved history",savedHistoryLoadedCount_other:"{{count}} saved histories loaded. Open saved history to choose one.",savedHistoryLoadedCount_one:"{{count}} saved history loaded. Open saved history to choose one.",savedHistoryBadge:"Saved history",resumeSavedHistory:"Resume saved history",startFresh:"Start fresh",resumingSavedHistory:"Resuming saved history…",startingFresh:"Starting fresh…",startIde:"Start IDE",startingIde:"Starting IDE…",recoverHostedRuntime:"Recover hosted runtime",hostedRuntimeRecoveryDescription:"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead.",openSavedHistory:"Open saved history",savedHistoryTitle:"Saved History",savedHistoryHelper:"Use saved history when you want continuity in the same provider conversation.",savedHistoryEmpty:"No saved history found yet.",refreshSavedHistory:"Refresh saved history",refreshingSavedHistory:"Refreshing saved history…",startFreshWith:"Start fresh with {{label}}?",restart:"Restart {{label}}?",startFreshReview:"Review the provider and target folder before starting fresh.",restartIdeReview:"Review or change the target workspace before restarting this IDE.",restartStoppedReview:"Review or change the target workspace before restarting this stopped session.",confirmStartFresh:"Start fresh",confirmRestart:"Restart",confirmStartingFresh:"Starting fresh…",confirmRestarting:"Restarting…",resumeWith:"Resume saved history with {{label}}?",resumeReview:"Review or change the target workspace before resuming saved history."},mk={layout:{expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse"},auth:{loading:"Loading standalone dashboard…",loadError:"Failed to load standalone auth status: {{error}}",signInTitle:"Standalone sign-in",passwordProtected:"This self-hosted dashboard is protected by a local password.",tokenProtected:"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session.",passwordPlaceholder:"Enter standalone password",unlock:"Unlock dashboard",signingIn:"Signing in…",noPasswordEnabled:"Password login is not enabled on this server."},machine:{loading:"Loading machine...",awaitingInput:"Awaiting your input ↑"},settings:{restartToApply:"Restart to apply",providersLink:"Providers",providersIntro:"IDEs and agents on this machine:",title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",publicHostWarning:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token.",daemonSection:"Daemon",versionLabel:"Version",statusLabel:"Status",statusRunning:"● Running",statusNotConnected:"○ Not connected",authLabel:"Auth",authPassword:"Password enabled",authToken:"Token enabled",authNone:"No auth configured",networkSection:"Network Access",networkHint:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token.",localhostLabel:"Localhost only",localhostHint:"Bind to 127.0.0.1. Best when only this machine should open the dashboard.",allInterfacesLabel:"All interfaces",allInterfacesHint:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points.",saveNetworkMode:"Save default network mode",saving:"Saving…",networkRestartHint:"Applies on next standalone restart. Current run stays bound to {{host}}.",networkSavedAll:"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.",networkSavedLocal:"Default standalone network mode set to localhost only. Restart standalone to apply it.",securitySection:"Dashboard Security",passwordSet:"A local password is currently required for browser access. Existing sessions are rotated when you change it.",passwordNotSet:"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended.",currentPasswordPlaceholder:"Current password",currentPasswordFirstTimePlaceholder:"Current password (not needed for first setup)",newPasswordPlaceholder:"New password",newPasswordFirstTimePlaceholder:"New standalone password",confirmPasswordPlaceholder:"Confirm new password",updatePassword:"Update password",enablePassword:"Enable password",disablePassword:"Disable password",passwordUpdated:"Standalone password updated.",passwordEnabled:"Standalone password enabled.",passwordDisabled:"Standalone password disabled.",passwordTooShort:"Password must be at least 4 characters.",passwordMismatch:"New password and confirmation do not match.",appearanceSection:"Appearance",fontsLabel:"Fonts",fontsDescription:"Standalone-only typography overrides for chat text, markdown code, and terminal output.",fontsSaved:"Standalone chat fonts saved for this self-hosted dashboard.",profileSection:"Profile",displayNameLabel:"Display Name",displayNameHint:"Your name shown in chat threads and on the team dashboard.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Welcome to ADHDev",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",selectedCount_one:"{{count}} selected",selectedCount_other:"{{count}} selected",intro:"Pick the providers you want to use. Defaults to the three officially supported CLI providers; you can install IDE or extension providers from the tabs below or later from Machines → Providers.",loadingRegistry:"Loading registry…",loadError:"Failed to load registry: {{error}}",noProviders:"No providers in this category.",installed:"✓ installed",installFailed:"✗ {{error}}"},about:{title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",selfHostedEdition:"Self-hosted edition",headline:"Keep the same dashboard experience, with the runtime fully on-device.",description:"Standalone keeps the browser, daemon, screenshots, and control path entirely on your own machine. Aside from multi-machine connectivity and mobile notifications, it is the same core product experience as Cloud.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Try Cloud ↗",includedSection:"Included in standalone",includedDescription:"The local-first feature set available without the cloud control plane.",inventorySection:"Built-in inventory",inventoryDescription:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",cloudExtrasSection:"Cloud-only extras",cloudExtrasDescription:"Capabilities that need the hosted control plane or team infrastructure.",comparisonSection:"Self-hosted vs Cloud",comparisonDescription:"The product split at a glance.",featureHeader:"Feature",selfhostHeader:"Selfhost",cloudHeader:"Cloud",cloudOptional:"Cloud is optional, not required",cloudOptionalDescription:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",compareCloud:"Compare Cloud ↗",discord:"Discord ↗",features:{localFirst:{title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},chatRelay:{title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},screenshots:{title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},remoteControl:{title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},multiIde:{title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},cli:{title:"CLI coverage",desc:"Track standalone CLI agents alongside IDE sessions."}},extras:{anywhere:{title:"Access from anywhere",desc:"Reach your machines from another laptop or phone without opening local ports."},p2pStream:{title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},mobileNotifications:{title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},restApi:{title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},teamWorkspace:{title:"Team workspace",desc:"Share machines, activity views, and policies across a team workspace."},enterpriseControls:{title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}},comparison:{chatRelay:"Agent chat relay",screenshots:"Live IDE screenshots",remoteControl:"Remote IDE control",multiIde:"Multi-IDE monitoring",extensionCli:"Extension and CLI agents",anyNetwork:"Access from any network",webrtc:"WebRTC P2P streaming",mobilePush:"Mobile push notifications",restApi:"REST API and webhooks",teamCollaboration:"Team collaboration",multiMachineDashboards:"Multi-machine dashboards",ssoRbacAuditLogs:"SSO, RBAC, audit logs"}},fonts:{fontOverridesNotice:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below.",chat:"Chat text",chatDescription:"Assistant/user prose, markdown text, thought cards, and system notes.",code:"Code blocks",codeDescription:"Markdown code fences, inline code, and preformatted command output.",terminal:"Terminal",terminalDescription:"Terminal transcript cards and tool/command rows in chat mode.",livePreview:"Live preview",resolvedStack:"Resolved stack:",saveFontSettings:"Save font settings",revertToSaved:"Revert to saved",resetToDefaults:"Reset to defaults",saving:"Saving…",customFamilyPlaceholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',previewSummary:"Chat: {{chat}} · Code: {{code}} · Terminal: {{terminal}}",defaultsSummary:"Defaults: {{chat}} / {{code}}",previewNow:"now",previewProse:"Readable prose, <strong>bold text</strong>, and <code>inline code</code> should all follow your standalone font choices.",presets:{default:"Default",defaultMono:"Default mono",custom:"Custom…",serif:"Serif"}}},hk={login:{eyebrow:"Cloud sign-in",title:"Sign in to ADHDev",subtitle:"Connect your machines, get approval and completion notifications, and keep your coding agents moving when you are away from your desk.",continueWith:"Continue with {{provider}}",connecting:"Connecting...",devDivider:"dev",devLogin:"Dev Login (test_jwt_token)",providerNote:"GitHub and Google are used only for authentication.",errorUnverifiedEmail:"This login provider did not return a verified email, so we could not safely sign you in.",termsPrefix:"By continuing, you agree to our ",termsLink:"Terms of Service",termsAnd:" and ",privacyLink:"Privacy Policy",termsSuffix:"."},account:{openMachines:"Open Machines",machinesSummaryShort:"{{count}} of {{limit}}",title:"Account",subtitle:"Profile, plan & activity",tabAccount:"Account",tabBilling:"Billing",tabActivity:"Activity",profile:"Profile",noName:"No name",displayName:"Display Name",displayNameDesc:"Your name shown in the dashboard and team workspaces.",nicknamePlaceholder:"Nickname",save:"Save",saving:"...",cancel:"Cancel",saved:"Saved",edit:"Edit",failedToSave:"Failed to save",userId:"User ID",loadingProfile:"Loading profile...",planLimits:"Plan limits",limitMachines:"Machines",limitP2P:"Connected machines",limitPushNotifications:"Daily Push Notifications",limitTurnRelay:"Relay fallback",enabled:"Enabled",disabled:"Disabled",frozen:"Frozen",session:"Session",logout:"Logout",logoutDesc:"Sign out of your ADHDev account on this device.",dangerZone:"Danger zone",dangerZoneDesc:"Permanently delete your account and all associated data. This action cannot be undone.",deleteAccount:"Delete account",deleteWillRemove:"This will permanently delete:",deleteItemProfile:"Your profile and login credentials",deleteItemKeys:"All API keys and connection tokens",deleteItemWebhooks:"Webhooks and delivery history",deleteItemPush:"Push notification subscriptions",deleteItemSessions:"Shared sessions and audit logs",deleteTypeConfirm:"Type {{keyword}} to confirm:",deleting:"Deleting...",permanentlyDelete:"Permanently delete",failedToDeleteAccount:"Failed to delete account",registeredMachines:"Registered Machines",machinesSummary:"{{count}} registered · {{online}} online",machinesLimit:"(limit: {{limit}})",loadingMachines:"Loading machines...",noMachinesRegistered:"No machines registered",runSetupPrefix:"Run ",runSetupMiddle:", then start ",runSetupSuffix:" on a machine to register it here.",removeMachineConfirm:"Remove this machine? It will need to run `adhdev setup` again to reconnect.",failedToDeleteMachine:"Failed to delete machine",failedToUpdate:"Failed to update",rename:"Rename",online:"Online",connecting:"Connecting",removeMachine:"Remove machine",never:"Never",frozenFeatureTitle:"Frozen — this feature is paused and not available."},billing:{currentPlan:"Current Plan:",statusTrial:"Trial",statusActive:"Active",statusPastDue:"Past Due",statusCanceled:"Canceled",nextBilling:"Next billing: {{date}}",trialEnds:"Trial ends: {{date}}",accessUntil:"Access until: {{date}}",updatePayment:"Please update your payment method",managePayment:"Manage Payment & Invoices",couldNotOpenPortal:"Could not open billing portal",checkoutSuccess:"Your subscription is active. Thanks for upgrading!",statMachines:"Machines",statSharedSessions:"Shared Sessions",statTurnRelay:"TURN Relay",statTurnOn:"On",resetsDailyUtc:"Resets daily at 00:00 UTC",resetsInHours_one:"~{{count}}h left",resetsInHours_other:"~{{count}}h left",resetsInMinutes_one:"~{{count}}m left",resetsInMinutes_other:"~{{count}}m left",resetsDailyUtcWithLeft:"Resets daily at 00:00 UTC · {{left}}",monthly:"Monthly",yearly:"Yearly",savePercent:"Save up to {{pct}}% yearly",pricesInUsd:"All prices in USD",paddleLoading:"Paddle is loading, please try again.",cancelConfirm:"Are you sure you want to cancel your subscription? You will retain access until the end of your billing period.",cancelSubscription:"Cancel Subscription",cancelRetainAccess:"You will retain access to {{plan}} features until the end of your current billing period.",cancelTeamDowngrade:" All team members will be downgraded to their personal plans.",cancelFailed:"Failed to cancel subscription"},about:{title:"About",subtitle:"Cloud overview, supported surfaces, and plan-level capabilities",cloudEdition:"Cloud edition",heroTitle:"Control your local CLI agents from anywhere — web or mobile.",heroDesc:"ADHDev Cloud surfaces the agents running on your machines in your browser: send prompts, approve actions, orchestrate work across machines, and get notified on your phone — code flows P2P directly to your daemon, never through the server.",openDashboard:"Open Dashboard",viewMachines:"View Machines",docs:"Docs ↗",whyTitle:"Why ADHDev Cloud",whyDesc:"Core capabilities available when your machines are connected through the cloud control plane.",howTitle:"How it works",howDesc:"The cloud onboarding path from install to remote control.",repoMeshTitle:"Repo Mesh",repoMeshDesc:"Orchestrate agents across machines — cloud only.",meshCard1Title:"One coordinator, many agents",meshCard1Desc:"Enqueue tasks against a mission and let idle nodes claim work from a local-first, pull-based queue. Fan out across machines and providers — Claude Code on one, Codex on another — then converge the results from a single coordinator session.",meshCard2Title:"Same repo, many machines at once",meshCard2Desc:"Each node is a checkout or an isolated git worktree, so parallel agents never collide. The refinery converges every branch — validate, merge, push, clean up — with safe submodule handling. Runs over a direct daemon-to-daemon P2P channel; the server only signals and authorizes same-account peers.",worksWith:"Works with",worksWithDesc:"Supported CLI agents, IDEs, and AI extensions.",groupCli:"CLI Agents",groupIdes:"IDEs",groupExtensions:"AI Agents",pricingTitle:"Pricing",pricingDesc:"Current cloud plans and machine capacity by tier.",planPopular:"Popular",readyTitle:"Ready to connect a machine",readyDesc:"Jump into your dashboard, inspect your connected machines, or continue in the docs if you are still setting up.",dashboard:"Dashboard",machines:"Machines",discord:"Discord ↗",github:"GitHub ↗",features:{webControlTitle:"Web control of local CLI agents",webControlDesc:"Drive any local CLI agent — Claude Code, Codex, Cursor CLI — from your browser: send prompts, approve actions, and steer sessions without touching the terminal.",chatRelayTitle:"Agent chat relay",chatRelayDesc:"Read and respond to agent conversations from anywhere, including mobile surfaces.",liveViewTitle:"Live session view",liveViewDesc:"Watch agent activity in real time; for IDE sessions, view and control the screen over P2P without switching windows.",mobileTitle:"Mobile-ready",mobileDesc:"Receive approvals and check progress while away from your development machine.",secureTitle:"Secure by default",secureDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC — the cloud handles auth and signaling metadata only. Your code never routes through the server."},steps:{step1Title:"One-line Install",step1Desc:"Run a single command on any machine you want to drive. It installs the ADHDev daemon plus the adhdev CLI.",step2Title:"Sign In",step2Desc:"Sign in with GitHub or Google and the daemon pairs itself to your account — no token to copy.",step3Title:"Drive Your Agents from Anywhere",step3Desc:"The machine appears in your dashboard instantly. Launch and control Claude Code, Codex, Cursor CLI, and other CLI agents from the web — IDE sessions too."},plans:{freeName:"Free",proName:"Pro",ultraName:"Ultra",freePer:"/mo",proPer:"/mo",ultraPer:"/mo",freeFeature1:"1 machine",freeFeature2:"Real-time chat relay",freeFeature3:"Web control for your local agents",proFeature1:"2 machines",proFeature2:"Unlimited AI agents",proFeature3:"P2P remote view",ultraFeature1:"5 machines — flat, not per-seat",ultraFeature2:"Everything in Pro",ultraFeature3:"Higher concurrency & usage limits",ultraFeature4:"Unlimited daily screenshot minutes"}},layout:{adminSection:"Admin",adminOverview:"Overview",adminUsers:"Users",adminAuditLogs:"Audit Logs",adminSystem:"System",adminTokens:"Admin Tokens",adminEntry:"Admin",footerPlanTitle:"Current plan: {{plan}} — manage or upgrade",expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse",logout:"Logout",machineLimitBadge:"Machines full",machineLimitBadgeTitle:"You've reached your plan limit of {{count}} machine{{plural}} — open billing to upgrade",pushBudget:"Daily notifications {{used}}/{{limit}}"},settings:{title:"Settings",subtitle:"Appearance & preferences",appearanceTitle:"Appearance"},planCard:{unlimited:"Unlimited",machineSingular:"{{count}} machine",machinePlural:"{{count}} machines",sharedSessionSingular:"{{count}} shared session",sharedSessionPlural:"{{count}} shared sessions",teamMemberSingular:"{{count}} team member",teamMemberPlural:"{{count}} team members",turnIncluded:"TURN relay included",recommended:"Recommended",currentPlan:"Current Plan",contactUs:"Contact Us",freeForever:"Free Forever",startTrial:"Start 7-day free trial",upgradeTo:"Upgrade to {{name}}",noChargeCancel:"No charge for 7 days. Cancel anytime.",periodSeatMo:"seat/mo",periodMo:"mo",yearlyNote:"${{yearly}}/year — Save ${{saved}}",pricingCustom:"Custom"},activity:{origin:{ide:"IDE",extension:"Extension",admin:"Admin",webhook:"Webhook",web:"Dashboard",user:"User",terminal:"Terminal",system:"System",registry:"Registry",mesh:"Mesh",machine:"Machine",daemon:"Daemon",connection:"Connection",cli:"CLI",auth:"Sign-in",api_key:"API key",api:"API",agent:"Agent"},filterPlaceholder:"Filter by action, resource, or source...",refresh:"Refresh",loading:"Loading...",noLogs:"No logs",noMatchingLogs:"No matching logs found.",logsWillAppear:"Actions will appear here as they happen.",colAction:"Action",colResource:"Resource",colSource:"Source",colTime:"Time",logCount:"{{count}} logs",logCountFiltered:" (filtered from {{total}})",action:{login:"Logged in",logout:"Logged out",api_key_create:"Created API key",api_key_revoke:"Revoked API key",agent_command:"Sent agent command",terminal_exec:"Ran terminal command",ide_command:"Sent IDE command",daemon_command:"Sent daemon command",daemon_disconnect:"Disconnected daemon",daemon_revoke:"Revoked daemon",webhook_create:"Created webhook",webhook_delete:"Deleted webhook",webhook_toggle:"Toggled webhook",registry_publish:"Published provider",registry_promote:"Promoted provider",registry_yank:"Yanked provider",registry_publish_token_issued:"Issued registry publish token",machine_registered:"Registered machine",machine_secret_rotated:"Rotated machine secret",shortcut_launch:"Launched session",shortcut_stop:"Stopped session",shortcut_chat:"Sent chat message",shortcut_chat_debug_bundle:"Exported chat debug bundle",shortcut_approve:"Approved agent action",shortcut_reject:"Rejected agent action",shortcut_git_push:"Pushed git changes",shortcut_git_checkpoint:"Created git checkpoint",shortcut_mesh_clone_node:"Cloned mesh node",shortcut_mesh_remove_node:"Removed mesh node",shortcut_mesh_refine_node:"Refined mesh node",admin_plan_change:"Changed user plan",admin_role_change:"Changed user role",admin_user_suspend:"Suspended user",admin_user_unsuspend:"Unsuspended user",admin_machine_delete:"Deleted machine",admin_token_create:"Created admin token",admin_apikey_rate_limit:"Changed API key rate limit",admin_apikey_scopes:"Changed API key scopes",admin_apikey_revoke:"Revoked API key",admin_plan_limits_update:"Updated plan limits",admin_plan_limits_reset:"Reset plan limits",admin_config_update:"Updated system config",admin_announcement:"Posted system announcement",admin_disconnect:"Disconnected connection"}},webhooks:{title:"Webhooks",subtitle:"Real-time event notifications",addWebhook:"+ Add Webhook",eventDaemonConnect:"Daemon Connected",eventDaemonDisconnect:"Daemon Disconnected",eventAgentStatus:"Agent Status Change",eventApprovalRequired:"Approval Required",failed:"Failed",deleteConfirm:"Delete this webhook?",testFailed:"Test failed",secretTitle:"Webhook Secret",secretShownOncePrefix:"Shown ",secretShownOnce:"only once",secretShownOnceSuffix:". Use to verify ",copy:"Copy",done:"Done",newWebhook:"New Webhook",labelUrl:"URL",urlPlaceholder:"https://your-service.com/webhook",labelEvents:"Events",allEvents:"All Events (*)",creating:"Creating...",create:"Create",cancel:"Cancel",loading:"Loading...",noWebhooks:"No webhooks",noWebhooksDesc:"Receive real-time notifications about events.",setupFirst:"Set up first webhook",off:"OFF",autoDisabled:"Auto-disabled",autoDisabledTitle:"Auto-disabled after 10 consecutive failures",failuresWarning:"{{count}} failures",failuresTitle:"{{count}} consecutive failures — will auto-disable at 10",all:"ALL",history:"History",test:"Test",delete:"Delete",deleting:"...",recentDeliveries:"Recent Deliveries",refresh:"Refresh",noDeliveries:"No deliveries yet. Send a test to verify the endpoint.",request:"REQUEST",response:"RESPONSE",securityTitle:"Security",securityVerifyPrefix:"Verify ",securityVerifySuffix:" with your secret",securityHttps:"Use HTTPS endpoints only",securityAsync:"Return 2xx immediately, process async",securityAutoDisable:"Auto-disabled after 10 consecutive failures"},apiKeys:{title:"API Keys",keyCount:"{{count}} keys",playground:"Playground",create:"+ Create",scopeDaemonRead:"Daemon Read",scopeDaemonReadDesc:"List daemons & status",scopeDaemonControl:"Daemon Control",scopeDaemonControlDesc:"Commands, launch/stop, disconnect",scopeAgentRead:"Agent Read",scopeAgentReadDesc:"Status & chat history",scopeAgentControl:"Agent Control",scopeAgentControlDesc:"Send, approve/reject",scopeTerminal:"Terminal",scopeTerminalDesc:"Execute commands",scopeWebhooks:"Webhooks",scopeWebhooksDesc:"Manage hooks & deliveries",frozen:"Frozen",revokeConfirm:"Revoke this API key? This cannot be undone.",failedToLoad:"Failed to load",failed:"Failed",upgradePlan:"Upgrade your plan →",keyCreated:"Key Created!",copyNow:"Copy now — shown only once.",copied:"Copied",copy:"Copy",testKey:"Test",dismiss:"Dismiss",playgroundTitle:"API Playground",enterKeyToTest:"Enter an API key to test.",open:"Open",createKeyTitle:"Create API Key",labelName:"Name",namePlaceholder:"e.g. Production Bot",permissions:"Permissions ({{count}})",createBtn:"Create",cancel:"Cancel",loading:"Loading...",noKeys:"No API Keys",noKeysDesc:"Create a key to integrate with external services.",createFirstKey:"Create First Key",usedDate:"Used {{date}}",neverUsed:"Never used",revoke:"Revoke",usageLabel:"Usage:",apiReference:"API Reference →",frozenFeatureTitle:"Frozen — this feature is paused."},shareModal:{title:"Share Session",chatView:{label:"View Only",desc:"Read AI conversation in real-time"},chatControl:{label:"Control",desc:"Read + send messages + approve/reject actions"},remoteView:{label:"View Only",desc:"Watch screenshots + chat in real-time"},remoteControl:{label:"Control",desc:"Screenshots + send messages + approve/reject"},remoteFull:{label:"Full Access",desc:"Full remote control including desktop input"}},onboarding:{title:"Connect your first machine",subtitle:"Install ADHDev on a machine and sign in — it pairs itself and shows up here. Then drive every agent on it from this dashboard.",platformMac:"macOS / Linux",platformWindows:"Windows",copyTitle:"Click to copy",copiedLabel:"✓ Copied",copyLabel:"Copy",listeningLabel:"Listening for your daemon — keep this page open, it will appear automatically.",connectingLabel:"Connecting to ADHDev…",step1Title:"Install the daemon",step1Desc:"Run the command above on any machine you want to drive. It installs the daemon plus the adhdev CLI.",step2Title:"Sign in — the machine pairs itself",step2Desc:"The daemon links to this account automatically. No token to copy; it appears here the moment it connects.",step3Title:"Launch your first session",step3Desc:"Once a machine is online, start Claude Code, Codex, Cursor, and other agents straight from the dashboard.",readDocs:"Read the documentation →",reconnectingLabel:"Connection lost — reconnecting… Check your network if this persists.",offlineLabel:"You're offline. Reconnect to the internet and this page will resume automatically.",authFailedLabel:"Session expired — sign in again to continue.",machineLimitLabel:"Machine limit reached — your plan allows up to {{limit}}. Remove a machine or upgrade your plan to connect this one.",machineLimitManage:"Manage machines →",machineLimitUpgrade:"Upgrade plan →",setupWizardLink:"Prefer a guided setup? Open the Setup Wizard →"},legal:{navHome:"Home",navDashboard:"Dashboard",footerHome:"Home",footerTerms:"Terms",footerPrivacy:"Privacy",footerRefund:"Refund Policy",footerCopyright:"© 2026 RacoLab. All rights reserved."},authCallback:{authFailed:"Authentication Failed",backToLogin:"Back to Login",completing:"Completing authentication...",noTokenError:"No access token received"},cliAuth:{title:"ADHDev CLI Authentication",verifying:"Verifying...",authorizeAs:"Authorize CLI as {{name}}?",noCodeError:"No authentication code provided.",approve:"✓ Approve",signInFirst:"Please sign in first to authorize the CLI.",signIn:"Sign In →",failed:"Failed",successMessage:"CLI authentication complete!",returnToTerminal:"You can return to the terminal.",registryPublishTitle:"Authorize Registry Publishing",authorizeRegistryPublishAs:"Grant provider registry publishing access as {{name}}?",registryPublishWarning:"This grants a short-lived token (15 minutes) that can publish, promote and yank provider packages in the registry. It is not a daemon registration. Only approve this if you started a registry publish yourself. Requires an admin account.",signInFirstRegistryPublish:"Please sign in with an admin account to authorize registry publishing.",approving:"Approving…",errorFriendly:"Couldn't complete CLI authorization.",tryAgain:"Try again"},privacy:{title:"Privacy Policy",lastUpdated:"Last updated: September 27, 2026",intro:'This Privacy Policy describes how RacoLab ("we", "us", "our") collects, uses, and protects your information when you use the ADHDev service ("Service") at',s1Title:"1. Information We Collect",s1h1:"1.1 Account Information",s1p1:"When you create an account, we collect information provided by your authentication provider (GitHub or Google), including your name, email address, and profile picture.",s1h2:"1.2 IDE & Agent Data",s1p2:"When you connect your development environment to the Service, the local daemon may transmit:",s1l1:'IDE type and version (e.g., "Cursor 0.49.1")',s1l2:"Active AI agent information (name, status, current model)",s1l3:"Chat messages between you and AI agents",s1l4:"IDE screenshots (transmitted via P2P, not stored on our servers)",s1l5:"Workspace paths and open file names",s1l6:"Machine information (hostname, OS, memory usage)",s1h3:"1.3 Usage Data",s1p3:"We automatically collect usage information including API calls, feature usage patterns, and connection logs for service improvement and debugging purposes.",s1p3Attribution:"We also count visits by traffic source in aggregate only (campaign tags such as utm_source, the referring website's domain and the landing page, kept in your browser's local storage — no IP address, device identifier or cookie), and when you create an account we record the source of your first visit so we can see which channels bring new users.",s1h4:"1.4 Payment Information",s1p4:"Payment processing is handled entirely by our Merchant of Record, Paddle (Paddle.com Market Limited). We do not directly collect or store credit card numbers, bank account details, or other financial information. Please refer to",s1p4PaddleLink:"Paddle's Privacy Policy",s1p4Suffix:"for their data handling practices.",s2Title:"2. How We Use Your Information",s2p1:"We use collected information to:",s2l1:"Provide and maintain the Service",s2l2:"Authenticate your identity and manage your account",s2l3:"Route commands and data between your dashboard and connected machines",s2l4:"Send notifications (browser and push) about agent status changes",s2l5:"Process billing and subscription management (via Paddle)",s2l6:"Detect and prevent abuse or unauthorized access",s2l7:"Improve the Service and develop new features",s2l8:"Respond to support requests",s3Title:"3. Data Storage & Security",s3h1:"3.1 Infrastructure",s3p1:"Our Service runs on Cloudflare's global network using Cloudflare Workers, Durable Objects, and D1 Database. Data is stored in Cloudflare's infrastructure and is subject to",s3p1CloudflareLink:"Cloudflare's Privacy Policy",s3h2:"3.2 P2P Data",s3p2:"IDE screenshots and real-time terminal data are transmitted directly between your browser and your machine via WebRTC peer-to-peer connections. This data does not pass through or get stored on our servers.",s3h3:"3.3 Security Measures",s3p3:"We implement the following security measures:",s3l1:"JWT-based authentication with short-lived access tokens and refresh token rotation",s3l2:"Encrypted WebSocket connections (WSS/TLS)",s3l3:"Per-connection tokens for daemon authentication",s3l4:"Rate limiting on all API endpoints",s3l5:"Audit logging for security-sensitive operations",s4Title:"4. Data Sharing",s4p1:"We do not sell your personal data to third parties. We may share data with:",s4l1:"Payment processing as Merchant of Record",s4l2:"Infrastructure provider (hosting, CDN, database)",s4l3Label:"Authentication providers",s4l3:"GitHub/Google for OAuth login",s4p2:"We may disclose data if required by law, legal process, or to protect our rights and the safety of our users.",s5Title:"5. Data Retention",s5p1:"We retain your account data for the duration of your active account. Chat messages and agent activity data are retained for up to 90 days for service functionality.",s5p2:"Upon account deletion, we will remove your personal data within 30 days. Some anonymized usage data may be retained for analytical purposes.",s6Title:"6. Your Rights",s6p1:"You have the right to:",s6l1Label:"Access",s6l1:"Request a copy of your personal data",s6l2Label:"Correction",s6l2:"Update or correct your personal information",s6l3Label:"Deletion",s6l3:"Request deletion of your account and associated data",s6l4Label:"Export",s6l4:"Download your data in a portable format",s6l5Label:"Object",s6l5:"Object to certain data processing activities",s6p2:"To exercise these rights, contact us at",s7Title:"7. Cookies",s7p1:"We use essential cookies only for authentication (session tokens) and user preferences (theme, notification settings). We do not use advertising or tracking cookies.",s8Title:"8. Children's Privacy",s8p1:"The Service is not intended for users under the age of 16. We do not knowingly collect personal information from children under 16.",s9Title:"9. International Data Transfers",s9p1:"Your data may be processed in various locations through Cloudflare's global network. By using the Service, you consent to the transfer and processing of your data in these locations.",s10Title:"10. Changes to This Policy",s10p1:"We may update this Privacy Policy from time to time. We will notify you of any material changes by email or through the Service. Your continued use after changes constitutes acceptance of the updated policy.",s11Title:"11. Contact",s11p1:"For questions about this Privacy Policy or data practices:",s11l1Prefix:"Email:",s11l2Prefix:"Website:"},terms:{title:"Terms of Service",lastUpdated:"Last updated: April 11, 2026",intro:'Welcome to ADHDev ("Service"), operated by RacoLab ("we", "us", "our"). By accessing or using our Service at',introSuffix:'you agree to be bound by these Terms of Service ("Terms"). If you do not agree, do not use the Service.',s1Title:"1. Service Description",s1p1:"ADHDev is a cloud developer tool that provides remote monitoring and control of AI coding agents (such as Cursor, VS Code, Antigravity, Claude Code, and others) through web and mobile dashboard surfaces. The Service includes a local daemon, remote dashboards, REST API access, and browser and push notifications.",s2Title:"2. Account Registration",s2p1:"You must create an account to use the Service. You are responsible for maintaining the confidentiality of your account credentials. You agree to provide accurate and complete information during registration and to keep your account information up to date.",s2p2:"You must be at least 16 years old to use the Service. By creating an account, you represent that you meet this age requirement.",s3Title:"3. Subscription Plans & Billing",s3p1:"The Service offers the following plans:",s3l1:"Limited features, 1 connected machine",s3l2:"2 connected machines, unlimited agents, P2P remote view, 7-day free trial",s3l3:"5 connected machines, everything in Pro plus higher concurrency and usage limits (flat price, not per-seat)",s3p2:"Paid subscriptions are billed in advance on a monthly or yearly basis. All payments are processed by our payment partner, Paddle (Paddle.com Market Limited), who acts as the Merchant of Record for all transactions.",s4Title:"4. Refund Policy",s4p1:"We offer a 14-day money-back guarantee for all paid plans. If you are not satisfied with the Service, you may request a full refund within 14 days of your initial purchase by contacting us at",s4p2:"Refunds for renewals are handled on a case-by-case basis. Paddle's refund policies also apply as they are the Merchant of Record.",s5Title:"5. Acceptable Use",s5p1:"You agree not to:",s5l1:"Use the Service for any unlawful purpose or in violation of any applicable laws",s5l2:"Attempt to gain unauthorized access to other users' accounts or data",s5l3:"Reverse-engineer, decompile, or attempt to extract the source code of the Service's server components",s5l4:"Use the Service to transmit malware, spam, or other harmful content",s5l5:"Resell or redistribute the Service without our written consent",s5l6:"Interfere with or disrupt the integrity or performance of the Service",s6Title:"6. Intellectual Property",s6p1:"The Service, including its original content, features, and functionality, is owned by RacoLab and is protected by applicable intellectual property laws. The local daemon component is available under an open-source license as specified in the project repository.",s6p2:"You retain ownership of all data and content you transmit through the Service.",s7Title:"7. Data & Privacy",s7p1:"Your use of the Service is also governed by our",s7PrivacyLink:"Privacy Policy",s7p1Suffix:"The Service processes IDE interactions, chat messages, and screenshots for the purpose of remote monitoring and control. We do not sell your data to third parties.",s8Title:"8. Service Availability",s8p1:"We strive to maintain high availability but do not guarantee uninterrupted access. The Service may be temporarily unavailable due to maintenance, updates, or circumstances beyond our control. We are not liable for any losses resulting from service interruptions.",s9Title:"9. Limitation of Liability",s9p1:"TO THE MAXIMUM EXTENT PERMITTED BY LAW, RacoLab SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR ANY LOSS OF PROFITS OR REVENUES, WHETHER INCURRED DIRECTLY OR INDIRECTLY, ARISING OUT OF YOUR USE OF THE SERVICE.",s9p2:"Our total liability for any claim arising from the Service shall not exceed the amount you paid us in the 12 months preceding the claim.",s10Title:"10. Termination",s10p1:"We may suspend or terminate your access to the Service at any time for violations of these Terms or for any other reason at our sole discretion. You may cancel your account at any time through the Settings page. Upon cancellation, your data will be deleted within 30 days.",s11Title:"11. Changes to Terms",s11p1:"We reserve the right to modify these Terms at any time. We will notify you of material changes via email or through the Service. Your continued use after changes constitutes acceptance of the modified Terms.",s12Title:"12. Governing Law",s12p1:"These Terms shall be governed by and construed in accordance with the laws of the Republic of Korea, without regard to conflict of law provisions.",s13Title:"13. Contact",s13p1:"If you have any questions about these Terms, please contact us:",s13l1Prefix:"Email:",s13l2Prefix:"Website:"},refund:{title:"Refund Policy",lastUpdated:"Last updated: March 24, 2026",intro:"ADHDev is operated by RacoLab. All payments are processed by our Merchant of Record,",introSuffix:"who manages billing, invoicing, and refunds on our behalf.",s1Title:"1. 14-Day Money-Back Guarantee",s1p1:"We offer a 14-day money-back guarantee on all paid plans (Pro). If you are not satisfied with the Service for any reason, you may request a full refund within 14 days of your initial subscription purchase.",s1p2:"To request a refund, contact us at",s1p2Suffix:"with your account email and order details. We will process your request within 3 business days.",s2Title:"2. Renewal Refunds",s2p1:"Refunds for subscription renewals (monthly or yearly) are handled on a case-by-case basis. If you were charged for a renewal you did not intend, please contact us within 7 days of the charge at",s3Title:"3. Non-Refundable Cases",s3p1:"Refunds will not be issued for:",s3l1:"Requests made after the 14-day guarantee period for initial purchases",s3l2Prefix:"Accounts suspended or terminated due to violations of our",s3l2Link:"Terms of Service",s3l3:"Partial months of service already used beyond the refund window",s4Title:"4. How Refunds Are Processed",s4p1:"Approved refunds are processed through Paddle and returned to the original payment method. Depending on your bank or card issuer, refunds may take 5–10 business days to appear. Paddle's own",s4p1RefundLink:"refund terms",s4p1Suffix:"also apply.",s5Title:"5. Cancellation",s5p1Prefix:"You may cancel your subscription at any time from the",s5p1BillingLink:"Billing",s5p1Suffix:"page in your dashboard. Cancellation stops future charges. You retain access to your plan's features until the end of the current billing period. Cancellation alone does not trigger a refund.",s6Title:"6. Contact",s6p1:"For refund requests or billing questions:",s6l1Prefix:"Email:",s6l2Prefix:"Website:"},sessionShare:{loading:"Loading session...",sessionNotFound:"Session Not Found",noLongerAvailable:"This session is no longer available",homeBtn:"← ADHDev Home",sharedSession:"Shared Session",host:"Host",mode:"Mode",permission:"Permission",auth:"Auth",authRequired:"Account required",viewers:"Viewers",joinChat:"Join Chat",joinSession:"Join Session",expires:"Expires: {{date}}",chatLabel:"Chat",remoteLabel:"Remote",waitingMessages:"Waiting for messages...",connecting:"Connecting... ({{state}})",sendMessageAs:"Send message as {{name}}...",sendAs:"Send as {{name}}...",ownerChat:"{{name}}'s Chat",ownerSession:"{{name}}'s Session",agentName:"{{name}}'s Agent",fullControlBadge:"Full Control Active",failedToJoin:"Failed to join session",sessionRevoked:"Session has been revoked by the host",sessionExpired:"Session has expired",authRequired2:"Authentication required for control share",unknownError:"Unknown error"},apiPlayground:{title:"API Playground",history:"History ({{count}})",apiRelayWarning:"Daemon API relay is opt-in. REST command/chat proxy routes stay disabled unless that daemon explicitly enables them with `adhdev daemon:api enable`.",authBearer:"Authorization: Bearer {{key}}",copyAsCurl:"cURL",copied:"Copied",targetDaemon:"Target Daemon",quickActions:"Quick Actions",requestBody:"Request Body (JSON)",recentRequests:"Recent Requests",clearHistory:"Clear",noDaemonsWarning:"No daemons connected. Start a daemon first or replace {daemonId} manually.",send:"▶ Send",sending:"⏳"},announcementBanner:{visibleUntil:"Visible until {{time}}",dismiss:"Dismiss"},push:{budgetResetsShort:"Resets at {{time}}",budgetRemainingShort:"{{count}} left on your plan today",budgetShort:"{{used}}/{{limit}} today",title:"Push Notifications",descUnsupported:"Not supported in this browser",descDenied:"Blocked — enable in browser settings",descEnabled:"On",descDefault:"Alerts even when the tab is closed",docsLink:"Push Notifications docs",sent:"Sent",test:"Test",iosHint:"On iPhone and iPad, push only works from the installed Safari PWA. A normal Safari tab cannot receive ADHDev push notifications.",unsupportedWarning:"This browser does not support Web Push here. Use Safari PWA on iPhone/iPad or a Chromium browser on desktop/Android.",deniedWarning:"Notifications are blocked in browser or site settings. Re-enable them there, then turn Push Notifications on again.",registeredDevices:"Registered devices: {{count}}",noDevices:"No active push devices found.",deviceLabel:"Device {{number}}",thisDevice:"This device",lastActive:"Last active",removing:"Removing...",removeHere:"Remove here",remove:"Remove"},mesh:{manualMcpSetup:"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",couldNotLoadMeshes:"Could not load meshes",untitledMesh:"Untitled mesh",chooseMachineFirst:"Choose a machine first.",launchFailed:"Launch failed",coordinatorLaunchFailed:"Coordinator launch failed",coordinatorLaunched:"Coordinator launched ({{sessionId}})",coordinatorLaunchSent:"Coordinator launch command sent"},plans:{free:"Free",pro:"Pro",ultra:"Ultra",team:"Team",enterprise:"Enterprise"},adminAudit:{title:"Global Audit",subtitle:"System-wide event tracking",allActions:"All Actions",allSources:"All Sources",filter:"Filter",noLogs:"No logs found",loading:"Loading...",loadMore:"Load More ↓"},adminDashboard:{failedToLoad:"Failed to load admin data",title:"Admin Dashboard",subtitle:"Service overview & management",accessDenied:"Admin access denied",backToDashboard:"Back to Dashboard",loading:"Loading admin dashboard",loadingDesc:"Collecting service stats and recent audit activity.",totalUsers:"Total Users",todayCommands:"Today Commands",activeApiKeys:"Active API Keys",todayLogins:"Today Logins",planDistribution:"Plan Distribution",quickActions:"Quick Actions",manageUsers:"Manage Users",apiKeys:"API Keys",auditLogs:"Audit Logs",systemConfig:"System Config",recentActivity:"Recent Activity",viewAll:"View All",noRecentActivity:"No recent activity"},adminTokens:{title:"Admin Tokens",subtitle:"Issue admin-scoped API tokens for deploy automation",superAdminOnly:"Super admin only",superAdminOnlyDesc:"Only a super admin can issue admin tokens. Ask a super admin if you need one.",issueTitle:"Issue a new token",nameLabel:"Name",namePlaceholder:"e.g. deploy-ci",scopesLabel:"Scopes",scopesHint:"admin covers most admin APIs. super_admin also allows issuing tokens and changing roles — grant it only when required.",expiryLabel:"Expires in",expiryDays:"{{count}} days",expiryHint:"Admin tokens always expire. The server caps the lifetime at 90 days.",issue:"Issue token",issuing:"Issuing...",issuedTitle:"Copy your token now",issuedWarning:"This is the only time the token is shown. Store it somewhere safe — you cannot retrieve it again.",issuedMeta:"Scopes: {{scopes}} · Expires: {{expiresAt}}",copy:"Copy",copied:"Copied",copyFailed:"Copy failed — select the token and copy it manually",dismiss:"Dismiss",expiryClamped:"Expiry was shortened to the 90-day maximum",existingTitle:"Active admin tokens",emptyTitle:"No admin tokens",emptyDesc:"Issue one above to authenticate deploys without the browser login.",expiresAt:"Expires: {{time}}",lastUsed:"Last used {{time}}",neverUsed:"Never used",noExpiry:"No expiry",expired:"Expired",revoke:"Revoke",revokeConfirm:'Revoke the token "{{name}}"? Anything using it will stop working immediately.',revoked:"Token revoked",loading:"Loading...",error:"Error: {{message}}"},adminSystem:{error:"Error: {{message}}",announcementSent:"Announcement sent",announcementCleared:"Announcement cleared",title:"System Settings",subtitle:"Announcements & system configuration",loading:"Loading system settings",loadingDesc:"Fetching current announcement state.",announcement:"Announcement",current:"Current:",untilTime:"(until {{time}})",untilCleared:"(until cleared)",announcementPlaceholder:"Enter announcement message...",severityInfo:"Info",severityWarning:"Warning",severityCritical:"Critical",duration1h:"1 hour",duration6h:"6 hours",duration24h:"24 hours",duration7d:"7 days",durationUntilCleared:"Until cleared",send:"Send"},adminUsers:{error:"Error: {{message}}",roleUpdated:"Role updated",planUpdated:"Plan updated",suspensionReasonPrompt:"Enter suspension reason:",userSuspended:"User suspended",userUnsuspended:"User unsuspended",title:"User Management",subtitle:"Manage users, roles, and suspension",usersTotal:"users total",searchPlaceholder:"Search email or name...",allRoles:"All Roles",roleUser:"User",roleAdmin:"Admin",roleSuperAdmin:"Super Admin",allPlans:"All Plans",search:"Search",colUser:"User",colRole:"Role",colPlan:"Plan",colStatus:"Status",colCreated:"Created",colActions:"Actions",noName:"No name",statusSuspended:"Suspended",statusActive:"Active",unsuspend:"Unsuspend",suspend:"Suspend",loading:"Loading...",prev:"← Prev",next:"Next →"}},pk={onboardingTour:{next:"Next",getStarted:"Get started",learnMore:"Learn more in the docs",closeAria:"Close onboarding",allSetStandalone:{desc:"This dashboard is already connected to your local daemon. Start a session from the Dashboard tab, or add more providers under Machines → Providers.",title:"You're all set"},getStartedCloud:{desc:"Run this on any machine you want to drive, then sign in — the daemon pairs itself to your dashboard automatically.",title:"Get started"},orchestrate:{desc:"Repo Mesh (Cloud Pro) lets one coordinator hand work to agents across many machines — parallel git worktrees, automatic branch convergence, and cross-checking the same repo from several angles.",title:"Orchestrate your agents"},watchAndSteer:{desc:"Follow each agent's session in real time and steer it as it works — switch sessions, take screenshots, and (for IDE sessions) view and control the screen over a direct connection.",title:"Watch and steer, live"},realtimeChat:{desc:"See what your AI agent is doing in real time. Send messages, approve or reject actions — all from your browser or phone.",title:"Real-time chat"},welcome:{desc:"Drive any local CLI coding agent — Claude Code, Codex, Antigravity CLI — straight from your browser or phone. The agents keep running on your machine; you control them from the web.",title:"Welcome to ADHDev"}},installCommand:{orViaNpm:"Or via npm:",clickToCopy:"Click to copy"},errorBoundary:{reload:"Reload page",description:"An unexpected error occurred. Please reload the page to continue.",title:"Something went wrong"},shellFreshness:{dismissAria:"Dismiss update notice",later:"Later",reload:"Reload",message:"A new version of ADHDev is available."},dashboardWire:{reloadTitle:"Reload required",reloadBody:"This page is older than the daemon it talks to, so it cannot read the daemon's state. Reload to get the current dashboard.",reload:"Reload",daemonUpdateTitle:"Daemon update required",daemonUpdateBody:"{{count}} machine(s) run an older daemon this dashboard cannot read. Update them with `adhdev update` (or the machine page's update action)."},openMenu:"Open menu",closeMenu:"Close menu"},fk={loadingOlderMessages:"Loading older messages...",waitingForMessages:"Waiting for messages...",agentGenerating:"Agent generating...",jumpToTop:"Jump to top",jumpToOldestMessages:"Jump to oldest messages",top:"↑ Top",latest:"↓ Latest",jumpToLatestMessages:"Jump to latest messages",jumpToBottom:"Jump to bottom",showEarlierMessages:"↑ Show {{count}} earlier messages...",showEarlierMessagesHidden:"↑ Show {{count}} earlier messages... ({{total}} hidden)",loadOlderMessages:"↑ Load older messages",loadErrorRetry:"↻ {{error}}"},bk={zoomOut:"Zoom Out",zoomIn:"Zoom In",resetZoom:"Reset Zoom",toggleFullscreen:"Toggle Fullscreen"},gk={screenshotAlt:"Remote View",mouse:"Mouse",touch:"Touch",connected:"Connected",ws:"Reconnecting",direct:"Direct",relay:"Relay",turnBlocked:"Daily view limit reached",turnUsage:"View {{used}}/{{budget}}m",typeAndEnter:"Type & Enter...",settings:"SETTINGS",zoom:"ZOOM:",fill:"FILL",fit:"FIT",directP2PTitle:"Direct P2P connection",turnRelayTitle:"TURN relay in use",dailyTurnTitle:"Remote view minutes used today (plan limit)",waitingState:{turnRelayActive:"TURN relay active"},waiting:{connectedLabel:"Connected. Waiting for first frame...",connectingLabel:"Connecting to Host...",reconnectingLabel:"Reconnecting to Host...",connectedHint:"The remote stream is warming up",reconnectingHint:"Waiting for the remote stream to catch up"},error:{title:"Remote connection lost",reasonFailed:"The connection to this host failed. Check that the daemon is running and try again.",reasonDisconnected:"Lost connection to the host and could not reconnect after 15 seconds.",retry:"Retry"},screenshotViewer:{altText:"IDE Screenshot",waitingForStream:"Waiting for screenshot stream...",p2pStatus:"P2P: {{state}}"}},xk={openChat:"Open chat",openCoordinatorChat:"Open coordinator chat",coordinatorGone:"coordinator session ended",chatNotFound:"No chat tab for this session on this dashboard — it may be running on another machine.",openChatHint:"Click to open this session’s chat"},yk={meshNodeUnavailable:"Mesh node info unavailable",roleCoordinator:"Mesh coordinator",rowProviderType:"Provider type",rowStarted:"Started",copyDiagnostics:"Copy diagnostics",gitClean:"clean",gitDirty:"uncommitted changes",gitDetached:"(detached)",blockRawMetadata:"Raw runtime metadata",blockFinalPrompt:"Final system prompt",blockExtraPrompt:"Extra prompt for this launch",quotaOkNoWindows:"No limit",sectionMeshWorker:"Spawned by coordinator",rowMeshId:"Mesh ID",rowTaskId:"Task",rowCoordinator:"Coordinator",title:"Session info",loading:"Loading…",close:"Close",failedToLoad:"Failed to load session info",stampedToNode:"This session is stamped to a mesh node that the coordinator no longer reports.",sectionSession:"Session",sectionLaunch:"Launch",sectionMeshNode:"Mesh node",sectionMeshCoordinator:"Mesh coordinator",sectionRuntime:"Runtime",rowSessionId:"Session ID",rowProvider:"Provider",rowTransport:"Transport",rowWorkspace:"Workspace",rowSpawnedAt:"Spawned at",rowProviderSessionId:"Provider session ID",rowMachine:"Machine",rowConnection:"Connection",rowCommand:"Command",rowWorkingDirectory:"Working directory",rowArgs:"Args",rowExtraArgs:"Extra args",rowExtraEnv:"Extra env",rowNodeId:"Node ID",rowRepoRoot:"Repo root",rowDaemonId:"Daemon ID",rowRole:"Role",rowMachineStatus:"Machine status",rowHealth:"Health",rowWorktree:"Worktree",rowLaunchReady:"Launch ready",rowGit:"Git",rowProviders:"Providers",rowProviderPriority:"Provider priority",rowCoordinatorCli:"Coordinator CLI",rowStartedAt:"Started at",rowPromptInjection:"Prompt injection",rowMcpConfig:"MCP config",rowRuntimeId:"Runtime ID",rowLifecycle:"Lifecycle",rowSurface:"Surface",rowRecoveryState:"Recovery state",rowRestoredFromStorage:"Restored from storage",rowAttachedClients:"Attached clients"},vk={mobile:{noHistoryMatches:"No saved history matches these filters.",workspaceMissing:"(workspace missing)",resumableOnly:"Only ones that can be resumed",sortMessages:"Most messages",sortOldest:"Oldest first",sortRecent:"Most recent",filterModel:"Filter by model",filterWorkspace:"Filter by workspace",searchHistory:"Search title or preview",useThisFolder:"Use this folder",browseDescription:"Move through folders like a normal file browser, then use the current folder for this machine.",browseTitle:"Select workspace",machineDetails:"Machine details",inspect:"Inspect",showMore:"Show {{count}} more",showFewer:"Show fewer",recentLaunches:"Recent launches",currentChats:"Current chats",machineFallback:"machine"},daemonUpdate:{previewUnknownDescription:"The app is connected to preview, but the server hasn't reported a preview target version yet.",previewUpToDateDescription:"This machine already runs the current preview daemon.",previewUnknownTitle:"Preview update status unknown",previewUpToDateTitle:"Preview daemon is up to date",mismatchDescription:"This machine runs a different daemon version than the current app. Update it before starting more sessions.",previewUpgradeDescription:"This machine can be updated to the current preview daemon without opening a remote shell.",requiredDescription:"This machine is on an incompatible daemon version. Update it before starting more sessions.",mismatchTitle:"Version mismatch detected",requiredTitle:"Daemon update required",upgrade:"Update",updateNow:"Update now"},launchPick:{empty:"No saved workspaces yet. Add one in the Workspace tab or type a path above.",description:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path.",title:"Where should this run?"},trustBadge:{externalUntrustedHint:"From a source you added, and it includes code that ADHDev will run. Review the source before enabling.",externalSafeHint:"From a source you added. Settings only — ADHDev never runs code from it.",trustedWithScriptsHint:"Provided officially by ADHDev. Includes scripts that ADHDev runs.",trustedHint:"Provided officially by ADHDev. Settings only — no provider code runs.",userCustomHint:"You wrote this provider in your own providers folder. It runs your own code.",externalUntrusted:"External · runs code",externalSafe:"External",trustedWithScripts:"Official · scripts",trusted:"Official",userCustom:"Custom"},providerSettings:{option:{high:"High",medium:"Medium",low:"Low"},notifications:{description:"Show notifications when {{provider}} changes state.",label:"Notifications"},showCoordinatorSystemPrompt:{description:"Show the injected system prompt as a message in the chat. Off by default — you can always see it in the chat header's Session Info (ⓘ).",label:"Show system prompt message"},showTerminal:{description:"Show terminal commands and their output in the chat.",label:"Show terminal"},showToolCalls:{description:"Show short summaries of tool calls (searched, edited, …) in the chat.",label:"Show tool calls"},showThinking:{description:"Show the agent's reasoning in the chat.",label:"Show thinking"},longGeneratingThresholdSec:{description:"How long a reply can run before the long-running alert fires.",label:"Long-running threshold (seconds)"},longGeneratingAlert:{description:"Notify you when a reply takes unusually long.",label:"Long-running alert"},approvalAlert:{description:"Notify you when {{provider}} is waiting for your approval.",label:"Approval notifications"},appPathOverride:{description:"Optional full path to the IDE app. Leave blank to look in the usual install locations.",label:"App path"},cliPathOverride:{description:"Optional full path to the IDE command-line launcher. Leave blank to use the detected one.",label:"CLI launcher path"},executableArgs:{description:"Optional arguments that replace the default ones when {{provider}} starts. Leave blank to use the defaults.",label:"Launch arguments"},executablePath:{description:"Optional full path to the {{provider}} program. Leave blank to find it on your PATH.",label:"Executable path"},autoApprove:{description:"Approve {{provider}} tool calls and prompts automatically, without asking you first.",label:"Auto approve"},enabled:{description:"Turn this on before ADHDev detects, launches, or checks {{provider}} on this machine.",label:"Enabled on this machine"},thisProvider:"this provider"},launchConfirm:{workspace:"Workspace",languageModel:"Language Model (Optional)",autoDetect:"Auto-detect or default",cliArgs:"CLI Arguments (Optional)",cliArgsPlaceholder:"e.g. --experimental",cancel:"Cancel",closeAria:"Close launch confirmation",launch:"Launch",launching:"Launching…"},confirmExternal:{aboutToActivateFrom:"You're about to turn on {{provider}} from {{source}}.",aboutToActivate:"You're about to turn on {{provider}}.",dialogAria:"Confirm untrusted external provider",title:"Activate untrusted external provider?",description:"This manifest ships JavaScript that the daemon will execute. Treat as untrusted code — review the source before enabling.",proceedWarning:"Only proceed if you trust the source URL you added and have reviewed the manifest.",cancel:"Cancel",activate:"Activate"},providers:{advancedHint:"Sources, load paths and provider details",filter:"Filter",sourceConfigTitle:"Provider source config",sourceConfigDesc:"Where the daemon looks for provider manifests. Affects resolution and reloads.",sourceMode:"Source mode",explicitProviderDir:"Explicit providerDir",providerDirPlaceholder:"Leave blank to use ~/.adhdev/providers",applying:"Applying…",applyReload:"Apply + Reload",userRoot:"User root:",upstreamRoot:"Upstream root:",providerRoots:"Provider roots:",loadingSettings:"Loading provider settings…",noProviders:"No providers installed yet — use Install above, or add a source under Advanced.",noFilteredProviders:"No {{filter}} providers installed.",refresh:"Refresh",updateAll:"Update all",advanced:"Advanced",newChannelTypesTitle:"Available to install",newChannelTypesDesc:"Published to the verified channel but never installed on this machine. Install activates the digest-verified bundle.",installNewType:"Install",modelListTitle:"Model lists",modelListStaleDesc:"Could not read the model list from these CLIs (signed out, offline, or unsupported output). The provider manifest's list is being used and may be out of date.",modelListStaleBadge:"unverified",installFailedTitle:"Install failed",installFailedDigestMismatch:"Install failed — try later",loadFailed:"Failed to load provider settings: {{error}}",quotaToggleFailed:"Failed to update quota probe for {{provider}}: {{error}}"},sourcesPanel:{title:"External sources",description:"3rd-party git URLs you've added. Providers here may ship JavaScript the daemon will execute — activation requires a confirmation.",addSource:"+ Add source",empty:'No external sources registered. Use "+ Add source" to register a 3rd-party provider git URL.',remove:"Remove",removing:"…",removeConfirmTitle:"Remove provider source {{name}}?",removeConfirmDescription:"This deletes the cloned manifests and clears any active-source entries that pointed here.",removeConfirmLabel:"Remove",conflictsTitle:"Conflicts",conflictsDescription:"Multiple sources expose the same provider type. Pick which source's copy should be active.",active:"Active",switchActiveTo:"Switch active to {{name}}",addTitle:"Add external source",gitUrl:"Git URL",ref:"Ref (branch/tag)",name:"Name (optional, auto-derived from URL)",cancel:"Cancel",cloning:"Cloning…",cloneAndRegister:"Clone + register",loadFailed:"Failed to load sources",addFailed:"Failed to add source",removeFailed:"Failed to remove source",setActiveFailed:"Failed to set active source"},providerRow:{detectDisabledHint:"Turn the provider on before checking it",detectHint:"Check that the configured program can be found and run",lifecycleDeprecated:"No longer supported",lifecycleExperimental:"Experimental",lifecycleBeta:"Beta",lifecycleStable:"Stable",checkFailed:"Failed",checkOk:"OK",statusDetected:"Detected",statusNotDetected:"Not detected",statusEnabledUnchecked:"Enabled (unchecked)",statusDisabled:"Disabled",labelType:"Type:",labelVersion:"Version:",labelBinary:"Binary:",labelStatus:"Status:",labelDetails:"Details:",labelSource:"Source:",labelTrust:"Trust:",labelLinks:"Links:",labelDetection:"Detection:",labelVerification:"Verification:",saving:"saving…",disable:"Disable",enable:"Enable",detect:"Detect",resetCommand:"Reset command",quotaAccountLabel:"Show account on quota",quotaAccountLabelHint:"Label this provider's plan quota with the signed-in account. Off means the account is never fetched, not just hidden.",quotaAccountLabelOn:"On",quotaAccountLabelOff:"Off",quotaTracking:"Quota tracking",quotaTrackingHint:"Periodically read this provider's plan quota for the dashboards. Off stops the reads entirely.",quotaTrackingOn:"On",quotaTrackingOff:"Off",quotaClaudeConfirmTitle:"Enable Claude quota tracking?",quotaClaudeConfirmBody:"Claude Code has no quota API, so ADHDev reads usage through its statusLine — the only path available. Enabling replaces the statusLine command in ~/.claude/settings.json with the ADHDev wrapper. Your existing command keeps running inside the wrapper and its output is passed through unchanged, so your prompt looks the same. No other setting in the file is modified. The current value is backed up first and can be restored with `adhdev quota claude:uninstall`.",quotaClaudeConfirmOk:"Enable and install",quotaClaudeConfirmCancel:"Cancel",labelSpecPin:"Spec pin:",labelActivatedAt:"Activated:",labelPreviousPin:"Previous pin:",labelDigest:"Digest:",specPinStale:"update {{latest}}",specPinStaleHint:"This machine loads an older spec. Channel offers {{latest}}.",updateInline:"Update",updateInlineHint:"Channel offers {{latest}}. Download, verify and activate it on this machine.",specPinUpdating:"Updating…",specPinRollback:"Roll back",specPinRollbackHint:"Return to spec {{version}} (local, no download).",specPinRollingBack:"Rolling back…"},installOptions:{title:"Set up {{provider}}",quotaLabel:"Track plan usage",quotaHint:"Periodically read this provider's plan quota so the dashboards and `adhdev quota` can show what's left. Off stops the reads entirely — nothing is collected.",quotaClaudeNote:"Claude Code has no quota API, so this installs the ADHDev statusLine wrapper into ~/.claude/settings.json. Your existing command keeps running inside it, and the original is backed up.",autoApproveLabel:"Approve tool calls automatically",autoApproveHint:"When this agent asks permission to run a command, edit a file or use a tool, ADHDev answers yes for you. You will not see the approval prompt, and the action runs without waiting.",autoApproveWarning:"The agent can run commands on this machine without asking you first. Turn this off to approve each one yourself.",cancel:"Cancel",confirm:"Enable provider"},card:{status:{offline:"Offline",failed:"Connection failed",connecting:"Connecting…",online:"Online"},slowLink:"Slow link",coresCount_other:"{{count}} cores",coresCount_one:"{{count}} core",onMachine:"on {{machine}}",sectionIDEs:"IDEs",sectionCLIs:"CLIs",cpu:"CPU",mem:"MEM",loading:"Loading your machines…",emptyHeadline:"Welcome to ADHDev",emptyBody:"Connect your first machine to the dashboard. Install ADHDev on that machine and sign in — it pairs automatically and appears here:",emptyDocsLink:"Read the documentation →",hidden:"Hidden",pageTitle:"Machines",burrowCount_one:"{{count}} machine",burrowCount_other:"{{count}} machines",onlineCount_one:"{{count}} online",onlineCount_other:"{{count}} online",agentsActive_one:"{{count}} agent active",agentsActive_other:"{{count}} agents active",activeNow:"Active Now",generating:"generating",connectionFailed:"Connection failed",reconnect:"Reconnect",transportRelay:"Connected through a relay server — slower than a direct link. Usually a firewall or NAT blocks the direct path.",transportDirect:"Direct connection",noAgentsRunning:"No agents running yet",launchCta:"Launch →"},detail:{relaunchFailed:"Couldn't relaunch",launchProvider:"Provider",launchType:"Type",tabsAriaLabel:"Machine sections",tabSessions:"Sessions",notFound:"Machine not found",save:"Save",cancel:"Cancel",loading:"Loading machine...",offlineHint:"The machine may be offline or not yet connected.",back:"← Back",tabHostedRuntimes:"Hosted Runtimes",tabProviders:"Providers",tabSystem:"System",tabLogs:"Logs",clickToSetNickname:"Click to set nickname",nicknamePlaceholder:"Machine nickname...",reconnect:"Reconnect",p2pConnected:"connected",providerUpdatesAvailable:"Provider updates available",providerSyncSuccess:"Provider channel synced — {{count}} updated",providerSyncAlreadyCurrent:"Provider channel is already current",providerSyncFailed:"Provider update failed"},commandCenter:{updateStatusUnknown:"Update status unknown",upToDate:"Up to date",updateDaemon:"Update daemon",updateToVersion:"Update to v{{version}}",updateChannel:{preview:"preview",stable:"stable"},updateTargetWithChannel:"Target: v{{version}} ({{channel}})",updateTarget:"Target: v{{version}}",currentChats:"Current Chats",recentLaunches:"Recent Launches",daemonUpdate:"Daemon Update"},workspaceBrowse:{currentFolder:"Current folder",parent:"Parent",go:"Go",pathPlaceholder:"Type a folder path",loading:"Loading folders…",noSubfolders:"No subfolders here.",useThisFolder:"Use this folder"},managedWorkspaces:{setDefaultHint:"Set as default workspace",unsetDefaultHint:"Default workspace — click to unset",title:"Workspaces",addWorkspace:"Add workspace",empty:'No saved workspaces yet. Click "{{button}}" to pick a folder.',addDialogDescription:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",remove:"Remove",newSession:"Start a new session in this workspace",newSessionShort:"Session",newMeshSession:"Start a mesh coordinator session in this workspace",newMeshSessionShort:"Mesh",removeConfirmTitle:"Remove workspace",removeConfirmDescription:'Remove "{{label}}" from the list? The folder itself is not deleted.',rename:"Rename",renamePlaceholder:"Workspace name",saveName:"Save",cancelRename:"Cancel",renameFailed:"Could not update workspace name"},overview:{diagnostics:"Diagnostics",p2p:"P2P",daemonVersion:"Daemon version",cores:"CPU cores",platform:"Platform",hostname:"Hostname",aboutMachine:"This machine",approx:"(approx.)",memory:"Memory",cpuDetail:"{{load}} avg / {{cores}} cores",cpuLoad:"CPU load",resourceUsage:"Resource usage",waiting:"Waiting…",uptime:"Uptime",waitingForStats:"Waiting for live stats…",waitingForStatsWithTotal:"Waiting for live stats… · {{total}} total"},quota:{text:{failureKind:{unknown:"unknown error","no-data":"no reading yet","setup-required":"setup required",unsupported:"not supported","cli-unavailable":"program not found",parse:"unreadable response",server:"provider server error",network:"network error","rate-limited":"rate limited","quota-exhausted":"plan limit reached",unauthorized:"access denied","expired-token":"sign-in expired","missing-credentials":"not signed in"},agoDays:"{{days}}d {{hours}}h ago",agoHours:"{{hours}}h {{minutes}}m ago",agoMinutes:"{{minutes}}m ago",justNow:"just now",unreadable:"could not read quota",unavailable:"not available on this machine",pool:"pool",usageSessions:"{{count}} sess",usageTokens:"{{count}} tok",windowReset:"reset · awaiting refresh",cue:{stale:"stale",refreshing:"refreshing"},resetsInDays:"resets in {{days}}d {{hours}}h",resetsInHours:"resets in {{hours}}h {{minutes}}m",resetsInMinutes:"resets in {{minutes}}m",resetsNow:"resets now",used:"{{percent}}% used"},title:"Plan quota",sessionHint:"Rolling 5-hour plan window reported by this machine",weeklyHint:"Rolling 7-day plan window reported by this machine",monthlyHint:"Rolling 30-day billing window reported by this machine",bucketHint:"Per-pool quota bucket reported by this machine — pools on one plan reset independently",failureHint:"This machine reported that it could not read this provider's quota",okNoWindows:"No limit",okNoWindowsHint:"The quota fetch succeeded; this provider reports no percentage window (e.g. included-usage plans).",accountHint:"The signed-in account this quota belongs to, as reported by the provider CLI",usageHint:"Absolute usage over the trailing window — this provider routes to your own upstream accounts, so there is no plan limit to show a percentage against."},actions:{nicknameSyncFailed:"Nickname updated on the machine, but account sync failed",nicknameFailed:"Couldn't save nickname",nicknameTimeout:"The machine didn't answer — check its connection and try again",nicknameSaved:"Nickname saved",pathMissing:"The path may be missing on disk",workspaceActionFailed:"Workspace update failed",workspaceAdded:"Workspace added",detectFailed:"IDE detection failed",usingDefaultWorkspace:"Using the default workspace",runningInHome:"Running in the home directory",launchPending:"{{name}} is starting — it will appear shortly",launchFailed:"Couldn't launch {{name}}",launching:"Launching {{name}}…",stopCliConfirmDescription:"This will terminate the process.",stopIdeConfirmDescription:"This will disconnect CDP and optionally kill the process.",stopped:"{{name}} stopped",launched:"{{name}} launched",stopFailed:"Couldn't stop",restartInitiated:"{{name}} restart initiated",restartFailed:"Couldn't restart",selectProviderFirst:"Select a CLI provider first",selectProvider:"Select a provider",workspaceRemoved:"Workspace removed",workspaceLabelUpdated:"Workspace name updated",defaultWorkspaceUpdated:"Default workspace updated",defaultWorkspaceCleared:"Default workspace cleared",idesFound_one:"Found {{count}} IDE",idesFound_other:"Found {{count}} IDEs"},logsTabSections:{view:"View",filterInfo:"Info+ ({{count}})",filterIssues:"Issues ({{count}})",filterAll:"All ({{count}})",searchPlaceholder:"Search diagnostics…",copyDiagnostics:"Copy diagnostics",copyVisible:"Copy visible",pause:"Pause",resume:"Resume",refresh:"↻ Refresh",clear:"Clear",advancedSourceScope:"Advanced source scope",daemonLevelPlus:"Daemon {{level}}+",diagnosticsTimeline:"Diagnostics timeline",visibleEventsIssues:"{{events}} visible event(s) · {{issues}} issue signal(s)",filteredBy:"Filtered by “{{query}}”",mergedByTime:"Daemon, trace, and browser signals merged by time",latestIssue:"Latest issue",noVisibleIssue:"No visible warn/error signal",sourceStatus:"Source status",needsAttention:"Needs attention",livePolling:"Live polling every 3s",paused:"Paused",lastUpdate:"Last update: {{time}}",notYetLoaded:"Not yet loaded",rawFile:"raw file",sourceDaemon:"daemon",sourceTrace:"trace",sourceBrowser:"browser",repeatedIssuePatterns:"Repeated issue patterns",unifiedTimeline:"Unified timeline",visibleDiagnosticEvents:"{{count}} visible diagnostic event(s)",hide:"Hide",show:"Show",loadingDiagnostics:"Loading diagnostics…",daemonLogsError:"Daemon logs: {{error}}",daemonTraceError:"Daemon trace: {{error}}",noDiagnosticsMatch:"No diagnostics match the current view.",rawSourceDaemonLogs:"Raw source · daemon logs",visibleRawLinesFallback:"{{count}} visible raw line(s) from file fallback",visibleStructuredLines:"{{count}} visible structured line(s)",loadingDaemonLogs:"Loading daemon logs…",noDaemonLogsYet:"No daemon logs captured yet for this machine.",noRawLinesMatchSearch:"No raw daemon log lines match the current search.",rawFallbackOnlyInAll:"Raw file-fallback logs are available only in All view.",noStructuredLogsMatch:"No structured daemon logs match the current view.",rawSourceDaemonTrace:"Raw source · daemon trace",sessionHostOnly:"session_host only",visibleTraceEvents:"{{count}} visible trace event(s)",loadingDaemonTrace:"Loading daemon trace…",noTraceEntriesMatchSearch:"No trace entries match the current search.",noSessionHostTraceYet:"No session host trace entries yet.",noTraceEntriesYet:"No trace entries yet.",noPayload:"No payload",rawSourceBrowserEvents:"Raw source · browser debug events",visibleBrowserEvents:"{{count}} visible browser event(s)",noBrowserEventsMatchSearch:"No browser debug events match the current search.",noBrowserEventsYet:"No browser debug events captured yet."}},wk={transition:{recover:"Recovered",detach:"Detached",attach:"Attached",start:"Started",stop:"Stopped",restart:"Restarted",resume:"Resumed"},lastErrorLabel:"Last error",endpointLabel:"Endpoint",activeAgo:"active {{time}}",title:"Hosted Runtime Recovery",stopConfirmTitle:"Stop {{name}}?",stopConfirmDescription:"This will terminate the hosted runtime.",pruneConfirmTitle:"Prune duplicate hosted runtimes?",pruneConfirmDescription:"The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.",prune:"Prune",pruning:"Pruning…",pruneDuplicatesCount:"Prune duplicates ({{count}})",toastResumed:"Session host resumed: {{name}}",toastRestarted:"Session host restarted: {{name}}",toastStopped:"Session host stopped: {{name}}",toastPruned:"Pruned {{pruned}} duplicate runtime(s) across {{groups}} group(s)",actionFailed:"Session host action failed",pruneFailed:"Duplicate prune failed",diagnosticsFailed:"Could not load hosted runtime diagnostics",diagnosticsAttention:"Hosted runtime diagnostics need attention",stop:"Stop",stopping:"Stopping…",restart:"Restart",restarting:"Restarting…",resume:"Resume",resuming:"Resuming…",recover:"Recover",recovering:"Recovering…",refresh:"Refresh",refreshing:"Refreshing…",noWorkspace:"No workspace",clientsCount_one:"{{count}} client",clientsCount_other:"{{count}} clients",statLive:"Live runtimes",statRecovery:"Recovery",statRequests:"Requests",statStarted:"Started",latestWarning:"Latest host warning",liveTitle:"Live Hosted Runtimes",recoveryTitle:"Recovery Snapshots",inactiveTitle:"Inactive Records",recentActivity:"Recent Host Activity",liveEmpty:"No live hosted runtimes on this machine right now.",recoveryEmpty:"No recovery snapshots currently need attention.",transitionsEmpty:"No recent runtime transitions yet.",nextAction:"Next: {{action}}"},Sk={managed:"Managed",checking:"Checking…",diagnosticsIssue:"Diagnostics issue",unavailable:"Unavailable",restoredAfterRestart:"restored after restart",restoreFailed:"restore failed",hostRestartInterrupted:"host restart interrupted",snapshotRecovered:"snapshot recovered",attach:"Attach",recover:"Recover",restart:"Restart",hintLive:"These runtimes are live now and are the only attachable targets.",hintRecovery:"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.",hintInactive:"These inactive records are shown for reference and usually need restart before they are useful again.",lifecycleStarting:"Starting",lifecycleRunning:"Running",lifecycleStopping:"Stopping",lifecycleStopped:"Stopped",lifecycleFailed:"Failed",lifecycleInterrupted:"Interrupted"},kk={advancedTitle:"Advanced",mobileMode:{workspaceMode:"Workspace",chatMode:"Chat mode",descriptionWorkspace:"Use the full workspace layout on phones and tablets.",descriptionChat:"Use the chat-first mobile inbox layout, closer to a messaging app.",label:"Mobile inbox (chat mode)"},theme:{preset:{honey:"Warm yellow accents",aurora:"Pink accent theme",ember:"Default amber theme, inspired by the landing page",midnight:"Classic violet theme"},presetCustomDescription:"Full app + chat customization",helloHelp:"Hello! How can I help?",fixBug:"Fix the bug please",onIt:"On it! ✨",customEditorTitle:"Custom Theme Editor",darkMode:"Dark mode",lightMode:"Light mode",sectionAppBackground:"App Background",sectionAppText:"App Text",sectionBordersAccent:"Borders & Accent",sectionChatBubbles:"Chat Bubbles",sectionChatLayout:"Chat Layout",colorBackground:"Background",colorSurface:"Surface",colorCard:"Card",colorPrimary:"Primary",colorSecondary:"Secondary",colorMuted:"Muted",colorBorderSubtle:"Border subtle",colorBorderDefault:"Border default",colorAccent:"Accent",colorUserBubble:"User bubble",colorUserText:"User text",colorAgentBubble:"Agent bubble",colorAgentText:"Agent text",colorChatBg:"Chat BG",colorSendButton:"Send button",colorInputBorder:"Input border",labelBubbleRadius:"Bubble radius",resetToDefaults:"Reset to defaults",customLabel:"Custom"},providerPriority:{undetectedHint_other:"{{count}} providers aren't detected here — kept in order, skipped until available.",undetectedHint_one:"{{count}} provider isn't detected here — kept in order, skipped until available.",orderHint:"Launches use this order, top to bottom.",noMoreProviders:"No other CLI providers detected",selectProvider:"Select provider…",moveDown:"Move down",moveUp:"Move up",keptUntilDetected:"Kept in order; skipped at launch until it's detected on this machine.",emptyWarning:"No provider priority configured. Launches that don't name a CLI provider will be refused.",available:"available",notOnMachine:"Not detected",remove:"Remove",addCliLabel:"Add available CLI provider",addProvider:"Add provider"},coordinatorPrompts:{saveFailed:"Couldn't save",loadFailed:"Couldn't load coordinator prompts",save:"Save",saved:"Saved",saving:"Saving…",appendPlaceholder:"(empty — nothing added at this layer)",overridePlaceholder:"(empty — use the default base prompt)",placeholdersHint:"Placeholders you can use:",resetHint:"Leave a field empty and save to remove it (back to the default).",intro:"Customize the prompt that this daemon's mesh coordinator sessions receive.",loading:"Loading…",connectDaemon:"Connect a daemon to edit coordinator prompts.",overrideDesc:"<strong>Override</strong> replaces the daemon's built-in base prompt for that CLI.",appendDesc:"<strong>Append</strong> stacks after whichever base wins.",overrideLabel:"Override",appendLabel:"Append",expandLabel:"Edit prompts",collapseLabel:"Collapse",customizedBadge:"Customized",collapsedNone:"No custom prompts — using daemon defaults.",tabsAriaLabel:"Coordinator prompt provider",sectionTitle:"Coordinator prompts",sectionDescription:"Per-CLI base prompt for mesh coordinator sessions on this machine. Mesh-level prompts live on the Repo Mesh page."},appearance:{modeSystem:"System",modeLight:"Light",modeDark:"Dark",modeLabel:"Mode",themeLabel:"Theme",mobileLabel:"Mobile",chatLabel:"Chat"},chatActivity:{rowLabel:"Show agent activity in chat",descriptionOn:"Tool calls, terminal output and thinking are shown between chat messages.",descriptionOff:"Only the conversation is shown. Tool calls, terminal output and thinking stay hidden."}},jk={chatHistory:"Chat History",startNewChat:"+ Start New Chat Session",creating:"Creating...",searchPlaceholder:"Search title or preview",filterWorkspace:"Filter by workspace",filterModel:"Filter by model",sortRecent:"Most recent",sortOldest:"Oldest first",sortMessages:"Most messages",resumeReadyOnly:"Resume-ready only",untitledSession:"Untitled Session",noSavedPreview:"No saved preview yet",workspaceUnknown:"Workspace unknown",selectedWorkspaceSuffix:" · selected workspace",msgCount:"{{count}} msgs",statusActive:"ACTIVE",statusMissingWorkspace:"MISSING WORKSPACE",statusResumeSelectedWorkspace:"RESUME IN SELECTED WORKSPACE",statusResuming:"RESUMING...",statusResume:"RESUME",noMatchingHistory:"No saved history matches these filters.",noRecentChats:"No recent chat sessions found.",refreshHistory:"Refresh History",refreshing:"Refreshing...",confirmSwitchTitle:"Switch session?",confirmSwitchDescription:'Switch to "{{target}}"? This will leave your current view.',confirmSwitchAction:"Switch"},Nk={gallery:{next:"Next view",previous:"Previous view",slides:{overview:"Missions & activity — from a phone",tasks:"Task queue across workers",map:"Live map of nodes and branches",desktop:"The same mesh, desktop view"}},theme:{system:"System theme",light:"Light theme",dark:"Dark theme"},nav:{home:"ADHDev Home",mesh:"Mesh",what:"What",agents:"Agents",pricing:"Pricing",install:"Install",github:"GitHub",docs:"Docs",getStarted:"Get started",toggleMenu:"Toggle menu",mainNavigation:"Main navigation"},hero:{badge:"Claude Code, Codex, Cursor & more — on all your machines",title:"Manage the coding agents running on your computer — from anywhere.",subtitleInstall:"Install ADHDev on your <os></os>.",subtitlePlace:"use your <device></device>",subtitleAsk:"to ask <coordinator></coordinator> to send <worker></worker> to <verb></verb> your repo.",subtitleFrom:"From <place></place>,",anywhere:"anywhere",subtitleLand:"Many agents at once — none of them step on each other.",axes:{os:["Mac","Windows","Linux"],place:["the subway","a cafe","your parents' place","bed","the couch","the garden","the passenger seat","the ferry","the gym","inside a container","the moon","a server rack"],device:["desktop","laptop","tablet","mobile phone"],verb:["debug","build","test","review"]},copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",getStarted:"Get started free",orInstall:"Or install the CLI",openSource:"Open source on GitHub",joinDiscord:"Join Discord",selfHost:"Self-host it",demoDesktop:"ADHDev command center driving live agent sessions across multiple machines",demoPush:"ADHDev mobile push notification and one-tap approval"},mesh:{sectionTitle:"Parallel agents that don't step on each other.",sectionSubtitle:"Running agents in parallel is the easy part — every tool does it now. The hard part is what comes after: a pile of branches that still have to be checked and merged. ADHDev does that for you, so finished work arrives on main instead of in your review queue.",refineryHighlight:"Automatic landing",refineryTitle:"Finished work merges to main on its own",refineryDesc:"Anyone can run ten agents at once. ADHDev then checks each branch against your project's own tests and lint, merges the ones that pass cleanly into main, and tidies up — automatically, and never with a force-push. Anything unclear is held back for you to review instead of merged.",asyncHighlight:"One place to drive it",asyncTitle:"You talk to one place. It runs the rest.",asyncDesc:"You hand work to a single coordinator, and it runs every agent across every machine for you. It only pings you when something needs approval or finishes — so there's no queue of agent windows to watch and nothing to sit in front of.",crossPlatformHighlight:"Every OS at once",crossPlatformTitle:"Mac, Windows, Linux — all at once",crossPlatformDesc:"Send a task to a specific operating system with one tag. A single prompt can build, test, or verify across Mac, Windows, and Linux machines you already own — in parallel, with no SSH setup and no virtual machines.",monoHighlight:"Works with real repos",monoTitle:"Safe even with git submodules",monoDesc:"Real production repos nest submodules — exactly where naive auto-merge breaks. ADHDev handles them safely: it makes sure submodule changes are published and pointed at correctly before it touches main. This project is itself a repo with two submodules, merged this way every day.",crossHighlight:"Second opinion",crossTitle:"Consensus over a single opinion",crossSubtitle:"One question, several independent agents",crossDesc:"Have the coordinator ask the same read-only question to several machines and models at once, then compare where they agree and disagree — more trustworthy than one agent's answer.",tryMesh:"Try Repo Mesh →",seePlans:"See plans",availableOn:"Connect a machine and open the <strong>Repo Mesh</strong> page to get started.",readGuide:"Read the guide"},compare:{sectionTitle:"Everyone runs agents in parallel. Not everyone keeps them out of each other's way.",sectionSubtitle:"Local CLIs spawn subagents; desktop orchestrators fan work across worktrees with a native UI. Both stop at the branch — reviewing and merging is left to you. Here's how they compare, including where each of them is the better fit.",colLocalCli:"Local CLI + subagents",colDesktop:"Desktop orchestrator",colAdhdev:"ADHDev Repo Mesh",rowLandsMain:"Lands finished work on main",rowLandsMainLocalCli:"You run the gates and merge by hand",rowLandsMainDesktop:"Parallelizes the work, then hands you the branches to review",rowLandsMainAdhdev:"The Refinery runs your repo's gates, checks patch equivalence, and rebases + merges onto main only if it hasn't moved — unattended, no force-push",rowSubmodules:"Safe with git submodules",rowSubmodulesLocalCli:"No merge automation to be aware of them",rowSubmodulesDesktop:"Worktree parallelism, but the merge is yours to get right",rowSubmodulesAdhdev:"Submodule-aware convergence: reachability gate, patch-equivalence check, atomic pointer bump — dogfooded on this monorepo daily",rowAsync:"Talk to one place, async",rowAsyncLocalCli:"One session at a time, synchronously",rowAsyncDesktop:"You supervise each agent window yourself",rowAsyncAdhdev:"One coordinator drives every worker on an event loop — it waits on completion/approval events, you don't poll or babysit",rowMultiMachine:"Multiple physical machines",rowMultiMachineLocalCli:"One host's processes only",rowMultiMachineDesktop:"Bound to the one machine it runs on",rowMultiMachineAdhdev:"Remote daemons over P2P — Mac, Windows, and Linux nodes in one mesh, no SSH plumbing",rowParallelBranch:"Parallel isolated-branch work",rowParallelBranchLocalCli:"Subagents share one working tree — concurrent writes collide",rowParallelBranchDesktop:"One git worktree per task — a core strength",rowParallelBranchAdhdev:"One git worktree per node — parallel across machines, not just cores",rowBrowser:"Drive it from a browser or phone",rowBrowserLocalCli:"You have to be at the terminal",rowBrowserDesktop:"Native desktop app — you're at that desk",rowBrowserAdhdev:"Web-first: control sessions and approve from any browser or phone",rowNativeApp:"Native desktop app",rowNativeAppLocalCli:"Terminal only",rowNativeAppDesktop:"Polished native window — genuinely nicer to sit in front of",rowNativeAppAdhdev:"We're web-first — a browser tab, not a native app",rowRestarts:"Survives restarts & context loss",rowRestartsLocalCli:"State lives in a session — close it and it's gone",rowRestartsDesktop:"State tied to the app process",rowRestartsAdhdev:"Missions persist to disk and resume after a coordinator or daemon restart — append-only audit trail",rowCrossCheck:"Cross-check the answer",rowCrossCheckLocalCli:"One agent's take, no second opinion",rowCrossCheckDesktop:"Parallel work, single verdict",rowCrossCheckAdhdev:"The coordinator sends the same read-only question to agents on different machines and providers and compares where they diverge",footnote:"For a single machine, a single branch, a one-shot task — a local CLI with subagents is lighter and works great, and a native desktop orchestrator is a nicer place to sit. Repo Mesh earns its keep when work fans out across machines and branches, needs to survive restarts, and should land on main automatically — controlled from wherever you are."},what:{sectionTitle:"Any agent, mixed freely",sectionSubtitle:"Vendor-neutral by design. Run Claude Code on the Mac, Codex on the Windows GPU box, Cursor CLI for review passes — all in the same mesh, driven from the same dashboard. Switch vendors without switching platforms.",cliHighlight:"CLI agents",cliTitle:"Drive any terminal agent from the web",cliDesc:"Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Grok, Kimi, and OpenCode — launched on your machine through a PTY adapter with proper resume and reconnect, driven from your browser. Send prompts and provide visual context instantly (paste, drag & drop, or upload multiple images at once).",uiHighlight:"One UI",uiTitle:"Same dashboard, any device",uiDesc:"Cloud-hosted at adhf.dev — drive every agent from a laptop or phone, whether you're at your desk or away from it.",ideHighlight:"IDE agents",ideTitle:"Also: attach to running editors",ideDesc:"Cursor, VS Code, VSCodium, Windsurf, Antigravity, Kiro, PearAI, Trae. Read live chat, send prompts, switch sessions, capture screenshots.",p2pHighlight:"Yours, end to end",p2pTitle:"P2P-first: your data stays yours",p2pDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC — your code never routes through the server. The cloud handles sign-in, connection setup and session status. The one exception: approval push notifications include up to 80 characters of what you're approving."},oss:{sectionTitle:"Open source & self-hostable",sectionSubtitle:"The daemon and dashboard are AGPL-3.0 and available on GitHub. Run them yourself on any machine or server — no account required.",github:"GitHub",selfHostDocs:"Self-hosting docs"},agents:{sectionTitle:"Supported agents",sectionSubtitle:"{{ides}} built-in IDE integrations, {{clis}} built-in CLI agents, and {{extensions}} IDE-resident extension agents. Provider scripts live in <code>adhdev-providers/</code> — add your own under <code>~/.adhdev/providers/</code>.",tierTested:"Tested",tierTestedDesc:"validated against a real app + version",tierCommunity:"Community",tierCommunityDesc:"built-in and community-supported",groupIdes:"IDEs",hintIdes:"Attached via Chrome DevTools Protocol. Read chat, send prompts, switch sessions, screenshot.",groupCli:"CLI agents",hintCli:"Driven through a PTY adapter with resume and reconnect.",groupExtensions:"In-IDE extension agents",hintExtensions:"CDP webview attachment for agents that live inside another IDE."},pricing:{sectionTitle:"Simple pricing as your agents grow",sectionSubtitle:"Start free on one machine. Go Pro for two, or Ultra for five. No per-seat math, no enterprise sales call — just the plans below.",mostPopular:"Most popular",upgradeToPro:"Upgrade to Pro",footnote:"Prices in USD, excluding applicable taxes. Prefer to self-host? The daemon and dashboard are open source.",plans:{free:{period:"forever",tagline:"Everything you need to drive one machine from anywhere.",cta:"Start free",features:{machine:"One machine, paired in a single command",p2p:"P2P chat, commands, screenshots, remote input",providers:"Every provider — CLI and IDE agents",push:"Push notifications for approvals & completions",share:"One shared session link"}},pro:{period:"/mo",tagline:"Two machines, so Repo Mesh can run agents across both — plus more concurrent sessions.",cta:"Start 7-day Pro trial",features:{machines:"2 machines — run agents on both",p2p:"More concurrent P2P sessions",push:"Unlimited push notifications",share:"More shared sessions"}},ultra:{period:"/mo",tagline:"Everything in Pro, scaled up — more machines and higher limits for heavy parallel work.",cta:"Go Ultra",features:{machines:"5 machines — flat price, not per-seat",everything:"Everything in Pro",p2p:"Highest concurrent P2P sessions",screenshots:"Unlimited daily screenshot minutes",webhooks:"Higher API call limits",share:"More shared sessions"}}}},install:{sectionTitle:"Three steps to a working dashboard",sectionSubtitle:"No configuration files. No API keys to wire up. ADHDev does not manage agent auth — each tool keeps its own login.",selectOs:"Select OS",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",platformNote:"macOS and Linux use the Unix script; Windows uses the PowerShell one. All three are in daily use.",arrow:"→",steps:{step1:{title:"Install the daemon",desc:"One command installs the daemon plus the adhdev CLI — the launcher you run to pair machines and start the daemon (not to be confused with the CLI agents it drives, like Claude Code or Codex). Same binary powers cloud and standalone."},step2:{title:"Link a machine",desc:"Sign in once with GitHub or Google and the daemon pairs itself — no token to copy."},step3:{title:"Drive your agents",desc:"Launch Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Kimi, and other agents from the dashboard. Read chat, send prompts, provide visual context (paste, drag & drop, or upload multiple images at once), approve actions, and switch sessions."}}},cta:{headline:"Stop juggling tabs. Drive every agent from one dashboard.",subtitle:"One command, one daemon, every agent you already use. Drive them all from the web.",getStarted:"Get started →",github:"GitHub",discord:"Discord"},footer:{docs:"Docs",github:"GitHub",discord:"Discord",dashboard:"Dashboard",terms:"Terms",privacy:"Privacy",contact:"Contact",copyright:"© {{year}} RacoLab. All rights reserved."},imagePaste:{sectionTitle:"Paste a screenshot. A terminal agent on another machine sees it instantly.",sectionSubtitle:"Grab a screenshot on your laptop or phone, paste it into the chat, and a CLI agent running in a terminal on a different machine gets it as visual context — no file juggling, no SSH. Paste, drag & drop, or upload up to 5 images (10MB each) at once.",point1:"Paste from clipboard, drag & drop, or upload",point2:"Up to 5 images, 10MB each",point3:"Lands in a PTY terminal agent on any of your machines",step1Label:"Paste the image, type a question",step2Label:"Sent — the agent picks it up",step3Label:"It saw the image and answered"},mobile:{sectionTitle:"Leave your desk. Your agents keep going.",sectionSubtitle:"A push notification hits your phone when an agent needs approval or finishes. Tap it, approve or reject, then follow up in chat — all from the mobile dashboard, wherever you are.",point1:"Push notification on approval or completion",point2:"One tap to approve or reject",point3:"Follow up with a chat instruction, then put your phone away",notificationLabel:"Mobile push notification for an agent approval",resumeLabel:"Approving and following up from the mobile dashboard",deviceShotLabel:"Real iOS lock screen showing an ADHDev approval push with the Bash command Claude Code wants to run",deviceShotCaption:"Real device — actual push notifications on a phone",point4:"No port forwarding, no VPN, no DMZ — P2P with TURN relay connects from cafés, hotspots, desktop or laptop, anywhere with internet"},brain:{sectionTitle:"Cheap models for easy work. Expensive ones only when it's hard.",sectionSubtitle:"Tag a task easy, medium, or difficult and the mesh applies a matching preset — provider, model, and thinking budget. Routine work runs on a cheap fast model; only the hard tasks reach for the expensive one. You spend tokens where they matter.",point1:"Difficulty-based presets: easy / medium / difficult",point2:"Each preset picks provider, model, and thinking level",point3:"Save tokens without hand-tuning every task"},scenario:{sectionTitle:"One prompt. Mac builds, Windows tests, main lands.",sectionSubtitle:"A real session in three steps: you describe the work once, agents run in parallel across your machines, and finished code arrives on main — without you sitting at the terminal.",step1Label:"Describe the work",step1Desc:"Tell it what to build, in one sentence. No config, no setup per machine.",step2Label:"Agents run in parallel",step2Desc:"The work splits across your Mac and Windows machines at once — each on its own branch, each running your project's tests and checks.",step3Label:"Finished code lands on main",step3Desc:"When the checks pass, the work merges into main automatically and safely. Anything unclear is held back for you to review — never force-pushed.",caveat:"Mac, Windows and Linux machines are all in daily use."}},Ck={submit:"Submit",submitting:"Submitting…",cancelAria:"Cancel the question",actionRequired:"Action Required",selectAllThatApply:"Select all that apply",multipleChoice:"Multiple choice",singleChoice:"Single choice",other:"Other",answersRequired_one:"{{count}} question still needs an answer",answersRequired_other:"{{count}} questions still need answers",errorReviewPageNotFocused:"The terminal is showing a different screen, so the answer was not submitted — check the terminal screen or close this and try again.",errorReviewUnconfirmed:"The answer keys reached the terminal, but the question is still on screen — the answer may not have been submitted. Check the terminal: if it was not submitted, answer there; resending from here could submit it twice."},_k={diffPreview:{truncatedAfter:"locally for the full output.",truncatedBefore:"Changes truncated — run",empty:"No changes to show.",binary:"Binary file — changes can't be shown.",loading:"Loading changes…"},changeList:{stagedHint:"Staged",noChanges:"No changed files.",binaryBadge:"bin",truncatedNote:"File list truncated — run <code>git status</code> locally for full output."},statusDialog:{working:"Working…",includeUntracked:"Include untracked files",messageRequired:"Message (required)",fileFallback:"file",confirmRevert:"Revert changes to {{path}}?",confirmPop:"Restore latest stash?",confirmStash:"Stash changes",confirmCheckpoint:"Create checkpoint commit",copySummary:"Copy summary",copied:"Copied to clipboard",checkoutSelected:"Revert selected",selectFileToRevert:"Select a file to revert",revertFile:"Revert changes to {{path}}",popStash:"Restore stash",noStashes:"No stashes to restore",popHint:"Restore the latest stash",resolveBeforePop:"Resolve conflicts before restoring a stash",stash:"Stash",stashHint:"Set current changes aside (git stash)",resolveBeforeStash:"Resolve conflicts before stashing",checkpoint:"Checkpoint",checkpointHint:"Create a git commit as a checkpoint",resolveBeforeCheckpoint:"Resolve conflicts before creating a checkpoint",selectFile:"Select a file to view its changes",noDiffData:"No diff data.",loading:"Loading…",fileCount_other:"{{count}} files",fileCount_one:"{{count}} file",stashed:"{{count}} stashed",deleted:"{{count}} deleted",untracked:"{{count}} untracked",modified:"{{count}} modified",staged:"{{count}} staged",behind:"{{count}} behind",ahead:"{{count}} ahead",refresh:"Refresh",openOnGithub:"Open on GitHub",title:"Git status",conflicts:"conflicts",clean:"clean"}},Ak={machineProviders:"Machine → Providers",perProviderIntro:"Per-provider alerts and auto-approve:",mixed:"(some off)",agentAlert:{noProgressDesc:"Alert when an agent has shown no progress for a while.",noProgress:"No progress",approvalDesc:"Alert when an agent is waiting for your approval.",approval:"Approval needed"},agentAlertsDesc:"Applies to every provider on your online machines. Fine-tune one provider in Machine → Providers.",permissionUnsupportedChip:"Not supported",permissionBlockedChip:"Blocked",permissionNeededChip:"Permission needed",permissionAllowedChip:"Allowed",title:"Notifications",subtitle:"Browser, push and agent alerts",sectionBrowserAlerts:"Browser alerts",masterToggleLabel:"Notifications",masterToggleDesc:"Master toggle for all alerts",browserNotificationsLabel:"Browser Notifications",browserNotificationsDesc:"Desktop alerts when tab is inactive",browserBackgroundInfo:"Browser alerts only fire while this dashboard tab stays open in the background.",browserBackgroundInfoWithPush:"Browser alerts only fire while this dashboard tab stays open in the background. If you close the tab, use Push Notifications instead.",permissionDefault:"This browser has not granted notification permission yet. Allow it to receive browser alerts.",allowNotifications:"Allow notifications",permissionDenied:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive desktop alerts.",permissionUnsupported:"This browser cannot show desktop notifications here. Use a supported desktop browser, or rely on Push Notifications where available.",completionAlertsLabel:"Completion Alerts",completionAlertsDesc:"Notify when agent finishes a task",approvalAlertsLabel:"Approval Alerts",approvalAlertsDesc:"Notify when agent needs approval",connectionAlertsLabel:"Connection Alerts",connectionAlertsDesc:"Alert when a machine disconnects",allDisabled:"All notifications are off.",sectionProviderAlerts:"Agent alerts",loading:"Loading...",refresh:"Refresh",noOnlineMachines:"No machines online.",loadingProviderSettings:"Loading provider settings...",soundEffectsLabel:"Sound Effects",soundEffectsDesc:"Play a sound when agent completes or needs approval"},Tk={pageTitle:"Approvals",pageSubtitle:"Sessions waiting on your decision.",pending:"Pending",loading:"Loading approvals…",emptyHint:"Approvals from any connected machine will appear here automatically."},Ik={title:"Guided mesh setup",close:"Close",machines:{title:"Select machines",description:"Pick the mesh to set up and attach the machines that should run its work. Creating a mesh also attaches the chosen workspace as its first node.",noMachinesDescription:"No machine is registered yet. Install the daemon on a machine first — it pairs automatically once signed in.",noMachinesFallback:"Start the local daemon and return here.",nodeCount:"{{count}} nodes",createNew:"Create new mesh",loadingMeshes:"Loading meshes…",meshName:"Mesh name",machine:"Machine",machineSelectPlaceholder:"Select a machine",workspace:"Workspace (repo path)",workspacePlaceholder:"/path/to/repo",workspaceSelectPlaceholder:"Select a workspace",workspaceCustom:"Enter a path manually…",pickFromKnown:"Pick from known workspaces",planChecking:"Checking the workspace…",planOk:"Workspace looks good: {{identity}}",planExists:"This workspace already belongs to an existing mesh — add it as a node there instead of creating a new mesh.",creating:"Creating…",create:"Create mesh",createFailed:"Create failed",attachTitle:"Attach another machine",allMachinesAttached:"Every registered machine is already attached to this mesh.",attaching:"Attaching…",addMachine:"Add machine"},quotaPolicy:{blankMeansDefaultShort:"Blank = default",title:"Quota-aware routing",description:"When a node reports how much of its AI provider quota is left, the coordinator can skip nodes that are nearly exhausted and prefer nodes with more headroom. These thresholds decide when that happens. Missing or outdated readings are always ignored, so a node is never excluded on stale data.",sessionMin:"Session floor",sessionMinHint:"Skip a provider whose short rolling window has less than this left.",weeklyMin:"Weekly floor",weeklyMinHint:"Skip a provider whose weekly window has less than this left.",resetImminent:"Reset grace",resetImminentHint:"Ignore a low session window when it resets within this long.",staleAfter:"Reading expiry",staleAfterHint:"Fallback only: a measured window stays valid until its own reset; this age limit applies just to readings without a reset time.",spreadBonus:"Headroom preference",spreadBonusHint:"How strongly more remaining quota is preferred. Never overrides a task-difficulty match.",sessionAxisWeeklyHeadroom:"Weekly headroom for session urgency",sessionAxisWeeklyHeadroomHint:"Only prioritize an imminent 5-hour session-window reset when weekly quota remaining is at or above this. Unused 5-hour quota is lost forever, but burning it when the weekly window is already tight costs more than it saves.",minutes:"min",blankMeansDefault:"Leave a field blank to use its default (shown as the greyed-out value).",useDefaults:"Use defaults",saving:"Saving…",errors:{notANumber:"Enter a number.",percentRange:"Must be between 0 and 100.",negative:"Cannot be negative."}},continueToMesh:"Continue to Mesh"},Mk={dashboard:"Dashboard",machines:"Machines",notifications:"Notifications",mesh:"Mesh",marketplace:"Marketplace",api:"API",webhooks:"Webhooks",account:"Account",settings:"Settings",docs:"Docs",about:"About",chats:"Chats"},Rk={controls:U0,sessionStatus:K0,language:q0,common:z0,connection:V0,toast:G0,notification:Y0,event:Q0,dashboard:J0,cliStop:X0,approval:Z0,chatControls:ek,newSession:tk,mobileInbox:nk,mesh:sk,chat:rk,chatPane:ok,chatInput:ak,paneGroup:ik,terminal:ck,conversation:lk,cliView:dk,launch:uk,standalone:mk,cloud:hk,app:pk,chatList:fk,screenshot:bk,remote:gk,sessionNav:xk,sessionInfo:yk,machine:vk,sessionHost:wk,sessionHostSurface:Sk,settings:kk,historyModal:jk,landing:Nk,interactivePrompt:Ck,git:_k,notifications:Ak,approvals:Tk,setupWizard:Ik,nav:Mk},pl="lang",ro="common",Pk={ko:()=>or(()=>import("./common-DGin0xxP.js"),[]),ja:()=>or(()=>import("./common-BFguc4-T.js"),[]),"zh-CN":()=>or(()=>import("./common-5_lp3RLE.js"),[]),es:()=>or(()=>import("./common-D_kCw4Zi.js"),[])};async function Ek(e){return!Rs(e)||e===Es?null:(await Pk[e]()).default}const Dk={type:"backend",init(){},read(e,t,s){if(t!==ro){s(null,{});return}Ek(e).then(r=>s(null,r??{}),r=>s(r instanceof Error?r:new Error(String(r)),!1))}};function Lk(e){return{resources:{[Es]:{[ro]:Rk}},partialBundledLanguages:!0,lng:e,fallbackLng:Es,supportedLngs:uf,ns:[ro],defaultNS:ro,interpolation:{escapeValue:!1},returnEmptyString:!1,react:{transKeepBasicHtmlNodesFor:["br","strong","i","p","em"]}}}function Ok(){try{const e=localStorage.getItem(pl);if(Rs(e))return e}catch{}return null}function mf(){const e=Ok();return e||(typeof navigator<"u"?W0(navigator.language):Es)}function fl(e){typeof document>"u"||document.documentElement.setAttribute("lang",e)}let bo=null,hf=!1;function pf(){if(bo)return Ge;const e=mf();return bo=Ge.use(Dk).use(Rx).init(Lk(e)).then(()=>{},()=>{}).finally(()=>{hf=!0}),fl(e),Ge}function $k(){return hf?!0:!!bo&&Ge.isInitialized&&Ge.hasLoadedNamespace(ro)}function Fk(){return bo||pf(),bo}function Ut(e){return(typeof e=="string"?e.trim():"")||void 0}function Yn(e,t){const s=Ut(t);return s?`${e}:${s}`:void 0}function us(e,t,s){const r=Yn(t,s),o=Ut(s);r&&e.push(r),o&&e.push(o)}function ar(e){const t=[],s=new Set;for(const r of e)!r||s.has(r)||(s.add(r),t.push(r));return t}function ff(e){return Ut(e.providerSessionId)||Ut(e.sessionId)||Ut(e.tabKey)||Ut(e.routeId)}function yi(e){return ar([Ut(e.historySessionId),Ut(e.providerSessionId),Ut(e.sessionId)])}function oo(e){const t=[];return us(t,"provider",e.providerSessionId),us(t,"session",e.sessionId),us(t,"tab",e.tabKey),us(t,"route",e.routeId),ar(t)}function Hk(e){const t=[];return Ut(e.providerSessionId)?(us(t,"provider",e.providerSessionId),ar(t)):Ut(e.sessionId)?(us(t,"session",e.sessionId),ar(t)):Ut(e.tabKey)?(us(t,"tab",e.tabKey),ar(t)):Ut(e.routeId)?(us(t,"route",e.routeId),ar(t)):[]}function bf(e){return Yn("provider",e.providerSessionId)||Yn("session",e.sessionId)||Yn("tab",e.tabKey)||Yn("route",e.routeId)||"unknown:"}function vi(e){return yi(e)[0]}function wi(e){const t=Ut(e.sessionId),s=vi(e);if(s&&!(t&&s===t))return s}function Bk(e){const t=Ut(e.providerSessionId),s=Ut(e.sessionId),r=Ut(e.tabKey),o=Ut(e.routeId),a=[Yn("provider",t),Yn("session",s),Yn("tab",r),Yn("route",o)].filter(d=>typeof d=="string"),i=oo({providerSessionId:t,sessionId:s,tabKey:r,routeId:o}),l=bf({providerSessionId:t,sessionId:s,tabKey:r,routeId:o});return{providerSessionId:t,sessionId:s,tabKey:r,routeId:o,canonicalKey:l,targetKey:l,targetValue:ff({providerSessionId:t,sessionId:s,tabKey:r,routeId:o}),historySessionId:vi({providerSessionId:t,sessionId:s}),runtimeSessionId:s,allKeys:a,lookupKeys:i}}function Zr(e,t){const s=Bk(e);return Hk(t).some(r=>s.lookupKeys.includes(r))}function gf(e){const t=String(e.daemonId||"").trim(),s=String(e.id||"").trim();return t&&s.startsWith(`${t}:`)?s.slice(t.length+1):s}function bl(e){if(String(e.ownerDaemonId||"").trim())return!0;const t=e.settings;return t?!!t.meshNodeFor||!!t.meshNodeId||t.launchedByCoordinator===!0||t._remoteOwnedSession===!0:!1}function Wk(e,t){const s=String(e.daemonId||"").trim(),r=String(e.id||"").trim(),o=gf(e);if(o&&t.has(o))return`mesh:${o}`;const a=String(e.ownerDaemonId||"").trim()||s;return a?o?`${a}:${o}`:a:r}function oc(e,t){return t||e||"unknown"}function Uk(e,t){return e.ownerDaemonId&&(t==null?void 0:t[e.ownerDaemonId])||e.ownerMachineName||void 0||e.daemonId&&(t==null?void 0:t[e.daemonId])||void 0}const Kk={vscode:"VS Code",pearai:"PearAI"};function Ot(e){return e?e.split("-").map(t=>Kk[t.toLowerCase()]||t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function qk(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const s=Math.floor(t/60),r=t%60;if(s<24)return r>0?`${s}h ${r}m`:`${s}h`;const o=Math.floor(s/24),a=s%24;return`${o}d ${a}h`}function ac(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function fa(e,t){const s=typeof t=="string"?t.trim():"";if(s)return s;const r=typeof e=="string"?e.trim():"";if(!r)return"";const o=r.replace(/[\\/]+$/,""),a=o.split(/[\\/]/).filter(Boolean);return a[a.length-1]||o}function zk(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),s=t[t.length-1];return s.length>12?`Machine-${s.substring(0,8)}`:s}return e}function Vk(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Gk(e){return zk(e.trim().replace(/\.local$/i,""))}function xf(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function bd(e,t={}){var o,a;const s=[e.hostname,(o=e.machine)==null?void 0:o.hostname,(a=e.system)==null?void 0:a.hostname].find(i=>typeof i=="string"&&i.trim().length>0&&!Vk(i));if(s&&s!=="Unknown")return Gk(s);const r=t.fallbackId||e.id;return r?`Machine-${r.substring(0,8)}`:t.fallbackLabel||"Machine"}function yn(e,t={}){return xf(e)||bd(e,t)}function yf(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function Yk(e,t,s={}){const r=String(t).trim();if(!e||!Array.isArray(e.items)||!r)return"";const o=e.items.find(a=>String((a==null?void 0:a.id)||"").trim()===r);return o?String(s.preferShortValue?o.shortValue||o.value||"":o.value||o.shortValue||"").trim():""}function go(e,t){return yf(e).join(" · ")}function xo(e){return e.transport==="pty"}const vf={darwin:"macOS",linux:"Linux",win32:"Windows"};function wf(e,t){var s,r;return(s=t==null?void 0:t.providerLabels)!=null&&s[e]?t.providerLabels[e]:(r=t==null?void 0:t.providerLabels)!=null&&r[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:Ot(e)}function qu(e,t,s){const r=(e||"").trim().toLowerCase();if(!r)return!0;const o=(t||"").trim().toLowerCase(),a=(s||"").trim().toLowerCase(),i=Ot(s||"").trim().toLowerCase();return r===o||r===a||r===i}function Qk(e,t=[],s=[]){var d,m,u,h;const r=Jt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(r==="waiting_approval")return"waiting_approval";if(r==="waiting_choice")return"waiting_choice";if(r==="generating")return"generating";const o=t.find(p=>Bu(p.status,{activeModal:p.activeModal})||dl(p.status));if(o)return Jt(o.status,{activeModal:o.activeModal});const a=s.find(p=>Bu(p.status,{activeModal:p.activeModal})||dl(p.status));if(a)return Jt(a.status,{activeModal:a.activeModal});if(r&&r!=="idle")return r;const i=Jt((d=t[0])==null?void 0:d.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(i!=="idle")return i;const l=Jt((u=s[0])==null?void 0:u.status,{activeModal:(h=s[0])==null?void 0:h.activeModal});return l!=="idle"?l:"idle"}function Jk(e){return Jt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Xk(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,s=["generating","finalizing","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const r of e){const o=(r.name||r.id||"").toLowerCase().replace(/\s+/g,"-"),a=t.get(o),i=Jt(r.status);if(!a){t.set(o,{...r,status:i});continue}const l=s.indexOf(a.status||"idle"),d=s.indexOf(i||"idle");d>=0&&(l<0||d<l)&&t.set(o,{...r,status:i})}return Array.from(t.values())}function Zk(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 ej(e){var s,r;const t=(r=(s=e==null?void 0:e.messages)==null?void 0:s.at)==null?void 0:r.call(s,-1);return t&&Zk(t.receivedAt)||0}function tj(e){return(e.recentLaunches||[]).reduce((s,r)=>Math.max(s,r.lastLaunchedAt||0),0)}function gl(e){return Math.max(tj(e),ej(e.activeChat))}function nj(e,t,s,r,o,a){const i=t-e;if(i!==0)return i;const l=s.localeCompare(r);return l!==0?l:o.localeCompare(a)}function La(e,t){return nj(gl(e),gl(t),yn(e,{fallbackId:e.id}),yn(t,{fallbackId:t.id}),e.id,t.id)}const Sf="adhdev_notification_prefs",zu={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function sj(){try{const e=localStorage.getItem(Sf);if(e){const t=JSON.parse(e);return{...zu,...t}}}catch{}return{...zu}}function rj(e){try{localStorage.setItem(Sf,JSON.stringify(e))}catch{}}let Gn=sj(),ba=[];function oj(){ba.forEach(e=>e())}function aj(e){Gn={...Gn,...e},rj(Gn),oj()}function ij(){const[,e]=c.useState(0);c.useEffect(()=>{const s=()=>e(r=>r+1);return ba.push(s),()=>{ba=ba.filter(r=>r!==s)}},[]);const t=c.useCallback(s=>{aj(s)},[]);return[{...Gn},t]}function ao(e){if(!Gn.globalEnabled)return!1;switch(e){case"disconnect":return Gn.disconnectAlert;case"completion":return Gn.completionAlert;case"approval":return Gn.approvalAlert;case"browser":return Gn.browserNotifications;default:return!0}}const cj={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function kf(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function jf(){return"Notification"in window&&Notification.permission==="granted"}function lj(e,t,s){return e?!(s==="waiting_choice"&&t!=="waiting_choice"):!1}let js=null;function dj(e){return e!==!1}async function uj(){if(js!==null)return js;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return js=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(js=!!await e.pushManager.getSubscription(),js):(js=!1,!1)}catch{return js=!1,!1}}function xl(e,t,s){if(jf())try{const r=new Notification(e,{body:t,icon:"/otter-logo.png",tag:s||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>r.close(),8e3),r.onclick=()=>{window.focus(),r.close()}}catch{}}function mj(e){const{name:t,prev:s,curr:r,questionEntered:o}=e,a=String(e.modalMessage||"").replace(/\s+/g," ").trim().slice(0,120);return o&&e.onApproval?{kind:"question",title:t,body:a?Ge.t("event.browser.questionWithMessage",{message:a}):Ge.t("event.browser.question")}:e.onApproval&&r==="waiting_approval"&&s!=="waiting_approval"?{kind:"approval",title:t,body:a?Ge.t("event.browser.approvalWithMessage",{message:a}):Ge.t("event.browser.approval")}:e.onComplete&&dl(s)&&r==="idle"?{kind:"complete",title:t,body:Ge.t("event.browser.finished")}:e.onError&&r==="error"&&s!=="error"?{kind:"error",title:t,body:Ge.t("event.browser.error")}:null}function hj(e,t={}){const s={...cj,...t},r=c.useRef(new Map),o=c.useRef(0),[a,i]=c.useState(null);c.useEffect(()=>{let d=!1;return uj().then(m=>{d||i(m)}),()=>{d=!0}},[]);const l=c.useCallback((d,m,u)=>{const h=Date.now();h-o.current<s.throttleMs||(o.current=h,xl(d,m,u))},[s.throttleMs]);c.useEffect(()=>{var d;if(!(!s.enabled||!jf())&&ao("browser")&&!dj(a)){if(document.hasFocus()){for(const m of e)r.current.set(m.id,Jt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=r.current.get(m.id),h=Jt(m.status,{activeModal:m.activeModal}),p=m.name||m.id,b=h==="waiting_choice"&&u!=="waiting_choice";if(lj(m.muted,u,h)){r.current.set(m.id,h);continue}const f=mj({name:p,prev:u,curr:h,modalMessage:(d=m.activeModal)==null?void 0:d.message,questionEntered:b,onApproval:s.onApproval&&ao("approval"),onComplete:s.onComplete&&ao("completion"),onError:s.onError});f&&l(f.title,f.body,`${f.kind}-${m.id}`),r.current.set(m.id,h)}}},[e,s.enabled,s.onApproval,s.onComplete,s.onError,a,l])}const pj=/^(run|approve|accept|yes|allow|always)/,fj=/^(run|approve|accept|yes|allow|always|proceed|save)/,bj=/^(reject|deny|delete|remove|abort|cancel|no)/;function gd(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").replace(/\s*\(\s*\)/g,"").trim()}function gj(e){const t=gd(e).toLowerCase();return pj.test(t)?"primary":bj.test(t)?"danger":"default"}function xj(e){return fj.test(gd(e).toLowerCase())?"approve":"reject"}function yj(e){return e.map((t,s)=>({label:gd(t),variant:gj(t),action:xj(t),button:t,buttonIndex:s}))}function vj(e,t,s){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:s}function wj(e,t,s,r){return[{label:"Approve",variant:"primary",onClick:()=>{s(e,t,"approve").catch(o=>r==null?void 0:r("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{s(e,t,"reject").catch(o=>r==null?void 0:r("reject",o))}}]}function xd(e){if(!(e==null||e==="")){if(typeof e=="string")return e.trim()||void 0;if(e instanceof Error)return e.message||String(e);if(typeof e=="object"){const t=e,s=t.error??t.message??t.reason;if(typeof s=="string"&&s.trim())return s.trim();if(s&&typeof s=="object")return xd(s);try{return JSON.stringify(e)}catch{return}}return String(e)}}class Sj{constructor(){ze(this,"dedupMap",new Map);ze(this,"DEDUP_WINDOW_MS",5e3);ze(this,"DEDUP_MAX_SIZE",50);ze(this,"DEDUP_CLEANUP_AGE_MS",1e4);ze(this,"toastCallbacks",[]);ze(this,"statusEventCallbacks",[]);ze(this,"resolveActionFn",null);ze(this,"viewRequestRespondFn",null);ze(this,"hydrateInteractivePromptFn",null);ze(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(s=>s!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(s=>s!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}setHydrateInteractivePrompt(t){this.hydrateInteractivePromptFn=t}hydrateInteractivePromptFromEvent(t){const s=this.hydrateInteractivePromptFn;if(!s)return;const r=t.targetSessionId;if(!r)return;const o=ll(t.interactivePrompt);o&&s(r,o)}emitToast(t){for(const s of this.toastCallbacks)s(t)}showToast(t,s="info",r){const o=(r==null?void 0:r.id)||Date.now();this.emitToast({id:o,message:t,type:s,timestamp:o,duration:5e3,...r})}showErrorToast(t,s,r){const o=xd(s);this.showToast(t,"warning",{duration:8e3,...o&&o!==t?{details:o}:{},...r})}isDuplicate(t){const s=Date.now(),r=this.dedupMap.get(t)||0;if(s-r<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,s),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[o,a]of this.dedupMap)s-a>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(o);return!1}resolveOwningDaemon(t){if(t.daemonId){const o=this.ides.find(a=>a.id===t.daemonId&&a.type==="adhdev-daemon");if(o)return o}const s=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(s){const o=s.daemonId;if(o){const a=this.ides.find(i=>i.id===o&&i.type==="adhdev-daemon");if(a)return a}}const r=this.ides.filter(o=>o.type==="adhdev-daemon");return r.length===1?r[0]:null}findOwningSession(t){for(const s of this.ides)if(s.id===t||s.sessionId===t||(Array.isArray(s.childSessions)?s.childSessions:[]).some(o=>(o==null?void 0:o.id)===t))return s;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const s=this.findOwningSession(t.targetSessionId);return(s==null?void 0:s.id)||(s==null?void 0:s.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}isConversationEventMuted(t){const s=t.targetSessionId;if(!s)return!1;for(const r of this.ides){if(r.id===s||r.sessionId===s)return!!r.muted;const a=(Array.isArray(r.childSessions)?r.childSessions:[]).find(i=>(i==null?void 0:i.id)===s);if(a)return!!a.muted}return!1}handleRawEvent(t,s){var x;const r=this.resolveConversationKey(t),o=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),a=r||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(o),l=`${a}:${t.event}:${i}`;if(t.event==="agent:waiting_choice"&&this.hydrateInteractivePromptFromEvent(t),this.isDuplicate(l))return;for(const g of this.statusEventCallbacks)g(t);const d=this.isConversationEventMuted(t),m=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,u=(m==null?void 0:m.type)||"";let h=u&&u!=="adhdev-daemon"?wf(u,{agentName:m==null?void 0:m.cliName}):Ot(u);const p=this.resolveOwningDaemon(t);if(p){const g=yn(p,{fallbackId:p.id});g&&(h=!u||u==="adhdev-daemon"?g:`${g}/${h}`)}let b="",f="info";if(t.event==="agent:generating_completed"){if(b=t.duration?`✅ ${Ge.t("event.taskCompletedWithDuration",{label:h,duration:xw(Number(t.duration)*1e3)})}`:`✅ ${Ge.t("event.taskCompleted",{label:h})}`,f="success",!d)try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started"){if(t.event==="agent:waiting_approval"){if(b=`⚡ ${Ge.t("event.approvalNeeded",{label:h})}`,f="warning",d)b="";else if((x=t.modalButtons)!=null&&x.length&&this.resolveActionFn){const g=this.resolveActionRouteTarget(t);if(!g)return;const S=this.resolveActionFn,w=yj(t.modalButtons).map(v=>({label:v.label,variant:v.variant,onClick:()=>{S(g,"resolve_action",{action:v.action,button:v.button,buttonIndex:v.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),_=vj(h,t.modalMessage,b),k=Date.now();this.emitToast({id:k,message:_,type:f,timestamp:k,targetKey:r||g,actions:w,duration:15e3}),b=""}}else if(t.event==="agent:waiting_choice"){b=`❓ ${Ge.t("event.questionNeeded",{label:h})}`,f="warning";const g=typeof t.modalMessage=="string"&&t.modalMessage.trim()?t.modalMessage.replace(/[\n\r]+/g," ").slice(0,120):"";g&&(b=`${b} — ${g}`);const S=Date.now();this.emitToast({id:S,message:b,type:f,timestamp:S,targetKey:r||t.daemonId,duration:1e4}),b=""}else if(t.event==="monitor:no_progress"){const g=t.elapsedSec?Math.round(t.elapsedSec/60):0;b=g?`⚠️ ${Ge.t("event.noProgressWithDuration",{label:h,minutes:g})}`:`⚠️ ${Ge.t("event.noProgress",{label:h})}`,f="warning",!d&&ao("browser")&&!document.hasFocus()&&xl(`⚠️ ${Ge.t("event.noProgressTitle",{label:h})}`,Ge.t("event.noProgressBody",{duration:g?`${g}m`:""}),`no-progress-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const g=t.requesterName||Ge.t("event.someoneRequester"),S=t.requestId,w=t.orgId;if(b=`${Ge.t("event.viewRequest",{requester:g})}`,f="warning",S&&w&&this.viewRequestRespondFn){const _=Date.now(),k=wj(w,S,this.viewRequestRespondFn,(v,y)=>console.error(`[EventManager] ${v} view request failed:`,y));this.emitToast({id:_,message:b,type:f,timestamp:_,actions:k,duration:3e4}),b=""}ao("browser")&&!document.hasFocus()&&xl(`${Ge.t("event.viewRequestTitle")}`,Ge.t("event.viewRequest",{requester:g}),`view-request-${S}`)}else if(t.event==="team:view_request_approved")b=`✅ ${Ge.t("event.viewRequestApproved")}`,f="success";else if(t.event==="team:view_request_rejected"){const g=t.targetName||Ge.t("event.someoneTarget");b=`❌ ${Ge.t("event.viewRequestDeclined",{target:g})}`,f="warning"}}if(b&&!d){const g=Date.now();this.emitToast({id:g,message:b,type:f,timestamp:g,targetKey:r||t.daemonId,duration:5e3})}}}const Ze=new Sj,Vu=new Map;function Nf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ir(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Si(e){return Xp(e)??null}function kj(e){const t=Si(e);return!t||!Nf(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function zo(e){const t=Si(e);return!t||!Nf(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function $r(e){const t=Si(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Vo(e){const t=Si(e);return!!t&&t.success===!1}function jj(e){var t,s;for(const r of e||[]){if(r.type==="toast"&&((t=r.toast)!=null&&t.message)){const o=r.toast.level==="warning"?"warning":r.toast.level==="success"?"success":"info";Ze.showToast(r.toast.message,o);continue}if(r.type==="notification"&&((s=r.notification)!=null&&s.body)){const o=r.notification.level==="warning"?"warning":r.notification.level==="success"?"success":"info";Ze.showToast(r.notification.body,o)}}}function Nj(e,t){return e&&ir(e.currentValue)?e.currentValue:t}function Cj(e,t){const s=Object.keys(e).filter(o=>t[o]!==void 0);if(s.length===0)return e;const r={...e};for(const o of s)delete r[o];return r}function _j(e,t){return ir(t)?ir(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Aj(e,t){var a,i;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(ir(l))return l}const r=(a=t.controlValues)==null?void 0:a[e];if(ir(r))return r;const o=(i=t.defaultValues)==null?void 0:i[e];return ir(o)?o:void 0}function ga(e,t){return e.options||t[e.id]||[]}const Tj={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session","stop"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function Ij(e,t,s){var r;return((r=Tj[t])==null?void 0:r.has(s.id))===!0}function Mj(e){if(e){if(ci(e))return["busy","generating","starting"];switch(e){case"idle":return["idle"];case"waiting_approval":case"approval":return["approval"];case"waiting_choice":return["picker"];default:return}}}function Rj(e,t){const s=e.visibleWhenState;if(!s||s.length===0)return!0;const r=Mj(t);return r?r.some(o=>s.includes(o)):!0}function yd(e,t){return(e||[]).filter(s=>s.placement==="bar"&&s.hidden!==!0&&!Ij(t.hostIdeType,t.providerType,s)&&Rj(s,t.currentStatus)).sort((s,r)=>(s.order??50)-(r.order??50))}function ic(e,t){return{value:t}}function Pj(e,t,s){var o;return s?((o=ga(e,t).find(a=>a.value===s))==null?void 0:o.label)||s:""}const Ej={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Dj({routeId:e,sessionId:t,hostIdeType:s,providerType:r,displayLabel:o,controls:a,controlValues:i,currentStatus:l,coordinatorHint:d}){const{t:m}=pe("common"),{sendCommand:u}=xt(),{confirm:h,confirmDialog:p}=wr(),b=`${e}:${t||r}`,f=Ej[r]||"#94a3b8",[x,g]=c.useState({}),S=c.useRef({}),w=c.useRef(i);S.current=x,w.current=i;const _=c.useRef(0),k={};for(const T of a||[])T.defaultValue!==void 0&&(k[T.id]=T.defaultValue);const v={...k,...i||{},...Date.now()<_.current?x:{}};c.useEffect(()=>{i&&Date.now()>_.current&&g(T=>Cj(T,i))},[i]);const[y,j]=c.useState(Vu.get(b)||{}),[N,A]=c.useState(null),[R,P]=c.useState(null),M=c.useCallback(async(T,$={})=>{const H={...$,...t&&{targetSessionId:t},...d??{}};return await u(e,T,H)},[e,t,u,d]),E=c.useCallback(async(T,$={})=>{const H=t?{targetSessionId:t}:{agentType:r,...s?{ideType:s}:{}};return await M("invoke_provider_script",{...H,scriptName:T,...$})},[M,r,s,t]),C=c.useCallback((T,$,H)=>{const q=Nj(H,$);g(U=>({...U,[T.id]:q})),jj(H==null?void 0:H.effects)},[]),I=c.useCallback((T,$)=>{g(H=>{const q={...H};return $===void 0?delete q[T.id]:q[T.id]=$,q}),_.current=0},[]);if(!a||a.length===0)return null;const O=yd(a,{hostIdeType:s,providerType:r,currentStatus:l});if(O.length===0)return null;const D=async T=>{if(N===T.id){A(null);return}if(ga(T,y).length>0){A(T.id);return}if(T.dynamic&&T.listScript){P(T.id);try{const H=await E(T.listScript,{}),q=kj(H);if(!q){const oe=$r(H);oe&&Ze.showErrorToast(m("controls.loadOptionsFailed",{label:T.label}),oe);return}const U=q.options;j(oe=>{const ke={...oe,[T.id]:U};return Vu.set(b,ke),ke});const K=Aj(T.id,{localOverrideUntil:_.current,localValues:S.current,controlValues:w.current,defaultValues:k});if(_j(K,q.currentValue)){const oe=q.currentValue;g(ke=>({...ke,[T.id]:oe}))}A(T.id)}catch(H){Ze.showErrorToast(m("controls.loadOptionsFailed",{label:T.label}),H)}finally{P(null)}}},F=async(T,$)=>{A(null);const H=(i==null?void 0:i[T.id])??k[T.id];g(q=>({...q,[T.id]:$})),_.current=Date.now()+5e3;try{if(!T.setScript)return;const q=await E(T.setScript,ic(T,$)),U=zo(q);if(U&&!U.ok||Vo(q))throw new Error((U==null?void 0:U.error)||$r(q)||`Could not update ${T.label}`);C(T,$,U)}catch(q){I(T,H),Ze.showErrorToast(m("controls.updateFailed",{label:T.label}),q)}},z=async T=>{const $=ga(T,y).map(ke=>ke.value);if($.length===0)return;const H=String(v[T.id]||""),U=($.indexOf(H)+1)%$.length,K=$[U];if(typeof K!="string")return;const oe=(i==null?void 0:i[T.id])??k[T.id];g(ke=>({...ke,[T.id]:K})),_.current=Date.now()+5e3;try{if(!T.setScript)return;const ke=await E(T.setScript,ic(T,K)),J=zo(ke);if(J&&!J.ok||Vo(ke))throw new Error((J==null?void 0:J.error)||$r(ke)||`Could not update ${T.label}`);C(T,K,J)}catch(ke){I(T,oe),Ze.showErrorToast(m("controls.updateFailed",{label:T.label}),ke)}},Z=async T=>{const H=!v[T.id],q=(i==null?void 0:i[T.id])??k[T.id];g(U=>({...U,[T.id]:H})),_.current=Date.now()+5e3;try{if(!T.setScript)return;const U=await E(T.setScript,ic(T,H)),K=zo(U);if(K&&!K.ok||Vo(U))throw new Error((K==null?void 0:K.error)||$r(U)||`Could not update ${T.label}`);C(T,H,K)}catch(U){I(T,q),Ze.showErrorToast(m("controls.updateFailed",{label:T.label}),U)}},W=async T=>{var H,q,U;if(!T.invokeScript||T.confirmMessage&&!await h({title:((H=T.confirmTitle)==null?void 0:H.trim())||T.confirmMessage,description:(q=T.confirmTitle)!=null&&q.trim()?T.confirmMessage:void 0,confirmLabel:((U=T.confirmLabel)==null?void 0:U.trim())||m("common.confirm")}))return;const $=(i==null?void 0:i[T.id])??k[T.id];try{const K=await E(T.invokeScript),oe=zo(K);if(oe&&!oe.ok||Vo(K))throw new Error((oe==null?void 0:oe.error)||$r(K)||`Could not run ${T.label}`);oe&&C(T,$??!0,oe)}catch(K){I(T,$),Ze.showErrorToast(m("controls.runFailed",{label:T.label}),K)}};return n.jsxs("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-2xs font-semibold tracking-[0.02em]",style:{borderColor:`${f}33`,background:`${f}12`,color:f},children:o}),O.map(T=>{const $=String(v[T.id]||""),H=Pj(T,y,$),q=N===T.id,U=R===T.id,K=ga(T,y),oe="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-xs font-medium transition-colors whitespace-nowrap";switch(T.type){case"select":return n.jsxs("div",{className:"relative max-w-full",children:[n.jsxs("button",{type:"button",className:`${oe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:q?`${f}55`:"var(--border-default)",background:q?`${f}10`:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void D(T),title:T.label,children:[T.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:T.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:U?m("chatControls.loading"):H||T.label}),n.jsx("span",{className:"text-4xs opacity-55",children:"▼"})]}),q&&K.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-[var(--z-dropdown)]",onClick:()=>A(null)}),n.jsxs("div",{className:"absolute bottom-full left-0 z-[var(--z-dropdown)] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[n.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-3xs font-semibold uppercase tracking-[0.08em] text-text-muted",children:T.label}),K.map(ke=>n.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-xs transition-colors",style:{background:ke.value===$?`${f}14`:"transparent",color:ke.value===$?"var(--text-primary)":"var(--text-secondary)",borderLeft:ke.value===$?`2px solid ${f}`:"2px solid transparent"},title:ke.description||ke.label,onMouseEnter:J=>{J.currentTarget.style.background=`${f}10`},onMouseLeave:J=>{J.currentTarget.style.background=ke.value===$?`${f}14`:"transparent"},onClick:()=>void F(T,ke.value),children:[n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ke.label}),ke.value===$&&n.jsx("span",{className:"shrink-0 text-2xs font-semibold",style:{color:f},children:"✓"})]},ke.value))]})]})]},T.id);case"cycle":return n.jsxs("button",{type:"button",className:`${oe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void z(T),title:`Click to cycle: ${K.map(ke=>ke.label).join(" → ")}`,children:[T.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:T.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:H||T.label}),n.jsx("span",{className:"text-3xs opacity-55",children:"⟳"})]},T.id);case"toggle":return n.jsxs("button",{type:"button",className:`${oe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${f}44`:"var(--border-default)",background:$?`${f}14`:"var(--surface-tertiary)",color:$?f:"var(--text-muted)"},onClick:()=>void Z(T),"aria-pressed":!!$,children:[T.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:T.icon}),T.label]},T.id);case"action":return n.jsxs("button",{type:"button",className:`${oe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void W(T),children:[T.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:T.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:T.resultDisplay==="inline"&&$?`${T.label}: ${$}`:T.label})]},T.id);case"display":return n.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-xs font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},children:[T.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:T.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$?`${T.label}: ${$}`:T.label})]},T.id);default:return null}})]}),p]})}function Lj(e){if(!e||typeof e!="object")return{};const t=e,s=av(t.launch);return{...s?{launch:s}:{},...typeof t.model=="string"&&t.model.trim()?{model:t.model.trim()}:{},...nd(t.modelSource)?{modelSource:t.modelSource}:{}}}const Gu={user:"chosen",remembered:"remembered",mesh_slot:"mesh slot",task_override:"task",provider_default:"default",unspecified:""};function Oj(e,t){return String(t.defaultValue??"").replace(/\{\{(\w+)\}\}/g,(s,r)=>String(t[r]??""))}function Cf(e,t=Oj){const s=e.launch?ov(e.launch.model):void 0,r=(s==null?void 0:s.value)??e.model;if(!r)return null;const o=(s==null?void 0:s.source)??e.modelSource??"unspecified";if(s!=null&&s.changedFrom)return{text:t("chatControls.launchModelChanged",{from:s.changedFrom,to:r,defaultValue:"{{from}} → {{to}} (changed)"}),source:o};const a=Gu[o]?t(`chatControls.launchModelSource.${o}`,{defaultValue:Gu[o]}):"";return{text:a?`${r} · ${a}`:r,source:o}}function $j({surface:e}){const{t}=pe("common"),s=Cf(e,t);return s?n.jsx("span",{className:"inline-flex items-center rounded-full border border-border-subtle px-2 py-0.5 text-2xs text-text-muted","data-testid":"session-launch-chip","data-model-source":s.source,children:s.text}):null}function Fj({isActive:e=!0,isCliTerminal:t=!1,routeId:s,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:l,controlValues:d,currentStatus:m,coordinatorHint:u,launchSurface:h}){const{isVisible:p}=fd(),b=yd(l,{hostIdeType:o,providerType:a,currentStatus:m}),f=b.length>0&&p,x=!!h&&!!Cf(h);return!e||t||!f&&!x?null:n.jsxs("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:[x&&h&&n.jsx("div",{className:"flex justify-end px-3 pt-1",children:n.jsx($j,{surface:h})}),f&&n.jsx(Dj,{routeId:s,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:b,controlValues:d,currentStatus:m,coordinatorHint:u})]})}const Fr=5,_f=10*1024*1024;function Hj({hasDraft:e,isBusy:t=!1}){return!e||t}function Bj(e){return new Promise((t,s)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>s(new Error("Failed to read file")),r.readAsDataURL(e)})}async function Wj(e){if(e.size>_f)return null;const t=await Bj(e),s=t.indexOf(",");if(s<0)return null;const r=t.slice(s+1);return{mimeType:e.type||"image/png",data:r,name:e.name,previewUrl:t}}function Uj(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}function Kj(e){return/[\u1100-\u11FF\u3130-\u318F\uAC00-\uD7A3]/.test(e)}const Af=c.memo(function({contextKey:t,panelLabel:s,isSending:r,isBusy:o=!1,statusMessage:a=null,inlineStatusMessage:i=null,onSend:l,isActive:d=!0,showControlsToggle:m=!1,animateVisibility:u=!0,onControlsToggle:h,messageInput:p}){const{t:b}=pe("common"),f=c.useRef(null),x=c.useRef(null),[g,S]=c.useState(""),[w,_]=c.useState([]),[k,v]=c.useState(null),[y,j]=c.useState(!1),N=c.useRef(!1),A=c.useRef(0),R=50,P=c.useRef(""),M=c.useRef(!1),E=c.useRef(null),C=30,{isVisible:I,toggleVisibility:O}=fd(),D=Uj(p),F=!!g.trim()||w.length>0;c.useEffect(()=>{S(""),_([]),v(null)},[t]),c.useEffect(()=>{var K;d&&((K=f.current)==null||K.focus({preventScroll:!0}))},[t,d]),c.useEffect(()=>{const K=f.current;K&&(K.style.height="auto",g&&(K.style.height=`${Math.min(K.scrollHeight,160)}px`))},[g]);const z=c.useCallback(async K=>{v(null);const oe=Array.from(K).filter(de=>de.type.startsWith("image/"));if(oe.length===0)return;const ke=Fr-w.length;if(ke<=0){v(`Max ${Fr} images`);return}const J=oe.slice(0,ke);if(J.filter(de=>de.size>_f).length>0){v("Image too large (max 10 MB)");return}const re=(await Promise.all(J.map(Wj))).filter(de=>de!==null);_(de=>[...de,...re])},[w.length]),Z=c.useCallback(K=>{_(oe=>oe.filter((ke,J)=>J!==K))},[]),W=c.useCallback(async()=>{const K=g.trim();if(!K&&w.length===0||o||N.current)return;N.current=!0;const oe=w.length>0?[...w]:void 0;try{await l(K,oe)!==!1&&(S(""),_([]),v(null))}finally{N.current=!1}},[g,w,o,l]),T=c.useRef(W);T.current=W;const $=c.useCallback(()=>{M.current&&(M.current=!1,E.current&&(clearTimeout(E.current),E.current=null),setTimeout(()=>{T.current()},0))},[]);c.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]);const H=c.useCallback(K=>{D&&(K.preventDefault(),j(!0))},[D]),q=c.useCallback(()=>j(!1),[]),U=c.useCallback(K=>{D&&(K.preventDefault(),j(!1),K.dataTransfer.files.length>0&&z(K.dataTransfer.files))},[D,z]);return n.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",u?"transition-all duration-200 ease-out":"",y?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:d?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:d?200:0,opacity:d?1:0,transform:d?"translateY(0)":"translateY(10px)",padding:d?"10px 12px":"0 12px",pointerEvents:d?"auto":"none"},"aria-hidden":!d,onDragOver:H,onDragLeave:q,onDrop:U,children:[w.length>0&&n.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:w.map((K,oe)=>n.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[n.jsx("img",{src:K.previewUrl,alt:K.name,className:"w-full h-full object-cover"}),n.jsx("button",{type:"button",onClick:()=>Z(oe),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-3xs leading-none","aria-label":`Remove ${K.name}`,children:"✕"})]},oe))}),n.jsxs("div",{className:"flex gap-2 items-center",title:d?b("chatInput.sendTo",{panel:s}):void 0,children:[m&&n.jsx("button",{type:"button",onClick:()=>{O(),h==null||h()},"aria-label":b(I?"chatInput.hideControls":"chatInput.showControls"),"aria-pressed":I,title:b(I?"chatInput.hideControls":"chatInput.showControls"),className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:n.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[n.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),n.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),n.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),D&&n.jsxs(n.Fragment,{children:[n.jsx("input",{ref:x,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:K=>{K.target.files&&z(K.target.files),K.target.value=""}}),n.jsx("button",{type:"button",onClick:()=>{var K;return(K=x.current)==null?void 0:K.click()},disabled:w.length>=Fr,title:w.length>=Fr?`Max ${Fr} images`:b("chatInput.attachImage"),className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":b("chatInput.attachImage"),children:n.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),n.jsx("div",{className:"flex-1 relative",children:n.jsx("textarea",{ref:f,rows:1,placeholder:a||(D&&w.length>0?b("chatInput.addMessageOptional"):b("chatInput.placeholder",{panel:s})),value:g,onChange:K=>S(K.target.value),onPaste:K=>{if(D&&K.clipboardData.files.length>0&&Array.from(K.clipboardData.files).some(ie=>ie.type.startsWith("image/"))){K.preventDefault(),z(K.clipboardData.files);return}const oe=K.clipboardData.getData("text/plain"),ke=Cv(oe);if(ke===oe)return;K.preventDefault();const J=f.current,ye=(J==null?void 0:J.selectionStart)??g.length,ae=(J==null?void 0:J.selectionEnd)??g.length,re=g.slice(0,ye)+ke+g.slice(ae);S(re);const de=ye+ke.length;requestAnimationFrame(()=>{J==null||J.setSelectionRange(de,de)})},onCompositionUpdate:K=>{P.current=K.data||""},onCompositionEnd:K=>{A.current=Date.now(),K.data&&(P.current=K.data),$()},onKeyDown:K=>{if(K.key!=="Enter"||K.shiftKey)return;if(K.nativeEvent.isComposing||K.keyCode===229||Date.now()-A.current<R){K.preventDefault(),Kj(P.current)&&!M.current&&(M.current=!0,E.current=setTimeout($,C));return}K.preventDefault(),W()},className:"w-full rounded-[20px] px-4 py-2 bg-bg-secondary text-sm text-text-primary resize-none leading-[1.4] block",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))",minHeight:40,maxHeight:160,overflowY:"auto",whiteSpace:"pre-wrap"}})}),n.jsx("button",{onClick:()=>{W()},disabled:Hj({hasDraft:F,isBusy:o}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${F&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:F&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":b("chatInput.sendMessage"),children:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:F?"text-white":"text-text-muted",children:n.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(k||D&&y)&&n.jsx("div",{className:`pt-1.5 px-1 text-2xs ${k?"text-red-400":"text-[var(--accent-primary)]"}`,children:k||b("chatInput.dropImage")}),i&&!k&&n.jsx("div",{className:"pt-2 px-1 text-2xs text-text-muted opacity-80",children:i})]})});function qj({entries:e,onSendNow:t,onCancelQueued:s,isSendingNow:r}){const{t:o}=pe(),a=e.filter(d=>d.queued===!0&&!!d.id);if(a.length===0)return null;const i=a.some(d=>d.stale!==!0),l=o(i?"chat.waitingToSendAria":"chat.notDeliveredAria");return n.jsx("div",{className:"chat-pending-queue-strip","data-testid":"pending-queue-strip","data-pending-queue-count":a.length,role:"region","aria-label":l,children:a.map(d=>n.jsxs("div",{className:"chat-pending-queue-row","data-chat-queued-row":"true","data-chat-queued-stale":d.stale===!0?"true":void 0,children:[n.jsxs("div",{className:"chat-bubble chat-bubble-user chat-pending-queue-bubble",title:d.content,children:[n.jsx("div",{className:"chat-pending-queue-body",children:d.content}),n.jsx("span",{className:d.stale===!0?"chat-pending-queue-clock chat-pending-queue-stale":"chat-pending-queue-clock",role:"img","aria-label":d.stale===!0?o("chat.notDeliveredAria"):o("chat.waitingToSendAria"),title:d.stale===!0?o("chat.notDelivered"):o("chat.waitingToSendAria"),children:d.stale===!0?"⚠":"⏱"})]}),t&&n.jsx("button",{type:"button",onClick:()=>t(d.id),disabled:r,className:"chat-pending-queue-send","aria-label":o("chat.sendNowAria"),title:o("chat.sendNowTitle"),children:"↑"}),s&&n.jsx("button",{type:"button",onClick:()=>s(d.id),disabled:r,className:"chat-pending-queue-cancel","aria-label":o("chat.cancelQueuedAria"),title:o("chat.cancelQueuedTitle"),children:"✕"})]},d.id))})}const zj=c.memo(qj,(e,t)=>e.onSendNow===t.onSendNow&&e.onCancelQueued===t.onCancelQueued&&e.isSendingNow===t.isSendingNow&&e.entries.length===t.entries.length&&e.entries.every((s,r)=>{const o=t.entries[r];return!!o&&s.id===o.id&&s.content===o.content&&s.queued===o.queued&&s.stale===o.stale})),Vj={accent:{track:"--accent-primary",head:"--accent-primary-light"},success:{track:"--status-online",head:"--status-online"},muted:{track:"--text-muted",head:"--text-muted"}};function Zt({size:e=28,thickness:t=2.5,color:s="accent",className:r,label:o}){const a=Vj[s],i={width:e,height:e,border:`${t}px solid color-mix(in srgb, var(${a.track}) 20%, transparent)`,borderTopColor:`var(${a.head})`};return n.jsx("span",{className:ct("block shrink-0 rounded-full animate-spin",r),style:i,role:o?"status":void 0,"aria-label":o,"aria-hidden":o?void 0:!0})}const Gj=1e4;function Yj({machineId:e,blocked:t,retryConnection:s}){const{t:r}=pe("common"),[o,a]=c.useState(!1),i=c.useRef(null);if(c.useEffect(()=>{t||a(!1)},[t]),c.useEffect(()=>{if(!o)return;const d=setTimeout(()=>a(!1),Gj);return()=>clearTimeout(d)},[o]),c.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),!e||!t||!s)return null;const l=()=>{o||(a(!0),s(e))};return n.jsxs("button",{type:"button","data-testid":"chat-machine-reconnect",onClick:l,disabled:o,"aria-label":r("chatPane.reconnectMachine"),title:r("chatPane.reconnectMachineTitle"),className:"inline-flex items-center justify-center gap-1 h-6 px-2 rounded-full leading-none text-3xs font-bold transition-colors bg-red-500/10 border border-red-500/25 text-red-400 hover:bg-red-500/20 disabled:opacity-60 disabled:cursor-not-allowed",style:{pointerEvents:"auto"},children:[o?n.jsx(Zt,{size:11,thickness:2,color:"muted"}):n.jsx(ur,{size:12}),n.jsx("span",{children:r(o?"chatPane.reconnectingMachine":"chatPane.reconnectMachine")})]})}let Tf=xn;function ki(){return Tf()}class Qj{constructor(){ze(this,"listeners",new Map)}send(t,s){return!1}isConnected(){return!1}on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>{var r;(r=this.listeners.get(t))==null||r.delete(s)}}emit(t,...s){var r;(r=this.listeners.get(t))==null||r.forEach(o=>o(...s))}}let If=new Qj;class Jj{sendPtyInput(t,s,r){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,s){return!1}get(t){}onScreenshot(t,s){return()=>{}}onRuntimeEvent(t,s,r){return()=>{}}requestRuntimeSnapshot(t,s,r){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let Dt=new Jj;function Xj(e){e.dashboardWS&&(If=e.dashboardWS),e.connectionManager&&(Dt=e.connectionManager),e.useDaemonsHook&&(Tf=e.useDaemonsHook)}function xa(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Mf="adhdev-pending-queued-messages-v1",Zj=256*1024,eN=24*60*60*1e3,Rf=10*60*1e3;function Pf(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Mf)||"{}");return{byKey:e.byKey&&typeof e.byKey=="object"?e.byKey:{}}}catch{return{byKey:{}}}}function tN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Mf,JSON.stringify(e))}catch{}}function nN(e,t){if(!e||typeof e!="object")return;const s=e;if(!Array.isArray(s.parts))return;let r=0;const o=new Set(s.omitted&&typeof s.omitted=="object"&&Array.isArray(s.omitted.partTypes)?s.omitted.partTypes.filter(l=>typeof l=="string"):[]),a=[];for(const l of s.parts){if(!l||typeof l!="object")continue;const d=l,m=typeof d.type=="string"?d.type:"";if(!m)continue;if(m==="text"){a.push({type:"text",text:typeof d.text=="string"?d.text:""});continue}const u=typeof d.data=="string"?d.data:void 0,h=u?u.length:0;if(u&&r+h<=Zj){r+=h,a.push({type:m,mimeType:typeof d.mimeType=="string"?d.mimeType:void 0,uri:typeof d.uri=="string"?d.uri:void 0,data:u,alt:typeof d.alt=="string"?d.alt:void 0});continue}if(!u){a.push({type:m,mimeType:typeof d.mimeType=="string"?d.mimeType:void 0,uri:typeof d.uri=="string"?d.uri:void 0,alt:typeof d.alt=="string"?d.alt:void 0});continue}o.add(m),a.push({type:m,mimeType:typeof d.mimeType=="string"?d.mimeType:void 0,alt:typeof d.alt=="string"?d.alt:void 0})}const i=typeof s.textFallback=="string"?s.textFallback:t;return{parts:a,textFallback:i,...o.size>0?{omitted:{omitted:!0,partTypes:[...o]}}:{}}}function Ef(e,t){if(!Array.isArray(e))return[];const s=new Set,r=[];let o=0;for(const a of e){if(!a||typeof a!="object")continue;const i=a,l=typeof i.content=="string"?i.content:"",d=typeof i.sentAt=="number"&&Number.isFinite(i.sentAt)?i.sentAt:0,m=typeof i.id=="string"&&i.id?i.id:"";if(!l.trim()||!d||!m||t-d>eN||s.has(m))continue;s.add(m);const u=i.stale===!0||t-d>Rf,h=nN(i.input,l);r.push({entry:{id:m,content:l,sentAt:d,queued:i.queued===!0,settled:!0,stale:u,...h?{input:h}:{}},index:o}),o+=1}return r.sort((a,i)=>a.entry.sentAt-i.entry.sentAt||a.index-i.index),r.map(a=>a.entry).slice(-20)}let Yu=0;function sN(e=Date.now()){try{const t=typeof globalThis<"u"?globalThis.crypto:void 0;if(typeof(t==null?void 0:t.randomUUID)=="function")return t.randomUUID()}catch{}return Yu+=1,`pq-${e}-${Yu}`}function rN(e,t=Date.now()){const s=String(e||"").trim();return s?Ef(Pf().byKey[s],t):[]}function oN(e,t,s=Date.now()){const r=String(e||"").trim();if(!r)return;const o=Pf(),a=Ef(t,s);a.length>0?o.byKey[r]=a:delete o.byKey[r],tN(o)}function Df(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}const aN=12e4;function iN(e){if(typeof e=="string")return e.trim();if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}const cN=/^(?:\s*(?:\[Image #\d+\]|\[image: [^\]\n]{1,100}\]))+\s*/;function lN(e,t){const s=iN(e);if(s===t)return!0;const r=s.replace(cN,"").trim();return r!==s&&r.length>0&&r===t}function dN(e,t){if(!t)return!1;const s=e.meta;return typeof(s==null?void 0:s.sourceMessageId)=="string"&&s.sourceMessageId===t}function Qu(e){const t=e.meta;return typeof(t==null?void 0:t.sourceMessageId)=="string"&&t.sourceMessageId.length>0}function Lf(e,t){if(!t)return 0;let s=0;for(const r of e)String(r.role||"").toLowerCase()==="user"&&lN(r.content,t)&&(s+=1);return s}function uN(e,t,s=Date.now(),r=Rf){if(!e||e.length===0)return{entries:[],changed:!1,retiredByEcho:0,markedStale:0};const o=new Map,a=[];let i=0,l=0,d=!1;const m=t.some(u=>Qu(u))?t.filter(u=>!Qu(u)):t;for(const u of e){const h=u.content.trim();if(!h){d=!0;continue}if(t.some(f=>dN(f,u.id))){i+=1,d=!0;continue}o.has(h)||o.set(h,Lf(m,h));const p=o.get(h)||0;if(p>0){o.set(h,p-1),i+=1,d=!0;continue}if(s-u.sentAt>r&&u.stale!==!0){l+=1,d=!0,a.push({...u,stale:!0});continue}a.push(u)}return d?{entries:a,changed:!0,retiredByEcho:i,markedStale:l}:{entries:e,changed:!1,retiredByEcho:0,markedStale:0}}function mN(e){return{id:`pending-local:${e.id||e.sentAt}`,role:"user",kind:"standard",content:e.content,senderName:"User",timestamp:e.sentAt,receivedAt:e.sentAt,meta:{pendingLocal:!0,queued:e.queued===!0,pendingId:e.id||String(e.sentAt)}}}function hN(e,t,s=Date.now(),r={}){if(!t||t.length===0)return e;const o=new Map,a=[];for(const i of t){const l=i.content.trim();if(!l||s-i.sentAt>aN)continue;o.has(l)||o.set(l,Lf(e,l));const d=o.get(l)||0;if(d>0){o.set(l,d-1);continue}r.excludeQueued&&i.queued===!0&&i.id||a.push(mN(i))}return a.length===0?e:[...e,...a]}function pN(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const s=String(e.kind||"standard").toLowerCase();return s===""||s==="standard"}function cc(e){return pN(e)?String(e.role||"").toLowerCase():""}const fN=4;function bN(e,t){if(e.length===0)return[];for(let a=t.length-1;a>=0;a-=1)if(cc(t[a])==="assistant")return[];const s=t.some(a=>cc(a)==="user"),r=[];let o=!1;for(let a=e.length-1;a>=0&&r.length<fN;a-=1){const i=e[a],l=cc(i);if(l){if(!o&&l==="assistant"){r.unshift(i),o=!0;continue}if(o&&l==="user"){s||r.unshift(i);break}}}return r}function gN(e){let t=!0;for(let s=1;s<e.length;s+=1)if(xa(e[s-1])>xa(e[s])){t=!1;break}return t?e:e.map((s,r)=>({message:s,index:r,ts:xa(s)})).sort((s,r)=>s.ts-r.ts||s.index-r.index).map(s=>s.message)}function xN(e){const{historyMessages:t,liveMessages:s,visibleLiveCount:r}=e,o=Math.max(0,s.length-r),a=o>0?s.slice(0,o):[],i=o>0?s.slice(-r):s,l=bN(a,i),d=l.length>0?[...l,...i]:i,m=t.length===0?d:[...t,...d];return gN(m)}const ht=e=>e.transport==="pty",kr=(e,t)=>ht(e)&&e.mode||"chat",Of=(e,t)=>ht(e)&&kr(e)==="terminal",yN=180;function ps(e){return e.streamSource!=="agent-stream"}function Jn(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function ji(e){var s;const t=typeof((s=e.settings)==null?void 0:s.meshCoordinatorDaemonId)=="string"?e.settings.meshCoordinatorDaemonId:void 0;return t?{meshCoordinatorDaemonId:t}:{}}function $f(e){return e.machineName||""}function ys(e){return Jn(e)}function On(e){return e.agentType||""}function Oa(e){return e.hostIdeType||""}function vd(e){return e.displayPrimary||e.agentName||"Agent"}function Ff(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function vN(e,t){const s=Df(e,t),r=[...s].reverse();return r.find(o=>!(o!=null&&o._localId)&&bi(o).isUserFacing)||r.find(o=>!(o!=null&&o._localId))||s[s.length-1]}function Hf(e,t){const s=vN(e,t),r=cr(s==null?void 0:s.content),o=cr(e.lastMessagePreview);return o&&e.lastMessageRole==="assistant"&&(s==null?void 0:s.role)==="user"?o:r||o||""}function wN(e,t=yN){const s=cr(e);if(!s||t<=0)return"";const r=Array.from(s);return r.length<=t?s:`${r.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function SN(e){return wN(Hf(e)||e.displaySecondary||"")}function Bf(e){return[e.displaySecondary,$f(e)].filter(Boolean)}function hr(e){return e.agentName||Ot(On(e))}function kN(e){var t,s;if(!ps(e)){const r=(s=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:s.trim();if(r)return r}return Ot(Oa(e)||On(e))}function Wf(e){return ps(e)?e.sessionId:e.nativeSessionId}function Ju(e){return ps(e)?"native":e.tabKey}function jN(e){return e.sessionId}function Uf(e,t){if(t)return ps(e)||!t.childSessions?t:t.childSessions.find(s=>s.id===e.sessionId||s.providerType===e.agentType)||t}function NN(e,t){const s=On(e),r=ps(e),o=ht(e),a=r?o?hr(e)||(t==null?void 0:t.cliName)||Ot(Oa(e)||s):t!=null&&t.type?Ot(t.type):Ot(Oa(e)||s):hr(e);return{isNativeConversation:r,isCli:ht(e),isCliTerminal:Of(e),providerType:s,displayLabel:a,targetEntry:Uf(e,t)}}function fs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:ht(e)?{agentType:On(e)}:e.streamSource==="agent-stream"?{agentType:On(e)}:t}function ms(e){return e?ys(e):""}function nr(e,t){e(s=>[...s,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}const CN="Waiting for approval…",_N="Waiting for your answer…";function Ni(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?e.status==="waiting_choice"?"Answer the pending question above.":"Approve or reject the pending request above.":null}function Kf(e){return Ni(e)?(e==null?void 0:e.status)==="waiting_choice"?_N:CN:null}function Go(e){const t=e instanceof Error?e.message:String(e||""),s=t.toLowerCase();return s.includes("awaiting confirmation")?"Approve or reject the pending request above.":s.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":s.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}function qf(){return"select_session"}function AN(){return"open_panel"}function TN({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function IN(e,t,s=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<s:!1}function Xu(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Ps(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}const eo="Waiting to send — the agent is still working.",MN="Too late to cancel — this message was already sent to the agent.";function Zu(e){return!e||typeof e!="object"?!1:e.queued===!0}function RN({feedbackMessage:e,lastSendQueued:t,isGenerating:s}){return!t||e!==eo?!1:!s}function wd(e){return e instanceof Error?e.message:String(e||"")}function em(e){const t=wd(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function tm(e,t){const s=wd(t);return s?s.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${s}`:`⚠️ **${e}** unavailable`}const PN=5e3;function EN(e,t,s=PN){const r=e.get(t);if(!r)return Promise.resolve("unknown");let o;const a=new Promise(i=>{o=setTimeout(()=>i("unknown"),s)});return Promise.race([r,a]).finally(()=>{o&&clearTimeout(o)})}function DN(e,t){if(!t||t.length===0)return;const s=t.map(r=>({type:"image",mimeType:r.mimeType,data:r.data,alt:r.name}));return e&&s.push({type:"text",text:e}),{parts:s,textFallback:e}}function nm(e,t,s,r,o={mode:"queue"}){const a=s?{parts:s.parts,textFallback:s.textFallback}:{parts:[{type:"text",text:t}],textFallback:t};return{messageId:e,input:a,policy:o,...fs(r)}}function Ci({sendDaemonCommand:e,activeConv:t,setActionLogs:s,isStandalone:r}){const[o,a]=c.useState(!1),[i,l]=c.useState(!1),[d,m]=c.useState(null),[u,h]=c.useState(!1),[p,b]=c.useState([]),f=c.useRef(!1),x=c.useRef(null),g=c.useRef([]);g.current=p;const S=c.useRef(new Map),w=(t==null?void 0:t.tabKey)||"",_=c.useRef(w);_.current=w;const k=c.useCallback(C=>{b(I=>{const O=C(I);return O===I?I:(oN(_.current,O),O)})},[]),v=c.useCallback(C=>{k(I=>{const O=uN(I,C);return O.changed?O.entries:I})},[k]);c.useEffect(()=>{m(null),h(!1),b(w?rN(w):[])},[t==null?void 0:t.tabKey,w]);const y=t?Bs(t):!1;c.useEffect(()=>{m(C=>RN({feedbackMessage:C,lastSendQueued:u,isGenerating:y})?null:C),!y&&u&&h(!1)},[y,u]);const j=c.useCallback(async(C,I)=>{if(!t||f.current)return!1;const O=C.trim(),D=Ni(t);if(TN({hasMessage:!!O,blockedMessage:D,sendInFlight:f.current}))return D&&m(D),!1;const F=Date.now(),z={tabKey:t.tabKey,message:O,timestamp:F};if(IN(x.current,z))return m(null),!0;f.current=!0,l(!0),m(null),h(!1),x.current=z;const Z=sN(F),W=DN(O,I);let T=()=>{};S.current.set(Z,new Promise(H=>{T=H}));let $="not-parked";k(H=>[...H,{id:Z,content:O,sentAt:F,...W?{input:W}:{}}].slice(-20));try{const H=ms(t);if(!H)return x.current=Xu(x.current,z),k(K=>K.filter(oe=>oe.id!==Z)),m("Unable to send message right now."),!1;const q=await e(H,"send_chat",nm(Z,O,W,t)),U=Ps(q);if(U!=null&&U.deduplicated)return m(null),!0;if(Zu(U))return $="parked",h(!0),k(K=>K.map(oe=>oe.id===Z?{...oe,queued:!0}:oe)),m(eo),!0;if((U==null?void 0:U.sent)===!1)throw new Error((U==null?void 0:U.error)||"Send failed");if((U==null?void 0:U.success)===!1)throw new Error((U==null?void 0:U.error)||"Send failed");return h(!1),m(null),!0}catch(H){const q=wd(H);return q.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",q):console.warn("Send blocked/failed",H),x.current=Xu(x.current,z),k(U=>U.filter(K=>K.id!==Z)),m(Go(H)),!1}finally{S.current.delete(Z),T($),k(H=>H.map(q=>q.id===Z?{...q,settled:!0}:q)),f.current=!1,l(!1)}},[t,e,k]),N=c.useCallback(async C=>{if(!t||f.current)return!1;const I=g.current,O=C?I.find(z=>z.id===C):I.find(z=>z.queued===!0);if(!O||!O.queued)return!1;const D=O.content.trim();if(!D)return!1;const F=O.id;f.current=!0,l(!0),m(null);try{const z=ms(t);if(!z)return m("Unable to send message right now."),!1;const Z=await e(z,"send_chat",nm(F,D,O.input,t,{mode:"send_now"})),W=Ps(Z);return(W==null?void 0:W.success)===!1?(m(Go(new Error((W==null?void 0:W.error)||"Send now failed"))),!1):(W==null?void 0:W.queuedWithAgent)===!0?(h(!1),k(T=>T.map($=>$.id===F?{...$,queued:!1}:$)),m(null),!0):Zu(W)?(h(!0),k(T=>T.map($=>$.id===F?{...$,queued:!0}:$)),m(eo),!0):(h(!1),k(T=>T.map($=>$.id===F?{...$,queued:!1}:$)),m(null),!0)}catch(z){return console.warn("Send now blocked/failed",z),m(Go(z)),!1}finally{f.current=!1,l(!1)}},[t,e,k]),A=c.useCallback(async C=>{if(!t||!C)return!1;const I=g.current.find(D=>D.id===C);if(!I)return!1;const O=I.content.trim();if(I.settled&&!I.queued)return k(D=>D.filter(F=>F.id!==C)),!0;if(!I.settled&&await EN(S.current,C)==="not-parked")return k(F=>F.filter(z=>z.id!==C)),!0;try{const D=ms(t);if(!D)return m("Unable to cancel this message right now."),!1;const F=await e(D,"cancel_queued_chat",{messageId:C,message:O,...fs(t)}),z=Ps(F),Z=typeof(z==null?void 0:z.cancelled)=="number"&&z.cancelled===0;return Z&&I.stale===!0?(k(W=>W.filter(T=>T.id!==C)),m(W=>W===eo?null:W),!0):(z==null?void 0:z.success)===!1||Z?(m(MN),!1):(k(W=>W.filter(T=>T.id!==C)),m(W=>W===eo?null:W),!0)}catch(D){return console.warn("Cancel queued send failed",D),m(Go(D)),!1}},[t,e,k]),R=c.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(C){console.error("Relaunch failed",C)}},[t,e]),P=c.useCallback(async C=>{if(t)try{const O=(t.modalButtons||[]).indexOf(C),D=C.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),F=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(D),z=ms(t);if(!z)return;const Z=await e(z,"resolve_action",{button:C,action:F?"approve":"reject",...O>=0&&{buttonIndex:O},...fs(t),...ji(t)}),W=Ps(Z);W.success||s(T=>[...T,{routeId:t.tabKey,text:tm(C,W==null?void 0:W.error),timestamp:Date.now()}])}catch(I){em(I)||console.error("[ModalButton] Error:",I),s(O=>[...O,{routeId:t.tabKey,text:em(I)?tm(C,I):`❌ **${C}** error`,timestamp:Date.now()}])}},[t,e,s]),M=c.useCallback(async()=>{if(!(!t||o)){a(!0);try{await e(t.routeId,AN(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(C){console.error("Focus agent failed",C)}finally{a(!1)}}},[t,o,e]),E=p.length>0?p[p.length-1]:null;return c.useMemo(()=>({isSendingChat:i,sendFeedbackMessage:d,lastSendQueued:u,pendingLocalMessage:E,pendingLocalMessages:p,isFocusingAgent:o,handleSendChat:j,handleSendNowQueued:N,handleCancelQueued:A,retireEchoedPendingMessages:v,handleRelaunch:R,handleModalButton:P,handleFocusAgent:M}),[i,d,u,E,p,o,j,N,A,v,R,P,M])}const LN=10,ON=8e3,$N=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function FN(e){return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s'"`]+/gi,"$1[REDACTED:bearer]").replace(/(Bearer\s+)[A-Za-z0-9._~+/-]{12,}=*/gi,"$1[REDACTED:bearer]").replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{20,}\b/g,"[REDACTED:github-token]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:api-key]").replace(/\b(?:adk|adm)_[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:adhdev-token]").replace(/((?:api[_-]?key|token|secret|password|passwd|client[_-]?secret)\s*[:=]\s*)[^\s,'"`}&]+/gi,"$1[REDACTED:secret]").replace(/([?&](?:api[_-]?key|token|secret|password|client_secret)=)[^&#\s]+/gi,"$1[REDACTED:secret]")}function yl(e,t="",s=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if($N.test(t)&&e.trim())return"[REDACTED:secret-field]";const r=FN(e);return r.length>8e3?`${r.slice(0,8e3)}…[truncated ${r.length-8e3} chars]`:r}if(typeof e!="object")return String(e);if(s>=6)return"[MaxDepth]";if(Array.isArray(e)){const r=e.slice(-20).map(o=>yl(o,t,s+1));return e.length>20?[{truncatedBefore:e.length-20},...r]:r}return Object.fromEntries(Object.entries(e).slice(0,80).map(([r,o])=>[r,yl(o,r,s+1)]))}function Hr(e,t){return Array.isArray(e)?e.slice(-t):[]}function HN(e,t=Date.now()){const s=e&&t-e.firstAt<=ON,r=s?e.count+1:1;return r>=LN?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:r,firstAt:s?e.firstAt:t},shouldCollect:!1}}function zf(e){var r,o;const{activeConv:t}=e,s={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((r=e.chatState.liveMessages)==null?void 0:r.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((o=e.chatState.historyMessages)==null?void 0:o.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Hr(e.chatState.liveMessages??t.messages,10),activeConversationMessagesTail:Hr(t.messages,10),visibleMessagesTail:Hr(e.visibleMessages,5),historyMessagesTail:Hr(e.chatState.historyMessages,5),actionLogsTail:Hr(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chat:{hasLiveSnapshot:!!e.chatState.hasLiveSnapshot,hasMoreHistory:!!e.chatState.hasMoreHistory,historyError:e.chatState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return yl(s)}function Vf(e,t={}){const s=e&&typeof e=="object"?e:{},r=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),o=r==="copied"?"locator copied":r==="manual"?"locator shown for manual copy":"locator copy failed";return s.delivery==="daemon_file"?`Chat debug signal sent${typeof s.bundleId=="string"&&s.bundleId.trim()?` (${s.bundleId})`:""}; saved on daemon, ${o}.`:`Chat debug signal sent; ${o}.`}async function Gf(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(s){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",s)}if(typeof document<"u"&&document.body){let s=null;try{if(s=document.createElement("textarea"),s.value=e,s.setAttribute("readonly","true"),s.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(s),s.focus(),s.select(),document.execCommand("copy"))return"copied"}catch{}finally{s==null||s.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function Yf(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const s=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&s.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&s.push("","warnings:",...t.warnings.map(r=>`- ${String(r)}`)),s.join(`
31
+ `})]})}function ll(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.promptId!="string"||!t.promptId.trim()||typeof t.providerType!="string"||!t.providerType.trim()||!Array.isArray(t.questions)||t.questions.length===0?null:t}function pS(e){var t;return ll(e.activeInteractivePrompt)||ll((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function fS(e){return e.sessionId||e.instanceId||e.id}function bS(e,t){let s;t==null?s={}:typeof t=="string"?s={sessionId:t,includeHidden:!!t.trim()}:s=t;const r=typeof s.sessionId=="string"?s.sessionId.trim():"",o=s.includeHidden===!0;for(const a of e){const i=pS(a);if(!i)continue;const l=fS(a);if(r&&r!==l&&r!==a.id||!o&&a.surfaceHidden===!0)continue;return{daemonId:a.daemonId||a.id.split(":")[0]||a.id,sessionId:l,routeId:a.id,providerType:a.type,title:a.title||a.cliName||a.type,prompt:i}}return null}function ef(e,t){var r;const s={};for(const o of e.questions){const a=t[o.questionId]||{},i=Array.from(new Set((a.selectedLabels||[]).map(d=>d.trim()).filter(Boolean))),l=(r=a.freeformText)==null?void 0:r.trim();s[o.questionId]={selectedLabels:i,...l?{freeformText:l}:{}}}return{promptId:e.promptId,answers:s}}function Un({children:e}){return typeof document>"u"?n.jsx(n.Fragment,{children:e}):Wn.createPortal(e,document.body)}function gS(e,t){const s=r=>{r.key==="Escape"&&(r.stopPropagation(),t())};return e.addEventListener("keydown",s,!0),()=>e.removeEventListener("keydown",s,!0)}const Ou='a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',xS=200;function $u(e){const t={};for(const s of(e==null?void 0:e.prompt.questions)||[])t[s.questionId]={selectedLabels:[],freeformText:""};return t}function Fu(e,t){var s,r;return!!((s=t==null?void 0:t.freeformText)!=null&&s.trim())||(((r=t==null?void 0:t.selectedLabels)==null?void 0:r.length)||0)>0||e.options.length===0&&!!e.allowFreeform}function yS({label:e,description:t,selected:s,multiSelect:r,disabled:o,onClick:a}){return n.jsx("button",{type:"button",disabled:o,role:r?"checkbox":"radio","aria-checked":s,onClick:a,className:`w-full text-left rounded-md border px-3 py-2 transition ${s?"border-accent-primary bg-accent-primary/15 text-text-primary":"border-border-default bg-surface-secondary text-text-secondary hover:bg-surface-secondary hover:text-text-primary"} ${o?"cursor-not-allowed opacity-60":""}`,children:n.jsxs("span",{className:"flex items-start gap-2",children:[n.jsx("span",{className:`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border ${r?"rounded-sm":"rounded-full"} ${s?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-subtle"}`,children:s?r?n.jsx(ui,{size:12}):n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-accent-on-primary"}):null}),n.jsxs("span",{className:"min-w-0",children:[n.jsx("span",{className:"block text-sm font-semibold leading-5",children:e}),t&&n.jsx("span",{className:"mt-0.5 line-clamp-3 block text-xs leading-5 text-text-muted",children:t})]})]})})}function hd({promptSession:e,isSubmitting:t=!1,error:s,onSubmit:r,onCancel:o}){const{t:a}=pe("common"),[i,l]=c.useState(()=>$u(e)),[d,m]=c.useState(!1),u=c.useRef(!1),h=c.useRef(null),p="interactive-prompt-title";c.useEffect(()=>{if(l($u(e)),m(!1),u.current=!1,!(e==null?void 0:e.prompt.promptId))return;const A=setTimeout(()=>{u.current=!0,m(!0)},xS);return()=>clearTimeout(A)},[e==null?void 0:e.prompt.promptId]),c.useEffect(()=>{if(e)return gS(window,o)},[e,o]);const b=e==null?void 0:e.prompt.promptId,f=e==null?void 0:e.sessionId,x=e==null?void 0:e.daemonId;c.useEffect(()=>{if(!b)return;const N=h.current;if(!N)return;const A=()=>Array.from(N.querySelectorAll(Ou)),R=P=>{if(P.key!=="Tab")return;const M=A();if(M.length===0)return;const E=M[0],C=M[M.length-1],I=document.activeElement;P.shiftKey?(I===E||!N.contains(I))&&(P.preventDefault(),C.focus()):(I===C||!N.contains(I))&&(P.preventDefault(),E.focus())};return N.addEventListener("keydown",R),()=>N.removeEventListener("keydown",R)},[b,f,x]),c.useEffect(()=>{if(!b)return;const N=h.current;if(!N)return;const A=document.activeElement;if(A instanceof Node&&N.contains(A))return;(Array.from(N.querySelectorAll(Ou))[0]||N).focus()},[b,f,x]);const g=(e==null?void 0:e.prompt.questions)||[],S=g.length===1,w=c.useMemo(()=>e?e.prompt.questions.every(N=>Fu(N,i[N.questionId])):!1,[e,i]),_=c.useMemo(()=>g.filter(N=>!Fu(N,i[N.questionId])).length,[g,i]);if(!e)return null;const k=(N,A)=>{l(R=>{const P=R[N.questionId]||{selectedLabels:[]},M=P.selectedLabels||[],E=N.multiSelect?M.includes(A)?M.filter(C=>C!==A):[...M,A]:[A];return{...R,[N.questionId]:{...P,selectedLabels:E}}})},v=(N,A)=>{l(R=>({...R,[N]:{...R[N]||{selectedLabels:[]},freeformText:A}}))},y=()=>{!w||t||!u.current||r(i)},j=ef(e.prompt,i);return n.jsx(Un,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50 px-4 pt-[calc(24px+env(safe-area-inset-top,0px))] pb-[calc(24px+env(safe-area-inset-bottom,0px))]",children:n.jsxs("div",{ref:h,role:"dialog","aria-modal":"true","aria-labelledby":p,tabIndex:-1,className:"flex max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-48px)] w-full max-w-2xl flex-col overflow-hidden rounded-lg border border-border-default bg-surface-primary shadow-2xl outline-none",children:[n.jsxs("div",{className:"flex shrink-0 items-start justify-between gap-4 border-b border-border-default px-5 py-4",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-normal text-status-warning",children:[n.jsx(Xt,{size:15})," ",a("interactivePrompt.actionRequired")]}),n.jsx("h2",{id:p,className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("button",{type:"button",onClick:o,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":a("interactivePrompt.cancelAria"),children:n.jsx(Pt,{size:16})})})]}),n.jsxs("div",{className:"interactive-prompt-question-list min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-4",children:[g.map((N,A)=>{var M,E;const R=((M=j.answers[N.questionId])==null?void 0:M.selectedLabels)||[],P=N.multiSelect?a("interactivePrompt.multipleChoice"):a("interactivePrompt.singleChoice");return n.jsxs("section",{className:A>0?"space-y-3 border-t border-border-default pt-5":"space-y-3",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[N.header&&n.jsx("span",{className:"text-xs font-semibold uppercase tracking-normal text-text-muted",children:N.header}),n.jsx("span",{className:"rounded-full border border-border-subtle px-2 py-0.5 text-3xs font-semibold uppercase tracking-normal text-text-muted",children:P})]}),n.jsxs("div",{className:"mt-1 text-sm font-semibold text-text-primary",children:[S?"":`${A+1}. `,N.question]}),N.multiSelect&&N.options.length>0&&n.jsx("div",{className:"mt-0.5 text-xs text-text-muted",children:a("interactivePrompt.selectAllThatApply")})]}),n.jsx("div",{className:"grid gap-2",role:N.multiSelect?"group":"radiogroup","aria-label":N.question,children:N.options.map(C=>n.jsx(yS,{label:C.label,description:C.description||C.preview,selected:R.includes(C.label),multiSelect:N.multiSelect,disabled:t,onClick:()=>k(N,C.label)},C.label))}),N.allowFreeform&&n.jsxs("label",{className:"block",children:[n.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:a("interactivePrompt.other")}),n.jsx("textarea",{value:((E=i[N.questionId])==null?void 0:E.freeformText)||"",disabled:t,onChange:C=>v(N.questionId,C.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-default bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]},N.questionId)}),s&&n.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:s})]}),n.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border-default px-5 pt-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))]",children:[!w&&_>0&&n.jsx("span",{className:"mr-auto text-xs text-text-muted",children:a("interactivePrompt.answersRequired",{count:_})}),n.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:o,disabled:t,children:a("common.cancel")}),n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:y,disabled:!w||t||!d,children:a(t?"interactivePrompt.submitting":"interactivePrompt.submit")})]})]})})})}function tn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var tf=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress"];tn(tf);var vS=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];tn(vS);var wS=["p2p_offer","p2p_ice"];tn(wS);var SS=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];tn(SS);var kS=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","daemon_mesh_command","p2p_offer","p2p_ice"];tn(kS);var jS=["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"];tn(jS);var NS=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],CS=[...tf,...NS];tn(CS);var _S=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];tn(_S);var AS=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];tn(AS);var TS=["p2p_ready","p2p_answer","p2p_ice"];tn(TS);var IS=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];tn(IS);var MS=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];tn(MS);var nf=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];tn(nf);var sf=["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"];tn(sf);[...new Set([...nf,...sf])];var rf=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"],RS={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"},PS=new Set(rf);function ES(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return PS.has(t)?t:RS[t]??null}var DS=["pending","assigned","completed","failed","cancelled"],LS=["completed","failed","cancelled"],OS=["code_change","validation","live_debug_readonly","launch_app","convergence"],$S=["low","normal","high"],FS=["when_idle","interrupt"],of=["completed","blocked","failed"],HS=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function Sr(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Sr(DS);Sr(LS);Sr(OS);Sr($S);Sr(FS);Sr(of);var BS=["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"],WS=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(WS);var US=["mesh_queue","mesh_direct","plain"],KS=["delivered","queued"],qS=["local","p2p"],zS=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],VS=["default","native_source"],GS=["restart","live_holder"],YS=["approval","choice"],QS=["approved","rejected","answered"],JS=["modal_button","auto_approve","prompt_answer"],XS=["genuine","weak"],ZS=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],e0=["completed","aborted"],t0=["alive","unknown","read_failed","dead"],n0=["auth_failed","billing_failed"],s0=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],r0=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],o0=["completed","failed"],a0=["operator_update","refine_terminal","validation_terminal"],i0=["delivered","queued","duplicate"],c0=[...rf,"unknown"],l0=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],d0=["completed","failed","cancelled"],u0=["genuine","weak","tool_report","operator"],m0=["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"],af=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],Gs={t:"id"},Ys={t:"id",optional:!0},as={t:"bool"},Uo={t:"bool",optional:!0},Hu={t:"ms"},h0={t:"ms",optional:!0},Ko={t:"int",optional:!0},Mt=e=>({t:"enum",values:e}),Or=e=>({t:"enum",values:e,optional:!0}),p0={dispatch_accepted:{scope:Mt(US),messageId:Gs,meshId:Ys,nodeId:Ys,providerType:Ys,attemptNo:Ko,dispatchNonce:Ko,consumeProfile:Or(VS),maxTaskRetries:Ko,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:Gs,outcome:Mt(KS),via:Mt(qS)},delivery_refused:{messageId:Gs,reason:Mt(BS)},dispatch_failed:{workerAbsent:as,reason:Mt(zS),refusalCode:Ys},duplicate_dispatch_refusal:{holderSessionId:Gs,holderAttemptId:Ys},session_rebound:{toSessionId:Gs,reason:Mt(GS)},turn_started:{retro:as},suspension:{modal:Mt(YS),modalKey:Ys},suspension_resolved:{resolution:Mt(QS),via:Mt(JS)},turn_end:{strength:Mt(XS),afterFinalizationTimeout:Uo,hollow:Uo,summary:{t:"summary_ref",optional:!0},blockReason:Or(ZS),releasedByHardCap:Uo,nativeOutcome:Or(e0),live:{t:"live",optional:!0},reportExpected:Uo},transcript_final:{selfAttributing:as,nativeRead:as,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:h0},transcript_activity:{newestActivityAt:Hu},no_progress:{stalledMs:Hu,observedStatus:Mt(c0),finalAssistantPresent:as},liveness:{result:Mt(t0)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:Or(n0)},session_error:{reason:Mt(s0)},worker_report:{outcome:Mt(of),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:as,branchState:Or(HS),touchedFileCount:Ko},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:as,commitsSinceDispatch:{t:"int"},attributable:as},cancel:{reason:Mt(r0)},operator_status:{status:Mt(o0),reason:Mt(a0)},coordinator_ack:{notify:Mt(af),outcome:Mt(i0)},hold_expired:{holdId:Gs,reason:Mt(l0)}},f0=Object.keys(p0);function _o(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}_o(f0);_o(m0);_o(af);_o(d0);_o(u0);function es(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var b0=["applied","recorded","rejected"];es(b0);var g0=["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(g0);var x0=["completed","failed"];es(x0);var y0=["operator_update","refine_terminal","validation_terminal"];es(y0);var v0=["own","fleet"];es(v0);var w0=["active","paused","completed","abandoned"];es(w0);var S0=["provider_quirk","pattern_to_avoid","recovery_lesson"];es(S0);var k0=["coordinator","unknown"];es(k0);var j0=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];es(j0);var N0=["turn_observe","mesh_record","turn_cancel","operator_status","turn_query","mesh_index_query","mission_upsert","mission_query","note_upsert","note_forget","tool_call_record","ledger_query","mission_list_query","record_local","queue_query","queue_enqueue","queue_enqueue_batch","queue_cancel","queue_requeue","direct_dispatch_record","active_work_query","recovery_context_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];es(N0);function C0(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Jt(e,t){return C0(t==null?void 0:t.activeModal)?"waiting_approval":ES(e)??"idle"}function dl(e){return Jt(e)==="generating"}function Bu(e,t){return Jt(e,t)==="waiting_approval"}function _0(e){return(e==null?void 0:e.surfaceHidden)===!0}function A0(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function ws(e){const t=e.connectionState==="failed"||e.connectionState==="closed",s=e.connectionState==="connecting"||e.connectionState==="new",r=ci(e.status),o=Jt(e.status),a=o==="waiting_approval",i=o==="waiting_choice",l=xy(o);return{isReconnecting:t,isConnecting:s,isGenerating:r,isWaiting:a,isWaitingChoice:i,isErrored:l}}function T0(e){const t=!e.hasLiveSnapshot&&e.visibleMessageCount===0,{isGenerating:s}=ws(e),r=s&&(!t||Jt(e.status)==="generating");return{awaitingFirstView:t,showWorkingIndicator:r}}function Bs(e){return ws(e).isGenerating}function I0(e){let t=0;for(const s of e)Bs(s)&&t++;return t}function Wu(e){let t=0;return e.unread!==void 0&&(t+=1),e.lastSeenAt!==void 0&&(t+=1),e.lastUpdated!==void 0&&(t+=1),e.inboxBucket!==void 0&&(t+=1),e.surfaceHidden!==void 0&&(t+=1),e.muted!==void 0&&(t+=1),e.completionMarker!==void 0&&(t+=1),e.seenCompletionMarker!==void 0&&(t+=1),t}function M0(e,t){const s=e.lastUpdated||0,r=t.lastUpdated||0;if(r!==s)return r>s;const o=Wu(e),a=Wu(t);return a!==o?a>o:!1}function Uu(e,t,s){return e===void 0?t:t===void 0?e:s?t:e}function cf(e){const t=new Map,s=new Map,r=(o,a)=>{if(!o)return;const i=s.get(o),l=t.get(o),d=(a.lastUpdated||0)>((i==null?void 0:i.lastUpdated)||0),m=Uu(l==null?void 0:l.surfaceHidden,typeof a.surfaceHidden=="boolean"?a.surfaceHidden:void 0,d),u=Uu(l==null?void 0:l.muted,typeof a.muted=="boolean"?a.muted:void 0,d);if(i&&!M0(i,a)){l&&t.set(o,{...l,surfaceHidden:m,muted:u});return}s.set(o,a),t.set(o,{sessionId:o,...A0(a),surfaceHidden:m,muted:u})};for(const o of e)if(o.type!=="adhdev-daemon"){r(o.sessionId,o);for(const a of o.childSessions||[])r(a.id,a)}return t}function xs(e,t){if(e.sessionId){const s=t.get(e.sessionId);if(s)return s}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:void 0,muted:void 0,completionMarker:"",seenCompletionMarker:""}}function gi(e,t,s){const r=xs(e,t),o=ws(e),a=o.isReconnecting,i=o.isConnecting,l=o.isGenerating,d=o.isWaiting,m=o.isWaitingChoice,u=r.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d||m,h=r.inboxBucket==="working"||l,b=!!(r.inboxBucket==="task_complete"&&r.unread&&!(s!=null&&s.hideOpenTaskCompleteUnread&&(s!=null&&s.isOpenConversation)));return{unread:b,requiresAction:u,isWorking:h,isReconnecting:a,isConnecting:i,isGenerating:l,isWaiting:d,inboxBucket:u?"needs_attention":h?"working":b?"task_complete":"idle"}}function R0(e,t,s){return gi(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:s==null?void 0:s.isOpenConversation}).unread}function P0(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function E0(e){const t=(e==null?void 0:e.result)??e;return typeof(t==null?void 0:t.error)=="string"?t.error:"Interactive prompt response failed"}async function D0(e,t,s){const r=await s(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let o=`HTTP ${r.status}`;try{const a=await r.json();typeof(a==null?void 0:a.error)=="string"&&(o=a.error)}catch{}throw new Error(o)}}async function L0({promptSession:e,response:t,useP2PCommand:s,sendCommand:r,fetchImpl:o=fetch}){if(s){const a=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!P0(a))throw new Error(E0(a));return}await D0(e.sessionId,t,o)}let ul=null;const ml=new Set;function O0(e){return ml.add(e),()=>{ml.delete(e)}}function Ku(){return ul}function qo(e){if(ul!==e){ul=e;for(const t of ml)t()}}function xi(e,t){const{t:s}=pe("common"),{ides:r,isP2PActive:o,p2pStates:a}=xn(),{sendCommand:i}=xt(),l=c.useSyncExternalStore(O0,Ku,Ku),[d,m]=c.useState(!1),[u,h]=c.useState(null),p=c.useRef(!1),b=(t==null?void 0:t.includeHidden)===!0,f=c.useMemo(()=>bS(r,{sessionId:e,includeHidden:b}),[r,e,b]),x=!!f,g=c.useMemo(()=>f?f.prompt.promptId===l?null:f:null,[l,f]),S=(f==null?void 0:f.prompt.promptId)??null;c.useEffect(()=>{h(null)},[S]);const w=c.useCallback(async v=>{if(!g||p.current)return;p.current=!0;const y=ef(g.prompt,v);m(!0),h(null);try{const j=(a==null?void 0:a[g.daemonId])==="connected"||o===!0;await L0({promptSession:g,response:y,useP2PCommand:j,sendCommand:i}),qo(g.prompt.promptId)}catch(j){let N=j instanceof Error?j.message:String(j);throw N.includes(by)?(qo(g.prompt.promptId),h(s("interactivePrompt.errorReviewUnconfirmed",{defaultValue:"The answer keys reached the terminal, but the question is still on screen — the answer may not have been submitted. Check the terminal: if it was not submitted, answer there; resending from here could submit it twice."})),j):(N.includes(fy)&&(N=s("interactivePrompt.errorReviewPageNotFocused",{defaultValue:"The terminal is showing a different screen, so the answer was not submitted — check the terminal screen or close this and try again."})),h(N),j)}finally{m(!1),p.current=!1}},[o,a,g,i]),_=c.useCallback(()=>{g&&qo(g.prompt.promptId)},[g]),k=c.useCallback(()=>{if(qo(null),!f){h(s("interactivePrompt.errorUnavailable",{defaultValue:"Could not load the question — answer it in the terminal view instead."}));return}h(null)},[f,s]);return{promptSession:g,hasActivePrompt:x,responseError:u,isSubmitting:d,submit:w,cancel:_,reopen:k}}function lf(e){return e.sessionId??e.routeId}const sc=e=>e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*\(\s*\b(?:Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)\b(?:\s*\+\s*\w+)*\s*\)/gi,"").replace(/\s*\b(?:Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)\b(?:\s*\+\s*\w+)*/gi,"").trim(),$0=12e3;function F0(e){return/^always\b|\balways allow\b|\bdon'?t ask again\b|\ballow all\b|^yes,? and allow\b/.test(e)?"always":/^(run|approve|accept|yes|allow)/.test(e)?"primary":/^(reject|deny|delete|remove|abort|no)\b/.test(e)?"danger":"neutral"}function df({activeConv:e,onModalButton:t}){const{t:s}=pe(),[r,o]=c.useState(null),{hasActivePrompt:a,promptSession:i,reopen:l}=xi(lf(e));c.useEffect(()=>{o(null)},[e.modalMessage,e.status,e.connectionState]),c.useEffect(()=>{if(!r)return;const h=setTimeout(()=>o(null),$0);return()=>clearTimeout(h)},[r]);const d=ws(e);if(!d.isWaiting&&!d.isWaitingChoice||!e.modalButtons)return null;const m=h=>{r||(o(h),t(h))},u=()=>n.jsx("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:n.jsx("div",{className:"flex items-center gap-2",children:n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(Xt,{size:14}),s("approval.questionUnavailable",{defaultValue:"Question waiting — could not load it here. Answer it in the terminal view."})]})})});return a&&!i?u():a?n.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&n.jsx("div",{className:"text-2xs opacity-85 mb-1.5 line-clamp-3 max-w-full whitespace-pre-wrap break-words",title:e.modalMessage,children:e.modalMessage}),n.jsxs("div",{className:"flex justify-between items-center gap-2",children:[n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(Xt,{size:14})," ",s("approval.questionPending",{defaultValue:"Question waiting"})]}),n.jsx("button",{onClick:l,className:"btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold cursor-pointer whitespace-nowrap shrink-0",style:{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"},children:s("approval.answerQuestion",{defaultValue:"Answer the question"})})]})]}):d.isWaitingChoice?u():n.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&n.jsx("div",{className:"text-2xs opacity-85 mb-1.5 line-clamp-4 max-w-full whitespace-pre-wrap break-words",title:e.modalMessage,children:e.modalMessage}),n.jsxs("div",{className:"flex justify-between items-center",children:[n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(Xt,{size:14})," ",s(r?"approval.processing":"approval.actionRequired")]}),n.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((h,p)=>{const b=sc(h).toLowerCase(),f=F0(b),x=f==="always",g=f==="primary",S=f==="danger",w=r===h,_=r!==null;return n.jsx("button",{onClick:()=>m(h),disabled:_,title:x?s("approval.alwaysAllowWarning"):void 0,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${g?"font-extrabold":S?"bg-red-500/30 text-white font-semibold":x?"text-white/90 font-semibold":"text-white font-semibold"} ${_&&!w?"opacity-40":"opacity-100"} ${_?"cursor-not-allowed":"cursor-pointer"}`,style:g?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:x?{background:"transparent",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 55%, transparent)"}:S?void 0:{background:"color-mix(in srgb, black 18%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 35%, transparent)"},children:w?n.jsx(mr,{size:12}):x?n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Xt,{size:11}),sc(h)]}):sc(h)},p)})})]})]})}const pd="adhdev_controls_bar_visible",hl="adhdev:controlsbarvisibilitychange";function rc(e){if(!e)return!1;try{return e.getItem(pd)==="1"}catch{return!1}}function H0(e,t){if(t)try{t.setItem(pd,e?"1":"0")}catch{}}function B0(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(hl,{detail:{visible:e}}))}function fd(){const[e,t]=c.useState(()=>typeof window>"u"?!1:rc(window.localStorage)),s=c.useRef(e),r=c.useCallback((i,l=!0)=>{s.current=i,t(i),typeof window<"u"&&H0(i,window.localStorage),l&&B0(i)},[]);c.useEffect(()=>{const i=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:rc(window.localStorage);s.current=u,t(u)},l=d=>{if(d.key!==pd)return;const m=rc(window.localStorage);s.current=m,t(m)};return window.addEventListener(hl,i),window.addEventListener("storage",l),()=>{window.removeEventListener(hl,i),window.removeEventListener("storage",l)}},[]);const o=c.useCallback(i=>{r(i)},[r]),a=c.useCallback(()=>{r(!s.current)},[r]);return{isVisible:e,setVisibility:o,toggleVisibility:a}}const uf=["en","ko","ja","zh-CN","es"],Es="en",ks=[{code:"en",label:"English"},{code:"ko",label:"한국어"},{code:"ja",label:"日本語"},{code:"zh-CN",label:"中文(简体)"},{code:"es",label:"Español"}];function Rs(e){return typeof e=="string"&&uf.includes(e)}function W0(e){if(!e)return Es;const t=e.trim().toLowerCase();if(!t)return Es;if(t==="zh"||t.startsWith("zh-")||t.startsWith("zh_"))return"zh-CN";const s=t.split(/[-_]/)[0];return s==="en"?"en":s==="ko"?"ko":s==="ja"?"ja":s==="es"?"es":Es}const U0={runFailed:"Couldn't run {{label}}",updateFailed:"Couldn't update {{label}}",loadOptionsFailed:"Couldn't load {{label}} options"},K0={unknown:"Unknown",starting:"Starting",stopped:"Stopped",failed:"Failed",idle:"Idle",generating:"Working",awaitingApproval:"Needs approval"},q0={label:"Language",select:"Select language"},z0={copy:"Copy",no:"No",yes:"Yes",diagnostics:"Diagnostics",done:"Done",edit:"Edit",copied:"Copied",copyId:"Copy ID",technicalDetails:"Technical details",saved:"Saved",refresh:"Refresh",moreInfo:"More info",closeDialog:"Close dialog",noRecords:"No records found.",close:"Close",back:"Back",cancel:"Cancel",confirm:"Confirm",confirmTitle:"Are you sure?"},V0={loadingShort:"Loading…",loadingDashboard:"Loading your dashboard...",machinesConnectedCount:"{{connected}}/{{total}} machines connected",disconnected:"Disconnected",connected:"Connected",connectedToDashboard:"Connected to dashboard",networkOffline:"Network offline",reconnecting:"Reconnecting",sessionExpired:"Session expired.",logInAgain:"Log in again",connectionFailed:"Connection failed — refresh the page or try again shortly.",reconnectNow:"Reconnect now"},G0={details:"Details",label:{success:"Done",warning:"Attention",info:"Update"},dismiss:"Dismiss"},Y0={actionNeeded:"Action needed",taskComplete:"Task complete",markRead:"Mark read",markUnread:"Mark unread",delete:"Delete"},Q0={browser:{error:"Stopped with an error",finished:"Finished",approvalWithMessage:"Needs approval: {{message}}",approval:"Needs approval",questionWithMessage:"Question: {{message}}",question:"Waiting for your answer"},taskCompleted:"{{label}} agent task completed",taskCompletedWithDuration:"{{label}} agent task completed ({{duration}})",approvalNeeded:"{{label}} approval needed",questionNeeded:"{{label}} question needs an answer",noProgress:"{{label}} agent shows no progress",noProgressWithDuration:"{{label}} agent shows no progress ({{minutes}}m)",noProgressTitle:"{{label}} — No Progress",noProgressBody:"Agent has shown no progress for over {{duration}}",viewRequest:"{{requester}} wants to view your session",viewRequestTitle:"View Request",viewRequestApproved:"View request approved",viewRequestDeclined:"{{target}} declined your view request",someoneRequester:"A team member",someoneTarget:"Team member"},J0={header:{moreActions:"More actions",title:"Dashboard",guide:"Dashboard guide",guideOpen:"Open dashboard guide",guideShort:"Guide",openGitStatus:"Open git status",meshGraph:"Mesh graph",stopCliProcess:"Stop CLI process",chatHistory:"Chat History",remoteControl:"Remote Control",generating:"generating",activityInbox:"Notifications"},hidden:{title:"Hidden tabs",dragHint:"Drag a tab here to hide it.",resetPanels:"Reset panels",restoreAll:"Restore all",hideCurrentTab:"Hide current tab",empty:"No hidden tabs.",resetPanelsConfirm:"Move every floating or popout panel back into the main dashboard grid?"},inbox:{unread:"Unread",read:"Read",empty:"No pending activity."},metaChips:{queuePending:"{{count}} waiting",queueTooltip:"Queue: {{pending}} waiting, {{assigned}} assigned, {{completed}} completed, {{failed}} failed"},meshRole:{coordinator:"Coordinator",worker:"Worker",coordinatorFor:"Coordinator for {{mesh}}",workerFor:"Worker for {{mesh}}",coordinatorUnknownMesh:"Mesh coordinator",workerUnknownMesh:"Mesh worker",openMeshGraph:"Open mesh graph"},versionBanner:{restarting:"restarting",upgrading:"updating…",unknownVersion:"unknown",updateAvailable:"Update available",required:"required",retry:"retry"},remoteDialog:{liveRemoteView:"Live remote view",remoteUnavailable:"Remote view unavailable",remoteOnly:"Remote only",splitView:"Split view",remoteFallback:"Remote",history:"History"},guide:{title:"Dashboard guide",subtitle:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune.",close:"Close dashboard guide",tabs:{overview:"Overview",quickstart:"Quick start",shortcuts:"Shortcuts"},overview:{whatLivesWhere:{title:"What lives where",tabsLabel:"Tabs:",tabsText:"active sessions across IDE and CLI agents.",hiddenLabel:"Hidden tabs:",hiddenText:"stash sessions you do not want in the main strip but still want to keep around.",inboxLabel:"Activity inbox:",inboxText:"sessions waiting for approval or finished tasks you have not reviewed yet.",cliToggleLabel:"CLI view toggle:",cliToggleText:"switch a PTY session between terminal and chat rendering without relaunching it."},usefulFlows:{title:"Useful flows",reviewLabel:"Review notifications:",reviewText:"open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane.",clutterLabel:"Reduce clutter:",clutterText:"hide less important sessions instead of closing them, then restore from hidden tabs when needed.",splitLabel:"Split work:",splitText:"keep one pane active for input and let secondary panes stay read-only until you focus them.",detachedLabel:"Detached views:",detachedText:"float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor.",dockingLabel:"Docking:",dockingText:"use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard.",perTabLabel:"Per-tab shortcuts:",perTabText:"right-click a Dockview tab to assign a direct shortcut for that specific session.",approvalLabel:"Approval buttons:",approvalText:"use {{keys}} for the first three visible approval actions on the active session."}},quickstart:{desktop:{title:"Desktop quick start",step1:"Start from the machine or workspace flow first. Pick or save a workspace before launching CLI sessions.",step2:"Keep the main strip focused on active work and push overflow into Hidden tabs.",step3:"Use the inbox for approval-required or completed sessions instead of scanning every tab.",step4:"Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."},mobile:{title:"Mobile quick start",step1:"Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions.",step2:"Start from the machine screen, choose a workspace, then launch IDE or CLI from there.",step3:"Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."}},shortcuts:{sections:{all:"All",workspace:"Workspace",panes:"Panes",approvals:"Approvals"},disableAll:"Disable all",resetToDefaults:"Reset to defaults",default:"Default:",listening:"Listening...",set:"Set",disable:"Disable",off:"Off",footer:"Use modifier shortcuts like {{keys}}, or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs.",resetConfirm:"Reset all dashboard shortcuts back to their default values?",setListening:"Listening"}},shortcutDefs:{openShortcutHelp:{label:"Open shortcuts",description:"Show the keyboard shortcuts panel."},openNewSession:{label:"New session",description:"Open the new session launcher."},hideCurrentTab:{label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs."},toggleHiddenTabs:{label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover."},openHistoryForActiveTab:{label:"Open history",description:"Open history for the active session."},openRemoteForActiveTab:{label:"Open remote",description:"Open remote control for the active session when available."},floatActiveTab:{label:"Float active tab",description:"Move the active tab into a floating panel."},popoutActiveTab:{label:"Open active tab in new window",description:"Move the active tab into a detached popout window."},dockActiveTab:{label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window."},splitActiveTabRight:{label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it."},splitActiveTabDown:{label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it."},focusLeftPane:{label:"Focus left pane",description:"Move focus to the pane on the left."},focusRightPane:{label:"Focus right pane",description:"Move focus to the pane on the right."},focusUpPane:{label:"Focus upper pane",description:"Move focus to the pane above."},focusDownPane:{label:"Focus lower pane",description:"Move focus to the pane below."},moveActiveTabToLeftPane:{label:"Move active tab left",description:"Move the active tab into the pane on the left."},moveActiveTabToRightPane:{label:"Move active tab right",description:"Move the active tab into the pane on the right."},moveActiveTabToUpPane:{label:"Move active tab up",description:"Move the active tab into the pane above."},moveActiveTabToDownPane:{label:"Move active tab down",description:"Move the active tab into the pane below."},triggerPrimaryApprovalAction:{label:"Approval action 1",description:"Press the first approval/action button for the active session."},triggerSecondaryApprovalAction:{label:"Approval action 2",description:"Press the second approval/action button for the active session."},triggerTertiaryApprovalAction:{label:"Approval action 3",description:"Press the third approval/action button for the active session."},setActiveTabShortcut:{label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab."},selectPreviousGroupTab:{label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group."},selectNextGroupTab:{label:"Next tab in group",description:"Move to the next tab inside the active Dockview group."},toggleCliView:{label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view."}}},X0={stopProcess:"Stop CLI process",title:"Stop {{agent}}?",gracefulDescription:"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.",forceOnlyDescription:"This provider does not support graceful stop. Force Stop will end the runtime immediately.",stop:"Stop",forceStop:"Force Stop"},Z0={processing:"PROCESSING...",actionRequired:"ACTION REQUIRED",alwaysAllowWarning:"Grants this permission permanently — future runs will not ask again",questionPending:"QUESTION WAITING",answerQuestion:"Answer the question"},ek={loading:"Loading…",launchModelChanged:"{{from}} → {{to}} (changed)",launchModelSource:{user:"chosen",remembered:"remembered",mesh_slot:"mesh slot",task_override:"task override",provider_default:"default"}},tk={noMeshesShort:"No meshes on this machine",noProvidersShort:"No agents available",advancedOptions:"Advanced options",agent:"Agent",defaultResolvesTo:"Default resolves to {{model}}",title:"Start session",close:"Close new session dialog",detectedLocally:"Detected locally",availableToOpen:"Available to open",machine:"Machine",selectMachine:"Select machine {{name}}",workspace:"Workspace",browse:"Browse…",launchTargetType:"Launch target type",modeWorkspace:"Workspace",modeWorkspaceDesc:"Normal session",modeMesh:"Mesh",modeMeshDesc:"Coordinator session",homeDirectory:"Home directory",customFolder:"Custom folder…",launchWithoutWorkspace:"Launch without a workspace.",selectWorkspaceFolder:"Select a workspace folder.",selectFolder:"Select folder",saving:"Saving…",saveWorkspace:"Save workspace",loadingMeshes:"Loading meshes…",noMeshes:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker.",mesh:"Mesh",repoMesh:"Repo mesh",nodeCount_one:"{{count}} node",nodeCount_other:"{{count}} nodes",coordinatorWorkspace:"Coordinator workspace: {{path}}",noProviders:"Nothing usable on the selected machine. If an agent is installed outside the default location, set its executable path in Machine → Providers.",startupArguments:"Startup arguments",optionalFlags:"Optional flags...",autoApproveMode:"Auto-approve mode",autoApproveModeDescription:"Choose how this session handles approval prompts.",autoApproveLegacy:"Auto approve",autoApproveLegacyDescription:"Automatically accept supported approval prompts for this session.",autoApproveRisk:{safe:"Safe",caution:"Caution",dangerous:"Dangerous"},dangerousModeTitle:"Confirm dangerous auto-approve mode",dangerousModeFallbackWarning:"This mode can bypass approval or sandbox protections. Use it only in a trusted workspace.",dangerousModeRisk:"Risk",dangerousModeLaunchArgs:"Injected launch arguments",dangerousModeConfirm:"Use dangerous mode",modelAndThinking:"Model & thinking (optional)",model:"Model",providerDefault:"(provider default)",custom:"Custom…",typeModelName:"Type a model name",backToModelList:"← Back to model list",thinkingLevel:"Thinking level",selectWorkspaceTitle:"Select workspace",start:"Start",starting:"Starting…",startMeshCoordinator:"Start mesh coordinator",startingCoordinator:"Starting coordinator…",startIde:"Start IDE",startingIde:"Starting IDE…",startFresh:"Start fresh",startingFresh:"Starting fresh…",resumeSavedHistory:"Resume saved history",resumingSavedHistory:"Resuming saved history…",errorLoadMeshes:"Could not load meshes",errorLoadFolder:"Could not load folder",errorLoadSavedSessions:"Could not load saved sessions",errorSaveWorkspace:"Could not save workspace",workspaceSaved:"Workspace saved. It will appear in the list once the machine state refreshes.",errorManualMcpSetup:"Manual MCP setup required before this provider can act as mesh coordinator.",errorStartMeshCoordinator:"Could not start mesh coordinator",errorStartSession:"Could not start session",errorResumeSession:"Could not resume session",errorWorkspaceContextRequired:"Choose a workspace — a directory, a saved/default workspace, or your home directory — before launching.",defaultWorkspace:"Default workspace"},nk={undo:"Undo",hiddenToast:"Hid {{title}}",moreActionsFor:"More actions for {{title}}",loading:"Loading...",loadingSubtitle:"Fetching your machines and sessions.",machines:"Machines",chats:"Chats",networkOffline:"Network offline",sessionExpired:"Session expired",reconnecting:"Reconnecting",waitingForNetwork:"Waiting for network…",pleaseLogInAgain:"Please log in again.",restoringConnection:"Restoring the server connection…",waitingForDaemon:"Waiting for your daemon",connectYourMachines:"Connect your machines",waitingForDaemonSubtitle:"Start the ADHDev daemon to connect.",connectYourMachinesSubtitle:"Install ADHDev on a machine and sign in.",newCount:"{{count}} new",chatCount_one:"{{count}} chat",chatCount_other:"{{count}} chats",idle:"Idle",unreadSuffix:" · {{count}} unread",noActiveChats:"No active chats",needsAttention:"Needs attention",taskComplete:"Task complete",workingNow:"Working now",earlier:"Earlier",connecting:"Connecting…",connectingSubtitle:"Waiting for server connection before loading conversations.",noMachinesConnected:"No machines connected",noMachinesSubtitle:"Connect a machine from the Machines tab.",noConversations:"No conversations yet",allCaughtUp:"All caught up.",hiddenTabs:"Hidden tabs",collapsedCount_one:"{{count}} collapsed conversation",collapsedCount_other:"{{count}} collapsed conversations",generatingCount:"{{count}} generating",collapsedGeneratingSuffix:" · {{count}} generating",restoreAll:"Restore all",hide:"Hide",reconnectingItem:"Reconnecting…",connectingItem:"Connecting…",actionNeeded:"Action needed",done:"Done",openMeshGraphFor:"Open mesh graph for {{title}}",openLiveMeshGraph:"Open live repo mesh graph",stopSessionTitle:"Stop session (terminates the agent)"},sk={hint:{daemon:{followUp:"Needs follow-up",merged:"Merged",notMergeable:"Can't merge yet — changes or conflicts",cleanup:"Merged — worktree can be cleaned up",needsMerge:"Pushed — ready to merge",blockedReview:"Needs review before merging"},anchorEmpty:"No workspace on the default branch",anchorWorkspaces:"{{count}} workspace(s) on {{branch}}",anchorNeedsFollowUp:"{{count}} on {{branch}} need follow-up",submoduleSynced:"{{path}} is in sync",submoduleChanged:"{{path}} has local changes",submoduleOutOfSync:"{{path}} is out of sync with its parent",gitAgeUnknown:"Git status age unknown",staleGit:"Git status is over 5 min old",missingSubmodule:"Submodule not reported: {{paths}}",noGitYet:"No git status received yet",noGitYetOnline:"Online — git status not received yet",waitingForGit:"Waiting for git status…",nodeError:"Node reported an error",upstreamUnverified:"Upstream not verified yet",noUpstream:"Push {{branch}} to set its upstream",mergeConflicts:"Resolve merge conflicts",detachedHead:"Detached HEAD — check out a branch",notGitRepo:"Not a git repository",noGitStatus:"No git status yet"},sessionCleanup:{stopAndDeleteHint:"Stop matching sessions, then remove their chat records.",stopAndDelete:"Stop and delete sessions",deleteStoppedHint:"Clear finished or stopped chats without stopping running sessions.",deleteStopped:"Delete stopped sessions only",stopHint:"Stop running session processes but keep their chat records.",stop:"Stop running sessions only",preserveHint:"Keep finished chat history and leave running sessions alone.",preserve:"Keep history and running sessions"},nodeHealth:{failed:"Failed",completed:"Completed",assigned:"Assigned",pending:"Pending",enabled:"Enabled",unknown:"Connecting…",wrongBranch:"Other branch",degradedHint:"The connection to this machine is down or timed out — often temporary. Wait a moment or reconnect the machine.",degraded:"Unreachable",offline:"Offline",dirty:"Uncommitted changes",online:"Online"},activity:{noKeyEvents:"No recent key events",showKey:"Show key events only",showAll:"Show all activity",nodeChanged:"Machine joined or left",worktreeCreated:"Worktree created",nodeJoined:"Node joined",nodeRemoved:"Node removed",sessionStarted:"Agent started",needsInput:"Needs your input",taskFailed:"Task failed",taskFinished:"Task finished",taskStarted:"Task started"},drift:{clean:"Clean",conflicts:"conflicts",submoduleOutOfSync_other:"{{count}} submodules out of sync",submoduleOutOfSync_one:"{{count}} submodule out of sync",submoduleChanged_other:"{{count}} submodules changed",submoduleChanged_one:"{{count}} submodule changed",changed_other:"{{count}} changed",changed_one:"{{count}} changed",upstreamUnverified:"upstream unverified",noGit:"No git info",probePending:"Checking git…"},graph:{slowLinkChip:"Slow link",observationUnreachableChip:"Unreachable",observationStaleChip:"Stale",remoteBadge:"remote",activeSessionAria:"active session",observationAsOf:"as of {{age}} ago",observationRefreshing:"as of {{age}} ago · refreshing",observationFetching:"fetching state…",observationUnreachable:"unreachable · last known {{age}} ago",observationUnreachableNoState:"unreachable · no state yet"},statusTab:{v2ScopeHint:"Pending events by scope",providerSkewHint:"Providers running different versions on different nodes",providerSkew:"{{count}} provider version mismatch",v2RatioHint:"Share of pending coordinator events in the current message format",daemonBuildHint:"Exact daemon build (version@commit) running on this node",quotaFailedHint:"This machine couldn't read this provider's usage",quotaOkNoWindowHint:"Read successfully — this provider has no percentage limit to show",nodeCountHint:"Mesh nodes (workspaces/worktrees) on this machine — they share one plan quota",nodeCount_other:"{{count}} nodes",nodeCount_one:"{{count}} node",daemonVersionHint:"Daemon version running on this machine",blockedReasonHint:"Why this node can't take a new code-changing task right now",providerCapHint:"Active tasks per provider on this node vs its declared limit",priorityHint:"Scheduling preference (higher is preferred)",priority:"priority {{value}}",loadHint:"Active tasks assigned to this node",load:"load {{count}}",readonlyCapHint:"Active read-only investigation tasks vs their limit (2× the write limit)",readonlyCap:"read-only {{active}}/{{max}}",writeCapHint:"Active tasks that change code vs the mesh-wide parallel limit",writeCap:"write {{active}}/{{max}}"},manualSetup:{restartHint:"Start a fresh CLI session after editing config.",configPath:"Config path:",format:"Format:",server:"Server:",titleFor:"Manual MCP setup required for {{provider}}",title:"Manual MCP setup required"},help:{toggleAria:"Mesh help",toggleTitle:"Mesh concept help",regionAria:"Mesh concept help",kicker:"Help",title:"Mesh concepts at a glance",close:"Close help",sections:{node:{term:"Node",summary:"A workspace participating in the mesh — a repo checkout or an isolated git worktree.",details:["Base node vs worktree clone node — a clone isolates parallel work without conflicts.","Shows health (online/offline) alongside git state (branch · ahead/behind · dirty).","Multiple nodes can share the same daemon."]},p2p:{term:"P2P connection",summary:"How the selected coordinator reaches each remote node over WebRTC.",details:["direct — a direct host/STUN path; lowest latency.","relay — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed — no live P2P link from the coordinator right now.","P2P connectivity is shown as transport and RTT chips on each node card (and in the node detail panel), not as a graph edge."]},session:{term:"Session",summary:"An agent CLI session running on a node.",details:["status = idle / generating / waiting_approval.","Distinguishes coordinator sessions (which dispatch and collect work) from delegated worker sessions (which do the work)."]},task:{term:"Task",summary:"A single unit of work handled by the queue-based pull model.",details:["States: pending → assigned → completed / failed / cancelled.","Idle nodes claim from the queue automatically; direct dispatch targets a specific session."]},mission:{term:"Mission",summary:"A multi-task batch aimed at one goal, and the durable record of that effort.",details:["States: active / paused / completed / abandoned.","Progress is derived from the states of its member tasks."]},refinery:{term:"Refinery (refine)",summary:"The process of safely converging and merging a worktree branch into the base.",details:["Config-driven (.adhdev/refine.*) — guarded by a patch-equivalence preflight and a no-op guard.","ff-only by principle; no force-push.","If a submodule commit is unreachable from origin it must be published → classified as blocked_review."]},completion:{term:"Completion model",summary:"Completion of delegated work is persisted to the queue (pending-events).",details:["The coordinator learns of completion via periodic polling or events.","Because it is persisted to the queue, completion signals are never lost."]},convergence:{term:"Branch convergence states",summary:"After worktree work, each branch is classified into exactly one final state.",details:["merged_to_main — merged into the base.","pushed_feature_branch_needs_merge — pushed, awaiting merge.","blocked_review — held back by review/reachability issues.","cleanup_candidate — ready to clean up.","not_mergeable — cannot be merged."]},blueprint:{term:"Blueprint",summary:"The plan view: live queue work and its task dependencies on one canvas.",details:["One axis — dependency depth, left to right. Root tasks are ordered newest first.","Cards carry their own time, so position never has to encode it.","Finished dependency chains fold away so live work stays in view."]},routingPreview:{term:"Routing preview",summary:"A read-only forecast of where a hypothetical task would land.",details:["Shown per difficulty; a task pinned to a node gets its own pinned preview (📌).","It is a prediction, not the owner — a card that already ran shows its real node below."]},worktree:{term:"Worktree node",summary:"A node backed by a git worktree rather than the main checkout.",details:["Labelled by its branch (⎇). Lets several tasks run on one machine without sharing a branch.","Orphan worktrees are reported as cleanup candidates and are never deleted automatically."]}}},approvals:{title:"PENDING APPROVALS",empty:"No sessions are awaiting an approval decision.",sessionFallback:"session {{id}}",approve:"Approve",reject:"Reject",waitingFor:"Waiting for {{duration}}"},difficulty:{easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"},panel:{outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusCoordinator:"coordinator",statusWorker:"worker",upstreamUnverified:"unverified",needsFollowUp:"needs follow-up",refined:"refined",tooltipLocalChanges:"Local changes",tooltipHasConflicts:"Has conflicts",tooltipOutOfSync:"Out of sync",tooltipNeedsFollowUp:"Needs follow-up",tooltipUpstreamUnverified:"Upstream unverified",tooltipRefineCompleted:"refine completed",tooltipRefinedBranch:"refined {{branch}}",tooltipP2PRelayed:"P2P link relayed through TURN (slower path)",tooltipPrefixStatus:"Status:",tooltipPrefixBranch:"Branch:",tooltipPrefixNote:"Note:",defaultBranch:"default branch",submoduleSynced:"synced",moreChats_one:"+{{count}} more chat",moreChats_other:"+{{count}} more chats",remote:"remote",chats_one:"{{count}} chat",chats_other:"{{count}} chats",generatingCount:"{{count}} generating",coordinatorAttached:"coordinator attached",coordinators:"{{count}} coordinators",workers_one:"{{count}} worker",workers_other:"{{count}} workers",sampledStatus:"sampled status"},legendEdge:{parentBranch:"default branch",cloneLink:"worktree clone",worktreeLink:"same branch",submoduleLink:"submodule",sessionLink:"session",orphanLink:"needs follow-up"},attention:{submoduleDrift:"submodule drift",submoduleDirty:"submodule dirty",conflictsPresent:"conflicts present",dirtyWorkspace:"dirty workspace",upstreamUnverified:"upstream unverified",pushBranch:"push branch",blockedReview:"blocked review",refineFailed:"refine failed",working:"working",refining:"refining…",needsMerge:"needs merge",refineWorktree:"refine worktree",needsFollowUp:"needs follow-up",offline:"offline",ahead:"ahead {{count}}",behind:"behind {{count}}",aheadBehind:"ahead {{ahead}} / behind {{behind}}"},summary:{anchor:"Default branch anchor",parent:"parent {{label}}",localChanges:"local changes",sessions_one:"{{count}} session",sessions_other:"{{count}} sessions",conflicts:"conflicts",clean:"Clean and even with upstream"},taskDag:{plan:{depsFailed_one:"{{count}} upstream failed",depsFailed_other:"{{count}} upstream failed"},time:{now:"just now",minutes_one:"{{count}}m ago",minutes_other:"{{count}}m ago",hours_one:"{{count}}h ago",hours_other:"{{count}}h ago",days_one:"{{count}}d ago",days_other:"{{count}}d ago"},empty:"No tasks yet",waitsOn_one:"waits on {{count}}",waitsOn_other:"waits on {{count}}",missingDeps_one:"{{count}} unknown dep",missingDeps_other:"{{count}} unknown deps",legend:{satisfied:"done",waiting:"waiting",failed:"failed"},predictedSlotPinned:"Pinned to a target node — predicted slot on that node"},obs:{fieldEdgeId:"Link ID",fieldHealthRaw:"Health",fieldNodeId:"Node ID",machineSection:"Machine",behindCount:"{{count}} behind",aheadCount:"{{count}} ahead",healUnavailableHint:"Only a clean checkout that is strictly behind a verified upstream can be updated here.",healHint:"Fast-forward this checkout to its upstream. It has no local changes, so nothing can be lost.",healFailed:"Couldn't update {{label}}: {{reason}}",healDone:"{{label}} is up to date",directionTBShort:"↓",directionLRShort:"→",tabMap:"Map",closeDetailAria:"Close detail panel",layoutDirectionAria:"Graph layout direction",viewAria:"Mesh view",tabOverview:"Overview",tabTasks:"Tasks",panHint:"drag or scroll to pan",headlineFollowUp_one:"{{count}} needs attention",headlineFollowUp_other:"{{count}} need attention",headlineIncomplete:"Some machines not visible",headlineConverged:"All synced",badgeBlocked:"{{count}} blocked",badgeBlockedTitle:"{{count}} blocked review",badgeNotMergeable:"{{count}} not mergeable",badgeNeedMerge_one:"{{count}} needs merge",badgeNeedMerge_other:"{{count}} need merge",badgeCleanupTitle:"{{count}} refine/cleanup",badgeOffline:"{{count}} offline",badgeIncompleteTitle:"{{count}} incomplete peer snapshot",badgeNoGitTitle:"{{count}} no git snapshot",badgeNoSubmodTitle:"{{count}} missing submodule visibility",badgeStaleTitle:"{{count}} stale peer snapshot",badgeActiveQueue:"{{count}} active queue",badgeNodes_one:"{{count}} node",badgeNodes_other:"{{count}} nodes",badgeAttachedChats_one:"{{count}} attached chat",badgeAttachedChats_other:"{{count}} attached chats",legendDirty:"{{count}} dirty",legendOrphan:"{{count}} orphan",legendRecentFailures_one:"{{count}} recent failure",legendRecentFailures_other:"{{count}} recent failures",legendAnchor:"Anchor = default branch",legendPeerLink:"Peer link = same-branch worktree",legendSubmoduleLink:"Submodule link = child checkout",healthRefineFailed:"{{count}} refine failed",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedEdge:"Selected edge",activeSessions:"Active Sessions",queueTasks:"Queue tasks",keyWarning:"Key warning",noResultCode:"No result code returned.",legend:"Legend",checking:"Updating…",heal:"Update",loadingGraph:"Loading graph…",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",connecting:"connecting...",providerUnknown:"provider unknown",directionLRTitle:"Left to right",directionTBTitle:"Top to bottom"},notes:{sectionHint:"Lessons the coordinator keeps between sessions — provider quirks, patterns to avoid, recovery steps.",expired:"expired",neverExpires:"never expires",durable:"durable",expiresIn:"expires {{when}}",tab:"Notes",addTitle:"Add operating note",listTitle:"Operating notes",textPlaceholder:"Record a provider quirk, a pattern to avoid, or a recovery lesson...",categoryLabel:"Category",categoryUncategorized:"Uncategorized",categoryProviderQuirk:"Provider quirk",categoryPatternToAvoid:"Pattern to avoid",categoryRecoveryLesson:"Recovery lesson",add:"Add",edit:"Edit",delete:"Delete",save:"Save",cancel:"Cancel",refresh:"Refresh",loading:"Loading notes...",empty:"No operating notes recorded yet.",unavailable:"Operating notes are unavailable — the coordinator is not reachable over P2P.",loadFailed:"Failed to load operating notes.",saveFailed:"Failed to save the operating note.",deleteFailed:"Failed to delete the operating note.",editFailed:"Failed to update the operating note.",showMore:"Show more",showLess:"Show less",pinned:"pinned"},dialog:{liveUpdatesOn:"Live updates on",liveUpdatesPaused:"Live updates paused — showing the last loaded state",refreshedAt:"Refreshed {{time}}",refreshFailedQuiet:"refresh failed · showing last loaded",refreshTitle:"Refresh live mesh graph",loadingStatus:"Loading live mesh status…",noGraph:"No live mesh graph is available for this coordinator yet. Tap the ? above to learn what a Repo Mesh does.",errorNoMeshId:"This coordinator does not expose a live mesh id."},health:{statFailed:"Failed",statPending:"Waiting"},blueprint:{schedPrediction:"Prediction",readonlyBadge:"read-only",schedObservedAt:"as of {{time}}",schedNoNodes:"No routable nodes.",schedQuotaButton:"Quota",schedQuotaButtonTitle:"Per-machine plan quota at a glance",schedNoWinner:"no eligible slot",schedNext:"Next up",schedWaiting:"Ready",schedFull:"At capacity",schedFloorExcluded:"Below difficulty",schedQuotaGated:"Quota-gated",schedCapFree:"Free",schedColSlot:"Slot",schedColScore:"Score",schedColQuota:"Quota",schedColParallel:"Parallel",schedColStatus:"Status",schedColMachine:"Machine",schedNextTitle:"Dispatch a task of this difficulty now and this slot takes it",schedTargetWorktreeTitle:"The task would run in this worktree checkout",schedUnpinnedTitle:"Hypothetical dispatch with no target pin — tasks pinned to a node show their own forecast on their cards",schedPointInTime:"Point-in-time prediction, not a settled assignment: slot capacity can go stale as soon as a slot is claimed or released",schedulingShort:"Scheduling",list:{barActive:"Active {{count}}",barBlocked:"Blocked {{count}}",barRecent:"Recent {{count}}",barMissions_one:"{{count}} mission",barMissions_other:"{{count}} missions",sectionRunning:"Running",sectionBlocked:"Blocked",sectionRecent:"Recent",sectionHistory:"History",generating:"generating",approvalNeeded:"approval needed",choiceNeeded:"choice needed",planShow:"plan",planHide:"hide",planTitle:"Show this task's dependency plan",noMission:"No mission",loadMore_one:"Show {{count}} more",loadMore_other:"Show {{count}} more",emptyActive:"Nothing running",waitingOn:"waiting on:",waitingOnMore:"+{{count}} more",blockedByDeadDependency:"blocked by failed/cancelled dependency:",chainGroup:"Chain: {{title}}"},graph:{viewSwitchLabel:"Blueprint view",viewList:"List",viewGraph:"Graph",activeOnly:"Active only",activeOnlyTitle:"Hide lanes where everything has finished",hiddenLanes_one:"{{count}} finished lane hidden",hiddenLanes_other:"{{count}} finished lanes hidden",emptyActive:"Nothing running",showFinished:"Show finished lanes",layoutFailed:"Graph layout failed: {{error}}",laneAdhoc:"Independent tasks",laneCollapse:"Collapse",laneExpand:"Expand",foldCompleted:"Fold completed",unfoldCompleted:"Show completed",foldNode_one:"{{count}} completed",foldNode_other:"{{count}} completed",countRunning_one:"{{count}} running",countRunning_other:"{{count}} running",countDead_one:"{{count}} stuck",countDead_other:"{{count}} stuck",countWaiting_one:"{{count}} waiting",countWaiting_other:"{{count}} waiting",countFailed_one:"{{count}} failed",countFailed_other:"{{count}} failed",countDone_one:"{{count}} done",countDone_other:"{{count}} done",timeRunning:"running {{age}}",timeFinished:"ended {{time}}",timeQueued:"queued {{age}}",tooltipTask:"Task: {{id}}",tooltipMission:"Mission: {{id}}",tooltipStatus:"Status: {{status}}",deadDirect:"A dependency failed or was cancelled — this task will not start on its own.",deadTransitive:"Something upstream failed or was cancelled — this task will not start on its own.",legendDepends:"depends on",legendRunning:"running",legendDead:"can never start",heldUntil:"until {{time}}",tone:{pending:"pending",running:"running",completed:"completed",failed:"failed",cancelled:"cancelled",dead:"stuck",plan:"planned",held:"held"}}},page:{title:"Repo Mesh",subtitle:"Multi-workspace orchestration",waitingForDaemon:"Waiting for daemon connection..."},list:{nodeCount_other:"{{count}} nodes",nodeCount_one:"{{count}} node",machinesOnline:"{{online}}/{{total}} machines online",settings:"Settings",open:"Open",title:"Repo Meshes",count_one:"{{count}} mesh",count_other:"{{count}} meshes",createMesh:"+ Create Mesh",createTitle:"Create Repo Mesh",createOnMachine:"Create on machine",noConnectedDaemon:"No connected daemon",workspace:"Workspace",workspaceHint:"Choose from workspaces registered by the selected daemon.",name:"Name",remoteUrl:"Repo remote URL (recommended)",remoteUrlHint:"Paste your repo URL — the identity (github.com/user/repo) is filled in automatically.",repoIdentity:"Repo identity",repoIdentityHint:"For a repo with no remote, or when the URL differs per machine. e.g. github.com/user/repo",advancedIdentityToggle:"Advanced: set identity manually",create:"Create",creating:"Creating…",cancel:"Cancel",loading:"Loading meshes...",emptyTitle:"No Repo Meshes",emptyWithDaemons:"Run several coding agents on one repo across your machines.",emptyNoDaemons:"Connect a machine first.",createFirst:"Create First Mesh",noRepoIdentity:"No repo identity"},detail:{useFromCli:"Use from CLI",optionNo:"No",optionYes:"Yes",distributionInOrderSummary:"First available node, in the order added",distributionSmartSummary:"Best-fit node for each task, spread by load",tabGeneral:"General",back:"← Back",delete:"Delete",observabilityOpenTitle:"Open the live view (overview, tasks, map)",observabilityDisabledTitle:"The host machine must be connected first",observabilityOpen:"Open",tabsAriaLabel:"Mesh settings sections",tabAdvanced:"Advanced",quotaBusyFallback:"Quota fallback when busy",quotaBusyFallbackHint:"When the best provider by quota has no free slot, try the next provider with quota on the same node instead of waiting. Never falls back to a provider that is low on quota, and never moves the task to another node.",distribution:"Distribution",distributionSmart:"Smart",distributionSmartDescription:"Match each task to the node whose capability slot fits it best (difficulty + capability tags), then spread by priority and load. Without slots it still spreads work evenly. Recommended when any node has slots.",distributionInOrder:"In order",distributionInOrderDescription:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading.",recommended:"Recommended",saving:"Saving…",visibilityTitle:"Dashboard visibility",visibilityLabel:"Coordinator-spawned worker sessions",visibilityHint:"Hidden = keep the inbox quiet and mute their notifications; you interact through the coordinator session. Visible = show every spawned worker as its own conversation.",visibilityHidden:"Hidden",visibilityVisible:"Visible",coordinatorPromptTitle:"Coordinator prompt",thisMeshHint:"Applies only to coordinator sessions for {{name}}. Leave empty to keep the daemon default.",overrideLabel:"Override (replaces default)",overrideHint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",overridePlaceholder:"(empty — daemon default applies)",appendLabel:"Append (added after the base)",appendHint:"Always added after whichever base prompt wins.",appendPlaceholder:"(empty — nothing appended)",availablePlaceholders:"Available placeholders",placeholdersIntro:"These tokens are replaced when rendering an override or append prompt:",saveCoordinatorPrompt:"Save coordinator prompt",clear:"Clear",clearTitle:"Clear both fields. Click Save to commit.",safetyTitle:"Safety & Git",safetyDescription:"Checkpointing, approval gates, and git safety behavior for coordinator-driven tasks.",checkpointBefore:"Auto-commit a checkpoint before each task",checkpointAfter:"Auto-commit a checkpoint after each task",pushApproval:"Push approval",requireApprovalBeforePush:"Require approval before push",doNotRequireApproval:"Do not require approval",destructiveGitApproval:"Destructive git approval",requireApproval:"Require approval",uncommittedChanges:"When the workspace has uncommitted changes",warnAndContinue:"Warn and continue",blockTask:"Block task",checkpointThenContinue:"Checkpoint then continue",autoPublishSubmodule:"Auto-publish submodule commits (advanced)",requireExplicitApproval:"Require explicit approval",allowRefineryPublish:"Allow Refinery non-force publish",autoFastForward:"Auto fast-forward idle nodes",ffEnabled:"Enabled (catch up online, clean, behind nodes)",ffDisabled:"Disabled",includeRemoteNodes:"Include remote nodes",includeRemoteNodesHint:"Off = only the coordinator's local workspace is auto fast-forwarded.",remoteNo:"No (local workspace only)",remoteYes:"Yes (delegate to remote owning daemons)",detectionMode:"Detection mode",detectionModeHint:"Idle = on a node's idle edge. Continuous = also scan periodically (base nodes only).",idleEdgeOnly:"Idle edge only",continuousScan:"Continuous (periodic scan)",sessionCleanupLabel:"When removing a node, its sessions…",sessionCleanupHint:"Separate transcript cleanup from runtime/process cleanup.",mcpDescription:"· The mesh MCP server can be used directly from your CLI agent.",repoMeshJsonTitle:"From repo file (read-only)",repoMeshJsonHint:"This repo commits coordinator prompt text that stacks with the fields above. Edit it in the repo file, not here:",repoMeshJsonOverrideLabel:"Repo override",repoMeshJsonAppendLabel:"Repo append",repoMeshJsonInvalid:"This repo's .adhdev/mesh.json could not be parsed, so its prompt layer is ignored."},nodeList:{advanced:"Advanced",launchBlockedChip:"No provider detected",usesTools:"Uses {{tools}}",addingIsExplicit:"Adding it is still up to you.",compatibleWorkspace:"Compatible Git workspace detected.",inspectingRepo:"Inspecting the Git repository (read-only)…",title:"Nodes & Providers ({{count}})",descriptionCloud:"Workspaces in this mesh and their preferred AI tools.",descriptionStandalone:"Workspaces participating in this mesh and their preferred AI tools.",daemonCandidates:"Machine daemon candidates",available:"{{count}} available",noDaemonsAvailable:"No connected machine daemons are currently available.",allDaemonsAttached:"All connected machine daemons are already attached.",selectedHost:"selected host",attachMachine:"Attach machine",addNode:"Add node",attachMachineTitle:"Attach Machine Daemon",addNodeTitle:"Add Node",machine:"Machine",selectMachine:"Select a machine...",workspacePath:"Workspace Path",enterCustomPath:"Or enter a custom path →",preferredTools:"Preferred AI tools (in order)",preferredToolsHint:"Order used when launching without an explicit provider.",add:"Add",cancel:"Cancel",emptyTitle:"No nodes",emptyDescription:"Add a workspace to this mesh.",slotsLabel:"Preferred AI tools (capability slots)",slotsHint:"Each slot = provider + model + thinking + the task difficulty/capability it handles + a per-slot parallel cap. Tasks are matched to the best-fit slot (order = preference). With no slots, this node uses its legacy provider order.",nodeInstruction:"Node instruction (optional)",nodeInstructionHint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",nodeInstructionPlaceholder:"e.g. 'Run only smoke tests here', 'Use opus on this node'",saveInstruction:"Save instruction",saving:"Saving…",removeNode:"Remove node",nodeId:"Node ID:",repoRoot:"Repo root:",activeSessionsLabel:"Active sessions:",added:"Added:",activeQueueAssignments:"Active queue assignments",noActiveAssignment:"No active assigned queue task for this node.",activeSessions:"Active sessions",launchBlocked:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)",titleNoCount:"Nodes & Providers",workspacesDetected:"{{count}} workspace(s) detected",pickFromSaved:"← Pick from saved workspaces",ownerMachine:"Owner: {{owner}} · Machine: {{machine}}",machineTabsLabel:"Machines in this mesh",machineTabCounts:"{{nodes}} node(s) · {{slots}} slot(s)"},host:{setHostConfirmTitle:"Set {{name}} as the host?",setupNode:"setup node",willHostOn:"Will host on",title:"Host machine",descriptionSet:"The machine that runs this mesh's coordinator. It is set once and not changed here.",descriptionUnset:"Choose the machine that will run this mesh's coordinator.",hostLabel:"Host:",hostNode:"Host node:",unknown:"Unknown",hostOffline:"Host offline",hostOfflineText:"Live status won't load until the host reconnects. Meanwhile you can send commands through another connected machine — this doesn't change the host.",reconnectToCommand:"Reconnect to command",reconnectToCommandHint:"Route commands through this connected daemon until the host is back. Does not change the mesh host.",waitForHost:"Wait for host to reconnect",noDaemonsToRoute:"No connected daemons available to route commands through. Bring the host (or another daemon) online.",setHostBanner:"Choose a host machine",hostDaemon:"Host daemon",hostDaemonHint:'Pick the daemon that will host this mesh, then confirm with "Set as host".',resolvingHost:"Resolving host… (or pick a daemon to host)",noDaemonsToHost:"No connected daemons. Bring a daemon online to host this mesh.",online:"online",offline:"offline",noCommandTarget:"No command target available — bring the host or a daemon online.",setHostAction:"Set as host",settingHost:"Setting host…",setHostActionHint:"Pins this daemon as the mesh host. Effectively permanent — it is not reassigned from here afterwards.",confirmSetsHost:"Confirm below to set it as the mesh host.",attachNodeThenSetHost:"Attach one of its workspaces as a node first, then set it as the host."},slotEditor:{emptyHint:"Without slots this node still runs tasks using its provider order. Add a slot to send specific task difficulties or capabilities to a specific tool.",empty:"No slots (optional)",moveUp:"Move up",moveDown:"Move down",removeSlot:"Remove slot",provider:"Provider",select:"(select)",model:"Model",providerDefault:"(provider default)",custom:"Custom…",modelPlaceholder:"model",backToModelList:"← Back to model list",thinking:"Thinking",thinkingDefault:"(default)",difficulty:"Difficulty (blank = freeform tasks only)",capabilityTags:"Capability tags (comma-separated)",maxParallel:"Max parallel (per slot)",maxParallelPlaceholder:"unlimited",addSlot:"Add slot",saving:"Saving…",saveSlots:"Save slots"},tagEditor:{emptyHint:"Tasks can run here without matching any specific tag. Add tags to target this node from a task's required tags.",noSpaces:"Tags cannot contain spaces.",reservedPrefix:"That prefix is auto-derived — pick a different tag.",alreadyAdded:"Already added.",routingTags:"Routing tags",autoDerivedTitle:"Auto-derived — can't be edited",customTagTitle:"Custom tag",remove:"Remove {{tag}}",addPlaceholder:"add a custom tag (e.g. test-runner)",add:"Add",saving:"Saving…",saveTags:"Save tags",empty:"No tags (optional)"},queue:{title:"Queue",description:"Inspect active queue work separately from historical completed, failed, and cancelled task records."},promptPreview:{connectPrompt:"Connect a daemon to preview the default.",errorRender:"Failed to render the default prompt",hide:"Hide the default prompt",view:"View the default prompt",rendering:"Rendering…",retry:"Retry",info:"This is what a coordinator session gets when Override is empty.",launchScopeNote:"Mission, recent activity and operating notes are added at launch and are not shown here."},providerAutoApprove:{partialInventoryChip_other:"{{count}} nodes pending",partialInventoryChip_one:"{{count}} node pending",title:"Provider auto-approve defaults",loading:"Loading provider defaults…",loadError:"Failed to load provider auto-approve defaults.",noProviders:"No CLI providers with auto-approve modes detected on this mesh's machines.",awaitingNodes:"Waiting for {{count}} node(s) to report their installed providers…",partialInventory:"Provider list may be incomplete — {{count}} node(s) have not reported yet.",noHostDaemon:"Connect the mesh host daemon to configure provider auto-approve defaults.",repoSection:{chip:"Shared with team",title:"Repository default",hint:"Committed to .adhdev/mesh.json — shared with the whole team. Sets which mode a delegated worker requests; it does not grant permission to run it.",usesProviderDefault:"Uses provider default",clear:"Use provider default"},machineSection:{chip:"This machine only",title:"This machine authorization",hint:"Local only (meshes.json) — never committed. Controls whether workers on THIS machine auto-approve at all, and whether dangerous modes are allowed.",autoApproveToggleLabel:"Delegated worker auto-approve",autoApproveToggleHint:"When off, workers delegated to this machine stop at every approval prompt.",dangerousToggleLabel:"Allow dangerous modes on this machine",dangerousToggleHint:"Opt-in: workers on this machine may run dangerous modes that execute tools with no approval at all.",dangerousDisabledHint:"No effect while auto-approve above is off.",confirmTitle:"Opt in to dangerous modes",confirmDescription:"This allows delegated workers on this machine to run dangerous provider modes. In a dangerous mode the agent executes tools and commands with no approval prompts at all.",confirmScopeLabel:"Scope",confirmScopeValue:"This machine only (local meshes.json — never committed)",confirmEffectLabel:"Effect",confirmEffectValue:"Repo-requested dangerous modes (e.g. Force, fully autonomous) are no longer downgraded to a safer interactive mode on this machine.",confirmConfirm:"Opt in"},effectiveSection:{statusDowngradedHint:"{{requested}} was requested, but this machine hasn't allowed dangerous modes, so it runs {{mode}}.",statusRequested:"Runs: {{mode}}",statusInvalidFallback:"Requested mode not found → runs provider default: {{mode}}",statusDowngraded:"{{mode}} (downgraded)",statusDisabled:"Auto-approve disabled on this machine — worker will ask for approval.",statusNone:"No usable auto-approve mode — worker will ask for approval."},dangerous:{sharedWarningDetail:"Saved in .adhdev/mesh.json. Each machine runs it only after opting in (delegatedWorkerDangerousModeAllow).",sharedWarningTitle:"This is committed to the repository",sharedWarning:"Committed to the repo and shared with your team. Machines that haven't allowed dangerous modes run a safer mode instead."},saving:"Saving…",saved:"Saved to .adhdev/mesh.json",saveError:"Failed to save provider defaults."},status:{healthErrorChip:"Error",offlineMachinesTitle:"Not reporting: {{machines}}",badgeBootstrap:"Setting up",badgeUpdatePending:"Update pending",quotaClaudeRefreshChip:"Needs refresh",quotaClaudeSetupChip:"Set up",machineNotReportingHint:"We haven't heard from this machine, so its plan quota is unknown.",quotaNotCollectedHint:"A machine reports its plan quota after its first refresh (about 15 minutes) and only while an agent has been active.",schedulingNotReportedHint:"This machine runs an older version that doesn't report scheduling details.",schedulingNotReported:"Update the daemon to see scheduling",schedulingTitle:"Scheduling",distributionTitle:"Distribution decides how work without a target is spread across nodes. Per-node load and limits are listed below.",protocolTitle:"Protocol & provider versions",noNodesReporting:"No nodes reporting runtime yet.",quotaNotCollected:"No quota yet",quotaFreshnessHint:"Last updated",machineNotReporting:"Offline · quota unknown",quotaClaudeSetupHint:"Set up Claude quota with `adhdev quota claude:install`.",quotaClaudeRefreshHint:"Open a Claude Code session once to refresh quota.",quotaAccountHint:"The signed-in account this quota belongs to, as reported by the provider CLI",quotaOkNoWindows:"No limit",healthNotGitRepo:"Not a git repo",healthProbePending:"Checking…",healthPeerConnection:"Connection {{state}}",healthNoLiveReport:"No report yet",badgeWorktree:"worktree",badgeWorktreeTitle:"Local worktree node",badgeWorktreeBranchTitle:"Worktree branch {{branch}}",badgeBootstrapTitle:"Worktree bootstrap is still in progress",badgeConnectionTitle:"Mesh peer connection state",badgeSessions_one:"{{count}} session",badgeSessions_other:"{{count}} sessions",badgeFastForwardReady:"fast-forward ready",badgeFastForwardReadyTitle:"Clean, behind upstream — safe for fast-forward",badgeStaleBuildTitle:"Live daemon was built behind workspace HEAD — merged fixes may not be live",badgeDeployLagTitle:"Running daemon build commit differs from origin/main — deploy + restart pending for this node",machinesNotReporting_one:"{{count}} offline",machinesNotReporting_other:"{{count}} offline",machinesSection:"Machines — plan · nodes",versionSkewTitle:"Version differs from this machine’s consensus (stale report or partial install)",machineVersionsTitle:"Provider CLI versions installed on this machine — shared by all its nodes"},overview:{tasksCount_other:"{{count}} tasks",tasksCount_one:"{{count}} task",sessionCount_other:"{{count}} sessions",sessionCount_one:"{{count}} session",providerUnknown:"provider unknown",truncated:"(truncated)",missionCard:"Missions",ledgerCard:"Activity",queueCard:"Queue",nodesCard:"Nodes",sessionsCard:"Active sessions",refineCard:"Refine jobs",recentActivity:"Recent activity",recentTasks:"Recent tasks",missionTasksHeading:"Mission tasks",showFewer:"Show fewer",showMore:"+{{count}} more",noActiveMissions:"No active missions",missionDataUnavailable:"Update the daemon to see missions",completedHistory:"Completed / abandoned history",noQueueActivity:"No queue activity.",noNodes:"No nodes in this mesh yet.",noActiveSessions:"No active sessions.",noRefineJobs:"No refine jobs.",closeDetail:"Close detail",loadingGoal:"Loading…",showFullGoal:"Show full goal",statCompleted:"Completed",statAssigned:"Assigned",statPending:"Pending",statFailed:"Failed",statBlocked:"Blocked",statCancelled:"Cancelled",statWallClock:"Wall clock",statTotalRuntime:"Total runtime",statRetries:"Retries",statDispatched:"Dispatched",statStalled:"Stalled",statSessions:"Sessions",statCheckpoints:"Checkpoints",statActive:"Active",statPaused:"Paused",statAbandoned:"Abandoned",recentFailures:"{{count}} recent failures",activeCount:"{{count}} active",failedCount:"{{count}} failed",detailKickerMission:"Mission",detailKickerLedger:"Ledger entry",detailKickerQueue:"Queue task",detailKickerSession:"Session",detailLabelMissionId:"Mission id",detailLabelCreated:"Created",detailLabelUpdated:"Updated",detailLabelElapsed:"Elapsed",detailLabelFullInstruction:"Show full instruction",detailLabelLastActivity:"Last task activity",detailLabelIncompleteEvidence:"Incomplete evidence",detailLabelEntryId:"Entry id",detailLabelWhen:"When",detailLabelNode:"Node",detailLabelDependsOn:"Depends on",detailLabelSession:"Session",detailLabelProvider:"Provider",detailLabelPayload:"Show raw payload",detailLabelTaskId:"Task id",detailLabelFinalSummary:"Final summary",detailLabelFullFinalSummary:"Show full report",detailFinalSummaryLoading:"Loading final summary…",detailFinalSummaryUnavailable:"Final summary unavailable",detailLabelAutoLaunch:"Auto launch",detailLabelCancelReason:"Cancel reason",detailLabelRequeueReason:"Requeue reason",detailLabelRequeued:"requeued {{count}}",detailLabelSessionId:"Session id",detailLabelBranch:"Branch",detailLabelRole:"Role",detailLabelStarted:"Started",detailLabelWorkspace:"Workspace",routingHeading:"Routing",routingDevice:"Device",routingDaemon:"Daemon",routingExecution:"Execution",routingVia:"Via",routingDifficulty:"Difficulty",routingFitness:"Fitness",routingReason:"Reason",routingRequiredTags:"Required tags",routingTagsUnsatisfied:"unsatisfied",routingSkipped:"Skipped candidates",routingSkippedMore:"+{{count}} more",pausedMissions:"Paused missions",ledgerAllTime:"all-time totals",sessionTasksHeading:"Tasks in this session",showOnCanvas:"Show on canvas"}},rk={showMoreChars:"Show more ({{count}} characters)",collapse:"Collapse",you:"You",toolMessageAria:"Tool message",activityMessageAria:"Activity message",activityFallback:"Activity",copyMessage:"Copy message",copyCode:"Copy code",showMore:"Show more",showLess:"Show less",thought:"Thought",toolExpand:"Show full output",toolCollapse:"Show less",toolExpandLoading:"Loading…",toolExpandUnavailable:"Full output could not be fetched for this step.",toolExpandStale:"Full output has moved — the transcript changed since this was read. Reload the conversation to fetch it.",waitingToSend:"Waiting to send — the agent is still working.",waitingToSendAria:"Waiting to send",notDelivered:"Not delivered — the agent never received this.",notDeliveredAria:"Not delivered",sendNow:"Send now",sending:"Sending…",sendNowAria:"Send now to the agent's queue, without interrupting its current turn",sendNowTitle:"Send this message to the agent now. It goes into the agent's own queue and is answered next — the turn in progress keeps running.",cancelQueued:"Cancel",cancelQueuedAria:"Cancel this queued message",cancelQueuedTitle:"Remove this message from the queue. It will not be sent to the agent."},ok={debugBundleFailed:"Couldn't collect debug info",connectingToMachine:"Connecting to your machine",establishingP2P:"Establishing P2P connection",agentNotMonitored:"Agent not monitored",clickToSwitchMonitoring:"Click to switch monitoring to this agent",agentPanelHidden:"Agent panel is not visible yet",openPanelHint:"Open the chat in your IDE",noMessagesYet:"No messages yet",loadingChat:"Loading chat...",openPanel:"Open {{label}} Panel",switchingPanel:"Switching...",openingPanel:"Opening...",busyNoProgress:"Agent shows no progress.",busyGenerating:"Agent is generating.",busyWaitingApproval:"Waiting for approval",activityToggleLabel:"Tool steps",activityToggleTitle:"Show tool, terminal and thinking steps",reconnectMachine:"Reconnect",reconnectingMachine:"Reconnecting…",reconnectMachineTitle:"Automatic reconnection gave up on this machine — reconnect now"},ak={addMessageOptional:"Add a message (optional)…",showControls:"Show controls",hideControls:"Hide controls",sendTo:"Send message to {{panel}}",attachImage:"Attach image",placeholder:"Send message to {{panel}}...",sendMessage:"Send message",dropImage:"Drop image here"},ik={cdpDisconnectedShort:"IDE disconnected",hideFromDashboard:"Hide from dashboard",removeShortcut:"Remove shortcut",changeShortcut:"Change shortcut ({{shortcut}})",dropSplitRight:"Split right",dropMoveHere:"Move here",dropSplitLeft:"Split left",relaunchWithCdp:"Relaunch with connection",cdpDisconnected:"Not connected to the IDE — chat history and screenshots are unavailable.",resizeHandleHint:"Drag to resize · Double-click to merge",shortcutListening:"Listening…",shortcutPressCombo:"Press a key combination (e.g. {{example1}}, {{example2}})",shortcutSetTitle:"Set shortcut",loadingSessions:"Loading sessions...",noConversations:"No conversations yet",waitingForDaemon:"Waiting for your daemon",connectYourMachines:"Connect your machines",daemonDescription:"Start the ADHDev daemon to connect.",installDescription:"Install ADHDev on a machine and sign in.",newSession:"New session",newSessionDescription:"Start a session with any installed agent.",noTabsInGroup:"No tabs in this group",pressEscToCancel:"Press Esc to cancel",noActiveAgent:"No active agent",moveTabHere:"Move a tab here to view"},ck={growViewport:"Enlarge terminal view",shrinkViewport:"Shrink terminal view",sendInterrupt:"Send interrupt (Ctrl-C)",arrowRight:"Arrow right",arrowDown:"Arrow down",arrowLeft:"Arrow left",arrowUp:"Arrow up",keysPanelTitle:"Terminal keys",keysButton:"Keys",copyHint:"Copy the selected terminal text, or the visible screen if nothing is selected",specDebugHint:"Spec debug — inspect current state, sections, and transition history",replayScrollbackHint:"Load earlier terminal output so you can scroll farther up",loadOlderOutput:"Load older terminal output",loadingOlder:"Loading older...",debug:"Debug",copy:"Copy",openControlKeys:"Open terminal control keys",closeControlKeys:"Close terminal control keys"},lk={muteThis:"Mute this chat",unmuteThis:"Unmute this chat"},dk={switchToTerminal:"Switch to Terminal view",switchToChat:"Switch to Chat view"},uk={updatedAt:"Updated {{time}}",messageCountShort_other:"{{count}} msgs",messageCountShort_one:"{{count}} msg",workspaceUnknown:"Workspace unknown",clearSelection:"Clear",selectedSavedHistory:"Selected saved history",loadingShort:"Loading…",savedHistoryNoneYet:"No saved history",savedHistoryLoadedCount_other:"{{count}} saved histories loaded. Open saved history to choose one.",savedHistoryLoadedCount_one:"{{count}} saved history loaded. Open saved history to choose one.",savedHistoryBadge:"Saved history",resumeSavedHistory:"Resume saved history",startFresh:"Start fresh",resumingSavedHistory:"Resuming saved history…",startingFresh:"Starting fresh…",startIde:"Start IDE",startingIde:"Starting IDE…",recoverHostedRuntime:"Recover hosted runtime",hostedRuntimeRecoveryDescription:"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead.",openSavedHistory:"Open saved history",savedHistoryTitle:"Saved History",savedHistoryHelper:"Use saved history when you want continuity in the same provider conversation.",savedHistoryEmpty:"No saved history found yet.",refreshSavedHistory:"Refresh saved history",refreshingSavedHistory:"Refreshing saved history…",startFreshWith:"Start fresh with {{label}}?",restart:"Restart {{label}}?",startFreshReview:"Review the provider and target folder before starting fresh.",restartIdeReview:"Review or change the target workspace before restarting this IDE.",restartStoppedReview:"Review or change the target workspace before restarting this stopped session.",confirmStartFresh:"Start fresh",confirmRestart:"Restart",confirmStartingFresh:"Starting fresh…",confirmRestarting:"Restarting…",resumeWith:"Resume saved history with {{label}}?",resumeReview:"Review or change the target workspace before resuming saved history."},mk={layout:{expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse"},auth:{loading:"Loading standalone dashboard…",loadError:"Failed to load standalone auth status: {{error}}",signInTitle:"Standalone sign-in",passwordProtected:"This self-hosted dashboard is protected by a local password.",tokenProtected:"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session.",passwordPlaceholder:"Enter standalone password",unlock:"Unlock dashboard",signingIn:"Signing in…",noPasswordEnabled:"Password login is not enabled on this server."},machine:{loading:"Loading machine...",awaitingInput:"Awaiting your input ↑"},settings:{restartToApply:"Restart to apply",providersLink:"Providers",providersIntro:"IDEs and agents on this machine:",title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",publicHostWarning:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token.",daemonSection:"Daemon",versionLabel:"Version",statusLabel:"Status",statusRunning:"● Running",statusNotConnected:"○ Not connected",authLabel:"Auth",authPassword:"Password enabled",authToken:"Token enabled",authNone:"No auth configured",networkSection:"Network Access",networkHint:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token.",localhostLabel:"Localhost only",localhostHint:"Bind to 127.0.0.1. Best when only this machine should open the dashboard.",allInterfacesLabel:"All interfaces",allInterfacesHint:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points.",saveNetworkMode:"Save default network mode",saving:"Saving…",networkRestartHint:"Applies on next standalone restart. Current run stays bound to {{host}}.",networkSavedAll:"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.",networkSavedLocal:"Default standalone network mode set to localhost only. Restart standalone to apply it.",securitySection:"Dashboard Security",passwordSet:"A local password is currently required for browser access. Existing sessions are rotated when you change it.",passwordNotSet:"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended.",currentPasswordPlaceholder:"Current password",currentPasswordFirstTimePlaceholder:"Current password (not needed for first setup)",newPasswordPlaceholder:"New password",newPasswordFirstTimePlaceholder:"New standalone password",confirmPasswordPlaceholder:"Confirm new password",updatePassword:"Update password",enablePassword:"Enable password",disablePassword:"Disable password",passwordUpdated:"Standalone password updated.",passwordEnabled:"Standalone password enabled.",passwordDisabled:"Standalone password disabled.",passwordTooShort:"Password must be at least 4 characters.",passwordMismatch:"New password and confirmation do not match.",appearanceSection:"Appearance",fontsLabel:"Fonts",fontsDescription:"Standalone-only typography overrides for chat text, markdown code, and terminal output.",fontsSaved:"Standalone chat fonts saved for this self-hosted dashboard.",profileSection:"Profile",displayNameLabel:"Display Name",displayNameHint:"Your name shown in chat threads and on the team dashboard.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Welcome to ADHDev",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",selectedCount_one:"{{count}} selected",selectedCount_other:"{{count}} selected",intro:"Pick the providers you want to use. Defaults to the three officially supported CLI providers; you can install IDE or extension providers from the tabs below or later from Machines → Providers.",loadingRegistry:"Loading registry…",loadError:"Failed to load registry: {{error}}",noProviders:"No providers in this category.",installed:"✓ installed",installFailed:"✗ {{error}}"},about:{title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",selfHostedEdition:"Self-hosted edition",headline:"Keep the same dashboard experience, with the runtime fully on-device.",description:"Standalone keeps the browser, daemon, screenshots, and control path entirely on your own machine. Aside from multi-machine connectivity and mobile notifications, it is the same core product experience as Cloud.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Try Cloud ↗",includedSection:"Included in standalone",includedDescription:"The local-first feature set available without the cloud control plane.",inventorySection:"Built-in inventory",inventoryDescription:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",cloudExtrasSection:"Cloud-only extras",cloudExtrasDescription:"Capabilities that need the hosted control plane or team infrastructure.",comparisonSection:"Self-hosted vs Cloud",comparisonDescription:"The product split at a glance.",featureHeader:"Feature",selfhostHeader:"Selfhost",cloudHeader:"Cloud",cloudOptional:"Cloud is optional, not required",cloudOptionalDescription:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",compareCloud:"Compare Cloud ↗",discord:"Discord ↗",features:{localFirst:{title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},chatRelay:{title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},screenshots:{title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},remoteControl:{title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},multiIde:{title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},cli:{title:"CLI coverage",desc:"Track standalone CLI agents alongside IDE sessions."}},extras:{anywhere:{title:"Access from anywhere",desc:"Reach your machines from another laptop or phone without opening local ports."},p2pStream:{title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},mobileNotifications:{title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},restApi:{title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},teamWorkspace:{title:"Team workspace",desc:"Share machines, activity views, and policies across a team workspace."},enterpriseControls:{title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}},comparison:{chatRelay:"Agent chat relay",screenshots:"Live IDE screenshots",remoteControl:"Remote IDE control",multiIde:"Multi-IDE monitoring",extensionCli:"Extension and CLI agents",anyNetwork:"Access from any network",webrtc:"WebRTC P2P streaming",mobilePush:"Mobile push notifications",restApi:"REST API and webhooks",teamCollaboration:"Team collaboration",multiMachineDashboards:"Multi-machine dashboards",ssoRbacAuditLogs:"SSO, RBAC, audit logs"}},fonts:{fontOverridesNotice:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below.",chat:"Chat text",chatDescription:"Assistant/user prose, markdown text, thought cards, and system notes.",code:"Code blocks",codeDescription:"Markdown code fences, inline code, and preformatted command output.",terminal:"Terminal",terminalDescription:"Terminal transcript cards and tool/command rows in chat mode.",livePreview:"Live preview",resolvedStack:"Resolved stack:",saveFontSettings:"Save font settings",revertToSaved:"Revert to saved",resetToDefaults:"Reset to defaults",saving:"Saving…",customFamilyPlaceholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',previewSummary:"Chat: {{chat}} · Code: {{code}} · Terminal: {{terminal}}",defaultsSummary:"Defaults: {{chat}} / {{code}}",previewNow:"now",previewProse:"Readable prose, <strong>bold text</strong>, and <code>inline code</code> should all follow your standalone font choices.",presets:{default:"Default",defaultMono:"Default mono",custom:"Custom…",serif:"Serif"}}},hk={login:{eyebrow:"Cloud sign-in",title:"Sign in to ADHDev",subtitle:"Connect your machines, get approval and completion notifications, and keep your coding agents moving when you are away from your desk.",continueWith:"Continue with {{provider}}",connecting:"Connecting...",devDivider:"dev",devLogin:"Dev Login (test_jwt_token)",providerNote:"GitHub and Google are used only for authentication.",errorUnverifiedEmail:"This login provider did not return a verified email, so we could not safely sign you in.",termsPrefix:"By continuing, you agree to our ",termsLink:"Terms of Service",termsAnd:" and ",privacyLink:"Privacy Policy",termsSuffix:"."},account:{openMachines:"Open Machines",machinesSummaryShort:"{{count}} of {{limit}}",title:"Account",subtitle:"Profile, plan & activity",tabAccount:"Account",tabBilling:"Billing",tabActivity:"Activity",profile:"Profile",noName:"No name",displayName:"Display Name",displayNameDesc:"Your name shown in the dashboard and team workspaces.",nicknamePlaceholder:"Nickname",save:"Save",saving:"...",cancel:"Cancel",saved:"Saved",edit:"Edit",failedToSave:"Failed to save",userId:"User ID",loadingProfile:"Loading profile...",planLimits:"Plan limits",limitMachines:"Machines",limitP2P:"Connected machines",limitPushNotifications:"Daily Push Notifications",limitTurnRelay:"Relay fallback",enabled:"Enabled",disabled:"Disabled",frozen:"Frozen",session:"Session",logout:"Logout",logoutDesc:"Sign out of your ADHDev account on this device.",dangerZone:"Danger zone",dangerZoneDesc:"Permanently delete your account and all associated data. This action cannot be undone.",deleteAccount:"Delete account",deleteWillRemove:"This will permanently delete:",deleteItemProfile:"Your profile and login credentials",deleteItemKeys:"All API keys and connection tokens",deleteItemWebhooks:"Webhooks and delivery history",deleteItemPush:"Push notification subscriptions",deleteItemSessions:"Shared sessions and audit logs",deleteTypeConfirm:"Type {{keyword}} to confirm:",deleting:"Deleting...",permanentlyDelete:"Permanently delete",failedToDeleteAccount:"Failed to delete account",registeredMachines:"Registered Machines",machinesSummary:"{{count}} registered · {{online}} online",machinesLimit:"(limit: {{limit}})",loadingMachines:"Loading machines...",noMachinesRegistered:"No machines registered",runSetupPrefix:"Run ",runSetupMiddle:", then start ",runSetupSuffix:" on a machine to register it here.",removeMachineConfirm:"Remove this machine? It will need to run `adhdev setup` again to reconnect.",failedToDeleteMachine:"Failed to delete machine",failedToUpdate:"Failed to update",rename:"Rename",online:"Online",connecting:"Connecting",removeMachine:"Remove machine",never:"Never",frozenFeatureTitle:"Frozen — this feature is paused and not available."},billing:{currentPlan:"Current Plan:",statusTrial:"Trial",statusActive:"Active",statusPastDue:"Past Due",statusCanceled:"Canceled",nextBilling:"Next billing: {{date}}",trialEnds:"Trial ends: {{date}}",accessUntil:"Access until: {{date}}",updatePayment:"Please update your payment method",managePayment:"Manage Payment & Invoices",couldNotOpenPortal:"Could not open billing portal",checkoutSuccess:"Your subscription is active. Thanks for upgrading!",statMachines:"Machines",statSharedSessions:"Shared Sessions",statTurnRelay:"TURN Relay",statTurnOn:"On",resetsDailyUtc:"Resets daily at 00:00 UTC",resetsInHours_one:"~{{count}}h left",resetsInHours_other:"~{{count}}h left",resetsInMinutes_one:"~{{count}}m left",resetsInMinutes_other:"~{{count}}m left",resetsDailyUtcWithLeft:"Resets daily at 00:00 UTC · {{left}}",monthly:"Monthly",yearly:"Yearly",savePercent:"Save up to {{pct}}% yearly",pricesInUsd:"All prices in USD",paddleLoading:"Paddle is loading, please try again.",cancelConfirm:"Are you sure you want to cancel your subscription? You will retain access until the end of your billing period.",cancelSubscription:"Cancel Subscription",cancelRetainAccess:"You will retain access to {{plan}} features until the end of your current billing period.",cancelTeamDowngrade:" All team members will be downgraded to their personal plans.",cancelFailed:"Failed to cancel subscription"},about:{title:"About",subtitle:"Cloud overview, supported surfaces, and plan-level capabilities",cloudEdition:"Cloud edition",heroTitle:"Control your local CLI agents from anywhere — web or mobile.",heroDesc:"ADHDev Cloud surfaces the agents running on your machines in your browser: send prompts, approve actions, orchestrate work across machines, and get notified on your phone — code flows P2P directly to your daemon, never through the server.",openDashboard:"Open Dashboard",viewMachines:"View Machines",docs:"Docs ↗",whyTitle:"Why ADHDev Cloud",whyDesc:"Core capabilities available when your machines are connected through the cloud control plane.",howTitle:"How it works",howDesc:"The cloud onboarding path from install to remote control.",repoMeshTitle:"Repo Mesh",repoMeshDesc:"Orchestrate agents across machines — cloud only.",meshCard1Title:"One coordinator, many agents",meshCard1Desc:"Enqueue tasks against a mission and let idle nodes claim work from a local-first, pull-based queue. Fan out across machines and providers — Claude Code on one, Codex on another — then converge the results from a single coordinator session.",meshCard2Title:"Same repo, many machines at once",meshCard2Desc:"Each node is a checkout or an isolated git worktree, so parallel agents never collide. The refinery converges every branch — validate, merge, push, clean up — with safe submodule handling. Runs over a direct daemon-to-daemon P2P channel; the server only signals and authorizes same-account peers.",worksWith:"Works with",worksWithDesc:"Supported CLI agents, IDEs, and AI extensions.",groupCli:"CLI Agents",groupIdes:"IDEs",groupExtensions:"AI Agents",pricingTitle:"Pricing",pricingDesc:"Current cloud plans and machine capacity by tier.",planPopular:"Popular",readyTitle:"Ready to connect a machine",readyDesc:"Jump into your dashboard, inspect your connected machines, or continue in the docs if you are still setting up.",dashboard:"Dashboard",machines:"Machines",discord:"Discord ↗",github:"GitHub ↗",features:{webControlTitle:"Web control of local CLI agents",webControlDesc:"Drive any local CLI agent — Claude Code, Codex, Cursor CLI — from your browser: send prompts, approve actions, and steer sessions without touching the terminal.",chatRelayTitle:"Agent chat relay",chatRelayDesc:"Read and respond to agent conversations from anywhere, including mobile surfaces.",liveViewTitle:"Live session view",liveViewDesc:"Watch agent activity in real time; for IDE sessions, view and control the screen over P2P without switching windows.",mobileTitle:"Mobile-ready",mobileDesc:"Receive approvals and check progress while away from your development machine.",secureTitle:"Secure by default",secureDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC — the cloud handles auth and signaling metadata only. Your code never routes through the server."},steps:{step1Title:"One-line Install",step1Desc:"Run a single command on any machine you want to drive. It installs the ADHDev daemon plus the adhdev CLI.",step2Title:"Sign In",step2Desc:"Sign in with GitHub or Google and the daemon pairs itself to your account — no token to copy.",step3Title:"Drive Your Agents from Anywhere",step3Desc:"The machine appears in your dashboard instantly. Launch and control Claude Code, Codex, Cursor CLI, and other CLI agents from the web — IDE sessions too."},plans:{freeName:"Free",proName:"Pro",ultraName:"Ultra",freePer:"/mo",proPer:"/mo",ultraPer:"/mo",freeFeature1:"1 machine",freeFeature2:"Real-time chat relay",freeFeature3:"Web control for your local agents",proFeature1:"2 machines",proFeature2:"Unlimited AI agents",proFeature3:"P2P remote view",ultraFeature1:"5 machines — flat, not per-seat",ultraFeature2:"Everything in Pro",ultraFeature3:"Higher concurrency & usage limits",ultraFeature4:"Unlimited daily screenshot minutes"}},layout:{adminSection:"Admin",adminOverview:"Overview",adminUsers:"Users",adminAuditLogs:"Audit Logs",adminSystem:"System",adminTokens:"Admin Tokens",adminEntry:"Admin",footerPlanTitle:"Current plan: {{plan}} — manage or upgrade",expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse",logout:"Logout",machineLimitBadge:"Machines full",machineLimitBadgeTitle:"You've reached your plan limit of {{count}} machine{{plural}} — open billing to upgrade",pushBudget:"Daily notifications {{used}}/{{limit}}"},settings:{title:"Settings",subtitle:"Appearance & preferences",appearanceTitle:"Appearance"},planCard:{unlimited:"Unlimited",machineSingular:"{{count}} machine",machinePlural:"{{count}} machines",sharedSessionSingular:"{{count}} shared session",sharedSessionPlural:"{{count}} shared sessions",teamMemberSingular:"{{count}} team member",teamMemberPlural:"{{count}} team members",turnIncluded:"TURN relay included",recommended:"Recommended",currentPlan:"Current Plan",contactUs:"Contact Us",freeForever:"Free Forever",startTrial:"Start 7-day free trial",upgradeTo:"Upgrade to {{name}}",noChargeCancel:"No charge for 7 days. Cancel anytime.",periodSeatMo:"seat/mo",periodMo:"mo",yearlyNote:"${{yearly}}/year — Save ${{saved}}",pricingCustom:"Custom"},activity:{origin:{ide:"IDE",extension:"Extension",admin:"Admin",webhook:"Webhook",web:"Dashboard",user:"User",terminal:"Terminal",system:"System",registry:"Registry",mesh:"Mesh",machine:"Machine",daemon:"Daemon",connection:"Connection",cli:"CLI",auth:"Sign-in",api_key:"API key",api:"API",agent:"Agent"},filterPlaceholder:"Filter by action, resource, or source...",refresh:"Refresh",loading:"Loading...",noLogs:"No logs",noMatchingLogs:"No matching logs found.",logsWillAppear:"Actions will appear here as they happen.",colAction:"Action",colResource:"Resource",colSource:"Source",colTime:"Time",logCount:"{{count}} logs",logCountFiltered:" (filtered from {{total}})",action:{login:"Logged in",logout:"Logged out",api_key_create:"Created API key",api_key_revoke:"Revoked API key",agent_command:"Sent agent command",terminal_exec:"Ran terminal command",ide_command:"Sent IDE command",daemon_command:"Sent daemon command",daemon_disconnect:"Disconnected daemon",daemon_revoke:"Revoked daemon",webhook_create:"Created webhook",webhook_delete:"Deleted webhook",webhook_toggle:"Toggled webhook",registry_publish:"Published provider",registry_promote:"Promoted provider",registry_yank:"Yanked provider",registry_publish_token_issued:"Issued registry publish token",machine_registered:"Registered machine",machine_secret_rotated:"Rotated machine secret",shortcut_launch:"Launched session",shortcut_stop:"Stopped session",shortcut_chat:"Sent chat message",shortcut_chat_debug_bundle:"Exported chat debug bundle",shortcut_approve:"Approved agent action",shortcut_reject:"Rejected agent action",shortcut_git_push:"Pushed git changes",shortcut_git_checkpoint:"Created git checkpoint",shortcut_mesh_clone_node:"Cloned mesh node",shortcut_mesh_remove_node:"Removed mesh node",shortcut_mesh_refine_node:"Refined mesh node",admin_plan_change:"Changed user plan",admin_role_change:"Changed user role",admin_user_suspend:"Suspended user",admin_user_unsuspend:"Unsuspended user",admin_machine_delete:"Deleted machine",admin_token_create:"Created admin token",admin_apikey_rate_limit:"Changed API key rate limit",admin_apikey_scopes:"Changed API key scopes",admin_apikey_revoke:"Revoked API key",admin_plan_limits_update:"Updated plan limits",admin_plan_limits_reset:"Reset plan limits",admin_config_update:"Updated system config",admin_announcement:"Posted system announcement",admin_disconnect:"Disconnected connection"}},webhooks:{title:"Webhooks",subtitle:"Real-time event notifications",addWebhook:"+ Add Webhook",eventDaemonConnect:"Daemon Connected",eventDaemonDisconnect:"Daemon Disconnected",eventAgentStatus:"Agent Status Change",eventApprovalRequired:"Approval Required",failed:"Failed",deleteConfirm:"Delete this webhook?",testFailed:"Test failed",secretTitle:"Webhook Secret",secretShownOncePrefix:"Shown ",secretShownOnce:"only once",secretShownOnceSuffix:". Use to verify ",copy:"Copy",done:"Done",newWebhook:"New Webhook",labelUrl:"URL",urlPlaceholder:"https://your-service.com/webhook",labelEvents:"Events",allEvents:"All Events (*)",creating:"Creating...",create:"Create",cancel:"Cancel",loading:"Loading...",noWebhooks:"No webhooks",noWebhooksDesc:"Receive real-time notifications about events.",setupFirst:"Set up first webhook",off:"OFF",autoDisabled:"Auto-disabled",autoDisabledTitle:"Auto-disabled after 10 consecutive failures",failuresWarning:"{{count}} failures",failuresTitle:"{{count}} consecutive failures — will auto-disable at 10",all:"ALL",history:"History",test:"Test",delete:"Delete",deleting:"...",recentDeliveries:"Recent Deliveries",refresh:"Refresh",noDeliveries:"No deliveries yet. Send a test to verify the endpoint.",request:"REQUEST",response:"RESPONSE",securityTitle:"Security",securityVerifyPrefix:"Verify ",securityVerifySuffix:" with your secret",securityHttps:"Use HTTPS endpoints only",securityAsync:"Return 2xx immediately, process async",securityAutoDisable:"Auto-disabled after 10 consecutive failures"},apiKeys:{title:"API Keys",keyCount:"{{count}} keys",playground:"Playground",create:"+ Create",scopeDaemonRead:"Daemon Read",scopeDaemonReadDesc:"List daemons & status",scopeDaemonControl:"Daemon Control",scopeDaemonControlDesc:"Commands, launch/stop, disconnect",scopeAgentRead:"Agent Read",scopeAgentReadDesc:"Status & chat history",scopeAgentControl:"Agent Control",scopeAgentControlDesc:"Send, approve/reject",scopeTerminal:"Terminal",scopeTerminalDesc:"Execute commands",scopeWebhooks:"Webhooks",scopeWebhooksDesc:"Manage hooks & deliveries",frozen:"Frozen",revokeConfirm:"Revoke this API key? This cannot be undone.",failedToLoad:"Failed to load",failed:"Failed",upgradePlan:"Upgrade your plan →",keyCreated:"Key Created!",copyNow:"Copy now — shown only once.",copied:"Copied",copy:"Copy",testKey:"Test",dismiss:"Dismiss",playgroundTitle:"API Playground",enterKeyToTest:"Enter an API key to test.",open:"Open",createKeyTitle:"Create API Key",labelName:"Name",namePlaceholder:"e.g. Production Bot",permissions:"Permissions ({{count}})",createBtn:"Create",cancel:"Cancel",loading:"Loading...",noKeys:"No API Keys",noKeysDesc:"Create a key to integrate with external services.",createFirstKey:"Create First Key",usedDate:"Used {{date}}",neverUsed:"Never used",revoke:"Revoke",usageLabel:"Usage:",apiReference:"API Reference →",frozenFeatureTitle:"Frozen — this feature is paused."},shareModal:{title:"Share Session",chatView:{label:"View Only",desc:"Read AI conversation in real-time"},chatControl:{label:"Control",desc:"Read + send messages + approve/reject actions"},remoteView:{label:"View Only",desc:"Watch screenshots + chat in real-time"},remoteControl:{label:"Control",desc:"Screenshots + send messages + approve/reject"},remoteFull:{label:"Full Access",desc:"Full remote control including desktop input"}},onboarding:{title:"Connect your first machine",subtitle:"Install ADHDev on a machine and sign in — it pairs itself and shows up here. Then drive every agent on it from this dashboard.",platformMac:"macOS / Linux",platformWindows:"Windows",copyTitle:"Click to copy",copiedLabel:"✓ Copied",copyLabel:"Copy",listeningLabel:"Listening for your daemon — keep this page open, it will appear automatically.",connectingLabel:"Connecting to ADHDev…",step1Title:"Install the daemon",step1Desc:"Run the command above on any machine you want to drive. It installs the daemon plus the adhdev CLI.",step2Title:"Sign in — the machine pairs itself",step2Desc:"The daemon links to this account automatically. No token to copy; it appears here the moment it connects.",step3Title:"Launch your first session",step3Desc:"Once a machine is online, start Claude Code, Codex, Cursor, and other agents straight from the dashboard.",readDocs:"Read the documentation →",reconnectingLabel:"Connection lost — reconnecting… Check your network if this persists.",offlineLabel:"You're offline. Reconnect to the internet and this page will resume automatically.",authFailedLabel:"Session expired — sign in again to continue.",machineLimitLabel:"Machine limit reached — your plan allows up to {{limit}}. Remove a machine or upgrade your plan to connect this one.",machineLimitManage:"Manage machines →",machineLimitUpgrade:"Upgrade plan →",setupWizardLink:"Prefer a guided setup? Open the Setup Wizard →"},legal:{navHome:"Home",navDashboard:"Dashboard",footerHome:"Home",footerTerms:"Terms",footerPrivacy:"Privacy",footerRefund:"Refund Policy",footerCopyright:"© 2026 RacoLab. All rights reserved."},authCallback:{authFailed:"Authentication Failed",backToLogin:"Back to Login",completing:"Completing authentication...",noTokenError:"No access token received"},cliAuth:{title:"ADHDev CLI Authentication",verifying:"Verifying...",authorizeAs:"Authorize CLI as {{name}}?",noCodeError:"No authentication code provided.",approve:"✓ Approve",signInFirst:"Please sign in first to authorize the CLI.",signIn:"Sign In →",failed:"Failed",successMessage:"CLI authentication complete!",returnToTerminal:"You can return to the terminal.",registryPublishTitle:"Authorize Registry Publishing",authorizeRegistryPublishAs:"Grant provider registry publishing access as {{name}}?",registryPublishWarning:"This grants a short-lived token (15 minutes) that can publish, promote and yank provider packages in the registry. It is not a daemon registration. Only approve this if you started a registry publish yourself. Requires an admin account.",signInFirstRegistryPublish:"Please sign in with an admin account to authorize registry publishing.",approving:"Approving…",errorFriendly:"Couldn't complete CLI authorization.",tryAgain:"Try again"},privacy:{title:"Privacy Policy",lastUpdated:"Last updated: September 27, 2026",intro:'This Privacy Policy describes how RacoLab ("we", "us", "our") collects, uses, and protects your information when you use the ADHDev service ("Service") at',s1Title:"1. Information We Collect",s1h1:"1.1 Account Information",s1p1:"When you create an account, we collect information provided by your authentication provider (GitHub or Google), including your name, email address, and profile picture.",s1h2:"1.2 IDE & Agent Data",s1p2:"When you connect your development environment to the Service, the local daemon may transmit:",s1l1:'IDE type and version (e.g., "Cursor 0.49.1")',s1l2:"Active AI agent information (name, status, current model)",s1l3:"Chat messages between you and AI agents",s1l4:"IDE screenshots (transmitted via P2P, not stored on our servers)",s1l5:"Workspace paths and open file names",s1l6:"Machine information (hostname, OS, memory usage)",s1h3:"1.3 Usage Data",s1p3:"We automatically collect usage information including API calls, feature usage patterns, and connection logs for service improvement and debugging purposes.",s1p3Attribution:"We also count visits by traffic source in aggregate only (campaign tags such as utm_source, the referring website's domain and the landing page, kept in your browser's local storage — no IP address, device identifier or cookie), and when you create an account we record the source of your first visit so we can see which channels bring new users.",s1h4:"1.4 Payment Information",s1p4:"Payment processing is handled entirely by our Merchant of Record, Paddle (Paddle.com Market Limited). We do not directly collect or store credit card numbers, bank account details, or other financial information. Please refer to",s1p4PaddleLink:"Paddle's Privacy Policy",s1p4Suffix:"for their data handling practices.",s2Title:"2. How We Use Your Information",s2p1:"We use collected information to:",s2l1:"Provide and maintain the Service",s2l2:"Authenticate your identity and manage your account",s2l3:"Route commands and data between your dashboard and connected machines",s2l4:"Send notifications (browser and push) about agent status changes",s2l5:"Process billing and subscription management (via Paddle)",s2l6:"Detect and prevent abuse or unauthorized access",s2l7:"Improve the Service and develop new features",s2l8:"Respond to support requests",s3Title:"3. Data Storage & Security",s3h1:"3.1 Infrastructure",s3p1:"Our Service runs on Cloudflare's global network using Cloudflare Workers, Durable Objects, and D1 Database. Data is stored in Cloudflare's infrastructure and is subject to",s3p1CloudflareLink:"Cloudflare's Privacy Policy",s3h2:"3.2 P2P Data",s3p2:"IDE screenshots and real-time terminal data are transmitted directly between your browser and your machine via WebRTC peer-to-peer connections. This data does not pass through or get stored on our servers.",s3h3:"3.3 Security Measures",s3p3:"We implement the following security measures:",s3l1:"JWT-based authentication with short-lived access tokens and refresh token rotation",s3l2:"Encrypted WebSocket connections (WSS/TLS)",s3l3:"Per-connection tokens for daemon authentication",s3l4:"Rate limiting on all API endpoints",s3l5:"Audit logging for security-sensitive operations",s4Title:"4. Data Sharing",s4p1:"We do not sell your personal data to third parties. We may share data with:",s4l1:"Payment processing as Merchant of Record",s4l2:"Infrastructure provider (hosting, CDN, database)",s4l3Label:"Authentication providers",s4l3:"GitHub/Google for OAuth login",s4p2:"We may disclose data if required by law, legal process, or to protect our rights and the safety of our users.",s5Title:"5. Data Retention",s5p1:"We retain your account data for the duration of your active account. Chat messages and agent activity data are retained for up to 90 days for service functionality.",s5p2:"Upon account deletion, we will remove your personal data within 30 days. Some anonymized usage data may be retained for analytical purposes.",s6Title:"6. Your Rights",s6p1:"You have the right to:",s6l1Label:"Access",s6l1:"Request a copy of your personal data",s6l2Label:"Correction",s6l2:"Update or correct your personal information",s6l3Label:"Deletion",s6l3:"Request deletion of your account and associated data",s6l4Label:"Export",s6l4:"Download your data in a portable format",s6l5Label:"Object",s6l5:"Object to certain data processing activities",s6p2:"To exercise these rights, contact us at",s7Title:"7. Cookies",s7p1:"We use essential cookies only for authentication (session tokens) and user preferences (theme, notification settings). We do not use advertising or tracking cookies.",s8Title:"8. Children's Privacy",s8p1:"The Service is not intended for users under the age of 16. We do not knowingly collect personal information from children under 16.",s9Title:"9. International Data Transfers",s9p1:"Your data may be processed in various locations through Cloudflare's global network. By using the Service, you consent to the transfer and processing of your data in these locations.",s10Title:"10. Changes to This Policy",s10p1:"We may update this Privacy Policy from time to time. We will notify you of any material changes by email or through the Service. Your continued use after changes constitutes acceptance of the updated policy.",s11Title:"11. Contact",s11p1:"For questions about this Privacy Policy or data practices:",s11l1Prefix:"Email:",s11l2Prefix:"Website:"},terms:{title:"Terms of Service",lastUpdated:"Last updated: April 11, 2026",intro:'Welcome to ADHDev ("Service"), operated by RacoLab ("we", "us", "our"). By accessing or using our Service at',introSuffix:'you agree to be bound by these Terms of Service ("Terms"). If you do not agree, do not use the Service.',s1Title:"1. Service Description",s1p1:"ADHDev is a cloud developer tool that provides remote monitoring and control of AI coding agents (such as Cursor, VS Code, Antigravity, Claude Code, and others) through web and mobile dashboard surfaces. The Service includes a local daemon, remote dashboards, REST API access, and browser and push notifications.",s2Title:"2. Account Registration",s2p1:"You must create an account to use the Service. You are responsible for maintaining the confidentiality of your account credentials. You agree to provide accurate and complete information during registration and to keep your account information up to date.",s2p2:"You must be at least 16 years old to use the Service. By creating an account, you represent that you meet this age requirement.",s3Title:"3. Subscription Plans & Billing",s3p1:"The Service offers the following plans:",s3l1:"Limited features, 1 connected machine",s3l2:"2 connected machines, unlimited agents, P2P remote view, 7-day free trial",s3l3:"5 connected machines, everything in Pro plus higher concurrency and usage limits (flat price, not per-seat)",s3p2:"Paid subscriptions are billed in advance on a monthly or yearly basis. All payments are processed by our payment partner, Paddle (Paddle.com Market Limited), who acts as the Merchant of Record for all transactions.",s4Title:"4. Refund Policy",s4p1:"We offer a 14-day money-back guarantee for all paid plans. If you are not satisfied with the Service, you may request a full refund within 14 days of your initial purchase by contacting us at",s4p2:"Refunds for renewals are handled on a case-by-case basis. Paddle's refund policies also apply as they are the Merchant of Record.",s5Title:"5. Acceptable Use",s5p1:"You agree not to:",s5l1:"Use the Service for any unlawful purpose or in violation of any applicable laws",s5l2:"Attempt to gain unauthorized access to other users' accounts or data",s5l3:"Reverse-engineer, decompile, or attempt to extract the source code of the Service's server components",s5l4:"Use the Service to transmit malware, spam, or other harmful content",s5l5:"Resell or redistribute the Service without our written consent",s5l6:"Interfere with or disrupt the integrity or performance of the Service",s6Title:"6. Intellectual Property",s6p1:"The Service, including its original content, features, and functionality, is owned by RacoLab and is protected by applicable intellectual property laws. The local daemon component is available under an open-source license as specified in the project repository.",s6p2:"You retain ownership of all data and content you transmit through the Service.",s7Title:"7. Data & Privacy",s7p1:"Your use of the Service is also governed by our",s7PrivacyLink:"Privacy Policy",s7p1Suffix:"The Service processes IDE interactions, chat messages, and screenshots for the purpose of remote monitoring and control. We do not sell your data to third parties.",s8Title:"8. Service Availability",s8p1:"We strive to maintain high availability but do not guarantee uninterrupted access. The Service may be temporarily unavailable due to maintenance, updates, or circumstances beyond our control. We are not liable for any losses resulting from service interruptions.",s9Title:"9. Limitation of Liability",s9p1:"TO THE MAXIMUM EXTENT PERMITTED BY LAW, RacoLab SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR ANY LOSS OF PROFITS OR REVENUES, WHETHER INCURRED DIRECTLY OR INDIRECTLY, ARISING OUT OF YOUR USE OF THE SERVICE.",s9p2:"Our total liability for any claim arising from the Service shall not exceed the amount you paid us in the 12 months preceding the claim.",s10Title:"10. Termination",s10p1:"We may suspend or terminate your access to the Service at any time for violations of these Terms or for any other reason at our sole discretion. You may cancel your account at any time through the Settings page. Upon cancellation, your data will be deleted within 30 days.",s11Title:"11. Changes to Terms",s11p1:"We reserve the right to modify these Terms at any time. We will notify you of material changes via email or through the Service. Your continued use after changes constitutes acceptance of the modified Terms.",s12Title:"12. Governing Law",s12p1:"These Terms shall be governed by and construed in accordance with the laws of the Republic of Korea, without regard to conflict of law provisions.",s13Title:"13. Contact",s13p1:"If you have any questions about these Terms, please contact us:",s13l1Prefix:"Email:",s13l2Prefix:"Website:"},refund:{title:"Refund Policy",lastUpdated:"Last updated: March 24, 2026",intro:"ADHDev is operated by RacoLab. All payments are processed by our Merchant of Record,",introSuffix:"who manages billing, invoicing, and refunds on our behalf.",s1Title:"1. 14-Day Money-Back Guarantee",s1p1:"We offer a 14-day money-back guarantee on all paid plans (Pro). If you are not satisfied with the Service for any reason, you may request a full refund within 14 days of your initial subscription purchase.",s1p2:"To request a refund, contact us at",s1p2Suffix:"with your account email and order details. We will process your request within 3 business days.",s2Title:"2. Renewal Refunds",s2p1:"Refunds for subscription renewals (monthly or yearly) are handled on a case-by-case basis. If you were charged for a renewal you did not intend, please contact us within 7 days of the charge at",s3Title:"3. Non-Refundable Cases",s3p1:"Refunds will not be issued for:",s3l1:"Requests made after the 14-day guarantee period for initial purchases",s3l2Prefix:"Accounts suspended or terminated due to violations of our",s3l2Link:"Terms of Service",s3l3:"Partial months of service already used beyond the refund window",s4Title:"4. How Refunds Are Processed",s4p1:"Approved refunds are processed through Paddle and returned to the original payment method. Depending on your bank or card issuer, refunds may take 5–10 business days to appear. Paddle's own",s4p1RefundLink:"refund terms",s4p1Suffix:"also apply.",s5Title:"5. Cancellation",s5p1Prefix:"You may cancel your subscription at any time from the",s5p1BillingLink:"Billing",s5p1Suffix:"page in your dashboard. Cancellation stops future charges. You retain access to your plan's features until the end of the current billing period. Cancellation alone does not trigger a refund.",s6Title:"6. Contact",s6p1:"For refund requests or billing questions:",s6l1Prefix:"Email:",s6l2Prefix:"Website:"},sessionShare:{loading:"Loading session...",sessionNotFound:"Session Not Found",noLongerAvailable:"This session is no longer available",homeBtn:"← ADHDev Home",sharedSession:"Shared Session",host:"Host",mode:"Mode",permission:"Permission",auth:"Auth",authRequired:"Account required",viewers:"Viewers",joinChat:"Join Chat",joinSession:"Join Session",expires:"Expires: {{date}}",chatLabel:"Chat",remoteLabel:"Remote",waitingMessages:"Waiting for messages...",connecting:"Connecting... ({{state}})",sendMessageAs:"Send message as {{name}}...",sendAs:"Send as {{name}}...",ownerChat:"{{name}}'s Chat",ownerSession:"{{name}}'s Session",agentName:"{{name}}'s Agent",fullControlBadge:"Full Control Active",failedToJoin:"Failed to join session",sessionRevoked:"Session has been revoked by the host",sessionExpired:"Session has expired",authRequired2:"Authentication required for control share",unknownError:"Unknown error"},apiPlayground:{title:"API Playground",history:"History ({{count}})",apiRelayWarning:"Daemon API relay is opt-in. REST command/chat proxy routes stay disabled unless that daemon explicitly enables them with `adhdev daemon:api enable`.",authBearer:"Authorization: Bearer {{key}}",copyAsCurl:"cURL",copied:"Copied",targetDaemon:"Target Daemon",quickActions:"Quick Actions",requestBody:"Request Body (JSON)",recentRequests:"Recent Requests",clearHistory:"Clear",noDaemonsWarning:"No daemons connected. Start a daemon first or replace {daemonId} manually.",send:"▶ Send",sending:"⏳"},announcementBanner:{visibleUntil:"Visible until {{time}}",dismiss:"Dismiss"},push:{budgetResetsShort:"Resets at {{time}}",budgetRemainingShort:"{{count}} left on your plan today",budgetShort:"{{used}}/{{limit}} today",title:"Push Notifications",descUnsupported:"Not supported in this browser",descDenied:"Blocked — enable in browser settings",descEnabled:"On",descDefault:"Alerts even when the tab is closed",docsLink:"Push Notifications docs",sent:"Sent",test:"Test",iosHint:"On iPhone and iPad, push only works from the installed Safari PWA. A normal Safari tab cannot receive ADHDev push notifications.",unsupportedWarning:"This browser does not support Web Push here. Use Safari PWA on iPhone/iPad or a Chromium browser on desktop/Android.",deniedWarning:"Notifications are blocked in browser or site settings. Re-enable them there, then turn Push Notifications on again.",registeredDevices:"Registered devices: {{count}}",noDevices:"No active push devices found.",deviceLabel:"Device {{number}}",thisDevice:"This device",lastActive:"Last active",removing:"Removing...",removeHere:"Remove here",remove:"Remove"},mesh:{manualMcpSetup:"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",couldNotLoadMeshes:"Could not load meshes",untitledMesh:"Untitled mesh",chooseMachineFirst:"Choose a machine first.",launchFailed:"Launch failed",coordinatorLaunchFailed:"Coordinator launch failed",coordinatorLaunched:"Coordinator launched ({{sessionId}})",coordinatorLaunchSent:"Coordinator launch command sent"},plans:{free:"Free",pro:"Pro",ultra:"Ultra",team:"Team",enterprise:"Enterprise"},adminAudit:{title:"Global Audit",subtitle:"System-wide event tracking",allActions:"All Actions",allSources:"All Sources",filter:"Filter",noLogs:"No logs found",loading:"Loading...",loadMore:"Load More ↓"},adminDashboard:{failedToLoad:"Failed to load admin data",title:"Admin Dashboard",subtitle:"Service overview & management",accessDenied:"Admin access denied",backToDashboard:"Back to Dashboard",loading:"Loading admin dashboard",loadingDesc:"Collecting service stats and recent audit activity.",totalUsers:"Total Users",todayCommands:"Today Commands",activeApiKeys:"Active API Keys",todayLogins:"Today Logins",planDistribution:"Plan Distribution",quickActions:"Quick Actions",manageUsers:"Manage Users",apiKeys:"API Keys",auditLogs:"Audit Logs",systemConfig:"System Config",recentActivity:"Recent Activity",viewAll:"View All",noRecentActivity:"No recent activity"},adminTokens:{title:"Admin Tokens",subtitle:"Issue admin-scoped API tokens for deploy automation",superAdminOnly:"Super admin only",superAdminOnlyDesc:"Only a super admin can issue admin tokens. Ask a super admin if you need one.",issueTitle:"Issue a new token",nameLabel:"Name",namePlaceholder:"e.g. deploy-ci",scopesLabel:"Scopes",scopesHint:"admin covers most admin APIs. super_admin also allows issuing tokens and changing roles — grant it only when required.",expiryLabel:"Expires in",expiryDays:"{{count}} days",expiryHint:"Admin tokens always expire. The server caps the lifetime at 90 days.",issue:"Issue token",issuing:"Issuing...",issuedTitle:"Copy your token now",issuedWarning:"This is the only time the token is shown. Store it somewhere safe — you cannot retrieve it again.",issuedMeta:"Scopes: {{scopes}} · Expires: {{expiresAt}}",copy:"Copy",copied:"Copied",copyFailed:"Copy failed — select the token and copy it manually",dismiss:"Dismiss",expiryClamped:"Expiry was shortened to the 90-day maximum",existingTitle:"Active admin tokens",emptyTitle:"No admin tokens",emptyDesc:"Issue one above to authenticate deploys without the browser login.",expiresAt:"Expires: {{time}}",lastUsed:"Last used {{time}}",neverUsed:"Never used",noExpiry:"No expiry",expired:"Expired",revoke:"Revoke",revokeConfirm:'Revoke the token "{{name}}"? Anything using it will stop working immediately.',revoked:"Token revoked",loading:"Loading...",error:"Error: {{message}}"},adminSystem:{error:"Error: {{message}}",announcementSent:"Announcement sent",announcementCleared:"Announcement cleared",title:"System Settings",subtitle:"Announcements & system configuration",loading:"Loading system settings",loadingDesc:"Fetching current announcement state.",announcement:"Announcement",current:"Current:",untilTime:"(until {{time}})",untilCleared:"(until cleared)",announcementPlaceholder:"Enter announcement message...",severityInfo:"Info",severityWarning:"Warning",severityCritical:"Critical",duration1h:"1 hour",duration6h:"6 hours",duration24h:"24 hours",duration7d:"7 days",durationUntilCleared:"Until cleared",send:"Send"},adminUsers:{error:"Error: {{message}}",roleUpdated:"Role updated",planUpdated:"Plan updated",suspensionReasonPrompt:"Enter suspension reason:",userSuspended:"User suspended",userUnsuspended:"User unsuspended",title:"User Management",subtitle:"Manage users, roles, and suspension",usersTotal:"users total",searchPlaceholder:"Search email or name...",allRoles:"All Roles",roleUser:"User",roleAdmin:"Admin",roleSuperAdmin:"Super Admin",allPlans:"All Plans",search:"Search",colUser:"User",colRole:"Role",colPlan:"Plan",colStatus:"Status",colCreated:"Created",colActions:"Actions",noName:"No name",statusSuspended:"Suspended",statusActive:"Active",unsuspend:"Unsuspend",suspend:"Suspend",loading:"Loading...",prev:"← Prev",next:"Next →"}},pk={onboardingTour:{next:"Next",getStarted:"Get started",learnMore:"Learn more in the docs",closeAria:"Close onboarding",allSetStandalone:{desc:"This dashboard is already connected to your local daemon. Start a session from the Dashboard tab, or add more providers under Machines → Providers.",title:"You're all set"},getStartedCloud:{desc:"Run this on any machine you want to drive, then sign in — the daemon pairs itself to your dashboard automatically.",title:"Get started"},orchestrate:{desc:"Repo Mesh (Cloud Pro) lets one coordinator hand work to agents across many machines — parallel git worktrees, automatic branch convergence, and cross-checking the same repo from several angles.",title:"Orchestrate your agents"},watchAndSteer:{desc:"Follow each agent's session in real time and steer it as it works — switch sessions, take screenshots, and (for IDE sessions) view and control the screen over a direct connection.",title:"Watch and steer, live"},realtimeChat:{desc:"See what your AI agent is doing in real time. Send messages, approve or reject actions — all from your browser or phone.",title:"Real-time chat"},welcome:{desc:"Drive any local CLI coding agent — Claude Code, Codex, Antigravity CLI — straight from your browser or phone. The agents keep running on your machine; you control them from the web.",title:"Welcome to ADHDev"}},installCommand:{orViaNpm:"Or via npm:",clickToCopy:"Click to copy"},errorBoundary:{reload:"Reload page",description:"An unexpected error occurred. Please reload the page to continue.",title:"Something went wrong"},shellFreshness:{dismissAria:"Dismiss update notice",later:"Later",reload:"Reload",message:"A new version of ADHDev is available."},dashboardWire:{reloadTitle:"Reload required",reloadBody:"This page is older than the daemon it talks to, so it cannot read the daemon's state. Reload to get the current dashboard.",reload:"Reload",daemonUpdateTitle:"Daemon update required",daemonUpdateBody:"{{count}} machine(s) run an older daemon this dashboard cannot read. Update them with `adhdev update` (or the machine page's update action)."},openMenu:"Open menu",closeMenu:"Close menu"},fk={loadingOlderMessages:"Loading older messages...",waitingForMessages:"Waiting for messages...",agentGenerating:"Agent generating...",jumpToTop:"Jump to top",jumpToOldestMessages:"Jump to oldest messages",top:"↑ Top",latest:"↓ Latest",jumpToLatestMessages:"Jump to latest messages",jumpToBottom:"Jump to bottom",showEarlierMessages:"↑ Show {{count}} earlier messages...",showEarlierMessagesHidden:"↑ Show {{count}} earlier messages... ({{total}} hidden)",loadOlderMessages:"↑ Load older messages",loadErrorRetry:"↻ {{error}}"},bk={zoomOut:"Zoom Out",zoomIn:"Zoom In",resetZoom:"Reset Zoom",toggleFullscreen:"Toggle Fullscreen"},gk={screenshotAlt:"Remote View",mouse:"Mouse",touch:"Touch",connected:"Connected",ws:"Reconnecting",direct:"Direct",relay:"Relay",turnBlocked:"Daily view limit reached",turnUsage:"View {{used}}/{{budget}}m",typeAndEnter:"Type & Enter...",settings:"SETTINGS",zoom:"ZOOM:",fill:"FILL",fit:"FIT",directP2PTitle:"Direct P2P connection",turnRelayTitle:"TURN relay in use",dailyTurnTitle:"Remote view minutes used today (plan limit)",waitingState:{turnRelayActive:"TURN relay active"},waiting:{connectedLabel:"Connected. Waiting for first frame...",connectingLabel:"Connecting to Host...",reconnectingLabel:"Reconnecting to Host...",connectedHint:"The remote stream is warming up",reconnectingHint:"Waiting for the remote stream to catch up"},error:{title:"Remote connection lost",reasonFailed:"The connection to this host failed. Check that the daemon is running and try again.",reasonDisconnected:"Lost connection to the host and could not reconnect after 15 seconds.",retry:"Retry"},screenshotViewer:{altText:"IDE Screenshot",waitingForStream:"Waiting for screenshot stream...",p2pStatus:"P2P: {{state}}"}},xk={openChat:"Open chat",openCoordinatorChat:"Open coordinator chat",coordinatorGone:"coordinator session ended",chatNotFound:"No chat tab for this session on this dashboard — it may be running on another machine.",openChatHint:"Click to open this session’s chat"},yk={meshNodeUnavailable:"Mesh node info unavailable",roleCoordinator:"Mesh coordinator",rowProviderType:"Provider type",rowStarted:"Started",copyDiagnostics:"Copy diagnostics",gitClean:"clean",gitDirty:"uncommitted changes",gitDetached:"(detached)",blockRawMetadata:"Raw runtime metadata",blockFinalPrompt:"Final system prompt",blockExtraPrompt:"Extra prompt for this launch",quotaOkNoWindows:"No limit",sectionMeshWorker:"Spawned by coordinator",rowMeshId:"Mesh ID",rowTaskId:"Task",rowCoordinator:"Coordinator",title:"Session info",loading:"Loading…",close:"Close",failedToLoad:"Failed to load session info",stampedToNode:"This session is stamped to a mesh node that the coordinator no longer reports.",sectionSession:"Session",sectionLaunch:"Launch",sectionMeshNode:"Mesh node",sectionMeshCoordinator:"Mesh coordinator",sectionRuntime:"Runtime",rowSessionId:"Session ID",rowProvider:"Provider",rowTransport:"Transport",rowWorkspace:"Workspace",rowSpawnedAt:"Spawned at",rowProviderSessionId:"Provider session ID",rowMachine:"Machine",rowConnection:"Connection",rowCommand:"Command",rowWorkingDirectory:"Working directory",rowArgs:"Args",rowExtraArgs:"Extra args",rowExtraEnv:"Extra env",rowNodeId:"Node ID",rowRepoRoot:"Repo root",rowDaemonId:"Daemon ID",rowRole:"Role",rowMachineStatus:"Machine status",rowHealth:"Health",rowWorktree:"Worktree",rowLaunchReady:"Launch ready",rowGit:"Git",rowProviders:"Providers",rowProviderPriority:"Provider priority",rowCoordinatorCli:"Coordinator CLI",rowStartedAt:"Started at",rowPromptInjection:"Prompt injection",rowMcpConfig:"MCP config",rowRuntimeId:"Runtime ID",rowLifecycle:"Lifecycle",rowSurface:"Surface",rowRecoveryState:"Recovery state",rowRestoredFromStorage:"Restored from storage",rowAttachedClients:"Attached clients"},vk={mobile:{noHistoryMatches:"No saved history matches these filters.",workspaceMissing:"(workspace missing)",resumableOnly:"Only ones that can be resumed",sortMessages:"Most messages",sortOldest:"Oldest first",sortRecent:"Most recent",filterModel:"Filter by model",filterWorkspace:"Filter by workspace",searchHistory:"Search title or preview",useThisFolder:"Use this folder",browseDescription:"Move through folders like a normal file browser, then use the current folder for this machine.",browseTitle:"Select workspace",machineDetails:"Machine details",inspect:"Inspect",showMore:"Show {{count}} more",showFewer:"Show fewer",recentLaunches:"Recent launches",currentChats:"Current chats",machineFallback:"machine"},daemonUpdate:{previewUnknownDescription:"The app is connected to preview, but the server hasn't reported a preview target version yet.",previewUpToDateDescription:"This machine already runs the current preview daemon.",previewUnknownTitle:"Preview update status unknown",previewUpToDateTitle:"Preview daemon is up to date",mismatchDescription:"This machine runs a different daemon version than the current app. Update it before starting more sessions.",previewUpgradeDescription:"This machine can be updated to the current preview daemon without opening a remote shell.",requiredDescription:"This machine is on an incompatible daemon version. Update it before starting more sessions.",mismatchTitle:"Version mismatch detected",requiredTitle:"Daemon update required",upgrade:"Update",updateNow:"Update now"},launchPick:{empty:"No saved workspaces yet. Add one in the Workspace tab or type a path above.",description:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path.",title:"Where should this run?"},trustBadge:{externalUntrustedHint:"From a source you added, and it includes code that ADHDev will run. Review the source before enabling.",externalSafeHint:"From a source you added. Settings only — ADHDev never runs code from it.",trustedWithScriptsHint:"Provided officially by ADHDev. Includes scripts that ADHDev runs.",trustedHint:"Provided officially by ADHDev. Settings only — no provider code runs.",userCustomHint:"You wrote this provider in your own providers folder. It runs your own code.",externalUntrusted:"External · runs code",externalSafe:"External",trustedWithScripts:"Official · scripts",trusted:"Official",userCustom:"Custom"},providerSettings:{option:{high:"High",medium:"Medium",low:"Low"},notifications:{description:"Show notifications when {{provider}} changes state.",label:"Notifications"},showCoordinatorSystemPrompt:{description:"Show the injected system prompt as a message in the chat. Off by default — you can always see it in the chat header's Session Info (ⓘ).",label:"Show system prompt message"},showTerminal:{description:"Show terminal commands and their output in the chat.",label:"Show terminal"},showToolCalls:{description:"Show short summaries of tool calls (searched, edited, …) in the chat.",label:"Show tool calls"},showThinking:{description:"Show the agent's reasoning in the chat.",label:"Show thinking"},longGeneratingThresholdSec:{description:"How long a reply can run before the long-running alert fires.",label:"Long-running threshold (seconds)"},longGeneratingAlert:{description:"Notify you when a reply takes unusually long.",label:"Long-running alert"},approvalAlert:{description:"Notify you when {{provider}} is waiting for your approval.",label:"Approval notifications"},appPathOverride:{description:"Optional full path to the IDE app. Leave blank to look in the usual install locations.",label:"App path"},cliPathOverride:{description:"Optional full path to the IDE command-line launcher. Leave blank to use the detected one.",label:"CLI launcher path"},executableArgs:{description:"Optional arguments that replace the default ones when {{provider}} starts. Leave blank to use the defaults.",label:"Launch arguments"},executablePath:{description:"Optional full path to the {{provider}} program. Leave blank to find it on your PATH.",label:"Executable path"},autoApprove:{description:"Approve {{provider}} tool calls and prompts automatically, without asking you first.",label:"Auto approve"},enabled:{description:"Turn this on before ADHDev detects, launches, or checks {{provider}} on this machine.",label:"Enabled on this machine"},thisProvider:"this provider"},launchConfirm:{workspace:"Workspace",languageModel:"Language Model (Optional)",autoDetect:"Auto-detect or default",cliArgs:"CLI Arguments (Optional)",cliArgsPlaceholder:"e.g. --experimental",cancel:"Cancel",closeAria:"Close launch confirmation",launch:"Launch",launching:"Launching…"},confirmExternal:{aboutToActivateFrom:"You're about to turn on {{provider}} from {{source}}.",aboutToActivate:"You're about to turn on {{provider}}.",dialogAria:"Confirm untrusted external provider",title:"Activate untrusted external provider?",description:"This manifest ships JavaScript that the daemon will execute. Treat as untrusted code — review the source before enabling.",proceedWarning:"Only proceed if you trust the source URL you added and have reviewed the manifest.",cancel:"Cancel",activate:"Activate"},providers:{advancedHint:"Sources, load paths and provider details",filter:"Filter",sourceConfigTitle:"Provider source config",sourceConfigDesc:"Where the daemon looks for provider manifests. Affects resolution and reloads.",sourceMode:"Source mode",explicitProviderDir:"Explicit providerDir",providerDirPlaceholder:"Leave blank to use ~/.adhdev/providers",applying:"Applying…",applyReload:"Apply + Reload",userRoot:"User root:",upstreamRoot:"Upstream root:",providerRoots:"Provider roots:",loadingSettings:"Loading provider settings…",noProviders:"No providers installed yet — use Install above, or add a source under Advanced.",noFilteredProviders:"No {{filter}} providers installed.",refresh:"Refresh",updateAll:"Update all",advanced:"Advanced",newChannelTypesTitle:"Available to install",newChannelTypesDesc:"Published to the verified channel but never installed on this machine. Install activates the digest-verified bundle.",installNewType:"Install",modelListTitle:"Model lists",modelListStaleDesc:"Could not read the model list from these CLIs (signed out, offline, or unsupported output). The provider manifest's list is being used and may be out of date.",modelListStaleBadge:"unverified",installFailedTitle:"Install failed",installFailedDigestMismatch:"Install failed — try later",loadFailed:"Failed to load provider settings: {{error}}",quotaToggleFailed:"Failed to update quota probe for {{provider}}: {{error}}"},sourcesPanel:{title:"External sources",description:"3rd-party git URLs you've added. Providers here may ship JavaScript the daemon will execute — activation requires a confirmation.",addSource:"+ Add source",empty:'No external sources registered. Use "+ Add source" to register a 3rd-party provider git URL.',remove:"Remove",removing:"…",removeConfirmTitle:"Remove provider source {{name}}?",removeConfirmDescription:"This deletes the cloned manifests and clears any active-source entries that pointed here.",removeConfirmLabel:"Remove",conflictsTitle:"Conflicts",conflictsDescription:"Multiple sources expose the same provider type. Pick which source's copy should be active.",active:"Active",switchActiveTo:"Switch active to {{name}}",addTitle:"Add external source",gitUrl:"Git URL",ref:"Ref (branch/tag)",name:"Name (optional, auto-derived from URL)",cancel:"Cancel",cloning:"Cloning…",cloneAndRegister:"Clone + register",loadFailed:"Failed to load sources",addFailed:"Failed to add source",removeFailed:"Failed to remove source",setActiveFailed:"Failed to set active source"},providerRow:{detectDisabledHint:"Turn the provider on before checking it",detectHint:"Check that the configured program can be found and run",lifecycleDeprecated:"No longer supported",lifecycleExperimental:"Experimental",lifecycleBeta:"Beta",lifecycleStable:"Stable",checkFailed:"Failed",checkOk:"OK",statusDetected:"Detected",statusNotDetected:"Not detected",statusEnabledUnchecked:"Enabled (unchecked)",statusDisabled:"Disabled",labelType:"Type:",labelVersion:"Version:",labelBinary:"Binary:",labelStatus:"Status:",labelDetails:"Details:",labelSource:"Source:",labelTrust:"Trust:",labelLinks:"Links:",labelDetection:"Detection:",labelVerification:"Verification:",saving:"saving…",disable:"Disable",enable:"Enable",detect:"Detect",resetCommand:"Reset command",quotaAccountLabel:"Show account on quota",quotaAccountLabelHint:"Label this provider's plan quota with the signed-in account. Off means the account is never fetched, not just hidden.",quotaAccountLabelOn:"On",quotaAccountLabelOff:"Off",quotaTracking:"Quota tracking",quotaTrackingHint:"Periodically read this provider's plan quota for the dashboards. Off stops the reads entirely.",quotaTrackingOn:"On",quotaTrackingOff:"Off",quotaClaudeConfirmTitle:"Enable Claude quota tracking?",quotaClaudeConfirmBody:"Claude Code has no quota API, so ADHDev reads usage through its statusLine — the only path available. Enabling replaces the statusLine command in ~/.claude/settings.json with the ADHDev wrapper. Your existing command keeps running inside the wrapper and its output is passed through unchanged, so your prompt looks the same. No other setting in the file is modified. The current value is backed up first and can be restored with `adhdev quota claude:uninstall`.",quotaClaudeConfirmOk:"Enable and install",quotaClaudeConfirmCancel:"Cancel",labelSpecPin:"Spec pin:",labelActivatedAt:"Activated:",labelPreviousPin:"Previous pin:",labelDigest:"Digest:",specPinStale:"update {{latest}}",specPinStaleHint:"This machine loads an older spec. Channel offers {{latest}}.",updateInline:"Update",updateInlineHint:"Channel offers {{latest}}. Download, verify and activate it on this machine.",specPinUpdating:"Updating…",specPinRollback:"Roll back",specPinRollbackHint:"Return to spec {{version}} (local, no download).",specPinRollingBack:"Rolling back…"},installOptions:{title:"Set up {{provider}}",quotaLabel:"Track plan usage",quotaHint:"Periodically read this provider's plan quota so the dashboards and `adhdev quota` can show what's left. Off stops the reads entirely — nothing is collected.",quotaClaudeNote:"Claude Code has no quota API, so this installs the ADHDev statusLine wrapper into ~/.claude/settings.json. Your existing command keeps running inside it, and the original is backed up.",autoApproveLabel:"Approve tool calls automatically",autoApproveHint:"When this agent asks permission to run a command, edit a file or use a tool, ADHDev answers yes for you. You will not see the approval prompt, and the action runs without waiting.",autoApproveWarning:"The agent can run commands on this machine without asking you first. Turn this off to approve each one yourself.",cancel:"Cancel",confirm:"Enable provider"},card:{status:{offline:"Offline",failed:"Connection failed",connecting:"Connecting…",online:"Online"},slowLink:"Slow link",coresCount_other:"{{count}} cores",coresCount_one:"{{count}} core",onMachine:"on {{machine}}",sectionIDEs:"IDEs",sectionCLIs:"CLIs",cpu:"CPU",mem:"MEM",loading:"Loading your machines…",emptyHeadline:"Welcome to ADHDev",emptyBody:"Connect your first machine to the dashboard. Install ADHDev on that machine and sign in — it pairs automatically and appears here:",emptyDocsLink:"Read the documentation →",hidden:"Hidden",pageTitle:"Machines",burrowCount_one:"{{count}} machine",burrowCount_other:"{{count}} machines",onlineCount_one:"{{count}} online",onlineCount_other:"{{count}} online",agentsActive_one:"{{count}} agent active",agentsActive_other:"{{count}} agents active",activeNow:"Active Now",generating:"generating",connectionFailed:"Connection failed",reconnect:"Reconnect",transportRelay:"Connected through a relay server — slower than a direct link. Usually a firewall or NAT blocks the direct path.",transportDirect:"Direct connection",noAgentsRunning:"No agents running yet",launchCta:"Launch →"},detail:{relaunchFailed:"Couldn't relaunch",launchProvider:"Provider",launchType:"Type",tabsAriaLabel:"Machine sections",tabSessions:"Sessions",notFound:"Machine not found",save:"Save",cancel:"Cancel",loading:"Loading machine...",offlineHint:"The machine may be offline or not yet connected.",back:"← Back",tabHostedRuntimes:"Hosted Runtimes",tabProviders:"Providers",tabSystem:"System",tabLogs:"Logs",clickToSetNickname:"Click to set nickname",nicknamePlaceholder:"Machine nickname...",reconnect:"Reconnect",p2pConnected:"connected",providerUpdatesAvailable:"Provider updates available",providerSyncSuccess:"Provider channel synced — {{count}} updated",providerSyncAlreadyCurrent:"Provider channel is already current",providerSyncFailed:"Provider update failed"},commandCenter:{updateStatusUnknown:"Update status unknown",upToDate:"Up to date",updateDaemon:"Update daemon",updateToVersion:"Update to v{{version}}",updateChannel:{preview:"preview",stable:"stable"},updateTargetWithChannel:"Target: v{{version}} ({{channel}})",updateTarget:"Target: v{{version}}",currentChats:"Current Chats",recentLaunches:"Recent Launches",daemonUpdate:"Daemon Update"},workspaceBrowse:{currentFolder:"Current folder",parent:"Parent",go:"Go",pathPlaceholder:"Type a folder path",loading:"Loading folders…",noSubfolders:"No subfolders here.",useThisFolder:"Use this folder"},managedWorkspaces:{setDefaultHint:"Set as default workspace",unsetDefaultHint:"Default workspace — click to unset",title:"Workspaces",addWorkspace:"Add workspace",empty:'No saved workspaces yet. Click "{{button}}" to pick a folder.',addDialogDescription:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",remove:"Remove",newSession:"Start a new session in this workspace",newSessionShort:"Session",newMeshSession:"Start a mesh coordinator session in this workspace",newMeshSessionShort:"Mesh",removeConfirmTitle:"Remove workspace",removeConfirmDescription:'Remove "{{label}}" from the list? The folder itself is not deleted.',rename:"Rename",renamePlaceholder:"Workspace name",saveName:"Save",cancelRename:"Cancel",renameFailed:"Could not update workspace name"},overview:{diagnostics:"Diagnostics",p2p:"P2P",daemonVersion:"Daemon version",cores:"CPU cores",platform:"Platform",hostname:"Hostname",aboutMachine:"This machine",approx:"(approx.)",memory:"Memory",cpuDetail:"{{load}} avg / {{cores}} cores",cpuLoad:"CPU load",resourceUsage:"Resource usage",waiting:"Waiting…",uptime:"Uptime",waitingForStats:"Waiting for live stats…",waitingForStatsWithTotal:"Waiting for live stats… · {{total}} total"},fleetQuota:{title:"Plan quota across machines",subtitle:"How much of each subscription's 5-hour and weekly window is left on every machine. The task queue skips plans that are nearly out and spends quota that would expire unused first.",machine:"Machine",unreadable:"unreadable"},quota:{text:{failureKind:{unknown:"unknown error","no-data":"no reading yet","setup-required":"setup required",unsupported:"not supported","cli-unavailable":"program not found",parse:"unreadable response",server:"provider server error",network:"network error","rate-limited":"rate limited","quota-exhausted":"plan limit reached",unauthorized:"access denied","expired-token":"sign-in expired","missing-credentials":"not signed in"},agoDays:"{{days}}d {{hours}}h ago",agoHours:"{{hours}}h {{minutes}}m ago",agoMinutes:"{{minutes}}m ago",justNow:"just now",unreadable:"could not read quota",unavailable:"not available on this machine",pool:"pool",usageSessions:"{{count}} sess",usageTokens:"{{count}} tok",windowReset:"reset · awaiting refresh",cue:{stale:"stale",refreshing:"refreshing"},resetsInDays:"resets in {{days}}d {{hours}}h",resetsInHours:"resets in {{hours}}h {{minutes}}m",resetsInMinutes:"resets in {{minutes}}m",resetsNow:"resets now",used:"{{percent}}% used"},title:"Plan quota",sessionHint:"Rolling 5-hour plan window reported by this machine",weeklyHint:"Rolling 7-day plan window reported by this machine",monthlyHint:"Rolling 30-day billing window reported by this machine",bucketHint:"Per-pool quota bucket reported by this machine — pools on one plan reset independently",failureHint:"This machine reported that it could not read this provider's quota",okNoWindows:"No limit",okNoWindowsHint:"The quota fetch succeeded; this provider reports no percentage window (e.g. included-usage plans).",accountHint:"The signed-in account this quota belongs to, as reported by the provider CLI",usageHint:"Absolute usage over the trailing window — this provider routes to your own upstream accounts, so there is no plan limit to show a percentage against."},actions:{nicknameSyncFailed:"Nickname updated on the machine, but account sync failed",nicknameFailed:"Couldn't save nickname",nicknameTimeout:"The machine didn't answer — check its connection and try again",nicknameSaved:"Nickname saved",pathMissing:"The path may be missing on disk",workspaceActionFailed:"Workspace update failed",workspaceAdded:"Workspace added",detectFailed:"IDE detection failed",usingDefaultWorkspace:"Using the default workspace",runningInHome:"Running in the home directory",launchPending:"{{name}} is starting — it will appear shortly",launchFailed:"Couldn't launch {{name}}",launching:"Launching {{name}}…",stopCliConfirmDescription:"This will terminate the process.",stopIdeConfirmDescription:"This will disconnect CDP and optionally kill the process.",stopped:"{{name}} stopped",launched:"{{name}} launched",stopFailed:"Couldn't stop",restartInitiated:"{{name}} restart initiated",restartFailed:"Couldn't restart",selectProviderFirst:"Select a CLI provider first",selectProvider:"Select a provider",workspaceRemoved:"Workspace removed",workspaceLabelUpdated:"Workspace name updated",defaultWorkspaceUpdated:"Default workspace updated",defaultWorkspaceCleared:"Default workspace cleared",idesFound_one:"Found {{count}} IDE",idesFound_other:"Found {{count}} IDEs"},logsTabSections:{view:"View",filterInfo:"Info+ ({{count}})",filterIssues:"Issues ({{count}})",filterAll:"All ({{count}})",searchPlaceholder:"Search diagnostics…",copyDiagnostics:"Copy diagnostics",copyVisible:"Copy visible",pause:"Pause",resume:"Resume",refresh:"↻ Refresh",clear:"Clear",advancedSourceScope:"Advanced source scope",daemonLevelPlus:"Daemon {{level}}+",diagnosticsTimeline:"Diagnostics timeline",visibleEventsIssues:"{{events}} visible event(s) · {{issues}} issue signal(s)",filteredBy:"Filtered by “{{query}}”",mergedByTime:"Daemon, trace, and browser signals merged by time",latestIssue:"Latest issue",noVisibleIssue:"No visible warn/error signal",sourceStatus:"Source status",needsAttention:"Needs attention",livePolling:"Live polling every 3s",paused:"Paused",lastUpdate:"Last update: {{time}}",notYetLoaded:"Not yet loaded",rawFile:"raw file",sourceDaemon:"daemon",sourceTrace:"trace",sourceBrowser:"browser",repeatedIssuePatterns:"Repeated issue patterns",unifiedTimeline:"Unified timeline",visibleDiagnosticEvents:"{{count}} visible diagnostic event(s)",hide:"Hide",show:"Show",loadingDiagnostics:"Loading diagnostics…",daemonLogsError:"Daemon logs: {{error}}",daemonTraceError:"Daemon trace: {{error}}",noDiagnosticsMatch:"No diagnostics match the current view.",rawSourceDaemonLogs:"Raw source · daemon logs",visibleRawLinesFallback:"{{count}} visible raw line(s) from file fallback",visibleStructuredLines:"{{count}} visible structured line(s)",loadingDaemonLogs:"Loading daemon logs…",noDaemonLogsYet:"No daemon logs captured yet for this machine.",noRawLinesMatchSearch:"No raw daemon log lines match the current search.",rawFallbackOnlyInAll:"Raw file-fallback logs are available only in All view.",noStructuredLogsMatch:"No structured daemon logs match the current view.",rawSourceDaemonTrace:"Raw source · daemon trace",sessionHostOnly:"session_host only",visibleTraceEvents:"{{count}} visible trace event(s)",loadingDaemonTrace:"Loading daemon trace…",noTraceEntriesMatchSearch:"No trace entries match the current search.",noSessionHostTraceYet:"No session host trace entries yet.",noTraceEntriesYet:"No trace entries yet.",noPayload:"No payload",rawSourceBrowserEvents:"Raw source · browser debug events",visibleBrowserEvents:"{{count}} visible browser event(s)",noBrowserEventsMatchSearch:"No browser debug events match the current search.",noBrowserEventsYet:"No browser debug events captured yet."}},wk={transition:{recover:"Recovered",detach:"Detached",attach:"Attached",start:"Started",stop:"Stopped",restart:"Restarted",resume:"Resumed"},lastErrorLabel:"Last error",endpointLabel:"Endpoint",activeAgo:"active {{time}}",title:"Hosted Runtime Recovery",stopConfirmTitle:"Stop {{name}}?",stopConfirmDescription:"This will terminate the hosted runtime.",pruneConfirmTitle:"Prune duplicate hosted runtimes?",pruneConfirmDescription:"The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.",prune:"Prune",pruning:"Pruning…",pruneDuplicatesCount:"Prune duplicates ({{count}})",toastResumed:"Session host resumed: {{name}}",toastRestarted:"Session host restarted: {{name}}",toastStopped:"Session host stopped: {{name}}",toastPruned:"Pruned {{pruned}} duplicate runtime(s) across {{groups}} group(s)",actionFailed:"Session host action failed",pruneFailed:"Duplicate prune failed",diagnosticsFailed:"Could not load hosted runtime diagnostics",diagnosticsAttention:"Hosted runtime diagnostics need attention",stop:"Stop",stopping:"Stopping…",restart:"Restart",restarting:"Restarting…",resume:"Resume",resuming:"Resuming…",recover:"Recover",recovering:"Recovering…",refresh:"Refresh",refreshing:"Refreshing…",noWorkspace:"No workspace",clientsCount_one:"{{count}} client",clientsCount_other:"{{count}} clients",statLive:"Live runtimes",statRecovery:"Recovery",statRequests:"Requests",statStarted:"Started",latestWarning:"Latest host warning",liveTitle:"Live Hosted Runtimes",recoveryTitle:"Recovery Snapshots",inactiveTitle:"Inactive Records",recentActivity:"Recent Host Activity",liveEmpty:"No live hosted runtimes on this machine right now.",recoveryEmpty:"No recovery snapshots currently need attention.",transitionsEmpty:"No recent runtime transitions yet.",nextAction:"Next: {{action}}"},Sk={managed:"Managed",checking:"Checking…",diagnosticsIssue:"Diagnostics issue",unavailable:"Unavailable",restoredAfterRestart:"restored after restart",restoreFailed:"restore failed",hostRestartInterrupted:"host restart interrupted",snapshotRecovered:"snapshot recovered",attach:"Attach",recover:"Recover",restart:"Restart",hintLive:"These runtimes are live now and are the only attachable targets.",hintRecovery:"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.",hintInactive:"These inactive records are shown for reference and usually need restart before they are useful again.",lifecycleStarting:"Starting",lifecycleRunning:"Running",lifecycleStopping:"Stopping",lifecycleStopped:"Stopped",lifecycleFailed:"Failed",lifecycleInterrupted:"Interrupted"},kk={advancedTitle:"Advanced",mobileMode:{workspaceMode:"Workspace",chatMode:"Chat mode",descriptionWorkspace:"Use the full workspace layout on phones and tablets.",descriptionChat:"Use the chat-first mobile inbox layout, closer to a messaging app.",label:"Mobile inbox (chat mode)"},theme:{preset:{honey:"Warm yellow accents",aurora:"Pink accent theme",ember:"Default amber theme, inspired by the landing page",midnight:"Classic violet theme"},presetCustomDescription:"Full app + chat customization",helloHelp:"Hello! How can I help?",fixBug:"Fix the bug please",onIt:"On it! ✨",customEditorTitle:"Custom Theme Editor",darkMode:"Dark mode",lightMode:"Light mode",sectionAppBackground:"App Background",sectionAppText:"App Text",sectionBordersAccent:"Borders & Accent",sectionChatBubbles:"Chat Bubbles",sectionChatLayout:"Chat Layout",colorBackground:"Background",colorSurface:"Surface",colorCard:"Card",colorPrimary:"Primary",colorSecondary:"Secondary",colorMuted:"Muted",colorBorderSubtle:"Border subtle",colorBorderDefault:"Border default",colorAccent:"Accent",colorUserBubble:"User bubble",colorUserText:"User text",colorAgentBubble:"Agent bubble",colorAgentText:"Agent text",colorChatBg:"Chat BG",colorSendButton:"Send button",colorInputBorder:"Input border",labelBubbleRadius:"Bubble radius",resetToDefaults:"Reset to defaults",customLabel:"Custom"},providerPriority:{undetectedHint_other:"{{count}} providers aren't detected here — kept in order, skipped until available.",undetectedHint_one:"{{count}} provider isn't detected here — kept in order, skipped until available.",orderHint:"Launches use this order, top to bottom.",noMoreProviders:"No other CLI providers detected",selectProvider:"Select provider…",moveDown:"Move down",moveUp:"Move up",keptUntilDetected:"Kept in order; skipped at launch until it's detected on this machine.",emptyWarning:"No provider priority configured. Launches that don't name a CLI provider will be refused.",available:"available",notOnMachine:"Not detected",remove:"Remove",addCliLabel:"Add available CLI provider",addProvider:"Add provider"},coordinatorPrompts:{saveFailed:"Couldn't save",loadFailed:"Couldn't load coordinator prompts",save:"Save",saved:"Saved",saving:"Saving…",appendPlaceholder:"(empty — nothing added at this layer)",overridePlaceholder:"(empty — use the default base prompt)",placeholdersHint:"Placeholders you can use:",resetHint:"Leave a field empty and save to remove it (back to the default).",intro:"Customize the prompt that this daemon's mesh coordinator sessions receive.",loading:"Loading…",connectDaemon:"Connect a daemon to edit coordinator prompts.",overrideDesc:"<strong>Override</strong> replaces the daemon's built-in base prompt for that CLI.",appendDesc:"<strong>Append</strong> stacks after whichever base wins.",overrideLabel:"Override",appendLabel:"Append",expandLabel:"Edit prompts",collapseLabel:"Collapse",customizedBadge:"Customized",collapsedNone:"No custom prompts — using daemon defaults.",tabsAriaLabel:"Coordinator prompt provider",sectionTitle:"Coordinator prompts",sectionDescription:"Per-CLI base prompt for mesh coordinator sessions on this machine. Mesh-level prompts live on the Repo Mesh page."},appearance:{modeSystem:"System",modeLight:"Light",modeDark:"Dark",modeLabel:"Mode",themeLabel:"Theme",mobileLabel:"Mobile",chatLabel:"Chat"},chatActivity:{rowLabel:"Show agent activity in chat",descriptionOn:"Tool calls, terminal output and thinking are shown between chat messages.",descriptionOff:"Only the conversation is shown. Tool calls, terminal output and thinking stay hidden."}},jk={chatHistory:"Chat History",startNewChat:"+ Start New Chat Session",creating:"Creating...",searchPlaceholder:"Search title or preview",filterWorkspace:"Filter by workspace",filterModel:"Filter by model",sortRecent:"Most recent",sortOldest:"Oldest first",sortMessages:"Most messages",resumeReadyOnly:"Resume-ready only",untitledSession:"Untitled Session",noSavedPreview:"No saved preview yet",workspaceUnknown:"Workspace unknown",selectedWorkspaceSuffix:" · selected workspace",msgCount:"{{count}} msgs",statusActive:"ACTIVE",statusMissingWorkspace:"MISSING WORKSPACE",statusResumeSelectedWorkspace:"RESUME IN SELECTED WORKSPACE",statusResuming:"RESUMING...",statusResume:"RESUME",noMatchingHistory:"No saved history matches these filters.",noRecentChats:"No recent chat sessions found.",refreshHistory:"Refresh History",refreshing:"Refreshing...",confirmSwitchTitle:"Switch session?",confirmSwitchDescription:'Switch to "{{target}}"? This will leave your current view.',confirmSwitchAction:"Switch"},Nk={gallery:{next:"Next view",previous:"Previous view",slides:{overview:"Missions & activity — from a phone",tasks:"Task queue across workers",map:"Live map of nodes and branches",desktop:"The same mesh, desktop view"}},theme:{system:"System theme",light:"Light theme",dark:"Dark theme"},nav:{home:"ADHDev Home",mesh:"Mesh",what:"What",agents:"Agents",pricing:"Pricing",install:"Install",github:"GitHub",docs:"Docs",getStarted:"Get started",toggleMenu:"Toggle menu",mainNavigation:"Main navigation"},hero:{badge:"Claude Code, Codex, Cursor & more — on all your machines",title:"The control plane for your coding agents.",subtitleInstall:"Install ADHDev on your <os></os>.",subtitlePlace:"use your <device></device>",subtitleAsk:"to ask <coordinator></coordinator> to send <worker></worker> to <verb></verb> your repo.",subtitleFrom:"From <place></place>,",anywhere:"anywhere",subtitleLand:"Every agent on every machine in one view, one shared task queue, and only work that passes your tests reaches main.",axes:{os:["Mac","Windows","Linux"],place:["the subway","a cafe","your parents' place","bed","the couch","the garden","the passenger seat","the ferry","the gym","inside a container","the moon","a server rack"],device:["desktop","laptop","tablet","mobile phone"],verb:["debug","build","test","review"]},copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",getStarted:"Get started free",orInstall:"Or install the CLI",openSource:"Open source on GitHub",joinDiscord:"Join Discord",selfHost:"Self-host it",demoDesktop:"ADHDev command center driving live agent sessions across multiple machines",demoPush:"ADHDev mobile push notification and one-tap approval"},mesh:{sectionTitle:"Parallel agents that don't step on each other.",sectionSubtitle:"Running agents in parallel is the easy part — every tool does it now. The hard part is what comes after: a pile of branches that still have to be checked and merged. ADHDev does that for you, so finished work arrives on main instead of in your review queue.",refineryHighlight:"Automatic landing",refineryTitle:"Finished work merges to main on its own",refineryDesc:"Anyone can run ten agents at once. ADHDev then checks each branch against your project's own tests and lint, merges the ones that pass cleanly into main, and tidies up — automatically, and never with a force-push. Anything unclear is held back for you to review instead of merged.",asyncHighlight:"One place to drive it",asyncTitle:"You talk to one place. It runs the rest.",asyncDesc:"You hand work to a single coordinator, and it runs every agent across every machine for you. It only pings you when something needs approval or finishes — so there's no queue of agent windows to watch and nothing to sit in front of.",crossPlatformHighlight:"Every OS at once",crossPlatformTitle:"Mac, Windows, Linux — all at once",crossPlatformDesc:"Send a task to a specific operating system with one tag. A single prompt can build, test, or verify across Mac, Windows, and Linux machines you already own — in parallel, with no SSH setup and no virtual machines.",monoHighlight:"Works with real repos",monoTitle:"Safe even with git submodules",monoDesc:"Real production repos nest submodules — exactly where naive auto-merge breaks. ADHDev handles them safely: it makes sure submodule changes are published and pointed at correctly before it touches main. This project is itself a repo with two submodules, merged this way every day.",crossHighlight:"Second opinion",crossTitle:"Consensus over a single opinion",crossSubtitle:"One question, several independent agents",crossDesc:"Have the coordinator ask the same read-only question to several machines and models at once, then compare where they agree and disagree — more trustworthy than one agent's answer.",tryMesh:"Try Repo Mesh →",seePlans:"See plans",availableOn:"Connect a machine and open the <strong>Repo Mesh</strong> page to get started.",readGuide:"Read the guide"},compare:{sectionTitle:"Everyone runs agents in parallel. Not everyone keeps them out of each other's way.",sectionSubtitle:"Local CLIs spawn subagents; desktop orchestrators fan work across worktrees with a native UI. Both stop at the branch — reviewing and merging is left to you. Here's how they compare, including where each of them is the better fit.",colLocalCli:"Local CLI + subagents",colDesktop:"Desktop orchestrator",colAdhdev:"ADHDev Repo Mesh",rowLandsMain:"Lands finished work on main",rowLandsMainLocalCli:"You run the gates and merge by hand",rowLandsMainDesktop:"Parallelizes the work, then hands you the branches to review",rowLandsMainAdhdev:"The Refinery runs your repo's gates, checks patch equivalence, and rebases + merges onto main only if it hasn't moved — unattended, no force-push",rowSubmodules:"Safe with git submodules",rowSubmodulesLocalCli:"No merge automation to be aware of them",rowSubmodulesDesktop:"Worktree parallelism, but the merge is yours to get right",rowSubmodulesAdhdev:"Submodule-aware convergence: reachability gate, patch-equivalence check, atomic pointer bump — dogfooded on this monorepo daily",rowAsync:"Talk to one place, async",rowAsyncLocalCli:"One session at a time, synchronously",rowAsyncDesktop:"You supervise each agent window yourself",rowAsyncAdhdev:"One coordinator drives every worker on an event loop — it waits on completion/approval events, you don't poll or babysit",rowMultiMachine:"Multiple physical machines",rowMultiMachineLocalCli:"One host's processes only",rowMultiMachineDesktop:"Bound to the one machine it runs on",rowMultiMachineAdhdev:"Remote daemons over P2P — Mac, Windows, and Linux nodes in one mesh, no SSH plumbing",rowParallelBranch:"Parallel isolated-branch work",rowParallelBranchLocalCli:"Subagents share one working tree — concurrent writes collide",rowParallelBranchDesktop:"One git worktree per task — a core strength",rowParallelBranchAdhdev:"One git worktree per node — parallel across machines, not just cores",rowBrowser:"Drive it from a browser or phone",rowBrowserLocalCli:"You have to be at the terminal",rowBrowserDesktop:"Native desktop app — you're at that desk",rowBrowserAdhdev:"Web-first: control sessions and approve from any browser or phone",rowNativeApp:"Native desktop app",rowNativeAppLocalCli:"Terminal only",rowNativeAppDesktop:"Polished native window — genuinely nicer to sit in front of",rowNativeAppAdhdev:"We're web-first — a browser tab, not a native app",rowRestarts:"Survives restarts & context loss",rowRestartsLocalCli:"State lives in a session — close it and it's gone",rowRestartsDesktop:"State tied to the app process",rowRestartsAdhdev:"Missions persist to disk and resume after a coordinator or daemon restart — append-only audit trail",rowCrossCheck:"Cross-check the answer",rowCrossCheckLocalCli:"One agent's take, no second opinion",rowCrossCheckDesktop:"Parallel work, single verdict",rowCrossCheckAdhdev:"The coordinator sends the same read-only question to agents on different machines and providers and compares where they diverge",footnote:"For a single machine, a single branch, a one-shot task — a local CLI with subagents is lighter and works great, and a native desktop orchestrator is a nicer place to sit. Repo Mesh earns its keep when work fans out across machines and branches, needs to survive restarts, and should land on main automatically — controlled from wherever you are."},what:{sectionTitle:"Any agent, mixed freely",sectionSubtitle:"Vendor-neutral by design. Run Claude Code on the Mac, Codex on the Windows GPU box, Cursor CLI for review passes — all in the same mesh, driven from the same dashboard. Switch vendors without switching platforms.",cliHighlight:"CLI agents",cliTitle:"Drive any terminal agent from the web",cliDesc:"Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Grok, Kimi, and OpenCode — launched on your machine through a PTY adapter with proper resume and reconnect, driven from your browser. Send prompts and provide visual context instantly (paste, drag & drop, or upload multiple images at once).",uiHighlight:"One UI",uiTitle:"Same dashboard, any device",uiDesc:"Cloud-hosted at adhf.dev — drive every agent from a laptop or phone, whether you're at your desk or away from it.",ideHighlight:"IDE agents",ideTitle:"Also: attach to running editors",ideDesc:"Cursor, VS Code, VSCodium, Windsurf, Antigravity, Kiro, PearAI, Trae. Read live chat, send prompts, switch sessions, capture screenshots.",p2pHighlight:"Yours, end to end",p2pTitle:"P2P-first: your data stays yours",p2pDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC — your code never routes through the server. The cloud handles sign-in, connection setup and session status. The one exception: approval push notifications include up to 80 characters of what you're approving."},oss:{sectionTitle:"Open source & self-hostable",sectionSubtitle:"The daemon and dashboard are AGPL-3.0 and available on GitHub. Run them yourself on any machine or server — no account required.",github:"GitHub",selfHostDocs:"Self-hosting docs"},agents:{sectionTitle:"Supported agents",sectionSubtitle:"{{ides}} built-in IDE integrations, {{clis}} built-in CLI agents, and {{extensions}} IDE-resident extension agents. Provider scripts live in <code>adhdev-providers/</code> — add your own under <code>~/.adhdev/providers/</code>.",tierTested:"Tested",tierTestedDesc:"validated against a real app + version",tierCommunity:"Community",tierCommunityDesc:"built-in and community-supported",groupIdes:"IDEs",hintIdes:"Attached via Chrome DevTools Protocol. Read chat, send prompts, switch sessions, screenshot.",groupCli:"CLI agents",hintCli:"Driven through a PTY adapter with resume and reconnect.",groupExtensions:"In-IDE extension agents",hintExtensions:"CDP webview attachment for agents that live inside another IDE."},pricing:{sectionTitle:"Simple pricing as your agents grow",sectionSubtitle:"Start free on one machine. Go Pro for two, or Ultra for five. No per-seat math, no enterprise sales call — just the plans below.",mostPopular:"Most popular",upgradeToPro:"Upgrade to Pro",footnote:"Prices in USD, excluding applicable taxes. Prefer to self-host? The daemon and dashboard are open source.",plans:{free:{period:"forever",tagline:"Everything you need to drive one machine from anywhere.",cta:"Start free",features:{machine:"One machine, paired in a single command",p2p:"P2P chat, commands, screenshots, remote input",providers:"Every provider — CLI and IDE agents",push:"Push notifications for approvals & completions",share:"One shared session link"}},pro:{period:"/mo",tagline:"Two machines, so Repo Mesh can run agents across both — plus more concurrent sessions.",cta:"Start 7-day Pro trial",features:{machines:"2 machines — run agents on both",p2p:"More concurrent P2P sessions",push:"Unlimited push notifications",share:"More shared sessions"}},ultra:{period:"/mo",tagline:"Everything in Pro, scaled up — more machines and higher limits for heavy parallel work.",cta:"Go Ultra",features:{machines:"5 machines — flat price, not per-seat",everything:"Everything in Pro",p2p:"Highest concurrent P2P sessions",screenshots:"Unlimited daily screenshot minutes",webhooks:"Higher API call limits",share:"More shared sessions"}}}},install:{sectionTitle:"Three steps to a working dashboard",sectionSubtitle:"No configuration files. No API keys to wire up. ADHDev does not manage agent auth — each tool keeps its own login.",selectOs:"Select OS",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",platformNote:"macOS and Linux use the Unix script; Windows uses the PowerShell one. All three are in daily use.",arrow:"→",steps:{step1:{title:"Install the daemon",desc:"One command installs the daemon plus the adhdev CLI — the launcher you run to pair machines and start the daemon (not to be confused with the CLI agents it drives, like Claude Code or Codex). Same binary powers cloud and standalone."},step2:{title:"Link a machine",desc:"Sign in once with GitHub or Google and the daemon pairs itself — no token to copy."},step3:{title:"Drive your agents",desc:"Launch Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Kimi, and other agents from the dashboard. Read chat, send prompts, provide visual context (paste, drag & drop, or upload multiple images at once), approve actions, and switch sessions."}}},cta:{headline:"Put every agent and every machine behind one queue.",subtitle:"One command, one daemon, every agent you already use. Queue the work, and only what passes your tests lands on main.",getStarted:"Get started →",github:"GitHub",discord:"Discord"},footer:{docs:"Docs",github:"GitHub",discord:"Discord",dashboard:"Dashboard",terms:"Terms",privacy:"Privacy",contact:"Contact",copyright:"© {{year}} RacoLab. All rights reserved."},imagePaste:{sectionTitle:"Paste a screenshot. A terminal agent on another machine sees it instantly.",sectionSubtitle:"Grab a screenshot on your laptop or phone, paste it into the chat, and a CLI agent running in a terminal on a different machine gets it as visual context — no file juggling, no SSH. Paste, drag & drop, or upload up to 5 images (10MB each) at once.",point1:"Paste from clipboard, drag & drop, or upload",point2:"Up to 5 images, 10MB each",point3:"Lands in a PTY terminal agent on any of your machines",step1Label:"Paste the image, type a question",step2Label:"Sent — the agent picks it up",step3Label:"It saw the image and answered"},mobile:{sectionTitle:"Leave your desk. Your agents keep going.",sectionSubtitle:"A push notification hits your phone when an agent needs approval or finishes. Tap it, approve or reject, then follow up in chat — all from the mobile dashboard, wherever you are.",point1:"Push notification on approval or completion",point2:"One tap to approve or reject",point3:"Follow up with a chat instruction, then put your phone away",notificationLabel:"Mobile push notification for an agent approval",resumeLabel:"Approving and following up from the mobile dashboard",deviceShotLabel:"Real iOS lock screen showing an ADHDev approval push with the Bash command Claude Code wants to run",deviceShotCaption:"Real device — actual push notifications on a phone",point4:"No port forwarding, no VPN, no DMZ — P2P with TURN relay connects from cafés, hotspots, desktop or laptop, anywhere with internet"},brain:{sectionTitle:"The right model for each task, on the subscription that still has room.",sectionSubtitle:"Tag a task easy, medium, or difficult and the mesh applies a matching preset — provider, model, and thinking budget. Every machine also reads how much of each subscription's 5-hour and weekly window is left: a plan that is nearly out gets skipped, and quota that would expire unused at the next reset is spent first.",point1:"Difficulty-based presets: easy / medium / difficult",point2:"Each preset picks provider, model, and thinking level",point3:"Routes around plans that are nearly out of quota"},scenario:{sectionTitle:"One prompt. Mac builds, Windows tests, main lands.",sectionSubtitle:"A real session in three steps: you describe the work once, agents run in parallel across your machines, and finished code arrives on main — without you sitting at the terminal.",step1Label:"Describe the work",step1Desc:"Tell it what to build, in one sentence. No config, no setup per machine.",step2Label:"Agents run in parallel",step2Desc:"The work splits across your Mac and Windows machines at once — each on its own branch, each running your project's tests and checks.",step3Label:"Finished code lands on main",step3Desc:"When the checks pass, the work merges into main automatically and safely. Anything unclear is held back for you to review — never force-pushed.",caveat:"Mac, Windows and Linux machines are all in daily use."}},Ck={submit:"Submit",submitting:"Submitting…",cancelAria:"Cancel the question",actionRequired:"Action Required",selectAllThatApply:"Select all that apply",multipleChoice:"Multiple choice",singleChoice:"Single choice",other:"Other",answersRequired_one:"{{count}} question still needs an answer",answersRequired_other:"{{count}} questions still need answers",errorReviewPageNotFocused:"The terminal is showing a different screen, so the answer was not submitted — check the terminal screen or close this and try again.",errorReviewUnconfirmed:"The answer keys reached the terminal, but the question is still on screen — the answer may not have been submitted. Check the terminal: if it was not submitted, answer there; resending from here could submit it twice."},_k={diffPreview:{truncatedAfter:"locally for the full output.",truncatedBefore:"Changes truncated — run",empty:"No changes to show.",binary:"Binary file — changes can't be shown.",loading:"Loading changes…"},changeList:{stagedHint:"Staged",noChanges:"No changed files.",binaryBadge:"bin",truncatedNote:"File list truncated — run <code>git status</code> locally for full output."},statusDialog:{working:"Working…",includeUntracked:"Include untracked files",messageRequired:"Message (required)",fileFallback:"file",confirmRevert:"Revert changes to {{path}}?",confirmPop:"Restore latest stash?",confirmStash:"Stash changes",confirmCheckpoint:"Create checkpoint commit",copySummary:"Copy summary",copied:"Copied to clipboard",checkoutSelected:"Revert selected",selectFileToRevert:"Select a file to revert",revertFile:"Revert changes to {{path}}",popStash:"Restore stash",noStashes:"No stashes to restore",popHint:"Restore the latest stash",resolveBeforePop:"Resolve conflicts before restoring a stash",stash:"Stash",stashHint:"Set current changes aside (git stash)",resolveBeforeStash:"Resolve conflicts before stashing",checkpoint:"Checkpoint",checkpointHint:"Create a git commit as a checkpoint",resolveBeforeCheckpoint:"Resolve conflicts before creating a checkpoint",selectFile:"Select a file to view its changes",noDiffData:"No diff data.",loading:"Loading…",fileCount_other:"{{count}} files",fileCount_one:"{{count}} file",stashed:"{{count}} stashed",deleted:"{{count}} deleted",untracked:"{{count}} untracked",modified:"{{count}} modified",staged:"{{count}} staged",behind:"{{count}} behind",ahead:"{{count}} ahead",refresh:"Refresh",openOnGithub:"Open on GitHub",title:"Git status",conflicts:"conflicts",clean:"clean"}},Ak={machineProviders:"Machine → Providers",perProviderIntro:"Per-provider alerts and auto-approve:",mixed:"(some off)",agentAlert:{noProgressDesc:"Alert when an agent has shown no progress for a while.",noProgress:"No progress",approvalDesc:"Alert when an agent is waiting for your approval.",approval:"Approval needed"},agentAlertsDesc:"Applies to every provider on your online machines. Fine-tune one provider in Machine → Providers.",permissionUnsupportedChip:"Not supported",permissionBlockedChip:"Blocked",permissionNeededChip:"Permission needed",permissionAllowedChip:"Allowed",title:"Notifications",subtitle:"Browser, push and agent alerts",sectionBrowserAlerts:"Browser alerts",masterToggleLabel:"Notifications",masterToggleDesc:"Master toggle for all alerts",browserNotificationsLabel:"Browser Notifications",browserNotificationsDesc:"Desktop alerts when tab is inactive",browserBackgroundInfo:"Browser alerts only fire while this dashboard tab stays open in the background.",browserBackgroundInfoWithPush:"Browser alerts only fire while this dashboard tab stays open in the background. If you close the tab, use Push Notifications instead.",permissionDefault:"This browser has not granted notification permission yet. Allow it to receive browser alerts.",allowNotifications:"Allow notifications",permissionDenied:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive desktop alerts.",permissionUnsupported:"This browser cannot show desktop notifications here. Use a supported desktop browser, or rely on Push Notifications where available.",completionAlertsLabel:"Completion Alerts",completionAlertsDesc:"Notify when agent finishes a task",approvalAlertsLabel:"Approval Alerts",approvalAlertsDesc:"Notify when agent needs approval",connectionAlertsLabel:"Connection Alerts",connectionAlertsDesc:"Alert when a machine disconnects",allDisabled:"All notifications are off.",sectionProviderAlerts:"Agent alerts",loading:"Loading...",refresh:"Refresh",noOnlineMachines:"No machines online.",loadingProviderSettings:"Loading provider settings...",soundEffectsLabel:"Sound Effects",soundEffectsDesc:"Play a sound when agent completes or needs approval"},Tk={pageTitle:"Approvals",pageSubtitle:"Sessions waiting on your decision.",pending:"Pending",loading:"Loading approvals…",emptyHint:"Approvals from any connected machine will appear here automatically."},Ik={title:"Guided mesh setup",close:"Close",machines:{title:"Select machines",description:"Pick the mesh to set up and attach the machines that should run its work. Creating a mesh also attaches the chosen workspace as its first node.",noMachinesDescription:"No machine is registered yet. Install the daemon on a machine first — it pairs automatically once signed in.",noMachinesFallback:"Start the local daemon and return here.",nodeCount:"{{count}} nodes",createNew:"Create new mesh",loadingMeshes:"Loading meshes…",meshName:"Mesh name",machine:"Machine",machineSelectPlaceholder:"Select a machine",workspace:"Workspace (repo path)",workspacePlaceholder:"/path/to/repo",workspaceSelectPlaceholder:"Select a workspace",workspaceCustom:"Enter a path manually…",pickFromKnown:"Pick from known workspaces",planChecking:"Checking the workspace…",planOk:"Workspace looks good: {{identity}}",planExists:"This workspace already belongs to an existing mesh — add it as a node there instead of creating a new mesh.",creating:"Creating…",create:"Create mesh",createFailed:"Create failed",attachTitle:"Attach another machine",allMachinesAttached:"Every registered machine is already attached to this mesh.",attaching:"Attaching…",addMachine:"Add machine"},quotaPolicy:{blankMeansDefaultShort:"Blank = default",title:"Quota-aware routing",description:"When a node reports how much of its AI provider quota is left, the coordinator can skip nodes that are nearly exhausted and prefer nodes with more headroom. These thresholds decide when that happens. Missing or outdated readings are always ignored, so a node is never excluded on stale data.",sessionMin:"Session floor",sessionMinHint:"Skip a provider whose short rolling window has less than this left.",weeklyMin:"Weekly floor",weeklyMinHint:"Skip a provider whose weekly window has less than this left.",resetImminent:"Reset grace",resetImminentHint:"Ignore a low session window when it resets within this long.",staleAfter:"Reading expiry",staleAfterHint:"Fallback only: a measured window stays valid until its own reset; this age limit applies just to readings without a reset time.",spreadBonus:"Headroom preference",spreadBonusHint:"How strongly more remaining quota is preferred. Never overrides a task-difficulty match.",sessionAxisWeeklyHeadroom:"Weekly headroom for session urgency",sessionAxisWeeklyHeadroomHint:"Only prioritize an imminent 5-hour session-window reset when weekly quota remaining is at or above this. Unused 5-hour quota is lost forever, but burning it when the weekly window is already tight costs more than it saves.",minutes:"min",blankMeansDefault:"Leave a field blank to use its default (shown as the greyed-out value).",useDefaults:"Use defaults",saving:"Saving…",errors:{notANumber:"Enter a number.",percentRange:"Must be between 0 and 100.",negative:"Cannot be negative."}},continueToMesh:"Continue to Mesh"},Mk={dashboard:"Dashboard",machines:"Machines",notifications:"Notifications",mesh:"Mesh",marketplace:"Marketplace",api:"API",webhooks:"Webhooks",account:"Account",settings:"Settings",docs:"Docs",about:"About",chats:"Chats"},Rk={controls:U0,sessionStatus:K0,language:q0,common:z0,connection:V0,toast:G0,notification:Y0,event:Q0,dashboard:J0,cliStop:X0,approval:Z0,chatControls:ek,newSession:tk,mobileInbox:nk,mesh:sk,chat:rk,chatPane:ok,chatInput:ak,paneGroup:ik,terminal:ck,conversation:lk,cliView:dk,launch:uk,standalone:mk,cloud:hk,app:pk,chatList:fk,screenshot:bk,remote:gk,sessionNav:xk,sessionInfo:yk,machine:vk,sessionHost:wk,sessionHostSurface:Sk,settings:kk,historyModal:jk,landing:Nk,interactivePrompt:Ck,git:_k,notifications:Ak,approvals:Tk,setupWizard:Ik,nav:Mk},pl="lang",ro="common",Pk={ko:()=>or(()=>import("./common-Dg6v-XzS.js"),[]),ja:()=>or(()=>import("./common-B7DF1Ru_.js"),[]),"zh-CN":()=>or(()=>import("./common-45VKQ9y1.js"),[]),es:()=>or(()=>import("./common-CFwb7FpY.js"),[])};async function Ek(e){return!Rs(e)||e===Es?null:(await Pk[e]()).default}const Dk={type:"backend",init(){},read(e,t,s){if(t!==ro){s(null,{});return}Ek(e).then(r=>s(null,r??{}),r=>s(r instanceof Error?r:new Error(String(r)),!1))}};function Lk(e){return{resources:{[Es]:{[ro]:Rk}},partialBundledLanguages:!0,lng:e,fallbackLng:Es,supportedLngs:uf,ns:[ro],defaultNS:ro,interpolation:{escapeValue:!1},returnEmptyString:!1,react:{transKeepBasicHtmlNodesFor:["br","strong","i","p","em"]}}}function Ok(){try{const e=localStorage.getItem(pl);if(Rs(e))return e}catch{}return null}function mf(){const e=Ok();return e||(typeof navigator<"u"?W0(navigator.language):Es)}function fl(e){typeof document>"u"||document.documentElement.setAttribute("lang",e)}let bo=null,hf=!1;function pf(){if(bo)return Ge;const e=mf();return bo=Ge.use(Dk).use(Rx).init(Lk(e)).then(()=>{},()=>{}).finally(()=>{hf=!0}),fl(e),Ge}function $k(){return hf?!0:!!bo&&Ge.isInitialized&&Ge.hasLoadedNamespace(ro)}function Fk(){return bo||pf(),bo}function Ut(e){return(typeof e=="string"?e.trim():"")||void 0}function Yn(e,t){const s=Ut(t);return s?`${e}:${s}`:void 0}function us(e,t,s){const r=Yn(t,s),o=Ut(s);r&&e.push(r),o&&e.push(o)}function ar(e){const t=[],s=new Set;for(const r of e)!r||s.has(r)||(s.add(r),t.push(r));return t}function ff(e){return Ut(e.providerSessionId)||Ut(e.sessionId)||Ut(e.tabKey)||Ut(e.routeId)}function yi(e){return ar([Ut(e.historySessionId),Ut(e.providerSessionId),Ut(e.sessionId)])}function oo(e){const t=[];return us(t,"provider",e.providerSessionId),us(t,"session",e.sessionId),us(t,"tab",e.tabKey),us(t,"route",e.routeId),ar(t)}function Hk(e){const t=[];return Ut(e.providerSessionId)?(us(t,"provider",e.providerSessionId),ar(t)):Ut(e.sessionId)?(us(t,"session",e.sessionId),ar(t)):Ut(e.tabKey)?(us(t,"tab",e.tabKey),ar(t)):Ut(e.routeId)?(us(t,"route",e.routeId),ar(t)):[]}function bf(e){return Yn("provider",e.providerSessionId)||Yn("session",e.sessionId)||Yn("tab",e.tabKey)||Yn("route",e.routeId)||"unknown:"}function vi(e){return yi(e)[0]}function wi(e){const t=Ut(e.sessionId),s=vi(e);if(s&&!(t&&s===t))return s}function Bk(e){const t=Ut(e.providerSessionId),s=Ut(e.sessionId),r=Ut(e.tabKey),o=Ut(e.routeId),a=[Yn("provider",t),Yn("session",s),Yn("tab",r),Yn("route",o)].filter(d=>typeof d=="string"),i=oo({providerSessionId:t,sessionId:s,tabKey:r,routeId:o}),l=bf({providerSessionId:t,sessionId:s,tabKey:r,routeId:o});return{providerSessionId:t,sessionId:s,tabKey:r,routeId:o,canonicalKey:l,targetKey:l,targetValue:ff({providerSessionId:t,sessionId:s,tabKey:r,routeId:o}),historySessionId:vi({providerSessionId:t,sessionId:s}),runtimeSessionId:s,allKeys:a,lookupKeys:i}}function Zr(e,t){const s=Bk(e);return Hk(t).some(r=>s.lookupKeys.includes(r))}function gf(e){const t=String(e.daemonId||"").trim(),s=String(e.id||"").trim();return t&&s.startsWith(`${t}:`)?s.slice(t.length+1):s}function bl(e){if(String(e.ownerDaemonId||"").trim())return!0;const t=e.settings;return t?!!t.meshNodeFor||!!t.meshNodeId||t.launchedByCoordinator===!0||t._remoteOwnedSession===!0:!1}function Wk(e,t){const s=String(e.daemonId||"").trim(),r=String(e.id||"").trim(),o=gf(e);if(o&&t.has(o))return`mesh:${o}`;const a=String(e.ownerDaemonId||"").trim()||s;return a?o?`${a}:${o}`:a:r}function oc(e,t){return t||e||"unknown"}function Uk(e,t){return e.ownerDaemonId&&(t==null?void 0:t[e.ownerDaemonId])||e.ownerMachineName||void 0||e.daemonId&&(t==null?void 0:t[e.daemonId])||void 0}const Kk={vscode:"VS Code",pearai:"PearAI"};function Ot(e){return e?e.split("-").map(t=>Kk[t.toLowerCase()]||t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function qk(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const s=Math.floor(t/60),r=t%60;if(s<24)return r>0?`${s}h ${r}m`:`${s}h`;const o=Math.floor(s/24),a=s%24;return`${o}d ${a}h`}function ac(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function fa(e,t){const s=typeof t=="string"?t.trim():"";if(s)return s;const r=typeof e=="string"?e.trim():"";if(!r)return"";const o=r.replace(/[\\/]+$/,""),a=o.split(/[\\/]/).filter(Boolean);return a[a.length-1]||o}function zk(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),s=t[t.length-1];return s.length>12?`Machine-${s.substring(0,8)}`:s}return e}function Vk(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Gk(e){return zk(e.trim().replace(/\.local$/i,""))}function xf(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function bd(e,t={}){var o,a;const s=[e.hostname,(o=e.machine)==null?void 0:o.hostname,(a=e.system)==null?void 0:a.hostname].find(i=>typeof i=="string"&&i.trim().length>0&&!Vk(i));if(s&&s!=="Unknown")return Gk(s);const r=t.fallbackId||e.id;return r?`Machine-${r.substring(0,8)}`:t.fallbackLabel||"Machine"}function yn(e,t={}){return xf(e)||bd(e,t)}function yf(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function Yk(e,t,s={}){const r=String(t).trim();if(!e||!Array.isArray(e.items)||!r)return"";const o=e.items.find(a=>String((a==null?void 0:a.id)||"").trim()===r);return o?String(s.preferShortValue?o.shortValue||o.value||"":o.value||o.shortValue||"").trim():""}function go(e,t){return yf(e).join(" · ")}function xo(e){return e.transport==="pty"}const vf={darwin:"macOS",linux:"Linux",win32:"Windows"};function wf(e,t){var s,r;return(s=t==null?void 0:t.providerLabels)!=null&&s[e]?t.providerLabels[e]:(r=t==null?void 0:t.providerLabels)!=null&&r[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:Ot(e)}function qu(e,t,s){const r=(e||"").trim().toLowerCase();if(!r)return!0;const o=(t||"").trim().toLowerCase(),a=(s||"").trim().toLowerCase(),i=Ot(s||"").trim().toLowerCase();return r===o||r===a||r===i}function Qk(e,t=[],s=[]){var d,m,u,h;const r=Jt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(r==="waiting_approval")return"waiting_approval";if(r==="waiting_choice")return"waiting_choice";if(r==="generating")return"generating";const o=t.find(p=>Bu(p.status,{activeModal:p.activeModal})||dl(p.status));if(o)return Jt(o.status,{activeModal:o.activeModal});const a=s.find(p=>Bu(p.status,{activeModal:p.activeModal})||dl(p.status));if(a)return Jt(a.status,{activeModal:a.activeModal});if(r&&r!=="idle")return r;const i=Jt((d=t[0])==null?void 0:d.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(i!=="idle")return i;const l=Jt((u=s[0])==null?void 0:u.status,{activeModal:(h=s[0])==null?void 0:h.activeModal});return l!=="idle"?l:"idle"}function Jk(e){return Jt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Xk(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,s=["generating","finalizing","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const r of e){const o=(r.name||r.id||"").toLowerCase().replace(/\s+/g,"-"),a=t.get(o),i=Jt(r.status);if(!a){t.set(o,{...r,status:i});continue}const l=s.indexOf(a.status||"idle"),d=s.indexOf(i||"idle");d>=0&&(l<0||d<l)&&t.set(o,{...r,status:i})}return Array.from(t.values())}function Zk(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 ej(e){var s,r;const t=(r=(s=e==null?void 0:e.messages)==null?void 0:s.at)==null?void 0:r.call(s,-1);return t&&Zk(t.receivedAt)||0}function tj(e){return(e.recentLaunches||[]).reduce((s,r)=>Math.max(s,r.lastLaunchedAt||0),0)}function gl(e){return Math.max(tj(e),ej(e.activeChat))}function nj(e,t,s,r,o,a){const i=t-e;if(i!==0)return i;const l=s.localeCompare(r);return l!==0?l:o.localeCompare(a)}function La(e,t){return nj(gl(e),gl(t),yn(e,{fallbackId:e.id}),yn(t,{fallbackId:t.id}),e.id,t.id)}const Sf="adhdev_notification_prefs",zu={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function sj(){try{const e=localStorage.getItem(Sf);if(e){const t=JSON.parse(e);return{...zu,...t}}}catch{}return{...zu}}function rj(e){try{localStorage.setItem(Sf,JSON.stringify(e))}catch{}}let Gn=sj(),ba=[];function oj(){ba.forEach(e=>e())}function aj(e){Gn={...Gn,...e},rj(Gn),oj()}function ij(){const[,e]=c.useState(0);c.useEffect(()=>{const s=()=>e(r=>r+1);return ba.push(s),()=>{ba=ba.filter(r=>r!==s)}},[]);const t=c.useCallback(s=>{aj(s)},[]);return[{...Gn},t]}function ao(e){if(!Gn.globalEnabled)return!1;switch(e){case"disconnect":return Gn.disconnectAlert;case"completion":return Gn.completionAlert;case"approval":return Gn.approvalAlert;case"browser":return Gn.browserNotifications;default:return!0}}const cj={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function kf(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function jf(){return"Notification"in window&&Notification.permission==="granted"}function lj(e,t,s){return e?!(s==="waiting_choice"&&t!=="waiting_choice"):!1}let js=null;function dj(e){return e!==!1}async function uj(){if(js!==null)return js;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return js=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(js=!!await e.pushManager.getSubscription(),js):(js=!1,!1)}catch{return js=!1,!1}}function xl(e,t,s){if(jf())try{const r=new Notification(e,{body:t,icon:"/otter-logo.png",tag:s||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>r.close(),8e3),r.onclick=()=>{window.focus(),r.close()}}catch{}}function mj(e){const{name:t,prev:s,curr:r,questionEntered:o}=e,a=String(e.modalMessage||"").replace(/\s+/g," ").trim().slice(0,120);return o&&e.onApproval?{kind:"question",title:t,body:a?Ge.t("event.browser.questionWithMessage",{message:a}):Ge.t("event.browser.question")}:e.onApproval&&r==="waiting_approval"&&s!=="waiting_approval"?{kind:"approval",title:t,body:a?Ge.t("event.browser.approvalWithMessage",{message:a}):Ge.t("event.browser.approval")}:e.onComplete&&dl(s)&&r==="idle"?{kind:"complete",title:t,body:Ge.t("event.browser.finished")}:e.onError&&r==="error"&&s!=="error"?{kind:"error",title:t,body:Ge.t("event.browser.error")}:null}function hj(e,t={}){const s={...cj,...t},r=c.useRef(new Map),o=c.useRef(0),[a,i]=c.useState(null);c.useEffect(()=>{let d=!1;return uj().then(m=>{d||i(m)}),()=>{d=!0}},[]);const l=c.useCallback((d,m,u)=>{const h=Date.now();h-o.current<s.throttleMs||(o.current=h,xl(d,m,u))},[s.throttleMs]);c.useEffect(()=>{var d;if(!(!s.enabled||!jf())&&ao("browser")&&!dj(a)){if(document.hasFocus()){for(const m of e)r.current.set(m.id,Jt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=r.current.get(m.id),h=Jt(m.status,{activeModal:m.activeModal}),p=m.name||m.id,b=h==="waiting_choice"&&u!=="waiting_choice";if(lj(m.muted,u,h)){r.current.set(m.id,h);continue}const f=mj({name:p,prev:u,curr:h,modalMessage:(d=m.activeModal)==null?void 0:d.message,questionEntered:b,onApproval:s.onApproval&&ao("approval"),onComplete:s.onComplete&&ao("completion"),onError:s.onError});f&&l(f.title,f.body,`${f.kind}-${m.id}`),r.current.set(m.id,h)}}},[e,s.enabled,s.onApproval,s.onComplete,s.onError,a,l])}const pj=/^(run|approve|accept|yes|allow|always)/,fj=/^(run|approve|accept|yes|allow|always|proceed|save)/,bj=/^(reject|deny|delete|remove|abort|cancel|no)/;function gd(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").replace(/\s*\(\s*\)/g,"").trim()}function gj(e){const t=gd(e).toLowerCase();return pj.test(t)?"primary":bj.test(t)?"danger":"default"}function xj(e){return fj.test(gd(e).toLowerCase())?"approve":"reject"}function yj(e){return e.map((t,s)=>({label:gd(t),variant:gj(t),action:xj(t),button:t,buttonIndex:s}))}function vj(e,t,s){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:s}function wj(e,t,s,r){return[{label:"Approve",variant:"primary",onClick:()=>{s(e,t,"approve").catch(o=>r==null?void 0:r("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{s(e,t,"reject").catch(o=>r==null?void 0:r("reject",o))}}]}function xd(e){if(!(e==null||e==="")){if(typeof e=="string")return e.trim()||void 0;if(e instanceof Error)return e.message||String(e);if(typeof e=="object"){const t=e,s=t.error??t.message??t.reason;if(typeof s=="string"&&s.trim())return s.trim();if(s&&typeof s=="object")return xd(s);try{return JSON.stringify(e)}catch{return}}return String(e)}}class Sj{constructor(){ze(this,"dedupMap",new Map);ze(this,"DEDUP_WINDOW_MS",5e3);ze(this,"DEDUP_MAX_SIZE",50);ze(this,"DEDUP_CLEANUP_AGE_MS",1e4);ze(this,"toastCallbacks",[]);ze(this,"statusEventCallbacks",[]);ze(this,"resolveActionFn",null);ze(this,"viewRequestRespondFn",null);ze(this,"hydrateInteractivePromptFn",null);ze(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(s=>s!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(s=>s!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}setHydrateInteractivePrompt(t){this.hydrateInteractivePromptFn=t}hydrateInteractivePromptFromEvent(t){const s=this.hydrateInteractivePromptFn;if(!s)return;const r=t.targetSessionId;if(!r)return;const o=ll(t.interactivePrompt);o&&s(r,o)}emitToast(t){for(const s of this.toastCallbacks)s(t)}showToast(t,s="info",r){const o=(r==null?void 0:r.id)||Date.now();this.emitToast({id:o,message:t,type:s,timestamp:o,duration:5e3,...r})}showErrorToast(t,s,r){const o=xd(s);this.showToast(t,"warning",{duration:8e3,...o&&o!==t?{details:o}:{},...r})}isDuplicate(t){const s=Date.now(),r=this.dedupMap.get(t)||0;if(s-r<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,s),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[o,a]of this.dedupMap)s-a>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(o);return!1}resolveOwningDaemon(t){if(t.daemonId){const o=this.ides.find(a=>a.id===t.daemonId&&a.type==="adhdev-daemon");if(o)return o}const s=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(s){const o=s.daemonId;if(o){const a=this.ides.find(i=>i.id===o&&i.type==="adhdev-daemon");if(a)return a}}const r=this.ides.filter(o=>o.type==="adhdev-daemon");return r.length===1?r[0]:null}findOwningSession(t){for(const s of this.ides)if(s.id===t||s.sessionId===t||(Array.isArray(s.childSessions)?s.childSessions:[]).some(o=>(o==null?void 0:o.id)===t))return s;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const s=this.findOwningSession(t.targetSessionId);return(s==null?void 0:s.id)||(s==null?void 0:s.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}isConversationEventMuted(t){const s=t.targetSessionId;if(!s)return!1;for(const r of this.ides){if(r.id===s||r.sessionId===s)return!!r.muted;const a=(Array.isArray(r.childSessions)?r.childSessions:[]).find(i=>(i==null?void 0:i.id)===s);if(a)return!!a.muted}return!1}handleRawEvent(t,s){var x;const r=this.resolveConversationKey(t),o=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),a=r||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(o),l=`${a}:${t.event}:${i}`;if(t.event==="agent:waiting_choice"&&this.hydrateInteractivePromptFromEvent(t),this.isDuplicate(l))return;for(const g of this.statusEventCallbacks)g(t);const d=this.isConversationEventMuted(t),m=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,u=(m==null?void 0:m.type)||"";let h=u&&u!=="adhdev-daemon"?wf(u,{agentName:m==null?void 0:m.cliName}):Ot(u);const p=this.resolveOwningDaemon(t);if(p){const g=yn(p,{fallbackId:p.id});g&&(h=!u||u==="adhdev-daemon"?g:`${g}/${h}`)}let b="",f="info";if(t.event==="agent:generating_completed"){if(b=t.duration?`✅ ${Ge.t("event.taskCompletedWithDuration",{label:h,duration:xw(Number(t.duration)*1e3)})}`:`✅ ${Ge.t("event.taskCompleted",{label:h})}`,f="success",!d)try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started"){if(t.event==="agent:waiting_approval"){if(b=`⚡ ${Ge.t("event.approvalNeeded",{label:h})}`,f="warning",d)b="";else if((x=t.modalButtons)!=null&&x.length&&this.resolveActionFn){const g=this.resolveActionRouteTarget(t);if(!g)return;const S=this.resolveActionFn,w=yj(t.modalButtons).map(v=>({label:v.label,variant:v.variant,onClick:()=>{S(g,"resolve_action",{action:v.action,button:v.button,buttonIndex:v.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),_=vj(h,t.modalMessage,b),k=Date.now();this.emitToast({id:k,message:_,type:f,timestamp:k,targetKey:r||g,actions:w,duration:15e3}),b=""}}else if(t.event==="agent:waiting_choice"){b=`❓ ${Ge.t("event.questionNeeded",{label:h})}`,f="warning";const g=typeof t.modalMessage=="string"&&t.modalMessage.trim()?t.modalMessage.replace(/[\n\r]+/g," ").slice(0,120):"";g&&(b=`${b} — ${g}`);const S=Date.now();this.emitToast({id:S,message:b,type:f,timestamp:S,targetKey:r||t.daemonId,duration:1e4}),b=""}else if(t.event==="monitor:no_progress"){const g=t.elapsedSec?Math.round(t.elapsedSec/60):0;b=g?`⚠️ ${Ge.t("event.noProgressWithDuration",{label:h,minutes:g})}`:`⚠️ ${Ge.t("event.noProgress",{label:h})}`,f="warning",!d&&ao("browser")&&!document.hasFocus()&&xl(`⚠️ ${Ge.t("event.noProgressTitle",{label:h})}`,Ge.t("event.noProgressBody",{duration:g?`${g}m`:""}),`no-progress-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const g=t.requesterName||Ge.t("event.someoneRequester"),S=t.requestId,w=t.orgId;if(b=`${Ge.t("event.viewRequest",{requester:g})}`,f="warning",S&&w&&this.viewRequestRespondFn){const _=Date.now(),k=wj(w,S,this.viewRequestRespondFn,(v,y)=>console.error(`[EventManager] ${v} view request failed:`,y));this.emitToast({id:_,message:b,type:f,timestamp:_,actions:k,duration:3e4}),b=""}ao("browser")&&!document.hasFocus()&&xl(`${Ge.t("event.viewRequestTitle")}`,Ge.t("event.viewRequest",{requester:g}),`view-request-${S}`)}else if(t.event==="team:view_request_approved")b=`✅ ${Ge.t("event.viewRequestApproved")}`,f="success";else if(t.event==="team:view_request_rejected"){const g=t.targetName||Ge.t("event.someoneTarget");b=`❌ ${Ge.t("event.viewRequestDeclined",{target:g})}`,f="warning"}}if(b&&!d){const g=Date.now();this.emitToast({id:g,message:b,type:f,timestamp:g,targetKey:r||t.daemonId,duration:5e3})}}}const Ze=new Sj,Vu=new Map;function Nf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ir(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Si(e){return Xp(e)??null}function kj(e){const t=Si(e);return!t||!Nf(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function zo(e){const t=Si(e);return!t||!Nf(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function $r(e){const t=Si(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Vo(e){const t=Si(e);return!!t&&t.success===!1}function jj(e){var t,s;for(const r of e||[]){if(r.type==="toast"&&((t=r.toast)!=null&&t.message)){const o=r.toast.level==="warning"?"warning":r.toast.level==="success"?"success":"info";Ze.showToast(r.toast.message,o);continue}if(r.type==="notification"&&((s=r.notification)!=null&&s.body)){const o=r.notification.level==="warning"?"warning":r.notification.level==="success"?"success":"info";Ze.showToast(r.notification.body,o)}}}function Nj(e,t){return e&&ir(e.currentValue)?e.currentValue:t}function Cj(e,t){const s=Object.keys(e).filter(o=>t[o]!==void 0);if(s.length===0)return e;const r={...e};for(const o of s)delete r[o];return r}function _j(e,t){return ir(t)?ir(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Aj(e,t){var a,i;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(ir(l))return l}const r=(a=t.controlValues)==null?void 0:a[e];if(ir(r))return r;const o=(i=t.defaultValues)==null?void 0:i[e];return ir(o)?o:void 0}function ga(e,t){return e.options||t[e.id]||[]}const Tj={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session","stop"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function Ij(e,t,s){var r;return((r=Tj[t])==null?void 0:r.has(s.id))===!0}function Mj(e){if(e){if(ci(e))return["busy","generating","starting"];switch(e){case"idle":return["idle"];case"waiting_approval":case"approval":return["approval"];case"waiting_choice":return["picker"];default:return}}}function Rj(e,t){const s=e.visibleWhenState;if(!s||s.length===0)return!0;const r=Mj(t);return r?r.some(o=>s.includes(o)):!0}function yd(e,t){return(e||[]).filter(s=>s.placement==="bar"&&s.hidden!==!0&&!Ij(t.hostIdeType,t.providerType,s)&&Rj(s,t.currentStatus)).sort((s,r)=>(s.order??50)-(r.order??50))}function ic(e,t){return{value:t}}function Pj(e,t,s){var o;return s?((o=ga(e,t).find(a=>a.value===s))==null?void 0:o.label)||s:""}const Ej={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Dj({routeId:e,sessionId:t,hostIdeType:s,providerType:r,displayLabel:o,controls:a,controlValues:i,currentStatus:l,coordinatorHint:d}){const{t:m}=pe("common"),{sendCommand:u}=xt(),{confirm:h,confirmDialog:p}=wr(),b=`${e}:${t||r}`,f=Ej[r]||"#94a3b8",[x,g]=c.useState({}),S=c.useRef({}),w=c.useRef(i);S.current=x,w.current=i;const _=c.useRef(0),k={};for(const T of a||[])T.defaultValue!==void 0&&(k[T.id]=T.defaultValue);const v={...k,...i||{},...Date.now()<_.current?x:{}};c.useEffect(()=>{i&&Date.now()>_.current&&g(T=>Cj(T,i))},[i]);const[y,j]=c.useState(Vu.get(b)||{}),[N,A]=c.useState(null),[R,P]=c.useState(null),M=c.useCallback(async(T,$={})=>{const H={...$,...t&&{targetSessionId:t},...d??{}};return await u(e,T,H)},[e,t,u,d]),E=c.useCallback(async(T,$={})=>{const H=t?{targetSessionId:t}:{agentType:r,...s?{ideType:s}:{}};return await M("invoke_provider_script",{...H,scriptName:T,...$})},[M,r,s,t]),C=c.useCallback((T,$,H)=>{const q=Nj(H,$);g(U=>({...U,[T.id]:q})),jj(H==null?void 0:H.effects)},[]),I=c.useCallback((T,$)=>{g(H=>{const q={...H};return $===void 0?delete q[T.id]:q[T.id]=$,q}),_.current=0},[]);if(!a||a.length===0)return null;const O=yd(a,{hostIdeType:s,providerType:r,currentStatus:l});if(O.length===0)return null;const D=async T=>{if(N===T.id){A(null);return}if(ga(T,y).length>0){A(T.id);return}if(T.dynamic&&T.listScript){P(T.id);try{const H=await E(T.listScript,{}),q=kj(H);if(!q){const oe=$r(H);oe&&Ze.showErrorToast(m("controls.loadOptionsFailed",{label:T.label}),oe);return}const U=q.options;j(oe=>{const ke={...oe,[T.id]:U};return Vu.set(b,ke),ke});const K=Aj(T.id,{localOverrideUntil:_.current,localValues:S.current,controlValues:w.current,defaultValues:k});if(_j(K,q.currentValue)){const oe=q.currentValue;g(ke=>({...ke,[T.id]:oe}))}A(T.id)}catch(H){Ze.showErrorToast(m("controls.loadOptionsFailed",{label:T.label}),H)}finally{P(null)}}},F=async(T,$)=>{A(null);const H=(i==null?void 0:i[T.id])??k[T.id];g(q=>({...q,[T.id]:$})),_.current=Date.now()+5e3;try{if(!T.setScript)return;const q=await E(T.setScript,ic(T,$)),U=zo(q);if(U&&!U.ok||Vo(q))throw new Error((U==null?void 0:U.error)||$r(q)||`Could not update ${T.label}`);C(T,$,U)}catch(q){I(T,H),Ze.showErrorToast(m("controls.updateFailed",{label:T.label}),q)}},z=async T=>{const $=ga(T,y).map(ke=>ke.value);if($.length===0)return;const H=String(v[T.id]||""),U=($.indexOf(H)+1)%$.length,K=$[U];if(typeof K!="string")return;const oe=(i==null?void 0:i[T.id])??k[T.id];g(ke=>({...ke,[T.id]:K})),_.current=Date.now()+5e3;try{if(!T.setScript)return;const ke=await E(T.setScript,ic(T,K)),J=zo(ke);if(J&&!J.ok||Vo(ke))throw new Error((J==null?void 0:J.error)||$r(ke)||`Could not update ${T.label}`);C(T,K,J)}catch(ke){I(T,oe),Ze.showErrorToast(m("controls.updateFailed",{label:T.label}),ke)}},Z=async T=>{const H=!v[T.id],q=(i==null?void 0:i[T.id])??k[T.id];g(U=>({...U,[T.id]:H})),_.current=Date.now()+5e3;try{if(!T.setScript)return;const U=await E(T.setScript,ic(T,H)),K=zo(U);if(K&&!K.ok||Vo(U))throw new Error((K==null?void 0:K.error)||$r(U)||`Could not update ${T.label}`);C(T,H,K)}catch(U){I(T,q),Ze.showErrorToast(m("controls.updateFailed",{label:T.label}),U)}},W=async T=>{var H,q,U;if(!T.invokeScript||T.confirmMessage&&!await h({title:((H=T.confirmTitle)==null?void 0:H.trim())||T.confirmMessage,description:(q=T.confirmTitle)!=null&&q.trim()?T.confirmMessage:void 0,confirmLabel:((U=T.confirmLabel)==null?void 0:U.trim())||m("common.confirm")}))return;const $=(i==null?void 0:i[T.id])??k[T.id];try{const K=await E(T.invokeScript),oe=zo(K);if(oe&&!oe.ok||Vo(K))throw new Error((oe==null?void 0:oe.error)||$r(K)||`Could not run ${T.label}`);oe&&C(T,$??!0,oe)}catch(K){I(T,$),Ze.showErrorToast(m("controls.runFailed",{label:T.label}),K)}};return n.jsxs("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-2xs font-semibold tracking-[0.02em]",style:{borderColor:`${f}33`,background:`${f}12`,color:f},children:o}),O.map(T=>{const $=String(v[T.id]||""),H=Pj(T,y,$),q=N===T.id,U=R===T.id,K=ga(T,y),oe="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-xs font-medium transition-colors whitespace-nowrap";switch(T.type){case"select":return n.jsxs("div",{className:"relative max-w-full",children:[n.jsxs("button",{type:"button",className:`${oe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:q?`${f}55`:"var(--border-default)",background:q?`${f}10`:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void D(T),title:T.label,children:[T.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:T.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:U?m("chatControls.loading"):H||T.label}),n.jsx("span",{className:"text-4xs opacity-55",children:"▼"})]}),q&&K.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-[var(--z-dropdown)]",onClick:()=>A(null)}),n.jsxs("div",{className:"absolute bottom-full left-0 z-[var(--z-dropdown)] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[n.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-3xs font-semibold uppercase tracking-[0.08em] text-text-muted",children:T.label}),K.map(ke=>n.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-xs transition-colors",style:{background:ke.value===$?`${f}14`:"transparent",color:ke.value===$?"var(--text-primary)":"var(--text-secondary)",borderLeft:ke.value===$?`2px solid ${f}`:"2px solid transparent"},title:ke.description||ke.label,onMouseEnter:J=>{J.currentTarget.style.background=`${f}10`},onMouseLeave:J=>{J.currentTarget.style.background=ke.value===$?`${f}14`:"transparent"},onClick:()=>void F(T,ke.value),children:[n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ke.label}),ke.value===$&&n.jsx("span",{className:"shrink-0 text-2xs font-semibold",style:{color:f},children:"✓"})]},ke.value))]})]})]},T.id);case"cycle":return n.jsxs("button",{type:"button",className:`${oe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void z(T),title:`Click to cycle: ${K.map(ke=>ke.label).join(" → ")}`,children:[T.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:T.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:H||T.label}),n.jsx("span",{className:"text-3xs opacity-55",children:"⟳"})]},T.id);case"toggle":return n.jsxs("button",{type:"button",className:`${oe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${f}44`:"var(--border-default)",background:$?`${f}14`:"var(--surface-tertiary)",color:$?f:"var(--text-muted)"},onClick:()=>void Z(T),"aria-pressed":!!$,children:[T.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:T.icon}),T.label]},T.id);case"action":return n.jsxs("button",{type:"button",className:`${oe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void W(T),children:[T.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:T.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:T.resultDisplay==="inline"&&$?`${T.label}: ${$}`:T.label})]},T.id);case"display":return n.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-xs font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},children:[T.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:T.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$?`${T.label}: ${$}`:T.label})]},T.id);default:return null}})]}),p]})}function Lj(e){if(!e||typeof e!="object")return{};const t=e,s=av(t.launch);return{...s?{launch:s}:{},...typeof t.model=="string"&&t.model.trim()?{model:t.model.trim()}:{},...nd(t.modelSource)?{modelSource:t.modelSource}:{}}}const Gu={user:"chosen",remembered:"remembered",mesh_slot:"mesh slot",task_override:"task",provider_default:"default",unspecified:""};function Oj(e,t){return String(t.defaultValue??"").replace(/\{\{(\w+)\}\}/g,(s,r)=>String(t[r]??""))}function Cf(e,t=Oj){const s=e.launch?ov(e.launch.model):void 0,r=(s==null?void 0:s.value)??e.model;if(!r)return null;const o=(s==null?void 0:s.source)??e.modelSource??"unspecified";if(s!=null&&s.changedFrom)return{text:t("chatControls.launchModelChanged",{from:s.changedFrom,to:r,defaultValue:"{{from}} → {{to}} (changed)"}),source:o};const a=Gu[o]?t(`chatControls.launchModelSource.${o}`,{defaultValue:Gu[o]}):"";return{text:a?`${r} · ${a}`:r,source:o}}function $j({surface:e}){const{t}=pe("common"),s=Cf(e,t);return s?n.jsx("span",{className:"inline-flex items-center rounded-full border border-border-subtle px-2 py-0.5 text-2xs text-text-muted","data-testid":"session-launch-chip","data-model-source":s.source,children:s.text}):null}function Fj({isActive:e=!0,isCliTerminal:t=!1,routeId:s,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:l,controlValues:d,currentStatus:m,coordinatorHint:u,launchSurface:h}){const{isVisible:p}=fd(),b=yd(l,{hostIdeType:o,providerType:a,currentStatus:m}),f=b.length>0&&p,x=!!h&&!!Cf(h);return!e||t||!f&&!x?null:n.jsxs("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:[x&&h&&n.jsx("div",{className:"flex justify-end px-3 pt-1",children:n.jsx($j,{surface:h})}),f&&n.jsx(Dj,{routeId:s,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:b,controlValues:d,currentStatus:m,coordinatorHint:u})]})}const Fr=5,_f=10*1024*1024;function Hj({hasDraft:e,isBusy:t=!1}){return!e||t}function Bj(e){return new Promise((t,s)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>s(new Error("Failed to read file")),r.readAsDataURL(e)})}async function Wj(e){if(e.size>_f)return null;const t=await Bj(e),s=t.indexOf(",");if(s<0)return null;const r=t.slice(s+1);return{mimeType:e.type||"image/png",data:r,name:e.name,previewUrl:t}}function Uj(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}function Kj(e){return/[\u1100-\u11FF\u3130-\u318F\uAC00-\uD7A3]/.test(e)}const Af=c.memo(function({contextKey:t,panelLabel:s,isSending:r,isBusy:o=!1,statusMessage:a=null,inlineStatusMessage:i=null,onSend:l,isActive:d=!0,showControlsToggle:m=!1,animateVisibility:u=!0,onControlsToggle:h,messageInput:p}){const{t:b}=pe("common"),f=c.useRef(null),x=c.useRef(null),[g,S]=c.useState(""),[w,_]=c.useState([]),[k,v]=c.useState(null),[y,j]=c.useState(!1),N=c.useRef(!1),A=c.useRef(0),R=50,P=c.useRef(""),M=c.useRef(!1),E=c.useRef(null),C=30,{isVisible:I,toggleVisibility:O}=fd(),D=Uj(p),F=!!g.trim()||w.length>0;c.useEffect(()=>{S(""),_([]),v(null)},[t]),c.useEffect(()=>{var K;d&&((K=f.current)==null||K.focus({preventScroll:!0}))},[t,d]),c.useEffect(()=>{const K=f.current;K&&(K.style.height="auto",g&&(K.style.height=`${Math.min(K.scrollHeight,160)}px`))},[g]);const z=c.useCallback(async K=>{v(null);const oe=Array.from(K).filter(de=>de.type.startsWith("image/"));if(oe.length===0)return;const ke=Fr-w.length;if(ke<=0){v(`Max ${Fr} images`);return}const J=oe.slice(0,ke);if(J.filter(de=>de.size>_f).length>0){v("Image too large (max 10 MB)");return}const re=(await Promise.all(J.map(Wj))).filter(de=>de!==null);_(de=>[...de,...re])},[w.length]),Z=c.useCallback(K=>{_(oe=>oe.filter((ke,J)=>J!==K))},[]),W=c.useCallback(async()=>{const K=g.trim();if(!K&&w.length===0||o||N.current)return;N.current=!0;const oe=w.length>0?[...w]:void 0;try{await l(K,oe)!==!1&&(S(""),_([]),v(null))}finally{N.current=!1}},[g,w,o,l]),T=c.useRef(W);T.current=W;const $=c.useCallback(()=>{M.current&&(M.current=!1,E.current&&(clearTimeout(E.current),E.current=null),setTimeout(()=>{T.current()},0))},[]);c.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]);const H=c.useCallback(K=>{D&&(K.preventDefault(),j(!0))},[D]),q=c.useCallback(()=>j(!1),[]),U=c.useCallback(K=>{D&&(K.preventDefault(),j(!1),K.dataTransfer.files.length>0&&z(K.dataTransfer.files))},[D,z]);return n.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",u?"transition-all duration-200 ease-out":"",y?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:d?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:d?200:0,opacity:d?1:0,transform:d?"translateY(0)":"translateY(10px)",padding:d?"10px 12px":"0 12px",pointerEvents:d?"auto":"none"},"aria-hidden":!d,onDragOver:H,onDragLeave:q,onDrop:U,children:[w.length>0&&n.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:w.map((K,oe)=>n.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[n.jsx("img",{src:K.previewUrl,alt:K.name,className:"w-full h-full object-cover"}),n.jsx("button",{type:"button",onClick:()=>Z(oe),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-3xs leading-none","aria-label":`Remove ${K.name}`,children:"✕"})]},oe))}),n.jsxs("div",{className:"flex gap-2 items-center",title:d?b("chatInput.sendTo",{panel:s}):void 0,children:[m&&n.jsx("button",{type:"button",onClick:()=>{O(),h==null||h()},"aria-label":b(I?"chatInput.hideControls":"chatInput.showControls"),"aria-pressed":I,title:b(I?"chatInput.hideControls":"chatInput.showControls"),className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:n.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[n.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),n.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),n.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),D&&n.jsxs(n.Fragment,{children:[n.jsx("input",{ref:x,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:K=>{K.target.files&&z(K.target.files),K.target.value=""}}),n.jsx("button",{type:"button",onClick:()=>{var K;return(K=x.current)==null?void 0:K.click()},disabled:w.length>=Fr,title:w.length>=Fr?`Max ${Fr} images`:b("chatInput.attachImage"),className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":b("chatInput.attachImage"),children:n.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),n.jsx("div",{className:"flex-1 relative",children:n.jsx("textarea",{ref:f,rows:1,placeholder:a||(D&&w.length>0?b("chatInput.addMessageOptional"):b("chatInput.placeholder",{panel:s})),value:g,onChange:K=>S(K.target.value),onPaste:K=>{if(D&&K.clipboardData.files.length>0&&Array.from(K.clipboardData.files).some(ie=>ie.type.startsWith("image/"))){K.preventDefault(),z(K.clipboardData.files);return}const oe=K.clipboardData.getData("text/plain"),ke=Cv(oe);if(ke===oe)return;K.preventDefault();const J=f.current,ye=(J==null?void 0:J.selectionStart)??g.length,ae=(J==null?void 0:J.selectionEnd)??g.length,re=g.slice(0,ye)+ke+g.slice(ae);S(re);const de=ye+ke.length;requestAnimationFrame(()=>{J==null||J.setSelectionRange(de,de)})},onCompositionUpdate:K=>{P.current=K.data||""},onCompositionEnd:K=>{A.current=Date.now(),K.data&&(P.current=K.data),$()},onKeyDown:K=>{if(K.key!=="Enter"||K.shiftKey)return;if(K.nativeEvent.isComposing||K.keyCode===229||Date.now()-A.current<R){K.preventDefault(),Kj(P.current)&&!M.current&&(M.current=!0,E.current=setTimeout($,C));return}K.preventDefault(),W()},className:"w-full rounded-[20px] px-4 py-2 bg-bg-secondary text-sm text-text-primary resize-none leading-[1.4] block",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))",minHeight:40,maxHeight:160,overflowY:"auto",whiteSpace:"pre-wrap"}})}),n.jsx("button",{onClick:()=>{W()},disabled:Hj({hasDraft:F,isBusy:o}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${F&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:F&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":b("chatInput.sendMessage"),children:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:F?"text-white":"text-text-muted",children:n.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(k||D&&y)&&n.jsx("div",{className:`pt-1.5 px-1 text-2xs ${k?"text-red-400":"text-[var(--accent-primary)]"}`,children:k||b("chatInput.dropImage")}),i&&!k&&n.jsx("div",{className:"pt-2 px-1 text-2xs text-text-muted opacity-80",children:i})]})});function qj({entries:e,onSendNow:t,onCancelQueued:s,isSendingNow:r}){const{t:o}=pe(),a=e.filter(d=>d.queued===!0&&!!d.id);if(a.length===0)return null;const i=a.some(d=>d.stale!==!0),l=o(i?"chat.waitingToSendAria":"chat.notDeliveredAria");return n.jsx("div",{className:"chat-pending-queue-strip","data-testid":"pending-queue-strip","data-pending-queue-count":a.length,role:"region","aria-label":l,children:a.map(d=>n.jsxs("div",{className:"chat-pending-queue-row","data-chat-queued-row":"true","data-chat-queued-stale":d.stale===!0?"true":void 0,children:[n.jsxs("div",{className:"chat-bubble chat-bubble-user chat-pending-queue-bubble",title:d.content,children:[n.jsx("div",{className:"chat-pending-queue-body",children:d.content}),n.jsx("span",{className:d.stale===!0?"chat-pending-queue-clock chat-pending-queue-stale":"chat-pending-queue-clock",role:"img","aria-label":d.stale===!0?o("chat.notDeliveredAria"):o("chat.waitingToSendAria"),title:d.stale===!0?o("chat.notDelivered"):o("chat.waitingToSendAria"),children:d.stale===!0?"⚠":"⏱"})]}),t&&n.jsx("button",{type:"button",onClick:()=>t(d.id),disabled:r,className:"chat-pending-queue-send","aria-label":o("chat.sendNowAria"),title:o("chat.sendNowTitle"),children:"↑"}),s&&n.jsx("button",{type:"button",onClick:()=>s(d.id),disabled:r,className:"chat-pending-queue-cancel","aria-label":o("chat.cancelQueuedAria"),title:o("chat.cancelQueuedTitle"),children:"✕"})]},d.id))})}const zj=c.memo(qj,(e,t)=>e.onSendNow===t.onSendNow&&e.onCancelQueued===t.onCancelQueued&&e.isSendingNow===t.isSendingNow&&e.entries.length===t.entries.length&&e.entries.every((s,r)=>{const o=t.entries[r];return!!o&&s.id===o.id&&s.content===o.content&&s.queued===o.queued&&s.stale===o.stale})),Vj={accent:{track:"--accent-primary",head:"--accent-primary-light"},success:{track:"--status-online",head:"--status-online"},muted:{track:"--text-muted",head:"--text-muted"}};function Zt({size:e=28,thickness:t=2.5,color:s="accent",className:r,label:o}){const a=Vj[s],i={width:e,height:e,border:`${t}px solid color-mix(in srgb, var(${a.track}) 20%, transparent)`,borderTopColor:`var(${a.head})`};return n.jsx("span",{className:ct("block shrink-0 rounded-full animate-spin",r),style:i,role:o?"status":void 0,"aria-label":o,"aria-hidden":o?void 0:!0})}const Gj=1e4;function Yj({machineId:e,blocked:t,retryConnection:s}){const{t:r}=pe("common"),[o,a]=c.useState(!1),i=c.useRef(null);if(c.useEffect(()=>{t||a(!1)},[t]),c.useEffect(()=>{if(!o)return;const d=setTimeout(()=>a(!1),Gj);return()=>clearTimeout(d)},[o]),c.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),!e||!t||!s)return null;const l=()=>{o||(a(!0),s(e))};return n.jsxs("button",{type:"button","data-testid":"chat-machine-reconnect",onClick:l,disabled:o,"aria-label":r("chatPane.reconnectMachine"),title:r("chatPane.reconnectMachineTitle"),className:"inline-flex items-center justify-center gap-1 h-6 px-2 rounded-full leading-none text-3xs font-bold transition-colors bg-red-500/10 border border-red-500/25 text-red-400 hover:bg-red-500/20 disabled:opacity-60 disabled:cursor-not-allowed",style:{pointerEvents:"auto"},children:[o?n.jsx(Zt,{size:11,thickness:2,color:"muted"}):n.jsx(ur,{size:12}),n.jsx("span",{children:r(o?"chatPane.reconnectingMachine":"chatPane.reconnectMachine")})]})}let Tf=xn;function ki(){return Tf()}class Qj{constructor(){ze(this,"listeners",new Map)}send(t,s){return!1}isConnected(){return!1}on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>{var r;(r=this.listeners.get(t))==null||r.delete(s)}}emit(t,...s){var r;(r=this.listeners.get(t))==null||r.forEach(o=>o(...s))}}let If=new Qj;class Jj{sendPtyInput(t,s,r){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,s){return!1}get(t){}onScreenshot(t,s){return()=>{}}onRuntimeEvent(t,s,r){return()=>{}}requestRuntimeSnapshot(t,s,r){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let Dt=new Jj;function Xj(e){e.dashboardWS&&(If=e.dashboardWS),e.connectionManager&&(Dt=e.connectionManager),e.useDaemonsHook&&(Tf=e.useDaemonsHook)}function xa(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Mf="adhdev-pending-queued-messages-v1",Zj=256*1024,eN=24*60*60*1e3,Rf=10*60*1e3;function Pf(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Mf)||"{}");return{byKey:e.byKey&&typeof e.byKey=="object"?e.byKey:{}}}catch{return{byKey:{}}}}function tN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Mf,JSON.stringify(e))}catch{}}function nN(e,t){if(!e||typeof e!="object")return;const s=e;if(!Array.isArray(s.parts))return;let r=0;const o=new Set(s.omitted&&typeof s.omitted=="object"&&Array.isArray(s.omitted.partTypes)?s.omitted.partTypes.filter(l=>typeof l=="string"):[]),a=[];for(const l of s.parts){if(!l||typeof l!="object")continue;const d=l,m=typeof d.type=="string"?d.type:"";if(!m)continue;if(m==="text"){a.push({type:"text",text:typeof d.text=="string"?d.text:""});continue}const u=typeof d.data=="string"?d.data:void 0,h=u?u.length:0;if(u&&r+h<=Zj){r+=h,a.push({type:m,mimeType:typeof d.mimeType=="string"?d.mimeType:void 0,uri:typeof d.uri=="string"?d.uri:void 0,data:u,alt:typeof d.alt=="string"?d.alt:void 0});continue}if(!u){a.push({type:m,mimeType:typeof d.mimeType=="string"?d.mimeType:void 0,uri:typeof d.uri=="string"?d.uri:void 0,alt:typeof d.alt=="string"?d.alt:void 0});continue}o.add(m),a.push({type:m,mimeType:typeof d.mimeType=="string"?d.mimeType:void 0,alt:typeof d.alt=="string"?d.alt:void 0})}const i=typeof s.textFallback=="string"?s.textFallback:t;return{parts:a,textFallback:i,...o.size>0?{omitted:{omitted:!0,partTypes:[...o]}}:{}}}function Ef(e,t){if(!Array.isArray(e))return[];const s=new Set,r=[];let o=0;for(const a of e){if(!a||typeof a!="object")continue;const i=a,l=typeof i.content=="string"?i.content:"",d=typeof i.sentAt=="number"&&Number.isFinite(i.sentAt)?i.sentAt:0,m=typeof i.id=="string"&&i.id?i.id:"";if(!l.trim()||!d||!m||t-d>eN||s.has(m))continue;s.add(m);const u=i.stale===!0||t-d>Rf,h=nN(i.input,l);r.push({entry:{id:m,content:l,sentAt:d,queued:i.queued===!0,settled:!0,stale:u,...h?{input:h}:{}},index:o}),o+=1}return r.sort((a,i)=>a.entry.sentAt-i.entry.sentAt||a.index-i.index),r.map(a=>a.entry).slice(-20)}let Yu=0;function sN(e=Date.now()){try{const t=typeof globalThis<"u"?globalThis.crypto:void 0;if(typeof(t==null?void 0:t.randomUUID)=="function")return t.randomUUID()}catch{}return Yu+=1,`pq-${e}-${Yu}`}function rN(e,t=Date.now()){const s=String(e||"").trim();return s?Ef(Pf().byKey[s],t):[]}function oN(e,t,s=Date.now()){const r=String(e||"").trim();if(!r)return;const o=Pf(),a=Ef(t,s);a.length>0?o.byKey[r]=a:delete o.byKey[r],tN(o)}function Df(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}const aN=12e4;function iN(e){if(typeof e=="string")return e.trim();if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}const cN=/^(?:\s*(?:\[Image #\d+\]|\[image: [^\]\n]{1,100}\]))+\s*/;function lN(e,t){const s=iN(e);if(s===t)return!0;const r=s.replace(cN,"").trim();return r!==s&&r.length>0&&r===t}function dN(e,t){if(!t)return!1;const s=e.meta;return typeof(s==null?void 0:s.sourceMessageId)=="string"&&s.sourceMessageId===t}function Qu(e){const t=e.meta;return typeof(t==null?void 0:t.sourceMessageId)=="string"&&t.sourceMessageId.length>0}function Lf(e,t){if(!t)return 0;let s=0;for(const r of e)String(r.role||"").toLowerCase()==="user"&&lN(r.content,t)&&(s+=1);return s}function uN(e,t,s=Date.now(),r=Rf){if(!e||e.length===0)return{entries:[],changed:!1,retiredByEcho:0,markedStale:0};const o=new Map,a=[];let i=0,l=0,d=!1;const m=t.some(u=>Qu(u))?t.filter(u=>!Qu(u)):t;for(const u of e){const h=u.content.trim();if(!h){d=!0;continue}if(t.some(f=>dN(f,u.id))){i+=1,d=!0;continue}o.has(h)||o.set(h,Lf(m,h));const p=o.get(h)||0;if(p>0){o.set(h,p-1),i+=1,d=!0;continue}if(s-u.sentAt>r&&u.stale!==!0){l+=1,d=!0,a.push({...u,stale:!0});continue}a.push(u)}return d?{entries:a,changed:!0,retiredByEcho:i,markedStale:l}:{entries:e,changed:!1,retiredByEcho:0,markedStale:0}}function mN(e){return{id:`pending-local:${e.id||e.sentAt}`,role:"user",kind:"standard",content:e.content,senderName:"User",timestamp:e.sentAt,receivedAt:e.sentAt,meta:{pendingLocal:!0,queued:e.queued===!0,pendingId:e.id||String(e.sentAt)}}}function hN(e,t,s=Date.now(),r={}){if(!t||t.length===0)return e;const o=new Map,a=[];for(const i of t){const l=i.content.trim();if(!l||s-i.sentAt>aN)continue;o.has(l)||o.set(l,Lf(e,l));const d=o.get(l)||0;if(d>0){o.set(l,d-1);continue}r.excludeQueued&&i.queued===!0&&i.id||a.push(mN(i))}return a.length===0?e:[...e,...a]}function pN(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const s=String(e.kind||"standard").toLowerCase();return s===""||s==="standard"}function cc(e){return pN(e)?String(e.role||"").toLowerCase():""}const fN=4;function bN(e,t){if(e.length===0)return[];for(let a=t.length-1;a>=0;a-=1)if(cc(t[a])==="assistant")return[];const s=t.some(a=>cc(a)==="user"),r=[];let o=!1;for(let a=e.length-1;a>=0&&r.length<fN;a-=1){const i=e[a],l=cc(i);if(l){if(!o&&l==="assistant"){r.unshift(i),o=!0;continue}if(o&&l==="user"){s||r.unshift(i);break}}}return r}function gN(e){let t=!0;for(let s=1;s<e.length;s+=1)if(xa(e[s-1])>xa(e[s])){t=!1;break}return t?e:e.map((s,r)=>({message:s,index:r,ts:xa(s)})).sort((s,r)=>s.ts-r.ts||s.index-r.index).map(s=>s.message)}function xN(e){const{historyMessages:t,liveMessages:s,visibleLiveCount:r}=e,o=Math.max(0,s.length-r),a=o>0?s.slice(0,o):[],i=o>0?s.slice(-r):s,l=bN(a,i),d=l.length>0?[...l,...i]:i,m=t.length===0?d:[...t,...d];return gN(m)}const ht=e=>e.transport==="pty",kr=(e,t)=>ht(e)&&e.mode||"chat",Of=(e,t)=>ht(e)&&kr(e)==="terminal",yN=180;function ps(e){return e.streamSource!=="agent-stream"}function Jn(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function ji(e){var s;const t=typeof((s=e.settings)==null?void 0:s.meshCoordinatorDaemonId)=="string"?e.settings.meshCoordinatorDaemonId:void 0;return t?{meshCoordinatorDaemonId:t}:{}}function $f(e){return e.machineName||""}function ys(e){return Jn(e)}function On(e){return e.agentType||""}function Oa(e){return e.hostIdeType||""}function vd(e){return e.displayPrimary||e.agentName||"Agent"}function Ff(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function vN(e,t){const s=Df(e,t),r=[...s].reverse();return r.find(o=>!(o!=null&&o._localId)&&bi(o).isUserFacing)||r.find(o=>!(o!=null&&o._localId))||s[s.length-1]}function Hf(e,t){const s=vN(e,t),r=cr(s==null?void 0:s.content),o=cr(e.lastMessagePreview);return o&&e.lastMessageRole==="assistant"&&(s==null?void 0:s.role)==="user"?o:r||o||""}function wN(e,t=yN){const s=cr(e);if(!s||t<=0)return"";const r=Array.from(s);return r.length<=t?s:`${r.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function SN(e){return wN(Hf(e)||e.displaySecondary||"")}function Bf(e){return[e.displaySecondary,$f(e)].filter(Boolean)}function hr(e){return e.agentName||Ot(On(e))}function kN(e){var t,s;if(!ps(e)){const r=(s=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:s.trim();if(r)return r}return Ot(Oa(e)||On(e))}function Wf(e){return ps(e)?e.sessionId:e.nativeSessionId}function Ju(e){return ps(e)?"native":e.tabKey}function jN(e){return e.sessionId}function Uf(e,t){if(t)return ps(e)||!t.childSessions?t:t.childSessions.find(s=>s.id===e.sessionId||s.providerType===e.agentType)||t}function NN(e,t){const s=On(e),r=ps(e),o=ht(e),a=r?o?hr(e)||(t==null?void 0:t.cliName)||Ot(Oa(e)||s):t!=null&&t.type?Ot(t.type):Ot(Oa(e)||s):hr(e);return{isNativeConversation:r,isCli:ht(e),isCliTerminal:Of(e),providerType:s,displayLabel:a,targetEntry:Uf(e,t)}}function fs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:ht(e)?{agentType:On(e)}:e.streamSource==="agent-stream"?{agentType:On(e)}:t}function ms(e){return e?ys(e):""}function nr(e,t){e(s=>[...s,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}const CN="Waiting for approval…",_N="Waiting for your answer…";function Ni(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?e.status==="waiting_choice"?"Answer the pending question above.":"Approve or reject the pending request above.":null}function Kf(e){return Ni(e)?(e==null?void 0:e.status)==="waiting_choice"?_N:CN:null}function Go(e){const t=e instanceof Error?e.message:String(e||""),s=t.toLowerCase();return s.includes("awaiting confirmation")?"Approve or reject the pending request above.":s.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":s.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}function qf(){return"select_session"}function AN(){return"open_panel"}function TN({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function IN(e,t,s=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<s:!1}function Xu(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Ps(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}const eo="Waiting to send — the agent is still working.",MN="Too late to cancel — this message was already sent to the agent.";function Zu(e){return!e||typeof e!="object"?!1:e.queued===!0}function RN({feedbackMessage:e,lastSendQueued:t,isGenerating:s}){return!t||e!==eo?!1:!s}function wd(e){return e instanceof Error?e.message:String(e||"")}function em(e){const t=wd(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function tm(e,t){const s=wd(t);return s?s.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${s}`:`⚠️ **${e}** unavailable`}const PN=5e3;function EN(e,t,s=PN){const r=e.get(t);if(!r)return Promise.resolve("unknown");let o;const a=new Promise(i=>{o=setTimeout(()=>i("unknown"),s)});return Promise.race([r,a]).finally(()=>{o&&clearTimeout(o)})}function DN(e,t){if(!t||t.length===0)return;const s=t.map(r=>({type:"image",mimeType:r.mimeType,data:r.data,alt:r.name}));return e&&s.push({type:"text",text:e}),{parts:s,textFallback:e}}function nm(e,t,s,r,o={mode:"queue"}){const a=s?{parts:s.parts,textFallback:s.textFallback}:{parts:[{type:"text",text:t}],textFallback:t};return{messageId:e,input:a,policy:o,...fs(r)}}function Ci({sendDaemonCommand:e,activeConv:t,setActionLogs:s,isStandalone:r}){const[o,a]=c.useState(!1),[i,l]=c.useState(!1),[d,m]=c.useState(null),[u,h]=c.useState(!1),[p,b]=c.useState([]),f=c.useRef(!1),x=c.useRef(null),g=c.useRef([]);g.current=p;const S=c.useRef(new Map),w=(t==null?void 0:t.tabKey)||"",_=c.useRef(w);_.current=w;const k=c.useCallback(C=>{b(I=>{const O=C(I);return O===I?I:(oN(_.current,O),O)})},[]),v=c.useCallback(C=>{k(I=>{const O=uN(I,C);return O.changed?O.entries:I})},[k]);c.useEffect(()=>{m(null),h(!1),b(w?rN(w):[])},[t==null?void 0:t.tabKey,w]);const y=t?Bs(t):!1;c.useEffect(()=>{m(C=>RN({feedbackMessage:C,lastSendQueued:u,isGenerating:y})?null:C),!y&&u&&h(!1)},[y,u]);const j=c.useCallback(async(C,I)=>{if(!t||f.current)return!1;const O=C.trim(),D=Ni(t);if(TN({hasMessage:!!O,blockedMessage:D,sendInFlight:f.current}))return D&&m(D),!1;const F=Date.now(),z={tabKey:t.tabKey,message:O,timestamp:F};if(IN(x.current,z))return m(null),!0;f.current=!0,l(!0),m(null),h(!1),x.current=z;const Z=sN(F),W=DN(O,I);let T=()=>{};S.current.set(Z,new Promise(H=>{T=H}));let $="not-parked";k(H=>[...H,{id:Z,content:O,sentAt:F,...W?{input:W}:{}}].slice(-20));try{const H=ms(t);if(!H)return x.current=Xu(x.current,z),k(K=>K.filter(oe=>oe.id!==Z)),m("Unable to send message right now."),!1;const q=await e(H,"send_chat",nm(Z,O,W,t)),U=Ps(q);if(U!=null&&U.deduplicated)return m(null),!0;if(Zu(U))return $="parked",h(!0),k(K=>K.map(oe=>oe.id===Z?{...oe,queued:!0}:oe)),m(eo),!0;if((U==null?void 0:U.sent)===!1)throw new Error((U==null?void 0:U.error)||"Send failed");if((U==null?void 0:U.success)===!1)throw new Error((U==null?void 0:U.error)||"Send failed");return h(!1),m(null),!0}catch(H){const q=wd(H);return q.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",q):console.warn("Send blocked/failed",H),x.current=Xu(x.current,z),k(U=>U.filter(K=>K.id!==Z)),m(Go(H)),!1}finally{S.current.delete(Z),T($),k(H=>H.map(q=>q.id===Z?{...q,settled:!0}:q)),f.current=!1,l(!1)}},[t,e,k]),N=c.useCallback(async C=>{if(!t||f.current)return!1;const I=g.current,O=C?I.find(z=>z.id===C):I.find(z=>z.queued===!0);if(!O||!O.queued)return!1;const D=O.content.trim();if(!D)return!1;const F=O.id;f.current=!0,l(!0),m(null);try{const z=ms(t);if(!z)return m("Unable to send message right now."),!1;const Z=await e(z,"send_chat",nm(F,D,O.input,t,{mode:"send_now"})),W=Ps(Z);return(W==null?void 0:W.success)===!1?(m(Go(new Error((W==null?void 0:W.error)||"Send now failed"))),!1):(W==null?void 0:W.queuedWithAgent)===!0?(h(!1),k(T=>T.map($=>$.id===F?{...$,queued:!1}:$)),m(null),!0):Zu(W)?(h(!0),k(T=>T.map($=>$.id===F?{...$,queued:!0}:$)),m(eo),!0):(h(!1),k(T=>T.map($=>$.id===F?{...$,queued:!1}:$)),m(null),!0)}catch(z){return console.warn("Send now blocked/failed",z),m(Go(z)),!1}finally{f.current=!1,l(!1)}},[t,e,k]),A=c.useCallback(async C=>{if(!t||!C)return!1;const I=g.current.find(D=>D.id===C);if(!I)return!1;const O=I.content.trim();if(I.settled&&!I.queued)return k(D=>D.filter(F=>F.id!==C)),!0;if(!I.settled&&await EN(S.current,C)==="not-parked")return k(F=>F.filter(z=>z.id!==C)),!0;try{const D=ms(t);if(!D)return m("Unable to cancel this message right now."),!1;const F=await e(D,"cancel_queued_chat",{messageId:C,message:O,...fs(t)}),z=Ps(F),Z=typeof(z==null?void 0:z.cancelled)=="number"&&z.cancelled===0;return Z&&I.stale===!0?(k(W=>W.filter(T=>T.id!==C)),m(W=>W===eo?null:W),!0):(z==null?void 0:z.success)===!1||Z?(m(MN),!1):(k(W=>W.filter(T=>T.id!==C)),m(W=>W===eo?null:W),!0)}catch(D){return console.warn("Cancel queued send failed",D),m(Go(D)),!1}},[t,e,k]),R=c.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(C){console.error("Relaunch failed",C)}},[t,e]),P=c.useCallback(async C=>{if(t)try{const O=(t.modalButtons||[]).indexOf(C),D=C.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),F=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(D),z=ms(t);if(!z)return;const Z=await e(z,"resolve_action",{button:C,action:F?"approve":"reject",...O>=0&&{buttonIndex:O},...fs(t),...ji(t)}),W=Ps(Z);W.success||s(T=>[...T,{routeId:t.tabKey,text:tm(C,W==null?void 0:W.error),timestamp:Date.now()}])}catch(I){em(I)||console.error("[ModalButton] Error:",I),s(O=>[...O,{routeId:t.tabKey,text:em(I)?tm(C,I):`❌ **${C}** error`,timestamp:Date.now()}])}},[t,e,s]),M=c.useCallback(async()=>{if(!(!t||o)){a(!0);try{await e(t.routeId,AN(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(C){console.error("Focus agent failed",C)}finally{a(!1)}}},[t,o,e]),E=p.length>0?p[p.length-1]:null;return c.useMemo(()=>({isSendingChat:i,sendFeedbackMessage:d,lastSendQueued:u,pendingLocalMessage:E,pendingLocalMessages:p,isFocusingAgent:o,handleSendChat:j,handleSendNowQueued:N,handleCancelQueued:A,retireEchoedPendingMessages:v,handleRelaunch:R,handleModalButton:P,handleFocusAgent:M}),[i,d,u,E,p,o,j,N,A,v,R,P,M])}const LN=10,ON=8e3,$N=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function FN(e){return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s'"`]+/gi,"$1[REDACTED:bearer]").replace(/(Bearer\s+)[A-Za-z0-9._~+/-]{12,}=*/gi,"$1[REDACTED:bearer]").replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{20,}\b/g,"[REDACTED:github-token]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:api-key]").replace(/\b(?:adk|adm)_[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:adhdev-token]").replace(/((?:api[_-]?key|token|secret|password|passwd|client[_-]?secret)\s*[:=]\s*)[^\s,'"`}&]+/gi,"$1[REDACTED:secret]").replace(/([?&](?:api[_-]?key|token|secret|password|client_secret)=)[^&#\s]+/gi,"$1[REDACTED:secret]")}function yl(e,t="",s=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if($N.test(t)&&e.trim())return"[REDACTED:secret-field]";const r=FN(e);return r.length>8e3?`${r.slice(0,8e3)}…[truncated ${r.length-8e3} chars]`:r}if(typeof e!="object")return String(e);if(s>=6)return"[MaxDepth]";if(Array.isArray(e)){const r=e.slice(-20).map(o=>yl(o,t,s+1));return e.length>20?[{truncatedBefore:e.length-20},...r]:r}return Object.fromEntries(Object.entries(e).slice(0,80).map(([r,o])=>[r,yl(o,r,s+1)]))}function Hr(e,t){return Array.isArray(e)?e.slice(-t):[]}function HN(e,t=Date.now()){const s=e&&t-e.firstAt<=ON,r=s?e.count+1:1;return r>=LN?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:r,firstAt:s?e.firstAt:t},shouldCollect:!1}}function zf(e){var r,o;const{activeConv:t}=e,s={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((r=e.chatState.liveMessages)==null?void 0:r.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((o=e.chatState.historyMessages)==null?void 0:o.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Hr(e.chatState.liveMessages??t.messages,10),activeConversationMessagesTail:Hr(t.messages,10),visibleMessagesTail:Hr(e.visibleMessages,5),historyMessagesTail:Hr(e.chatState.historyMessages,5),actionLogsTail:Hr(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chat:{hasLiveSnapshot:!!e.chatState.hasLiveSnapshot,hasMoreHistory:!!e.chatState.hasMoreHistory,historyError:e.chatState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return yl(s)}function Vf(e,t={}){const s=e&&typeof e=="object"?e:{},r=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),o=r==="copied"?"locator copied":r==="manual"?"locator shown for manual copy":"locator copy failed";return s.delivery==="daemon_file"?`Chat debug signal sent${typeof s.bundleId=="string"&&s.bundleId.trim()?` (${s.bundleId})`:""}; saved on daemon, ${o}.`:`Chat debug signal sent; ${o}.`}async function Gf(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(s){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",s)}if(typeof document<"u"&&document.body){let s=null;try{if(s=document.createElement("textarea"),s.value=e,s.setAttribute("readonly","true"),s.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(s),s.focus(),s.select(),document.execCommand("copy"))return"copied"}catch{}finally{s==null||s.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function Yf(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const s=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&s.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&s.push("","warnings:",...t.warnings.map(r=>`- ${String(r)}`)),s.join(`
32
32
  `)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
33
33
 
34
34
  \`\`\`json
@@ -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-1-miPo1F.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-Mhmnf_CX.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.68",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.68",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.70",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.70",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.68"),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.70"),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.68"]}),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.68"]}),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.70"]}),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.70"]}),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.68"]})]}),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.70"]})]}),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};