@adhdev/daemon-standalone 1.0.76-rc.4 → 1.0.76-rc.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +4 -4
- package/package.json +2 -2
- package/public/assets/{DashboardMeshGraphDialog-BoHsr8ue.js → DashboardMeshGraphDialog-DX6lkI__.js} +1 -1
- package/public/assets/common-CtbYNW-n.js +1 -0
- package/public/assets/common-Diyetrxr.js +1 -0
- package/public/assets/common-PfaWB_e3.js +1 -0
- package/public/assets/common-wAqqVnE7.js +1 -0
- package/public/assets/index-BuGRmTOW.js +122 -0
- package/public/index.html +1 -1
- package/vendor/mcp-server/index.js +1 -1
- package/public/assets/common-B-bcABBd.js +0 -1
- package/public/assets/common-BRmyrjB5.js +0 -1
- package/public/assets/common-D___Aqd4.js +0 -1
- package/public/assets/common-V_b-iyjQ.js +0 -1
- package/public/assets/index-CI4uEMUa.js +0 -122
|
@@ -0,0 +1,122 @@
|
|
|
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-DX6lkI__.js","assets/mesh-graph-7mv6fb91.js","assets/DashboardMeshGraphDialog-B6V-kTJw.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var ey=Object.defineProperty;var ty=(e,t,s)=>t in e?ey(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var ze=(e,t,s)=>ty(e,typeof t!="symbol"?t+"":t,s);import{r as c,j as n,u as he,i as Qe,M as ny,b as sy,d as ry,e as oy,t as ay,f as iy,a as An,h as cy,R as yt,T as Da,k as Vs,l as ol,m as al,D as ly,n as pi,o as gp,p as dy,q as uy,L as xp,B as my,v as hy,w as Pn,N as il,x as py}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 fy(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),s=[];return{record(r){const o={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...r,payload:r.payload?{...r.payload}:{}};return s.push(o),s.length>t&&s.splice(0,s.length-t),o},list(r={}){const o=Math.max(1,Math.floor(r.limit||100));return s.filter(a=>!r.interactionId||a.interactionId===r.interactionId).filter(a=>!r.topic||a.topic===r.topic).filter(a=>!r.kind||a.kind===r.kind).slice(-o).map(a=>({...a,payload:a.payload?{...a.payload}:{}}))},clear(){s.splice(0,s.length)}}}const bo=fy();function wu(e){const t={};for(const s of e)s.transport&&(t[s.transport]=(t[s.transport]||0)+1);return{count:e.length,ids:e.map(s=>s.id),statuses:e.map(s=>String(s.status||"unknown")),transports:t}}function by(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Su(e){return Array.isArray(e)?[...e]:[]}function yp(e,t){if(!e)return t??null;const s=Object.prototype.hasOwnProperty.call(e,"messages"),r=Object.prototype.hasOwnProperty.call(e,"activeModal"),o=typeof e.id=="string"?e.id.trim():"",a=typeof(t==null?void 0:t.id)=="string"?t.id.trim():"",i=!!o&&!!a&&o!==a;return t?{...t,...e,messages:s?Su(e.messages):i?[]:t.messages,activeModal:r?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...s?{messages:Su(e.messages)}:{},...r?{activeModal:e.activeModal??null}:{}}}function xa(e,t){const s=by(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:yp(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 vp(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?xa(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 et(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 $t(...e){return je(...e)??""}function un(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Vt(...e){for(const t of e)if(typeof t=="boolean")return t}function sc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function gy(e,t){const s=typeof e=="string"?e.trim().replace(/[\\/]+$/,""):"",r=typeof t=="string"?t.trim():"";if(r){if(/^(?:[A-Za-z]:[\\/]|\/)/.test(r))return r;if(s)return`${s}/${r.replace(/^[\\/]+/,"")}`}}function cd(e){switch(e){case"fresh":return 30;case"no_upstream":return 4;case"unchecked":case void 0:return 0;case"stale":return-10;case"unavailable":return-15;default:return 0}}function xy(e,t){if(!Array.isArray(e))return;const s=e.map(r=>{const o=et(r),a=je(o.path),i=je(o.commit),l=je(o.repoPath,o.repo_root)??gy(t,a);if(!a||!i)return null;const d={path:a,commit:i,dirty:Vt(o.dirty)??!1,outOfSync:Vt(o.outOfSync,o.out_of_sync)??!1},u=un(o.lastCheckedAt,o.last_checked_at);u!==void 0&&(d.lastCheckedAt=u),l&&(d.repoPath=l);const m=je(o.error);return m&&(d.error=m),d}).filter(r=>r!==null);return s.length>0?s:void 0}function yy(e){return Vt(e.isGitRepo)!==void 0||!!je(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!je(e.repoRoot,e.repo_root,e.workspace)||un(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 ya(e,t,s){const r=Vt(e.isGitRepo);if(!Object.keys(e).length||!yy(e))return;const o=r??!0,a=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(k=>typeof k=="string"):[],i=un(e.conflicts)??a.length,l=Vt(e.hasConflicts)??i>0,d=je(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,u=xy(e.submodules,d),m=je(e.upstreamStatus,e.upstream_status),h=un(e.upstreamFetchedAt,e.upstream_fetched_at),p=je(e.upstreamFetchError,e.upstream_fetch_error),b=je(e.error),f=un(e.staged)??0,x=un(e.modified)??0,g=un(e.untracked)??0,v=un(e.deleted)??0,S=un(e.renamed)??0,A=un(e.lastCheckedAt,e.last_checked_at);return{workspace:je(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:o,branch:je(e.branch)??null,headCommit:je(e.headCommit)??null,headMessage:je(e.headMessage)??null,upstream:je(e.upstream)??null,upstreamStatus:m??"unchecked",...h!==void 0?{upstreamFetchedAt:h}:{},...p?{upstreamFetchError:p}:{},ahead:un(e.ahead)??0,behind:un(e.behind)??0,staged:f,modified:x,untracked:g,deleted:v,renamed:S,dirty:Vt(e.dirty,e.isDirty,e.is_dirty)??(f+x+g+v+S>0||l),hasConflicts:l,conflictFiles:a,stashCount:un(e.stashCount,e.stash_count)??0,...A!==void 0?{lastCheckedAt:A}:{},...u?{submodules:u}:{},...e.daemonBuildBehind&&typeof e.daemonBuildBehind=="object"?{daemonBuildBehind:e.daemonBuildBehind}:{},...b?{error:b}:{}}}function vy(e){if(!e)return Number.NEGATIVE_INFINITY;let t=0;return e.isGitRepo===!0&&(t+=50),e.isGitRepo===!1&&(t-=10),e.branch&&(t+=20),e.headCommit&&(t+=20),e.upstream&&(t+=10),t+=cd(e.upstreamStatus),typeof e.ahead=="number"&&(t+=2),typeof e.behind=="number"&&(t+=2),Array.isArray(e.submodules)&&e.submodules.length>0&&(t+=4+e.submodules.length),e.error&&(t-=20),t}function wy(e,t){const s=et(e.lastGit??e.last_git),r=et(s.result),o=et(s.status),a=et(r.status),i=et(e.lastProbe??e.last_probe),l=et(i.git),d=et(l.result),u=et(l.status),m=et(d.status);let h=null;for(const p of[o,a,u,m]){const b=ya(p,e);if(!b)continue;const f=vy(b);(!h||f>h.score)&&(h={git:b,score:f})}return h==null?void 0:h.git}function Sy(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 Oa(e){const t=et(e),s=je(t.sessionId,t.session_id,t.id)??Sy(t);return s?{sessionId:s,...je(t.providerType,t.provider)?{providerType:je(t.providerType,t.provider)}:{},...je(t.state,t.status)?{state:je(t.state,t.status)}:{},...je(t.chatStatus,t.chat_status)?{chatStatus:je(t.chatStatus,t.chat_status)}:{},...je(t.lifecycle)?{lifecycle:je(t.lifecycle)}:{},...je(t.surfaceKind,t.surface_kind)?{surfaceKind:je(t.surfaceKind,t.surface_kind)}:{},...je(t.recoveryState,t.recovery_state)?{recoveryState:je(t.recoveryState,t.recovery_state)}:{},...je(t.workspace)?{workspace:je(t.workspace)}:{},...je(t.title)?{title:je(t.title)}:{},...je(t.role)?{role:je(t.role)}:{},...Vt(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:Vt(t.isSelfCoordinator,t.is_self_coordinator)}:{},...je(t.statusNote,t.status_note)?{statusNote:je(t.statusNote,t.status_note)}:{},...je(t.createdAt,t.created_at)?{createdAt:je(t.createdAt,t.created_at)}:{},...je(t.startedAt,t.started_at)?{startedAt:je(t.startedAt,t.started_at)}:{},...je(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:je(t.lastActivityAt,t.last_activity_at)}:{},...Vt(t.isCached,t.is_cached)!==void 0?{isCached:Vt(t.isCached,t.is_cached)}:{}}:null}function ky(e){const t=e&&typeof e=="object"?e:{};return je(t.id,t.nodeId,t.node_id)}function jy(e,t){if(!t)return!1;const s=t.trim();return s?ky(e)===s:!1}var Ny=["antigravity-cli","claude-cli","codex-cli","cursor-cli","grok-cli","kimi","opencode"];function cl(e){const t=e==null?void 0:e.metadata,s=typeof(t==null?void 0:t.accountEmail)=="string"?t.accountEmail.trim():"",r=typeof(t==null?void 0:t.planType)=="string"?t.planType.trim():"",o=[s,r].filter(Boolean);return o.length>0?o.join(" · "):null}var Cy=["daemon_","standalone_"];function _y(e){const t=je(e);return!!t&&/^[0-9a-f]{64}$/i.test(t)}function wp(e){var s,r;return!e||!_y(e.id)?!1:!!!(je(e.machineNickname)||je(e.nickname)||je(e.hostname)||je(e.platform)||je((s=e.machine)==null?void 0:s.hostname)||je((r=e.machine)==null?void 0:r.platform)||je(e.machineId)||Array.isArray(e.sessions)&&e.sessions.length>0)}function ll(e){const t=je(e);if(t){for(const s of Cy)if(t.startsWith(s))return t.slice(s.length).trim()||void 0;return t}}function Ay(e){const t=ll(e);if(t)return t.startsWith("mach_")?`daemon_${t}`:t}function en(e,t){const s=ll(e),r=ll(t);return!s||!r?!1:s===r}var Sp=["easy","medium","difficult","freeform"];function Ty(e){return typeof e=="string"&&Sp.includes(e)}function Iy(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(Ty):[],i=Array.isArray(t.capability)?t.capability.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[],l=Number(t.maxParallel),d=Number.isFinite(l)&&l>0?Math.floor(l):void 0;return{provider:s,...r?{model:r}:{},...o?{thinkingLevel:o}:{},...a.length?{difficulty:a}:{},...i.length?{capability:i}:{},...d!==void 0?{maxParallel:d}:{}}}function kp(e){if(!Array.isArray(e))return[];const t=[];for(const s of e){const r=Iy(s);r&&t.push(r)}return t}function My(e){const t=new Set,s=[];for(const r of kp(e))t.has(r.provider)||(t.add(r.provider),s.push(r.provider));return s}function sn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var jp=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress"];sn(jp);var Ry=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];sn(Ry);var Py=["p2p_offer","p2p_ice"];sn(Py);var Ey=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];sn(Ey);var Ly=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","daemon_mesh_command","p2p_offer","p2p_ice"];sn(Ly);var Dy=["auth_ok","auth_error","machine_evicted","force_disconnect","token_revoked","version_mismatch","force_update_required","command","agent_command","resolve_action","daemon_mesh_result","p2p_ready","p2p_offer","p2p_answer","p2p_ice","mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];sn(Dy);var Oy=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],$y=[...jp,...Oy];sn($y);var Fy=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];sn(Fy);var Hy=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];sn(Hy);var By=["p2p_ready","p2p_answer","p2p_ice"];sn(By);var Wy=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];sn(Wy);var Uy=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];sn(Uy);var Np=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];sn(Np);var Cp=["ping","pong","p2p_evicted","status_event","topic_update","topic_update_chunk","session_output","session_output_chunk","session_io_error","command_result","command_result_chunk","response","transcript_topics_available"];sn(Cp);[...new Set([...Np,...Cp])];var _p=2;function Ky(e,t){const s=typeof t=="number"&&Number.isFinite(t)?t:1;return s===e?"ok":s>e?"reload_required":"daemon_update_required"}var qy="Claude TUI review page is not focused",zy="Claude TUI answer delivered but not confirmed",ld=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"],Ap={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"},Tp={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"},Vy=new Set(ld);function fi(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return Vy.has(t)?t:Tp[t]??null}function dd(e){const t=fi(e);return t?Ap[t]:"unknown"}function bi(e){return dd(e)==="working"}function Gy(e){return dd(e)==="dead"}function Yy(e){const t=dd(e);return t==="working"||t==="blocked"}function ku(e){return ld.filter(t=>Ap[t]===e)}var Qy=["pending","assigned","completed","failed","cancelled"],Jy=["completed","failed","cancelled"],Xy=["code_change","validation","live_debug_readonly","launch_app","convergence"],Zy=["low","normal","high"],ev=["when_idle","interrupt"],Ip=["completed","blocked","failed"],tv=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function Nr(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Nr(Qy);var JO=Nr(Jy);Nr(Xy);Nr(Zy);Nr(ev);Nr(Ip);var nv=["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"],sv=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(sv);var rv=["projects","project_status","project_send","project_read","project_add","discover_repos","memory","skill_view","skill_manage","project_note"];new Set(rv);var ov=["mesh_queue","mesh_direct","plain"],av=["delivered","queued"],iv=["local","p2p"],cv=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],lv=["default","native_source"],dv=["restart","live_holder"],uv=["approval","choice"],mv=["approved","rejected","answered"],hv=["modal_button","auto_approve","prompt_answer"],pv=["genuine","weak"],fv=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],bv=["completed","aborted"],gv=["alive","unknown","read_failed","dead"],ju=["auth_failed","billing_failed"],xv=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],yv=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],vv=["completed","failed"],wv=["operator_update","refine_terminal","validation_terminal"],Sv=["delivered","queued","duplicate"],kv=[...ld,"unknown"],jv=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],Nv=["completed","failed","cancelled"],Cv=["genuine","weak","tool_report","operator"],_v=["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"],Mp=["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"},Ko={t:"bool",optional:!0},Nu={t:"ms"},Av={t:"ms",optional:!0},qo={t:"int",optional:!0},Rt=e=>({t:"enum",values:e}),Qs=e=>({t:"enum",values:e,optional:!0}),Tv={dispatch_accepted:{scope:Rt(ov),messageId:Gs,meshId:Ys,nodeId:Ys,providerType:Ys,attemptNo:qo,dispatchNonce:qo,consumeProfile:Qs(lv),maxTaskRetries:qo,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:Gs,outcome:Rt(av),via:Rt(iv)},delivery_refused:{messageId:Gs,reason:Rt(nv)},dispatch_failed:{workerAbsent:as,reason:Rt(cv),refusalCode:Ys},duplicate_dispatch_refusal:{holderSessionId:Gs,holderAttemptId:Ys},session_rebound:{toSessionId:Gs,reason:Rt(dv)},turn_started:{retro:as},suspension:{modal:Rt(uv),modalKey:Ys},suspension_resolved:{resolution:Rt(mv),via:Rt(hv)},turn_end:{strength:Rt(pv),afterFinalizationTimeout:Ko,hollow:Ko,summary:{t:"summary_ref",optional:!0},blockReason:Qs(fv),releasedByHardCap:Ko,nativeOutcome:Qs(bv),live:{t:"live",optional:!0},reportExpected:Ko,providerFailure:Qs(ju)},transcript_final:{selfAttributing:as,nativeRead:as,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:Av},transcript_activity:{newestActivityAt:Nu},no_progress:{stalledMs:Nu,observedStatus:Rt(kv),finalAssistantPresent:as},liveness:{result:Rt(gv)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:Qs(ju)},session_error:{reason:Rt(xv)},worker_report:{outcome:Rt(Ip),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:as,branchState:Qs(tv),touchedFileCount:qo},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:as,commitsSinceDispatch:{t:"int"},attributable:as},cancel:{reason:Rt(yv)},operator_status:{status:Rt(vv),reason:Rt(wv)},coordinator_ack:{notify:Rt(Mp),outcome:Rt(Sv)},hold_expired:{holdId:Gs,reason:Rt(jv)}},Iv=Object.keys(Tv);function No(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}No(Iv);No(_v);No(Mp);No(Nv);No(Cv);var Mv=["user","remembered","mesh_slot","task_override","provider_default","unspecified"];function ud(e){return typeof e=="string"&&Mv.includes(e)}var Rv=["dashboard","mesh","cli","api","restore","assistant"];function Pv(e){return typeof e=="string"&&Rv.includes(e)}function Ev(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??Rp(e)}function Rp(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 Lv(e){const t=Ev(e);if(!e||!t)return;const s=Rp(e);return{value:t,...s&&s!==t?{changedFrom:s}:{},source:ud(e.source)?e.source:"unspecified"}}function dl(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Cu(e){if(!e||typeof e!="object")return;const t=e,s=[];if(Array.isArray(t.history))for(const u of t.history){if(!u||typeof u!="object")continue;const m=u,h=je(m.value),p=dl(m.at),b=m.via==="launch"||m.via==="change_model"||m.via==="observed"?m.via:void 0;h&&p!==void 0&&b&&s.push({at:p,value:h,via:b})}const r=je(t.requested),o=je(t.launchValue),a=je(t.resolvedDefault),i=je(t.current),l=je(t.observed),d=dl(t.observedAt);return{source:ud(t.source)?t.source:"unspecified",...r?{requested:r}:{},...o?{launchValue:o}:{},...a?{resolvedDefault:a}:{},...i?{current:i}:{},...l?{observed:l}:{},...d!==void 0?{observedAt:d}:{},history:s.slice(-20)}}function Dv(e){if(!e||typeof e!="object")return;const t=e,s=je(t.sessionId),r=je(t.providerType),o=dl(t.launchedAt),a=Cu(t.model),i=Cu(t.thinkingLevel);if(!s||!r||o===void 0||!a||!i)return;const l=je(t.providerVersion),d=je(t.workspace),u=je(t.autoApproveModeId);return{sessionId:s,providerType:r,...l?{providerVersion:l}:{},...t.providerChannel==="stable"||t.providerChannel==="preview"?{providerChannel:t.providerChannel}:{},launchedBy:Pv(t.launchedBy)?t.launchedBy:"api",launchedAt:o,...d?{workspace:d}:{},model:a,thinkingLevel:i,...u?{autoApproveModeId:u}:{}}}function es(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var Ov=["applied","recorded","rejected"];es(Ov);var $v=["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($v);var Fv=["completed","failed"];es(Fv);var Hv=["operator_update","refine_terminal","validation_terminal"];es(Hv);var Bv=["own","fleet"];es(Bv);var Wv=["active","paused","completed","abandoned"];es(Wv);var Uv=["provider_quirk","pattern_to_avoid","recovery_lesson"];es(Uv);var Kv=["coordinator","unknown"];es(Kv);var qv=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];es(qv);var zv=["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(zv);function xs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Vv(e,t){const[s,r]=$a(t);if(!r)return e[s];const o=e[s];return xs(o)?o[r]:void 0}function $a(e){const t=e.indexOf(".");return t<0?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function Gv(e,t){const s={...e};for(const r of Object.keys(t.collections)){const[o,a]=$a(r);if(!a){delete s[o];continue}const i=s[o];if(!xs(i)||!(a in i))continue;const l={...i};delete l[a],s[o]=l}return s}function Yv(e,t,s){const r=new Map,o=[];for(const d of Array.isArray(e)?e:[])!xs(d)||typeof d[s]!="string"||(r.set(d[s],d),o.push(d[s]));for(const d of t.removed??[])r.delete(d);for(const d of t.upsert??[]){const u=d[s];if(typeof u!="string")continue;const m=r.get(u);r.set(u,m?{...m,...d}:{...d})}for(const[d,u]of Object.entries(t.unsetFields??{})){const m=r.get(d);if(!m)continue;const h={...m};for(const p of u)delete h[p];r.set(d,h)}const a=t.order??o,i=[],l=new Set;for(const d of a){const u=r.get(d);!u||l.has(d)||(i.push(u),l.add(d))}for(const[d,u]of r)l.has(d)||i.push(u);return i}function Qv(e,t,s){var a;const r=new Map;for(const i of Object.keys(s.collections))r.set(i,Vv(e,i));const o=Gv(e,s);for(const i of t.unset??[])delete o[i];Object.assign(o,t.set??{});for(const[i,l]of Object.entries(t.objects??{})){const d=xs(o[i])?{...o[i]}:{};for(const u of l.unset??[])delete d[u];Object.assign(d,l.set??{}),o[i]=d}for(const[i,l]of Object.entries(s.collections)){const d=(a=t.collections)==null?void 0:a[i],u=r.get(i);if(d!=null&&d.absent){const[f,x]=$a(i);x||delete o[f];continue}if(!d&&u===void 0)continue;const m=d?Yv(u,d,l):u,[h,p]=$a(i);if(!p){o[h]=m;continue}const b=xs(o[h])?{...o[h]}:{};b[p]=m,o[h]=b}return o}var Jv={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}},Xv={collections:{nodes:"nodeId","queue.tasks":"id",missions:"id"},volatileTopLevel:["refreshedAt","sourceOfTruth","turnPresentationCounters","meshProtocolV2Counters","pendingRetentionCounters","meshProtocolMetrics"],stableRow:(e,t)=>e==="nodes"?Zv(t):t};function Fr(e,t){if(!xs(e))return e;const s={...e};for(const r of t)delete s[r];return s}function Zv(e){const t={...e};if(delete t.lastSeenAt,delete t.updatedAt,delete t.last_seen_at,delete t.updated_at,"dataFreshness"in t&&(t.dataFreshness=Fr(t.dataFreshness,["ageMs","lastProbeAt","staleness"])),"connection"in t&&(t.connection=Fr(t.connection,["lastStateChangeAt"])),"git"in t){const r=Fr(t.git,["lastCheckedAt"]);xs(r)&&Array.isArray(r.submodules)&&r.submodules.length===0&&delete r.submodules,t.git=r}"nodeFacts"in t&&(t.nodeFacts=Fr(t.nodeFacts,["reportedAt"]));const s=t.gitObservation;return xs(s)&&(s.source==="self"||s.source==="local")&&(t.gitObservation=Fr(s,["observedAt"])),t}const ew=new Set(["no_progress","long_generating"]);function tw(e){return!e||ew.has(e)?e:fi(e)??e}function _u(e){return!!e&&typeof e=="object"&&"text"in e}function md(e,t){const s=(t==null?void 0:t.joiner)??" ",r=(t==null?void 0:t.normalizeWhitespace)??!1;let o="";return typeof e=="string"?o=e:Array.isArray(e)?o=e.map(a=>typeof a=="string"?a:_u(a)?String(a.text||""):"").join(s):_u(e)?o=String(e.text||""):o=String(e||""),r?o.replace(/\s+/g," ").trim():o}function fr(e){return md(e,{normalizeWhitespace:!0})}function nw(e){let t="";for(let s=0;s<e.length;s++){const r=e[s],o=e.charCodeAt(s);if(!(o<=31&&r!==`
|
|
3
|
+
`&&r!==" ")&&!(o>=127&&o<=159)&&!(o>=8203&&o<=8207||o>=8234&&o<=8238||o===8288||o===65279)&&o!==65533){if(o===65038||o===65039){const a=t.length>0?t[t.length-1]:"";if(!a||a===`
|
|
4
|
+
`||a===" "||a===" ")continue}t+=r}}return t}function Au(e){var s,r;let t=0;return e.activeChat!==void 0&&(t+=4),e.activeInteractivePrompt!==void 0&&(t+=2),(s=e.childSessions)!=null&&s.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(r=e.agents)!=null&&r.length&&(t+=1),t}function Pp(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 sw(e){let t=2166136261;for(let s=0;s<e.length;s+=1)t^=e.charCodeAt(s),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function rc(e){if(!e||typeof e!="object")return"";const t=e,s=sw(fr(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 rw(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let s=2166136261;for(const r of e){const o=rc(r);for(let a=0;a<o.length;a+=1)s^=o.charCodeAt(a),s=Math.imul(s,16777619)>>>0}return{count:e.length,hash:s.toString(16).padStart(8,"0"),first:rc(e[0]),last:rc(e[e.length-1])}}function ul(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function ml(e,t,s){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ul(e)&&ul(t)){const i=e.messages;Array.isArray(i)&&i===t.messages&&s.add(i)}if(Array.isArray(e)&&Array.isArray(t)){const i=Math.min(e.length,t.length);for(let l=0;l<i;l+=1)ml(e[l],t[l],s);return}const r=e,o=t,a=new Set([...Object.keys(r),...Object.keys(o)]);for(const i of a)i!=="messages"&&ml(r[i],o[i],s)}function ao(e,t){return Array.isArray(e)?e.map(s=>ao(s,t)):!e||typeof e!="object"?e:ul(e)?Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>[r,r==="messages"?rw(o,t):ao(o,t)])):Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,ao(r,t)]))}function ow(e,t){try{const s=new WeakSet;return ml(e,t,s),JSON.stringify(ao(e,s))===JSON.stringify(ao(t,s))}catch{return!1}}function hl(e,t,s){return ow(e,t)?(e._lastUpdate=s,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Ep(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function aw(e,t,s){t[s]!==void 0&&(e[s]=t[s])}function Tu(e,t,s,r){var d;const o=(d=t.chats)!=null&&d.length?t.chats:e.chats,a=vp(e.childSessions,t.childSessions,{preserveMissing:r}),i=yp(t.activeChat,e.activeChat),l=t.workspace||e.workspace;return Pp(e,t,{...e,...t,chats:o,childSessions:a,activeChat:i,workspace:l,_lastUpdate:s})}function iw(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=vp(e.childSessions,t.childSessions,{preserveMissing:s})),(o=t.chats)!=null&&o.length&&!((a=e.chats)!=null&&a.length)&&(r.chats=t.chats),t.workspace&&(r.workspace=t.workspace);for(const i of["title","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","muted","assistant","managedByAssistant","model","modelSource","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])aw(r,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(r.machineNickname=t.machineNickname),t.versionMismatch===!0&&(r.versionMismatch=!0),r}function cw(e,t,s,r){const o=iw(e,t,r),a=Object.keys(o).length>0?Pp(e,t,{...e,...o,_lastUpdate:s}):{...e,_lastUpdate:s};return hl(e,a,s)}function lw(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=Ep(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 dw(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 uw(e,t,s,r,o){return e.transport?s.has(t)&&!r.has(t)?!0:o.has(t):!1}function mw(e,t,s){var m,h;const r=Date.now(),o=new Set((s==null?void 0:s.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(p=>({...p,_lastUpdate:r}));const a=new Map;for(const p of t)a.set(p.id,p);const{incomingIds:i,incomingDaemonIds:l,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:u}=lw(e);for(const p of e){const b=a.get(p.id);if(!b){a.set(p.id,{...p,_lastUpdate:r});continue}const f=Au(p),x=Au(b),g=Ep(p),v=!o.has(g);if(f>x){const y=Tu(b,p,r,v);a.set(p.id,hl(b,y,r));continue}if(f<x){a.set(p.id,cw(b,p,r,v));continue}const S=y=>typeof y=="number"&&Number.isFinite(y),A=S(p.timestamp)&&S(b.timestamp),k=A?p.timestamp:p.timestamp||r,w=A?b.timestamp:b._lastUpdate||b.timestamp||0;if(k>=w){const y=Tu(b,p,r,v);a.set(p.id,hl(b,y,r));continue}(m=p.chats)!=null&&m.length&&!((h=b.chats)!=null&&h.length)&&a.set(p.id,{...b,chats:p.chats})}for(const[p,b]of a){const f=b.daemonId||p.split(":")[0];if(!l.has(f))continue;if(o.has(f)&&u.has(f)&&!i.has(p)){a.delete(p);continue}const x=r-(b._lastUpdate||b.timestamp||0);dw(b,f,x,i,o,d)&&a.delete(p)}for(const[p,b]of a){const f=b.daemonId||p.split(":")[0];if(uw(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 hw(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 pw(e,t){return e.id===t||e.sessionId===t||e.instanceId===t}function fw(e,t,s){const r=t.trim();if(!r)return e;let o=!1;const a=e.map(i=>{if(!pw(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 Lp=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}),Dp=c.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[],hydrateInteractivePrompt:()=>{}}),Op=c.createContext({userName:void 0,setUserName:()=>{},userRole:void 0,usesP2P:!0});function bw({children:e,connectionOverrides:t}){const[s,r]=c.useState([]),[o,a]=c.useState(!1),[i,l]=c.useState([]),[d,u]=c.useState(void 0),m=c.useRef(s);c.useEffect(()=>{m.current=s},[s]);const h=c.useCallback((A,k)=>{r(w=>{let y=!1;const N=w.map(j=>j.id!==A||j.chats===k?j:(y=!0,{...j,chats:k}));return y?N:w})},[]),p=c.useCallback((A,k)=>{r(w=>{const y=w.length===0?A:mw(A,w,k),N=!hw(w,y);return N&&bo.record({kind:"dashboard.entries_applied",payload:{incoming:wu(A),next:wu(y)}}),N?y:w})},[]),b=c.useCallback(()=>a(!0),[]),f=c.useCallback((A,k)=>{r(w=>fw(w,A,k))},[]),x=c.useMemo(()=>({injectEntries:p,markLoaded:b,getIdes:()=>m.current,hydrateInteractivePrompt:f}),[p,b,f]),g=t,v=c.useMemo(()=>({ides:s,updateRouteChats:h,initialLoaded:o,toasts:i,setToasts:l,wsStatus:(g==null?void 0:g.wsStatus)??"connected",isConnected:(g==null?void 0:g.isConnected)??!0,connectionStates:(g==null?void 0:g.connectionStates)??{},connectionTransports:(g==null?void 0:g.connectionTransports)??{},showReconnected:(g==null?void 0:g.showReconnected)??!1,retryConnection:g==null?void 0:g.retryConnection,retryServerConnection:g==null?void 0:g.retryServerConnection,connectionLoginUrl:g==null?void 0:g.connectionLoginUrl,isP2PActive:(g==null?void 0:g.isP2PActive)??!1,p2pStates:(g==null?void 0:g.p2pStates)??{},usesP2P:(g==null?void 0:g.usesP2P)??!0,userRole:g==null?void 0:g.userRole,connectionRetryStatuses:g==null?void 0:g.connectionRetryStatuses,userName:d,setUserName:u}),[s,h,o,i,g==null?void 0:g.wsStatus,g==null?void 0:g.isConnected,g==null?void 0:g.connectionStates,g==null?void 0:g.connectionTransports,g==null?void 0:g.showReconnected,g==null?void 0:g.retryConnection,g==null?void 0:g.retryServerConnection,g==null?void 0:g.connectionLoginUrl,g==null?void 0:g.isP2PActive,g==null?void 0:g.p2pStates,g==null?void 0:g.usesP2P,g==null?void 0:g.userRole,g==null?void 0:g.connectionRetryStatuses,d]),S=c.useMemo(()=>({userName:d,setUserName:u,userRole:g==null?void 0:g.userRole,usesP2P:(g==null?void 0:g.usesP2P)??!0}),[d,u,g==null?void 0:g.userRole,g==null?void 0:g.usesP2P]);return n.jsx(Dp.Provider,{value:x,children:n.jsx(Op.Provider,{value:S,children:n.jsx(Lp.Provider,{value:v,children:e})})})}function yn(){return c.useContext(Lp)}function gw(){return c.useContext(Op)}function br(){return c.useContext(Dp)}const xw=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={...}>.`)}}}),yw=c.createContext(xw);function vw({client:e,children:t}){return n.jsx(yw.Provider,{value:e,children:t})}const ww={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},$p=c.createContext(ww);function Sw({value:e,children:t}){return n.jsx($p.Provider,{value:e,children:t})}function wt(){return c.useContext($p)}function Fp(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function kw(e){const t=Fp(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 jw(e){const[t,s]=c.useState(null),r=c.useCallback(async(i,l)=>{const d=h=>e(i,"launch_cli",{...l,...h}),u=await d({}),m=kw(u);return m?new Promise(h=>{s({providerType:m.providerType||String(l.cliType??"?"),sourceName:m.sourceName,description:m.description,retry:()=>d({confirmExternalUntrusted:!0}),resolve:p=>{p.cancelled?h({success:!1,error:"user_cancelled_untrusted_launch"}):h(p.response)}})}):u},[e]),o=c.useCallback(async()=>{const i=t;if(i){s(null);try{const l=await i.retry(),d=Fp(l);d!=null&&d.success?i.resolve({ok:!0,response:l}):i.resolve({ok:!1,error:(d==null?void 0:d.error)||"launch failed after confirm",response:l})}catch(l){i.resolve({ok:!1,error:(l==null?void 0:l.message)||String(l)})}}},[t]),a=c.useCallback(()=>{const i=t;i&&(s(null),i.resolve({ok:!1,cancelled:!0}))},[t]);return{launchCli:r,pending:t,confirm:o,cancel:a}}const Ue={size:18};function Hp({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("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 gi({size:e=Ue.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}function gr({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),n.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),n.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),n.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),n.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),n.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Nw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("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 Cw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.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 _w({size:e=Ue.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function hd({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),n.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),n.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),n.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Bp({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),n.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),n.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),n.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),n.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Cr({size:e=Ue.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("polyline",{points:"20 6 9 17 4 12"})})}function Aw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"}),n.jsx("path",{d:"m15 5 4 4"})]})}function _r({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Co({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),n.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function XO({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),n.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Tw({size:e=Ue.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Cn({size:e=Ue.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Bn({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),n.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Wp({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"}),n.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),n.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Ws({size:e=Ue.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function Ar({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polyline",{points:"23 4 23 10 17 10"}),n.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function tn({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),n.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),n.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function xr({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M12 22v-5"}),n.jsx("path",{d:"M9 8V2"}),n.jsx("path",{d:"M15 8V2"}),n.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function On({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"5",r:"2"}),n.jsx("circle",{cx:"5",cy:"19",r:"2"}),n.jsx("circle",{cx:"19",cy:"19",r:"2"}),n.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),n.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),n.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function pl({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"}),n.jsx("path",{d:"M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"})]})}function Iw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),n.jsx("polyline",{points:"2 12 12 17 22 12"}),n.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function pd({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function xi({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),n.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),n.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),n.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function fd({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Mw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),n.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),n.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function bd({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polyline",{points:"4 17 10 11 4 5"}),n.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Rw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Up({size:e=Ue.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function go({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function Pw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.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 Lt({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Kp({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",className:t,children:[n.jsx("circle",{cx:"5",cy:"12",r:"1.9"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.9"}),n.jsx("circle",{cx:"19",cy:"12",r:"1.9"})]})}function yi({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"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 Ew({size:e=Ue.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function qp({size:e=Ue.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})})}function Lw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),n.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function Jn({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),n.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function fl({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M8.7 3A6 6 0 0 1 18 8c0 3 .6 5 1.4 6.5"}),n.jsx("path",{d:"M17 17H3s3-2 3-9a5.98 5.98 0 0 1 .6-2.6"}),n.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"}),n.jsx("line",{x1:"2",y1:"2",x2:"22",y2:"22"})]})}function zp({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"5"}),n.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),n.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),n.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),n.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),n.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),n.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),n.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),n.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Vp({size:e=Ue.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Gp({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),n.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),n.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function vi({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),n.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Iu({size:e=Ue.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Dw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("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 Ow({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("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 $w({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),n.jsx("path",{d:"M13 2h9v9"}),n.jsx("path",{d:"M22 2L13 11"})]})}function Fw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polyline",{points:"9 14 4 9 9 4"}),n.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Yp({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("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 Hw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),n.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function Bw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),n.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),n.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function Qp({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"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 yr({size:e=Ue.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`animate-spin ${t??""}`,children:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.22-8.56"})})}function Ww({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polyline",{points:"16 3 21 3 21 8"}),n.jsx("line",{x1:"4",y1:"20",x2:"21",y2:"3"}),n.jsx("polyline",{points:"21 16 21 21 16 21"}),n.jsx("line",{x1:"15",y1:"15",x2:"21",y2:"21"}),n.jsx("line",{x1:"4",y1:"4",x2:"9",y2:"9"})]})}function Jp({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"}),n.jsx("path",{d:"M13 13l6 6"})]})}function Uw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M18 11V6a2 2 0 0 0-4 0v5"}),n.jsx("path",{d:"M14 10V4a2 2 0 0 0-4 0v6"}),n.jsx("path",{d:"M10 10.5V6a2 2 0 0 0-4 0v8"}),n.jsx("path",{d:"M18 8a2 2 0 0 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15"})]})}function Kw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("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 qw({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2",ry:"2"}),n.jsx("line",{x1:"12",y1:"18",x2:"12.01",y2:"18"})]})}function Fa({size:e=Ue.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),n.jsx("circle",{cx:"18",cy:"6",r:"3"}),n.jsx("circle",{cx:"6",cy:"18",r:"3"}),n.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function zw({providerType:e,sourceName:t,description:s,onConfirm:r,onCancel:o}){const{t:a}=he("common"),i=c.useRef(null);return c.useEffect(()=>{var l;(l=i.current)==null||l.focus()},[]),c.useEffect(()=>{const l=d=>{d.key==="Escape"&&o()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[o]),n.jsx("div",{role:"dialog","aria-modal":"true","aria-label":a("machine.confirmExternal.dialogAria"),className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:o,style:{pointerEvents:"auto"},children:n.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-amber-500/40 rounded-lg shadow-xl max-w-lg w-full",onClick:l=>l.stopPropagation(),children:[n.jsxs("div",{className:"px-4 py-3 border-b border-border-subtle flex items-center gap-2",children:[n.jsx("span",{"aria-hidden":!0,className:"text-amber-400",children:n.jsx(tn,{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 Xp=c.createContext(null);function Vw({sendDaemonCommand:e,children:t}){const s=jw(e),r=c.useMemo(()=>({launchCli:s.launchCli}),[s.launchCli]);return n.jsxs(Xp.Provider,{value:r,children:[t,s.pending&&n.jsx(zw,{providerType:s.pending.providerType,sourceName:s.pending.sourceName,description:s.pending.description,onConfirm:s.confirm,onCancel:s.cancel})]})}function wi(){const e=c.useContext(Xp);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(),u=o(l),m=l.startsWith("http")?new URL(u):new URL(u,typeof window<"u"?window.location.origin:"http://localhost");return d&&m.searchParams.set("token",d),!l.startsWith("http")&&!t?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function i(l,d={}){const u={"Content-Type":"application/json",...d.headers||{}},m=s==null?void 0:s();m&&(u.Authorization=`Bearer ${m}`);const h=o(l),p=new AbortController,b=setTimeout(()=>p.abort(),15e3);try{const f=await fetch(h,{...d,headers:u,signal:p.signal});if(f.status===401)throw r==null||r(),new Error("Unauthorized");if(!f.ok){const x=await f.json().catch(()=>({error:f.statusText}));throw new Error(x.error||`API Error: ${f.status}`)}return f.json()}finally{clearTimeout(b)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:l=>i(`/api/v1/daemons/${l}/status`),sendCommand:(l,d,u={})=>i(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:d,payload:u})}),execTerminal:(l,d,u)=>i(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:u})}),sendAgentMessage:(l,d,u)=>i(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:u})}),getAgentStatus:l=>i(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,d,u)=>i(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:u?"approve":"reject"})}),getMuxState:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,d,u={})=>i(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:u})}),getMuxEventsUrl:l=>a(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>a(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:i}}function Si(e,t={}){if(!e)return"";const{suffix:s="",nowLabel:r="now",nowThreshold:o=60}=t,a=Date.now()-e,i=Math.floor(a/1e3);if(i<o)return r;const l=Math.floor(i/60);if(l<60)return`${l}m${s}`;const d=Math.floor(l/60);if(d<24)return`${d}h${s}`;const u=Math.floor(d/24);return u<7?`${u}d${s}`:new Date(e).toLocaleDateString()}const Zp=e=>Si(e);function _o(e){if(e==null||e==="")return null;const t=e instanceof Date?e.getTime():typeof e=="number"?e:Date.parse(e);return Number.isFinite(t)&&t>0?t:null}function Ao(e){var s,r;if(e)return e;const t=((s=Qe)==null?void 0:s.resolvedLanguage)||((r=Qe)==null?void 0:r.language);return t&&t!=="cimode"?t:void 0}function Ha(e,t={}){const s=_o(e);if(s===null)return"";const r=Ao(t.locale),o=t.now??Date.now(),a=Math.round((s-o)/1e3),i=Math.abs(a);let l;try{l=new Intl.RelativeTimeFormat(r,{numeric:"auto",style:"short"})}catch{l=new Intl.RelativeTimeFormat(void 0,{numeric:"auto",style:"short"})}return i<45?l.format(0,"second"):i<3600?l.format(Math.round(a/60),"minute"):i<86400?l.format(Math.round(a/3600),"hour"):i<7*86400?l.format(Math.round(a/86400),"day"):xd(s,{locale:r})}function gd(e,t){try{return new Intl.DateTimeFormat(e,t)}catch{return new Intl.DateTimeFormat(void 0,t)}}function To(e,t={}){const s=_o(e);return s===null?"":gd(Ao(t.locale),{dateStyle:"medium",timeStyle:t.seconds?"medium":"short"}).format(s)}function xd(e,t={}){const s=_o(e);return s===null?"":gd(Ao(t.locale),{dateStyle:"medium"}).format(s)}function ki(e,t={}){const s=_o(e);return s===null?"":gd(Ao(t.locale),{timeStyle:t.seconds?"medium":"short"}).format(s)}function ZO(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const s=Math.floor(t/60);if(s<60)return`${s}m`;const r=Math.floor(s/60);return r<48?`${r}h ${s%60}m`:`${Math.floor(r/24)}d ${r%24}h`}function is(e,t,s){try{return new Intl.NumberFormat(s,{style:"unit",unit:t,unitDisplay:"short"}).format(e)}catch{return`${e}${t[0]}`}}function Yw(e,t={}){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";const s=Ao(t.locale),r=Math.round(e/1e3);if(r<60)return is(r,"second",s);const o=Math.floor(r/60);if(o<60)return is(o,"minute",s);const a=Math.floor(o/60);if(a<48){const d=o%60;return d?`${is(a,"hour",s)} ${is(d,"minute",s)}`:is(a,"hour",s)}const i=Math.floor(a/24),l=a%24;return l?`${is(i,"day",s)} ${is(l,"hour",s)}`:is(i,"day",s)}function ef(e){return e?ki(e):""}function yd(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Qw(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}const Jw=new Set(["https:","http:","mailto:","file:"]);function Mu(e){if(e)try{const t=new URL(e);return Jw.has(t.protocol)?e:void 0}catch{return}}function Hr(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function oc(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function Ru(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t^e.charCodeAt(s),t|=0;return(t>>>0).toString(36)}function Xw(e){const t=tf(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 tf(e){const t=e.toolBlockRef;if(t&&typeof t=="object")return{toolBlockRef:t};const s=e;return s._expandable===!0&&typeof s.messageId=="string"&&s.messageId?{messageId:s.messageId}:null}function vd(e,t){const s=e;if(typeof s.messageId=="string"&&s.messageId)return`mid:${s.messageId}`;const r=md(e.content,{joiner:`
|
|
5
|
+
`}),o=[e.id?`id:${e.id}`:"",s._localId?`local:${s._localId}`:"",e.bubbleId?`bubble:${e.bubbleId}`:"",e.providerUnitKey?`unit:${e.providerUnitKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",typeof e.sequence=="number"?`seq:${e.sequence}`:""].filter(Boolean),a=[e.id?`id:${e.id}`:"",s._localId?`local:${s._localId}`:"",s._turnKey?`turn:${s._turnKey}`:"",e.bubbleId?`bubble:${e.bubbleId}`:"",e.providerUnitKey?`unit:${e.providerUnitKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",typeof e.sequence=="number"?`seq:${e.sequence}`:""].filter(Boolean);if(a.length>0){if(o.length===0){const d=e.receivedAt||e.timestamp||0;return[...a,`role:${e.role??""}`,`chash:${Ru(r)}`,...d?[`ts:${d}`]:[]].join("|")}return a.join("|")}const i=e.receivedAt||e.timestamp||0;return[e.role?`role:${e.role}`:"role:",`chash:${Ru(r)}`,i?`ts:${i}`:""].filter(Boolean).join("|")}function Zw(e){const t=e.map((o,a)=>vd(o)),s=new Map;for(const o of t)s.set(o,(s.get(o)??0)+1);const r=new Map;return t.map(o=>{if((s.get(o)??0)<2)return o;const a=r.get(o)??0;return r.set(o,a+1),`${o}|dup:${a}`})}function nf(e){let t=2166136261;for(const s of e){const r=String(s||"");for(let o=0;o<r.length;o+=1)t^=r.charCodeAt(o),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function eS(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function sf(e){return e?nf([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),eS(e.content)]):""}const wd=200,tS=80,Pu=650,Br=new Map;function Ba(e,t){if(!e)return!1;const s=String(e.messageFingerprint||"");return s?s===String(t||""):!0}function nS(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=String(t||"").trim();if(s)return`${e.length}:${s}`;const r=e[e.length-1];return`${e.length}:${sf(r)}`}function sS(e,t,s,r){return e||!t?!1:Ba(s,r)}function rS({scrollTop:e,scrollHeight:t,clientHeight:s,topThresholdPx:r=tS,bottomThresholdPx:o=wd}){const a=Math.max(0,Number(e)||0),i=Math.max(0,Number(t)||0),l=Math.max(0,Number(s)||0);return Math.max(0,i-l)<=0?{showTop:!1,showBottom:!1}:{showTop:a>r,showBottom:Math.max(0,i-a-l)>o}}function oS(e){return rS({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function to(e,t=wd){return!!e&&e.fromBottom>=t}function aS(e,t){return Ba(e,t)?!to(e):!0}function iS({hasSelection:e,userScrolledUp:t,hasChatContentChanged:s=!0}){return!(e||t||!s)}function cS({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:s}){return e?!1:s||!t}function ac(e,t){const s=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(s)?s:t.top}function rf({text:e,size:t="sm"}){const{t:s}=he("common"),[r,o]=c.useState(!1),a=c.useCallback(u=>{u.preventDefault(),u.stopPropagation(),navigator.clipboard.writeText(e).then(()=>{o(!0),setTimeout(()=>o(!1),1500)}).catch(()=>{})},[e]),i=t==="code",l=s(i?"chat.copyCode":"chat.copyMessage"),d=i?12:11;return n.jsx("button",{type:"button",onClick:a,"aria-label":l,title:i?l:void 0,className:i?"chat-code-copy-btn":"chat-copy-btn",children:r?n.jsx(Cr,{size:d}):n.jsx(Bp,{size:d})})}function bl(e){var t;if(e==null||typeof e=="boolean")return"";if(typeof e=="string"||typeof e=="number")return String(e);if(Array.isArray(e))return e.map(bl).join("");if(c.isValidElement(e)){const s=(t=e.props)==null?void 0:t.children;return bl(s)}return""}function lS(e){const t=bl(e.children);return n.jsxs("pre",{...e,children:[e.children,n.jsx(rf,{text:t,size:"code"})]})}const dS={pre:lS},uS=[sy,{singleTilde:!1}],mS=[uS,ry,oy],ji=c.memo(function({content:t,renderAsPreformatted:s,renderAsMarkdown:r}){return s?n.jsx("pre",{className:"chat-preformatted",children:t}):r?n.jsx(ny,{remarkPlugins:mS,components:dS,children:t}):n.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function Eu({text:e,preformatted:t}){return e?n.jsx(ji,{content:e,renderAsPreformatted:t,renderAsMarkdown:!t&&yd(e)}):null}function zo({kind:e,label:t,detail:s}){return n.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[n.jsx("span",{className:"font-medium",children:e}),t?n.jsx("span",{className:"ml-1 break-all",children:t}):null,s?n.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:s}):null]})}function hS({part:e,preformatted:t}){if(e.type==="text")return n.jsx("div",{children:n.jsx(Eu,{text:String(e.text||""),preformatted:t})});if(e.type==="image"){const s=oc(e),r=e.alt||e.description||Hr(e.uri,"image");return s?n.jsx("img",{src:s,alt:r,className:"max-w-full rounded-md border border-border-subtle"}):n.jsx("div",{children:n.jsx(zo,{kind:"Image",label:r,detail:e.mimeType})})}if(e.type==="audio"){const s=oc(e);return s?n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("audio",{controls:!0,src:s,className:"max-w-full"}),e.transcript?n.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:e.transcript}):null]}):n.jsx("div",{children:n.jsx(zo,{kind:"Audio",label:Hr(e.uri,"audio"),detail:e.transcript||e.mimeType})})}if(e.type==="video"){const s=oc(e),r=e.title||e.name||e.alt||Hr(e.uri,"video"),o=[e.transcript,e.description,e.mimeType].filter(Boolean).join(`
|
|
6
|
+
`);return n.jsxs("div",{className:"flex flex-col gap-1",children:[s?n.jsx("video",{controls:!0,src:s,poster:e.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):n.jsx(zo,{kind:"Video",label:r,detail:o}),s&&o?n.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]})}if(e.type==="resource_link"){const s=e.title||e.name||Hr(e.uri,"resource"),r=[e.description,e.mimeType].filter(Boolean).join(`
|
|
7
|
+
`),o=Mu(e.uri);return n.jsxs("div",{className:"flex flex-col gap-1",children:[o?n.jsx("a",{href:o,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:s}):n.jsx(zo,{kind:"Resource",label:s,detail:r}),o&&r?n.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r}):null]})}if(e.type==="resource"&&e.resource){const s=Hr(e.resource.uri,"resource");if(e.resource.text)return n.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[n.jsx("div",{className:"text-2xs opacity-70 mb-1",children:s}),n.jsx(Eu,{text:e.resource.text,preformatted:!0})]});const r=Mu(e.resource.uri);if(r)return n.jsx("a",{href:r,target:"_blank",rel:"noreferrer",className:"underline break-all",children:s})}return null}function pS({parts:e,renderAsPreformatted:t}){return n.jsx("div",{className:"flex flex-col gap-2",children:e.map((s,r)=>n.jsx(hS,{part:s,preformatted:t},`${s.type}-${r}`))})}function fS({body:e,className:t,text:s,asPre:r}){if(e.type==="parts"){const a=n.jsx(pS,{parts:e.parts,renderAsPreformatted:e.preformatted});return t===null?a:n.jsx("div",{className:t,children:a})}const o=s??e.text;return t===null?n.jsx(n.Fragment,{children:o}):r&&e.type==="pre"?n.jsx("pre",{className:t,children:o}):e.type==="plain"?n.jsx("div",{className:t,style:{whiteSpace:"pre-wrap"},children:o}):n.jsx("div",{className:t,children:n.jsx(ji,{content:o,renderAsPreformatted:e.type==="pre",renderAsMarkdown:e.type==="markdown"})})}const Lu="chat-bubble-header",bS={user:{outer:"chat-message-row chat-message-row-user self-end",root:"chat-bubble chat-bubble-user",header:Lu,label:"chat-sender",meta:"chat-bubble-header-end",body:"chat-markdown",expand:"chat-bubble-expand",showLabel:!0},assistant:{outer:"chat-message-row chat-message-row-assistant self-start",root:"chat-bubble chat-bubble-assistant",header:Lu,label:"chat-sender",meta:"chat-bubble-header-end",body:"chat-markdown",expand:"chat-bubble-expand",showLabel:!0},tool:{root:"self-start chat-msg-tool",header:"chat-msg-tool-meta",headerAria:"chat.toolMessageAria",label:"tool-label",meta:"chat-bubble-header-end chat-msg-tool-header-end",body:"tool-text w-full",expand:"chat-msg-tool-expand",showLabel:!0},thought:{root:"self-start chat-msg-thought",header:"chat-msg-header",label:"chat-row-label",meta:"chat-bubble-header-end",body:"chat-msg-body",expand:"chat-msg-thought-expand",showLabel:!0},terminal:{root:"self-start chat-msg-terminal",header:"chat-msg-header",label:"chat-row-label",meta:"chat-bubble-header-end",body:"chat-msg-body",bodyPre:!0,expand:"chat-msg-terminal-expand",showLabel:!0},activity:{root:"self-start chat-msg-activity",header:"chat-msg-activity-meta",headerAria:"chat.activityMessageAria",label:"chat-row-label",meta:"chat-bubble-header-end",body:"chat-msg-activity-body",expand:"chat-msg-activity-expand",showLabel:!0},system:{root:"self-center chat-msg-system",header:"chat-msg-system-meta",label:"chat-row-label",meta:"chat-bubble-header-end",body:null,expand:"chat-msg-system-expand",headerLast:!0}};function gS(e){const{t}=he("common");return"text"in e?e.text:t(e.i18nKey)}function xS({icon:e}){switch(e){case"thought":return n.jsx(Ew,{size:13});case"tool-dot":return n.jsx("span",{className:"tool-icon","aria-hidden":"true"});case"activity-dot":return n.jsx("span",{className:"activity-dot"});case"running":return n.jsx("span",{children:n.jsx(yr,{size:12})});case"done":return n.jsx("span",{children:n.jsx(Cr,{size:12})});case"git":return n.jsx("span",{className:"chat-row-icon","aria-hidden":"true",children:n.jsx(Fa,{size:11})});default:return null}}function Sd({className:e,copyText:t,timestamp:s}){return t===null&&s===null?null:n.jsxs("span",{className:`chat-row-meta ${e}`,children:[t!==null&&n.jsx(rf,{text:t}),s!==null&&n.jsx("span",{className:"chat-time",children:ef(s)})]})}function of({collapse:e,className:t,expanded:s,onToggle:r,remoteState:o,onExpandRemote:a,onCollapseRemote:i}){const{t:l}=he("common"),d=`chat-row-expand ${t}`;if(e.mode==="none")return null;if(e.mode==="remote"){if(!a)return null;if((o==null?void 0:o.status)==="loading")return n.jsx("div",{className:d,"aria-live":"polite",children:l("chat.toolExpandLoading")});if((o==null?void 0:o.status)==="error"){const m=o.error==="source_changed";return n.jsx("div",{className:`${d} chat-row-expand-error ${t}-error`,role:"status","data-expand-error-reason":o.error??"unknown",children:l(m?"chat.toolExpandStale":"chat.toolExpandUnavailable")})}const u=(o==null?void 0:o.status)==="expanded";return n.jsx("button",{type:"button",className:d,"aria-expanded":u,onClick:u?i:()=>a(e.address),children:l(u?"chat.toolCollapse":"chat.toolExpand")})}return r?n.jsx("button",{type:"button",className:d,"aria-expanded":s,onClick:r,children:l(s?"chat.toolCollapse":"chat.toolExpand")}):null}function yS(e,t,s){if(e.body.type==="parts")return;const r=(s==null?void 0:s.status)==="expanded"&&s.text!==void 0?s.text:e.body.text,o=e.collapse;return o.mode==="local"&&!t&&r.length>o.threshold?`${r.slice(0,o.previewChars)}…`:r}function vS({model:e,expanded:t,onToggle:s,remoteState:r,onExpandRemote:o,onCollapseRemote:a,children:i}){const{t:l}=he("common"),d=e.kind==="injected"?"system":e.kind,u=bS[d],m=gS(e.label),h=e.surface==="activity",p=!!u.outer,b=e.body.type==="parts"||e.body.text.length>0,f=t||(r==null?void 0:r.status)==="expanded",x=yS(e,f,r);if(p&&!b&&e.kind!=="user")return n.jsx("div",{className:u.outer});const g=u.headerLast?"span":"div",v=n.jsxs(g,{className:`chat-row-header ${u.header}${p?b?" mb-1.5":" mb-0":""}`,"aria-label":u.headerAria?l(u.headerAria):void 0,children:[n.jsx(xS,{icon:e.icon}),u.showLabel&&n.jsx("span",{className:u.label,children:m}),n.jsx(Sd,{className:u.meta,copyText:b?e.copyText:null,timestamp:e.timestamp})]}),S=b?n.jsx(fS,{body:e.body,className:u.body,text:x,asPre:u.bodyPre}):null,A=n.jsx(of,{collapse:e.collapse,className:u.expand,expanded:f,onToggle:s,remoteState:r,onExpandRemote:o,onCollapseRemote:a}),k=n.jsxs("div",{className:`chat-row chat-row-${e.kind} ${u.root}`,"data-chat-row-kind":e.kind,"data-chat-activity-row":h?"true":void 0,title:d==="system"&&e.body.type!=="parts"?e.body.text:void 0,children:[!u.headerLast&&v,S,A,u.headerLast&&v,i]});return u.outer?n.jsx("div",{className:u.outer,children:k}):k}const wS={mode:"local",threshold:0,previewChars:0};function SS({segment:e,timestamp:t,open:s,onToggle:r}){const{t:o}=he("common"),a=e.outcome||"",i=o("chat.relayLabel",{project:e.project||"",outcome:o(`chat.relayOutcome.${a}`,{defaultValue:a})});return n.jsxs("div",{className:"chat-relay-card","data-relay-outcome":a,"data-expanded":s?"true":"false",children:[n.jsxs("div",{className:"chat-row-header chat-relay-header",children:[n.jsx("span",{className:"chat-row-icon","aria-hidden":"true",children:n.jsx(Ww,{size:12})}),n.jsx("span",{className:"chat-relay-label",children:i}),e.idle&&n.jsx("span",{className:"chat-relay-badge",children:o("chat.relayIdle")}),n.jsx(Sd,{className:"chat-bubble-header-end",copyText:e.body||null,timestamp:t})]}),s?n.jsx("div",{className:"chat-relay-body chat-markdown",children:n.jsx(ji,{content:e.body,renderAsPreformatted:!1,renderAsMarkdown:yd(e.body)})}):e.preview?n.jsx("div",{className:"chat-relay-preview",children:e.preview}):null,e.body&&n.jsx(of,{collapse:wS,className:"chat-relay-expand",expanded:s,onToggle:r})]})}function kS({segment:e,timestamp:t}){const{t:s}=he("common"),r=e.source==="signal"?e.project||"":e.source==="review"?s("chat.reviewLabel"):s("chat.daemonNoticeLabel"),o=e.source==="review"?hd:Jn;return n.jsxs("div",{className:"chat-notice-chip","data-injected-source":e.source,title:e.body,children:[n.jsx("span",{className:"chat-row-icon","aria-hidden":"true",children:n.jsx(o,{size:11})}),n.jsx("span",{className:"chat-notice-chip-label",children:r}),n.jsx("span",{className:"chat-notice-chip-text",children:e.preview}),n.jsx(Sd,{className:"chat-bubble-header-end",copyText:e.body||null,timestamp:t})]})}function jS({model:e,openSegments:t,onToggleSegment:s}){var a,i;const r=((a=e.injected)==null?void 0:a.segments)??[],o=new Set(t?t.split(","):[]);return n.jsx("div",{className:"chat-row chat-row-injected self-stretch chat-msg-injected","data-chat-row-kind":"injected","data-injected-source":(i=e.injected)==null?void 0:i.source,children:r.map((l,d)=>l.source==="relay"?n.jsx(SS,{segment:l,timestamp:e.timestamp,open:o.has(String(d)),onToggle:s?()=>s(d):void 0},`relay-${d}`):l.source==="text"?n.jsx("div",{className:"chat-injected-text",style:{whiteSpace:"pre-wrap"},children:l.body},`text-${d}`):n.jsx(kS,{segment:l,timestamp:e.timestamp},`${l.source}-${d}`))})}const kd="adhdev_chat_activity_visible",Du=new Set(["hidden","debug","internal"]),Ou=new Set(["visible","user","chat"]),NS=new Set(["debug","trace","internal"]),CS=new Set(["tool_call","terminal_command","runtime_activity"]),_S=new Set(["runtime_status","provider_chrome","control"]),AS=new Set(["thought","tool","terminal"]);function af(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function ir(e){return typeof e=="string"?e.trim().toLowerCase():""}function ic(e,t,s){return e[s]??(t==null?void 0:t[s])}function $u(e,t,s){const r=e;return s.some(o=>r[o]===!0||(t==null?void 0:t[o])===!0)}function TS(e,t){const s=ir(e.kind);return s||(t==="tool"?"tool":"standard")}const cr={terminal:{text:"Terminal",key:"chat.activityTerminal"},tool:{text:"Tool",key:"chat.tool"},thought:{text:"Thought",key:"chat.thought"},runtime:{text:"Runtime",key:"chat.activityRuntime"},activity:{text:"Activity",key:"chat.activityFallback"}};function cf(e,t){return e==="terminal"||t==="terminal_command"?cr.terminal:e==="tool"||t==="tool_call"?cr.tool:e==="thought"?cr.thought:t==="runtime_activity"?cr.runtime:cr.activity}function cc(e,t,s){const r=af(e),o=typeof(r==null?void 0:r.label)=="string"?r.label.trim():"";return o||cf(t,s).text}function IS(e){const t=e.content;return Array.isArray(t)&&t.some(s=>!!s&&typeof s=="object"&&s.type!=="text")}function jd(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal",labelKey:cr.activity.key};const t=af(e),s=ir(e.role),r=TS(e,s),o=ir(ic(e,t,"visibility")),a=ir(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??o),i=ir(ic(e,t,"audience")),l=ir(ic(e,t,"source")),d=Du.has(o)||Du.has(a)||NS.has(i)||$u(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),u=Ou.has(o)||Ou.has(a)||i==="chat"||$u(e,t,["userFacing"]),m=AS.has(r)||CS.has(l),h=cf(r,l).key;if(d)return{surface:m?"activity":"internal",isUserFacing:!1,isActivityFacing:m,isInternal:!m,role:s,kind:r,label:cc(e,r,l),labelKey:h};if(u)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:s,kind:r,label:cc(e,r,l),labelKey:h};if((s==="system"||r==="system")&&IS(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:s,kind:r,label:"Chat",labelKey:h};if(_S.has(l)||s==="system"||r==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:s,kind:r,label:"Internal",labelKey:h};if(m)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:s,kind:r,label:cc(e,r,l),labelKey:h};const p=(s==="user"||s==="human"||s==="assistant")&&(r==="standard"||r==="");return{surface:p?"chat":"internal",isUserFacing:p,isActivityFacing:!1,isInternal:!p,role:s,kind:r,label:p?"Chat":"Internal",labelKey:h}}function MS(e){return(Array.isArray(e)?e:[]).filter(t=>jd(t).isActivityFacing)}const Fu=new WeakMap;function lf(e){const t=Fu.get(e);if(t!==void 0)return t;const s=e.content,r=typeof s=="string"?s:(()=>{try{return JSON.stringify(s??"")}catch{return String(s??"")}})();return Fu.set(e,r),r}function RS(e){return`${String(e.role||"")}::${lf(e)}`}function PS(e){if(e.length<2)return e;const t=[];let s="";for(const r of e){const o=RS(r);lf(r).trim().length>0&&o===s||(t.push(r),s=o)}return t}function ES(e,t,s){return!s||t.length===0?e:[...e,...t].sort((r,o)=>{const a=Number(r.receivedAt??r.timestamp??0)||0,i=Number(o.receivedAt??o.timestamp??0)||0;if(a!==i)return a-i;const l=Number(r.index??0)||0,d=Number(o.index??0)||0;return l-d})}function xo(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(kd))!=="0"}catch{return!0}}function LS(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(kd,e?"1":"0")}catch{}}const gl="adhdev:chat-activity-visibility-change";function df(e){LS(e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(gl,{detail:e}))}function uf(e){if(typeof window>"u")return()=>{};const t=r=>{const o=r.detail;e(typeof o=="boolean"?o:xo())},s=r=>{r.key&&r.key!==kd||e(xo())};return window.addEventListener(gl,t),window.addEventListener("storage",s),()=>{window.removeEventListener(gl,t),window.removeEventListener("storage",s)}}const mf="adhdev_assistant_activity_visible";function DS(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(mf))==="1"}catch{return!1}}function OS(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(mf,e?"1":"0")}catch{}}const $S=/^\s*\[System\]\s/,FS=/^\s*\[ADHDev relay · project (\S+) · (\w+)\]\s*$/,HS=/^\s*\[\/relay\]\s*$/,BS=/^Untrusted agent output from the \S+ project follows\./,WS=/^\s*\[idle\]\s*$/,US=[{source:"relay",re:FS},{source:"signal",re:/^\s*\[project ([^\]\s]+)\]\s+(.*)$/},{source:"review",re:/^\s*\[ADHDev review\]\s+(.*)$/},{source:"notice",re:/^\s*\[ADHDev (?:restart|first run)\]\s+(.*)$/}],Hu=160;function xl(e){for(const t of US){const s=t.re.exec(e);if(s)return{rule:t,match:s}}return null}function yo(e){for(const t of e.split(`
|
|
8
|
+
`))if(t.trim())return t;return""}function Wa(e){const t=e.trim();return t.length>Hu?`${t.slice(0,Hu-1)}…`:t}function hf(e){let t=0,s=e.length;for(;t<s&&!e[t].trim();)t++;for(;s>t&&!e[s-1].trim();)s--;return e.slice(t,s)}function KS(e,t,s){let r=!1;const o=s.filter(i=>BS.test(i.trim())?!1:WS.test(i)?(r=!0,!1):!0),a=hf(o).join(`
|
|
9
|
+
`);return{source:"relay",project:e,outcome:t,idle:r,preview:Wa(yo(a)),body:a}}function qS(e){const t=e.replace(/\r\n?/g,`
|
|
10
|
+
`).split(`
|
|
11
|
+
`),s=[];let r=[];const o=()=>{const i=hf(r);if(r=[],!i.length)return;const l=i.join(`
|
|
12
|
+
`);s.push({source:"text",preview:Wa(yo(l)),body:l})};let a=0;for(;a<t.length;){const i=xl(t[a]);if(!i){r.push(t[a]),a++;continue}if(o(),i.rule.source==="relay"){const u=[];for(a++;a<t.length&&!HS.test(t[a]);)u.push(t[a++]);a++,s.push(KS(i.match[1],i.match[2],u));continue}const l=[i.match[i.rule.source==="signal"?2:1]??""];for(a++;a<t.length&&t[a].trim()&&!xl(t[a]);)l.push(t[a++]);const d=l.join(`
|
|
13
|
+
`).trim();s.push({source:i.rule.source,...i.rule.source==="signal"?{project:i.match[1]}:{},preview:Wa(yo(d)),body:d})}return o(),s}function zS(e){if(!e)return null;if($S.test(e))return{source:"system",segments:[{source:"system",preview:Wa(yo(e)),body:e}]};const t=xl(yo(e));return t?{source:t.rule.source,segments:qS(e)}:null}const Bu={mode:"local",threshold:100,previewChars:100},Wu={mode:"local",threshold:600,previewChars:599},VS=new Set(["thought","tool","terminal"]);function GS(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vo(e){return typeof e.label=="string"?e.label:""}function Js(e,t){return e?{text:e}:{i18nKey:t}}function YS(e,t,s,r){if(r)return r.source==="system"?"system":"injected";const o=e.kind||(t==="tool"?"tool":"standard");return s&&!VS.has(o)?"activity":o==="thought"||o==="tool"||o==="terminal"||o==="system"?o:t==="system"?"system":t==="user"||t==="human"?"user":"assistant"}function QS(e,t,s,r,o){switch(e){case"user":return Js(r.userName||"","chat.you");case"assistant":return Js(t.senderName||r.agentName||"","chat.agent");case"tool":return Js(Vo(s)||(typeof t.toolName=="string"?t.toolName:""),"chat.tool");case"thought":return Js(Vo(s),"chat.thought");case"terminal":return Js(Vo(s),"chat.ranCommand");case"activity":return Js(Vo(s).trim(),o);case"system":return{i18nKey:"chat.system"};case"injected":return{i18nKey:"chat.injected"}}}function JS(e,t){switch(e){case"thought":return"thought";case"tool":return"tool-dot";case"activity":return"activity-dot";case"terminal":return t.isRunning?"running":"done";case"system":return t.source==="git-system-bubble"?"git":null;default:return null}}function XS(e,t,s,r){const a=(typeof r.renderMode=="string"?r.renderMode.trim():"")==="preformatted";if(s)return{type:"parts",parts:s,preformatted:e==="terminal"||(e==="user"||e==="assistant")&&a};if(e==="terminal")return{type:"pre",text:t};if(e==="assistant"){if(a)return{type:"pre",text:t};if(yd(t))return{type:"markdown",text:t}}return e==="user"&&a?{type:"pre",text:t}:{type:"plain",text:t}}function ZS(e,t,s,r){if(r)return{mode:"none"};if(e==="tool"){const o=tf(t);return o?{mode:"remote",address:o}:s.length>Wu.threshold?Wu:{mode:"none"}}return e==="system"?s.length>Bu.threshold?Bu:{mode:"none"}:{mode:"none"}}function e0(e){if(!(e.pendingLocal!==!0||e.queued!==!0))return{queued:{pendingId:typeof e.pendingId=="string"?e.pendingId:""}}}function t0(e){return"text"in e?`t:${e.text}`:`k:${e.i18nKey}`}function n0(e){if(e.mode==="local")return`local:${e.threshold}:${e.previewChars}`;if(e.mode==="remote"){const t=e.address;return"messageId"in t?`remote:mid:${t.messageId}`:`remote:ref:${t.toolBlockRef.recordIndex}:${t.toolBlockRef.blockIndex}:${t.toolBlockRef.sourceMtimeMs}`}return"none"}function s0(e,t){var r;const s=t.body;return nf([sf(e),t.key,t.expandKey??"",t.kind,t.surface,t0(t.label),t.icon??"",String(t.timestamp??""),t.copyText===null?"":"copy",s.type==="parts"?`parts:${s.preformatted}`:s.type,n0(t.collapse),(r=t.status)!=null&&r.queued?`queued:${t.status.queued.pendingId}`:"",t.injected?t.injected.segments.map(o=>`${o.source}:${o.project??""}:${o.outcome??""}:${o.idle?1:0}`).join(","):""])}const Uu=new WeakMap;function r0(e,t){var f;const s=jd(e),r=GS(e),o=(e.role||"").toLowerCase(),a=Qw(e.content)?e.content:null,i=a!=null&&a.some(x=>x.type!=="text")?a:null,l=md(e.content,{joiner:`
|
|
14
|
+
`}),d=(o==="user"||o==="human")&&!i&&r.pendingLocal!==!0?zS(l):null,u=d?{source:d.source,segments:d.segments}:void 0,m=YS(e,o,s.isActivityFacing,u),h=vd(e),p=t.receivedAt!==void 0?t.receivedAt:Number(e.receivedAt||((f=t.receivedAtMap)==null?void 0:f[h])||0)||null,b={key:h,expandKey:Xw(e),kind:m,surface:s.surface,label:QS(m,e,r,t,s.labelKey),icon:JS(m,r),timestamp:p||null,copyText:l||null,body:XS(m,l,i,r),collapse:ZS(m,e,l,!!i),...u?{injected:u}:{},...m==="user"?{status:e0(r)}:{}};return b.status===void 0&&delete b.status,{...b,signature:s0(e,b)}}function yl(e,t={}){const s=Uu.get(e);if(s&&s.agentName===t.agentName&&s.userName===t.userName&&s.receivedAt===t.receivedAt&&s.receivedAtMap===t.receivedAtMap)return s.model;const r=r0(e,t);return Uu.set(e,{agentName:t.agentName,userName:t.userName,receivedAt:t.receivedAt,receivedAtMap:t.receivedAtMap,model:r}),r}const o0=c.memo(function({log:t}){return n.jsxs("div",{className:"self-center chat-msg-action",children:[n.jsx(ji,{content:t.text,renderAsPreformatted:!1,renderAsMarkdown:!0}),n.jsx("span",{className:"action-time",children:ef(t.timestamp)})]})},(e,t)=>e.log===t.log);function lc(e){return e.row??yl(e.message,{agentName:e.agentName,userName:e.userName,receivedAt:e.receivedAt??null})}function a0({pendingId:e,onSendNow:t,isSendingNow:s,onCancelQueued:r}){const{t:o}=he("common");return n.jsxs("div",{className:"chat-bubble-queued","data-chat-queued-row":"true",children:[n.jsx("span",{className:"chat-bubble-queued-label","aria-label":o("chat.waitingToSendAria"),children:o("chat.waitingToSend")}),t&&n.jsx("button",{type:"button",onClick:()=>t(e||void 0),disabled:s,className:"chat-bubble-send-now","aria-label":o("chat.sendNowAria"),title:o("chat.sendNowTitle"),children:o(s?"chat.sending":"chat.sendNow")}),r&&e&&n.jsx("button",{type:"button",onClick:()=>r(e),disabled:s,className:"chat-bubble-cancel-queued","aria-label":o("chat.cancelQueuedAria"),title:o("chat.cancelQueuedTitle"),children:o("chat.cancelQueued")})]})}const i0=c.memo(function(t){var p;const s=lc(t),{isTextExpanded:r,onToggleTextExpanded:o,onSendNow:a,isSendingNow:i,onCancelQueued:l,onExpandToolBlock:d,onCollapseToolBlock:u,toolExpand:m}=t;if(s.kind==="injected")return n.jsx(jS,{model:s,openSegments:t.openSegments??"",onToggleSegment:t.onToggleSegment});const h=(p=s.status)==null?void 0:p.queued;return n.jsx(vS,{model:s,expanded:r,onToggle:o,remoteState:m,onExpandRemote:d,onCollapseRemote:u,children:h&&n.jsx(a0,{pendingId:h.pendingId,onSendNow:a,isSendingNow:i,onCancelQueued:l})})},(e,t)=>(e.message===t.message&&e.row===t.row||lc(e).signature===lc(t).signature)&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded&&e.openSegments===t.openSegments&&e.isSendingNow===t.isSendingNow&&e.onSendNow===t.onSendNow&&e.onCancelQueued===t.onCancelQueued&&e.toolExpand===t.toolExpand),c0="";function l0(e,t){const[s,r]=c.useState({}),o=c.useCallback(d=>{r(u=>{var p;const m=u[d],h={...u};return m!=null&&m.open||((p=m==null?void 0:m.remote)==null?void 0:p.status)==="expanded"?delete h[d]:h[d]={open:!0},h})},[]),a=c.useCallback(d=>{r(u=>{if(!u[d])return u;const m={...u};return delete m[d],m})},[]),i=c.useCallback((d,u)=>{t&&(r(m=>({...m,[d]:{remote:{status:"loading"}}})),t(u).catch(()=>({status:"error"})).then(m=>r(h=>({...h,[d]:{remote:m}}))))},[t]);return c.useCallback(d=>{var b;const u=`${e}${c0}${d}`,m=s[u],h=`${u}#`,p=[];for(const f of Object.keys(s))f.startsWith(h)&&((b=s[f])!=null&&b.open)&&p.push(Number(f.slice(h.length)));return{isTextExpanded:(m==null?void 0:m.open)===!0,onToggleTextExpanded:()=>o(u),toolExpand:m==null?void 0:m.remote,onExpandToolBlock:t?f=>i(u,f):void 0,onCollapseToolBlock:t?()=>a(u):void 0,openSegments:p.sort((f,x)=>f-x).join(","),onToggleSegment:f=>o(`${h}${f}`)}},[a,e,s,i,t,o])}const d0=c.forwardRef(function({messages:t,actionLogs:s,agentName:r="Agent",userName:o,isCliMode:a=!1,isWorking:i=!1,contextKey:l="",receivedAtMap:d={},lastMessageHash:u,showActivityMessages:m=!1,emptyState:h,onLoadMore:p,isLoadingMore:b,hasMoreHistory:f,hiddenLiveCount:x=0,loadError:g,scrollToBottomRequestNonce:v,isVisible:S=!0,onSendNow:A,isSendingNow:k,onCancelQueued:w,fetchToolBlock:y},N){const{t:j}=he("common"),C=c.useRef(null),E=c.useRef(null),P=c.useRef(null),T=c.useRef(0),M=c.useRef(""),_=c.useRef(""),I=c.useRef(!1),D=c.useRef(null),L=c.useRef(!1),$=c.useRef(null),q=c.useRef(!1),G=l0(l,y),[W,R]=c.useState({showTop:!1,showBottom:!1}),O=c.useRef(!1),B=c.useRef(!1),H=c.useRef(S),U=c.useRef(S),K=c.useRef(null);U.current=S;const oe=()=>{const Z=C.current;return Z?Z.scrollHeight-Z.scrollTop-Z.clientHeight<wd:!0},ge=c.useCallback(()=>{const Z=C.current,ae=Z?oS(Z):{showTop:!1,showBottom:!1};R(F=>F.showTop===ae.showTop&&F.showBottom===ae.showBottom?F:ae)},[]),J=c.useCallback((Z="auto")=>{var F;const ae=C.current;ae&&(ae.scrollTo({top:ae.scrollHeight,behavior:Z}),(F=ae.ownerDocument.defaultView)==null||F.requestAnimationFrame(()=>ge()))},[ge]),ke=c.useCallback((Z="auto")=>{var F;const ae=C.current;ae&&(ae.scrollTo({top:0,behavior:Z}),(F=ae.ownerDocument.defaultView)==null||F.requestAnimationFrame(()=>ge()))},[ge]),de=c.useCallback(()=>{var me;const Z=C.current,ae=(me=window.getSelection)==null?void 0:me.call(window);if(!Z||!ae||ae.rangeCount===0||ae.isCollapsed){q.current=!1;return}const F=ae.anchorNode,se=ae.focusNode;q.current=!!(F&&se&&Z.contains(F)&&Z.contains(se))},[]),{visibleMessages:ne,rowByMessage:le}=c.useMemo(()=>{const Z=new Map,ae=[],F=[];for(const se of Array.isArray(t)?t:[]){const me=yl(se,{agentName:r,userName:o,receivedAtMap:d});Z.set(se,me),me.surface==="chat"?ae.push(se):me.surface==="activity"&&F.push(se)}return{visibleMessages:PS(ES(ae,F,m)),rowByMessage:Z}},[t,m,r,o,d]),te=ne.length===t.length?u:void 0,ce=nS(ne,te),Ce=c.useCallback(()=>{const Z=C.current;if(!Z||!l||!U.current)return;const ae={top:Z.scrollTop,fromBottom:Math.max(0,Z.scrollHeight-Z.scrollTop-Z.clientHeight),messageFingerprint:ce};K.current={contextKey:l,snapshot:ae},Br.set(l,ae)},[l,ce]),Q=c.useCallback((Z="auto")=>{D.current!=null&&cancelAnimationFrame(D.current),D.current=requestAnimationFrame(()=>{D.current=null,J(Z)})},[J]),z=c.useCallback(()=>{O.current=!1,L.current=!0,B.current=!0,$.current!=null&&window.clearTimeout($.current),$.current=window.setTimeout(()=>{L.current=!1,$.current=null},Pu)},[]);c.useEffect(()=>{const Z=!I.current,ae=_.current!==l;if(_.current=l,Z||ae){I.current=!0;const se=l?Br.get(l):null,me=!!se&&Ba(se,ce);O.current=me?to(se):!1,L.current=aS(se,ce),q.current||(me?requestAnimationFrame(()=>{const re=C.current;re&&(ac(re,se),O.current=to(se),ge(),B.current=!0)}):Q("auto")),T.current=ne.length,M.current=ce;return}ne.length>T.current;const F=ce!==M.current;iS({hasSelection:q.current,userScrolledUp:O.current,hasChatContentChanged:F})&&Q("auto"),T.current=ne.length,M.current=ce},[ce,l,ne.length,Q,ge]),c.useEffect(()=>{v&&(z(),q.current||Q("auto"))},[z,Q,v]),c.useEffect(()=>{const Z=H.current;Z&&!S&&Ce(),U.current=S,H.current=S;const ae=l?Br.get(l):null;if(sS(Z,S,ae,ce)){if(!ae)return;O.current=to(ae),L.current=!1,q.current||requestAnimationFrame(()=>{const F=C.current;F&&(ac(F,ae),ge())});return}},[S,l,ce,z,Ce,Q,ge]),c.useEffect(()=>()=>{const Z=K.current;Z&&Br.set(Z.contextKey,Z.snapshot),D.current!=null&&cancelAnimationFrame(D.current),$.current!=null&&window.clearTimeout($.current)},[]),c.useEffect(()=>{const Z=E.current,ae=C.current;if(!Z||!ae)return;const F=()=>{$.current!=null&&window.clearTimeout($.current),$.current=window.setTimeout(()=>{L.current=!1,$.current=null},Pu)},se=new ResizeObserver(()=>{ge();const me=L.current;cS({hasSelection:q.current,userScrolledUp:O.current,contextAutoScrollActive:me})&&(Q("auto"),me&&F())});return se.observe(Z),ae!==Z&&se.observe(ae),()=>{se.disconnect(),$.current!=null&&(window.clearTimeout($.current),$.current=null)}},[Q,l,ge]),c.useImperativeHandle(N,()=>({scrollToBottom:(Z="smooth")=>{J(Z)}}),[J]),c.useEffect(()=>{const Z=C.current;if(!Z)return;let ae;const F=()=>{Ce(),clearTimeout(ae),ae=setTimeout(()=>{O.current=!oe(),ge()},50)};return Z.addEventListener("scroll",F,{passive:!0}),()=>{Z.removeEventListener("scroll",F),clearTimeout(ae)}},[Ce,ge]),c.useEffect(()=>(document.addEventListener("selectionchange",de),()=>document.removeEventListener("selectionchange",de)),[de]);const X=c.useRef(0),pe=c.useRef(!1);c.useEffect(()=>{const Z=C.current;if(!Z||!pe.current||X.current===0)return;const ae=Z.scrollHeight-X.current;ae>0&&(Z.scrollTop=ae),ge(),Ce(),X.current=0,pe.current=!1},[ne.length,Ce,ge]),c.useEffect(()=>{if(B.current||!l)return;const Z=Br.get(l),ae=C.current;if(!(!Z||!ae)){if(!Ba(Z,ce)){J("auto"),B.current=!0;return}ac(ae,Z),O.current=to(Z),ge(),B.current=!0}},[l,ce,ne.length,J,ge]);const Re=()=>{const Z=C.current;Z&&(X.current=Z.scrollHeight),pe.current=!0,p==null||p()},Oe=()=>{O.current=!0,ke("smooth"),Ce()},De=()=>{z(),J("smooth"),Ce()},we=c.useMemo(()=>{const Z=Zw(ne),ae=ne.map((re,Se)=>{const Y=le.get(re)??yl(re,{agentName:r,userName:o,receivedAtMap:d});return{type:"message",data:re,row:Y,index:Se,ts:Y.timestamp??0,stableKey:Z[Se]}});if(!s||s.length===0)return ae;const F=[...s].sort((re,Se)=>re.timestamp-Se.timestamp).map((re,Se)=>({type:"action",data:re,index:Se,ts:re.timestamp})),se=[];let me=0;for(const re of ae){for(;me<F.length&&re.ts>0&&F[me].ts<re.ts;)se.push(F[me++]);se.push(re)}for(;me<F.length;)se.push(F[me++]);return se},[ne,le,s,r,o,d]),V=x>0||!!f,xe=x>0?x>80?j("chatList.showEarlierMessagesHidden",{count:Math.min(x,80),total:x}):j("chatList.showEarlierMessages",{count:Math.min(x,80)}):g?j("chatList.loadErrorRetry",{error:g}):j("chatList.loadOlderMessages");return n.jsxs("div",{className:"chat-scroll-frame",children:[n.jsx("div",{ref:C,"data-chat-scroll":!0,className:"chat-container",children:n.jsxs("div",{ref:E,className:"chat-container-content",children:[b&&n.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:j("chatList.loadingOlderMessages")}),V&&!b&&n.jsx("div",{className:"text-center py-2",children:n.jsx("button",{type:"button",onClick:Re,className:`text-2xs rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${g&&x===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:xe})}),we.length===0&&!V&&(h||n.jsx("div",{className:"text-center mt-16 opacity-20 text-xxs",children:j("chatList.waitingForMessages")})),we.map(Z=>{if(Z.type==="action"){const re=Z.data;return n.jsx(o0,{log:re},`action-${Z.index}`)}const ae=Z.data,F=Z.row,se=Z.stableKey,me=G(F.expandKey??se);return n.jsx(i0,{message:ae,row:F,receivedAt:F.timestamp??void 0,agentName:r,userName:o,isCliMode:a,onSendNow:A,isSendingNow:k,onCancelQueued:w,...me},`msg-${se}`)}),i&&n.jsx("div",{className:"self-start chat-typing-wrapper",children:n.jsxs("div",{className:"typing-indicator",children:[n.jsx("div",{className:"dot"}),n.jsx("div",{className:"dot"}),n.jsx("div",{className:"dot"}),n.jsx("span",{className:"text-2xs text-text-muted ml-1",children:j("chatList.agentGenerating")})]})}),n.jsx("div",{className:"min-h-10",ref:P})]})}),(W.showTop||W.showBottom)&&n.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":j("chatList.jumpToTop"),children:[W.showTop&&n.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:Oe,"aria-label":j("chatList.jumpToOldestMessages"),title:j("chatList.jumpToTop"),children:j("chatList.top")}),W.showBottom&&n.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:De,"aria-label":j("chatList.jumpToLatestMessages"),title:j("chatList.jumpToBottom"),children:j("chatList.latest")})]})]})}),u0=c.memo(d0,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.showActivityMessages===t.showActivityMessages&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible&&e.onSendNow===t.onSendNow&&e.isSendingNow===t.isSendingNow&&e.onCancelQueued===t.onCancelQueued&&e.fetchToolBlock===t.fetchToolBlock),m0="modulepreload",h0=function(e){return"/"+e},Ku={},mr=function(t,s,r){let o=Promise.resolve();if(s&&s.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),l=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));o=Promise.allSettled(s.map(d=>{if(d=h0(d),d in Ku)return;Ku[d]=!0;const u=d.endsWith(".css"),m=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${m}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":m0,u||(h.as="script"),h.crossOrigin="",h.href=d,l&&h.setAttribute("nonce",l),document.head.appendChild(h),u)return new Promise((p,b)=>{h.addEventListener("load",p),h.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${d}`)))})}))}function a(i){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=i,window.dispatchEvent(l),!l.defaultPrevented)throw i}return o.then(i=>{for(const l of i||[])l.status==="rejected"&&a(l.reason);return t().catch(a)})};let qu=!1;const pf=c.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:s,fontSize:r=13,readOnly:o=!1,sizingMode:a="measured"},i)=>{const l=c.useRef(null),[d,u]=c.useState(null),m=c.useRef([]),h=c.useRef(!1),p=c.useRef(!1),b=c.useRef(!1),f=c.useRef(!1),x=()=>{const g=l.current;if(g){h.current&&(g.clear(),h.current=!1);for(const v of m.current)g.write(v.data,v.onProcessed);m.current=[],p.current&&(g.fit(),p.current=!1),b.current&&(g.bumpResize(),b.current=!1),f.current&&(g.scrollToTop(),f.current=!1)}};return c.useImperativeHandle(i,()=>({write:(g,v)=>{l.current?l.current.write(g,v):m.current.push({data:g,onProcessed:v})},clear:()=>{l.current?l.current.clear():(m.current=[],h.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(m.current=[],h.current=!0)},resize:(g,v)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(g,v)},fit:()=>{l.current?l.current.fit():p.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():b.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():f.current=!0},getSelection:()=>{var g,v;return((v=(g=l.current)==null?void 0:g.getSelection)==null?void 0:v.call(g))||""},getVisibleText:()=>{var g,v;return((v=(g=l.current)==null?void 0:g.getVisibleText)==null?void 0:v.call(g))||""}}),[]),c.useEffect(()=>{d&&x()},[d]),c.useEffect(()=>{let g=!1;return mr(()=>import("./terminal-dI1yRint.js"),__vite__mapDeps([0,1,2])).then(v=>{qu||(qu=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),g||u(()=>v.GhosttyTerminalView)}).catch(v=>{console.error("[CliTerminal] failed to load terminal renderer",v)}),()=>{g=!0}},[]),d?n.jsx(d,{ref:l,onInput:e,onViewportMetrics:t,onScrollMetrics:s,fontSize:r,readOnly:o,sizingMode:a,className:"w-full h-full rounded-lg overflow-hidden"}):n.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});pf.displayName="CliTerminal";function ct(...e){return ay(iy(e))}const p0={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},f0={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},hn=c.forwardRef(function({radius:t="xl",padding:s="md",className:r,...o},a){return n.jsx("div",{ref:a,className:ct("border border-border-subtle bg-bg-secondary",p0[t],f0[s],r),...o})});function dc({label:e,value:t,sub:s,icon:r}){return n.jsxs(hn,{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsx("span",{className:"text-base flex items-center",children:r}),n.jsx("span",{className:"text-3xs text-text-muted uppercase tracking-wide font-semibold",children:e})]}),n.jsx("div",{className:"text-[22px] leading-[30px] font-bold text-text-primary tracking-tight",children:t}),s&&n.jsx("div",{className:"text-2xs text-text-muted mt-0.5",children:s})]})}function ff({title:e,description:t,confirmLabel:s,cancelLabel:r,tone:o="default",busy:a=!1,onConfirm:i,onCancel:l}){const{t:d}=he("common");c.useEffect(()=>{const m=h=>{h.key==="Escape"&&l()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[l]);const u=n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 backdrop-blur-[2px] p-4",role:"dialog","aria-modal":"true","aria-labelledby":"confirm-dialog-title",onClick:m=>{m.target===m.currentTarget&&l()},children:n.jsxs("div",{className:"w-full max-w-sm rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden",children:[n.jsxs("div",{className:"px-5 py-4",children:[n.jsx("div",{id:"confirm-dialog-title",className:"text-sm font-semibold text-text-primary",children:e}),t&&n.jsx("div",{className:"mt-1.5 text-xs text-text-secondary whitespace-pre-line break-words",children:t})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-border-subtle",children:[n.jsx("button",{type:"button",className:"btn btn-secondary h-9 px-4 text-sm",disabled:a,onClick:l,children:r??d("common.cancel")}),n.jsx("button",{type:"button",autoFocus:!0,className:`btn ${o==="danger"?"btn-danger":"btn-primary"} h-9 px-4 text-sm font-semibold`,disabled:a,onClick:i,children:s})]})]})});return An.createPortal(u,document.body)}function bf(e){if(!e||typeof e!="object")return;const t=e;return"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Tr(){const[e,t]=c.useState(null),s=c.useRef(null),r=c.useCallback(i=>{t(null);const l=s.current;s.current=null,l==null||l(i)},[]),o=c.useCallback(i=>new Promise(l=>{var d;(d=s.current)==null||d.call(s,!1),s.current=l,t(i)}),[]);c.useEffect(()=>()=>{var i;(i=s.current)==null||i.call(s,!1)},[]);const a=e?n.jsx(ff,{title:e.title,description:e.description,confirmLabel:e.confirmLabel,cancelLabel:e.cancelLabel,tone:e.tone,onConfirm:()=>r(!0),onCancel:()=>r(!1)}):null;return{confirm:o,confirmDialog:a}}function zu({value:e,max:t,label:s,color:r="#8b5cf6",detail:o,compact:a=!1}){const i=t>0?Math.min(Math.round(e/t*100),100):0,l=i>85?"#ef4444":i>60?"var(--status-warning)":r;return a?n.jsxs("div",{className:"flex-1",children:[n.jsxs("div",{className:"flex justify-between mb-0.5",children:[n.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide font-semibold",children:s}),n.jsxs("span",{className:"text-3xs text-text-secondary font-semibold",children:[i,"%"]})]}),n.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:n.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${i}%`,background:l}})})]}):n.jsxs("div",{className:"flex-1",children:[n.jsxs("div",{className:"flex justify-between mb-1.5",children:[n.jsx("span",{className:"text-2xs text-text-secondary font-medium",children:s}),n.jsxs("span",{className:"text-xxs text-text-primary font-bold",children:[i,"%"]})]}),n.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:n.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${i}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),o&&n.jsx("div",{className:"text-3xs text-text-muted mt-0.5",children:o})]})}function b0({cursorPos:e,viewportRef:t,imgRef:s}){var S;if(!e||!s.current)return null;const r=s.current,o=r.getBoundingClientRect(),a=(S=t.current)==null?void 0:S.getBoundingClientRect();if(!a)return null;const i=r.naturalWidth||o.width,l=r.naturalHeight||o.height,d=i/l,u=o.width/o.height;let m,h,p,b;d>u?(m=o.width,h=o.width/d,p=0,b=(o.height-h)/2):(h=o.height,m=o.height*d,p=(o.width-m)/2,b=0);const f=o.left-a.left+p+m*e.nx,x=o.top-a.top+b+h*e.ny,g=Math.max(8,Math.min(a.width-8,f)),v=Math.max(8,Math.min(a.height-8,x));return n.jsxs("div",{style:{position:"absolute",left:g-8,top:v-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[n.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),n.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),n.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function uc(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function g0({inputMode:e,onToggleInputMode:t,isImeOpen:s,setIsImeOpen:r,isMenuOpen:o,setIsMenuOpen:a,imeText:i,setImeText:l,handleImeSubmit:d,isConnActive:u,zoom:m,isMobile:h,mobileFillZoom:p,onZoomOut:b,onZoomReset:f,onZoomIn:x,transportType:g,screenshotUsage:v,lastActionStatus:S}){const{t:A}=he("common");return n.jsxs(n.Fragment,{children:[n.jsxs("div",{onTouchStart:k=>k.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[n.jsxs("div",{role:"button",tabIndex:0,onClick:t,onKeyDown:uc(t),className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[n.jsx("span",{className:"text-sm",children:e==="mouse"?n.jsx(Jp,{size:14}):n.jsx(Uw,{size:14})}),n.jsx("span",{className:`text-3xs font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:A(e==="mouse"?"remote.mouse":"remote.touch")})]}),n.jsxs("div",{className:"relative",children:[n.jsx("div",{role:"button",tabIndex:0,onClick:()=>{r(k=>!k),a(!1)},onKeyDown:uc(()=>{r(k=>!k),a(!1)}),className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${s?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:n.jsx("span",{className:"text-sm",children:n.jsx(Yp,{size:14})})}),s&&n.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:n.jsx("input",{type:"text",placeholder:A("remote.typeAndEnter"),value:i,autoFocus:!0,onTouchStart:k=>k.stopPropagation(),onChange:k=>l(k.target.value),onKeyDown:k=>{d(k)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-xxs outline-none"})})]}),n.jsx("div",{className:"relative",children:n.jsx("div",{role:"button",tabIndex:0,onClick:()=>{a(k=>!k),r(!1)},onKeyDown:uc(()=>{a(k=>!k),r(!1)}),className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${o?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:n.jsx("span",{className:"text-sm",children:n.jsx(_r,{size:14})})})}),n.jsx("div",{className:"w-px h-[18px] bg-white/10"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:u?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[n.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:u?"#22c55e":"#eab308",boxShadow:u?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),n.jsx("span",{className:"text-5xs font-extrabold",style:{color:u?"#22c55e":"#eab308"},children:A(u?"remote.connected":"remote.ws")})]}),m>1&&n.jsxs("span",{className:"text-5xs font-bold text-indigo-400",children:[Math.round(m*100),"%"]}),g==="direct"&&n.jsx("span",{className:"text-5xs font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:A("remote.directP2PTitle"),children:A("remote.direct")}),g==="relay"&&n.jsx("span",{className:"text-5xs font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:A("remote.turnRelayTitle"),children:A("remote.relay")}),v&&v.dailyBudgetMinutes>0&&n.jsx("span",{className:"text-5xs font-bold px-1 py-0.5 rounded",style:{color:v.budgetExhausted?"#ef4444":"#c4b5fd",background:v.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:A("remote.dailyTurnTitle"),children:v.budgetExhausted?A("remote.turnBlocked"):A("remote.turnUsage",{used:v.dailyUsedMinutes,budget:v.dailyBudgetMinutes})}),S&&n.jsx("span",{className:"text-5xs text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:S})]})]}),o&&n.jsxs("div",{onTouchStart:k=>k.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[n.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:A("remote.settings")}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[n.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:[A("remote.zoom")," ",m<=(h?p:1)+.01?A(h?"remote.fill":"remote.fit"):`${Math.round(m*100)}%`]}),n.jsxs("div",{style:{display:"flex",gap:4},children:[n.jsx("button",{onClick:k=>{k.stopPropagation(),b()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),n.jsx("button",{onClick:k=>{k.stopPropagation(),f()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:A(h?"remote.fill":"remote.fit")}),n.jsx("button",{onClick:k=>{k.stopPropagation(),x()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function x0({waitingLabel:e,waitingHint:t,transportType:s}){const{t:r}=he("common");return n.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[n.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:n.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),n.jsx("div",{className:"text-white/85 text-xxs font-semibold tracking-wide",children:e}),n.jsx("div",{className:"text-2xs text-white/40",children:t}),s==="relay"&&n.jsx("div",{className:"text-3xs font-medium",style:{color:"var(--status-warning)",opacity:.8},children:r("remote.waitingState.turnRelayActive")})]})}function y0({connState:e,onRetry:t}){const{t:s}=he("common"),r=e==="failed"?"remote.error.reasonFailed":"remote.error.reasonDisconnected";return n.jsxs("div",{"data-testid":"remote-error-state",className:"text-center flex flex-col items-center gap-3 px-6",children:[n.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-red-500/25 bg-red-500/10 shadow-[0_10px_30px_rgba(0,0,0,0.35)]",children:n.jsx(tn,{size:22,className:"text-red-400"})}),n.jsx("div",{className:"text-white/90 text-[13px] leading-[1.45] font-semibold tracking-wide",children:s("remote.error.title")}),n.jsx("div",{className:"text-2xs text-white/50 max-w-[260px]",children:s(r)}),t&&n.jsxs("button",{type:"button",onClick:t,className:"mt-1 h-8 px-3.5 rounded-lg flex items-center gap-1.5 bg-white/[0.08] border border-white/15 text-white/90 text-2xs font-bold hover:bg-white/[0.14] transition-colors",children:[n.jsx(Ar,{size:13}),s("remote.error.retry")]})]})}function v0(){if(typeof window>"u")return!1;try{return window.__ADHDEV_DEBUG_RENDERS__===!0||window.localStorage.getItem("adhdev_debug_renders")==="1"}catch{return window.__ADHDEV_DEBUG_RENDERS__===!0}}function Vu(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function Io(e,t){const s=c.useRef(null),r=c.useRef(0);c.useEffect(()=>{if(!v0())return;r.current+=1;const o=s.current;if(!o){console.debug(`[render-trace] ${e}#${r.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,l])=>[i,Vu(l)]))}),s.current=t;return}const a=Object.keys({...o,...t}).filter(i=>!Object.is(o[i],t[i]));a.length>0&&console.debug(`[render-trace] ${e}#${r.current}`,{changed:a,snapshot:Object.fromEntries(a.map(i=>[i,Vu(t[i])]))}),s.current=t})}function w0({containerRef:e,viewportRef:t,imgRef:s,inputMode:r,setInputMode:o,minZoom:a,zoomRef:i,panXRef:l,panYRef:d,setPanX:u,setPanY:m,setZoom:h,lastWheelTimeRef:p,onAction:b,setLastActionStatus:f,spawnRippleFromNormalized:x,clampPan:g,isMobile:v,mobileFillZoom:S}){const[A,k]=c.useState(null),w=c.useRef(null),y=c.useRef(null),N=c.useRef(null),j=c.useRef(!1),C=c.useRef(null),E=c.useRef(0),P=c.useRef(null),T=c.useRef(1),M=c.useRef({x:0,y:0}),_=c.useRef(!1),I=c.useRef(r),D=c.useRef(b),L=30,$=550,q=18,G=60,W=400,R=12,O=()=>{if(w.current)return;const U={nx:.5,ny:.5};w.current=U,k(U)};return c.useEffect(()=>{I.current=r,r==="mouse"&&O()},[r]),c.useEffect(()=>{D.current=b},[b]),c.useEffect(()=>{const U=e.current;if(!U)return;const K=ne=>{if(!s.current)return null;const le=s.current.getBoundingClientRect();return!le.width||!le.height?null:{nx:Math.max(0,Math.min(1,(ne.clientX-le.left)/le.width)),ny:Math.max(0,Math.min(1,(ne.clientY-le.top)/le.height))}},oe=(ne,le)=>{if(!s.current)return{dnx:0,dny:0};const te=s.current,ce=te.getBoundingClientRect(),Ce=te.naturalWidth||ce.width,Q=te.naturalHeight||ce.height,z=Ce/Q,X=ce.width/ce.height;let pe,Re;return z>X?(pe=ce.width,Re=ce.width/z):(Re=ce.height,pe=ce.height*z),{dnx:ne/pe,dny:le/Re}},ge=(ne,le,te)=>{if(te<=1.05)return;const ce=-(ne-.5)*100,Ce=-(le-.5)*100,Q=g(ce,Ce,te);(Math.abs(Q.x-l.current)>.1||Math.abs(Q.y-d.current)>.1)&&(u(Q.x),m(Q.y),l.current=Q.x,d.current=Q.y)},J=ne=>{const le=t.current;if(le&&ne.target instanceof Node&&le.contains(ne.target))ne.preventDefault();else return;if(ne.touches.length===1){const te=ne.touches[0];y.current={x:te.clientX,y:te.clientY,time:Date.now()},N.current={x:te.clientX,y:te.clientY},_.current||(j.current=!1),C.current=setTimeout(()=>{if(!j.current&&!_.current)if(j.current=!0,I.current==="mouse"){const ce=w.current||{nx:.5,ny:.5};f("Right Click"),x(ce.nx,ce.ny,"right"),D.current("input_click",{...ce,button:"right"}).catch(()=>{})}else{const ce=K(te);ce&&(f("Right Click"),x(ce.nx,ce.ny,"right"),D.current("input_click",{...ce,button:"right"}).catch(()=>{}))}},500);return}if(ne.touches.length===2){C.current&&clearTimeout(C.current),j.current=!0,_.current=!0;const te=ne.touches[1].clientX-ne.touches[0].clientX,ce=ne.touches[1].clientY-ne.touches[0].clientY;P.current=Math.sqrt(te*te+ce*ce),T.current=i.current,M.current={x:(ne.touches[0].clientX+ne.touches[1].clientX)/2,y:(ne.touches[0].clientY+ne.touches[1].clientY)/2}}},ke=ne=>{const le=t.current;if(le&&ne.target instanceof Node&&le.contains(ne.target)&&ne.preventDefault(),ne.touches.length===1&&N.current){const te=ne.touches[0],ce=te.clientX-N.current.x,Ce=te.clientY-N.current.y;if(!j.current&&y.current){const Q=te.clientX-y.current.x,z=te.clientY-y.current.y;Math.sqrt(Q*Q+z*z)>8&&(j.current=!0,C.current&&clearTimeout(C.current))}if(j.current)if(I.current==="mouse"){const Q=oe(ce,Ce),z=w.current||{nx:.5,ny:.5},X=Math.max(0,Math.min(1,z.nx+Q.dnx)),pe=Math.max(0,Math.min(1,z.ny+Q.dny));w.current={nx:X,ny:pe},k({nx:X,ny:pe}),f(`Cursor: ${Math.round(X*100)}%, ${Math.round(pe*100)}%`),ge(X,pe,i.current);const Re=Date.now();Re-p.current>=30&&(p.current=Re,D.current("input_mouseMoved",{nx:X,ny:pe}).catch(()=>{}))}else if(i.current>1){const Q=t.current;if(Q){const z=Q.clientWidth,X=Q.clientHeight,pe=l.current+ce/z*100,Re=d.current+Ce/X*100,Oe=g(pe,Re,i.current);u(Oe.x),m(Oe.y),l.current=Oe.x,d.current=Oe.y}}else{const Q=K(te);if(Q){const z=Date.now();z-p.current>=40&&(p.current=z,f("Scroll"),D.current("input_wheel",{nx:Q.nx,ny:Q.ny,deltaX:Math.round(-ce*2.5),deltaY:Math.round(-Ce*2.5)}).catch(()=>{}))}}N.current={x:te.clientX,y:te.clientY};return}if(ne.touches.length===2&&P.current!==null){const te=ne.touches[1].clientX-ne.touches[0].clientX,ce=ne.touches[1].clientY-ne.touches[0].clientY,Q=Math.sqrt(te*te+ce*ce)/P.current,z=(ne.touches[0].clientX+ne.touches[1].clientX)/2,X=(ne.touches[0].clientY+ne.touches[1].clientY)/2,pe=z-M.current.x,Re=X-M.current.y,Oe=Math.abs(Q-1)>.03;if(I.current==="mouse"){if(Oe){const De=Math.max(a,Math.min(5,T.current*Q));h(De),i.current=De}else if(Math.abs(pe)>2||Math.abs(Re)>2){const De=w.current||{nx:.5,ny:.5},we=Date.now();we-p.current>=30&&(p.current=we,f("Scroll"),D.current("input_wheel",{nx:De.nx,ny:De.ny,deltaX:Math.round(-pe*3),deltaY:Math.round(-Re*3)}).catch(()=>{}))}}else{const De=Math.max(a,Math.min(5,T.current*Q));h(De),i.current=De;const we=t.current;if(we&&De>1){const V=we.clientWidth,xe=we.clientHeight,Z=l.current+pe/V*100,ae=d.current+Re/xe*100,F=g(Z,ae,De);u(F.x),m(F.y),l.current=F.x,d.current=F.y}}M.current={x:z,y:X}}},de=ne=>{var le;if(C.current&&clearTimeout(C.current),P.current=null,ne.touches.length===1&&_.current){const te=ne.touches[0];y.current={x:te.clientX,y:te.clientY,time:Date.now()},N.current={x:te.clientX,y:te.clientY},j.current=!0;return}if(ne.touches.length===0){if(_.current){_.current=!1,j.current=!1;return}if(ne.changedTouches.length===1){const te=ne.changedTouches[0],ce=Date.now(),Ce=ce-(((le=y.current)==null?void 0:le.time)||0),Q=y.current?te.clientX-y.current.x:0,z=y.current?te.clientY-y.current.y:0,X=Math.sqrt(Q*Q+z*z);if(I.current==="mouse"){if(Ce<L||Ce>$||X>q){j.current=!1;return}const pe=w.current||K(te);pe&&(f(`Click: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),x(pe.nx,pe.ny,"left"),D.current("input_click",{...pe}).catch(()=>{}))}else{if(j.current){j.current=!1;return}if(Ce<G||Ce>W||X>R){j.current=!1;return}const pe=K(te);if(!pe)return;ce-E.current<300?(f("Double tap"),x(pe.nx,pe.ny,"double"),D.current("input_click",{...pe,clickCount:2}).catch(()=>{}),E.current=0):(f(`Tap: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),x(pe.nx,pe.ny,"left"),D.current("input_click",{...pe}).catch(()=>{}),E.current=ce)}}j.current=!1}};return U.addEventListener("touchstart",J,{passive:!1}),U.addEventListener("touchmove",ke,{passive:!1}),U.addEventListener("touchend",de,{passive:!1}),()=>{U.removeEventListener("touchstart",J),U.removeEventListener("touchmove",ke),U.removeEventListener("touchend",de),C.current&&clearTimeout(C.current)}},[e,t,s,a,i,l,d,u,m,h,p,f,x,g]),{cursorPos:A,cursorPosRef:w,handleToggleInputMode:()=>{o(U=>{const K=U==="touch"?"mouse":"touch";return K==="mouse"&&O(),K})},handleZoomReset:()=>{const U=v?S:1;h(U),i.current=U,u(0),m(0),l.current=0,d.current=0}}}const S0=15e3;function gf({onAction:e,addLog:t,connState:s,connScreenshot:r,screenshotUsage:o,transportType:a,onRetry:i}){const{t:l}=he("common"),d=c.useRef(null),u=c.useRef(null),m=c.useRef(null),[h,p]=c.useState(null),[b,f]=c.useState(""),[,x]=c.useState(!1),[g,v]=c.useState(!1),[S,A]=c.useState(!1),[k,w]=c.useState([]),y=c.useRef(0),N=c.useRef(new Set),[j,C]=c.useState(!1),[E,P]=c.useState(!1),T=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[M,_]=c.useState(T?"mouse":"touch"),[I,D]=c.useState(1),L=c.useRef(!1),[$,q]=c.useState(1),[G,W]=c.useState(0),[R,O]=c.useState(0);Io("RemoteView",{connState:s,hasScreenshot:!!r,inputMode:M,zoom:$,panX:G,panY:R,isMenuOpen:j,isImeOpen:E});const B=c.useRef(0),H=c.useRef($),U=c.useRef(G),K=c.useRef(R);c.useEffect(()=>{H.current=$},[$]),c.useEffect(()=>{U.current=G},[G]),c.useEffect(()=>{K.current=R},[R]),c.useEffect(()=>{var V;(V=d.current)==null||V.focus()},[]),c.useEffect(()=>{s!=="connected"&&v(!1)},[s]),c.useEffect(()=>{if(s==="connected"){A(!1);return}A(!1);const V=setTimeout(()=>A(!0),S0);return()=>clearTimeout(V)},[s]);const oe=s==="connected",ge=r,J=s==="failed"||s==="disconnected"&&S,ke=l(oe?"remote.waiting.connectedLabel":s==="connecting"?"remote.waiting.connectingLabel":"remote.waiting.reconnectingLabel"),de=l(oe?"remote.waiting.connectedHint":"remote.waiting.reconnectingHint");c.useEffect(()=>{if(!T||L.current||!ge)return;const V=m.current,xe=u.current;if(!V||!xe)return;const Z=()=>{const ae=xe.clientWidth,F=xe.clientHeight,se=V.naturalWidth,me=V.naturalHeight;if(!se||!me||!ae||!F)return;const re=Math.min(ae/se,F/me),Y=Math.max(ae/se,F/me)/re;Y>1.01&&(D(Y),q(Y),H.current=Y),L.current=!0};if(V.complete&&V.naturalWidth){Z();return}return V.addEventListener("load",Z,{once:!0}),()=>V.removeEventListener("load",Z)},[ge,T]);const ne=.5;c.useEffect(()=>{$<=ne&&(W(0),O(0))},[$,ne]);const le=(V,xe,Z)=>{if(Z<=ne)return{x:0,y:0};const ae=(Z-1)/(2*Z)*100,F=(Z-1)/(2*Z)*100;return{x:Math.max(-ae,Math.min(ae,V)),y:Math.max(-F,Math.min(F,xe))}},te=(V,xe)=>{if(!m.current)return null;const Z=m.current.getBoundingClientRect();return!Z.width||!Z.height?null:{nx:Math.max(0,Math.min(1,(V-Z.left)/Z.width)),ny:Math.max(0,Math.min(1,(xe-Z.top)/Z.height))}},ce=V=>{const xe=setTimeout(()=>{N.current.delete(xe),w(Z=>Z.filter(ae=>ae.id!==V))},600);N.current.add(xe)};c.useEffect(()=>{const V=N.current;return()=>{for(const xe of V)clearTimeout(xe);V.clear()}},[]);const Ce=(V,xe,Z)=>{const ae=u.current;if(!ae)return;const F=ae.getBoundingClientRect(),se=++y.current;w(me=>[...me,{id:se,x:V-F.left,y:xe-F.top,type:Z}]),ce(se)},Q=(V,xe,Z)=>{const ae=m.current,F=u.current;if(!ae||!F)return;const se=ae.getBoundingClientRect(),me=F.getBoundingClientRect(),re=ae.naturalWidth||se.width,Se=ae.naturalHeight||se.height,Y=re/Se,ue=se.width/se.height;let fe,Ie,Ke,_e;Y>ue?(fe=se.width,Ie=se.width/Y,Ke=0,_e=(se.height-Ie)/2):(Ie=se.height,fe=se.height*Y,Ke=(se.width-fe)/2,_e=0);const Ne=se.left-me.left+Ke+fe*V,Be=se.top-me.top+_e+Ie*xe,$e=++y.current;w(it=>[...it,{id:$e,x:Ne,y:Be,type:Z}]),ce($e)},z=async V=>{var Z;const xe=te(V.clientX,V.clientY);if(xe){p(`Click: ${Math.round(xe.nx*100)}%, ${Math.round(xe.ny*100)}%`),(Z=d.current)==null||Z.focus(),v(!0);try{const ae=await e("input_click",{nx:xe.nx,ny:xe.ny});if(!(ae!=null&&ae.success)){t(`❌ Click failed: ${ae==null?void 0:ae.error}`);return}Ce(V.clientX,V.clientY,"left")}catch(ae){t(`❌ Click error: ${ae.message||ae}`)}}},X=async(V,xe,Z,ae=0)=>{try{await e("input_key",{type:Z?"char":"keyDown",key:V,code:xe,text:Z?V:void 0,unmodifiedText:Z?V:void 0,modifiers:ae})}catch(F){t(`❌ Key error: ${F.message||F}`)}},pe=async V=>{if(V.target.tagName==="INPUT"||!g||V.key==="Escape")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter"].includes(V.key)&&V.preventDefault();let Z=0;V.altKey&&(Z|=1),V.ctrlKey&&(Z|=2),V.metaKey&&(Z|=4),V.shiftKey&&(Z|=8),p(`Key: ${V.key}`),await X(V.key,V.code,V.key.length===1,Z)},Re=async V=>{if(V.key==="Enter"){if(V.nativeEvent.isComposing)return;if(b){const xe=b;f(""),p(`IME Sent: ${xe}`);try{const Z=await e("input_type",{text:xe});Z!=null&&Z.success||t(`❌ IME error: ${Z==null?void 0:Z.error}`)}catch(Z){t(`❌ IME error: ${Z.message}`)}}else p("Key: Enter"),await X("Enter","Enter",!1)}};c.useEffect(()=>{const V=d.current;if(!V)return;const xe=Z=>{var ae;if((ae=m.current)!=null&&ae.contains(Z.target)){Z.preventDefault();const F=Date.now();if(F-B.current<40)return;B.current=F;const se=te(Z.clientX,Z.clientY);if(!se)return;p(`Scroll: ${Math.round(Z.deltaY)}`),e("input_wheel",{nx:se.nx,ny:se.ny,deltaX:Math.round(Z.deltaX),deltaY:Math.round(Z.deltaY)}).catch(()=>{})}};return V.addEventListener("wheel",xe,{passive:!1}),()=>V.removeEventListener("wheel",xe)},[e]);const{cursorPos:Oe,handleToggleInputMode:De,handleZoomReset:we}=w0({containerRef:d,viewportRef:u,imgRef:m,inputMode:M,setInputMode:_,minZoom:ne,zoomRef:H,panXRef:U,panYRef:K,setPanX:W,setPanY:O,setZoom:q,lastWheelTimeRef:B,onAction:e,setLastActionStatus:p,spawnRippleFromNormalized:Q,clampPan:le,isMobile:T,mobileFillZoom:I});return n.jsxs("div",{ref:d,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:pe,onContextMenu:V=>V.preventDefault(),onFocus:()=>x(!0),onBlur:()=>x(!1),tabIndex:0,children:[n.jsxs("div",{ref:u,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[J?n.jsx(y0,{connState:s,onRetry:i}):ge?n.jsx("img",{ref:m,src:ge,alt:l("remote.screenshotAlt"),style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${$}) translate(${G}%, ${R}%)`,transformOrigin:"center center",cursor:M==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:z,onContextMenu:V=>V.preventDefault(),onDragStart:V=>V.preventDefault()}):n.jsx(x0,{waitingLabel:ke,waitingHint:de,transportType:a}),M==="mouse"&&!J&&ge&&n.jsx(b0,{cursorPos:Oe,viewportRef:u,imgRef:m}),k.map(V=>{const Z={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[V.type];return n.jsxs("div",{style:{position:"absolute",left:V.x,top:V.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${Z}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),n.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${Z}, 0.9)`,boxShadow:`0 0 12px rgba(${Z}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},V.id)})]}),n.jsx(g0,{inputMode:M,onToggleInputMode:De,isImeOpen:E,setIsImeOpen:P,isMenuOpen:j,setIsMenuOpen:C,imeText:b,setImeText:f,handleImeSubmit:Re,isConnActive:oe,zoom:$,isMobile:T,mobileFillZoom:I,onZoomOut:()=>q(V=>Math.max(.5,V-.25)),onZoomReset:we,onZoomIn:()=>q(V=>Math.min(5,V+.25)),transportType:a,screenshotUsage:o,lastActionStatus:h}),n.jsx("style",{children:`
|
|
15
|
+
@keyframes slideUp {
|
|
16
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
17
|
+
to { opacity: 1; transform: translateY(0); }
|
|
18
|
+
}
|
|
19
|
+
@keyframes slideUpSidebar {
|
|
20
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
21
|
+
to { opacity: 1; transform: translateY(0); }
|
|
22
|
+
}
|
|
23
|
+
@keyframes click-ripple-ring {
|
|
24
|
+
0% { transform: scale(0.3); opacity: 1; }
|
|
25
|
+
100% { transform: scale(2.2); opacity: 0; }
|
|
26
|
+
}
|
|
27
|
+
@keyframes click-ripple-dot {
|
|
28
|
+
0% { transform: scale(1); opacity: 0.9; }
|
|
29
|
+
50% { transform: scale(1.8); opacity: 0.6; }
|
|
30
|
+
100% { transform: scale(0.5); opacity: 0; }
|
|
31
|
+
}
|
|
32
|
+
@keyframes remote-float {
|
|
33
|
+
0% { transform: translateY(0px); }
|
|
34
|
+
50% { transform: translateY(-7px); }
|
|
35
|
+
100% { transform: translateY(0px); }
|
|
36
|
+
}
|
|
37
|
+
`})]})}function vl(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.promptId!="string"||!t.promptId.trim()||typeof t.providerType!="string"||!t.providerType.trim()||!Array.isArray(t.questions)||t.questions.length===0?null:t}function k0(e){var t;return vl(e.activeInteractivePrompt)||vl((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function j0(e){return e.sessionId||e.instanceId||e.id}function N0(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=k0(a);if(!i)continue;const l=j0(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 xf(e,t){var r;const s={};for(const o of e.questions){const a=t[o.questionId]||{},i=Array.from(new Set((a.selectedLabels||[]).map(d=>d.trim()).filter(Boolean))),l=(r=a.freeformText)==null?void 0:r.trim();s[o.questionId]={selectedLabels:i,...l?{freeformText:l}:{}}}return{promptId:e.promptId,answers:s}}function Un({children:e}){return typeof document>"u"?n.jsx(n.Fragment,{children:e}):An.createPortal(e,document.body)}function C0(e,t){const s=r=>{r.key==="Escape"&&(r.stopPropagation(),t())};return e.addEventListener("keydown",s,!0),()=>e.removeEventListener("keydown",s,!0)}const Gu='a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',_0=200;function Yu(e){const t={};for(const s of(e==null?void 0:e.prompt.questions)||[])t[s.questionId]={selectedLabels:[],freeformText:""};return t}function Qu(e,t){var s,r;return!!((s=t==null?void 0:t.freeformText)!=null&&s.trim())||(((r=t==null?void 0:t.selectedLabels)==null?void 0:r.length)||0)>0||e.options.length===0&&!!e.allowFreeform}function A0({label:e,description:t,selected:s,multiSelect:r,disabled:o,onClick:a}){return n.jsx("button",{type:"button",disabled:o,role:r?"checkbox":"radio","aria-checked":s,onClick:a,className:`w-full text-left rounded-md border px-3 py-2 transition ${s?"border-accent-primary bg-accent-primary/15 text-text-primary":"border-border-default bg-surface-secondary text-text-secondary hover:bg-surface-secondary hover:text-text-primary"} ${o?"cursor-not-allowed opacity-60":""}`,children:n.jsxs("span",{className:"flex items-start gap-2",children:[n.jsx("span",{className:`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border ${r?"rounded-sm":"rounded-full"} ${s?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-subtle"}`,children:s?r?n.jsx(vi,{size:12}):n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-accent-on-primary"}):null}),n.jsxs("span",{className:"min-w-0",children:[n.jsx("span",{className:"block text-sm font-semibold leading-5",children:e}),t&&n.jsx("span",{className:"mt-0.5 line-clamp-3 block text-xs leading-5 text-text-muted",children:t})]})]})})}function Nd({promptSession:e,isSubmitting:t=!1,error:s,onSubmit:r,onCancel:o}){const{t:a}=he("common"),[i,l]=c.useState(()=>Yu(e)),[d,u]=c.useState(!1),m=c.useRef(!1),h=c.useRef(null),p="interactive-prompt-title";c.useEffect(()=>{if(l(Yu(e)),u(!1),m.current=!1,!(e==null?void 0:e.prompt.promptId))return;const C=setTimeout(()=>{m.current=!0,u(!0)},_0);return()=>clearTimeout(C)},[e==null?void 0:e.prompt.promptId]),c.useEffect(()=>{if(e)return C0(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 j=h.current;if(!j)return;const C=()=>Array.from(j.querySelectorAll(Gu)),E=P=>{if(P.key!=="Tab")return;const T=C();if(T.length===0)return;const M=T[0],_=T[T.length-1],I=document.activeElement;P.shiftKey?(I===M||!j.contains(I))&&(P.preventDefault(),_.focus()):(I===_||!j.contains(I))&&(P.preventDefault(),M.focus())};return j.addEventListener("keydown",E),()=>j.removeEventListener("keydown",E)},[b,f,x]),c.useEffect(()=>{if(!b)return;const j=h.current;if(!j)return;const C=document.activeElement;if(C instanceof Node&&j.contains(C))return;(Array.from(j.querySelectorAll(Gu))[0]||j).focus()},[b,f,x]);const g=(e==null?void 0:e.prompt.questions)||[],v=g.length===1,S=c.useMemo(()=>e?e.prompt.questions.every(j=>Qu(j,i[j.questionId])):!1,[e,i]),A=c.useMemo(()=>g.filter(j=>!Qu(j,i[j.questionId])).length,[g,i]);if(!e)return null;const k=(j,C)=>{l(E=>{const P=E[j.questionId]||{selectedLabels:[]},T=P.selectedLabels||[],M=j.multiSelect?T.includes(C)?T.filter(_=>_!==C):[...T,C]:[C];return{...E,[j.questionId]:{...P,selectedLabels:M}}})},w=(j,C)=>{l(E=>({...E,[j]:{...E[j]||{selectedLabels:[]},freeformText:C}}))},y=()=>{!S||t||!m.current||r(i)},N=xf(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(tn,{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(Lt,{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((j,C)=>{var T,M;const E=((T=N.answers[j.questionId])==null?void 0:T.selectedLabels)||[],P=j.multiSelect?a("interactivePrompt.multipleChoice"):a("interactivePrompt.singleChoice");return n.jsxs("section",{className:C>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:[j.header&&n.jsx("span",{className:"text-xs font-semibold uppercase tracking-normal text-text-muted",children:j.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:[v?"":`${C+1}. `,j.question]}),j.multiSelect&&j.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:j.multiSelect?"group":"radiogroup","aria-label":j.question,children:j.options.map(_=>n.jsx(A0,{label:_.label,description:_.description||_.preview,selected:E.includes(_.label),multiSelect:j.multiSelect,disabled:t,onClick:()=>k(j,_.label)},_.label))}),j.allowFreeform&&n.jsxs("label",{className:"block",children:[n.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:a("interactivePrompt.other")}),n.jsx("textarea",{value:((M=i[j.questionId])==null?void 0:M.freeformText)||"",disabled:t,onChange:_=>w(j.questionId,_.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-default bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]},j.questionId)}),s&&n.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:s})]}),n.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border-default px-5 pt-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))]",children:[!S&&A>0&&n.jsx("span",{className:"mr-auto text-xs text-text-muted",children:a("interactivePrompt.answersRequired",{count:A})}),n.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:o,disabled:t,children:a("common.cancel")}),n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:y,disabled:!S||t||!d,children:a(t?"interactivePrompt.submitting":"interactivePrompt.submit")})]})]})})})}function rn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var yf=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress"];rn(yf);var T0=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];rn(T0);var I0=["p2p_offer","p2p_ice"];rn(I0);var M0=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];rn(M0);var R0=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","daemon_mesh_command","p2p_offer","p2p_ice"];rn(R0);var P0=["auth_ok","auth_error","machine_evicted","force_disconnect","token_revoked","version_mismatch","force_update_required","command","agent_command","resolve_action","daemon_mesh_result","p2p_ready","p2p_offer","p2p_answer","p2p_ice","mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];rn(P0);var E0=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],L0=[...yf,...E0];rn(L0);var D0=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];rn(D0);var O0=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];rn(O0);var $0=["p2p_ready","p2p_answer","p2p_ice"];rn($0);var F0=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];rn(F0);var H0=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];rn(H0);var vf=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];rn(vf);var wf=["ping","pong","p2p_evicted","status_event","topic_update","topic_update_chunk","session_output","session_output_chunk","session_io_error","command_result","command_result_chunk","response","transcript_topics_available"];rn(wf);[...new Set([...vf,...wf])];var Sf=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"],B0={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"},W0=new Set(Sf);function U0(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return W0.has(t)?t:B0[t]??null}var K0=["pending","assigned","completed","failed","cancelled"],q0=["completed","failed","cancelled"],z0=["code_change","validation","live_debug_readonly","launch_app","convergence"],V0=["low","normal","high"],G0=["when_idle","interrupt"],kf=["completed","blocked","failed"],Y0=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function Ir(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Ir(K0);Ir(q0);Ir(z0);Ir(V0);Ir(G0);Ir(kf);var Q0=["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"],J0=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(J0);var X0=["projects","project_status","project_send","project_read","project_add","discover_repos","memory","skill_view","skill_manage","project_note"];new Set(X0);var Z0=["mesh_queue","mesh_direct","plain"],ek=["delivered","queued"],tk=["local","p2p"],nk=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],sk=["default","native_source"],rk=["restart","live_holder"],ok=["approval","choice"],ak=["approved","rejected","answered"],ik=["modal_button","auto_approve","prompt_answer"],ck=["genuine","weak"],lk=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],dk=["completed","aborted"],uk=["alive","unknown","read_failed","dead"],Ju=["auth_failed","billing_failed"],mk=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],hk=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],pk=["completed","failed"],fk=["operator_update","refine_terminal","validation_terminal"],bk=["delivered","queued","duplicate"],gk=[...Sf,"unknown"],xk=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],yk=["completed","failed","cancelled"],vk=["genuine","weak","tool_report","operator"],wk=["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"],jf=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],Xs={t:"id"},Zs={t:"id",optional:!0},cs={t:"bool"},Go={t:"bool",optional:!0},Xu={t:"ms"},Sk={t:"ms",optional:!0},Yo={t:"int",optional:!0},Pt=e=>({t:"enum",values:e}),er=e=>({t:"enum",values:e,optional:!0}),kk={dispatch_accepted:{scope:Pt(Z0),messageId:Xs,meshId:Zs,nodeId:Zs,providerType:Zs,attemptNo:Yo,dispatchNonce:Yo,consumeProfile:er(sk),maxTaskRetries:Yo,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:Xs,outcome:Pt(ek),via:Pt(tk)},delivery_refused:{messageId:Xs,reason:Pt(Q0)},dispatch_failed:{workerAbsent:cs,reason:Pt(nk),refusalCode:Zs},duplicate_dispatch_refusal:{holderSessionId:Xs,holderAttemptId:Zs},session_rebound:{toSessionId:Xs,reason:Pt(rk)},turn_started:{retro:cs},suspension:{modal:Pt(ok),modalKey:Zs},suspension_resolved:{resolution:Pt(ak),via:Pt(ik)},turn_end:{strength:Pt(ck),afterFinalizationTimeout:Go,hollow:Go,summary:{t:"summary_ref",optional:!0},blockReason:er(lk),releasedByHardCap:Go,nativeOutcome:er(dk),live:{t:"live",optional:!0},reportExpected:Go,providerFailure:er(Ju)},transcript_final:{selfAttributing:cs,nativeRead:cs,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:Sk},transcript_activity:{newestActivityAt:Xu},no_progress:{stalledMs:Xu,observedStatus:Pt(gk),finalAssistantPresent:cs},liveness:{result:Pt(uk)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:er(Ju)},session_error:{reason:Pt(mk)},worker_report:{outcome:Pt(kf),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:cs,branchState:er(Y0),touchedFileCount:Yo},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:cs,commitsSinceDispatch:{t:"int"},attributable:cs},cancel:{reason:Pt(hk)},operator_status:{status:Pt(pk),reason:Pt(fk)},coordinator_ack:{notify:Pt(jf),outcome:Pt(bk)},hold_expired:{holdId:Xs,reason:Pt(xk)}},jk=Object.keys(kk);function Mo(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Mo(jk);Mo(wk);Mo(jf);Mo(yk);Mo(vk);function ts(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var Nk=["applied","recorded","rejected"];ts(Nk);var Ck=["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(Ck);var _k=["completed","failed"];ts(_k);var Ak=["operator_update","refine_terminal","validation_terminal"];ts(Ak);var Tk=["own","fleet"];ts(Tk);var Ik=["active","paused","completed","abandoned"];ts(Ik);var Mk=["provider_quirk","pattern_to_avoid","recovery_lesson"];ts(Mk);var Rk=["coordinator","unknown"];ts(Rk);var Pk=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];ts(Pk);var Ek=["turn_observe","mesh_record","turn_cancel","operator_status","turn_query","mesh_index_query","mission_upsert","mission_query","note_upsert","note_forget","tool_call_record","ledger_query","mission_list_query","record_local","queue_query","queue_enqueue","queue_enqueue_batch","queue_cancel","queue_requeue","direct_dispatch_record","active_work_query","recovery_context_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];ts(Ek);function Lk(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Zt(e,t){return Lk(t==null?void 0:t.activeModal)?"waiting_approval":U0(e)??"idle"}function wl(e){return Zt(e)==="generating"}function Zu(e,t){return Zt(e,t)==="waiting_approval"}function Dk(e){return(e==null?void 0:e.surfaceHidden)===!0}function Ok(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function Ss(e){const t=e.connectionState==="failed"||e.connectionState==="closed",s=e.connectionState==="connecting"||e.connectionState==="new",r=bi(e.status),o=Zt(e.status),a=o==="waiting_approval",i=o==="waiting_choice",l=Gy(o);return{isReconnecting:t,isConnecting:s,isGenerating:r,isWaiting:a,isWaitingChoice:i,isErrored:l}}function $k(e){const t=!e.hasLiveSnapshot&&e.visibleMessageCount===0,{isGenerating:s}=Ss(e),r=s&&(!t||Zt(e.status)==="generating");return{awaitingFirstView:t,showWorkingIndicator:r}}function Us(e){return Ss(e).isGenerating}function Fk(e){let t=0;for(const s of e)Us(s)&&t++;return t}function em(e){let t=0;return e.unread!==void 0&&(t+=1),e.lastSeenAt!==void 0&&(t+=1),e.lastUpdated!==void 0&&(t+=1),e.inboxBucket!==void 0&&(t+=1),e.surfaceHidden!==void 0&&(t+=1),e.muted!==void 0&&(t+=1),e.completionMarker!==void 0&&(t+=1),e.seenCompletionMarker!==void 0&&(t+=1),t}function Hk(e,t){const s=e.lastUpdated||0,r=t.lastUpdated||0;if(r!==s)return r>s;const o=em(e),a=em(t);return a!==o?a>o:!1}function tm(e,t,s){return e===void 0?t:t===void 0?e:s?t:e}function Nf(e){const t=new Map,s=new Map,r=(o,a)=>{if(!o)return;const i=s.get(o),l=t.get(o),d=(a.lastUpdated||0)>((i==null?void 0:i.lastUpdated)||0),u=tm(l==null?void 0:l.surfaceHidden,typeof a.surfaceHidden=="boolean"?a.surfaceHidden:void 0,d),m=tm(l==null?void 0:l.muted,typeof a.muted=="boolean"?a.muted:void 0,d);if(i&&!Hk(i,a)){l&&t.set(o,{...l,surfaceHidden:u,muted:m});return}s.set(o,a),t.set(o,{sessionId:o,...Ok(a),surfaceHidden:u,muted:m})};for(const o of e)if(o.type!=="adhdev-daemon"){r(o.sessionId,o);for(const a of o.childSessions||[])r(a.id,a)}return t}function ys(e,t){if(e.sessionId){const s=t.get(e.sessionId);if(s)return s}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:void 0,muted:void 0,completionMarker:"",seenCompletionMarker:""}}function Ni(e,t,s){const r=ys(e,t),o=Ss(e),a=o.isReconnecting,i=o.isConnecting,l=o.isGenerating,d=o.isWaiting,u=o.isWaitingChoice,m=r.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d||u,h=r.inboxBucket==="working"||l,b=!!(r.inboxBucket==="task_complete"&&r.unread&&!(s!=null&&s.hideOpenTaskCompleteUnread&&(s!=null&&s.isOpenConversation)));return{unread:b,requiresAction:m,isWorking:h,isReconnecting:a,isConnecting:i,isGenerating:l,isWaiting:d,inboxBucket:m?"needs_attention":h?"working":b?"task_complete":"idle"}}function Bk(e,t,s){return Ni(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:s==null?void 0:s.isOpenConversation}).unread}function Wk(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Uk(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 Kk(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 qk({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(!Wk(a))throw new Error(Uk(a));return}await Kk(e.sessionId,t,o)}let Sl=null;const kl=new Set;function zk(e){return kl.add(e),()=>{kl.delete(e)}}function nm(){return Sl}function Qo(e){if(Sl!==e){Sl=e;for(const t of kl)t()}}function Ci(e,t){const{t:s}=he("common"),{ides:r,isP2PActive:o,p2pStates:a}=yn(),{sendCommand:i}=wt(),l=c.useSyncExternalStore(zk,nm,nm),[d,u]=c.useState(!1),[m,h]=c.useState(null),p=c.useRef(!1),b=(t==null?void 0:t.includeHidden)===!0,f=c.useMemo(()=>N0(r,{sessionId:e,includeHidden:b}),[r,e,b]),x=!!f,g=c.useMemo(()=>f?f.prompt.promptId===l?null:f:null,[l,f]),v=(f==null?void 0:f.prompt.promptId)??null;c.useEffect(()=>{h(null)},[v]);const S=c.useCallback(async w=>{if(!g||p.current)return;p.current=!0;const y=xf(g.prompt,w);u(!0),h(null);try{const N=(a==null?void 0:a[g.daemonId])==="connected"||o===!0;await qk({promptSession:g,response:y,useP2PCommand:N,sendCommand:i}),Qo(g.prompt.promptId)}catch(N){let j=N instanceof Error?N.message:String(N);throw j.includes(zy)?(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."})),N):(j.includes(qy)&&(j=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(j),N)}finally{u(!1),p.current=!1}},[o,a,g,i]),A=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:m,isSubmitting:d,submit:S,cancel:A,reopen:k}}function Cf(e){return e.sessionId??e.routeId}const mc=e=>e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*\(\s*\b(?:Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)\b(?:\s*\+\s*\w+)*\s*\)/gi,"").replace(/\s*\b(?:Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)\b(?:\s*\+\s*\w+)*/gi,"").trim(),Vk=12e3;function Gk(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 _f({activeConv:e,onModalButton:t}){const{t:s}=he(),[r,o]=c.useState(null),{hasActivePrompt:a,promptSession:i,reopen:l}=Ci(Cf(e));c.useEffect(()=>{o(null)},[e.modalMessage,e.status,e.connectionState]),c.useEffect(()=>{if(!r)return;const h=setTimeout(()=>o(null),Vk);return()=>clearTimeout(h)},[r]);const d=Ss(e);if(!d.isWaiting&&!d.isWaitingChoice||!e.modalButtons)return null;const u=h=>{r||(o(h),t(h))},m=()=>n.jsx("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:n.jsx("div",{className:"flex items-center gap-2",children:n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(tn,{size:14}),s("approval.questionUnavailable",{defaultValue:"Question waiting — could not load it here. Answer it in the terminal view."})]})})});return a&&!i?m():a?n.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&n.jsx("div",{className:"text-2xs opacity-85 mb-1.5 line-clamp-3 max-w-full whitespace-pre-wrap break-words",title:e.modalMessage,children:e.modalMessage}),n.jsxs("div",{className:"flex justify-between items-center gap-2",children:[n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(tn,{size:14})," ",s("approval.questionPending",{defaultValue:"Question waiting"})]}),n.jsx("button",{onClick:l,className:"btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold cursor-pointer whitespace-nowrap shrink-0",style:{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"},children:s("approval.answerQuestion",{defaultValue:"Answer the question"})})]})]}):d.isWaitingChoice?m():n.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&n.jsx("div",{className:"text-2xs opacity-85 mb-1.5 line-clamp-4 max-w-full whitespace-pre-wrap break-words",title:e.modalMessage,children:e.modalMessage}),n.jsxs("div",{className:"flex justify-between items-center",children:[n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(tn,{size:14})," ",s(r?"approval.processing":"approval.actionRequired")]}),n.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((h,p)=>{const b=mc(h).toLowerCase(),f=Gk(b),x=f==="always",g=f==="primary",v=f==="danger",S=r===h,A=r!==null;return n.jsx("button",{onClick:()=>u(h),disabled:A,title:x?s("approval.alwaysAllowWarning"):void 0,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${g?"font-extrabold":v?"bg-red-500/30 text-white font-semibold":x?"text-white/90 font-semibold":"text-white font-semibold"} ${A&&!S?"opacity-40":"opacity-100"} ${A?"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)"}:v?void 0:{background:"color-mix(in srgb, black 18%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 35%, transparent)"},children:S?n.jsx(yr,{size:12}):x?n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(tn,{size:11}),mc(h)]}):mc(h)},p)})})]})]})}const Cd="adhdev_controls_bar_visible",jl="adhdev:controlsbarvisibilitychange";function hc(e){if(!e)return!1;try{return e.getItem(Cd)==="1"}catch{return!1}}function Yk(e,t){if(t)try{t.setItem(Cd,e?"1":"0")}catch{}}function Qk(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(jl,{detail:{visible:e}}))}function _d(){const[e,t]=c.useState(()=>typeof window>"u"?!1:hc(window.localStorage)),s=c.useRef(e),r=c.useCallback((i,l=!0)=>{s.current=i,t(i),typeof window<"u"&&Yk(i,window.localStorage),l&&Qk(i)},[]);c.useEffect(()=>{const i=d=>{const u=d.detail,m=typeof(u==null?void 0:u.visible)=="boolean"?u.visible:hc(window.localStorage);s.current=m,t(m)},l=d=>{if(d.key!==Cd)return;const u=hc(window.localStorage);s.current=u,t(u)};return window.addEventListener(jl,i),window.addEventListener("storage",l),()=>{window.removeEventListener(jl,i),window.removeEventListener("storage",l)}},[]);const o=c.useCallback(i=>{r(i)},[r]),a=c.useCallback(()=>{r(!s.current)},[r]);return{isVisible:e,setVisibility:o,toggleVisibility:a}}const Af=["en","ko","ja","zh-CN","es"],Ds="en",Ns=[{code:"en",label:"English"},{code:"ko",label:"한국어"},{code:"ja",label:"日本語"},{code:"zh-CN",label:"中文(简体)"},{code:"es",label:"Español"}];function Es(e){return typeof e=="string"&&Af.includes(e)}function Jk(e){if(!e)return Ds;const t=e.trim().toLowerCase();if(!t)return Ds;if(t==="zh"||t.startsWith("zh-")||t.startsWith("zh_"))return"zh-CN";const s=t.split(/[-_]/)[0];return s==="en"?"en":s==="ko"?"ko":s==="ja"?"ja":s==="es"?"es":Ds}const Xk={runFailed:"Couldn't run {{label}}",updateFailed:"Couldn't update {{label}}",loadOptionsFailed:"Couldn't load {{label}} options"},Zk={unknown:"Unknown",starting:"Starting",stopped:"Stopped",failed:"Failed",idle:"Idle",generating:"Working",awaitingApproval:"Needs approval"},ej={label:"Language",select:"Select language"},tj={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?"},nj={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"},sj={details:"Details",label:{success:"Done",warning:"Attention",info:"Update"},dismiss:"Dismiss"},rj={actionNeeded:"Action needed",taskComplete:"Task complete",markRead:"Mark read",markUnread:"Mark unread",delete:"Delete"},oj={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"},aj={header:{moreActions:"More actions",title:"Dashboard",guide:"Dashboard guide",guideOpen:"Open dashboard guide",guideShort:"Guide",openGitStatus:"Open git status",meshGraph:"Mesh graph",stopCliProcess:"Stop CLI process",chatHistory:"Chat History",remoteControl:"Remote Control",generating:"generating",activityInbox:"Notifications"},hidden:{title:"Hidden tabs",dragHint:"Drag a tab here to hide it.",resetPanels:"Reset panels",restoreAll:"Restore all",hideCurrentTab:"Hide current tab",empty:"No hidden tabs.",resetPanelsConfirm:"Move every floating or popout panel back into the main dashboard grid?"},inbox:{unread:"Unread",read:"Read",empty:"No pending activity."},metaChips:{queuePending:"{{count}} waiting",queueTooltip:"Queue: {{pending}} waiting, {{assigned}} assigned, {{completed}} completed, {{failed}} failed"},meshRole:{coordinator:"Coordinator",worker:"Worker",coordinatorFor:"Coordinator for {{mesh}}",workerFor:"Worker for {{mesh}}",coordinatorUnknownMesh:"Mesh coordinator",workerUnknownMesh:"Mesh worker",openMeshGraph:"Open mesh graph"},assistant:{label:"Assistant",start:"Start assistant",starting:"Starting…",startHint:"Start your personal assistant — a chat that manages your projects and coordinators",startFailed:"Could not start the assistant: {{error}}"},assistantLaunch:{chooseCli:"Choose the assistant's CLI",startWith:"Starts with {{cli}}",noToolLock:"no tool lock",noToolLockHint:"Only the assistant's instructions limit this CLI's tools — it keeps its own shell and file tools",unavailable:"Unavailable: {{reason}}",unsupported:"This CLI can't host the assistant",hostsProjects_one:"hosts {{count}} project",hostsProjects_other:"hosts {{count}} projects",hostsProjectsHint:"The assistant can manage only the projects hosted on its own machine",model:"Model",thinking:"Thinking",defaultOption:"Default",start:"Start assistant"},versionBanner:{restarting:"restarting",upgrading:"updating…",unknownVersion:"unknown",updateAvailable:"Update available",required:"required",retry:"retry"},remoteDialog:{liveRemoteView:"Live remote view",remoteUnavailable:"Remote view unavailable",remoteOnly:"Remote only",splitView:"Split view",remoteFallback:"Remote",history:"History"},guide:{title:"Dashboard guide",subtitle:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune.",close:"Close dashboard guide",tabs:{overview:"Overview",quickstart:"Quick start",shortcuts:"Shortcuts"},overview:{whatLivesWhere:{title:"What lives where",tabsLabel:"Tabs:",tabsText:"active sessions across IDE and CLI agents.",hiddenLabel:"Hidden tabs:",hiddenText:"stash sessions you do not want in the main strip but still want to keep around.",inboxLabel:"Activity inbox:",inboxText:"sessions waiting for approval or finished tasks you have not reviewed yet.",cliToggleLabel:"CLI view toggle:",cliToggleText:"switch a PTY session between terminal and chat rendering without relaunching it."},usefulFlows:{title:"Useful flows",reviewLabel:"Review notifications:",reviewText:"open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane.",clutterLabel:"Reduce clutter:",clutterText:"hide less important sessions instead of closing them, then restore from hidden tabs when needed.",splitLabel:"Split work:",splitText:"keep one pane active for input and let secondary panes stay read-only until you focus them.",detachedLabel:"Detached views:",detachedText:"float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor.",dockingLabel:"Docking:",dockingText:"use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard.",perTabLabel:"Per-tab shortcuts:",perTabText:"right-click a Dockview tab to assign a direct shortcut for that specific session.",approvalLabel:"Approval buttons:",approvalText:"use {{keys}} for the first three visible approval actions on the active session."}},quickstart:{desktop:{title:"Desktop quick start",step1:"Start from the machine or workspace flow first. Pick or save a workspace before launching CLI sessions.",step2:"Keep the main strip focused on active work and push overflow into Hidden tabs.",step3:"Use the inbox for approval-required or completed sessions instead of scanning every tab.",step4:"Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."},mobile:{title:"Mobile quick start",step1:"Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions.",step2:"Start from the machine screen, choose a workspace, then launch IDE or CLI from there.",step3:"Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."}},shortcuts:{sections:{all:"All",workspace:"Workspace",panes:"Panes",approvals:"Approvals"},disableAll:"Disable all",resetToDefaults:"Reset to defaults",default:"Default:",listening:"Listening...",set:"Set",disable:"Disable",off:"Off",footer:"Use modifier shortcuts like {{keys}}, or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs.",resetConfirm:"Reset all dashboard shortcuts back to their default values?",setListening:"Listening"}},shortcutDefs:{openShortcutHelp:{label:"Open shortcuts",description:"Show the keyboard shortcuts panel."},openNewSession:{label:"New session",description:"Open the new session launcher."},hideCurrentTab:{label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs."},toggleHiddenTabs:{label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover."},openHistoryForActiveTab:{label:"Open history",description:"Open history for the active session."},openRemoteForActiveTab:{label:"Open remote",description:"Open remote control for the active session when available."},floatActiveTab:{label:"Float active tab",description:"Move the active tab into a floating panel."},popoutActiveTab:{label:"Open active tab in new window",description:"Move the active tab into a detached popout window."},dockActiveTab:{label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window."},splitActiveTabRight:{label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it."},splitActiveTabDown:{label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it."},focusLeftPane:{label:"Focus left pane",description:"Move focus to the pane on the left."},focusRightPane:{label:"Focus right pane",description:"Move focus to the pane on the right."},focusUpPane:{label:"Focus upper pane",description:"Move focus to the pane above."},focusDownPane:{label:"Focus lower pane",description:"Move focus to the pane below."},moveActiveTabToLeftPane:{label:"Move active tab left",description:"Move the active tab into the pane on the left."},moveActiveTabToRightPane:{label:"Move active tab right",description:"Move the active tab into the pane on the right."},moveActiveTabToUpPane:{label:"Move active tab up",description:"Move the active tab into the pane above."},moveActiveTabToDownPane:{label:"Move active tab down",description:"Move the active tab into the pane below."},triggerPrimaryApprovalAction:{label:"Approval action 1",description:"Press the first approval/action button for the active session."},triggerSecondaryApprovalAction:{label:"Approval action 2",description:"Press the second approval/action button for the active session."},triggerTertiaryApprovalAction:{label:"Approval action 3",description:"Press the third approval/action button for the active session."},setActiveTabShortcut:{label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab."},selectPreviousGroupTab:{label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group."},selectNextGroupTab:{label:"Next tab in group",description:"Move to the next tab inside the active Dockview group."},toggleCliView:{label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view."}}},ij={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"},cj={processing:"PROCESSING...",actionRequired:"ACTION REQUIRED",alwaysAllowWarning:"Grants this permission permanently — future runs will not ask again",questionPending:"QUESTION WAITING",answerQuestion:"Answer the question"},lj={loading:"Loading…",launchModelChanged:"{{from}} → {{to}} (changed)",launchModelSource:{user:"chosen",remembered:"remembered",mesh_slot:"mesh slot",task_override:"task override",provider_default:"default"}},dj={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"},uj={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)"},mj={hint:{daemon:{followUp:"Needs follow-up",merged:"Merged",notMergeable:"Can't merge yet — changes or conflicts",cleanup:"Merged — worktree can be cleaned up",needsMerge:"Pushed — ready to merge",blockedReview:"Needs review before merging"},anchorEmpty:"No workspace on the default branch",anchorWorkspaces:"{{count}} workspace(s) on {{branch}}",anchorNeedsFollowUp:"{{count}} on {{branch}} need follow-up",submoduleSynced:"{{path}} is in sync",submoduleChanged:"{{path}} has local changes",submoduleOutOfSync:"{{path}} is out of sync with its parent",gitAgeUnknown:"Git status age unknown",staleGit:"Git status is over 5 min old",missingSubmodule:"Submodule not reported: {{paths}}",noGitYet:"No git status received yet",noGitYetOnline:"Online — git status not received yet",waitingForGit:"Waiting for git status…",nodeError:"Node reported an error",upstreamUnverified:"Upstream not verified yet",noUpstream:"Push {{branch}} to set its upstream",mergeConflicts:"Resolve merge conflicts",detachedHead:"Detached HEAD — check out a branch",notGitRepo:"Not a git repository",noGitStatus:"No git status yet"},sessionCleanup:{stopAndDeleteHint:"Stop matching sessions, then remove their chat records.",stopAndDelete:"Stop and delete sessions",deleteStoppedHint:"Clear finished or stopped chats without stopping running sessions.",deleteStopped:"Delete stopped sessions only",stopHint:"Stop running session processes but keep their chat records.",stop:"Stop running sessions only",preserveHint:"Keep finished chat history and leave running sessions alone.",preserve:"Keep history and running sessions"},nodeHealth:{failed:"Failed",completed:"Completed",assigned:"Assigned",pending:"Pending",enabled:"Enabled",unknown:"Connecting…",wrongBranch:"Other branch",degradedHint:"The connection to this machine is down or timed out — often temporary. Wait a moment or reconnect the machine.",degraded:"Unreachable",offline:"Offline",dirty:"Uncommitted changes",online:"Online"},activity:{noKeyEvents:"No recent key events",showKey:"Show key events only",showAll:"Show all activity",nodeChanged:"Machine joined or left",worktreeCreated:"Worktree created",nodeJoined:"Node joined",nodeRemoved:"Node removed",sessionStarted:"Agent started",needsInput:"Needs your input",taskFailed:"Task failed",taskFinished:"Task finished",taskStarted:"Task started"},drift:{clean:"Clean",conflicts:"conflicts",submoduleOutOfSync_other:"{{count}} submodules out of sync",submoduleOutOfSync_one:"{{count}} submodule out of sync",submoduleChanged_other:"{{count}} submodules changed",submoduleChanged_one:"{{count}} submodule changed",changed_other:"{{count}} changed",changed_one:"{{count}} changed",upstreamUnverified:"upstream unverified",noGit:"No git info",probePending:"Checking git…"},graph:{slowLinkChip:"Slow link",observationUnreachableChip:"Unreachable",observationStaleChip:"Stale",remoteBadge:"remote",activeSessionAria:"active session",observationAsOf:"as of {{age}} ago",observationRefreshing:"as of {{age}} ago · refreshing",observationFetching:"fetching state…",observationUnreachable:"unreachable · last known {{age}} ago",observationUnreachableNoState:"unreachable · no state yet"},statusTab:{v2ScopeHint:"Pending events by scope",providerSkewHint:"Providers running different versions on different nodes",providerSkew:"{{count}} provider version mismatch",v2RatioHint:"Share of pending coordinator events in the current message format",daemonBuildHint:"Exact daemon build (version@commit) running on this node",quotaFailedHint:"This machine couldn't read this provider's usage",quotaOkNoWindowHint:"Read successfully — this provider has no percentage limit to show",nodeCountHint:"Mesh nodes (workspaces/worktrees) on this machine — they share one plan quota",nodeCount_other:"{{count}} nodes",nodeCount_one:"{{count}} node",daemonVersionHint:"Daemon version running on this machine",blockedReasonHint:"Why this node can't take a new code-changing task right now",providerCapHint:"Active tasks per provider on this node vs its declared limit",priorityHint:"Scheduling preference (higher is preferred)",priority:"priority {{value}}",loadHint:"Active tasks assigned to this node",load:"load {{count}}",readonlyCapHint:"Active read-only investigation tasks vs their limit (2× the write limit)",readonlyCap:"read-only {{active}}/{{max}}",writeCapHint:"Active tasks that change code vs the mesh-wide parallel limit",writeCap:"write {{active}}/{{max}}"},manualSetup:{restartHint:"Start a fresh CLI session after editing config.",configPath:"Config path:",format:"Format:",server:"Server:",titleFor:"Manual MCP setup required for {{provider}}",title:"Manual MCP setup required"},help:{toggleAria:"Mesh help",toggleTitle:"Mesh concept help",regionAria:"Mesh concept help",kicker:"Help",title:"Mesh concepts at a glance",close:"Close help",sections:{node:{term:"Node",summary:"A workspace participating in the mesh — a repo checkout or an isolated git worktree.",details:["Base node vs worktree clone node — a clone isolates parallel work without conflicts.","Shows health (online/offline) alongside git state (branch · ahead/behind · dirty).","Multiple nodes can share the same daemon."]},p2p:{term:"P2P connection",summary:"How the selected coordinator reaches each remote node over WebRTC.",details:["direct — a direct host/STUN path; lowest latency.","relay — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed — no live P2P link from the coordinator right now.","P2P connectivity is shown as transport and RTT chips on each node card (and in the node detail panel), not as a graph edge."]},session:{term:"Session",summary:"An agent CLI session running on a node.",details:["status = idle / generating / waiting_approval.","Distinguishes coordinator sessions (which dispatch and collect work) from delegated worker sessions (which do the work)."]},task:{term:"Task",summary:"A single unit of work handled by the queue-based pull model.",details:["States: pending → assigned → completed / failed / cancelled.","Idle nodes claim from the queue automatically; direct dispatch targets a specific session."]},mission:{term:"Mission",summary:"A multi-task batch aimed at one goal, and the durable record of that effort.",details:["States: active / paused / completed / abandoned.","Progress is derived from the states of its member tasks."]},refinery:{term:"Refinery (refine)",summary:"The process of safely converging and merging a worktree branch into the base.",details:["Config-driven (.adhdev/refine.*) — guarded by a patch-equivalence preflight and a no-op guard.","ff-only by principle; no force-push.","If a submodule commit is unreachable from origin it must be published → classified as blocked_review."]},completion:{term:"Completion model",summary:"Completion of delegated work is persisted to the queue (pending-events).",details:["The coordinator learns of completion via periodic polling or events.","Because it is persisted to the queue, completion signals are never lost."]},convergence:{term:"Branch convergence states",summary:"After worktree work, each branch is classified into exactly one final state.",details:["merged_to_main — merged into the base.","pushed_feature_branch_needs_merge — pushed, awaiting merge.","blocked_review — held back by review/reachability issues.","cleanup_candidate — ready to clean up.","not_mergeable — cannot be merged."]},blueprint:{term:"Blueprint",summary:"The plan view: live queue work and its task dependencies on one canvas.",details:["One axis — dependency depth, left to right. Root tasks are ordered newest first.","Cards carry their own time, so position never has to encode it.","Finished dependency chains fold away so live work stays in view."]},routingPreview:{term:"Routing preview",summary:"A read-only forecast of where a hypothetical task would land.",details:["Shown per difficulty; a task pinned to a node gets its own pinned preview (📌).","It is a prediction, not the owner — a card that already ran shows its real node below."]},worktree:{term:"Worktree node",summary:"A node backed by a git worktree rather than the main checkout.",details:["Labelled by its branch (⎇). Lets several tasks run on one machine without sharing a branch.","Orphan worktrees are reported as cleanup candidates and are never deleted automatically."]}}},approvals:{title:"PENDING APPROVALS",empty:"No sessions are awaiting an approval decision.",sessionFallback:"session {{id}}",approve:"Approve",reject:"Reject",waitingFor:"Waiting for {{duration}}"},difficulty:{easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"},panel:{outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusCoordinator:"coordinator",statusWorker:"worker",upstreamUnverified:"unverified",needsFollowUp:"needs follow-up",refined:"refined",tooltipLocalChanges:"Local changes",tooltipHasConflicts:"Has conflicts",tooltipOutOfSync:"Out of sync",tooltipNeedsFollowUp:"Needs follow-up",tooltipUpstreamUnverified:"Upstream unverified",tooltipRefineCompleted:"refine completed",tooltipRefinedBranch:"refined {{branch}}",tooltipP2PRelayed:"P2P link relayed through TURN (slower path)",tooltipPrefixStatus:"Status:",tooltipPrefixBranch:"Branch:",tooltipPrefixNote:"Note:",defaultBranch:"default branch",submoduleSynced:"synced",moreChats_one:"+{{count}} more chat",moreChats_other:"+{{count}} more chats",remote:"remote",chats_one:"{{count}} chat",chats_other:"{{count}} chats",generatingCount:"{{count}} generating",coordinatorAttached:"coordinator attached",coordinators:"{{count}} coordinators",workers_one:"{{count}} worker",workers_other:"{{count}} workers",sampledStatus:"sampled status"},legendEdge:{parentBranch:"default branch",cloneLink:"worktree clone",worktreeLink:"same branch",submoduleLink:"submodule",sessionLink:"session",orphanLink:"needs follow-up"},attention:{submoduleDrift:"submodule drift",submoduleDirty:"submodule dirty",conflictsPresent:"conflicts present",dirtyWorkspace:"dirty workspace",upstreamUnverified:"upstream unverified",pushBranch:"push branch",blockedReview:"blocked review",refineFailed:"refine failed",working:"working",refining:"refining…",needsMerge:"needs merge",refineWorktree:"refine worktree",needsFollowUp:"needs follow-up",offline:"offline",ahead:"ahead {{count}}",behind:"behind {{count}}",aheadBehind:"ahead {{ahead}} / behind {{behind}}"},summary:{anchor:"Default branch anchor",parent:"parent {{label}}",localChanges:"local changes",sessions_one:"{{count}} session",sessions_other:"{{count}} sessions",conflicts:"conflicts",clean:"Clean and even with upstream"},taskDag:{plan:{depsFailed_one:"{{count}} upstream failed",depsFailed_other:"{{count}} upstream failed"},time:{now:"just now",minutes_one:"{{count}}m ago",minutes_other:"{{count}}m ago",hours_one:"{{count}}h ago",hours_other:"{{count}}h ago",days_one:"{{count}}d ago",days_other:"{{count}}d ago"},empty:"No tasks yet",waitsOn_one:"waits on {{count}}",waitsOn_other:"waits on {{count}}",missingDeps_one:"{{count}} unknown dep",missingDeps_other:"{{count}} unknown deps",legend:{satisfied:"done",waiting:"waiting",failed:"failed"},predictedSlotPinned:"Pinned to a target node — predicted slot on that node"},obs:{fieldEdgeId:"Link ID",fieldHealthRaw:"Health",fieldNodeId:"Node ID",machineSection:"Machine",behindCount:"{{count}} behind",aheadCount:"{{count}} ahead",healUnavailableHint:"Only a clean checkout that is strictly behind a verified upstream can be updated here.",healHint:"Fast-forward this checkout to its upstream. It has no local changes, so nothing can be lost.",healFailed:"Couldn't update {{label}}: {{reason}}",healDone:"{{label}} is up to date",directionTBShort:"↓",directionLRShort:"→",tabMap:"Map",closeDetailAria:"Close detail panel",layoutDirectionAria:"Graph layout direction",viewAria:"Mesh view",tabOverview:"Overview",tabTasks:"Tasks",panHint:"drag or scroll to pan",headlineFollowUp_one:"{{count}} needs attention",headlineFollowUp_other:"{{count}} need attention",headlineIncomplete:"Some machines not visible",headlineConverged:"All synced",badgeBlocked:"{{count}} blocked",badgeBlockedTitle:"{{count}} blocked review",badgeNotMergeable:"{{count}} not mergeable",badgeNeedMerge_one:"{{count}} needs merge",badgeNeedMerge_other:"{{count}} need merge",badgeCleanupTitle:"{{count}} refine/cleanup",badgeOffline:"{{count}} offline",badgeIncompleteTitle:"{{count}} incomplete peer snapshot",badgeNoGitTitle:"{{count}} no git snapshot",badgeNoSubmodTitle:"{{count}} missing submodule visibility",badgeStaleTitle:"{{count}} stale peer snapshot",badgeActiveQueue:"{{count}} active queue",badgeNodes_one:"{{count}} node",badgeNodes_other:"{{count}} nodes",badgeAttachedChats_one:"{{count}} attached chat",badgeAttachedChats_other:"{{count}} attached chats",legendDirty:"{{count}} dirty",legendOrphan:"{{count}} orphan",legendRecentFailures_one:"{{count}} recent failure",legendRecentFailures_other:"{{count}} recent failures",legendAnchor:"Anchor = default branch",legendPeerLink:"Peer link = same-branch worktree",legendSubmoduleLink:"Submodule link = child checkout",healthRefineFailed:"{{count}} refine failed",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedEdge:"Selected edge",activeSessions:"Active Sessions",queueTasks:"Queue tasks",keyWarning:"Key warning",noResultCode:"No result code returned.",legend:"Legend",checking:"Updating…",heal:"Update",loadingGraph:"Loading graph…",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",connecting:"connecting...",providerUnknown:"provider unknown",directionLRTitle:"Left to right",directionTBTitle:"Top to bottom"},notes:{sectionHint:"Lessons the coordinator keeps between sessions — provider quirks, patterns to avoid, recovery steps.",expired:"expired",neverExpires:"never expires",durable:"durable",expiresIn:"expires {{when}}",tab:"Notes",addTitle:"Add operating note",listTitle:"Operating notes",textPlaceholder:"Record a provider quirk, a pattern to avoid, or a recovery lesson...",categoryLabel:"Category",categoryUncategorized:"Uncategorized",categoryProviderQuirk:"Provider quirk",categoryPatternToAvoid:"Pattern to avoid",categoryRecoveryLesson:"Recovery lesson",add:"Add",edit:"Edit",delete:"Delete",save:"Save",cancel:"Cancel",refresh:"Refresh",loading:"Loading notes...",empty:"No operating notes recorded yet.",unavailable:"Operating notes are unavailable — the coordinator is not reachable over P2P.",loadFailed:"Failed to load operating notes.",saveFailed:"Failed to save the operating note.",deleteFailed:"Failed to delete the operating note.",editFailed:"Failed to update the operating note.",showMore:"Show more",showLess:"Show less",pinned:"pinned"},dialog:{liveUpdatesOn:"Live updates on",liveUpdatesPaused:"Live updates paused — showing the last loaded state",refreshedAt:"Refreshed {{time}}",refreshFailedQuiet:"refresh failed · showing last loaded",refreshTitle:"Refresh live mesh graph",loadingStatus:"Loading live mesh status…",noGraph:"No live mesh graph is available for this coordinator yet. Tap the ? above to learn what a Repo Mesh does.",errorNoMeshId:"This coordinator does not expose a live mesh id."},health:{statFailed:"Failed",statPending:"Waiting"},blueprint:{schedPrediction:"Prediction",readonlyBadge:"read-only",schedObservedAt:"as of {{time}}",schedNoNodes:"No routable nodes.",schedQuotaButton:"Quota",schedQuotaButtonTitle:"Per-machine plan quota at a glance",schedNoWinner:"no eligible slot",schedNext:"Next up",schedWaiting:"Ready",schedFull:"At capacity",schedFloorExcluded:"Below difficulty",schedQuotaGated:"Quota-gated",schedCapFree:"Free",schedColSlot:"Slot",schedColScore:"Score",schedColQuota:"Quota",schedColParallel:"Parallel",schedColStatus:"Status",schedColMachine:"Machine",schedNextTitle:"Dispatch a task of this difficulty now and this slot takes it",schedTargetWorktreeTitle:"The task would run in this worktree checkout",schedUnpinnedTitle:"Hypothetical dispatch with no target pin — tasks pinned to a node show their own forecast on their cards",schedPointInTime:"Point-in-time prediction, not a settled assignment: slot capacity can go stale as soon as a slot is claimed or released",schedulingShort:"Scheduling",list:{barActive:"Active {{count}}",barBlocked:"Blocked {{count}}",barRecent:"Recent {{count}}",barMissions_one:"{{count}} mission",barMissions_other:"{{count}} missions",sectionRunning:"Running",sectionBlocked:"Blocked",sectionRecent:"Recent",sectionHistory:"History",generating:"generating",approvalNeeded:"approval needed",choiceNeeded:"choice needed",planShow:"plan",planHide:"hide",planTitle:"Show this task's dependency plan",noMission:"No mission",loadMore_one:"Show {{count}} more",loadMore_other:"Show {{count}} more",emptyActive:"Nothing running",waitingOn:"waiting on:",waitingOnMore:"+{{count}} more",blockedByDeadDependency:"blocked by failed/cancelled dependency:",chainGroup:"Chain: {{title}}"},graph:{viewSwitchLabel:"Blueprint view",viewList:"List",viewGraph:"Graph",activeOnly:"Active only",activeOnlyTitle:"Hide lanes where everything has finished",hiddenLanes_one:"{{count}} finished lane hidden",hiddenLanes_other:"{{count}} finished lanes hidden",emptyActive:"Nothing running",showFinished:"Show finished lanes",layoutFailed:"Graph layout failed: {{error}}",laneAdhoc:"Independent tasks",laneCollapse:"Collapse",laneExpand:"Expand",foldCompleted:"Fold completed",unfoldCompleted:"Show completed",foldNode_one:"{{count}} completed",foldNode_other:"{{count}} completed",countRunning_one:"{{count}} running",countRunning_other:"{{count}} running",countDead_one:"{{count}} stuck",countDead_other:"{{count}} stuck",countWaiting_one:"{{count}} waiting",countWaiting_other:"{{count}} waiting",countFailed_one:"{{count}} failed",countFailed_other:"{{count}} failed",countDone_one:"{{count}} done",countDone_other:"{{count}} done",timeRunning:"running {{age}}",timeFinished:"ended {{time}}",timeQueued:"queued {{age}}",tooltipTask:"Task: {{id}}",tooltipMission:"Mission: {{id}}",tooltipStatus:"Status: {{status}}",deadDirect:"A dependency failed or was cancelled — this task will not start on its own.",deadTransitive:"Something upstream failed or was cancelled — this task will not start on its own.",legendDepends:"depends on",legendRunning:"running",legendDead:"can never start",heldUntil:"until {{time}}",tone:{pending:"pending",running:"running",completed:"completed",failed:"failed",cancelled:"cancelled",dead:"stuck",plan:"planned",held:"held"}}},page:{title:"Repo Mesh",subtitle:"Multi-workspace orchestration",waitingForDaemon:"Waiting for daemon connection..."},list:{nodeCount_other:"{{count}} nodes",nodeCount_one:"{{count}} node",machinesOnline:"{{online}}/{{total}} machines online",settings:"Settings",open:"Open",title:"Repo Meshes",count_one:"{{count}} mesh",count_other:"{{count}} meshes",createMesh:"+ Create Mesh",createTitle:"Create Repo Mesh",createOnMachine:"Create on machine",noConnectedDaemon:"No connected daemon",workspace:"Workspace",workspaceHint:"Choose from workspaces registered by the selected daemon.",name:"Name",remoteUrl:"Repo remote URL (recommended)",remoteUrlHint:"Paste your repo URL — the identity (github.com/user/repo) is filled in automatically.",repoIdentity:"Repo identity",repoIdentityHint:"For a repo with no remote, or when the URL differs per machine. e.g. github.com/user/repo",advancedIdentityToggle:"Advanced: set identity manually",create:"Create",creating:"Creating…",cancel:"Cancel",loading:"Loading meshes...",emptyTitle:"No Repo Meshes",emptyWithDaemons:"Run several coding agents on one repo across your machines.",emptyNoDaemons:"Connect a machine first.",createFirst:"Create First Mesh",noRepoIdentity:"No repo identity"},detail:{useFromCli:"Use from CLI",distributionInOrderSummary:"First available node, in the order added",distributionSmartSummary:"Best-fit node for each task, spread by load",tabGeneral:"General",back:"← Back",delete:"Delete",observabilityOpenTitle:"Open the live view (overview, tasks, map)",observabilityDisabledTitle:"The host machine must be connected first",observabilityOpen:"Open",tabsAriaLabel:"Mesh settings sections",tabAdvanced:"Advanced",quotaBusyFallback:"Quota fallback when busy",quotaBusyFallbackHint:"When the best provider by quota has no free slot, try the next provider with quota on the same node instead of waiting. Never falls back to a provider that is low on quota, and never moves the task to another node.",distribution:"Distribution",distributionSmart:"Smart",distributionSmartDescription:"Match each task to the node whose capability slot fits it best (difficulty + capability tags), then spread by priority and load. Without slots it still spreads work evenly. Recommended when any node has slots.",distributionInOrder:"In order",distributionInOrderDescription:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading.",recommended:"Recommended",saving:"Saving…",visibilityTitle:"Dashboard visibility",visibilityLabel:"Coordinator-spawned worker sessions",visibilityHint:"Hidden = keep the inbox quiet and mute their notifications; you interact through the coordinator session. Visible = show every spawned worker as its own conversation.",visibilityHidden:"Hidden",visibilityVisible:"Visible",coordinatorPromptTitle:"Coordinator prompt",thisMeshHint:"Applies only to coordinator sessions for {{name}}. Leave empty to keep the daemon default.",overrideLabel:"Override (replaces default)",overrideHint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",overridePlaceholder:"(empty — daemon default applies)",appendLabel:"Append (added after the base)",appendHint:"Always added after whichever base prompt wins.",appendPlaceholder:"(empty — nothing appended)",availablePlaceholders:"Available placeholders",placeholdersIntro:"These tokens are replaced when rendering an override or append prompt:",saveCoordinatorPrompt:"Save coordinator prompt",clear:"Clear",clearTitle:"Clear both fields. Click Save to commit.",safetyTitle:"Safety & Git",safetyDescription:"Approval gates and git safety behavior for coordinator-driven tasks. Uncommitted changes follow a fixed rule: a dirty base node never takes write tasks; a dirty worktree takes only follow-ups on its own branch; Refinery refuses to merge a branch worktree with uncommitted changes.",policyDefaultBadge:"Default",policyResetToDefault:"Reset to default",pushApproval:"Push approval",requireApprovalBeforePush:"Require approval before push",doNotRequireApproval:"Do not require approval",destructiveGitApproval:"Destructive git approval",requireApproval:"Require approval",autoPublishSubmodule:"Auto-publish submodule commits (advanced)",requireExplicitApproval:"Require explicit approval",allowRefineryPublish:"Allow Refinery non-force publish",autoFastForward:"Auto fast-forward idle nodes",ffEnabled:"Enabled (catch up online, clean, behind nodes)",ffDisabled:"Disabled",includeRemoteNodes:"Include remote nodes",includeRemoteNodesHint:"Off = only the coordinator's local workspace is auto fast-forwarded.",remoteNo:"No (local workspace only)",remoteYes:"Yes (delegate to remote owning daemons)",detectionMode:"Detection mode",detectionModeHint:"Idle = on a node's idle edge. Continuous = also scan periodically (base nodes only).",idleEdgeOnly:"Idle edge only",continuousScan:"Continuous (periodic scan)",sessionCleanupLabel:"When removing a node, its sessions…",sessionCleanupHint:"Separate transcript cleanup from runtime/process cleanup.",sessionCleanupByNodeType:"By node type (worktree: stop and delete, base: keep)",sessionCleanupByNodeTypeHint:"Not set: removing a worktree node stops and deletes its sessions; removing a base node keeps them.",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"}},hj={showMoreChars:"Show more ({{count}} characters)",collapse:"Collapse",you:"You",toolMessageAria:"Tool message",activityMessageAria:"Activity message",activityFallback:"Activity",copyMessage:"Copy message",copyCode:"Copy code",showMore:"Show more",showLess:"Show less",thought:"Thought",toolExpand:"Show full output",toolCollapse:"Show less",toolExpandLoading:"Loading…",toolExpandUnavailable:"Full output could not be fetched for this step.",toolExpandStale:"Full output has moved — the transcript changed since this was read. Reload the conversation to fetch it.",waitingToSend:"Waiting to send — the agent is still working.",waitingToSendAria:"Waiting to send",notDelivered:"Not delivered — the agent never received this.",notDeliveredAria:"Not delivered",sendNow:"Send now",sending:"Sending…",sendNowAria:"Send now to the agent's queue, without interrupting its current turn",sendNowTitle:"Send this message to the agent now. It goes into the agent's own queue and is answered next — the turn in progress keeps running.",cancelQueued:"Cancel",cancelQueuedAria:"Cancel this queued message",cancelQueuedTitle:"Remove this message from the queue. It will not be sent to the agent.",agent:"Agent",tool:"Tool",ranCommand:"Ran command",activityTerminal:"Terminal",activityRuntime:"Runtime",system:"System",injected:"Injected input",relayLabel:"Relay · {{project}} · {{outcome}}",relayOutcome:{completed:"completed",failed:"failed",cancelled:"cancelled"},relayIdle:"Nothing left running",reviewLabel:"Memory review",daemonNoticeLabel:"Notice"},pj={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"},fj={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"},bj={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"},gj={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"},xj={muteThis:"Mute this chat",unmuteThis:"Unmute this chat"},yj={switchToTerminal:"Switch to Terminal view",switchToChat:"Switch to Chat view"},vj={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."},wj={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"}}},Sj={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 →"}},kj={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"},jj={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}}"},Nj={zoomOut:"Zoom Out",zoomIn:"Zoom In",resetZoom:"Reset Zoom",toggleFullscreen:"Toggle Fullscreen"},Cj={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}}"}},_j={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"},Aj={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"},Tj={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."}},Ij={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}}"},Mj={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"},Rj={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."}},Pj={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"},Ej={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."}},Lj={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."},Dj={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"}},Oj={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"},$j={pageTitle:"Approvals",pageSubtitle:"Sessions waiting on your decision.",pending:"Pending",loading:"Loading approvals…",emptyHint:"Approvals from any connected machine will appear here automatically."},Fj={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"},Hj={dashboard:"Dashboard",machines:"Machines",notifications:"Notifications",mesh:"Mesh",marketplace:"Marketplace",api:"API",webhooks:"Webhooks",account:"Account",settings:"Settings",docs:"Docs",about:"About",chats:"Chats"},Bj={controls:Xk,sessionStatus:Zk,language:ej,common:tj,connection:nj,toast:sj,notification:rj,event:oj,dashboard:aj,cliStop:ij,approval:cj,chatControls:lj,newSession:dj,mobileInbox:uj,mesh:mj,chat:hj,chatPane:pj,chatInput:fj,paneGroup:bj,terminal:gj,conversation:xj,cliView:yj,launch:vj,standalone:wj,cloud:Sj,app:kj,chatList:jj,screenshot:Nj,remote:Cj,sessionNav:_j,sessionInfo:Aj,machine:Tj,sessionHost:Ij,sessionHostSurface:Mj,settings:Rj,historyModal:Pj,landing:Ej,interactivePrompt:Lj,git:Dj,notifications:Oj,approvals:$j,setupWizard:Fj,nav:Hj},Nl="lang",io="common",Wj={ko:()=>mr(()=>import("./common-Diyetrxr.js"),[]),ja:()=>mr(()=>import("./common-wAqqVnE7.js"),[]),"zh-CN":()=>mr(()=>import("./common-CtbYNW-n.js"),[]),es:()=>mr(()=>import("./common-PfaWB_e3.js"),[])};async function Uj(e){return!Es(e)||e===Ds?null:(await Wj[e]()).default}const Kj={type:"backend",init(){},read(e,t,s){if(t!==io){s(null,{});return}Uj(e).then(r=>s(null,r??{}),r=>s(r instanceof Error?r:new Error(String(r)),!1))}};function qj(e){return{resources:{[Ds]:{[io]:Bj}},partialBundledLanguages:!0,lng:e,fallbackLng:Ds,supportedLngs:Af,ns:[io],defaultNS:io,interpolation:{escapeValue:!1},returnEmptyString:!1,react:{transKeepBasicHtmlNodesFor:["br","strong","i","p","em"]}}}function zj(){try{const e=localStorage.getItem(Nl);if(Es(e))return e}catch{}return null}function Tf(){const e=zj();return e||(typeof navigator<"u"?Jk(navigator.language):Ds)}function Cl(e){typeof document>"u"||document.documentElement.setAttribute("lang",e)}let vo=null,If=!1;function Mf(){if(vo)return Qe;const e=Tf();return vo=Qe.use(Kj).use(cy).init(qj(e)).then(()=>{},()=>{}).finally(()=>{If=!0}),Cl(e),Qe}function Vj(){return If?!0:!!vo&&Qe.isInitialized&&Qe.hasLoadedNamespace(io)}function Gj(){return vo||Mf(),vo}function Kt(e){return(typeof e=="string"?e.trim():"")||void 0}function Yn(e,t){const s=Kt(t);return s?`${e}:${s}`:void 0}function hs(e,t,s){const r=Yn(t,s),o=Kt(s);r&&e.push(r),o&&e.push(o)}function hr(e){const t=[],s=new Set;for(const r of e)!r||s.has(r)||(s.add(r),t.push(r));return t}function Rf(e){return Kt(e.providerSessionId)||Kt(e.sessionId)||Kt(e.tabKey)||Kt(e.routeId)}function _i(e){return hr([Kt(e.historySessionId),Kt(e.providerSessionId),Kt(e.sessionId)])}function co(e){const t=[];return hs(t,"provider",e.providerSessionId),hs(t,"session",e.sessionId),hs(t,"tab",e.tabKey),hs(t,"route",e.routeId),hr(t)}function Yj(e){const t=[];return Kt(e.providerSessionId)?(hs(t,"provider",e.providerSessionId),hr(t)):Kt(e.sessionId)?(hs(t,"session",e.sessionId),hr(t)):Kt(e.tabKey)?(hs(t,"tab",e.tabKey),hr(t)):Kt(e.routeId)?(hs(t,"route",e.routeId),hr(t)):[]}function Pf(e){return Yn("provider",e.providerSessionId)||Yn("session",e.sessionId)||Yn("tab",e.tabKey)||Yn("route",e.routeId)||"unknown:"}function Ai(e){return _i(e)[0]}function Ti(e){const t=Kt(e.sessionId),s=Ai(e);if(s&&!(t&&s===t))return s}function Qj(e){const t=Kt(e.providerSessionId),s=Kt(e.sessionId),r=Kt(e.tabKey),o=Kt(e.routeId),a=[Yn("provider",t),Yn("session",s),Yn("tab",r),Yn("route",o)].filter(d=>typeof d=="string"),i=co({providerSessionId:t,sessionId:s,tabKey:r,routeId:o}),l=Pf({providerSessionId:t,sessionId:s,tabKey:r,routeId:o});return{providerSessionId:t,sessionId:s,tabKey:r,routeId:o,canonicalKey:l,targetKey:l,targetValue:Rf({providerSessionId:t,sessionId:s,tabKey:r,routeId:o}),historySessionId:Ai({providerSessionId:t,sessionId:s}),runtimeSessionId:s,allKeys:a,lookupKeys:i}}function no(e,t){const s=Qj(e);return Yj(t).some(r=>s.lookupKeys.includes(r))}function Ef(e){const t=String(e.daemonId||"").trim(),s=String(e.id||"").trim();return t&&s.startsWith(`${t}:`)?s.slice(t.length+1):s}function _l(e){if(String(e.ownerDaemonId||"").trim())return!0;const t=e.settings;return t?!!t.meshNodeFor||!!t.meshNodeId||t.launchedByCoordinator===!0||t._remoteOwnedSession===!0:!1}function Jj(e,t){const s=String(e.daemonId||"").trim(),r=String(e.id||"").trim(),o=Ef(e);if(o&&t.has(o))return`mesh:${o}`;const a=String(e.ownerDaemonId||"").trim()||s;return a?o?`${a}:${o}`:a:r}function pc(e,t){return t||e||"unknown"}function Xj(e,t){return e.ownerDaemonId&&(t==null?void 0:t[e.ownerDaemonId])||e.ownerMachineName||void 0||e.daemonId&&(t==null?void 0:t[e.daemonId])||void 0}const Zj={vscode:"VS Code",pearai:"PearAI"};function Ft(e){return e?e.split("-").map(t=>Zj[t.toLowerCase()]||t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function eN(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const s=Math.floor(t/60),r=t%60;if(s<24)return r>0?`${s}h ${r}m`:`${s}h`;const o=Math.floor(s/24),a=s%24;return`${o}d ${a}h`}function fc(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function va(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 tN(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 nN(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function sN(e){return tN(e.trim().replace(/\.local$/i,""))}function Lf(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Ad(e,t={}){var o,a;const s=[e.hostname,(o=e.machine)==null?void 0:o.hostname,(a=e.system)==null?void 0:a.hostname].find(i=>typeof i=="string"&&i.trim().length>0&&!nN(i));if(s&&s!=="Unknown")return sN(s);const r=t.fallbackId||e.id;return r?`Machine-${r.substring(0,8)}`:t.fallbackLabel||"Machine"}function pn(e,t={}){return Lf(e)||Ad(e,t)}function Df(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 rN(e,t,s={}){const r=String(t).trim();if(!e||!Array.isArray(e.items)||!r)return"";const o=e.items.find(a=>String((a==null?void 0:a.id)||"").trim()===r);return o?String(s.preferShortValue?o.shortValue||o.value||"":o.value||o.shortValue||"").trim():""}function wo(e,t){return Df(e).join(" · ")}function So(e){return e.transport==="pty"}const Of={darwin:"macOS",linux:"Linux",win32:"Windows"};function $f(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:Ft(e)}function sm(e,t,s){const r=(e||"").trim().toLowerCase();if(!r)return!0;const o=(t||"").trim().toLowerCase(),a=(s||"").trim().toLowerCase(),i=Ft(s||"").trim().toLowerCase();return r===o||r===a||r===i}function oN(e,t=[],s=[]){var d,u,m,h;const r=Zt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(r==="waiting_approval")return"waiting_approval";if(r==="waiting_choice")return"waiting_choice";if(r==="generating")return"generating";const o=t.find(p=>Zu(p.status,{activeModal:p.activeModal})||wl(p.status));if(o)return Zt(o.status,{activeModal:o.activeModal});const a=s.find(p=>Zu(p.status,{activeModal:p.activeModal})||wl(p.status));if(a)return Zt(a.status,{activeModal:a.activeModal});if(r&&r!=="idle")return r;const i=Zt((d=t[0])==null?void 0:d.status,{activeModal:(u=t[0])==null?void 0:u.activeModal});if(i!=="idle")return i;const l=Zt((m=s[0])==null?void 0:m.status,{activeModal:(h=s[0])==null?void 0:h.activeModal});return l!=="idle"?l:"idle"}function aN(e){return Zt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function iN(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,s=["generating","finalizing","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const r of e){const o=(r.name||r.id||"").toLowerCase().replace(/\s+/g,"-"),a=t.get(o),i=Zt(r.status);if(!a){t.set(o,{...r,status:i});continue}const l=s.indexOf(a.status||"idle"),d=s.indexOf(i||"idle");d>=0&&(l<0||d<l)&&t.set(o,{...r,status:i})}return Array.from(t.values())}function cN(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 lN(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&&cN(t.receivedAt)||0}function dN(e){return(e.recentLaunches||[]).reduce((s,r)=>Math.max(s,r.lastLaunchedAt||0),0)}function Al(e){return Math.max(dN(e),lN(e.activeChat))}function uN(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 Ua(e,t){return uN(Al(e),Al(t),pn(e,{fallbackId:e.id}),pn(t,{fallbackId:t.id}),e.id,t.id)}const Ff="adhdev_notification_prefs",rm={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function mN(){try{const e=localStorage.getItem(Ff);if(e){const t=JSON.parse(e);return{...rm,...t}}}catch{}return{...rm}}function hN(e){try{localStorage.setItem(Ff,JSON.stringify(e))}catch{}}let Gn=mN(),wa=[];function pN(){wa.forEach(e=>e())}function fN(e){Gn={...Gn,...e},hN(Gn),pN()}function bN(){const[,e]=c.useState(0);c.useEffect(()=>{const s=()=>e(r=>r+1);return wa.push(s),()=>{wa=wa.filter(r=>r!==s)}},[]);const t=c.useCallback(s=>{fN(s)},[]);return[{...Gn},t]}function lo(e){if(!Gn.globalEnabled)return!1;switch(e){case"disconnect":return Gn.disconnectAlert;case"completion":return Gn.completionAlert;case"approval":return Gn.approvalAlert;case"browser":return Gn.browserNotifications;default:return!0}}const gN={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Hf(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Bf(){return"Notification"in window&&Notification.permission==="granted"}function xN(e,t,s){return e?!(s==="waiting_choice"&&t!=="waiting_choice"):!1}let Cs=null;function yN(e){return e!==!1}async function vN(){if(Cs!==null)return Cs;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Cs=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Cs=!!await e.pushManager.getSubscription(),Cs):(Cs=!1,!1)}catch{return Cs=!1,!1}}function Tl(e,t,s){if(Bf())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 wN(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?Qe.t("event.browser.questionWithMessage",{message:a}):Qe.t("event.browser.question")}:e.onApproval&&r==="waiting_approval"&&s!=="waiting_approval"?{kind:"approval",title:t,body:a?Qe.t("event.browser.approvalWithMessage",{message:a}):Qe.t("event.browser.approval")}:e.onComplete&&wl(s)&&r==="idle"?{kind:"complete",title:t,body:Qe.t("event.browser.finished")}:e.onError&&r==="error"&&s!=="error"?{kind:"error",title:t,body:Qe.t("event.browser.error")}:null}function SN(e,t={}){const s={...gN,...t},r=c.useRef(new Map),o=c.useRef(0),[a,i]=c.useState(null);c.useEffect(()=>{let d=!1;return vN().then(u=>{d||i(u)}),()=>{d=!0}},[]);const l=c.useCallback((d,u,m)=>{const h=Date.now();h-o.current<s.throttleMs||(o.current=h,Tl(d,u,m))},[s.throttleMs]);c.useEffect(()=>{var d;if(!(!s.enabled||!Bf())&&lo("browser")&&!yN(a)){if(document.hasFocus()){for(const u of e)r.current.set(u.id,Zt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const m=r.current.get(u.id),h=Zt(u.status,{activeModal:u.activeModal}),p=u.name||u.id,b=h==="waiting_choice"&&m!=="waiting_choice";if(xN(u.muted,m,h)){r.current.set(u.id,h);continue}const f=wN({name:p,prev:m,curr:h,modalMessage:(d=u.activeModal)==null?void 0:d.message,questionEntered:b,onApproval:s.onApproval&&lo("approval"),onComplete:s.onComplete&&lo("completion"),onError:s.onError});f&&l(f.title,f.body,`${f.kind}-${u.id}`),r.current.set(u.id,h)}}},[e,s.enabled,s.onApproval,s.onComplete,s.onError,a,l])}const kN=/^(run|approve|accept|yes|allow|always)/,jN=/^(run|approve|accept|yes|allow|always|proceed|save)/,NN=/^(reject|deny|delete|remove|abort|cancel|no)/;function Td(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").replace(/\s*\(\s*\)/g,"").trim()}function CN(e){const t=Td(e).toLowerCase();return kN.test(t)?"primary":NN.test(t)?"danger":"default"}function _N(e){return jN.test(Td(e).toLowerCase())?"approve":"reject"}function AN(e){return e.map((t,s)=>({label:Td(t),variant:CN(t),action:_N(t),button:t,buttonIndex:s}))}function TN(e,t,s){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:s}function IN(e,t,s,r){return[{label:"Approve",variant:"primary",onClick:()=>{s(e,t,"approve").catch(o=>r==null?void 0:r("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{s(e,t,"reject").catch(o=>r==null?void 0:r("reject",o))}}]}function Id(e){if(!(e==null||e==="")){if(typeof e=="string")return e.trim()||void 0;if(e instanceof Error)return e.message||String(e);if(typeof e=="object"){const t=e,s=t.error??t.message??t.reason;if(typeof s=="string"&&s.trim())return s.trim();if(s&&typeof s=="object")return Id(s);try{return JSON.stringify(e)}catch{return}}return String(e)}}class MN{constructor(){ze(this,"dedupMap",new Map);ze(this,"DEDUP_WINDOW_MS",5e3);ze(this,"DEDUP_MAX_SIZE",50);ze(this,"DEDUP_CLEANUP_AGE_MS",1e4);ze(this,"toastCallbacks",[]);ze(this,"statusEventCallbacks",[]);ze(this,"resolveActionFn",null);ze(this,"viewRequestRespondFn",null);ze(this,"hydrateInteractivePromptFn",null);ze(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(s=>s!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(s=>s!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}setHydrateInteractivePrompt(t){this.hydrateInteractivePromptFn=t}hydrateInteractivePromptFromEvent(t){const s=this.hydrateInteractivePromptFn;if(!s)return;const r=t.targetSessionId;if(!r)return;const o=vl(t.interactivePrompt);o&&s(r,o)}emitToast(t){for(const s of this.toastCallbacks)s(t)}showToast(t,s="info",r){const o=(r==null?void 0:r.id)||Date.now();this.emitToast({id:o,message:t,type:s,timestamp:o,duration:5e3,...r})}showErrorToast(t,s,r){const o=Id(s);this.showToast(t,"warning",{duration:8e3,...o&&o!==t?{details:o}:{},...r})}isDuplicate(t){const s=Date.now(),r=this.dedupMap.get(t)||0;if(s-r<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,s),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[o,a]of this.dedupMap)s-a>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(o);return!1}resolveOwningDaemon(t){if(t.daemonId){const o=this.ides.find(a=>a.id===t.daemonId&&a.type==="adhdev-daemon");if(o)return o}const s=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(s){const o=s.daemonId;if(o){const a=this.ides.find(i=>i.id===o&&i.type==="adhdev-daemon");if(a)return a}}const r=this.ides.filter(o=>o.type==="adhdev-daemon");return r.length===1?r[0]:null}findOwningSession(t){for(const s of this.ides)if(s.id===t||s.sessionId===t||(Array.isArray(s.childSessions)?s.childSessions:[]).some(o=>(o==null?void 0:o.id)===t))return s;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const s=this.findOwningSession(t.targetSessionId);return(s==null?void 0:s.id)||(s==null?void 0:s.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}isConversationEventMuted(t){const s=t.targetSessionId;if(!s)return!1;for(const r of this.ides){if(r.id===s||r.sessionId===s)return!!r.muted;const a=(Array.isArray(r.childSessions)?r.childSessions:[]).find(i=>(i==null?void 0:i.id)===s);if(a)return!!a.muted}return!1}handleRawEvent(t,s){var x;const r=this.resolveConversationKey(t),o=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),a=r||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(o),l=`${a}:${t.event}:${i}`;if(t.event==="agent:waiting_choice"&&this.hydrateInteractivePromptFromEvent(t),this.isDuplicate(l))return;for(const g of this.statusEventCallbacks)g(t);const d=this.isConversationEventMuted(t),u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let h=m&&m!=="adhdev-daemon"?$f(m,{agentName:u==null?void 0:u.cliName}):Ft(m);const p=this.resolveOwningDaemon(t);if(p){const g=pn(p,{fallbackId:p.id});g&&(h=!m||m==="adhdev-daemon"?g:`${g}/${h}`)}let b="",f="info";if(t.event==="agent:generating_completed"){if(b=t.duration?`✅ ${Qe.t("event.taskCompletedWithDuration",{label:h,duration:Yw(Number(t.duration)*1e3)})}`:`✅ ${Qe.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=`⚡ ${Qe.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 v=this.resolveActionFn,S=AN(t.modalButtons).map(w=>({label:w.label,variant:w.variant,onClick:()=>{v(g,"resolve_action",{action:w.action,button:w.button,buttonIndex:w.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),A=TN(h,t.modalMessage,b),k=Date.now();this.emitToast({id:k,message:A,type:f,timestamp:k,targetKey:r||g,actions:S,duration:15e3}),b=""}}else if(t.event==="agent:waiting_choice"){b=`❓ ${Qe.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 v=Date.now();this.emitToast({id:v,message:b,type:f,timestamp:v,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?`⚠️ ${Qe.t("event.noProgressWithDuration",{label:h,minutes:g})}`:`⚠️ ${Qe.t("event.noProgress",{label:h})}`,f="warning",!d&&lo("browser")&&!document.hasFocus()&&Tl(`⚠️ ${Qe.t("event.noProgressTitle",{label:h})}`,Qe.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||Qe.t("event.someoneRequester"),v=t.requestId,S=t.orgId;if(b=`${Qe.t("event.viewRequest",{requester:g})}`,f="warning",v&&S&&this.viewRequestRespondFn){const A=Date.now(),k=IN(S,v,this.viewRequestRespondFn,(w,y)=>console.error(`[EventManager] ${w} view request failed:`,y));this.emitToast({id:A,message:b,type:f,timestamp:A,actions:k,duration:3e4}),b=""}lo("browser")&&!document.hasFocus()&&Tl(`${Qe.t("event.viewRequestTitle")}`,Qe.t("event.viewRequest",{requester:g}),`view-request-${v}`)}else if(t.event==="team:view_request_approved")b=`✅ ${Qe.t("event.viewRequestApproved")}`,f="success";else if(t.event==="team:view_request_rejected"){const g=t.targetName||Qe.t("event.someoneTarget");b=`❌ ${Qe.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 nt=new MN,om=new Map;function Wf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function pr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ii(e){return bf(e)??null}function RN(e){const t=Ii(e);return!t||!Wf(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Jo(e){const t=Ii(e);return!t||!Wf(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Wr(e){const t=Ii(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Xo(e){const t=Ii(e);return!!t&&t.success===!1}function PN(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";nt.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";nt.showToast(r.notification.body,o)}}}function EN(e,t){return e&&pr(e.currentValue)?e.currentValue:t}function LN(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 DN(e,t){return pr(t)?pr(e)?typeof e=="string"&&e.trim()==="":!0:!1}function ON(e,t){var a,i;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(pr(l))return l}const r=(a=t.controlValues)==null?void 0:a[e];if(pr(r))return r;const o=(i=t.defaultValues)==null?void 0:i[e];return pr(o)?o:void 0}function Sa(e,t){return e.options||t[e.id]||[]}const $N={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 FN(e,t,s){var r;return((r=$N[t])==null?void 0:r.has(s.id))===!0}function HN(e){if(e){if(bi(e))return["busy","generating","starting"];switch(e){case"idle":return["idle"];case"waiting_approval":case"approval":return["approval"];case"waiting_choice":return["picker"];default:return}}}function BN(e,t){const s=e.visibleWhenState;if(!s||s.length===0)return!0;const r=HN(t);return r?r.some(o=>s.includes(o)):!0}function Md(e,t){return(e||[]).filter(s=>s.placement==="bar"&&s.hidden!==!0&&!FN(t.hostIdeType,t.providerType,s)&&BN(s,t.currentStatus)).sort((s,r)=>(s.order??50)-(r.order??50))}function bc(e,t){return{value:t}}function WN(e,t,s){var o;return s?((o=Sa(e,t).find(a=>a.value===s))==null?void 0:o.label)||s:""}const UN={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function KN({routeId:e,sessionId:t,hostIdeType:s,providerType:r,displayLabel:o,controls:a,controlValues:i,currentStatus:l,coordinatorHint:d}){const{t:u}=he("common"),{sendCommand:m}=wt(),{confirm:h,confirmDialog:p}=Tr(),b=`${e}:${t||r}`,f=UN[r]||"#94a3b8",[x,g]=c.useState({}),v=c.useRef({}),S=c.useRef(i);v.current=x,S.current=i;const A=c.useRef(0),k={};for(const R of a||[])R.defaultValue!==void 0&&(k[R.id]=R.defaultValue);const w={...k,...i||{},...Date.now()<A.current?x:{}};c.useEffect(()=>{i&&Date.now()>A.current&&g(R=>LN(R,i))},[i]);const[y,N]=c.useState(om.get(b)||{}),[j,C]=c.useState(null),[E,P]=c.useState(null),T=c.useCallback(async(R,O={})=>{const B={...O,...t&&{targetSessionId:t},...d??{}};return await m(e,R,B)},[e,t,m,d]),M=c.useCallback(async(R,O={})=>{const B=t?{targetSessionId:t}:{agentType:r,...s?{ideType:s}:{}};return await T("invoke_provider_script",{...B,scriptName:R,...O})},[T,r,s,t]),_=c.useCallback((R,O,B)=>{const H=EN(B,O);g(U=>({...U,[R.id]:H})),PN(B==null?void 0:B.effects)},[]),I=c.useCallback((R,O)=>{g(B=>{const H={...B};return O===void 0?delete H[R.id]:H[R.id]=O,H}),A.current=0},[]);if(!a||a.length===0)return null;const D=Md(a,{hostIdeType:s,providerType:r,currentStatus:l});if(D.length===0)return null;const L=async R=>{if(j===R.id){C(null);return}if(Sa(R,y).length>0){C(R.id);return}if(R.dynamic&&R.listScript){P(R.id);try{const B=await M(R.listScript,{}),H=RN(B);if(!H){const oe=Wr(B);oe&&nt.showErrorToast(u("controls.loadOptionsFailed",{label:R.label}),oe);return}const U=H.options;N(oe=>{const ge={...oe,[R.id]:U};return om.set(b,ge),ge});const K=ON(R.id,{localOverrideUntil:A.current,localValues:v.current,controlValues:S.current,defaultValues:k});if(DN(K,H.currentValue)){const oe=H.currentValue;g(ge=>({...ge,[R.id]:oe}))}C(R.id)}catch(B){nt.showErrorToast(u("controls.loadOptionsFailed",{label:R.label}),B)}finally{P(null)}}},$=async(R,O)=>{C(null);const B=(i==null?void 0:i[R.id])??k[R.id];g(H=>({...H,[R.id]:O})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const H=await M(R.setScript,bc(R,O)),U=Jo(H);if(U&&!U.ok||Xo(H))throw new Error((U==null?void 0:U.error)||Wr(H)||`Could not update ${R.label}`);_(R,O,U)}catch(H){I(R,B),nt.showErrorToast(u("controls.updateFailed",{label:R.label}),H)}},q=async R=>{const O=Sa(R,y).map(ge=>ge.value);if(O.length===0)return;const B=String(w[R.id]||""),U=(O.indexOf(B)+1)%O.length,K=O[U];if(typeof K!="string")return;const oe=(i==null?void 0:i[R.id])??k[R.id];g(ge=>({...ge,[R.id]:K})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const ge=await M(R.setScript,bc(R,K)),J=Jo(ge);if(J&&!J.ok||Xo(ge))throw new Error((J==null?void 0:J.error)||Wr(ge)||`Could not update ${R.label}`);_(R,K,J)}catch(ge){I(R,oe),nt.showErrorToast(u("controls.updateFailed",{label:R.label}),ge)}},G=async R=>{const B=!w[R.id],H=(i==null?void 0:i[R.id])??k[R.id];g(U=>({...U,[R.id]:B})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const U=await M(R.setScript,bc(R,B)),K=Jo(U);if(K&&!K.ok||Xo(U))throw new Error((K==null?void 0:K.error)||Wr(U)||`Could not update ${R.label}`);_(R,B,K)}catch(U){I(R,H),nt.showErrorToast(u("controls.updateFailed",{label:R.label}),U)}},W=async R=>{var B,H,U;if(!R.invokeScript||R.confirmMessage&&!await h({title:((B=R.confirmTitle)==null?void 0:B.trim())||R.confirmMessage,description:(H=R.confirmTitle)!=null&&H.trim()?R.confirmMessage:void 0,confirmLabel:((U=R.confirmLabel)==null?void 0:U.trim())||u("common.confirm")}))return;const O=(i==null?void 0:i[R.id])??k[R.id];try{const K=await M(R.invokeScript),oe=Jo(K);if(oe&&!oe.ok||Xo(K))throw new Error((oe==null?void 0:oe.error)||Wr(K)||`Could not run ${R.label}`);oe&&_(R,O??!0,oe)}catch(K){I(R,O),nt.showErrorToast(u("controls.runFailed",{label:R.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}),D.map(R=>{const O=String(w[R.id]||""),B=WN(R,y,O),H=j===R.id,U=E===R.id,K=Sa(R,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(R.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:H?`${f}55`:"var(--border-default)",background:H?`${f}10`:"var(--surface-tertiary)",color:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void L(R),title:R.label,children:[R.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:R.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:U?u("chatControls.loading"):B||R.label}),n.jsx("span",{className:"text-4xs opacity-55",children:"▼"})]}),H&&K.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-[var(--z-dropdown)]",onClick:()=>C(null)}),n.jsxs("div",{className:"absolute bottom-full left-0 z-[var(--z-dropdown)] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[n.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-3xs font-semibold uppercase tracking-[0.08em] text-text-muted",children:R.label}),K.map(ge=>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:ge.value===O?`${f}14`:"transparent",color:ge.value===O?"var(--text-primary)":"var(--text-secondary)",borderLeft:ge.value===O?`2px solid ${f}`:"2px solid transparent"},title:ge.description||ge.label,onMouseEnter:J=>{J.currentTarget.style.background=`${f}10`},onMouseLeave:J=>{J.currentTarget.style.background=ge.value===O?`${f}14`:"transparent"},onClick:()=>void $(R,ge.value),children:[n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ge.label}),ge.value===O&&n.jsx("span",{className:"shrink-0 text-2xs font-semibold",style:{color:f},children:"✓"})]},ge.value))]})]})]},R.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:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void q(R),title:`Click to cycle: ${K.map(ge=>ge.label).join(" → ")}`,children:[R.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:R.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:B||R.label}),n.jsx("span",{className:"text-3xs opacity-55",children:"⟳"})]},R.id);case"toggle":return n.jsxs("button",{type:"button",className:`${oe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:O?`${f}44`:"var(--border-default)",background:O?`${f}14`:"var(--surface-tertiary)",color:O?f:"var(--text-muted)"},onClick:()=>void G(R),"aria-pressed":!!O,children:[R.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:R.icon}),R.label]},R.id);case"action":return n.jsxs("button",{type:"button",className:`${oe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void W(R),children:[R.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:R.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:R.resultDisplay==="inline"&&O?`${R.label}: ${O}`:R.label})]},R.id);case"display":return n.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-xs font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:O?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:R.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:O?`${R.label}: ${O}`:R.label})]},R.id);default:return null}})]}),p]})}function qN(e){if(!e||typeof e!="object")return{};const t=e,s=Dv(t.launch);return{...s?{launch:s}:{},...typeof t.model=="string"&&t.model.trim()?{model:t.model.trim()}:{},...ud(t.modelSource)?{modelSource:t.modelSource}:{}}}const am={user:"chosen",remembered:"remembered",mesh_slot:"mesh slot",task_override:"task",provider_default:"default",unspecified:""};function zN(e,t){return String(t.defaultValue??"").replace(/\{\{(\w+)\}\}/g,(s,r)=>String(t[r]??""))}function Uf(e,t=zN){const s=e.launch?Lv(e.launch.model):void 0,r=(s==null?void 0:s.value)??e.model;if(!r)return null;const o=(s==null?void 0:s.source)??e.modelSource??"unspecified";if(s!=null&&s.changedFrom)return{text:t("chatControls.launchModelChanged",{from:s.changedFrom,to:r,defaultValue:"{{from}} → {{to}} (changed)"}),source:o};const a=am[o]?t(`chatControls.launchModelSource.${o}`,{defaultValue:am[o]}):"";return{text:a?`${r} · ${a}`:r,source:o}}function VN({surface:e}){const{t}=he("common"),s=Uf(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 GN({isActive:e=!0,isCliTerminal:t=!1,routeId:s,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:l,controlValues:d,currentStatus:u,coordinatorHint:m,launchSurface:h}){const{isVisible:p}=_d(),b=Md(l,{hostIdeType:o,providerType:a,currentStatus:u}),f=b.length>0&&p,x=!!h&&!!Uf(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(VN,{surface:h})}),f&&n.jsx(KN,{routeId:s,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:b,controlValues:d,currentStatus:u,coordinatorHint:m})]})}const Ur=5,Kf=10*1024*1024;function YN({hasDraft:e,isBusy:t=!1}){return!e||t}function QN(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 JN(e){if(e.size>Kf)return null;const t=await QN(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 XN(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}function ZN(e){return/[\u1100-\u11FF\u3130-\u318F\uAC00-\uD7A3]/.test(e)}const qf=c.memo(function({contextKey:t,panelLabel:s,isSending:r,isBusy:o=!1,statusMessage:a=null,inlineStatusMessage:i=null,onSend:l,isActive:d=!0,showControlsToggle:u=!1,animateVisibility:m=!0,onControlsToggle:h,messageInput:p}){const{t:b}=he("common"),f=c.useRef(null),x=c.useRef(null),[g,v]=c.useState(""),[S,A]=c.useState([]),[k,w]=c.useState(null),[y,N]=c.useState(!1),j=c.useRef(!1),C=c.useRef(0),E=50,P=c.useRef(""),T=c.useRef(!1),M=c.useRef(null),_=30,{isVisible:I,toggleVisibility:D}=_d(),L=XN(p),$=!!g.trim()||S.length>0;c.useEffect(()=>{v(""),A([]),w(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 q=c.useCallback(async K=>{w(null);const oe=Array.from(K).filter(le=>le.type.startsWith("image/"));if(oe.length===0)return;const ge=Ur-S.length;if(ge<=0){w(`Max ${Ur} images`);return}const J=oe.slice(0,ge);if(J.filter(le=>le.size>Kf).length>0){w("Image too large (max 10 MB)");return}const ne=(await Promise.all(J.map(JN))).filter(le=>le!==null);A(le=>[...le,...ne])},[S.length]),G=c.useCallback(K=>{A(oe=>oe.filter((ge,J)=>J!==K))},[]),W=c.useCallback(async()=>{const K=g.trim();if(!K&&S.length===0||o||j.current)return;j.current=!0;const oe=S.length>0?[...S]:void 0;try{await l(K,oe)!==!1&&(v(""),A([]),w(null))}finally{j.current=!1}},[g,S,o,l]),R=c.useRef(W);R.current=W;const O=c.useCallback(()=>{T.current&&(T.current=!1,M.current&&(clearTimeout(M.current),M.current=null),setTimeout(()=>{R.current()},0))},[]);c.useEffect(()=>()=>{M.current&&clearTimeout(M.current)},[]);const B=c.useCallback(K=>{L&&(K.preventDefault(),N(!0))},[L]),H=c.useCallback(()=>N(!1),[]),U=c.useCallback(K=>{L&&(K.preventDefault(),N(!1),K.dataTransfer.files.length>0&&q(K.dataTransfer.files))},[L,q]);return n.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",y?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:d?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:d?200:0,opacity:d?1:0,transform:d?"translateY(0)":"translateY(10px)",padding:d?"10px 12px":"0 12px",pointerEvents:d?"auto":"none"},"aria-hidden":!d,onDragOver:B,onDragLeave:H,onDrop:U,children:[S.length>0&&n.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:S.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:()=>G(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:[u&&n.jsx("button",{type:"button",onClick:()=>{D(),h==null||h()},"aria-label":b(I?"chatInput.hideControls":"chatInput.showControls"),"aria-pressed":I,title:b(I?"chatInput.hideControls":"chatInput.showControls"),className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:n.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[n.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),n.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),n.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),L&&n.jsxs(n.Fragment,{children:[n.jsx("input",{ref:x,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:K=>{K.target.files&&q(K.target.files),K.target.value=""}}),n.jsx("button",{type:"button",onClick:()=>{var K;return(K=x.current)==null?void 0:K.click()},disabled:S.length>=Ur,title:S.length>=Ur?`Max ${Ur} images`:b("chatInput.attachImage"),className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":b("chatInput.attachImage"),children:n.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),n.jsx("div",{className:"flex-1 relative",children:n.jsx("textarea",{ref:f,rows:1,placeholder:a||(L&&S.length>0?b("chatInput.addMessageOptional"):b("chatInput.placeholder",{panel:s})),value:g,onChange:K=>v(K.target.value),onPaste:K=>{if(L&&K.clipboardData.files.length>0&&Array.from(K.clipboardData.files).some(ce=>ce.type.startsWith("image/"))){K.preventDefault(),q(K.clipboardData.files);return}const oe=K.clipboardData.getData("text/plain"),ge=nw(oe);if(ge===oe)return;K.preventDefault();const J=f.current,ke=(J==null?void 0:J.selectionStart)??g.length,de=(J==null?void 0:J.selectionEnd)??g.length,ne=g.slice(0,ke)+ge+g.slice(de);v(ne);const le=ke+ge.length;requestAnimationFrame(()=>{J==null||J.setSelectionRange(le,le)})},onCompositionUpdate:K=>{P.current=K.data||""},onCompositionEnd:K=>{C.current=Date.now(),K.data&&(P.current=K.data),O()},onKeyDown:K=>{if(K.key!=="Enter"||K.shiftKey)return;if(K.nativeEvent.isComposing||K.keyCode===229||Date.now()-C.current<E){K.preventDefault(),ZN(P.current)&&!T.current&&(T.current=!0,M.current=setTimeout(O,_));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:YN({hasDraft:$,isBusy:o}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${$&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:$&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":b("chatInput.sendMessage"),children:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:$?"text-white":"text-text-muted",children:n.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(k||L&&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 eC({entries:e,onSendNow:t,onCancelQueued:s,isSendingNow:r}){const{t:o}=he(),a=e.filter(d=>d.queued===!0&&!!d.id);if(a.length===0)return null;const i=a.some(d=>d.stale!==!0),l=o(i?"chat.waitingToSendAria":"chat.notDeliveredAria");return n.jsx("div",{className:"chat-pending-queue-strip","data-testid":"pending-queue-strip","data-pending-queue-count":a.length,role:"region","aria-label":l,children:a.map(d=>n.jsxs("div",{className:"chat-pending-queue-row","data-chat-queued-row":"true","data-chat-queued-stale":d.stale===!0?"true":void 0,children:[n.jsxs("div",{className:"chat-bubble chat-bubble-user chat-pending-queue-bubble",title:d.content,children:[n.jsx("div",{className:"chat-pending-queue-body",children:d.content}),n.jsx("span",{className:d.stale===!0?"chat-pending-queue-clock chat-pending-queue-stale":"chat-pending-queue-clock",role:"img","aria-label":d.stale===!0?o("chat.notDeliveredAria"):o("chat.waitingToSendAria"),title:d.stale===!0?o("chat.notDelivered"):o("chat.waitingToSendAria"),children:d.stale===!0?"⚠":"⏱"})]}),t&&n.jsx("button",{type:"button",onClick:()=>t(d.id),disabled:r,className:"chat-pending-queue-send","aria-label":o("chat.sendNowAria"),title:o("chat.sendNowTitle"),children:"↑"}),s&&n.jsx("button",{type:"button",onClick:()=>s(d.id),disabled:r,className:"chat-pending-queue-cancel","aria-label":o("chat.cancelQueuedAria"),title:o("chat.cancelQueuedTitle"),children:"✕"})]},d.id))})}const tC=c.memo(eC,(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})),nC={accent:{track:"--accent-primary",head:"--accent-primary-light"},success:{track:"--status-online",head:"--status-online"},muted:{track:"--text-muted",head:"--text-muted"}};function nn({size:e=28,thickness:t=2.5,color:s="accent",className:r,label:o}){const a=nC[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 sC=1e4;function rC({machineId:e,blocked:t,retryConnection:s}){const{t:r}=he("common"),[o,a]=c.useState(!1),i=c.useRef(null);if(c.useEffect(()=>{t||a(!1)},[t]),c.useEffect(()=>{if(!o)return;const d=setTimeout(()=>a(!1),sC);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(nn,{size:11,thickness:2,color:"muted"}):n.jsx(xr,{size:12}),n.jsx("span",{children:r(o?"chatPane.reconnectingMachine":"chatPane.reconnectMachine")})]})}let zf=yn;function Mi(){return zf()}class oC{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 Vf=new oC;class aC{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 Ot=new aC;function iC(e){e.dashboardWS&&(Vf=e.dashboardWS),e.connectionManager&&(Ot=e.connectionManager),e.useDaemonsHook&&(zf=e.useDaemonsHook)}function ka(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Gf="adhdev-pending-queued-messages-v1",cC=256*1024,lC=24*60*60*1e3,Yf=10*60*1e3;function Qf(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Gf)||"{}");return{byKey:e.byKey&&typeof e.byKey=="object"?e.byKey:{}}}catch{return{byKey:{}}}}function dC(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Gf,JSON.stringify(e))}catch{}}function uC(e,t){if(!e||typeof e!="object")return;const s=e;if(!Array.isArray(s.parts))return;let r=0;const o=new Set(s.omitted&&typeof s.omitted=="object"&&Array.isArray(s.omitted.partTypes)?s.omitted.partTypes.filter(l=>typeof l=="string"):[]),a=[];for(const l of s.parts){if(!l||typeof l!="object")continue;const d=l,u=typeof d.type=="string"?d.type:"";if(!u)continue;if(u==="text"){a.push({type:"text",text:typeof d.text=="string"?d.text:""});continue}const m=typeof d.data=="string"?d.data:void 0,h=m?m.length:0;if(m&&r+h<=cC){r+=h,a.push({type:u,mimeType:typeof d.mimeType=="string"?d.mimeType:void 0,uri:typeof d.uri=="string"?d.uri:void 0,data:m,alt:typeof d.alt=="string"?d.alt:void 0});continue}if(!m){a.push({type:u,mimeType:typeof d.mimeType=="string"?d.mimeType:void 0,uri:typeof d.uri=="string"?d.uri:void 0,alt:typeof d.alt=="string"?d.alt:void 0});continue}o.add(u),a.push({type:u,mimeType:typeof d.mimeType=="string"?d.mimeType:void 0,alt:typeof d.alt=="string"?d.alt:void 0})}const i=typeof s.textFallback=="string"?s.textFallback:t;return{parts:a,textFallback:i,...o.size>0?{omitted:{omitted:!0,partTypes:[...o]}}:{}}}function Jf(e,t){if(!Array.isArray(e))return[];const s=new Set,r=[];let o=0;for(const a of e){if(!a||typeof a!="object")continue;const i=a,l=typeof i.content=="string"?i.content:"",d=typeof i.sentAt=="number"&&Number.isFinite(i.sentAt)?i.sentAt:0,u=typeof i.id=="string"&&i.id?i.id:"";if(!l.trim()||!d||!u||t-d>lC||s.has(u))continue;s.add(u);const m=i.stale===!0||t-d>Yf,h=uC(i.input,l);r.push({entry:{id:u,content:l,sentAt:d,queued:i.queued===!0,settled:!0,stale:m,...h?{input:h}:{}},index:o}),o+=1}return r.sort((a,i)=>a.entry.sentAt-i.entry.sentAt||a.index-i.index),r.map(a=>a.entry).slice(-20)}let im=0;function mC(e=Date.now()){try{const t=typeof globalThis<"u"?globalThis.crypto:void 0;if(typeof(t==null?void 0:t.randomUUID)=="function")return t.randomUUID()}catch{}return im+=1,`pq-${e}-${im}`}function hC(e,t=Date.now()){const s=String(e||"").trim();return s?Jf(Qf().byKey[s],t):[]}function pC(e,t,s=Date.now()){const r=String(e||"").trim();if(!r)return;const o=Qf(),a=Jf(t,s);a.length>0?o.byKey[r]=a:delete o.byKey[r],dC(o)}function Xf(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}const fC=12e4;function bC(e){if(typeof e=="string")return e.trim();if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}const gC=/^(?:\s*(?:\[Image #\d+\]|\[image: [^\]\n]{1,100}\]))+\s*/;function xC(e,t){const s=bC(e);if(s===t)return!0;const r=s.replace(gC,"").trim();return r!==s&&r.length>0&&r===t}function yC(e,t){if(!t)return!1;const s=e.meta;return typeof(s==null?void 0:s.sourceMessageId)=="string"&&s.sourceMessageId===t}function cm(e){const t=e.meta;return typeof(t==null?void 0:t.sourceMessageId)=="string"&&t.sourceMessageId.length>0}function Zf(e,t){if(!t)return 0;let s=0;for(const r of e)String(r.role||"").toLowerCase()==="user"&&xC(r.content,t)&&(s+=1);return s}function vC(e,t,s=Date.now(),r=Yf){if(!e||e.length===0)return{entries:[],changed:!1,retiredByEcho:0,markedStale:0};const o=new Map,a=[];let i=0,l=0,d=!1;const u=t.some(m=>cm(m))?t.filter(m=>!cm(m)):t;for(const m of e){const h=m.content.trim();if(!h){d=!0;continue}if(t.some(f=>yC(f,m.id))){i+=1,d=!0;continue}o.has(h)||o.set(h,Zf(u,h));const p=o.get(h)||0;if(p>0){o.set(h,p-1),i+=1,d=!0;continue}if(s-m.sentAt>r&&m.stale!==!0){l+=1,d=!0,a.push({...m,stale:!0});continue}a.push(m)}return d?{entries:a,changed:!0,retiredByEcho:i,markedStale:l}:{entries:e,changed:!1,retiredByEcho:0,markedStale:0}}function wC(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 SC(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>fC)continue;o.has(l)||o.set(l,Zf(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(wC(i))}return a.length===0?e:[...e,...a]}function kC(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const s=String(e.kind||"standard").toLowerCase();return s===""||s==="standard"}function gc(e){return kC(e)?String(e.role||"").toLowerCase():""}const jC=4;function NC(e,t){if(e.length===0)return[];for(let a=t.length-1;a>=0;a-=1)if(gc(t[a])==="assistant")return[];const s=t.some(a=>gc(a)==="user"),r=[];let o=!1;for(let a=e.length-1;a>=0&&r.length<jC;a-=1){const i=e[a],l=gc(i);if(l){if(!o&&l==="assistant"){r.unshift(i),o=!0;continue}if(o&&l==="user"){s||r.unshift(i);break}}}return r}function CC(e){let t=!0;for(let s=1;s<e.length;s+=1)if(ka(e[s-1])>ka(e[s])){t=!1;break}return t?e:e.map((s,r)=>({message:s,index:r,ts:ka(s)})).sort((s,r)=>s.ts-r.ts||s.index-r.index).map(s=>s.message)}function _C(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=NC(a,i),d=l.length>0?[...l,...i]:i,u=t.length===0?d:[...t,...d];return CC(u)}const ft=e=>e.transport==="pty",Mr=(e,t)=>ft(e)&&e.mode||"chat",eb=(e,t)=>ft(e)&&Mr(e)==="terminal",AC=180;function bs(e){return e.streamSource!=="agent-stream"}function Xn(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Ri(e){var s;const t=typeof((s=e.settings)==null?void 0:s.meshCoordinatorDaemonId)=="string"?e.settings.meshCoordinatorDaemonId:void 0;return t?{meshCoordinatorDaemonId:t}:{}}function tb(e){return e.machineName||""}function vs(e){return Xn(e)}function $n(e){return e.agentType||""}function Ka(e){return e.hostIdeType||""}function Rd(e){return e.displayPrimary||e.agentName||"Agent"}function nb(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function TC(e,t){const s=Xf(e,t),r=[...s].reverse();return r.find(o=>!(o!=null&&o._localId)&&jd(o).isUserFacing)||r.find(o=>!(o!=null&&o._localId))||s[s.length-1]}function sb(e,t){const s=TC(e,t),r=fr(s==null?void 0:s.content),o=fr(e.lastMessagePreview);return o&&e.lastMessageRole==="assistant"&&(s==null?void 0:s.role)==="user"?o:r||o||""}function IC(e,t=AC){const s=fr(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 MC(e){return IC(sb(e)||e.displaySecondary||"")}function rb(e){return[e.displaySecondary,tb(e)].filter(Boolean)}function vr(e){return e.agentName||Ft($n(e))}function RC(e){var t,s;if(!bs(e)){const r=(s=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:s.trim();if(r)return r}return Ft(Ka(e)||$n(e))}function ob(e){return bs(e)?e.sessionId:e.nativeSessionId}function lm(e){return bs(e)?"native":e.tabKey}function PC(e){return e.sessionId}function ab(e,t){if(t)return bs(e)||!t.childSessions?t:t.childSessions.find(s=>s.id===e.sessionId||s.providerType===e.agentType)||t}function EC(e,t){const s=$n(e),r=bs(e),o=ft(e),a=r?o?vr(e)||(t==null?void 0:t.cliName)||Ft(Ka(e)||s):t!=null&&t.type?Ft(t.type):Ft(Ka(e)||s):vr(e);return{isNativeConversation:r,isCli:ft(e),isCliTerminal:eb(e),providerType:s,displayLabel:a,targetEntry:ab(e,t)}}function gs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:ft(e)?{agentType:$n(e)}:e.streamSource==="agent-stream"?{agentType:$n(e)}:t}function ps(e){return e?vs(e):""}function lr(e,t){e(s=>[...s,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}const LC="Waiting for approval…",DC="Waiting for your answer…";function Pi(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?e.status==="waiting_choice"?"Answer the pending question above.":"Approve or reject the pending request above.":null}function ib(e){return Pi(e)?(e==null?void 0:e.status)==="waiting_choice"?DC:LC:null}function Zo(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 cb(){return"select_session"}function OC(){return"open_panel"}function $C({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function FC(e,t,s=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<s:!1}function dm(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Ls(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}const so="Waiting to send — the agent is still working.",HC="Too late to cancel — this message was already sent to the agent.";function um(e){return!e||typeof e!="object"?!1:e.queued===!0}function BC({feedbackMessage:e,lastSendQueued:t,isGenerating:s}){return!t||e!==so?!1:!s}function Pd(e){return e instanceof Error?e.message:String(e||"")}function mm(e){const t=Pd(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function hm(e,t){const s=Pd(t);return s?s.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${s}`:`⚠️ **${e}** unavailable`}const WC=5e3;function UC(e,t,s=WC){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 KC(e,t){if(!t||t.length===0)return;const s=t.map(r=>({type:"image",mimeType:r.mimeType,data:r.data,alt:r.name}));return e&&s.push({type:"text",text:e}),{parts:s,textFallback:e}}function pm(e,t,s,r,o={mode:"queue"}){const a=s?{parts:s.parts,textFallback:s.textFallback}:{parts:[{type:"text",text:t}],textFallback:t};return{messageId:e,input:a,policy:o,...gs(r)}}function Ei({sendDaemonCommand:e,activeConv:t,setActionLogs:s,isStandalone:r}){const[o,a]=c.useState(!1),[i,l]=c.useState(!1),[d,u]=c.useState(null),[m,h]=c.useState(!1),[p,b]=c.useState([]),f=c.useRef(!1),x=c.useRef(null),g=c.useRef([]);g.current=p;const v=c.useRef(new Map),S=(t==null?void 0:t.tabKey)||"",A=c.useRef(S);A.current=S;const k=c.useCallback(_=>{b(I=>{const D=_(I);return D===I?I:(pC(A.current,D),D)})},[]),w=c.useCallback(_=>{k(I=>{const D=vC(I,_);return D.changed?D.entries:I})},[k]);c.useEffect(()=>{u(null),h(!1),b(S?hC(S):[])},[t==null?void 0:t.tabKey,S]);const y=t?Us(t):!1;c.useEffect(()=>{u(_=>BC({feedbackMessage:_,lastSendQueued:m,isGenerating:y})?null:_),!y&&m&&h(!1)},[y,m]);const N=c.useCallback(async(_,I)=>{if(!t||f.current)return!1;const D=_.trim(),L=Pi(t);if($C({hasMessage:!!D,blockedMessage:L,sendInFlight:f.current}))return L&&u(L),!1;const $=Date.now(),q={tabKey:t.tabKey,message:D,timestamp:$};if(FC(x.current,q))return u(null),!0;f.current=!0,l(!0),u(null),h(!1),x.current=q;const G=mC($),W=KC(D,I);let R=()=>{};v.current.set(G,new Promise(B=>{R=B}));let O="not-parked";k(B=>[...B,{id:G,content:D,sentAt:$,...W?{input:W}:{}}].slice(-20));try{const B=ps(t);if(!B)return x.current=dm(x.current,q),k(K=>K.filter(oe=>oe.id!==G)),u("Unable to send message right now."),!1;const H=await e(B,"send_chat",pm(G,D,W,t)),U=Ls(H);if(U!=null&&U.deduplicated)return u(null),!0;if(um(U))return O="parked",h(!0),k(K=>K.map(oe=>oe.id===G?{...oe,queued:!0}:oe)),u(so),!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),u(null),!0}catch(B){const H=Pd(B);return H.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",H):console.warn("Send blocked/failed",B),x.current=dm(x.current,q),k(U=>U.filter(K=>K.id!==G)),u(Zo(B)),!1}finally{v.current.delete(G),R(O),k(B=>B.map(H=>H.id===G?{...H,settled:!0}:H)),f.current=!1,l(!1)}},[t,e,k]),j=c.useCallback(async _=>{if(!t||f.current)return!1;const I=g.current,D=_?I.find(q=>q.id===_):I.find(q=>q.queued===!0);if(!D||!D.queued)return!1;const L=D.content.trim();if(!L)return!1;const $=D.id;f.current=!0,l(!0),u(null);try{const q=ps(t);if(!q)return u("Unable to send message right now."),!1;const G=await e(q,"send_chat",pm($,L,D.input,t,{mode:"send_now"})),W=Ls(G);return(W==null?void 0:W.success)===!1?(u(Zo(new Error((W==null?void 0:W.error)||"Send now failed"))),!1):(W==null?void 0:W.queuedWithAgent)===!0?(h(!1),k(R=>R.map(O=>O.id===$?{...O,queued:!1}:O)),u(null),!0):um(W)?(h(!0),k(R=>R.map(O=>O.id===$?{...O,queued:!0}:O)),u(so),!0):(h(!1),k(R=>R.map(O=>O.id===$?{...O,queued:!1}:O)),u(null),!0)}catch(q){return console.warn("Send now blocked/failed",q),u(Zo(q)),!1}finally{f.current=!1,l(!1)}},[t,e,k]),C=c.useCallback(async _=>{if(!t||!_)return!1;const I=g.current.find(L=>L.id===_);if(!I)return!1;const D=I.content.trim();if(I.settled&&!I.queued)return k(L=>L.filter($=>$.id!==_)),!0;if(!I.settled&&await UC(v.current,_)==="not-parked")return k($=>$.filter(q=>q.id!==_)),!0;try{const L=ps(t);if(!L)return u("Unable to cancel this message right now."),!1;const $=await e(L,"cancel_queued_chat",{messageId:_,message:D,...gs(t)}),q=Ls($),G=typeof(q==null?void 0:q.cancelled)=="number"&&q.cancelled===0;return G&&I.stale===!0?(k(W=>W.filter(R=>R.id!==_)),u(W=>W===so?null:W),!0):(q==null?void 0:q.success)===!1||G?(u(HC),!1):(k(W=>W.filter(R=>R.id!==_)),u(W=>W===so?null:W),!0)}catch(L){return console.warn("Cancel queued send failed",L),u(Zo(L)),!1}},[t,e,k]),E=c.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(_){console.error("Relaunch failed",_)}},[t,e]),P=c.useCallback(async _=>{if(t)try{const D=(t.modalButtons||[]).indexOf(_),L=_.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),$=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(L),q=ps(t);if(!q)return;const G=await e(q,"resolve_action",{button:_,action:$?"approve":"reject",...D>=0&&{buttonIndex:D},...gs(t),...Ri(t)}),W=Ls(G);W.success||s(R=>[...R,{routeId:t.tabKey,text:hm(_,W==null?void 0:W.error),timestamp:Date.now()}])}catch(I){mm(I)||console.error("[ModalButton] Error:",I),s(D=>[...D,{routeId:t.tabKey,text:mm(I)?hm(_,I):`❌ **${_}** error`,timestamp:Date.now()}])}},[t,e,s]),T=c.useCallback(async()=>{if(!(!t||o)){a(!0);try{await e(t.routeId,OC(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(_){console.error("Focus agent failed",_)}finally{a(!1)}}},[t,o,e]),M=p.length>0?p[p.length-1]:null;return c.useMemo(()=>({isSendingChat:i,sendFeedbackMessage:d,lastSendQueued:m,pendingLocalMessage:M,pendingLocalMessages:p,isFocusingAgent:o,handleSendChat:N,handleSendNowQueued:j,handleCancelQueued:C,retireEchoedPendingMessages:w,handleRelaunch:E,handleModalButton:P,handleFocusAgent:T}),[i,d,m,M,p,o,N,j,C,w,E,P,T])}const qC=10,zC=8e3,VC=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function GC(e){return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s'"`]+/gi,"$1[REDACTED:bearer]").replace(/(Bearer\s+)[A-Za-z0-9._~+/-]{12,}=*/gi,"$1[REDACTED:bearer]").replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{20,}\b/g,"[REDACTED:github-token]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:api-key]").replace(/\b(?:adk|adm)_[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:adhdev-token]").replace(/((?:api[_-]?key|token|secret|password|passwd|client[_-]?secret)\s*[:=]\s*)[^\s,'"`}&]+/gi,"$1[REDACTED:secret]").replace(/([?&](?:api[_-]?key|token|secret|password|client_secret)=)[^&#\s]+/gi,"$1[REDACTED:secret]")}function Il(e,t="",s=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(VC.test(t)&&e.trim())return"[REDACTED:secret-field]";const r=GC(e);return r.length>8e3?`${r.slice(0,8e3)}…[truncated ${r.length-8e3} chars]`:r}if(typeof e!="object")return String(e);if(s>=6)return"[MaxDepth]";if(Array.isArray(e)){const r=e.slice(-20).map(o=>Il(o,t,s+1));return e.length>20?[{truncatedBefore:e.length-20},...r]:r}return Object.fromEntries(Object.entries(e).slice(0,80).map(([r,o])=>[r,Il(o,r,s+1)]))}function Kr(e,t){return Array.isArray(e)?e.slice(-t):[]}function YC(e,t=Date.now()){const s=e&&t-e.firstAt<=zC,r=s?e.count+1:1;return r>=qC?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:r,firstAt:s?e.firstAt:t},shouldCollect:!1}}function lb(e){var r,o;const{activeConv:t}=e,s={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((r=e.chatState.liveMessages)==null?void 0:r.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((o=e.chatState.historyMessages)==null?void 0:o.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Kr(e.chatState.liveMessages??t.messages,10),activeConversationMessagesTail:Kr(t.messages,10),visibleMessagesTail:Kr(e.visibleMessages,5),historyMessagesTail:Kr(e.chatState.historyMessages,5),actionLogsTail:Kr(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chat:{hasLiveSnapshot:!!e.chatState.hasLiveSnapshot,hasMoreHistory:!!e.chatState.hasMoreHistory,historyError:e.chatState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return Il(s)}function db(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 ub(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 mb(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const s=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&s.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&s.push("","warnings:",...t.warnings.map(r=>`- ${String(r)}`)),s.join(`
|
|
38
|
+
`)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
|
|
39
|
+
|
|
40
|
+
\`\`\`json
|
|
41
|
+
${JSON.stringify(t.bundle,null,2)}
|
|
42
|
+
\`\`\``:`# ADHDev Chat Debug Bundle
|
|
43
|
+
|
|
44
|
+
\`\`\`json
|
|
45
|
+
${JSON.stringify(t,null,2)}
|
|
46
|
+
\`\`\``}function hb(e,t,s){if(s.mode!=="delta")return{...s,mode:"snapshot"};const r=t?e.docOf(t):void 0;return!t||!r||typeof t.seq=="number"&&s.seq!==t.seq+1?null:e.snapshotOf(Qv(r,e.deltaOf(s),e.spec),s,t)}const QC=["topic","key","mode","seq","timestamp","wireVersion"],JC={spec:Jv,docOf:e=>{if(e.status===void 0)return;const t={...e};for(const s of QC)delete t[s];return t},deltaOf:e=>e.delta,snapshotOf:(e,t,s)=>{const r=e;return{...r,topic:"daemon.metadata",key:t.key,mode:"snapshot",daemonId:t.daemonId||s.daemonId,status:{...r.status,timestamp:t.timestamp},seq:t.seq,timestamp:t.timestamp}}},XC={spec:Xv,docOf:e=>e.status||void 0,deltaOf:e=>e.delta,snapshotOf:(e,t,s)=>({topic:"mesh.status",key:t.key,mode:"snapshot",meshId:t.meshId||s.meshId,status:e,seq:t.seq,timestamp:t.timestamp})};function ZC(e,t){return hb(JC,e,t)}function e_(e,t){return hb(XC,e,t)}const qa=new Map,Ml=new Set;let ja={reloadRequired:!1,daemonUpdateRequired:[]};function t_(){const e=[];let t=!1;for(const[s,r]of qa)r==="reload_required"?t=!0:r==="daemon_update_required"&&e.push(s);if(e.sort(),!(t===ja.reloadRequired&&e.join(`
|
|
47
|
+
`)===ja.daemonUpdateRequired.join(`
|
|
48
|
+
`))){ja={reloadRequired:t,daemonUpdateRequired:e};for(const s of Ml)s()}}function Rl(e,t){const s=Ky(_p,t);return s==="ok"?qa.delete(e):qa.set(e,s),t_(),s}function n_(e){return qa.get(e)??"ok"}function fm(){return ja}function s_(e){return Ml.add(e),()=>{Ml.delete(e)}}function xc(e,t){return`${e}:${t}`}const r_=new Set(["intervalMs"]);function bm(e){const t={};for(const s of e)for(const[r,o]of Object.entries(s)){if(!(r in t)||t[r]===void 0){t[r]=o;continue}const a=t[r];typeof a=="boolean"&&typeof o=="boolean"?t[r]=a||o:typeof a=="number"&&typeof o=="number"?t[r]=r_.has(r)?Math.min(a,o):Math.max(a,o):t[r]=o}return t}function gm(e){const t=e.params;return t&&typeof t=="object"?{...t}:{}}function xm(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function o_(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function ls(e,t){o_()&&console.debug(`[subscription-manager] ${e}`,t)}class a_{constructor(){ze(this,"active",new Map);ze(this,"retryTimers",new Map)}subscribe(t,s,r,o,a){var h,p;r={...r,wireVersion:_p};const i=xc(r.topic,r.key),l=this.active.get(i);let d=!0;if(l){l.transport=t,l.handlers.add(o),l.handlerParams.set(o,gm(r));const b={...r,params:bm(l.handlerParams.values())};(!xm(l.request,b)||l.daemonId!==s)&&(l.daemonId=s,l.request=b,d=((h=t.sendData)==null?void 0:h.call(t,s,b))??!1,!d&&(a!=null&&a.retryIntervalMs)?this.scheduleRetry(i,t,a.retryIntervalMs):d&&this.clearRetry(i),ls("subscribe_update",{daemonId:s,topic:r.topic,key:r.key,accepted:d})),l.lastUpdate&&o(l.lastUpdate)}else{const b={daemonId:s,request:r,handlers:new Set([o]),handlerParams:new Map([[o,gm(r)]]),transport:t};this.active.set(i,b),ls("subscribe",{daemonId:s,topic:r.topic,key:r.key}),d=((p=t.sendData)==null?void 0:p.call(t,s,r))??!1,!d&&(a!=null&&a.retryIntervalMs)&&this.scheduleRetry(i,t,a.retryIntervalMs)}let u=!1;const m=()=>{var g,v;if(u)return;u=!0,this.clearRetry(i);const b=this.active.get(i);if(!b)return;if(b.handlers.delete(o),b.handlerParams.delete(o),b.handlers.size>0){const S={...b.request,params:bm(b.handlerParams.values())};xm(b.request,S)||(b.request=S,(g=t.sendData)==null||g.call(t,b.daemonId,S));return}this.active.delete(i);const f=b.daemonId,x={type:"unsubscribe",topic:r.topic,key:r.key};ls("unsubscribe",{daemonId:f,topic:r.topic,key:r.key}),(v=t.sendData)==null||v.call(t,f,x)};return m.initialSendAccepted=d,m}publish(t){var l,d,u,m;const s=t,r=xc(s.topic,s.key),o=this.active.get(r);if(!o)return;this.clearRetry(r);const a=s.mode;if(a==="protocol_mismatch"){Rl(o.daemonId,t.daemonWireVersion);return}if((s.topic==="daemon.metadata"||s.topic==="mesh.status")&&a!=="delta"){if(Rl(o.daemonId,s.wireVersion)!=="ok")return}else if(n_(o.daemonId)!=="ok")return;let i=s;if(s.topic==="daemon.metadata"){const h=ZC(o.lastUpdate,s);if(!h){ls("metadata_resync",{daemonId:o.daemonId,key:s.key,seq:s.seq}),o.lastUpdate=void 0,(d=(l=o.transport)==null?void 0:l.sendData)==null||d.call(l,o.daemonId,o.request);return}i=h}else if(s.topic==="mesh.status"){const h=e_(o.lastUpdate,s);if(!h){ls("mesh_status_resync",{daemonId:o.daemonId,key:s.key,seq:s.seq}),o.lastUpdate=void 0,(m=(u=o.transport)==null?void 0:u.sendData)==null||m.call(u,o.daemonId,o.request);return}i=h}o.lastUpdate=i,bo.record({interactionId:typeof i.interactionId=="string"?i.interactionId:void 0,kind:"subscription.publish",topic:i.topic,payload:{key:i.key}}),o.handlers.forEach(h=>{h(i),bo.record({interactionId:typeof i.interactionId=="string"?i.interactionId:void 0,kind:"subscription.handler_invoked",topic:i.topic,payload:{key:i.key}})})}updateParams(t,s,r){const o=xc(t,s),a=this.active.get(o);if(a){a.request={...a.request,params:{...a.request.params,...r}};for(const[i,l]of a.handlerParams)a.handlerParams.set(i,{...l,...r})}}resubscribeAll(t){var s;ls("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(r=>({daemonId:r.daemonId,topic:r.request.topic,key:r.request.key}))});for(const r of this.active.values())r.transport=t,(s=t.sendData)==null||s.call(t,r.daemonId,r.request)}resubscribeForDaemon(t,s){var o;const r=Array.from(this.active.values()).filter(a=>a.daemonId===t);ls("resubscribe_daemon",{daemonId:t,count:r.length,subscriptions:r.map(a=>({topic:a.request.topic,key:a.request.key}))});for(const a of r)a.transport=s,(o=s.sendData)==null||o.call(s,a.daemonId,a.request)}scheduleRetry(t,s,r){if(this.retryTimers.has(t))return;const o=setTimeout(()=>{var l;this.retryTimers.delete(t);const a=this.active.get(t);if(!a)return;const i=((l=s.sendData)==null?void 0:l.call(s,a.daemonId,a.request))??!1;ls("subscribe_retry",{id:t,accepted:i,topic:a.request.topic,key:a.request.key}),i||this.scheduleRetry(t,s,r)},r);this.retryTimers.set(t,o)}clearRetry(t){const s=this.retryTimers.get(t);s!==void 0&&(clearTimeout(s),this.retryTimers.delete(t))}}const Fn=new a_,ym=["lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash"],vm=["controlValues","providerControls","summaryMetadata","settings","messageInput"];function i_(e){const t=e;return{...t.assistant===!0?{assistant:!0}:{},...t.managedByAssistant===!0?{managedByAssistant:!0}:{}}}const c_=["runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients"];function qr(e,t){const s={};for(const r of t)e[r]!==void 0&&(s[r]=e[r]);return s}function l_(e){const{ownerDaemonId:t,ownerMachineName:s}=e;return{...t&&{ownerDaemonId:t},...s&&{ownerMachineName:s}}}function d_(e,t){const s=new Map;for(const r of e||[])if((r.daemonId||r.id.includes(":")&&r.id.split(":")[0]||"")===t&&r.sessionId){s.set(r.sessionId,{parentSessionId:r.parentSessionId,providerSessionId:r.providerSessionId,workspace:r.workspace??null,sessionCapabilities:r.sessionCapabilities,cdpConnected:r.cdpConnected,activeChat:r.activeChat,controlValues:r.controlValues,providerControls:r.providerControls,summaryMetadata:r.summaryMetadata,runtimeWriteOwner:r.runtimeWriteOwner,runtimeAttachedClients:r.runtimeAttachedClients,cliName:r.cliName,type:r.type,mode:r.mode,status:r.status,lastMessagePreview:r.lastMessagePreview,lastMessageRole:r.lastMessageRole,lastMessageAt:r.lastMessageAt,lastMessageHash:r.lastMessageHash,completionMarker:r.completionMarker,seenCompletionMarker:r.seenCompletionMarker,settings:r.settings,activeInteractivePrompt:r.activeInteractivePrompt});for(const a of r.childSessions||[]){if(!(a!=null&&a.id))continue;const i=s.get(a.id)||{};s.set(a.id,{...i,...a})}}return s}function u_(e){const t=[],s=new Map;for(const r of e)if(r.parentId){const o=s.get(r.parentId)||[];o.push(r),s.set(r.parentId,o)}else t.push(r);return{topLevel:t,childrenByParent:s}}function wm(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function m_(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function h_(e){m_()&&console.debug("[dashboard-conversations] statusPayloadToEntries",e.map(t=>({id:t.id,daemonId:t.daemonId,sessionId:t.sessionId,instanceId:t.instanceId,providerSessionId:t.providerSessionId,transport:t.transport,type:t.type})))}function pb(e,t){const s=[],{daemonId:r,existingDaemon:o,existingEntries:a,timestamp:i}=t,l=i||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:u,childrenByParent:m}=u_(d),h=d_(a,r),p=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,b=u.filter(x=>x.kind==="workspace"&&x.transport==="cdp-page"),f=u.filter(x=>x.kind==="agent"&&x.transport==="pty");s.push({...o||{},id:r,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...p&&{machine:p,platform:p.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},...e.screenshotUsage!==void 0&&{screenshotUsage:e.screenshotUsage},...e.providerChannelStaleness&&{providerChannelStaleness:e.providerChannelStaleness},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:b.some(x=>!!x.cdpConnected)});for(const x of b){const g=h.get(x.id),v=xa(x,g),S=(m.get(x.id)||[]).map(A=>xa(A,h.get(A.id)));s.push({id:`${r}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(g==null?void 0:g.providerSessionId),parentSessionId:v.parentId,sessionKind:v.kind,transport:v.transport,sessionCapabilities:v.capabilities,type:v.providerType,status:v.cdpConnected?"online":"detected",daemonId:r,instanceId:wm(r,x.id),workspace:v.workspace,terminals:0,childSessions:S,agents:S.map(A=>({id:A.id,name:A.providerName||A.providerType,type:A.providerType,status:A.status})),activeChat:v.activeChat,...v.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:v.activeInteractivePrompt},chats:[],cdpConnected:v.cdpConnected,...qr(v,ym),lastUpdated:v.lastUpdated,unread:v.unread,lastSeenAt:v.lastSeenAt,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,seenCompletionMarker:v.seenCompletionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,...qr(v,vm),timestamp:l})}for(const x of f){const g=h.get(x.id),v=xa(x,g);s.push({id:`${r}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(g==null?void 0:g.providerSessionId),parentSessionId:v.parentId,sessionKind:v.kind,transport:v.transport,sessionCapabilities:v.capabilities,type:v.providerType,agentType:v.providerType,status:tw(v.status)||"generating",daemonId:r,instanceId:wm(r,x.id),cliName:v.providerName||v.providerType,mode:v.mode||(g==null?void 0:g.mode)||"terminal",workspace:v.workspace||"",...l_(x),activeChat:v.activeChat,...v.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:v.activeInteractivePrompt},...v.resume!==void 0&&{resume:v.resume},...qr(v,c_),...qr(v,ym),lastUpdated:v.lastUpdated,unread:v.unread,lastSeenAt:v.lastSeenAt,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,seenCompletionMarker:v.seenCompletionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,...qr(v,vm),...i_(v),timestamp:l,_isCli:!0})}return h_(s),s}const yc=new Set;function Rr(){const{sendData:e}=wt(),{injectEntries:t,getIdes:s}=br(),r=c.useRef(new Map);return c.useEffect(()=>{const o=r.current;return()=>{for(const[a,i]of o)i(),yc.delete(a);o.clear()}},[]),c.useCallback(async(o,a)=>{var l;if(!o||!e||yc.has(o))return;const i=Fn.subscribe({sendData:e},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},d=>{const u=s(),m=u.find(p=>p.id===o),h=pb(d.status,{daemonId:o,existingDaemon:m,existingEntries:u,timestamp:d.timestamp});h.length>0&&t(h,{authoritativeDaemonIds:[o]})});(l=r.current.get(o))==null||l(),r.current.set(o,i),yc.add(o)},[s,t,e])}const p_=60,f_=50;function b_(e={}){return e.isCliLike?f_:p_}const fb=new Map;function Sm(e,t){if(!e)return t;const s=fb.get(e);return typeof s=="number"&&s>t?s:t}function g_(e,t){e&&fb.set(e,t)}function x_(e){return e.omittedBefore?{"data-transcript-omitted-before":"true"}:{}}function bb(e){const t={role:e.role,kind:e.kind,content:e.content,id:e.messageId,messageId:e.messageId,_ord:e.ord,_rev:e.rev};return e.receivedAt!==null&&(t.receivedAt=e.receivedAt),e.timestamp!==null&&(t.timestamp=e.timestamp),e.bubbleState!==null&&(t.bubbleState=e.bubbleState),e.senderName!==null&&(t.senderName=e.senderName),e.toolName!==null&&e.toolName&&(t.toolName=e.toolName,t.meta={...t.meta??{},label:e.toolName}),e.expandable&&(t._expandable=!0),e.turnKey!==null&&(t._turnKey=e.turnKey),t}class gb{constructor(){ze(this,"entries",new Map)}map(t){const s=new Map,r=t.map(o=>{const a=this.entries.get(o.messageId);let i=a;return!a||a.source!==o&&(a.source.rev!==o.rev||a.source.ord!==o.ord||a.source.content!==o.content)?i={source:o,mapped:bb(o)}:a.source!==o&&(i={source:o,mapped:a.mapped}),s.set(o.messageId,i),i.mapped});return this.entries=s,r}}function xb(e){if(!e||typeof e!="object")return!1;const t=e;if(t.schemaVersion!==2||typeof t.sessionId!="string"||!t.sessionId||typeof t.status!="string"||!t.status||!Array.isArray(t.messages)||!t.provenance||typeof t.provenance!="object"||!("activeModal"in t))return!1;const s=t.activeModal;if(s!==null){if(!s||typeof s!="object")return!1;const r=s;if(typeof r.message!="string"||!Array.isArray(r.buttons))return!1}return!0}function yb(e,t={}){var s;return{messages:t.cache?t.cache.map(e.messages):e.messages.map(bb),status:e.status,omittedBefore:((s=e.coverage)==null?void 0:s.omittedBefore)===!0}}const y_=new Set([...ku("working"),...ku("blocked"),...Object.keys(Tp).filter(e=>Yy(e))]);function v_(e){return bi(e)}const w_=new Set(["agent:generating_completed","agent:stopped","agent:waiting_approval","agent:waiting_choice"]);function vb(e){return typeof e=="string"&&w_.has(e)}function S_(e,t){const{sendData:s,sendCommand:r}=wt(),o=(t==null?void 0:t.enabled)!==!1,a=vs(e),i=e.sessionId||"",l=Ti(e),d=e.messages.length,u=c.useMemo(()=>!o||!a||!i?null:kb({daemonId:a,sessionId:i,historySessionId:l,sendData:s,fallbackRecentCount:d}),[a,o,l,s,i]);c.useEffect(()=>{u==null||u.updateOptions({fallbackRecentCount:d})},[u,d]);const[m,h]=c.useState(()=>(u==null?void 0:u.getSnapshot())||za());c.useEffect(()=>{if(!u){h(za());return}u.retain(),h(u.getSnapshot());const b=u.subscribe(f=>{h(f)});return()=>{b(),u.release()}},[u]);const p=c.useCallback(async()=>{!u||!a||!i||await u.loadHistoryPage(async({offset:b,excludeRecentCount:f,excludeFromIdentity:x})=>{const g=await r(a,"chat_history",{agentType:e.agentType,offset:b,limit:30,targetSessionId:i,historySessionId:l,excludeRecentCount:f,...x?{excludeFromIdentity:x}:{},...xo()?{includeActivity:!0}:{}}),v=g&&typeof g=="object"&&"result"in g?g.result||{}:g||{};return{messages:Array.isArray(v.messages)?v.messages:[],hasMore:v.hasMore===!0}})},[e.agentType,u,a,l,r,i]);return c.useMemo(()=>D_(m,p),[p,m])}function k_(e,t){const{sendData:s}=wt(),r=(t==null?void 0:t.enabled)!==!1,o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Ed)),a=F_(o),[i,l]=c.useState(0);c.useEffect(()=>{if(!r||e.length===0)return;const u=setInterval(()=>{l(m=>m+1)},a);return()=>{clearInterval(u)}},[e.length,r,a]);const d=c.useMemo(()=>H_(e,{recentActivityMs:o}),[e,o,i]);c.useEffect(()=>{if(!r||d.descriptors.length===0)return;const u=d.descriptors.map(m=>kb({...m,...s?{sendData:s}:{}}));return u.forEach(m=>m.retain()),()=>{u.forEach(m=>m.release())}},[d.signature,r,s])}function j_(e){const[t,s]=c.useState(0),r=c.useMemo(()=>{const i=[];for(const l of e){const d=vs(l),u=l.sessionId||"";if(!d||!u)continue;const m=Ti(l);i.push(Ro(d,u,m||u))}return i},[e]),o=r.join("|"),a=c.useSyncExternalStore(Sb,jm,jm);return c.useEffect(()=>{if(r.length===0)return;const i=[];for(const l of r){const d=Zn.get(l);if(!d)continue;let u=!1;i.push(d.subscribe(()=>{if(!u){u=!0;return}s(m=>m+1)}))}return()=>{for(const l of i)l()}},[o,a]),t}function N_(e){if(!e)return"";const t=e;return t.providerUnitKey?`unit:${t.providerUnitKey}`:t.bubbleId?`bubble:${t.bubbleId}`:typeof t.sequence=="number"&&Number.isFinite(t.sequence)?`seq:${t.sequence}`:""}const km=500,C_=15e3,Ed=12e4,Zn=new Map;let wb=0;const Pl=new Set;function El(){wb+=1;for(const e of Pl)e()}let vc=!1;function __(){vc||(vc=!0,queueMicrotask(()=>{vc=!1,El()}))}function Sb(e){return Pl.add(e),()=>{Pl.delete(e)}}function jm(){return wb}function Ro(e,t,s){return`${e}::${t}::${s||t}`}function za(){return{liveMessages:[],hasLiveSnapshot:!1,historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null,omittedBefore:!1}}function A_(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}class T_{constructor(t){ze(this,"sendData");ze(this,"daemonId");ze(this,"sessionId");ze(this,"fallbackRecentCount");ze(this,"now");ze(this,"snapshot",za());ze(this,"listeners",new Set);ze(this,"retainCount",0);ze(this,"loadHistoryPromise",null);ze(this,"bubbleCache",new gb);ze(this,"lastViewStatus",null);ze(this,"lastTerminalBaseRequestAt",0);this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.now=t.now??(()=>Date.now())}updateOptions(t){t.sendData&&(this.sendData=t.sendData),t.now&&(this.now=t.now),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount))}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...za(),hasLiveSnapshot:!0},this.emit()}applyTranscriptView(t,s={}){if(!xb(t))return;const r=s.mapped??yb(t,{cache:this.bubbleCache});this.lastViewStatus=r.status;const o=this.snapshot,a=o.historyOffset>0?o.hasMoreHistory:r.omittedBefore;o.hasLiveSnapshot&&A_(o.liveMessages,r.messages)&&o.omittedBefore===r.omittedBefore&&o.hasMoreHistory===a||(this.snapshot={...o,liveMessages:r.messages,hasLiveSnapshot:!0,omittedBefore:r.omittedBefore,hasMoreHistory:a},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.retainCount+=1,this.retainCount===1&&El()}release(){const t=this.retainCount>0;this.retainCount=Math.max(0,this.retainCount-1),t&&this.retainCount===0&&El()}isRetained(){return this.retainCount>0}getIdentity(){return{daemonId:this.daemonId,sessionId:this.sessionId}}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const s=(async()=>{try{const o=this.snapshot.hasLiveSnapshot?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),a=await t({offset:this.snapshot.historyOffset,excludeRecentCount:o,excludeFromIdentity:N_(this.snapshot.liveMessages[0])}),i=Array.isArray(a.messages)?a.messages:[],l=[...i,...this.snapshot.historyMessages],d=l.length>km?l.slice(l.length-km):l;this.snapshot={...this.snapshot,historyMessages:d,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:a.hasMore===!0,historyError:null}}catch(r){this.snapshot={...this.snapshot,historyError:r instanceof Error?r.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=s,s}requestTranscriptBase(){if(!this.sendData||!this.daemonId||!this.sessionId)return!1;try{return this.sendData(this.daemonId,{type:"command",commandType:"request_transcript_base",data:{rawSessionId:this.sessionId}})===!0}catch{return!1}}noteTerminalStatusEvent(t){if(!vb(t)||!this.isRetained()||!v_(this.lastViewStatus))return!1;const s=this.now();return this.lastTerminalBaseRequestAt>0&&s-this.lastTerminalBaseRequestAt<C_?!1:(this.lastTerminalBaseRequestAt=s,this.requestTranscriptBase())}dispose(){this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null,this.lastViewStatus=null,this.lastTerminalBaseRequestAt=0}emit(){this.listeners.forEach(t=>t(this.snapshot))}}function kb(e){const t=Ro(e.daemonId,e.sessionId,e.historySessionId),s=Zn.get(t);if(s)return s.updateOptions(e),s;const r=new T_(e);return Zn.set(t,r),__(),r}function I_(e,t,s){if(!e||!t)return;const r=`${e}::${t}::`,o=Ro(e,t,s);for(const[a,i]of Zn.entries())(a===o||a.startsWith(r))&&i.clearLiveSnapshot()}function jb(e){const t=vs(e),s=e.sessionId||"";if(!t||!s)return;const r=Ti(e),o=Ro(t,s,r||s),a=Zn.get(o);if(!a)return;const i=a.getSnapshot();return i.hasLiveSnapshot?i:void 0}const wc=new Map;function M_(e,t,s){if(!e||!t)return 0;const r=`${e}::${t}::`;let o,a=0;for(const[i,l]of Zn.entries())if(i.startsWith(r)){if(!o&&xb(s)){let d=wc.get(r);d||(d=new gb,wc.set(r,d)),o=yb(s,{cache:d})}l.applyTranscriptView(s,o?{mapped:o}:{}),a+=1}return a===0&&wc.delete(r),a}function R_(e,t){if(!e||!t)return!1;const s=`${e}::${t}::`;for(const[r,o]of Zn.entries())if(r.startsWith(s)&&o.requestTranscriptBase())return!0;return!1}function P_(e,t,s){if(!e||!t||!vb(s))return!1;const r=`${e}::${t}::`;for(const[o,a]of Zn.entries())if(o.startsWith(r)&&a.noteTerminalStatusEvent(s))return!0;return!1}function E_(){const e=new Map;for(const s of Zn.values()){if(!s.isRetained())continue;const{daemonId:r,sessionId:o}=s.getIdentity();if(!r||!o)continue;const a=e.get(r);a?a.add(o):e.set(r,new Set([o]))}const t=new Map;for(const[s,r]of e.entries())t.set(s,[...r].sort());return t}function L_(e){return Sb(e)}function D_(e,t){return{...e,loadHistoryPage:t}}function O_(e,t){return e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function $_(e,t={}){const s=String(e.status||"").trim().toLowerCase();if(y_.has(s)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const r=t.now??Date.now(),o=Math.max(0,Number(t.recentActivityMs??Ed)),a=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return a>0?r-a<=o:Array.isArray(e.messages)&&e.messages.length>0}function F_(e=Ed){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function H_(e,t={}){const s=new Set,r=[];for(const o of e){if(!$_(o,t))continue;const a=vs(o),i=o.sessionId||"";if(!a||!i)continue;const l=Ti(o),d=Ro(a,i,l||i);s.has(d)||(s.add(d),r.push({daemonId:a,sessionId:i,historySessionId:l}))}return r.sort(O_),{descriptors:r,signature:r.map(o=>`${o.daemonId}|${o.sessionId}|${o.historySessionId}`).join("||")}}function B_(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function W_(e){return B_(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Na=new Map,Ll=new Set;function Nm(e,t){!e||Na.get(e)===t||(t?Na.set(e,!0):Na.delete(e),Ll.forEach(r=>r(e,t)))}function U_(e){return e?Na.get(e)===!0:!1}function K_(e){return Ll.add(e),()=>{Ll.delete(e)}}function q_(e,t,s=`${t}s`){return`${e} ${e===1?t:s}`}function z_(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function V_(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Nb(e){return bi(e.status)||e.inboxBucket==="working"}function Cb(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function G_(e){return Nb(e)?!1:e.inboxBucket==="task_complete"&&Cb(e).length>0}function Cm(e){return e.branch||"detached HEAD"}function Y_(e){if(e.error)return`${Cm(e)} · Git error: ${e.error}`;const t=[Cm(e)];return e.changedFiles>0?t.push(q_(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function Q_(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Y_(t)}`}function J_(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function X_(e,t={}){if(t.enabled===!1)return[];if(!V_(e))return[];const s=Nb(e)?"working":G_(e)?"complete":null;if(!s)return[];const r=s==="complete"?Cb(e):"";return[{id:s==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${z_(r)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",visibility:"visible",content:Q_(s,e.git),timestamp:J_(e,e.git),meta:{source:"git-system-bubble",phase:s,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const Z_=60,e1=3e4;function t1(e){return{enabled:!!e.sessionId}}function n1(e,t){return e.status==="no_progress"||e.status==="long_generating"?t("chatPane.busyNoProgress"):e.status==="generating"?t("chatPane.busyGenerating"):e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?t("chatPane.busyWaitingApproval"):null}const s1=["unsupported_source","source_unavailable","source_changed","block_not_found","not_a_tool_block"];function r1(e){return s1.find(t=>t===e)}function _b({activeConv:e,ideEntry:t,handleSendChat:s,handleSendNowQueued:r,handleCancelQueued:o,isSendingChat:a=!1,sendFeedbackMessage:i=null,pendingLocalMessage:l=null,pendingLocalMessages:d=null,retireEchoedPendingMessages:u,handleFocusAgent:m,isFocusingAgent:h,actionLogs:p,userName:b,scrollToBottomRequestNonce:f,isInputActive:x=!0,isVisible:g=!0}){var re,Se,Y,ue,fe,Ie,Ke;const{t:v}=he("common"),S=c.useRef(new Map),A=c.useRef(void 0),k=Rr(),{sendCommand:w}=wt(),{isVisible:y}=_d(),N=Mi(),j=vs(e),C=yt.useMemo(()=>{const _e=N.connectionRetryStatuses;if(!_e||!j)return;const Ne=_e[j];if(Ne)return Ne;const Be=Object.keys(_e).find($e=>en($e,j));return Be?_e[Be]:void 0},[N.connectionRetryStatuses,j]);Io("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:p.length,isSendingChat:a});const E=yt.useMemo(()=>Ss(e),[e.status,e.connectionState]);yt.useEffect(()=>{const _e=e.sessionId;if(_e)return Nm(_e,E.isGenerating),()=>{Nm(_e,!1)}},[e.sessionId,E.isGenerating]);const P=c.useMemo(()=>EC(e,t),[e,t]),T=c.useMemo(()=>qN(P.targetEntry),[P.targetEntry]),M=c.useMemo(()=>{var _e;return Md((_e=P.targetEntry)==null?void 0:_e.providerControls,{hostIdeType:e.hostIdeType,providerType:P.providerType})},[e.hostIdeType,P.providerType,(re=P.targetEntry)==null?void 0:re.providerControls]),_=b_({isCliLike:P.isCli}),I=S_(e,t1({sessionId:e.sessionId})),[D,L]=c.useState(()=>Sm(e.tabKey,_)),$=e.assistant===!0,[q,G]=c.useState(()=>xo()),[W,R]=c.useState(()=>DS()),O=$?W:q,B=e.tabKey,H=I.historyMessages,U=I.hasMoreHistory,K=I.historyError,oe=Xf(e,I),ge=$k({status:e.status,connectionState:e.connectionState,hasLiveSnapshot:I.hasLiveSnapshot,visibleMessageCount:oe.length}),J=SC(oe,d??(l?[l]:null),void 0,{excludeQueued:!0}),ke=((d==null?void 0:d.length)??0)>0;c.useEffect(()=>{if(!u||(u(oe),!ke))return;const _e=setInterval(()=>u(oe),e1);return()=>clearInterval(_e)},[u,oe,ke]);const de=c.useMemo(()=>MS(J).length,[J]);c.useEffect(()=>{L(Sm(B,_))},[_,B]);const ne=Math.max(0,J.length-D),le=Rd(e),te=vs(e),ce=W_(e),Ce=Pi(e),Q=n1(e,v),z=i||null,X=ib(e)||i||Q,pe=!!Ce,[Re,Oe]=c.useState(!1);c.useEffect(()=>{const _e=P.targetEntry;te&&(!_e||_e.providerControls===void 0||_e.controlValues===void 0)&&k(te,{minFreshMs:3e4}).catch(()=>{})},[te,(Se=P.targetEntry)==null?void 0:Se.providerControls,(Y=P.targetEntry)==null?void 0:Y.controlValues,k]);const De=c.useCallback(async()=>{if(!Re){if(J.length>D){L(_e=>{const Ne=Math.min(J.length,_e+Z_);return g_(B,Ne),Ne});return}Oe(!0);try{await I.loadHistoryPage()}finally{Oe(!1)}}},[I,Re,J.length,B,D]),{allMessages:we,receivedAtMap:V}=c.useMemo(()=>{const _e=_C({historyMessages:H,liveMessages:J,visibleLiveCount:D}),Ne=X_(e),Be=Ne.length>0?[..._e,...Ne]:_e,$e={};return Be.forEach((it,dt)=>{const ut=vd(it),It=`${e.tabKey}:${ut}`;let bt=ka(it)||S.current.get(It)||0;bt||(bt=Date.now(),S.current.set(It,bt)),$e[ut]=bt}),{allMessages:Be,receivedAtMap:$e}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,ne,H,J,D]),xe=c.useMemo(()=>p.filter(_e=>_e.routeId===e.tabKey).sort((_e,Ne)=>_e.timestamp-Ne.timestamp),[p,e.tabKey]),Z=c.useCallback(async _e=>{if(!te)return{status:"error"};try{const Ne=await w(te,"expand_tool_block",{targetSessionId:e.sessionId,agentType:P.providerType||e.agentType,..."messageId"in _e?{messageId:_e.messageId}:{toolBlockRef:_e.toolBlockRef}}),Be=Ls(Ne),$e=Be!=null&&Be.success?Be.callArgs!==void 0?`${Be.toolName?`${Be.toolName}: `:""}${Be.callArgs}`:Be.result:void 0;return $e!==void 0?{status:"expanded",text:$e}:{status:"error",error:r1(Be==null?void 0:Be.reason)}}catch{return{status:"error"}}},[e.agentType,e.sessionId,P.providerType,te,w]),ae=c.useCallback(async()=>{var dt,ut;if(!te)return;const _e=lb({activeConv:e,visibleMessages:we,actionLogs:p,controls:(dt=P.targetEntry)==null?void 0:dt.providerControls,controlValues:(ut=P.targetEntry)==null?void 0:ut.controlValues,visibleBarControlCount:M.length,chatState:{liveMessages:I.liveMessages,hasLiveSnapshot:I.hasLiveSnapshot,hasMoreHistory:U,historyError:K,historyMessages:H},ui:{controlsVisible:y,visibleLiveCount:D,activityVisible:O,activityCount:de,hiddenLiveCount:ne,isInputActive:x,isVisible:g}}),Ne=await w(te,"get_chat_debug_bundle",{agentType:P.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:_e}),Be=Ls(Ne),$e=mb(Be),it=await ub($e);it==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),nt.showToast(db(Be,{locatorCopyStatus:it}),it==="failed"?"warning":"success")},[e,p,de,we,y,I.hasLiveSnapshot,I.liveMessages,P.providerType,(ue=P.targetEntry)==null?void 0:ue.controlValues,(fe=P.targetEntry)==null?void 0:fe.providerControls,te,U,ne,H,x,g,K,w,O,M.length,D]);c.useEffect(()=>uf(G),[]);const F=c.useCallback(()=>{if($){R(_e=>{const Ne=!_e;return OS(Ne),Ne});return}G(_e=>{const Ne=!_e;return df(Ne),Ne})},[$]),se=c.useCallback(()=>{const _e=YC(A.current);A.current=_e.state,_e.shouldCollect&&ae().catch(Ne=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",Ne),nt.showErrorToast(v("chatPane.debugBundleFailed"),Ne)})},[ae,v]),me=c.useMemo(()=>{if(J.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[n.jsx("div",{className:"connecting-logo-float",children:n.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),n.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[n.jsxs("div",{className:"text-xxs text-blue-400 font-medium",children:[v("chatPane.connectingToMachine"),n.jsx("span",{className:"connecting-dots"})]}),n.jsx("div",{className:"text-2xs opacity-35",children:v("chatPane.establishingP2P")})]})]});if(E.isGenerating&&Oe(!1),e.status==="not_monitored"&&ce)return n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[n.jsx("div",{className:"text-3xl opacity-60",children:n.jsx(xr,{size:28})}),n.jsx("div",{className:"text-xxs opacity-50",children:v("chatPane.agentNotMonitored")}),n.jsx("button",{onClick:m,disabled:h,className:"btn btn-primary",children:h?n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(yr,{size:12}),v("chatPane.switchingPanel")]}):n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Ws,{size:14})," ",v("chatPane.openPanel",{label:le})]})}),n.jsx("div",{className:"text-2xs opacity-35 max-w-[280px]",children:v("chatPane.clickToSwitchMonitoring")})]});if(e.status==="panel_hidden"&&ce)return n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[n.jsx("div",{className:"text-3xl opacity-60",children:n.jsx(pd,{size:28})}),n.jsx("div",{className:"text-xxs opacity-50",children:v("chatPane.agentPanelHidden")}),n.jsx("button",{onClick:m,disabled:h,className:"btn btn-primary",children:h?n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(yr,{size:12}),v("chatPane.openingPanel")]}):n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Ws,{size:14})," ",v("chatPane.openPanel",{label:le})]})}),n.jsx("div",{className:"text-2xs opacity-35 max-w-[280px]",children:v("chatPane.openPanelHint")})]});if(ge.awaitingFirstView)return n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3","data-chat-pane-state":"awaiting-first-view",children:[n.jsx("div",{className:"opacity-40 animate-pulse",children:n.jsx(Cn,{size:26})}),n.jsx("div",{className:"text-xxs opacity-40",children:v("chatPane.loadingChat")})]});if(e.status==="idle"&&!Re)return!U&&H.length===0?n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[n.jsx("div",{className:"opacity-40",children:n.jsx(Cn,{size:26})}),n.jsx("div",{className:"text-xxs opacity-40",children:v("chatPane.noMessagesYet")})]}):n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[n.jsx("div",{className:"opacity-40 animate-pulse",children:n.jsx(Cn,{size:26})}),n.jsx("div",{className:"text-xxs opacity-40",children:v("chatPane.loadingChat")})]})}},[e.connectionState,e.status,ce,ge.awaitingFirstView,m,U,H.length,h,Re,J.length,le,E.isGenerating]);return n.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",...x_(I),children:[n.jsxs("div",{className:"chat-activity-toggle-bar",children:[n.jsxs("button",{type:"button",className:`chat-activity-toggle ${O?"chat-activity-toggle-active":""}`,onClick:F,"aria-pressed":O,title:v("chatPane.activityToggleTitle"),children:[n.jsx("span",{className:"chat-activity-toggle-dot"}),v("chatPane.activityToggleLabel"),de>0&&n.jsx("span",{className:"chat-activity-toggle-count",children:de})]}),n.jsx("div",{className:"ml-auto flex items-center gap-1",children:n.jsx(rC,{machineId:j,blocked:!!(C!=null&&C.blocked),retryConnection:N.retryConnection})})]}),n.jsx(u0,{messages:we,actionLogs:xe,agentName:vr(e)||le||"Agent",userName:b,isCliMode:P.isCli,isWorking:ge.showWorkingIndicator,contextKey:e.tabKey,receivedAtMap:V,lastMessageHash:e.lastMessageHash,showActivityMessages:O,onLoadMore:De,isLoadingMore:Re,hasMoreHistory:U,hiddenLiveCount:ne,loadError:K??void 0,emptyState:me,scrollToBottomRequestNonce:f,isVisible:g,onSendNow:r,isSendingNow:a,onCancelQueued:o,fetchToolBlock:Z}),n.jsx(tC,{entries:d??(l?[l]:[]),onSendNow:r,onCancelQueued:o,isSendingNow:a}),n.jsx(GN,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:P.providerType,displayLabel:P.displayLabel,controls:(Ie=P.targetEntry)==null?void 0:Ie.providerControls,controlValues:(Ke=P.targetEntry)==null?void 0:Ke.controlValues,currentStatus:e.status,coordinatorHint:Ri(e),isActive:x,isCliTerminal:P.isCliTerminal,launchSurface:T}),!P.isCliTerminal&&n.jsx(qf,{contextKey:e.tabKey,panelLabel:le,isSending:a,isBusy:pe,statusMessage:X,inlineStatusMessage:z,onSend:s,isActive:x,showControlsToggle:M.length>0,onControlsToggle:se,messageInput:e.messageInput})]})}const o1=.5,a1=1.25,Sn="\x1B",_m={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function i1(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function Am(e,t){let s=e;if(t.shift&&s.length===1&&(s=s.toUpperCase()),t.ctrl){const r=s.toUpperCase().charCodeAt(0);return String.fromCharCode(r&31)}return s}function c1(e,t){if(t in _m){const r=_m[t],o=i1(e);return o===1?`${Sn}[${r}`:`${Sn}[1;${o}${r}`}switch(t){case"Enter":return e.alt?`${Sn}\r`:"\r";case"Escape":return e.alt?`${Sn}${Sn}`:Sn;case"Backspace":{const r=e.ctrl?"\b":"";return e.alt?`${Sn}${r}`:r}case"Tab":{const r=e.shift?`${Sn}[Z`:" ";return e.alt&&!e.shift?`${Sn} `:r}case"Space":{const r=Am(" ",e);return e.alt?`${Sn}${r}`:r}}const s=Am(t,e);return e.alt?`${Sn}${s}`:s}const Ab="adhdev:mesh-names:v1",l1=200;let zr=null,Tb=0;const Dl=new Set;function Ib(){if(zr)return zr;zr=new Map;try{const e=typeof localStorage<"u"?localStorage.getItem(Ab):null,t=e?JSON.parse(e):null;if(t&&typeof t=="object"&&!Array.isArray(t))for(const[s,r]of Object.entries(t))typeof r=="string"&&r.trim()&&zr.set(s,r.trim())}catch{}return zr}function d1(e){try{if(typeof localStorage>"u")return;const t=[...e.entries()].slice(-l1);localStorage.setItem(Ab,JSON.stringify(Object.fromEntries(t)))}catch{}}function Va(e){const t=Ib();let s=!1;for(const r of e){const o=typeof(r==null?void 0:r.id)=="string"?r.id.trim():"",a=typeof(r==null?void 0:r.name)=="string"?r.name.trim():"";!o||!a||a===o||t.get(o)!==a&&(t.delete(o),t.set(o,a),s=!0)}if(s){Tb+=1,d1(t);for(const r of[...Dl])try{r()}catch{}}}function u1(e,t){Va([{id:e,name:t}])}function m1(e){return e?Ib().get(e)??null:null}function h1(e){return Dl.add(e),()=>{Dl.delete(e)}}function Tm(){return Tb}const Im=Object.freeze({role:null,meshId:null,meshName:null});function Sc(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ld(e,t=m1){var a;if(!e)return Im;const s=e.settings||{},r=Sc((a=e.coordinator)==null?void 0:a.meshId)||Sc(s.meshCoordinatorFor);if(r)return{role:"coordinator",meshId:r,meshName:t(r)};const o=Sc(s.meshNodeFor);return o?{role:"worker",meshId:o,meshName:t(o)}:s.launchedByCoordinator===!0?{role:"worker",meshId:null,meshName:null}:Im}function Mb(e){return Ld(e).role==="coordinator"}function Rb(e){return!!(e!=null&&e.daemonId)&&Mb(e)}function p1(e){return e.meshName||e.meshId}function Pb(e){return c.useSyncExternalStore(h1,Tm,Tm),Ld(e)}function kt(e){return Rd(e)}function Po(e){return rb(e).join(" · ")}function Eb(e,t){const s=sb(e,t);return s||(e.title?e.title:Po(e)||"No messages yet")}function Lb(e,t){const{isReconnecting:s,isConnecting:r,isErrored:o}=Ss(e);return s?"Reconnecting…":r?"Connecting…":t!=null&&t.requiresAction?"Action needed":o?"Needs attention":null}function f1(e,t){const s=["Chat",...rb(e)];return t!=null&&t.timestampLabel&&s.push(t.timestampLabel),s.filter(Boolean).join(" · ")}function Os(e){return Lb(e)||Po(e)}function b1(e,t){return`${kt(e)} · ${Eb(e,t)}`}function g1(e){const t=Ka(e),s=t?Ft(t):vr(e);return`${kt(e)} — ${s||"Agent"}`}function x1(e){return vr(e)||"CLI"}function Db(e){return nb(e)}function Ob(e){return e?`Remote · ${kt(e)||e.workspaceName||"Session"}`:"Remote"}const Mm=[{kind:"regex",label:"section matches",hint:"regex against a screen section",make:e=>({section:e[0],matches:""})},{kind:"elapsed",label:"elapsed_ms",hint:"N ms since state entered",make:()=>({elapsed_ms:1e3})},{kind:"stable",label:"stable_ms",hint:"region unchanged for N ms",make:()=>({stable_ms:1e3,cursor_above:5})},{kind:"changed",label:"changed",hint:"region changed vs prev frame",make:()=>({cursor_above:3,changed:!0})},{kind:"all",label:"all (AND)",hint:"every child must match",make:()=>({all:[]})},{kind:"any",label:"any (OR)",hint:"some child must match",make:()=>({any:[]})},{kind:"not",label:"not",hint:"invert a condition",make:()=>({not:{matches:""}})}],y1=[{label:"active spinner (busy)",cond:{section:"body",matches:"(?:^|\\n)\\s*[·✢✳✶✽✷✸✹]\\s+\\w.*?(?:…|\\.\\.\\.)"}},{label:"completion marker (done)",cond:{section:"body",matches:"✻\\s+\\w+ed\\s+for\\s+(?:\\d+h\\s+)?(?:\\d+m\\s+)?\\d+s"}},{label:"approval prompt (❯ 1.)",cond:{section:"footer",matches:"(?:^|\\n)\\s*[❯›>]\\s*1\\.\\s*.+"}},{label:"picker (Select a …)",cond:{section:"modal",matches:"Select (?:a |an )?(?:model|mode|option)\\b"}},{label:"stable 1.2s (settled)",cond:{stable_ms:1200,cursor_above:5}}];function v1(e){return"all"in e?"all":"any"in e?"any":"not"in e?"not":"elapsed_ms"in e?"elapsed":"stable_ms"in e&&!("changed"in e)?"stable":"changed"in e?"changed":"regex"}function Dd({cond:e,path:t,sections:s,onChange:r,onRemove:o,onPreview:a,preview:i}){const l=v1(e),d=i[t],u=m=>{const h=Mm.find(p=>p.kind===m);h&&r(h.make(s))};return n.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-1.5 space-y-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("select",{value:l,onChange:m=>u(m.target.value),className:"bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1 py-0.5",children:Mm.map(m=>n.jsx("option",{value:m.kind,children:m.label},m.kind))}),(l==="regex"||l==="stable"||l==="changed"||l==="elapsed")&&n.jsx("button",{type:"button",className:"text-3xs text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>a(t,e),children:"test"}),d&&d!=="loading"&&n.jsx("span",{className:`text-3xs font-mono px-1.5 py-0.5 rounded ${d.result?"text-status-online bg-status-online/20":"text-text-secondary bg-bg-glass"}`,children:d.result?"match ✓":"no match"}),d==="loading"&&n.jsx("span",{className:"text-3xs text-text-muted",children:"testing…"}),o&&n.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-xs px-1",onClick:o,children:"×"})]}),l==="regex"&&n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsxs("select",{value:e.section??"",onChange:m=>r({...e,section:m.target.value||void 0}),className:"bg-bg-secondary text-accent-primary text-3xs font-mono rounded border border-border-default px-1 py-0.5",children:[n.jsx("option",{value:"",children:"(whole screen)"}),s.map(m=>n.jsx("option",{value:m,children:m},m))]}),n.jsx("input",{value:e.matches??"",onChange:m=>r({...e,matches:m.target.value}),placeholder:"regex",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),l==="elapsed"&&n.jsx(fs,{label:"elapsed_ms",value:e.elapsed_ms,onChange:m=>r({elapsed_ms:m})}),l==="stable"&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(fs,{label:"stable_ms",value:e.stable_ms,onChange:m=>r({...e,stable_ms:m})}),n.jsx(fs,{label:"cursor_above",value:e.cursor_above??0,onChange:m=>r({...e,cursor_above:m||void 0})})]}),l==="changed"&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(fs,{label:"cursor_above",value:e.cursor_above,onChange:m=>r({...e,cursor_above:m})}),n.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:[n.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:m=>r({...e,changed:m.target.checked}),className:"accent-[var(--accent-primary)]"}),"changed"]})]}),(l==="all"||l==="any")&&n.jsx(w1,{kind:l,cond:e,path:t,sections:s,onChange:r,onPreview:a,preview:i}),l==="not"&&n.jsx("div",{className:"pl-2 border-l border-border-default",children:n.jsx(Dd,{cond:e.not,path:`${t}.not`,sections:s,onChange:m=>r({not:m}),onPreview:a,preview:i})})]})}function w1({kind:e,cond:t,path:s,sections:r,onChange:o,onPreview:a,preview:i}){const l=(e==="all"?t.all:t.any)??[],d=u=>o(e==="all"?{all:u}:{any:u});return n.jsxs("div",{className:"pl-2 border-l border-border-default space-y-1",children:[l.map((u,m)=>n.jsx(Dd,{cond:u,path:`${s}.${e}[${m}]`,sections:r,onChange:h=>d(l.map((p,b)=>b===m?h:p)),onRemove:()=>d(l.filter((h,p)=>p!==m)),onPreview:a,preview:i},m)),n.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d([...l,{section:r[0],matches:""}]),children:"+ condition"}),y1.map(u=>n.jsxs("button",{type:"button",className:"text-3xs text-accent-primary/80 hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>d([...l,JSON.parse(JSON.stringify(u.cond))]),title:"insert verified pattern",children:["+ ",u.label]},u.label))]})]})}function fs({label:e,value:t,onChange:s}){return n.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary font-mono",children:[e,n.jsx("input",{type:"number",value:Number.isFinite(t)?t:0,onChange:r=>s(Number(r.target.value)),className:"w-20 bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5 outline-none focus:border-accent"})]})}function S1({sections:e,otherSectionIds:t,onChange:s,onTest:r,testResult:o}){const a=Object.keys(e),i=o&&o!=="loading"&&!("error"in o)?Object.fromEntries(o.sections.map(h=>[h.id,h])):{},l=(h,p)=>{if(!p||p===h||e[p])return;const b={};for(const[f,x]of Object.entries(e))b[f===h?p:f]=x;s(b)},d=(h,p)=>s({...e,[h]:p}),u=h=>{const p={...e};delete p[h],s(p)},m=()=>{let h="section",p=1;for(;e[h];)h=`section${p++}`;s({...e,[h]:{from_top:0}})};return n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"Sections"}),n.jsx("span",{className:"text-text-muted text-3xs",children:"— how the screen is split; conditions match against these"}),n.jsx("button",{type:"button",className:"ml-auto text-3xs text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:r,title:"Resolve all sections against the live session screen",children:o==="loading"?"testing…":"test on live screen"}),n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:m,children:"+ section"})]}),o&&o!=="loading"&&"error"in o&&n.jsx("div",{className:"text-status-error bg-status-error/15 border border-status-error/40 rounded p-1.5 text-3xs mb-1",children:o.error}),n.jsx("div",{className:"space-y-1.5",children:a.map(h=>{var x;const p=e[h],b=p.anchor!=null?"anchor":"positional",f=g=>{g==="anchor"?d(h,{anchor:p.anchor??"^",anchor_last:p.anchor_last,until:p.until}):d(h,{from_top:p.from_top??0,until:p.until})};return n.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{value:h,onChange:g=>l(h,g.target.value.trim()),className:"w-28 bg-bg-secondary text-accent-primary font-mono text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),n.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-3xs",children:[n.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${b==="positional"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>f("positional"),children:"positional"}),n.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${b==="anchor"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>f("anchor"),children:"anchor"})]}),n.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-sm px-1",onClick:()=>u(h),children:"×"})]}),b==="positional"?n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx(fs,{label:"from_top",value:typeof p.from_top=="number"?p.from_top:0,onChange:g=>d(h,{...p,from_top:g,from_bottom:void 0})}),n.jsx(fs,{label:"from_bottom",value:typeof p.from_bottom=="number"?p.from_bottom:0,onChange:g=>d(h,{...p,from_bottom:g||void 0})}),n.jsx(Rm,{def:p,otherIds:t(h),onChange:g=>d(h,g)})]}):n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"text-3xs text-text-muted w-16",children:"anchor"}),n.jsx("input",{value:p.anchor??"",onChange:g=>d(h,{...p,anchor:g.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),n.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:[n.jsx("input",{type:"checkbox",checked:!!p.anchor_last,onChange:g=>d(h,{...p,anchor_last:g.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"last"]})]}),n.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:n.jsx(Rm,{def:p,otherIds:t(h),onChange:g=>d(h,g)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"text-3xs text-text-muted w-16",children:"ctx next"}),n.jsx("input",{value:((x=p.anchor_context)==null?void 0:x.next)??"",onChange:g=>d(h,{...p,anchor_context:{...p.anchor_context,next:g.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-secondary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})]}),i[h]&&n.jsxs("div",{className:"border-t border-border-subtle pt-1",children:[n.jsxs("div",{className:"text-4xs text-text-muted mb-0.5",children:["captured lines ",i[h].fromLine,"–",i[h].toLine,i[h].text.trim()===""&&n.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),n.jsx("pre",{className:"font-mono text-3xs text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary rounded border border-border-subtle px-2 py-1 max-h-28 overflow-y-auto",children:i[h].text||"(empty)"})]})]},h)})})]})}function Rm({def:e,otherIds:t,onChange:s}){const r=e.until??"",o=r.startsWith("^");return n.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:["until",n.jsxs("select",{value:o?"__regex__":r,onChange:a=>{const i=a.target.value;s(i===""?{...e,until:void 0}:i==="__regex__"?{...e,until:r.startsWith("^")?r:"^"}:{...e,until:i})},className:"bg-bg-secondary text-accent-primary rounded border border-border-default px-1 py-0.5",children:[n.jsx("option",{value:"",children:"(none)"}),t.map(a=>n.jsx("option",{value:a,children:a},a)),n.jsx("option",{value:"__regex__",children:"regex…"})]}),o&&n.jsx("input",{value:r,onChange:a=>s({...e,until:a.target.value}),spellCheck:!1,className:"w-40 bg-bg-secondary text-text-primary font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})}function k1({model:e,onChange:t,onPreview:s,preview:r,onTestSections:o,sectionPreview:a}){const i=e.states.map(h=>h.id),l=Object.keys(e.sections??{}),d=c.useCallback(h=>t({...e,...h}),[e,t]),u=(h,p)=>d({states:e.states.map((b,f)=>f===h?{...b,...p}:b)}),m=(h,p)=>d({transitions:e.transitions.map((b,f)=>f===h?{...b,...p}:b)});return n.jsxs("div",{className:"space-y-3",children:[n.jsx(S1,{sections:e.sections??{},otherSectionIds:h=>l.filter(p=>p!==h),onChange:h=>d({sections:h}),onTest:()=>o(e.sections??{}),testResult:a}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"States"}),n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),n.jsx("div",{className:"space-y-1.5",children:e.states.map((h,p)=>n.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1",children:[n.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[n.jsxs("label",{className:"flex flex-col gap-0.5",children:[n.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide",children:"id (used by transitions)"}),n.jsx("input",{value:h.id,onChange:b=>u(p,{id:b.target.value}),placeholder:"idle",className:"w-32 bg-bg-secondary text-accent-primary font-mono text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),n.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[n.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide",children:"label (shown in dashboard)"}),n.jsx("input",{value:h.label,onChange:b=>u(p,{label:b.target.value}),placeholder:"Ready",className:"w-full bg-bg-secondary text-text-primary text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),n.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1 pb-0.5",onClick:()=>d({states:e.states.filter((b,f)=>f!==p)}),children:"×"})]}),n.jsxs("div",{className:"flex items-center gap-3 text-3xs text-text-secondary flex-wrap",children:[n.jsxs("label",{className:"flex items-center gap-1",children:[n.jsx("input",{type:"radio",name:"initial",checked:!!h.initial,onChange:()=>d({states:e.states.map((b,f)=>({...b,initial:f===p}))}),className:"accent-[var(--accent-primary)]"}),"initial"]}),n.jsxs("label",{className:"flex items-center gap-1",children:[n.jsx("input",{type:"checkbox",checked:!!h.modal,onChange:b=>u(p,{modal:b.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"modal"]}),n.jsxs("label",{className:"flex items-center gap-1",children:["status",n.jsxs("select",{value:h.status??"",onChange:b=>u(p,{status:b.target.value||void 0}),className:"bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5",children:[n.jsx("option",{value:"",children:"(auto)"}),n.jsx("option",{value:"idle",children:"idle"}),n.jsx("option",{value:"generating",children:"generating"}),n.jsx("option",{value:"approval",children:"approval"})]})]})]})]},p))})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"Transitions"}),n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d({transitions:[...e.transitions,{from:i[0]??"",to:i[0]??""}]}),children:"+ transition"})]}),n.jsx("div",{className:"space-y-1.5",children:e.transitions.map((h,p)=>n.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:"text-3xs text-text-muted",children:"from"}),n.jsx(j1,{value:h.from,states:i,onChange:b=>m(p,{from:b})}),n.jsx("span",{className:"text-3xs text-text-muted",children:"→"}),n.jsx("select",{value:h.to,onChange:b=>m(p,{to:b.target.value}),className:"bg-bg-secondary text-status-online font-mono text-3xs rounded border border-border-default px-1 py-0.5",children:i.map(b=>n.jsx("option",{value:b,children:b},b))}),n.jsx("span",{className:"text-3xs text-text-muted ml-1",children:"label"}),n.jsx("input",{value:h.label??"",onChange:b=>m(p,{label:b.target.value||void 0}),placeholder:"debug name only (optional)",title:"Display name shown in the debug history/transition table. Does not affect behaviour.",className:"flex-1 min-w-[120px] bg-bg-secondary text-text-secondary text-3xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),n.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1",onClick:()=>d({transitions:e.transitions.filter((b,f)=>f!==p)}),children:"×"})]}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(fs,{label:"min_hold_ms",value:h.min_hold_ms??0,onChange:b=>m(p,{min_hold_ms:b||void 0})}),n.jsx(fs,{label:"priority",value:h.priority??0,onChange:b=>m(p,{priority:b||void 0})})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-3xs text-text-muted",children:"when"}),!h.when&&n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>m(p,{when:{section:l[0],matches:""}}),children:"+ guard condition"}),h.when&&n.jsx("button",{type:"button",className:"text-3xs text-text-muted hover:text-status-error",onClick:()=>m(p,{when:void 0}),children:"remove guard"})]}),h.when&&n.jsx(Dd,{cond:h.when,path:`t${p}`,sections:l,onChange:b=>m(p,{when:b}),onPreview:s,preview:r})]})]},p))})]})]})}function j1({value:e,states:t,onChange:s}){const r=new Set(Array.isArray(e)?e:e==="*"?t:[e]),o=e==="*",a=i=>{const l=new Set(r);l.has(i)?l.delete(i):l.add(i);const d=t.filter(u=>l.has(u));s(d.length===1?d[0]:d)};return n.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>n.jsx("button",{type:"button",onClick:()=>a(i),className:`font-mono text-3xs px-1 py-0.5 rounded border ${o||r.has(i)?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-muted border-border-default hover:border-border-default"}`,children:i},i))})}function N1(e){return e&&typeof e=="object"?e:{}}function kc(e){return typeof e=="string"?e:""}function C1(e){const t=N1(e);return!!(typeof t.spec_id=="string"&&t.spec_id.length>0||"current_state"in t||Array.isArray(t.stateHistory))}function Pm(e){if(e==null||typeof e!="object"||!C1(e))return null;const t=e;return{cliType:kc(t.cliType),spec_id:kc(t.spec_id),specPath:typeof t.specPath=="string"?t.specPath:void 0,current_state:t.current_state??null,current_modal:t.current_modal??null,activeInteractivePrompt:t.activeInteractivePrompt,exited:t.exited===!0,screen:kc(t.screen),sections:t.sections??void 0,stateHistory:Array.isArray(t.stateHistory)?t.stateHistory:[],idleHoldPending:t.idleHoldPending===!0,lastBusyAt:typeof t.lastBusyAt=="number"?t.lastBusyAt:0,cursorPosition:t.cursorPosition??null,completionIdleDebounce:t.completionIdleDebounce??null,fsm:t.fsm??null,name:typeof t.name=="string"?t.name:void 0,status:typeof t.status=="string"?t.status:void 0,workingDir:typeof t.workingDir=="string"?t.workingDir:void 0,spawnedAtMs:typeof t.spawnedAtMs=="number"?t.spawnedAtMs:void 0,providerSessionId:t.providerSessionId??null,messages:t.messages??void 0,committedMessages:t.committedMessages??void 0}}function Vr(e){const t=Date.now()-e;return t<0?Ha(e):t<2e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:Ha(e)}function Em(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const _1={busy_hold_expired:"text-status-warning bg-status-warning/20 border border-status-warning/40",idle_hold_committed:"text-status-online bg-status-online/20 border border-status-online/40",completion_idle_after:"text-accent-primary bg-accent-primary/20 border border-accent",forced_completion:"text-orange-200 bg-orange-500/20 border border-orange-500/30",forceEmit:"text-purple-200 bg-purple-500/20 border border-purple-500/30",spec_reload:"text-purple-200 bg-purple-500/20 border border-purple-500/30",eval_match:"text-text-secondary bg-bg-glass border border-border-default"},A1={idle:"text-status-online bg-status-online/20 border border-status-online/40",busy:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",generating:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",waiting_approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",picker:"text-accent-primary bg-accent-primary/20 border border-accent",signing_in:"text-accent-primary bg-accent-primary/20 border border-accent"};function jc(e){return A1[e]??"text-text-primary bg-bg-glass border border-border-default"}function ea({children:e}){return n.jsx("div",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function ta(){return n.jsx("div",{className:"border-t border-white/8 my-2"})}function $b({node:e,depth:t=0}){var o;const s=e.result?"text-status-online":"text-text-muted",r=e.result?"●":"○";return n.jsxs("div",{style:{marginLeft:t*10},className:"font-mono text-3xs leading-relaxed",children:[n.jsxs("span",{className:s,children:[r," "]}),n.jsx("span",{className:"text-text-secondary",children:e.kind}),n.jsxs("span",{className:"text-text-muted",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&n.jsxs("span",{className:"text-status-warning",children:[" (",e.remainingMs,"ms left)"]}),(o=e.children)==null?void 0:o.map((a,i)=>n.jsx($b,{node:a,depth:t+1},i))]})}function T1({t:e}){const[t,s]=c.useState(!1),r=e.fires?"text-status-online bg-status-online/20 border-status-online/40":e.holdSatisfied?"text-text-secondary bg-bg-glass border-border-default":"text-status-warning bg-status-warning/20 border-status-warning/40";return n.jsxs("div",{className:"border border-border-default rounded bg-surface-secondary overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-bg-glass-hover text-left",onClick:()=>s(o=>!o),children:[n.jsx("span",{className:"text-3xs text-text-muted w-3",children:e.cond?t?"▾":"▸":" "}),n.jsxs("span",{className:`font-mono text-2xs px-1.5 py-0.5 rounded border ${r}`,children:["→ ",e.to]}),n.jsx("span",{className:"text-text-secondary font-mono text-3xs truncate",children:e.label}),n.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.fires&&n.jsx("span",{className:"text-status-online text-3xs font-mono",children:"FIRES"}),!e.holdSatisfied&&n.jsxs("span",{className:"text-status-warning text-3xs font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),n.jsx("span",{className:`text-3xs font-mono ${e.condResult?"text-status-online":"text-text-muted"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&n.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-bg-secondary border-t border-border-default",children:n.jsx($b,{node:e.cond})})]})}function I1({activeConv:e,onClose:t}){var ne,le,te,ce,Ce;const{sendCommand:s}=wt(),[r,o]=c.useState(!0),[a,i]=c.useState(null),[l,d]=c.useState(null),[u,m]=c.useState(!1),[h,p]=c.useState(new Set(["footer"])),[b,f]=c.useState("Snapshot"),[x,g]=c.useState(!1),[v,S]=c.useState(null),[A,k]=c.useState(!1),[w,y]=c.useState(""),[N,j]=c.useState(!1),[C,E]=c.useState("idle"),[P,T]=c.useState(null),[M,_]=c.useState([]),[I,D]=c.useState({}),[L,$]=c.useState(null),[q,G]=c.useState(!1),W=e.daemonId||((ne=e.routeId)==null?void 0:ne.split(":")[0])||e.routeId||"",R=e.sessionId||"",O=c.useCallback(async()=>{o(!0),d(null);try{const Q=await s(W,"get_spec_debug",{targetSessionId:R}),z=Q&&typeof Q=="object"?Q:{},X=z.result&&typeof z.result=="object"?z.result:z;X!=null&&X.success?i(X):(d((X==null?void 0:X.error)||"Failed to load spec debug"),i(null))}catch(Q){d((Q==null?void 0:Q.message)||String(Q)),i(null)}finally{o(!1)}},[s,W,R]);c.useEffect(()=>{O()},[O]),c.useEffect(()=>{if(!q)return;const Q=setInterval(()=>{O()},1e3);return()=>clearInterval(Q)},[q,O]),c.useEffect(()=>{const Q=z=>{z.key==="Escape"&&!x&&t()};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[t,x]);const B=c.useCallback(async Q=>{try{const z=await s(W,"validate_spec",{content:JSON.stringify(Q)}),X=z&&typeof z=="object"?z:{},pe=X.result&&typeof X.result=="object"?X.result:X;_(pe!=null&&pe.valid?[]:(pe==null?void 0:pe.errors)??["validation failed"])}catch(z){_([(z==null?void 0:z.message)||String(z)])}},[s,W]),H=c.useCallback(async()=>{T(null),E("idle"),D({});try{const Q=await s(W,"get_spec_source",{targetSessionId:R}),z=Q&&typeof Q=="object"?Q:{},X=z.result&&typeof z.result=="object"?z.result:z;if(!(X!=null&&X.success)||typeof X.content!="string"){T((X==null?void 0:X.error)||"Failed to load spec source");return}y(X.content);let pe=null;try{pe=JSON.parse(X.content)}catch{}pe&&pe.$schema==="adhdev:cli/spec@4"?(S(pe),k(!1),B(pe)):(S(null),k(!0)),j(!1),g(!0)}catch(Q){T((Q==null?void 0:Q.message)||String(Q))}},[s,W,R,B]),U=c.useCallback(Q=>{S(Q),y(JSON.stringify(Q,null,2)),j(!0),E("idle"),B(Q)},[B]),K=c.useCallback(async(Q,z)=>{D(X=>({...X,[Q]:"loading"}));try{const X=await s(W,"eval_condition_preview",{targetSessionId:R,condition:z}),pe=X&&typeof X=="object"?X:{},Re=pe.result&&typeof pe.result=="object"?pe.result:pe;!(Re!=null&&Re.success)||!Re.result?D(Oe=>({...Oe,[Q]:{result:!1,detail:Re==null?void 0:Re.error}})):D(Oe=>({...Oe,[Q]:{result:Re.result.result,detail:Re.result.detail}}))}catch(X){D(pe=>({...pe,[Q]:{result:!1,detail:X==null?void 0:X.message}}))}},[s,W,R]),oe=c.useCallback(async Q=>{$("loading");try{const z=await s(W,"resolve_section_preview",{targetSessionId:R,sections:Q}),X=z&&typeof z=="object"?z:{},pe=X.result&&typeof X.result=="object"?X.result:X;!(pe!=null&&pe.success)||!Array.isArray(pe.sections)?$({error:(pe==null?void 0:pe.error)||"resolve failed"}):$({sections:pe.sections,screenLineCount:pe.screenLineCount??0})}catch(z){$({error:(z==null?void 0:z.message)||String(z)})}},[s,W,R]),ge=c.useCallback(async()=>{var X,pe;const Q=(X=a==null?void 0:a.snapshot)==null?void 0:X.specPath;if(!Q){T("No spec path on this session");return}if(!A&&M.length>0){T("Fix validation errors before saving");return}const z=!A&&v?JSON.stringify(v,null,2):w;E("saving"),T(null);try{const Re=await s(W,"write_spec_source",{specPath:Q,content:z}),Oe=Re&&typeof Re=="object"?Re:{},De=Oe.result&&typeof Oe.result=="object"?Oe.result:Oe;if(!(De!=null&&De.success)){E("error"),T(((pe=De==null?void 0:De.validationErrors)==null?void 0:pe.join(`
|
|
49
|
+
`))||(De==null?void 0:De.error)||"Save failed");return}E("saved"),j(!1),setTimeout(()=>{O()},400),setTimeout(()=>E("idle"),1500)}catch(Re){E("error"),T((Re==null?void 0:Re.message)||String(Re))}},[s,W,(le=a==null?void 0:a.snapshot)==null?void 0:le.specPath,w,v,A,M,O]),J=Pm(a==null?void 0:a.snapshot),ke=async()=>{var De,we,V;let Q=a;Q||(await O(),Q=a);const z=Pm(Q==null?void 0:Q.snapshot),X=[];if(X.push("# Spec Debug Snapshot"),X.push(`Generated: ${new Date().toISOString()}`),X.push(`Session: ${(Q==null?void 0:Q.sessionId)??""} (${(Q==null?void 0:Q.providerType)??""})`),X.push(`Spec: ${(z==null?void 0:z.spec_id)??""} (${(z==null?void 0:z.specPath)??""})`),X.push(`Provider: ${(z==null?void 0:z.name)??""} (${(z==null?void 0:z.cliType)??""})`),X.push(`Working dir: ${(z==null?void 0:z.workingDir)??""}`),X.push(`Spawned: ${z!=null&&z.spawnedAtMs?new Date(z.spawnedAtMs).toISOString():""}`),X.push(""),X.push("## Current State"),X.push(`State: ${((De=z==null?void 0:z.current_state)==null?void 0:De.id)??"none"} (${((we=z==null?void 0:z.current_state)==null?void 0:we.label)??""})`),X.push(`Status: ${(z==null?void 0:z.status)??""}`),X.push(`Idle hold pending: ${(z==null?void 0:z.idleHoldPending)??!1}`),X.push(`Exited: ${(z==null?void 0:z.exited)??!1}`),X.push(`Last busy: ${z!=null&&z.lastBusyAt?Vr(z.lastBusyAt):""}`),X.push(`Cursor: ${(z==null?void 0:z.cursorPosition)!=null?`(${z.cursorPosition.row},${z.cursorPosition.col})`:"n/a"}`),(V=z==null?void 0:z.completionIdleDebounce)!=null&&V.active){const xe=z.completionIdleDebounce;X.push(`completion_idle_after: age=${xe.ageMs}ms hold=${xe.holdMs}ms force=${xe.forceAfterMs}ms remaining=${Math.max(0,xe.holdMs-xe.ageMs)}ms`)}if(X.push(""),X.push("## Modal"),z!=null&&z.current_modal){const xe=z.current_modal.buttons.map(Z=>Z.label).join(" / ");X.push(`${z.current_modal.title??""} [${xe}]`)}else X.push("none");X.push(""),X.push("## State History (last 20)");const pe=z!=null&&z.stateHistory?[...z.stateHistory].reverse().slice(0,20):[];for(const xe of pe){const Z=xe.reason!=null?typeof xe.reason=="string"?xe.reason:JSON.stringify(xe.reason):"",ae=xe.debounceKind!=null?typeof xe.debounceKind=="string"?xe.debounceKind:JSON.stringify(xe.debounceKind):"",F=xe.matchedStateId!=null?String(xe.matchedStateId):"",se=(xe.matchedRules??[]).map(me=>typeof me=="string"?me:JSON.stringify(me)).join(", ");X.push(`- ${xe.stateId} @ ${new Date(xe.at).toISOString()} held ${xe.durationMs}ms | reason: ${Z} | debounce: ${ae} | eval→${F} | rules: ${se}`)}if(X.push(""),X.push("## Sections"),z!=null&&z.sections)for(const[xe,Z]of Object.entries(z.sections)){const ae=Z.split(`
|
|
50
|
+
`).slice(0,3).join(`
|
|
51
|
+
`);X.push(`${xe}: ${ae}`)}X.push(""),X.push("## Last Assistant Message");const Oe=[...(z==null?void 0:z.messages)??(z==null?void 0:z.committedMessages)??[]].reverse().find(xe=>xe.role==="assistant");X.push(Oe?Oe.content.slice(0,400):""),X.push(""),X.push("## Screen (first 50 lines)"),X.push(z!=null&&z.screen?z.screen.split(`
|
|
52
|
+
`).slice(0,50).join(`
|
|
53
|
+
`):"");try{await navigator.clipboard.writeText(X.join(`
|
|
54
|
+
`)),f("Copied!"),setTimeout(()=>f("Snapshot"),1500)}catch(xe){console.error("[SpecDebugPanel] clipboard write failed",xe)}},de=Q=>{p(z=>{const X=new Set(z);return X.has(Q)?X.delete(Q):X.add(Q),X})};return n.jsx(Un,{children:n.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Spec debug",className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center bg-black/60 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] px-0 sm:items-center sm:p-4",onClick:t,style:{pointerEvents:"auto"},children:n.jsxs("div",{className:"bg-bg-secondary text-text-primary border border-border-default rounded-t-xl sm:rounded-lg shadow-2xl max-w-2xl w-full max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[88vh] flex flex-col",onClick:Q=>Q.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-border-default px-4 py-2.5 shrink-0 gap-2 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 overflow-hidden",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary shrink-0",children:"Spec Debug"}),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):H()},disabled:r,children:x?"Close Editor":"Edit Spec"}),n.jsx("button",{type:"button",className:"text-2xs text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{ke()},disabled:r,children:b}),n.jsx("button",{type:"button",className:"text-2xs text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{O()},disabled:r,children:r?"Loading…":"Refresh"}),n.jsx("button",{type:"button",className:"text-text-secondary hover:text-text-primary transition-colors text-xl leading-none w-7 h-7 flex items-center justify-center rounded hover:bg-bg-glass-hover",onClick:t,"aria-label":"Close",children:"×"})]})]}),x&&n.jsxs("div",{className:"flex-1 flex flex-col min-h-0 px-4 py-3 gap-2",children:[n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[n.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-3xs",children:[n.jsx("button",{type:"button",className:`px-2 py-0.5 ${A?"text-text-secondary hover:bg-bg-glass-hover":"bg-accent-primary/20 text-accent-primary"}`,onClick:()=>{if(A)try{const Q=JSON.parse(w);S(Q),B(Q)}catch{return}k(!1)},disabled:!v&&A,children:"Form"}),n.jsx("button",{type:"button",className:`px-2 py-0.5 ${A?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>{v&&y(JSON.stringify(v,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("/")}),N&&n.jsx("span",{className:"text-status-warning text-3xs",children:"unsaved"}),!A&&M.length>0&&n.jsxs("span",{className:"text-status-error text-3xs",children:[M.length," error",M.length>1?"s":""]}),n.jsx("button",{type:"button",className:`text-2xs px-2.5 py-1 rounded border transition-colors ${C==="saving"||!A&&M.length>0?"text-text-muted border-border-default cursor-not-allowed":"text-status-online bg-status-online/20 border-status-online/40 hover:bg-status-online/20"}`,onClick:()=>{ge()},disabled:C==="saving"||!A&&M.length>0,children:C==="saving"?"Saving…":C==="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}),!A&&M.length>0&&n.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-1.5 text-3xs shrink-0 max-h-24 overflow-y-auto space-y-0.5",children:M.map((Q,z)=>n.jsx("div",{className:"font-mono",children:Q},z))}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:A||!v?n.jsx("textarea",{value:w,onChange:Q=>{y(Q.target.value),j(!0),E("idle")},spellCheck:!1,className:"w-full h-full min-h-[300px] font-mono text-2xs leading-relaxed bg-bg-secondary text-text-primary border border-border-default rounded p-3 resize-none outline-none focus:border-accent"}):n.jsx(k1,{model:v,onChange:U,onPreview:K,preview:I,onTestSections:oe,sectionPreview:L})}),n.jsx("div",{className:"text-3xs text-text-muted shrink-0",children:A?"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:Vr(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?jc(J.current_state.id):"text-text-muted"}`,children:J.current_state?J.current_state.id:"none"}),((te=J.current_state)==null?void 0:te.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!==((ce=J.current_state)==null?void 0:ce.id)&&n.jsxs("span",{className:"text-text-muted text-2xs",children:["engine: ",n.jsx("span",{className:`font-mono ${jc(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:Vr(J.lastBusyAt)})]})]}),((Ce=J.completionIdleDebounce)==null?void 0:Ce.active)&&n.jsxs("div",{className:"flex items-center gap-2 text-2xs bg-accent-primary/20 border border-accent rounded-md px-3 py-1.5 font-mono",children:[n.jsx("span",{className:"text-accent-primary",children:"completion_idle_after"}),n.jsxs("span",{className:"text-text-secondary",children:["age: ",n.jsxs("span",{className:"text-accent-primary",children:[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(Q=>Q.label).join(" / "),"]"]})]}),J.fsm&&n.jsxs(n.Fragment,{children:[n.jsx(ta,{}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsxs(ea,{children:["FSM — outgoing from ",n.jsx("span",{className:"text-accent-primary font-mono normal-case",children:J.fsm.currentState})," (held ",Em(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:q,onChange:Q=>G(Q.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((Q,z)=>n.jsx(T1,{t:Q},z))]})]})]}),n.jsx(ta,{}),J.sections&&Object.keys(J.sections).length>0&&n.jsxs("div",{children:[n.jsx(ea,{children:"Sections"}),n.jsx("div",{className:"space-y-1",children:Object.entries(J.sections).map(([Q,z])=>{var Oe;const X=h.has(Q),pe=z.split(`
|
|
55
|
+
`),Re=((Oe=pe[0])==null?void 0:Oe.slice(0,80))||"(empty)";return n.jsxs("div",{className:"border border-border-default rounded overflow-hidden bg-surface-secondary",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-bg-glass-hover transition-colors text-left",onClick:()=>de(Q),children:[n.jsx("span",{className:"text-3xs text-text-muted w-3",children:X?"▾":"▸"}),n.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-2xs",children:Q}),!X&&n.jsx("span",{className:"text-text-secondary truncate font-mono text-2xs",children:Re}),n.jsxs("span",{className:"ml-auto text-text-muted text-3xs shrink-0",children:[pe.length,"L"]})]}),X&&n.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-2xs text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary max-h-40 overflow-y-auto border-t border-border-default",children:z||"(empty)"})]},Q)})})]}),n.jsx(ta,{}),J.stateHistory&&J.stateHistory.length>0&&n.jsxs("div",{children:[n.jsxs(ea,{children:["State History (",J.stateHistory.length,")"]}),n.jsx("div",{className:"space-y-px",children:[...J.stateHistory].reverse().slice(0,20).map((Q,z)=>n.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:`font-mono text-2xs font-semibold px-1.5 py-0.5 rounded shrink-0 ${jc(Q.stateId)}`,children:Q.stateId}),n.jsx("span",{className:"text-text-secondary text-2xs shrink-0 tabular-nums",children:Vr(Q.at)}),Q.durationMs>0&&n.jsxs("span",{className:"text-text-muted text-2xs",children:["held ",n.jsx("span",{className:"text-text-secondary",children:Em(Q.durationMs)})]}),Q.reason&&n.jsx("span",{className:`text-3xs px-1.5 py-0.5 rounded font-mono shrink-0 ${_1[String(Q.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(Q.reason)}),Q.debounceKind&&String(Q.debounceKind)!=="none"&&n.jsxs("span",{className:"text-text-muted text-3xs font-mono",children:["debounce:",String(Q.debounceKind)]}),Q.matchedStateId&&String(Q.matchedStateId)!==Q.stateId&&n.jsxs("span",{className:"text-text-muted text-3xs font-mono",children:["eval→",n.jsx("span",{className:"text-text-secondary",children:String(Q.matchedStateId)})]})]}),Q.matchedRules&&Q.matchedRules.length>0&&n.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-border-default",children:[Q.matchedRules.slice(0,3).map((X,pe)=>n.jsx("span",{className:"font-mono text-3xs text-accent-primary bg-accent-primary/20 border border-accent px-1.5 py-0.5 rounded break-all",children:typeof X=="string"?X:JSON.stringify(X)},pe)),Q.matchedRules.length>3&&n.jsxs("span",{className:"text-3xs text-text-muted",children:["+",Q.matchedRules.length-3," more"]})]})]},z))})]}),n.jsx(ta,{}),(()=>{const Q=J.messages??J.committedMessages??[];if(Q.length===0)return null;const z=Q.filter(Re=>Re.role==="user").length,X=Q.filter(Re=>Re.role==="assistant").length,pe=[...Q].reverse().find(Re=>Re.role==="assistant");return n.jsxs("div",{children:[n.jsxs(ea,{children:["Transcript (",Q.length," — ",z,"u / ",X,"a)"]}),pe&&n.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-md p-2.5 text-2xs",children:[n.jsxs("div",{className:"text-text-muted mb-1 text-3xs",children:["Last assistant ",pe.receivedAt?Vr(pe.receivedAt):""]}),n.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[pe.content.slice(0,400),pe.content.length>400?"…":""]})]})]})})(),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:()=>m(Q=>!Q),children:[n.jsx("span",{className:"text-text-muted",children:u?"▾":"▸"}),n.jsxs("span",{children:["Raw screen (",J.screen?J.screen.split(`
|
|
56
|
+
`).length:0," lines)"]})]}),u&&n.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-2xs text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:J.screen||"(empty)"})]})]})]})]})})})}function Fb(e,t){if(typeof window>"u")return!1;try{return window[e]===!0||window.localStorage.getItem(t)==="1"}catch{return window[e]===!0}}function M1(){return Fb("__ADHDEV_DEBUG_SPEC__","adhdev_debug_spec")}function R1(){return Fb("__ADHDEV_DEBUG_MOBILE_BUNDLE__","adhdev_debug_mobile_bundle")}function P1({activeConv:e,clearToken:t=0,terminalRef:s,handleSendChat:r,isSendingChat:o=!1,sendFeedbackMessage:a=null,isVisible:i=!0,isInputActive:l=!0}){var gt;const{t:d}=he("common");yn();const{sendPtyInput:u}=wt(),[m,h]=c.useState(!1),p=c.useRef(!1);p.current=m;const[b,f]=c.useState("Runtime terminal unavailable"),[x,g]=c.useState(!1),[v,S]=c.useState(null),[A,k]=c.useState(!1),[w,y]=c.useState(!1),[N,j]=c.useState(1),[C,E]=c.useState(!1),[P,T]=c.useState(!1),[M,_]=c.useState(!1),[I,D]=c.useState(!1),[L,$]=c.useState(!1),q=M1(),[G,W]=c.useState({width:0,height:0}),[R,O]=c.useState({width:0,height:0}),[B,H]=c.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[U,K]=c.useState(null),oe=c.useRef(null),ge=c.useRef(null),J=c.useRef(!1),ke=c.useRef(!1),de=c.useRef(i),ne=c.useRef(0),le=c.useRef(!1),te=c.useRef(""),ce=c.useRef(null),Ce=c.useRef(!1),Q=c.useRef(!1),z=c.useRef(null),X=c.useRef(null),pe=c.useRef(null),Re=32*1024,Oe=()=>{var ye,Ae,Le,Ve;return((Ae=(ye=oe.current)==null?void 0:ye.ownerDocument)==null?void 0:Ae.defaultView)||((Ve=(Le=ge.current)==null?void 0:Le.ownerDocument)==null?void 0:Ve.defaultView)||window},De=ye=>{const Ae=Oe();return{ownerWindow:Ae,frameId:Ae.requestAnimationFrame(ye)}},we=()=>{const ye=z.current;if(ye){try{ye.ownerWindow.cancelAnimationFrame(ye.frameId)}catch{}z.current=null}},V=()=>{const ye=X.current;if(ye){try{ye.ownerWindow.clearTimeout(ye.timeoutId)}catch{}X.current=null}},xe=()=>{const ye=pe.current;if(ye){try{ye.ownerWindow.clearTimeout(ye.timeoutId)}catch{}pe.current=null}},Z=()=>{i&&z.current===null&&(z.current=De(()=>{It()}))},ae=e.tabKey,F=e.sessionId||"",se=e.daemonId||((gt=e.routeId)==null?void 0:gt.split(":")[0])||e.routeId||"",me=Pi(e),re=m?ib(e)||a:b,Se=m&&a||null,Y=o1,ue=a1,fe=.05,Ie=()=>{const ye=R.width,Ae=R.height;if(!Number.isFinite(G.width)||G.width<=0||!Number.isFinite(G.height)||G.height<=0||!Number.isFinite(ye)||ye<=0||!Number.isFinite(Ae)||Ae<=0)return 1;const Le=G.width/ye,Ve=G.height/Ae;return Number(Math.min(ue,Math.max(Y,Math.min(Le,Ve))).toFixed(2))},Ke=Ie(),_e=J.current&&N>Ke,Ne=Number.isFinite(R.width)&&R.width>0?Math.max(G.width,Math.round(R.width*N)):G.width,Be=Number.isFinite(R.height)&&R.height>0?Math.max(G.height,Math.round(R.height*N)):G.height,$e=()=>{De(()=>{const ye=ge.current;ye&&(ye.scrollLeft=0,ye.scrollTop=ye.scrollHeight-ye.clientHeight)})},it=()=>{var ye,Ae;ne.current=0,le.current=!1,te.current="",ce.current=null,Ce.current=!1,Q.current=!1,J.current||(ke.current=!1,j(1)),z.current!==null&&we(),h(!1),f("Runtime terminal unavailable"),xe(),V(),S(null),K(null),E(!1),g(!1),k(!1),y(!1),(Ae=(ye=s.current)==null?void 0:ye.reset)==null||Ae.call(ye)},dt=()=>{var ye,Ae;ne.current=0,le.current=!1,te.current="",ce.current=null,Ce.current=!1,Q.current=!1,z.current!==null&&we(),h(!0),f(""),xe(),V(),S(null),K(null),E(!1),g(!1),k(!1),y(!1),(Ae=(ye=s.current)==null?void 0:ye.reset)==null||Ae.call(ye)},ut=()=>{Q.current&&(Q.current=!1,De(()=>{var ye,Ae;(Ae=(ye=s.current)==null?void 0:ye.scrollToTop)==null||Ae.call(ye)}))},It=()=>{if(z.current=null,!i)return;const ye=te.current;if(!ye)return;const Ae=ye.slice(0,Re);te.current=ye.slice(Ae.length);const Le=s.current;if(!Le){te.current=Ae+te.current,Z();return}Le.write(Ae,()=>{if(te.current.length>0){Z();return}ut()})},bt=ye=>{ye&&(te.current+=ye,Z())},jt=(ye,Ae=0,Le,Ve,Je={})=>{var st,Nt,xt,Wt;const ht=!!Je.force;!ht&&Ae>0&&ne.current>=Ae||!ht&&Ae===0&&le.current||(ne.current=Ae,Ae>0&&k(!0),h(!0),f(""),typeof Le=="number"&&typeof Ve=="number"&&Le>0&&Ve>0&&((Nt=(st=s.current)==null?void 0:st.resize)==null||Nt.call(st,Le,Ve)),te.current="",(Wt=(xt=s.current)==null?void 0:xt.reset)==null||Wt.call(xt),ye?bt(ye):ut())};c.useEffect(()=>{it()},[F]),c.useEffect(()=>{var Ae;if(!F)return;const ye=((Ae=Ot.onRuntimeEvent)==null?void 0:Ae.call(Ot,F,Le=>{if(!(!Le||Le.sessionId!==F)){if(Le.type==="runtime_snapshot"){if(!i){ce.current={text:Le.text||"",seq:Le.seq||0,cols:Le.cols,rows:Le.rows,force:!!Le.force};return}jt(Le.text||"",Le.seq||0,Le.cols,Le.rows,{force:!!Le.force});return}if(Le.type==="session_output"){le.current=!0,typeof Le.seq=="number"&&(ne.current=Math.max(ne.current,Le.seq),Le.seq>0&&k(!0)),p.current||h(!0),p.current||f(""),typeof Le.data=="string"&&bt(Le.data);return}if(Le.type==="session_cleared"){if(!i){Ce.current=!0,te.current="",ce.current=null;return}dt();return}if(Le.type==="session_io_error"){const Ve=typeof Le.error=="string"&&Le.error?Le.error:typeof Le.reason=="string"&&Le.reason?Le.reason:"unknown error";h(!1),f(`Runtime input failed: ${Ve}`);return}}},se))||(()=>{});return()=>{ye()}},[se,F,s,i]);const ee=async(ye={})=>{var Ae;if(!se||!F)return{success:!1,error:"daemonId and sessionId are required"};ye.preserveStatus||f(ye.loadingMessage||"Loading runtime terminal...");try{const Le=await((Ae=Ot.requestRuntimeSnapshot)==null?void 0:Ae.call(Ot,se,F,{sinceSeq:ye.sinceSeq,force:ye.force}));return Le&&Le.success===!1?(ye.preserveStatus||(h(!1),f(`Runtime terminal unavailable: ${Le.error}`)),Le):Le||{success:!0}}catch(Le){const Ve=(Le==null?void 0:Le.message)||String(Le);return ye.preserveStatus||(h(!1),f(`Runtime terminal unavailable: ${Ve}`)),{success:!1,error:Ve}}},ie=async ye=>{var ht,st;const Ae=((ht=oe.current)==null?void 0:ht.ownerDocument)||document,Le=Ae.defaultView||window,Ve=(st=Le.navigator)==null?void 0:st.clipboard;if(Ve!=null&&Ve.writeText&&Le.isSecureContext)try{return await Ve.writeText(ye),!0}catch{}let Je=null;try{return Je=Ae.createElement("textarea"),Je.value=ye,Je.setAttribute("readonly","true"),Je.style.position="fixed",Je.style.left="-9999px",Je.style.top="0",Ae.body.appendChild(Je),Je.focus(),Je.select(),Ae.execCommand("copy")}catch{return!1}finally{Je==null||Je.remove()}},ve=ye=>{V(),K(ye);const Ae=Oe();X.current={ownerWindow:Ae,timeoutId:Ae.setTimeout(()=>{X.current=null,K(Le=>Le===ye?null:Le)},2200)}},Te=ye=>{xe(),S(ye);const Ae=Oe();pe.current={ownerWindow:Ae,timeoutId:Ae.setTimeout(()=>{pe.current=null,S(Le=>Le===ye?null:Le)},2200)}},Ee=async()=>{var Je,ht,st,Nt;const ye=((ht=(Je=s.current)==null?void 0:Je.getSelection)==null?void 0:ht.call(Je))||"",Ae=((Nt=(st=s.current)==null?void 0:st.getVisibleText)==null?void 0:Nt.call(st))||"",Le=ye.trimEnd()||Ae.trimEnd();if(!Le){ve("Nothing to copy");return}if(!await ie(Le)){ve("Copy failed");return}ve(ye.trimEnd()?"Copied selection":"Copied visible terminal")},Ye=ye=>{if(!m||!i)return;((u==null?void 0:u(se,F,ye))??!1)||ve("Terminal input failed")},qe=ye=>{Ye(c1({ctrl:P,alt:M,shift:I},ye)),T(!1),_(!1),D(!1)},Pe=async()=>{if(x)return;g(!0),S("Loading older terminal output..."),Q.current=!0;const ye=await ee({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(g(!1),(ye==null?void 0:ye.success)===!1){Q.current=!1,S(`Older terminal output unavailable: ${ye.error}`);return}y(!0),Te("Older terminal output loaded"),De(()=>{var Ae;(Ae=s.current)==null||Ae.bumpResize()})};c.useEffect(()=>{var Ae,Le;if(!F)return;se&&((Ae=Ot.getState)==null?void 0:Ae.call(Ot,se))==="connected"&&ee();const ye=(Le=Ot.onStateChange)==null?void 0:Le.call(Ot,(Ve,Je)=>{Ve!==se||Je!=="connected"||ee()});return()=>{ye==null||ye()}},[se,F,s]),c.useEffect(()=>{t&&it()},[t,ae,s]),c.useEffect(()=>{var Ve,Je;const ye=oe.current,Ae=(Je=(Ve=ye==null?void 0:ye.ownerDocument)==null?void 0:Ve.defaultView)==null?void 0:Je.ResizeObserver;if(!ye||!Ae)return;const Le=new Ae(ht=>{const st=ht[0];if(!st)return;const{width:Nt,height:xt}=st.contentRect;W(Wt=>{const Jt=Math.round(Nt),an=Math.round(xt);return Wt.width===Jt&&Wt.height===an?Wt:{width:Jt,height:an}})});return Le.observe(ye),()=>Le.disconnect()},[]),c.useEffect(()=>{if(J.current)return;const ye=Ie();!Number.isFinite(ye)||ye<=0||j(Ae=>ke.current?ye<Ae-fe?ye:Ae:(ke.current=!0,ye))},[R.height,R.width,G.height,G.width]),c.useEffect(()=>{_e&&$e()},[_e,Be,Ne]),c.useEffect(()=>{var Le;const ye=de.current;if(de.current=i,!i)return;ye||y(!1),Ce.current&&(Ce.current=!1,dt());const Ae=ce.current;Ae&&(ce.current=null,jt(Ae.text,Ae.seq,Ae.cols,Ae.rows,{force:!!Ae.force})),se&&F&&((Le=Ot.getState)==null?void 0:Le.call(Ot,se))==="connected"&&ee(),te.current&&z.current===null&&Z(),De(()=>{var Ve;(Ve=s.current)==null||Ve.bumpResize()})},[se,i,F]),c.useEffect(()=>()=>{z.current!==null&&we(),V(),xe()},[]),c.useEffect(()=>{const ye=Ve=>{var ht;const Je=Ve.detail;Je!=null&&Je.sessionId&&Je.sessionId!==F||m&&((ht=s.current)==null||ht.bumpResize())},Ae=Oe(),Le=Ae===window?[window]:[window,Ae];for(const Ve of Le)Ve.addEventListener("adhdev:fit-cli-terminal",ye);return()=>{for(const Ve of Le)Ve.removeEventListener("adhdev:fit-cli-terminal",ye)}},[m,F,s]);const At=m&&A&&!w&&(B.atTop||!B.canScroll)||x||!!v;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{ref:oe,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[At&&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:()=>{Pe()},disabled:!F||x,title:d("terminal.replayScrollbackHint"),children:d(x?"terminal.loadingOlder":"terminal.loadOlderOutput")}),v&&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:v})]}),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}),q&&n.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-2xs font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>$(ye=>!ye),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:()=>{Ee()},disabled:!m,title:d("terminal.copyHint"),children:d("terminal.copy")}),n.jsxs("div",{className:"relative",children:[n.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-2xs font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>E(ye=>!ye),disabled:!m,"aria-label":d(C?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":C,"aria-controls":"terminal-control-keys-popover",title:d("terminal.openControlKeys"),children:d("terminal.keysButton")}),C&&n.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":d("terminal.openControlKeys"),className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-3xs font-semibold uppercase tracking-[0.14em] text-white/45",children:d("terminal.keysPanelTitle")}),n.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-2xs text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>E(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),n.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",P,T],["Alt",M,_],["Shift",I,D]].map(([ye,Ae,Le])=>n.jsx("button",{type:"button","aria-pressed":Ae,className:`h-9 rounded-lg border text-xs font-semibold transition-colors ${Ae?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>Le(Ve=>!Ve),children:ye},ye))}),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:()=>Ye(""),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,j(ye=>{const Ae=Math.max(Ke,Number((ye-.1).toFixed(2)));return Ae>Ke&&$e(),Ae})},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,j(ye=>{const Ae=Math.min(ue,Number((ye+.1).toFixed(2)));return Ae>Ke&&$e(),Ae})},title:d("terminal.growViewport"),children:"+"})]}),n.jsx("div",{ref:ge,className:_e?"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:Be>0?`${Be}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:n.jsx("div",{style:{width:R.width>0?`${R.width}px`:"100%",height:R.height>0?`${R.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:N},children:n.jsx(pf,{ref:s,readOnly:!m||!i,sizingMode:"measured",onViewportMetrics:O,onScrollMetrics:H,onInput:ye=>{!m||(u==null||u(se,F,ye))}})})})}),!m&&n.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-2xs text-red-300 pointer-events-none",children:b})]}),n.jsx(qf,{contextKey:e.tabKey,panelLabel:kt(e),isSending:o,isBusy:!!me,statusMessage:re,inlineStatusMessage:Se,onSend:async ye=>me?!1:r(ye),isActive:l&&i,showControlsToggle:!1,animateVisibility:!1}),L&&n.jsx(I1,{activeConv:e,onClose:()=>$(!1)})]})}const E1=5e3,L1=12e3,D1=15e3;function O1(e){return e==="disconnected"||e==="reconnecting"}function $1({wsStatus:e,showReconnected:t,loginUrl:s,onReconnect:r,reconnectDelayMs:o=E1,reconnectActionDelayMs:a=L1}){const{t:i}=he(),l=O1(e),[d,u]=c.useState(()=>!l||o<=0),[m,h]=c.useState(()=>!l||a<=0),p=c.useRef(!1),[b,f]=c.useState(!1);c.useEffect(()=>{if(!l){u(!1);return}if(p.current=!1,o<=0){p.current=!0,u(!0);return}u(!1);const C=setTimeout(()=>{p.current=!0,u(!0)},o);return()=>clearTimeout(C)},[o,l]),c.useEffect(()=>{if(!l){h(!1);return}if(a<=0){h(!0);return}h(!1);const C=setTimeout(()=>{h(!0)},a);return()=>clearTimeout(C)},[a,l]),c.useEffect(()=>{e!=="reconnecting"&&f(!1)},[e]),c.useEffect(()=>{if(!b)return;const C=setTimeout(()=>f(!1),D1);return()=>clearTimeout(C)},[b]);const x=()=>{f(!0),r==null||r()},g=l?d:e==="offline"||e==="auth_failed",v=!!(r&&e!=="auth_failed"&&(!l||m)),S=c.useMemo(()=>!t||e!=="connected"?!1:o<=0||p.current,[o,t,e]),A=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))"},w={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},y={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},N="fixed left-1/2 top-[calc(env(safe-area-inset-top,0px)+64px)] sm:top-[calc(env(safe-area-inset-top,0px)+16px)] z-[var(--z-toast)] flex items-center justify-center pointer-events-none",j={transform:"translateX(-50%)"};return n.jsxs(n.Fragment,{children:[g&&n.jsx("div",{className:N,style:j,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[A],border:w[A],color:y[A]},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"))]}),v&&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(nn,{size:11,thickness:2,color:"muted"}),i(b?"connection.reconnecting":"connection.reconnectNow")]})]})}),S&&n.jsx("div",{className:N,style:j,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 F1(){const e=c.useSyncExternalStore(s_,fm,fm),{t}=he("common");return e.reloadRequired?n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal,1000)] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4",role:"alertdialog","aria-modal":"true","aria-labelledby":"dashboard-wire-reload-title","data-testid":"dashboard-wire-reload-overlay",children:n.jsxs("div",{className:"max-w-[420px] w-full rounded-2xl border border-border-default bg-bg-primary p-5 shadow-2xl text-text-primary",children:[n.jsx("h2",{id:"dashboard-wire-reload-title",className:"text-base font-semibold mb-2",children:t("app.dashboardWire.reloadTitle")}),n.jsx("p",{className:"text-sm text-text-secondary mb-4",children:t("app.dashboardWire.reloadBody")}),n.jsx("button",{type:"button",className:"w-full rounded-lg px-3 py-2 text-sm font-semibold bg-accent-primary text-white hover:opacity-90",onClick:()=>window.location.reload(),children:t("app.dashboardWire.reload")})]})}):e.daemonUpdateRequired.length===0?null:n.jsxs("div",{className:"fixed left-1/2 top-[calc(env(safe-area-inset-top,0px)+12px)] z-[var(--z-toast)] max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-4 py-2.5 text-[13px] leading-[1.6] shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{transform:"translateX(-50%)",background:"color-mix(in srgb, var(--status-warning, #f59e0b) 14%, var(--bg-primary))",border:"1px solid color-mix(in srgb, var(--status-warning, #f59e0b) 40%, transparent)"},role:"status","data-testid":"dashboard-wire-daemon-update",children:[n.jsx("div",{className:"font-semibold",children:t("app.dashboardWire.daemonUpdateTitle")}),n.jsx("div",{className:"text-text-secondary",children:t("app.dashboardWire.daemonUpdateBody",{count:e.daemonUpdateRequired.length})})]})}function Li(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Hb(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 Bb(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 Wb(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 H1(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 B1(e){var t;return e.category!=="cli"||!Hb(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function Wn(e){var r;const t=new Set,s=[];for(const o of e||[]){if(!B1(o))continue;const a=Hb(o);if(!a||t.has(a))continue;t.add(a);const i=String(o.displayName||o.name||a),l=o.detectedPath||((r=o.lastDetection)==null?void 0:r.path)||null;s.push({type:a,label:i,icon:o.icon,statusLabel:l?`Detected at ${l}`:"Detected on this machine",detectedPath:l,...Array.isArray(o.modelOptions)&&o.modelOptions.length?{modelOptions:o.modelOptions}:{},...Array.isArray(o.thinkingLevelOptions)&&o.thinkingLevelOptions.length?{thinkingLevelOptions:o.thinkingLevelOptions}:{}})}return s}function Eo(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],s=new Set,r=[];for(const o of t){const a=typeof o=="string"?o.trim():"";!a||s.has(a)||(s.add(a),r.push(a))}return r}function Ks(e){return e.map(t=>t.type)}function W1(e,t){const s=Eo(e),r=t.trim();return!r||s.includes(r)?s:[...s,r]}function U1(e,t){return Eo(e).filter(s=>s!==t)}function Lm(e,t,s){const r=Eo(e),o=r.indexOf(t);if(o<0)return r;const a=r.filter(l=>l!==t);if(s==="top")return[t,...a];if(s==="bottom")return[...a,t];const i=s==="up"?Math.max(0,o-1):Math.min(a.length,o+1);return a.splice(i,0,t),a}const K1="Assistant",q1="claude-cli",z1="launch_assistant";function Ub(e){var t;return e?e.assistant===!0||((t=e.settings)==null?void 0:t.assistant)===!0:!1}function wr(e){return Ub(e)}function Kb(e,t){return Number(wr(t))-Number(wr(e))}function qb(e){return e.some(wr)}function zb(){return{fresh:new Set,pinned:new Set}}function Vb(e,t){const s=[];for(const r of e){const o=r.tabKey;!t.fresh.has(o)||t.pinned.has(o)||!wr(r)||(t.pinned.add(o),t.fresh.delete(o),s.push(o))}return s}function V1(e){const t=String(e.status||"").toLowerCase();return t!=="offline"&&t!=="disconnected"}function G1(e){const t=e.assistant;return{cliType:e.type,label:e.displayName||e.name||e.type,supported:t?t.supported===!0:!0,...t&&!t.supported&&t.reason?{reason:t.reason}:{},promptOnly:t?t.toolRestriction==="prompt_only":!1,modelOptions:Bb([e],e.type),thinkingLevelOptions:Wb([e],e.type)}}function Ya(e,t,s){const r=s!=null&&s.model&&t.modelOptions.includes(s.model)?s.model:void 0,o=s!=null&&s.thinkingLevel&&t.thinkingLevelOptions.includes(s.thinkingLevel)?s.thinkingLevel:void 0;return{machineId:e,cliType:t.cliType,...r?{model:r}:{},...o?{thinkingLevel:o}:{}}}function Y1(e){return{cliType:e.cliType,...e.model?{model:e.model}:{},...e.thinkingLevel?{thinkingLevel:e.thinkingLevel}:{}}}function Q1(e,t){const s={};for(const r of e){if(!r)continue;const o=t.find(a=>!!(a!=null&&a.id)&&en(a.id,r));o&&(s[o.id]=(s[o.id]||0)+1)}return s}function J1(e,t){const s=[];for(const r of e){if(!(r!=null&&r.id)||!V1(r))continue;const o=(r.availableProviders||[]).filter(i=>Li(i,"cli")).map(G1);if(o.length===0)continue;const a=i=>(i.supported?0:2)+(i.cliType===q1?0:1);o.sort((i,l)=>a(i)-a(l)),s.push({machineId:r.id,label:pn(r,{fallbackId:r.id}),clis:o,hostedProjects:(t==null?void 0:t[r.id])||0})}return s.sort((r,o)=>o.hostedProjects-r.hostedProjects)}function X1(e,t,s){const r=J1(e,s),o=(a,i)=>a.clis.find(l=>l.supported&&(!i||l.cliType===i));if(t!=null&&t.cliType){const a=t.machineId?r.filter(i=>i.machineId===t.machineId):r;for(const i of a){const l=o(i,t.cliType);if(l)return{machines:r,defaultTarget:Ya(i.machineId,l,t)}}}for(const a of r){const i=o(a);if(i)return{machines:r,defaultTarget:Ya(a.machineId,i)}}return{machines:r,defaultTarget:null}}const Gb="adhdev_assistant_launch_choice";function Z1(e=typeof localStorage<"u"?localStorage:void 0){try{const t=e==null?void 0:e.getItem(Gb);if(!t)return null;const s=JSON.parse(t);if(!s||typeof s.cliType!="string"||!s.cliType)return null;const r=o=>typeof s[o]=="string"&&s[o]?{[o]:s[o]}:{};return{cliType:s.cliType,...r("machineId"),...r("model"),...r("thinkingLevel")}}catch{return null}}function eA(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(Gb,JSON.stringify({machineId:e.machineId,cliType:e.cliType,...e.model?{model:e.model}:{},...e.thinkingLevel?{thinkingLevel:e.thinkingLevel}:{}}))}catch{}}function tA(e,t){return!!t&&!qb(e)}const Nc=280;function nA({onStart:e,onStartWith:t,machines:s=[],defaultTarget:r=null,pending:o=!1,error:a=null}){var C,E,P;const{t:i}=he("common"),[l,d]=c.useState(!1),[u,m]=c.useState(null),[h,p]=c.useState(null),b=c.useRef(null),f=c.useRef(null),x=s.length>1,g=!!t&&s.some(T=>T.clis.length>0),v=r?((E=(C=s.find(T=>T.machineId===r.machineId))==null?void 0:C.clis.find(T=>T.cliType===r.cliType))==null?void 0:E.label)||r.cliType:"",S=v&&(r!=null&&r.model)?`${v} · ${r.model}`:v,A=u?(P=s.find(T=>T.machineId===u.machineId))==null?void 0:P.clis.find(T=>T.cliType===u.cliType&&T.supported):void 0,k=()=>{l||m(r),d(!l)},w=(T,M)=>{!u||!A||m(Ya(u.machineId,A,{...u,[T]:M||void 0}))},y=c.useCallback((T=!1)=>{var M;d(!1),T&&((M=b.current)==null||M.focus())},[]);c.useLayoutEffect(()=>{var _;if(!l||typeof window>"u"){p(null);return}const T=(_=b.current)==null?void 0:_.getBoundingClientRect();if(!T)return;const M=Math.min(Math.max(8,T.left),window.innerWidth-Nc-8);p({top:T.bottom+6,left:Math.max(8,M)})},[l]),c.useEffect(()=>{if(!l||typeof window>"u")return;const T=I=>{I.key==="Escape"&&(I.stopPropagation(),y(!0))},M=I=>{var L,$;const D=I.target;D&&((L=b.current)!=null&&L.contains(D)||($=f.current)!=null&&$.contains(D)||y())},_=()=>y();return window.addEventListener("keydown",T,!0),document.addEventListener("mousedown",M,!0),window.addEventListener("resize",_),()=>{window.removeEventListener("keydown",T,!0),document.removeEventListener("mousedown",M,!0),window.removeEventListener("resize",_)}},[y,l]),c.useEffect(()=>{var M;if(!l)return;const T=f.current;(M=(T==null?void 0:T.querySelector('[role="menuitemradio"][aria-checked="true"]:not([disabled])'))??(T==null?void 0:T.querySelector('[role="menuitemradio"]:not([disabled])')))==null||M.focus()},[l,h]);const N=T=>{var D,L,$;if(T.key!=="ArrowDown"&&T.key!=="ArrowUp"||((L=(D=T.target)==null?void 0:D.getAttribute)==null?void 0:L.call(D,"role"))!=="menuitemradio")return;T.preventDefault();const M=Array.from((($=f.current)==null?void 0:$.querySelectorAll('[role="menuitemradio"]:not([disabled])'))??[]);if(M.length===0)return;const _=M.indexOf(document.activeElement),I=M[(_+(T.key==="ArrowDown"?1:-1)+M.length)%M.length];I==null||I.focus()},j=a?i("dashboard.assistant.startFailed",{error:a}):S?`${i("dashboard.assistant.startHint")} · ${i("dashboard.assistantLaunch.startWith",{cli:S})}`:i("dashboard.assistant.startHint");return n.jsxs("span",{className:"ml-2 inline-flex items-stretch","data-testid":"dashboard-start-assistant-group",children:[n.jsxs("button",{type:"button",onClick:e,disabled:o,className:ct("btn btn-secondary btn-sm inline-flex items-center gap-1.5",g&&"rounded-r-none"),title:j,"aria-label":i("dashboard.assistant.start"),"data-testid":"dashboard-start-assistant",children:[n.jsx(pl,{size:14}),n.jsx("span",{children:i(o?"dashboard.assistant.starting":"dashboard.assistant.start")})]}),g&&n.jsx("button",{ref:b,type:"button",onClick:k,disabled:o,className:"btn btn-secondary btn-sm rounded-l-none border-l border-border-default px-1.5 inline-flex items-center",title:i("dashboard.assistantLaunch.chooseCli"),"aria-label":i("dashboard.assistantLaunch.chooseCli"),"aria-haspopup":"menu","aria-expanded":l,"data-testid":"dashboard-start-assistant-menu",children:n.jsx(gi,{size:12,className:"-rotate-90"})}),l&&g&&typeof document<"u"&&An.createPortal(n.jsxs("div",{ref:f,role:"menu","aria-label":i("dashboard.assistantLaunch.chooseCli"),onKeyDown:N,"data-testid":"dashboard-start-assistant-options",className:"fixed z-[var(--z-popover)] flex max-h-[70vh] flex-col rounded-xl border border-border-default bg-bg-card p-1 shadow-xl backdrop-blur-xl",style:h?{top:h.top,left:h.left,width:Nc}:{top:-9999,left:-9999,width:Nc,visibility:"hidden"},children:[n.jsx("div",{className:"flex min-h-0 flex-col overflow-y-auto",children:s.map(T=>n.jsxs("div",{role:"group","aria-label":T.label,className:"flex flex-col",children:[x&&n.jsxs("div",{className:"flex min-w-0 items-baseline gap-1.5 px-2.5 pb-1 pt-2 text-2xs text-text-muted",children:[n.jsx("span",{className:"truncate font-semibold uppercase tracking-wide",children:T.label}),T.hostedProjects>0&&n.jsx("span",{className:"shrink-0 font-normal",title:i("dashboard.assistantLaunch.hostsProjectsHint"),"data-testid":"assistant-machine-hosts-projects",children:i("dashboard.assistantLaunch.hostsProjects",{count:T.hostedProjects})})]}),T.clis.map(M=>{const _=!!u&&u.machineId===T.machineId&&u.cliType===M.cliType;return n.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":_,disabled:!M.supported,"data-assistant-cli":M.cliType,"data-assistant-machine":T.machineId,title:M.supported?M.promptOnly?i("dashboard.assistantLaunch.noToolLockHint"):void 0:i("dashboard.assistantLaunch.unavailable",{reason:M.reason||i("dashboard.assistantLaunch.unsupported")}),onClick:()=>{if(!M.supported)return;const I=r&&r.machineId===T.machineId&&r.cliType===M.cliType;m(Ya(T.machineId,M,I?r:null))},className:ct("flex w-full items-start gap-2.5 rounded-lg border-none bg-transparent px-2.5 py-2 text-left text-xs font-medium text-text-secondary transition-colors",M.supported?"hover:bg-bg-secondary hover:text-text-primary focus-visible:bg-bg-secondary focus-visible:text-text-primary focus-visible:outline-none":"cursor-not-allowed opacity-50"),children:[n.jsx("span",{className:"mt-0.5 flex w-4 shrink-0 justify-center","aria-hidden":!0,children:_?n.jsx(Cr,{size:13}):null}),n.jsxs("span",{className:"flex min-w-0 flex-col",children:[n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx("span",{className:"truncate",children:M.label}),M.supported&&M.promptOnly&&n.jsx("span",{className:"shrink-0 rounded border border-border-default px-1 text-2xs text-text-muted","data-testid":"assistant-cli-no-tool-lock",children:i("dashboard.assistantLaunch.noToolLock")})]}),!M.supported&&n.jsx("span",{className:"line-clamp-2 text-2xs font-normal text-text-muted","data-testid":"assistant-cli-unavailable-reason",children:M.reason||i("dashboard.assistantLaunch.unsupported")})]})]},M.cliType)})]},T.machineId))}),u&&A&&n.jsxs("div",{className:"mt-1 flex flex-col gap-1.5 border-t border-border-default px-1.5 pb-1 pt-2","data-testid":"assistant-launch-options",children:[(A.modelOptions.length>0||A.thinkingLevelOptions.length>0)&&n.jsxs("div",{className:"flex gap-1.5",children:[A.modelOptions.length>0&&n.jsxs("label",{className:"flex min-w-0 flex-1 flex-col gap-0.5 text-2xs text-text-muted",children:[i("dashboard.assistantLaunch.model"),n.jsxs("select",{value:u.model??"",onChange:T=>w("model",T.target.value),className:"min-w-0 rounded-md border border-border-default bg-bg-secondary px-1.5 py-1 text-xs text-text-primary","data-testid":"assistant-launch-model",children:[n.jsx("option",{value:"",children:i("dashboard.assistantLaunch.defaultOption")}),A.modelOptions.map(T=>n.jsx("option",{value:T,children:T},T))]})]}),A.thinkingLevelOptions.length>0&&n.jsxs("label",{className:"flex w-[88px] shrink-0 flex-col gap-0.5 text-2xs text-text-muted",children:[i("dashboard.assistantLaunch.thinking"),n.jsxs("select",{value:u.thinkingLevel??"",onChange:T=>w("thinkingLevel",T.target.value),className:"min-w-0 rounded-md border border-border-default bg-bg-secondary px-1.5 py-1 text-xs text-text-primary","data-testid":"assistant-launch-thinking",children:[n.jsx("option",{value:"",children:i("dashboard.assistantLaunch.defaultOption")}),A.thinkingLevelOptions.map(T=>n.jsx("option",{value:T,children:T},T))]})]})]}),n.jsxs("button",{type:"button",onClick:()=>{y(),t==null||t(u)},className:"btn btn-primary btn-sm inline-flex items-center justify-center gap-1.5","data-testid":"assistant-launch-start",children:[n.jsx(pl,{size:13}),n.jsx("span",{children:i("dashboard.assistantLaunch.start")})]})]})]}),document.body)]})}function Yb({mode:e,onChange:t,compact:s=!1}){const{t:r}=he("common"),o=s?14:15;return n.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:r(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?n.jsx(bd,{size:o}):n.jsx(Cn,{size:o})})}function sA(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 rA(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 oA(e){switch(e){case"conflict":return"border-status-error/40 bg-status-error/10 text-status-error";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-status-online/40 bg-status-online/10 text-status-online"}}function Od({git:e,className:t="",compact:s=!1}){const r=sA(e),o=rA(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 ${oA(o)} ${t}`.trim(),title:a.join(" · ")||r,"data-git-tone":o,children:[n.jsx("span",{"aria-hidden":"true",children:"⑂"}),n.jsx("span",{className:"truncate",children:r})]})}const _s=8,Dm=6;function aA(e,t,s){const r=Math.max(_s,s.width-t.width-_s),o=e.left+e.width/2-t.width/2,a=Math.min(Math.max(_s,o),r),i=e.bottom+Dm,l=i+t.height<=s.height-_s,d=e.top-Dm-t.height;return!l&&d>=_s?{top:d,left:a,placement:"above"}:{top:Math.max(_s,Math.min(i,s.height-t.height-_s)),left:a,placement:"below"}}function $d(){const e=c.useRef(null),t=c.useRef(null),[s,r]=c.useState({pinned:!1,peeking:!1}),[o,a]=c.useState(null),i=s.pinned||s.peeking,l=c.useCallback(()=>r({pinned:!1,peeking:!1}),[]),d=c.useCallback(()=>r(h=>h.pinned?{pinned:!1,peeking:!1}:{pinned:!0,peeking:!1}),[]),u=c.useCallback(h=>r(p=>p.peeking===h?p:{...p,peeking:h}),[]),m=c.useCallback(()=>{const h=e.current,p=t.current;if(!h||!p||typeof window>"u")return;const b=h.getBoundingClientRect(),f=p.getBoundingClientRect();a(aA({top:b.top,bottom:b.bottom,left:b.left,width:b.width},{width:f.width,height:f.height},{width:window.innerWidth,height:window.innerHeight}))},[]);return c.useLayoutEffect(()=>{if(!i){a(null);return}m()},[i,m]),c.useEffect(()=>{if(!i||typeof window>"u")return;const h=f=>{var x,g;f.key==="Escape"&&(f.stopPropagation(),f.preventDefault(),l(),(g=(x=e.current)==null?void 0:x.focus)==null||g.call(x))},p=f=>{var g,v;const x=f.target;x&&((g=e.current)!=null&&g.contains(x)||(v=t.current)!=null&&v.contains(x)||l())},b=()=>m();return window.addEventListener("keydown",h,!0),document.addEventListener("pointerdown",p,!0),document.addEventListener("mousedown",p,!0),window.addEventListener("resize",b),window.addEventListener("scroll",b,!0),()=>{window.removeEventListener("keydown",h,!0),document.removeEventListener("pointerdown",p,!0),document.removeEventListener("mousedown",p,!0),window.removeEventListener("resize",b),window.removeEventListener("scroll",b,!0)}},[l,i,m]),{anchorRef:e,popoverRef:t,open:i,pinned:s.pinned,position:o,close:l,togglePinned:d,setPeeking:u}}function Fd({id:e,popoverRef:t,position:s,children:r,className:o,role:a="tooltip",ariaLabel:i}){return typeof document>"u"?null:An.createPortal(n.jsx("div",{ref:t,id:e,role:a,"aria-label":i,"data-placement":(s==null?void 0:s.placement)??"below",className:ct("fixed z-[var(--z-tooltip)] max-w-[min(20rem,calc(100vw-16px))] rounded-lg border border-border-default bg-bg-card px-3 py-2 text-xs leading-relaxed text-text-secondary shadow-xl backdrop-blur-xl","whitespace-pre-line break-words normal-case tracking-normal font-normal text-left",o),style:s?{top:s.top,left:s.left}:{top:-9999,left:-9999,visibility:"hidden"},children:r}),document.body)}function Qb(e){return e==null||e===!1||e===""}function rt({content:e,label:t,size:s=13,className:r,popoverClassName:o}){const{t:a}=he("common"),i=c.useId(),l=`${i}-pop`,d=`${i}-desc`,{anchorRef:u,popoverRef:m,open:h,position:p,togglePinned:b,setPeeking:f}=$d();return Qb(e)?null:n.jsxs("span",{className:"inline-flex items-center align-middle",children:[n.jsx("button",{ref:x=>{u.current=x},type:"button","data-infotip":"","aria-label":t??a("common.moreInfo"),"aria-expanded":h,"aria-controls":h?l:void 0,"aria-describedby":d,onClick:x=>{x.preventDefault(),x.stopPropagation(),b()},onPointerEnter:x=>{x.pointerType==="mouse"&&f(!0)},onPointerLeave:x=>{x.pointerType==="mouse"&&f(!1)},className:ct("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded-full border-none bg-transparent p-0 text-text-muted transition-colors hover:text-text-primary focus-visible:text-text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent",h&&"text-text-primary",r),children:n.jsx(Co,{size:s})}),n.jsx("span",{id:d,className:"sr-only",children:e}),h&&n.jsx(Fd,{id:l,popoverRef:m,position:p,className:o,children:e})]})}function Qt({content:e,children:t,className:s,popoverClassName:r}){const o=c.useId(),a=`${o}-pop`,i=`${o}-desc`,{anchorRef:l,popoverRef:d,open:u,position:m,togglePinned:h,setPeeking:p}=$d();if(Qb(e))return n.jsx(n.Fragment,{children:t});const b=n.jsx("span",{ref:f=>{l.current=f},"data-tooltip":"",tabIndex:0,"aria-describedby":i,className:ct("inline-flex max-w-full cursor-default items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-accent/60",s),onPointerEnter:f=>{f.pointerType==="mouse"&&p(!0)},onPointerLeave:f=>{f.pointerType==="mouse"&&p(!1)},onPointerUp:f=>{f.pointerType!=="mouse"&&h()},onFocus:()=>p(!0),onBlur:()=>p(!1),onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),h())},children:t});return n.jsxs(n.Fragment,{children:[b,n.jsx("span",{id:i,className:"sr-only",children:e}),u&&n.jsx(Fd,{id:a,popoverRef:d,position:m,className:r,children:e})]})}function e3({children:e,content:t,label:s,className:r,popoverClassName:o}){const i=`${c.useId()}-pop`,{anchorRef:l,popoverRef:d,open:u,position:m,togglePinned:h}=$d();return n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:p=>{l.current=p},type:"button","aria-label":s,"aria-expanded":u,"aria-haspopup":"dialog","aria-controls":u?i:void 0,onClick:p=>{p.preventDefault(),p.stopPropagation(),h()},className:r,children:e}),u&&n.jsx(Fd,{id:i,popoverRef:d,position:m,role:"dialog",ariaLabel:s,className:ct("whitespace-normal",o),children:t})]})}function Jb({value:e,live:t=!0,fallback:s="",className:r}){const{i18n:o}=he("common"),[,a]=c.useState(0),i=_o(e);if(c.useEffect(()=>{if(!t||i===null||typeof window>"u")return;const d=window.setInterval(()=>a(u=>u+1),3e4);return()=>window.clearInterval(d)},[t,i]),i===null)return s?n.jsx("span",{className:r,children:s}):null;const l=(o==null?void 0:o.resolvedLanguage)||(o==null?void 0:o.language);return n.jsx(Qt,{content:To(i,{locale:l,seconds:!0}),children:n.jsx("time",{dateTime:new Date(i).toISOString(),className:r,children:Ha(i,{locale:l})})})}async function Xb(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 Zb({value:e,label:t,className:s}){const{t:r}=he("common"),[o,a]=c.useState(!1),i=c.useRef(null);return c.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),n.jsx("button",{type:"button",onClick:async l=>{l.stopPropagation(),await Xb(e)&&(a(!0),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500))},title:e,"aria-label":`${t??r("common.copyId")}: ${e}`,className:ct("inline-flex shrink-0 items-center rounded-md border border-border-subtle bg-transparent px-1.5 py-0.5 text-3xs font-medium text-text-muted transition-colors hover:border-border-default hover:text-text-primary",s),children:n.jsx("span",{"aria-live":"polite",children:o?r("common.copied"):t??r("common.copyId")})})}function Hd({rows:e=[],children:t,summary:s,className:r,summaryClassName:o}){const{t:a}=he("common"),i=e.filter(l=>typeof l.value=="string"&&l.value);return i.length===0&&!t?null:n.jsxs("details",{className:ct("group text-xs",r),"data-technical-details":"",children:[n.jsxs("summary",{className:ct("cursor-pointer select-none list-none text-3xs font-medium uppercase tracking-wide text-text-muted [&::-webkit-details-marker]:hidden",o),children:[n.jsx("span",{className:"mr-1 inline-block transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),s??a("common.technicalDetails")]}),n.jsxs("div",{className:"mt-2 flex flex-col gap-1.5",children:[i.map(l=>n.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[n.jsx("span",{className:"shrink-0 text-3xs text-text-muted",children:l.label}),n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx("span",{className:"min-w-0 truncate font-mono text-3xs text-text-secondary",title:l.value,children:l.value}),l.copyable!==!1&&n.jsx(Zb,{value:l.value})]})]},l.label)),t]})]})}function eg(e){const t=e.replace(/[\\/]+$/,""),s=t.split(/[\\/]/);return s[s.length-1]||t||e}const iA=c.createContext(null);function Bd(){return c.useContext(iA)}function cA(e){const t=e.replace(/^(daemon_|standalone_)/,"");return t.length<=20?t:`${t.slice(0,17)}…`}function lA(e){return wy(e)}function dA(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 uA(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 Qa(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=dA(e);return t.outOfSync?"degraded":t.dirty||uA(e)?"dirty":"online"}function mA(e,t){const s=t?Qa(t):void 0;return!e||e==="unknown"?s:e}function hA(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(Oa).filter(i=>i!==null);if(a.length>0)return a}const s=et(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=Oa(r);return o?[o]:void 0}function pA(e){const t=et(e.connection);return Object.keys(t).length>0?t:void 0}function fA(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 tg(e){var s;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((s=t.submodules)==null?void 0:s.length)??0)>0))}function Om(e){var r,o,a,i,l,d;let t=0;const s=e.git;return tg(e)&&(t+=80,(s==null?void 0:s.isGitRepo)===!0&&(t+=20),(s==null?void 0:s.isGitRepo)===!1&&(t+=5),s!=null&&s.branch&&(t+=20),s!=null&&s.upstream&&(t+=12),s!=null&&s.headCommit&&(t+=12),t+=cd(s==null?void 0:s.upstreamStatus),typeof(s==null?void 0:s.lastCheckedAt)=="number"&&(t+=6),t+=(((r=s==null?void 0:s.submodules)==null?void 0:r.length)??0)*6),(o=e.branchConvergence)!=null&&o.status&&(t+=12),(((a=e.connection)==null?void 0:a.state)==="connected"||((i=e.connection)==null?void 0:i.state)==="self")&&(t+=8),((l=e.connection)==null?void 0:l.transport)==="direct"&&(t+=4),((d=e.connection)==null?void 0:d.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function bA(e,t){var f,x,g,v;const s=Om(e),o=Om(t)>s?t:e,a=o===t?e:t,i=o.git??a.git,l=(((f=o.providers)==null?void 0:f.length)??0)>0?o.providers:a.providers,d=(((x=o.activeSessions)==null?void 0:x.length)??0)>0?o.activeSessions:a.activeSessions,u=(((g=o.activeSessionDetails)==null?void 0:g.length)??0)>0?o.activeSessionDetails:a.activeSessionDetails,m=(((v=o.providerPriority)==null?void 0:v.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")?Qa(i):o.health,providers:l??[],activeSessions:d??[],...u&&u.length>0?{activeSessionDetails:u}:{},...m&&m.length>0?{providerPriority:m}:{},...h?{connection:h}:{},...i?{git:i}:{}},b=et(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 gA=new Set(["self","local","member_push","coordinator_probe","none"]);function Ol(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function $m(e){const t=et(e),s=je(t.source);if(!s||!gA.has(s))return null;const r=je(t.lastRefreshError);return{source:s,observedAt:Ol(t.observedAt),refreshing:t.refreshing===!0,unreachableSince:Ol(t.unreachableSince),...r?{lastRefreshError:r}:{}}}function ng(e){const t=et(e),s=je(t.nodeId,t.id);if(!s)return null;const r=et(t.cachedStatus),o=lA(t),a=o?void 0:ya(et(t.git),t)??ya(t,t),i=o??a,l=i?void 0:ya(et(r.git),t),d=i??l,u=je(t.machineStatus,t.machine_status,r.machineStatus,r.machine_status),m=je(t.health),h=o?Qa(d):mA(m,i)||(d?Qa(d):void 0)||je(r.health)||u||je(t.status)||"unknown",b=(o?void 0:je(t.error))??(i?void 0:je(r.error)),f=hA(t),x=sc(t.activeSessions),g=(f==null?void 0:f.map(j=>j.sessionId))??[],v=sc(t.providerPriority),S=Vt(t.gitProbePending,t.git_probe_pending),A=i?void 0:S,k=pA(t),w=et(t.branchConvergence??t.branch_convergence),y=k==null?void 0:k.state,N=o&&(!(k!=null&&k.reported)||y==="unknown")?fA(k):k;return{nodeId:s,machineLabel:je(t.machineLabel,t.machine_label,t.hostname)||cA(je(t.daemonId,t.daemon_id,t.machineId,t.machine_id,s)||s),workspace:je(t.workspace,d==null?void 0:d.workspace)||"",...je(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:je(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...je(t.daemonId,t.daemon_id)?{daemonId:je(t.daemonId,t.daemon_id)}:{},...je(t.machineId,t.machine_id)?{machineId:je(t.machineId,t.machine_id)}:{},...u?{machineStatus:u}:{},...Vt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Vt(t.isLocalWorktree,t.is_local_worktree)}:{},...je(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:je(t.worktreeBranch,t.worktree_branch)}:{},...je(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:je(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:h,...d?{git:d}:{},...A!==void 0?{gitProbePending:A}:{},providers:sc(t.providers),activeSessions:x.length>0?x:g,...f&&f.length>0?{activeSessionDetails:f}:{},...v.length>0?{providerPriority:v}:{},...Vt(t.launchReady)!==void 0?{launchReady:Vt(t.launchReady)}:o?{launchReady:!0}:{},...je(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)?{lastSeenAt:je(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)}:{},...je(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)?{updatedAt:je(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)}:{},...N?{connection:N}:{},...Object.keys(w).length>0?{branchConvergence:w}:{},...t.scheduling&&typeof t.scheduling=="object"?{scheduling:t.scheduling}:{},...Vt(t.autoFastForwardEligible,t.auto_fast_forward_eligible)===!0?{autoFastForwardEligible:!0}:{},...t.worktreeBootstrap&&typeof t.worktreeBootstrap=="object"?{worktreeBootstrap:t.worktreeBootstrap}:{},...t.staleDaemonBuild&&typeof t.staleDaemonBuild=="object"?{staleDaemonBuild:t.staleDaemonBuild}:{},...t.providerVersions&&typeof t.providerVersions=="object"&&!Array.isArray(t.providerVersions)?{providerVersions:t.providerVersions}:{},...je(t.daemonBuildVersion,t.daemon_build_version)?{daemonBuildVersion:je(t.daemonBuildVersion,t.daemon_build_version)}:{},...t.nodeFacts&&typeof t.nodeFacts=="object"&&!Array.isArray(t.nodeFacts)?{nodeFacts:t.nodeFacts}:{},...$m(t.gitObservation)?{gitObservation:$m(t.gitObservation)}:{},...Fm(t.heldRuntime??t.held_runtime)?{heldRuntime:Fm(t.heldRuntime??t.held_runtime)}:{},...je(t.role)?{role:je(t.role)}:{},...je(t.nodeLabel,t.node_label)?{nodeLabel:je(t.nodeLabel,t.node_label)}:{},...b?{error:b}:{}}}const xA=new Set(["member_push","coordinator_probe","none"]);function Fm(e){const t=et(e);if(Object.keys(t).length===0)return null;const s=je(t.source)||"none";if(!xA.has(s))return null;const r=Array.isArray(t.sessions)?t.sessions.filter(o=>Object.keys(et(o)).length>0):[];return{...t,source:s,observedAt:Ol(t.observedAt),refreshing:t.refreshing===!0,sessions:r}}function yA(e,t,s){const r=et(e),o=et(r.settings),a=et(r.activeChat),i=je(et(r.coordinator).meshId,o.meshCoordinatorFor),l=t&&i===t?"coordinator":t&&je(o.meshNodeFor)===t?"worker":void 0,d=Oa({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 vA(e,t,s,r){const o=et(e),a=et(o.settings),i=je(a.meshNodeId);return i?i===s.nodeId:!r||!t?!1:je(et(o.coordinator).meshId,a.meshCoordinatorFor)===t||je(a.meshNodeFor)===t}function sg(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=>vA(d,e,r,a)).map(d=>yA(d,e,r.workspace||void 0)).filter(d=>d!==null);if(i.length===0)return r;const l=Ja([...r.activeSessionDetails??[],...i]);return{...r,activeSessionDetails:l,activeSessions:Ja([...l,...(r.activeSessions??[]).map(d=>({sessionId:d}))]).map(d=>d.sessionId)}})}function Ja(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 rg(e,t){const s=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],r=s.map(Oa).filter(o=>o!==null);return r.length===0?t:t.map(o=>{const a=r.filter(l=>{const d=et(s.find(p=>{const b=et(p);return je(b.sessionId,b.session_id,b.id)===l.sessionId})),u=je(d.nodeId,d.node_id),m=je(d.daemonId,d.daemon_id),h=je(d.workspace);return u&&u===o.nodeId?!0:en(m,o.daemonId)?!h||!o.workspace||h===o.workspace:!!(h&&o.workspace&&h===o.workspace)});if(a.length===0)return o;const i=Ja([...o.activeSessionDetails??[],...a]);return{...o,activeSessionDetails:i,activeSessions:Ja([...o.activeSessionDetails??[],...a,...(o.activeSessions??[]).map(l=>({sessionId:l}))]).map(l=>l.sessionId)}})}function wA(e){const t=et(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||je(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||Vt(t.is_local_worktree)!==void 0}function og(e){const t=new Map,s=[];for(const r of e){const o=wA(r)?ng(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=bA(a,o);t.set(o.nodeId,i);const l=s.findIndex(d=>d.nodeId===o.nodeId);l>=0&&(s[l]=i)}return s}function t3(e){const t=e??{},s=og(t.nodes??[]);return{...t,nodes:sg(je(t.meshId)||"",rg(t,s))}}function n3(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:tg(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 SA(e){const t=je(e.meshId,e.mesh_id,e.id),s=e.nodes,r=Array.isArray(s)?s.map(d=>ng(d)).filter(d=>d!==null):null;if(!t||!r)return null;const o=sg(t,rg(e,og(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 kA(e){var a;let t=0;const s=et(e.sourceOfTruth),r=et(s.directPeerTruth);je(s.currentStatus)==="live_git_and_session_probes"&&(t+=100),s.coordinatorOwnsLiveTruth===!0&&(t+=25),r.satisfied===!0&&(t+=15);for(const i of e.nodes){const l=i.git;if(!l){i.gitProbePending&&(t-=8);continue}t+=10,l.isGitRepo===!0&&(t+=5),l.isGitRepo===!1&&(t+=1),l.branch&&(t+=4),l.upstream&&(t+=3),l.headCommit&&(t+=3),t+=cd(l.upstreamStatus),typeof l.ahead=="number"&&(t+=1),typeof l.behind=="number"&&(t+=1),typeof l.lastCheckedAt=="number"&&(t+=2),t+=(((a=l.submodules)==null?void 0:a.length)??0)*2}return t}function jA(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 NA=20;function Hm(e){let t=null;for(const s of e){const r=SA(et(s));if(!r)continue;const o=kA(r),a=jA(r);if(!t){t={status:r,score:o,refreshedAt:a};continue}(Math.abs(o-t.score)<=NA?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 Di(e){const s=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,r=Hm([s==null?void 0:s.status,s]);return r||Hm([e==null?void 0:e.status,e])}function CA(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 _A(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 AA(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 TA(e,t){var o,a;if(!t)return null;const s=Di(e),r=(o=s==null?void 0:s.nodes)==null?void 0:o.find(i=>jy(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 IA={sm:"max-w-md",md:"max-w-lg",lg:"max-w-3xl"},Bm={center:"items-center justify-center",sheet:"items-end justify-center sm:items-center",stretch:"items-stretch justify-center md:items-center"};function Sr({open:e=!0,onClose:t,align:s="center",size:r="md",chrome:o=!0,closeOnBackdrop:a=!0,closeOnEsc:i=!0,ariaLabel:l,ariaLabelledBy:d,overlayClassName:u,surfaceClassName:m,children:h}){c.useEffect(()=>{if(!e||!i)return;const g=v=>{v.key==="Escape"&&t()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[e,i,t]);const p=c.useCallback(g=>{a&&g.target===g.currentTarget&&t()},[a,t]);if(!e)return null;const b=o?ct("fixed inset-0 flex",Bm[s],"bg-black/60 px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",u):ct("fixed inset-0 flex",Bm[s],u),f=o?ct("relative flex max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-2rem)] w-full flex-col overflow-hidden","rounded-xl border border-border-default bg-surface-primary shadow-2xl",IA[r],m):ct(m),x=n.jsx("div",{className:b,style:o?{zIndex:"var(--z-modal-backdrop)"}:void 0,onClick:p,children:n.jsx("div",{role:"dialog","aria-modal":"true","aria-label":l,"aria-labelledby":d,className:f,style:o?{zIndex:"var(--z-modal)"}:void 0,onClick:g=>g.stopPropagation(),children:h})});return typeof document>"u"?x:An.createPortal(x,document.body)}function ag({open:e,onClose:t,size:s="md",title:r,footer:o,children:a,showClose:i=!0,closeOnBackdrop:l=!0,closeOnEsc:d=!0,ariaLabel:u,className:m,contentClassName:h}){const p=r!=null||i;return n.jsxs(Sr,{open:e,onClose:t,size:s,closeOnBackdrop:l,closeOnEsc:d,ariaLabel:r==null?u:void 0,overlayClassName:m,surfaceClassName:h,children:[p&&n.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-4 border-b border-border-default px-5 py-4",children:[n.jsx("div",{className:"min-w-0",children:typeof r=="string"||typeof r=="number"?n.jsx("h2",{className:"truncate text-lg font-bold text-text-primary",children:r}):r}),i&&n.jsx("button",{type:"button",onClick:t,className:"-m-1.5 inline-flex h-11 w-11 shrink-0 items-center justify-center","aria-label":Qe.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(Lt,{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 MA(e){return{meshId:e,daemonId:null,status:null,response:null,loadedAt:null,loading:!1,refreshing:!1,error:null}}function Oi(e){let t=$l.get(e);return t||(t={snapshot:MA(e),inFlight:null,queuedRefresh:null,listeners:new Set},$l.set(e,t)),t}function us(e,t){var r;const s=Oi(e);(r=t.status)!=null&&r.meshName&&u1(e,t.status.meshName),s.snapshot={...s.snapshot,...t};for(const o of[...s.listeners])try{o()}catch{}}function uo(e){var t;return e?((t=$l.get(e))==null?void 0:t.snapshot)??null:null}function RA(e,t){const s=Oi(e);return s.listeners.add(t),()=>{s.listeners.delete(t)}}function PA(e,t,s=null){us(e,{status:t,daemonId:s,loadedAt:t?Date.now():null,error:null})}function EA(e,t,s){us(e,{status:t,daemonId:s,loadedAt:Date.now(),error:null,loading:!1})}function LA(e){Oi(e).snapshot.status||us(e,{loading:!0,error:null})}function DA(e){return e instanceof Error?e.message:typeof e=="string"?e:"Failed to load mesh status"}function $i(e){const{meshId:t,daemonId:s,load:r}=e,o=e.refresh===!0,a=e.extract??(m=>Di(m));if(!t||!s)return Promise.resolve(null);const i=Oi(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,$i(e)))),i.queuedRefresh);const d=i.snapshot.status!==null;us(t,{loading:!d,refreshing:d,error:null});const u=(async()=>{var m;await null;try{const h=await r(s,t,{refresh:o}),p=a(h);return p?(us(t,{status:p,response:h,daemonId:s,loadedAt:Date.now(),error:null}),p):(us(t,{error:"mesh_status returned an unexpected payload."}),null)}catch(h){return us(t,{error:DA(h)}),null}finally{((m=i.inFlight)==null?void 0:m.promise)===u&&(i.inFlight=null),us(t,{loading:!1,refreshing:!1})}})();return i.inFlight={daemonId:s,refresh:o,promise:u},u}const Xa=new Set;function OA(e){if(Xa.size===0)return!1;for(const t of[...Xa])try{t(e)}catch{}return!0}function $A(e){return Xa.add(e),()=>Xa.delete(e)}const ks={used:e=>`${e}% used`,resetsNow:()=>"resets now",resetsInMinutes:e=>`resets in ${e}m`,resetsInHours:(e,t)=>`resets in ${e}h ${t}m`,resetsInDays:(e,t)=>`resets in ${e}d ${t}h`,cue:e=>e,windowReset:()=>"reset · awaiting refresh",usageTokens:e=>`${e} tok`,usageSessions:e=>`${e} sess`,pool:()=>"pool",failureKind:(e,t)=>t,unavailable:()=>"not available on this node",unreadable:()=>"could not read quota",justNow:()=>"just now",agoMinutes:e=>`${e}m ago`,agoHours:(e,t)=>`${e}h ${t}m ago`,agoDays:(e,t)=>`${e}d ${t}h ago`},FA=new Set(["missing-credentials","expired-token","unauthorized","quota-exhausted","rate-limited","network","server","parse","cli-unavailable","unsupported","setup-required","no-data","unknown"]);function Wd(e){const t="machine.quota.text.";return{used:s=>e(`${t}used`,{percent:s}),resetsNow:()=>e(`${t}resetsNow`),resetsInMinutes:s=>e(`${t}resetsInMinutes`,{minutes:s}),resetsInHours:(s,r)=>e(`${t}resetsInHours`,{hours:s,minutes:r}),resetsInDays:(s,r)=>e(`${t}resetsInDays`,{days:s,hours:r}),cue:s=>e(`${t}cue.${s}`),windowReset:()=>e(`${t}windowReset`),usageTokens:s=>e(`${t}usageTokens`,{count:s}),usageSessions:s=>e(`${t}usageSessions`,{count:s}),pool:()=>e(`${t}pool`),failureKind:(s,r)=>FA.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 HA={"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 BA(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 WA(e,t=ks){var i;const s=(i=e.metadata)==null?void 0:i.usage;if(!s||typeof s.days!="number")return null;const r=[];typeof s.totalCostUsd=="number"&&r.push(`$${s.totalCostUsd.toFixed(2)}`);const o=typeof s.inputTokens=="number"?s.inputTokens:null,a=typeof s.outputTokens=="number"?s.outputTokens:null;return(o!==null||a!==null)&&r.push(t.usageTokens(BA((o??0)+(a??0)))),typeof s.sessions=="number"&&r.push(t.usageSessions(s.sessions)),r.length===0?null:`${s.days}d ${r.join(" · ")}`}function kr(e){return HA[e]??e}function Wm(e){return Number.isFinite(e)?e>=90?"danger":e>=70?"warn":"good":"default"}function UA(e,t=Date.now(),s=ks){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;const r=e-t;if(r<=0)return s.resetsNow();const o=Math.round(r/6e4);if(o<60)return s.resetsInMinutes(o);const a=Math.floor(o/60);return a<24?s.resetsInHours(a,o%60):s.resetsInDays(Math.floor(a/24),a%24)}function Ca(e,t=Date.now()){const s=e==null?void 0:e.resetsAt;return typeof s=="number"&&Number.isFinite(s)&&s>0&&s<=t}ks.windowReset();function Um(e){return!!e&&typeof e.usedPercent=="number"&&Number.isFinite(e.usedPercent)}function KA(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 qA(e){return Um(e.session)||Um(e.weekly)?!0:Array.isArray(e.buckets)&&e.buckets.some(t=>!!t&&typeof t.usedPercent=="number"&&Number.isFinite(t.usedPercent))}function zA(e){var t;if(!KA(e)&&qA(e))return"stale";if(((t=e.metadata)==null?void 0:t.lastGoodWindows)===!0)return"refreshing"}function Km(e,t=Date.now(),s=!1,r=ks){if(!e||typeof e.usedPercent!="number"||!Number.isFinite(e.usedPercent))return null;if(Ca(e,t))return r.windowReset();const o=r.used(e.usedPercent.toFixed(1)),a=UA(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 VA(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 GA(e,t=ks){var o;const s=e.buckets;if(!Array.isArray(s)||s.length<2)return[];const r=[];for(const a of s){if(!a||typeof a!="object")continue;const i=Number(a.usedPercent),l=Number(a.windowMinutes);if(!Number.isFinite(i)||!Number.isFinite(l)||l<=0)continue;const u=(o=(typeof a.name=="string"?a.name:"").split("·")[0])==null?void 0:o.trim().replace(/\s+(Models?|Bundled Models?)$/i,"").trim();r.push({label:`${u||t.pool()} ${VA(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 YA(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 QA(e,t=ks){var l;const s=typeof e.error=="string"?e.error.trim():"",r=(l=e.metadata)==null?void 0:l.failureKind,o=typeof r=="string"?r.trim():"",a=o?o.replace(/[_-]+/g," "):"",i=o?t.failureKind(o,a):"";return s&&a&&!s.toLowerCase().includes(a.toLowerCase())?`${s} (${i})`:s||i||(e.status==="unavailable"?t.unavailable():t.unreadable())}function JA(e,t=Date.now(),s=ks){const r=zA(e),o=(b,f,x)=>{const g=Km(b,t,r,s);if(!g)return null;const v=b.usedPercent,S=Ca(b,t);return{key:f,label:`${x} ${g}`,usedPercent:S?null:v,hint:f,tone:S?"default":Wm(v)}},a=o(e.session,"session","5h"),i=o(e.weekly,"weekly","7d"),l=o(e.monthly,"monthly","30d"),d=GA(e,s).map(b=>({key:b.label,label:`${b.label} ${Km(b.window,t,r,s)}`,usedPercent:Ca(b.window,t)?null:b.usedPercent,hint:"bucket",tone:Ca(b.window,t)?"default":Wm(b.usedPercent)})),u=d.length>0?d:[a,i,l].filter(b=>b!==null),m=WA(e,s),h=m?{key:"usage",label:m,usedPercent:null,hint:"usage",tone:"info"}:null,p=a??i??h;return u.length>0?{kind:"chips",cue:r,chips:u,usageLabel:null,message:null,compactChip:p}:h?{kind:"usage",cue:r,chips:[],usageLabel:m,message:null,compactChip:p}:e.status==="ok"?{kind:"okNoWindows",cue:r,chips:[],usageLabel:null,message:YA(e),compactChip:null}:{kind:"failure",cue:r,chips:[],usageLabel:null,message:QA(e,s),compactChip:null}}function Ud(e){return(t,s=Date.now())=>JA(t,s,e)}function s3(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 ig(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[];for(const[s,r]of Object.entries(e))!r||typeof r!="object"||Array.isArray(r)||t.push({provider:s,quota:r});return t.sort((s,r)=>kr(s.provider).localeCompare(kr(r.provider)))}function r3(e,t=Date.now(),s=ks){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;const r=t-e;if(r<0)return s.justNow();const o=Math.floor(r/6e4);if(o<1)return s.justNow();if(o<60)return s.agoMinutes(o);const a=Math.floor(o/60);return a<24?s.agoHours(a,o%60):s.agoDays(Math.floor(a/24),a%24)}function qm(e){return To(e,{seconds:!0})||"—"}function XA({sessionId:e,daemonId:t,conv:s,onClose:r}){var L;const{t:o}=he("common"),a=Ud(Wd(o)),{sendCommand:i}=wt(),l=Bd(),[d,u]=c.useState(!0),[m,h]=c.useState(null),[p,b]=c.useState(null),[f,x]=c.useState(null),[g,v]=c.useState(null),S=c.useMemo(()=>_A(s),[s]),A=c.useMemo(()=>AA(s),[s]),k=c.useCallback(async()=>{u(!0),b(null);try{const $=await i(t,"get_session_info",{targetSessionId:e}),q=$&&typeof $=="object"?$:{},G=q.result&&typeof q.result=="object"?q.result:q;G!=null&&G.success?h(G):(b((G==null?void 0:G.error)||o("sessionInfo.failedToLoad")),h(null))}catch($){b(($==null?void 0:$.message)||String($)),h(null)}finally{u(!1)}},[i,t,e,o]);c.useEffect(()=>{k()},[k]);const w=c.useMemo(()=>{var $,q;return CA({conv:s,sessionDaemonId:t,heldCoordinatorDaemonId:S?($=uo(S))==null?void 0:$.daemonId:null,reportedCoordinatorDaemonId:(q=m==null?void 0:m.meshWorker)==null?void 0:q.coordinatorDaemonId})},[s,t,S,(L=m==null?void 0:m.meshWorker)==null?void 0:L.coordinatorDaemonId]),y=c.useCallback(async()=>{var W,R;if(x(null),v(null),!S||!A||!w)return;const q=((W=uo(S))==null?void 0:W.status)??null??await $i({meshId:S,daemonId:w,refresh:!1,load:(O,B,H)=>l!=null&&l.loadMeshStatus?l.loadMeshStatus(O,B,{refresh:H.refresh}):i(O,"mesh_status",{meshId:B})});if(!q){v(((R=uo(S))==null?void 0:R.error)||o("sessionInfo.meshNodeUnavailable"));return}const G=TA(q,A);if(!G){v(o("sessionInfo.stampedToNode"));return}x(G)},[l,i,w,S,A,o]);c.useEffect(()=>{y()},[y]);const[N,j]=c.useState(!1),C=c.useCallback(async()=>{await Xb(ZA({sessionId:e,daemonId:t,conv:s,data:m,meshNode:f,meshNodeError:g}))&&(j(!0),setTimeout(()=>j(!1),1500))},[s,t,m,f,g,e]),E=n.jsxs(n.Fragment,{children:[(m||p)&&n.jsx("button",{type:"button",onClick:()=>void C(),"data-testid":"session-info-copy-diagnostics",className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:n.jsx("span",{"aria-live":"polite",children:o(N?"common.copied":"sessionInfo.copyDiagnostics")})}),n.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:o("sessionInfo.close")})]}),P=$=>o($?"common.yes":"common.no"),T=m==null?void 0:m.session,M=(T==null?void 0:T.workspace)||(s==null?void 0:s.workspacePath)||"",_=(s==null?void 0:s.machineName)||(m==null?void 0:m.machineNickname)||"",I=m==null?void 0:m.meshWorker,D=ig((f==null?void 0:f.quota)??(m==null?void 0:m.quota));return n.jsx(ag,{open:!0,onClose:r,title:o("sessionInfo.title"),size:"lg",footer:E,children:n.jsxs("div",{className:"text-sm space-y-4",children:[d&&n.jsx("div",{className:"text-text-secondary",children:o("sessionInfo.loading")}),p&&n.jsx("div",{className:"text-red-500",children:o("sessionInfo.failedToLoad")}),T&&n.jsxs("div",{className:"space-y-1.5","data-testid":"session-info-summary",children:[n.jsx(Xe,{k:o("sessionInfo.rowProvider"),v:T.providerName||T.providerType}),M&&n.jsx(Xe,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(Qt,{content:M,children:n.jsx("span",{className:"truncate",children:eg(M)})})}),_&&n.jsx(Xe,{k:o("sessionInfo.rowMachine"),v:_}),T.spawnedAtMs?n.jsx(Xe,{k:o("sessionInfo.rowStarted"),v:n.jsx(Jb,{value:T.spawnedAtMs})}):null,(s==null?void 0:s.git)&&n.jsx(Xe,{k:o("sessionInfo.rowGit"),v:n.jsxs("span",{children:[s.git.branch||o("sessionInfo.gitDetached"),s.git.ahead?` ↑${s.git.ahead}`:"",s.git.behind?` ↓${s.git.behind}`:"",s.git.dirty?` · ${o("sessionInfo.gitDirty")}`:` · ${o("sessionInfo.gitClean")}`]})}),(m==null?void 0:m.coordinator)&&n.jsx(Xe,{k:o("sessionInfo.rowRole"),v:o("sessionInfo.roleCoordinator")}),D.map(({provider:$,quota:q})=>{const G=a(q);return n.jsx(Xe,{k:[kr($),cl(q)].filter(Boolean).join(" · "),v:G.kind==="chips"?n.jsx("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:G.chips.map(W=>n.jsx(zm,{label:W.label,tone:W.tone},W.key))}):G.kind==="usage"?n.jsx(zm,{label:G.usageLabel,tone:"info"}):G.kind==="okNoWindows"?n.jsx("span",{className:"text-text-secondary",children:G.message??o("sessionInfo.quotaOkNoWindows")}):n.jsx("span",{className:"text-text-secondary",children:G.message})},$)}),(I==null?void 0:I.coordinatorSessionId)&&n.jsx(Xe,{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:()=>{OA({sessionId:I.coordinatorSessionId,source:"session-info-dialog"}),r()},children:o("sessionNav.openCoordinatorChat")})]})})]}),(T||f||(m==null?void 0:m.coordinator)||g&&(S||A))&&n.jsxs("details",{className:"group rounded-lg border border-border-subtle px-3 py-2","data-testid":"session-info-technical-details",children:[n.jsxs("summary",{className:"cursor-pointer select-none list-none text-xs font-medium text-text-secondary [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"mr-1 inline-block transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),o("common.technicalDetails")]}),n.jsxs("div",{className:"mt-3 space-y-4",children:[T&&n.jsxs(Ms,{title:o("sessionInfo.sectionSession"),children:[n.jsx(Xe,{k:o("sessionInfo.rowSessionId"),v:n.jsx(_t,{children:T.sessionId})}),n.jsx(Xe,{k:o("sessionInfo.rowProviderType"),v:n.jsx(_t,{children:T.providerType})}),T.transport&&n.jsx(Xe,{k:o("sessionInfo.rowTransport"),v:T.transport}),M&&n.jsx(Xe,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(_t,{children:M})}),T.spawnedAtMs?n.jsx(Xe,{k:o("sessionInfo.rowSpawnedAt"),v:qm(T.spawnedAtMs)}):null,T.providerSessionId&&n.jsx(Xe,{k:o("sessionInfo.rowProviderSessionId"),v:n.jsx(_t,{children:T.providerSessionId})}),(s==null?void 0:s.connectionState)&&n.jsx(Xe,{k:o("sessionInfo.rowConnection"),v:s.connectionState})]}),I&&(I.meshId||I.taskId||I.coordinatorSessionId)&&n.jsxs(Ms,{title:o("sessionInfo.sectionMeshWorker"),children:[I.meshId&&n.jsx(Xe,{k:o("sessionInfo.rowMeshId"),v:n.jsx(_t,{children:I.meshId})}),I.taskId&&n.jsx(Xe,{k:o("sessionInfo.rowTaskId"),v:n.jsx(_t,{children:I.taskId})}),I.coordinatorSessionId&&n.jsx(Xe,{k:o("sessionInfo.rowCoordinator"),v:n.jsx(_t,{children:I.coordinatorSessionId})})]}),(T==null?void 0:T.launch)&&n.jsxs(Ms,{title:o("sessionInfo.sectionLaunch"),children:[T.launch.command&&n.jsx(Xe,{k:o("sessionInfo.rowCommand"),v:n.jsx(_t,{children:T.launch.command})}),T.launch.cwd&&n.jsx(Xe,{k:o("sessionInfo.rowWorkingDirectory"),v:n.jsx(_t,{children:T.launch.cwd})}),Array.isArray(T.launch.args)&&T.launch.args.length>0&&n.jsx(Xe,{k:o("sessionInfo.rowArgs"),v:n.jsx(_t,{children:T.launch.args.join(" ")})}),Array.isArray(T.launch.extraArgs)&&T.launch.extraArgs.length>0&&n.jsx(Xe,{k:o("sessionInfo.rowExtraArgs"),v:n.jsx(_t,{children:T.launch.extraArgs.join(" ")})}),Array.isArray(T.launch.extraEnvKeys)&&T.launch.extraEnvKeys.length>0&&n.jsx(Xe,{k:o("sessionInfo.rowExtraEnv"),v:n.jsx(_t,{children:T.launch.extraEnvKeys.join(", ")})})]}),f&&n.jsxs(Ms,{title:o("sessionInfo.sectionMeshNode"),children:[f.nodeId&&n.jsx(Xe,{k:o("sessionInfo.rowNodeId"),v:n.jsx(_t,{children:f.nodeId})}),f.workspace&&n.jsx(Xe,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(_t,{children:f.workspace})}),f.repoRoot&&f.repoRoot!==f.workspace&&n.jsx(Xe,{k:o("sessionInfo.rowRepoRoot"),v:n.jsx(_t,{children:f.repoRoot})}),f.daemonId&&n.jsx(Xe,{k:o("sessionInfo.rowDaemonId"),v:n.jsx(_t,{children:f.daemonId})}),f.role&&n.jsx(Xe,{k:o("sessionInfo.rowRole"),v:f.role}),f.machineStatus&&n.jsx(Xe,{k:o("sessionInfo.rowMachineStatus"),v:f.machineStatus}),f.health&&n.jsx(Xe,{k:o("sessionInfo.rowHealth"),v:f.health}),f.isLocalWorktree&&n.jsx(Xe,{k:o("sessionInfo.rowWorktree"),v:f.worktreeBranch?n.jsx(_t,{children:f.worktreeBranch}):o("common.yes")}),typeof f.launchReady=="boolean"&&n.jsx(Xe,{k:o("sessionInfo.rowLaunchReady"),v:P(f.launchReady)}),f.git&&n.jsx(Xe,{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(Xe,{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(Xe,{k:o("sessionInfo.rowProviders"),v:n.jsx(_t,{children:f.providers.join(", ")})}),Array.isArray(f.providerPriority)&&f.providerPriority.length>0&&n.jsx(Xe,{k:o("sessionInfo.rowProviderPriority"),v:n.jsx(_t,{children:f.providerPriority.join(" › ")})})]}),!f&&g&&(S||A)&&n.jsx(Ms,{title:o("sessionInfo.sectionMeshNode"),children:n.jsx("div",{className:"text-text-secondary italic",children:g})}),(m==null?void 0:m.coordinator)&&n.jsxs(Ms,{title:o("sessionInfo.sectionMeshCoordinator"),children:[n.jsx(Xe,{k:o("sessionInfo.rowMeshId"),v:n.jsx(_t,{children:m.coordinator.meshId})}),m.coordinator.cliType&&n.jsx(Xe,{k:o("sessionInfo.rowCoordinatorCli"),v:m.coordinator.cliType}),m.coordinator.startedAt?n.jsx(Xe,{k:o("sessionInfo.rowStartedAt"),v:qm(m.coordinator.startedAt)}):null,m.coordinator.injection&&n.jsx(Xe,{k:o("sessionInfo.rowPromptInjection"),v:`${m.coordinator.injection.mode}${m.coordinator.injection.target?` → ${m.coordinator.injection.target}`:""}`}),m.coordinator.mcpConfigPath&&n.jsx(Xe,{k:o("sessionInfo.rowMcpConfig"),v:n.jsx(_t,{children:m.coordinator.mcpConfigPath})}),m.coordinator.extraSystemPrompt&&n.jsx(Fl,{title:o("sessionInfo.blockExtraPrompt"),body:m.coordinator.extraSystemPrompt}),m.coordinator.systemPrompt&&n.jsx(Fl,{title:o("sessionInfo.blockFinalPrompt"),body:m.coordinator.systemPrompt})]}),(T==null?void 0:T.runtimeMetadata)!=null&&n.jsx(eT,{meta:T.runtimeMetadata}),p&&n.jsx("div",{className:"font-mono text-xs text-text-secondary break-all",children:p})]})]})]})})}function ZA(e){const{sessionId:t,daemonId:s,conv:r,data:o,meshNode:a,meshNodeError:i}=e,l={sessionId:t,daemonId:s,machine:(r==null?void 0:r.machineName)||(o==null?void 0:o.machineNickname)||null,connectionState:(r==null?void 0:r.connectionState)??null,git:(r==null?void 0:r.git)??null,session:(o==null?void 0:o.session)??null,meshWorker:(o==null?void 0:o.meshWorker)??null,coordinator:(o==null?void 0:o.coordinator)??null,meshNode:a??null,meshNodeError:i??null,error:(o==null?void 0:o.error)??null};try{return JSON.stringify(l,null,2)}catch{return String(l)}}function Ms({title:e,children:t}){return n.jsxs("div",{children:[n.jsx("h3",{className:"text-xs uppercase tracking-wide text-text-secondary mb-1",children:e}),n.jsx("div",{className:"space-y-1",children:t})]})}function Xe({k:e,v:t}){return n.jsxs("div",{className:"flex flex-col sm:flex-row gap-1 sm:gap-3",children:[n.jsx("div",{className:"w-full sm:w-36 sm:shrink-0 text-text-secondary font-medium sm:font-normal",children:e}),n.jsx("div",{className:"min-w-0 break-all",children:t})]})}function _t({children:e}){return n.jsx("code",{className:"font-mono text-xs",children:e})}function zm({label:e,tone:t}){const s=t==="danger"?"bg-red-500/10 text-red-500":t==="warn"?"bg-amber-500/10 text-amber-500":t==="good"?"bg-emerald-500/10 text-emerald-500":"bg-white/5 text-text-secondary";return n.jsx("span",{className:`rounded-full px-2 py-0.5 text-3xs font-medium ${s}`,children:e})}function eT({meta:e}){const{t}=he("common");if(!e||typeof e!="object")return null;const s=e,r=u=>typeof u=="string"&&u.trim()?u:null,o=r(s.runtimeId),a=r(s.lifecycle),i=r(s.surfaceKind),l=r(s.recoveryState),d=Array.isArray(s.attachedClients)?s.attachedClients.length:null;return n.jsxs(Ms,{title:t("sessionInfo.sectionRuntime"),children:[o&&n.jsx(Xe,{k:t("sessionInfo.rowRuntimeId"),v:n.jsx(_t,{children:o})}),a&&n.jsx(Xe,{k:t("sessionInfo.rowLifecycle"),v:a}),i&&n.jsx(Xe,{k:t("sessionInfo.rowSurface"),v:i}),l&&n.jsx(Xe,{k:t("sessionInfo.rowRecoveryState"),v:l}),typeof s.restoredFromStorage=="boolean"&&n.jsx(Xe,{k:t("sessionInfo.rowRestoredFromStorage"),v:s.restoredFromStorage?t("common.yes"):t("common.no")}),d!=null&&n.jsx(Xe,{k:t("sessionInfo.rowAttachedClients"),v:String(d)}),n.jsx(Fl,{title:t("sessionInfo.blockRawMetadata"),body:tT(e)})]})}function tT(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Fl({title:e,body:t,defaultOpen:s=!1}){const[r,o]=c.useState(s);return n.jsxs("div",{className:"mt-2",children:[n.jsxs("button",{type:"button",onClick:()=>o(a=>!a),className:"text-xs uppercase tracking-wide text-text-secondary hover:text-text-primary",style:{pointerEvents:"auto"},children:[r?"▾":"▸"," ",e]}),r&&n.jsx("pre",{className:"mt-1 p-2 bg-[var(--surface-secondary)] border border-border-subtle rounded text-xs whitespace-pre-wrap overflow-x-auto max-h-96 overflow-y-auto",children:t})]})}const nT=8e3;function sT({sessionId:e,daemonId:t,muted:s,sendDaemonCommand:r}){const[o,a]=c.useState(null),i=c.useRef(null);c.useEffect(()=>{o!==null&&s===o&&a(null)},[s,o]),c.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]);const l=o!==null?o:s,d=!!e&&!!t,u=c.useCallback(()=>{if(!e||!t)return;const m=!l;a(m),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(null),nT),r(t,"set_conversation_prefs",{sessionId:e,muted:m}).catch(h=>{console.warn("[conversation-prefs] toggle mute failed",h),a(null)})},[t,l,r,e]);return{available:d,muted:l,toggle:u}}const na=220;function cg({conversation:e,onOpenHistory:t,onOpenRemote:s,onOpenGit:r,className:o,iconSize:a=16}){const{t:i}=he("common"),{ides:l}=yn(),{sendCommand:d}=wt(),[u,m]=c.useState(!1),[h,p]=c.useState(!1),[b,f]=c.useState(null),x=c.useRef(null),g=c.useRef(null),v=ft(e),S=c.useMemo(()=>{const N=l.find(j=>j.id===e.routeId);return ab(e,N)},[e,l]),A=sT({sessionId:e.sessionId,daemonId:e.daemonId,muted:!!(S!=null&&S.muted),sendDaemonCommand:d}),k=[];if(t&&k.push({key:"history",label:i("dashboard.header.chatHistory"),icon:n.jsx(Wp,{size:15}),onSelect:()=>t(e)}),s&&!v&&k.push({key:"remote",label:i("dashboard.header.remoteControl"),icon:n.jsx(Bn,{size:15}),onSelect:()=>s(e)}),r&&e.git&&e.daemonId&&e.workspacePath){const N=e.daemonId,j=e.workspacePath;k.push({key:"git",label:i("dashboard.header.openGitStatus"),icon:n.jsx(Fa,{size:15}),onSelect:()=>r(N,j)})}A.available&&k.push({key:"mute",label:A.muted?i("conversation.unmuteThis"):i("conversation.muteThis"),icon:A.muted?n.jsx(fl,{size:15}):n.jsx(Jn,{size:15}),onSelect:A.toggle,pressed:A.muted}),e.sessionId&&e.daemonId&&k.push({key:"info",label:i("sessionInfo.title"),icon:n.jsx(Co,{size:15}),onSelect:()=>p(!0)});const w=c.useCallback((N=!1)=>{var j;m(!1),N&&((j=x.current)==null||j.focus())},[]);if(c.useLayoutEffect(()=>{var C;if(!u||typeof window>"u"){f(null);return}const N=(C=x.current)==null?void 0:C.getBoundingClientRect();if(!N)return;const j=Math.min(Math.max(8,N.right-na),window.innerWidth-na-8);f({top:N.bottom+6,left:j})},[u]),c.useEffect(()=>{if(!u||typeof window>"u")return;const N=E=>{E.key==="Escape"&&(E.stopPropagation(),w(!0))},j=E=>{var T,M;const P=E.target;P&&((T=x.current)!=null&&T.contains(P)||(M=g.current)!=null&&M.contains(P)||w())},C=()=>w();return window.addEventListener("keydown",N,!0),document.addEventListener("mousedown",j,!0),window.addEventListener("resize",C),()=>{window.removeEventListener("keydown",N,!0),document.removeEventListener("mousedown",j,!0),window.removeEventListener("resize",C)}},[w,u]),c.useEffect(()=>{var N,j;u&&((j=(N=g.current)==null?void 0:N.querySelector('[role="menuitem"]'))==null||j.focus())},[u,b]),k.length===0)return null;const y=N=>{var P;if(N.key!=="ArrowDown"&&N.key!=="ArrowUp")return;N.preventDefault();const j=Array.from(((P=g.current)==null?void 0:P.querySelectorAll('[role="menuitem"]'))??[]),C=j.indexOf(document.activeElement),E=j[(C+(N.key==="ArrowDown"?1:-1)+j.length)%j.length];E==null||E.focus()};return n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:x,type:"button","data-testid":"conversation-actions-menu","aria-label":i("dashboard.header.moreActions"),title:i("dashboard.header.moreActions"),"aria-haspopup":"menu","aria-expanded":u,onClick:()=>m(N=>!N),className:o??"btn btn-secondary btn-sm",style:{pointerEvents:"auto"},children:n.jsx(Kp,{size:a})}),u&&typeof document<"u"&&An.createPortal(n.jsx("div",{ref:g,role:"menu","aria-label":i("dashboard.header.moreActions"),onKeyDown:y,className:"fixed z-[var(--z-popover)] flex flex-col rounded-xl border border-border-default bg-bg-card p-1 shadow-xl backdrop-blur-xl",style:b?{top:b.top,left:b.left,width:na}:{top:-9999,left:-9999,width:na,visibility:"hidden"},children:k.map(N=>n.jsxs("button",{type:"button",role:"menuitem","data-menu-item":N.key,"aria-pressed":N.pressed,onClick:()=>{w(),N.onSelect()},className:ct("flex w-full items-center gap-2.5 rounded-lg border-none bg-transparent px-2.5 py-2 text-left text-xs font-medium text-text-secondary transition-colors hover:bg-bg-secondary hover:text-text-primary focus-visible:bg-bg-secondary focus-visible:text-text-primary focus-visible:outline-none",N.pressed&&"text-amber-500"),children:[n.jsx("span",{className:"flex w-4 shrink-0 justify-center","aria-hidden":!0,children:N.icon}),n.jsx("span",{className:"min-w-0 truncate",children:N.label})]},N.key))}),document.body),h&&e.sessionId&&e.daemonId&&n.jsx(XA,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e,onClose:()=>p(!1)})]})}function lg(e){const{t}=he("common");if(!e.role)return null;const s=p1(e);return e.role==="coordinator"?{short:t("dashboard.meshRole.coordinator"),full:s?t("dashboard.meshRole.coordinatorFor",{mesh:s}):t("dashboard.meshRole.coordinatorUnknownMesh"),mesh:s}:{short:t("dashboard.meshRole.worker"),full:s?t("dashboard.meshRole.workerFor",{mesh:s}):t("dashboard.meshRole.workerUnknownMesh"),mesh:s}}function Kd(e){var o;const{t}=he("common"),s=Pb(e),r=((o=lg(s))==null?void 0:o.full)??null;return wr(e)?t("dashboard.assistant.label"):r}function ws({conversation:e,className:t,size:s=12}){const{t:r}=he("common"),o=Pb(e),a=lg(o);if(wr(e)){const i=r("dashboard.assistant.label");return n.jsx("span",{role:"img","aria-label":i,title:i,"data-assistant-role":"assistant",className:ct("mesh-role-icon","is-assistant",t),children:n.jsx(pl,{size:s})})}return!Mb(e)||!a?null:n.jsx("span",{role:"img","aria-label":a.full,title:a.full,"data-mesh-role":o.role,className:ct("mesh-role-icon",`is-${o.role}`,t),children:n.jsx(On,{size:s})})}function Hl(){return mr(()=>import("./DashboardMeshGraphDialog-DX6lkI__.js"),__vite__mapDeps([3,1,4,5]))}const rT=c.lazy(Hl);function oT({onClose:e}){const{t}=he(),s=t("connection.loadingShort");return n.jsx(Sr,{onClose:e,size:"sm",ariaLabel:s,children:n.jsx("div",{className:"flex items-center justify-center p-8","data-testid":"mesh-graph-dialog-loading",children:n.jsx(nn,{label:s})})})}function qd(e){return n.jsx(c.Suspense,{fallback:n.jsx(oT,{onClose:e.onClose}),children:n.jsx(rT,{...e})})}function dg({conversation:e,onOpenMeshGraph:t,showLabel:s=!1,iconSize:r=14,className:o}){const{t:a}=he("common"),i=Kd(e);if(!t||!Rb(e))return null;const l=i?`${a("dashboard.meshRole.openMeshGraph")} · ${i}`:a("dashboard.meshRole.openMeshGraph");return n.jsxs("button",{type:"button","data-testid":"conversation-mesh-graph-button",onClick:()=>t(e),onPointerEnter:()=>{Hl()},onFocus:()=>{Hl()},className:ct("btn btn-secondary btn-sm dashboard-header-mesh-button inline-flex items-center gap-1.5",o),title:l,"aria-label":l,children:[n.jsx(On,{size:r}),s&&n.jsx("span",{className:"hidden lg:inline",children:a("dashboard.header.meshGraph")})]})}function aT({wsStatus:e,isConnected:t,daemonCount:s,p2pStates:r={},usesP2P:o=!0}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};if(s>0&&!o)return t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null};const i=Object.values(r).filter(l=>l==="connected").length;return s>0?i>=s?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.machinesConnectedCount",subtitleParams:{connected:i,total:s}}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function Vm({value:e}){return e?n.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Gm({notification:e,shortcutIndex:t,onOpen:s,onMarkRead:r,onMarkUnread:o,onDelete:a}){const{t:i}=he(),l=Si(e.updatedAt),d=!e.readAt;return n.jsxs("div",{className:`dashboard-header-inbox-item ${d?"is-attention":""}`.trim(),children:[n.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:s,children:[n.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),n.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?n.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?i("notification.actionNeeded"):i("notification.taskComplete"),l].filter(Boolean).join(" · ")]}),e.preview?n.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),n.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[d?n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),r()},children:i("notification.markRead")}):n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),o()},children:i("notification.markUnread")}),n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:i("notification.delete")})]})]})}function iT({activeConv:e,wsStatus:t,isConnected:s,conversations:r,onOpenHistory:o,onOpenRemote:a,onStopCli:i,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:u,hiddenConversations:m=[],onShowConversation:h,onShowAllHidden:p,onResetPanelsToMain:b,inboxOpen:f,onInboxOpenChange:x,hiddenOpen:g,onHiddenOpenChange:v,onOpenNewSession:S,onStartAssistant:A,startAssistantPending:k=!1,startAssistantError:w=null,onStartAssistantWith:y,startAssistantMachines:N,startAssistantDefault:j=null,onOpenDashboardGuide:C,guideNudgeVisible:E=!1,actionShortcuts:P,notifications:T,notificationUnreadCount:M,onOpenNotification:_,onMarkNotificationRead:I,onMarkNotificationUnread:D,onDeleteNotification:L,onOpenGitDialog:$,onOpenMeshGraph:q}){const{t:G}=he(),{ides:W,p2pStates:R={},usesP2P:O=!0}=yn(),B=!!e&&ft(e),H=l||(e?eb(e)?"terminal":"chat":null),[U,K]=c.useState(!1),[oe,ge]=c.useState(!1),J=c.useRef(null),ke=c.useRef(null),de=c.useRef(null),ne=W.filter(we=>we.type==="adhdev-daemon"),le=aT({wsStatus:t,isConnected:s,daemonCount:ne.length,p2pStates:R,usesP2P:O}),te=G(le.titleKey),ce=le.subtitleKey?G(le.subtitleKey,le.subtitleParams):null,Ce=le.tone==="connected"?"#22c55e":le.tone==="limited"?"#eab308":"#ef4444",Q=le.tone==="connected"?"0 0 4px #22c55e80":le.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",z=c.useMemo(()=>T.filter(we=>!we.readAt),[T]),X=c.useMemo(()=>T.filter(we=>!!we.readAt),[T]),pe=c.useMemo(()=>z.slice(0,9),[z]),Re=M;c.useEffect(()=>{if(!f)return;const we=V=>{var xe;(xe=ke.current)!=null&&xe.contains(V.target)||x(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[f,x]),c.useEffect(()=>{if(!g)return;const we=V=>{var xe;(xe=de.current)!=null&&xe.contains(V.target)||v(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[g,v]),c.useEffect(()=>{if(!g&&!f)return;const we=V=>{if(!V.altKey)return;const xe=V.code.match(/^Digit([1-9])$/);if(!xe)return;const Z=Number(xe[1])-1,ae=g?m[Z]:void 0,F=f?pe[Z]:void 0;if(!(!ae&&!F)){if(V.preventDefault(),V.stopPropagation(),ae){h==null||h(ae),v(!1);return}F&&(_(F),x(!1))}};return window.addEventListener("keydown",we,!0),()=>window.removeEventListener("keydown",we,!0)},[m,g,f,pe,v,x,_,h]),c.useEffect(()=>{const we=m.length;if(J.current===null){J.current=we;return}we>J.current&&ge(!0),J.current=we},[m.length]);const Oe=()=>ge(!1),De=we=>{if(!we)return;const V=r.find(xe=>xe.tabKey===we);V&&(u==null||u(V))};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:G("dashboard.header.title")}),e&&n.jsx(ws,{conversation:e,size:14,className:"header-title-mobile-role"}),n.jsx("span",{className:"header-title-mobile",children:e?kt(e):G("dashboard.header.title")}),n.jsx(Qt,{content:ce?`${te} · ${ce}`:te,className:"ml-0.5",children:n.jsx("span",{role:"img","aria-label":te,"data-connection-tone":le.tone,className:"header-title-status-dot",style:{background:Ce,boxShadow:Q}})})]}),n.jsxs("div",{className:"header-subtitle flex items-center",children:[S&&n.jsx("button",{type:"button",onClick:S,className:"btn btn-secondary btn-sm ml-2",title:`${G("paneGroup.newSession")}${P!=null&&P.openNewSession?` (${P.openNewSession})`:""}`,"aria-label":G("paneGroup.newSession"),children:n.jsx(go,{size:14})}),A&&n.jsx(nA,{onStart:A,onStartWith:y,machines:N,defaultTarget:j,pending:k,error:w})]})]})})}),n.jsxs("div",{className:"flex gap-2 items-center",children:[C&&n.jsxs("button",{type:"button",onClick:C,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:G("dashboard.header.guide"),"aria-label":G("dashboard.header.guideOpen"),children:[n.jsx("span",{className:"font-semibold leading-none",children:"?"}),E&&n.jsx("span",{children:G("dashboard.header.guideShort")})]}),e&&n.jsxs("div",{className:"dashboard-header-actions-group","data-testid":"dashboard-pane-toolbar",children:[n.jsx(Od,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),B&&d&&H&&n.jsx(Yb,{mode:H,onChange:d,compact:!0}),B&&i&&n.jsx("button",{type:"button",onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:G("dashboard.header.stopCliProcess"),"aria-label":G("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(Lt,{size:14})}),n.jsx(dg,{conversation:e,onOpenMeshGraph:q,showLabel:!0}),n.jsx(cg,{conversation:e,onOpenHistory:o,onOpenRemote:a?()=>a():void 0,onOpenGit:$,iconSize:14})]}),n.jsxs("div",{className:"dashboard-header-inbox",ref:ke,children:[n.jsxs("div",{className:`dashboard-header-hidden${U?" is-drop-target":""}${oe?" hidden-spawn-flash":""}${(m??[]).some(Us)?" hidden-generating-spin":""}`,onAnimationEnd:Oe,ref:de,onDragEnter:we=>{we.dataTransfer.types.includes("text/tab-key")&&(we.preventDefault(),K(!0))},onDragOver:we=>{we.dataTransfer.types.includes("text/tab-key")&&(we.preventDefault(),we.dataTransfer.dropEffect="move",K(!0))},onDragLeave:we=>{we.currentTarget.contains(we.relatedTarget)||K(!1)},onDrop:we=>{const V=we.dataTransfer.getData("text/tab-key");we.preventDefault(),K(!1),De(V)},children:[n.jsxs("button",{type:"button",onClick:()=>v(!g),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${G("dashboard.hidden.title")}${P!=null&&P.toggleHiddenTabs?` (${P.toggleHiddenTabs})`:""}. ${G("dashboard.hidden.dragHint")}`,children:[n.jsx(xi,{size:16}),m.length>0&&n.jsx("span",{className:`dashboard-header-hidden-badge${oe?" hidden-badge-pop":""}`,children:m.length})]}),g&&n.jsxs("div",{className:"dashboard-header-hidden-popover",children:[n.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:G("dashboard.hidden.title")}),n.jsx(Vm,{value:P==null?void 0:P.toggleHiddenTabs})]}),n.jsxs("div",{className:"dashboard-header-hidden-actions",children:[b&&n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:b,children:G("dashboard.hidden.resetPanels")}),m.length>0&&p&&n.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{p(),v(!1)},children:G("dashboard.hidden.restoreAll")})]})]}),e&&u&&n.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>u(e),children:[n.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[n.jsx("span",{className:"dashboard-header-hidden-current-label",children:G("dashboard.hidden.hideCurrentTab")}),n.jsx(Vm,{value:P==null?void 0:P.hideCurrentTab})]}),n.jsx("span",{className:"dashboard-header-hidden-current-title",children:kt(e)})]}),m.length>0?n.jsx("div",{className:"dashboard-header-hidden-list",children:m.map(we=>n.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(we),v(!1)},children:[n.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[Us(we)&&n.jsx(nn,{size:12,thickness:2,color:"success",label:G("dashboard.header.generating")}),n.jsx(ws,{conversation:we,size:12}),kt(we)]}),n.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[m.indexOf(we)<9?n.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",m.indexOf(we)+1]}):null,Po(we)]})]},we.tabKey))}):n.jsx("div",{className:"dashboard-header-inbox-empty",children:G("dashboard.hidden.empty")})]})]}),n.jsxs("button",{type:"button",onClick:()=>x(!f),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:G("dashboard.header.activityInbox"),children:[n.jsx(Jn,{size:16}),Re>0&&n.jsx("span",{className:"dashboard-header-inbox-badge",children:Re})]}),f&&n.jsxs("div",{className:"dashboard-header-inbox-popover",children:[z.length>0&&n.jsxs("div",{className:"dashboard-header-inbox-section",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title",children:G("dashboard.inbox.unread")}),z.map(we=>n.jsx(Gm,{notification:we,shortcutIndex:pe.indexOf(we)>=0?pe.indexOf(we)+1:void 0,onOpen:()=>_(we),onMarkRead:()=>I(we.id),onMarkUnread:()=>D(we.id),onDelete:()=>L(we.id)},we.id))]}),X.length>0&&n.jsxs("div",{className:"dashboard-header-inbox-section",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title",children:G("dashboard.inbox.read")}),X.map(we=>n.jsx(Gm,{notification:we,onOpen:()=>_(we),onMarkRead:()=>I(we.id),onMarkUnread:()=>D(we.id),onDelete:()=>L(we.id)},we.id))]}),T.length===0&&n.jsx("div",{className:"dashboard-header-inbox-empty",children:G("dashboard.inbox.empty")})]})]})]})]})}function mn(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function cT(e,t){return String(e||"")!==String(t||"")}function lT(e,t={}){const s=String(t.textQuery||"").trim().toLowerCase(),r=String(t.workspaceQuery||"").trim().toLowerCase(),o=String(t.modelQuery||"").trim().toLowerCase(),a=!!t.resumableOnly;return!s&&!r&&!o&&!a?e:e.filter(i=>!(a&&!i.canResume||s&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
57
|
+
`).includes(s)||r&&!String(i.workspace||"").toLowerCase().includes(r)||o&&!Df(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
58
|
+
`).includes(o)))}function dT(e,t="recent"){const s=e.slice();return s.sort((r,o)=>{if(t==="oldest")return(Number(r.lastMessageAt)||0)-(Number(o.lastMessageAt)||0);if(t==="messages"){const a=(Number(o.messageCount)||0)-(Number(r.messageCount)||0);if(a!==0)return a}return(Number(o.lastMessageAt)||0)-(Number(r.lastMessageAt)||0)}),s}function zd(e,t={}){return dT(lT(e,t),t.sortMode||"recent")}function Bl(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function ug(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function uT(e){return e?e("launch.startFresh"):"Start fresh"}function mT(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function hT(e){return e?e("launch.openSavedHistory"):"Open saved history"}function Wl(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function Vd(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function mg(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function pT(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function fT(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function Za(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 ei(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 ti(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function ni(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function hg(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function pg(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function Ym(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function bT({activeConv:e,ides:t,isCreatingChat:s,isRefreshingHistory:r,savedSessions:o=[],isSavedSessionsLoading:a=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:u,onClose:m,onNewChat:h,onSwitchSession:p,onRefreshHistory:b,onResumeSavedSession:f}){var M;const{t:x}=he("common"),g=t.find(_=>_.id===e.routeId),v=(g==null?void 0:g.chats)||[],S=(M=g==null?void 0:g.activeChat)==null?void 0:M.id,A=ft(e),[k,w]=c.useState(()=>mn()),[y,N]=c.useState(null),j=l||k,C=String(d||"").trim(),E=_=>{if(u){u(_);return}w(_)},P=c.useMemo(()=>o.map(_=>{const I=String(_.workspace||"").trim();return _.canResume||I||!C?_:{..._,workspace:C,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[C,o]),T=c.useMemo(()=>zd(P,{textQuery:j.textQuery,workspaceQuery:j.workspaceQuery,modelQuery:j.modelQuery,resumableOnly:j.resumableOnly,sortMode:j.sortMode}),[P,j.modelQuery,j.resumableOnly,j.sortMode,j.textQuery,j.workspaceQuery]);return n.jsxs(n.Fragment,{children:[n.jsxs(Sr,{chrome:!1,onClose:m,closeOnEsc:!y,ariaLabel:A?Wl(x):x("historyModal.chatHistory"),overlayClassName:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4 bg-black/60 backdrop-blur-sm",surfaceClassName:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[n.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"m-0 text-lg font-extrabold",children:A?Wl(x):x("historyModal.chatHistory")}),n.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:g1(e)}),A&&n.jsx("div",{className:"text-2xs text-text-muted mt-1",children:Vd(x)})]}),n.jsx("button",{onClick:m,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:n.jsx(Lt,{size:16})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!A&&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")}),A?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:j.textQuery,onChange:_=>E({...j,textQuery:_.target.value}),placeholder:x("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),n.jsx("input",{type:"text",value:j.workspaceQuery,onChange:_=>E({...j,workspaceQuery:_.target.value}),placeholder:x("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),n.jsx("input",{type:"text",value:j.modelQuery,onChange:_=>E({...j,modelQuery:_.target.value}),placeholder:x("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),n.jsxs("select",{value:j.sortMode,onChange:_=>E({...j,sortMode:_.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[n.jsx("option",{value:"recent",children:x("historyModal.sortRecent")}),n.jsx("option",{value:"oldest",children:x("historyModal.sortOldest")}),n.jsx("option",{value:"messages",children:x("historyModal.sortMessages")})]})]}),n.jsxs("label",{className:"mt-2 flex items-center gap-2 text-2xs text-text-muted",children:[n.jsx("input",{type:"checkbox",checked:j.resumableOnly,onChange:_=>E({...j,resumableOnly:_.target.checked})}),x("historyModal.resumeReadyOnly")]})]}),T.map(_=>{const I=e.providerSessionId===_.providerSessionId,D=I||!_.canResume||!!i,L=_.workspaceFallbackSource==="selected-workspace";return n.jsxs("button",{type:"button",onClick:()=>{D||!f||N({kind:"saved",session:_})},disabled:D,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${I?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${D?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:`font-bold text-sm mb-1 truncate ${I?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:_.title||x("historyModal.untitledSession")}),n.jsx("div",{className:"text-2xs text-text-muted font-mono truncate",children:_.providerSessionId})]}),n.jsx("div",{className:"text-2xs text-text-muted shrink-0",children:Ym(_.lastMessageAt)})]}),n.jsx("div",{className:"mt-2 text-xs text-text-muted line-clamp-2",children:_.preview||x("historyModal.noSavedPreview")}),n.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-2xs text-text-muted",children:[n.jsxs("div",{className:"truncate",children:[_.workspace||x("historyModal.workspaceUnknown"),L?x("historyModal.selectedWorkspaceSuffix"):"",wo(_.summaryMetadata)?` · ${wo(_.summaryMetadata)}`:"",_.messageCount>0?` · ${x("historyModal.msgCount",{count:_.messageCount})}`:""]}),n.jsx("div",{className:"shrink-0",children:I?x("historyModal.statusActive"):_.canResume?L?x("historyModal.statusResumeSelectedWorkspace"):i===_.providerSessionId?x("historyModal.statusResuming"):x("historyModal.statusResume"):x("historyModal.statusMissingWorkspace")})]})]},_.id)})]}):v.map(_=>n.jsxs("div",{onClick:()=>{_.id!==S&&N({kind:"chat",id:_.id,title:_.title||x("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${S===_.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[n.jsx("div",{className:`font-bold text-sm mb-1 ${S===_.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:_.title||x("historyModal.untitledSession")}),n.jsxs("div",{className:"flex justify-between items-center",children:[n.jsxs("div",{className:"text-2xs text-text-muted font-mono",children:[_.id.substring(0,12),"..."]}),S===_.id&&n.jsx("span",{className:"text-3xs bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:x("historyModal.statusActive")})]})]},_.id)),(A&&!a&&T.length===0||!A&&v.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(Lw,{size:32})}),n.jsx("div",{className:"text-xxs",children:A?o.length>0?x("historyModal.noMatchingHistory"):mg(x):x("historyModal.noRecentChats")})]}),A&&a&&n.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:n.jsx("div",{className:"text-xxs",children:fT(x)})})]}),n.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:n.jsx("button",{onClick:b,disabled:r||a,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||a?x("historyModal.refreshing"):n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Ar,{size:13})," ",A?pT(x):x("historyModal.refreshHistory")]})})})]}),y&&n.jsxs(Sr,{chrome:!1,onClose:()=>N(null),overlayClassName:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm",surfaceClassName:"card fade-in relative w-full sm:w-[min(92vw,420px)] max-w-[420px] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[n.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[n.jsx("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:x("historyModal.confirmSwitchTitle")}),n.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:x("historyModal.confirmSwitchDescription",{target:y.kind==="chat"?y.title:y.session.title||x("historyModal.untitledSession")})}),y.kind==="saved"&&n.jsxs("div",{className:"mt-2 text-2xs text-text-muted font-mono truncate",children:[y.session.workspace||x("historyModal.workspaceUnknown"),y.session.lastMessageAt?` · ${Ym(y.session.lastMessageAt)}`:""]})]}),n.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[n.jsx("button",{onClick:()=>{const _=y;N(null),_.kind==="chat"?(p(e.routeId,_.id),m()):f&&f(_.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:x("historyModal.confirmSwitchAction")}),n.jsx("button",{onClick:()=>N(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:x("common.cancel")})]})]})]})}const Qm={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.success"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.warning"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.info"}};function gT({toast:e}){const{t}=he(),{setToasts:s}=yn(),[r,o]=c.useState(!1);return e.details?n.jsxs("div",{className:"mt-2","data-toast-details":"",children:[n.jsxs("button",{type:"button",className:"bg-transparent border-none p-0 text-xs font-semibold text-text-muted hover:text-text-primary cursor-pointer","aria-expanded":r,onClick:a=>{a.stopPropagation();const i=!r;o(i),i&&s(l=>l.map(d=>d.id===e.id?{...d,pinned:!0}:d))},children:[n.jsx("span",{className:"mr-1 inline-block transition-transform",style:{transform:r?"rotate(90deg)":void 0},"aria-hidden":!0,children:"▸"}),t("toast.details")]}),r&&n.jsx("pre",{className:"mt-1.5 max-h-40 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-border-subtle bg-bg-secondary/60 px-2.5 py-2 font-mono text-3xs leading-relaxed text-text-secondary",children:e.details})]}):null}function fg({toasts:e,onDismiss:t,onClickToast:s}){const{t:r}=he();return n.jsx("div",{className:"fixed right-4 top-[calc(env(safe-area-inset-top,0px)+64px)] z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none sm:top-[calc(env(safe-area-inset-top,0px)+16px)]",children:e.map(o=>{const a=Qm[o.type]||Qm.info;return n.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=o.actions)!=null&&i.length||s&&s(o)},children:[n.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),n.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(o.id)},"aria-label":r("toast.dismiss"),children:n.jsx(Lt,{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(gT,{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 xT=e=>e.transport==="pty"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function yT(e){const t=e.workspace||"";if(!t)return"";const s=t.split(/[/\\]/).filter(Boolean);return s.length>0?s[s.length-1]:t}function vT(e,t){return bg(e)||t}function bg(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 wT(e){return bg(e)||void 0}function ST(e){return e.sessionId||e.instanceId||e.agentType}function gg(e=[]){const t={};for(const s of e)s.type==="adhdev-daemon"&&(t[s.id]=pn(s,{fallbackId:s.id}));return t}function xg(e,t={}){var r;const s=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:Xj(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[s]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Gd(e,t={}){return kT(e,xg(e,t))}function kT(e,t={}){var p,b,f,x,g,v,S,A,k;const s=[],r=t.machineName,o=t.connectionState,a=yT(e),i=e.workspace||"",l=$f(e.type,{agentName:e.cliName}),d=ft(e)?l:Ft(e.type),u=vT(e,d),m=Array.isArray(e.childSessions)?e.childSessions.map(w=>{var y,N,j;return{sessionId:w.id,instanceId:w.id,providerSessionId:w.providerSessionId,activeChatId:(y=w.activeChat)==null?void 0:y.id,transport:w.transport,sessionCapabilities:w.capabilities,agentType:w.providerType,agentName:w.providerName||Ft(w.providerType),model:wT(w),status:w.status,title:w.title,lastMessagePreview:w.lastMessagePreview,lastMessageRole:w.lastMessageRole,lastMessageAt:w.lastMessageAt,lastMessageHash:w.lastMessageHash,messages:((N=w.activeChat)==null?void 0:N.messages)||[],activeModal:((j=w.activeChat)==null?void 0:j.activeModal)||void 0,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,inboxBucket:w.inboxBucket,completionMarker:w.completionMarker,surfaceHidden:w.surfaceHidden,muted:w.muted,git:w.git,settings:w.settings,coordinator:w.coordinator,messageInput:w.messageInput}}):[],h=xT(e);if(h){const w=e.sessionId||e.instanceId,y=(p=e.settings)==null?void 0:p.meshCoordinatorFor,N=((b=e.settings)==null?void 0:b.meshNodeFor)||!((f=e.settings)!=null&&f.meshCoordinatorFor)&&((x=e.settings)==null?void 0:x.launchedByCoordinator),j=Ub(e),C=j?" (Assistant)":y?" (Coordinator)":N?" (Mesh Node)":"",E=l+C,P=(g=e.activeChat)==null?void 0:g.activeModal,T=P&&Array.isArray(P.buttons)&&P.buttons.length>0,M=oN(e.activeChat,[{status:e.status,activeModal:(v=e.activeChat)==null?void 0:v.activeModal}],e.agents||[]),_=e.activeChat||{title:"",messages:[]};let I=_.title&&String(_.title).trim()?String(_.title).trim():"";const D=(S=e.activeChat)==null?void 0:S.id,L=e.chats;if(D&&Array.isArray(L)&&L.length>0){const H=L.find(U=>U.id===D||U.id&&String(U.id)===String(D));H!=null&&H.title&&String(H.title).trim()&&(I=String(H.title).trim())}const $=(ft(e),e.type),q=ft(e)&&sm(I,E,$)?"":I,G=_.messages||[],W=typeof D=="string"?D.trim():"",R=ft(e)&&W===String(e.type||"").trim(),O=W&&!R?W:e.providerSessionId,B=e.coordinator||(typeof((A=e.settings)==null?void 0:A.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);s.push({routeId:e.id,sessionId:w,providerSessionId:e.providerSessionId,historySessionId:O,nativeSessionId:w,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ft(e)&&e.mode||"chat",agentName:E,agentType:$,status:M,title:q,messages:G,resume:e.resume,hostIdeType:ft(e)?void 0:e.type,workspaceName:a,workspacePath:i,git:e.git,displayPrimary:(j?K1:"")||a||q||(ft(e)?e.mode==="chat"?E:`Terminal${C}`:E),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:T?P.buttons:void 0,modalMessage:T?P.message:void 0,streamSource:"native",tabKey:pc(w,e.id),machineName:r,connectionState:o,settings:e.settings,coordinator:B,...j?{assistant:!0}:{},messageInput:e.messageInput})}if(h&&ft(e))return s;for(const w of m){const y=w.activeModal&&Array.isArray(w.activeModal.buttons)&&w.activeModal.buttons.length>0,N=aN(w),j=ST(w),C=`${e.id}:${j}`,E=w.title&&String(w.title).trim()||"",P=sm(E,w.agentName,w.agentType)?"":E,T=w.messages||[];if(!(w.transport==="cdp-webview"||!!w.sessionId||!!w.providerSessionId||T.length>0||y||!!P||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const _=w.coordinator||(typeof((k=w.settings)==null?void 0:k.meshCoordinatorFor)=="string"&&w.settings.meshCoordinatorFor?{meshId:w.settings.meshCoordinatorFor,role:"coordinator"}:void 0);s.push({routeId:e.id,sessionId:w.sessionId||w.instanceId,providerSessionId:w.providerSessionId,historySessionId:w.activeChatId||w.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:w.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:w.sessionCapabilities,mode:"chat",agentName:w.agentName,agentType:w.agentType,status:N,title:P,messages:T,hostIdeType:e.type,workspaceName:a,workspacePath:i,git:w.git||e.git,displayPrimary:a||P||w.agentName||d,displaySecondary:w.model&&w.model.trim()?w.model.trim():`${d} · ${w.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:w.lastMessagePreview,lastMessageRole:w.lastMessageRole,lastMessageAt:w.lastMessageAt,lastMessageHash:w.lastMessageHash,lastUpdated:w.lastUpdated||e.lastUpdated,inboxBucket:w.inboxBucket,completionMarker:w.completionMarker,modalButtons:y?w.activeModal.buttons:void 0,modalMessage:y?w.activeModal.message:void 0,streamSource:"agent-stream",tabKey:pc(w.sessionId||w.instanceId,C),machineName:r,connectionState:o,settings:w.settings,coordinator:_,messageInput:w.messageInput})}return s.length===0&&s.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:a,workspacePath:i,git:e.git,displayPrimary:a||d,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:pc(e.sessionId||e.instanceId,e.id),connectionState:o,settings:e.settings,messageInput:e.messageInput}),s}const Ul="https://adhf.dev",jT="https://dev.adhf.dev";function NT(e){return e==="adhf.dev"||e==="adhdev-web.pages.dev"||e==="localhost"||e==="127.0.0.1"?Ul:jT}function CT(){return typeof window>"u"?Ul:NT(window.location.hostname)}function _T(){const e=CT();return{unix:{cmd:`curl -fsSL ${e}/install | sh`,shell:"Terminal",prompt:"$ "},powershell:{cmd:`irm ${e}/install.ps1 | iex`,shell:"PowerShell",prompt:"PS> "},cmd:{cmd:`curl -fsSL ${e}/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd`,shell:"CMD",prompt:"> "}}}const AT={"claude-cli":{monogram:"CL",hue:"#D97757"},"codex-cli":{monogram:"CX",hue:"#10A37F"},"gemini-cli":{monogram:"GM",hue:"#4285F4"},"kimi-cli":{monogram:"KM",hue:"#6366F1"},"antigravity-cli":{monogram:"AG",hue:"#8B5CF6"},"cursor-cli":{monogram:"CU",hue:"#64748B"},"opencode-cli":{monogram:"OC",hue:"#CA8A04"},"grok-cli":{monogram:"GK",hue:"#475569"},antigravity:{monogram:"AG",hue:"#8B5CF6"},cursor:{monogram:"CU",hue:"#64748B"},kiro:{monogram:"KI",hue:"#F59E0B"},pearai:{monogram:"PA",hue:"#22C55E"},trae:{monogram:"TR",hue:"#EF4444"},vscode:{monogram:"VS",hue:"#3B82F6"},vscodium:{monogram:"VC",hue:"#2DD4BF"},windsurf:{monogram:"WS",hue:"#0EA5E9"},cline:{monogram:"CN",hue:"#0284C7"},"roo-code":{monogram:"RC",hue:"#F97316"}},Jm=["#0EA5E9","#8B5CF6","#10B981","#F59E0B","#EF4444","#14B8A6","#6366F1","#EC4899","#84CC16","#F97316","#06B6D4","#A855F7"];function TT(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 IT(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 Fi({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(Kw,{size:s,className:r});const i=AT[o],l=(i==null?void 0:i.monogram)??IT((t==null?void 0:t.trim())||o.replace(/-cli$/,"")),d=(i==null?void 0:i.hue)??Jm[TT(o||a)%Jm.length];return n.jsx("span",{"aria-hidden":!0,className:`inline-flex shrink-0 select-none items-center justify-center font-semibold ${r??""}`,style:{width:s,height:s,borderRadius:Math.max(4,Math.round(s*.3)),backgroundColor:`${d}21`,border:`1px solid ${d}4D`,color:d,fontSize:Math.max(7,Math.round(s*.42)),letterSpacing:"0.02em",lineHeight:1},children:l})}function Xm({direction:e}){return n.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?n.jsx("polyline",{points:"18 15 12 9 6 15"}):n.jsx("polyline",{points:"6 9 12 15 18 9"})})}function MT({value:e,availableProviders:t,onChange:s,disabled:r=!1,saveButton:o}){const{t:a}=he("common"),[i,l]=c.useState(""),d=c.useMemo(()=>new Map(t.map(b=>[b.type,b])),[t]),u=c.useMemo(()=>Eo(e),[e]),m=u.filter(b=>!d.has(b)).length,h=t.filter(b=>!u.includes(b.type)),p=()=>{i&&(s(W1(u,i)),l(""))};return n.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[n.jsx("div",{className:"flex flex-col gap-2",children:u.length===0?n.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-300",children:a("settings.providerPriority.emptyWarning")}):u.map((b,f)=>{const x=d.get(b),g=!!x;return n.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${g?"bg-bg-primary":"bg-bg-primary/40"}`,children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsxs("span",{className:"text-3xs font-semibold text-text-muted",children:["#",f+1]}),n.jsx(Fi,{type:b,label:x==null?void 0:x.label,size:14}),n.jsx("span",{className:`font-mono text-xs ${g?"text-text-primary":"text-text-muted"}`,children:b}),g?n.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-4xs font-semibold text-green-400",children:a("settings.providerPriority.available")}):n.jsx(Qt,{content:a("settings.providerPriority.keptUntilDetected"),children:n.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-4xs font-semibold text-amber-400",children:a("settings.providerPriority.notOnMachine")})})]}),x&&n.jsx("div",{className:"mt-1 text-3xs text-text-muted",children:`${x.label} · ${x.statusLabel}`})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":a("settings.providerPriority.moveUp"),disabled:r||f===0,title:a("settings.providerPriority.moveUp"),onClick:()=>s(Lm(u,b,"up")),children:n.jsx(Xm,{direction:"up"})}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":a("settings.providerPriority.moveDown"),disabled:r||f===u.length-1,title:a("settings.providerPriority.moveDown"),onClick:()=>s(Lm(u,b,"down")),children:n.jsx(Xm,{direction:"down"})}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>s(U1(u,b)),children:a("settings.providerPriority.remove")})]})]},b)})}),n.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[n.jsxs("label",{className:"flex-1 text-2xs text-text-secondary",children:[n.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:a("settings.providerPriority.addCliLabel")}),n.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:b=>l(b.target.value),disabled:r||h.length===0,children:[n.jsx("option",{value:"",children:h.length?a("settings.providerPriority.selectProvider"):a("settings.providerPriority.noMoreProviders")}),h.map(b=>n.jsxs("option",{value:b.type,children:[b.label," (",b.type,")"]},b.type))]})]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:r||!i,onClick:p,children:a("settings.providerPriority.addProvider")}),o]}),n.jsx("div",{className:"mt-2 flex items-center gap-1 text-2xs text-text-muted",children:n.jsx(rt,{content:[a("settings.providerPriority.orderHint"),m>0?a("settings.providerPriority.undetectedHint",{count:m}):""].filter(Boolean).join(`
|
|
59
|
+
|
|
60
|
+
`)})})]})}function RT(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function yg(e,t){const s=RT(e);return{daemonId:s.daemonId,payload:{...t,...s.targetSessionId&&!t.targetSessionId?{targetSessionId:s.targetSessionId}:{}}}}const PT=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],ET=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"grok-cli",name:"Grok",icon:"🛰️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],LT=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}];function vg({icon:e,title:t,subtitle:s,subtitleInline:r=!1,badge:o,actions:a,className:i}){return n.jsxs("div",{className:ct("dashboard-header",i),children:[n.jsxs("div",{children:[n.jsxs("h1",{className:"header-title flex items-center gap-2",children:[n.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,s&&!r&&n.jsx(rt,{content:s}),o&&n.jsxs("span",{className:"text-3xs font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[o.count!==void 0?o.count:""," ",o.text]})]}),s&&r&&n.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:s})]}),a&&n.jsx("div",{className:"flex gap-2",children:a})]})}function Lo({icon:e,title:t,subtitle:s,subtitleInline:r,badge:o,actions:a,widthClassName:i="max-w-6xl",contentClassName:l,children:d}){return n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsx(vg,{icon:e,title:t,subtitle:s,subtitleInline:r,badge:o,actions:a}),n.jsx("div",{className:"page-content",children:n.jsx("div",{className:ct("mx-auto flex w-full flex-col gap-4",i,l),children:d})})]})}const Kl="adhdev:themechange";function DT(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function dr(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ur(e){return e==="system"?DT():e}function wg(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function _a(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Kl,{detail:{preference:e,theme:t}}))}function OT(){const e=dr(),t=ur(e);wg(t),_a(e,t)}function Hi(){const[e,t]=c.useState(dr),[s,r]=c.useState(()=>ur(dr()));c.useEffect(()=>{wg(s)},[s]),c.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const u=d.matches?"light":"dark";r(u),_a("system",u)}};return i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[e]),c.useEffect(()=>{const i=d=>{const u=d.detail||{},m=u.preference,h=u.theme;t(m==="dark"||m==="light"||m==="system"?m:dr()),r(h==="dark"||h==="light"?h:ur(dr()))},l=d=>{if(d.key!=="theme")return;const u=dr(),m=ur(u);t(u),r(m)};return window.addEventListener(Kl,i),window.addEventListener("storage",l),()=>{window.removeEventListener(Kl,i),window.removeEventListener("storage",l)}},[]);const o=c.useCallback(i=>{const l=ur(i);t(i),r(l);try{localStorage.setItem("theme",i)}catch{}_a(i,l)},[]),a=c.useCallback(()=>{t(i=>{const l=i==="dark"?"light":i==="light"?"system":"dark",d=ur(l);r(d);try{localStorage.setItem("theme",l)}catch{}return _a(l,d),l})},[]);return{theme:s,preference:e,setPreference:o,cycleTheme:a,isDark:s==="dark"}}const Zm={dark:"Dark",light:"Light",system:"System"};function $T({collapsed:e}){const{preference:t,cycleTheme:s}=Hi(),r=t==="dark"?n.jsx(Vp,{size:16}):t==="light"?n.jsx(zp,{size:16}):n.jsx(Gp,{size:16});return n.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:s,title:`Theme: ${Zm[t]} (click to cycle)`,children:[n.jsx("span",{className:"nav-icon",children:r}),!e&&n.jsx("span",{className:"text-xs",children:Zm[t]})]})}const ql="adhdev:langchange";function FT(){const e=Qe.language;return Es(e)?e:Tf()}function HT(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ql,{detail:{language:e}}))}function BT(){const[e,t]=c.useState(FT);c.useEffect(()=>{const r=i=>{Es(i)&&t(i)},o=i=>{const l=i.detail||{};Es(l.language)&&t(l.language)},a=i=>{if(i.key!==Nl)return;const l=i.newValue;Es(l)&&l!==Qe.language&&(Qe.changeLanguage(l),Cl(l))};return Qe.on("languageChanged",r),window.addEventListener(ql,o),window.addEventListener("storage",a),()=>{Qe.off("languageChanged",r),window.removeEventListener(ql,o),window.removeEventListener("storage",a)}},[]);const s=c.useCallback(r=>{if(Es(r)){t(r);try{localStorage.setItem(Nl,r)}catch{}Qe.changeLanguage(r),Cl(r),HT(r)}},[]);return{language:e,setLanguage:s}}function WT({trigger:e,viewport:t,menu:s,variant:r,gap:o=6,margin:a=8}){const i=e.top-a,l=t.height-e.bottom-a,d=r==="sidebar";let u=d;d&&i<s.height&&l>i&&(u=!1),!d&&l<s.height&&i>l&&(u=!0);const m=u?i:l,h=Math.max(80,Math.min(s.height,m));let p;u?p=e.top-o-h:p=e.bottom+o,p=eh(p,a,Math.max(a,t.height-h-a));const b=eh(e.left,a,Math.max(a,t.width-s.width-a));return{top:p,left:b,maxHeight:h}}function eh(e,t,s){return Math.min(Math.max(e,t),s)}function UT({open:e}){return n.jsx("svg",{width:12,height:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:`lang-switch-caret${e?" open":""}`,children:n.jsx("polyline",{points:"6 9 12 15 18 9"})})}function KT({collapsed:e,variant:t="sidebar"}){const{language:s,setLanguage:r}=BT(),{t:o}=he("common"),[a,i]=c.useState(!1),[l,d]=c.useState(0),u=c.useRef(null),m=c.useRef(null),h=c.useRef(null),p=c.useId(),[b,f]=c.useState(null),x=c.useCallback(()=>{const T=m.current;if(!T)return;const M=T.getBoundingClientRect(),_=h.current,I=Math.max((_==null?void 0:_.offsetWidth)??0,168),D=(_==null?void 0:_.scrollHeight)??Ns.length*36+12;f(WT({trigger:{top:M.top,left:M.left,right:M.right,bottom:M.bottom,width:M.width,height:M.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:I,height:D},variant:t}))},[t]),g=Math.max(0,Ns.findIndex(T=>T.code===s)),v=Ns[g]??Ns[0],S=o("language.label",{defaultValue:"Language"}),A=o("language.select",{defaultValue:"Select language"}),k=T=>`${p}-opt-${T}`,w=c.useCallback(()=>{d(g),i(!0)},[g]),y=c.useCallback((T=!0)=>{var M;i(!1),T&&((M=m.current)==null||M.focus())},[]),N=c.useCallback(T=>{const M=Ns[T];M&&r(M.code),y()},[r,y]);c.useEffect(()=>{if(!a)return;const T=I=>{var D,L;return!!((D=u.current)!=null&&D.contains(I)||(L=h.current)!=null&&L.contains(I))},M=I=>{T(I.target)||i(!1)},_=I=>{T(I.target)||i(!1)};return document.addEventListener("pointerdown",M,!0),document.addEventListener("focusin",_,!0),()=>{document.removeEventListener("pointerdown",M,!0),document.removeEventListener("focusin",_,!0)}},[a]),c.useLayoutEffect(()=>{if(!a){f(null);return}x();const T=()=>x();return window.addEventListener("resize",T),window.addEventListener("scroll",T,!0),()=>{window.removeEventListener("resize",T),window.removeEventListener("scroll",T,!0)}},[a,x]),c.useEffect(()=>{var T;a&&b&&((T=h.current)==null||T.focus())},[a,b]);const j=T=>{const M=Ns.length-1;switch(T.key){case"ArrowDown":T.preventDefault(),d(_=>_>=M?0:_+1);break;case"ArrowUp":T.preventDefault(),d(_=>_<=0?M:_-1);break;case"Home":T.preventDefault(),d(0);break;case"End":T.preventDefault(),d(M);break;case"Enter":case" ":T.preventDefault(),N(l);break;case"Escape":T.preventDefault(),y();break;case"Tab":i(!1);break}},C=T=>{a||(T.key==="ArrowDown"||T.key==="ArrowUp"||T.key==="Enter"||T.key===" ")&&(T.preventDefault(),w())},E=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,P=t==="landing"||!e;return n.jsxs("div",{ref:u,className:"lang-switch",children:[n.jsxs("button",{ref:m,type:"button",className:E,"aria-haspopup":"listbox","aria-expanded":a,"aria-label":`${S}: ${v.label}`,title:`${S}: ${v.label}`,onClick:()=>a?y(!1):w(),onKeyDown:C,children:[n.jsx("span",{className:"nav-icon lang-switch-icon",children:n.jsx(Qp,{size:16})}),P&&n.jsx("span",{className:"lang-switch-label text-xs",children:v.label}),P&&n.jsx(UT,{open:a})]}),a&&typeof document<"u"&&An.createPortal(n.jsx("ul",{ref:h,role:"listbox",tabIndex:-1,"aria-label":A,"aria-activedescendant":k(l),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(b==null?void 0:b.top)??0,left:(b==null?void 0:b.left)??0,maxHeight:b==null?void 0:b.maxHeight,overflowY:"auto",visibility:b?"visible":"hidden"},onKeyDown:j,children:Ns.map((T,M)=>{const _=T.code===v.code,I=M===l;return n.jsxs("li",{id:k(M),role:"option","aria-selected":_,className:`lang-switch-option${I?" is-active":""}${_?" is-selected":""}`,onMouseEnter:()=>d(M),onClick:()=>N(M),children:[n.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:_?n.jsx(Cr,{size:14}):null}),n.jsx("span",{className:"lang-switch-option-label",children:T.label})]},T.code)})}),document.body)]})}const qT=[],zT=[];function Cc(e,t){return e?typeof e=="function"?e(t):e:null}const VT=c.memo(function({renderState:t,brand:s,navItems:r,sidebarSections:o,footerItems:a,footerInfo:i,footerActions:l,closeMobileMenu:d}){const{t:u}=he("common"),{collapsed:m,mobileMenuOpen:h}=t,p=f=>`nav-item${f.active?" active":""} cursor-pointer ${m?"justify-center py-2.5 px-0":""}${f.className?` ${f.className}`:""}`,b=f=>n.jsxs("div",{className:p(f),id:`nav-${f.id}`,onClick:()=>{f.onSelect(),d()},title:m?f.title??(typeof f.label=="string"?f.label:void 0):f.title,children:[n.jsx("span",{className:"nav-icon",children:f.icon}),!m&&f.label]},f.id);return n.jsxs("aside",{className:`sidebar ${h?"sidebar-open":""}`,children:[n.jsxs("div",{className:"sidebar-header",children:[n.jsx("div",{className:`sidebar-logo ${m?"justify-center gap-0":""}`,children:Cc(s,t)}),n.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":u("app.closeMenu"),onClick:d,children:n.jsx(Lt,{size:16})})]}),n.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),o.map(f=>n.jsxs("div",{className:f.className??"border-t border-border-subtle pt-2 mt-2",children:[!m&&f.title?n.jsx("div",{className:"px-3 py-1 text-3xs text-text-muted uppercase tracking-widest",children:f.title}):null,f.items.map(b)]},f.key)),n.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),Cc(i,t),n.jsx($T,{collapsed:m}),n.jsx(KT,{collapsed:m}),Cc(l,t)]})]})});function GT({children:e,brand:t,navItems:s,sidebarSections:r=qT,footerItems:o=zT,footerInfo:a,footerActions:i,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const{t:u}=he("common"),[m,h]=c.useState(!1),[p,b]=c.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),f=c.useCallback(()=>h(!0),[]),x=c.useCallback(()=>h(!1),[]),g=c.useCallback(()=>{b(S=>{const A=!S;try{localStorage.setItem(d,A?"1":"0")}catch{}return A})},[d]),v=c.useMemo(()=>({collapsed:p,mobileMenuOpen:m,openMobileMenu:f,closeMobileMenu:x,toggleCollapsed:g}),[p,m,f,x,g]);return n.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${p?" sidebar-collapsed":""}`,children:[n.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":u("app.openMenu"),onClick:f,children:[n.jsx("span",{className:"mobile-menu-icon"}),n.jsx("span",{className:"mobile-menu-icon"}),n.jsx("span",{className:"mobile-menu-icon"})]}),m&&n.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":u("app.closeMenu"),onClick:x,onKeyDown:S=>S.key==="Escape"&&x()}),n.jsx(VT,{renderState:v,brand:t,navItems:s,sidebarSections:r,footerItems:o,footerInfo:a,footerActions:i,closeMobileMenu:x}),n.jsx("main",{className:"main-content relative",children:n.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function vt({title:e,icon:t,description:s,descriptionInline:r=!1,accentColor:o,className:a,collapsible:i,defaultOpen:l=!0,badge:d,action:u,children:m}){const[h,p]=c.useState(l),b=i?h:!0,f=()=>p(v=>!v),x=n.jsxs(n.Fragment,{children:[t&&n.jsx("span",{children:t}),n.jsx("span",{children:e})]}),g=(e||s||u)&&n.jsxs("div",{className:ct("flex items-start justify-between gap-3",b&&"mb-4",i&&"cursor-pointer"),onClick:i?f:void 0,children:[n.jsxs("div",{className:"min-w-0",children:[e&&n.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[i?n.jsx("button",{type:"button",className:"inline-flex items-center gap-1.5 bg-transparent border-none p-0 text-left font-semibold text-text-primary cursor-pointer",onClick:v=>{v.stopPropagation(),f()},"aria-expanded":b,children:x}):x,s&&!r&&n.jsx("span",{onClick:v=>v.stopPropagation(),className:"inline-flex",children:n.jsx(rt,{content:s})}),d]}),s&&(r||!e)&&n.jsx("p",{className:"text-xxs text-text-muted mt-1",children:s})]}),u&&n.jsx("div",{className:"flex shrink-0 items-center gap-2",onClick:v=>v.stopPropagation(),children:u}),i&&n.jsx("span",{className:ct("mt-0.5 shrink-0 text-text-muted transition-transform select-none",b?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return n.jsxs("div",{className:ct("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",o&&"border-l-[3px]",a),style:o?{borderLeftColor:o}:void 0,children:[g,b&&m]})}function Bi({icon:e,title:t,description:s,action:r,className:o,variant:a="default"}){return a==="compact"?n.jsxs("div",{className:ct("flex flex-wrap items-center justify-center gap-2 rounded-xl border border-dashed border-border-subtle px-4 py-5 text-center text-xs text-text-muted",o),children:[e&&n.jsx("span",{className:"flex items-center opacity-60","aria-hidden":!0,children:e}),n.jsx("span",{className:"font-medium text-text-secondary",children:t}),s?n.jsx(rt,{content:s}):null,r]}):n.jsxs("div",{className:ct("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),children:[e&&n.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),n.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s?n.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:s}):n.jsx("div",{className:"mb-3"}),r]})}const YT={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},QT={error:tn,warning:tn,success:vi,info:Co};function Bt({variant:e,children:t,onDismiss:s,className:r}){return n.jsxs("div",{className:ct("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-xxs",YT[e],r),children:[n.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const o=QT[e];return n.jsx(o,{size:14})})(),n.jsx("span",{children:t})]}),s&&n.jsx("button",{onClick:s,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Ht({label:e,hint:t,hintInline:s=!1,children:r,className:o}){return n.jsxs("div",{className:ct("mb-5",o),children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1",children:[n.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider",children:e}),t&&!s&&n.jsx(rt,{content:t})]}),r,t&&s&&n.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function Nn(e){const{className:t,...s}=e;return n.jsx("input",{...s,className:ct("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const JT={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Qn=c.forwardRef(function({variant:t="secondary",size:s="md",type:r,className:o,...a},i){return n.jsx("button",{ref:i,type:r??"button",className:ct("btn",JT[t],s==="sm"&&"btn-sm",o),...a})}),XT=c.forwardRef(function({options:t,children:s,className:r,...o},a){return n.jsx("select",{ref:a,className:ct("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",r),...o,children:s??(t==null?void 0:t.map(i=>n.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})});function Yd({tabs:e,activeKey:t,onSelect:s,variant:r="pill",ariaLabel:o,className:a,tabIdPrefix:i,panelIdPrefix:l}){const d=r==="underline",u=m=>{var x;if(m.key!=="ArrowRight"&&m.key!=="ArrowLeft"&&m.key!=="Home"&&m.key!=="End")return;const h=Math.max(0,e.findIndex(g=>g.key===t)),p=m.key==="Home"?0:m.key==="End"?e.length-1:(h+(m.key==="ArrowRight"?1:-1)+e.length)%e.length,b=e[p];if(!b)return;m.preventDefault(),s(b.key),(x=m.currentTarget.querySelectorAll('[role="tab"]')[p])==null||x.focus()};return n.jsx("div",{className:ct(d?"flex shrink-0 items-center gap-1 overflow-x-auto border-b border-border-subtle px-4 md:px-6 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden":"mb-5 inline-flex w-full flex-wrap items-center gap-1 rounded-xl border border-border-subtle bg-bg-secondary/60 p-1 sm:w-fit",a),role:"tablist","aria-label":o,onKeyDown:u,children:e.map(m=>{const h=m.key===t;return n.jsxs("button",{id:i?`${i}-${m.key}`:void 0,type:"button",role:"tab","aria-selected":h,"aria-controls":l?`${l}-${m.key}`:void 0,tabIndex:h?0:-1,className:ct(d?["-mb-px flex shrink-0 cursor-pointer items-center gap-1.5 whitespace-nowrap border-b-2 bg-transparent px-3 py-2.5 text-xxs font-medium transition-colors",h?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"]:["flex flex-1 items-center justify-center gap-1.5 rounded-lg px-3.5 py-1.5 text-xxs font-medium transition-colors sm:flex-none",h?"bg-bg-card text-text-primary shadow-sm border border-border-default":"text-text-muted border border-transparent hover:text-text-secondary hover:bg-white/[0.03]"]),onClick:()=>s(m.key),children:[m.icon,m.label,m.trailing]},m.key)})})}function Sg({tabs:e,defaultTabKey:t,activeKey:s,onTabChange:r,variant:o="pill",ariaLabel:a,className:i,tabListClassName:l,panelClassName:d,tabIdPrefix:u,unmountInactivePanels:m=!1}){var g;const[h,p]=c.useState(t??((g=e[0])==null?void 0:g.key)),b=s!==void 0,f=b?s:h,x=v=>{b||p(v),r==null||r(v)};return n.jsxs("div",{className:i,children:[n.jsx(Yd,{tabs:e,activeKey:f,onSelect:x,variant:o,ariaLabel:a,className:l,tabIdPrefix:u}),e.map(v=>{const S=v.key===f;return m&&!S?null:n.jsx("div",{role:"tabpanel","aria-labelledby":u?`${u}-${v.key}`:void 0,className:S?ct("flex flex-col gap-4",d):"hidden",children:v.content},v.key)})]})}class ZT extends c.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,s){console.error("[ErrorBoundary] Uncaught error:",t,s)}render(){return this.state.hasError?n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",background:"var(--bg-primary, #0a0e1a)",color:"var(--text-secondary, #c4c9d4)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:n.jsxs("div",{style:{textAlign:"center",maxWidth:420,padding:24},children:[n.jsx("div",{style:{display:"flex",justifyContent:"center",marginBottom:16},children:n.jsx(tn,{size:44,className:"text-status-warning"})}),n.jsx("h2",{style:{margin:"0 0 8px",fontSize:18,fontWeight:600,color:"var(--text-primary, #eee)"},children:Qe.t("app.errorBoundary.title")}),n.jsx("p",{style:{margin:"0 0 20px",fontSize:14,opacity:.7,lineHeight:1.5},children:Qe.t("app.errorBoundary.description")}),n.jsx("button",{onClick:()=>window.location.reload(),style:{padding:"10px 24px",borderRadius:8,border:"1px solid rgba(99, 102, 241, 0.4)",background:"rgba(99, 102, 241, 0.1)",color:"#a5b4fc",fontSize:14,fontWeight:500,cursor:"pointer"},children:Qe.t("app.errorBoundary.reload")})]})}):this.props.children}}const e2={sm:"w-[34px] h-[19px]",md:"w-[40px] h-[22px]"},th={sm:{base:"w-[16px] h-[16px]",on:"translate-x-[15px]"},md:{base:"w-[19px] h-[19px]",on:"translate-x-[18px]"}};function Pr({checked:e,onChange:t,disabled:s=!1,busy:r=!1,size:o="md",id:a,title:i,className:l,as:d="button",...u}){const m=s||r,h=f=>{f.stopPropagation(),!m&&t(!e)},p={id:a,title:i,role:"switch","aria-checked":e,"aria-disabled":s||void 0,"aria-busy":r||void 0,"aria-label":u["aria-label"],"aria-labelledby":u["aria-labelledby"],"aria-describedby":u["aria-describedby"],"data-state":e?"on":"off",className:ct("relative inline-flex shrink-0 items-center rounded-full border-none bg-transparent p-0 outline-none","focus-visible:ring-2 focus-visible:ring-accent/60 focus-visible:ring-offset-1 focus-visible:ring-offset-bg-primary",s?"cursor-not-allowed opacity-50":r?"cursor-wait opacity-60":"cursor-pointer",l)},b=n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,className:ct("inline-block rounded-full transition-colors duration-200 ease-in-out",e2[o]),style:{backgroundColor:e?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),n.jsx("span",{"aria-hidden":!0,className:ct("absolute left-[1.5px] top-[1.5px] rounded-full bg-white shadow-[0_1px_2px_rgba(0,0,0,0.15)] transition-transform duration-200 ease-in-out",th[o].base,e?th[o].on:"translate-x-0")})]});return d==="span"?n.jsx("span",{...p,tabIndex:s?-1:0,onClick:h,onKeyDown:f=>{(f.key===" "||f.key==="Enter")&&(f.preventDefault(),h(f))},children:b}):n.jsx("button",{type:"button",...p,disabled:s,onClick:h,children:b})}function Wi({onClick:e,refreshing:t=!1,disabled:s=!1,label:r,size:o=14,showLabel:a=!1,className:i}){const{t:l}=he("common"),d=r??l("common.refresh");return n.jsxs("button",{type:"button",onClick:e,disabled:s||t,"aria-label":a?void 0:d,"aria-busy":t||void 0,title:d,className:ct("inline-flex shrink-0 items-center justify-center gap-1.5 rounded-lg border border-border-subtle bg-transparent text-text-muted transition-colors","hover:border-border-default hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-50","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent",a?"px-2.5 py-1 text-xs font-medium":"h-8 w-8",i),children:[n.jsx(Ar,{size:o,className:t?"animate-spin":void 0}),a&&n.jsx("span",{children:d})]})}const o3={recentFailures:0};function a3(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}const t2={online:"mesh.nodeHealth.online",dirty:"mesh.nodeHealth.dirty",offline:"mesh.nodeHealth.offline",degraded:"mesh.nodeHealth.degraded",wrong_branch:"mesh.nodeHealth.wrongBranch",unknown:"mesh.nodeHealth.unknown",enabled:"mesh.nodeHealth.enabled",pending:"mesh.nodeHealth.pending",assigned:"mesh.nodeHealth.assigned",completed:"mesh.nodeHealth.completed",failed:"mesh.nodeHealth.failed"};function n2(e,t){const s=t2[(e||"unknown").toLowerCase()];return s?t(s):String(e)}function i3(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function kg(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return{bucket:"other",normalized:""};const r=fi(t)??t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?{bucket:"awaiting_approval",normalized:r}:r.includes("generating")||r.includes("running")||r.includes("busy")?{bucket:"generating",normalized:r}:r.includes("failed")||r==="error"||r.includes("stopped")||r.includes("interrupted")?{bucket:"failed",normalized:r}:r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?{bucket:"idle",normalized:r}:{bucket:"other",normalized:r}}function c3(e){const{bucket:t,normalized:s}=kg(e);if(!s&&t==="other")return"unknown";switch(t){case"awaiting_approval":return"awaiting approval";case"generating":return"generating";case"idle":return"idle";default:return s.replace(/_/g," ")}}function l3(e,t){const{bucket:s,normalized:r}=kg(e);switch(s){case"awaiting_approval":return t("sessionStatus.awaitingApproval");case"generating":return t("sessionStatus.generating");case"idle":return t("sessionStatus.idle");case"failed":return r.includes("stopped")||r.includes("interrupted")?t("sessionStatus.stopped"):t("sessionStatus.failed");default:return r?r==="starting"||r==="pending"||r==="launching"?t("sessionStatus.starting"):r.replace(/_/g," "):t("sessionStatus.unknown")}}function d3(e,t){if(e.isSelfCoordinator)return t("mesh.panel.statusCoordinator");const s=typeof e.role=="string"?e.role.trim():"";return!s||s==="worker"?t("mesh.panel.statusWorker"):s==="coordinator"?t("mesh.panel.statusCoordinator"):s}function s2(e){return e.startedAt||e.createdAt||null}function u3(e){const t=s2(e);if(!t)return"runtime age not reported";const s=Date.parse(t);if(!Number.isFinite(s))return"runtime age not reported";const r=Math.max(0,Math.floor((Date.now()-s)/1e3));if(r<60)return`${r}s`;const o=Math.floor(r/60);if(o<60)return`${o}m`;const a=Math.floor(o/60);return a<48?`${a}h ${o%60}m`:`${Math.floor(a/24)}d ${a%24}h`}function m3(e,t){const s=(d,u,m)=>t?t(d,m):u,r=e.git;if(!r)return e.gitProbePending?s("mesh.drift.probePending","Git probe pending"):s("mesh.drift.noGit","No git probe");const o=(r.staged??0)+(r.modified??0)+(r.untracked??0)+(r.deleted??0)+(r.renamed??0),a=[];r.branch&&a.push(r.branch),r.upstream&&r.upstreamStatus!=="fresh"&&a.push(s("mesh.drift.upstreamUnverified","upstream unverified")),r.upstreamStatus==="fresh"&&((r.ahead??0)>0||(r.behind??0)>0)&&a.push(`↑${r.ahead??0}/↓${r.behind??0}`),o>0&&a.push(s("mesh.drift.changed",`${o} dirty`,{count:o}));const i=(r.submodules??[]).filter(d=>d.dirty),l=(r.submodules??[]).filter(d=>d.outOfSync||d.error);return i.length>0&&a.push(s("mesh.drift.submoduleChanged",`${i.length} submodule dirty`,{count:i.length})),l.length>0&&a.push(s("mesh.drift.submoduleOutOfSync",`${l.length} submodule drift`,{count:l.length})),r.hasConflicts&&a.push(s("mesh.drift.conflicts","conflicts")),a.join(" · ")||s("mesh.drift.clean","Clean")}function r2(e){var r;const t=(r=e.nodeFacts)==null?void 0:r.quota;if(!t||typeof t!="object"||Array.isArray(t))return[];const s=[];for(const[o,a]of Object.entries(t))!a||typeof a!="object"||Array.isArray(a)||s.push({provider:o,quota:a});return s.sort((o,a)=>kr(o.provider).localeCompare(kr(a.provider)))}function jg(e){return Ay(e.daemonId)||e.machineId||e.nodeId}function h3(e){var s;const t=new Map;for(const r of e.nodes){const o=r.nodeFacts,a=jg(r);if(!a)continue;let i=t.get(a);i||(i={machineKey:a,label:"",nodeCount:0,hasReported:!1,quota:[]},t.set(a,i)),i.nodeCount+=1;const l=typeof(o==null?void 0:o.reportedAt)=="number"&&Number.isFinite(o.reportedAt)?o.reportedAt:void 0,d=l!==void 0&&(i.reportedAt===void 0||l>i.reportedAt);d&&(i.reportedAt=l),o&&(i.hasReported=!0);const u=r2(r);u.length>0&&(d||i.quota.length===0)&&(i.quota=u);const m=((s=o==null?void 0:o.daemonBuild)==null?void 0:s.version)||r.daemonBuildVersion;m&&(d||!i.daemonBuildVersion)&&(i.daemonBuildVersion=m)}for(const r of t.values())r.label=a2(e,r.machineKey);return[...t.values()].sort((r,o)=>r.label.localeCompare(o.label)||r.machineKey.localeCompare(o.machineKey))}function o2(e){const t=typeof e.worktreeBranch=="string"&&e.worktreeBranch.trim()?e.worktreeBranch.trim():"";if(t)return`⎇ ${t}`;const s=typeof e.nodeLabel=="string"&&e.nodeLabel.trim()?e.nodeLabel.trim():"";return s||(typeof e.workspace=="string"?e.workspace.replace(/[\\/]+$/,"").split(/[\\/]/).pop():"")||e.machineLabel||(e.nodeId?e.nodeId.slice(0,12):"node")}function p3(e){const t=o2(e),s=typeof e.machineLabel=="string"?e.machineLabel.trim():"";return!s||s===t?t:`${t} · ${s}`}function a2(e,t){var i,l,d;const s=[],r=[],o=[];for(const u of e.nodes){if(jg(u)!==t)continue;const h=(i=u.nodeFacts)==null?void 0:i.machineNickname;typeof h=="string"&&h.trim()&&s.push(h.trim());const p=u.machine,b=(p!=null&&p.sameMachine?p.coordinatorHostname:void 0)??((d=(l=p==null?void 0:p.identityEvidence)==null?void 0:l.find(x=>((x==null?void 0:x.label)==="hostname"||(x==null?void 0:x.label)==="machineName")&&typeof x.value=="string"&&x.value.trim()))==null?void 0:d.value);typeof b=="string"&&b.trim()&&r.push(b.trim().replace(/\.local$/i,""));const f=typeof u.machineLabel=="string"?u.machineLabel.trim():"";f&&f!==u.nodeId&&f!==u.daemonId&&f!==t&&o.push(f)}const a=u=>u.length===0?void 0:[...u].sort((m,h)=>m.localeCompare(h))[0];return a(s)??a(r)??a(o)??Ng(t)}function Ng(e){const t=e.replace(/^(daemon_|standalone_)/,"");return t.length<=20?t:`${t.slice(0,17)}…`}const f3={first_eligible:"In order",fitness:"Smart",least_loaded:"Smart",round_robin:"Smart (round-robin)",priority_only:"Smart (priority)"};function b3(e){if(e.startsWith("max_provider_parallel_reached:"))return`provider cap reached (${e.slice(30)})`;switch(e){case"global_max_parallel_tasks_reached":return"global parallel cap reached";case"node_has_active_assignment":return"already running a write task";default:return e.replace(/_/g," ")}}function g3(e){var s;const t=[];for(const r of e.nodes){const o=r.activeSessionDetails&&r.activeSessionDetails.length>0?r.activeSessionDetails:(r.activeSessions??[]).map(a=>({sessionId:a,workspace:r.workspace,isCached:!0}));for(const a of o)t.push({nodeId:r.nodeId,machineLabel:r.machineLabel,workspace:r.workspace,branch:((s=r.git)==null?void 0:s.branch)??null,nodeHealth:r.health,session:a})}return t}function x3(e){return e.assignedNodeId||e.targetNodeId||null}function nh(e){return e?e.slice(0,7):null}function i2(e,t){var a,i,l;const s=nh((a=e==null?void 0:e.git)==null?void 0:a.headCommit),r=((l=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:l.trim())||"";if(s||r)return[s,r].filter(Boolean).join(" · ");const o=t[0];return o?[nh(o.commit),o.message].filter(Boolean).join(" · "):null}function y3(e,t){const s=i2(e,t);return s||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function v3(e){const t=(e==null?void 0:e.result)??e,s=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(s==null?void 0:s.entries)?s.entries:[]}function w3(e){var o,a,i,l,d,u,m;const t=((o=e.selectedSessionEntry)==null?void 0:o.session.workspace)||((a=e.selectedSessionEntry)==null?void 0:a.workspace)||((l=(i=e.selectedNodeStatus)==null?void 0:i.git)==null?void 0:l.workspace)||((d=e.selectedNodeStatus)==null?void 0:d.workspace)||null;if(!t||!e.selectedSessionEntry&&!e.selectedNodeStatus)return null;const s=((u=e.selectedNodeStatus)==null?void 0:u.nodeId)||((m=e.selectedSessionEntry)==null?void 0:m.nodeId)||null,r=e.coordinatorDaemonId||null;return r&&s?{daemonId:r,workspace:t,nodeId:s}:null}function S3(e){var s;const t=e.source;return t!=null&&t.kind?t.kind:((s=t==null?void 0:t.connection)==null?void 0:s.source)??"mesh_status"}function k3(e,t){return t?e.nodes.find(s=>s.id===t)??null:null}function j3(e){var t,s,r,o;return[e.meshId,e.refreshedAt,e.nodes.length,((s=(t=e.queue)==null?void 0:t.summary)==null?void 0:s.active)??"",((o=(r=e.ledger)==null?void 0:r.summary)==null?void 0:o.recentFailures)??"",...e.nodes.map(a=>{var i,l,d,u,m,h,p,b,f,x,g,v,S,A,k,w,y,N,j,C,E,P;return[a.nodeId,a.daemonId??"",a.machineId??"",a.machineLabel,a.machineStatus??"",((i=a.connection)==null?void 0:i.state)??"",((l=a.connection)==null?void 0:l.transport)??"",((d=a.connection)==null?void 0:d.source)??"",a.health,a.gitProbePending?1:0,((u=a.git)==null?void 0:u.branch)??"",((m=a.git)==null?void 0:m.upstream)??"",((h=a.git)==null?void 0:h.upstreamStatus)??"",((p=a.git)==null?void 0:p.ahead)??"",((b=a.git)==null?void 0:b.behind)??"",((f=a.git)==null?void 0:f.headCommit)??"",((x=a.git)==null?void 0:x.staged)??"",((g=a.git)==null?void 0:g.modified)??"",((v=a.git)==null?void 0:v.untracked)??"",((S=a.git)==null?void 0:S.deleted)??"",((A=a.git)==null?void 0:A.renamed)??"",(k=a.git)!=null&&k.hasConflicts?1:0,((w=a.git)==null?void 0:w.lastCheckedAt)??"",((y=a.activeSessions)==null?void 0:y.join(","))??"",((N=a.activeSessionDetails)==null?void 0:N.length)??"",((j=a.activeSessionDetails)==null?void 0:j.map(T=>[T.sessionId,T.providerType??"",T.state??"",T.chatStatus??"",T.lifecycle??"",T.role??"",T.isSelfCoordinator?1:0,T.statusNote??"",T.startedAt??"",T.createdAt??""].join("/")).join(","))??"",((C=a.providers)==null?void 0:C.join(","))??"",((E=a.providerPriority)==null?void 0:E.join(","))??"",a.error??"",(((P=a.git)==null?void 0:P.submodules)??[]).map(T=>[T.path,T.commit,T.dirty?1:0,T.outOfSync?1:0,T.error??""].join("/")).join(",")].join("|")})].join("::")}function N3(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function Vn({label:e,description:t,descriptionInline:s=!1,checked:r,disabled:o,onChange:a,extra:i}){const l=c.useId();return n.jsxs("div",{className:`flex justify-between items-center ${o?"opacity-60":""}`,children:[n.jsxs("div",{className:"pr-4 min-w-0",children:[n.jsxs("div",{className:"font-medium text-sm flex items-center gap-1",children:[n.jsx("span",{id:l,children:e}),t&&!s&&n.jsx(rt,{content:t})]}),t&&s&&n.jsx("div",{className:"text-2xs text-text-muted mt-0.5",children:t})]}),n.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,n.jsx(Pr,{checked:r,disabled:o,onChange:a,"aria-labelledby":l})]})]})}const c2=["default","claude-cli","codex-cli","antigravity-cli"];function l2({daemonId:e,knownCliTypes:t=c2,embedded:s=!1}){const{t:r}=he("common"),{sendCommand:o}=wt(),[a,i]=c.useState({}),[l,d]=c.useState({}),[u,m]=c.useState(!0),[h,p]=c.useState(null),[b,f]=c.useState(null),[x,g]=c.useState(""),[v,S]=c.useState(!1),A=s||v,[k,w]=c.useState(null),y=c.useCallback(async()=>{if(e){m(!0),f(null);try{const _=await o(e,"list_coordinator_prompts",{}),I=_!=null&&_.result&&typeof _.result=="object"?_.result:_;if(!(I!=null&&I.success)){f((I==null?void 0:I.error)||r("settings.coordinatorPrompts.loadFailed"));return}const D=I.entries||{};g(I.dir||"");const L={};for(const $ of t)L[$]=D[$]||{override:"",append:""};for(const $ of Object.keys(D))L[$]||(L[$]=D[$]);i(L),d(JSON.parse(JSON.stringify(L)))}catch(_){f((_==null?void 0:_.message)||String(_))}finally{m(!1)}}},[o,e,t,r]);c.useEffect(()=>{y()},[y]);const N=c.useCallback(async(_,I)=>{var D;if(e){p(`${_}:${I}`),f(null);try{const L=((D=a[_])==null?void 0:D[I])||"",$=await o(e,"write_coordinator_prompt",{key:_,kind:I,content:L}),q=$!=null&&$.result&&typeof $.result=="object"?$.result:$;if(!(q!=null&&q.success)){f((q==null?void 0:q.error)||r("settings.coordinatorPrompts.saveFailed"));return}d(G=>({...G,[_]:{...G[_]||{override:"",append:""},[I]:L}}))}catch(L){f((L==null?void 0:L.message)||String(L))}finally{p(null)}}},[o,e,a,r]),j=c.useMemo(()=>(_,I)=>{var D,L;return(((D=a[_])==null?void 0:D[I])||"")!==(((L=l[_])==null?void 0:L[I])||"")},[a,l]),C=c.useCallback(async _=>{j(_,"override")&&await N(_,"override"),j(_,"append")&&await N(_,"append")},[j,N]),E=c.useCallback(_=>{const I=l[_];return!!(I&&((I.override||"").trim()||(I.append||"").trim()))},[l]),P=Object.keys(a),T=P.filter(E),M=k&&a[k]?k:P[0];return e?A?n.jsxs("div",{className:"flex flex-col gap-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1 text-xs text-text-muted",children:[n.jsx("span",{className:"truncate font-mono text-2xs",children:x||"~/.adhdev/coordinator-prompts/"}),n.jsx(rt,{content:n.jsxs("span",{children:[r("settings.coordinatorPrompts.intro")," ",x||"~/.adhdev/coordinator-prompts/",`
|
|
61
|
+
|
|
62
|
+
`,n.jsx(Da,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:n.jsx("strong",{})}})," ",n.jsx(Da,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:n.jsx("strong",{})}}),`
|
|
63
|
+
|
|
64
|
+
`,r("settings.coordinatorPrompts.resetHint")," ",r("settings.coordinatorPrompts.placeholdersHint")," ",n.jsxs("span",{className:"font-mono",children:["{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}"]}),"…"]})})]}),!s&&n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>S(!1),children:r("settings.coordinatorPrompts.collapseLabel")})]}),b&&n.jsx("div",{className:"text-xs text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:b}),u&&n.jsx("div",{className:"text-xs text-text-muted",children:r("settings.coordinatorPrompts.loading")}),P.length>0&&n.jsx(Sg,{activeKey:M,onTabChange:w,ariaLabel:r("settings.coordinatorPrompts.tabsAriaLabel"),tabIdPrefix:"coordinator-prompt-tab",tabs:P.map(_=>{const I=a[_],D=j(_,"override")||j(_,"append");return{key:_,label:n.jsxs("span",{className:"flex items-center gap-1.5 font-mono text-xs",children:[_,E(_)&&n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-accent-primary",title:r("settings.coordinatorPrompts.customizedBadge")}),D&&n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:"var(--status-warning)"},"aria-hidden":!0})]}),content:n.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[n.jsx("label",{className:"block text-2xs uppercase tracking-wide text-text-muted mb-1",children:r("settings.coordinatorPrompts.overrideLabel")}),n.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-xs font-mono text-text-primary",rows:4,value:I.override,onChange:L=>i($=>({...$,[_]:{...$[_],override:L.target.value}})),placeholder:r("settings.coordinatorPrompts.overridePlaceholder"),disabled:h===`${_}:override`}),n.jsx("div",{className:"mb-3"}),n.jsx("label",{className:"block text-2xs uppercase tracking-wide text-text-muted mb-1",children:r("settings.coordinatorPrompts.appendLabel")}),n.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-xs font-mono text-text-primary",rows:3,value:I.append,onChange:L=>i($=>({...$,[_]:{...$[_],append:L.target.value}})),placeholder:r("settings.coordinatorPrompts.appendPlaceholder"),disabled:h===`${_}:append`}),n.jsx("div",{className:"mt-2 flex justify-end",children:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm","data-testid":"coordinator-prompt-save",onClick:()=>void C(_),disabled:!!(h!=null&&h.startsWith(`${_}:`))||!D,children:h!=null&&h.startsWith(`${_}:`)?r("settings.coordinatorPrompts.saving"):r(D?"settings.coordinatorPrompts.save":"settings.coordinatorPrompts.saved")})})]})}})})]}):n.jsxs("div",{className:"flex flex-col gap-3",children:[b&&n.jsx("div",{className:"text-xs text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:b}),n.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[n.jsx("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5 text-xs text-text-muted",children:u?n.jsx("span",{children:r("settings.coordinatorPrompts.loading")}):T.length===0?n.jsx("span",{children:r("settings.coordinatorPrompts.collapsedNone")}):n.jsxs(n.Fragment,{children:[n.jsxs("span",{children:[r("settings.coordinatorPrompts.customizedBadge"),":"]}),T.map(_=>n.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-accent-primary/10 px-1.5 py-0.5 font-mono text-2xs text-accent-primary",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-accent-primary","aria-hidden":!0}),_]},_))]})}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>S(!0),children:r("settings.coordinatorPrompts.expandLabel")})]})]}):n.jsx("div",{className:"text-xs text-text-muted",children:r("settings.coordinatorPrompts.connectDaemon")})}const d2=[{id:"dark",labelKey:"settings.appearance.modeDark",icon:Vp},{id:"light",labelKey:"settings.appearance.modeLight",icon:zp},{id:"system",labelKey:"settings.appearance.modeSystem",icon:Gp}];function u2(){const{preference:e,setPreference:t}=Hi(),{t:s}=he("common");return n.jsx("div",{className:"flex gap-2",children:d2.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 m2(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 h2(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function _c(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function sh(e){const{r:t,g:s,b:r}=h2(e);return .2126*_c(t)+.7152*_c(s)+.0722*_c(r)}function rh(e,t){const s=sh(e),r=sh(t),o=Math.max(s,r),a=Math.min(s,r);return(o+.05)/(a+.05)}function Cg(e){const t=m2(e);if(!t)return"#111827";const s="#111827",r="#ffffff";return rh(t,s)>=rh(t,r)?s:r}const zl={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},Vl={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},p2=[{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"}}}],_g="adhdev-chat-theme",Ag="adhdev-chat-theme-custom";function Aa(){if(typeof window>"u")return"ember";try{return localStorage.getItem(_g)||"ember"}catch{return"ember"}}function jn(e){try{const t=localStorage.getItem(Ag);if(t){const s=JSON.parse(t);return{...e==="dark"?zl:Vl,...s[e]}}}catch{}return e==="dark"?zl:Vl}function sa(e,t){try{localStorage.setItem(Ag,JSON.stringify({dark:e,light:t}))}catch{}}function bn(e,t){const s=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16);return`rgba(${s}, ${r}, ${o}, ${t})`}function si(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 f2={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function mo(e,t){var o;const s=(o=f2[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",si(s,24)),r.style.setProperty("--accent-on-primary",Cg(s)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${s}, ${si(s,18)})`),r.style.setProperty("--border-accent",bn(s,.35)),r.style.setProperty("--nav-active-bg",bn(s,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${s}, 0 0 12px ${bn(s,.06)}`)}function $s(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",bn(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",bn(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",bn(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",bn(e.borderSubtle,.5)),t.style.setProperty("--border-default",bn(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",si(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Cg(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${si(e.accentColor,40)})`),t.style.setProperty("--border-accent",bn(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",bn(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${bn(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${bn(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Qd(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(s=>e.style.removeProperty(s))}function b2(e){try{localStorage.setItem(_g,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Fs()?"dark":"light";$s(jn(t))}else Qd(),mo(e,Fs()?"dark":"light")}function g2(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Aa();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Fs()?"dark":"light";$s(jn(t))}else Qd(),mo(e,Fs()?"dark":"light")}function Fs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Gt({label:e,value:t,onChange:s}){return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[n.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[n.jsx("input",{type:"color",value:t,onChange:r=>s(r.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),n.jsx("input",{type:"text",value:t,onChange:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&s(r.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Gr({title:e,children:t}){return n.jsxs("div",{style:{marginBottom:14},children:[n.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function x2({dark:e,onColorsChange:t}){const{t:s}=he("common"),r=e?"dark":"light",[o,a]=c.useState(()=>jn(r));c.useEffect(()=>{a(jn(r))},[r]);const i=c.useCallback((l,d)=>{a(u=>{const m={...u,[l]:d},p=jn(r==="dark"?"light":"dark");return r==="dark"?sa(m,p):sa(p,m),$s(m),t(m),m})},[r,t]);return n.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[n.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[s("settings.theme.customEditorTitle"),n.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:s(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[n.jsxs("div",{children:[n.jsxs(Gr,{title:s("settings.theme.sectionAppBackground"),children:[n.jsx(Gt,{label:s("settings.theme.colorBackground"),value:o.bgPrimary,onChange:l=>i("bgPrimary",l)}),n.jsx(Gt,{label:s("settings.theme.colorSurface"),value:o.bgSecondary,onChange:l=>i("bgSecondary",l)}),n.jsx(Gt,{label:s("settings.theme.colorCard"),value:o.surfacePrimary,onChange:l=>i("surfacePrimary",l)})]}),n.jsxs(Gr,{title:s("settings.theme.sectionAppText"),children:[n.jsx(Gt,{label:s("settings.theme.colorPrimary"),value:o.textPrimary,onChange:l=>i("textPrimary",l)}),n.jsx(Gt,{label:s("settings.theme.colorSecondary"),value:o.textSecondary,onChange:l=>i("textSecondary",l)}),n.jsx(Gt,{label:s("settings.theme.colorMuted"),value:o.textMuted,onChange:l=>i("textMuted",l)})]}),n.jsxs(Gr,{title:s("settings.theme.sectionBordersAccent"),children:[n.jsx(Gt,{label:s("settings.theme.colorBorderSubtle"),value:o.borderSubtle,onChange:l=>i("borderSubtle",l)}),n.jsx(Gt,{label:s("settings.theme.colorBorderDefault"),value:o.borderDefault,onChange:l=>i("borderDefault",l)}),n.jsx(Gt,{label:s("settings.theme.colorAccent"),value:o.accentColor,onChange:l=>i("accentColor",l)})]})]}),n.jsxs("div",{children:[n.jsxs(Gr,{title:s("settings.theme.sectionChatBubbles"),children:[n.jsx(Gt,{label:s("settings.theme.colorUserBubble"),value:o.userBubble,onChange:l=>i("userBubble",l)}),n.jsx(Gt,{label:s("settings.theme.colorUserText"),value:o.userText,onChange:l=>i("userText",l)}),n.jsx(Gt,{label:s("settings.theme.colorAgentBubble"),value:o.assistantBubble,onChange:l=>i("assistantBubble",l)}),n.jsx(Gt,{label:s("settings.theme.colorAgentText"),value:o.assistantText,onChange:l=>i("assistantText",l)})]}),n.jsxs(Gr,{title:s("settings.theme.sectionChatLayout"),children:[n.jsx(Gt,{label:s("settings.theme.colorChatBg"),value:o.containerBg,onChange:l=>i("containerBg",l)}),n.jsx(Gt,{label:s("settings.theme.colorSendButton"),value:o.sendButton,onChange:l=>i("sendButton",l)}),n.jsx(Gt,{label:s("settings.theme.colorInputBorder"),value:o.inputBorder,onChange:l=>i("inputBorder",l)}),n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[n.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:s("settings.theme.labelBubbleRadius")}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[n.jsx("input",{type:"range",min:4,max:24,value:o.bubbleRadius,onChange:l=>i("bubbleRadius",Number(l.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),n.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[o.bubbleRadius,"px"]})]})]})]})]})]}),n.jsx("button",{onClick:()=>{const l=e?zl:Vl,u=jn(e?"light":"dark");e?sa(l,u):sa(u,l),a(l),$s(l),t(l)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:s("settings.theme.resetToDefaults")})]})}function y2(){const{t:e}=he("common"),[t,s]=c.useState(Aa),[r,o]=c.useState(!0),[a,i]=c.useState(()=>jn("dark"));c.useEffect(()=>{o(Fs());const u=new MutationObserver(()=>{const p=Fs();o(p);const b=Aa();b==="custom"?$s(jn(p?"dark":"light")):mo(b,p?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),h=()=>{const p=Fs();o(p);const b=Aa();b==="custom"?$s(jn(p?"dark":"light")):mo(b,p?"dark":"light")};return m.addEventListener("change",h),()=>{u.disconnect(),m.removeEventListener("change",h)}},[]),c.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?$s(jn(r?"dark":"light")):(Qd(),mo(t,r?"dark":"light"))},[t,r]),c.useEffect(()=>{i(jn(r?"dark":"light"))},[r]);const l=u=>{s(u),b2(u)},d=[...p2,{id:"custom",name:"Custom",description:e("settings.theme.presetCustomDescription"),preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return n.jsxs("div",{children:[n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(u=>{const m=t===u.id,h=r?u.preview.dark:u.preview.light,p=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return n.jsxs("button",{onClick:()=>l(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[n.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:h.containerBg},children:[n.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-3xs max-w-[75%]",style:{background:h.assistantBubble,border:h.assistantBorder,color:h.textColor},children:e("settings.theme.helloHelp")}),n.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-3xs max-w-[75%]",style:{background:h.userBubble,color:p},children:e("settings.theme.fixBug")}),n.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-3xs max-w-[75%]",style:{background:h.assistantBubble,border:h.assistantBorder,color:h.textColor},children:e("settings.theme.onIt")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[m&&n.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?e("settings.theme.customLabel"):u.name}),n.jsx("div",{className:"text-3xs text-text-muted",children:u.id==="custom"?u.description:e(`settings.theme.preset.${u.id}`,{defaultValue:u.description})})]})]})]},u.id)})}),t==="custom"&&n.jsx(x2,{dark:r,onColorsChange:u=>i(u)})]})}const Jd="adhdev_mobileDashboardMode_v1",Gl="adhdev:mobile-dashboard-mode-change";function Xd(){try{return localStorage.getItem(Jd)==="workspace"?"workspace":"chat"}catch{return"chat"}}function v2(e){if(typeof window>"u")return()=>{};const t=o=>{e(o??Xd())},s=o=>{const a=o.detail;t(a)},r=o=>{o.key&&o.key!==Jd||t()};return window.addEventListener(Gl,s),window.addEventListener("storage",r),()=>{window.removeEventListener(Gl,s),window.removeEventListener("storage",r)}}function w2(e){try{localStorage.setItem(Jd,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Gl,{detail:e}))}function S2(){const{t:e}=he("common"),[t,s]=c.useState(!0);return c.useEffect(()=>{s(Xd()==="chat")},[]),n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Cn,{size:15})," ",e("settings.mobileMode.label")]}),description:e(t?"settings.mobileMode.descriptionChat":"settings.mobileMode.descriptionWorkspace"),checked:t,onChange:r=>{s(r),w2(r?"chat":"workspace")},extra:n.jsx("span",{className:"text-2xs text-text-muted",children:e(t?"settings.mobileMode.chatMode":"settings.mobileMode.workspaceMode")})})}function k2(){const{t:e}=he("common"),[t,s]=c.useState(()=>xo());return c.useEffect(()=>uf(s),[]),n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(qp,{size:15})," ",e("settings.chatActivity.rowLabel")]}),description:e(t?"settings.chatActivity.descriptionOn":"settings.chatActivity.descriptionOff"),checked:t,onChange:r=>{s(r),df(r)}})}function j2({fontsSlot:e}){const{t}=he("common");return n.jsxs("div",{className:"flex flex-col gap-5",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:t("settings.appearance.modeLabel")}),n.jsx(u2,{})]}),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(y2,{})]}),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(k2,{})]}),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(S2,{})]})]})}function N2({children:e,fallback:t=null}){const[s,r]=c.useState(Vj);return c.useEffect(()=>{if(s)return;let o=!0;return Gj().then(()=>{o&&r(!0)}),()=>{o=!1}},[s]),n.jsx(n.Fragment,{children:s?e:t})}const C2=15e3,_2=15e3,oh=12,A2=8e3,T2=4e3,Ac=new Map,ah=new Map;function I2(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 M2(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 Tg(){const{sendCommand:e}=wt(),{injectEntries:t,getIdes:s}=br();return c.useCallback(async(r,o)=>{if(!r)return;const a=(o==null?void 0:o.minFreshMs)??_2,i=ah.get(r)||0;if(!(o!=null&&o.force)&&i>0&&Date.now()-i<a)return;const l=Ac.get(r);if(l)return l;const d=(async()=>{const u=await e(r,"get_machine_runtime_stats"),m=I2(u);if(!m)return;const h=s().find(b=>b.id===r),p=M2(h,r,m.machine,m.timestamp||Date.now());t([p]),ah.set(r,Date.now())})().finally(()=>{Ac.delete(r)});return Ac.set(r,d),d},[s,t,e])}function R2(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 P2(e,t){const{sendData:s}=wt(),{injectEntries:r,getIdes:o}=br(),a=Array.from(new Set(e.filter(Boolean))).join("|");c.useEffect(()=>{if(!(t!=null&&t.enabled)||!s)return;const i=a?a.split("|"):[];if(i.length===0)return;const l=i.map(d=>Fn.subscribe({sendData:s},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},m=>{const h=o().find(b=>b.id===d),p=R2(h,d,m);r([p])}));return()=>{l.forEach(d=>d())}},[a,o,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,s])}function E2(e,t){const{sendData:s}=wt(),[r,o]=c.useState(null),[a,i]=c.useState(!1);return c.useEffect(()=>{if(!e){o(null),i(!1);return}if(!(t!=null&&t.enabled)||!s){i(!1);return}o(null),i(!0);let l=null;const d=Fn.subscribe({sendData:s},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},u=>{l&&(clearTimeout(l),l=null),o(u.diagnostics),i(!1)});return d.initialSendAccepted?l=setTimeout(()=>{i(!1)},T2):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 L2=[{icon:yi,key:"welcome",visual:Qp},{icon:Cn,key:"realtimeChat",visual:qw},{icon:pd,key:"watchAndSteer",visual:Jp},{icon:Fa,key:"orchestrate",visual:Fa}],D2={icon:yi,key:"getStartedCloud",code:"curl -fsSL https://adhf.dev/install | sh"},O2={icon:yi,key:"allSetStandalone",visual:vi},Yl="adhdev:first-run-dialog";function $2({onClose:e,standalone:t=!1}){const[s,r]=c.useState(0),{t:o}=he("common"),a=[...L2,t?O2:D2],i=a[s],l=s===a.length-1;return c.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]),n.jsx(Un,{children:n.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:"var(--z-modal)",background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",padding:"calc(16px + env(safe-area-inset-top, 0px)) 16px calc(16px + env(safe-area-inset-bottom, 0px))",animation:"fadeIn 0.3s ease-out"},onClick:d=>{d.stopPropagation()},children:[n.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",maxHeight:"calc(100dvh - env(safe-area-inset-top, 0px) - env(safe-area-inset-bottom, 0px) - 32px)",overflowY:"auto",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[n.jsx("button",{onClick:e,"aria-label":o("app.onboardingTour.closeAria"),className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",style:{minWidth:44,minHeight:44,margin:-6,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:n.jsx(Lt,{size:20})}),n.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:a.map((d,u)=>n.jsx("div",{style:{width:u===s?24:8,height:8,borderRadius:4,background:u===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},u))}),n.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:(()=>{const d=i.visual||i.icon;return n.jsx(d,{size:44})})()}),n.jsxs("div",{style:{textAlign:"center"},children:[n.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[n.jsx(i.icon,{size:18})," ",o(`app.onboardingTour.${i.key}.title`)]}),n.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:o(`app.onboardingTour.${i.key}.desc`)}),i.code&&n.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[n.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),i.code]}),l&&n.jsxs("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:[o("app.onboardingTour.learnMore")," →"]})]}),n.jsx("div",{className:"flex justify-end items-center mt-6",children:n.jsx("button",{onClick:()=>l?e():r(d=>d+1),className:"btn btn-primary",children:l?`${o("app.onboardingTour.getStarted")} →`:`${o("app.onboardingTour.next")} →`})})]}),n.jsx("style",{children:`
|
|
65
|
+
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
66
|
+
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
67
|
+
`})]})})}function Ig(e){return e instanceof Error?e.message:String(e||"")}function F2(e){const t=Ig(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 H2(e){const t=Ig(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Mg({conversation:e,mode:t,ides:s,sendDaemonCommand:r,setCliViewModeOverrides:o}){if(!e||!ft(e))return;const a=Mr(e);if(a===t)return;const i=e.sessionId;i&&o(l=>({...l,[i]:t}));try{await r(Xn(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:$n(e),mode:t})}catch(l){const d=H2(l);i&&!d&&o(u=>{const m={...u};return a===W2(s,i)?delete m[i]:m[i]=a,m}),F2(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function ih(e,t){const s=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!s||e.transport!=="pty")return e;const r=t[s];return!r||e.mode===r?e:{...e,mode:r}}function B2(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let s=!1;const r=e.map(o=>{const a=ih(o,t),i=Array.isArray(o.childSessions)?o.childSessions.map(d=>ih(d,t)):o.childSessions,l=i!==o.childSessions;return a!==o||l?(s=!0,{...a,...l?{childSessions:i}:{}}):o});return s?r:e}function W2(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 U2({visibleConversations:e,clearedTabs:t,setClearedTabs:s,setActionLogs:r,isConversationMuted:o}){c.useEffect(()=>{Hf()},[]);const a=c.useMemo(()=>e.map(i=>({id:i.tabKey,name:Db(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 SN(a),c.useEffect(()=>{if(Object.keys(t).length===0)return;const l=setTimeout(()=>{s(d=>{const u=Date.now(),m={};for(const[h,p]of Object.entries(d))u-p<5e3&&(m[h]=p);return Object.keys(m).length===Object.keys(d).length?d:m})},5500);return()=>clearTimeout(l)},[t,s]),c.useEffect(()=>{const i=setInterval(()=>{const l=Date.now()-3e5;r(d=>{const u=d.filter(m=>m.timestamp>l).slice(-100);return u.length===d.length?d:u})},6e4);return()=>clearInterval(i)},[r]),null}function ch(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Hs(e){const t=[...e.messages].reverse().find(o=>!(o!=null&&o._localId))||e.messages[e.messages.length-1],s=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=ch(t==null?void 0:t.receivedAt)||ch(t==null?void 0:t.timestamp)||0;return Math.max(s,r)}function Ql(e,t=0){return Hs(e)||e.lastUpdated||t||0}function Rg(e){return Hs(e)||e.lastUpdated||0}function Pg(e,t,s=Rg){const r=Kb(e,t);if(r!==0)return r;const o=s(t)-s(e);if(o!==0)return o;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const l=e.displaySecondary.localeCompare(t.displaySecondary);return l!==0?l:e.tabKey.localeCompare(t.tabKey)}function Jl(e){var s;const t=Zt(e.status,{activeModal:(s=e.modalButtons)!=null&&s.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function K2(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Jl(e)&&!e.title.trim()}function q2(e){return e.length===0?null:[...e].sort((t,s)=>{const r=Number(Jl(s))-Number(Jl(t));if(r!==0)return r;const o=s.messages.length-t.messages.length;return o!==0?o:Pg(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=q2(o);return r?a&&K2(r)?a:r:a||s[0]||null}function z2(e){const t=e.filter(o=>o.type!=="adhdev-daemon"),s=new Set;for(const o of t){if(!_l(o))continue;const a=Ef(o);a&&s.add(a)}const r=new Map;for(const o of t){const a=Jj(o,s),i=r.get(a);if(!i){r.set(a,o);continue}const l=h=>(h.workspace?1:0)+(h.activeChat?1:0)+(h.lastMessagePreview?1:0),d=l(i),u=l(o),m=u>d||u===d&&(o.timestamp||0)>(i.timestamp||0)?o:i;r.set(a,V2(m,m===o?i:o))}return Array.from(r.values())}function V2(e,t){const s=_l(t),r=_l(e);if(!s&&!r)return e;const o=r?s?void 0:t:e,a=r?e:s?t:void 0,i=o&&String(o.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,l=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=a==null?void 0:a.settings;return{...e,...i&&{ownerDaemonId:i},...l&&!e.ownerMachineName&&{ownerMachineName:l},...d&&!r&&{settings:{...d,...e.settings??{}}}}}function Tc(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}function G2(e){let t=2166136261;for(let s=0;s<e.length;s+=1)t^=e.charCodeAt(s),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function lh(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],s=t[t.length-1],r=s?G2(fr(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 Y2(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),lh(e.activeChat),...t.map(s=>[s.id||"",s.providerSessionId||"",s.transport||"",s.mode||"",s.status||"",s.title||"",s.lastMessageHash||"",String(s.lastMessageAt||""),s.lastMessagePreview||"",s.lastMessageRole||"",String(s.lastUpdated||""),lh(s.activeChat)].join(":"))].join("|")}function Q2(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 J2(e,t){const s=new Map;for(const r of e){const o=t.get(r.routeId)||r;for(const a of co({routeId:r.routeId}))s.set(a,o);for(const a of co({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))s.set(a,r.streamSource==="native"?o:r);for(const a of co({tabKey:r.tabKey}))s.set(a,r)}return s}function X2(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Z2(e){const t=X2(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=fr(t.content).slice(0,240);return`${e.messages.length}:${s}:${r}`}function eI({ides:e,connectionStates:t,clearedTabs:s}){const r=c.useMemo(()=>z2(e),[e]),o=c.useMemo(()=>Nf(e),[e]),a=c.useMemo(()=>gg(e),[e]),i=c.useRef([]),l=c.useRef([]),d=c.useRef([]),u=c.useRef(new Map),m=c.useRef(new Map),h=c.useMemo(()=>{const k=new Map,w=[];for(const C of r){const{connectionState:E="new",machineName:P}=xg(C,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),T=Y2(C),M=u.current.get(C.id);if(M&&M.ide===C&&M.sourceSignature===T&&M.connectionState===E&&M.machineName===P){k.set(C.id,M),w.push(...M.conversations);continue}const _=Gd(C,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),I={ide:C,sourceSignature:T,connectionState:E,machineName:P,conversations:_};k.set(C.id,I),w.push(..._)}u.current=k;const y=new Map,N=C=>{const E=Z2(C),P=m.current.get(C.tabKey);if(P&&P.signature===E)return y.set(C.tabKey,P),P.timestamp;const T={signature:E,timestamp:Rg(C)||(P==null?void 0:P.timestamp)||0};return y.set(C.tabKey,T),T.timestamp},j=[...w].sort((C,E)=>Pg(C,E,N));return m.current=y,j},[r,t,a]),p=c.useMemo(()=>{const k=Q2(h,s);return Tc(i.current,k)?i.current:(i.current=k,k)},[h,s]),b=c.useMemo(()=>{const k=new Map,w=Array.from(new Set(p.map(y=>y.routeId)));for(const y of w){const N=_n(p,y);N&&k.set(y,N)}return k},[p]),f=c.useMemo(()=>{const k=new Map;for(const w of p){const y=b.get(w.routeId),N=w.streamSource==="native"&&y?y:w;for(const j of co({providerSessionId:w.providerSessionId,sessionId:w.sessionId,tabKey:w.tabKey}))k.set(j,N)}return k},[p,b]),x=c.useMemo(()=>J2(p,b),[p,b]),g=c.useCallback(k=>{if(k)return f.get(k)},[f]),v=c.useCallback(k=>{if(k)return x.get(k)},[x]),S=c.useMemo(()=>{const k=p.filter(w=>!ys(w,o).surfaceHidden);return Tc(l.current,k)?l.current:(l.current=k,k)},[p,o]),A=c.useMemo(()=>{const k=S.map(w=>w.tabKey);return Tc(d.current,k)?d.current:(d.current=k,k)},[S]);return{chatIdes:r,conversations:p,visibleConversations:S,visibleTabKeys:A,resolveConversationBySessionId:g,resolveConversationByTarget:v}}function tI({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 nI({ides:e,sendDaemonCommand:t,setToasts:s,resolveConversationByTarget:r,hydrateInteractivePrompt:o}){c.useEffect(()=>{nt.setIdes(e)},[e]),c.useEffect(()=>{nt.setResolveAction((a,i,l)=>{t(a,i,l).catch(()=>{})})},[t]),c.useEffect(()=>{nt.setHydrateInteractivePrompt(o)},[o]),c.useEffect(()=>{const a=nt.onToast(i=>{s(d=>d.some(m=>m.message===i.message&&i.timestamp-m.timestamp<3e3)?d:[...d.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions,details:i.details}]);const l=i.duration||5e3;setTimeout(()=>s(d=>d.filter(u=>u.id!==i.id||u.pinned)),l)});return()=>{a()}},[s]),c.useEffect(()=>{const a=Vf.on("status_event",i=>{nt.handleRawEvent(i,"ws")});return()=>{a()}},[]),c.useEffect(()=>{var i;const a=l=>{var g;const d=l.data;if((d==null?void 0:d.type)!=="notification_action"||typeof d.action!="string"||!d.action.startsWith("approval_")||!(d.daemonId||d.targetSessionId||d.targetKey))return;const u=d.targetSessionId||d.targetKey||d.daemonId,m=r(u),h=(m==null?void 0:m.routeId)||d.daemonId;if(!h)return;const p=Number(d.buttonIndex),b=d.button||((g=m==null?void 0:m.modalButtons)==null?void 0:g[p])||"Approve",f=String(b).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),x=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(f);t(h,"resolve_action",{action:x?"approve":"reject",button:b,...Number.isFinite(p)&&{buttonIndex:p},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...d.targetSessionId&&{targetSessionId:d.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};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 sI="adhdev_dashboardLayout_v1",rI="adhdev_dashboardDockview_v1",oI="adhdev_dashboardDockviewHiddenRestore_v1",Yr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Zd(e,t){try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}}function aI(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Eg(e){return`${sI}:${e}`}function iI(e){const t=Eg(e);return Zd(t,null)}function cI(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=Eg(e);if(s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Lg(e){return`${rI}:${e}`}function lI(e){const t=Lg(e);return Zd(t,null)}function dI(e,t){try{const s=Lg(e);if(!t){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function Dg(e){return`${oI}:${e}`}function uI(e){const t=Dg(e);return Zd(t,{})}function mI(e,t){try{const s=Dg(e);if(Object.keys(t).length===0){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function hI(){return{groupAssignments:[...Yr.groupAssignments],focusedGroup:Yr.focusedGroup,groupActiveTabIds:{...Yr.groupActiveTabIds},groupTabOrders:{...Yr.groupTabOrders},groupSizes:[...Yr.groupSizes]}}function pI(e,t){return e?e.length===t.length&&e.every((s,r)=>s===t[r]):t.length===0}function fI(){const[e]=c.useState(()=>aI(typeof window<"u"?window.innerWidth:1280)),[t,s]=c.useState(()=>new Map),[r,o]=c.useState(0),[a,i]=c.useState({}),[l,d]=c.useState({}),[u,m]=c.useState([]),[h,p]=c.useState(()=>typeof window<"u"&&window.innerWidth<768),[b,f]=c.useState(!1),x=c.useCallback(()=>{if(b)return;const C=iI(e)??hI();s(new Map(C.groupAssignments)),o(C.focusedGroup),i(C.groupActiveTabIds),d(C.groupTabOrders),m(C.groupSizes),f(!0)},[b,e]);c.useEffect(()=>{b&&cI(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:a,groupTabOrders:l,groupSizes:u})},[b,e,t,r,a,l,u]),c.useEffect(()=>{const C=window.matchMedia("(max-width: 767px)"),E=P=>p(P.matches);return C.addEventListener("change",E),()=>C.removeEventListener("change",E)},[]);const g=c.useCallback(C=>{s(C)},[]),v=c.useCallback(C=>{o(C)},[]),S=c.useCallback(C=>{i(C)},[]),A=c.useCallback(C=>{d(C)},[]),k=c.useCallback(C=>{m(C)},[]),w=c.useCallback(C=>{v(C)},[v]),y=c.useCallback((C,E)=>{i(P=>(P[C]??null)===(E??null)?P:{...P,[C]:E})},[]),N=c.useCallback((C,E)=>{d(P=>{const T=P[C];return pI(T,E)?P:{...P,[C]:E}})},[]),j=c.useCallback((C,E)=>{const P=E.get(C)??0;return y(P,C),w(P),P},[w,y]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:g,focusedGroup:r,updateFocusedGroup:v,focusGroup:w,groupActiveTabIds:a,updateGroupActiveTabIds:S,setGroupActiveTab:y,groupTabOrders:l,updateGroupTabOrders:A,setGroupTabOrder:N,groupSizes:u,updateGroupSizes:k,isMobile:h,hasHydratedStoredLayout:b,hydrateStoredLayout:x,focusConversationTab:j}}function bI(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const s=e[0],r=_i(t);return typeof(s==null?void 0:s.id)=="string"&&r.includes(s.id)}function gI({urlActiveTab:e,conversations:t,resolveConversationBySessionId:s,normalizedGroupAssignments:r,hasHydratedStoredLayout:o,hydrateStoredLayout:a,focusConversationTab:i,setSearchParams:l,historyModalOpen:d,activeConv:u,isRefreshingHistory:m,ides:h,handleRefreshHistory:p}){const b=c.useRef(!1),f=c.useRef(!1),x=c.useRef(null),g=c.useRef(!1);c.useEffect(()=>{if(!e||b.current||t.length===0)return;if(!o){a();return}const v=s(e);v&&(i(v.tabKey,r),b.current=!0,f.current=!0,x.current!=null&&(window.clearTimeout(x.current),x.current=null),l(S=>{const A=new URLSearchParams(S);return A.delete("activeTab"),A},{replace:!0}))},[e,t,s,r,o,a,i,l]),c.useEffect(()=>{if(!(f.current||o)&&t.length!==0){if(!e){a(),f.current=!0;return}if(b.current){f.current=!0;return}if(x.current==null)return x.current=window.setTimeout(()=>{x.current=null,!(f.current||o)&&(a(),f.current=!0)},1500),()=>{x.current!=null&&(window.clearTimeout(x.current),x.current=null)}}},[e,t.length,o,a]),c.useEffect(()=>{if(!d){g.current=!1;return}if(!u||g.current||m)return;const v=h.find(S=>S.id===u.routeId);v&&(!v.chats||v.chats.length===0||bI(v.chats,u))&&(g.current=!0,p())},[d,u,m,h,p])}function Ic(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const s=e[0];if((s==null?void 0:s.active)===!0)return!0;const r=_i(t);return typeof(s==null?void 0:s.id)=="string"&&r.includes(s.id)}function Og({sendDaemonCommand:e,activeConv:t,chats:s,updateRouteChats:r,setToasts:o,setClearedTabs:a}){const[i,l]=c.useState(!1),[d,u]=c.useState(!1),m=c.useCallback(async f=>{try{await e("standalone","launch_ide",{ideType:f,enableCdp:!0})}catch(x){console.error("Launch failed",x)}},[e]),h=c.useCallback(async(f,x)=>{try{const g=f||(t==null?void 0:t.daemonId)||"",v=await e(g,"switch_chat",{id:x,sessionId:x,...gs(t)}),S=v==null?void 0:v.result;if((v==null?void 0:v.success)===!0||S==="switched"||S==="switched-by-title")return;S===!1||S==="not_found"?lr(o,"⚠️ Session tab not found — try refreshing history"):typeof S=="string"&&S.startsWith("error:")?lr(o,`⚠️ Switch error: ${S}`):lr(o,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),lr(o,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,o]),p=c.useCallback(async()=>{if(!(!t||i)){l(!0);try{const f=ps(t);await e(f,"new_chat",{...gs(t)}),I_(f,t.sessionId,_i(t)[0]),a(x=>({...x,[t.tabKey]:Date.now()}))}catch(f){console.error("New chat failed",f)}finally{l(!1)}}},[t,i,e,a]),b=c.useCallback(async()=>{var f,x;if(!(!t||d)){u(!0);try{const g=ps(t),v=async()=>e(g,"list_chats",{forceExpand:!0,...gs(t)});let S=await v(),A=(S==null?void 0:S.chats)||((f=S==null?void 0:S.result)==null?void 0:f.chats);Ic(A,t)&&(await new Promise(k=>setTimeout(k,450)),S=await v(),A=(S==null?void 0:S.chats)||((x=S==null?void 0:S.result)==null?void 0:x.chats)),S!=null&&S.success&&Array.isArray(A)&&(r(t.routeId,A),Ic(A,t)&&!Ic(s,t)&&lr(o,"⚠️ History dialog did not fully open — try once more"))}catch(g){console.error("Refresh history failed",g)}finally{u(!1)}}},[t,s,d,e,r,o]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:m,handleSwitchSession:h,handleNewChat:p,handleRefreshHistory:b}}function xI(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 yI(e,t){return e.length!==t.length?!1:e.every((s,r)=>s===t[r])}function dh(e,t){const s=Object.keys(e),r=Object.keys(t);return s.length!==r.length?!1:s.every(o=>t[Number(o)]===e[Number(o)])}function ra(e,t){const s=new Set(t),r=t.length>0?[0]:[];for(const[i,l]of e)!s.has(i)||l<=0||r.includes(l)||r.push(l);r.sort((i,l)=>i-l);const o={};r.forEach((i,l)=>{o[i]=l}),r.length===0&&(o[0]=0);const a=new Map;for(const[i,l]of e){if(!s.has(i)||l<=0)continue;const d=o[l];typeof d=="number"&&d>0&&a.set(i,d)}return{assignments:a,groupCount:Math.max(1,r.length),mapping:o,usedGroups:r}}function uh(e,t){const s={};for(const[r,o]of Object.entries(e)){const a=t[Number(r)];typeof a=="number"&&(s[a]=o)}return s}function vI(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 wI(e,t,s){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),o=r.length===t.length?r:Array(s).fill(100/s),a=o.reduce((i,l)=>i+l,0);return a>0?o.map(i=>i/a*100):Array(s).fill(100/s)}function mh(e,t){const s={};for(const[r,o]of Object.entries(e)){const a=Number(r);s[a>=t?a+1:a]=o}return s}function hh(e){return Array(e).fill(100/e)}function SI({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:s,updateGroupActiveTabIds:r,updateGroupTabOrders:o,groupSizes:a,updateGroupSizes:i,isMobile:l,visibleConversations:d,visibleTabKeys:u}){const m=c.useRef(null),h=c.useMemo(()=>ra(e,u),[e,u]),p=h.assignments,b=c.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),f=b>1,x=c.useCallback((w,y)=>{t(N=>{const j=new Map(ra(N,u).assignments);return y===0?j.delete(w):j.set(w,y),j}),r(N=>({...N,[y]:w})),s(y)},[t,u,r,s]),g=c.useCallback(w=>{t(y=>{const N=ra(y,u).assignments,j=new Map;for(const[C,E]of N)E!==w&&(E>w?j.set(C,E-1):j.set(C,E));return j}),i(y=>{if(y.length<=1)return[];const N=[...y];N.splice(w,1);const j=N.reduce((C,E)=>C+E,0);return j>0?N.map(C=>C/j*100):[]}),s(0)},[t,u,i,s]),v=c.useCallback((w,y)=>{y.preventDefault();const N=m.current;if(!N)return;const j=y.clientX,C=N.offsetWidth,E=a.length===b?[...a]:hh(b),P=M=>{const I=(M.clientX-j)/C*100,D=[...E];D[w]=Math.max(15,E[w]+I),D[w+1]=Math.max(15,E[w+1]-I),i(D)},T=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",P),document.addEventListener("mouseup",T)},[a,b,i]),S=c.useCallback((w,y,N)=>{if(b>=4)return;const j=N==="left"?y:y+1;t(C=>{const E=ra(C,u).assignments,P=new Map;for(const T of d){const M=E.get(T.tabKey)??0,_=M>=j?M+1:M;_>0&&P.set(T.tabKey,_)}return j>0&&P.set(w,j),P}),i(C=>{const E=C.length===b?[...C]:hh(b),P=E[y]??100/b,T=Math.max(15,P/2),M=Math.max(15,P/2),_=[...E];_[y]=T,_.splice(j,0,M);const I=_.reduce((D,L)=>D+L,0);return _.map(D=>D/I*100)}),r(C=>{const E=mh(C,j);return E[j]=w,E}),o(C=>{const E=mh(C,j);return E[j]=[w],E}),s(j)},[b,t,u,d,i,r,o,s]);c.useEffect(()=>{xI(e,p)||t(p)},[e,p,t]),c.useEffect(()=>{const{mapping:w,usedGroups:y}=h;r(N=>{const j=uh(N,w);return dh(N,j)?N:j}),o(N=>{const j=uh(N,w);return dh(N,j)?N:j}),s(N=>{const j=l?0:vI(N,y,w);return N===j?N:j}),i(N=>{const j=l?[]:wI(N,y,h.groupCount);return yI(N,j)?N:j})},[h,l,r,o,s,i]);const A=c.useMemo(()=>{const w=Array.from({length:b},()=>[]);for(const y of d){const N=p.get(y.tabKey)??0,j=Math.min(N,b-1);w[j].push(y)}return w},[d,p,b]),k=c.useCallback(()=>{t(new Map),s(0)},[t,s]);return{containerRef:m,normalizedGroupAssignments:p,numGroups:b,isSplitMode:f,groupedConvs:A,moveTabToGroup:x,closeGroup:g,handleResizeStart:v,splitTabRelative:S,clearAllSplits:k}}function Mc(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function kI(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function ro(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function eu(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},s=Mc(t.channel)||Mc(e.updateChannel)||Mc(e.releaseChannel)||void 0,r=kI(t.npmTag)||(s==="preview"?"next":s==="stable"?"latest":void 0),o=ro(t.targetVersion)||ro(e.serverVersion)||void 0,a=ro(t.minVersion)||void 0,i=ro(t.updateCommand)||(s?"adhdev update":void 0);return{...s?{channel:s}:{},...r?{npmTag:r}:{},...o?{targetVersion:o}:{},...a?{minVersion:a}:{},...i?{updateCommand:i}:{}}}function Rs(e,t=null){return eu(e).targetVersion||t}function jI(e){return eu(e).channel||null}function tu(e){return!e||!eu(e).channel?null:{}}function $g(e,t={},s){const r=ro(t.targetVersion);return r?s?s("machine.commandCenter.updateToVersion",{version:r}):`Update to v${r}`:t.fallback?t.fallback:s?t.required?s("machine.daemonUpdate.updateNow"):s("machine.daemonUpdate.upgrade"):t.required?"Update now":"Upgrade"}function ri(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const s=t[4]??null;let r=null;if(s){const o=s.match(/(?:^|\.)(\d+)$/);r=o?Number(o[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:s!==null}}function ph(e){var t;return((t=ri(e))==null?void 0:t.base)??null}function Fg(e,t){const s=ri(e),r=ri(t);if(!s||!r)return e!==t;for(let o=0;o<3;o+=1){if(s.base[o]<r.base[o])return!0;if(s.base[o]>r.base[o])return!1}return s.isPrerelease&&r.isPrerelease?s.prereleaseNumber===null||r.prereleaseNumber===null?!1:s.prereleaseNumber<r.prereleaseNumber:!1}function nu(e,t){const s=e.version||null;return!s||!t||e.versionMismatch===!0&&!ri(t)?!1:Fg(s,t)}function Ta(e,t){if(e.versionUpdateRequired===!0)return!0;const s=e.version||null;if(!s||!t||!Fg(s,t))return!1;const r=ph(s),o=ph(t);return!r||!o?!1:r[0]!==o[0]||r[1]!==o[1]}function NI({ides:e,sendDaemonCommand:t}){const s="1.0.75",r=c.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:nu(h,Rs(h,s))).sort((h,p)=>Number(Ta(p,Rs(p,s)))-Number(Ta(h,Rs(h,s)))),[s,e]),o=c.useMemo(()=>r.some(h=>Ta(h,Rs(h,s))),[s,r]),a=c.useMemo(()=>r.map(h=>Rs(h,s)).find(h=>typeof h=="string"&&h.trim().length>0)||s,[s,r]),[i,l]=c.useState(!1),[d,u]=c.useState({}),m=c.useCallback(async h=>{var f,x;const p=e.find(g=>g.id===h);if(!p)return;u(g=>({...g,[h]:"upgrading"}));const b=tu(p);if(!b){u(g=>({...g,[h]:"error"}));return}try{const g=await t(h,"daemon_upgrade",b);(f=g==null?void 0:g.result)!=null&&f.upgraded||(x=g==null?void 0:g.result)!=null&&x.success?u(v=>({...v,[h]:"done"})):u(v=>({...v,[h]:"error"}))}catch{u(g=>({...g,[h]:"error"}))}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:o,targetVersion:a,versionBannerDismissed:i,setVersionBannerDismissed:l,upgradingDaemons:d,handleBannerUpgrade:m}}const Hg=80;function Ia(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function CI(e){return{...e,createdAt:Ia(e.createdAt),updatedAt:Ia(e.updatedAt,e.createdAt),lastEventAt:Ia(e.lastEventAt,e.updatedAt||e.createdAt)}}function _I(e){const t=Pf(e);return t==="unknown:"?e.id:t}function AI(e){return[e.type,Rf(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function TI(e,t=Hg){const s=new Map;for(const r of e){if(r.deletedAt)continue;const o=_I(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 II(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=Ni(o,t),l=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!l)continue;const d=Ia(o.lastMessageAt||(a==null?void 0:a.lastUpdated)||o.lastUpdated,s),u=AI({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(CI({id:u,dedupKey:u,type:l,routeId:o.routeId,machineId:o.daemonId||o.routeId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,tabKey:o.tabKey,title:nb(o),preview:MC(o),createdAt:d,updatedAt:d,lastEventAt:d}))}return TI(r)}function MI(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function RI(e){const{conversations:t,liveSessionInboxState:s,maxItems:r=Hg}=e,o=c.useMemo(()=>II(t,s).slice(0,Math.max(0,r)),[t,s,r]),a=c.useMemo(()=>MI(o),[o]);return{notifications:o,unreadCount:a}}function PI({notifications:e,sendDaemonCommand:t}){const s=c.useCallback(a=>{const i=e.find(d=>d.id===a),l=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:l}).catch(()=>{})},[e,t]),r=c.useCallback(a=>{const i=e.find(l=>l.id===a);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),o=c.useCallback(a=>{const i=e.find(l=>l.id===a);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:s,handleMarkDashboardNotificationUnread:r,handleDeleteDashboardNotification:o}}function su(...e){const t=new Set,s=[],r=o=>{const a=typeof o=="string"?o.trim():"";if(!a)return;const i=a.toLowerCase();t.has(i)||(t.add(i),s.push(a))};for(const o of e){if(Array.isArray(o)){for(const a of o)r(a);continue}r(o)}return s}function EI(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const s=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(s){const r=s[1].toUpperCase(),o=(s[2]||"").replace(/[\\/]+/g,"\\");return o?`${r}:\\${o}`:`${r}:\\`}return null}function ru(e,t=[]){if(e==="win32"){for(const s of t){if(typeof s!="string")continue;const r=EI(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 LI(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 DI(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function ou(e,t,s){const r=await e(t,"file_list_browse",{path:s}),o=DI(r);if(!(o!=null&&o.success))throw new Error((o==null?void 0:o.error)||(r==null?void 0:r.error)||"Could not browse folder");const a=typeof(o==null?void 0:o.path)=="string"?o.path:s,i=a.includes("\\")?"\\":"/",l=(u,m)=>/^[A-Za-z]:\\?$/.test(u)?`${u.replace(/\\?$/,"\\")}${m}`:u==="/"||u==="\\"?`${i}${m}`:`${u.replace(/[\\/]+$/,"")}${i}${m}`,d=Array.isArray(o==null?void 0:o.files)?o.files.filter(u=>(u==null?void 0:u.type)==="directory"&&typeof(u==null?void 0:u.name)=="string").map(u=>({name:u.name,path:typeof(u==null?void 0:u.path)=="string"&&u.path.trim()?u.path:l(a,u.name)})).sort((u,m)=>u.name.localeCompare(m.name)):[];return{path:a,directories:d}}function fh(e,t){const s=t.meshId||"",r={meshId:s,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${s}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(o,a)=>r[a]||"")}function OI(e,t={}){const s=e==null?void 0:e.mcpConfig;if((s==null?void 0:s.mode)!=="manual")return null;const o=fh(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"}).trim();return!o.includes(`
|
|
68
|
+
`)&&!o.startsWith("{")?null:{serverName:s.serverName||"adhdev-mesh",configFormat:s.format,configPathCommand:s.configPathCommand,requiresRestart:s.requiresRestart===!0,instructions:s.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:fh(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"})}}function $I(e){if(!e||typeof e!="object")return null;const t=e,s=typeof t.instructions=="string"?t.instructions:"",r=typeof t.template=="string"?t.template:"";return!s&&!r?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:s||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:r}}function ko(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Bg(e){return Ai(e)||e.tabKey||e.routeId||null}function Wg(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",s=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",o=e.conversations.find(a=>{if(r&&a.routeId!==r)return!1;const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey].map(l=>typeof l=="string"?l.trim():"").filter(Boolean);return!!(t&&i.includes(t)||s&&i.includes(s)||r&&a.routeId===r)});if(o!=null&&o.tabKey)return o.tabKey;if(r){const a=_n(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(a!=null&&a.tabKey)return a.tabKey}return t||s||r||null}function ms(e){return String(e||"").trim()}function Ug(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function oi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function FI(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function HI(e,t){const s=ms(e.providerSessionId),r=ms(e.targetSessionId),o=t.find(a=>{const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey,a.routeId].map(ms).filter(Boolean);return!!(s&&i.includes(s)||r&&i.includes(r))});return o?o.tabKey:r||s||null}function BI(e,t,s){if(t.event!=="agent:generating_completed")return null;const r=Ug(t.daemonId);if(r&&r!==e.machineId)return null;const o=ms(t.providerType);if(e.providerType&&o!==e.providerType)return null;const a=ms(e.resumeSessionId),i=ms(e.launchedSessionId),l=ms(t.providerSessionId),d=ms(t.targetSessionId);if(a&&a!==l&&a!==d||i&&i!==l&&i!==d)return null;const u=oi(e.workspacePath);if(u){const m=oi(t.workspaceName);if(m&&!FI(m,u))return null}return HI(t,s)}function bh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function WI({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=oi(r.workspacePath),u=e.find(h=>{var g,v,S,A;if(!h||h.type==="adhdev-daemon"||Ug(h.daemonId||h.id)!==r.machineId||(So(h)?"cli":"ide")!==r.kind)return!1;const f=String(h.agentType||h.type||"");if(r.providerType&&f!==r.providerType)return!1;if(r.resumeSessionId)return String(h.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const 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=oi(h.workspace||h.runtimeWorkspaceLabel);return k?k===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((A=(S=(v=(g=h.activeChat)==null?void 0:g.messages)==null?void 0:v.at)==null?void 0:S.call(v,-1))==null?void 0:A.timestamp)||0)>=r.startedAt-5e3});if(!u)return;const m=Wg({entrySessionId:u.sessionId,entryInstanceId:u.instanceId,entryRouteId:u.id,conversations:t});m&&(i(),s(m))},[i,t,e,s,r]),c.useEffect(()=>nt.onStatusEvent(d=>{const u=a.current;if(!u)return;const m=BI(u,d,t);m&&(i(),s(m))}),[i,t,s]),c.useEffect(()=>{if(!r)return;const d=window.setTimeout(()=>{o(u=>!u||u.startedAt!==r.startedAt?u:(a.current=null,null))},45e3);return()=>window.clearTimeout(d)},[r]),{trackPendingLaunch:l}}function UI(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 KI(e,t,s){var i,l,d,u;const r={meshId:e.trim()};t.trim()&&(r.cliType=t.trim());const o=(i=s==null?void 0:s.initialModel)==null?void 0:i.trim(),a=(l=s==null?void 0:s.initialThinkingLevel)==null?void 0:l.trim();return o&&(r.initialModel=o),a&&(r.initialThinkingLevel=a),o&&(s!=null&&s.modelSource)&&(r.modelSource=s.modelSource),a&&(s!=null&&s.thinkingLevelSource)&&(r.thinkingLevelSource=s.thinkingLevelSource),(d=s==null?void 0:s.settings)!=null&&d.autoApproveMode?r.autoApproveMode=s.settings.autoApproveMode:typeof((u=s==null?void 0:s.settings)==null?void 0:u.autoApprove)=="boolean"&&(r.autoApprove=s.settings.autoApprove),r}function qI({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:s,activeConv:r,ides:o,setCliViewModeOverrides:a}){const i=Bd(),{launchCli:l}=wi(),d=c.useCallback(async(g,v)=>ou(e,g,v),[e]),u=c.useCallback(async(g,v)=>{if(!v.trim())return{ok:!1,error:"Choose a workspace path first."};try{const S=await e(g,"workspace_add",{path:v.trim()});return S!=null&&S.success?{ok:!0}:{ok:!1,error:(S==null?void 0:S.error)||"Could not save workspace"}}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not save workspace"}}},[e]),m=c.useCallback(async(g,v,S)=>{var A;try{const k={ideType:v,enableCdp:!0};(A=S==null?void 0:S.workspacePath)!=null&&A.trim()&&(k.workspace=S.workspacePath.trim());const w=await e(g,"launch_ide",k);return!(w!=null&&w.success)&&(w==null?void 0:w.success)!==void 0?{ok:!1,error:(w==null?void 0:w.error)||"Could not launch IDE"}:(t({machineId:g,kind:"ide",providerType:v,workspacePath:(S==null?void 0:S.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,v,S,A)=>{const k=Date.now();try{const w=UI(S,A),y=await l(g,w),N=(y==null?void 0:y.result)||y,j=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);return y!=null&&y.success&&j?(t({machineId:g,kind:v,providerType:S,workspacePath:(A==null?void 0:A.workspacePath)||null,resumeSessionId:(A==null?void 0:A.resumeSessionId)||null,launchedSessionId:j,startedAt:k}),{ok:!0}):y!=null&&y.success?(t({machineId:g,kind:v,providerType:S,workspacePath:(A==null?void 0:A.workspacePath)||null,resumeSessionId:(A==null?void 0:A.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(N==null?void 0:N.error)||`Could not launch ${v.toUpperCase()} session`,code:(y==null?void 0:y.code)||(N==null?void 0:N.code)||void 0}}catch(w){return bh(w)?(t({machineId:g,kind:v,providerType:S,workspacePath:(A==null?void 0:A.workspacePath)||null,resumeSessionId:(A==null?void 0:A.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:w instanceof Error?w.message:`Could not launch ${v.toUpperCase()} session`}}},[l,e,t]),p=c.useCallback(async g=>{var v;if(i!=null&&i.listMeshes){const S=await i.listMeshes(g);return Va(S),S}if(!g)return[];try{const S=await e(g,"list_meshes",{}),A=(S==null?void 0:S.result)??S;if((A==null?void 0:A.success)===!1)throw new Error((A==null?void 0:A.error)||"Could not load meshes");const w=(Array.isArray(A==null?void 0:A.meshes)?A.meshes:Array.isArray((v=A==null?void 0:A.result)==null?void 0:v.meshes)?A.result.meshes:[]).map(y=>{var N;return{id:String((y==null?void 0:y.id)||""),name:String((y==null?void 0:y.name)||(y==null?void 0:y.id)||"Untitled mesh"),repoIdentity:(y==null?void 0:y.repoIdentity)||(y==null?void 0:y.repo_identity)||null,workspace:Array.isArray(y==null?void 0:y.nodes)&&y.nodes.length>0?String(((N=y.nodes[0])==null?void 0:N.workspace)||""):null,nodesCount:Array.isArray(y==null?void 0:y.nodes)?y.nodes.length:void 0,status:(y==null?void 0:y.status)||null}}).filter(y=>y.id);return Va(w),w}catch(S){throw console.error("List meshes failed",S),S}},[i,e]),b=c.useCallback(async(g,v,S,A)=>{if(!v.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(g,v,S,A);const k=Date.now();try{const w=KI(v,S,A),y=await e(g,"launch_mesh_coordinator",w),N=(y==null?void 0:y.result)??y;if((N==null?void 0:N.success)===!1||(y==null?void 0:y.success)===!1){const C=String((N==null?void 0:N.code)||(y==null?void 0:y.code)||""),E=$I((N==null?void 0:N.meshCoordinatorSetup)||(N==null?void 0:N.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(N==null?void 0:N.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:C||void 0,manualSetup:E}}const j=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);return j?s(j):t({machineId:g,kind:"cli",providerType:(N==null?void 0:N.cliType)||S.trim()||void 0,workspacePath:(N==null?void 0:N.workspace)||null,startedAt:k}),{ok:!0}}catch(w){return bh(w)?(t({machineId:g,kind:"cli",providerType:S.trim()||void 0,startedAt:k}),{ok:!0}):{ok:!1,error:w instanceof Error?w.message:"Could not launch mesh coordinator"}}},[i,s,e,t]),f=c.useCallback(async(g,v)=>{if(!g||!v)return[];try{const S=await e(g,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),A=(S==null?void 0:S.result)??S;return Array.isArray(A==null?void 0:A.sessions)?A.sessions:[]}catch(S){return console.error("List saved sessions failed",S),[]}},[e]),x=c.useCallback(async g=>{await Mg({conversation:r,mode:g,ides:o,sendDaemonCommand:e,setCliViewModeOverrides:a})},[r,o,e,a]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:u,handleLaunchMachineIde:m,handleLaunchMachineProvider:h,handleListMachineMeshes:p,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:f,setActiveCliViewMode:x}}function zI(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 VI(e,t,s=Date.now()){return!e||!zI(t)?null:{tabKey:e,nonce:s}}function GI({isMobile:e,conversations:t,visibleConversations:s,groupActiveTabIds:r,focusedGroup:o,groupedConvs:a,setSearchParams:i}){const[l,d]=c.useState(null),[u,m]=c.useState(null),h=c.useMemo(()=>{var g,v;if(!e){if(l){const S=t.find(A=>A.tabKey===l);if(S)return S}return s[0]}const x=r[o];if(x){const S=t.find(A=>A.tabKey===x);if(S)return S}return((g=a[o])==null?void 0:g[0])||((v=a[0])==null?void 0:v[0])},[t,l,o,r,a,e,s]),p=c.useCallback(x=>{d(x)},[]),b=c.useCallback(x=>{d(x.tabKey),i(g=>{const v=new URLSearchParams(g),S=PC(x);return S?v.set("activeTab",S):v.delete("activeTab"),v},{replace:!0})},[i]),f=c.useCallback((x,g)=>{const v=VI(x,g);v&&m(v)},[]);return{activeConv:h,openDesktopConversation:b,requestScrollToBottom:f,scrollToBottomRequest:u,setDesktopActiveTab:p}}function YI(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 QI(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 JI({activeConv:e,isMobile:t,liveSessionInboxState:s,sendDaemonCommand:r}){const o=c.useRef(null),a=c.useRef(null),i=c.useRef(null),l=c.useRef(null),d=c.useRef(null);c.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),l.current&&(clearTimeout(l.current),l.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),a.current=null};if(t){u(),o.current=null;return}if(!(e!=null&&e.sessionId)){u(),o.current=null;return}const m=ys(e,s),h=QI({tabKey:e.tabKey,historySessionId:Ai(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Hs(e),liveState:m}),p=h.autoReadKey,b=YI({autoReadKey:p,shouldMarkSeen:h.shouldMarkSeen,completedKey:o.current,pendingKey:a.current});if(!h.shouldMarkSeen){b.shouldCancelPending&&u(),o.current=p;return}if(!b.shouldSchedule)return;b.shouldCancelPending&&u();const f=()=>{if(document.visibilityState!=="visible"||o.current===p)return;o.current=p,a.current=null,i.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const g=h.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:g,completionMarker:h.completionMarker}).catch(()=>{})};if(a.current=b.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(f,1500);const g=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=g,document.addEventListener("visibilitychange",g);return}const x=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(f,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=x,document.addEventListener("visibilitychange",x)},[e,t,s,r]),c.useEffect(()=>()=>{i.current&&clearTimeout(i.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Rc(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const s=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(s)?s:""}function XI({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:s,ides:r,sendDaemonCommand:o,updateRouteChats:a,setToasts:i,setClearedTabs:l,setSearchParams:d}){var $;const{launchCli:u}=wi(),[m,h]=c.useState(!1),[p,b]=c.useState([]),[f,x]=c.useState(()=>mn()),[g,v]=c.useState(!1),[S,A]=c.useState(null),k=c.useRef(null),w=c.useMemo(()=>s||t||e,[e,s,t]),y=!!w&&ft(w),N=c.useMemo(()=>{if(!w||!y)return null;const q=w.daemonId||w.routeId||"",G=$n(w),W=Rc(w);return`${q}:${G}:${w.providerSessionId||""}:${W}`},[w,y]),j=c.useMemo(()=>!w||!y?"":Rc(w),[w,y]),{isCreatingChat:C,isRefreshingHistory:E,handleSwitchSession:P,handleNewChat:T,handleRefreshHistory:M}=Og({sendDaemonCommand:o,activeConv:w,chats:($=r.find(q=>q.id===(w==null?void 0:w.routeId)))==null?void 0:$.chats,updateRouteChats:a,setToasts:i,setClearedTabs:l}),_=c.useCallback(()=>{h(!0)},[]),I=c.useCallback(()=>{h(!1)},[]),D=c.useCallback(async()=>{if(!(!w||!y||g)){v(!0);try{const q=w.daemonId||w.routeId,G=$n(w),W=Rc(w),R=await o(q,"list_saved_sessions",{agentType:G,providerType:G,kind:"cli",limit:50,...w.providerSessionId?{providerSessionId:w.providerSessionId}:{},...W?{workspace:W}:{}}),O=(R==null?void 0:R.result)??R;b(Array.isArray(O==null?void 0:O.sessions)?O.sessions:[])}catch(q){console.error("Refresh saved sessions failed",q),b([])}finally{v(!1)}}},[w,g,y,o]);c.useEffect(()=>{if(!m){k.current=null;return}if(!y){k.current=null,b([]),v(!1);return}!N||g||k.current!==N&&(k.current=N,D())},[D,m,g,y,N]);const L=c.useCallback(async q=>{if(!w||!y||!q.providerSessionId||!q.workspace)return;const G=w.daemonId||w.routeId,W=$n(w);try{A(q.providerSessionId);const R=rN(q.summaryMetadata,"model",{preferShortValue:!0})||void 0,O=await u(G,{cliType:W,dir:q.workspace,resumeSessionId:q.providerSessionId,initialModel:R,...R?{modelSource:"remembered"}:{}}),B=(O==null?void 0:O.result)??O,H=typeof(B==null?void 0:B.sessionId)=="string"?B.sessionId:typeof(B==null?void 0:B.id)=="string"?B.id:"";H&&d(U=>{const K=new URLSearchParams(U);return K.set("activeTab",H),K},{replace:!0}),I()}catch(R){console.error("Resume saved session failed",R)}finally{A(null)}},[I,w,y,o,d]);return{historyModalOpen:m,openHistoryModal:_,closeHistoryModal:I,historyTargetConv:w,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:C,isHistoryRefreshingHistory:E,handleHistorySwitchSession:P,handleHistoryNewChat:T,handleHistoryRefresh:M,savedHistorySessions:p,savedHistoryFilters:f,setSavedHistoryFilters:x,missingWorkspaceResumePath:j,isSavedHistoryLoading:g,resumingSavedHistorySessionId:S,handleRefreshSavedHistory:D,handleResumeSavedHistorySession:L}}function ZI({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:l}){const[d,u]=c.useState(null),[m,h]=c.useState(null),p=c.useMemo(()=>{if(e||!r)return null;const v=l(r);return v&&!ft(v)?v:null},[e,r,l]),b=c.useMemo(()=>{const v=d==null?void 0:d.routeId;if(!v)return null;const S=d!=null&&d.tabKey?a.find(A=>A.tabKey===d.tabKey):o?a.find(A=>A.tabKey===o):null;return(S==null?void 0:S.routeId)===v?S:_n(a,v)},[a,d,o]),f=c.useMemo(()=>{if(b)return i.find(v=>v.id===b.routeId)},[i,b]);c.useEffect(()=>{p&&(u({routeId:p.routeId,tabKey:lm(p)}),h(p),s({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,s,p]);const x=c.useCallback(v=>{v&&(u({routeId:v.routeId,tabKey:lm(v)}),h(v))},[]),g=c.useCallback(()=>{u(null),h(null)},[]);return{remoteDialogConv:b,remoteDialogIdeEntry:f,remoteDialogActiveConv:m,setRemoteDialogActiveConv:h,openRemoteDialog:x,closeRemoteDialog:g}}function eM({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:u}){const{remoteDialogConv:m,remoteDialogIdeEntry:h,remoteDialogActiveConv:p,setRemoteDialogActiveConv:b,openRemoteDialog:f,closeRemoteDialog:x}=ZI({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:l}),[g,v]=c.useState(!1),[S,A]=c.useState(null),k=c.useCallback(async N=>{const j=N||d;!j||!ft(j)||(A(j),v(!0))},[d]),w=c.useCallback(()=>{v(!1),A(null)},[]),y=c.useCallback(async N=>{const j=S||d;if(!j||!ft(j)){w();return}v(!1);try{const C=$n(j),E=j.routeId||j.daemonId||"";await u(E,"stop_cli",{cliType:C,targetSessionId:j.sessionId,mode:N,...Ri(j)})}catch(C){console.error("Stop CLI failed:",C)}finally{A(null)}},[d,w,S,u]);return{remoteDialogConv:m,remoteDialogIdeEntry:h,remoteDialogActiveConv:p,setRemoteDialogActiveConv:b,openRemoteDialog:f,closeRemoteDialog:x,cliStopDialogOpen:g,cliStopTargetConv:S,requestCliStop:k,cancelCliStop:w,confirmCliStop:y}}function Pc(e,t=!0){return(e??!0)&&t}const au=c.memo(function({activeConv:t,clearToken:s,isCliTerminal:r,ideEntry:o,terminalRef:a,commands:i,actionLogs:l,userName:d,scrollToBottomRequestNonce:u,isInputActive:m=!0,isVisible:h=!0}){const{handleModalButton:p,handleRelaunch:b,handleSendChat:f,handleSendNowQueued:x,handleCancelQueued:g,isSendingChat:v,sendFeedbackMessage:S,pendingLocalMessage:A,pendingLocalMessages:k,retireEchoedPendingMessages:w,handleFocusAgent:y,isFocusingAgent:N}=i,j=r,C=!r,E=Pc(h,j),P=Pc(h,C),T=Pc(h),{t:M}=he("common"),_=I=>n.jsx(_b,{activeConv:t,ideEntry:o,handleSendChat:f,handleSendNowQueued:x,handleCancelQueued:g,isSendingChat:v,sendFeedbackMessage:S,pendingLocalMessage:A,pendingLocalMessages:k,retireEchoedPendingMessages:w,handleFocusAgent:y,isFocusingAgent:N,actionLogs:l,userName:d,scrollToBottomRequestNonce:u,isInputActive:m&&I,isVisible:I});return n.jsxs(n.Fragment,{children:[n.jsx(_f,{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(tn,{size:14})}),n.jsxs("span",{className:"flex flex-1 items-center gap-1",children:[n.jsx("span",{className:"font-semibold",children:M("paneGroup.cdpDisconnectedShort")}),n.jsx(rt,{content:M("paneGroup.cdpDisconnected"),size:12})]}),n.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-3xs whitespace-nowrap shrink-0",onClick:b,children:M("paneGroup.relaunchWithCdp")})]})}):null,t.transport==="pty"?n.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[n.jsx("div",{"aria-hidden":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:n.jsx(P1,{activeConv:t,clearToken:s,terminalRef:a,handleSendChat:f,isSendingChat:v,sendFeedbackMessage:S,isVisible:E,isInputActive:m&&E})}),n.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:_(P)})]}):_(T)]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.commands===t.commands&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function tM({conversation:e,className:t="",onOpenNativeConversation:s,onOpenMachine:r,interactive:o=!0,meshOnly:a=!1}){const{t:i}=he("common"),l=Vs(),d=Xn(e),u=a?null:tb(e),m=!a&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),h=!a&&e.streamSource==="agent-stream"&&!!e.agentName,p=!a&&!h&&e.transport==="pty",b=vr(e),f=RC(e),x=Ld(e).role,g=e.meshQueueStats,v=x==="coordinator",S=c.useCallback(()=>{if(r){r();return}d&&l("/dashboard",{state:{openMachineId:d}})},[d,l,r]),A=c.useCallback(()=>{if(s){s();return}const k=Bg(e);k&&l(ko(k))},[e,l,s]);return!m&&!h&&!p&&!u&&!x&&!g?null:n.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(o?n.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:A,title:f,children:[n.jsx(Bn,{size:12}),n.jsx("span",{children:f})]}):n.jsxs("span",{className:"conversation-meta-chip",title:f,children:[n.jsx(Bn,{size:12}),n.jsx("span",{children:f})]})),h&&n.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[n.jsx(xr,{size:12}),n.jsx("span",{children:b})]}),p&&n.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[n.jsx(xr,{size:12}),n.jsx("span",{children:b})]}),u&&(o?n.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:u,children:[n.jsx(gr,{size:12}),n.jsx("span",{children:u})]}):n.jsxs("span",{className:"conversation-meta-chip",title:u,children:[n.jsx(gr,{size:12}),n.jsx("span",{children:u})]})),v&&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(Iw,{size:12}),n.jsx("span",{children:i("dashboard.metaChips.queuePending",{count:g.pending})})]})]})}function nM({selectedConversation:e,isStandalone:t,selectedIdeEntry:s,actionLogs:r,userName:o,commands:a,onBack:i,onOpenNativeConversation:l,onOpenMachine:d,onOpenHistory:u,onOpenRemote:m,onOpenMeshGraph:h,onStopCli:p,cliViewMode:b,onSetCliViewMode:f}){const{t:x}=he("common"),g=c.useRef(null),v=Ci(Cf(e)),S=ft(e),A=S&&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(gi,{size:18})}),n.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 text-[17px] leading-[26px] font-extrabold tracking-tight text-text-primary",children:[n.jsx(ws,{conversation:e,size:15}),n.jsx("span",{className:"min-w-0 truncate",children:kt(e)})]}),n.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:n.jsx(tM,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>l(e),onOpenMachine:()=>d(e)})})]})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&b&&n.jsx(Yb,{mode:b,onChange:f,compact:!0}),S&&p&&n.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:x("cliStop.stopProcess"),"aria-label":x("cliStop.stopProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:n.jsx(Lt,{size:14})}),n.jsx(dg,{conversation:e,onOpenMeshGraph:h}),n.jsx(cg,{conversation:e,onOpenHistory:u,onOpenRemote:m,iconSize:14})]})]}),n.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:n.jsx(au,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:s,terminalRef:g,commands:a,actionLogs:r,userName:o})}),n.jsx(Nd,{promptSession:v.promptSession,isSubmitting:v.isSubmitting,error:v.responseError,onSubmit:v.submit,onCancel:v.cancel})]})}function sM(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Kg({isStandalone:e=!1}={}){const{t}=he("common"),[s,r]=c.useState("unix"),[o,a]=c.useState("powershell"),[i,l]=c.useState(!1),d=s==="unix"?"unix":o,u=c.useMemo(()=>_T(),[]);c.useEffect(()=>{r(sM())},[]);const m=c.useCallback(()=>{navigator.clipboard.writeText(u[d].cmd).catch(()=>{}),l(!0),setTimeout(()=>l(!1),2e3)},[d]);return n.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[n.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[n.jsx("button",{className:`text-3xs px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${s==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>r("unix"),children:"macOS / Linux"}),n.jsx("button",{className:`text-3xs px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${s==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>r("windows"),children:"Windows"})]}),s==="windows"&&n.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[n.jsx("button",{className:`text-4xs px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${o==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("powershell"),children:"PowerShell"}),n.jsx("button",{className:`text-4xs px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${o==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("cmd"),children:">_ CMD"})]}),n.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:m,title:t("app.installCommand.clickToCopy"),children:[n.jsx("span",{className:"text-text-muted select-none",children:u[d].prompt}),n.jsx("span",{className:"flex-1 break-all",children:u[d].cmd}),n.jsx("span",{className:"text-4xs font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:i?n.jsx(Cr,{size:12}):n.jsx(Bp,{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 qg({section:e,onSectionChange:t}){const{t:s}=he("common"),r=[{key:"machines",label:s("nav.machines"),icon:Bn},{key:"chats",label:s("nav.chats"),icon:Cn}];return n.jsx("div",{className:"px-3 py-2.5 pb-[calc(20px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:n.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:o,label:a,icon:i})=>{const l=e===o;return n.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-xxs font-semibold tracking-tight transition-all border ${l?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:l?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(o),type:"button","aria-pressed":l,children:[n.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${l?"text-accent-primary":"bg-transparent text-current"}`,style:l?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:n.jsx(i,{size:15})}),n.jsx("span",{children:a})]},o)})})})}function oa({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 tr({children:e,className:t=""}){return n.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function As({icon:e,title:t,subtitle:s,children:r}){return n.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[n.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),n.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),n.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:s}),r]})}function rM({title:e,isMuted:t,onToggleMute:s,onHide:r,onStop:o}){const{t:a}=he(),[i,l]=c.useState(!1),d=c.useRef(null);if(c.useEffect(()=>{if(!i)return;const h=b=>{var f;(f=d.current)!=null&&f.contains(b.target)||l(!1)},p=b=>{b.key==="Escape"&&l(!1)};return document.addEventListener("pointerdown",h,!0),document.addEventListener("mousedown",h,!0),window.addEventListener("keydown",p),()=>{document.removeEventListener("pointerdown",h,!0),document.removeEventListener("mousedown",h,!0),window.removeEventListener("keydown",p)}},[i]),!s&&!r&&!o)return null;const u="flex w-full items-center gap-2.5 rounded-lg border-none bg-transparent px-3 py-2.5 text-left text-sm font-medium text-text-secondary hover:bg-bg-secondary hover:text-text-primary",m=h=>p=>{p.preventDefault(),p.stopPropagation(),l(!1),h()};return n.jsxs("div",{ref:d,className:"relative",children:[n.jsx("button",{type:"button",className:`mobile-inbox-row-menu-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${t?"border-amber-500/60 bg-amber-500/15 text-amber-500":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:h=>{h.preventDefault(),h.stopPropagation(),l(p=>!p)},"aria-haspopup":"menu","aria-expanded":i,"aria-label":a("mobileInbox.moreActionsFor",{title:e}),title:a("dashboard.header.moreActions"),children:t?n.jsx(fl,{size:13}):n.jsx(Kp,{size:14})}),i&&n.jsxs("div",{role:"menu",className:"absolute right-0 top-full z-[var(--z-popover)] mt-1 flex w-48 flex-col rounded-xl border border-border-default bg-bg-card p-1 shadow-xl",children:[s&&n.jsxs("button",{type:"button",role:"menuitem",className:`mobile-inbox-mute-button ${u}`,onClick:m(s),children:[t?n.jsx(Jn,{size:15}):n.jsx(fl,{size:15}),a(t?"conversation.unmuteThis":"conversation.muteThis")]}),r&&n.jsxs("button",{type:"button",role:"menuitem",className:`mobile-inbox-hide-button ${u}`,onClick:m(r),children:[n.jsx(xi,{size:15}),a("mobileInbox.hide")]}),o&&n.jsxs("button",{type:"button",role:"menuitem",className:`mobile-inbox-stop-button ${u} !text-status-error`,onClick:m(o),children:[n.jsx(Lt,{size:15}),a("mobileInbox.stopSessionTitle")]})]})]})}function aa({item:e,type:t,getAvatarText:s,onOpenConversation:r,onRequestHideConversation:o,onRequestStopCli:a,onOpenMeshGraph:i,onCollectChatDebugBundle:l,isMuted:d,onToggleMute:u}){const{t:m}=he(),h=t==="needs_attention"||t==="task_complete",p=t==="working",b=t==="earlier",f=t==="task_complete",{isReconnecting:x,isConnecting:g,isErrored:v}=Ss(e.conversation),S=kt(e.conversation),A=Po(e.conversation),k=Lb(e.conversation,{requiresAction:t==="needs_attention"}),w=h?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":p?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":b?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",y=h?"bg-accent-primary shadow-glow":p?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":b?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",N=b?"text-text-secondary":"text-text-primary",j=b?"text-text-muted":"text-text-secondary",C=b?"text-text-secondary opacity-80":"text-text-muted",E=b?"text-text-muted opacity-80":"text-text-muted",P=!p&&!f,T=Rb(e.conversation),M="text-[color:var(--status-warning)]",_=I=>{if(!l||!R1())return;I.preventDefault(),I.stopPropagation();const D=l==null?void 0:l(e.conversation);Promise.resolve(D).catch(L=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",L)})};return n.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${w}`,children:n.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[h||p?n.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,n.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[n.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${y}`,style:h?{color:"var(--accent-on-primary)"}:void 0,children:s(S)}),T&&i&&n.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-[color:color-mix(in_srgb,var(--mesh-coordinator)_34%,transparent)] bg-bg-primary/70 text-[color:var(--mesh-coordinator)] transition-colors hover:bg-[color:color-mix(in_srgb,var(--mesh-coordinator)_10%,transparent)]",onClick:I=>{I.preventDefault(),I.stopPropagation(),i(e.conversation)},"aria-label":m("mobileInbox.openMeshGraphFor",{title:S}),title:m("mobileInbox.openLiveMeshGraph"),children:n.jsx(On,{size:13})})]}),n.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>r(e.conversation),onContextMenu:_,type:"button",children:[n.jsxs("div",{className:"flex items-center gap-1.5 pr-[92px]",children:[n.jsx(ws,{conversation:e.conversation,size:13}),n.jsx("span",{className:`text-[15px] leading-[22px] font-bold truncate tracking-tight ${N}`,children:S})]}),n.jsxs("div",{className:`text-xs font-medium truncate flex items-center ${j}`,children:[n.jsx("span",{className:"truncate",children:A}),n.jsx(Od,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),x?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:`${M} animate-pulse`,children:m("mobileInbox.reconnectingItem")})]}):g?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:"text-text-muted",children:m("mobileInbox.connectingItem")})]}):k==="Action needed"?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:M,children:m("mobileInbox.actionNeeded")})]}):v&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:"text-[color:var(--status-error)]",children:m("mobileInbox.needsAttention")})]})]}),n.jsx("div",{className:`mt-0.5 truncate text-xxs ${C}`,children:e.preview})]}),n.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[P&&n.jsx("span",{className:`mr-0.5 text-2xs font-medium shrink-0 ${E}`,children:Zp(e.timestamp)}),f&&n.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-3xs font-bold text-accent-primary",children:m("mobileInbox.done")}),n.jsx(rM,{title:S,isMuted:d,onToggleMute:u,onHide:o,onStop:a})]})]})},e.conversation.tabKey)}function gh({count:e,label:t}){return e<=0?null:n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-accent-primary","aria-live":"polite",children:[n.jsxs("span",{className:"relative flex h-2 w-2 shrink-0",children:[n.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-accent-primary/60"}),n.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-accent-primary"})]}),n.jsx("span",{className:"font-semibold",children:t})]})}function oM({section:e,attentionItems:t,unreadItems:s,workingItems:r,completedItems:o,hiddenConversations:a,machineCards:i,getAvatarText:l,actionLogs:d,sendDaemonCommand:u,onOpenConversation:m,onShowAllHidden:h,onHideConversation:p,onShowHiddenConversation:b,onOpenMeshGraph:f,onStopCli:x,onOpenNewSession:g,onOpenMachine:v,onOpenSettings:S,onSectionChange:A,wsStatus:k="connected",initialDataLoaded:w=!0,conversationsLoaded:y,isStandalone:N=!1,onCollectChatDebugBundle:j,isConversationMuted:C,onToggleMuteConversation:E}){const{t:P}=he(),T=k==="disconnected"||k==="reconnecting"||k==="offline"||k==="auth_failed",M=!T&&!w,_=!T&&!(y??w),I=i.length>0,D=t.length>0||s.length>0||r.length>0||o.length>0,L=P(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),$=N?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",q=N?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",G=c.useCallback(async O=>{const B=ps(O);if(!B)return;const H=Array.isArray(O.messages)?O.messages:[],U=lb({activeConv:O,visibleMessages:H,actionLogs:d,visibleBarControlCount:0,chatState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:H.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),K=await u(B,"get_chat_debug_bundle",{...gs(O),delivery:"daemon_file",frontendSnapshot:U}),oe=Ls(K),ge=mb(oe),J=await ub(ge);J==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),nt.showToast(db(oe,{locatorCopyStatus:J}),J==="failed"?"warning":"success")},[d,u]),W=j||G,R=c.useCallback(O=>{p&&(p(O),nt.showToast(P("mobileInbox.hiddenToast",{title:kt(O)}),"info",{duration:6e3,actions:[{label:P("mobileInbox.undo"),variant:"primary",onClick:()=>{b?b(O):h()}}]}))},[p,h,b,P]);return n.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[n.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${$}`,children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:L}),n.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||s.length>0)&&n.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-2xs font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[n.jsx(Jn,{size:13}),n.jsx("span",{children:t.length+s.length})]}),n.jsx("button",{onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:n.jsx(_r,{size:18})})]})]})}),n.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${q}`,children:[e==="machines"&&n.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:T?n.jsx(As,{icon:n.jsx(nn,{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")}):M?n.jsx(As,{icon:n.jsx(nn,{size:32}),title:P("mobileInbox.loading"),subtitle:P("mobileInbox.loadingSubtitle")}):i.length===0?n.jsx(As,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:P(N?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:P(N?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!N&&n.jsx("div",{className:"w-full max-w-[360px] mt-4",children:n.jsx(Kg,{})})}):n.jsx(tr,{children:i.map((O,B)=>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] ${B>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(O.id),type:"button",children:[n.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(O.label)}),n.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-[15px] leading-[22px] font-bold text-text-primary truncate tracking-tight",children:O.label}),n.jsxs("span",{className:"flex items-center gap-2 text-2xs font-medium text-text-muted shrink-0",children:[n.jsx(gh,{count:O.generatingCount,label:P("mobileInbox.generatingCount",{count:O.generatingCount})}),O.unread>0?n.jsx("span",{className:"text-accent-primary",children:P("mobileInbox.newCount",{count:O.unread})}):O.total>0?P("mobileInbox.chatCount",{count:O.total}):P("mobileInbox.idle")]})]}),n.jsx("div",{className:"text-xs font-medium text-text-secondary truncate",children:O.subtitle}),O.total>0?n.jsxs("div",{className:"text-xxs text-text-muted mt-0.5",children:[P("mobileInbox.chatCount",{count:O.total}),O.unread>0?P("mobileInbox.unreadSuffix",{count:O.unread}):"",O.generatingCount>0?P("mobileInbox.collapsedGeneratingSuffix",{count:O.generatingCount}):""]}):O.generatingCount>0?n.jsx("div",{className:"text-xxs text-accent-primary mt-0.5 font-medium",children:P("mobileInbox.generatingCount",{count:O.generatingCount})}):n.jsx("div",{className:"text-xxs text-text-muted mt-0.5 italic opacity-70",children:P("mobileInbox.noActiveChats")})]})]},O.id))})}),e==="chats"&&t.length>0&&n.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[n.jsx(oa,{title:P("mobileInbox.needsAttention"),className:"mb-0"}),n.jsx(tr,{children:t.map((O,B)=>n.jsx("div",{className:B>0?"border-t border-border-subtle/70":"",children:n.jsx(aa,{item:O,type:"needs_attention",getAvatarText:l,onOpenConversation:m,onRequestHideConversation:p?()=>R(O.conversation):void 0,onRequestStopCli:x?()=>x(O.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:W,isMuted:C==null?void 0:C(O.conversation),onToggleMute:E?()=>E(O.conversation):void 0})},O.conversation.tabKey))})]}),e==="chats"&&s.length>0&&n.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[n.jsx(oa,{title:P("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),n.jsx(tr,{children:s.map((O,B)=>n.jsx("div",{className:B>0?"border-t border-border-subtle/70":"",children:n.jsx(aa,{item:O,type:"task_complete",getAvatarText:l,onOpenConversation:m,onRequestHideConversation:p?()=>R(O.conversation):void 0,onRequestStopCli:x?()=>x(O.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:W,isMuted:C==null?void 0:C(O.conversation),onToggleMute:E?()=>E(O.conversation):void 0})},O.conversation.tabKey))})]}),e==="chats"&&r.length>0&&n.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[n.jsx(oa,{title:P("mobileInbox.workingNow"),className:"mb-0 mt-2"}),n.jsx(tr,{children:r.map((O,B)=>n.jsx("div",{className:B>0?"border-t border-border-subtle/70":"",children:n.jsx(aa,{item:O,type:"working",getAvatarText:l,onOpenConversation:m,onRequestHideConversation:p?()=>R(O.conversation):void 0,onRequestStopCli:x?()=>x(O.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:W,isMuted:C==null?void 0:C(O.conversation),onToggleMute:E?()=>E(O.conversation):void 0})},O.conversation.tabKey))})]}),e==="chats"&&n.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&n.jsx(oa,{title:P("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?n.jsx(tr,{children:o.map((O,B)=>n.jsx("div",{className:B>0?"border-t border-border-subtle/70":"",children:n.jsx(aa,{item:O,type:"earlier",getAvatarText:l,onOpenConversation:m,onRequestHideConversation:p?()=>R(O.conversation):void 0,onRequestStopCli:x?()=>x(O.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:W,isMuted:C==null?void 0:C(O.conversation),onToggleMute:E?()=>E(O.conversation):void 0})},O.conversation.tabKey))}):D?n.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:P("mobileInbox.allCaughtUp")}):T?n.jsx(As,{icon:n.jsx(nn,{size:28}),title:P("mobileInbox.connecting"),subtitle:P("mobileInbox.connectingSubtitle")}):_?n.jsx(As,{icon:n.jsx(nn,{size:28}),title:P("mobileInbox.loading"),subtitle:P("mobileInbox.loadingSubtitle")}):I?n.jsx(As,{icon:n.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:n.jsx(Cn,{size:20})}),title:P("mobileInbox.noConversations"),subtitle:P("paneGroup.newSessionDescription"),children:g&&n.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:g,"aria-label":P("paneGroup.newSession"),title:P("paneGroup.newSession"),children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),n.jsx("span",{children:P("paneGroup.newSession")})]})}):n.jsx(As,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:P("mobileInbox.noMachinesConnected"),subtitle:P("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&a.length>0&&(()=>{const O=Fk(a);return n.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:n.jsx(tr,{className:"mt-4 border-dashed bg-bg-secondary/20",children:n.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-xs font-bold uppercase tracking-wider text-text-secondary",children:P("mobileInbox.hiddenTabs")}),n.jsx(gh,{count:O,label:P("mobileInbox.generatingCount",{count:O})})]}),n.jsxs("div",{className:"mt-0.5 text-xxs text-text-muted",children:[P("mobileInbox.collapsedCount",{count:a.length}),O>0?P("mobileInbox.collapsedGeneratingSuffix",{count:O}):""]})]}),n.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-xs font-semibold text-accent-primary hover:border-border-default",onClick:h,children:P("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&g&&D&&n.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:g,"aria-label":P("paneGroup.newSession"),title:P("paneGroup.newSession"),children:n.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),n.jsx(qg,{section:e,onSectionChange:A})]})}function aM(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 zg(e,t){const s=[e.workspace||(t?t("launch.workspaceUnknown"):"Workspace unknown")],r=wo(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(t?t("launch.messageCountShort",{count:e.messageCount}):`${e.messageCount} msgs`);const o=aM(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:o?t?t("launch.updatedAt",{time:o}):`Updated ${o}`:"",preview:(e.preview||"").trim()}}function iu({title:e,description:t,currentPath:s,directories:r,busy:o=!1,error:a="",confirmLabel:i,inline:l=!1,onClose:d,onNavigate:u,onConfirm:m}){const[h,p]=c.useState(s),{t:b}=he("common"),f=i??b("machine.workspaceBrowse.useThisFolder");c.useEffect(()=>{p(s)},[s]);const x=LI(s),g=h.trim(),v=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(Lt,{size:16})})]}),n.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[n.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!x||o||u(x)},disabled:!x||o,children:[n.jsx(gi,{size:15}),b("machine.workspaceBrowse.parent")]}),n.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.workspaceBrowse.currentFolder")}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"text",value:h,onChange:S=>p(S.target.value),onKeyDown:S=>{S.key!=="Enter"||!g||o||(S.preventDefault(),u(g))},placeholder:b("machine.workspaceBrowse.pathPlaceholder"),className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),n.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!g||o||u(g)},disabled:!g||o,children:b("machine.workspaceBrowse.go")})]})]})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?n.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:b("machine.workspaceBrowse.loading")}):a?n.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:a}):r.length===0?n.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:b("machine.workspaceBrowse.noSubfolders")}):n.jsx("div",{className:"p-3",children:r.map(S=>n.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(S.path),children:[n.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:n.jsx(Ws,{size:17})}),n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:S.name}),n.jsx("span",{className:"block text-2xs text-text-muted truncate",children:S.path})]})]},S.path))})}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[n.jsx("button",{type:"button",className:"btn btn-secondary h-9 px-4 text-sm",onClick:d,children:b("common.cancel")}),n.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(g||s),disabled:!g&&!s||o,children:f})]})]});return l?n.jsx("div",{className:"mt-3 flex max-h-[min(60vh,440px)] flex-col overflow-hidden rounded-xl border border-border-subtle bg-bg-secondary",role:"region","aria-labelledby":"workspace-browse-title","data-testid":"workspace-browse-inline",children:v}):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:v})})})}function Ui({title:e,description:t,details:s,workspaceOptions:r,selectedWorkspaceKey:o,onWorkspaceChange:a,confirmLabel:i,busyLabel:l,busy:d=!1,showArgsInput:u,argsValue:m,onArgsChange:h,showModelInput:p,modelValue:b,onModelChange:f,historyProviderNode:x,onConfirm:g,onCancel:v}){const{t:S}=he("common"),A=i??S("machine.launchConfirm.launch"),k=l??S("machine.launchConfirm.launching"),w=r==null?void 0:r.find(N=>N.key===o),y=n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:n.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),n.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),n.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:v,"aria-label":S("machine.launchConfirm.closeAria"),children:n.jsx(Lt,{size:16})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[r&&r.length>0&&a&&n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:S("machine.launchConfirm.workspace")}),n.jsx("select",{value:o||"",onChange:N=>a(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:r.map(N=>n.jsx("option",{value:N.key,children:N.label},N.key))}),(w==null?void 0:w.description)&&n.jsx("div",{className:"mt-2 text-2xs text-text-muted break-all",children:w.description})]}),x,s.map((N,j)=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:N.label}),n.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${j}`)),p&&f&&n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:S("machine.launchConfirm.languageModel")}),n.jsx("input",{type:"text",value:b||"",onChange:N=>f(N.target.value),placeholder:S("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),u&&h&&n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:S("machine.launchConfirm.cliArgs")}),n.jsx("input",{type:"text",value:m||"",onChange:N=>h(N.target.value),placeholder:S("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[n.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:v,disabled:d,children:S("machine.launchConfirm.cancel")}),n.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:g,disabled:d,children:[n.jsx(Up,{size:14}),d?k:A]})]})]})});return typeof document>"u"?y:An.createPortal(y,document.body)}function xh(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Vg(e){const{machine:t,currentWorkspacePath:s,currentWorkspaceId:r,includeHome:o=!0,homeLabel:a="Home directory",homeDescription:i="Launch without a workspace"}=e,l=[];o&&l.push({key:"__home__",label:a,description:i,workspaceId:null,workspacePath:null});for(const m of t.workspaces||[])l.push({key:`saved:${m.id}`,label:`${m.id===t.defaultWorkspaceId?"⭐ ":""}${xh(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const d=(s==null?void 0:s.trim())||"",u=d?(t.workspaces||[]).find(m=>m.path===d):null;if(d&&!u&&l.push({key:`custom:${d}`,label:xh(d),description:d,workspaceId:null,workspacePath:d}),r){const m=`saved:${r}`;if(l.some(h=>h.key===m))return{options:l,selectedKey:m}}return u?{options:l,selectedKey:`saved:${u.id}`}:d?{options:l,selectedKey:`custom:${d}`}:{options:l,selectedKey:"__home__"}}function iM(e){return e==="ide"?"IDE":"CLI"}function cM(e,t){return[iM(e.kind),e.subtitle||"",e.providerSessionId?t?t("launch.savedHistoryBadge"):"Saved history":""].filter(Boolean).join(" · ")}function lM(e){return e.lastLaunchedAt?Si(e.lastLaunchedAt):""}function Gg(e,t){return{metaText:cM(e,t),updatedLabel:lM(e)}}function Ec(e,t){return e?"ide":t>0?"cli":null}function dM({selectedMachineEntry:e,cliProviders:t,machineAction:s,onBrowseDirectory:r,onListSavedSessions:o}){var fe,Ie,Ke,_e;const a=Rr(),[i,l]=c.useState(!1),d=(((fe=e.detectedIdes)==null?void 0:fe.length)||0)>0,u=c.useMemo(()=>(e.workspaces||[]).map(Ne=>({id:Ne.id,path:Ne.path,label:Ne.label})),[e]),m=e.defaultWorkspaceId||null,[h,p]=c.useState(m||((Ie=u[0])==null?void 0:Ie.id)||""),[b,f]=c.useState(""),[x,g]=c.useState(""),[v,S]=c.useState([]),[A,k]=c.useState(!1),[w,y]=c.useState(""),[N,j]=c.useState(!1),[C,E]=c.useState(Ec(d,t.length)),P=c.useRef(null),[T,M]=c.useState(null),_=c.useRef("__home__"),[I,D]=c.useState("__home__"),[L,$]=c.useState(""),[q,G]=c.useState(""),[W,R]=c.useState(""),[O,B]=c.useState([]),[H,U]=c.useState(()=>mn().textQuery),[K,oe]=c.useState(()=>mn().workspaceQuery),[ge,J]=c.useState(()=>mn().modelQuery),[ke,de]=c.useState(()=>mn().resumableOnly),[ne,le]=c.useState(()=>mn().sortMode),[te,ce]=c.useState(!1),[Ce,Q]=c.useState(!1),z=c.useRef(0),X=c.useRef(0),pe=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 Oe=h==="__custom__"?b.trim():((Ke=u.find(Ne=>Ne.id===h))==null?void 0:Ke.path)||"",De=h==="__custom__"&&!!Oe&&s.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(s.message),we=h!=="__custom__"&&((_e=u.find(Ne=>Ne.id===h))==null?void 0:_e.path)||"",V=c.useMemo(()=>(e.recentLaunches||[]).map(Ne=>Ne.workspace),[e]),xe=c.useCallback(async Ne=>{const Be=z.current+1;z.current=Be,k(!0),y("");try{const $e=await r(Ne);if(z.current!==Be)return;g($e.path),f($e.path),S($e.directories)}catch($e){if(z.current!==Be)return;y($e instanceof Error?$e.message:"Could not load folder")}finally{z.current===Be&&k(!1)}},[r]),Z=c.useCallback(()=>{var Be;p("__custom__"),j(!0);const Ne=ru(e.platform,su(b.trim(),we,V,e.defaultWorkspacePath,(Be=u.find($e=>$e.id===m))==null?void 0:Be.path,u.map($e=>$e.path)));xe(Ne)},[b,m,xe,V,we,e.platform,u]),ae=c.useCallback(Ne=>{if(Ne!=null&&Ne.workspaceId){p(Ne.workspaceId),f("");return}if(Ne!=null&&Ne.workspacePath){p("__custom__"),f(Ne.workspacePath);return}p(""),f("")},[]),F=c.useCallback(Ne=>{if(p(Ne),Ne==="__custom__"){Z();return}f("")},[Z]),se=c.useCallback(Ne=>{p("__custom__"),f(Ne)},[]),me=c.useCallback((Ne,Be)=>{const $e=X.current+1;X.current=$e,P.current=Be,_.current=Ne.selectedWorkspaceKey||"__home__",D(Ne.selectedWorkspaceKey||"__home__"),$(Ne.initialArgs||""),G(Ne.initialModel||""),R(""),B([]);const it=Ne.providerType?`${e.id}:${Ne.providerType}`:null;if(cT(Re.current,it)){const dt=mn();U(dt.textQuery),oe(dt.workspaceQuery),J(dt.modelQuery),de(dt.resumableOnly),le(dt.sortMode)}Re.current=it,M(Ne),Ne.providerType&&o?(ce(!0),o(Ne.providerType).then(dt=>{X.current===$e&&B(dt||[])}).catch(dt=>{X.current===$e&&console.warn("Failed to load saved sessions",dt)}).finally(()=>{X.current===$e&&ce(!1)})):ce(!1)},[o,e.id]),re=c.useMemo(()=>zd(O,{textQuery:H,workspaceQuery:K,modelQuery:ge,resumableOnly:ke,sortMode:ne}),[ge,ke,O,ne,H,K]);c.useEffect(()=>{W&&(re.some(Ne=>Ne.providerSessionId===W)||R(""))},[re,W]);const Se=c.useCallback(()=>{P.current&&(Q(!0),P.current().finally(()=>{P.current=null,Q(!1),M(null)}))},[]),Y=c.useCallback(()=>{X.current+=1,P.current=null,ce(!1),M(null)},[]),ue=c.useCallback(Ne=>{_.current=Ne,D(Ne)},[]);return c.useEffect(()=>{var Ne;pe.current!==e.id&&(z.current+=1,X.current+=1,pe.current=e.id,p(m||((Ne=u[0])==null?void 0:Ne.id)||"__custom__"),f(""),g(""),S([]),k(!1),y(""),j(!1),P.current=null,M(null),B([]),ce(!1),Q(!1),U(mn().textQuery),oe(mn().workspaceQuery),J(mn().modelQuery),de(mn().resumableOnly),le(mn().sortMode),Re.current=null,E(Ec(d,t.length)))},[t.length,m,d,e.id,u]),c.useEffect(()=>{var Ne;h!=="__custom__"&&(h&&u.some(Be=>Be.id===h)||p(m||((Ne=u[0])==null?void 0:Ne.id)||"__custom__"))},[m,h,u]),c.useEffect(()=>{C==="ide"&&d||C==="cli"&&t.length>0||E(Ec(d,t.length))},[C,t.length,d]),{showAllRecent:i,setShowAllRecent:l,hasIdeOptions:d,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:h,customWorkspacePath:b,browseCurrentPath:x,browseDirectories:v,browseBusy:A,browseError:w,browseDialogOpen:N,activeLauncherKind:C,launchConfirm:T,launchConfirmWorkspaceKeyRef:_,launchConfirmWorkspaceKey:I,launchConfirmArgs:L,launchConfirmModel:q,launchConfirmResumeId:W,launchConfirmSavedSessions:O,launchConfirmTextFilter:H,launchConfirmWorkspaceFilter:K,launchConfirmModelFilter:ge,launchConfirmResumableOnly:ke,launchConfirmSortMode:ne,filteredLaunchConfirmSavedSessions:re,launchConfirmSessionsLoading:te,launchConfirmBusy:Ce,resolvedWorkspacePath:Oe,canCreateMissingWorkspace:De,openBrowseDialog:Z,loadBrowsePath:xe,handleWorkspaceChoiceChange:F,chooseCustomWorkspacePath:se,setCustomWorkspacePath:f,setBrowseDialogOpen:j,setActiveLauncherKind:E,openLaunchConfirm:me,handleConfirmLaunch:Se,closeLaunchConfirm:Y,setWorkspaceSelectionFromOption:ae,setLaunchConfirmWorkspaceKeyAndSync:ue,setLaunchConfirmArgs:$,setLaunchConfirmModel:G,setLaunchConfirmResumeId:R,setLaunchConfirmTextFilter:U,setLaunchConfirmWorkspaceFilter:oe,setLaunchConfirmModelFilter:J,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:le}}function uM({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:s,cliProviders:r,selectedMachineNeedsUpgrade:o,appVersion:a,machineAction:i,isStandalone:l,section:d,showBottomNav:u,onBack:m,onSectionChange:h,onOpenConversation:p,onOpenRecent:b,onOpenMachineDetails:f,onMachineUpgrade:x,onBrowseDirectory:g,onListSavedSessions:v}){const{t:S}=he("common"),A=M=>M==="ide"?"IDE":"CLI",k=s.slice(0,4),w=t.slice(0,3),y=dM({selectedMachineEntry:e,cliProviders:r,machineAction:i,onBrowseDirectory:g,onListSavedSessions:v}),N=c.useMemo(()=>k.map(M=>{const{metaText:_,updatedLabel:I}=Gg(M,S);return{key:`recent-launch:${M.id}`,primary:M.label,secondary:_,updatedLabel:I,onClick:()=>{const{options:D,selectedKey:L}=Vg({machine:{workspaces:y.workspaceRows,defaultWorkspaceId:y.defaultWorkspaceId},currentWorkspacePath:M.workspace,homeLabel:S("newSession.homeDirectory"),homeDescription:S("newSession.launchWithoutWorkspace")});y.openLaunchConfirm({title:M.kind==="ide"?Za(S,"restart-ide",M.label):M.providerSessionId?hg(S,M.label):Za(S,"start-fresh",M.label),description:M.kind==="ide"?ei(S,"restart-ide"):M.providerSessionId?pg(S):ei(S,"start-fresh"),confirmLabel:M.kind==="ide"?ti(S,"restart-ide"):M.providerSessionId?Bl(S,!0):ti(S,"start-fresh"),busyLabel:M.kind==="ide"?ni(S,"restart-ide"):M.providerSessionId?ug(S,!0):ni(S,"start-fresh"),workspaceOptions:D,selectedWorkspaceKey:L,details:[{label:"Mode",value:A(M.kind)},...M.providerType?[{label:"Provider",value:M.providerType}]:[]]},async()=>{const $=D.find(q=>q.key===y.launchConfirmWorkspaceKeyRef.current);y.setWorkspaceSelectionFromOption($),await b({...M,workspace:($==null?void 0:$.workspacePath)??null})})}}}),[y,b,k,S]),j=c.useMemo(()=>w.map(M=>({key:`recent-chat:${M.conversation.tabKey}`,conversation:M.conversation,primary:kt(M.conversation),secondary:f1(M.conversation,{timestampLabel:M.timestamp?Zp(M.timestamp):null}),unread:M.unread,onClick:()=>p(M.conversation)})),[p,w]),C=y.showAllRecent?N:N.slice(0,4),E=N.length>0,P=j.length>0,T=l?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`flex items-center justify-between gap-3 ${T} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:n.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[n.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":S("common.back"),children:n.jsx(gi,{size:18})}),n.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[n.jsx("div",{className:"flex items-center gap-2 text-[17px] leading-[26px] font-extrabold tracking-tight text-text-primary truncate",children:pn(e,{fallbackId:e.id})}),n.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||S("machine.mobile.machineFallback"),e.version?` · v${e.version}`:""]})]})]})}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[P&&n.jsxs("section",{className:"flex flex-col gap-0",children:[n.jsx("div",{className:"text-2xs font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:S("machine.mobile.currentChats")}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:j.map(M=>n.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${M.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:M.onClick,children:[n.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 text-sm font-bold text-text-primary",children:[n.jsx(ws,{conversation:M.conversation,size:13}),n.jsx("span",{className:"min-w-0 truncate",children:M.primary})]}),n.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.key))})]}),E&&n.jsxs("section",{className:"flex flex-col gap-0",children:[n.jsx("div",{className:"text-2xs font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:S("machine.mobile.recentLaunches")}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:C.map(M=>n.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:M.onClick,children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[n.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:M.primary}),M.updatedLabel&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:M.updatedLabel})]}),n.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.key))}),N.length>4&&n.jsx("div",{className:"flex justify-center px-4 pt-2",children:n.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>y.setShowAllRecent(M=>!M),children:y.showAllRecent?S("machine.mobile.showFewer"):S("machine.mobile.showMore",{count:N.length-4})})})]}),n.jsxs("section",{className:"flex flex-col gap-0",children:[n.jsx("div",{className:"text-2xs font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:S("machine.mobile.inspect")}),n.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&n.jsx("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:n.jsx("span",{className:"text-sm font-bold text-text-primary",children:S("machine.commandCenter.updateToVersion",{version:a})})}),n.jsx("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:f,children:n.jsx("span",{className:"text-sm font-bold text-text-primary",children:S("machine.mobile.machineDetails")})})]})]})]}),y.browseDialogOpen&&n.jsx(iu,{title:S("machine.mobile.browseTitle"),description:S("machine.mobile.browseDescription"),currentPath:y.browseCurrentPath,directories:y.browseDirectories,busy:y.browseBusy,error:y.browseError,confirmLabel:S("machine.mobile.useThisFolder"),onClose:()=>y.setBrowseDialogOpen(!1),onNavigate:M=>{y.loadBrowsePath(M)},onConfirm:M=>{y.chooseCustomWorkspacePath(M),y.setBrowseDialogOpen(!1)}}),y.launchConfirm&&n.jsx(Ui,{title:y.launchConfirm.title,description:y.launchConfirm.description,details:y.launchConfirm.details,workspaceOptions:y.launchConfirm.workspaceOptions,selectedWorkspaceKey:y.launchConfirmWorkspaceKey,onWorkspaceChange:y.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:y.launchConfirm.providerType?Bl(S,!!y.launchConfirmResumeId):y.launchConfirm.confirmLabel,busyLabel:y.launchConfirm.providerType?void 0:y.launchConfirm.busyLabel,busy:y.launchConfirmBusy,showArgsInput:y.launchConfirm.showArgsInput,argsValue:y.launchConfirmArgs,onArgsChange:y.setLaunchConfirmArgs,showModelInput:y.launchConfirm.showModelInput,modelValue:y.launchConfirmModel,onModelChange:y.setLaunchConfirmModel,historyProviderNode:y.launchConfirm.providerType&&(y.launchConfirmSessionsLoading||y.launchConfirmSavedSessions.length>0)&&n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsxs("div",{className:"flex items-center justify-between mb-1",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted",children:S("launch.resumeSavedHistory")}),y.launchConfirmSessionsLoading&&n.jsx("div",{className:"text-3xs text-text-secondary font-medium",children:S("launch.loadingShort")})]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2",children:Vd(S)}),n.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[n.jsx("input",{type:"text",value:y.launchConfirmTextFilter,onChange:M=>y.setLaunchConfirmTextFilter(M.target.value),placeholder:S("machine.mobile.searchHistory"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),n.jsx("input",{type:"text",value:y.launchConfirmWorkspaceFilter,onChange:M=>y.setLaunchConfirmWorkspaceFilter(M.target.value),placeholder:S("machine.mobile.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),n.jsx("input",{type:"text",value:y.launchConfirmModelFilter,onChange:M=>y.setLaunchConfirmModelFilter(M.target.value),placeholder:S("machine.mobile.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),n.jsxs("select",{value:y.launchConfirmSortMode,onChange:M=>y.setLaunchConfirmSortMode(M.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading,children:[n.jsx("option",{value:"recent",children:S("machine.mobile.sortRecent")}),n.jsx("option",{value:"oldest",children:S("machine.mobile.sortOldest")}),n.jsx("option",{value:"messages",children:S("machine.mobile.sortMessages")})]})]}),n.jsxs("label",{className:"mb-2 flex items-center gap-2 text-2xs text-text-muted",children:[n.jsx("input",{type:"checkbox",checked:y.launchConfirmResumableOnly,onChange:M=>y.setLaunchConfirmResumableOnly(M.target.checked),disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),S("machine.mobile.resumableOnly")]}),n.jsxs("select",{value:y.launchConfirmResumeId,onChange:M=>y.setLaunchConfirmResumeId(M.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading,children:[n.jsx("option",{value:"",children:uT(S)}),y.filteredLaunchConfirmSavedSessions.map(M=>n.jsxs("option",{value:M.providerSessionId,disabled:!M.canResume,children:[M.title||M.providerSessionId," ",M.canResume?"":S("machine.mobile.workspaceMissing")]},M.providerSessionId))]}),!y.launchConfirmSessionsLoading&&y.launchConfirmSavedSessions.length>0&&y.filteredLaunchConfirmSavedSessions.length===0&&n.jsx("div",{className:"mt-2 text-2xs text-text-muted",children:S("machine.mobile.noHistoryMatches")}),y.launchConfirmResumeId&&(()=>{const M=y.filteredLaunchConfirmSavedSessions.find(I=>I.providerSessionId===y.launchConfirmResumeId);if(!M)return null;const _=zg(M,S);return n.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-2xs text-text-muted leading-relaxed",children:[n.jsx("div",{className:"font-semibold text-text-primary truncate",children:_.title}),n.jsx("div",{className:"font-mono break-all mt-0.5",children:_.providerSessionId}),n.jsx("div",{className:"mt-1",children:_.metaLine}),_.updatedLabel&&n.jsx("div",{className:"mt-1 text-text-secondary",children:_.updatedLabel}),_.preview&&n.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:_.preview})]})})()]}),onConfirm:y.handleConfirmLaunch,onCancel:y.closeLaunchConfirm}),u&&n.jsx(qg,{section:d,onSectionChange:h})]})}const yh=8e3;function mM(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 Yg(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,v]of b){const S=e.get(g),A=v.muted===void 0||(S?S.muted===v.muted:!1),k=v.hidden===void 0||(S?S.surfaceHidden===v.hidden:!1),w=f-v.at>yh;(A&&k||w)&&(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[v,S]of f)x-S.at>yh&&(f.delete(v),g=!0);g&&a(),f.size===0&&clearInterval(b)},1e3);return()=>clearInterval(b)});const i=c.useCallback((b,f)=>{const x=r.current.get(b);r.current.set(b,{...x,...f,at:Date.now()}),a()},[a]),l=c.useCallback(b=>{const f=b.sessionId,x=f?r.current.get(f):void 0;return(x==null?void 0:x.muted)!==void 0?x.muted:ys(b,e).muted??!1},[e]),d=c.useCallback(b=>{const f=b.sessionId,x=f?r.current.get(f):void 0;return(x==null?void 0:x.hidden)!==void 0?x.hidden:ys(b,e).surfaceHidden??!1},[e]),u=c.useCallback((b,f)=>{const x=Xn(b),g=b.sessionId;!x||!g||(i(g,f),t(x,"set_conversation_prefs",{sessionId:g,...f,...Ri(b)}).then(v=>{const S=mM(v);S.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",S.reason),r.current.delete(g),a(),s==null||s(`Couldn't update conversation — ${S.reason}`))}).catch(v=>{console.warn("[conversation-prefs] set_conversation_prefs failed",v),r.current.delete(g),a();const S=v instanceof Error?v.message:String(v??"the daemon is unreachable");s==null||s(`Couldn't update conversation — ${S}`)}))},[t,i,a,s]),m=c.useCallback(b=>{u(b,{muted:!l(b)})},[u,l]),h=c.useCallback((b,f)=>{u(b,{hidden:f})},[u]),p=c.useCallback(b=>{u(b,{hidden:!d(b)})},[u,d]);return{isMuted:l,isHidden:d,toggleMute:m,setHidden:h,toggleHidden:p}}function Ma(e){return[...e].sort((t,s)=>{const r=Kb(t.conversation,s.conversation);if(r!==0)return r;const o=s.timestamp-t.timestamp;return o!==0?o:t.conversation.tabKey.localeCompare(s.conversation.tabKey)})}function hM(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:Ma(e)}function pM(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:Ma(s),unreadItems:Ma(r),workingItems:hM(o,t),completedItems:Ma(a)}}function Ki(e,t){if(!t)return!1;const s=e.filter(r=>r.type==="adhdev-daemon"&&Qg(r)==="Connected");return s.length===0?!0:s.every(r=>r._sessionListAuthoritative===!0)}function Qg(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 fM(e,t){if(!e)return[];const s=e.recentLaunches||[];return s.length>0?s.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:wo(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var a;const o=So(r)?"cli":"ide";return{id:`${o}:${r.type}:${r.workspace||""}`,label:((a=r.activeChat)==null?void 0:a.title)||So(r)&&r.cliName||r.type,kind:o,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,o)=>o.timestamp-r.timestamp).map(({timestamp:r,...o})=>o)}function bM(e,t,s=[]){const r=new Map;for(const a of t){const i=Xn(a.conversation),l=r.get(i);l?l.push(a):r.set(i,[a])}const o=new Map;for(const a of s){const i=Xn(a),l=o.get(i);l?l.push(a):o.set(i,[a])}return e.map(a=>{const i=r.get(a.id)||[],l=o.get(a.id)||[],d=[...i].sort((x,g)=>g.timestamp-x.timestamp)[0]||null,u=(d==null?void 0:d.conversation)||null,m=Al(a),h=i.filter(x=>x.unread||x.requiresAction).length,p=i.filter(x=>Us(x.conversation)).length+l.filter(Us).length,b=Qg(a),f=[a.platform||"machine",b].filter(Boolean);return{id:a.id,label:pn(a,{fallbackId:a.id}),subtitle:f.join(" · "),unread:h,total:i.length,generatingCount:p,latestConversation:u,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:m,preview:u?b1(u,jb(u)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE or CLI session."}}).sort((a,i)=>{const l=a.latestTimestamp||a.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==l?d-l:a.label.localeCompare(i.label)})}function gM(e){return e==="chat"}function ia(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 xM({conversations:e,machineEntries:t,items:s,selectedConversation:r,selectedTabKey:o,screen:a,liveSessionInboxState:i,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:b,setSelectedTabKey:f,setScreen:x,setSelectedMachineId:g,setSection:v,setMachineBackTarget:S,resetMachineAction:A}){const k=c.useRef(null),w=c.useCallback(y=>{if(!(y!=null&&y.sessionId))return;const N=ys(y,i),j=Math.max(Date.now(),Hs(y),N.lastUpdated||0);ia("mark_read:start",{tabKey:y.tabKey,sessionId:y.sessionId,displayPrimary:kt(y),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Hs(y),readAt:j}),l(Xn(y)||y.routeId,"mark_session_seen",{sessionId:y.sessionId,providerSessionId:y.providerSessionId,seenAt:j,completionMarker:N.completionMarker}).then(C=>{ia("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:C})}).catch(C=>{ia("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:C instanceof Error?C.message:String(C)})})},[i,l]);return c.useEffect(()=>{var N;if(!r){gM(a)&&x("inbox"),f(((N=e[0])==null?void 0:N.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,w(r))},[e,w,a,r,x,f]),c.useEffect(()=>{if(!d)return;const y=e.find(N=>N.tabKey===d);y&&(f(y.tabKey),x("chat"),u==null||u())},[e,u,d,x,f]),c.useEffect(()=>{if(!m)return;const y=t.find(N=>N.id===m);y&&(g(y.id),A(),v("machines"),S("inbox"),x("machine"),h==null||h())},[t,h,m,A,S,x,v,g]),c.useEffect(()=>{p&&(v(p),x("inbox"),b==null||b())},[b,p,x,v]),c.useEffect(()=>{const y=s.filter(N=>N.inboxBucket==="task_complete"||N.unread);y.length!==0&&ia("inbox_state",{screen:a,selectedTabKey:o,items:y.map(N=>{const j=ys(N.conversation,i);return{liveState:j,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:kt(N.conversation),serverBucket:j.inboxBucket,computedBucket:N.inboxBucket,serverUnread:j.unread,computedUnread:N.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:Hs(N.conversation)}})})},[s,i,a,o]),{markConversationRead:w}}const yM="Cannot update: node update policy unavailable; refresh and try again";async function vM(e,t,s){var o,a,i,l,d,u;const r=tu(s);if(!r)return{state:"error",message:yM};try{const m=await e(t,"daemon_upgrade",r);return(o=m==null?void 0:m.result)!=null&&o.alreadyLatest?{state:"done",message:`Already on v${((a=m==null?void 0:m.result)==null?void 0:a.version)||"latest"}.`}:(i=m==null?void 0:m.result)!=null&&i.upgraded||(l=m==null?void 0:m.result)!=null&&l.success?{state:"done",message:`Upgrade to v${((d=m==null?void 0:m.result)==null?void 0:d.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((u=m==null?void 0:m.result)==null?void 0:u.error)||"Upgrade failed"}}catch(m){return{state:"error",message:m instanceof Error?m.message:"Upgrade failed"}}}function wM(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function vh(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function SM(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function kM({sendDaemonCommand:e,navigate:t,ides:s,conversations:r}){const{launchCli:o}=wi(),[a,i]=c.useState("idle"),[l,d]=c.useState(""),[u,m]=c.useState(null),h=c.useCallback(()=>{i("idle"),d(""),m(null)},[]),p=c.useCallback(async(A,k,w)=>{var y;try{i("loading"),d(`Launching ${k}…`);const N={ideType:k,enableCdp:!0};(y=w==null?void 0:w.workspacePath)!=null&&y.trim()&&(N.workspace=w.workspacePath.trim()),await e(A,"launch_ide",N),i("done"),d(`${k} launch requested`)}catch(N){i("error"),d(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),b=c.useCallback(async(A,k,w)=>{if(k.trim())try{i("loading"),d(w!=null&&w.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(A,"workspace_add",{path:k.trim(),createIfMissing:(w==null?void 0:w.createIfMissing)===!0});if(y!=null&&y.success){i("done"),d(w!=null&&w.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 A=>{i("loading"),d("Starting daemon upgrade…");const k=s.find(y=>y.id===A||y.daemonId===A),w=await vM(e,A,k);i(w.state),d(w.message)},[s,e]),x=c.useCallback(async(A,k,w,y)=>{var C,E,P;const N=Date.now(),j={machineId:A,kind:k,providerType:w,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:N};try{i("loading"),d(`Launching ${w}…`),m(j);const T={cliType:w};(C=y==null?void 0:y.workspacePath)!=null&&C.trim()?T.dir=y.workspacePath.trim():y!=null&&y.workspaceId?T.workspaceId=y.workspaceId:y!=null&&y.useHome&&(T.useHome=!0),y!=null&&y.resumeSessionId&&(T.resumeSessionId=y.resumeSessionId),(E=y==null?void 0:y.args)!=null&&E.trim()&&(T.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(P=y==null?void 0:y.model)!=null&&P.trim()&&(T.initialModel=y.model.trim());const M=await o(A,T),_=(M==null?void 0:M.result)||M,I=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(M!=null&&M.success&&I){m(null),i("done"),d(`${w} launched`),t(ko(I));return}if(M!=null&&M.success){i("loading"),d(`${w} launch requested — waiting for session…`);return}m(null),i("error"),d((M==null?void 0:M.error)||(_==null?void 0:_.error)||`Could not launch ${k.toUpperCase()} workspace`)}catch(T){if(SM(T)){i("loading"),d(`${w} launch requested — waiting for session…`);return}m(null),i("error"),d(T instanceof Error?T.message:`Could not launch ${k.toUpperCase()} workspace`)}},[t,e]),g=c.useCallback(async(A,k)=>{try{const w=await e(A,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),y=(w==null?void 0:w.result)??w;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(w){return console.error("Failed to list saved sessions on mobile:",w),[]}},[e]),v=c.useCallback(async(A,k)=>ou(e,A,k),[e]);c.useEffect(()=>{if(!u)return;const A=vh(u.workspacePath),k=s.find(y=>{var T,M,_,I;if(!y||y.type==="adhdev-daemon"||wM(y.daemonId||y.id)!==u.machineId||(y.transport==="pty"?"cli":null)!==u.kind||String(y.agentType||y.type||"")!==u.providerType)return!1;const E=String(y.providerSessionId||"");if(u.resumeSessionId&&E)return E===u.resumeSessionId;if(A){const D=vh(y.workspace||y.runtimeWorkspaceLabel);return D?D===A:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((I=(_=(M=(T=y.activeChat)==null?void 0:T.messages)==null?void 0:M.at)==null?void 0:_.call(M,-1))==null?void 0:I.timestamp)||0)>=u.startedAt-5e3});if(!k)return;const w=Wg({entrySessionId:k.sessionId,entryInstanceId:k.instanceId,entryRouteId:k.id,conversations:r});w&&(m(null),i("done"),d(`${u.providerType} launched`),t(ko(w)))},[r,s,t,u]),c.useEffect(()=>{if(!u)return;const A=window.setTimeout(()=>{m(k=>!k||k.startedAt!==u.startedAt?k:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(A)},[u]);const S=c.useCallback(async(A,k)=>{var w;if(k.kind==="ide"&&k.providerType){await p(A,k.providerType,{workspacePath:k.workspace||null});return}if(k.kind==="cli"&&k.providerType){const y=((w=k.workspace)==null?void 0:w.trim())||"";await x(A,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:v,handleOpenRecent:S}}function jM({conversations:e,selectedConversation:t,machineBackTarget:s,markConversationRead:r,resetMachineAction:o,setSelectedTabKey:a,setScreen:i,setSelectedMachineId:l,setSection:d,setMachineBackTarget:u}){const m=c.useCallback(v=>{a(v.tabKey),i("chat"),r(v)},[r,i,a]),h=c.useCallback(v=>{const S=e.find(A=>A.routeId===v.routeId&&A.streamSource==="native");S&&(a(S.tabKey),i("chat"),r(S))},[e,r,i,a]),p=c.useCallback(()=>{r(t),i("inbox")},[r,t,i]),b=c.useCallback((v,S="inbox")=>{l(v),o(),d("machines"),u(S),i("machine")},[o,u,i,d,l]),f=c.useCallback(v=>{const S=Xn(v);S&&b(S,"chat")},[b]),x=c.useCallback(()=>{o(),i(s)},[s,o,i]),g=c.useCallback(v=>{d(v),i("inbox")},[i,d]);return{openConversation:m,openNativeConversation:h,backFromConversation:p,openMachine:b,openConversationMachine:f,backFromMachine:x,changeMachineSection:g}}function NM(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function CM({conversations:e,hiddenConversations:t,ides:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:b,onOpenHistory:f,onOpenRemote:x,onStopCli:g,wsStatus:v,isConnected:S,initialDataLoaded:A=!0,onShowAllHiddenConversations:k,onHideConversation:w,onShowHiddenConversation:y,onOpenMeshGraph:N,onOpenNewSession:j,liveSessionInboxState:C,setCliViewModeOverrides:E}){const[P,T]=c.useState(()=>{var ae;return((ae=e[0])==null?void 0:ae.tabKey)||null}),[M,_]=c.useState(()=>e[0]?"chat":"inbox"),[I,D]=c.useState("chats"),[L,$]=c.useState(null),[q,G]=c.useState("inbox"),W=c.useRef([]),R=Vs(),O="1.0.75",B=c.useMemo(()=>e.find(ae=>ae.tabKey===P)||e[0]||null,[e,P]),H=c.useMemo(()=>B?s.find(ae=>ae.id===B.routeId):void 0,[s,B]),U=c.useMemo(()=>!B||!ft(B)?null:Mr(B),[B]),K=c.useMemo(()=>s.filter(ae=>ae.type==="adhdev-daemon").sort(Ua),[s]),oe=c.useMemo(()=>K.find(ae=>ae.id===L)||null,[K,L]),ge=Ei({sendDaemonCommand:o,activeConv:B||void 0,setActionLogs:a,isStandalone:i}),J=kM({sendDaemonCommand:o,navigate:R,ides:s,conversations:e}),ke=j_(e),de=c.useMemo(()=>e.map(ae=>{const F=M==="chat"&&(B==null?void 0:B.tabKey)===ae.tabKey,se=Ni(ae,C,{hideOpenTaskCompleteUnread:!0,isOpenConversation:F}),me=Hs(ae),re=jb(ae),Se=Eb(ae,re);return{conversation:ae,timestamp:me,preview:Se,unread:se.unread,requiresAction:se.requiresAction,isWorking:se.isWorking,inboxBucket:se.inboxBucket}}),[e,C,M,B,ke]),{markConversationRead:ne}=xM({conversations:e,machineEntries:K,items:de,selectedConversation:B,selectedTabKey:P,screen:M,liveSessionInboxState:C,sendDaemonCommand:o,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:b,setSelectedTabKey:T,setScreen:_,setSelectedMachineId:$,setSection:D,setMachineBackTarget:G,resetMachineAction:J.resetMachineAction}),le=jM({conversations:e,selectedConversation:B,machineBackTarget:q,markConversationRead:ne,resetMachineAction:J.resetMachineAction,setSelectedTabKey:T,setScreen:_,setSelectedMachineId:$,setSection:D,setMachineBackTarget:G}),{isMuted:te,toggleMute:ce}=Yg(C,o),{attentionItems:Ce,unreadItems:Q,workingItems:z,completedItems:X}=c.useMemo(()=>pM(de,W.current),[de]);c.useEffect(()=>{W.current=z.map(ae=>ae.conversation.tabKey)},[z]);const pe=c.useMemo(()=>oe?de.filter(ae=>Xn(ae.conversation)===oe.id):[],[de,oe]),Re=c.useMemo(()=>fM(oe,s),[s,oe]),Oe=!!oe&&nu(oe,Rs(oe,O)),De=c.useMemo(()=>(oe==null?void 0:oe.availableProviders)||[],[oe]),we=c.useMemo(()=>De.filter(ae=>Li(ae,"cli")).map(ae=>({type:ae.type,displayName:ae.displayName||ae.type,icon:ae.icon})),[De]),V=c.useMemo(()=>bM(K,de,t),[de,K,t]),xe=c.useMemo(()=>Ki(s,A),[s,A]),Z=c.useCallback(async ae=>{oe&&await J.handleOpenRecent(oe.id,ae)},[J,oe]);return n.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&B?n.jsx(nM,{selectedConversation:B,isStandalone:i,selectedIdeEntry:H,actionLogs:r,userName:l,commands:ge,onBack:le.backFromConversation,onOpenNativeConversation:le.openNativeConversation,onOpenMachine:le.openConversationMachine,onOpenHistory:f,onOpenRemote:x,onOpenMeshGraph:N,onStopCli:g,cliViewMode:U,onSetCliViewMode:async ae=>{await Mg({conversation:B,mode:ae,ides:s,sendDaemonCommand:o,setCliViewModeOverrides:E})}}):M==="machine"&&oe?n.jsx(uM,{selectedMachineEntry:oe,selectedMachineConversations:pe,selectedMachineRecentLaunches:Re,cliProviders:we,selectedMachineNeedsUpgrade:Oe,appVersion:O,machineAction:J.machineAction,isStandalone:i,section:I,showBottomNav:q==="inbox",onBack:le.backFromMachine,onSectionChange:le.changeMachineSection,onOpenConversation:le.openConversation,onOpenRecent:Z,onOpenMachineDetails:()=>R(`/machines/${oe.id}`),onMachineUpgrade:()=>J.handleMachineUpgrade(oe.id),onBrowseDirectory:ae=>J.handleBrowseDirectory(oe.id,ae),onListSavedSessions:ae=>J.handleListSavedSessions(oe.id,ae)}):n.jsx(oM,{section:I,attentionItems:Ce,unreadItems:Q,workingItems:z,completedItems:X,hiddenConversations:t,machineCards:V,getAvatarText:NM,actionLogs:r,sendDaemonCommand:o,onOpenConversation:le.openConversation,onShowAllHidden:k,onHideConversation:w,onShowHiddenConversation:y,onOpenMeshGraph:N,onStopCli:g,onOpenNewSession:j,onOpenMachine:le.openMachine,onOpenSettings:()=>R("/settings"),onSectionChange:D,wsStatus:v,isConnected:S,initialDataLoaded:A,conversationsLoaded:xe,isStandalone:i,isConversationMuted:te,onToggleMuteConversation:ce})})}function Lc(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function _M({conversations:e,numGroups:t,onMoveTab:s,onReceiveTab:r,onOwnTabDrop:o,onClearPreviewOrder:a}){const i=c.useRef(0),[l,d]=c.useState(!1),[u,m]=c.useState(null),h=c.useCallback(()=>{i.current=0,d(!1),m(null)},[]);c.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const p=c.useCallback(g=>{g.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),b=c.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!Lc(t,s)){m("merge");return}const v=g.currentTarget.getBoundingClientRect(),S=g.clientX-v.left,A=v.width/3;S<A?m("split-left"):S>A*2?m("split-right"):m("merge")},[t,s]),f=c.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),m(null))},[]),x=c.useCallback(g=>{i.current=0,d(!1);const v=g.dataTransfer.getData("text/tab-key"),S=v?e.some(k=>k.tabKey===v):!1,A=u;if(m(null),a(),!!v){if(g.preventDefault(),A==="split-left"&&Lc(t,s)){s==null||s(v,"split-left");return}if(A==="split-right"&&Lc(t,s)){s==null||s(v,"split-right");return}if(S){o(v);return}r==null||r(v)}},[e,u,t,s,r,o,a]);return{dragOver:l,dropAction:u,resetDragState:h,handleDragEnter:p,handleDragOver:b,handleDragLeave:f,handleDrop:x}}function AM(e,t,s){const r=new Set(t.map(d=>d.tabKey)),o=e.filter(d=>r.has(d)),a=t.filter(d=>!e.includes(d.tabKey)).map(d=>d.tabKey);for(const d of a)s.fresh.add(d);const i=Vb(t,s);if(i.length===0)return[...o,...a];const l=new Set(i);return[...i,...[...o,...a].filter(d=>!l.has(d))]}function TM({conversations:e,initialActiveTabId:t,initialTabOrder:s,onActiveTabChange:r,onTabOrderChange:o}){const[a,i]=c.useState(t??null),[l,d]=c.useState(s??[]),u=c.useRef(l);u.current=l;const m=c.useRef(null);m.current||(m.current=zb());const[h,p]=c.useState(null),b=c.useRef(null),f=c.useRef(null),x=c.useRef(r),g=c.useRef(o);c.useEffect(()=>{x.current=r},[r]),c.useEffect(()=>{g.current=o},[o]),c.useEffect(()=>{t&&t!==a&&i(t)},[t,a]),c.useEffect(()=>{const C=u.current,E=AM(C,e,m.current);E.length===C.length&&E.every((P,T)=>P===C[T])||(u.current=E,d(E))},[e]);const v=c.useMemo(()=>{const C=h??l;if(C.length===0)return e;const E=new Map(C.map((P,T)=>[P,T]));return[...e].sort((P,T)=>{const M=E.get(P.tabKey)??999,_=E.get(T.tabKey)??999;return M-_})},[e,h,l]);c.useEffect(()=>{var E,P;if(v.length===0){a!==null&&(i(null),(E=x.current)==null||E.call(x,null));return}if(a&&v.some(T=>T.tabKey===a))return;const C=v[0].tabKey;C!==a&&(i(C),(P=x.current)==null||P.call(x,C))},[v,a]);const S=c.useMemo(()=>v.find(C=>C.tabKey===a),[v,a]),A=c.useCallback(C=>{var E;i(C),(E=x.current)==null||E.call(x,C)},[]),k=c.useCallback((C,E,P)=>{d(T=>{var D;const M=T.filter(L=>L!==C),_=M.indexOf(E);if(_<0)return T;const I=P==="left"?_:_+1;return M.splice(I,0,C),(D=g.current)==null||D.call(g,M),M}),p(null)},[]),w=c.useCallback((C,E,P)=>{const M=(l.length>0?l:e.map(D=>D.tabKey)).filter(D=>D!==C),_=M.indexOf(E);if(_<0)return;const I=P==="left"?_:_+1;M.splice(I,0,C),b.current=M,p(M)},[l,e]),y=c.useCallback(()=>{var E;const C=b.current;C&&(d(C),(E=g.current)==null||E.call(g,C))},[]),N=c.useCallback(()=>{b.current=null,p(null)},[]),j=c.useCallback(C=>{d(E=>{var T;const P=E.filter(M=>M!==C);return P.push(C),(T=g.current)==null||T.call(g,P),P})},[]);return{activeTabId:a,activeConv:S,sortedConversations:v,previewOrderRef:b,draggingTabRef:f,selectTab:A,handleTabReorder:k,updatePreviewOrder:w,commitPreviewOrder:y,clearPreviewOrder:N,moveTabToEnd:j,setDraggingTabKey:C=>{f.current=C}}}function IM({dropAction:e,canSplit:t}){const{t:s}=he("common");return n.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[n.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:n.jsx("div",{className:"px-3 py-1.5 rounded-full text-2xs font-semibold text-white bg-black/45 backdrop-blur-sm",children:s("paneGroup.dropSplitLeft")})}),n.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:n.jsx("div",{className:"px-3 py-1.5 rounded-full text-2xs font-semibold text-white bg-black/45 backdrop-blur-sm",children:s("paneGroup.dropMoveHere")})}),n.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:n.jsx("div",{className:"px-3 py-1.5 rounded-full text-2xs font-semibold text-white bg-black/45 backdrop-blur-sm",children:s("paneGroup.dropSplitRight")})})]})}function cu({conversationsCount:e,isSplitMode:t,isStandalone:s,hasRegisteredMachines:r=!1,suppressGuide:o=!1,onOpenNewSession:a,isLoading:i=!1}){const{t:l}=he("common");if(o)return n.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:l("paneGroup.noActiveAgent")});if(i)return n.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center gap-3 -mt-8 text-text-muted",children:[n.jsx(nn,{}),n.jsx("p",{className:"text-sm",children:l("paneGroup.loadingSessions")})]});const d=!s&&!r,u=r&&!!a,m=l(r?"paneGroup.noConversations":s?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),h=l(r?"paneGroup.newSessionDescription":s?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?n.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[n.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),n.jsxs("div",{className:"text-center max-w-lg",children:[n.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:m}),n.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:h}),u&&n.jsx("div",{className:"flex items-center justify-center mb-4",children:n.jsxs("button",{type:"button",onClick:a,className:"btn btn-primary btn-sm inline-flex items-center gap-2",title:l("paneGroup.newSession"),"aria-label":l("paneGroup.newSession"),children:[n.jsx(go,{size:14}),n.jsx("span",{children:l("paneGroup.newSession")})]})}),d&&n.jsx(Kg,{}),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 Jg="adhdev-tab-shortcuts";function Xg(){try{return JSON.parse(localStorage.getItem(Jg)||"{}")}catch{return{}}}function Zg({enabled:e=!0,sortedTabKeys:t,onFocus:s,onSelectTab:r}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[a,i]=c.useState(()=>Xg()),[l,d]=c.useState(null),u=c.useCallback(h=>{const p=[];return h.metaKey&&p.push(o?"⌘":"Meta"),h.ctrlKey&&p.push("Ctrl"),h.altKey&&p.push(o?"⌥":"Alt"),h.shiftKey&&p.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(p.push(h.key.length===1?h.key.toUpperCase():h.key),p.join("+"))},[o]),m=c.useCallback(h=>{i(h);try{localStorage.setItem(Jg,JSON.stringify(h))}catch{}},[]);return c.useEffect(()=>{if(!e||!l)return;const h=p=>{if(p.preventDefault(),p.stopPropagation(),p.key==="Escape"){d(null);return}const b=u(p);if(!b)return;const f={...a};for(const[x,g]of Object.entries(f))g===b&&delete f[x];f[l]=b,m(f),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,a,m,u]),c.useEffect(()=>{if(!e)return;const h=p=>{if(!(!p.ctrlKey&&!p.metaKey&&!p.altKey)){for(const[b,f]of Object.entries(a))if(t.includes(b)&&u(p)===f){p.preventDefault(),s(),r(b);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,a,t,s,r,u]),{isMac:o,tabShortcuts:a,shortcutListening:l,setShortcutListening:d,saveShortcuts:m}}const Dc=e=>{e.preventDefault()},MM=c.memo(function({conv:t,isActive:s,isDraggedTab:r,isTaskCompleteUnread:o,shortcut:a,conversationKeys:i,draggingTabRef:l,onFocus:d,onSelectTab:u,onConversationActivated:m,onPreviewReorder:h,onReorderTab:p,onCommitPreviewOrder:b,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:g,onReceiveTab:v,onOpenContextMenu:S,longPressTimer:A,isGroupActive:k}){const w=Ss(t),y=w.isGenerating?"agent-tab-generating":w.isWaiting?"agent-tab-waiting":"",N=w.isReconnecting,j=Kd(t),C=c.useCallback($=>{l.current=t.tabKey,g(t.tabKey),$.dataTransfer.setData("text/tab-key",t.tabKey),$.dataTransfer.effectAllowed="move"},[t.tabKey,l,g]),E=c.useCallback(()=>{l.current=null,g(null),b(),f(),x()},[l,g,b,f,x]),P=c.useCallback($=>{const q=l.current;if(!(!q||q===t.tabKey)&&$.dataTransfer.types.includes("text/tab-key")){$.preventDefault(),$.stopPropagation();const G=$.currentTarget.getBoundingClientRect(),W=$.clientX<G.left+G.width/2?"left":"right";h(q,t.tabKey,W)}},[t.tabKey,l,h]),T=c.useCallback($=>{$.preventDefault(),$.stopPropagation();const q=$.dataTransfer.getData("text/tab-key");if(q&&q!==t.tabKey){const G=$.currentTarget.getBoundingClientRect(),W=$.clientX<G.left+G.width/2?"left":"right";i.includes(q)?p(q,t.tabKey,W):v&&v(q)}f()},[t.tabKey,i,p,v,f]),M=c.useCallback($=>{$.stopPropagation(),d(),u(t.tabKey),m(t)},[t,m,d,u]),_=c.useCallback($=>{$.preventDefault(),S($.clientX,$.clientY,t.tabKey)},[t.tabKey,S]),I=c.useCallback($=>{const q=$.touches[0];A.current=setTimeout(()=>{S(q.clientX,q.clientY,t.tabKey)},600)},[t.tabKey,A,S]),D=c.useCallback(()=>{A.current&&clearTimeout(A.current)},[A]),L=["adhdev-dockview-tab",y,s&&"is-active",k&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return n.jsxs("div",{"data-tabkey":t.tabKey,className:L,draggable:!0,onDragStart:C,onDragEnd:E,onDragOver:P,onDrop:T,onClick:M,onContextMenu:_,onTouchStart:I,onTouchEnd:D,onTouchMove:D,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[o&&n.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),n.jsx("div",{className:"adhdev-dockview-tab-status",children:w.isGenerating?n.jsx(nn,{size:12,thickness:2,color:"success"}):w.isWaiting?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):w.isConnecting?n.jsx(nn,{size:12,thickness:2}):t.connectionState==="connected"?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):n.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),n.jsx(ws,{conversation:t,size:12}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("span",{className:"adhdev-dockview-tab-primary",title:j?`${kt(t)} · ${j}`:kt(t),children:kt(t)}),n.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Os(t)}):w.isConnecting?n.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Os(t),n.jsx("span",{className:"connecting-dots"})]}):n.jsx("span",{className:"truncate",children:Os(t)}),n.jsx(Od,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),a&&n.jsx("span",{className:"text-4xs opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:a,children:a})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function RM({conversations:e,activeTabId:t,groupIndex:s,unreadTabKeys:r,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:l,onPreviewReorder:d,onReorderTab:u,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:b,onReceiveTab:f,onHideTab:x,isGroupActive:g,allowTabShortcuts:v=!0}){const{t:S}=he("common"),[A,k]=c.useState(null),w=c.useRef(null),y=c.useRef(null),N=c.useMemo(()=>e.map(_=>_.tabKey),[e]);Io("PaneGroupTabBar",{groupIndex:s,activeTabId:t,tabCount:e.length,ctxMenuTab:(A==null?void 0:A.tabKey)||null});const{isMac:j,tabShortcuts:C,shortcutListening:E,setShortcutListening:P,saveShortcuts:T}=Zg({enabled:v,sortedTabKeys:e.map(_=>_.tabKey),onFocus:a,onSelectTab:i});c.useEffect(()=>{if(!A)return;const _=I=>{const D=document.querySelector("[data-pane-context-menu]");D&&D.contains(I.target)||k(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[A]),c.useEffect(()=>{const _=y.current;if(!_)return;const I=D=>{Math.abs(D.deltaY)<=Math.abs(D.deltaX)||(D.preventDefault(),_.scrollLeft+=D.deltaY)};return _.addEventListener("wheel",I,{passive:!1}),()=>_.removeEventListener("wheel",I)},[]);const M=c.useCallback((_,I,D)=>{k({x:_,y:I,tabKey:D})},[]);return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:n.jsxs("div",{ref:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(_=>n.jsx(MM,{conv:_,isActive:t===_.tabKey,isDraggedTab:o.current===_.tabKey,isTaskCompleteUnread:r.has(_.tabKey),shortcut:v?C[_.tabKey]:void 0,conversationKeys:N,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:l,onPreviewReorder:d,onReorderTab:u,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:b,onReceiveTab:f,onOpenContextMenu:M,longPressTimer:w,isGroupActive:g},_.tabKey)),e.length===0&&n.jsx("div",{className:"p-2 text-xs opacity-40",children:S("paneGroup.noTabsInGroup")})]})}),A&&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:A.x,top:A.y},children:[v&&n.jsxs(n.Fragment,{children:[n.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Dc,onClick:_=>{_.stopPropagation(),P(A.tabKey),k(null)},children:["⌨ ",C[A.tabKey]?S("paneGroup.changeShortcut",{shortcut:C[A.tabKey]}):S("paneGroup.shortcutSetTitle")]}),C[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:Dc,onClick:()=>{const _={...C};delete _[A.tabKey],T(_),k(null)},children:["✕ ",S("paneGroup.removeShortcut")]})]}),x&&n.jsxs(n.Fragment,{children:[v&&n.jsx("div",{className:"border-t border-border-subtle my-1"}),n.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Dc,onClick:()=>{x(A.tabKey),k(null)},children:n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(xi,{size:12}),S("paneGroup.hideFromDashboard")]})})]})]}),v&&E&&n.jsx(Un,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>P(null),children:n.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:_=>_.stopPropagation(),children:[n.jsxs("div",{className:"text-sm font-bold text-text-primary mb-2",children:["⌨ ",S("paneGroup.shortcutSetTitle")]}),n.jsx("div",{className:"text-xs text-text-secondary mb-4",children:S("paneGroup.shortcutPressCombo",{example1:j?"⌘+1":"Ctrl+1",example2:j?"⌥+A":"Alt+A"})}),n.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:S("paneGroup.shortcutListening")}),n.jsx("div",{className:"text-3xs text-text-muted mt-3",children:S("paneGroup.pressEscToCancel")})]})})})]})}function PM({conversations:e,ides:t,clearedTabs:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:l,initialDataLoaded:d=!0,userName:u,groupIndex:m,onFocus:h,isSplitMode:p,numGroups:b,onMoveTab:f,onReceiveTab:x,style:g,onActiveTabChange:v,initialActiveTabId:S,initialTabOrder:A,onTabOrderChange:k,onHideTab:w,isFocused:y,allowTabShortcuts:N=!0,onOpenNewSession:j,liveSessionInboxState:C}){const{sendCommand:E}=wt(),P=c.useRef(null),{activeTabId:T,activeConv:M,sortedConversations:_,draggingTabRef:I,selectTab:D,handleTabReorder:L,updatePreviewOrder:$,commitPreviewOrder:q,clearPreviewOrder:G,moveTabToEnd:W,setDraggingTabKey:R}=TM({conversations:e,initialActiveTabId:S,initialTabOrder:A,onActiveTabChange:v,onTabOrderChange:k}),O=Ei({sendDaemonCommand:o,activeConv:M,setActionLogs:a,isStandalone:i}),{dragOver:B,dropAction:H,resetDragState:U,handleDragEnter:K,handleDragOver:oe,handleDragLeave:ge,handleDrop:J}=_M({conversations:e,numGroups:b,onMoveTab:f,onReceiveTab:x,onOwnTabDrop:W,onClearPreviewOrder:G}),ke=M&&Mr(M)==="terminal",de=c.useMemo(()=>M?t.find(ce=>ce.id===M.routeId):void 0,[t,M]),ne=c.useMemo(()=>M?r.filter(ce=>ce.routeId===M.tabKey):[],[r,M]),le=c.useMemo(()=>new Set(_.filter(ce=>Bk(ce,C,{isOpenConversation:ce.tabKey===T})).map(ce=>ce.tabKey)),[T,C,_]);Io("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:T,dragOver:B});const te=c.useCallback(ce=>{ce.streamSource==="agent-stream"&&ce.agentType&&E(ce.routeId,cb(),{agentType:ce.agentType,...ce.sessionId&&{targetSessionId:ce.sessionId}}).catch(()=>{})},[E]);return n.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...g,outline:B?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[n.jsx(RM,{conversations:_,activeTabId:T,groupIndex:m,numGroups:b,unreadTabKeys:le,draggingTabRef:I,onFocus:h,onSelectTab:D,onConversationActivated:te,onPreviewReorder:$,onReorderTab:L,onCommitPreviewOrder:q,onClearPreviewOrder:G,onDragStateReset:U,onDragTabKeyChange:R,onMoveTab:f,onReceiveTab:x,onHideTab:w,isGroupActive:y??!1,allowTabShortcuts:N}),n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:K,onDragOver:oe,onDragLeave:ge,onDrop:J,children:[B&&n.jsx(IM,{dropAction:H,canSplit:!!(b<4&&f)}),M?n.jsx(au,{activeConv:M,clearToken:s[M.tabKey]||0,isCliTerminal:!!ke,ideEntry:de,terminalRef:P,commands:O,actionLogs:ne,userName:u,isInputActive:!p||!!y}):n.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:n.jsx(cu,{conversationsCount:e.length,isSplitMode:p,isStandalone:i,hasRegisteredMachines:l,onOpenNewSession:j,isLoading:!Ki(t,d)})})]})]})}function EM({containerRef:e,isSplitMode:t,numGroups:s,groupSizes:r,groupedConvs:o,clearedTabs:a,ides:i,actionLogs:l,sendDaemonCommand:d,setActionLogs:u,isStandalone:m,hasRegisteredMachines:h,initialDataLoaded:p,userName:b,focusedGroup:f,focusGroup:x,moveTabToGroup:g,splitTabRelative:v,closeGroup:S,handleResizeStart:A,groupActiveTabIds:k,setGroupActiveTab:w,groupTabOrders:y,setGroupTabOrder:N,toggleHiddenTab:j,onOpenNewSession:C,allowTabShortcuts:E=!0,liveSessionInboxState:P}){const{t:T}=he("common");return n.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:o.map((M,_)=>{const I=t&&r.length===s?`${r[_]}%`:void 0;return n.jsxs(yt.Fragment,{children:[t&&_>0&&n.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:D=>A(_-1,D),onDoubleClick:()=>S(_),title:T("paneGroup.resizeHandleHint"),children:n.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),n.jsx(PM,{style:t?{flexBasis:I??`${100/s}%`,flexGrow:I?0:1,flexShrink:I?0:1}:void 0,conversations:M,clearedTabs:a,ides:i,actionLogs:l,sendDaemonCommand:d,setActionLogs:u,isStandalone:m,hasRegisteredMachines:h,initialDataLoaded:p,userName:b,groupIndex:_,isFocused:t&&f===_,onFocus:()=>x(_),isSplitMode:t,numGroups:s,onMoveTab:(D,L)=>{L==="left"&&_>0?g(D,_-1):L==="right"&&_<s-1?g(D,_+1):L==="split-left"&&s<4?v(D,_,"left"):L==="split-right"&&s<4&&v(D,_,"right")},onReceiveTab:D=>g(D,_),onActiveTabChange:D=>w(_,D),initialActiveTabId:k[_],initialTabOrder:y[_],onTabOrderChange:D=>N(_,D),onHideTab:j,onOpenNewSession:C,allowTabShortcuts:E,liveSessionInboxState:P})]},_)})})}const ex="adhdev-dashboard-action-shortcuts",LM=1200,DM=[["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 OM(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function pt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function tx(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:pt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:pt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:pt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:pt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:pt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:pt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:pt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:pt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:pt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:pt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:pt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:pt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:pt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:pt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:pt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:pt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:pt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:pt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:pt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:pt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:pt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:pt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:pt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:pt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:pt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:pt("toggleCliView",e)}]}function lu(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function ai(e){const t=Object.fromEntries(tx(e).map(s=>[s.id,s.defaultShortcut]));try{const s=JSON.parse(localStorage.getItem(ex)||"{}"),r={...t,...s};for(const[o,a]of DM)r[o]===a&&(r[o]=t[o]);return r}catch{return t}}function nx(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function $M({enabled:e=!0,onTrigger:t}){const s=OM(),[r,o]=c.useState(()=>ai(s)),[a,i]=c.useState(null),[l,d]=c.useState([]),u=c.useRef({parts:[],timer:null}),m=c.useCallback(x=>{const g=[];return x.metaKey&&g.push(s?"⌘":"Meta"),x.ctrlKey&&g.push("Ctrl"),x.altKey&&g.push(s?"⌥":"Alt"),x.shiftKey&&x.key.length!==1&&g.push(s?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(g.push(nx(x.key)),g.join("+"))},[s]),h=c.useCallback(x=>{o(x);try{localStorage.setItem(ex,JSON.stringify(x))}catch{}},[]);c.useEffect(()=>{const x=ai(s),g=Object.entries(r),v=Object.entries(x);g.length===v.length&&g.every(([S,A])=>x[S]===A)||h(x)},[r,s,h]);const p=c.useCallback(()=>{typeof window<"u"&&u.current.timer!=null&&window.clearTimeout(u.current.timer),u.current={parts:[],timer:null}},[]),b=c.useCallback(()=>{typeof window>"u"||(u.current.timer!=null&&window.clearTimeout(u.current.timer),u.current.timer=window.setTimeout(()=>{u.current={parts:[],timer:null}},LM))},[]);c.useEffect(()=>{if(!a)return;const x=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){i(null),d([]);return}const v=m(g);if(!v)return;const A=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(v);if(l.length===0&&A){d([v]);return}const w=[...l,v].slice(0,2).join(" "),y={...r};for(const[N,j]of Object.entries(y))j===w&&delete y[N];y[a]=w,h(y),i(null),d([])};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[r,m,h,a,l]),c.useEffect(()=>{if(!e||a)return;const x=g=>{if(g.defaultPrevented)return;const v=m(g);if(!v)return;const S=g.metaKey||g.ctrlKey||g.altKey;if(lu(g.target))return;const A=u.current.parts,k=S?[v]:[...A.slice(-1),v].slice(-2),w=k.join(" "),y=k[k.length-1],N=Object.entries(r).filter(([,T])=>!!T),j=N.find(([,T])=>T===w);if(j){g.preventDefault(),p(),t(j[0]);return}if(N.some(([,T])=>T.startsWith(`${w} `))){g.preventDefault(),u.current.parts=k,b();return}const E=N.find(([,T])=>T===y);if(E){g.preventDefault(),p(),t(E[0]);return}if(N.some(([,T])=>T.startsWith(`${y} `))){g.preventDefault(),u.current.parts=[y],b();return}p()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[r,b,e,m,t,p,a]),c.useEffect(()=>()=>p(),[p]);const f=c.useMemo(()=>tx(s),[s]);return{isMac:s,actionDefinitions:f,actionShortcuts:r,shortcutListening:a,shortcutListeningDraft:l,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:h}}function FM({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 sx(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function wh({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:s,ides:r}){return!e||s>0?!1:t?!sx(r):!0}function HM({previousVisibleConversationCount:e,visibleConversationCount:t,ides:s}){return t>0||e<=0?!1:sx(s)}const rx=2e4;function BM(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+rx}:null}function WM(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 ox=1e3,UM=4;function Sh(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function kh(e,t,s){return Math.abs(t.clientX-e.clientX)>s||Math.abs(t.clientY-e.clientY)>s}function KM({detachDelayMs:e=ox,stillnessThresholdPx:t=UM,onDetach:s,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:o=globalThis.clearTimeout.bind(globalThis)}){let a=null,i=null,l=null,d=null,u=null,m=!1;const h=()=>{u!=null&&(o(u),u=null)},p=()=>{h(),l=null},b=()=>{h(),a=null,i=null,l=null,d=null,m=!1},f=()=>{!a||!l||!d||m||u!=null||(u=r(()=>{u=null,!(!a||!l||!d||m)&&Sh(d,i)&&(kh(l,d,t)||(m=!0,s({panelId:a,clientX:d.clientX,clientY:d.clientY})))},e))},x=v=>{if(!(!a||m)){if(!Sh(v,i)){d={clientX:v.clientX,clientY:v.clientY},p();return}(!l||kh(l,v,t))&&(h(),l={clientX:v.clientX,clientY:v.clientY}),d={clientX:v.clientX,clientY:v.clientY},f()}},g=v=>{!a||m||(v&&(d={clientX:v.clientX,clientY:v.clientY}),p())};return{startDrag:v=>{h(),a=v.panelId,i=v.selfPanelBounds??null,l=null,d={clientX:v.clientX,clientY:v.clientY},m=!1},markSelfPanel:x,markNonSelfPanel:g,markNoDropTarget:g,markDockTarget:g,endDrag:b,isDragging:()=>a!=null,hasDetached:()=>m,dispose:b}}function qM(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function zM(e,t,s){const r=m=>({clientX:m.clientX,clientY:m.clientY}),o=m=>{const h=m==null?void 0:m.getBoundingClientRect();return h?{left:h.left,right:h.right,top:h.top,bottom:h.bottom}:null},a=m=>{var p;const h=(p=t())==null?void 0:p.getBoundingClientRect();return h?m.clientX<h.left||m.clientX>h.right||m.clientY<h.top||m.clientY>h.bottom:!1},i=KM({detachDelayMs:ox,onDetach:({panelId:m,clientX:h,clientY:p})=>{var S,A;const b=e.getPanel(m);if(!b)return;try{if(b.group.model.location.type!=="grid")return}catch{return}const f=(S=t())==null?void 0:S.getBoundingClientRect(),x=(A=b.group.element)==null?void 0:A.getBoundingClientRect(),g=Math.round(Math.min(Math.max((x==null?void 0:x.width)??600,360),720)),v=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:v}),b.api.setActive(),s()}}),l=[e.onWillDragPanel(m=>{if(!(m.nativeEvent.defaultPrevented||m.nativeEvent.shiftKey)){try{if(m.panel.group.model.location.type!=="grid")return}catch{return}i.startDrag({panelId:m.panel.id,selfPanelBounds:o(m.panel.group.element),...r(m.nativeEvent)})}}),e.onWillShowOverlay(m=>{if(i.hasDetached()){m.preventDefault();return}i.markDockTarget(r(m.nativeEvent))}),e.onWillDrop(m=>{if(i.hasDetached()){m.preventDefault(),i.endDrag();return}i.markDockTarget(r(m.nativeEvent))}),e.onDidDrop(()=>i.endDrag()),e.onUnhandledDragOverEvent(m=>{i.isDragging()&&i.markSelfPanel(r(m.nativeEvent))})],d=m=>{if(!i.isDragging())return;const h=r(m);a(h)&&i.markNonSelfPanel(h)},u=()=>i.endDrag();return window.addEventListener("dragover",d,!0),window.addEventListener("drop",u,!0),window.addEventListener("dragend",u,!0),()=>{i.dispose();for(const m of l)m.dispose();window.removeEventListener("dragover",d,!0),window.removeEventListener("drop",u,!0),window.removeEventListener("dragend",u,!0)}}function Ra(e){return kt(e)||e.tabKey}function VM(e){return`remote:${e}`}function gn(e){return e.startsWith("remote:")}function jh(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Oc(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const s=o=>{if(o)try{o.focus({preventScroll:!0})}catch{try{o.focus()}catch{}}};try{t.focus(),s(e==null?void 0:e.body),s(e==null?void 0:e.documentElement),(r=t.requestAnimationFrame)==null||r.call(t,()=>{try{t.focus(),s(e==null?void 0:e.body)}catch{}})}catch{}}function du(e,t){e.classList.remove(ol.className,al.className),e.classList.add(t==="light"?ol.className:al.className)}function Nh(e){return e?Array.from(new Set(e.groups.map(t=>{var s,r;return(r=(s=t.element)==null?void 0:s.ownerDocument)==null?void 0:r.defaultView}).filter(t=>!!t&&t!==window))):[]}function GM(e,t){var p;const s=e.activeGroup||((p=e.activePanel)==null?void 0:p.group);if(!s)return;const r=e.groups||[],o=r.find(b=>b.id===s.id);if(!o)return;const a=o.element.getBoundingClientRect(),i=a.left+a.width/2,l=a.top+a.height/2,d=(b,f,x,g)=>Math.max(0,Math.min(f,g)-Math.max(b,x)),u=b=>{const f=b.element.getBoundingClientRect(),x=f.left+f.width/2,g=f.top+f.height/2;let v=0,S=0,A=0,k=!1;if(t==="left"?(k=x<i,v=Math.max(0,a.left-f.right),S=Math.abs(g-l),A=d(a.top,a.bottom,f.top,f.bottom)):t==="right"?(k=x>i,v=Math.max(0,f.left-a.right),S=Math.abs(g-l),A=d(a.top,a.bottom,f.top,f.bottom)):t==="above"?(k=g<l,v=Math.max(0,a.top-f.bottom),S=Math.abs(x-i),A=d(a.left,a.right,f.left,f.right)):(k=g>l,v=Math.max(0,f.top-a.bottom),S=Math.abs(x-i),A=d(a.left,a.right,f.left,f.right)),!k)return Number.POSITIVE_INFINITY;const w=A>0?0:120;return v*3+S+w};let m=null,h=Number.POSITIVE_INFINITY;for(const b of r){if(b.id===o.id)continue;const f=u(b);Number.isFinite(f)&&(f>=h||(h=f,m=b))}return m||void 0}function ax(e,t,s){var r;if(s)for(const o of Vb(t,s)){const a=e.getPanel(o);if(!a||a.group.panels.indexOf(a)<=0)continue;const i=((r=a.group.activePanel)==null?void 0:r.id)===a.id;a.api.moveTo({group:a.group,position:"center",index:0,skipSetActive:!0}),i&&a.api.setActive()}}function YM(e,t,s,r){var l;const o=[t];let a;for(const d of o){let u;for(const m of d){const h=e.addPanel({id:m.tabKey,component:"conversation",title:Ra(m),params:{kind:"conversation",tabKey:m.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=h.id),r==null||r.fresh.add(h.id)}a=u??a}return ax(e,t,r),s??((l=t[0])==null?void 0:l.tabKey)??null}function $c(e,t,s,r){const o=new Set(t.map(i=>i.tabKey)),a=new Map;for(const i of t)a.set(i.tabKey,(a.get(i.tabKey)||0)+1);for(const i of[...e.panels])gn(i.id)||!o.has(i.id)&&!(s!=null&&s.has(i.id))&&e.removePanel(i);for(const i of t){const l=e.getPanel(i.tabKey);if(l){(a.get(i.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:i.tabKey,daemonId:i.daemonId,sessionId:i.sessionId,providerSessionId:i.providerSessionId,panelId:l.id}),l.update({params:{tabKey:i.tabKey}}),l.title!==Ra(i)&&l.api.setTitle(Ra(i));continue}e.addPanel({id:i.tabKey,component:"conversation",title:Ra(i),params:{kind:"conversation",tabKey:i.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}:{}}),r==null||r.fresh.add(i.tabKey)}ax(e,t,r)}function Ch(e,t,s){var d,u;const r=s?VM(s):null;for(const m of[...e.panels])gn(m.id)&&(!r||m.id!==r)&&e.removePanel(m);if(!s||!r)return;const o=_n(t,s);if(!o&&e.totalPanels===0)return;const a=e.getPanel(r),i=Ob(o);if(a){a.title!==i&&a.api.setTitle(i);return}const l=(o==null?void 0:o.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((u=e.panels.find(m=>!gn(m.id)))==null?void 0:u.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:s},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function QM(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 ix({doId:e,targetSessionId:t,connState:s,viewMode:r}){var u;const[o,a]=c.useState(null),{ides:i}=Mi(),l=((u=i.find(m=>m.id===e&&m.type==="adhdev-daemon"))==null?void 0:u.screenshotUsage)??null;c.useEffect(()=>e?Ot.onScreenshot("ide-page",(h,p)=>{if(h!==e)return;const b=new FileReader;b.onload=()=>a(b.result),b.readAsDataURL(p)}):void 0,[e]),c.useEffect(()=>{s!=="connected"&&a(null)},[s]),c.useEffect(()=>{a(null)},[e,t]),c.useEffect(()=>{const m=e?Ot.get(e):null;if(!(!m||s!=="connected"))return r!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[r,s,t,e]);const d=c.useCallback(async(m,h)=>{const p=e?Ot.get(e):null;return!p||s!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):p.sendInput(m,h,t)},[e,s,t]);return{connScreenshot:o,screenshotUsage:l,handleRemoteAction:d}}const cx=c.createContext(null);function qi(){const e=c.useContext(cx);if(!e)throw new Error("DashboardDockviewContext missing");return e}function JM(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 XM({params:e}){var u;const t=qi(),{t:s}=he("common"),r=c.useMemo(()=>_n([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),o=c.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:l,handleRemoteAction:d}=ix({doId:a,targetSessionId:r?ob(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(gf,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:l,transportType:r.transport,onAction:d})}):n.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:s("dashboard.remoteDialog.remoteUnavailable")})}function ZM(){const e=qi();return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:n.jsx(cu,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!Ki(e.ides,e.initialDataLoaded)})})}function eR(e){var k,w;JM(e);const t=qi(),{t:s}=he("common"),r=c.useCallback(y=>{"button"in y&&y.button!==0||e.api.setActive()},[e.api]),o=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=o==null?void 0:o.sessionId,i=c.useCallback(y=>K_(y),[]),l=c.useCallback(()=>U_(a),[a]),d=c.useSyncExternalStore(i,l,l),u=Kd(o);if(e.params.kind==="remote"){const y=_n([...t.conversationsByTabKey.values()],e.params.routeId),N=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,j=e.api.isGroupActive;return n.jsxs("div",{className:`adhdev-dockview-tab${N?" is-active":""}${j?" is-group-active":""}`,title:e.api.title||s("dashboard.remoteDialog.remoteFallback"),"data-tab-key":(y==null?void 0:y.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[n.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:n.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||s("dashboard.remoteDialog.remoteFallback")}),n.jsx("div",{className:"adhdev-dockview-tab-meta",children:y!=null&&y.machineName?n.jsxs(n.Fragment,{children:[n.jsx("span",{children:s("dashboard.remoteDialog.liveRemoteView")}),n.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),n.jsx("span",{className:"adhdev-dockview-tab-machine",children:y.machineName})]}):n.jsx("span",{children:s("dashboard.remoteDialog.liveRemoteView")})})]})]})}const m=t.conversationsByTabKey.get(e.params.tabKey);if(!m)return n.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:n.jsx("div",{className:"adhdev-dockview-tab-copy",children:n.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const h=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,p=e.api.isGroupActive,b=Ni(m,t.liveSessionInboxState,{isOpenConversation:h}),f=b.isReconnecting,x=b.isConnecting,g=b.isGenerating||d,v=b.isWaiting,S=b.unread,A=t.tabShortcuts[m.tabKey];return n.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${p?" is-group-active":""}${f?" is-reconnecting":""}`,title:u?`${kt(m)} · ${u}`:kt(m),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:y=>{var N;y.preventDefault(),r(y),t.openTabContextMenu({x:y.clientX,y:y.clientY,tabKey:m.tabKey,sourceDocument:((N=y.target)==null?void 0:N.ownerDocument)??document})},children:[S&&n.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),n.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:g?n.jsx(nn,{size:12,thickness:2,color:"success"}):v?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(nn,{size:12,thickness:2}):m.connectionState==="connected"?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):n.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),n.jsx(ws,{conversation:m,size:12}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("div",{className:"adhdev-dockview-tab-primary",children:kt(m)}),n.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Os(m)}):x?n.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Os(m)}):n.jsx("span",{children:Os(m)})})]}),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})]})}function tR(e,t){const{encodeShortcut:s,isMac:r,isShortcutListening:o,isVisibleTab:a,selectTabByShortcut:i,triggerAction:l}=t;let d=[],u=null;const m=()=>{u!=null&&e.clearTimeout(u),u=null,d=[]},h=()=>{u!=null&&e.clearTimeout(u),u=e.setTimeout(()=>{u=null,d=[]},1200)},p=f=>{if(!f.ctrlKey&&!f.metaKey&&!f.altKey)return;const x=s(f);if(!x)return;const g=Xg();for(const[v,S]of Object.entries(g))if(a(v)&&S===x){f.preventDefault(),i(v);return}},b=f=>{if(f.defaultPrevented||o())return;const x=s(f);if(!x)return;const g=f.metaKey||f.ctrlKey||f.altKey;if(lu(f.target))return;const v=ai(r),S=Object.entries(v).filter(([E,P])=>!!P&&(E==="splitActiveTabRight"||E==="splitActiveTabDown"||E==="floatActiveTab"||E==="popoutActiveTab"||E==="dockActiveTab"||E==="focusLeftPane"||E==="focusRightPane"||E==="focusUpPane"||E==="focusDownPane"||E==="moveActiveTabToLeftPane"||E==="moveActiveTabToRightPane"||E==="moveActiveTabToUpPane"||E==="moveActiveTabToDownPane"||E==="selectPreviousGroupTab"||E==="selectNextGroupTab"||E==="setActiveTabShortcut"||E==="hideCurrentTab")),A=g?[x]:[...d.slice(-1),x].slice(-2),k=A.join(" "),w=A[A.length-1],y=S.find(([,E])=>E===k);if(y){f.preventDefault(),m(),l(y[0]);return}if(S.some(([,E])=>E.startsWith(`${k} `))){f.preventDefault(),d=A,h();return}const j=S.find(([,E])=>E===w);if(j){f.preventDefault(),m(),l(j[0]);return}if(S.some(([,E])=>E.startsWith(`${w} `))){f.preventDefault(),d=[w],h();return}m()};return e.addEventListener("keydown",p),e.addEventListener("keydown",b),()=>{m(),e.removeEventListener("keydown",p),e.removeEventListener("keydown",b)}}function nR(e){e.preventDefault()}function sR(e){switch(e){case"dockInWindow":case"dockBackToGrid":return n.jsx(Bw,{size:13,className:"shrink-0 opacity-70"});case"moveBackToMain":return n.jsx(Fw,{size:13,className:"shrink-0 opacity-70"});case"floatAsPanel":return n.jsx(Hw,{size:13,className:"shrink-0 opacity-70"});case"openInNewWindow":return n.jsx($w,{size:13,className:"shrink-0 opacity-70"});case"removeShortcut":return n.jsx(Lt,{size:13,className:"shrink-0 opacity-70"});case"hideTab":return n.jsx(xi,{size:13,className:"shrink-0 opacity-70"});default:return n.jsx(Yp,{size:13,className:"shrink-0 opacity-70"})}}function rR({x:e,y:t,sourceDocument:s,items:r,onSelect:o}){return An.createPortal(n.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[var(--z-popover)] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:e,top:t},children:r.map(a=>a.type==="separator"?n.jsx("div",{className:"border-t border-border-subtle my-1"},a.id):n.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${a.tone==="muted"?"text-text-muted":""}`,onMouseDown:nR,onClick:i=>o(a.id,i),children:[sR(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 oR(e,t){const s=document,r=e.document;for(const d of s.querySelectorAll('link[rel="stylesheet"]')){const u=r.createElement("link");u.rel="stylesheet",u.href=d.href,d.crossOrigin&&(u.crossOrigin=d.crossOrigin),r.head.appendChild(u)}for(const d of s.querySelectorAll("style")){const u=r.createElement("style");u.textContent=d.textContent,r.head.appendChild(u)}const o=[];for(const d of s.styleSheets)try{for(const u of d.cssRules)u instanceof CSSStyleRule&&(u.selectorText===":root"||u.selectorText==="html")&&o.push(u.cssText)}catch{}if(o.length>0){const d=r.createElement("style");d.textContent=o.join(`
|
|
69
|
+
`),r.head.appendChild(d)}const a=s.documentElement.getAttribute("data-theme");a&&r.documentElement.setAttribute("data-theme",a),r.documentElement.style.colorScheme=a==="light"?"light":"dark",r.body.className=s.body.className;const i=s.documentElement.getAttribute("style");i&&r.documentElement.setAttribute("style",i);const l=r.getElementById("dv-popout-window");l instanceof HTMLElement&&(l.classList.add("adhdev-dockview"),du(l,t))}function aR(e,t){var s;for(const r of e.groups)try{const o=(s=r.element)==null?void 0:s.ownerDocument;if(!o||o===document)continue;const a=o.getElementById("dv-popout-window");a instanceof HTMLElement&&(a.classList.add("adhdev-dockview"),du(a,t));const i=document.documentElement.getAttribute("data-theme");i&&o.documentElement.setAttribute("data-theme",i),o.documentElement.style.colorScheme=i==="light"?"light":"dark",o.body.className=document.body.className;const l=document.documentElement.getAttribute("style");l?o.documentElement.setAttribute("style",l):o.documentElement.removeAttribute("style")}catch{}}function iR(e,t,s){var r,o;for(const a of e.groups){const i=(r=a.element)==null?void 0:r.ownerDocument;if(!i||i===document)continue;const l=i.getElementById("dv-popout-window");if(!(l instanceof HTMLElement))continue;let d=null,u=i.title||"ADHDev",m="Popout workspace";const h=a.activePanel;if(h)if(d=h.id,gn(h.id)){const g=((o=h.params)==null?void 0:o.routeId)||h.id.slice(7),v=_n([...t.values()],g);u=Ob(v),m=v!=null&&v.machineName?`Remote view · ${v.machineName}`:"Remote view"}else{const g=t.get(h.id);u=g?kt(g):h.title||h.id,m=g?Os(g):"Dockview panel"}i.title=`${u} — ADHDev`;const p=Array.from(i.querySelectorAll("#adhdev-popout-header"));for(const g of p)g.remove();const b=i.createElement("div");b.id="adhdev-popout-header",i.body.appendChild(b),b.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),b.innerHTML=`
|
|
70
|
+
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
71
|
+
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
72
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${jh(u)}</div>
|
|
73
|
+
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${jh(m)}</div>
|
|
74
|
+
</div>
|
|
75
|
+
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
76
|
+
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
77
|
+
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
78
|
+
</div>
|
|
79
|
+
`,l.style.top="52px",l.style.height="calc(100% - 52px)";const f=b.querySelector("[data-adhdev-popout-focus]");f&&(f.onclick=()=>{window.focus()});const x=b.querySelector("[data-adhdev-popout-dock]");x&&(x.disabled=!d,x.style.opacity=d?"1":"0.5",x.style.cursor=d?"pointer":"default",x.onclick=()=>{var g;d&&s(d),(g=i.defaultView)==null||g.focus()})}}const cR=[];function ca(e){return e.isActive}function _h(e){return e.isVisible}function lR({params:e,api:t}){var f;const s=qi(),r=c.useRef(null),[o,a]=c.useState(()=>ca(t)),[i,l]=c.useState(()=>_h(t)),d=s.conversationsByTabKey.get(e.tabKey),u=Ei({sendDaemonCommand:s.sendDaemonCommand,activeConv:d,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone});c.useEffect(()=>{a(ca(t)),l(_h(t));const x=[t.onDidActiveChange(g=>a(g.isActive)),t.onDidActiveGroupChange(g=>{if(!ca(t)&&!g.isActive){a(!1);return}a(ca(t))}),t.onDidVisibilityChange(g=>l(g.isVisible))];return()=>{for(const g of x)g.dispose()}},[t]);const m=c.useMemo(()=>d?s.ides.find(x=>x.id===d.routeId):void 0,[s.ides,d]),h=d==null?void 0:d.tabKey,p=c.useMemo(()=>h?s.actionLogs.filter(x=>x.routeId===h):cR,[s.actionLogs,h]);if(!d)return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:n.jsx(cu,{conversationsCount:0,isSplitMode:!1,isStandalone:s.isStandalone,hasRegisteredMachines:s.hasRegisteredMachines,onOpenNewSession:s.onOpenNewSession,suppressGuide:s.hasDetachedConversationPanels,isLoading:!Ki(s.ides,s.initialDataLoaded)})});const b=Mr(d)==="terminal";return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:n.jsx(au,{activeConv:d,clearToken:s.clearedTabs[d.tabKey]||0,isCliTerminal:b,ideEntry:m,terminalRef:r,commands:u,actionLogs:p,userName:s.userName,scrollToBottomRequestNonce:((f=s.scrollToBottomRequest)==null?void 0:f.tabKey)===d.tabKey?s.scrollToBottomRequest.nonce:void 0,isInputActive:o,isVisible:i})})}function dR({visibleConversations:e,clearedTabs:t,ides:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:l,initialDataLoaded:d,userName:u,toggleHiddenTab:m,actionShortcuts:h,registerActionHandlers:p,onActiveTabChange:b,onOpenNewSession:f,onRequestScrollToBottom:x,requestedActiveTabKey:g,requestedRemoteIdeId:v,onRequestedActiveTabConsumed:S,scrollToBottomRequest:A,liveSessionInboxState:k,layoutProfile:w}){var It,bt,jt;const{t:y}=he("common"),{theme:N}=Hi(),{sendCommand:j}=wt(),C=c.useRef(null),E=c.useRef(null),P=c.useRef(null),T=c.useRef(!1),M=c.useRef(!1),_=c.useRef(!1),I=c.useRef(null),D=c.useRef([]),L=c.useRef(null),$=c.useRef(zb()),q=c.useRef(e);q.current=e;const[G,W]=c.useState(null),[R,O]=c.useState(0),B=c.useRef(typeof window>"u"?{}:uI(w)),H=c.useMemo(()=>new Map(e.map(ee=>[ee.tabKey,ee])),[e]),U=c.useMemo(()=>{const ee=C.current;return ee?ee.groups.some(ie=>{try{const ve=ie.model.location.type;return ve!=="floating"&&ve!=="popout"?!1:ie.panels.some(Te=>H.has(Te.id))}catch{return!1}}):!1},[H,R,e]),K=c.useCallback(()=>{var ee;(ee=C.current)==null||ee.focus()},[]),oe=c.useCallback((ee,ie)=>{x==null||x(ee,ie)},[x]),ge=c.useCallback(ee=>{oR(ee,N)},[N]),J=c.useCallback(()=>{const ee=C.current;ee&&aR(ee,N)},[N]),ke=c.useCallback(ee=>{const ie=C.current;if(!ie)return;const ve=ie.getPanel(ee);ve&&ie.addPopoutGroup(ve,{popoutUrl:"/popout.html",onDidOpen:({window:Te})=>{ge(Te),X();const Ee=H.get(ee);Te.document.title=Ee?`${kt(Ee)} — ADHDev`:"ADHDev — Popout"}})},[H,ge]),de=c.useCallback(ee=>{const ie=C.current,ve=ie==null?void 0:ie.getPanel(ee);if(!ie||!ve)return;const Te=ie.groups.filter(Ee=>{var Ye;try{return((Ye=Ee.element)==null?void 0:Ye.ownerDocument)===document}catch{return!0}});Te.length>0?ve.api.moveTo({group:Te[0],position:"center"}):ve.api.moveTo({position:"center"}),ve.api.setActive()},[]),ne=c.useCallback(ee=>{var Te;const ie=C.current;if(!ie)return!1;const ve=ie.getPanel(ee);if(!ve)return!1;try{return((Te=ve.group.element)==null?void 0:Te.ownerDocument)!==document}catch{return!1}},[]),le=c.useCallback(ee=>{ne(ee)&&de(ee),m(ee)},[ne,de,m]),te=c.useCallback(ee=>{const ie=C.current,ve=ie==null?void 0:ie.getPanel(ee);!ie||!ve||ie.addFloatingGroup(ve,{width:600,height:500})},[]),ce=c.useCallback(ee=>{var ve;const ie=(ve=C.current)==null?void 0:ve.getPanel(ee);if(!ie)return!1;try{return ie.group.model.location.type==="floating"}catch{return!1}},[]),Ce=c.useCallback(()=>{var ie,ve;const ee=(ve=(ie=C.current)==null?void 0:ie.activePanel)==null?void 0:ve.id;return!ee||gn(ee)?null:H.has(ee)?ee:null},[H]),Q=c.useCallback(ee=>{const ie=C.current,ve=ie==null?void 0:ie.getPanel(ee);if(!ie||!ve)return;const Te=ie.groups.filter(Ee=>{try{return Ee.model.location.type==="grid"}catch{return!0}});Te.length>0?ve.api.moveTo({group:Te[0],position:"center"}):ve.api.moveTo({position:"center"}),ve.api.setActive()},[]),z=c.useCallback(()=>{var Ye;const ee=C.current;if(!ee)return;const ve=ee.groups.filter(qe=>{var Pe;try{return((Pe=qe.element)==null?void 0:Pe.ownerDocument)===document&&qe.model.location.type==="grid"}catch{return!1}})[0]||null,Te=[...ee.panels];for(const qe of Te){const Pe=(Ye=qe.group.element)==null?void 0:Ye.ownerDocument,tt=qe.group.model.location.type;Pe===document&&tt==="grid"||(ve&&ve.id!==qe.group.id?qe.api.moveTo({group:ve,position:"center"}):qe.api.moveTo({position:"center"}))}const Ee=ee.activePanel;Ee&&(Ee.group.model.openPanel(Ee),Ee.api.setActive()),Oc(document)},[]),X=c.useCallback(()=>{const ee=C.current;ee&&iR(ee,H,de)},[H,de]),pe=c.useCallback(ee=>{var Te;const ie=C.current,ve=ie==null?void 0:ie.getPanel(ee);if(!(!ie||!ve)){ve.group.model.openPanel(ve),ve.api.setActive(),oe(ee,"dockview-shortcut");try{const Ee=ve.group.model.location;Ee.type==="popout"?Ee.getWindow().focus():Oc((Te=ve.group.element)==null?void 0:Te.ownerDocument)}catch{}}},[oe]),Re=c.useCallback(ee=>{const ie=C.current,ve=ie==null?void 0:ie.activePanel,Te=(ie==null?void 0:ie.activeGroup)||(ve==null?void 0:ve.group);if(!ie||!ve||!Te)return;const Ee=Te.panels||[];if(Ee.length<=1)return;const Ye=Ee.findIndex(tt=>tt.id===ve.id);if(Ye<0)return;const qe=(Ye+ee+Ee.length)%Ee.length,Pe=Ee[qe];Pe&&(Pe.group.model.openPanel(Pe),Pe.api.setActive(),gn(Pe.id)||oe(Pe.id,"dockview-shortcut"))},[oe]),Oe=c.useCallback(ee=>{const ie=C.current;return ie?GM(ie,ee):void 0},[]),De=c.useCallback(ee=>{var Te;const ie=Oe(ee);if(!ie)return;const ve=ie.activePanel||ie.panels[0];ve&&(ie.model.openPanel(ve),ve.api.setActive(),gn(ve.id)||oe(ve.id,"dockview-focus"),Oc((Te=ie.element)==null?void 0:Te.ownerDocument))},[Oe,oe]),we=c.useCallback((ee,ie)=>{const ve=C.current,Te=ve==null?void 0:ve.activePanel,Ee=(ve==null?void 0:ve.activeGroup)||(Te==null?void 0:Te.group);if(!ve||!Te||!Ee)return;let Ye=Oe(ee);!Ye&&(ie!=null&&ie.createGroupIfMissing)&&(Ye=ve.addGroup({referenceGroup:Ee,direction:ee})),Ye&&(Te.api.moveTo({group:Ye,position:"center"}),Te.group.model.openPanel(Te),Te.api.setActive(),gn(Te.id)||oe(Te.id,ie!=null&&ie.createGroupIfMissing?"dockview-split":"dockview-move"))},[Oe,oe]),{isMac:V,tabShortcuts:xe,shortcutListening:Z,setShortcutListening:ae,saveShortcuts:F}=Zg({sortedTabKeys:e.map(ee=>ee.tabKey),onFocus:K,onSelectTab:pe}),se=c.useCallback(()=>{var ve;const ee=C.current;if(!ee)return;const ie=ee.activePanel;if(ie){if(gn(ie.id)){const Te=((ve=ie.params)==null?void 0:ve.routeId)||ie.id.slice(7),Ee=_n(e,Te);Ee!=null&&Ee.tabKey&&ae(Ee.tabKey);return}H.has(ie.id)&&ae(ie.id)}},[H,pe,ae,e]),me=c.useCallback(ee=>{const ie=[];return ee.metaKey&&ie.push(V?"⌘":"Meta"),ee.ctrlKey&&ie.push("Ctrl"),ee.altKey&&ie.push(V?"⌥":"Alt"),ee.shiftKey&&ee.key.length!==1&&ie.push(V?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(ee.key)?null:(ie.push(nx(ee.key)),ie.join("+"))},[V]),re=c.useCallback(ee=>{var ie,ve;switch(ee){case"splitActiveTabRight":we("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":we("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const Te=Ce();Te&&te(Te);return}case"popoutActiveTab":{const Te=Ce();Te&&ke(Te);return}case"dockActiveTab":{const Te=Ce();if(!Te)return;ne(Te)?de(Te):ce(Te)&&Q(Te);return}case"focusLeftPane":De("left");return;case"focusRightPane":De("right");return;case"focusUpPane":De("above");return;case"focusDownPane":De("below");return;case"moveActiveTabToLeftPane":we("left");return;case"moveActiveTabToRightPane":we("right");return;case"moveActiveTabToUpPane":we("above");return;case"moveActiveTabToDownPane":we("below");return;case"selectPreviousGroupTab":Re(-1);return;case"selectNextGroupTab":Re(1);return;case"setActiveTabShortcut":se();return;case"hideCurrentTab":{const Te=(ve=(ie=C.current)==null?void 0:ie.activePanel)==null?void 0:ve.id;Te&&!gn(Te)&&le(Te);return}default:return}},[Re,Q,De,te,Ce,le,ce,ne,de,we,ke,se]);c.useEffect(()=>{if(!G)return;const ee=G.sourceDocument,ie=ee.defaultView??window,ve=Te=>{const Ee=ee.querySelector("[data-dockview-tab-context-menu]");Ee&&Ee.contains(Te.target)||W(null)};return ie.addEventListener("mousedown",ve,!0),ie!==window&&window.addEventListener("mousedown",()=>W(null),!0),()=>{ie.removeEventListener("mousedown",ve,!0),ie!==window&&window.removeEventListener("mousedown",()=>W(null),!0)}},[G]);const Se=c.useMemo(()=>({actionLogs:r,clearedTabs:t,conversationsByTabKey:H,hasDetachedConversationPanels:U,ides:s,isStandalone:i,hasRegisteredMachines:l,initialDataLoaded:d,onOpenNewSession:f,liveSessionInboxState:k,sendDaemonCommand:o,setActionLogs:a,toggleHiddenTab:le,userName:u,scrollToBottomRequest:A,tabShortcuts:xe,openTabContextMenu:({x:ee,y:ie,tabKey:ve,sourceDocument:Te})=>W({x:ee,y:ie,tabKey:ve,sourceDocument:Te??document}),popoutTab:ke,moveTabBackToMain:de,isTabInPopout:ne,floatTab:te,isTabFloating:ce}),[r,t,H,U,s,i,l,d,f,k,o,a,le,u,A,xe,ke,de,ne,te,ce]),Y=G?FM({isTabInPopout:ne(G.tabKey),isTabFloating:ce(G.tabKey),tabShortcut:xe[G.tabKey],actionShortcuts:h}):[],ue=c.useCallback(ee=>{var Te;const ie=C.current;if((((Te=ie==null?void 0:ie.activePanel)==null?void 0:Te.id)??null)===ee.id){ee.group.model.openPanel(ee);return}ee.group.model.openPanel(ee),ee.api.setActive()},[]),fe=c.useCallback((ee,ie="requested-tab")=>{if(!ee)return!1;const ve=C.current;if(!ve)return!1;const Te=ve.getPanel(ee);return Te?(ue(Te),oe(ee,ie),S==null||S(),!0):!1},[ue,S,oe]),Ie=c.useCallback(()=>{if(_.current)return!1;const ee=fe(I.current,"stored-layout-restore");return ee&&(_.current=!0),ee},[fe]),Ke=c.useCallback(()=>{var ie;const ee=C.current;ee&&dI(w,{activeTabId:((ie=ee.activePanel)==null?void 0:ie.id)??null,layout:ee.toJSON()})},[w]),_e=c.useCallback(()=>{mI(w,B.current)},[w]),Ne=c.useCallback(ee=>{const ie=C.current;return ie?QM(ie,ee):{kind:"grid"}},[]),Be=c.useCallback(ee=>{const ie=C.current;if(!ie)return;const ve=ie.getPanel(ee),Te=B.current[ee];if(!ve||!Te||Te.kind==="grid")return;if(ve.group.model.location.type===Te.kind){delete B.current[ee],_e();return}if(Te.kind==="floating"){ie.addFloatingGroup(ve,{x:Te.position.left??24,y:Te.position.top??24,width:Te.position.width,height:Te.position.height}),delete B.current[ee],_e();return}delete B.current[ee],_e()},[_e]);c.useEffect(()=>(p==null||p({setShortcutForActiveTab:se,restoreHiddenTabToSavedLocation:Be,activateConversationTab:pe,resetAllPanelsToMain:z,activatePreviousTabInGroup:()=>Re(-1),activateNextTabInGroup:()=>Re(1),floatActiveTab:()=>{const ee=Ce();ee&&te(ee)},popoutActiveTab:()=>{const ee=Ce();ee&&ke(ee)},dockActiveTab:()=>{const ee=Ce();ee&&(ne(ee)?de(ee):ce(ee)&&Q(ee))},splitActiveTabRight:()=>we("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>we("below",{createGroupIfMissing:!0}),focusLeftPane:()=>De("left"),focusRightPane:()=>De("right"),focusUpPane:()=>De("above"),focusDownPane:()=>De("below"),moveActiveTabToLeftPane:()=>we("left"),moveActiveTabToRightPane:()=>we("right"),moveActiveTabToUpPane:()=>we("above"),moveActiveTabToDownPane:()=>we("below")}),()=>p==null?void 0:p(null)),[Re,Q,te,De,Ce,ce,ne,we,de,ke,p,z,Be,pe,se]),c.useEffect(()=>()=>{var ee;(ee=P.current)==null||ee.call(P),P.current=null},[]);const $e=c.useCallback(ee=>WM(L,ee.map(ie=>ie.tabKey)),[]),it=c.useCallback(ee=>{var ve,Te;C.current=ee.api,(ve=P.current)==null||ve.call(P),P.current=null;const ie=lI(w);if(I.current=(ie==null?void 0:ie.activeTabId)??null,ie!=null&&ie.layout&&(ee.api.fromJSON(ie.layout,{reuseExistingPanels:!1}),L.current=BM(ee.api.panels.map(Ee=>Ee.id),e.map(Ee=>Ee.tabKey),gn),L.current&&window.setTimeout(()=>{const Ee=C.current;!Ee||!L.current||(L.current=null,$c(Ee,q.current,null,$.current))},rx+50)),M.current=wh({hasStoredLayout:!!(ie!=null&&ie.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:s}),M.current||($c(ee.api,e,$e(e),$.current),Ch(ee.api,e,v)),ee.api.totalPanels===0&&e.length>0){const Ee=YM(ee.api,e,g,$.current);if(Ee){const Ye=ee.api.getPanel(Ee);Ye&&ue(Ye)}}else!M.current&&!fe(g)&&Ie();T.current=!0,ee.api.onDidActivePanelChange(Ee=>{var qe;if(I.current=(Ee==null?void 0:Ee.id)??null,_.current=!0,X(),Ee&&gn(Ee.id)){const Pe=((qe=Ee.params)==null?void 0:qe.routeId)||Ee.id.slice(7),tt=_n(e,Pe);b((tt==null?void 0:tt.tabKey)??null),Ke();return}if(b((Ee==null?void 0:Ee.id)??null),Ke(),!Ee)return;const Ye=H.get(Ee.id);(Ye==null?void 0:Ye.streamSource)==="agent-stream"&&Ye.agentType&&j(Ye.routeId,cb(),{agentType:Ye.agentType,...Ye.sessionId&&{targetSessionId:Ye.sessionId}}).catch(()=>{})}),ee.api.onDidLayoutChange(()=>{Ke(),X(),O(Ee=>Ee+1)}),qM()&&(P.current=zM(ee.api,()=>E.current,()=>{Ke(),X(),O(Ee=>Ee+1)})),ee.api.onDidAddGroup(Ee=>{requestAnimationFrame(()=>{var Ye,qe;try{const Pe=(Ye=Ee.element)==null?void 0:Ye.ownerDocument;if(!Pe||Pe===document)return;(qe=Pe.getElementById("dv-popout-window"))==null||qe.classList.add("adhdev-dockview");const tt=document.documentElement.getAttribute("data-theme");tt&&Pe.documentElement.setAttribute("data-theme",tt),Pe.body.className=document.body.className;const At=document.documentElement.getAttribute("style");At&&Pe.documentElement.setAttribute("style",At)}catch{}X(),O(Pe=>Pe+1)})}),b(((Te=ee.api.activePanel)==null?void 0:Te.id)??null)},[ue,fe,H,s,d,w,b,Ke,g,v,$e,j,X,e]);c.useLayoutEffect(()=>{const ee=C.current;if(!ee||!T.current||M.current&&wh({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:s}))return;M.current&&(M.current=!1);const ie=D.current,ve=new Set(ie),Te=e.map(gt=>gt.tabKey),Ee=new Set(Te),Ye=HM({previousVisibleConversationCount:ie.length,visibleConversationCount:e.length,ides:s});let qe=!1;for(const gt of ie)Ee.has(gt)||Ye||(B.current[gt]=Ne(gt),qe=!0);qe&&_e(),Ye||($c(ee,e,$e(e),$.current),Ch(ee,e,v));const Pe=Te.filter(gt=>!ve.has(gt));let tt=!1;for(const gt of Pe){const ye=ee.getPanel(gt),Ae=B.current[gt];if(!ye||!Ae||Ae.kind==="grid")continue;if(ye.group.model.location.type===Ae.kind){delete B.current[gt],tt=!0;continue}if(Ae.kind==="floating"){ee.addFloatingGroup(ye,{x:Ae.position.left??24,y:Ae.position.top??24,width:Ae.position.width,height:Ae.position.height}),delete B.current[gt],tt=!0;continue}}if(tt&&_e(),D.current=Te,g&&fe(g))return;!ee.activePanel&&ee.panels[0]&&ue(ee.panels[0]),!!(ee.activePanel&&ee.getPanel(ee.activePanel.id))||Ie()},[ue,fe,Ie,s,d,_e,Ne,g,v,$e,e]),c.useEffect(()=>{T.current&&fe(g)},[fe,g]),c.useEffect(()=>{const ee=ve=>{const Te=ve.target;if(!Te)return;const Ee=Te.querySelector("[data-tab-key]")||Te.closest("[data-tab-key]");if(Ee){const Ye=Ee.getAttribute("data-tab-key");if(Ye&&ve.dataTransfer){const qe=Te.closest(".dv-tab")||Ee.closest(".dv-tab")||Ee;ve.dataTransfer.effectAllowed="move",ve.dataTransfer.setData("text/tab-key",Ye),qe instanceof HTMLElement&&ve.dataTransfer.setDragImage(qe,Math.max(12,Math.round(qe.clientWidth/2)),Math.max(10,Math.round(qe.clientHeight/2)))}}};window.addEventListener("dragstart",ee);const ie=Nh(C.current);for(const ve of ie)ve.addEventListener("dragstart",ee);return()=>{window.removeEventListener("dragstart",ee);for(const ve of ie)ve.removeEventListener("dragstart",ee)}},[R]),c.useEffect(()=>{var ie;const ee=(ie=E.current)==null?void 0:ie.querySelector(".adhdev-dockview");ee instanceof HTMLElement&&du(ee,N),J(),X()},[X,J,N]),c.useEffect(()=>{X()},[X]),c.useEffect(()=>{const ee=ie=>{if(ie.defaultPrevented||Z)return;const ve=me(ie);if(!ve)return;const Te=ie.metaKey||ie.ctrlKey||ie.altKey;lu(ie.target)&&!Te||ai(V).setActiveTabShortcut!==ve||(ie.preventDefault(),ie.stopPropagation(),se())};return window.addEventListener("keydown",ee,!0),()=>window.removeEventListener("keydown",ee,!0)},[me,V,Z,se]),c.useEffect(()=>{const ee=E.current;if(!ee)return;const ie=ve=>{var Pe,tt;if(!ve.isTrusted)return;const Te=(tt=(Pe=ve.target)==null?void 0:Pe.closest)==null?void 0:tt.call(Pe,".dv-scrollable");if(!Te)return;ve.preventDefault(),ve.stopPropagation();const Ee=Math.abs(ve.deltaX),Ye=Math.abs(ve.deltaY),qe=Ee>Ye?ve.deltaX:ve.deltaY;Te.dispatchEvent(new WheelEvent("wheel",{deltaY:qe,deltaMode:ve.deltaMode,bubbles:!1,cancelable:!0}))};return ee.addEventListener("wheel",ie,{passive:!1,capture:!0}),()=>ee.removeEventListener("wheel",ie,{capture:!0})},[]),c.useEffect(()=>{const ee=Nh(C.current);if(ee.length===0)return;const ie=ee.map(ve=>tR(ve,{encodeShortcut:me,isMac:V,isShortcutListening:()=>!!Z,isVisibleTab:Te=>e.some(Ee=>Ee.tabKey===Te),selectTabByShortcut:pe,triggerAction:re}));return()=>{for(const ve of ie)ve()}},[me,V,R,pe,Z,re,e]);const dt=N==="light"?ol:al,ut=((jt=(bt=(It=C.current)==null?void 0:It.activePanel)==null?void 0:bt.group.element)==null?void 0:jt.ownerDocument)??document;return n.jsxs(cx.Provider,{value:Se,children:[n.jsx("div",{ref:E,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:n.jsx(ly,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:lR,remote:XM},defaultTabComponent:eR,watermarkComponent:ZM,onReady:it,singleTabMode:"default",tabAnimation:"smooth",theme:dt,popoutUrl:"/popout.html"})}),G&&n.jsx(rR,{x:G.x,y:G.y,sourceDocument:G.sourceDocument,items:Y,onSelect:(ee,ie)=>{switch(ee){case"dockInWindow":case"dockBackToGrid":Q(G.tabKey);break;case"moveBackToMain":de(G.tabKey);break;case"floatAsPanel":te(G.tabKey);break;case"openInNewWindow":ke(G.tabKey);break;case"setShortcut":ie.stopPropagation(),ae(G.tabKey);break;case"removeShortcut":{const ve={...xe};delete ve[G.tabKey],F(ve);break}case"hideTab":le(G.tabKey);break}W(null)}}),Z&&An.createPortal(n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>ae(null),children:n.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:ee=>ee.stopPropagation(),children:[n.jsxs("div",{className:"text-sm font-bold text-text-primary mb-2",children:["⌨ ",y("paneGroup.shortcutSetTitle")]}),n.jsx("div",{className:"text-xs text-text-secondary mb-4",children:y("paneGroup.shortcutPressCombo",{example1:V?"⌘+1":"Ctrl+1",example2:V?"⌥+A":"Alt+A"})}),n.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:y("paneGroup.shortcutListening")}),n.jsx("div",{className:"text-3xs text-text-muted mt-3",children:y("paneGroup.pressEscToCancel")})]})}),ut.body)]})}const lx="adhdev-recent-launch-args-v1",uR=8;function mR(e){return String(e||"").trim().replace(/\s+/g," ")}function dx(e,t){return`${e.trim()}::${t.trim()}`}function ux(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(lx)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function hR(e){if(!(typeof window>"u"))try{window.localStorage.setItem(lx,JSON.stringify(e))}catch{}}function pR(e,t){var a;const s=String(e||"").trim(),r=String(t||"").trim();return!s||!r?[]:((a=ux().byKey[dx(s,r)])==null?void 0:a.items)||[]}function fR(e,t,s){var m;const r=String(e||"").trim(),o=String(t||"").trim(),a=mR(s);if(!r||!o||!a)return;const i=ux(),l=dx(r,o),d=((m=i.byKey[l])==null?void 0:m.items)||[],u=[a,...d.filter(h=>h!==a)].slice(0,uR);i.byKey[l]={items:u},hR(i)}const bR="adhdev.remember.";function Xl(e){return`${bR}${e.trim()}`}function Fc(e){if(typeof window>"u"||!e.trim())return null;try{const t=window.localStorage.getItem(Xl(e));if(!t)return null;const s=JSON.parse(t);if(!s||typeof s!="object"||Array.isArray(s))return null;const r={};for(const[o,a]of Object.entries(s))typeof a=="string"&&a&&(r[o]=a);return Object.keys(r).length>0?r:null}catch{return null}}function la(e,t){if(!(typeof window>"u"||!e.trim()))try{const s={};for(const[r,o]of Object.entries(t))typeof o=="string"&&o&&(s[r]=o);if(Object.keys(s).length===0){window.localStorage.removeItem(Xl(e));return}window.localStorage.setItem(Xl(e),JSON.stringify(s))}catch{}}function gR({sessions:e,loading:t,busy:s=!1,resumingSessionId:r=null,fallbackWorkspacePath:o,onResume:a,onRefresh:i,onClose:l}){const{t:d}=he("common"),[u,m]=c.useState(""),h=String(o||"").trim(),p=c.useMemo(()=>{const b=e.map(f=>f.canResume||String(f.workspace||"").trim()||!h?f:{...f,workspace:h,canResume:!0,workspaceFallbackSource:"selected-workspace"});return zd(b,{textQuery:u,sortMode:"recent"})},[h,u,e]);return n.jsxs("div",{className:"mt-3 flex max-h-[min(55vh,420px)] flex-col overflow-hidden rounded-xl border border-border-subtle bg-bg-secondary",role:"region","aria-label":Wl(d),"data-testid":"saved-history-inline",children:[n.jsxs("div",{className:"flex items-center gap-2 border-b border-border-subtle px-3 py-2",children:[n.jsx("input",{type:"search",value:u,onChange:b=>m(b.target.value),placeholder:d("historyModal.searchPlaceholder"),"aria-label":d("historyModal.searchPlaceholder"),className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-1.5 text-sm text-text-primary"}),n.jsx(Wi,{onClick:i,refreshing:t,className:"h-8 w-8"}),n.jsx("button",{type:"button",onClick:l,"aria-label":d("common.close"),className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border-subtle bg-transparent text-text-muted hover:text-text-primary",children:n.jsx(Lt,{size:14})})]}),n.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-2",children:[p.map(b=>{const f=r===b.providerSessionId,x=String(b.workspace||"").trim();return n.jsxs("div",{className:"flex items-center gap-3 rounded-lg px-2.5 py-2 hover:bg-bg-primary/60",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"truncate text-sm font-semibold text-text-primary",children:b.title||d("historyModal.untitledSession")}),n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-2xs text-text-muted",children:[n.jsx(Jb,{value:b.lastMessageAt}),x&&n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx(Qt,{content:x,children:n.jsx("span",{className:"truncate",children:eg(x)})})]}),b.messageCount>0&&n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:"shrink-0",children:d("historyModal.msgCount",{count:b.messageCount})})]})]})]}),b.canResume?n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",disabled:s||!!r,onClick:()=>a(b),children:d(f?"historyModal.statusResuming":"historyModal.statusResume")}):n.jsx("span",{className:"shrink-0 text-2xs text-text-muted",children:d("historyModal.statusMissingWorkspace")})]},b.id)}),!t&&p.length===0&&n.jsx("div",{className:"px-3 py-6 text-center text-xs text-text-muted",children:e.length>0?d("historyModal.noMatchingHistory"):mg(d)}),t&&p.length===0&&n.jsx("div",{className:"px-3 py-6 text-center text-xs text-text-muted",children:d("launch.loadingShort")})]})]})}function xR(e){return!e.hasLoadedInitialResults&&!e.isLoading}function qs({title:e,description:t,action:s,children:r,className:o="",contentClassName:a=""}){return n.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${o}`.trim(),children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted",children:e}),t&&n.jsx(rt,{content:t,size:12})]}),s?n.jsx("div",{className:"flex items-center gap-2",children:s}):null]}),r?n.jsx("div",{className:s?`mt-3 ${a}`.trim():`mt-2 ${a}`.trim(),children:r}):null]})}function yR(e,{savedSessionsLoading:t,savedSessionsLoaded:s,savedSessionsCount:r=0}){return t?e("launch.refreshingSavedHistory"):s?r>0?e("launch.savedHistoryLoadedCount",{count:r}):e("launch.savedHistoryNoneYet"):""}function vR({busy:e,savedSessionsLoading:t,savedSessionsError:s,savedSessionsLoaded:r,savedSessionsCount:o=0,selectedSession:a,historyOpen:i=!1,onOpenHistory:l,onClearSelection:d}){const{t:u}=he("common"),m=a?zg(a,u):null,h=yR(u,{savedSessionsLoading:t,savedSessionsLoaded:r,savedSessionsCount:o}),p=!!m||!!h||!!s;return n.jsx(qs,{title:u("launch.savedHistoryBadge"),description:Vd(u),action:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,"aria-expanded":i,onClick:l,children:hT(u)}),children:p?n.jsxs(n.Fragment,{children:[m?n.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-2xs text-text-muted leading-relaxed",children:n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted",children:u("launch.selectedSavedHistory")}),n.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",title:m.providerSessionId,children:m.title}),n.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&n.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&n.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:u("launch.clearSelection")})]})}):h?n.jsx("div",{className:"text-2xs text-text-muted","aria-live":"polite",children:h}):null,s?n.jsx("div",{className:"mt-2 text-2xs text-status-error",children:s}):null]}):null})}function wR({setup:e,providerName:t,className:s=""}){const{t:r}=he("common");return e?n.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${s}`,children:[n.jsx("div",{className:"font-semibold",children:t?r("mesh.manualSetup.titleFor",{provider:t}):r("mesh.manualSetup.title")}),e.instructions&&n.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-2xs text-text-muted",children:[e.serverName&&n.jsxs("span",{children:[r("mesh.manualSetup.server")," ",n.jsx("code",{children:e.serverName})]}),e.configFormat&&n.jsxs("span",{children:[r("mesh.manualSetup.format")," ",n.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&n.jsxs("span",{children:[r("mesh.manualSetup.configPath")," ",n.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&n.jsx("span",{children:r("mesh.manualSetup.restartHint")})]}),e.template&&n.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}const SR={cli:"CLI",ide:"IDE"},ho="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm";function kR({machines:e,selectedMachineId:t,useDropdown:s,busy:r,onSelect:o,onPrefetch:a}){const{t:i}=he();return n.jsx(qs,{title:i("newSession.machine"),children:s?n.jsx("select",{"aria-label":i("newSession.machine"),value:t,onChange:l=>o(l.target.value),onFocus:()=>e.forEach(l=>a(l.id)),className:ho,disabled:r,children:e.map(l=>n.jsx("option",{value:l.id,children:pn(l,{fallbackId:l.id})},l.id))}):n.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":i("newSession.machine"),children:e.map(l=>{const d=pn(l,{fallbackId:l.id}),u=t===l.id;return n.jsxs("button",{type:"button","aria-label":i("newSession.selectMachine",{name:d}),"aria-pressed":u,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${u?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>o(l.id),onMouseEnter:()=>a(l.id),onFocus:()=>a(l.id),disabled:r,title:d,children:[n.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${l.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),n.jsx("span",{className:"truncate",children:d})]},l.id)})})})}function jR({loading:e,error:t,meshes:s,selectedMeshId:r,busy:o,onSelect:a}){const{t:i}=he();return n.jsxs("div",{className:"space-y-3",children:[e&&n.jsx("div",{className:"text-sm text-text-muted",children:i("newSession.loadingMeshes")}),!e&&t&&n.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:t}),!e&&!t&&s.length===0&&n.jsxs("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:[i("newSession.noMeshesShort"),n.jsx(rt,{content:i("newSession.noMeshes")})]}),s.length>0&&n.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":i("newSession.mesh"),children:s.map(l=>n.jsxs("button",{type:"button",role:"radio","aria-checked":r===l.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${r===l.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>a(l.id),disabled:o,children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:l.name}),n.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[l.repoIdentity||i("newSession.repoMesh"),typeof l.nodesCount=="number"?` · ${i("newSession.nodeCount",{count:l.nodesCount})}`:""]}),l.workspace&&n.jsx("div",{className:"mt-1 text-2xs text-text-muted break-all",children:i("newSession.coordinatorWorkspace",{path:l.workspace})})]},l.id))})]})}function NR({targets:e,activeKind:t,selectedTarget:s,showCategory:r,busy:o,onSelect:a}){const{t:i}=he();return n.jsx(qs,{title:i("newSession.agent"),children:n.jsxs("div",{className:"grid grid-cols-1 gap-1.5",role:"radiogroup","aria-label":i("newSession.agent"),children:[e.map(l=>{const d=t===l.kind&&s===l.id;return n.jsxs("button",{type:"button",role:"radio","aria-checked":d,"data-launch-kind":l.kind,className:`flex w-full items-center justify-between gap-3 rounded-xl border px-3.5 py-2.5 text-left transition-colors ${d?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>a(l),disabled:o,children:[n.jsx("span",{className:"min-w-0 truncate text-sm font-semibold text-text-primary",children:l.label}),n.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[l.meta&&n.jsx("span",{className:"text-2xs text-text-muted",children:l.meta}),r&&n.jsx("span",{className:"rounded-full border border-border-subtle px-1.5 py-px text-3xs font-semibold uppercase tracking-wide text-text-muted",children:SR[l.kind]})]})]},`${l.kind}:${l.id}`)}),e.length===0&&n.jsxs("div",{className:"flex items-center gap-1 text-sm text-text-muted",children:[i("newSession.noProvidersShort"),n.jsx(rt,{content:i("newSession.noProviders")})]})]})})}function CR({value:e,recentOptions:t,busy:s,onChange:r}){const{t:o}=he();return n.jsxs(qs,{title:o("newSession.startupArguments"),children:[n.jsx("input",{type:"text",value:e,onChange:a=>r(a.target.value),placeholder:o("newSession.optionalFlags"),className:ho,disabled:s}),t.length>0&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.map(a=>n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>r(a),disabled:s,title:a,children:a},a))})]})}function _R({modelOptions:e,thinkingOptions:t,model:s,thinkingLevel:r,modelIsCustom:o,busy:a,onModelIsCustomChange:i,onModelChange:l,onThinkingChange:d}){const{t:u}=he();return n.jsx(qs,{title:u("newSession.modelAndThinking"),children:n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:u("newSession.model")}),e.length>0&&!o?n.jsxs(n.Fragment,{children:[n.jsxs("select",{value:e.includes(s)?s:"",onChange:m=>{m.target.value==="__custom__"?(i(!0),l("")):l(m.target.value)},className:ho,disabled:a,children:[n.jsx("option",{value:"",children:u("newSession.providerDefault")}),e.map(m=>n.jsx("option",{value:m,children:m},m)),n.jsx("option",{value:"__custom__",children:u("newSession.custom")})]}),!s.trim()&&n.jsx("span",{className:"text-2xs text-text-muted","data-testid":"new-session-default-model",children:u("newSession.defaultResolvesTo",{model:e[0],defaultValue:"Default resolves to {{model}}"})})]}):n.jsxs(n.Fragment,{children:[n.jsx("input",{type:"text",value:s,onChange:m=>l(m.target.value),placeholder:u("newSession.typeModelName"),className:ho,disabled:a,autoFocus:o}),e.length>0&&n.jsx("button",{type:"button",className:"self-start text-2xs text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{i(!1),l("")},disabled:a,children:u("newSession.backToModelList")})]})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:u("newSession.thinkingLevel")}),n.jsxs("select",{value:r,onChange:m=>d(m.target.value),className:ho,disabled:a,children:[n.jsx("option",{value:"",children:u("newSession.providerDefault")}),t.map(m=>n.jsx("option",{value:m,children:m},m))]})]})]})})}function ii(e,t){var s;return e?t==="ide"?(((s=e.detectedIdes)==null?void 0:s.length)||0)>0:(e.availableProviders||[]).some(r=>Li(r,t)):!1}function Hc(e){return e?ii(e,"cli")?"cli":ii(e,"ide")?"ide":null:null}const Bc="new-session-dialog",Ah="new-session-workspace",Th="new-session-mesh",Zl={value:"",source:null};function Ih(e,t){return e?{value:e,source:t}:Zl}function Mh(e,t){return{...e.value.trim()&&e.source?{modelSource:e.source}:{},...t.value.trim()&&t.source?{thinkingLevelSource:t.source}:{}}}function AR(e){return e==="cli"||e==="ide"}function nr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}const TR=new Set(["--dangerously-skip-permissions","--dangerously-bypass-approvals-and-sandbox","bypassPermissions","sandbox_mode=danger-full-access","approval_policy=never"]);function IR(e){const t=e.trim();return TR.has(t)||t.startsWith("--dangerously-skip-permissions=")||t.startsWith("--dangerously-bypass-approvals-and-sandbox=")}function Hn(e){var t;return(t=e.launchArgs)!=null&&t.some(IR)?"dangerous":e.risk}function MR(e){var s,r;if(!e)return"";const t=e.modes.find(o=>o.id===e.default);return t&&Hn(t)!=="dangerous"?t.id:((s=e.modes.find(o=>o.strategy==="pty-parse-default"&&Hn(o)!=="dangerous"))==null?void 0:s.id)||((r=e.modes.find(o=>Hn(o)!=="dangerous"))==null?void 0:r.id)||""}function RR(e,t,s){return e?t?{autoApproveMode:t}:{autoApprove:!1}:{autoApprove:s}}const PR={safe:"border-status-online/25 bg-status-online/10 text-status-online",caution:"border-status-warning/30 bg-status-warning/10 text-status-warning",dangerous:"border-status-error/30 bg-status-error/10 text-status-error"};function mx({risk:e}){const{t}=he();return n.jsx("span",{className:`rounded-full border px-2 py-0.5 text-3xs font-semibold uppercase tracking-wide ${PR[e]}`,children:t(`newSession.autoApproveRisk.${e}`)})}function hx({config:e,selectedModeId:t,disabled:s=!1,onSelectMode:r}){const{t:o}=he();return n.jsx("div",{className:"space-y-2",children:n.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":o("newSession.autoApproveMode"),children:e.modes.map(a=>{const i=Hn(a),l=t===a.id;return n.jsxs("button",{type:"button",role:"radio","aria-checked":l,className:`flex w-full items-center justify-between gap-3 rounded-xl border px-3.5 py-3 text-left transition-colors ${l?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>r(a),disabled:s,children:[n.jsx("span",{className:"min-w-0 text-sm font-semibold text-text-primary",children:a.label}),n.jsx(mx,{risk:i})]},a.id)})})})}function ER({checked:e,disabled:t=!1,onChange:s}){const{t:r}=he();return n.jsxs("div",{className:"flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-secondary/40 px-3.5 py-3",children:[n.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[n.jsx("span",{id:"legacy-auto-approve-label",className:"text-sm font-semibold text-text-primary",children:r("newSession.autoApproveLegacy")}),n.jsx(rt,{content:r("newSession.autoApproveLegacyDescription")})]}),n.jsx(Pr,{checked:e,onChange:s,disabled:t,"aria-labelledby":"legacy-auto-approve-label"})]})}function px({mode:e,onConfirm:t,onCancel:s}){const{t:r}=he();return n.jsx(Ui,{title:r("newSession.dangerousModeTitle"),description:e.warning||r("newSession.dangerousModeFallbackWarning"),details:[{label:r("newSession.dangerousModeRisk"),value:r("newSession.autoApproveRisk.dangerous")},{label:r("newSession.dangerousModeLaunchArgs"),value:JSON.stringify(e.launchArgs||[])}],confirmLabel:r("newSession.dangerousModeConfirm"),onConfirm:t,onCancel:s})}function LR({machines:e,ides:t,onClose:s,onBrowseDirectory:r,onSaveWorkspace:o,onLaunchIde:a,onLaunchProvider:i,onListMeshes:l,onLaunchMeshCoordinator:d,onListSavedSessions:u,initialMachineId:m,initialWorkspaceId:h,initialLaunchMode:p,initialMeshWorkspacePath:b}){var Ze,Mt,wn,$r,bu,gu,xu,yu,vu;const{t:f}=he(),x=Rr(),g=c.useMemo(()=>[...e].sort(Ua),[e]),[v]=c.useState(()=>({dialog:Fc(Bc),workspace:Fc(Ah),mesh:Fc(Th)})),[S,A]=c.useState(()=>{var He,Fe;if(m&&e.some(at=>at.id===m))return m;const be=(He=v.dialog)==null?void 0:He.machineId;return be&&e.some(at=>at.id===be)?be:((Fe=[...e].sort(Ua)[0])==null?void 0:Fe.id)||""}),k=c.useMemo(()=>g.find(be=>be.id===S)||g[0],[S,g]),w=c.useMemo(()=>((k==null?void 0:k.workspaces)||[]).map(be=>({id:be.id,path:be.path,label:be.label})),[k]),y=(k==null?void 0:k.defaultWorkspaceId)||null,[N,j]=c.useState("workspace"),[C,E]=c.useState(""),[P,T]=c.useState(""),[M,_]=c.useState([]),[I,D]=c.useState(""),[L,$]=c.useState(!1),[q,G]=c.useState(null),[W,R]=c.useState(""),[O,B]=c.useState(Hc(g[0])),[H,U]=c.useState(""),[K,oe]=c.useState(""),[ge,J]=c.useState(!1),[ke,de]=c.useState(""),[ne,le]=c.useState(null),[te,ce]=c.useState(Zl),[Ce,Q]=c.useState(Zl),z=te.value,X=Ce.value,pe=c.useCallback((be,He)=>{ce(Ih(be,He))},[]),Re=c.useCallback((be,He)=>{Q(Ih(be,He))},[]),[Oe,De]=c.useState(!1),[we,V]=c.useState([]),[xe,Z]=c.useState(""),[ae,F]=c.useState([]),[se,me]=c.useState(!1),[re,Se]=c.useState(!1),[Y,ue]=c.useState(""),[fe,Ie]=c.useState(!1),[Ke,_e]=c.useState(null),[Ne,Be]=c.useState(!1),[$e,it]=c.useState(""),[dt,ut]=c.useState("error"),[It,bt]=c.useState(null),[jt,ee]=c.useState(!1),[ie,ve]=c.useState(""),[Te,Ee]=c.useState([]),[Ye,qe]=c.useState(!1),[Pe,tt]=c.useState(""),[At,gt]=c.useState(!1),ye=c.useRef(null),Ae=c.useRef(h||null),Le=c.useRef(p||(((Ze=v.dialog)==null?void 0:Ze.mode)==="mesh"||((Mt=v.dialog)==null?void 0:Mt.mode)==="workspace"?v.dialog.mode:null)),Ve=c.useRef(b||null),Je=c.useRef(h?null:((wn=v.workspace)==null?void 0:wn.workspaceChoice)||null),ht=($r=v.workspace)==null?void 0:$r.kind,st=c.useRef(AR(ht)?ht:null),Nt=c.useRef(((bu=v.workspace)==null?void 0:bu.target)||null),xt=c.useRef(((gu=v.mesh)==null?void 0:gu.meshId)||null),Wt=c.useRef(((xu=v.mesh)==null?void 0:xu.cliType)||null),Jt=c.useRef(!0),an=c.useRef(!0),qt=c.useRef(0),Tt=c.useRef(0),cn=c.useRef(0);c.useEffect(()=>{var be,He;if(!S&&((be=g[0])!=null&&be.id)){const Fe=(He=v.dialog)==null?void 0:He.machineId,at=m&&g.some(dn=>dn.id===m)?m:Fe&&g.some(dn=>dn.id===Fe)?Fe:g[0].id;A(at)}},[m,v,S,g]),c.useEffect(()=>{!k||!(!k.workspaces||!k.availableProviders||!k.detectedIdes||!k.recentLaunches)||x(k.id,{minFreshMs:3e4}).catch(()=>{})},[x,k]);const Kn=c.useCallback(be=>{be&&x(be,{minFreshMs:3e4}).catch(()=>{})},[x]),Ct=c.useMemo(()=>((k==null?void 0:k.availableProviders)||[]).filter(be=>Li(be,"cli")),[k]),ln=c.useMemo(()=>((k==null?void 0:k.detectedIdes)||[]).map(be=>({id:be.type,label:be.name||be.type,meta:be.running?f("newSession.detectedLocally"):f("newSession.availableToOpen")})),[k,f]),fn=c.useMemo(()=>O==="cli"?Ct.map(be=>({id:be.type,label:be.displayName||be.type,meta:""})):ln,[O,Ct,ln]),Ge=c.useMemo(()=>{const be=Ct.map(Fe=>({kind:"cli",id:Fe.type,label:Fe.displayName||Fe.type,meta:""}));if(N==="mesh")return be;const He=ln.map(Fe=>({kind:"ide",...Fe}));return[...be,...He]},[Ct,ln,N]),lt=c.useMemo(()=>M.find(be=>be.id===I)||null,[M,I]),Me=c.useMemo(()=>Ct.find(be=>be.type===H)||null,[Ct,H]),We=c.useMemo(()=>Ct.find(be=>be.type===H),[Ct,H]),ot=O==="cli"?We==null?void 0:We.autoApproveModes:void 0,St=JSON.stringify(ot||null),zt=MR(ot),mt=c.useMemo(()=>Bb(We?[We]:[],We==null?void 0:We.type),[We]),Yt=c.useMemo(()=>{const be=Wb(We?[We]:[],We==null?void 0:We.type);return be.length?be:["low","medium","high"]},[We]),Tn=c.useMemo(()=>OI(Me==null?void 0:Me.meshCoordinator,{meshId:(lt==null?void 0:lt.id)||"",workspace:(lt==null?void 0:lt.workspace)||""}),[Me,lt]),vn=It||Tn,In=c.useCallback(async be=>{const He=cn.current+1;cn.current=He,$(!0),R("");try{const Fe=await l(be);if(cn.current!==He)return;_(Fe),D(at=>{var dn;return Fe.some(os=>os.id===at)?at:((dn=Fe[0])==null?void 0:dn.id)||""}),G(be)}catch(Fe){if(cn.current!==He)return;_([]),D(""),G(be),R(Fe instanceof Error?Fe.message:f("newSession.errorLoadMeshes"))}finally{cn.current===He&&$(!1)}},[l,f]);c.useEffect(()=>{var dn,os;if(!k)return;if(ye.current!==k.id){Tt.current+=1,cn.current+=1,ye.current!==null&&(Ae.current=null,Le.current=null,Ve.current=null,Je.current=null,st.current=null,Nt.current=null,xt.current=null,Wt.current=null,Jt.current=!1,an.current=!1),ye.current=k.id;const Dt=Le.current;Le.current=null,j(Dt||"workspace");const Rn=Ae.current,zn=Je.current;T(""),ee(!1),ve(""),Ee([]),qe(!1),tt(""),Rn&&w.some(nc=>nc.id===Rn)?(Ae.current=null,E(Rn)):zn==="__home__"?(Je.current=null,E("__home__")):zn==="__custom__"&&((dn=v.workspace)!=null&&dn.customWorkspacePath)?(Je.current=null,E("__custom__"),T(v.workspace.customWorkspacePath)):zn&&w.some(nc=>nc.id===zn)?(Je.current=null,E(zn)):E(y||((os=w[0])==null?void 0:os.id)||"__home__"),_([]),D(""),$(!1),G(null),R("");const tc=st.current;tc&&ii(k,tc)?(st.current=null,B(tc)):B(Hc(k)),U(""),oe(""),J(!1),de(""),le(null),pe("","user"),Re("","user"),De(!1),Z(""),F([]),Se(!1),ue(""),Ie(!1),it(""),bt(null);return}const He=Ae.current,Fe=Je.current;He&&w.some(Dt=>Dt.id===He)?(Ae.current=null,E(He)):Fe&&w.some(Dt=>Dt.id===Fe)?(Je.current=null,E(Fe)):E(Dt=>{var Rn;return Dt==="__custom__"||Dt==="__home__"||w.some(zn=>zn.id===Dt)?Dt:y||((Rn=w[0])==null?void 0:Rn.id)||"__home__"});const at=st.current;at&&ii(k,at)?(st.current=null,B(at)):B(Dt=>Dt==="ide"&&ln.length>0||Dt==="cli"&&Ct.length>0?Dt:Hc(k))},[Ct.length,y,ln.length,v,k,w]),c.useEffect(()=>{!k||N!=="mesh"||q===k.id||L||In(k.id)},[In,q,L,k,N]),c.useEffect(()=>{if(M.length===0)return;const be=Ve.current;if(be){Ve.current=null,xt.current=null;const Fe=M.find(at=>nr(at.workspace)===nr(be));Fe&&D(Fe.id);return}const He=xt.current;He&&(xt.current=null,M.some(Fe=>Fe.id===He)&&D(He))},[M]),c.useEffect(()=>{N==="mesh"&&O!=="cli"&&Ct.length>0&&B("cli")},[O,Ct.length,N]),c.useEffect(()=>{var Fe;if(!O||fn.some(at=>at.id===H))return;let be=((Fe=fn[0])==null?void 0:Fe.id)||"";const He=Nt.current;N!=="mesh"&&He&&fn.length>0&&O===ht&&(Nt.current=null,fn.some(at=>at.id===He)&&(be=He)),U(be)},[O,fn,ht,H,N]),c.useEffect(()=>{if(N!=="mesh")return;const be=Wt.current;!be||Ct.length===0||(Wt.current=null,Ct.some(He=>He.type===be)&&U(be))},[Ct,N]),c.useEffect(()=>{bt(null)},[k==null?void 0:k.id,I,H,N]),c.useEffect(()=>{pe("","user"),Re("","user"),De(!1)},[H,pe,Re]),c.useEffect(()=>{de(zt),J(!1),le(null)},[St,zt,k==null?void 0:k.id,H]),c.useEffect(()=>{if(!H)return;const be=N==="mesh",He=be?an:Jt;if(!He.current)return;const Fe=be?v.mesh:v.workspace,at=be?Fe==null?void 0:Fe.cliType:Fe==null?void 0:Fe.target;if(!Fe||at!==H)return;He.current=!1;const dn=Fe.model||"";dn&&(mt.length>0&&!mt.includes(dn)&&De(!0),pe(dn,"remembered"));const os=Fe.thinkingLevel||"";os&&Yt.includes(os)&&Re(os,"remembered");const Dt=Fe.autoApproveModeId||"";if(Dt&&ot){const Rn=ot.modes.find(zn=>zn.id===Dt);Rn&&Hn(Rn)!=="dangerous"&&de(Rn.id)}},[ot,St,mt,v,H,pe,Re,Yt,N]);const Xt=c.useCallback(be=>{if(Hn(be)==="dangerous"){le(be);return}de(be.id)},[]),Mn=c.useMemo(()=>RR(ot,ke,ge),[ot,ge,ke]),ss=c.useCallback(async(be,He)=>{const Fe=qt.current+1;return qt.current=Fe,me(!0),ue(""),u(be,He).then(at=>{qt.current===Fe&&F(at)}).catch(at=>{qt.current===Fe&&(F([]),ue(at instanceof Error?at.message:f("newSession.errorLoadSavedSessions")))}).finally(()=>{qt.current===Fe&&(me(!1),Se(!0))})},[u,f]),qn=c.useCallback((be,He)=>{V(pR(be,He))},[]);c.useEffect(()=>{qt.current+=1,Z(""),Ie(!1),!k||!H||O==="ide"?V([]):qn(k.id,H),Se(!1),F([]),ue(""),me(!1)},[O,qn,ss,k,H]),c.useEffect(()=>{if(!xe)return;const be=ae.find(He=>He.providerSessionId===xe);be!=null&&be.canResume||Z("")},[ae,xe]);const Ut=C==="__custom__"?P.trim():C==="__home__"?"":((yu=w.find(be=>be.id===C))==null?void 0:yu.path)||"",js=c.useMemo(()=>k?t.filter(be=>be.id!==k.id&&be.daemonId===k.id).map(be=>be.workspace):[],[t,k]),rs=c.useMemo(()=>((k==null?void 0:k.recentLaunches)||[]).map(be=>be.workspace),[k]),$o=c.useCallback(be=>{const He=String(be.workspace||"").trim();if(!He)return;const Fe=w.find(at=>nr(at.path)===nr(He));if(Fe){E(Fe.id),T("");return}E("__custom__"),T(He)},[w]),Fo=c.useCallback(be=>{const He=String(be.workspace||"").trim();if(!He)return{workspaceId:null,workspacePath:null,useHome:!0};const Fe=w.find(at=>nr(at.path)===nr(He));return Fe?{workspaceId:Fe.id,workspacePath:null,useHome:!1}:{workspaceId:null,workspacePath:He,useHome:!1}},[w]),Qi=c.useMemo(()=>ae.find(be=>be.providerSessionId===xe)||null,[ae,xe]),Ji=c.useCallback(be=>{if(!k||!H||Ke||!be.canResume)return;const He=Fo(be);Z(be.providerSessionId),$o(be),_e(be.providerSessionId),Ie(!1),Be(!0),it(""),i(k.id,"cli",H,{workspaceId:He.workspaceId,workspacePath:He.workspacePath,useHome:He.useHome,resumeSessionId:be.providerSessionId,settings:Mn}).then(Fe=>{if(!Fe.ok){ut("error"),it(Fe.code==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"?f("newSession.errorWorkspaceContextRequired"):Fe.error||f("newSession.errorResumeSession"));return}s()}).finally(()=>{Be(!1),_e(Fe=>Fe===be.providerSessionId?null:Fe)})},[$o,Mn,s,i,Fo,Ke,k,H,f]),Xi=((vu=ot==null?void 0:ot.modes.find(be=>be.id===ke))==null?void 0:vu.label)||"",Lr=[K.trim(),z.trim(),X.trim(),O==="cli"||N==="mesh"?ot?Xi:ge?f("newSession.autoApproveLegacy"):"":""].filter(Boolean).join(" · "),Dr=c.useCallback(()=>{var Fe;if(!k)return;const be=Tt.current+1;Tt.current=be,E("__custom__"),ee(!0),tt("");const He=ru(k.platform,su(P.trim(),Ut,js,rs,k.defaultWorkspacePath,(Fe=w.find(at=>at.id===y))==null?void 0:Fe.path,w.map(at=>at.path)));qe(!0),r(k.id,He).then(at=>{Tt.current===be&&(ve(at.path),T(at.path),Ee(at.directories))}).catch(at=>{Tt.current===be&&tt(at instanceof Error?at.message:f("newSession.errorLoadFolder"))}).finally(()=>{Tt.current===be&&qe(!1)})},[P,y,rs,js,r,Ut,k,w]),Zi=c.useCallback(be=>{if(!k)return;const He=Tt.current+1;Tt.current=He,qe(!0),tt(""),r(k.id,be).then(Fe=>{Tt.current===He&&(ve(Fe.path),T(Fe.path),Ee(Fe.directories))}).catch(Fe=>{Tt.current===He&&tt(Fe instanceof Error?Fe.message:f("newSession.errorLoadFolder"))}).finally(()=>{Tt.current===He&&qe(!1)})},[r,k]),ec=c.useCallback(async()=>{if(!k||!Ut)return;gt(!0),it("");const be=await o(k.id,Ut);if(gt(!1),!be.ok){ut("error"),it(be.error||f("newSession.errorSaveWorkspace"));return}ut("info"),it(f("newSession.workspaceSaved"))},[o,Ut,k,f]),Ho=c.useCallback(async()=>{if(!k)return;if(N==="mesh"){if(!I||!H)return;Be(!0),it(""),bt(null);const Fe=await d(k.id,I,H,{initialModel:z.trim()?z.trim():null,initialThinkingLevel:X.trim()?X.trim():null,...Mh(te,Ce),settings:Mn});if(Be(!1),!Fe.ok){if(Fe.code==="mesh_coordinator_manual_mcp_setup_required"&&Fe.manualSetup){bt(Fe.manualSetup),ut("info"),it(f("newSession.errorManualMcpSetup"));return}ut("error"),it(Fe.error||f("newSession.errorStartMeshCoordinator"));return}la(Bc,{machineId:k.id,mode:"mesh"}),la(Th,{meshId:I,cliType:H,model:z.trim(),thinkingLevel:X.trim(),autoApproveModeId:ke}),s();return}if(!O||!H)return;Be(!0),it("");const be=K.trim()?K.trim().split(/\s+/).filter(Boolean):[],He=O==="ide"?await a(k.id,H,{workspacePath:Ut||null}):await i(k.id,O,H,{workspaceId:C!=="__home__"&&C!=="__custom__"?C:null,workspacePath:C==="__custom__"&&Ut||null,useHome:C==="__home__",resumeSessionId:O==="cli"&&xe?xe:null,cliArgs:be,initialModel:z.trim()?z.trim():null,initialThinkingLevel:X.trim()?X.trim():null,...Mh(te,Ce),settings:Mn});if(Be(!1),!He.ok){ut("error"),it(He.code==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"?f("newSession.errorWorkspaceContextRequired"):He.error||f("newSession.errorStartSession"));return}O!=="ide"&&K.trim()&&(fR(k.id,H,K),qn(k.id,H)),la(Bc,{machineId:k.id,mode:"workspace"}),la(Ah,{workspaceChoice:C,customWorkspacePath:C==="__custom__"?Ut:"",kind:O,target:H,model:O==="ide"?"":z.trim(),thinkingLevel:O==="ide"?"":X.trim(),autoApproveModeId:O==="cli"?ke:""}),s()},[O,K,z,X,te,Ce,Mn,qn,s,a,d,i,Ut,ke,k,I,xe,H,C,N,f]),Or=O==="cli"&&!!xe,Bo=f(N==="mesh"?"newSession.startMeshCoordinator":O==="cli"?Or?"newSession.resumeSavedHistory":"newSession.startFresh":O==="ide"?"newSession.startIde":"newSession.start"),Wo=f(N==="mesh"?"newSession.startingCoordinator":O==="cli"?Or?"newSession.resumingSavedHistory":"newSession.startingFresh":O==="ide"?"newSession.startingIde":"newSession.starting"),Uo=g.length>5;return k?n.jsxs(n.Fragment,{children:[n.jsxs(Sr,{chrome:!1,onClose:s,closeOnBackdrop:!1,closeOnEsc:!1,ariaLabelledBy:"dashboard-new-title",overlayClassName:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",surfaceClassName:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[n.jsx("div",{className:"min-w-0",children:n.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:f("newSession.title")})}),n.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:s,"aria-label":f("newSession.close"),children:n.jsx(Lt,{size:16})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[g.length>1&&n.jsx(kR,{machines:g,selectedMachineId:k.id,useDropdown:Uo,busy:Ne,onSelect:A,onPrefetch:Kn}),n.jsxs(qs,{title:f("newSession.workspace"),action:N==="workspace"?n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Dr,disabled:Ne,children:f("newSession.browse")}):void 0,children:[n.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":f("newSession.launchTargetType"),children:[{id:"workspace",label:f("newSession.modeWorkspace"),desc:f("newSession.modeWorkspaceDesc")},{id:"mesh",label:f("newSession.modeMesh"),desc:f("newSession.modeMeshDesc")}].map(be=>n.jsxs("button",{type:"button",role:"radio","aria-checked":N===be.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${N===be.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{j(be.id),it(""),be.id==="mesh"&&k&&q!==k.id&&!L&&In(k.id)},disabled:Ne,children:[n.jsx("div",{className:"text-sm font-semibold",children:be.label}),n.jsx("div",{className:"mt-0.5 text-2xs opacity-80",children:be.desc})]},be.id))}),N==="workspace"?n.jsxs(n.Fragment,{children:[n.jsxs("select",{value:C,onChange:be=>{const He=be.target.value;Je.current=null,E(He),He==="__custom__"?Dr():it("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Ne,children:[n.jsx("option",{value:"__home__",children:f("newSession.homeDirectory")}),w.map(be=>n.jsxs("option",{value:be.id,children:[be.id===y?"★ ":"",va(be.path,be.label)||be.path]},be.id)),n.jsx("option",{value:"__custom__",children:f("newSession.customFolder")})]}),n.jsx("div",{className:"mt-2 text-2xs text-text-muted break-all",children:C==="__home__"?f("newSession.launchWithoutWorkspace"):Ut||f("newSession.selectWorkspaceFolder")}),jt&&n.jsx(iu,{inline:!0,title:f("newSession.selectWorkspaceTitle"),description:"",currentPath:ie,directories:Te,busy:Ye,error:Pe,onClose:()=>ee(!1),onNavigate:Zi,onConfirm:be=>{T(be),ve(be),E("__custom__"),ee(!1)}}),!jt&&C==="__custom__"&&Ut&&n.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[n.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Dr,disabled:Ne,children:[n.jsx(Ws,{size:14}),f("newSession.selectFolder")]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ec,disabled:Ne||At,children:f(At?"newSession.saving":"newSession.saveWorkspace")})]})]}):n.jsx(jR,{loading:L,error:W,meshes:M,selectedMeshId:I,busy:Ne,onSelect:be=>{xt.current=null,D(be)}})]}),n.jsx(NR,{targets:Ge,activeKind:O,selectedTarget:H,showCategory:N!=="mesh",busy:Ne,onSelect:be=>{st.current=null,Nt.current=null,Wt.current=null,B(be.kind),U(be.id)}}),N==="mesh"&&vn&&n.jsx(wR,{setup:vn,providerName:(Me==null?void 0:Me.displayName)||(Me==null?void 0:Me.name)||H}),(N==="mesh"&&!!H||N!=="mesh"&&O!=="ide")&&n.jsxs("details",{className:"group rounded-xl border border-border-subtle bg-bg-primary","data-testid":"new-session-advanced",children:[n.jsxs("summary",{className:"flex cursor-pointer select-none list-none items-center gap-2 px-4 py-3 [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"inline-block text-text-muted transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),n.jsx("span",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted",children:f("newSession.advancedOptions")}),Lr&&n.jsx("span",{className:"ml-auto min-w-0 truncate text-2xs text-text-secondary","data-testid":"new-session-advanced-summary",children:Lr})]}),n.jsxs("div",{className:"space-y-3 px-3 pb-3",children:[N!=="mesh"&&O!=="ide"&&n.jsx(CR,{value:K,recentOptions:we,busy:Ne,onChange:oe}),(N==="mesh"&&!!H||N!=="mesh"&&O==="cli")&&n.jsx(qs,{title:f("newSession.autoApproveMode"),description:ot?f("newSession.autoApproveModeDescription"):void 0,children:ot?n.jsx(hx,{config:ot,selectedModeId:ke,disabled:Ne,onSelectMode:Xt}):n.jsx(ER,{checked:ge,disabled:Ne,onChange:J})}),(N==="mesh"&&!!H||N!=="mesh"&&O!=="ide")&&n.jsx(_R,{modelOptions:mt,thinkingOptions:Yt,model:z,thinkingLevel:X,modelIsCustom:Oe,busy:Ne,onModelIsCustomChange:De,onModelChange:be=>pe(be,"user"),onThinkingChange:be=>Re(be,"user")})]})]}),N!=="mesh"&&O==="cli"&&n.jsx(vR,{busy:Ne,savedSessionsLoading:se,savedSessionsError:Y,savedSessionsLoaded:re,savedSessionsCount:ae.length,selectedSession:Qi,historyOpen:fe,onOpenHistory:()=>{if(!(!k||!H)){if(fe){Ie(!1);return}Ie(!0),xR({hasLoadedInitialResults:re,isLoading:se})&&ss(k.id,H)}},onClearSelection:()=>Z("")}),N!=="mesh"&&O==="cli"&&fe&&n.jsx(gR,{sessions:ae,loading:se,busy:Ne,resumingSessionId:Ke,fallbackWorkspacePath:Ut||null,onRefresh:()=>{!k||!H||ss(k.id,H)},onClose:()=>Ie(!1),onResume:Ji}),$e&&n.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${dt==="info"?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:$e})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[n.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:s,disabled:Ne,children:f("common.cancel")}),n.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:Ho,disabled:Ne||(N==="mesh"?!I||!H||O!=="cli"||L:!O||!H||C==="__custom__"&&!Ut),children:[n.jsx(Up,{size:14}),Ne?Wo:Bo]})]})]}),ne&&n.jsx(px,{mode:ne,onConfirm:()=>{de(ne.id),le(null)},onCancel:()=>le(null)})]}):null}function DR(e,t){const{sendCommand:s}=wt(),[r,o]=c.useState(null),[a,i]=c.useState(!1),l=c.useRef(0);c.useEffect(()=>{const u=l.current+1;if(l.current=u,o(null),!e||!t){i(!1);return}return i(!0),s(e,"git_remote_url",{workspace:t}).then(m=>{if(l.current!==u)return;const h=(m==null?void 0:m.result)??m;o(typeof(h==null?void 0:h.remoteUrl)=="string"?h.remoteUrl:null)}).catch(()=>{l.current===u&&o(null)}).finally(()=>{l.current===u&&i(!1)}),()=>{l.current+=1}},[e,t,s]);const d=OR(r);return{remoteUrl:r,githubUrl:d,loading:a}}function OR(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const s=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return s?`https://github.com/${s[1]}`:null}const fx=5e3;function $R(e,t){return t?`git:${t}:${e}`:`git:${e}`}function FR({workspace:e,daemonId:t,includeDiffSummary:s=!1,intervalMs:r=fx}){return{type:"subscribe",topic:"workspace.git",key:$R(e,t),params:{workspace:e,includeDiffSummary:s,intervalMs:r}}}function uu(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function zs(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const s=e;if(typeof s.error=="string"&&s.error.trim())return s.error;if(typeof s.message=="string"&&s.message.trim())return s.message}return t}function HR(e){const t=uu(e);return(t==null?void 0:t.success)===!1?{status:null,error:zs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:zs(t,"Git status response did not include status")}}function BR(e){const t=uu(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:zs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:zs(t,"Git diff summary response did not include diffSummary")}}function Wc(e){return e===void 0||typeof e=="boolean"}function WR(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Wc(t.binary)&&Wc(t.truncated)&&Wc(t.staged)}function UR(e){const t=uu(e);return(t==null?void 0:t.success)===!1?{diff:null,error:zs(t,"Git file diff request failed")}:WR(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:zs(t,"Git file diff response did not include a valid diff object")}}function KR({daemonId:e,workspace:t,enabled:s=!0,includeDiffSummary:r=!1,intervalMs:o=fx}){const{sendCommand:a,sendData:i}=wt(),l=typeof t=="string"?t.trim():"",d=!!(s&&e&&l),[u,m]=c.useState(null),[h,p]=c.useState(null),[b,f]=c.useState(!1),[x,g]=c.useState(null),v=c.useRef(0),S=c.useCallback(async()=>{if(!d||!e||!l)return;const k=v.current+1;v.current=k,f(!0),g(null);try{const w=HR(await a(e,"git_status",{workspace:l}));if(v.current!==k)return;if(w.error){m(null),p(null),g(w.error);return}if(m(w.status),!r){p(null);return}const y=BR(await a(e,"git_diff_summary",{workspace:l}));if(v.current!==k)return;if(y.error){p(null),g(y.error);return}p(y.diffSummary)}catch(w){if(v.current!==k)return;g(zs(w,"Git status request failed"))}finally{v.current===k&&f(!1)}},[d,e,r,a,l]),A=c.useMemo(()=>l?FR({workspace:l,daemonId:e,includeDiffSummary:r,intervalMs:o}):null,[e,r,o,l]);return c.useEffect(()=>{if(v.current+=1,m(null),p(null),f(!1),g(null),!d||!e||!l||!A)return;const k=i?Fn.subscribe({sendData:i},e,A,w=>{var y,N;w.workspace===l&&(m(w.status),p(w.diffSummary??null),g(((y=w.status)==null?void 0:y.error)||((N=w.diffSummary)==null?void 0:N.error)||null),f(!1))},{retryIntervalMs:1e3}):null;return S(),()=>{v.current+=1,k==null||k()}},[d,e,S,A,i,l]),{status:u,diffSummary:h,loading:b,error:x,refresh:S}}const qR={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},zR={added:"text-status-online",modified:"text-orange-400",deleted:"text-status-error",renamed:"text-accent-primary",copied:"text-accent-primary",untracked:"text-text-muted",conflict:"text-status-error font-bold"};function Rh(e){return e.split("/").pop()??e}function VR(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function GR({files:e,truncated:t,onFileClick:s,selectedPath:r,className:o=""}){const{t:a}=he("common");return e.length===0?n.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:a("git.changeList.noChanges")}):n.jsxs("div",{className:`flex flex-col ${o}`,children:[n.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(i=>{const l=r===i.path,d=qR[i.status]??"?",u=zR[i.status]??"text-text-muted",m=VR(i.path),h=Rh(i.path),p=i.staged?n.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-status-online align-middle",title:a("git.changeList.stagedHint")}):null;return n.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${l?"bg-surface-elevated":""}`,onClick:()=>s==null?void 0:s(i),children:[n.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${u}`,title:i.status,children:d}),n.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&n.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),n.jsx("span",{className:"text-text-primary",children:h}),i.oldPath&&n.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Rh(i.oldPath)]}),p]}),!i.binary&&(i.insertions>0||i.deletions>0)&&n.jsxs("span",{className:"shrink-0 font-mono text-3xs",children:[i.insertions>0&&n.jsxs("span",{className:"text-status-online",children:["+",i.insertions]}),i.insertions>0&&i.deletions>0&&n.jsx("span",{className:"text-text-secondary",children:" "}),i.deletions>0&&n.jsxs("span",{className:"text-status-error",children:["-",i.deletions]})]}),i.binary&&n.jsx("span",{className:"shrink-0 text-3xs text-text-secondary",children:a("git.changeList.binaryBadge")})]},`${i.path}-${i.staged?"S":"U"}`)})}),t&&n.jsx("p",{className:"px-3 py-1.5 text-3xs text-text-secondary",children:n.jsx(Da,{i18nKey:"git.changeList.truncatedNote",ns:"common",components:{code:n.jsx("code",{className:"font-mono"})}})})]})}function YR(e,t){let s="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?s="bg-status-online/10 text-status-online":e.startsWith("-")&&!e.startsWith("---")?s="bg-status-error/10 text-status-error":e.startsWith("@@")?s="text-accent-primary":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(s="text-text-secondary"),n.jsx("div",{className:`px-3 ${s}`,children:n.jsx("code",{className:"whitespace-pre font-mono text-2xs leading-5",children:e})},t)}function QR({diff:e,binary:t,truncated:s,loading:r,error:o,className:a=""}){const{t:i}=he("common"),l=c.useRef(null);if(c.useEffect(()=>{l.current&&(l.current.scrollTop=0)},[e]),r)return n.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${a}`,children:i("git.diffPreview.loading")});if(o)return n.jsx("div",{className:`px-3 py-4 text-xs text-status-error ${a}`,children:o});if(t)return n.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${a}`,children:i("git.diffPreview.binary")});if(!e)return n.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${a}`,children:i("git.diffPreview.empty")});const d=e.split(`
|
|
80
|
+
`);return n.jsxs("div",{ref:l,className:`overflow-auto ${a}`,children:[n.jsx("div",{className:"py-1",children:d.map((u,m)=>YR(u,m))}),s&&n.jsxs("p",{className:"px-3 py-1.5 text-3xs text-text-secondary border-t border-border/30",children:[i("git.diffPreview.truncatedBefore")," ",n.jsx("code",{className:"font-mono",children:"git diff"})," ",i("git.diffPreview.truncatedAfter")]})]})}function JR(e,t){const s=[`Branch: ${e||"unknown"}`];s.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const r={};for(const o of t.files)r[o.status]||(r[o.status]=[]),r[o.status].push(o.path);for(const[o,a]of Object.entries(r))s.push(`${o}: ${a.slice(0,5).join(", ")}${a.length>5?` (+${a.length-5} more)`:""}`);return s.join(`
|
|
81
|
+
`)}function bx({daemonId:e,workspace:t,onClose:s}){const{t:r}=he("common"),{sendCommand:o}=wt(),{status:a,diffSummary:i,loading:l,error:d,refresh:u}=KR({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,h]=c.useState(null),[p,b]=c.useState(null),[f,x]=c.useState(""),[g,v]=c.useState(!1),[S,A]=c.useState(!1),[k,w]=c.useState(null),[y,N]=c.useState(null),{githubUrl:j}=DR(e,t),C=c.useCallback(async I=>{if(!((m==null?void 0:m.path)===I.path&&!m.loading)){h({path:I.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const D=await o(e,"git_diff_file",{workspace:t,path:I.path,staged:I.staged}),L=UR(D);if(L.error||!L.diff){h({path:I.path,diff:"",binary:!1,truncated:!1,loading:!1,error:L.error??"Failed to load diff"});return}h({path:I.path,diff:L.diff.diff,binary:L.diff.binary??!1,truncated:L.diff.truncated??!1,loading:!1,error:null})}catch(D){const L=D instanceof Error?D.message:"Failed to load diff";h({path:I.path,diff:"",binary:!1,truncated:!1,loading:!1,error:L})}}},[e,o,m,t]),E=c.useCallback(I=>{x(""),v(!1),w(null),N(null),b(I)},[]),P=c.useCallback(()=>{b(null),w(null),A(!1)},[]),T=c.useCallback(async()=>{var I,D,L;if(p){A(!0),w(null);try{let $;p==="checkpoint"?$=await o(e,"git_checkpoint",{workspace:t,message:f,includeUntracked:g}):p==="stash"?$=await o(e,"git_stash_push",{workspace:t,message:f,includeUntracked:g}):p==="stash_pop"?$=await o(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&m&&($=await o(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const q=($==null?void 0:$.result)??$;if((q==null?void 0:q.success)===!1||q!=null&&q.error){w((q==null?void 0:q.error)??"Action failed"),A(!1);return}p==="checkpoint"?N(`Checkpoint created: ${((D=(I=q==null?void 0:q.checkpoint)==null?void 0:I.commit)==null?void 0:D.slice(0,7))??"done"}`):p==="stash"?N(`Stashed as ${((L=q==null?void 0:q.stash)==null?void 0:L.stashRef)??"stash@{0}"}`):p==="stash_pop"?N("Stash restored"):(N("File reverted"),h(null)),b(null),await u()}catch($){w($ instanceof Error?$.message:"Action failed")}finally{A(!1)}}},[p,o,e,t,f,g,m,u]),M=!!(a!=null&&a.hasConflicts);c.useEffect(()=>{const I=D=>{D.key==="Escape"&&(p?P():s())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[p,P,s]);const _=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return n.jsx(Un,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",onClick:I=>{I.target===I.currentTarget&&s()},children:n.jsxs("div",{className:"relative flex h-[80dvh] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-2rem)] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[n.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[n.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??r("git.statusDialog.title")}),n.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),j&&n.jsx("a",{href:`${j}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-3xs text-text-secondary hover:text-accent-primary underline",title:r("git.statusDialog.openOnGithub"),children:"GitHub ↗"})]}),n.jsx("button",{onClick:u,disabled:l,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:r("git.statusDialog.refresh"),children:"↺"}),n.jsx("button",{type:"button",onClick:s,className:"-m-1.5 flex h-11 w-11 shrink-0 items-center justify-center rounded text-text-secondary hover:text-text-primary","aria-label":r("common.close"),children:n.jsx(Lt,{className:"h-4 w-4"})})]}),a&&n.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&n.jsxs("span",{title:a.headMessage??void 0,children:[n.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&n.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&n.jsxs("span",{className:"text-orange-400",children:["↑",r("git.statusDialog.ahead",{count:a.ahead})]}),a.behind>0&&n.jsxs("span",{className:"text-orange-400",children:["↓",r("git.statusDialog.behind",{count:a.behind})]}),a.staged>0&&n.jsx("span",{className:"text-status-online",children:r("git.statusDialog.staged",{count:a.staged})}),a.modified>0&&n.jsx("span",{children:r("git.statusDialog.modified",{count:a.modified})}),a.untracked>0&&n.jsx("span",{children:r("git.statusDialog.untracked",{count:a.untracked})}),a.deleted>0&&n.jsx("span",{className:"text-status-error",children:r("git.statusDialog.deleted",{count:a.deleted})}),a.stashCount>0&&n.jsx("span",{children:r("git.statusDialog.stashed",{count:a.stashCount})}),a.hasConflicts&&n.jsx("span",{className:"font-bold text-status-error",children:r("git.statusDialog.conflicts")}),_===0&&!a.error&&n.jsx("span",{className:"text-status-online",children:r("git.statusDialog.clean")}),i&&i.files.length>0&&n.jsxs("span",{className:"text-text-secondary",children:[r("git.statusDialog.fileCount",{count:i.files.length}),i.totalInsertions>0&&n.jsxs("span",{className:"text-status-online",children:[" +",i.totalInsertions]}),i.totalDeletions>0&&n.jsxs("span",{className:"text-status-error",children:[" -",i.totalDeletions]})]})]}),d&&n.jsx("div",{className:"shrink-0 border-b border-border/50 bg-status-error/10 px-4 py-2 text-xs text-status-error",children:d}),n.jsxs("div",{className:"flex min-h-0 flex-1",children:[n.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[l&&!i&&n.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:r("git.statusDialog.loading")}),i&&n.jsx(GR,{files:i.files,truncated:i.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:C}),!l&&!i&&!d&&n.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:r("git.statusDialog.noDiffData")})]}),n.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?n.jsx(QR,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):n.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:r("git.statusDialog.selectFile")})})]}),y&&n.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-status-online/10 px-4 py-2 text-xs text-status-online flex items-center justify-between",children:[n.jsx("span",{children:y}),n.jsx("button",{onClick:()=>N(null),className:"ml-2 text-status-online hover:text-text-primary",children:"×"})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[n.jsx("button",{onClick:()=>E("checkpoint"),disabled:M,title:r(M?"git.statusDialog.resolveBeforeCheckpoint":"git.statusDialog.checkpointHint"),className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:r("git.statusDialog.checkpoint")}),n.jsx("button",{onClick:()=>E("stash"),disabled:M,title:r(M?"git.statusDialog.resolveBeforeStash":"git.statusDialog.stashHint"),className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:r("git.statusDialog.stash")}),n.jsx("button",{onClick:()=>E("stash_pop"),disabled:M||!(a!=null&&a.stashCount),title:M?r("git.statusDialog.resolveBeforePop"):a!=null&&a.stashCount?r("git.statusDialog.popHint"):r("git.statusDialog.noStashes"),className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:r("git.statusDialog.popStash")}),n.jsx("button",{onClick:()=>E("checkout_files"),disabled:!m,title:m?r("git.statusDialog.revertFile",{path:m.path}):r("git.statusDialog.selectFileToRevert"),className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:r("git.statusDialog.checkoutSelected")}),i&&i.files.length>0&&n.jsx("button",{onClick:()=>{const I=JR((a==null?void 0:a.branch)??null,i);navigator.clipboard.writeText(I),N(r("git.statusDialog.copied")),setTimeout(()=>N(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:r("git.statusDialog.copySummary")})]}),p&&n.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:n.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[n.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[p==="checkpoint"&&r("git.statusDialog.confirmCheckpoint"),p==="stash"&&r("git.statusDialog.confirmStash"),p==="stash_pop"&&r("git.statusDialog.confirmPop"),p==="checkout_files"&&r("git.statusDialog.confirmRevert",{path:(m==null?void 0:m.path)??r("git.statusDialog.fileFallback")})]}),(p==="checkpoint"||p==="stash")&&n.jsxs(n.Fragment,{children:[n.jsx("input",{type:"text",value:f,onChange:I=>x(I.target.value),maxLength:200,placeholder:r("git.statusDialog.messageRequired"),className:"rounded border border-border bg-surface-secondary px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),n.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:g,onChange:I=>v(I.target.checked)}),r("git.statusDialog.includeUntracked")]})]}),k&&n.jsx("p",{className:"text-xs text-status-error",children:k}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{onClick:P,disabled:S,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:r("common.cancel")}),n.jsx("button",{onClick:T,disabled:S||(p==="checkpoint"||p==="stash")&&!f.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:r(S?"git.statusDialog.working":"common.confirm")})]})]})})]})})})}function XR({isMobile:e,showMobileChatMode:t,visibleConversationCount:s}){const[r,o]=c.useState(!1),[a,i]=c.useState(!1),[l,d]=c.useState(!1),[u,m]=c.useState(!1),[h,p]=c.useState(!1),[b,f]=c.useState("quickstart"),[x,g]=c.useState("workspace"),v=c.useMemo(()=>!t&&!e,[t,e]),S=c.useCallback(j=>{o(j),j&&i(!1)},[]),A=c.useCallback(j=>{i(j),j&&o(!1)},[]),k=c.useCallback(()=>{f(s===0?"quickstart":"shortcuts"),g("workspace"),d(!0),o(!1),i(!1)},[s]),w=c.useCallback(()=>{d(!1)},[]),y=c.useCallback(()=>{m(!0)},[]),N=c.useCallback(()=>{m(!1)},[]);return c.useEffect(()=>{if(!v){p(!1);return}p(!0);const j=window.setTimeout(()=>{p(!1)},1e4);return()=>window.clearTimeout(j)},[v]),{inboxOpen:r,hiddenOpen:a,shortcutHelpOpen:l,newSessionOpen:u,guideNudgeVisible:h,guideTab:b,shortcutSection:x,isDesktopDashboard:v,setGuideTab:f,setShortcutSection:g,handleInboxOpenChange:S,handleHiddenOpenChange:A,handleOpenShortcutHelp:k,closeShortcutHelp:w,openNewSession:y,closeNewSession:N}}function ed(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function ZR(e,t,s,r,o){if(!e.length)return"";const a=String(o||"");if(a){const d=e.find(u=>en(u.id,a));return d?d.id:a}const i=t.find(d=>d.role==="host"),l=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(l){const d=e.find(u=>en(u.id,l));if(d)return d.id}return""}function Do(e,t){var l;if(t.length===1&&((l=t[0])!=null&&l.id))return t[0].id;if(!e)return"";const s=ed(e.meshHost),r=Array.isArray(e.nodes)?e.nodes:[],o=(s.hostNodeId?r.find(d=>String(d.id)===s.hostNodeId):void 0)??r.find(d=>d.role==="host"),a=s.hostDaemonId||String((o==null?void 0:o.daemon_id)||(o==null?void 0:o.daemonId)||"");if(!a)return"";const i=t.find(d=>en(d.id,a));return i?i.id:a}function gx(e,t){const s=[],r=new Map;for(const o of e)for(const a of o.meshes)a!=null&&a.id&&(r.has(a.id)||(r.set(a.id,[]),s.push(a.id)),r.get(a.id).push({daemonId:o.daemonId,mesh:a}));return s.map(o=>{const a=r.get(o),i=a.map(d=>Do(d.mesh,t)).find(Boolean)||"";return((i?a.find(d=>en(d.daemonId,i)):void 0)??a[0]).mesh})}async function eP(e,t,s){const r=new Array(e.length);let o=0;const a=()=>gx(r.filter(i=>!!i),e);return await Promise.all(e.map(async(i,l)=>{try{r[l]=await t(i)}catch{}o+=1,s==null||s({merged:a(),settled:o,total:e.length})})),a()}function tP(e,t){const s=new Map(t.map(a=>[a.id,a])),r=new Set,o=e.map(a=>(r.add(a.id),s.get(a.id)??a));for(const a of t)r.has(a.id)||o.push(a);return o}const Qr=new Map;async function xx(e){var o,a,i,l,d,u,m,h,p,b,f;const{sendCommand:t,unwrapResult:s}=e,r={meshCreated:!1,meshId:"",error:null,warning:null,plan:null};try{const x=e.reusablePlan??s(await t(e.targetDaemonId,"plan_mesh_onboarding",{workspace:e.workspace||void 0,operation:"auto",meshInventory:e.meshInventory}));if(r.plan=x,(x==null?void 0:x.success)===!1)return{...r,error:`${x.code||"onboarding_blocked"}: ${x.error}${x.action?` ${x.action}`:""}`};if(((o=x==null?void 0:x.plan)==null?void 0:o.kind)!=="create_mesh_and_onboard")return{...r,error:((a=x==null?void 0:x.plan)==null?void 0:a.summary)||"A compatible mesh already exists; add this workspace to it instead of creating a duplicate mesh."};const g={name:e.name.trim()};(e.repoRemoteUrl||(d=(l=(i=x==null?void 0:x.discovery)==null?void 0:i.origin)==null?void 0:l.urls)!=null&&d[0])&&(g.repoRemoteUrl=e.repoRemoteUrl||x.discovery.origin.urls[0]),(e.repoIdentity||(u=x==null?void 0:x.discovery)!=null&&u.repoIdentity)&&(g.repoIdentity=e.repoIdentity||x.discovery.repoIdentity),(m=x==null?void 0:x.discovery)!=null&&m.defaultBranch&&(g.defaultBranch=x.discovery.defaultBranch);const v=await t(e.targetDaemonId,"create_mesh",g),S=s(v);if((S==null?void 0:S.success)===!1)return{...r,error:S.error||"Create failed"};const A=typeof((h=S==null?void 0:S.mesh)==null?void 0:h.id)=="string"?S.mesh.id:"",k={...r,meshCreated:!0,meshId:A};if(!A||!e.attachWorkspace||!e.workspace)return k;try{const w=await t(e.targetDaemonId,"add_mesh_node",{meshId:A,daemonId:e.targetDaemonId,machineId:e.machineId,workspace:((p=x==null?void 0:x.discovery)==null?void 0:p.repoRoot)||e.workspace,repoRoot:(b=x==null?void 0:x.discovery)==null?void 0:b.repoRoot,isLocalWorktree:((f=x==null?void 0:x.discovery)==null?void 0:f.isLinkedWorktree)===!0,role:"host",providerPriority:e.providerPriority}),y=s(w);return(y==null?void 0:y.success)===!1?{...k,warning:Ph(y.error||"add_mesh_node failed")}:k}catch(w){return{...k,warning:Ph((w==null?void 0:w.message)||"add_mesh_node failed")}}}catch(x){return{...r,error:(x==null?void 0:x.message)||"Create failed"}}}function Ph(e){return`Mesh created, but attaching the workspace failed: ${e}. Add the workspace from the mesh's node list.`}function Uc(e,t){return e===t?!0:e.length!==t.length?!1:JSON.stringify(e)===JSON.stringify(t)}function yx({daemons:e,primaryDaemonId:t,sendCommand:s,unwrapResult:r,normalizeMesh:o,features:a,loadDaemonMetadata:i,confirmAction:l}){const d=e.map(ke=>ke.id).filter(Boolean).sort().join(","),[u,m]=c.useState(()=>Qr.get(d)??[]);c.useEffect(()=>{Va(u)},[u]);const[h,p]=c.useState(null),[b,f]=c.useState(()=>!Qr.has(d)),[x,g]=c.useState(null),[v,S]=c.useState(!1),[A,k]=c.useState(!1),[w,y]=c.useState(null),[N,j]=c.useState(""),[C,E]=c.useState(""),[P,T]=c.useState(""),[M,_]=c.useState(""),[I,D]=c.useState(""),[L,$]=c.useState(null),[q,G]=c.useState(!1),W=a.createDaemonPicker?M:t,R=c.useMemo(()=>e.find(ke=>ke.id===W),[e,W]),O=(R==null?void 0:R.workspaces)||[],B=c.useMemo(()=>Wn((R==null?void 0:R.availableProviders)||[]),[R]);c.useEffect(()=>{!i||!W||!R||!(!R.workspaces||!R.availableProviders)||Promise.resolve(i(W,{minFreshMs:3e4})).catch(()=>{})},[i,W,R]),c.useEffect(()=>{if(!v||!W||!I){$(null),G(!1);return}let ke=!1;return G(!0),s(W,"plan_mesh_onboarding",{workspace:I,operation:"auto",meshInventory:u}).then(de=>{if(ke)return;const ne=r(de);$(ne),ne!=null&&ne.success&&(E(le=>{var te;return le||((te=ne.discovery)==null?void 0:te.repoIdentity)||""}),T(le=>{var te,ce,Ce,Q,z,X;return le||((Ce=(ce=(te=ne.discovery)==null?void 0:te.origin)==null?void 0:ce.urls)==null?void 0:Ce[0])||((X=(z=(Q=ne.discovery)==null?void 0:Q.upstream)==null?void 0:z.urls)==null?void 0:X[0])||""}),j(le=>{var te,ce;return le||`${String(((te=ne.discovery)==null?void 0:te.repoIdentity)||((ce=ne.discovery)==null?void 0:ce.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(de=>{ke||$({success:!1,error:(de==null?void 0:de.message)||"Git discovery failed"})}).finally(()=>{ke||G(!1)}),()=>{ke=!0}},[v,W,I,u,s,r]);const H=c.useMemo(()=>e.map(ke=>ke.id).filter(Boolean).sort().join(","),[e]),U=c.useRef(0),K=c.useCallback(async(ke=!1)=>{const de=++U.current,ne=()=>U.current===de;if(a.createDaemonPicker?!H:!t){f(!0);return}const le=ke||Qr.has(H);f(te=>le?te:!0);try{if(a.createDaemonPicker){const te=await eP(e,async ce=>{if(!ce.id)return{daemonId:"",meshes:[]};const Ce=await s(ce.id,"list_meshes",{}),Q=r(Ce);if((Q==null?void 0:Q.success)===!1)throw new Error(Q.error||"Failed to load meshes");const z=(Array.isArray(Q==null?void 0:Q.meshes)?Q.meshes:[]).map(X=>o(X,ce.id)).filter(X=>X.id);return{daemonId:ce.id,meshes:z}},({merged:ce,settled:Ce,total:Q})=>{!ne()||Ce>=Q||ce.length!==0&&(m(z=>{const X=le?tP(z,ce):ce;return Uc(z,X)?z:X}),f(!1))});if(!ne())return;m(ce=>Uc(ce,te)?ce:te),Qr.set(H,te),g(null)}else{const te=await s(t,"list_meshes");if(!ne())return;if(te!=null&&te.success){const ce=(te.meshes||[]).map(Ce=>o(Ce,t));m(Ce=>Uc(Ce,ce)?Ce:ce),Qr.set(H,ce),g(null)}else g((te==null?void 0:te.error)||"Failed to load meshes")}}catch(te){ne()&&g((te==null?void 0:te.message)||"Failed to load meshes")}finally{ne()&&f(!1)}},[H,t,s,r,o,a.createDaemonPicker]);async function oe(){const ke=a.createDaemonPicker?M:t;if(!ke||!N.trim())return;const de=P.trim(),ne=C.trim(),le=I.trim();if(!(!le&&!de&&!ne)&&!A){k(!0),y(null);try{const te=await xx({targetDaemonId:ke,name:N,repoRemoteUrl:de,repoIdentity:ne,workspace:le,attachWorkspace:!!le,machineId:R==null?void 0:R.machineId,providerPriority:Ks(B),meshInventory:u,sendCommand:s,unwrapResult:r,reusablePlan:!q&&L?L:void 0});if(te.plan!==null&&$(te.plan),te.warning&&y(te.warning),!te.meshCreated){g(te.error||"Create failed");return}S(!1),j(""),E(""),T(""),D(""),await K(),te.meshId&&p(te.meshId)}finally{k(!1)}}}async function ge(ke){var te;const de=((te=u.find(ce=>ce.id===ke))==null?void 0:te.name)||ke;if(!(l?await l({title:"Delete this mesh?",description:`"${de}" will be removed from this daemon. This cannot be undone.`,confirmLabel:"Delete",tone:"danger"}):confirm("Delete this mesh? This cannot be undone.")))return;const le=Do(u.find(ce=>ce.id===ke),e)||(a.createDaemonPicker?"":t);if(!le){g(Qe.t("mesh.host.noCommandTarget"));return}try{const ce=await s(le,"delete_mesh",{meshId:ke}),Ce=r(ce);if((Ce==null?void 0:Ce.success)===!1)throw new Error(Ce.error||"Failed to delete");h===ke&&p(null),await K()}catch(ce){g((ce==null?void 0:ce.message)||"Delete failed")}}function J(){S(!1),j(""),E(""),T(""),D(""),$(null),y(null)}return{meshes:u,setMeshes:m,selectedMeshId:h,setSelectedMeshId:p,loading:b,error:x,setError:g,showCreate:v,setShowCreate:S,creating:A,createWarning:w,setCreateWarning:y,createName:N,setCreateName:j,createRepoIdentity:C,setCreateRepoIdentity:E,createRepoRemoteUrl:P,setCreateRepoRemoteUrl:T,newMeshDaemonId:M,setNewMeshDaemonId:_,newMeshWorkspace:I,setNewMeshWorkspace:D,createPickerWorkspaces:O,createPickerProviders:B,createOnboardingPlan:L,createPlanLoading:q,loadMeshes:K,handleCreate:oe,handleDelete:ge,cancelCreate:J}}function vx(e){const t=String(e.status||"").toLowerCase();return t!=="offline"&&t!=="disconnected"}async function nP(e,t){const s=e.filter(i=>!!(i!=null&&i.id)),r=e.filter(i=>!!(i!=null&&i.id)&&vx(i)),o=await Promise.all(r.map(async i=>{try{const l=await t(i.id,"list_meshes",{}),d=l!=null&&l.result&&typeof l.result=="object"&&!Array.isArray(l.result)?l.result:l;if((d==null?void 0:d.success)===!1)return null;const u=(Array.isArray(d==null?void 0:d.meshes)?d.meshes:[]).filter(m=>m&&typeof m.id=="string"&&m.id);return{daemonId:i.id,meshes:u}}catch{return null}})),a=gx(o.filter(i=>!!i),s);return Q1(a.map(i=>Do(i,s)),e)}function sP(e,t,s){const[r,o]=c.useState(null),a=c.useMemo(()=>e.filter(d=>!!(d!=null&&d.id)&&vx(d)).map(d=>d.id).sort().join("|"),[e]),i=c.useRef(e);i.current=e;const l=c.useRef(t);return l.current=t,c.useEffect(()=>{if(!s||!a||(r==null?void 0:r.key)===a)return;let d=!1;return nP(i.current,l.current).then(u=>{d||o({key:a,counts:u})}),()=>{d=!0}},[s,a,r==null?void 0:r.key]),(r==null?void 0:r.counts)??null}function rP({machineEntries:e,conversations:t,sendDaemonCommand:s}){const[r,o]=c.useState(!1),[a,i]=c.useState(null),[l,d]=c.useState(()=>Z1()),u=c.useRef(!1),m=sP(e,s,!qb(t)),h=c.useMemo(()=>X1(e,l,m),[e,l,m]),p=h.defaultTarget,b=tA(t,p),f=c.useCallback(async x=>{const g=x||p;if(!(!g||u.current)){x&&(eA(x),d({...x})),u.current=!0,o(!0),i(null);try{const v=await s(g.machineId,z1,Y1(g)),S=(v==null?void 0:v.result)||v;((v==null?void 0:v.success)===!1||(S==null?void 0:S.success)===!1)&&i(String((S==null?void 0:S.error)||(v==null?void 0:v.error)||(S==null?void 0:S.code)||"launch_assistant failed"))}catch(v){i(v instanceof Error?v.message:String(v))}finally{u.current=!1,o(!1)}}},[s,p]);return{visible:b,pending:r,error:a,defaultTarget:p,machines:h.machines,start:f}}function oP(e){switch(e.id){case"triggerPrimaryApprovalAction":case"triggerSecondaryApprovalAction":case"triggerTertiaryApprovalAction":return"approvals";case"splitActiveTabRight":case"splitActiveTabDown":case"focusLeftPane":case"focusRightPane":case"focusUpPane":case"focusDownPane":case"moveActiveTabToLeftPane":case"moveActiveTabToRightPane":case"moveActiveTabToUpPane":case"moveActiveTabToDownPane":return"panes";default:return"workspace"}}function aP(e){return e instanceof Error?e.message:String(e||"")}function iP(e){const t=aP(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function cP({showMobileChatMode:e,isMobile:t,activeConv:s,wsStatus:r,isConnected:o,onOpenHistory:a,onOpenRemote:i,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:u,mobileChatConversations:m,hiddenConversations:h,ides:p,actionLogs:b,sendDaemonCommand:f,setActionLogs:x,setCliViewModeOverrides:g,isStandalone:v,initialDataLoaded:S,userName:A,requestedMobileTabKey:k,onRequestedMobileTabConsumed:w,requestedMachineId:y,onRequestedMachineConsumed:N,requestedNewSessionLaunch:j,onRequestedNewSessionLaunchConsumed:C,requestedMobileSection:E,onRequestedMobileSectionConsumed:P,containerRef:T,isSplitMode:M,numGroups:_,groupSizes:I,groupedConvs:D,clearedTabs:L,focusedGroup:$,focusGroup:q,moveTabToGroup:G,splitTabRelative:W,closeGroup:R,handleResizeStart:O,groupActiveTabIds:B,setGroupActiveTab:H,groupTabOrders:U,setGroupTabOrder:K,toggleHiddenTab:oe,visibleConversations:ge,requestedDesktopTabKey:J,onRequestedDesktopTabConsumed:ke,onDesktopActiveTabChange:de,onRequestScrollToBottom:ne,onHideConversation:le,onShowHiddenConversation:te,onShowAllHiddenConversations:ce,scrollToBottomRequest:Ce,machineEntries:Q,layoutProfile:z,onBrowseMachineDirectory:X,onSaveMachineWorkspace:pe,onLaunchMachineIde:Re,onLaunchMachineProvider:Oe,onListMachineMeshes:De,onLaunchMeshCoordinator:we,onListMachineSavedSessions:V,notifications:xe,notificationUnreadCount:Z,liveSessionInboxState:ae,onMarkNotificationRead:F,onMarkNotificationUnread:se,onDeleteNotification:me}){const{t:re}=he(),Se=yt.useRef(null),{inboxOpen:Y,hiddenOpen:ue,shortcutHelpOpen:fe,newSessionOpen:Ie,guideNudgeVisible:Ke,guideTab:_e,shortcutSection:Ne,isDesktopDashboard:Be,setGuideTab:$e,setShortcutSection:it,handleInboxOpenChange:dt,handleHiddenOpenChange:ut,handleOpenShortcutHelp:It,closeShortcutHelp:bt,openNewSession:jt,closeNewSession:ee}=XR({isMobile:t,showMobileChatMode:e,visibleConversationCount:ge.length}),[ie,ve]=yt.useState(null);yt.useEffect(()=>{j&&(ve({machineId:j.machineId,workspaceId:j.workspaceId??null,mode:j.mode||"workspace",meshWorkspacePath:j.meshWorkspacePath??null}),jt(),C==null||C())},[j,jt,C]);const Te=yt.useCallback(()=>{ve(null),ee()},[ee]),{confirm:Ee,confirmDialog:Ye}=Tr(),[qe,Pe]=yt.useState(null),[tt,At]=yt.useState(null),gt=yt.useCallback((Me,We)=>{Pe({daemonId:Me,workspace:We})},[]),ye=yt.useCallback(Me=>{At(Me)},[]),Ae=yt.useCallback(Me=>{var We;An.flushSync(()=>{te(Me)}),(We=Se.current)==null||We.restoreHiddenTabToSavedLocation(Me.tabKey)},[te]),Le=yt.useCallback(Me=>{var ot;const We=m.find(St=>no(St,Me))||h.find(St=>no(St,Me));We&&(h.some(St=>St.tabKey===We.tabKey)&&Ae(We),de(We.tabKey),(ot=Se.current)==null||ot.activateConversationTab(We.tabKey),ne(We.tabKey,"notification-open")),F(Me.id),dt(!1)},[Ae,h,m,de,F,ne]);yt.useEffect(()=>$A(Me=>{var St;const We=[{sessionId:Me.sessionId},...Me.providerSessionId?[{providerSessionId:Me.providerSessionId}]:[]];let ot;for(const zt of We)if(ot=m.find(mt=>no(mt,zt))||h.find(mt=>no(mt,zt)),ot)break;if(!ot){nt.showToast(re("sessionNav.chatNotFound"),"info");return}h.some(zt=>zt.tabKey===ot.tabKey)&&Ae(ot),At(null),de(ot.tabKey),(St=Se.current)==null||St.activateConversationTab(ot.tabKey),ne(ot.tabKey,"conversation-open")}),[Ae,h,m,de,ne,re]);const Ve=yt.useCallback(async()=>{var We;await Ee({title:re("common.confirmTitle"),description:re("dashboard.hidden.resetPanelsConfirm"),confirmLabel:re("common.confirm")})&&((We=Se.current)==null||We.resetAllPanelsToMain(),ut(!1))},[Ee,ut,re]),Je=yt.useCallback(async Me=>{var mt;if(!s)return;const We=(mt=s.modalButtons)==null?void 0:mt[Me];if(!We)return;const ot=ps(s);if(!ot)return;const St=We.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),zt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(St);try{await f(ot,"resolve_action",{button:We,action:zt?"approve":"reject",buttonIndex:Me,...gs(s)})}catch(Yt){iP(Yt)||console.error("[Shortcut approval] Failed:",Yt)}},[s,f]),{isMac:ht,actionDefinitions:st,actionShortcuts:Nt,shortcutListening:xt,shortcutListeningDraft:Wt,setShortcutListening:Jt,setShortcutListeningDraft:an,saveShortcuts:qt}=$M({enabled:Be&&!fe,onTrigger:Me=>{var We,ot,St,zt,mt,Yt,Tn,vn,In,Xt,Mn,ss,qn,Ut,js,rs;if(Me==="openShortcutHelp"){It();return}if(Me==="openNewSession"){jt();return}if(Me==="hideCurrentTab"){s&&le(s);return}if(Me==="toggleHiddenTabs"){ut(!ue);return}if(Me==="openHistoryForActiveTab"){s&&a(s);return}if(Me==="openRemoteForActiveTab"){s&&!ft(s)&&i(s);return}if(Me==="splitActiveTabRight"){(We=Se.current)==null||We.splitActiveTabRight();return}if(Me==="splitActiveTabDown"){(ot=Se.current)==null||ot.splitActiveTabDown();return}if(Me==="floatActiveTab"){(St=Se.current)==null||St.floatActiveTab();return}if(Me==="popoutActiveTab"){(zt=Se.current)==null||zt.popoutActiveTab();return}if(Me==="dockActiveTab"){(mt=Se.current)==null||mt.dockActiveTab();return}if(Me==="focusLeftPane"){(Yt=Se.current)==null||Yt.focusLeftPane();return}if(Me==="focusRightPane"){(Tn=Se.current)==null||Tn.focusRightPane();return}if(Me==="focusUpPane"){(vn=Se.current)==null||vn.focusUpPane();return}if(Me==="focusDownPane"){(In=Se.current)==null||In.focusDownPane();return}if(Me==="moveActiveTabToLeftPane"){(Xt=Se.current)==null||Xt.moveActiveTabToLeftPane();return}if(Me==="moveActiveTabToRightPane"){(Mn=Se.current)==null||Mn.moveActiveTabToRightPane();return}if(Me==="moveActiveTabToUpPane"){(ss=Se.current)==null||ss.moveActiveTabToUpPane();return}if(Me==="moveActiveTabToDownPane"){(qn=Se.current)==null||qn.moveActiveTabToDownPane();return}if(Me==="triggerPrimaryApprovalAction"){Je(0);return}if(Me==="triggerSecondaryApprovalAction"){Je(1);return}if(Me==="triggerTertiaryApprovalAction"){Je(2);return}if(Me==="setActiveTabShortcut"){(Ut=Se.current)==null||Ut.setShortcutForActiveTab();return}if(Me==="selectPreviousGroupTab"){(js=Se.current)==null||js.activatePreviousTabInGroup();return}if(Me==="selectNextGroupTab"){(rs=Se.current)==null||rs.activateNextTabInGroup();return}!s||!ft(s)||Me==="toggleCliView"&&u(d==="chat"?"terminal":"chat")}}),Tt=yt.useCallback(()=>{bt(),Jt(null),an([])},[bt,Jt,an]),cn=yt.useMemo(()=>Ne==="all"?st:st.filter(Me=>oP(Me)===Ne),[st,Ne]),Kn=yt.useMemo(()=>[pt("triggerPrimaryApprovalAction",ht),pt("triggerSecondaryApprovalAction",ht),pt("triggerTertiaryApprovalAction",ht)].filter(Boolean).join(" / "),[ht]),Ct=ht?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",ln=yt.useCallback(()=>{const Me=Object.fromEntries(st.map(We=>[We.id,""]));qt(Me)},[st,qt]),fn=yt.useCallback(async()=>{if(!await Ee({title:re("common.confirmTitle"),description:re("dashboard.guide.shortcuts.resetConfirm"),confirmLabel:re("common.confirm")}))return;const We=Object.fromEntries(st.map(ot=>[ot.id,ot.defaultShortcut]));qt(We)},[st,Ee,qt,re]);yt.useEffect(()=>{const Me=We=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?We.metaKey&&We.key.toLowerCase()==="w":We.ctrlKey&&We.key.toLowerCase()==="w")&&(We.preventDefault(),s&&le&&le(s))};return window.addEventListener("keydown",Me),()=>window.removeEventListener("keydown",Me)},[s,le]),yt.useEffect(()=>{if(!fe||xt)return;const Me=We=>{We.key==="Escape"&&(We.preventDefault(),Tt())};return window.addEventListener("keydown",Me,!0),()=>window.removeEventListener("keydown",Me,!0)},[Tt,fe,xt]);const Ge=yt.useMemo(()=>[...ge,...h],[ge,h]),lt=rP({machineEntries:Q,conversations:Ge,sendDaemonCommand:f});return n.jsxs(n.Fragment,{children:[!e&&n.jsx(iT,{activeConv:s,wsStatus:r,isConnected:o,conversations:ge,hiddenConversations:h,onOpenHistory:a,onHideConversation:le,onShowConversation:Ae,onShowAllHidden:ce,onResetPanelsToMain:Ve,notifications:xe,notificationUnreadCount:Z,onOpenNotification:Le,onMarkNotificationRead:F,onMarkNotificationUnread:se,onDeleteNotification:me,inboxOpen:Y,onInboxOpenChange:dt,hiddenOpen:ue,onHiddenOpenChange:ut,onOpenNewSession:t?void 0:jt,onStartAssistant:lt.visible?()=>{lt.start()}:void 0,startAssistantPending:lt.pending,startAssistantError:lt.error,onStartAssistantWith:lt.visible?Me=>{lt.start(Me)}:void 0,startAssistantMachines:lt.machines,startAssistantDefault:lt.defaultTarget,onOpenDashboardGuide:It,guideNudgeVisible:Ke,actionShortcuts:Nt,onOpenRemote:()=>{!s||ft(s)||i(s)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:u,onOpenGitDialog:gt,onOpenMeshGraph:ye}),e?n.jsx(CM,{conversations:m,hiddenConversations:h,ides:p,actionLogs:b,sendDaemonCommand:f,setActionLogs:x,setCliViewModeOverrides:g,isStandalone:v,userName:A,requestedActiveTabKey:k,onRequestedActiveTabConsumed:w,requestedMachineId:y,onRequestedMachineConsumed:N,requestedMobileSection:E,onRequestedMobileSectionConsumed:P,onOpenHistory:a,onOpenRemote:i,onStopCli:l,wsStatus:r,isConnected:o,initialDataLoaded:S,onShowAllHiddenConversations:ce,onHideConversation:le,onShowHiddenConversation:Ae,onOpenMeshGraph:ye,onOpenNewSession:jt,liveSessionInboxState:ae}):t?n.jsx(EM,{containerRef:T,isSplitMode:M,numGroups:_,groupSizes:I,groupedConvs:D,clearedTabs:L,ides:p,actionLogs:b,sendDaemonCommand:f,setActionLogs:x,isStandalone:v,hasRegisteredMachines:Q.length>0,initialDataLoaded:S,userName:A,focusedGroup:$,focusGroup:q,moveTabToGroup:G,splitTabRelative:W,closeGroup:R,handleResizeStart:O,groupActiveTabIds:B,setGroupActiveTab:H,groupTabOrders:U,setGroupTabOrder:K,toggleHiddenTab:oe,onOpenNewSession:jt,allowTabShortcuts:!1,liveSessionInboxState:ae}):n.jsx(dR,{visibleConversations:ge,clearedTabs:L,ides:p,actionLogs:b,sendDaemonCommand:f,setActionLogs:x,isStandalone:v,hasRegisteredMachines:Q.length>0,initialDataLoaded:S,userName:A,toggleHiddenTab:oe,actionShortcuts:Nt,registerActionHandlers:Me=>{Se.current=Me},onActiveTabChange:de,requestedActiveTabKey:J,onRequestedActiveTabConsumed:ke,onRequestScrollToBottom:ne,scrollToBottomRequest:Ce,onOpenNewSession:jt,liveSessionInboxState:ae,layoutProfile:z}),Ie&&n.jsx(LR,{machines:Q,ides:p,initialMachineId:(ie==null?void 0:ie.machineId)||null,initialWorkspaceId:(ie==null?void 0:ie.workspaceId)||null,initialLaunchMode:(ie==null?void 0:ie.mode)||null,initialMeshWorkspacePath:(ie==null?void 0:ie.meshWorkspacePath)||null,onClose:Te,onBrowseDirectory:X,onSaveWorkspace:pe,onLaunchIde:Re,onLaunchProvider:Oe,onListMeshes:De,onLaunchMeshCoordinator:we,onListSavedSessions:V},ie?`${ie.machineId}:${ie.workspaceId||""}:${ie.mode||""}:${ie.meshWorkspacePath||""}`:"default"),tt&&n.jsx(qd,{activeConv:tt,sendDaemonCommand:f,onClose:()=>At(null)}),Ye,qe&&n.jsx(bx,{daemonId:qe.daemonId,workspace:qe.workspace,onClose:()=>Pe(null)}),fe&&n.jsxs(Sr,{chrome:!1,onClose:Tt,closeOnEsc:!1,ariaLabel:re("dashboard.guide.title"),overlayClassName:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50 backdrop-blur-[2px]",surfaceClassName:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",children:[n.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-bold text-text-primary",children:re("dashboard.guide.title")}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:re("dashboard.guide.subtitle")})]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Tt,"aria-label":re("dashboard.guide.close"),children:n.jsx(Lt,{size:14})})]}),n.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:re("dashboard.guide.tabs.overview")},{id:"quickstart",label:re("dashboard.guide.tabs.quickstart")},{id:"shortcuts",label:re("dashboard.guide.tabs.shortcuts")}].map(Me=>n.jsx("button",{type:"button",className:`btn btn-sm ${_e===Me.id?"btn-primary":"btn-secondary"}`,onClick:()=>$e(Me.id),children:Me.label},Me.id))}),_e==="overview"&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:re("dashboard.guide.overview.whatLivesWhere.title")}),n.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.whatLivesWhere.tabsLabel")})," ",re("dashboard.guide.overview.whatLivesWhere.tabsText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.whatLivesWhere.hiddenLabel")})," ",re("dashboard.guide.overview.whatLivesWhere.hiddenText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.whatLivesWhere.inboxLabel")})," ",re("dashboard.guide.overview.whatLivesWhere.inboxText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.whatLivesWhere.cliToggleLabel")})," ",re("dashboard.guide.overview.whatLivesWhere.cliToggleText")]})]})]}),n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.title")}),n.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.reviewLabel")})," ",re("dashboard.guide.overview.usefulFlows.reviewText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.clutterLabel")})," ",re("dashboard.guide.overview.usefulFlows.clutterText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.splitLabel")})," ",re("dashboard.guide.overview.usefulFlows.splitText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.detachedLabel")})," ",re("dashboard.guide.overview.usefulFlows.detachedText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.dockingLabel")})," ",re("dashboard.guide.overview.usefulFlows.dockingText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.perTabLabel")})," ",re("dashboard.guide.overview.usefulFlows.perTabText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:re("dashboard.guide.overview.usefulFlows.approvalLabel")})," ",re("dashboard.guide.overview.usefulFlows.approvalText",{keys:Kn})]})]})]})]}),_e==="quickstart"&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:re("dashboard.guide.quickstart.desktop.title")}),n.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," ",re("dashboard.guide.quickstart.desktop.step1")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," ",re("dashboard.guide.quickstart.desktop.step2")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," ",re("dashboard.guide.quickstart.desktop.step3")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," ",re("dashboard.guide.quickstart.desktop.step4")]})]})]}),n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:re("dashboard.guide.quickstart.mobile.title")}),n.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," ",re("dashboard.guide.quickstart.mobile.step1")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," ",re("dashboard.guide.quickstart.mobile.step2")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," ",re("dashboard.guide.quickstart.mobile.step3")]})]})]})]}),_e==="shortcuts"&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[n.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:re("dashboard.guide.shortcuts.sections.all")},{id:"workspace",label:re("dashboard.guide.shortcuts.sections.workspace")},{id:"panes",label:re("dashboard.guide.shortcuts.sections.panes")},{id:"approvals",label:re("dashboard.guide.shortcuts.sections.approvals")}].map(Me=>n.jsx("button",{type:"button",className:`btn btn-sm ${Ne===Me.id?"btn-primary":"btn-secondary"}`,onClick:()=>it(Me.id),children:Me.label},Me.id))}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ln,children:re("dashboard.guide.shortcuts.disableAll")}),n.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:fn,children:re("dashboard.guide.shortcuts.resetToDefaults")})]})]}),n.jsx("div",{className:"space-y-2",children:cn.map(Me=>n.jsx("div",{className:`rounded-xl border px-4 py-3 ${xt===Me.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:re(`dashboard.shortcutDefs.${Me.id}.label`,Me.label)}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:re(`dashboard.shortcutDefs.${Me.id}.description`,Me.description)}),n.jsxs("div",{className:"text-2xs text-text-muted mt-2",children:[re("dashboard.guide.shortcuts.default")," ",n.jsx("span",{className:"font-mono",children:Me.defaultShortcut})]})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[n.jsx("span",{className:"text-2xs font-mono px-2 py-1 rounded bg-surface-secondary border border-border-subtle min-w-[72px] text-center",children:xt===Me.id?Wt.length>0?`${Wt.join(" ")} ...`:re("dashboard.guide.shortcuts.listening"):Nt[Me.id]||re("dashboard.guide.shortcuts.off")}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Jt(Me.id),an([])},children:xt===Me.id?re("dashboard.guide.shortcuts.setListening"):re("dashboard.guide.shortcuts.set")}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const We={...Nt};We[Me.id]="",qt(We)},children:re("dashboard.guide.shortcuts.disable")})]})]})},Me.id))}),n.jsx("div",{className:"text-2xs text-text-muted mt-4",children:re("dashboard.guide.shortcuts.footer",{keys:Ct})})]})]})]})}function lP({hasExtensions:e,ideName:t,activeChatTab:s,extensionTabs:r,onSelectTab:o}){return e?n.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[n.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-2xs font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${s==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o("native"),children:t}),r.map(a=>{const i=s===a.tabKey,l=a.status==="waiting_approval",d=Us(a);return n.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-2xs font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${i?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o(a.tabKey),children:[n.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),a.title,l&&n.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-3xs font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},a.tabKey)})]}):null}function dP({ideData:e,allIdes:t,connectionStates:s,ideName:r,preferredTabKey:o}){const[a,i]=c.useState(()=>o||"native"),l=c.useMemo(()=>gg(t),[t]),d=c.useMemo(()=>e?Gd(e,{machineNames:l,connectionStates:s,defaultConnectionState:"new"}):[],[e,l,s]),u=c.useMemo(()=>d.find(x=>x.streamSource==="native"),[d]),m=c.useMemo(()=>d.filter(x=>x.streamSource==="agent-stream"),[d]),h=c.useMemo(()=>e?_n(d,e.id):null,[d,e]);c.useEffect(()=>{o&&i(o)},[o]),c.useEffect(()=>{if(o||!h)return;const x=h.streamSource==="native"?"native":h.tabKey;!x||a===x||a==="native"&&i(x)},[a,h,o]),c.useEffect(()=>{var x;a!=="native"&&(m.some(g=>g.tabKey===a)||i(((x=m[0])==null?void 0:x.tabKey)||"native"))},[a,m]),c.useEffect(()=>{a==="native"&&(u||m[0]&&i(m[0].tabKey))},[a,u,m]);const p=c.useMemo(()=>a==="native"&&u?u:m.find(x=>x.tabKey===a)||h||u||m[0],[a,u,h,m]),b=c.useMemo(()=>m.map(x=>({tabKey:x.tabKey,title:Db(x)||r,status:x.status})),[m,r]),f=c.useCallback(x=>{if(x)return d.find(g=>no(g,{sessionId:x,routeId:x,tabKey:x,providerSessionId:x}))},[d]);return{activeChatTab:a,setActiveChatTab:i,activeConv:p,conversations:d,extensionTabs:b,hasExtensions:b.length>0,resolveConversationByTarget:f}}function uP({activeConv:e,ideEntry:t,ides:s,connectionStates:r,actionLogs:o,sendDaemonCommand:a,setActionLogs:i,isStandalone:l,userName:d,onOpenHistory:u,onConversationChange:m,onClose:h,onRetryConnection:p}){const{t:b}=he("common"),[f,x]=c.useState("split"),[g,v]=c.useState(()=>bs(e)?"native":e.tabKey),S=c.useRef(null),A=c.useMemo(()=>t||s.find(W=>W.id===e.routeId),[e.routeId,t,s]),k=c.useMemo(()=>Ft((A==null?void 0:A.type)||""),[A==null?void 0:A.type]),{conversations:w,extensionTabs:y,hasExtensions:N}=dP({ideData:A,allIdes:s,connectionStates:r,ideName:k||"IDE",preferredTabKey:bs(e)?void 0:e.tabKey}),j=c.useMemo(()=>A?_n(w,A.id):null,[A,w]);c.useEffect(()=>{const W=S.current,R={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(S.current=R,!(W&&W.routeId===R.routeId&&W.tabKey===R.tabKey&&W.streamSource===R.streamSource)){if(bs(e)){v("native");return}v(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),c.useEffect(()=>{if(g==="native"){if(w.some(W=>W.streamSource==="native"))return;(j==null?void 0:j.streamSource)==="agent-stream"&&v(j.tabKey);return}if(!w.some(W=>W.tabKey===g)){if((j==null?void 0:j.streamSource)==="agent-stream"){v(j.tabKey);return}v("native")}},[w,g,j]);const C=c.useMemo(()=>g==="native"?w.find(W=>W.streamSource==="native")||e:w.find(W=>W.tabKey===g)||e,[e,w,g]),E=vs(C),P=Ei({sendDaemonCommand:a,activeConv:C,setActionLogs:i,isStandalone:l}),{connScreenshot:T,screenshotUsage:M,handleRemoteAction:_}=ix({doId:E,targetSessionId:ob(C),connState:C.connectionState||"new",viewMode:f}),I=c.useMemo(()=>o.filter(W=>W.routeId===C.tabKey),[o,C.tabKey]),D=C.tabKey,L=c.useCallback(W=>{i(R=>[...R,{routeId:D,text:W,timestamp:Date.now()}])},[D,i]),$=A==null?void 0:A.machineId,q=c.useMemo(()=>{if(!(!p||!$))return()=>p($)},[p,$]);c.useEffect(()=>{m==null||m(C)},[C,m]),c.useEffect(()=>{const W=R=>{R.key==="Escape"&&h()};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[h]);const G=c.useCallback(W=>{W.stopPropagation()},[]);return n.jsx(Un,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center p-0 md:p-3 bg-black/60 backdrop-blur-md",onClick:h,children:n.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:G,children:[n.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[n.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:n.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-lg md:text-xl tracking-tight text-text-primary",children:[n.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:n.jsx(Bn,{size:16})}),n.jsx("span",{className:"truncate",children:Rd(C)||b("dashboard.remoteDialog.remoteFallback")})]})}),n.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:b("common.close")})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[n.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(W=>{const R=f===W;return n.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${R?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>x(W),title:b(W==="split"?"dashboard.remoteDialog.splitView":"dashboard.remoteDialog.remoteOnly"),children:W==="split"?n.jsx(Rw,{size:15}):n.jsx(Bn,{size:15})},W)})}),n.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),n.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>u(C),title:b("dashboard.remoteDialog.history"),children:[n.jsx(Wp,{size:14,className:"md:mr-1.5"}),n.jsx("span",{className:"hidden md:inline",children:b("dashboard.remoteDialog.history")})]}),n.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:b("common.close")})]})]}),n.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[f!=="remote"&&n.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[n.jsx(lP,{hasExtensions:N,ideName:k||"IDE",activeChatTab:g,extensionTabs:y,onSelectTab:v}),n.jsx(_f,{activeConv:C,onModalButton:P.handleModalButton}),n.jsx(_b,{activeConv:C,ideEntry:A,showMetaChips:!1,handleSendChat:P.handleSendChat,handleSendNowQueued:P.handleSendNowQueued,handleCancelQueued:P.handleCancelQueued,isSendingChat:P.isSendingChat,sendFeedbackMessage:P.sendFeedbackMessage,pendingLocalMessage:P.pendingLocalMessage,pendingLocalMessages:P.pendingLocalMessages,retireEchoedPendingMessages:P.retireEchoedPendingMessages,handleFocusAgent:P.handleFocusAgent,isFocusingAgent:P.isFocusingAgent,actionLogs:I,userName:d})]}),n.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-1 md:order-2":""}`,children:n.jsx(gf,{addLog:L,connState:C.connectionState||"new",connScreenshot:T,screenshotUsage:M,transportType:C.transport,onAction:_,onRetry:q})})]})]})})})}function mP({activeConv:e,canSaveAndStop:t=!1,onCancel:s,onStopNow:r,onSaveAndStop:o}){const{t:a}=he(),i=x1(e);return n.jsx(Un,{children:n.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[n.jsx("div",{onClick:s,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),n.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[n.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[n.jsx("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:a("cliStop.title",{agent:i})}),n.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a(t?"cliStop.gracefulDescription":"cliStop.forceOnlyDescription")})]}),n.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&n.jsx("button",{onClick:o,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("cliStop.stop")}),n.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:a("cliStop.forceStop")}),n.jsx("button",{onClick:s,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})})}function hP({historyModal:e,remoteDialog:t,cliStopDialog:s,connectionBanner:r,toastOverlay:o,onboarding:a,interactivePrompt:i,suppressInteractivePrompt:l=!1}){var d;return n.jsxs(n.Fragment,{children:[!r.suppress&&n.jsx($1,{wsStatus:r.wsStatus,showReconnected:r.showReconnected,loginUrl:r.loginUrl,onReconnect:r.onReconnect}),e.open&&e.targetConv&&n.jsx(bT,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&n.jsx(uP,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose,onRetryConnection:t.onRetryConnection}),s.open&&s.targetConv&&ft(s.targetConv)&&n.jsx(mP,{activeConv:s.targetConv,canSaveAndStop:ft(s.targetConv)&&!!((d=s.targetConv.resume)!=null&&d.supported),onCancel:s.onCancel,onStopNow:s.onStopNow,onSaveAndStop:s.onSaveAndStop}),n.jsx(fg,{toasts:o.toasts,onDismiss:o.onDismiss,onClickToast:o.onClick}),!l&&n.jsx(Nd,{promptSession:(i==null?void 0:i.promptSession)??null,isSubmitting:(i==null?void 0:i.isSubmitting)??!1,error:(i==null?void 0:i.responseError)??null,onSubmit:(i==null?void 0:i.submit)??(async()=>{}),onCancel:(i==null?void 0:i.cancel)??(()=>{})}),a.open&&n.jsx($2,{onClose:a.onClose,standalone:a.standalone})]})}function pP({daemons:e,targetVersion:t,required:s=!1,upgradingDaemons:r,onUpgrade:o,onDismiss:a}){const{t:i}=he("common");return e.length===0?null:n.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:s?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:s?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[n.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:s?"var(--status-danger)":"var(--status-warning)"},children:n.jsx(Ar,{size:14})}),n.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[n.jsxs("span",{children:[i(s?"machine.daemonUpdate.requiredTitle":"dashboard.versionBanner.updateAvailable"),t?n.jsxs(n.Fragment,{children:[": ",n.jsxs("strong",{children:["v",t]})]}):null]}),e.map(l=>{const d=pn(l,{fallbackId:l.id}),u=r[l.id],m=l.version||l.daemonVersion||i("dashboard.versionBanner.unknownVersion"),h=l.versionUpdateRequired===!0,p=$g(l,{targetVersion:t,required:h},i);return n.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:h?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${h?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[n.jsx("span",{className:"font-medium text-text-primary",children:d}),n.jsxs("span",{className:"text-3xs text-text-muted",children:["v",m]}),h&&n.jsx("span",{className:"text-3xs",style:{color:"var(--status-danger)"},children:i("dashboard.versionBanner.required")}),u==="upgrading"?n.jsx("span",{className:"text-3xs animate-pulse",style:{color:h?"var(--status-danger)":"var(--status-warning)"},children:i("dashboard.versionBanner.upgrading")}):u==="done"?n.jsxs("span",{className:"text-3xs text-green-400",children:["✓ ",i("dashboard.versionBanner.restarting")]}):u==="error"?n.jsx("button",{className:"text-3xs text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>o(l.id),children:i("dashboard.versionBanner.retry")}):n.jsx("button",{className:"text-3xs font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:h?"var(--status-danger)":"var(--status-warning)",background:h?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${h?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(l.id),children:p})]},l.id)})]}),!s&&n.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:a,title:i("toast.dismiss"),children:n.jsx(Lt,{size:16})})]})}function fP(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function bP(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function gP(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>bP(t)).map(t=>t.id)}}function xP({suppressConnectionBanner:e=!1}={}){var Ho,Or,Bo,Wo,Uo;const{sendCommand:t}=wt(),s=Rr(),r=Tg(),o=pi(),a=Vs(),[i,l]=gp(),d=i.get("activeTab"),u=((Ho=o.state)==null?void 0:Ho.openRemoteForTabKey)||null,m=((Or=o.state)==null?void 0:Or.openMachineId)||null,h=((Bo=o.state)==null?void 0:Bo.openNewSession)||null,p=((Wo=o.state)==null?void 0:Wo.mobileSection)||null,b=Mi(),f=b.ides||[],x=b.initialLoaded??!0,{updateRouteChats:g,setToasts:v}=b,{hydrateInteractivePrompt:S}=br(),[A,k]=c.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}});c.useEffect(()=>{const Ze=()=>k(!1);return window.addEventListener(Yl,Ze),()=>window.removeEventListener(Yl,Ze)},[]);const w=b.toasts||[],y=b.wsStatus||"connected",N=b.isConnected??!0,j=b.connectionStates||{},C=b.showReconnected||!1,{layoutProfile:E,groupAssignments:P,updateGroupAssignments:T,focusedGroup:M,updateFocusedGroup:_,focusGroup:I,groupActiveTabIds:D,updateGroupActiveTabIds:L,setGroupActiveTab:$,groupTabOrders:q,updateGroupTabOrders:G,setGroupTabOrder:W,groupSizes:R,updateGroupSizes:O,isMobile:B,hasHydratedStoredLayout:H,hydrateStoredLayout:U,focusConversationTab:K}=fI(),[oe,ge]=c.useState(()=>Xd());c.useEffect(()=>v2(ge),[]);const J=c.useMemo(()=>fP({isMobile:B,mobileViewMode:oe}),[B,oe]),[ke,de]=c.useState([]),[ne,le]=c.useState({}),[te,ce]=c.useState({});Io("Dashboard",{ideCount:f.length,toastCount:w.length,focusedGroup:M,groupCount:Object.keys(P).length,actionLogCount:ke.length});const Ce=c.useMemo(()=>f.filter(Ze=>Ze.type==="adhdev-daemon").sort(Ua),[f]),z=!!Ce[0];c.useEffect(()=>{const{metadataDaemonIds:Ze,runtimeDaemonIds:Mt}=gP(Ce);for(const wn of Ze)s(wn,{minFreshMs:3e4}).catch(()=>{});for(const wn of Mt)r(wn,{minFreshMs:3e4}).catch(()=>{})},[s,r,Ce]);const X=c.useMemo(()=>B2(f,ne),[f,ne]),{conversations:pe,visibleConversations:Re,visibleTabKeys:Oe,resolveConversationBySessionId:De,resolveConversationByTarget:we}=eI({ides:X,connectionStates:j,clearedTabs:te}),V=c.useMemo(()=>new Map(pe.map(Ze=>[Ze.tabKey,Ze])),[pe]);k_(Re,J);const xe=c.useMemo(()=>Nf(f),[f]),Z=Yg(xe,t,c.useCallback(Ze=>lr(v,Ze),[v])),{notifications:ae,unreadCount:F}=RI({conversations:pe,liveSessionInboxState:xe}),{handleMarkDashboardNotificationRead:se,handleMarkDashboardNotificationUnread:me,handleDeleteDashboardNotification:re}=PI({notifications:ae,sendDaemonCommand:t}),{containerRef:Se,normalizedGroupAssignments:Y,numGroups:ue,isSplitMode:fe,groupedConvs:Ie,moveTabToGroup:Ke,closeGroup:_e,handleResizeStart:Ne,splitTabRelative:Be}=SI({groupAssignments:P,updateGroupAssignments:T,updateFocusedGroup:_,updateGroupActiveTabIds:L,updateGroupTabOrders:G,groupSizes:R,updateGroupSizes:O,isMobile:B,visibleConversations:Re,visibleTabKeys:Oe}),{activeConv:$e,openDesktopConversation:it,requestScrollToBottom:dt,scrollToBottomRequest:ut,setDesktopActiveTab:It}=GI({isMobile:B,conversations:pe,visibleConversations:Re,groupActiveTabIds:D,focusedGroup:M,groupedConvs:Ie,setSearchParams:l});JI({activeConv:$e,isMobile:B,liveSessionInboxState:xe,sendDaemonCommand:t});const{requestedDesktopTabKey:bt,requestedMobileTabKey:jt,consumeRequestedActiveTab:ee}=tI({isMobile:B,urlActiveTab:d,resolveConversationBySessionId:De,setSearchParams:l}),{remoteDialogConv:ie,remoteDialogIdeEntry:ve,remoteDialogActiveConv:Te,setRemoteDialogActiveConv:Ee,openRemoteDialog:Ye,closeRemoteDialog:qe,cliStopDialogOpen:Pe,cliStopTargetConv:tt,requestCliStop:At,cancelCliStop:gt,confirmCliStop:ye}=eM({isMobile:B,location:o,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:bt,conversations:pe,ides:f,resolveConversationByTarget:we,activeConv:$e,sendDaemonCommand:t}),{historyModalOpen:Ae,openHistoryModal:Le,closeHistoryModal:Ve,historyTargetConv:Je,isSavedSessionHistoryTarget:ht,isHistoryCreatingChat:st,isHistoryRefreshingHistory:Nt,handleHistorySwitchSession:xt,handleHistoryNewChat:Wt,handleHistoryRefresh:Jt,savedHistorySessions:an,savedHistoryFilters:qt,setSavedHistoryFilters:Tt,missingWorkspaceResumePath:cn,isSavedHistoryLoading:Kn,resumingSavedHistorySessionId:Ct,handleRefreshSavedHistory:ln,handleResumeSavedHistorySession:fn}=XI({activeConv:$e,remoteDialogConv:ie,remoteDialogActiveConv:Te,ides:f,sendDaemonCommand:t,updateRouteChats:g,setToasts:v,setClearedTabs:ce,setSearchParams:l}),Ge=c.useMemo(()=>Re,[Re]),lt=B&&oe==="chat",Me=c.useMemo(()=>pe.filter(Ze=>Dk(ys(Ze,xe))),[pe,xe]),We=c.useCallback(Ze=>{const Mt=new URLSearchParams(i);Mt.set("activeTab",Ze),l(Mt,{replace:!0})},[i,l]),{trackPendingLaunch:ot}=WI({ides:f,conversations:pe,onOpenSession:We}),{handleBrowseMachineDirectory:St,handleSaveMachineWorkspace:zt,handleLaunchMachineIde:mt,handleLaunchMachineProvider:Yt,handleListMachineMeshes:Tn,handleLaunchMeshCoordinator:vn,handleListMachineSavedSessions:In,setActiveCliViewMode:Xt}=qI({sendDaemonCommand:t,trackPendingLaunch:ot,onOpenSession:We,activeConv:$e,ides:f,setCliViewModeOverrides:le});U2({visibleConversations:Re,clearedTabs:te,setClearedTabs:ce,setActionLogs:de,isConversationMuted:Z.isMuted}),nI({ides:f,sendDaemonCommand:t,setToasts:v,resolveConversationByTarget:we,hydrateInteractivePrompt:S});const Mn=Ci(($e==null?void 0:$e.sessionId)??($e==null?void 0:$e.routeId)??null),{isRefreshingHistory:ss,handleRefreshHistory:qn}=Og({sendDaemonCommand:t,activeConv:$e,chats:(Uo=f.find(Ze=>Ze.id===($e==null?void 0:$e.routeId)))==null?void 0:Uo.chats,updateRouteChats:g,setToasts:v,setClearedTabs:ce});gI({urlActiveTab:B&&!lt?d:null,conversations:pe,resolveConversationBySessionId:De,normalizedGroupAssignments:Y,hasHydratedStoredLayout:B&&!lt?H:!0,hydrateStoredLayout:B&&!lt?U:()=>{},focusConversationTab:K,setSearchParams:l,historyModalOpen:Ae,activeConv:$e,isRefreshingHistory:ss,ides:f,handleRefreshHistory:qn});const Ut=c.useMemo(()=>!$e||!ft($e)?null:Mr($e),[$e]),{versionMismatchDaemons:js,hasRequiredVersionDaemons:rs,targetVersion:$o,versionBannerDismissed:Fo,setVersionBannerDismissed:Qi,upgradingDaemons:Ji,handleBannerUpgrade:Xi}=NI({ides:f,sendDaemonCommand:t}),Lr=c.useCallback(Ze=>{Z.setHidden(Ze,!1),it(Ze)},[it,Z]),Dr=c.useCallback(()=>{for(const Ze of Me)Z.setHidden(Ze,!1)},[Me,Z]),Zi=c.useCallback(Ze=>{Z.setHidden(Ze,!0)},[Z]),ec=c.useCallback(Ze=>{Z.toggleHidden(Ze)},[Z]);return n.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!Fo||rs)&&n.jsx(pP,{daemons:js,targetVersion:$o,required:rs,upgradingDaemons:Ji,onUpgrade:Xi,onDismiss:()=>Qi(!0)}),n.jsx(cP,{showMobileChatMode:lt,isMobile:B,activeConv:$e,wsStatus:y,isConnected:N,onOpenHistory:Ze=>{Ze&&Ee(Ze),Le()},onOpenRemote:Ye,onStopCli:At,activeCliViewMode:Ut,onSetActiveCliViewMode:Xt,mobileChatConversations:Ge,ides:f,actionLogs:ke,sendDaemonCommand:t,setActionLogs:de,setCliViewModeOverrides:le,isStandalone:z,initialDataLoaded:x,userName:b.userName,requestedMobileTabKey:jt,onRequestedMobileTabConsumed:ee,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(o.pathname+o.search,{replace:!0,state:null})},requestedNewSessionLaunch:h,onRequestedNewSessionLaunchConsumed:()=>{a(o.pathname+o.search,{replace:!0,state:null})},requestedMobileSection:p,onRequestedMobileSectionConsumed:()=>{a(o.pathname+o.search,{replace:!0,state:null})},containerRef:Se,isSplitMode:fe,numGroups:ue,groupSizes:R,groupedConvs:Ie,clearedTabs:te,focusedGroup:M,focusGroup:I,moveTabToGroup:Ke,splitTabRelative:Be,closeGroup:_e,handleResizeStart:Ne,groupActiveTabIds:D,setGroupActiveTab:$,groupTabOrders:q,setGroupTabOrder:W,toggleHiddenTab:Ze=>{const Mt=V.get(Ze);Mt&&ec(Mt)},visibleConversations:Re,hiddenConversations:Me,requestedDesktopTabKey:bt,onRequestedDesktopTabConsumed:ee,onDesktopActiveTabChange:It,onRequestScrollToBottom:dt,onHideConversation:Zi,onShowHiddenConversation:Lr,onShowAllHiddenConversations:Dr,scrollToBottomRequest:ut,machineEntries:Ce,layoutProfile:E,onBrowseMachineDirectory:St,onSaveMachineWorkspace:zt,onLaunchMachineIde:mt,onLaunchMachineProvider:Yt,onListMachineMeshes:Tn,onLaunchMeshCoordinator:vn,onListMachineSavedSessions:In,notifications:ae,notificationUnreadCount:F,liveSessionInboxState:xe,onMarkNotificationRead:se,onMarkNotificationUnread:me,onDeleteNotification:re}),n.jsx("style",{children:`
|
|
82
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
83
|
+
`}),n.jsx(hP,{historyModal:{open:Ae,targetConv:Je,ides:f,isCreatingChat:st,isRefreshingHistory:ht?!1:Nt,savedSessions:an,savedHistoryFilters:qt,missingWorkspaceResumePath:cn||null,onSavedHistoryFiltersChange:Tt,isSavedSessionsLoading:Kn,isResumingSavedSessionId:Ct,onClose:Ve,onNewChat:Wt,onSwitchSession:xt,onRefreshHistory:ht?ln:Jt,onResumeSavedSession:fn},remoteDialog:{conversation:ie,ideEntry:ve,ides:f,connectionStates:j,actionLogs:ke,sendDaemonCommand:t,setActionLogs:de,isStandalone:z,userName:b.userName,onOpenHistory:Ze=>{Ze&&Ee(Ze),Le()},onConversationChange:Ee,onClose:qe,onRetryConnection:b.retryConnection},cliStopDialog:{open:Pe,targetConv:tt,onCancel:gt,onStopNow:async()=>{await ye("hard")},onSaveAndStop:async()=>{await ye("save")}},connectionBanner:{wsStatus:y,showReconnected:C,loginUrl:b.connectionLoginUrl,onReconnect:b.retryServerConnection,suppress:e},toastOverlay:{toasts:w.filter(Ze=>{var Mt,wn,$r;return!((Mt=Ze.actions)!=null&&Mt.length&&Ze.targetKey&&((wn=$e==null?void 0:$e.modalButtons)!=null&&wn.length)&&(($r=we(Ze.targetKey))==null?void 0:$r.tabKey)===$e.tabKey)}),onDismiss:Ze=>v(Mt=>Mt.filter(wn=>wn.id!==Ze)),onClick:Ze=>{if(Ze.targetKey){const Mt=we(Ze.targetKey);Mt&&(K(Mt.tabKey,Y),Lr(Mt),dt(Mt.tabKey,"toast-open"))}}},onboarding:{open:A,standalone:z,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}k(!1)}},interactivePrompt:Mn,suppressInteractivePrompt:lt})]})}const yP=15e3;async function vP(e,t){let s;try{const r=await Promise.race([e,new Promise((o,a)=>{s=setTimeout(()=>a(new Error(t.timeoutMessage)),t.timeoutMs)})]);if(r&&r.success===!1)throw new Error(r.error||t.failedMessage)}finally{s&&clearTimeout(s)}}function wP({machineId:e,registeredMachineId:t,sendDaemonCommand:s,onNicknameSynced:r,logsEndRef:o}){const{t:a}=he("common"),{launchCli:i}=wi(),{confirm:l,confirmDialog:d}=Tr(),[u,m]=c.useState([]),[h,p]=c.useState(null),[b,f]=c.useState(null),[x,g]=c.useState(!1),[v,S]=c.useState(null),[A,k]=c.useState(!1),[w,y]=c.useState(""),N=c.useRef(null),j=c.useCallback(B=>{N.current=B},[]),C=c.useCallback((B,H,U=!1,K)=>{const oe=Id(K),ge=oe&&oe!==H?`${H} — ${oe}`:H;m(J=>[...J.slice(-100),{timestamp:Date.now(),level:B,message:ge}]),setTimeout(()=>{var J;return(J=o.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),U&&(B==="error"||B==="warn"?nt.showErrorToast(H,K):nt.showToast(H,"success"))},[o]),E=c.useCallback(B=>{const H=B instanceof Error?B.message:String(B||"");return H.includes("P2P command timeout")||H.includes("P2P not connected")||H.includes("P2P not available")},[]),P=c.useCallback(async(B,H)=>{var U;if(!e||h)return!1;p(B),C("info",a("machine.actions.launching",{name:Ft(B)}));try{const K={ideType:B,enableCdp:!0};(U=H==null?void 0:H.workspace)!=null&&U.trim()?K.workspace=H.workspace.trim():H!=null&&H.useDefaultWorkspace&&(K.useDefaultWorkspace=!0);const oe=await s(e,"launch_ide",K);return oe!=null&&oe.success?C("info",a("machine.actions.launched",{name:Ft(B)}),!0):C("error",a("machine.actions.launchFailed",{name:Ft(B)}),!0,oe==null?void 0:oe.error),!!(oe!=null&&oe.success)}catch(K){return C("error",a("machine.actions.launchFailed",{name:Ft(B)}),!0,K),!1}finally{p(null)}},[e,h,C,s,a]),T=c.useCallback(async B=>{if(!e)return{success:!1};const{cliType:H,dir:U,workspaceId:K,useDefaultWorkspace:oe,useHome:ge,argsStr:J,model:ke,resumeSessionId:de}=B;if(!H)return C("warn",a("machine.actions.selectProviderFirst"),!0),{success:!1};const ne=J?J.split(/\s+/).filter(Boolean):void 0,le=(U==null?void 0:U.trim())||(K?"(saved id)":oe?"(default workspace)":ge?"(home)":"");C("info",a("machine.actions.launching",{name:H}),!1,[le,ke].filter(Boolean).join(" · ")||void 0),f(H);try{const te={cliType:H,cliArgs:ne,initialModel:ke||void 0};U!=null&&U.trim()?te.dir=U.trim():K?te.workspaceId=K:oe?te.useDefaultWorkspace=!0:ge&&(te.useHome=!0),de&&(te.resumeSessionId=de);const ce=await i(e,te),Ce=(ce==null?void 0:ce.result)||ce;return ce!=null&&ce.success?(C("info",a("machine.actions.launched",{name:H}),!0),(Ce==null?void 0:Ce.launchSource)==="home"?C("info",a("machine.actions.runningInHome")):(Ce==null?void 0:Ce.launchSource)==="defaultWorkspace"&&C("info",a("machine.actions.usingDefaultWorkspace")),{success:!0,sessionId:Ce==null?void 0:Ce.sessionId}):(C("error",a("machine.actions.launchFailed",{name:H}),!0,(ce==null?void 0:ce.error)||(Ce==null?void 0:Ce.error)),(ce==null?void 0:ce.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&S({cliType:H,argsStr:J,model:ke}),{success:!1,sessionId:Ce==null?void 0:Ce.sessionId})}catch(te){return E(te)?(C("warn",a("machine.actions.launchPending",{name:H}),!0),{success:!1,pending:!0}):(C("error",a("machine.actions.launchFailed",{name:H}),!0,te),{success:!1})}finally{f(null)}},[e,C,E,s,a]),M=c.useCallback(async(B,H,U,K)=>e?B?H.trim()?T({cliType:B,dir:H,argsStr:U,model:K}):(S({cliType:B,argsStr:U,model:K}),{success:!1}):(C("warn",a("machine.actions.selectProvider"),!0),{success:!1}):{success:!1},[e,C,T,a]),_=c.useCallback(async(B,H,U)=>{if(e&&await l({title:a("cliStop.title",{agent:B}),description:a("machine.actions.stopCliConfirmDescription"),confirmLabel:a("cliStop.stop"),tone:"danger"}))try{const K=await s(e,"stop_cli",{cliType:B,dir:H,targetSessionId:U});K!=null&&K.success?C("info",a("machine.actions.stopped",{name:B}),!0):C("error",a("machine.actions.stopFailed"),!0,K==null?void 0:K.error)}catch(K){C("error",a("machine.actions.stopFailed"),!0,K)}},[e,C,l,s,a]),I=c.useCallback(async B=>{try{await s(B.daemonId,"restart_ide",{ideType:B.type}),C("info",a("machine.actions.restartInitiated",{name:Ft(B.type)}),!0)}catch(H){C("error",a("machine.actions.restartFailed"),!0,H)}},[C,s,a]),D=c.useCallback(async B=>{if(await l({title:a("cliStop.title",{agent:Ft(B.type)}),description:a("machine.actions.stopIdeConfirmDescription"),confirmLabel:a("cliStop.stop"),tone:"danger"}))try{const H=await s(B.daemonId,"stop_ide",{ideType:B.type,killProcess:!0});H!=null&&H.success?C("info",a("machine.actions.stopped",{name:Ft(B.type)}),!0):C("error",a("machine.actions.stopFailed"),!0,H==null?void 0:H.error)}catch(H){C("error",a("machine.actions.stopFailed"),!0,H)}},[C,l,s,a]),L=c.useCallback(async()=>{if(e)try{const B=await s(e,"detect_ides",{});C("info",a("machine.actions.idesFound",{count:((B==null?void 0:B.result)||[]).length}),!0)}catch(B){C("error",a("machine.actions.detectFailed"),!0,B)}},[e,C,s,a]),$=c.useCallback(async B=>{if(!e||!B.trim())return!1;g(!0);try{const H=await s(e,"workspace_add",{path:B.trim()});return H!=null&&H.success?(C("info",a("machine.actions.workspaceAdded"),!1,B.trim()),!0):(C("error",a("machine.actions.workspaceActionFailed"),!1,H==null?void 0:H.error),!1)}catch(H){return C("error",a("machine.actions.workspaceActionFailed"),!1,H),!1}finally{g(!1)}},[e,C,s,a]),q=c.useCallback(async B=>{if(e){g(!0);try{const H=await s(e,"workspace_remove",{id:B});H!=null&&H.success?C("info",a("machine.actions.workspaceRemoved"),!0):C("error",a("machine.actions.workspaceActionFailed"),!0,H==null?void 0:H.error)}catch(H){C("error",a("machine.actions.workspaceActionFailed"),!0,H)}finally{g(!1)}}},[e,C,s,a]),G=c.useCallback(async B=>{var H;if(e){g(!0);try{const U=await s(e,"workspace_set_default",B===null?{clear:!0}:{id:B});if(U!=null&&U.success){C("info",a(B?"machine.actions.defaultWorkspaceUpdated":"machine.actions.defaultWorkspaceCleared"),!0);const K=typeof U.defaultWorkspacePath=="string"?U.defaultWorkspacePath:"";K&&((H=N.current)==null||H.call(N,K))}else C("error",a("machine.actions.workspaceActionFailed"),!0,U==null?void 0:U.error)}catch(U){C("error",a("machine.actions.workspaceActionFailed"),!0,U)}finally{g(!1)}}},[e,C,s,a]),W=c.useCallback(async(B,H)=>{if(!e||!B.trim())return!1;g(!0);try{const U=await s(e,"workspace_set_label",{path:B.trim(),label:H});return U!=null&&U.success?(await s(e,"workspace_list",{}),C("info",a("machine.actions.workspaceLabelUpdated"),!0),!0):(C("error",a("machine.managedWorkspaces.renameFailed"),!0,U==null?void 0:U.error),!1)}catch(U){return C("error",a("machine.managedWorkspaces.renameFailed"),!0,U),!1}finally{g(!1)}},[e,C,s,a]),R=c.useCallback(async B=>{var U;if(!e||!B.trim())return;const H=B.trim();g(!0);try{const K=await s(e,"workspace_set_default",{path:H});K!=null&&K.success?(C("info",a("machine.actions.defaultWorkspaceUpdated")),(U=N.current)==null||U.call(N,H)):C("error",a("machine.actions.workspaceActionFailed"),!1,(K==null?void 0:K.error)||a("machine.actions.pathMissing"))}catch(K){C("error",a("machine.actions.workspaceActionFailed"),!1,K)}finally{g(!1)}},[e,C,s,a]),O=c.useCallback(async()=>{if(e)try{if(await vP(s(e,"set_machine_nickname",{nickname:w}),{timeoutMs:yP,timeoutMessage:a("machine.actions.nicknameTimeout"),failedMessage:a("machine.actions.nicknameFailed")}),r)try{await r({machineRuntimeId:e,registeredMachineId:t,nickname:w})}catch(B){C("warn",a("machine.actions.nicknameSyncFailed"),!1,B)}C("info",a("machine.actions.nicknameSaved")),k(!1)}catch(B){C("error",a("machine.actions.nicknameFailed"),!0,B)}},[e,w,t,C,r,s,a]);return{logs:u,launchingIde:h,launchingAgentType:b,workspaceBusy:x,launchPick:v,setLaunchPick:S,editingNickname:A,setEditingNickname:k,nicknameInput:w,setNicknameInput:y,addLog:C,handleLaunchIde:P,runLaunchCliCore:T,handleLaunchCli:M,handleStopCli:_,handleRestartIde:I,handleStopIde:D,handleDetectIdes:L,handleWorkspaceAdd:$,handleWorkspaceRemove:q,handleWorkspaceSetDefault:G,handleWorkspaceSetLabel:W,handleWorkspaceResumePath:R,handleSaveNickname:O,confirmDialog:d,setOnDefaultWorkspaceChanged:j}}const Eh={good:"bg-emerald-500/10 text-emerald-500",warn:"bg-amber-500/10 text-amber-500",danger:"bg-red-500/10 text-red-500",default:"bg-white/5 text-text-secondary",info:"bg-blue-500/10 text-blue-500"},SP={bucket:"machine.quota.bucketHint",session:"machine.quota.sessionHint",weekly:"machine.quota.weeklyHint",monthly:"machine.quota.monthlyHint",usage:"machine.quota.usageHint"};function Lh({label:e,tone:t,title:s}){return n.jsx("span",{title:s,className:`rounded-full px-2 py-0.5 text-3xs font-medium ${Eh[t]??Eh.default}`,children:e})}function kP({machine:e}){const{t}=he("common"),s=Ud(Wd(t)),r=ig(e.quota);return r.length===0?null:n.jsxs(hn,{padding:"lg",className:"mb-5",children:[n.jsx("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mb-3",children:t("machine.quota.title")}),n.jsx("div",{className:"flex flex-col gap-2",children:r.map(({provider:o,quota:a})=>{const i=s(a);return n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"text-xs text-text-primary min-w-[92px]",children:kr(o)}),cl(a)&&n.jsx("span",{className:"text-3xs text-text-secondary",title:t("machine.quota.accountHint"),children:cl(a)}),i.kind==="chips"&&i.chips.map(l=>n.jsx(Lh,{label:l.label,tone:l.tone,title:t(SP[l.hint])},l.key)),i.kind==="usage"&&n.jsx(Lh,{label:i.usageLabel,tone:"info",title:t("machine.quota.usageHint")}),i.kind==="okNoWindows"&&n.jsx("span",{className:"text-2xs text-text-secondary",title:t("machine.quota.okNoWindowsHint"),children:i.message??t("machine.quota.okNoWindows")}),i.kind==="failure"&&n.jsx("span",{className:"text-2xs text-text-secondary",title:t("machine.quota.failureHint"),children:i.message})]},o)})})]})}function Dh({title:e,defaultOpen:t=!1,testId:s,children:r}){const[o,a]=c.useState(t),[i,l]=c.useState(t);return n.jsxs("details",{className:"group rounded-xl border border-border-subtle bg-bg-glass",open:o,"data-testid":s,onToggle:d=>{const u=d.currentTarget.open;a(u),u&&l(!0)},children:[n.jsxs("summary",{className:"flex cursor-pointer select-none list-none items-center gap-2 px-4 py-3 text-sm font-semibold text-text-primary [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"inline-block text-text-muted transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),e]}),i&&n.jsx("div",{className:"px-4 pb-4",children:r()})]})}function jP({machine:e,ideSessions:t,cliSessions:s,daemonVersion:r,renderHostedRuntimes:o,renderLogs:a,initialDiagnostics:i=null}){var p,b;const{t:l}=he("common"),d=typeof e.uptime=="number"||typeof e.freeMem=="number"||typeof e.availableMem=="number"||Array.isArray(e.loadavg)&&e.loadavg.length>0,u=e.availableMem??e.freeMem??e.totalMem,m=d&&e.totalMem>0?Math.min(100,Math.max(0,Math.round((e.totalMem-u)/e.totalMem*100))):0,h=((p=e.loadavg)==null?void 0:p[0])||0;return n.jsxs("div",{children:[n.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[n.jsx(dc,{icon:n.jsx(fd,{size:16}),label:l("machine.overview.uptime"),value:typeof e.uptime=="number"?eN(e.uptime):l("machine.overview.waiting")}),n.jsx(dc,{icon:n.jsx(Bn,{size:16}),label:"IDEs",value:`${t.length}`}),n.jsx(dc,{icon:n.jsx(bd,{size:16}),label:"CLIs",value:`${s.length}`})]}),n.jsxs(hn,{padding:"lg",className:"mb-5",children:[n.jsx("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mb-3",children:l("machine.overview.resourceUsage")}),n.jsxs("div",{className:"flex gap-6",children:[n.jsx(zu,{value:d?Math.min(Math.round(h/e.cpus*100),100):0,max:100,label:l("machine.overview.cpuLoad"),color:"#8b5cf6",detail:d?l("machine.overview.cpuDetail",{load:h.toFixed(2),cores:e.cpus}):l("machine.overview.waitingForStats")}),n.jsx(zu,{value:m,max:100,label:l("machine.overview.memory"),color:"#3b82f6",detail:d?`${fc(e.totalMem-u)} / ${fc(e.totalMem)}${e.platform==="darwin"?` ${l("machine.overview.approx")}`:""}`:l("machine.overview.waitingForStatsWithTotal",{total:fc(e.totalMem)})})]})]}),n.jsx(kP,{machine:e}),n.jsxs(hn,{padding:"lg",className:"mb-5",children:[n.jsx("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mb-3",children:l("machine.overview.aboutMachine")}),n.jsxs("dl",{className:"grid grid-cols-1 gap-x-6 gap-y-2 text-xs sm:grid-cols-2","data-testid":"machine-about",children:[n.jsx(Jr,{label:l("machine.overview.hostname"),value:e.hostname}),n.jsx(Jr,{label:l("machine.overview.platform"),value:[Of[e.platform]||e.platform,e.arch].filter(Boolean).join(" · ")}),e.cpus>0&&n.jsx(Jr,{label:l("machine.overview.cores"),value:String(e.cpus)}),r&&n.jsx(Jr,{label:l("machine.overview.daemonVersion"),value:`v${r}`}),((b=e.p2p)==null?void 0:b.available)&&n.jsx(Jr,{label:l("machine.overview.p2p"),value:e.p2p.state==="connected"?l("machine.detail.p2pConnected"):e.p2p.state})]})]}),(o||a)&&n.jsxs("details",{className:"group mb-5","data-testid":"machine-diagnostics",open:i?!0:void 0,children:[n.jsxs("summary",{className:"mb-3 flex cursor-pointer select-none list-none items-center gap-2 text-2xs font-semibold uppercase tracking-wider text-text-muted [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"inline-block transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),l("machine.overview.diagnostics")]}),n.jsxs("div",{className:"flex flex-col gap-3",children:[o&&n.jsx(Dh,{title:l("machine.detail.tabHostedRuntimes"),defaultOpen:i==="hosted-runtimes",testId:"machine-diagnostics-hosted-runtimes",children:o}),a&&n.jsx(Dh,{title:l("machine.detail.tabLogs"),defaultOpen:i==="logs",testId:"machine-diagnostics-logs",children:a})]})]})]})}function Jr({label:e,value:t}){return t?n.jsxs("div",{className:"flex min-w-0 items-baseline justify-between gap-3 sm:justify-start",children:[n.jsx("dt",{className:"shrink-0 text-text-muted sm:w-28",children:e}),n.jsx("dd",{className:"m-0 min-w-0 truncate text-text-primary",children:t})]}):null}function wx(e){if(!e||typeof e!="object")return null;const t=e,s=t.result&&typeof t.result=="object"?t.result:t;return!s.settings||typeof s.settings!="object"?null:{settings:s.settings,values:s.values&&typeof s.values=="object"?s.values:{}}}function Sx(e,t,s){const r=[];for(const[o,a]of Object.entries(e.settings)){const i=s!=null&&s.filterSchema?s.filterSchema(a):a;if(i.length===0)continue;const l=t.find(d=>d.type===o);r.push({type:o,displayName:(l==null?void 0:l.displayName)||o,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:i,values:e.values[o]||{}})}return r}function Kc(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function Oh(e){if(!e||typeof e!="object")return null;if(Kc(e))return e;const t=e,s=t.result;return Kc(s)?s:Kc(t.sourceConfig)?t.sourceConfig:null}function NP(e){const t=e.trim();return t||null}function CP({providerType:e,displayName:t,supportsQuota:s,quotaInstallsClaudeStatusline:r,onCancel:o,onConfirm:a}){const{t:i}=he("common"),[l,d]=c.useState(!0),[u,m]=c.useState(!0);return n.jsx(Un,{children:n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:o,children:n.jsxs("div",{className:"w-[min(520px,92vw)] rounded-xl border border-border-default bg-surface-primary p-5 shadow-2xl",onClick:h=>h.stopPropagation(),role:"dialog","aria-modal":"true",children:[n.jsx("div",{className:"text-xxs font-semibold text-text-primary",children:i("machine.installOptions.title",{provider:t})}),n.jsxs("div",{className:"mt-4 flex flex-col gap-3",children:[s&&n.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5",children:[n.jsx("input",{type:"checkbox",checked:l,onChange:h=>d(h.target.checked),className:"mt-0.5 h-3.5 w-3.5 shrink-0 accent-accent-primary"}),n.jsx("span",{className:"min-w-0",children:n.jsxs("span",{className:"flex items-center gap-1 text-xs font-medium text-text-primary",children:[i("machine.installOptions.quotaLabel"),n.jsx(rt,{content:[i("machine.installOptions.quotaHint"),r&&l?i("machine.installOptions.quotaClaudeNote"):""].filter(Boolean).join(`
|
|
84
|
+
|
|
85
|
+
`),size:12})]})})]}),n.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5",children:[n.jsx("input",{type:"checkbox",checked:u,onChange:h=>m(h.target.checked),className:"mt-0.5 h-3.5 w-3.5 shrink-0 accent-accent-primary"}),n.jsxs("span",{className:"min-w-0",children:[n.jsx("span",{className:"block text-xs font-medium text-text-primary",children:i("machine.installOptions.autoApproveLabel")}),n.jsx("span",{className:"mt-0.5 block text-2xs text-text-muted",children:i("machine.installOptions.autoApproveHint")}),u&&n.jsx("span",{className:"mt-1 block text-2xs text-amber-400",children:i("machine.installOptions.autoApproveWarning")})]})]})]}),n.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[n.jsx("button",{onClick:o,className:"machine-btn text-2xs px-3 py-1",children:i("machine.installOptions.cancel")}),n.jsx("button",{onClick:()=>a({quotaEnabled:s?l:void 0,autoApprove:u}),className:"machine-btn text-2xs px-3 py-1 border-accent-primary/30 bg-accent-primary/15 text-accent-primary","data-provider-type":e,children:i("machine.installOptions.confirm")})]})]})})})}const $h={"user-custom":"machine.trustBadge.userCustom",trusted:"machine.trustBadge.trusted","trusted-with-scripts":"machine.trustBadge.trustedWithScripts","external-safe":"machine.trustBadge.externalSafe","external-untrusted":"machine.trustBadge.externalUntrusted"},Fh={"user-custom":"machine.trustBadge.userCustomHint",trusted:"machine.trustBadge.trustedHint","trusted-with-scripts":"machine.trustBadge.trustedWithScriptsHint","external-safe":"machine.trustBadge.externalSafeHint","external-untrusted":"machine.trustBadge.externalUntrustedHint"},_P={"user-custom":"bg-violet-500/[0.10] border-violet-500/25 text-violet-300",trusted:"bg-green-500/[0.10] border-green-500/25 text-green-400","trusted-with-scripts":"bg-emerald-500/[0.10] border-emerald-500/25 text-emerald-400","external-safe":"bg-sky-500/[0.10] border-sky-500/25 text-sky-400","external-untrusted":"bg-amber-500/[0.10] border-amber-500/30 text-amber-300"};function AP({trust:e,sourceName:t,description:s}){const{t:r}=he("common"),o=$h[e]?r($h[e]):e,a=t&&(e==="external-safe"||e==="external-untrusted")?`${o} · ${t}`:o,i=Fh[e]?r(Fh[e]):s;return n.jsx("span",{className:`text-3xs px-1.5 py-0.5 rounded border whitespace-nowrap ${_P[e]??""}`,title:i,children:a})}const TP={ide:{badge:"bg-blue-500/10 text-blue-300 border-blue-500/20",accent:"border-blue-500/[0.12]"},cli:{badge:"bg-indigo-500/10 text-indigo-300 border-indigo-500/20",accent:"border-indigo-500/[0.12]"},extension:{badge:"bg-teal-500/10 text-teal-300 border-teal-500/20",accent:"border-teal-500/[0.12]"}},IP=["enabled","autoApprove","executablePath","executableArgs","cliPathOverride","appPathOverride","approvalAlert","longGeneratingAlert","longGeneratingThresholdSec","showThinking","showToolCalls","showTerminal","showCoordinatorSystemPrompt","notifications"],MP=new Set(IP);function RP(e,t,s){if(!MP.has(t.key))return{label:t.label||t.key,description:t.description||""};const r={provider:s||e("machine.providerSettings.thisProvider")};return{label:e(`machine.providerSettings.${t.key}.label`,r),description:e(`machine.providerSettings.${t.key}.description`,r)}}function PP(e,t){const s=String(t??""),r=s.replace(/[-_]+/g," ").trim().replace(/^./,o=>o.toUpperCase());return/^[a-z0-9][a-z0-9_-]*$/i.test(s)?e(`machine.providerSettings.option.${s.toLowerCase()}`,{defaultValue:r||s}):r||s}function EP(e){if(typeof e!="string")return null;try{const t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?t.toString():null}catch{return null}}const Hh={detected:"bg-green-500/[0.10] border-green-500/25 text-green-400",not_detected:"bg-red-500/[0.10] border-red-500/25 text-red-400",enabled_unchecked:"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400",disabled:"bg-white/[0.04] border-white/[0.10] text-text-muted"},LP={bucket:"machine.quota.bucketHint",session:"machine.quota.sessionHint",weekly:"machine.quota.weeklyHint",monthly:"machine.quota.monthlyHint",usage:"machine.quota.usageHint"},DP={default:"bg-white/[0.04] border-white/[0.10] text-text-muted",good:"bg-green-500/[0.10] border-green-500/25 text-green-400",warn:"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400",danger:"bg-red-500/[0.10] border-red-500/25 text-red-400",info:"bg-sky-500/[0.10] border-sky-500/25 text-sky-300"};function Bh(e,t){if(!t)return"—";const s=t.ok?e("machine.providerRow.checkOk"):e("machine.providerRow.checkFailed"),r=t.message||t.path||t.command||"";return r?`${s} — ${r}`:s}const Wh={Stable:"machine.providerRow.lifecycleStable",Beta:"machine.providerRow.lifecycleBeta",Experimental:"machine.providerRow.lifecycleExperimental",Deprecated:"machine.providerRow.lifecycleDeprecated"};function OP(e){return e==="cli"}function qc({checked:e,busy:t,label:s,onToggle:r}){return n.jsx(Pr,{as:"span",size:"sm",checked:e,busy:t,"aria-label":s,onChange:()=>r()})}function $P({prov:e,quota:t,providerInfo:s,savingKey:r,onSetSetting:o,onEnableToggle:a,onDetect:i,onResetCommand:l,quotaAccountLabelEnabled:d,onQuotaAccountLabelToggle:u,quotaEnabled:m,onQuotaToggle:h,pin:p,onUpdate:b,updating:f,onRollbackUpdate:x,showAdvanced:g=!1}){var _;const[v,S]=c.useState(null),[A,k]=c.useState(!1),{t:w}=he("common"),y={detected:w("machine.providerRow.statusDetected"),not_detected:w("machine.providerRow.statusNotDetected"),enabled_unchecked:w("machine.providerRow.statusEnabledUnchecked"),disabled:w("machine.providerRow.statusDisabled")},[N,j]=c.useState(!1),C=(s==null?void 0:s.enabled)===!0||e.values.enabled===!0,E=s==null?void 0:s.machineStatus,P=C&&E==="disabled"?"enabled_unchecked":E||(C?"enabled_unchecked":"disabled"),T=OP(e.category),M=(()=>{if(!t)return null;const D=Ud(Wd(w))(t).compactChip;return D?{label:D.label,tone:DP[D.tone],title:w(LP[D.hint])}:null})();return n.jsxs(hn,{padding:"none",children:[n.jsxs("button",{onClick:()=>j(I=>!I),className:"w-full px-4 py-2.5 flex items-center gap-3 text-left",children:[n.jsx(Fi,{type:e.type,label:e.displayName,size:20,className:"shrink-0"}),n.jsx("span",{className:"text-xxs font-semibold text-text-primary truncate",children:e.displayName}),n.jsx("span",{className:`text-4xs font-semibold px-1.5 py-px rounded border ${((_=TP[e.category])==null?void 0:_.badge)??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(s==null?void 0:s.trust)&&n.jsx(AP,{trust:s.trust,sourceName:s.sourceName??null,description:s.trustDescription}),T&&n.jsx("span",{className:`text-4xs font-semibold px-1.5 py-px rounded border ${Hh[P]??Hh.disabled}`,children:y[P]??P}),n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[b&&(p==null?void 0:p.stale)&&p.latestVersion&&n.jsx("span",{role:"button",tabIndex:0,"aria-disabled":f?!0:void 0,title:w("machine.providerRow.updateInlineHint",{latest:p.latestVersion}),onClick:I=>{I.stopPropagation(),!f&&b()},onKeyDown:I=>{I.key!=="Enter"&&I.key!==" "||(I.preventDefault(),I.stopPropagation(),!f&&b())},className:`text-3xs font-semibold px-2 py-0.5 rounded-md border border-amber-500/30 text-amber-400 shrink-0 ${f?"opacity-60 cursor-wait":"cursor-pointer hover:bg-amber-500/15"}`,children:w(f?"machine.providerRow.specPinUpdating":"machine.providerRow.updateInline")}),M&&n.jsx("span",{className:`text-4xs font-semibold px-1.5 py-px rounded border shrink-0 ${M.tone}`,title:M.title,children:M.label}),T&&n.jsx(qc,{checked:C,busy:r===`${e.type}.enabled`,label:w(C?"machine.providerRow.disable":"machine.providerRow.enable"),onToggle:()=>{a(e.type,!C)}}),n.jsx("span",{className:"text-text-muted text-xs",children:N?"▾":"▸"})]})]}),N&&n.jsxs("div",{className:"border-t border-border-subtle px-4 py-3 flex flex-col gap-3",children:[e.schema.length>0&&n.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(I=>{const D=RP(w,I,e.displayName);return n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("div",{className:"flex-1 min-w-0",children:n.jsxs("div",{className:"flex items-center gap-1 text-2xs font-medium text-text-primary",children:[D.label,D.description&&n.jsx(rt,{content:D.description,size:11}),r===`${e.type}.${I.key}`&&n.jsx("span",{className:"ml-1.5 text-4xs text-accent-primary",children:w("machine.providerRow.saving")})]})}),n.jsx("div",{className:"shrink-0",children:I.type==="boolean"?n.jsx(Pr,{checked:!!(e.values[I.key]??I.default),busy:r===`${e.type}.${I.key}`,"aria-label":D.label,onChange:L=>void o(e.type,I.key,L)}):I.type==="number"?n.jsx("input",{type:"number",value:Number(e.values[I.key]??I.default??0)||0,min:I.min,max:I.max,onChange:L=>{const $=parseInt(L.target.value)||0;I.min!==void 0&&$<I.min||I.max!==void 0&&$>I.max||o(e.type,I.key,$)},className:"machine-input w-20 text-center text-2xs"}):I.type==="select"&&I.options?n.jsx("select",{value:String(e.values[I.key]??I.default??""),onChange:L=>void o(e.type,I.key,L.target.value),className:"machine-input text-2xs",children:I.options.map(L=>n.jsx("option",{value:L,children:PP(w,L)},L))}):n.jsx("input",{type:"text",defaultValue:String(e.values[I.key]??I.default??""),onBlur:L=>void o(e.type,I.key,L.target.value),className:"machine-input w-[180px] text-2xs"})})]},I.key)})}),h&&m!==void 0&&n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1 text-2xs text-text-secondary font-medium",children:[w("machine.providerRow.quotaTracking"),n.jsx(rt,{content:w("machine.providerRow.quotaTrackingHint"),size:11})]}),A?n.jsxs("div",{className:"flex flex-col items-end gap-1.5 shrink-0",children:[n.jsx("div",{className:"text-2xs font-medium text-amber-400",children:w("machine.providerRow.quotaClaudeConfirmTitle")}),n.jsx("div",{className:"text-3xs text-text-muted max-w-[420px] text-right",children:w("machine.providerRow.quotaClaudeConfirmBody")}),n.jsxs("div",{className:"flex gap-1.5",children:[n.jsx("button",{onClick:I=>{I.stopPropagation(),k(!1),h(e.type,!0)},className:"machine-btn text-3xs px-2 py-0.5 text-amber-400 border-amber-500/25",children:w("machine.providerRow.quotaClaudeConfirmOk")}),n.jsx("button",{onClick:I=>{I.stopPropagation(),k(!1)},className:"machine-btn text-3xs px-2 py-0.5",children:w("machine.providerRow.quotaClaudeConfirmCancel")})]})]}):n.jsx(qc,{checked:m,label:w("machine.providerRow.quotaTracking"),onToggle:()=>{e.type==="claude-cli"&&!m?k(!0):h(e.type,!m)}})]}),u&&d!==void 0&&n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1 text-2xs text-text-secondary font-medium",children:[w("machine.providerRow.quotaAccountLabel"),n.jsx(rt,{content:w("machine.providerRow.quotaAccountLabelHint"),size:11})]}),n.jsx(qc,{checked:d,label:w("machine.providerRow.quotaAccountLabel"),onToggle:()=>{u(!d)}})]}),g&&n.jsxs("div",{className:"grid gap-1 text-3xs text-text-muted","data-testid":"provider-row-metadata",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelType")})," ",n.jsx("span",{className:"font-mono",children:e.type})]}),(s==null?void 0:s.providerVersion)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelVersion")})," ",s.providerVersion]}),(p==null?void 0:p.activeVersion)&&n.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelSpecPin")}),n.jsx("span",{className:"font-mono",children:p.activeVersion}),p.stale&&p.latestVersion&&n.jsx("span",{className:"px-1 py-px rounded border border-amber-500/30 text-amber-400",title:w("machine.providerRow.specPinStaleHint",{latest:p.latestVersion}),children:w("machine.providerRow.specPinStale",{latest:p.latestVersion})})]}),(p==null?void 0:p.activatedAt)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelActivatedAt")})," ",To(p.activatedAt)]}),(p==null?void 0:p.previousVersion)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelPreviousPin")})," ",n.jsx("span",{className:"font-mono",children:p.previousVersion})]}),(p==null?void 0:p.digest)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelDigest")})," ",n.jsx("span",{className:"font-mono",children:p.digest.replace(/^sha256:/,"").slice(0,12)})]}),g&&(s==null?void 0:s.binary)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelBinary")})," ",n.jsx("span",{className:"font-mono",children:s.binary})]}),(s==null?void 0:s.status)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelStatus")})," ",Wh[s.status]?w(Wh[s.status]):s.status]}),g&&(s==null?void 0:s.details)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelDetails")})," ",s.details]}),g&&(s==null?void 0:s.sourceLayer)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelSource")})," ",n.jsx("span",{className:"font-mono",children:s.sourceLayer}),s.sourceName?` · ${s.sourceName}`:""]}),g&&(s==null?void 0:s.trust)&&(s==null?void 0:s.trustDescription)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelTrust")})," ",n.jsx("span",{className:"font-mono",children:s.trust})," — ",s.trustDescription]}),(()=>{const I=s==null?void 0:s.links;if(!I)return null;const D=Object.entries(I).map(([L,$])=>({k:L,href:EP($)})).filter(L=>L.href!==null);return D.length===0?null:n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelLinks")})," ",D.map(({k:L,href:$})=>n.jsx("a",{href:$,target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary hover:underline mr-2",children:L},L))]})})()]}),T&&(g||(s==null?void 0:s.lastDetection)||(s==null?void 0:s.lastVerification))&&n.jsxs("div",{className:"grid gap-1 text-3xs text-text-muted",children:[(g||(s==null?void 0:s.lastDetection))&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelDetection")})," ",Bh(w,s==null?void 0:s.lastDetection)]}),(g||(s==null?void 0:s.lastVerification))&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:w("machine.providerRow.labelVerification")})," ",Bh(w,s==null?void 0:s.lastVerification)]})]}),n.jsxs("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:[T&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>void i(e.type),disabled:!C||r===`${e.type}.detect`,className:`machine-btn text-3xs px-2 py-0.5 text-blue-400 border-blue-500/25 ${C?"":"opacity-40 cursor-not-allowed"}`,title:w(C?"machine.providerRow.detectHint":"machine.providerRow.detectDisabledHint"),children:w("machine.providerRow.detect")}),n.jsx("button",{onClick:()=>void l(e.type),className:"machine-btn text-3xs px-2 py-0.5",children:w("machine.providerRow.resetCommand")})]}),x&&(p==null?void 0:p.previousVersion)&&n.jsx("button",{onClick:()=>{S("rollback"),x().finally(()=>S(null))},disabled:v!==null||f===!0,className:"machine-btn text-3xs px-2 py-0.5",title:w("machine.providerRow.specPinRollbackHint",{version:p.previousVersion}),children:w(v==="rollback"?"machine.providerRow.specPinRollingBack":"machine.providerRow.specPinRollback")})]})]})]})}function FP(e){if(!e||typeof e!="object")return null;const t=e,s=t.result;return s&&typeof s=="object"?s:t}function Uh(e){const t=FP(e);if(!t)return[];const s=[];t.success===!1&&typeof t.error=="string"&&t.error.trim()&&s.push({code:"COMMAND_FAILED",message:t.error});const r=t.channelSync,o=r&&typeof r=="object"?r.errors:void 0;if(Array.isArray(o))for(const a of o){if(!a||typeof a!="object")continue;const i=a,l=typeof i.code=="string"?i.code:"UNKNOWN",d=typeof i.message=="string"?i.message:"";s.push({code:l,message:d,...typeof i.providerType=="string"?{providerType:i.providerType}:{}})}return s}function HP(e){return e.some(t=>t.code==="DIGEST_MISMATCH")}function da(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function BP({machineId:e,sendDaemonCommand:t,onChange:s,reloadToken:r=0}){const{t:o}=he("common"),{confirm:a,confirmDialog:i}=Tr(),[l,d]=c.useState([]),[u,m]=c.useState([]),[h,p]=c.useState(!1),[b,f]=c.useState(null),[x,g]=c.useState(!1),[v,S]=c.useState(""),[A,k]=c.useState("main"),[w,y]=c.useState(""),[N,j]=c.useState(!1),[C,E]=c.useState(null),[P,T]=c.useState(null),M=c.useCallback(async()=>{if(e){p(!0),f(null);try{const L=da(await t(e,"list_provider_sources",{}));if(!(L!=null&&L.success)){f((L==null?void 0:L.error)||o("machine.sourcesPanel.loadFailed"));return}d(L.sources||[]),m(L.conflicts||[])}catch(L){f((L==null?void 0:L.message)||o("machine.sourcesPanel.loadFailed"))}finally{p(!1)}}},[e,t,o]);c.useEffect(()=>{M()},[M,r]);const _=async()=>{if(v.trim()){j(!0),f(null);try{const L=da(await t(e,"add_provider_source",{url:v.trim(),ref:A.trim()||"main",...w.trim()?{name:w.trim()}:{}}));L!=null&&L.success?(g(!1),S(""),k("main"),y(""),await M(),s==null||s()):f((L==null?void 0:L.error)||o("machine.sourcesPanel.addFailed"))}catch(L){f((L==null?void 0:L.message)||o("machine.sourcesPanel.addFailed"))}finally{j(!1)}}},I=async L=>{if(await a({title:o("machine.sourcesPanel.removeConfirmTitle",{name:L}),description:o("machine.sourcesPanel.removeConfirmDescription"),confirmLabel:o("machine.sourcesPanel.removeConfirmLabel"),cancelLabel:o("machine.sourcesPanel.cancel"),tone:"danger"})){E(L),f(null);try{const q=da(await t(e,"remove_provider_source",{name:L}));q!=null&&q.success?(await M(),s==null||s()):f((q==null?void 0:q.error)||o("machine.sourcesPanel.removeFailed"))}catch(q){f((q==null?void 0:q.message)||o("machine.sourcesPanel.removeFailed"))}finally{E(null)}}},D=async(L,$)=>{T(`${L}:${$}`),f(null);try{const q=da(await t(e,"set_active_provider_source",{type:L,sourceName:$}));q!=null&&q.success?(await M(),s==null||s()):f((q==null?void 0:q.error)||o("machine.sourcesPanel.setActiveFailed"))}catch(q){f((q==null?void 0:q.message)||o("machine.sourcesPanel.setActiveFailed"))}finally{T(null)}};return n.jsxs(hn,{padding:"none",className:"px-4.5 py-3.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[n.jsxs("div",{className:"flex items-center gap-1 text-2xs font-semibold uppercase tracking-wider text-sky-400",children:[o("machine.sourcesPanel.title"),n.jsx(rt,{content:o("machine.sourcesPanel.description"),size:12}),h&&n.jsx("span",{className:"ml-1 normal-case tracking-normal font-normal text-text-muted",children:"…"})]}),n.jsx("div",{className:"flex gap-1.5",children:n.jsx("button",{onClick:()=>g(!0),className:"machine-btn text-3xs bg-sky-500/[0.08] border-sky-500/20 text-sky-300 hover:bg-sky-500/[0.14]",children:o("machine.sourcesPanel.addSource")})})]}),b&&n.jsx("div",{className:"mb-2 text-2xs text-red-400 bg-red-500/10 border border-red-500/20 rounded px-2 py-1",children:b}),l.length===0?n.jsx("div",{className:"text-2xs text-text-muted italic",children:o("machine.sourcesPanel.empty")}):n.jsx("ul",{className:"flex flex-col gap-2",children:l.map(L=>n.jsxs("li",{className:"rounded border border-border-subtle bg-bg-primary/40 px-3 py-2",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"font-mono text-xs text-text-primary",children:L.name}),n.jsxs("div",{className:"text-3xs text-text-muted truncate",children:[L.url," ",n.jsxs("span",{className:"opacity-60",children:["@ ",L.ref]})]})]}),n.jsx("button",{type:"button",onClick:()=>void I(L.name),disabled:C===L.name,className:"machine-btn text-3xs text-red-400 hover:bg-red-500/[0.10]",children:C===L.name?o("machine.sourcesPanel.removing"):o("machine.sourcesPanel.remove")})]}),n.jsx("div",{className:"mt-1.5 text-3xs text-text-muted",children:Object.entries(L.providers).map(([$,q])=>n.jsxs("span",{className:"mr-3",children:[n.jsxs("span",{className:"text-text-secondary",children:[$,":"]})," ",q.length]},$))})]},L.name))}),u.length>0&&n.jsxs("div",{className:"mt-3 rounded border border-amber-500/30 bg-amber-500/[0.06] px-3 py-2",children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1 text-2xs font-semibold text-amber-300",children:[o("machine.sourcesPanel.conflictsTitle"),n.jsx(rt,{content:o("machine.sourcesPanel.conflictsDescription"),size:12})]}),n.jsx("ul",{className:"flex flex-col gap-1.5",children:u.map(L=>n.jsxs("li",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"font-mono text-2xs",children:[L.type," ",n.jsxs("span",{className:"text-text-muted",children:["(",L.category,")"]})]}),n.jsx("div",{className:"flex gap-1.5 flex-wrap",children:L.candidates.map($=>n.jsxs("button",{type:"button",onClick:()=>void D(L.type,$),disabled:P===`${L.type}:${$}`,className:`text-3xs px-2 py-0.5 rounded border ${L.active===$?"bg-amber-500/[0.18] border-amber-500/40 text-amber-200":"border-border-subtle text-text-secondary hover:bg-amber-500/[0.06]"}`,title:L.active===$?o("machine.sourcesPanel.active"):o("machine.sourcesPanel.switchActiveTo",{name:$}),children:[L.active===$?"● ":"",$]},$))})]},L.type))})]}),x&&n.jsxs("div",{className:"mt-3 rounded border border-sky-500/30 bg-sky-500/[0.06] px-3 py-3",children:[n.jsx("div",{className:"text-2xs font-semibold text-sky-300 mb-2",children:o("machine.sourcesPanel.addTitle")}),n.jsxs("div",{className:"grid md:grid-cols-3 gap-2",children:[n.jsxs("label",{className:"flex flex-col gap-1 text-3xs text-text-secondary md:col-span-3",children:[n.jsx("span",{children:o("machine.sourcesPanel.gitUrl")}),n.jsx("input",{type:"text",value:v,onChange:L=>S(L.target.value),placeholder:"https://github.com/vendor/extra-providers",className:"machine-input text-2xs font-mono"})]}),n.jsxs("label",{className:"flex flex-col gap-1 text-3xs text-text-secondary",children:[n.jsx("span",{children:o("machine.sourcesPanel.ref")}),n.jsx("input",{type:"text",value:A,onChange:L=>k(L.target.value),placeholder:"main",className:"machine-input text-2xs"})]}),n.jsxs("label",{className:"flex flex-col gap-1 text-3xs text-text-secondary md:col-span-2",children:[n.jsx("span",{children:o("machine.sourcesPanel.name")}),n.jsx("input",{type:"text",value:w,onChange:L=>y(L.target.value),placeholder:"@vendor-extra-providers",className:"machine-input text-2xs font-mono"})]})]}),n.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>g(!1),className:"machine-btn text-3xs",children:o("machine.sourcesPanel.cancel")}),n.jsx("button",{type:"button",onClick:()=>void _(),disabled:N||!v.trim(),className:"machine-btn text-3xs bg-sky-500/[0.10] border-sky-500/30 text-sky-200 hover:bg-sky-500/[0.18]",children:o(N?"machine.sourcesPanel.cloning":"machine.sourcesPanel.cloneAndRegister")})]})]}),i]})}function Kh(e){var o;const t=bf(e);if(!t)return{ok:!1,error:"empty response"};if(t.success===!1)return{ok:!1,error:typeof t.error=="string"&&t.error.trim()?t.error:"sync failed"};const s=t.channelSync;if(s&&typeof s=="object"&&s.status==="error"){const a=Array.isArray(s.errors)?(o=s.errors[0])==null?void 0:o.message:void 0;return{ok:!1,error:typeof a=="string"&&a.trim()?a:"channel sync failed"}}return{ok:!0,activatedCount:Array.isArray(t.activated)?t.activated.length:0}}const qh=new Set(["codex-cli"]),ua=new Set(Ny);function WP({machineId:e,providers:t,sendDaemonCommand:s,quota:r}){var re,Se;const{t:o}=he("common"),[a,i]=c.useState(null),[l,d]=c.useState(void 0),[u,m]=c.useState({}),[h,p]=c.useState({}),[b,f]=c.useState([]),[x,g]=c.useState([]),[v,S]=c.useState(null),[A,k]=c.useState({}),[w,y]=c.useState(!1),[N,j]=c.useState({}),[C,E]=c.useState(!1),[P,T]=c.useState(null),[M,_]=c.useState(null),[I,D]=c.useState("cli"),[L,$]=c.useState(null),[q,G]=c.useState(!1),[W,R]=c.useState(0),[O,B]=c.useState(null),[H,U]=c.useState("normal"),[K,oe]=c.useState(""),[ge,J]=c.useState(!1),ke=c.useCallback(async()=>{if(e)try{const Y=await s(e,"get_provider_source_config",{}),ue=Oh(Y);ue&&(B(ue),U(ue.sourceMode),oe(ue.explicitProviderDir||""))}catch(Y){T(o("machine.providers.loadFailed",{error:(Y==null?void 0:Y.message)||String(Y)}))}},[e,s,o]),de=c.useCallback(async Y=>{if(e){Y!=null&&Y.explicit&&E(!0);try{const ue=await s(e,"get_provider_settings",{}),fe=wx(ue);fe&&(i(fe),T(null))}catch(ue){T(o("machine.providers.loadFailed",{error:(ue==null?void 0:ue.message)||String(ue)}))}finally{Y!=null&&Y.explicit&&E(!1)}}},[e,s,o]),ne=c.useMemo(()=>{if(!a)return[];const Y=Sx(a,t,{filterSchema:ue=>ue.filter(fe=>fe.key!=="enabled")});return Y.sort((ue,fe)=>ue.category.localeCompare(fe.category)||ue.displayName.localeCompare(fe.displayName)),Y},[a,t]),le=c.useCallback((Y,ue,fe)=>{i(Ie=>Ie&&{...Ie,values:{...Ie.values,[Y]:{...Ie.values[Y]||{},[ue]:fe}}})},[]),te=c.useCallback(async()=>{if(e)try{const Y=await s(e,"get_quota_account_label",{}),ue=Y&&typeof Y=="object"&&"result"in Y?Y.result:Y;typeof(ue==null?void 0:ue.enabled)=="boolean"&&d(ue.enabled)}catch{}},[e,s]),ce=c.useCallback(async Y=>{if(e){d(Y);try{const ue=await s(e,"set_quota_account_label",{enabled:Y}),fe=ue&&typeof ue=="object"&&"result"in ue?ue.result:ue;(fe==null?void 0:fe.success)===!1&&await te()}catch{await te()}}},[e,s,te]),Ce=c.useCallback(async Y=>{if(e)try{const ue=await s(e,"get_quota_provider_enabled",{providerType:Y}),fe=ue&&typeof ue=="object"&&"result"in ue?ue.result:ue;typeof(fe==null?void 0:fe.enabled)=="boolean"&&m(Ie=>({...Ie,[Y]:fe.enabled}))}catch{}},[e,s]),Q=c.useCallback(async()=>{await Promise.all([...ua].map(Y=>Ce(Y)))},[Ce]),z=c.useCallback(async(Y,ue)=>{if(e){m(fe=>({...fe,[Y]:ue}));try{const fe=await s(e,"set_quota_provider_enabled",{providerType:Y,enabled:ue}),Ie=fe&&typeof fe=="object"&&"result"in fe?fe.result:fe;(Ie==null?void 0:Ie.success)===!1&&(T(o("machine.providers.quotaToggleFailed",{provider:Y,error:typeof Ie.error=="string"?Ie.error:"unknown error"})),await Ce(Y))}catch(fe){T(o("machine.providers.quotaToggleFailed",{provider:Y,error:(fe==null?void 0:fe.message)||String(fe)})),await Ce(Y)}}},[e,s,Ce,o]),X=c.useCallback(async()=>{var Y,ue;if(e)try{const fe=await s(e,"check_provider_updates",{}),Ie=fe&&typeof fe=="object"&&"result"in fe?fe.result:fe,Ke={};for(const _e of(Ie==null?void 0:Ie.providers)??[])typeof(_e==null?void 0:_e.type)=="string"&&(Ke[_e.type]={activeVersion:_e.activeVersion??null,latestVersion:_e.latestVersion??null,stale:_e.stale===!0,digest:_e.digest??null,activatedAt:_e.activatedAt??null,previousVersion:_e.previousVersion??null});p(Ke),f(Array.isArray((Y=Ie==null?void 0:Ie.channelStaleness)==null?void 0:Y.newTypes)?Ie.channelStaleness.newTypes:[]),g(Array.isArray((ue=Ie==null?void 0:Ie.modelStaleness)==null?void 0:ue.staleTypes)?Ie.modelStaleness.staleTypes:[])}catch{}},[e,s]),pe=c.useCallback(async Y=>{if(e){S(Y),j(ue=>{if(!(Y in ue))return ue;const fe={...ue};return delete fe[Y],fe});try{const ue=await s(e,"activate_provider_updates",{types:[Y]}),fe=Uh(ue);fe.length>0&&j(Ie=>({...Ie,[Y]:fe}))}catch(ue){j(fe=>({...fe,[Y]:[{code:"COMMAND_FAILED",message:ue instanceof Error?ue.message:String(ue)}]}))}finally{S(null),await X(),de()}}},[e,s,X,de]),Re=c.useCallback(async()=>{if(e){y(!0);try{const Y=await s(e,"activate_provider_updates",{}),ue=Kh(Y);"error"in ue?nt.showErrorToast(o("machine.detail.providerSyncFailed"),ue.error):nt.showToast(ue.activatedCount>0?o("machine.detail.providerSyncSuccess",{count:ue.activatedCount}):o("machine.detail.providerSyncAlreadyCurrent"),"success")}catch(Y){nt.showErrorToast(o("machine.detail.providerSyncFailed"),Y)}finally{y(!1),await X(),de()}}},[e,s,X,de,o]),Oe=c.useCallback(async Y=>{if(e)try{await s(e,"rollback_provider_update",{providerType:Y})}finally{await X(),de()}},[e,s,X,de]),De=c.useCallback(async Y=>{if(e){k(ue=>({...ue,[Y]:!0}));try{const ue=await s(e,"activate_provider_updates",{types:[Y],only:!0}),fe=Kh(ue),Ie=Uh(ue);if("error"in fe||Ie.length>0){const Ke="error"in fe?fe.error:Ie.map(_e=>_e.message||_e.code).join("; ");nt.showErrorToast(o("machine.detail.providerSyncFailed"),Ke)}else nt.showToast(fe.activatedCount>0?o("machine.detail.providerSyncSuccess",{count:fe.activatedCount}):o("machine.detail.providerSyncAlreadyCurrent"),"success")}catch(ue){nt.showErrorToast(o("machine.detail.providerSyncFailed"),ue)}finally{k(ue=>{const fe={...ue};return delete fe[Y],fe}),await X(),de()}}},[e,s,X,de,o]);c.useEffect(()=>{a||de({explicit:!0}),O||ke(),l===void 0&&te(),Q(),X()},[]);const we=async(Y,ue,fe)=>{_(`${Y}.${ue}`),le(Y,ue,fe);try{const Ie=await s(e,"set_provider_setting",{providerType:Y,key:ue,value:fe});Ie!=null&&Ie.success||de()}catch{de()}_(null)},V=async(Y,ue)=>{if(ue){$(Y);return}await we(Y,"enabled",!1)},xe=c.useCallback(async(Y,ue)=>{$(null),_(`${Y}.enabled`);try{ue.quotaEnabled!==void 0&&await s(e,"set_quota_provider_enabled",{providerType:Y,enabled:ue.quotaEnabled});const fe=await s(e,"set_provider_setting",{providerType:Y,key:"autoApprove",value:ue.autoApprove}),Ie=await s(e,"set_provider_setting",{providerType:Y,key:"enabled",value:!0});if((fe==null?void 0:fe.success)===!1||(Ie==null?void 0:Ie.success)===!1)throw new Error("set_provider_setting refused");le(Y,"autoApprove",ue.autoApprove),le(Y,"enabled",!0),ue.quotaEnabled!==void 0&&m(Ke=>({...Ke,[Y]:ue.quotaEnabled}))}catch{de(),Ce(Y)}finally{_(null)}},[e,s,de,Ce,le]),Z=async Y=>{_(`${Y}.detect`);try{const ue=await s(e,"detect_provider",{providerType:Y}),fe=ue&&typeof ue=="object"&&"result"in ue?ue.result:ue;(fe==null?void 0:fe.success)===!1&&T(o("machine.providers.loadFailed",{error:typeof fe.error=="string"?fe.error:"detect failed"}))}catch(ue){T(o("machine.providers.loadFailed",{error:(ue==null?void 0:ue.message)||String(ue)}))}finally{_(null)}},ae=async Y=>{await we(Y,"executablePath",""),await we(Y,"executableArgs","")},F=async()=>{J(!0);try{const Y=await s(e,"set_provider_source_config",{providerSourceMode:H,providerDir:NP(K)}),ue=Oh(Y);ue?(B(ue),U(ue.sourceMode),oe(ue.explicitProviderDir||"")):await ke(),de()}catch{await ke()}J(!1)},se=ne.filter(Y=>I==="all"||Y.category===I),me=Object.values(h).filter(Y=>Y.stale).length;return n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[n.jsxs("div",{className:"flex gap-1 items-center",children:[n.jsx("span",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mr-2",children:o("machine.providers.filter")}),["cli","ide","extension","all"].map(Y=>n.jsx("button",{onClick:()=>D(Y),className:`machine-btn text-3xs px-2 py-0.5 ${I===Y?"bg-accent-primary/15 border-accent-primary/40 text-accent-primary":""}`,children:Y.toUpperCase()},Y))]}),n.jsxs("div",{className:"flex gap-1.5 items-center",children:[me>=2&&n.jsxs("button",{onClick:()=>{Re()},disabled:w,className:"machine-btn text-3xs text-amber-400 border-amber-500/25",children:[w?n.jsx(yr,{size:11}):null," ",o("machine.providers.updateAll")]}),n.jsx(Wi,{onClick:()=>{de({explicit:!0}),X(),q&&(ke(),R(Y=>Y+1))},refreshing:C,label:o("machine.providers.refresh"),size:12,className:"h-7 w-7"}),n.jsx("button",{onClick:()=>G(Y=>!Y),"aria-expanded":q,className:`machine-btn text-3xs ${q?"bg-accent-primary/10 border-accent-primary/30 text-accent-primary":""}`,title:o("machine.providers.advancedHint"),children:o("machine.providers.advanced")})]})]}),P&&n.jsx(Bt,{variant:"error",onDismiss:()=>T(null),children:P}),b.length>0&&n.jsxs(hn,{padding:"none",className:"px-4.5 py-3.5",children:[n.jsxs("div",{className:"mb-2.5 flex items-center gap-1 text-2xs font-semibold uppercase tracking-wider text-accent-primary",children:[o("machine.providers.newChannelTypesTitle"),n.jsx(rt,{content:o("machine.providers.newChannelTypesDesc"),size:12})]}),n.jsx("div",{className:"flex flex-col gap-1.5",children:b.map(Y=>{const ue=N[Y]??[];return n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 text-xxs",children:[n.jsx("span",{className:"font-mono text-text-primary",children:Y}),n.jsx("button",{onClick:()=>{pe(Y)},disabled:v!==null,className:"px-2.5 py-1 rounded-md text-xs font-medium bg-accent-primary/15 text-accent-primary hover:bg-accent-primary/25 disabled:opacity-50",children:v===Y?n.jsx(yr,{size:11}):o("machine.providers.installNewType")})]}),ue.length>0&&n.jsxs("div",{className:"rounded-md border border-red-500/30 bg-red-500/[0.07] px-2.5 py-1.5",children:[n.jsx("div",{className:"text-3xs font-semibold text-red-300",children:HP(ue)?o("machine.providers.installFailedDigestMismatch"):o("machine.providers.installFailedTitle")}),n.jsx(Hd,{summary:o("toast.details"),className:"mt-1",children:n.jsx("ul",{className:"flex flex-col gap-0.5",children:ue.map((fe,Ie)=>n.jsxs("li",{className:"text-3xs text-text-muted font-mono break-all",children:[n.jsx("span",{className:"text-red-300/90",children:fe.code}),fe.providerType?` [${fe.providerType}]`:"",fe.message?`: ${fe.message}`:""]},`${fe.code}-${Ie}`))})})]})]},Y)})})]}),x.length>0&&n.jsxs(hn,{padding:"none",className:"px-4.5 py-3.5",children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1 text-2xs font-semibold uppercase tracking-wider text-text-secondary",children:[o("machine.providers.modelListTitle"),n.jsx(rt,{content:o("machine.providers.modelListStaleDesc"),size:12})]}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:x.map(Y=>n.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-amber-500/30 bg-amber-500/[0.07] px-2 py-0.5",children:[n.jsx("span",{className:"font-mono text-xxs text-text-primary",children:Y}),n.jsx("span",{className:"text-3xs uppercase tracking-wider text-amber-300/90",children:o("machine.providers.modelListStaleBadge")})]},Y))})]}),q&&n.jsx(BP,{machineId:e,sendDaemonCommand:s,onChange:()=>{de()},reloadToken:W}),q&&n.jsxs(hn,{padding:"none",className:"px-4.5 py-3.5",children:[n.jsx("div",{className:"flex items-center justify-between gap-3 mb-3",children:n.jsxs("div",{className:"flex items-center gap-1 text-2xs font-semibold uppercase tracking-wider text-accent-primary",children:[o("machine.providers.sourceConfigTitle"),n.jsx(rt,{content:o("machine.providers.sourceConfigDesc"),size:12})]})}),n.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[n.jsxs("label",{className:"flex flex-col gap-1 text-2xs text-text-secondary",children:[n.jsx("span",{className:"font-medium text-text-primary",children:o("machine.providers.sourceMode")}),n.jsxs("select",{value:H,onChange:Y=>U(Y.target.value),className:"machine-input text-2xs",children:[n.jsx("option",{value:"normal",children:"normal"}),n.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),n.jsxs("label",{className:"flex flex-col gap-1 text-2xs text-text-secondary",children:[n.jsx("span",{className:"font-medium text-text-primary",children:o("machine.providers.explicitProviderDir")}),n.jsx("input",{type:"text",value:K,onChange:Y=>oe(Y.target.value),placeholder:o("machine.providers.providerDirPlaceholder"),className:"machine-input text-2xs"})]}),n.jsx("button",{onClick:()=>void F(),disabled:ge,className:"machine-btn text-3xs bg-accent-primary/[0.08] border-accent-primary/20 text-accent-primary hover:bg-accent-primary/[0.14]",children:o(ge?"machine.providers.applying":"machine.providers.applyReload")})]}),n.jsx("div",{className:"mt-3 flex flex-col gap-1.5","data-testid":"provider-source-paths",children:[{label:o("machine.providers.userRoot"),value:O==null?void 0:O.userDir},{label:o("machine.providers.upstreamRoot"),value:O==null?void 0:O.upstreamDir},{label:o("machine.providers.providerRoots"),value:(re=O==null?void 0:O.providerRoots)==null?void 0:re.join(" → ")}].map(Y=>n.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 text-3xs",children:[n.jsx("span",{className:"shrink-0 font-medium text-text-secondary",children:Y.label}),n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx("span",{className:"min-w-0 truncate font-mono text-text-muted",title:Y.value||void 0,children:Y.value||"—"}),Y.value&&n.jsx(Zb,{value:Y.value,label:o("common.copy")})]})]},Y.label))})]}),C&&ne.length===0?n.jsx("div",{className:"p-10 text-center text-text-muted",children:o("machine.providers.loadingSettings")}):se.length===0?n.jsx(hn,{padding:"none",className:"px-4.5 py-8 text-center",children:n.jsx("div",{className:"text-xs text-text-muted",children:I==="all"?o("machine.providers.noProviders"):o("machine.providers.noFilteredProviders",{filter:I.toUpperCase()})})}):n.jsx("div",{className:"flex flex-col gap-1.5",children:se.map(Y=>n.jsx($P,{quota:r==null?void 0:r[Y.type],prov:Y,providerInfo:t.find(ue=>ue.type===Y.type),savingKey:M,onSetSetting:we,onEnableToggle:V,onDetect:Z,onResetCommand:ae,quotaAccountLabelEnabled:qh.has(Y.type)?l:void 0,onQuotaAccountLabelToggle:qh.has(Y.type)?ce:void 0,quotaEnabled:ua.has(Y.type)?u[Y.type]??!0:void 0,onQuotaToggle:ua.has(Y.type)?z:void 0,pin:h[Y.type],onUpdate:()=>De(Y.type),updating:A[Y.type]===!0,onRollbackUpdate:()=>Oe(Y.type),showAdvanced:q},Y.type))}),L&&n.jsx(CP,{providerType:L,displayName:((Se=ne.find(Y=>Y.type===L))==null?void 0:Se.displayName)||L,supportsQuota:ua.has(L),quotaInstallsClaudeStatusline:L==="claude-cli",onCancel:()=>$(null),onConfirm:Y=>{xe(L,Y)}})]})}const UP=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function KP({count:e,since:t,category:s}){return{count:e,since:t,...s==="all"?{}:{category:s}}}function qP(e,t){return t==="all"?e:e.filter(s=>s.category===t)}function zP(e){return e.trim().toLowerCase()}function zi(e,t){const s=zP(t);return s?e.some(r=>String(r??"").toLowerCase().includes(s)):!0}function mu(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function jr(e,t=220){const s=mu(e);return s?s.length>t?`${s.slice(0,t)}…`:s:""}function VP(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.map(s=>{const r=s;return{timestamp:Number(r.ts)||0,level:r.level||"info",message:`[${String(r.category||"daemon")}] ${String(r.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const s=t.trim();return{kind:s?"text":"empty",entries:[],rawText:s}}return{kind:"empty",entries:[],rawText:""}}function GP(e,t){return e.filter(s=>zi([s.level,s.message],t))}function zh(e){return`${e.timestamp}:${e.level}:${e.message}`}function YP(e,t,s=300){if(t.entries.length>0){const r=new Map;for(const i of e.entries)r.set(zh(i),i);for(const i of t.entries)r.set(zh(i),i);const o=Array.from(r.values()).sort((i,l)=>i.timestamp-l.timestamp).slice(-s),a=o.reduce((i,l)=>Math.max(i,Number(l.timestamp||0)),e.lastTs);return{entries:o,kind:"structured",rawText:"",lastTs:a}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function QP(e,t,s=120){if(t.length===0)return e;const r=new Map;for(const o of e)r.set(o.id,o);for(const o of t)r.set(o.id,o);return Array.from(r.values()).sort((o,a)=>o.ts-a.ts).slice(-s)}function JP(e,t){return e.split(`
|
|
86
|
+
`).map(s=>s.trimEnd()).filter(Boolean).filter(s=>zi([s],t))}function XP(e,t){return e.filter(s=>zi([s.level,s.category,s.stage,s.interactionId,mu(s.payload)],t))}function ZP(e,t){return e.filter(s=>zi([s.kind,s.topic,s.interactionId,mu(s.payload)],t))}function Vh(e){return e==="warn"||e==="error"}function eE({daemonLogs:e,daemonRawLines:t,trace:s,webEvents:r}){return{all:e.length+t.length+s.length+r.length,info:e.filter(o=>o.level!=="debug").length+s.filter(o=>o.level!=="debug").length+r.length,issues:e.filter(o=>Vh(o.level)).length+s.filter(o=>Vh(o.level)).length}}function tE({daemonLogs:e,daemonRawLines:t,trace:s,webEvents:r}){const o=[];return e.length>0?o.push(["[daemon logs]",...e.map(a=>`${new Date(a.timestamp).toISOString()} ${a.level.toUpperCase()} ${a.message}`)].join(`
|
|
87
|
+
`)):t.length>0&&o.push(["[daemon logs]",...t].join(`
|
|
88
|
+
`)),s.length>0&&o.push(["[trace]",...s.map(a=>`${new Date(a.ts).toISOString()} ${a.level.toUpperCase()} ${a.category}.${a.stage} ${jr(a.payload,500)}`.trim())].join(`
|
|
89
|
+
`)),r.length>0&&o.push(["[browser events]",...r.map(a=>`${new Date(a.ts).toISOString()} ${a.kind}${a.topic?` topic=${a.topic}`:""} ${jr(a.payload,500)}`.trim())].join(`
|
|
90
|
+
`)),o.join(`
|
|
91
|
+
|
|
92
|
+
`)}function nE({machineId:e,sendDaemonCommand:t}){const[s,r]=c.useState([]),[o,a]=c.useState("empty"),[i,l]=c.useState(""),[d,u]=c.useState([]),[m,h]=c.useState([]),[p,b]=c.useState(null),[f,x]=c.useState(!0),[g,v]=c.useState("info"),[S,A]=c.useState("all"),[k,w]=c.useState(!0),[y,N]=c.useState(!0),[j,C]=c.useState(""),[E,P]=c.useState(""),[T,M]=c.useState(0),_=c.useRef(0),I=c.useRef(0),D=c.useRef(0),L=c.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),$=c.useRef([]),q=c.useCallback(()=>{const U={entries:[],kind:"empty",rawText:"",lastTs:0};L.current=U,I.current=0,r([]),l(""),a("empty"),w(!0)},[]),G=c.useCallback(()=>{$.current=[],D.current=0,u([]),N(!0)},[]),W=c.useCallback(U=>{U!==g&&(q(),v(U))},[g,q]),R=c.useCallback(U=>{A(K=>K===U?K:U)},[]),O=c.useCallback(()=>{q(),G(),h([]),b(null),C(""),P(""),bo.clear()},[q,G]),B=c.useCallback(()=>{M(U=>U+1)},[]),H=c.useCallback(async()=>{if(!e)return;const U=_.current+1;_.current=U;const K=I.current,oe=D.current,[ge,J]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:g,since:K}),t(e,"get_debug_trace",KP({count:120,since:oe,category:S}))]);if(_.current===U){if(ge.status==="fulfilled"){const ke=ge.value,de=(ke==null?void 0:ke.result)||ke,ne=VP(de),le=YP(L.current,ne,300);L.current=le,I.current=le.lastTs,w(!1),C((ke==null?void 0:ke.success)===!1?String((ke==null?void 0:ke.error)||"Could not load daemon logs"):""),a(le.kind),l(le.rawText),r(le.entries)}else w(!1),C(ge.reason instanceof Error?ge.reason.message:"Could not load daemon logs");if(J.status==="fulfilled"){const ke=J.value,de=(ke==null?void 0:ke.result)||ke;if((ke==null?void 0:ke.success)===!1)P(String((ke==null?void 0:ke.error)||"Could not load daemon trace"));else if(Array.isArray(de==null?void 0:de.trace)){const ne=de.trace,le=QP($.current,ne,120),te=ne.reduce((ce,Ce)=>Math.max(ce,Number(Ce.ts||0)),oe);$.current=le,te>oe&&(D.current=te),P(""),u(le)}else P("");N(!1)}else N(!1),P(J.reason instanceof Error?J.reason.message:"Could not load daemon trace");h(bo.list({limit:120})),b(Date.now())}},[g,e,t,S]);return c.useEffect(()=>{G()},[G,S]),c.useEffect(()=>{_.current+=1,q(),G(),h([]),b(null),C(""),P("")},[e,q,G]),c.useEffect(()=>{if(!e)return;if(H(),!f)return()=>{_.current+=1};const U=setInterval(()=>{H()},3e3);return()=>{_.current+=1,clearInterval(U)}},[f,H,e,T]),{daemonLogs:s,daemonLogKind:o,daemonRawText:i,debugTrace:d,webEvents:m,lastUpdatedAt:p,autoRefresh:f,logLevel:g,traceCategory:S,daemonLoading:k,traceLoading:y,daemonFetchError:j,traceFetchError:E,setAutoRefresh:x,setLogLevel:W,setTraceCategory:R,refresh:B,clear:O}}function sE({daemonLoading:e,traceLoading:t,daemonFetchError:s,traceFetchError:r,daemonLogKind:o,daemonLogsCount:a,daemonRawLineCount:i,traceCount:l,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:s?"error":e?"loading":a>0||i>0?"ok":"empty",detail:s||(o==="text"?`${i} raw file-fallback line(s)`:`${a} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:r?"error":t?"loading":l>0?"ok":"empty",detail:r||`${l} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function Gh(e){return e==="warn"||e==="error"}function rE(e){const t=e.toLowerCase();return/\[(err|error)\]/i.test(e)||t.includes(" error ")||t.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||t.includes(" warning ")||t.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function oE(e,t){const s=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(s){const r=Date.parse(s[0]);if(Number.isFinite(r))return r}return Number.MAX_SAFE_INTEGER-1e5+t}function Yh(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function aE(e){const t=jr(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function iE(e){const t=jr(e.payload,320),s=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${s} ${t}`:`${e.kind}${s}`}function cE({daemonLogs:e,daemonRawLines:t,trace:s,webEvents:r}){const o=[];return e.forEach((a,i)=>{o.push({id:`daemon-log-${a.timestamp}-${i}`,source:"daemon_log",ts:Number(a.timestamp||0),severity:a.level,message:a.message,raw:a.message})}),r.forEach(a=>{o.push({id:`browser-event-${a.id}`,source:"browser_event",ts:Number(a.ts||0),severity:"info",message:iE(a),topic:a.topic,interactionId:a.interactionId,payload:a.payload})}),s.forEach(a=>{o.push({id:`daemon-trace-${a.id}`,source:"daemon_trace",ts:Number(a.ts||0),severity:a.level,message:aE(a),category:a.category,stage:a.stage,interactionId:a.interactionId,payload:a.payload})}),t.forEach((a,i)=>{o.push({id:`raw-file-${i}`,source:"raw_file",ts:oE(a,i),severity:rE(a),message:a,raw:a})}),o.sort((a,i)=>a.ts!==i.ts?a.ts-i.ts:Yh(a.source)-Yh(i.source))}function lE(e){return`${e.source}:${e.severity}:${e.message}`}function dE(e){const t=e.filter(r=>Gh(r.severity)).sort((r,o)=>o.ts-r.ts),s=new Map;for(const r of e){if(!Gh(r.severity))continue;const o=lE(r),a=s.get(o);a?(a.count+=1,a.firstTs=Math.min(a.firstTs,r.ts),a.lastTs=Math.max(a.lastTs,r.ts)):s.set(o,{key:o,source:r.source,severity:r.severity,message:r.message,count:1,firstTs:r.ts,lastTs:r.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(s.values()).filter(r=>r.count>1).sort((r,o)=>o.count!==r.count?o.count-r.count:o.lastTs-r.lastTs).slice(0,5)}}function uE(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Qh(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",s=e.interactionId?` ix=${e.interactionId}`:"";return`${uE(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${s} ${e.message}`.trim()}function mE({events:e,summary:t,sources:s,maxTimelineEvents:r=80}){const o=[];o.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
93
|
+
`)),o.push(["[source status]",...s.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
|
|
94
|
+
`)),t.latestIssue&&o.push(["[latest issue]",Qh(t.latestIssue)].join(`
|
|
95
|
+
`)),t.repeatedPatterns.length>0&&o.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
|
|
96
|
+
`));const a=e.slice(-r);return o.push(["[timeline]",...a.length>0?a.map(Qh):["No diagnostic events captured."]].join(`
|
|
97
|
+
`)),o.join(`
|
|
98
|
+
|
|
99
|
+
`)}function hE(e,t){return t==="issues"?e.filter(s=>s.level==="warn"||s.level==="error"):t==="info"?e.filter(s=>s.level!=="debug"):e}function pE(e,t){return t==="issues"?e.filter(s=>s.level==="warn"||s.level==="error"):t==="info"?e.filter(s=>s.level!=="debug"):e}function fE({daemonLogs:e,daemonRawText:t,daemonLogKind:s,debugTrace:r,webEvents:o,traceCategory:a,quickFilter:i,searchQuery:l,daemonLoading:d,traceLoading:u,daemonFetchError:m,traceFetchError:h}){const p=qP(r,a),b=GP(e,l),f=JP(t,l),x=XP(p,l),g=ZP(o,l),v=hE(b,i),S=i==="all"?f:[],A=pE(x,i),k=i==="issues"?[]:g,w=eE({daemonLogs:b,daemonRawLines:f,trace:x,webEvents:g}),y=cE({daemonLogs:v,daemonRawLines:S,trace:A,webEvents:k}),N=dE(y),j=sE({daemonLoading:d,traceLoading:u,daemonFetchError:m,traceFetchError:h,daemonLogKind:s,daemonLogsCount:b.length,daemonRawLineCount:f.length,traceCount:x.length,webEventCount:g.length});return{filteredDaemonLogs:b,filteredDaemonRawLines:f,filteredTraceEntries:x,filteredWebEvents:g,visibleDaemonLogs:v,visibleDaemonRawLines:S,visibleTraceEntries:A,visibleWebEvents:k,quickFilterCounts:w,diagnosticEvents:y,diagnosticsSummary:N,sourceStates:j}}function bE(e,t){return e?ki(e,{seconds:!0}):t("machine.logsTabSections.notYetLoaded")}function kx(e,t){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?t("machine.logsTabSections.rawFile"):ki(e,{seconds:!0})}function td(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 zc(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function hu(e,t){return t(e==="daemon_log"?"machine.logsTabSections.sourceDaemon":e==="daemon_trace"?"machine.logsTabSections.sourceTrace":e==="browser_event"?"machine.logsTabSections.sourceBrowser":"machine.logsTabSections.rawFile")}function gE({event:e}){const{t}=he("common");return n.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${td(e.severity)}`,children:[n.jsxs("div",{className:"flex gap-2 text-3xs text-text-muted flex-wrap",children:[n.jsx("span",{children:kx(e.ts,t)}),n.jsx("span",{children:e.severity.toUpperCase()}),n.jsx("span",{children:hu(e.source,t)}),e.category&&e.stage&&n.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&n.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&n.jsxs("span",{children:["ix=",e.interactionId]})]}),n.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function xE({quickFilter:e,quickFilterCounts:t,searchQuery:s,autoRefresh:r,onQuickFilterChange:o,onSearchQueryChange:a,onCopyDiagnostics:i,onCopyVisible:l,onToggleAutoRefresh:d,onRefresh:u,onClear:m}){const{t:h}=he("common");return n.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx("span",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mr-1",children:h("machine.logsTabSections.view")}),n.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:h("machine.logsTabSections.filterInfo",{count:t.info})},{id:"issues",label:h("machine.logsTabSections.filterIssues",{count:t.issues})},{id:"all",label:h("machine.logsTabSections.filterAll",{count:t.all})}].map(p=>n.jsx("button",{type:"button",onClick:()=>o(p.id),className:`rounded-md px-2.5 py-1 text-2xs transition-colors ${e===p.id?"bg-accent-primary/15 text-accent-primary border border-accent-primary/30":"text-text-secondary hover:text-text-primary"}`,children:p.label},p.id))}),n.jsx("input",{value:s,onChange:p=>a(p.target.value),placeholder:h("machine.logsTabSections.searchPlaceholder"),className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-primary placeholder:text-text-muted"})]}),n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx("button",{onClick:i,className:"machine-btn",children:h("machine.logsTabSections.copyDiagnostics")}),n.jsx("button",{onClick:l,className:"machine-btn",children:h("machine.logsTabSections.copyVisible")}),n.jsx("button",{onClick:d,className:`machine-btn ${r?"text-green-500 border-green-500/30":""}`,children:h(r?"machine.logsTabSections.pause":"machine.logsTabSections.resume")}),n.jsx("button",{onClick:u,className:"machine-btn",children:h("machine.logsTabSections.refresh")}),n.jsx("button",{onClick:m,className:"machine-btn",children:h("machine.logsTabSections.clear")})]})]})}function yE({logLevel:e,traceCategory:t,onLogLevelChange:s,onTraceCategoryChange:r}){const{t:o}=he("common");return n.jsx(hn,{padding:"sm",children:n.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx("span",{className:"text-3xs uppercase tracking-wider text-text-muted font-semibold",children:o("machine.logsTabSections.advancedSourceScope")}),["debug","info","warn","error"].map(a=>n.jsx("button",{onClick:()=>s(a),className:`machine-btn text-3xs px-2 py-0.5 ${e===a?"bg-accent-primary/15 border-accent-primary/40 text-accent-primary":""}`,children:o("machine.logsTabSections.daemonLevelPlus",{level:a.toUpperCase()})},a))]}),n.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:UP.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 vE({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:s,searchQuery:r,lastUpdatedAt:o,autoRefresh:a,daemonFetchError:i,traceFetchError:l}){var h,p;const{t:d}=he("common"),u=((h=e.latestIssue)==null?void 0:h.severity)==="error"?"danger":((p=e.latestIssue)==null?void 0:p.severity)==="warn"?"warning":"good",m=i||l?"danger":a?"good":"neutral";return n.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[n.jsxs("div",{className:`rounded-xl border p-3 ${zc(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 ${zc(u)}`,children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted mb-2",children:d("machine.logsTabSections.latestIssue")}),e.latestIssue?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"text-xxs text-text-primary font-medium",children:[hu(e.latestIssue.source,d)," · ",e.latestIssue.severity.toUpperCase()]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),n.jsx("div",{className:"text-3xs text-text-muted mt-2",children:kx(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 ${zc(m)}`,children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted mb-2",children:d("machine.logsTabSections.sourceStatus")}),n.jsx("div",{className:"text-xxs text-text-primary font-medium",children:d(i||l?"machine.logsTabSections.needsAttention":a?"machine.logsTabSections.livePolling":"machine.logsTabSections.paused")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:d("machine.logsTabSections.lastUpdate",{time:bE(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 wE({patterns:e}){const{t}=he("common");return e.length===0?null:n.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted mb-2",children:t("machine.logsTabSections.repeatedIssuePatterns")}),n.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(s=>n.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[n.jsxs("div",{className:"text-xs text-text-primary font-medium",children:[s.count,"× ",s.severity.toUpperCase()," · ",hu(s.source,t)]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1 line-clamp-2",children:s.message})]},s.key))})]})}function SE({streams:e,sectionsOpen:t,setSectionsOpen:s,diagnosticEvents:r,visibleDaemonLogs:o,visibleDaemonRawLines:a,visibleTraceEntries:i,visibleWebEvents:l,quickFilter:d,searchQuery:u}){const{t:m}=he("common");return n.jsxs("div",{className:"grid gap-3",children:[n.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(h=>({...h,timeline:!h.timeline})),children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted",children:m("machine.logsTabSections.unifiedTimeline")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:m("machine.logsTabSections.visibleDiagnosticEvents",{count:r.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.timeline?m("machine.logsTabSections.hide"):m("machine.logsTabSections.show")})]}),t.timeline&&n.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-2xs leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.loadingDiagnostics")}),(e.daemonFetchError||e.traceFetchError)&&r.length===0&&n.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&n.jsx("div",{children:m("machine.logsTabSections.daemonLogsError",{error:e.daemonFetchError})}),e.traceFetchError&&n.jsx("div",{children:m("machine.logsTabSections.daemonTraceError",{error:e.traceFetchError})})]}),!e.daemonLoading&&!e.traceLoading&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.noDiagnosticsMatch")}),r.map(h=>n.jsx(gE,{event:h},h.id))]})]}),n.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(h=>({...h,daemon:!h.daemon})),children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted",children:m("machine.logsTabSections.rawSourceDaemonLogs")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:e.daemonLogKind==="text"?m("machine.logsTabSections.visibleRawLinesFallback",{count:a.length}):m("machine.logsTabSections.visibleStructuredLines",{count:o.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.daemon?m("machine.logsTabSections.hide"):m("machine.logsTabSections.show")})]}),t.daemon&&n.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-2xs leading-relaxed",children:[e.daemonLoading&&o.length===0&&a.length===0&&!e.daemonFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.loadingDaemonLogs")}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&n.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.noDaemonLogsYet")}),e.daemonLogKind==="text"&&a.length===0&&e.daemonRawText&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m(d==="all"?"machine.logsTabSections.noRawLinesMatchSearch":"machine.logsTabSections.rawFallbackOnlyInAll")}),e.daemonLogKind==="structured"&&o.length===0&&e.daemonLogs.length>0&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.noStructuredLogsMatch")}),e.daemonLogKind==="text"&&a.map((h,p)=>n.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:h},`raw-${p}`)),e.daemonLogKind!=="text"&&o.map((h,p)=>n.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${td(h.level)}`,children:[n.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(h.timestamp).toLocaleTimeString()}),n.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-4xs",children:h.level==="error"?"ERR":h.level==="warn"?"WRN":h.level==="debug"?"DBG":"INF"}),n.jsx("span",{className:"break-words",children:h.message})]},`log-${p}`))]})]}),n.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(h=>({...h,trace:!h.trace})),children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-3xs uppercase tracking-wider text-text-muted",children:[m("machine.logsTabSections.rawSourceDaemonTrace"),e.traceCategory==="session_host"?` · ${m("machine.logsTabSections.sessionHostOnly")}`:""]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:m("machine.logsTabSections.visibleTraceEvents",{count:i.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.trace?m("machine.logsTabSections.hide"):m("machine.logsTabSections.show")})]}),t.trace&&n.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-2xs leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.loadingDaemonTrace")}),!e.traceLoading&&e.traceFetchError&&i.length===0&&n.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:u.trim()?m("machine.logsTabSections.noTraceEntriesMatchSearch"):e.traceCategory==="session_host"?m("machine.logsTabSections.noSessionHostTraceYet"):m("machine.logsTabSections.noTraceEntriesYet")}),i.map(h=>n.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${td(h.level)}`,children:[n.jsxs("div",{className:"flex gap-2 text-3xs text-text-muted flex-wrap",children:[n.jsx("span",{children:new Date(h.ts).toLocaleTimeString()}),n.jsx("span",{children:h.level.toUpperCase()}),n.jsxs("span",{children:[h.category,".",h.stage]}),h.interactionId&&n.jsxs("span",{children:["ix=",h.interactionId]})]}),n.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:jr(h.payload,360)||m("machine.logsTabSections.noPayload")})]},h.id))]})]}),n.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(h=>({...h,web:!h.web})),children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted",children:m("machine.logsTabSections.rawSourceBrowserEvents")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:m("machine.logsTabSections.visibleBrowserEvents",{count:l.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.web?m("machine.logsTabSections.hide"):m("machine.logsTabSections.show")})]}),t.web&&n.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-2xs leading-relaxed",children:[l.length===0&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:u.trim()?m("machine.logsTabSections.noBrowserEventsMatchSearch"):m("machine.logsTabSections.noBrowserEventsYet")}),l.map(h=>n.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[n.jsxs("div",{className:"flex gap-2 text-3xs text-text-muted flex-wrap",children:[n.jsx("span",{children:new Date(h.ts).toLocaleTimeString()}),n.jsx("span",{children:h.kind}),h.topic&&n.jsxs("span",{children:["topic=",h.topic]}),h.interactionId&&n.jsxs("span",{children:["ix=",h.interactionId]})]}),n.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:jr(h.payload,360)||m("machine.logsTabSections.noPayload")})]},h.id))]})]})]})}function kE({machineId:e,sendDaemonCommand:t}){const s=nE({machineId:e,sendDaemonCommand:t}),[r,o]=c.useState("info"),[a,i]=c.useState(""),[l,d]=c.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),u=c.useRef(null),m=c.useRef(!1),h=c.useMemo(()=>fE({daemonLogs:s.daemonLogs,daemonRawText:s.daemonRawText,daemonLogKind:s.daemonLogKind,debugTrace:s.debugTrace,webEvents:s.webEvents,traceCategory:s.traceCategory,quickFilter:r,searchQuery:a,daemonLoading:s.daemonLoading,traceLoading:s.traceLoading,daemonFetchError:s.daemonFetchError,traceFetchError:s.traceFetchError}),[r,a,s.daemonFetchError,s.daemonLoading,s.daemonLogKind,s.daemonLogs,s.daemonRawText,s.debugTrace,s.traceCategory,s.traceFetchError,s.traceLoading,s.webEvents]);c.useEffect(()=>{if(s.autoRefresh&&h.diagnosticEvents.length>0){const f=m.current?"smooth":"instant";setTimeout(()=>{var x;(x=u.current)==null||x.scrollIntoView({behavior:f}),m.current=!0},50)}},[h.diagnosticEvents.length,s.autoRefresh]);const p=c.useCallback(async()=>{var x;const f=tE({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!f.trim()){nt.showToast("No visible logs to copy.","info");return}try{await((x=navigator.clipboard)==null?void 0:x.writeText(f)),nt.showToast("Copied visible logs to clipboard.","success")}catch(g){nt.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=mE({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((x=navigator.clipboard)==null?void 0:x.writeText(f)),nt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){nt.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(xE,{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(yE,{logLevel:s.logLevel,traceCategory:s.traceCategory,onLogLevelChange:s.setLogLevel,onTraceCategoryChange:s.setTraceCategory}),n.jsx(vE,{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(wE,{patterns:h.diagnosticsSummary.repeatedPatterns}),n.jsx(SE,{streams:s,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:r,searchQuery:a}),n.jsx("div",{ref:u})]})}function jE(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 jx(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 NE(e){var o;const t=[],s=[],r=[];for(const a of e||[]){const i=String((a==null?void 0:a.lifecycle)||"").trim(),l=jx((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 CE(e,t){return e==="live"?t?t("sessionHostSurface.attach"):"Attach":e==="recovery"?t?t("sessionHostSurface.recover"):"Recover":t?t("sessionHostSurface.restart"):"Restart"}function Vc(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 _E={starting:"sessionHostSurface.lifecycleStarting",running:"sessionHostSurface.lifecycleRunning",stopping:"sessionHostSurface.lifecycleStopping",stopped:"sessionHostSurface.lifecycleStopped",failed:"sessionHostSurface.lifecycleFailed",interrupted:"sessionHostSurface.lifecycleInterrupted"},AE={starting:"Starting",running:"Running",stopping:"Stopping",stopped:"Stopped",failed:"Failed",interrupted:"Interrupted"};function Jh(e,t){const s=_E[e];return s?t?t(s):AE[e]??e:e}function Gc(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Yc(e){return ki(e,{seconds:!0})||"—"}function Xh(e){return Ha(e)||"—"}function TE(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 IE(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ME(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 RE(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 PE({machineId:e,cliSessions:t,sendDaemonCommand:s}){const{t:r}=he("common"),[o,a]=c.useState(""),[i,l]=c.useState(null),{confirm:d,confirmDialog:u}=Tr(),[m,h]=c.useState(!1),p=E2(e,{enabled:!!e,includeSessions:!0,limit:oh,intervalMs:A2}),b=p.diagnostics,f=p.loading,x=p.applyDiagnostics,g=c.useMemo(()=>jE({diagnostics:b,loading:f,refreshing:m,error:o,t:r}),[b,f,m,o,r]),v=c.useMemo(()=>new Map(t.map(_=>[_.sessionId||_.id,_])),[t]),S=c.useCallback(async()=>{if(e){h(!0);try{const _=await s(e,"session_host_get_diagnostics",{includeSessions:!0,limit:oh}),I=Gc(_);if(!(I!=null&&I.success))throw new Error((I==null?void 0:I.error)||r("sessionHost.diagnosticsFailed"));x(I.diagnostics||I.result||null),a("")}catch(_){const I=_ instanceof Error?_.message:r("sessionHost.diagnosticsFailed");a(I)}finally{h(!1)}}},[x,e,s,r]);c.useEffect(()=>{!e||b||f||m||S()},[b,f,e,S,m]);const A=c.useCallback(async(_,I)=>{const D=`${_}:${I.sessionId}`;if(!(_==="session_host_stop_session"&&!await d({title:r("sessionHost.stopConfirmTitle",{name:I.displayName}),description:r("sessionHost.stopConfirmDescription"),confirmLabel:r("sessionHost.stop"),tone:"danger"}))){l(D);try{const L=await s(e,_,{sessionId:I.sessionId}),$=Gc(L);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||r("sessionHost.actionFailed"));const q=_==="session_host_resume_session"?"sessionHost.toastResumed":_==="session_host_restart_session"?"sessionHost.toastRestarted":"sessionHost.toastStopped";nt.showToast(r(q,{name:I.displayName}),"success"),await S()}catch(L){const $=L instanceof Error?L.message:r("sessionHost.actionFailed");nt.showToast($,"warning"),a($)}finally{l(L=>L===D?null:L)}}},[d,e,S,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",{}),D=Gc(I);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||r("sessionHost.pruneFailed"));const L=D.result||{},$=Array.isArray(L.prunedSessionIds)?L.prunedSessionIds.length:0,q=typeof L.duplicateGroupCount=="number"?L.duplicateGroupCount:0;nt.showToast(r("sessionHost.toastPruned",{pruned:$,groups:q}),"success"),await S()}catch(I){const D=I instanceof Error?I.message:r("sessionHost.pruneFailed");nt.showToast(D,"warning"),a(D)}finally{l(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[d,e,S,s,r]),w=c.useMemo(()=>[...(b==null?void 0:b.sessions)||[]].sort((_,I)=>(I.lastActivityAt||0)-(_.lastActivityAt||0)),[b==null?void 0:b.sessions]),y=c.useMemo(()=>b!=null&&b.liveRuntimes||b!=null&&b.recoverySnapshots||b!=null&&b.inactiveRecords?{liveRuntimes:(b==null?void 0:b.liveRuntimes)||[],recoverySnapshots:(b==null?void 0:b.recoverySnapshots)||[],inactiveRecords:(b==null?void 0:b.inactiveRecords)||[]}:NE(w),[b==null?void 0:b.inactiveRecords,b==null?void 0:b.liveRuntimes,b==null?void 0:b.recoverySnapshots,w]),N=y.liveRuntimes,j=y.recoverySnapshots,C=y.inactiveRecords,E=c.useMemo(()=>RE(N),[N]),P=c.useMemo(()=>[...(b==null?void 0:b.recentTransitions)||[]].slice(-6).reverse(),[b==null?void 0:b.recentTransitions]),T=c.useMemo(()=>[...(b==null?void 0:b.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[b==null?void 0:b.recentLogs]),M=(_,I)=>{var U;const D=i===`session_host_resume_session:${_.sessionId}`,L=i===`session_host_restart_session:${_.sessionId}`,$=i===`session_host_stop_session:${_.sessionId}`,q=jx(_.meta,r),G=v.get(_.sessionId),W=r("sessionHost.clientsCount",{count:_.attachedClients.length}),R=r(I==="recovery"?"sessionHost.recover":"sessionHost.resume"),O=r(I==="recovery"?"sessionHost.recovering":"sessionHost.resuming"),B=CE(I,r),H=Jh(_.lifecycle,r);return n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("div",{className:"font-medium text-xxs text-text-primary",children:_.displayName||(G==null?void 0:G.cliName)||_.providerType}),n.jsx("span",{className:`px-2 py-0.5 rounded-md text-3xs font-semibold ${ME(_.lifecycle)}`,children:H}),q&&n.jsx("span",{className:"px-2 py-0.5 rounded-md text-3xs font-semibold bg-sky-500/[0.08] text-sky-300",children:q})]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1 flex flex-wrap gap-2",children:n.jsx(Qt,{content:[_.runtimeKey,_.osPid?`pid ${_.osPid}`:""].filter(Boolean).join(" · "),children:n.jsx("span",{className:"text-text-primary/90",children:_.workspaceLabel||(G==null?void 0:G.runtimeWorkspaceLabel)||_.workspace||r("sessionHost.noWorkspace")})})}),n.jsxs("div",{className:"text-3xs text-text-secondary mt-1 flex flex-wrap gap-2",children:[n.jsx("span",{className:((U=_.writeOwner)==null?void 0:U.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:IE(_.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(Nw,{size:11})," ",W]}),n.jsx("span",{className:"text-text-muted",children:"·"}),n.jsx("span",{className:"text-text-primary/85",children:r("sessionHost.activeAgo",{time:Xh(_.lastActivityAt)})}),n.jsx("span",{className:"text-text-muted",children:"·"}),n.jsx("span",{className:"text-sky-200",children:r("sessionHost.nextAction",{action:B})})]})]}),n.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[I==="recovery"&&(_.lifecycle==="interrupted"||_.lifecycle==="failed"||_.lifecycle==="stopped")&&n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1",disabled:!!i,onClick:()=>{A("session_host_resume_session",_)},children:D?O:R}),n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1",disabled:!!i,onClick:()=>{A("session_host_restart_session",_)},children:r(L?"sessionHost.restarting":"sessionHost.restart")}),I==="live"&&(_.lifecycle==="running"||_.lifecycle==="starting"||_.lifecycle==="interrupted")&&n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{A("session_host_stop_session",_)},children:r($?"sessionHost.stopping":"sessionHost.stop")})]})]})},_.sessionId)};return n.jsxs(hn,{padding:"lg",className:"mb-5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[n.jsx(gr,{size:14})," ",r("sessionHost.title")]}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:mT()})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[E>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:E})}),n.jsx("span",{className:`px-2 py-1 rounded-md text-3xs font-semibold ${g.toneClass}`,children:g.label}),n.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{S()},disabled:f||m,children:[n.jsx(Ar,{size:13}),r(f||m?"sessionHost.refreshing":"sessionHost.refresh")]})]})]}),o&&!b&&n.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-xs text-amber-200 mb-3",children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(tn,{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:j.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:Xh(b.hostStartedAt)}),n.jsx("div",{className:"text-3xs text-text-secondary mt-0.5",children:Yc(b.hostStartedAt)})]})]}),T&&n.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-2xs text-text-secondary mb-4",children:[n.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[n.jsx(tn,{size:13})," ",r("sessionHost.latestWarning")]}),n.jsx("div",{className:"text-text-primary leading-relaxed",children:T.message}),n.jsxs("div",{className:"text-3xs text-text-secondary mt-1",children:[Yc(T.timestamp),T.sessionId?` · ${T.sessionId}`:""]})]}),n.jsxs("div",{className:"mb-4 space-y-4",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[n.jsx(bd,{size:14})," ",r("sessionHost.liveTitle")]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2.5",children:Vc("live",r)}),N.length===0?n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-xs text-text-secondary",children:r("sessionHost.liveEmpty")}):n.jsx("div",{className:"space-y-2",children:N.map(_=>M(_,"live"))})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[n.jsx(gr,{size:14})," ",r("sessionHost.recoveryTitle")]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2.5",children:Vc("recovery",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.recoveryEmpty")}):n.jsx("div",{className:"space-y-2",children:j.map(_=>M(_,"recovery"))})]}),C.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:Vc("inactive",r)}),n.jsx("div",{className:"space-y-2 opacity-85",children:C.map(_=>M(_,"inactive"))})]})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:r("sessionHost.recentActivity")}),P.length===0?n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-xs text-text-secondary",children:r("sessionHost.transitionsEmpty")}):n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:P.map(_=>{var D;const I=w.find(L=>L.sessionId===_.sessionId);return n.jsxs("div",{className:"px-3.5 py-2.5 text-2xs flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-text-primary font-medium",children:(I==null?void 0:I.displayName)||((D=v.get(_.sessionId))==null?void 0:D.cliName)||_.sessionId}),n.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[TE(_.action,r),_.lifecycle?` · ${Jh(_.lifecycle,r)}`:"",(_.detail||_.error)&&n.jsx(rt,{content:[_.detail,_.error].filter(Boolean).join(`
|
|
100
|
+
`),size:11,className:"ml-1"})]})]}),n.jsx("div",{className:`shrink-0 text-3xs ${_.success===!1?"text-red-300":"text-text-secondary"}`,children:Yc(_.timestamp)})]},`${_.sessionId}:${_.timestamp}:${_.action}`)})})]}),n.jsx(Hd,{className:"mt-3",rows:[{label:r("sessionHost.endpointLabel"),value:b.endpoint||null},{label:r("sessionHost.lastErrorLabel"),value:o||null,copyable:!1}]})]}),u]})}function EE({machine:e,launchPick:t,actions:s}){const{t:r}=he("common"),{runLaunchCliCore:o,setLaunchPick:a}=s;return c.useEffect(()=>{const i=l=>{l.key==="Escape"&&a(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[a]),n.jsx(Un,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",onClick:()=>a(null),children:n.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",onClick:i=>i.stopPropagation(),children:[n.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:r("machine.launchPick.title")}),n.jsx("p",{className:"text-2xs text-text-muted m-0 mb-4",children:r("machine.launchPick.description")}),n.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?n.jsx("span",{className:"text-2xs text-text-muted",children:r("machine.launchPick.empty")}):(e.workspaces||[]).map(i=>n.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-accent-primary/10 transition-colors",onClick:()=>{a(null),o({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[n.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),n.jsx("span",{className:"text-3xs text-text-muted font-mono truncate block",children:i.path})]},i.id))}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsx("button",{type:"button",className:"machine-btn text-2xs flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),o({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.defaultWorkspace")}),n.jsx("button",{type:"button",className:"machine-btn text-2xs flex-1 min-w-[120px]",onClick:()=>{a(null),o({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.homeDirectory")}),n.jsx("button",{type:"button",className:"machine-btn text-2xs flex-1 min-w-[80px]",onClick:()=>a(null),children:r("common.cancel")})]})]})})})}function LE(e,t){const s=jI(e),r=Rs(e,t),o=nu(e,r),a=Ta(e,r),i=$g(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 Qc({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 Jc({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 DE({machineEntry:e,providers:t,recentLaunches:s,currentConversations:r,onUpgradeDaemon:o,onOpenRecent:a,onOpenConversation:i}){const{t:l}=he("common"),d=r.slice(0,6),u=s.slice(0,4),h=LE(e,"1.0.75"),p=h.visible?[l(h.descriptionKey),h.targetVersion?h.channel?l("machine.commandCenter.updateTargetWithChannel",{version:h.targetVersion,channel:l(`machine.commandCenter.updateChannel.${h.channel}`)}):l("machine.commandCenter.updateTarget",{version:h.targetVersion}):""].filter(Boolean).join(`
|
|
101
|
+
`):"";return n.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(Qc,{icon:n.jsx(Cn,{size:13}),children:l("machine.commandCenter.currentChats")}),n.jsx(Jc,{children:n.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(b=>{const f=Ql(b);return n.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(b),children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[n.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[n.jsx(ws,{conversation:b,size:12}),n.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:kt(b)})]}),f>0&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:Si(f)})]}),n.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Po(b)})]},b.tabKey)})})})]}),u.length>0&&n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(Qc,{icon:n.jsx(fd,{size:13}),children:l("machine.commandCenter.recentLaunches")}),n.jsx(Jc,{children:n.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(b=>{const{metaText:f,updatedLabel:x}=Gg(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(Qc,{icon:n.jsx(tn,{size:13}),children:l("machine.commandCenter.daemonUpdate")}),n.jsx(Jc,{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(rt,{content:p})]}),n.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:o,children:[n.jsx(Ar,{size:13}),n.jsx("span",{className:"text-sm font-medium",children:h.targetVersion?l("machine.commandCenter.updateToVersion",{version:h.targetVersion}):l("machine.commandCenter.updateDaemon")})]})]})})]}),h.visible&&!h.showButton&&n.jsx("div",{"data-testid":"daemon-update-chip",children:n.jsx(Qt,{content:p,children:n.jsx("span",{className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-2xs font-medium ${h.tone==="good"?"border-emerald-500/20 bg-emerald-500/5 text-emerald-400":"border-border-subtle bg-bg-glass text-text-secondary"}`,children:h.tone==="good"?l("machine.commandCenter.upToDate"):l("machine.commandCenter.updateStatusUnknown")})})})]})}function nd(e){return e.trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function OE(e,t){return t.has(nd(e))}function $E({displayLabel:e,path:t,busy:s,onSave:r}){const{t:o}=he("common"),[a,i]=c.useState(!1),[l,d]=c.useState(e),[u,m]=c.useState(!1),h=c.useRef(null);c.useEffect(()=>{var x,g;a&&((x=h.current)==null||x.focus(),(g=h.current)==null||g.select())},[a]);const p=()=>{d(e),i(!0)},b=()=>{i(!1),d(e)},f=async()=>{m(!0);try{await r(t,l)&&i(!1)}finally{m(!1)}};return a?n.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[n.jsx("input",{ref:h,autoFocus:!0,value:l,maxLength:64,disabled:s||u,onChange:x=>d(x.target.value),onKeyDown:x=>{x.key==="Enter"&&f(),x.key==="Escape"&&b()},placeholder:o("machine.managedWorkspaces.renamePlaceholder"),"aria-label":o("machine.managedWorkspaces.rename"),className:"min-w-0 flex-1 px-1.5 py-0.5 rounded border border-accent/30 bg-bg-secondary text-text-primary text-2xs font-medium"}),n.jsx("button",{type:"button",title:o("machine.managedWorkspaces.saveName"),"aria-label":o("machine.managedWorkspaces.saveName"),className:"shrink-0 p-0.5 rounded text-green-400 hover:bg-green-500/15 transition-colors",disabled:s||u,onClick:()=>{f()},children:n.jsx(Cr,{size:12})}),n.jsx("button",{type:"button",title:o("machine.managedWorkspaces.cancelRename"),"aria-label":o("machine.managedWorkspaces.cancelRename"),className:"shrink-0 p-0.5 rounded text-text-muted/60 hover:text-text-primary hover:bg-bg-glass-hover transition-colors",disabled:u,onClick:b,children:n.jsx(Lt,{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(Aw,{size:12})})]})}function FE({machineId:e,machine:t,ideSessions:s,cliSessions:r,actions:o,sendDaemonCommand:a}){const{workspaceBusy:i,handleWorkspaceAdd:l,handleWorkspaceRemove:d,handleWorkspaceSetDefault:u,handleWorkspaceSetLabel:m}=o,{t:h}=he("common"),p=Vs(),b=Bd(),[f,x]=c.useState(!1),[g,v]=c.useState(()=>new Set),[S,A]=c.useState(null);c.useEffect(()=>{let D=!1;return(async()=>{try{let L=[];if(b!=null&&b.listMeshes)L=(await b.listMeshes(e)).map($=>$.workspace);else{const $=await a(e,"list_meshes",{}),q=($==null?void 0:$.result)??$;L=(Array.isArray(q==null?void 0:q.meshes)?q.meshes:[]).map(W=>{var R;return Array.isArray(W==null?void 0:W.nodes)&&W.nodes.length>0?String(((R=W.nodes[0])==null?void 0:R.workspace)||""):null})}if(D)return;v(new Set(L.filter($=>!!$).map(nd)))}catch{}})(),()=>{D=!0}},[e,b,a]);const k=c.useCallback(D=>{p("/dashboard",{state:{openNewSession:{machineId:e,workspaceId:D}}})},[e,p]),w=c.useCallback((D,L)=>{p("/dashboard",{state:{openNewSession:{machineId:e,workspaceId:D,mode:"mesh",meshWorkspacePath:L}}})},[e,p]),[y,N]=c.useState(""),[j,C]=c.useState([]),[E,P]=c.useState(!1),[T,M]=c.useState(""),_=c.useCallback(async D=>{P(!0),M("");try{const L=await ou(a,e,D);N(L.path),C(L.directories)}catch(L){M(L instanceof Error?L.message:"Could not load folder")}finally{P(!1)}},[e,a]),I=c.useCallback(()=>{x(!0);const D=[...s.map($=>$.workspace),...r.map($=>$.workspace)],L=ru(t.platform,su(D,t.defaultWorkspacePath,(t.workspaces||[]).map($=>$.path)));_(L)},[r,s,_,t.defaultWorkspacePath,t.platform,t.workspaces]);return n.jsxs(n.Fragment,{children:[n.jsxs(hn,{padding:"lg",className:"mb-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[n.jsxs("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[n.jsx(Ws,{size:14})," ",h("machine.managedWorkspaces.title")]}),n.jsxs("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:i,onClick:I,children:["+ ",h("machine.managedWorkspaces.addWorkspace")]})]}),(t.workspaces||[]).length===0?n.jsx("div",{className:"text-2xs text-text-muted py-4 text-center",children:h("machine.managedWorkspaces.empty",{button:h("machine.managedWorkspaces.addWorkspace")})}):n.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(D=>{const L=D.id===t.defaultWorkspaceId;return n.jsxs("li",{className:`flex items-start gap-2 text-2xs rounded-lg border px-2.5 py-2 transition-colors ${L?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[n.jsx("button",{type:"button",title:h(L?"machine.managedWorkspaces.unsetDefaultHint":"machine.managedWorkspaces.setDefaultHint"),disabled:i,onClick:()=>void u(L?null:D.id),className:`text-base leading-none shrink-0 transition-colors ${L?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[OE(D.path,g)?n.jsx($E,{displayLabel:va(D.path,D.label),path:D.path,busy:i,onSave:m}):n.jsx("div",{className:"font-medium text-text-primary truncate",children:va(D.path,D.label)}),n.jsx("div",{className:"font-mono text-text-muted truncate text-3xs",title:D.path,children:D.path})]}),n.jsxs("button",{type:"button",title:h("machine.managedWorkspaces.newSession"),className:"btn shrink-0 flex items-center gap-1 bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-2 py-1 rounded transition-colors text-3xs",disabled:i,onClick:()=>k(D.id),children:[n.jsx(go,{size:11}),h("machine.managedWorkspaces.newSessionShort")]}),g.has(nd(D.path))&&n.jsxs("button",{type:"button",title:h("machine.managedWorkspaces.newMeshSession"),className:"btn shrink-0 flex items-center gap-1 bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-2 py-1 rounded transition-colors text-3xs",disabled:i,onClick:()=>w(D.id,D.path),children:[n.jsx(go,{size:11}),h("machine.managedWorkspaces.newMeshSessionShort")]}),n.jsx("button",{type:"button",title:h("machine.managedWorkspaces.remove"),"aria-label":h("machine.managedWorkspaces.remove"),className:"shrink-0 p-1 rounded text-text-muted/60 hover:text-red-400 hover:bg-red-500/10 transition-colors",disabled:i,onClick:()=>A({id:D.id,label:va(D.path,D.label)}),children:n.jsx(Pw,{size:13})})]},D.id)})})]}),f&&n.jsx(iu,{title:h("machine.managedWorkspaces.addWorkspace"),description:h("machine.managedWorkspaces.addDialogDescription"),currentPath:y,directories:j,busy:E,error:T,confirmLabel:h("machine.managedWorkspaces.addWorkspace"),onClose:()=>x(!1),onNavigate:D=>{_(D)},onConfirm:D=>{(async()=>{if(!D)return;await l(D)&&x(!1)})()}}),S&&n.jsx(ff,{title:h("machine.managedWorkspaces.removeConfirmTitle"),description:h("machine.managedWorkspaces.removeConfirmDescription",{label:S.label}),confirmLabel:h("machine.managedWorkspaces.remove"),tone:"danger",busy:i,onCancel:()=>A(null),onConfirm:()=>{const D=S;A(null),D&&d(D.id)}})]})}function HE({machine:e,machineId:t,ideSessions:s,cliSessions:r,actions:o,sendDaemonCommand:a}){const{t:i}=he("common");return n.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[n.jsx("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:n.jsx("div",{className:"text-lg font-semibold text-text-primary",children:i("machine.managedWorkspaces.title")})}),a&&n.jsx(FE,{machineId:t,machine:e,ideSessions:s,cliSessions:r,actions:o,sendDaemonCommand:a})]})}function BE({onNicknameSynced:e}={}){var z,X,pe,Re,Oe,De,we,V,xe,Z,ae;const{t}=he("common"),{id:s}=dy(),r=Vs(),o=pi(),{sendCommand:a}=wt(),i=Rr(),l=Tg(),d=Mi(),u=d.ides||[],m=d.initialLoaded??!0,h=u.find(F=>F.id===s&&F.type==="adhdev-daemon"),p=u.some(F=>F.type==="adhdev-daemon"),b=s?(z=d.connectionRetryStatuses)==null?void 0:z[s]:void 0,f=!!(b!=null&&b.blocked),[x,g]=c.useState("workspace"),[v,S]=c.useState(null),[,A]=c.useState("ide"),k=c.useRef(null),[w,y]=c.useState(null),N=c.useRef("__home__"),[j,C]=c.useState("__home__"),[E,P]=c.useState(!1),T=c.useRef(null);c.useEffect(()=>{!s||!h||!(!h.workspaces||!h.availableProviders||!h.detectedIdes||!h.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,h,s]),c.useEffect(()=>{if(!s||!h||x!=="overview"&&x!=="providers")return;const F=h.machine;(typeof(F==null?void 0:F.cpus)!="number"||typeof(F==null?void 0:F.totalMem)!="number"||typeof(F==null?void 0:F.arch)!="string"||typeof(F==null?void 0:F.release)!="string"||!(F!=null&&F.quota))&&l(s,{minFreshMs:3e4}).catch(()=>{})},[x,l,h,s]),P2(s&&x==="overview"?[s]:[],{enabled:x==="overview",intervalMs:C2});const M=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},_=wP({machineId:s,registeredMachineId:(h==null?void 0:h.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:T});c.useEffect(()=>nt.onToast(se=>{d.setToasts(re=>{if(re.some(ue=>ue.message===se.message&&se.timestamp-ue.timestamp<3e3))return re;const Y={id:se.id,message:se.message,type:se.type,timestamp:se.timestamp,targetKey:se.targetKey,actions:se.actions,details:se.details};return[...re.slice(-4),Y]});const me=se.duration||5e3;setTimeout(()=>d.setToasts(re=>re.filter(Se=>Se.id!==se.id||Se.pinned)),me)}),[d]);const I=(h==null?void 0:h.availableProviders)||[],D={};for(const F of I)D[F.type]=F.icon;const L=h?{id:h.id,hostname:Ad(h,{fallbackId:h.id}),platform:((X=h.machine)==null?void 0:X.platform)||"unknown",arch:((pe=h.machine)==null?void 0:pe.arch)||"",cpus:((Re=h.machine)==null?void 0:Re.cpus)||0,totalMem:((Oe=h.machine)==null?void 0:Oe.totalMem)||0,freeMem:(De=h.machine)==null?void 0:De.freeMem,availableMem:(we=h.machine)==null?void 0:we.availableMem,loadavg:(V=h.machine)==null?void 0:V.loadavg,uptime:(xe=h.machine)==null?void 0:xe.uptime,release:((Z=h.machine)==null?void 0:Z.release)||"",cdpConnected:!!h.cdpConnected,machineNickname:h.machineNickname||null,...(ae=h.machine)!=null&&ae.quota?{quota:h.machine.quota}:{},p2p:h.p2p?{screenshotActive:!1,...h.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:h.detectedIdes||[],workspaces:h.workspaces||[],defaultWorkspaceId:h.defaultWorkspaceId??h.activeWorkspaceId??null,defaultWorkspacePath:h.defaultWorkspacePath??h.activeWorkspacePath??null}:null,$=u.filter(F=>F.daemonId===s&&F.type!=="adhdev-daemon").filter(F=>!So(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,version:F.version||"",instanceId:F.instanceId||"",status:F.status,workspace:F.workspace||null,terminals:F.terminals||0,aiAgents:iN(F.aiAgents||(F.agents||[]).map(se=>({id:se.name,name:se.name,status:se.status,version:se.version}))),activeChat:F.activeChat||null,chats:F.chats||[],childSessions:F.childSessions||[],cdpConnected:F.cdpConnected||!1,daemonId:s,lastMessageAt:F.lastMessageAt})),q=u.filter(F=>F.daemonId===s&&So(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,cliName:F.cliName||F.type,status:F.status,workspace:F.workspace||"",activeChat:F.activeChat||null,providerSessionId:F.providerSessionId,mode:F.mode,runtimeKey:F.runtimeKey,runtimeDisplayName:F.runtimeDisplayName,runtimeWorkspaceLabel:F.runtimeWorkspaceLabel,runtimeWriteOwner:F.runtimeWriteOwner||null,runtimeAttachedClients:F.runtimeAttachedClients||[],daemonId:s,lastMessageAt:F.lastMessageAt})),G=h?pn(h,{fallbackId:s}):"",W="workspace",R=o.state,O=R==null?void 0:R.initialMachineTab,B=R==null?void 0:R.initialWorkspaceCategory;R==null||R.initialWorkspaceId,R==null||R.initialWorkspacePath;const H=O==="session-host"?"hosted-runtimes":O==="logs"?"logs":null,U=O==="ides"||O==="clis"?"workspace":H?"overview":O||W,K=O==="ides"?"ide":O==="clis"?"cli":B,oe=[...$.map(F=>{var se;return{id:`ide:${F.type}:${F.workspace||""}`,label:((se=F.activeChat)==null?void 0:se.title)||F.type,kind:"ide",providerType:F.type,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),...q.map(F=>{var se;return{id:`cli:${F.type}:${F.workspace||""}`,label:((se=F.activeChat)==null?void 0:se.title)||F.cliName,kind:"cli",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}})].sort((F,se)=>(se.lastLaunchedAt||0)-(F.lastLaunchedAt||0)),ge=((h==null?void 0:h.recentLaunches)||[]).length>0?((h==null?void 0:h.recentLaunches)||[]).map(F=>({id:F.id,label:F.title||F.providerName||F.providerType,kind:F.kind,providerType:F.providerType,providerSessionId:F.providerSessionId,subtitle:wo(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace,summaryMetadata:F.summaryMetadata,lastLaunchedAt:F.lastLaunchedAt})):oe,J=c.useMemo(()=>{var se;const F=((se=d.connectionStates)==null?void 0:se[s||""])||void 0;return u.filter(me=>me.daemonId===s&&me.type!=="adhdev-daemon").flatMap(me=>Gd(me,{connectionStates:s&&F?{[s]:F}:void 0,defaultConnectionState:F})).filter(me=>!(me.transport==="pty"&&me.mode==="terminal")).sort((me,re)=>Ql(re)-Ql(me))},[u,d.connectionStates,s]),ke=c.useCallback(F=>{const se=Bg(F);se&&r(ko(se))},[r]),de=c.useCallback(()=>{k.current&&(P(!0),k.current().finally(()=>{k.current=null,P(!1),y(null)}))},[]),ne=c.useCallback(F=>{if(!L)return;const{options:se,selectedKey:me}=Vg({machine:L,currentWorkspacePath:F.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),re=async()=>{A(F.kind),g("workspace")};if(k.current=async()=>{const Se=se.find(fe=>fe.key===N.current),Y=(Se==null?void 0:Se.workspacePath)??null,ue=(Se==null?void 0:Se.workspaceId)??null;if(F.kind==="ide"&&F.providerType){await _.handleLaunchIde(F.providerType,Y?{workspace:Y}:void 0);return}if(F.kind==="cli"&&F.providerType){await _.runLaunchCliCore({cliType:F.providerType,dir:ue?void 0:Y||"",workspaceId:ue||void 0,resumeSessionId:F.providerSessionId});return}await re()},N.current=me,se.length<=1){const Se=k.current;k.current=null,Se==null||Se().catch(Y=>nt.showErrorToast(t("machine.detail.relaunchFailed"),Y));return}C(me),y({title:F.kind==="ide"?Za(t,"restart-ide",F.label):F.providerSessionId?hg(t,F.label):Za(t,"start-fresh",F.label),description:F.kind==="ide"?ei(t,"restart-ide"):F.providerSessionId?pg(t):ei(t,"start-fresh"),confirmLabel:F.kind==="ide"?ti(t,"restart-ide"):F.providerSessionId?Bl(t,!0):ti(t,"start-fresh"),busyLabel:F.kind==="ide"?ni(t,"restart-ide"):F.providerSessionId?ug(t,!0):ni(t,"start-fresh"),workspaceOptions:se,details:[{label:t("machine.detail.launchType"),value:F.kind.toUpperCase()},...F.providerType?[{label:t("machine.detail.launchProvider"),value:(()=>{const Se=I.find(ue=>ue.type===F.providerType),Y=(Se==null?void 0:Se.displayName)||F.providerType;return n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Fi,{type:F.providerType,label:Y,size:14}),Y]})})()}]:[]]})},[_,L,I,t]);if(c.useEffect(()=>{g(U)},[W,U,s]),c.useEffect(()=>{K&&A(K)},[K,s]),!L)return m?n.jsxs("div",{className:"p-10 text-center text-text-muted",children:[n.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),n.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),n.jsx("button",{onClick:M,className:"machine-btn-back",children:t("machine.detail.back")})]}):n.jsx("div",{className:"p-10 text-center text-text-muted",children:n.jsx("p",{children:t("machine.detail.loading")})});const le=(h==null?void 0:h.providerChannelStaleness)??null,te=!!le&&le.staleTypes.length+le.newTypes.length>0,ce=$.length+q.length,Ce=[{key:"workspace",icon:n.jsx(Bn,{size:14}),label:t("machine.detail.tabSessions"),trailing:ce>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:ce}):void 0},{key:"providers",icon:n.jsx(_r,{size:14}),label:t("machine.detail.tabProviders"),trailing:te?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(Mw,{size:14}),label:t("machine.detail.tabSystem")}],Q=Of[L.platform]||L.platform;return n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-border-subtle",children:[n.jsx("div",{className:"flex items-center justify-between w-full",children:n.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[n.jsx("button",{onClick:M,className:"flex items-center justify-center w-8 h-8 rounded-full bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),n.jsxs("div",{className:"flex flex-col min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[_.editingNickname?n.jsxs("div",{className:"flex gap-1.5 items-center",children:[n.jsx("input",{autoFocus:!0,value:_.nicknameInput,onChange:F=>_.setNicknameInput(F.target.value),onKeyDown:F=>{F.key==="Enter"&&_.handleSaveNickname(),F.key==="Escape"&&_.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-accent/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),n.jsx("button",{onClick:_.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:t("machine.detail.save")}),n.jsx("button",{onClick:()=>_.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-bg-glass text-text-muted hover:bg-bg-glass-hover hover:text-text-primary text-sm font-medium transition-colors",children:t("machine.detail.cancel")})]}):n.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{_.setEditingNickname(!0),_.setNicknameInput(L.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:G}),f?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),d.retryConnection&&s&&n.jsx("button",{onClick:()=>d.retryConnection(s),className:"px-2.5 py-0.5 rounded text-2xs font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):null]}),n.jsx("div",{className:"mt-1 text-xs text-text-secondary","data-testid":"machine-detail-subtitle",children:[t(f?"machine.card.status.failed":"machine.card.status.online"),Q].filter(Boolean).join(" · ")})]})]})}),n.jsx(Yd,{variant:"underline",tabs:Ce,activeKey:x,onSelect:F=>g(F),ariaLabel:t("machine.detail.tabsAriaLabel"),className:"mt-4 -mx-1 border-b-0 px-0 md:px-0",tabIdPrefix:"machine-tab"})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:n.jsx("div",{className:"max-w-7xl mx-auto h-full",children:n.jsxs("div",{className:"h-full",children:[x==="workspace"&&n.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[n.jsx(DE,{machineEntry:h,providers:I,recentLaunches:ge,currentConversations:J,onUpgradeDaemon:async()=>{const F=tu(h);if(F)try{await a(s,"daemon_upgrade",F)}catch{}},onOpenRecent:ne,onOpenConversation:ke}),n.jsx(HE,{machine:L,machineId:s,ideSessions:$,cliSessions:q,actions:_,sendDaemonCommand:a})]}),x==="providers"&&n.jsx(WP,{machineId:s,providers:I,sendDaemonCommand:a,quota:L.quota}),x==="overview"&&n.jsx(jP,{machine:L,ideSessions:$,cliSessions:q,daemonVersion:h==null?void 0:h.version,initialDiagnostics:H,renderHostedRuntimes:()=>n.jsx(PE,{machineId:s,cliSessions:q,sendDaemonCommand:a}),renderLogs:()=>n.jsx(kE,{machineId:s,sendDaemonCommand:a})})]})})}),_.launchPick&&L&&n.jsx(EE,{machine:L,launchPick:_.launchPick,actions:_}),w&&n.jsx(Ui,{title:w.title,description:w.description,details:w.details,workspaceOptions:w.workspaceOptions,selectedWorkspaceKey:j,onWorkspaceChange:F=>{N.current=F,C(F)},confirmLabel:w.confirmLabel,busyLabel:w.busyLabel,busy:E,onConfirm:de,onCancel:()=>{k.current=null,y(null)}}),v&&n.jsx(bx,{daemonId:v.daemonId,workspace:v.workspace,onClose:()=>S(null)}),_.confirmDialog,n.jsx(fg,{toasts:d.toasts||[],onDismiss:F=>d.setToasts(se=>se.filter(me=>me.id!==F)),onClickToast:F=>{F.targetKey&&r(ko(F.targetKey))}}),n.jsx("style",{children:`
|
|
102
|
+
@keyframes toast-in {
|
|
103
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
104
|
+
to { opacity: 1; transform: translateX(0); }
|
|
105
|
+
}
|
|
106
|
+
`})]})}const WE=new Set(["approvalAlert","noProgressAlert","noProgressThresholdSec","longGeneratingAlert","longGeneratingThresholdSec"]),UE=[{id:"approval",keys:["approvalAlert"]},{id:"noProgress",keys:["noProgressAlert","longGeneratingAlert"]}];function KE(e){return e.filter(t=>WE.has(t.key))}function qE({machineId:e,children:t}){return n.jsx(xp,{to:`/machines/${e}`,state:{initialMachineTab:"providers"},className:"text-accent-primary hover:underline",children:t})}function zE({machineId:e,children:t}){return uy()?n.jsx(qE,{machineId:e,children:t}):n.jsx("a",{href:`/machines/${e}`,className:"text-accent-primary hover:underline",children:t})}function VE({machines:e,onBrowserPrefChange:t,renderPushSection:s,initialLoaded:r=!0}){const{t:o}=he("common"),[a,i]=bN(),{sendCommand:l}=wt(),[d,u]=c.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission),[m,h]=c.useState({}),[p,b]=c.useState(!1),f=c.useMemo(()=>e.filter(w=>w.status==="online"),[e]);c.useEffect(()=>{const w=()=>{if(typeof window>"u"||!("Notification"in window)){u("unsupported");return}u(Notification.permission)};return w(),window.addEventListener("focus",w),document.addEventListener("visibilitychange",w),()=>{window.removeEventListener("focus",w),document.removeEventListener("visibilitychange",w)}},[]);const x=c.useCallback(async()=>{b(!0);const w={};for(const y of f)try{const N=await l(y.id,"get_provider_settings",{}),j=wx(N);if(j){const C=Sx(j,y.providers||[],{filterSchema:KE});C.length>0&&(w[y.id]=C)}}catch(N){console.warn("[Notifications] Failed to fetch settings from",y.id,N)}h(w),b(!1)},[f,l]);c.useEffect(()=>{f.length>0&&x()},[f.length]);const g=c.useMemo(()=>{const w=[];for(const[y,N]of Object.entries(m)){const j=f.find(E=>E.id===y),C=j?pn(j,{fallbackId:y}):y.slice(0,8);for(const E of N)w.push({...E,machineId:y,machineLabel:C})}return w},[m,f]),v=c.useCallback(async(w,y,N,j)=>{h(C=>{const E={...C};return E[w]=(E[w]||[]).map(P=>P.type===y?{...P,values:{...P.values,[N]:j}}:P),E});try{await l(w,"set_provider_setting",{providerType:y,key:N,value:j})}catch{}},[l]),S=c.useMemo(()=>UE.map(w=>{const y=g.map(j=>({entry:j,key:w.keys.find(C=>j.schema.some(E=>E.key===C))})).filter(j=>!!j.key),N=y.filter(({entry:j,key:C})=>{var E;return!!(j.values[C]??((E=j.schema.find(P=>P.key===C))==null?void 0:E.default))}).length;return{id:w.id,targets:y,total:y.length,onCount:N}}).filter(w=>w.total>0),[g]),A=c.useCallback(async(w,y)=>{const N=S.find(j=>j.id===w);if(N)for(const{entry:j,key:C}of N.targets)await v(j.machineId,j.type,C,y)},[S,v]),k=(w,y)=>{i({[w]:y}),t==null||t(w,y)};return n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsx(vg,{icon:n.jsx(Jn,{className:"text-text-primary"}),title:o("notifications.title"),subtitle:o("notifications.subtitle")}),n.jsxs("div",{className:"page-content",children:[n.jsx(vt,{title:o("notifications.sectionBrowserAlerts"),className:"mb-4",children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Jn,{size:15})," ",o("notifications.masterToggleLabel")]}),description:o("notifications.masterToggleDesc"),checked:a.globalEnabled,onChange:w=>k("globalEnabled",w)}),a.globalEnabled&&n.jsx("div",{className:"border-t border-border-subtle my-0.5"}),a.globalEnabled&&n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Bn,{size:15})," ",o("notifications.browserNotificationsLabel")]}),description:o("notifications.browserNotificationsDesc"),checked:a.browserNotifications,onChange:w=>k("browserNotifications",w)}),a.globalEnabled&&n.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-wrap items-center gap-2","data-testid":"browser-permission-row",children:[d==="granted"&&n.jsx("span",{className:"inline-flex items-center rounded-full border border-emerald-500/25 bg-emerald-500/10 px-2 py-0.5 text-3xs font-semibold text-emerald-400",children:o("notifications.permissionAllowedChip")}),d==="default"&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"inline-flex items-center rounded-full border border-amber-500/25 bg-amber-500/10 px-2 py-0.5 text-3xs font-semibold text-amber-400",children:o("notifications.permissionNeededChip")}),n.jsx("button",{onClick:()=>{Hf().then(u)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-2xs text-text-secondary hover:text-text-primary transition-colors",children:o("notifications.allowNotifications")})]}),d==="denied"&&n.jsx("span",{className:"inline-flex items-center rounded-full border border-amber-500/25 bg-amber-500/10 px-2 py-0.5 text-3xs font-semibold text-amber-400",children:o("notifications.permissionBlockedChip")}),d==="unsupported"&&n.jsx("span",{className:"inline-flex items-center rounded-full border border-border-subtle bg-bg-glass px-2 py-0.5 text-3xs font-semibold text-text-muted",children:o("notifications.permissionUnsupportedChip")}),n.jsx(rt,{content:[o(s?"notifications.browserBackgroundInfoWithPush":"notifications.browserBackgroundInfo"),d==="default"?o("notifications.permissionDefault"):d==="denied"?o("notifications.permissionDenied"):d==="unsupported"?o("notifications.permissionUnsupported"):""].filter(Boolean).join(`
|
|
107
|
+
|
|
108
|
+
`)})]}),a.globalEnabled&&a.browserNotifications&&n.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(vi,{size:15})," ",o("notifications.completionAlertsLabel")]}),description:o("notifications.completionAlertsDesc"),checked:a.completionAlert,onChange:w=>k("completionAlert",w)}),n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Iu,{size:15})," ",o("notifications.approvalAlertsLabel")]}),description:o("notifications.approvalAlertsDesc"),checked:a.approvalAlert,onChange:w=>k("approvalAlert",w)}),n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(xr,{size:15})," ",o("notifications.connectionAlertsLabel")]}),description:o("notifications.connectionAlertsDesc"),checked:a.disconnectAlert,onChange:w=>k("disconnectAlert",w)})]}),a.globalEnabled&&(s==null?void 0:s()),a.globalEnabled&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"border-t border-border-subtle my-0.5"}),n.jsx(GE,{})]}),!a.globalEnabled&&n.jsx("p",{className:"text-2xs text-text-muted italic",children:o("notifications.allDisabled")})]})}),n.jsx(vt,{title:o("notifications.sectionProviderAlerts"),description:o("notifications.agentAlertsDesc"),action:n.jsx(Wi,{onClick:()=>{x()},refreshing:p,label:o("notifications.refresh")}),className:"mb-4",children:r?f.length===0?n.jsx("p",{className:"text-sm text-text-muted py-6 text-center",children:o("notifications.noOnlineMachines")}):p&&g.length===0?n.jsx("p",{className:"text-sm text-text-muted py-6 text-center",children:o("notifications.loadingProviderSettings")}):n.jsxs("div",{className:"flex flex-col gap-3","data-testid":"agent-alert-toggles",children:[S.map(({id:w,total:y,onCount:N})=>n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[w==="approval"?n.jsx(Iu,{size:15}):n.jsx(fd,{size:15}),n.jsx("span",{children:o(`notifications.agentAlert.${w}`)}),N>0&&N<y&&n.jsx("span",{className:"text-3xs text-text-muted",children:o("notifications.mixed")})]}),description:o(`notifications.agentAlert.${w}Desc`),checked:N===y,onChange:j=>void A(w,j)},w)),n.jsxs("div",{className:"border-t border-border-subtle pt-3 text-2xs text-text-muted","data-testid":"per-provider-link",children:[o("notifications.perProviderIntro")," ",f.map((w,y)=>n.jsxs("span",{children:[y>0?", ":"",n.jsx(zE,{machineId:w.id,children:f.length>1?pn(w,{fallbackId:w.id}):o("notifications.machineProviders")})]},w.id))]})]}):n.jsx("p",{className:"text-sm text-text-muted py-6 text-center",children:o("notifications.loading")})})]})]})}function GE(){const{t:e}=he("common"),[t,s]=c.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),r=o=>{s(o);try{localStorage.setItem("adhdev_sound",o?"1":"0")}catch{}};return n.jsx(Vn,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Dw,{size:15})," ",e("notifications.soundEffectsLabel")]}),description:e("notifications.soundEffectsDesc"),checked:t,onChange:r})}const Xc=[];function Nx(...e){const t=new Set;for(const s of e){const r=$t(s);r&&t.add(r)}return[...t]}function YE(e,t){var h,p;const s=et(e==null?void 0:e.settings),r=$t((h=e==null?void 0:e.coordinator)==null?void 0:h.meshId)||$t(s.meshCoordinatorFor),o=$t(s.meshNodeFor),a=!!r||!!o,i=r===t||o===t;if(a&&!i)return null;const l=et(e==null?void 0:e.activeChat),d=Nx(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,l.sessionId,l.session_id,l.providerSessionId,l.provider_session_id),u=d[0]||"";if(!u)return null;const m=r===t?$t((p=e==null?void 0:e.coordinator)==null?void 0:p.role)||"coordinator":o===t?$t(s.meshNodeRole)||"worker":$t(e==null?void 0:e.role)||$t(s.meshNodeRole)||void 0;return{sessionId:u,aliases:d,meshId:t,nodeId:i&&$t(s.meshNodeId)||null,providerType:$t(e==null?void 0:e.providerType)||void 0,state:fi(e==null?void 0:e.status)??void 0,chatStatus:$t(l.status)||void 0,lifecycle:$t(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:$t(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:$t(e==null?void 0:e.runtimeRecoveryState)||void 0,...m?{role:m}:{},...i?{isSelfCoordinator:r===t}:{},workspace:$t(e==null?void 0:e.workspace)||null}}function Cx(e,t){var r;return t?(Array.isArray((r=e.status)==null?void 0:r.sessions)?e.status.sessions:[]).map(o=>YE(o,t)).filter(o=>o!==null):[]}function ci(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function QE(e,t){const s=new Set(ci(t));return ci(e).some(r=>s.has(r))}function JE(e,t){const s=t.filter(o=>!!o);return s.length===0?e:[...e.filter(o=>!s.some(a=>QE(o,a))),...s]}function XE(e,t){const s=e.nodes??[],r=s.filter(l=>{var d;return((d=l.connection)==null?void 0:d.state)==="self"}),o=r.length>0?r:t?s.filter(l=>en(String(l.daemonId||""),t)):[];if(o.length===1)return o[0].nodeId;const a=o.filter(l=>l.role==="host");if(a.length===1)return a[0].nodeId;const i=o.filter(l=>!l.isLocalWorktree);return i.length===1?i[0].nodeId:null}function ZE(e,t,s){if(t.length===0)return e;const r=t.some(d=>d.isSelfCoordinator&&!d.nodeId)?XE(e,s):null,o=new Map;for(const d of t)for(const u of ci(d))o.set(u,d);let a=!1;const l=(e.nodes??[]).map(d=>{const u=Array.isArray(d.activeSessionDetails)?d.activeSessionDetails:Array.isArray(d.sessions)?d.sessions:[],m=new Map;for(const p of u){const b=Nx(p==null?void 0:p.sessionId,p==null?void 0:p.session_id,p==null?void 0:p.id,p==null?void 0:p.providerSessionId,p==null?void 0:p.provider_session_id),f=b[0]||"";if(!f)continue;const x=b.map(g=>o.get(g)).find(Boolean);x&&(a=!0),m.set(f,x?{...p,sessionId:f,providerType:x.providerType||p.providerType,state:x.state||p.state,chatStatus:x.chatStatus||p.chatStatus,lifecycle:x.lifecycle||p.lifecycle,surfaceKind:x.surfaceKind||p.surfaceKind,recoveryState:x.recoveryState||p.recoveryState,role:x.role||p.role,isSelfCoordinator:x.isSelfCoordinator??p.isSelfCoordinator,workspace:x.workspace||p.workspace}:{...p,sessionId:f})}for(const p of d.activeSessions??[])m.has(p)||m.set(p,{sessionId:p,workspace:d.workspace,isCached:!0});for(const p of t){if(ci(p).some(g=>m.has(g)))continue;const f=p.nodeId!=null&&p.nodeId===d.nodeId,x=p.isSelfCoordinator&&!p.nodeId&&r!==null&&r===d.nodeId;!f&&!x||(a=!0,m.set(p.sessionId,{sessionId:p.sessionId,providerType:p.providerType,state:p.state,chatStatus:p.chatStatus,lifecycle:p.lifecycle,surfaceKind:p.surfaceKind,recoveryState:p.recoveryState,role:p.role,isSelfCoordinator:p.isSelfCoordinator,workspace:p.workspace||d.workspace}))}const h=[...m.values()];return h.length===0?d:{...d,activeSessionDetails:h,activeSessions:h.map(p=>p.sessionId)}});return a?{...e,nodes:l}:e}function eL(e,t){const r=Cx(e,t).map(o=>{var d;const a=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(u=>$t(u==null?void 0:u.id)===o.sessionId),i=et(a==null?void 0:a.activeInteractivePrompt),l=a!=null&&a.meshQueueStats&&typeof a.meshQueueStats=="object"?JSON.stringify(a.meshQueueStats):"";return[o.sessionId,o.providerType??"",o.state??"",o.chatStatus??"",o.lifecycle??"",o.surfaceKind??"",o.recoveryState??"",$t(i.status)||$t(i.kind)||$t(i.type),o.nodeId??"",o.isSelfCoordinator?"coordinator":"worker",l].join("|")}).filter(o=>!!o).sort();return r.length>0?r.join(`
|
|
109
|
+
`):null}function tL({status:e,daemonId:t,meshId:s,sendData:r,extraLiveSessions:o=Xc}){const[a,i]=c.useState(Xc),l=c.useRef(null);c.useEffect(()=>{l.current=null,i(Xc)},[t,s]),c.useEffect(()=>{if(!s||!r||!t)return;const u=Fn.subscribe({sendData:r},t,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${t}`,params:{includeSessions:!0}},m=>{if(m.topic!=="daemon.metadata")return;const h=eL(m,s);h!==l.current&&(l.current=h,i(Cx(m,s)))});return()=>{u()}},[t,s,r]);const d=c.useMemo(()=>JE(a,o),[o,a]);return c.useMemo(()=>e?ZE(e,d,t):null,[d,e,t])}function nL(e){return`mesh:status:${e}`}function _x({meshId:e,daemonId:t,sendData:s}){c.useEffect(()=>{if(!(!e||!t||!s))return LA(e),Fn.subscribe({sendData:s},t,{type:"subscribe",topic:"mesh.status",key:nL(e),params:{meshId:e}},r=>{if(r.topic!=="mesh.status"||r.meshId!==e)return;const o=Di(r.status);o&&EA(e,o,t)},{retryIntervalMs:2e3})},[e,t,s])}const Ax={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,coordinatorPrompt:!0,nodeInstruction:!0,reviewInbox:!0},Tx=c.createContext(null);function sL(){const e=c.useContext(Tx);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function pu(e){var r,o;const t=((r=e==null?void 0:e.error)==null?void 0:r.trim())||"Git discovery failed",s=(o=e==null?void 0:e.action)==null?void 0:o.trim();return s?`${t} ${s}`:t}const li="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function sd({workspaces:e,value:t,onChange:s,autoFocus:r}){const{t:o}=he("common"),[a,i]=c.useState(!1),l=new Set(e.map(u=>u.path)),d=a?"__custom":l.has(t)?t:"";return e.length===0||a?n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("input",{type:"text",className:li,value:t,autoFocus:r,placeholder:o("setupWizard.machines.workspacePlaceholder"),onChange:u=>s(u.target.value)}),e.length>0&&n.jsx("button",{type:"button",className:"self-start text-3xs text-accent-primary hover:underline",onClick:()=>i(!1),children:o("setupWizard.machines.pickFromKnown")})]}):n.jsxs("select",{className:li,value:d,onChange:u=>{u.target.value==="__custom"?(i(!0),s("")):s(u.target.value)},children:[n.jsx("option",{value:"",children:o("setupWizard.machines.workspaceSelectPlaceholder")}),e.map(u=>n.jsx("option",{value:u.path,children:u.label||u.path},u.path)),n.jsx("option",{value:"__custom",children:o("setupWizard.machines.workspaceCustom")})]})}function di(e){var t;return!!(e!=null&&e.success)&&((t=e==null?void 0:e.plan)==null?void 0:t.kind)!==void 0&&e.plan.kind!=="create_mesh_and_onboard"}function Ix(e,t){const[s,r]=c.useState(!1),o=c.useRef(null);return c.useEffect(()=>(e?o.current=setTimeout(()=>r(!0),t):r(!1),()=>{o.current&&clearTimeout(o.current)}),[e,t]),e&&s}function Mx({plan:e,loading:t}){var i,l,d;const{t:s}=he("common"),r=Ix(t,250);let o=null,a="text-2xs text-text-muted";return r?o=s("setupWizard.machines.planChecking"):(e==null?void 0:e.success)===!1?(a="text-2xs text-red-400",o=n.jsxs(n.Fragment,{children:[e.error,e.action?` ${e.action}`:""]})):di(e)?(a="text-2xs text-amber-400",o=((i=e.plan)==null?void 0:i.summary)||s("setupWizard.machines.planExists")):e&&(a="text-2xs text-emerald-400",o=s("setupWizard.machines.planOk",{identity:((l=e.discovery)==null?void 0:l.repoIdentity)||((d=e.discovery)==null?void 0:d.repoRoot)||""})),n.jsx("p",{className:`${a} min-h-[1.4em]`,children:o})}function rL(e){var t;return e.creating||e.planLoading||!e.name.trim()||e.showDaemonPicker&&!e.daemonId||((t=e.plan)==null?void 0:t.success)===!1||di(e.plan)?!0:e.workspace.trim()?!1:!e.repoRemoteUrl.trim()&&!e.repoIdentity.trim()}function Rx(e){var _,I;const{variant:t="page",showDaemonPicker:s,daemons:r,daemonLabel:o,name:a,onNameChange:i,daemonId:l,onDaemonIdChange:d,workspace:u,onWorkspaceChange:m,workspaces:h,plan:p,planLoading:b,repoRemoteUrl:f,onRepoRemoteUrlChange:x,repoIdentity:g,onRepoIdentityChange:v,manualOpen:S,onManualOpenChange:A,creating:k,warning:w,onCreate:y,onCancel:N}=e,{t:j}=he("common"),C=rL({creating:k,planLoading:b,plan:p,name:a,workspace:u,showDaemonPicker:s,daemonId:l,repoRemoteUrl:f,repoIdentity:g}),E=Ix(b,250),P=S||!!f.trim()||!!g.trim(),T=s&&r.length>0&&n.jsxs("select",{className:t==="wizard"?li:"input w-full",value:l,onChange:D=>d(D.target.value),children:[n.jsx("option",{value:"",children:j("setupWizard.machines.machineSelectPlaceholder")}),r.map(D=>n.jsx("option",{value:D.id,children:o(D)},D.id))]}),M=P?n.jsxs(n.Fragment,{children:[n.jsx(Ht,{label:j("mesh.list.remoteUrl"),hint:j("mesh.list.remoteUrlHint"),children:n.jsx(Nn,{value:f,onChange:D=>x(D.target.value),placeholder:"https://github.com/user/repo"})}),n.jsx(Ht,{label:j("mesh.list.repoIdentity"),hint:j("mesh.list.repoIdentityHint"),children:n.jsx(Nn,{value:g,onChange:D=>v(D.target.value),placeholder:"github.com/user/repo"})})]}):n.jsx("button",{type:"button",className:"self-start text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-3 bg-transparent border-none cursor-pointer p-0",onClick:()=>A(!0),children:j("mesh.list.advancedIdentityToggle")});return t==="wizard"?n.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:j("setupWizard.machines.meshName")}),n.jsx("input",{type:"text",className:li,value:a,onChange:D=>i(D.target.value)})]}),s&&r.length>1&&n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:j("setupWizard.machines.machine")}),T]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:j("setupWizard.machines.workspace")}),n.jsx(sd,{workspaces:h,value:u,onChange:m})]}),n.jsx(Mx,{plan:p,loading:b}),w&&n.jsx("p",{className:"text-2xs text-amber-400",children:w}),n.jsx("div",{className:"flex justify-end",children:n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:y,disabled:C,children:j(k?"setupWizard.machines.creating":"setupWizard.machines.create")})})]}):n.jsxs(n.Fragment,{children:[n.jsx("h3",{className:"text-base font-bold mb-4",children:j("mesh.list.createTitle")}),s&&n.jsx(Ht,{label:j("mesh.list.createOnMachine"),children:r.length===0?n.jsx("select",{className:"input w-full",disabled:!0,children:n.jsx("option",{value:"",children:j("mesh.list.noConnectedDaemon")})}):T}),n.jsx(Ht,{label:j("mesh.list.workspace"),hint:j("mesh.list.workspaceHint"),children:n.jsx(sd,{workspaces:h,value:u,onChange:m})}),(E||p)&&n.jsx(Bt,{variant:(p==null?void 0:p.success)===!1?"error":di(p)?"warning":"info",className:"mb-4",children:E?j("setupWizard.machines.planChecking"):(p==null?void 0:p.success)===!1?pu(p):di(p)?((_=p.plan)==null?void 0:_.summary)||j("setupWizard.machines.planExists"):`${((I=p.plan)==null?void 0:I.summary)||"Git repository detected."} No changes will be made until you click Create.`}),n.jsx(Ht,{label:j("mesh.list.name"),children:n.jsx(Nn,{value:a,onChange:D=>i(D.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),n.jsx("div",{className:"flex flex-col",children:M}),n.jsxs("div",{className:"flex gap-2 mt-3",children:[n.jsx("button",{className:"btn btn-primary btn-sm",onClick:y,disabled:C,children:j(k?"mesh.list.creating":"mesh.list.create")}),N&&n.jsx("button",{className:"btn btn-secondary btn-sm",onClick:N,disabled:k,children:j("mesh.list.cancel")})]})]})}function oL({size:e=14}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),n.jsx("circle",{cx:"18",cy:"6",r:"3"}),n.jsx("circle",{cx:"6",cy:"18",r:"3"}),n.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function aL({size:e=14}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function iL({size:e=14}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}const cL={online:"#22c55e",dirty:"#f59e0b",offline:"#6b7280",degraded:"#ef4444",enabled:"#22c55e",pending:"#a855f7",assigned:"#3b82f6",completed:"#22c55e",failed:"#ef4444",unknown:"#6b7280"};function lL({status:e}){const{t}=he("common"),s=cL[e]??"#6b7280",r=e==="degraded"?t("mesh.nodeHealth.degradedHint"):void 0,o=n.jsxs("span",{className:"inline-flex items-center gap-1 text-3xs font-semibold px-2 py-0.5 rounded-md",style:{background:s+"15",color:s,border:`1px solid ${s}25`},children:[n.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:s}}),n2(e,t)]});return r?n.jsx(Qt,{content:r,children:o}):o}function Px(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function dL(e){const t=new Map;for(const s of e)s!=null&&s.id&&t.set(s.id,Wn(s.availableProviders||[]));return t}function uL(e,t){const s=String(e.daemon_id||e.daemonId||"");return s&&t.has(s)?t.get(s):!s&&t.size===1?[...t.values()][0]:[]}function Ex(e){if(!e)return null;const t=et(e.nodeFacts).availableProviders;if(Array.isArray(t)&&t.length>0)return t;const s=et(e.heldRuntime).availableProviders;return Array.isArray(s)&&s.length>0?s:null}function mL(e){if(!e)return[];const t=et(e.nodeFacts),s=Object.keys(et(e.providerVersions)).length>0?et(e.providerVersions):et(t.providerVersions),r=et(t.providerEnablement);return Object.keys(s).map(o=>o.trim()).filter(o=>o&&et(r[o]).enabled!==!1)}function hL(e,t,s){const r=Ex(s);if(r)return Wn(r);const o=uL(e,t),a=mL(s);if(a.length===0)return o;if(o.length>0){const i=new Set(a);return o.filter(l=>i.has(l.type))}return Wn(a.map(i=>({type:i,category:"cli",installed:!0})))}function pL(e,t,s){const r=new Map;for(const d of t)d!=null&&d.id&&r.set(d.id,Array.isArray(d.availableProviders)?d.availableProviders:[]);const o=new Set,a=[];let i=0,l=0;for(const d of Array.isArray(e)?e:[]){const u=String((d==null?void 0:d.daemon_id)||(d==null?void 0:d.daemonId)||""),m=fu(d,s),h=Ex(m)??(u?r.get(u):r.size===1?[...r.values()][0]:void 0);if(!h||h.length===0){l++;continue}i++;for(const p of h){const b=String((p==null?void 0:p.type)||(p==null?void 0:p.id)||"").trim();!b||o.has(b)||(o.add(b),a.push(p))}}return a.sort((d,u)=>String((d==null?void 0:d.type)||(d==null?void 0:d.id)||"").localeCompare(String((u==null?void 0:u.type)||(u==null?void 0:u.id)||""))),{providers:a,reportedNodeCount:i,unreportedNodeCount:l}}function fu(e,t){const s=String((e==null?void 0:e.id)||(e==null?void 0:e.nodeId)||"").trim();if(!(!s||!Array.isArray(t)))return t.find(r=>(r==null?void 0:r.nodeId)===s)}function fL(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},s=new Set,r=[],o=a=>{const i=typeof a=="string"?a.trim():"";!i||s.has(i)||(s.add(i),r.push(i))};for(const a of kp(t.slots))o(a.provider);if(Array.isArray(t.providerPriority))for(const a of t.providerPriority)o(a);return r}function bL(e){var d,u;const t=e,s=[],r=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of r){const h=typeof m=="string"?m.trim():"";h&&s.push({tag:h,custom:!0})}const o=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),a=(((u=t.userOverrides)==null?void 0:u.arch)||t.reportedArch||"").toString().trim();o&&s.push({tag:`os=${o}`,custom:!1}),a&&s.push({tag:`arch=${a}`,custom:!1});for(const m of fL(t.policy))s.push({tag:`provider=${m}`,custom:!1});const i=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";t.isLocalWorktree===!0&&i&&s.push({tag:`worktree=${i}`,custom:!1});const l=new Set;return s.filter(m=>l.has(m.tag)?!1:(l.add(m.tag),!0))}function gL(e){return(Array.isArray(e==null?void 0:e.activeSessionDetails)?e.activeSessionDetails:[]).filter(s=>!!(s!=null&&s.sessionId)).map(s=>({id:s.sessionId,provider:s.providerType||"unknown",status:s.chatStatus||s.state||"unknown"}))}function Lx(e){var r,o;if(!e)return null;const t=typeof e.machineStatus=="string"?e.machineStatus.trim():"";if(t)return t;const s=(r=e.connection)==null?void 0:r.state;return s==="self"||s==="connected"?"online":typeof((o=e.gitObservation)==null?void 0:o.unreachableSince)=="number"||s==="failed"||s==="closed"||s==="disconnected"?"offline":null}function xL(e){const t=e==null?void 0:e.nodeFacts,s=typeof(t==null?void 0:t.machineNickname)=="string"&&t.machineNickname.trim()?t.machineNickname.trim():void 0,r=typeof(t==null?void 0:t.platform)=="string"&&t.platform.trim()?t.platform.trim():void 0;return{...s?{machineNickname:s}:{},...r?{platform:r}:{}}}const yL=["","low","medium","high"],vL={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Zh(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function ep(e){const t=e.provider.trim();if(!t)return null;const s=e.model.trim(),r=e.thinkingLevel.trim()||void 0,o=Number(e.maxParallel),a=Number.isFinite(o)&&o>0?Math.floor(o):void 0;return{provider:t,...s?{model:s}:{},...r?{thinkingLevel:r}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...a!==void 0?{maxParallel:a}:{}}}function wL(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const Ts="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function SL({slots:e,availableProviders:t,saving:s,onSave:r}){const{t:o}=he("common"),[a,i]=c.useState(()=>e.map(Zh)),l=c.useMemo(()=>JSON.stringify(e),[e]);c.useEffect(()=>{i(e.map(Zh))},[l]);const d=c.useMemo(()=>[...new Set(t.map(S=>S.type).filter(Boolean))],[t]),u=c.useMemo(()=>H1(t),[t]),m=c.useMemo(()=>{const S=a.map(ep).filter(Boolean);return JSON.stringify(S)!==JSON.stringify(e)},[a,e]),h=(S,A)=>i(k=>k.map((w,y)=>y===S?{...w,...A}:w)),p=(S,A)=>i(k=>k.map((w,y)=>{var C;if(y!==S)return w;const N=((C=u.get(A))==null?void 0:C.models)??[],j=!w.model||N.length===0||N.includes(w.model);return{...w,provider:A,...j?{}:{model:""}}})),b=S=>i(A=>A.filter((k,w)=>w!==S)),f=()=>i(S=>[...S,wL()]),x=(S,A)=>i(k=>{const w=S+A;if(w<0||w>=k.length)return k;const y=[...k];return[y[S],y[w]]=[y[w],y[S]],y}),g=(S,A)=>i(k=>k.map((w,y)=>{if(y!==S)return w;const N=w.difficulty.includes(A);return{...w,difficulty:N?w.difficulty.filter(j=>j!==A):[...w.difficulty,A]}})),v=()=>r(a.map(ep).filter(Boolean));return n.jsxs("div",{className:"flex flex-col gap-2",onClick:S=>S.stopPropagation(),children:[a.length===0&&n.jsxs("div",{className:"flex items-center gap-1 text-xs text-text-muted",children:[n.jsx("span",{children:o("mesh.slotEditor.empty")}),n.jsx(rt,{content:o("mesh.slotEditor.emptyHint"),size:12})]}),a.map((S,A)=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[n.jsxs("span",{className:"text-2xs font-semibold text-text-muted",children:["#",A+1]}),n.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[n.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:A===0,onClick:()=>x(A,-1),title:o("mesh.slotEditor.moveUp"),children:"↑"}),n.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:A===a.length-1,onClick:()=>x(A,1),title:o("mesh.slotEditor.moveDown"),children:"↓"}),n.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>b(A),"aria-label":o("mesh.slotEditor.removeSlot"),children:n.jsx(Lt,{size:12})})]})]}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.provider")}),d.length>0?n.jsxs("select",{className:Ts,value:S.provider,onChange:k=>p(A,k.target.value),children:[n.jsx("option",{value:"",children:o("mesh.slotEditor.select")}),d.map(k=>n.jsx("option",{value:k,children:k},k)),S.provider&&!d.includes(S.provider)&&n.jsx("option",{value:S.provider,children:S.provider})]}):n.jsx("input",{className:Ts,value:S.provider,placeholder:"claude-cli",onChange:k=>h(A,{provider:k.target.value})})]}),(()=>{var j;const k=u.get(S.provider),w=(k==null?void 0:k.models)??[],y=(j=k==null?void 0:k.thinking)!=null&&j.length?["",...k.thinking]:yL,N=!!S.model&&w.length>0&&!w.includes(S.model);return n.jsxs(n.Fragment,{children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.model")}),w.length>0&&!N?n.jsxs("select",{className:Ts,value:w.includes(S.model)?S.model:"",onChange:C=>h(A,{model:C.target.value==="__custom__"?" ":C.target.value}),children:[n.jsx("option",{value:"",children:o("mesh.slotEditor.providerDefault")}),w.map(C=>n.jsx("option",{value:C,children:C},C)),n.jsx("option",{value:"__custom__",children:o("mesh.slotEditor.custom")})]}):n.jsxs(n.Fragment,{children:[n.jsx("input",{className:Ts,value:S.model.trim(),placeholder:S.provider?`${S.provider} model`:o("mesh.slotEditor.modelPlaceholder"),onChange:C=>h(A,{model:C.target.value})}),w.length>0&&n.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-3xs text-text-muted hover:underline",onClick:()=>h(A,{model:""}),children:o("mesh.slotEditor.backToModelList")})]})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.thinking")}),n.jsx("select",{className:Ts,value:S.thinkingLevel,onChange:C=>h(A,{thinkingLevel:C.target.value}),children:y.map(C=>n.jsx("option",{value:C,children:C||o("mesh.slotEditor.thinkingDefault")},C||"_default"))})]})]})})()]}),n.jsxs("div",{className:"mt-2",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.difficulty")}),n.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:Sp.map(k=>{const w=S.difficulty.includes(k);return n.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-2xs font-medium transition-colors ${w?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>g(A,k),children:vL[k]},k)})})]}),n.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.capabilityTags")}),n.jsx("input",{className:Ts,value:S.capability.join(", "),placeholder:"worktree, os=darwin",onChange:k=>h(A,{capability:k.target.value.split(",").map(w=>w.trim()).filter(Boolean)})})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.maxParallel")}),n.jsx("input",{type:"number",inputMode:"numeric",min:1,className:Ts,value:S.maxParallel,placeholder:o("mesh.slotEditor.maxParallelPlaceholder"),onChange:k=>h(A,{maxParallel:k.target.value})})]})]})]},A)),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:f,children:[n.jsx(go,{size:13})," ",o("mesh.slotEditor.addSlot")]}),n.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:v,disabled:!!s||!m,children:o(s?"mesh.slotEditor.saving":"mesh.slotEditor.saveSlots")})]})]})}function kL(e){const t=e.capabilities;return Array.isArray(t)?t.map(s=>typeof s=="string"?s.trim():"").filter(Boolean):[]}const jL=["os=","arch=","provider=","worktree="];function NL({node:e,saving:t,onSave:s}){const{t:r}=he("common"),o=c.useMemo(()=>bL(e).filter(x=>!x.custom),[e]),a=c.useMemo(()=>kL(e),[e]),[i,l]=c.useState(a),[d,u]=c.useState(""),m=JSON.stringify(i)!==JSON.stringify(a),p=(x=>{const g=x.trim();return g?/\s/.test(g)?r("mesh.tagEditor.noSpaces"):jL.some(v=>g.toLowerCase().startsWith(v))?r("mesh.tagEditor.reservedPrefix"):i.includes(g)?r("mesh.tagEditor.alreadyAdded"):null:null})(d);function b(){const x=d.trim();!x||p||(l(g=>[...g,x]),u(""))}function f(x){l(g=>g.filter(v=>v!==x))}return n.jsxs("div",{className:"mt-2",onClick:x=>x.stopPropagation(),children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[n.jsx("span",{className:"text-3xs uppercase tracking-wide text-text-muted mr-1",children:r("mesh.tagEditor.routingTags")}),o.map(x=>n.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-3xs text-text-muted",title:r("mesh.tagEditor.autoDerivedTitle"),children:x.tag},x.tag)),i.map(x=>n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-3xs text-accent-primary",title:r("mesh.tagEditor.customTagTitle"),children:[x,n.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>f(x),disabled:t,"aria-label":r("mesh.tagEditor.remove",{tag:x}),children:"×"})]},x))]}),n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[n.jsx("input",{type:"text",value:d,onChange:x=>u(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),b())},placeholder:r("mesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-xs text-text-primary"}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:b,disabled:t||!d.trim()||!!p,children:r("mesh.tagEditor.add")}),m&&n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>s(i),disabled:t,children:r(t?"mesh.tagEditor.saving":"mesh.tagEditor.saveTags")})]}),p&&n.jsx("div",{className:"mt-1 text-2xs text-amber-400",children:p}),i.length===0&&o.length===0&&n.jsxs("div",{className:"mt-1 flex items-center gap-1 text-2xs text-text-muted",children:[n.jsx("span",{children:r("mesh.tagEditor.empty")}),n.jsx(rt,{content:r("mesh.tagEditor.emptyHint"),size:12})]})]})}function CL(e,t){var s;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((s=e==null?void 0:e.user)==null?void 0:s.name)||t||"You"}function tp({nodes:e,statusNodes:t,meshQueue:s,daemons:r,userName:o,features:a,providersByDaemonId:i,savingNodeSlotsId:l,onUpdateNodeSlots:d,savingNodeCapabilitiesId:u,onUpdateNodeCapabilities:m,nodeSystemPromptDrafts:h,onNodeSystemPromptDraftChange:p,savingNodeSystemPromptId:b,onSaveNodeSystemPrompt:f,selectedNodeId:x,onSelectNode:g,onRemoveNode:v}){const{t:S}=he("common"),[A,k]=c.useState(()=>new Set),w=y=>k(N=>{const j=new Set(N);return j.has(y)?j.delete(y):j.add(y),j});return e.length===0?n.jsx(Bi,{variant:"compact",icon:n.jsx(Ws,{size:14}),title:S("mesh.nodeList.emptyTitle"),description:S("mesh.nodeList.emptyDescription")}):n.jsx("div",{className:"flex flex-col gap-2",children:e.map(y=>{var L;const N=IL(y),j=_L(y,s),C=fu(y,t),E=gL(C),P=x===y.id,T=A.has(y.id),M=Lx(C)||y.status||(j.length>0||E.length>0?"active":"enabled"),_=a.addNodeDaemonPicker?y.machine_label||y.machine_nickname||y.hostname||y.workspace:y.workspace.split("/").pop()||y.workspace,I=N.configured?N.label.split(" → "):[],D=a.addNodeDaemonPicker?S("mesh.nodeList.ownerMachine",{owner:CL(r.find($=>$.id===String(y.daemon_id||"")),o),machine:y.machine_label||y.daemon_id||y.workspace}):null;return n.jsxs("div",{className:`rounded-xl border bg-bg-glass px-4 py-3 transition-colors ${a.addNodeDaemonPicker?"border-border-subtle":`cursor-pointer ${P?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:a.addNodeDaemonPicker?void 0:"button",tabIndex:a.addNodeDaemonPicker?void 0:0,onClick:a.addNodeDaemonPicker?void 0:()=>g(P?null:y.id),onKeyDown:a.addNodeDaemonPicker?void 0:$=>{$.target===$.currentTarget&&($.key==="Enter"||$.key===" ")&&($.preventDefault(),g(P?null:y.id))},children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[n.jsx("span",{className:"truncate text-sm font-semibold text-text-primary",title:y.workspace,children:_}),a.addNodeDaemonPicker&&n.jsx(lL,{status:M}),!N.configured&&n.jsx(Qt,{content:S("mesh.nodeList.launchBlocked"),children:n.jsx("span",{className:"rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-3xs font-medium text-amber-400",children:S("mesh.nodeList.launchBlockedChip")})})]}),n.jsxs("div",{className:"mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 text-2xs text-text-muted",children:[I.length>0&&n.jsx("span",{className:"truncate",children:S("mesh.nodeList.usesTools",{tools:I.join(", ")})}),a.addNodeDaemonPicker&&n.jsx("span",{className:"truncate font-mono text-3xs",title:y.workspace,children:y.workspace.split("/").filter(Boolean).pop()||y.workspace})]})]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0","aria-expanded":T,onClick:$=>{$.stopPropagation(),w(y.id)},children:S(T?"common.done":"common.edit")}),n.jsx("button",{type:"button",className:"shrink-0 bg-transparent border-none cursor-pointer text-text-muted transition-colors hover:text-red-400",onClick:$=>{$.stopPropagation(),v(y.id)},"aria-label":S("mesh.nodeList.removeNode"),title:S("mesh.nodeList.removeNode"),children:n.jsx(aL,{size:14})})]}),T&&n.jsxs("div",{className:"mt-3 max-w-2xl cursor-default",onClick:$=>$.stopPropagation(),children:[n.jsx(Ht,{label:S("mesh.nodeList.slotsLabel"),hint:S("mesh.nodeList.slotsHint"),children:n.jsx(SL,{slots:Array.isArray((L=y.policy)==null?void 0:L.slots)?y.policy.slots:[],availableProviders:hL(y,i,C),saving:l===y.id,onSave:$=>d(y,$)})}),n.jsxs("details",{className:"group",children:[n.jsxs("summary",{className:"cursor-pointer select-none text-xs text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[n.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",S("mesh.nodeList.advanced")]}),n.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[n.jsx(NL,{node:y,saving:u===y.id,onSave:$=>m(y,$)}),a.nodeInstruction&&n.jsxs(Ht,{label:S("mesh.nodeList.nodeInstruction"),hint:S("mesh.nodeList.nodeInstructionHint"),className:"mb-0",children:[n.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:h[y.id]??"",onChange:$=>{const q=$.target.value;p(y.id,q)},disabled:b===y.id,placeholder:S("mesh.nodeList.nodeInstructionPlaceholder")}),n.jsx("div",{className:"mt-2 flex items-center gap-2",children:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>f(y),disabled:b===y.id,children:b===y.id?S("mesh.nodeList.saving"):S("mesh.nodeList.saveInstruction")})})]}),n.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-xs text-text-muted",children:[D&&n.jsx("div",{className:"mb-2",children:D}),n.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary",children:S("mesh.nodeList.repoRoot")})," ",n.jsx("span",{className:"font-mono break-all",children:y.repoRoot||y.workspace})]}),n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary",children:S("mesh.nodeList.activeSessionsLabel")})," ",E.length]}),a.addNodeDaemonPicker&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary",children:S("mesh.nodeList.added")})," ",xd(y.created_at||y.createdAt)||"—"]})]}),n.jsxs("div",{className:"mt-3",children:[n.jsx("div",{className:"text-text-secondary mb-1",children:S("mesh.nodeList.activeQueueAssignments")}),j.length===0?n.jsx("div",{children:S("mesh.nodeList.noActiveAssignment")}):n.jsx("ul",{className:"m-0 pl-4",children:j.map($=>n.jsx("li",{className:"font-mono",children:AL($)},$.id))})]}),E.length>0&&n.jsxs("div",{className:"mt-3",children:[n.jsx("div",{className:"text-text-secondary mb-1",children:S("mesh.nodeList.activeSessions")}),n.jsx("ul",{className:"m-0 pl-4",children:E.map($=>n.jsxs("li",{className:"font-mono",children:[$.provider," / ",$.status]},$.id))})]}),n.jsx(Hd,{className:"mt-3",rows:[{label:S("mesh.nodeList.nodeId"),value:y.id},...E.map($=>({label:S("mesh.nodeList.activeSessions"),value:$.id}))]})]})]})]})]})]},y.id)})})}function _L(e,t){return t.filter(s=>s.status!=="assigned"?!1:(s.assignedNodeId||s.nodeId)===e.id)}function AL(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",s=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${s}`}function TL(e){var o,a;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((o=e.policy)==null?void 0:o.providerPriority)?e.policy.providerPriority:[],s=new Set,r=t.map(i=>typeof i=="string"?i.trim():"").filter(Boolean).filter(i=>s.has(i)?!1:(s.add(i),!0));return r.length?r:My((a=e.policy)==null?void 0:a.slots)}function IL(e){const t=TL(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider configured on this node — task launch is blocked until a capability slot or provider priority is set."}}function ML(e){return e.isLocalWorktree===!0}function ui(e){return e&&(e.machineNickname||e.nickname||e.hostname||(e.id?Ng(e.id):void 0))||"Unknown"}function RL(e){return String(e.daemon_id||e.daemonId||"")}function Dx(e,t,s){const r=new Map(t.map(i=>[i.id,i])),o=[],a=new Map;for(const i of e){const l=RL(i);a.has(l)||(a.set(l,[]),o.push(l)),a.get(l).push(i)}return o.map(i=>{const l=a.get(i),d=i?r.get(i):void 0,u=l[0],m=l.map(g=>fu(g,s)).filter(g=>!!g),h=m.map(g=>xL(g).machineNickname).find(Boolean),p=i?h||(d?ui(d):(u==null?void 0:u.machine_label)||(u==null?void 0:u.machine_nickname)||(u==null?void 0:u.hostname)||i):ui(d),b=m.map(g=>Lx(g)).filter(g=>!!g),f=b.length>0?b.includes("online"):(d==null?void 0:d.status)==="online",x=l.reduce((g,v)=>{var S;return g+(Array.isArray((S=v.policy)==null?void 0:S.slots)?v.policy.slots.length:0)},0);return{key:i,label:p,online:f,nodes:l,slotCount:x}})}function PL({groups:e,activeKey:t,onChange:s}){const{t:r}=he("common");return n.jsx(Yd,{variant:"underline",ariaLabel:r("mesh.nodeList.machineTabsLabel"),activeKey:t,onSelect:s,className:"mb-4 px-1 md:px-1",tabs:e.map(o=>({key:o.key,icon:n.jsx("span",{"aria-hidden":!0,className:`w-1.5 h-1.5 rounded-full shrink-0 ${o.online?"bg-green-400":"bg-neutral-500"}`}),label:n.jsx("span",{className:"truncate max-w-[160px]",children:o.label}),trailing:n.jsx("span",{className:"text-2xs text-text-muted font-normal",children:r("mesh.nodeList.machineTabCounts",{nodes:o.nodes.length,slots:o.slotCount})})}))})}function EL({nodes:e,statusNodes:t,meshQueue:s,activeDaemon:r,daemons:o,selectedMeshId:a,userName:i,features:l,coordinatorDaemonId:d,availableCliProviders:u,savingNodeSlotsId:m,onUpdateNodeSlots:h,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:b,nodeSystemPromptDrafts:f,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:v,selectedNodeId:S,onSelectNode:A,showAddNode:k,onShowAddNode:w,onCancelAddNode:y,nodeWorkspace:N,onNodeWorkspaceChange:j,nodeProviderPriority:C,onNodeProviderPriorityChange:E,nodeDaemonId:P,onNodeDaemonIdChange:T,nodeCustomPath:M,onNodeCustomPathChange:_,nodePickerWorkspaces:I,nodePickerProviders:D,nodeOnboardingPlan:L,nodePlanLoading:$,attachableDaemons:q,onAddNode:G,onRemoveNode:W}){var ge,J,ke;const{t:R}=he("common"),O=c.useMemo(()=>dL(o),[o]),B=c.useMemo(()=>e.filter(de=>!ML(de)),[e]),H=c.useMemo(()=>l.addNodeDaemonPicker?Dx(B,o,t):[],[l.addNodeDaemonPicker,B,o,t]),[U,K]=c.useState(null),oe=H.some(de=>de.key===U)?U:((ge=H[0])==null?void 0:ge.key)??"";return n.jsxs(vt,{title:l.addNodeDaemonPicker?R("mesh.nodeList.title",{count:B.length}):R("mesh.nodeList.titleNoCount"),description:l.addNodeDaemonPicker?R("mesh.nodeList.descriptionCloud"):R("mesh.nodeList.descriptionStandalone"),children:[l.addNodeDaemonPicker&&n.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[n.jsx("div",{className:"min-w-0 text-sm font-semibold text-text-primary",children:R("mesh.nodeList.daemonCandidates")}),n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:R("mesh.nodeList.available",{count:q.length})})]}),o.length===0?n.jsx("div",{className:"text-xs text-text-muted",children:R("mesh.nodeList.noDaemonsAvailable")}):q.length===0?n.jsx("div",{className:"text-xs text-text-muted",children:R("mesh.nodeList.allDaemonsAttached")}):n.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:q.map(de=>n.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors min-w-0 ${de.id===d?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{T(de.id),j(""),_(!1),E(Ks(Wn(de.availableProviders||[]))),w()},children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-sm font-medium truncate min-w-0",children:ui(de)}),de.id===d&&n.jsx("span",{className:"text-3xs text-accent-primary shrink-0",children:R("mesh.nodeList.selectedHost")})]}),n.jsx("div",{className:"mt-1 text-2xs text-text-muted",children:R("mesh.nodeList.workspacesDetected",{count:(de.workspaces||[]).length})})]},de.id))})]}),!k&&n.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:w,children:[n.jsx(iL,{size:13})," ",l.addNodeDaemonPicker?R("mesh.nodeList.attachMachine"):R("mesh.nodeList.addNode")]}),k&&n.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[n.jsxs("div",{className:"flex justify-between items-center mb-3",children:[n.jsx("h4",{className:"text-sm font-bold",children:l.addNodeDaemonPicker?R("mesh.nodeList.attachMachineTitle"):R("mesh.nodeList.addNodeTitle")}),n.jsx("button",{onClick:()=>{y(),T(""),_(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:n.jsx(Lt,{size:16})})]}),l.addNodeDaemonPicker&&n.jsx(Ht,{label:R("mesh.nodeList.machine"),children:n.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:P,onChange:de=>{var ne;T(de.target.value),j(""),_(!1),E(Ks(Wn(((ne=o.find(le=>le.id===de.target.value))==null?void 0:ne.availableProviders)||[])))},children:[n.jsx("option",{value:"",children:R("mesh.nodeList.selectMachine")}),o.map(de=>n.jsx("option",{value:de.id,children:ui(de)},de.id))]})}),(l.addNodeDaemonPicker?P:!0)&&n.jsx(Ht,{label:R("mesh.nodeList.workspacePath"),children:l.addNodeDaemonPicker&&!M&&I.length>0?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:I.map(de=>n.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${N===de.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>j(de.path),children:[n.jsx("span",{className:"font-medium block truncate",children:de.label||de.path.split("/").pop()}),n.jsx("span",{className:"text-3xs text-text-muted font-mono truncate block",children:de.path})]},de.id||de.path))}),n.jsx("button",{type:"button",className:"text-2xs text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{_(!0),j("")},children:R("mesh.nodeList.enterCustomPath")})]}):n.jsx(n.Fragment,{children:l.addNodeDaemonPicker?n.jsxs(n.Fragment,{children:[n.jsx(Nn,{value:N,onChange:de=>j(de.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:de=>{de.key==="Enter"&&G()}}),I.length>0&&n.jsx("button",{type:"button",className:"text-2xs text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{_(!1),j("")},children:R("mesh.nodeList.pickFromSaved")})]}):(()=>{var le;const de=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],ne=`mesh-add-node-workspaces-${a||"new"}`;return n.jsxs(n.Fragment,{children:[n.jsx(Nn,{value:N,onChange:te=>j(te.target.value),placeholder:((le=de[0])==null?void 0:le.path)||"/Users/dev/projects/myapp",list:de.length>0?ne:void 0,autoFocus:!0}),de.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("datalist",{id:ne,children:de.map(te=>n.jsx("option",{value:te.path,children:te.label||te.path},te.id||te.path))}),n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:de.slice(0,6).map(te=>n.jsx("button",{type:"button",onClick:()=>j(te.path),className:"text-2xs px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:te.path,children:te.label||te.path.split("/").filter(Boolean).pop()||te.path},te.id||te.path))})]})]})})()})}),($||L)&&n.jsx(Bt,{variant:(L==null?void 0:L.success)===!1?"error":"info",className:"mb-4",children:$?R("mesh.nodeList.inspectingRepo"):L!=null&&L.success?`${((J=L.plan)==null?void 0:J.summary)||R("mesh.nodeList.compatibleWorkspace")} ${R("mesh.nodeList.addingIsExplicit")}`:pu(L)}),n.jsx(Ht,{label:R("mesh.nodeList.preferredTools"),hint:R("mesh.nodeList.preferredToolsHint"),children:n.jsx(MT,{value:C,availableProviders:l.addNodeDaemonPicker?D:u,onChange:E})}),n.jsxs("div",{className:"flex gap-2 mt-3",children:[n.jsx("button",{onClick:G,disabled:$||(L==null?void 0:L.success)===!1||!N.trim()||l.addNodeDaemonPicker&&!P,className:"btn btn-primary btn-sm",children:R("mesh.nodeList.add")}),n.jsx("button",{onClick:()=>{y(),T(""),_(!1)},className:"btn btn-secondary btn-sm",children:R("mesh.nodeList.cancel")})]})]}),B.length===0?n.jsx(Bi,{icon:n.jsx(Ws,{}),title:R("mesh.nodeList.emptyTitle"),description:R("mesh.nodeList.emptyDescription")}):l.addNodeDaemonPicker?n.jsxs(n.Fragment,{children:[H.length>1&&n.jsx(PL,{groups:H,activeKey:oe,onChange:K}),n.jsx(tp,{nodes:((ke=H.find(de=>de.key===oe))==null?void 0:ke.nodes)||B,statusNodes:t,meshQueue:s,daemons:o,userName:i,features:l,providersByDaemonId:O,savingNodeSlotsId:m,onUpdateNodeSlots:h,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:b,nodeSystemPromptDrafts:f,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:v,selectedNodeId:S,onSelectNode:A,onRemoveNode:W})]}):n.jsx(tp,{nodes:B,statusNodes:t,meshQueue:s,daemons:o,userName:i,features:l,providersByDaemonId:O,savingNodeSlotsId:m,onUpdateNodeSlots:h,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:b,nodeSystemPromptDrafts:f,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:v,selectedNodeId:S,onSelectNode:A,onRemoveNode:W})]})}function LL(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function DL({meshes:e,loading:t,error:s,onDismissError:r,daemons:o,features:a,showCreate:i,onToggleCreate:l,createName:d,onCreateNameChange:u,createRepoIdentity:m,onCreateRepoIdentityChange:h,createRepoRemoteUrl:p,onCreateRepoRemoteUrlChange:b,newMeshDaemonId:f,onNewMeshDaemonIdChange:x,newMeshWorkspace:g,onNewMeshWorkspaceChange:v,createPickerWorkspaces:S,createOnboardingPlan:A,createPlanLoading:k,creating:w,createWarning:y,onDismissCreateWarning:N,onSelectMesh:j,onCreate:C,onCancelCreate:E,sendCommand:P}){const{t:T}=he("common"),[M,_]=c.useState(!1),[I,D]=c.useState(null);return n.jsxs(Lo,{icon:n.jsx(On,{}),title:T("mesh.list.title"),subtitle:T("mesh.list.count",{count:e.length}),subtitleInline:!0,widthClassName:"max-w-5xl",actions:n.jsx("button",{className:"btn btn-primary btn-sm",onClick:l,children:T("mesh.list.createMesh")}),children:[s&&n.jsx(Bt,{variant:"error",onDismiss:r,className:"mb-4",children:s}),y&&n.jsx(Bt,{variant:"warning",onDismiss:N,className:"mb-4",children:y}),i&&n.jsx(vt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:n.jsx(Rx,{variant:"page",showDaemonPicker:a.createDaemonPicker,daemons:o,daemonLabel:LL,name:d,onNameChange:u,daemonId:f,onDaemonIdChange:x,workspace:g,onWorkspaceChange:v,workspaces:S,plan:A,planLoading:k,repoRemoteUrl:p,onRepoRemoteUrlChange:b,repoIdentity:m,onRepoIdentityChange:h,manualOpen:M,onManualOpenChange:_,creating:w,onCreate:C,onCancel:E})}),t?n.jsx("div",{className:"text-sm text-text-muted p-4",children:T("mesh.list.loading")}):e.length===0?n.jsx(Bi,{icon:n.jsx(On,{}),title:T("mesh.list.emptyTitle"),description:o.length>0?T("mesh.list.emptyWithDaemons"):T("mesh.list.emptyNoDaemons"),action:n.jsx("button",{className:"btn btn-primary btn-sm",disabled:!o.length,onClick:l,children:T("mesh.list.createFirst")})}):n.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(L=>{const $=Array.isArray(L.nodes)?L.nodes:[],q=Dx($.filter(H=>H.isLocalWorktree!==!0),o).filter(H=>H.key),G=q.filter(H=>H.online).length,W=Do(L,o),R=!!W&&o.some(H=>en(H.id,W)&&(H.status===void 0||H.status==="online")),O=L.createdAt||L.created_at,B=q.length===0?"bg-neutral-500":G===q.length?"bg-green-400":G===0?"bg-red-400":"bg-amber-400";return n.jsxs("div",{className:"flex w-full flex-col gap-3 rounded-xl border border-border-subtle bg-bg-glass px-4 py-3.5 transition-colors hover:border-border-default sm:flex-row sm:items-center",children:[n.jsxs("button",{type:"button",onClick:()=>j(L.id),className:"min-w-0 flex-1 cursor-pointer border-none bg-transparent p-0 text-left",children:[n.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[n.jsx(On,{size:16}),n.jsx("span",{className:"truncate text-sm font-bold text-text-primary",children:L.name})]}),n.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs text-text-muted",children:[n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx("span",{"aria-hidden":!0,className:`h-1.5 w-1.5 rounded-full ${B}`}),q.length>0?T("mesh.list.machinesOnline",{online:G,total:q.length}):T("mesh.list.nodeCount",{count:$.length||L.nodeCount||0})]}),n.jsx("span",{className:"truncate font-mono",children:L.repoIdentity||L.repo_identity||T("mesh.list.noRepoIdentity")}),(L.defaultBranch||L.default_branch)&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(oL,{size:11}),L.defaultBranch||L.default_branch]}),O&&n.jsx(Qt,{content:To(O),children:n.jsx("span",{children:xd(O)})})]})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>j(L.id),children:T("mesh.list.settings")}),P&&n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",disabled:!R,title:R?void 0:T("mesh.detail.observabilityDisabledTitle"),onClick:()=>D({meshId:L.id,daemonId:W,meshName:L.name}),children:T("mesh.list.open")})]})]},L.id)})}),I&&P&&n.jsx(qd,{activeConv:Px(I),sendDaemonCommand:P,onClose:()=>D(null)})]})}const C3="inline-flex h-5 min-w-0 max-w-full shrink-0 items-center gap-1 whitespace-nowrap rounded-full border px-2 text-3xs font-medium leading-none";function _3(e){return`inline-flex h-6 shrink-0 items-center gap-1 whitespace-nowrap rounded-full border px-2.5 text-3xs font-medium leading-none transition-colors ${e?"border-accent/50 bg-accent/10 text-accent":"border-border-default bg-transparent text-text-secondary hover:bg-bg-glass-hover hover:text-text-primary"}`}function A3(e){switch(e){case"good":return"border-status-online/30 text-status-online";case"warn":return"border-status-warning/35 text-status-warning";case"danger":return"border-status-error/35 text-status-error";case"neutral":default:return"border-border-default text-text-secondary"}}const T3="rounded-md border border-border-default bg-surface-primary px-1.5 py-0.5 text-3xs font-medium",OL={default:"border-border-default bg-transparent text-text-secondary",good:"border-status-online/30 bg-transparent text-status-online",warn:"border-status-warning/35 bg-transparent text-status-warning",danger:"border-status-error/35 bg-transparent text-status-error",info:"border-border-default bg-transparent text-text-secondary"},$L={default:"border-border-default bg-bg-glass text-text-primary hover:bg-bg-glass-hover",info:"border-accent/40 bg-transparent text-accent hover:bg-accent/10",success:"border-status-online/35 bg-transparent text-status-online hover:bg-status-online/10"},np={textPrimary:"text-text-primary",textSecondary:"text-text-secondary",textMuted:"text-text-muted",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-xl border border-border-subtle bg-bg-secondary",graphStatChipClass:"rounded-full border border-border-default bg-surface-primary px-3 py-1 text-text-secondary",graphHintChipClass:"rounded-full border border-border-default bg-surface-primary px-3 py-1 text-3xs text-text-muted",graphControlsClass:"!bottom-3 !left-3 !shadow-sm",blueprintShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-xl border border-border-subtle bg-bg-secondary",edgeLabelTextColor:"var(--text-secondary)",edgeLabelBackgroundColor:"var(--surface-primary)",edgeLabelBorderColor:"var(--border-default)",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-2 border-b border-border-subtle bg-bg-primary px-4 pb-0 pt-4 md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-text-primary md:text-xl",dialogKickerClass:"rounded-full border border-border-default px-2.5 py-1 text-2xs text-text-secondary",dialogSubtitleClass:"mt-1 truncate text-sm text-text-muted",dialogRefreshedChipClass:"rounded-full border border-border-default px-3 py-1.5 text-xs text-text-secondary",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-lg border border-border-default bg-bg-glass text-text-secondary transition hover:bg-bg-glass-hover hover:text-text-primary",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-bg-primary px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-xl border border-dashed border-border-default px-6 text-center text-sm text-text-muted",cardClass:"rounded-xl border border-border-subtle bg-bg-card",cardHeaderClass:"border-b border-border-subtle px-4 py-3",cardTitleClass:"text-sm font-semibold text-text-primary",cardSubtitleClass:"mt-1 text-xs text-text-muted",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-border-subtle py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-text-muted",rowValueClass:"min-w-0 flex-1 break-all text-right text-text-primary",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-border-default bg-surface-primary p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-border-subtle bg-surface-primary p-4 text-xs text-text-muted md:w-64",panelTitleClass:"truncate text-xs font-semibold text-text-primary",panelCloseButtonClass:"text-xs text-text-muted hover:text-text-primary",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-border-subtle py-0.5 text-2xs",panelFieldLabelClass:"shrink-0 text-text-muted",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-text-primary",infoCalloutClass:"mt-1 rounded-md border border-border-default bg-bg-glass px-2 py-1.5 text-3xs text-text-secondary",badge:e=>OL[e],actionButton:e=>$L[e]};function Ox(e){return e==="light"?{...np,theme:e,isDark:!1,flowColorMode:"light",graphBackgroundDotColor:"rgba(15, 23, 42, 0.10)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center bg-[rgba(15,23,42,0.55)] px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",dialogShellClass:"flex shrink-0 h-[calc(100dvh-32px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-2rem)] w-full flex-col overflow-hidden rounded-xl border border-border-default bg-bg-primary shadow-lg md:h-[calc(100dvh-32px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-2xl"}:{...np,theme:e,isDark:!0,flowColorMode:"dark",graphBackgroundDotColor:"rgba(255, 255, 255, 0.06)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center bg-[rgba(0,0,0,0.72)] px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",dialogShellClass:"flex shrink-0 h-[calc(100dvh-32px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-2rem)] w-full flex-col overflow-hidden rounded-xl border border-border-default bg-bg-primary shadow-lg md:h-[calc(100dvh-32px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-2xl"}}const Vi=c.createContext(Ox("dark"));function Xr({label:e,tone:t="default",className:s,title:r}){const o=c.useContext(Vi),a=n.jsx("span",{className:`inline-flex h-5 shrink-0 items-center whitespace-nowrap rounded-full border px-2 align-middle text-3xs font-medium leading-none ${o.badge(t)}${s?` ${s}`:""}`,children:e});return r?n.jsx(Qt,{content:r,children:a}):a}function I3({label:e,value:t}){const s=c.useContext(Vi);return n.jsxs("div",{className:s.rowClass,children:[n.jsx("span",{className:s.rowLabelClass,children:e}),n.jsx("span",{className:s.rowValueClass,children:t})]})}function $x(e){let t=e??"";return t?(t=t.replace(/^```[^\n]*\n?/gm,""),t=t.replace(/^#{1,6}\s+/gm,""),t=t.replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm,""),t=t.replace(/^>\s?/gm,""),t=t.replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"$2"),t=t.replace(/(^|\W)[*_](?=\S)([^*_\n]*\S)[*_](?=\W|$)/g,"$1$2"),t=t.replace(/`([^`\n]*)`/g,"$1"),t=t.replace(/[ \t]{2,}/g," "),t=t.replace(/\n{3,}/g,`
|
|
110
|
+
|
|
111
|
+
`),t.trim()):""}function M3(e){return $x((e??"").trim())}const ma=["provider_quirk","pattern_to_avoid","recovery_lesson"],sp=240,FL={provider_quirk:"warn",pattern_to_avoid:"danger",recovery_lesson:"good"};function Zc(e,t){return e(t==="provider_quirk"?"mesh.notes.categoryProviderQuirk":t==="pattern_to_avoid"?"mesh.notes.categoryPatternToAvoid":t==="recovery_lesson"?"mesh.notes.categoryRecoveryLesson":"mesh.notes.categoryUncategorized")}function ha(e){return To(e)}function HL({meshId:e,daemonId:t,sendDaemonCommand:s}){const{t:r}=he("common"),o=c.useContext(Vi),[a,i]=c.useState([]),[l,d]=c.useState(!1),[u,m]=c.useState(null),[h,p]=c.useState(!1),[b,f]=c.useState(!1),[x,g]=c.useState(""),[v,S]=c.useState(""),[A,k]=c.useState(new Set),[w,y]=c.useState(null),[N,j]=c.useState(""),[C,E]=c.useState(""),P=!!(s&&t&&e),T=c.useCallback(async()=>{if(!(!s||!t||!e)){d(!0),m(null);try{const W=await s(t,"list_mesh_notes",{meshId:e,tail:100}),R=(W==null?void 0:W.result)??W;if(R&&R.success===!1){m(typeof R.error=="string"?R.error:r("mesh.notes.loadFailed")),i([]);return}const O=Array.isArray(R==null?void 0:R.notes)?R.notes:[];i([...O].reverse())}catch(W){m(W instanceof Error?W.message:r("mesh.notes.loadFailed")),i([])}finally{d(!1)}}},[s,t,e,r]);c.useEffect(()=>{T()},[T]);const M=c.useCallback(async()=>{if(!s||!t||!e)return;const W=x.trim();if(!(!W||h)){p(!0),m(null);try{const R=await s(t,"record_mesh_note",{meshId:e,text:W,...v?{category:v}:{}}),O=(R==null?void 0:R.result)??R;if(O&&O.success===!1){m(typeof O.error=="string"?O.error:r("mesh.notes.saveFailed"));return}g(""),S(""),f(!1),await T()}catch(R){m(R instanceof Error?R.message:r("mesh.notes.saveFailed"))}finally{p(!1)}}},[s,t,e,x,v,h,T,r]),_=c.useCallback(async W=>{if(!(!s||!t||!e||h)){p(!0),m(null);try{const R=await s(t,"forget_mesh_note",{meshId:e,noteId:W}),O=(R==null?void 0:R.result)??R;if(O&&O.success===!1){m(typeof O.error=="string"?O.error:r("mesh.notes.deleteFailed"));return}await T()}catch(R){m(R instanceof Error?R.message:r("mesh.notes.deleteFailed"))}finally{p(!1)}}},[s,t,e,h,T,r]),I=c.useCallback(W=>{y(W.id),j(W.text),E(ma.includes(W.category)?W.category:"")},[]),D=c.useCallback(()=>{y(null),j(""),E("")},[]),L=c.useCallback(async W=>{if(!s||!t||!e||h)return;const R=N.trim();if(R){p(!0),m(null);try{const O=await s(t,"forget_mesh_note",{meshId:e,noteId:W}),B=(O==null?void 0:O.result)??O;if(B&&B.success===!1){m(typeof B.error=="string"?B.error:r("mesh.notes.editFailed"));return}const H=await s(t,"record_mesh_note",{meshId:e,text:R,...C?{category:C}:{}}),U=(H==null?void 0:H.result)??H;if(U&&U.success===!1){m(typeof U.error=="string"?U.error:r("mesh.notes.editFailed"));return}D(),await T()}catch(O){m(O instanceof Error?O.message:r("mesh.notes.editFailed"))}finally{p(!1)}}},[s,t,e,N,C,h,D,T,r]),$=o.isDark?"rounded-lg border border-white/10 bg-slate-950/40 px-2.5 py-1.5 text-xs text-slate-200":"rounded-lg border border-slate-300 bg-white px-2.5 py-1.5 text-xs text-slate-700",q=o.isDark?"w-full rounded-lg border border-white/10 bg-slate-950/40 px-3 py-2 text-sm text-slate-100 placeholder:text-slate-500":"w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-slate-800 placeholder:text-slate-400",G=W=>`rounded-lg border px-2.5 py-1 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-45 ${o.actionButton(W)}`;return P?n.jsxs("div",{className:"flex flex-col gap-3",children:[b?n.jsxs("div",{className:`${o.cardClass} rounded-2xl p-4`,children:[n.jsx("div",{className:`mb-2 text-sm font-semibold ${o.textPrimary}`,children:r("mesh.notes.addTitle")}),n.jsx("textarea",{value:x,onChange:W=>g(W.target.value),rows:2,placeholder:r("mesh.notes.textPlaceholder"),className:q,autoFocus:!0}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[n.jsxs("select",{value:v,onChange:W=>S(W.target.value),className:$,"aria-label":r("mesh.notes.categoryLabel"),children:[n.jsx("option",{value:"",children:r("mesh.notes.categoryUncategorized")}),ma.map(W=>n.jsx("option",{value:W,children:Zc(r,W)},W))]}),n.jsx("button",{type:"button",onClick:()=>{M()},disabled:h||!x.trim(),className:G("success"),children:r("mesh.notes.add")}),n.jsx("button",{type:"button",onClick:()=>f(!1),disabled:h,className:G("default"),children:r("mesh.notes.cancel")})]})]}):n.jsx("div",{children:n.jsxs("button",{type:"button",onClick:()=>f(!0),className:G("info"),children:["+ ",r("mesh.notes.addTitle")]})}),u&&n.jsx("div",{className:o.isDark?"rounded-xl border border-rose-400/20 bg-rose-500/10 px-3 py-2 text-xs text-rose-100":"rounded-xl border border-rose-300 bg-rose-50 px-3 py-2 text-xs text-rose-700",children:u}),n.jsxs("div",{className:`${o.cardClass} rounded-2xl p-4`,children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[n.jsx("div",{className:`text-sm font-semibold ${o.textPrimary}`,children:r("mesh.notes.listTitle")}),n.jsx(Wi,{onClick:()=>{T()},refreshing:l,disabled:h,label:r("mesh.notes.refresh"),size:13,className:"h-7 w-7"})]}),l?n.jsx("div",{className:`py-6 text-center text-sm ${o.textMuted}`,children:r("mesh.notes.loading")}):a.length===0?n.jsx("div",{className:`py-6 text-center text-sm ${o.textMuted}`,children:r("mesh.notes.empty")}):n.jsx("div",{className:"flex flex-col gap-2",children:a.map(W=>n.jsx("div",{className:`rounded-xl border px-3 py-2.5 ${o.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:w===W.id?n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("textarea",{value:N,onChange:R=>j(R.target.value),rows:2,className:q}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsxs("select",{value:C,onChange:R=>E(R.target.value),className:$,"aria-label":r("mesh.notes.categoryLabel"),children:[n.jsx("option",{value:"",children:r("mesh.notes.categoryUncategorized")}),ma.map(R=>n.jsx("option",{value:R,children:Zc(r,R)},R))]}),n.jsx("button",{type:"button",onClick:()=>{L(W.id)},disabled:h||!N.trim(),className:G("success"),children:r("mesh.notes.save")}),n.jsx("button",{type:"button",onClick:D,disabled:h,className:G("default"),children:r("mesh.notes.cancel")})]})]}):n.jsxs(n.Fragment,{children:[(()=>{const R=$x(W.text),O=A.has(W.id),B=R.length>sp,H=!B||O?R:`${R.slice(0,sp).trimEnd()}…`;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`whitespace-pre-wrap break-words text-sm ${o.textPrimary}`,children:H}),B&&n.jsx("button",{type:"button",onClick:()=>k(U=>{const K=new Set(U);return K.has(W.id)?K.delete(W.id):K.add(W.id),K}),className:`mt-1 text-2xs font-medium ${o.isDark?"text-sky-300 hover:text-sky-200":"text-sky-600 hover:text-sky-700"}`,children:r(O?"mesh.notes.showLess":"mesh.notes.showMore")})]})})(),n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[n.jsx(Xr,{label:Zc(r,W.category),tone:ma.includes(W.category)?FL[W.category]:"default"}),W.pinned&&n.jsx(Xr,{label:r("mesh.notes.pinned"),tone:"info"}),W.expired?n.jsx(Xr,{label:r("mesh.notes.expired"),tone:"danger"}):W.pinned?n.jsx(Xr,{label:r("mesh.notes.neverExpires"),tone:"default"}):ha(W.effectiveExpiresAt)?n.jsx("span",{className:`text-2xs ${o.textMuted}`,title:W.effectiveExpiresAt,children:r("mesh.notes.expiresIn",{when:ha(W.effectiveExpiresAt)})}):n.jsx(Xr,{label:r("mesh.notes.durable"),tone:"default"}),ha(W.createdAt)&&n.jsx("span",{className:`text-2xs ${o.textMuted}`,children:ha(W.createdAt)}),n.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>I(W),disabled:h,className:G("info"),children:r("mesh.notes.edit")}),n.jsx("button",{type:"button",onClick:()=>{_(W.id)},disabled:h,className:G("default"),children:r("mesh.notes.delete")})]})]})]})},W.id))})]})]}):n.jsx("div",{className:`${o.cardClass} rounded-2xl p-4 text-xs ${o.textSecondary}`,children:r("mesh.notes.unavailable")})}const sr={sessionMinRemainingPercent:10,weeklyMinRemainingPercent:15,sessionResetImminentMinutes:5,staleAfterMinutes:30,spreadBonusMax:30,sessionAxisWeeklyHeadroomPercent:40},rd=60*1e3;function rp(e){return e===void 0||!Number.isFinite(e)?"":String(e/rd)}function Pa(e){const t=e??{};return{sessionMinRemainingPercent:t.sessionMinRemainingPercent!==void 0?String(t.sessionMinRemainingPercent):"",weeklyMinRemainingPercent:t.weeklyMinRemainingPercent!==void 0?String(t.weeklyMinRemainingPercent):"",sessionResetImminentMinutes:rp(t.sessionResetImminentMs),staleAfterMinutes:rp(t.staleAfterMs),spreadBonusMax:t.spreadBonusMax!==void 0?String(t.spreadBonusMax):"",sessionAxisWeeklyHeadroomPercent:t.sessionAxisWeeklyHeadroomPercent!==void 0?String(t.sessionAxisWeeklyHeadroomPercent):""}}function BL(e,t){const s=t.trim();if(!s)return null;const r=Number(s);if(!Number.isFinite(r))return"notANumber";const o=e==="sessionMinRemainingPercent"||e==="weeklyMinRemainingPercent"||e==="sessionAxisWeeklyHeadroomPercent";return o&&(r<0||r>100)?"percentRange":!o&&r<0?"negative":null}function od(e){const t={},s=u=>{const m=u.trim();if(!m)return;const h=Number(m);return Number.isFinite(h)?h:void 0},r=s(e.sessionMinRemainingPercent);r!==void 0&&(t.sessionMinRemainingPercent=r);const o=s(e.weeklyMinRemainingPercent);o!==void 0&&(t.weeklyMinRemainingPercent=o);const a=s(e.sessionResetImminentMinutes);a!==void 0&&(t.sessionResetImminentMs=a*rd);const i=s(e.staleAfterMinutes);i!==void 0&&(t.staleAfterMs=i*rd);const l=s(e.spreadBonusMax);l!==void 0&&(t.spreadBonusMax=l);const d=s(e.sessionAxisWeeklyHeadroomPercent);return d!==void 0&&(t.sessionAxisWeeklyHeadroomPercent=d),t}const WL="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs",UL="w-full rounded-lg border border-red-500/60 bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function KL({quotaRouting:e,saving:t,error:s,onSave:r,hideHeader:o=!1}){const{t:a}=he("common"),[i,l]=c.useState(()=>Pa(e)),d=c.useCallback((v,S)=>{l(A=>({...A,[v]:S}))},[]),u=c.useMemo(()=>{const v={};for(const S of Object.keys(i)){const A=BL(S,i[S]);A&&(v[S]=A)}return v},[i]),m=Object.keys(u).length>0,h=c.useMemo(()=>JSON.stringify(od(i))!==JSON.stringify(op(e)),[i,e]),p=c.useRef(!1),b=JSON.stringify(op(e));c.useEffect(()=>{p.current||l(Pa(e))},[b]);const f=c.useCallback(()=>{p.current=!1,!(m||!h)&&r(od(i))},[h,i,m,r]),x=c.useCallback(()=>{l(Pa(null)),r({})},[r]),g=[{key:"sessionMinRemainingPercent",label:a("setupWizard.quotaPolicy.sessionMin"),hint:a("setupWizard.quotaPolicy.sessionMinHint"),placeholder:sr.sessionMinRemainingPercent,unit:"%"},{key:"weeklyMinRemainingPercent",label:a("setupWizard.quotaPolicy.weeklyMin"),hint:a("setupWizard.quotaPolicy.weeklyMinHint"),placeholder:sr.weeklyMinRemainingPercent,unit:"%"},{key:"sessionResetImminentMinutes",label:a("setupWizard.quotaPolicy.resetImminent"),hint:a("setupWizard.quotaPolicy.resetImminentHint"),placeholder:sr.sessionResetImminentMinutes,unit:a("setupWizard.quotaPolicy.minutes")},{key:"staleAfterMinutes",label:a("setupWizard.quotaPolicy.staleAfter"),hint:a("setupWizard.quotaPolicy.staleAfterHint"),placeholder:sr.staleAfterMinutes,unit:a("setupWizard.quotaPolicy.minutes")},{key:"spreadBonusMax",label:a("setupWizard.quotaPolicy.spreadBonus"),hint:a("setupWizard.quotaPolicy.spreadBonusHint"),placeholder:sr.spreadBonusMax,unit:""},{key:"sessionAxisWeeklyHeadroomPercent",label:a("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroom"),hint:a("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroomHint"),placeholder:sr.sessionAxisWeeklyHeadroomPercent,unit:"%"}];return n.jsxs("div",{className:"flex flex-col gap-3",children:[!o&&n.jsxs("h3",{className:"flex items-center gap-1 text-sm font-semibold text-text-primary",children:[a("setupWizard.quotaPolicy.title"),n.jsx(rt,{content:a("setupWizard.quotaPolicy.description")})]}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-2",children:g.map(v=>{const S=u[v.key],A=`quota-policy-${v.key}`;return n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsxs("span",{className:"flex items-center gap-1 text-2xs text-text-muted",children:[n.jsxs("label",{htmlFor:A,children:[v.label,v.unit?` (${v.unit})`:""]}),n.jsx(rt,{content:v.hint,size:12})]}),n.jsx("input",{id:A,type:"number",inputMode:"decimal",className:S?UL:WL,value:i[v.key],placeholder:String(v.placeholder),"aria-invalid":S?!0:void 0,onChange:k=>{p.current=!0,d(v.key,k.target.value)},onBlur:f,onKeyDown:k=>{k.key==="Enter"&&f()}}),S&&n.jsx("span",{className:"text-3xs leading-snug text-red-400",children:a(`setupWizard.quotaPolicy.errors.${S}`)})]},v.key)})}),s?n.jsx("p",{className:"text-2xs text-red-400",children:s}):null,n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:x,disabled:!!t,children:a("setupWizard.quotaPolicy.useDefaults")}),n.jsxs("span",{className:"flex items-center gap-1 text-3xs text-text-muted",children:[a(t?"setupWizard.quotaPolicy.saving":"setupWizard.quotaPolicy.blankMeansDefaultShort"),!t&&n.jsx(rt,{content:a("setupWizard.quotaPolicy.blankMeansDefault"),size:12})]})]})]})}function op(e){return od(Pa(e))}function qL(e,t,s,r){const{t:o}=he(),[a,i]=c.useState(!1),[l,d]=c.useState(null),[u,m]=c.useState(null),[h,p]=c.useState(null),b=c.useCallback(async()=>{if(!e||!t){d(o("mesh.promptPreview.connectPrompt"));return}i(!0),d(null);try{const f=await r(e,"coordinator_prompt_preview",{meshId:t,cliType:s}),x=f!=null&&f.result&&typeof f.result=="object"?f.result:f;if(!(x!=null&&x.success))return d((x==null?void 0:x.error)||o("mesh.promptPreview.errorRender")),null;const g=typeof x.prompt=="string"?x.prompt:"";return m(g),p(typeof x.bytes=="number"?x.bytes:null),g}catch(f){return d((f==null?void 0:f.message)||String(f)),null}finally{i(!1)}},[e,t,s,r,o]);return{loading:a,error:l,prompt:u,bytes:h,load:b}}function zL({daemonId:e,meshId:t,cliType:s,sendCommand:r,defaultOpen:o=!1}){const{t:a}=he(),[i,l]=c.useState(o),{loading:d,error:u,prompt:m,bytes:h,load:p}=qL(e,t,s,r),b=c.useRef(!1);c.useEffect(()=>{i&&!b.current&&(b.current=!0,p())},[i,p]);const f=c.useCallback(()=>{l(x=>!x)},[]);return n.jsxs("div",{className:"mt-2",children:[n.jsxs("button",{type:"button",onClick:f,className:"inline-flex items-center gap-1 text-xs text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[n.jsx("span",{className:`transition-transform ${i?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),a(i?"mesh.promptPreview.hide":"mesh.promptPreview.view"),n.jsxs("span",{className:"text-text-muted",children:["(",s,")"]})]}),i&&n.jsxs("div",{className:"mt-2",children:[d&&n.jsx("div",{className:"text-xs text-text-muted",children:a("mesh.promptPreview.rendering")}),u&&n.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-300",children:[u,n.jsx("button",{type:"button",onClick:()=>void p(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:a("mesh.promptPreview.retry")})]}),!d&&!u&&m!==null&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between text-2xs text-text-muted",children:[n.jsx(rt,{content:`${a("mesh.promptPreview.info")}
|
|
112
|
+
${a("mesh.promptPreview.launchScopeNote")}`,size:12}),h!==null&&n.jsxs("span",{children:[(h/1024).toFixed(1)," KB"]})]}),n.jsx("textarea",{readOnly:!0,value:m,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-xs text-text-secondary font-mono",onFocus:x=>x.currentTarget.select()})]})]})]})}function VL(e){var i;const t=e!=null&&e.result&&typeof e.result=="object"?e.result:e;if(!t||typeof t!="object"||t.success===!1)return null;if((t.sourceType==="repo_file"||t.sourceType==="invalid"?t.sourceType:"unavailable")==="invalid")return{append:"",override:"",path:typeof t.path=="string"?t.path:"",sourceType:"invalid",error:typeof t.error=="string"?t.error:""};const r=(i=t==null?void 0:t.config)==null?void 0:i.coordinator,o=typeof(r==null?void 0:r.systemPromptAppend)=="string"?r.systemPromptAppend:"",a=typeof(r==null?void 0:r.systemPromptOverride)=="string"?r.systemPromptOverride:"";return!o.trim()&&!a.trim()?null:{append:o,override:a,path:typeof t.path=="string"?t.path:"",sourceType:"repo_file",error:""}}function GL({daemonId:e,workspace:t,sendCommand:s}){const{t:r}=he(),[o,a]=c.useState(null),i=c.useCallback(async()=>{if(!e||!t){a(null);return}try{const l=await s(e,"read_mesh_json_config",{workspace:t});a(VL(l))}catch{a(null)}},[e,t,s]);return c.useEffect(()=>{i()},[i]),o?o.sourceType==="invalid"?n.jsxs("div",{className:"mt-3 rounded-lg border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-300",children:[r("mesh.detail.repoMeshJsonInvalid"),o.error&&n.jsx("span",{className:"ml-1 font-mono text-2xs opacity-80",children:o.error})]}):n.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[n.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-1",children:[n.jsx("span",{className:"text-[13px] leading-tight font-semibold",children:r("mesh.detail.repoMeshJsonTitle")}),n.jsx(rt,{content:`${r("mesh.detail.repoMeshJsonHint")}${o.path?`
|
|
113
|
+
${o.path}`:""}`,size:12})]}),o.override.trim()&&n.jsxs("div",{className:"mb-2",children:[n.jsx("label",{className:"mb-1 block text-2xs uppercase tracking-wide text-text-muted",children:r("mesh.detail.repoMeshJsonOverrideLabel")}),n.jsx("textarea",{readOnly:!0,value:o.override,rows:4,className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 font-mono text-xs text-text-secondary",onFocus:l=>l.currentTarget.select()})]}),o.append.trim()&&n.jsxs("div",{children:[n.jsx("label",{className:"mb-1 block text-2xs uppercase tracking-wide text-text-muted",children:r("mesh.detail.repoMeshJsonAppendLabel")}),n.jsx("textarea",{readOnly:!0,value:o.append,rows:4,className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 font-mono text-xs text-text-secondary",onFocus:l=>l.currentTarget.select()})]})]}):null}const YL=[{token:"meshName",description:"This mesh's display name.",example:"my-app"},{token:"repo",description:"Repo identity (owner/repo or workspace path).",example:"vilmire/adhdev"},{token:"defaultBranch",description:"The mesh's default branch.",example:"main"},{token:"cliType",description:"The coordinator CLI type this prompt is being rendered for.",example:"claude-cli"},{token:"nodes",description:"Live node status table, or the configured node list if no live status is available.",example:"(rendered node table)"},{token:"mission",description:"Current mission section, when a mission is active. Empty otherwise.",example:"(mission summary or empty)"},{token:"recentActivity",description:"Recent mesh activity summary. Empty when none.",example:"(recent activity or empty)"},{token:"operatingNotes",description:"Accumulated operating notes for this mesh. Empty when none.",example:"(operating notes or empty)"},{token:"policy",description:"The mesh's effective policy section (safety, scheduling, etc.).",example:"(rendered policy section)"},{token:"tools",description:"The canonical MCP tools reference table.",example:"(tools table)"},{token:"workflow",description:"The standard coordinator workflow guidance section.",example:"(workflow section)"},{token:"quota",description:"The quota-awareness section.",example:"(quota section)"},{token:"onboarding",description:"Onboarding/reinit guidance section.",example:"(onboarding section)"},{token:"rules",description:"CLI-type-specific and policy-derived rules section.",example:"(rules section)"},{token:"toolExposurePreflight",description:"Preflight guidance for verifying tool exposure before relying on it.",example:"(preflight section)"}];function ap(e,t){if(t)return e.modes.find(s=>s.id===t)}function QL(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&Hn(t)!=="dangerous")}function JL({config:e,requestedModeId:t,machineAutoApproveEnabled:s,machineDangerousAllowed:r}){const o=ap(e,e.default),a=o==null?void 0:o.id,i=(t==null?void 0:t.trim())||void 0;if(!s)return{status:"disabled",requestedModeId:i,providerDefaultModeId:a,requestedModeUnknown:!1,downgraded:!1};const l=ap(e,i),d=!!i&&!l,u=l??o;if(!u||u.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:a,requestedModeUnknown:d,downgraded:!1};if(Hn(u)==="dangerous"&&!r){const m=QL(e);return{status:m?"downgraded":"none",requestedModeId:i,providerDefaultModeId:a,effectiveMode:m,requestedModeUnknown:d,downgraded:!0}}return{status:d?"invalid_fallback":"requested",requestedModeId:i,providerDefaultModeId:a,effectiveMode:u,requestedModeUnknown:d,downgraded:!1}}function XL(e){const t=[];for(const s of e||[]){if(!s||s.category!=="cli")continue;const r=s.autoApproveModes;if(!r||!Array.isArray(r.modes)||r.modes.length===0)continue;const o=String(s.type||s.id||"").trim();o&&t.push({type:o,label:String(s.displayName||s.name||o),autoApproveModes:r})}return t}function ZL({hostDaemonId:e,hostOnline:t,hostWorkspace:s,meshProviders:r,unreportedNodeCount:o=0,machineAutoApproveEnabled:a,machineDangerousAllowed:i,onUpdatePolicy:l,savingPolicy:d,sendCommand:u}){const{t:m}=he("common"),h=c.useMemo(()=>XL(r),[r]),[p,b]=c.useState({}),[f,x]=c.useState(!1),[g,v]=c.useState(null),[S,A]=c.useState(!1),[k,w]=c.useState(null),[y,N]=c.useState(!1),[j,C]=c.useState(null),[E,P]=c.useState(!1),T=!!e&&t&&!!s,M=!!l&&!d,_=c.useCallback(async()=>{var W,R,O;if(T){x(!0),v(null);try{const B=await u(e,"read_mesh_json_config",{workspace:s}),H=(B==null?void 0:B.result)??B,U=((W=H==null?void 0:H.providerDefaults)==null?void 0:W.autoApproveModes)||((O=(R=H==null?void 0:H.config)==null?void 0:R.providerDefaults)==null?void 0:O.autoApproveModes),K={};if(U&&typeof U=="object")for(const[oe,ge]of Object.entries(U))typeof ge=="string"&&ge.trim()&&(K[oe]=ge.trim());b(K)}catch(B){v((B==null?void 0:B.message)||m("mesh.providerAutoApprove.loadError"))}finally{x(!1)}}},[T,e,s,u,m]);c.useEffect(()=>{_()},[_]);const I=c.useRef(null),D=c.useRef(p);D.current=p;const L=c.useCallback((W,R)=>{var B;N(!1);const O={...D.current};R&&R.trim()?O[W]=R.trim():delete O[W],D.current=O,b(O),(B=I.current)==null||B.call(I,O)},[]),$=c.useCallback((W,R)=>{if(Hn(R)==="dangerous"){C({type:W,mode:R});return}L(W,R.id)},[L]),q=c.useCallback(()=>{j&&L(j.type,j.mode.id),C(null)},[L,j]),G=c.useCallback(async W=>{if(T){A(!0),w(null),N(!1);try{const R=await u(e,"set_mesh_provider_defaults",{workspace:s,autoApproveModes:W,merge:!1,write:!0}),O=(R==null?void 0:R.result)??R;if((O==null?void 0:O.success)===!1)throw new Error((O==null?void 0:O.error)||m("mesh.providerAutoApprove.saveError"));N(!0),nt.showToast(m("common.saved"),"success"),await _()}catch(R){w((R==null?void 0:R.message)||m("mesh.providerAutoApprove.saveError"))}finally{A(!1)}}},[T,e,s,_,u,m]);return I.current=G,n.jsxs(vt,{title:m("mesh.providerAutoApprove.title"),collapsible:!0,defaultOpen:!1,children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-3.5",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary",children:m("mesh.providerAutoApprove.machineSection.title")}),n.jsx(Qt,{content:m("mesh.providerAutoApprove.machineSection.hint"),children:n.jsx("span",{className:"rounded-full border border-border-subtle bg-surface-secondary/40 px-2 py-0.5 text-3xs font-medium text-text-muted",children:m("mesh.providerAutoApprove.machineSection.chip")})})]}),n.jsxs("div",{className:"mt-3 space-y-2",children:[n.jsx(ip,{label:m("mesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:m("mesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:a,disabled:!M,onChange:W=>l==null?void 0:l({delegatedWorkerAutoApprove:W})}),n.jsx(ip,{label:m("mesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:m(a?"mesh.providerAutoApprove.machineSection.dangerousToggleHint":"mesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:i,disabled:!M||!a,onChange:W=>{W?P(!0):l==null||l({delegatedWorkerDangerousModeAllow:!1})}})]})]}),T?f?n.jsx("div",{className:"text-xxs text-text-muted",children:m("mesh.providerAutoApprove.loading")}):h.length===0?n.jsx("div",{className:"text-xxs text-text-muted",children:o>0?m("mesh.providerAutoApprove.awaitingNodes",{count:o}):m("mesh.providerAutoApprove.noProviders")}):n.jsxs("div",{className:"space-y-6",children:[g&&n.jsx(Bt,{variant:"error",onDismiss:()=>v(null),children:g}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary",children:m("mesh.providerAutoApprove.repoSection.title")}),n.jsx(Qt,{content:m("mesh.providerAutoApprove.repoSection.hint"),children:n.jsx("span",{className:"rounded-full border border-border-subtle bg-surface-secondary/40 px-2 py-0.5 text-3xs font-medium text-text-muted",children:m("mesh.providerAutoApprove.repoSection.chip")})}),o>0&&n.jsx(Qt,{content:m("mesh.providerAutoApprove.partialInventory",{count:o}),children:n.jsx("span",{className:"rounded-full border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 text-3xs font-medium text-amber-400",children:m("mesh.providerAutoApprove.partialInventoryChip",{count:o})})}),S&&n.jsx("span",{className:"text-3xs text-text-muted",children:m("mesh.providerAutoApprove.saving")})]}),n.jsx("div",{className:"space-y-5",children:h.map(W=>{const R=p[W.type],O=JL({config:W.autoApproveModes,requestedModeId:R,machineAutoApproveEnabled:a,machineDangerousAllowed:i});return n.jsxs("div",{className:"rounded-xl border border-border-subtle p-3.5",children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary",children:W.label}),n.jsx("button",{type:"button",className:"text-2xs text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>L(W.type,void 0),disabled:!R||S,children:m("mesh.providerAutoApprove.repoSection.clear")})]}),n.jsx(hx,{config:W.autoApproveModes,selectedModeId:R||"",disabled:S,onSelectMode:B=>$(W.type,B)}),!R&&n.jsx("div",{className:"mt-1.5 text-2xs text-text-muted",children:m("mesh.providerAutoApprove.repoSection.usesProviderDefault")}),n.jsx(eD,{effective:O,config:W.autoApproveModes})]},W.type)})}),k&&n.jsx(Bt,{variant:"error",onDismiss:()=>w(null),children:k}),y&&n.jsx("span",{className:"sr-only",role:"status",children:m("mesh.providerAutoApprove.saved")})]}):n.jsx("div",{className:"text-xxs text-text-muted",children:m("mesh.providerAutoApprove.noHostDaemon")}),E&&n.jsx(Ui,{title:m("mesh.providerAutoApprove.machineSection.confirmTitle"),description:m("mesh.providerAutoApprove.machineSection.confirmDescription"),details:[{label:m("mesh.providerAutoApprove.machineSection.confirmScopeLabel"),value:m("mesh.providerAutoApprove.machineSection.confirmScopeValue")},{label:m("mesh.providerAutoApprove.machineSection.confirmEffectLabel"),value:m("mesh.providerAutoApprove.machineSection.confirmEffectValue")}],confirmLabel:m("mesh.providerAutoApprove.machineSection.confirmConfirm"),onConfirm:()=>{P(!1),l==null||l({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>P(!1)}),j&&n.jsx(px,{mode:j.mode,onConfirm:q,onCancel:()=>C(null)}),j&&n.jsx("div",{className:"fixed inset-x-0 bottom-6 z-[60] mx-auto max-w-lg px-4",children:n.jsxs("div",{className:"rounded-xl border border-status-error/40 bg-bg-primary p-3.5 shadow-lg",children:[n.jsxs("div",{className:"flex items-center gap-1 text-sm font-semibold text-status-error",children:[m("mesh.providerAutoApprove.dangerous.sharedWarningTitle"),n.jsx(rt,{content:m("mesh.providerAutoApprove.dangerous.sharedWarningDetail")})]}),n.jsx("div",{className:"mt-1 text-xs text-text-muted",children:m("mesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function eD({effective:e,config:t}){var d,u,m,h;const{t:s}=he("common"),r=p=>{var b;return(p?(b=t.modes.find(f=>f.id===p))==null?void 0:b.label:void 0)||p||""};let o,a=null,i="ok";switch(e.status){case"requested":o=s("mesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((d=e.effectiveMode)==null?void 0:d.label)||""});break;case"invalid_fallback":o=s("mesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((u=e.effectiveMode)==null?void 0:u.label)||""}),i="warn";break;case"downgraded":o=s("mesh.providerAutoApprove.effectiveSection.statusDowngraded",{mode:((m=e.effectiveMode)==null?void 0:m.label)||""}),a=s("mesh.providerAutoApprove.effectiveSection.statusDowngradedHint",{requested:r(e.requestedModeId)||r(e.providerDefaultModeId),mode:((h=e.effectiveMode)==null?void 0:h.label)||""}),i="warn";break;case"disabled":o=s("mesh.providerAutoApprove.effectiveSection.statusDisabled"),i="muted";break;default:o=s("mesh.providerAutoApprove.effectiveSection.statusNone"),i="muted"}const l=i==="ok"?"border-status-online/25 bg-status-online/5 text-text-secondary":i==="warn"?"border-status-warning/30 bg-status-warning/5 text-status-warning":"border-border-subtle bg-surface-secondary/30 text-text-muted";return n.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-lg border px-3 py-2 text-xs ${l}`,children:[e.effectiveMode&&n.jsx(mx,{risk:Hn(e.effectiveMode)}),n.jsx("span",{className:"min-w-0",children:o}),a&&n.jsx(rt,{content:a,size:12})]})}function ip({label:e,hint:t,checked:s,disabled:r=!1,onChange:o}){const a=c.useId();return n.jsxs("div",{className:`flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-primary/60 px-3.5 py-2.5 ${r?"opacity-60":""}`,children:[n.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[n.jsx("span",{id:a,className:"text-xxs font-semibold text-text-primary",children:e}),n.jsx(rt,{content:t,size:12})]}),n.jsx(Pr,{checked:s,disabled:r,onChange:o,"aria-labelledby":a})]})}function pa(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function tD({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:s,isHostNodeAttached:r,selectedHostNode:o,hostPinned:a,hostLabel:i,hostOnline:l,hostRebindDaemonId:d,onHostRebindDaemonIdChange:u,settingMeshHost:m,onSetMeshHost:h}){const{t:p}=he("common");if(a)return n.jsxs(vt,{title:p("mesh.host.title"),description:p("mesh.host.descriptionSet"),children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xxs text-text-primary ${l?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[n.jsx("span",{className:"text-text-muted",children:p("mesh.host.hostLabel")}),n.jsx("span",{className:"font-medium",children:i||p("mesh.host.unknown")}),n.jsxs("span",{className:l?"text-text-muted":"text-amber-400",children:["· ",p(l?"mesh.host.online":"mesh.host.offline")]})]}),(o==null?void 0:o.workspace)&&n.jsxs("span",{className:"text-xs text-text-muted",children:[p("mesh.host.hostNode")," ",n.jsx("span",{className:"font-mono text-text-secondary",children:o.workspace})]})]}),!l&&n.jsxs("div",{className:"mt-4",children:[n.jsx(Bt,{variant:"warning",className:"mb-3",children:n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("strong",{children:p("mesh.host.hostOffline")}),n.jsx(rt,{content:p("mesh.host.hostOfflineText")})]})}),e.length>0?n.jsx(Ht,{label:p("mesh.host.reconnectToCommand"),hint:p("mesh.host.reconnectToCommandHint"),children:n.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:d,onChange:x=>u(x.target.value),children:[n.jsx("option",{value:"",children:p("mesh.host.waitForHost")}),e.map(x=>n.jsx("option",{value:x.id,children:pa(x)},x.id))]})}):n.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-muted",children:p("mesh.host.noDaemonsToRoute")})]})]});const b=e.find(x=>x.id===t),f=h&&t?n.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>h(t),disabled:!!m,children:p(m?"mesh.host.settingHost":"mesh.host.setHostAction")}):null;return n.jsxs(vt,{title:p("mesh.host.title"),description:p("mesh.host.descriptionUnset"),children:[n.jsx(Bt,{variant:"info",className:"mb-4",children:n.jsx("strong",{children:p("mesh.host.setHostBanner")})}),e.length>0?n.jsxs(n.Fragment,{children:[t?n.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-muted",children:r?n.jsxs(n.Fragment,{children:[p("mesh.host.willHostOn")," ",n.jsx("span",{className:"font-medium text-text-primary",children:pa(b)}),o!=null&&o.workspace?n.jsxs(n.Fragment,{children:[" · ",p("mesh.host.setupNode")," ",n.jsx("span",{className:"font-mono text-text-secondary",children:o.workspace})]}):null,". ",p("mesh.host.confirmSetsHost")]}):n.jsxs(n.Fragment,{children:[p("mesh.host.willHostOn")," ",n.jsx("span",{className:"font-medium text-text-primary",children:pa(b)}),". ",p("mesh.host.attachNodeThenSetHost")]})}):n.jsx(Ht,{label:p("mesh.host.hostDaemon"),hint:p("mesh.host.hostDaemonHint"),children:n.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:x=>s(x.target.value),children:[n.jsx("option",{value:"",children:p("mesh.host.resolvingHost")}),e.map(x=>n.jsx("option",{value:x.id,children:pa(x)},x.id))]})}),f&&n.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:f})]}):n.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-muted",children:p("mesh.host.noDaemonsToHost")})]})}const el=[{value:"preserve",labelKey:"mesh.sessionCleanup.preserve",descriptionKey:"mesh.sessionCleanup.preserveHint"},{value:"stop",labelKey:"mesh.sessionCleanup.stop",descriptionKey:"mesh.sessionCleanup.stopHint"},{value:"delete_stopped",labelKey:"mesh.sessionCleanup.deleteStopped",descriptionKey:"mesh.sessionCleanup.deleteStoppedHint"},{value:"stop_and_delete",labelKey:"mesh.sessionCleanup.stopAndDelete",descriptionKey:"mesh.sessionCleanup.stopAndDeleteHint"}],nD=[{value:"smart",labelKey:"mesh.detail.distributionSmart",summaryKey:"mesh.detail.distributionSmartSummary",descriptionKey:"mesh.detail.distributionSmartDescription"},{value:"in_order",labelKey:"mesh.detail.distributionInOrder",summaryKey:"mesh.detail.distributionInOrderSummary",descriptionKey:"mesh.detail.distributionInOrderDescription"}];function sD(e){return e==="smart"?"fitness":"first_eligible"}function rD(e,t){const s=e||"first_eligible";return s==="fitness"||s==="least_loaded"||s==="round_robin"||s==="priority_only"&&t!=null&&t.priorityConfigured?"smart":"in_order"}function Fx(e){return{...(e==null?void 0:e.effectivePolicy)||(e==null?void 0:e.policy)||{}}}function cp(e,t){const s=e==null?void 0:e.policy;return!!s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,t)}function oD({selectedMesh:e,error:t,onDismissError:s,onBack:r,onDelete:o,displayedMeshStatus:a,graphError:i,onRefreshGraph:l,savingPolicy:d,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:h,savingCoordinatorPrompt:p,onSaveCoordinatorPrompt:b,daemons:f,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:g,coordinatorCliType:v,isHostNodeAttached:S,selectedHostNode:A,hostPinned:k,hostLabel:w,hostOnline:y,hostRebindDaemonId:N,onHostRebindDaemonIdChange:j,settingMeshHost:C,onSetMeshHost:E,activeDaemon:P,activeDaemonId:T,meshQueue:M,userName:_,availableCliProviders:I,savingNodeSlotsId:D,onUpdateNodeSlots:L,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:q,nodeSystemPromptDrafts:G,onNodeSystemPromptDraftChange:W,savingNodeSystemPromptId:R,onSaveNodeSystemPrompt:O,selectedNodeId:B,onSelectNode:H,showAddNode:U,onShowAddNode:K,onCancelAddNode:oe,nodeWorkspace:ge,onNodeWorkspaceChange:J,nodeProviderPriority:ke,onNodeProviderPriorityChange:de,nodeDaemonId:ne,onNodeDaemonIdChange:le,nodeCustomPath:te,onNodeCustomPathChange:ce,nodePickerWorkspaces:Ce,nodePickerProviders:Q,nodeOnboardingPlan:z,nodePlanLoading:X,attachableDaemons:pe,onAddNode:Re,onRemoveNode:Oe,features:De,sendCommand:we}){var qe;const{t:V}=he("common"),xe=Fx(e),Z=e.nodes||[],ae=(a==null?void 0:a.nodes)??null,F=c.useMemo(()=>pL(Z,f,ae),[Z,f,ae]),se=Z.some(Pe=>{var At;const tt=Number((At=Pe.policy)==null?void 0:At.schedulingPriority);return Number.isFinite(tt)&&tt!==0}),me=!xe.schedulingStrategy,re=c.useMemo(()=>Z.some(Pe=>{var tt;return Array.isArray((tt=Pe.policy)==null?void 0:tt.slots)&&Pe.policy.slots.length>0}),[Z]),Se=me&&(re||Z.length>=2)?"smart":null,[Y,ue]=c.useState(!1),fe=!!T&&!!e.id,{theme:Ie}=Hi(),Ke=c.useMemo(()=>Ox(Ie),[Ie]),_e="w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",Ne=(qe=e.policy)==null?void 0:qe.quotaRouting,Be=Ne&&typeof Ne=="object"?Ne:{},$e=Be.quotaBusyFallback!==!1,it=rD(xe.schedulingStrategy,{priorityConfigured:se}),dt=n.jsxs(n.Fragment,{children:[De.meshHostDaemonSection&&n.jsx(tD,{daemons:f,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:g,isHostNodeAttached:S,selectedHostNode:A,hostPinned:k,hostLabel:w,hostOnline:y,hostRebindDaemonId:N,onHostRebindDaemonIdChange:Pe=>{j(Pe),l()},settingMeshHost:C,onSetMeshHost:E}),n.jsx(EL,{nodes:Z,statusNodes:ae,meshQueue:M,activeDaemon:P,daemons:f,selectedMeshId:e.id,userName:_,features:{addNodeDaemonPicker:De.addNodeDaemonPicker,nodeInstruction:De.nodeInstruction},coordinatorDaemonId:x,availableCliProviders:I,savingNodeSlotsId:D,onUpdateNodeSlots:L,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:q,nodeSystemPromptDrafts:G,onNodeSystemPromptDraftChange:W,savingNodeSystemPromptId:R,onSaveNodeSystemPrompt:O,selectedNodeId:B,onSelectNode:H,showAddNode:U,onShowAddNode:K,onCancelAddNode:oe,nodeWorkspace:ge,onNodeWorkspaceChange:J,nodeProviderPriority:ke,onNodeProviderPriorityChange:de,nodeDaemonId:ne,onNodeDaemonIdChange:le,nodeCustomPath:te,onNodeCustomPathChange:ce,nodePickerWorkspaces:Ce,nodePickerProviders:Q,nodeOnboardingPlan:z,nodePlanLoading:X,attachableDaemons:pe,onAddNode:Re,onRemoveNode:Oe}),n.jsx(vt,{title:V("mesh.detail.distribution"),children:n.jsxs("fieldset",{className:"border-none p-0 m-0",children:[n.jsx("legend",{className:"sr-only",children:V("mesh.detail.distribution")}),n.jsx("div",{className:"flex flex-col gap-2",children:nD.map(Pe=>{const tt=it===Pe.value;return n.jsxs("label",{className:`flex items-center gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${tt?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[n.jsx("input",{type:"radio",name:"mesh-distribution",className:"accent-[var(--accent-primary)]",value:Pe.value,checked:tt,disabled:d,onChange:()=>u({schedulingStrategy:sD(Pe.value)})}),n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[V(Pe.labelKey),Se===Pe.value&&n.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-3xs font-medium text-accent-primary",children:V("mesh.detail.recommended")})]}),n.jsx("span",{className:"block truncate text-xs text-text-muted",children:V(Pe.summaryKey)})]}),n.jsx(rt,{content:V(Pe.descriptionKey)})]},Pe.value)})})]})}),n.jsx(vt,{title:V("mesh.detail.visibilityTitle"),description:V("mesh.detail.visibilityHint"),children:n.jsxs("select",{className:_e,"aria-label":V("mesh.detail.visibilityLabel"),value:xe.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:Pe=>u({spawnedSessionVisibility:Pe.target.value==="visible"?"visible":"hidden"}),disabled:d,children:[n.jsx("option",{value:"hidden",children:V("mesh.detail.visibilityHidden")}),n.jsx("option",{value:"visible",children:V("mesh.detail.visibilityVisible")})]})}),n.jsx(ZL,{hostDaemonId:x,hostOnline:y,hostWorkspace:(A==null?void 0:A.workspace)||"",meshProviders:F.providers,unreportedNodeCount:F.unreportedNodeCount,machineAutoApproveEnabled:xe.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:xe.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:u,savingPolicy:d,sendCommand:we})]}),ut=xe.autoFastForward&&typeof xe.autoFastForward=="object"?xe.autoFastForward:{},It=ut.enabled!==!1,bt=ut.remoteNodes===!0,jt=ut.mode==="continuous"?"continuous":"idle",ee=Pe=>u({autoFastForward:{...ut,...Pe}}),ie=el.find(Pe=>Pe.value===xe.sessionCleanupOnNodeRemove)??el[0],ve=cp(e,"sessionCleanupOnNodeRemove"),Te=Pe=>cp(e,Pe)?n.jsx("button",{type:"button",className:"mt-1.5 text-2xs text-text-muted underline hover:text-text-primary disabled:opacity-50",disabled:d,onClick:()=>u({[Pe]:null}),children:V("mesh.detail.policyResetToDefault")}):n.jsx("span",{className:"mt-1.5 inline-block rounded border border-border-subtle px-1.5 py-0.5 text-2xs uppercase tracking-wider text-text-muted",children:V("mesh.detail.policyDefaultBadge")}),Ee=n.jsxs(n.Fragment,{children:[n.jsxs(vt,{title:V("setupWizard.quotaPolicy.title"),description:V("setupWizard.quotaPolicy.description"),collapsible:!0,defaultOpen:!1,children:[n.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[n.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-sm text-text-primary",children:[n.jsx("span",{id:"mesh-quota-busy-fallback-label",children:V("mesh.detail.quotaBusyFallback")}),n.jsx(rt,{content:V("mesh.detail.quotaBusyFallbackHint")})]}),n.jsx(Pr,{checked:$e,disabled:d,"aria-labelledby":"mesh-quota-busy-fallback-label",onChange:Pe=>u({quotaRouting:{...Be,quotaBusyFallback:Pe}})})]}),n.jsx(KL,{quotaRouting:Ne??null,saving:d,error:t,hideHeader:!0,onSave:Pe=>u({quotaRouting:{...Pe,...Be.quotaBusyFallback!==void 0?{quotaBusyFallback:Be.quotaBusyFallback}:{}}})})]}),n.jsxs(vt,{title:V("mesh.detail.safetyTitle"),collapsible:!0,defaultOpen:!1,description:V("mesh.detail.safetyDescription"),children:[n.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:V("mesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",V("mesh.detail.requireApprovalBeforePush")],["not_required",V("mesh.detail.doNotRequireApproval")]],val:Pe=>Pe?"required":"not_required",parse:Pe=>Pe==="required"},{label:V("mesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",V("mesh.detail.requireExplicitApproval")],["enabled",V("mesh.detail.allowRefineryPublish")]],val:Pe=>Pe?"enabled":"disabled",parse:Pe=>Pe==="enabled"}].map(({label:Pe,key:tt,opts:At,val:gt,parse:ye})=>n.jsxs(Ht,{label:Pe,children:[n.jsx("select",{className:_e,value:gt(xe[tt]),onChange:Ae=>u({[tt]:ye(Ae.target.value)}),disabled:d,children:At.map(([Ae,Le])=>n.jsx("option",{value:Ae,children:Le},Ae))}),Te(tt)]},tt))}),n.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[n.jsxs(Ht,{label:V("mesh.detail.autoFastForward"),children:[n.jsxs("select",{className:_e,value:It?"enabled":"disabled",onChange:Pe=>ee({enabled:Pe.target.value==="enabled"}),disabled:d,children:[n.jsx("option",{value:"enabled",children:V("mesh.detail.ffEnabled")}),n.jsx("option",{value:"disabled",children:V("mesh.detail.ffDisabled")})]}),Te("autoFastForward")]}),n.jsx(Ht,{label:V("mesh.detail.includeRemoteNodes"),hint:V("mesh.detail.includeRemoteNodesHint"),children:n.jsxs("select",{className:_e,value:bt?"yes":"no",onChange:Pe=>ee({remoteNodes:Pe.target.value==="yes"}),disabled:d||!It,children:[n.jsx("option",{value:"no",children:V("mesh.detail.remoteNo")}),n.jsx("option",{value:"yes",children:V("mesh.detail.remoteYes")})]})}),n.jsx(Ht,{label:V("mesh.detail.detectionMode"),hint:V("mesh.detail.detectionModeHint"),children:n.jsxs("select",{className:_e,value:jt,onChange:Pe=>ee({mode:Pe.target.value==="continuous"?"continuous":"idle"}),disabled:d||!It||!bt,children:[n.jsx("option",{value:"idle",children:V("mesh.detail.idleEdgeOnly")}),n.jsx("option",{value:"continuous",children:V("mesh.detail.continuousScan")})]})}),n.jsxs(Ht,{label:V("mesh.detail.sessionCleanupLabel"),hint:`${V("mesh.detail.sessionCleanupHint")}
|
|
114
|
+
${V(ve?ie.descriptionKey:"mesh.detail.sessionCleanupByNodeTypeHint")}`,children:[n.jsxs("select",{className:_e,value:ve?xe.sessionCleanupOnNodeRemove:"",onChange:Pe=>u({sessionCleanupOnNodeRemove:Pe.target.value||null}),disabled:d,children:[!ve&&n.jsx("option",{value:"",children:V("mesh.detail.sessionCleanupByNodeType")}),el.map(Pe=>n.jsx("option",{value:Pe.value,children:V(Pe.labelKey)},Pe.value))]}),Te("sessionCleanupOnNodeRemove")]})]})]}),De.coordinatorPrompt&&n.jsxs(vt,{title:V("mesh.detail.coordinatorPromptTitle"),collapsible:!0,defaultOpen:!1,description:V("mesh.detail.thisMeshHint",{name:e.name}),children:[n.jsx(zL,{daemonId:T,meshId:e.id,cliType:v,sendCommand:we,defaultOpen:!0}),n.jsx(Ht,{label:V("mesh.detail.overrideLabel"),hint:V("mesh.detail.overrideHint"),className:"mt-3",children:n.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:Pe=>h({...m,override:Pe.target.value}),disabled:p,placeholder:V("mesh.detail.overridePlaceholder")})}),n.jsx(Ht,{label:V("mesh.detail.appendLabel"),hint:V("mesh.detail.appendHint"),children:n.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:Pe=>h({...m,append:Pe.target.value}),disabled:p,placeholder:V("mesh.detail.appendPlaceholder")})}),n.jsx(GL,{daemonId:x,workspace:(A==null?void 0:A.workspace)||"",sendCommand:we}),n.jsxs("details",{className:"mt-2 text-xs text-text-muted",children:[n.jsxs("summary",{className:"cursor-pointer select-none inline-flex items-center gap-1",children:[V("mesh.detail.availablePlaceholders"),n.jsx(rt,{content:V("mesh.detail.placeholdersIntro"),size:12})]}),n.jsx("div",{className:"mt-2 overflow-x-auto",children:n.jsx("table",{className:"w-full text-left border-collapse",children:n.jsx("tbody",{children:YL.map(Pe=>n.jsxs("tr",{className:"border-t border-border-subtle/60 align-top",children:[n.jsx("td",{className:"py-1 pr-3 font-mono whitespace-nowrap text-text-secondary",children:`{{${Pe.token}}}`}),n.jsx("td",{className:"py-1 pr-3",children:Pe.description}),n.jsx("td",{className:"py-1 font-mono text-text-muted/80",children:Pe.example})]},Pe.token))})})})]}),n.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:b,disabled:p,children:V(p?"mesh.detail.saving":"mesh.detail.saveCoordinatorPrompt")}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h({override:"",append:""}),disabled:p,title:V("mesh.detail.clearTitle"),children:V("mesh.detail.clear")})]})]}),n.jsx(vt,{title:V("mesh.notes.tab"),collapsible:!0,defaultOpen:!1,description:V("mesh.notes.sectionHint"),children:n.jsx(Vi.Provider,{value:Ke,children:n.jsx(HL,{meshId:e.id,daemonId:T,sendDaemonCommand:we})})}),De.meshHostDaemonSection&&n.jsx(vt,{title:V("mesh.detail.useFromCli"),collapsible:!0,defaultOpen:!1,description:V("mesh.detail.mcpDescription"),children:n.jsxs("code",{className:"block overflow-x-auto rounded-lg bg-bg-secondary px-3 py-2 text-xs",children:["adhdev mcp --repo-mesh ",e.id]})})]}),Ye=[{key:"general",icon:n.jsx(_r,{size:14}),label:V("mesh.detail.tabGeneral"),content:dt},{key:"advanced",icon:n.jsx(qp,{size:14}),label:V("mesh.detail.tabAdvanced"),content:Ee}];return n.jsxs(Lo,{icon:n.jsx(On,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",subtitleInline:!0,widthClassName:"max-w-5xl",contentClassName:"gap-4",actions:n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{className:"btn btn-secondary btn-sm",onClick:r,children:V("mesh.detail.back")}),n.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>ue(!0),disabled:!fe,title:V(fe?"mesh.detail.observabilityOpenTitle":"mesh.detail.observabilityDisabledTitle"),children:[n.jsx(On,{size:14}),V("mesh.detail.observabilityOpen")]}),n.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>o(e.id),children:V("mesh.detail.delete")})]}),children:[t&&n.jsx(Bt,{variant:"error",onDismiss:s,children:t}),i&&n.jsx(Bt,{variant:"warning",children:i}),n.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-subtle bg-bg-card/30",children:n.jsx(Sg,{variant:"underline",tabs:Ye,tabIdPrefix:"mesh-settings-tab",ariaLabel:V("mesh.detail.tabsAriaLabel"),panelClassName:"p-4 md:p-6"})}),Y&&fe&&n.jsx(qd,{activeConv:Px({meshId:e.id,daemonId:T,meshName:e.name}),sendDaemonCommand:we,onClose:()=>ue(!1)})]})}function aD({selectedMesh:e,selectedMeshId:t,activeDaemonId:s,daemons:r,sendCommand:o,unwrapResult:a,loadLiveMesh:i,resolveCommandTarget:l,launchCoordinator:d,features:u,loadMeshes:m,reloadMeshStatus:h,setError:p,confirmAction:b}){const f=s;function x(){return f||(p(Qe.t("mesh.host.noCommandTarget")),null)}const[g,v]=c.useState(null),[S,A]=c.useState(!1),[k,w]=c.useState(""),[y,N]=c.useState([]),[j,C]=c.useState(""),[E,P]=c.useState(!1),[T,M]=c.useState(null),[_,I]=c.useState(!1),[D,L]=c.useState(""),[$,q]=c.useState(!1),[G,W]=c.useState(!1),[R,O]=c.useState(null),[B,H]=c.useState(!1),[U,K]=c.useState({override:"",append:""}),[oe,ge]=c.useState(!1),[J,ke]=c.useState({}),[de,ne]=c.useState(null),le=c.useMemo(()=>r.find(F=>F.id===j),[r,j]),te=(le==null?void 0:le.workspaces)||[],ce=c.useMemo(()=>Wn((le==null?void 0:le.availableProviders)||[]),[le]);c.useEffect(()=>{if(!S||!t||!k.trim()){M(null);return}const F=u.addNodeDaemonPicker?j:f;if(!F)return;let se=!1;return I(!0),o(F,"plan_mesh_onboarding",{workspace:k.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(me=>{se||M(a(me))}).catch(me=>{se||M({success:!1,error:(me==null?void 0:me.message)||"Git discovery failed"})}).finally(()=>{se||I(!1)}),()=>{se=!0}},[S,t,e,k,j,f,u.addNodeDaemonPicker,o,a]);async function Ce(){var me,re,Se;if(!t)return;const F=k.trim();if(!F)return;const se=x();if(se)try{const Y=u.addNodeDaemonPicker?j:se,ue=await o(Y,"plan_mesh_onboarding",{workspace:F,meshId:t,inlineMesh:e,operation:"add_existing"}),fe=a(ue);if(M(fe),(fe==null?void 0:fe.success)===!1)throw new Error(pu(fe));const Ie={meshId:t,workspace:((me=fe==null?void 0:fe.discovery)==null?void 0:me.repoRoot)||F,repoRoot:(re=fe==null?void 0:fe.discovery)==null?void 0:re.repoRoot,isLocalWorktree:((Se=fe==null?void 0:fe.discovery)==null?void 0:Se.isLinkedWorktree)===!0};u.addNodeDaemonPicker&&j&&(Ie.daemonId=j,Ie.machineId=le==null?void 0:le.machineId),Ie.providerPriority=Eo(y);const Ke=await o(se,"add_mesh_node",Ie),_e=a(Ke);if((_e==null?void 0:_e.success)===!1)throw new Error(_e.error||"Add node failed");A(!1),w(""),N([]),C(""),P(!1),await m(),await h()}catch(Y){p((Y==null?void 0:Y.message)||"Add node failed")}}async function Q(F){var fe;if(!e)return;const se=Fx(e),me=(e.nodes||[]).find(Ie=>Ie.id===F),re=se.sessionCleanupOnNodeRemove||((me==null?void 0:me.isLocalWorktree)===!0?"stop_and_delete":"preserve"),Se=((fe=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(Ie=>Ie.value===re))==null?void 0:fe.label)||"Preserve history and runtimes";if(!(b?await b({title:"Remove this node?",description:`Node removal cleanup policy: ${Se}`,confirmLabel:"Remove",tone:"danger"}):confirm(`Remove this node?
|
|
115
|
+
|
|
116
|
+
Node removal cleanup policy: ${Se}`)))return;const ue=x();if(ue)try{const Ie=await o(ue,"remove_mesh_node",{meshId:e.id,nodeId:F}),Ke=a(Ie);if((Ke==null?void 0:Ke.success)===!1)throw new Error(Ke.error||"Remove failed");g===F&&v(null),await m(),await h()}catch(Ie){p((Ie==null?void 0:Ie.message)||"Remove node failed")}}async function z(F){if(!e)return;const se={...F},me=x();if(me)try{H(!0),p(null);const re=await o(me,"update_mesh",{meshId:e.id,policy:se}),Se=a(re);if((Se==null?void 0:Se.success)===!1)throw new Error(Se.error||"Policy update failed");nt.showToast(Qe.t("common.saved"),"success"),await m()}catch(re){p((re==null?void 0:re.message)||"Policy update failed")}finally{H(!1)}}const[X,pe]=c.useState(null);async function Re(F,se){if(!t)return;const me=x();if(me)try{pe(F.id),p(null);const re=await o(me,"update_mesh_node",{meshId:t,nodeId:F.id,policy:{slots:se}}),Se=a(re);if((Se==null?void 0:Se.success)===!1){p(Se.error||"Node slots update failed");return}nt.showToast(Qe.t("common.saved"),"success"),await m()}catch(re){p((re==null?void 0:re.message)||"Node slots update failed")}finally{pe(null)}}const[Oe,De]=c.useState(null);async function we(F,se){if(!t)return;const me=x();if(!me)return;const re=se.map(Se=>Se.trim()).filter(Boolean);try{De(F.id),p(null);const Se=await o(me,"update_mesh_node",{meshId:t,nodeId:F.id,capabilities:re}),Y=a(Se);if((Y==null?void 0:Y.success)===!1){p(Y.error||"Node tag update failed");return}nt.showToast(Qe.t("common.saved"),"success"),await m()}catch(Se){p((Se==null?void 0:Se.message)||"Node tag update failed")}finally{De(null)}}async function V(){if(!t)return;const F=x();if(!F)return;const me={...(e==null?void 0:e.coordinator)||{}};U.override.trim()?me.systemPromptOverride=U.override:delete me.systemPromptOverride,U.append.trim()?me.systemPromptAppend=U.append:delete me.systemPromptAppend,delete me.systemPromptSuffix;try{ge(!0),p(null);const re=await o(F,"update_mesh",{meshId:t,coordinator:me}),Se=a(re);if((Se==null?void 0:Se.success)===!1){p(Se.error||"Coordinator prompt save failed");return}nt.showToast(Qe.t("common.saved"),"success"),await m()}catch(re){p((re==null?void 0:re.message)||"Coordinator prompt save failed")}finally{ge(!1)}}async function xe(F){if(!t)return;const se=x();if(!se)return;const me=(J[F.id]||"").trim();try{ne(F.id),p(null);const re=await o(se,"update_mesh_node",{meshId:t,nodeId:F.id,systemPrompt:me}),Se=a(re);if((Se==null?void 0:Se.success)===!1){p(Se.error||"Node instruction save failed");return}nt.showToast(Qe.t("common.saved"),"success"),await m()}catch(re){p((re==null?void 0:re.message)||"Node instruction save failed")}finally{ne(null)}}async function Z(F){if(!(!e||!F)){if(b){const se=r.find(Se=>Se.id===F),me=(se==null?void 0:se.machineNickname)||(se==null?void 0:se.nickname)||(se==null?void 0:se.hostname)||F;if(!await b({title:Qe.t("mesh.host.setHostConfirmTitle",{name:me}),description:Qe.t("mesh.host.setHostActionHint"),confirmLabel:Qe.t("mesh.host.setHostAction")}))return}p(null),O(null);try{W(!0);const se=(e.nodes||[]).find(Se=>en(String(Se.daemon_id||Se.daemonId||""),F)),me=await o(F,"set_mesh_host",{meshId:e.id,hostDaemonId:F,...se!=null&&se.id?{hostNodeId:se.id}:{}}),re=a(me);if((re==null?void 0:re.success)===!1){p(re.error||"Setting the mesh host failed");return}await m()}catch(se){p((se==null?void 0:se.message)||"Setting the mesh host failed")}finally{W(!1)}}}async function ae(){if(e){p(null),O(null);try{q(!0);const F=i?await i(s,e.id,e):null,se=l(s,e.id,e,e.nodes||[],F);if("error"in se)throw new Error(se.error);const me=await d(se.targetDaemonId,{meshId:e.id,inlineMesh:se.inlineMesh,coordinatorNodeId:se.coordinatorNodeId,cliType:D.trim()||void 0});O(me.message)}catch(F){p((F==null?void 0:F.message)||"Coordinator launch failed")}finally{q(!1)}}}return{selectedNodeId:g,setSelectedNodeId:v,showAddNode:S,setShowAddNode:A,nodeWorkspace:k,setNodeWorkspace:w,nodeProviderPriority:y,setNodeProviderPriority:N,nodeDaemonId:j,setNodeDaemonId:C,nodeCustomPath:E,setNodeCustomPath:P,nodePickerWorkspaces:te,nodePickerProviders:ce,nodeOnboardingPlan:T,nodePlanLoading:_,coordinatorCliType:D,setCoordinatorCliType:L,launchingCoordinator:$,launchResult:R,settingMeshHost:G,savingPolicy:B,coordinatorPromptDraft:U,setCoordinatorPromptDraft:K,savingCoordinatorPrompt:oe,nodeSystemPromptDrafts:J,setNodeSystemPromptDrafts:ke,savingNodeSystemPromptId:de,savingNodeSlotsId:X,savingNodeCapabilitiesId:Oe,handleAddNode:Ce,handleRemoveNode:Q,handleUpdatePolicy:z,handleUpdateNodeSlots:Re,handleUpdateNodeCapabilities:we,handleSaveCoordinatorPrompt:V,handleSaveNodeSystemPrompt:xe,handleLaunchCoordinator:ae,handleSetMeshHost:Z}}const iD=[];function cD(e){const t=e==null?void 0:e.queue,s=t&&typeof t=="object"&&!Array.isArray(t)?t.tasks:t;return Array.isArray(s)?s.filter(r=>!!r&&typeof r=="object"&&typeof r.id=="string"):iD}function lD({status:e}){return{meshQueue:c.useMemo(()=>cD(e),[e])}}const dD=()=>()=>{};function Hx(e){const t=c.useCallback(r=>e?RA(e,r):dD(),[e]),s=c.useCallback(()=>uo(e),[e]);return c.useSyncExternalStore(t,s,s)}function R3({meshId:e,daemonId:t,load:s,extract:r,sendData:o}){const a=Hx(e),i=c.useRef(s);i.current=s;const l=c.useRef(r);l.current=r;const d=c.useCallback(h=>{const p=i.current;return!e||!t||!p?Promise.resolve(null):$i({meshId:e,daemonId:t,refresh:h,load:p,extract:l.current})},[e,t]);_x({meshId:e,daemonId:t,sendData:o});const u=c.useCallback(()=>d(!0),[d]),m=c.useCallback(()=>d(!1),[d]);return{status:(a==null?void 0:a.status)??null,loading:(a==null?void 0:a.loading)??!1,refreshing:(a==null?void 0:a.refreshing)??!1,error:(a==null?void 0:a.error)??null,loadedAt:(a==null?void 0:a.loadedAt)??null,refresh:u,reload:m}}function uD(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}function mD({selectedMeshId:e,loadMeshStatus:t,extractStatus:s,normalizeNode:r}){const o=Hx(e),[a,i]=c.useState(null),[l,d]=c.useState("idle"),u=(o==null?void 0:o.status)??null,m=c.useMemo(()=>!u||!r?u:{...u,nodes:(u.nodes??[]).map(b=>r(b,u.meshId??e??"",""))},[u,r,e]);function h(b){e&&PA(e,b,(o==null?void 0:o.daemonId)??null)}async function p(b,f=e,x=!1){var v;if(!b||!f)return;i(null),d(x?"settling":"first_paint"),await $i({meshId:f,daemonId:b,refresh:x,load:(S,A,k)=>t(S,A,{refresh:k.refresh}),extract:S=>s(S)})?d("settled"):(i(((v=uo(f))==null?void 0:v.error)||"Failed to load mesh graph"),d("idle"))}return{meshGraphStatus:m,setMeshGraphStatus:h,graphLoading:!!(o!=null&&o.loading)&&!u,graphError:a??(u?null:(o==null?void 0:o.error)??null),setGraphError:i,graphProvenance:l,graphBootstrapFallback:uD(o==null?void 0:o.response),loadGraph:p}}function hD(){var fn;const e=sL(),{t}=he("common"),{confirm:s,confirmDialog:r}=Tr(),{sendCommand:o,sendData:a,daemons:i,userName:l,loadMeshStatus:d,launchCoordinator:u,loadLiveMesh:m,extractStatus:h,unwrapResult:p,normalizeMesh:b,normalizeNode:f,resolveCommandTarget:x,features:g}=e,v=Rr(),S=i[0],A=(S==null?void 0:S.id)||"",k=c.useMemo(()=>Wn((S==null?void 0:S.availableProviders)||[]),[S]),{meshes:w,selectedMeshId:y,setSelectedMeshId:N,loading:j,error:C,setError:E,showCreate:P,setShowCreate:T,createName:M,setCreateName:_,createRepoIdentity:I,setCreateRepoIdentity:D,createRepoRemoteUrl:L,setCreateRepoRemoteUrl:$,newMeshDaemonId:q,setNewMeshDaemonId:G,newMeshWorkspace:W,setNewMeshWorkspace:R,createPickerWorkspaces:O,createOnboardingPlan:B,createPlanLoading:H,creating:U,createWarning:K,setCreateWarning:oe,loadMeshes:ge,handleCreate:J,handleDelete:ke,cancelCreate:de}=yx({confirmAction:s,daemons:i,primaryDaemonId:A,sendCommand:o,unwrapResult:p,normalizeMesh:b,features:g,loadDaemonMetadata:v}),ne=w.find(Ge=>Ge.id===y)||null,{meshGraphStatus:le,graphLoading:te,graphError:ce,setGraphError:Ce,loadGraph:Q}=mD({selectedMeshId:y,loadMeshStatus:d,extractStatus:h,normalizeNode:f}),[z,X]=c.useState(""),[pe,Re]=c.useState(""),Oe=g.meshHostDaemonSection?z:A,{meshQueue:De}=lD({status:le}),we=async()=>{!y||!Oe||await Q(Oe,y,!1)},{selectedNodeId:V,setSelectedNodeId:xe,showAddNode:Z,setShowAddNode:ae,nodeWorkspace:F,setNodeWorkspace:se,nodeProviderPriority:me,setNodeProviderPriority:re,nodeDaemonId:Se,setNodeDaemonId:Y,nodeCustomPath:ue,setNodeCustomPath:fe,nodePickerWorkspaces:Ie,nodePickerProviders:Ke,nodeOnboardingPlan:_e,nodePlanLoading:Ne,coordinatorCliType:Be,savingPolicy:$e,coordinatorPromptDraft:it,setCoordinatorPromptDraft:dt,savingCoordinatorPrompt:ut,nodeSystemPromptDrafts:It,setNodeSystemPromptDrafts:bt,savingNodeSystemPromptId:jt,savingNodeSlotsId:ee,savingNodeCapabilitiesId:ie,handleAddNode:ve,handleRemoveNode:Te,handleUpdatePolicy:Ee,handleUpdateNodeSlots:Ye,handleUpdateNodeCapabilities:qe,handleSaveCoordinatorPrompt:Pe,handleSaveNodeSystemPrompt:tt,settingMeshHost:At,handleSetMeshHost:gt}=aD({confirmAction:s,selectedMesh:ne,selectedMeshId:y,activeDaemonId:Oe,daemons:i,availableCliProviders:k,sendCommand:o,unwrapResult:p,loadLiveMesh:m,resolveCommandTarget:x,launchCoordinator:u,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:ge,reloadMeshStatus:we,setError:E}),ye=c.useMemo(()=>i.find(Ge=>Ge.id===Oe)||S,[i,Oe,S]),Ae=c.useMemo(()=>new Set(((ne==null?void 0:ne.nodes)||[]).map(Ge=>String(Ge.daemon_id||Ge.daemonId||""))),[ne]),Le=c.useMemo(()=>i.filter(Ge=>Ge.id&&!Ae.has(Ge.id)&&!wp(Ge)),[i,Ae]),Ve=(ne==null?void 0:ne.nodes)||[],Je=c.useMemo(()=>Ve.find(Ge=>en(String(Ge.daemon_id||Ge.daemonId||""),z)),[Ve,z]),ht=g.meshHostDaemonSection?!!Je:!0,st=c.useMemo(()=>{if(!g.meshHostDaemonSection||!ne)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Ge=ne.meshHost,lt=le!=null&&le.meshId&&String(le.meshId)===String(ne.id??"")?le.meshHost:void 0,Me=lt!=null&<.hostDaemonId?lt:Ge??lt,We=ed(Me),ot=We.hostDaemonId,St=Ve.find(Xt=>Xt.role==="host"),zt=We.hostNodeId||String((St==null?void 0:St.id)||""),mt=zt?Ve.find(Xt=>String(Xt.id)===zt):void 0,Yt=String((mt==null?void 0:mt.daemon_id)||(mt==null?void 0:mt.daemonId)||""),Tn=ot||Yt;if(!Tn)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const vn=i.find(Xt=>ot&&en(Xt.id,ot))||(Yt?i.find(Xt=>en(Xt.id,Yt)):void 0);if(vn)return{pinned:!0,daemonId:vn.id,label:pD(vn),online:!0,hostNode:mt};const In=String((mt==null?void 0:mt.machineLabel)||"")||String((mt==null?void 0:mt.workspace)||"")||Tn;return{pinned:!0,daemonId:Tn,label:In,online:!1,hostNode:mt}},[ne,Ve,i,le,g.meshHostDaemonSection]),Nt=st.daemonId,xt=st.online,Wt=st.pinned?st.hostNode:Je,Jt=c.useMemo(()=>!g.meshHostDaemonSection||!st.pinned?"":!xt&&pe&&i.some(Ge=>Ge.id===pe)?pe:Nt,[g.meshHostDaemonSection,st.pinned,xt,pe,i,Nt]),an=tL({status:le,daemonId:Oe||null,meshId:y,sendData:a});c.useEffect(()=>{const Ge=(ne==null?void 0:ne.coordinator)||{};dt({override:typeof Ge.systemPromptOverride=="string"?Ge.systemPromptOverride:"",append:typeof Ge.systemPromptAppend=="string"?Ge.systemPromptAppend:typeof Ge.systemPromptSuffix=="string"?Ge.systemPromptSuffix:""}),bt(Object.fromEntries(((ne==null?void 0:ne.nodes)||[]).map(lt=>[lt.id,typeof lt.systemPrompt=="string"?lt.systemPrompt:""])))},[ne]),c.useEffect(()=>{const Ge=g.addNodeDaemonPicker?Ks(Ke):Ks(k);Z&&me.length===0&&Ge.length>0&&re(Ge)},[Z,k,Ke,me.length,g.addNodeDaemonPicker]),c.useEffect(()=>{const Ge=new Set(((ne==null?void 0:ne.nodes)||[]).map(lt=>lt.id));V&&!Ge.has(V)&&xe(null)},[ne,V]);const qt=c.useMemo(()=>{if(!(!(le!=null&&le.meshId)||String(le.meshId)!==String((ne==null?void 0:ne.id)??"")))return ed(le.meshHost).hostDaemonId||void 0},[le,ne]),Tt=c.useMemo(()=>ZR(i,Ve,Oe,A,qt),[i,Ve,Oe,A,qt]);c.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!i.length&&!st.pinned){X("");return}const Ge=st.pinned?Jt:Tt;Ge&&!en(Ge,z)&&X(Ge)},[i,z,st.pinned,Jt,Tt,g.meshHostDaemonSection]),c.useEffect(()=>{pe&&(xt||!i.some(Ge=>Ge.id===pe))&&Re("")},[xt,pe,i]),c.useEffect(()=>{if(g.createDaemonPicker){if(!i.length){G("");return}(!q||!i.some(Ge=>Ge.id===q))&&G(i[0].id)}},[i,q,g.createDaemonPicker]);const cn=c.useRef(null),Kn=((fn=O[0])==null?void 0:fn.path)||"";c.useEffect(()=>{g.createDaemonPicker&&(cn.current!==q&&(cn.current=q,R("")),q&&Kn&&R(Ge=>Ge||Kn))},[q,Kn,g.createDaemonPicker]),c.useEffect(()=>{Ce(null)},[y,Oe]),_x({meshId:y,daemonId:Oe||null,sendData:a});const Ct=c.useMemo(()=>i.map(Ge=>Ge.id).filter(Boolean).sort().join(","),[i]),ln=c.useRef(!1);return c.useEffect(()=>{ge(ln.current),Ct&&(ln.current=!0)},[Ct]),A?ne?n.jsxs(n.Fragment,{children:[r,n.jsx(oD,{selectedMesh:ne,error:C,onDismissError:()=>E(null),onBack:()=>{N(null)},onDelete:ke,displayedMeshStatus:an,graphLoading:te,graphError:ce,onRefreshGraph:()=>{Q(Oe,y,!0)},savingPolicy:$e,onUpdatePolicy:Ee,coordinatorPromptDraft:it,onCoordinatorPromptDraftChange:dt,savingCoordinatorPrompt:ut,onSaveCoordinatorPrompt:Pe,daemons:i,coordinatorDaemonId:z,onCoordinatorDaemonIdChange:X,coordinatorCliType:Be,isHostNodeAttached:ht,selectedHostNode:Wt,hostPinned:st.pinned,hostLabel:st.label,hostOnline:xt,hostRebindDaemonId:pe,onHostRebindDaemonIdChange:Ge=>Re(Ge),settingMeshHost:At,onSetMeshHost:gt,activeDaemon:ye,activeDaemonId:Oe,meshQueue:De,userName:l,availableCliProviders:k,savingNodeSlotsId:ee,onUpdateNodeSlots:Ye,savingNodeCapabilitiesId:ie,onUpdateNodeCapabilities:qe,nodeSystemPromptDrafts:It,onNodeSystemPromptDraftChange:(Ge,lt)=>bt(Me=>({...Me,[Ge]:lt})),savingNodeSystemPromptId:jt,onSaveNodeSystemPrompt:tt,selectedNodeId:V,onSelectNode:xe,showAddNode:Z,onShowAddNode:()=>ae(!0),onCancelAddNode:()=>ae(!1),nodeWorkspace:F,onNodeWorkspaceChange:se,nodeProviderPriority:me,onNodeProviderPriorityChange:re,nodeDaemonId:Se,onNodeDaemonIdChange:Y,nodeCustomPath:ue,onNodeCustomPathChange:fe,nodePickerWorkspaces:Ie,nodePickerProviders:Ke,nodeOnboardingPlan:_e,nodePlanLoading:Ne,attachableDaemons:Le,onAddNode:ve,onRemoveNode:Te,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:o})]}):n.jsxs(n.Fragment,{children:[r,n.jsx(DL,{meshes:w,loading:j,error:C,onDismissError:()=>E(null),daemons:i,features:{createDaemonPicker:g.createDaemonPicker},showCreate:P,onToggleCreate:()=>T(!P),createName:M,onCreateNameChange:_,createRepoIdentity:I,onCreateRepoIdentityChange:D,createRepoRemoteUrl:L,onCreateRepoRemoteUrlChange:$,newMeshDaemonId:q,onNewMeshDaemonIdChange:G,newMeshWorkspace:W,onNewMeshWorkspaceChange:R,createPickerWorkspaces:O,createOnboardingPlan:B,createPlanLoading:H,creating:U,createWarning:K,onDismissCreateWarning:()=>oe(null),onSelectMesh:N,onCreate:J,onCancelCreate:de,sendCommand:o})]}):n.jsx(Lo,{icon:n.jsx(On,{}),title:"Repo Mesh",subtitle:t("mesh.page.subtitle"),children:n.jsx("div",{className:"text-sm text-text-muted p-4",children:t("mesh.page.waitingForDaemon")})})}function pD(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function fD({children:e}){const{sendCommand:t,sendData:s}=wt(),{ides:r}=yn(),o=c.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),a=c.useMemo(()=>({sendCommand:t,sendData:s,daemons:o,userName:void 0,loadMeshStatus:async(i,l,d)=>t(i,"mesh_status",(d==null?void 0:d.refresh)===!0?{meshId:l,refresh:!0}:{meshId:l}),launchCoordinator:async(i,l)=>{var p;const d={meshId:l.meshId};l.cliType&&(d.cliType=l.cliType);const u=await t(i,"launch_mesh_coordinator",d),m=(u==null?void 0:u.result)??u;if((m==null?void 0:m.success)===!1)throw new Error(m.error||"Coordinator launch failed");const h=(m==null?void 0:m.sessionId)||((p=m==null?void 0:m.session)==null?void 0:p.id)||(m==null?void 0:m.targetSessionId);return{sessionId:h,message:h?`Coordinator launched (${h})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Di,unwrapResult:i=>i,normalizeMesh:(i,l)=>i,normalizeNode:(i,l,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:Ax}),[t,s,o]);return n.jsx(Tx.Provider,{value:a,children:e})}function bD(e){const{daemons:t,features:s,meshes:r,meshesLoading:o,selectedMeshId:a,onSelectMesh:i,createMode:l,onCreateModeChange:d,createName:u,onCreateNameChange:m,createDaemonId:h,onCreateDaemonIdChange:p,createWorkspace:b,onCreateWorkspaceChange:f,createPickerWorkspaces:x,createPlan:g,createPlanLoading:v,creating:S,createWarning:A,onCreate:k,createRepoRemoteUrl:w,onCreateRepoRemoteUrlChange:y,createRepoIdentity:N,onCreateRepoIdentityChange:j,createManualOpen:C,onCreateManualOpenChange:E,nodes:P,attachableDaemons:T,attachDaemonId:M,onAttachDaemonIdChange:_,attachWorkspace:I,onAttachWorkspaceChange:D,attachPickerWorkspaces:L,attachPlan:$,attachPlanLoading:q,attaching:G,onAttach:W,renderInstallOnboarding:R,nodeLabel:O,daemonLabel:B}=e,{t:H}=he("common");if(t.length===0)return n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:H("setupWizard.machines.title")}),n.jsx("p",{className:"mt-1 text-2xs leading-relaxed text-text-muted",children:H("setupWizard.machines.noMachinesDescription")})]}),R?R():n.jsx("p",{className:"text-2xs text-text-muted",children:H("setupWizard.machines.noMachinesFallback")})]});const U=G||q||($==null?void 0:$.success)===!1||!I.trim()||s.addNodeDaemonPicker&&!M;return n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:H("setupWizard.machines.title")}),n.jsx("p",{className:"mt-1 text-2xs leading-relaxed text-text-muted",children:H("setupWizard.machines.description")})]}),n.jsxs("div",{className:"flex flex-col gap-2",children:[r.map(K=>{const oe=!l&&a===K.id;return n.jsx("button",{type:"button",onClick:()=>{d(!1),i(K.id)},className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${oe?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:n.jsxs("span",{className:"min-w-0",children:[n.jsx("span",{className:"block truncate text-sm text-text-primary",children:K.name}),n.jsxs("span",{className:"block truncate text-2xs text-text-muted",children:[K.repoIdentity||K.repoRemoteUrl||""," · ",H("setupWizard.machines.nodeCount",{count:(K.nodes||[]).length})]})]})},K.id)}),n.jsx("button",{type:"button",onClick:()=>d(!0),className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${l?"border-accent-primary/60 bg-accent-primary/10":"border-dashed border-border-subtle bg-bg-secondary/40 hover:border-border-default"}`,children:n.jsxs("span",{className:"text-sm text-text-primary",children:["+ ",H("setupWizard.machines.createNew")]})}),o&&r.length===0&&n.jsx("p",{className:"text-2xs text-text-muted",children:H("setupWizard.machines.loadingMeshes")})]}),l&&n.jsx(Rx,{variant:"wizard",showDaemonPicker:s.createDaemonPicker,daemons:t,daemonLabel:B,name:u,onNameChange:m,daemonId:h,onDaemonIdChange:p,workspace:b,onWorkspaceChange:f,workspaces:x,plan:g,planLoading:v,repoRemoteUrl:w,onRepoRemoteUrlChange:y,repoIdentity:N,onRepoIdentityChange:j,manualOpen:C,onManualOpenChange:E,creating:S,warning:A,onCreate:k}),!l&&a&&n.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[P.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1.5",children:P.map(K=>n.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-3xs text-text-secondary",children:O(K)},K.id))}),n.jsx("span",{className:"text-2xs font-medium text-text-secondary",children:H("setupWizard.machines.attachTitle")}),s.addNodeDaemonPicker&&(T.length>0?n.jsx("div",{className:"flex flex-wrap gap-1.5",children:T.map(K=>{const oe=M===K.id;return n.jsx("button",{type:"button",onClick:()=>_(K.id),className:`rounded-full border px-2.5 py-1 text-2xs transition-colors ${oe?"border-accent-primary/60 bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-secondary text-text-secondary hover:border-border-default"}`,children:B(K)},K.id)})}):n.jsx("p",{className:"text-2xs text-text-muted",children:H("setupWizard.machines.allMachinesAttached")})),(!s.addNodeDaemonPicker||M)&&n.jsxs(n.Fragment,{children:[n.jsx(sd,{workspaces:L,value:I,onChange:D}),n.jsx(Mx,{plan:$,loading:q}),n.jsx("div",{className:"flex justify-end",children:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:W,disabled:U,children:H(G?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function gD(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function xD(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function yD({daemons:e,features:t,sendCommand:s,unwrapResult:r,normalizeMesh:o,loadDaemonMetadata:a,initialMeshId:i,onClose:l,renderInstallOnboarding:d}){var F,se;const{t:u}=he("common"),m=((F=e[0])==null?void 0:F.id)||"",{meshes:h,loading:p,error:b,setError:f,loadMeshes:x,selectedMeshId:g,setSelectedMeshId:v}=yx({daemons:e,primaryDaemonId:m,sendCommand:s,unwrapResult:r,normalizeMesh:o,features:{createDaemonPicker:t.createDaemonPicker,addNodeDaemonPicker:t.addNodeDaemonPicker},loadDaemonMetadata:a});c.useEffect(()=>{x()},[x]);const S=c.useRef(h);S.current=h;const A=c.useMemo(()=>h.map(me=>me.id).sort().join(","),[h]),k=c.useRef(s);k.current=s;const w=c.useRef(r);w.current=r,c.useEffect(()=>{g||h.length===0||(i&&h.some(me=>me.id===i)?v(i):h.length===1&&v(h[0].id))},[h,g,i,v]);const y=c.useMemo(()=>h.find(me=>me.id===g)??null,[h,g]),N=c.useMemo(()=>(y==null?void 0:y.nodes)||[],[y]),j=c.useCallback(me=>Do(me,e),[e]),[C,E]=c.useState(!1),[P,T]=c.useState(""),[M,_]=c.useState(""),[I,D]=c.useState(""),[L,$]=c.useState(null),[q,G]=c.useState(!1),[W,R]=c.useState(!1),[O,B]=c.useState(null),[H,U]=c.useState(""),[K,oe]=c.useState(""),[ge,J]=c.useState(!1),ke=t.createDaemonPicker&&M||m,de=c.useMemo(()=>e.find(me=>me.id===ke),[e,ke]),ne=(de==null?void 0:de.workspaces)||[];c.useEffect(()=>{if(!C||!ke||!I.trim()){$(null),G(!1);return}let me=!1;const re=setTimeout(()=>{me||(G(!0),k.current(ke,"plan_mesh_onboarding",{workspace:I.trim(),operation:"auto",meshInventory:S.current}).then(Se=>{if(me)return;const Y=w.current(Se);$(Y),Y!=null&&Y.success&&(T(ue=>{var fe,Ie;return ue||`${String(((fe=Y.discovery)==null?void 0:fe.repoIdentity)||((Ie=Y.discovery)==null?void 0:Ie.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),oe(ue=>{var fe;return ue||((fe=Y.discovery)==null?void 0:fe.repoIdentity)||""}),U(ue=>{var fe,Ie,Ke,_e,Ne,Be;return ue||((Ke=(Ie=(fe=Y.discovery)==null?void 0:fe.origin)==null?void 0:Ie.urls)==null?void 0:Ke[0])||((Be=(Ne=(_e=Y.discovery)==null?void 0:_e.upstream)==null?void 0:Ne.urls)==null?void 0:Be[0])||""}))}).catch(Se=>{me||$({success:!1,error:(Se==null?void 0:Se.message)||"Git discovery failed"})}).finally(()=>{me||G(!1)}))},300);return()=>{me=!0,clearTimeout(re)}},[C,ke,I,A]);const le=c.useCallback(async()=>{const me=ke,re=I.trim(),Se=H.trim(),Y=K.trim();if(!(!me||!P.trim()||W)&&!(!re&&!Se&&!Y)){R(!0),B(null),f(null);try{const ue=await xx({targetDaemonId:me,name:P,repoRemoteUrl:Se,repoIdentity:Y,workspace:re,attachWorkspace:!!re,machineId:de==null?void 0:de.machineId,providerPriority:Ks(Wn((de==null?void 0:de.availableProviders)||[])),meshInventory:h,sendCommand:s,unwrapResult:r});if(ue.warning&&B(ue.warning),!ue.meshCreated){f(ue.error||u("setupWizard.machines.createFailed"));return}await x(!0),ue.meshId&&v(ue.meshId),E(!1)}finally{R(!1)}}},[ke,P,I,H,K,W,de,h,s,r,x,v,f,u]),[te,ce]=c.useState(""),[Ce,Q]=c.useState(""),[z,X]=c.useState(null),[pe,Re]=c.useState(!1),[Oe,De]=c.useState(!1),we=c.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const me=new Set(N.map(re=>String(re.daemon_id||re.daemonId||"")));return e.filter(re=>re.id&&!me.has(re.id)&&!wp(re))},[t.addNodeDaemonPicker,N,e]),V=c.useMemo(()=>e.find(me=>me.id===te),[e,te]),xe=t.addNodeDaemonPicker?(V==null?void 0:V.workspaces)||[]:((se=e.find(me=>me.id===m))==null?void 0:se.workspaces)||[];c.useEffect(()=>{if(C||!g||!Ce.trim()){X(null);return}const me=t.addNodeDaemonPicker?te:j(y);if(!me)return;let re=!1;return Re(!0),s(me,"plan_mesh_onboarding",{workspace:Ce.trim(),meshId:g,inlineMesh:y,operation:"add_existing"}).then(Se=>{re||X(r(Se))}).catch(Se=>{re||X({success:!1,error:(Se==null?void 0:Se.message)||"Git discovery failed"})}).finally(()=>{re||Re(!1)}),()=>{re=!0}},[C,g,y,Ce,te,t.addNodeDaemonPicker,j,s,r]);const Z=c.useCallback(async()=>{var Se,Y,ue,fe;const me=j(y);if(!g||Oe)return;if(!me){f(u("mesh.host.noCommandTarget"));return}const re=Ce.trim();if(re){De(!0),f(null);try{const Ie=t.addNodeDaemonPicker?te:me,Ke=await s(Ie,"plan_mesh_onboarding",{workspace:re,meshId:g,inlineMesh:y,operation:"add_existing"}),_e=r(Ke);if(X(_e),(_e==null?void 0:_e.success)===!1)throw new Error(`${_e.code||"onboarding_blocked"}: ${_e.error}${_e.action?` ${_e.action}`:""}`);const Ne={meshId:g,workspace:((Se=_e==null?void 0:_e.discovery)==null?void 0:Se.repoRoot)||re,repoRoot:(Y=_e==null?void 0:_e.discovery)==null?void 0:Y.repoRoot,isLocalWorktree:((ue=_e==null?void 0:_e.discovery)==null?void 0:ue.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&te&&(Ne.daemonId=te,Ne.machineId=V==null?void 0:V.machineId),Ne.providerPriority=Ks(Wn(((fe=t.addNodeDaemonPicker?V:e[0])==null?void 0:fe.availableProviders)||[]));const Be=await s(me,"add_mesh_node",Ne),$e=r(Be);if(($e==null?void 0:$e.success)===!1)throw new Error($e.error||"Add node failed");Q(""),X(null),await x(!0)}catch(Ie){f((Ie==null?void 0:Ie.message)||"Add node failed")}finally{De(!1)}}},[y,g,Ce,te,V,Oe,t.addNodeDaemonPicker,j,e,s,r,x,f,u]),ae=!C&&!!y&&N.length>0;return n.jsxs("div",{className:"mx-auto flex w-full max-w-2xl flex-col gap-4 p-4",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-base font-semibold text-text-primary",children:u("setupWizard.title")}),n.jsx("p",{className:"mt-1.5 text-2xs text-text-muted",children:u("setupWizard.machines.description")})]}),b&&n.jsx("p",{className:"text-2xs text-red-400",children:b}),n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary p-4",children:n.jsx(bD,{daemons:e,features:t,meshes:h,meshesLoading:p,selectedMeshId:g,onSelectMesh:me=>{v(me),Q(""),ce("")},createMode:C,onCreateModeChange:E,createName:P,onCreateNameChange:T,createDaemonId:M,onCreateDaemonIdChange:_,createWorkspace:I,onCreateWorkspaceChange:D,createPickerWorkspaces:ne,createPlan:L,createPlanLoading:q,creating:W,createWarning:O,onCreate:le,createRepoRemoteUrl:H,onCreateRepoRemoteUrlChange:U,createRepoIdentity:K,onCreateRepoIdentityChange:oe,createManualOpen:ge,onCreateManualOpenChange:J,nodes:N,attachableDaemons:we,attachDaemonId:te,onAttachDaemonIdChange:me=>{ce(me),Q("")},attachWorkspace:Ce,onAttachWorkspaceChange:Q,attachPickerWorkspaces:xe,attachPlan:z,attachPlanLoading:pe,attaching:Oe,onAttach:Z,renderInstallOnboarding:d,nodeLabel:xD,daemonLabel:gD})}),n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("div",{className:"ml-auto flex items-center gap-2",children:n.jsx("button",{type:"button",className:ae?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:l,children:u(ae?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function Gi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function vD(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),s=Gi();return s&&!t.searchParams.has("token")&&t.searchParams.set("token",s),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function En(e,t){return await fetch(vD(e),{credentials:"same-origin",...t})}function Bx(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class wD{constructor(){ze(this,"adapters",new Map);ze(this,"states",new Map);ze(this,"runtimeListeners",new Map);ze(this,"screenshotCallbacks",new Map);ze(this,"stateChangeCallbacks",new Set);ze(this,"ptyInputSender",null);ze(this,"dataSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const s of this.adapters.keys())if(s.startsWith("standalone"))return s}return null}register(t,s){this.adapters.set(t,s),this.states.set(t,s.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,s){this.states.set(t,s);const r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(o=>o(r,s))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const s=this.resolveDaemonId(t);return s?this.adapters.get(s):void 0}getState(t){const s=this.resolveDaemonId(t);return s&&this.states.get(s)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}registerDataSender(t){this.dataSender=t}sendData(t,s){return!1}sendPtyInput(t,s,r){return this.ptyInputSender?this.ptyInputSender(t,s,r):!1}onScreenshot(t,s){return this.screenshotCallbacks.set(t,s),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,s){this.screenshotCallbacks.forEach(r=>r(t,s))}emitRuntimeSnapshot(t,s,r=0,o=!1,a,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:s,truncated:o,cols:a,rows:i})}emitSessionOutput(t,s,r){!t||typeof s!="string"||!s||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:s})}onRuntimeEvent(t,s,r){const o=this.runtimeListeners.get(t)||new Set;o.add(s),this.runtimeListeners.set(t,o);const a=this.dataSender,i=a&&t?Fn.subscribe({sendData:(l,d)=>a(l,d)},r||this.resolveDaemonId("standalone")||"standalone",{type:"subscribe",topic:"session.runtime_output",key:`runtime:${t}`,params:{targetSessionId:t}},()=>{}):void 0;return()=>{i==null||i();const l=this.runtimeListeners.get(t);l&&(l.delete(s),l.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,s,r){if(!s)return{success:!1,error:"sessionId is required"};const o=new URL(`/api/v1/runtime/${encodeURIComponent(s)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&o.searchParams.set("sinceSeq",String(r.sinceSeq));const a=await En(`${o.pathname}${o.search}`);if(!a.ok){let l=`Runtime snapshot unavailable (${a.status})`;try{const d=await a.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}const i=await a.json();return this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,s){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(o=>o(s))}}const Ln=new wD;function SD(e,t,s,r){if(!e||typeof e!="object"||e.type!=="status_event")return!1;const o=e.payload;if(!o||typeof o!="object"||typeof o.event!="string")return!0;const a=t||"standalone",i=o.targetSessionId;return r&&typeof i=="string"&&i&&r(a,i,o.event),s.handleRawEvent({...o,daemonId:a},"ws"),!0}const kD="/ws/seqscribe",jD="standalone_dashboard",lp=3e3,ND=3e4,CD=3e4,_D=1e3,AD=6e4;function TD(e,t){const r=`${e.protocol==="https:"?"wss":"ws"}://${e.host}${kD}`;return t?`${r}?token=${encodeURIComponent(t)}`:r}const ID=["request_transcript_base"];function MD(e){if(!e||typeof e!="object")return!1;const t=e;return t.type==="subscribe"||t.type==="unsubscribe"?!0:t.type==="command"&&typeof t.commandType=="string"&&ID.includes(t.commandType)}const ad=new Set;function RD(e){if(e.length!==0)for(const t of[...ad])try{t(e)}catch{}}function PD(e){return ad.add(e),()=>{ad.delete(e)}}class ED{constructor(t){ze(this,"socket",null);ze(this,"host",null);ze(this,"openedAt",null);ze(this,"reconnectTimer",null);ze(this,"reconnectDelay",lp);ze(this,"unsubscribeInterest",null);ze(this,"unsubscribeTopicsAvailable",null);ze(this,"sessionDaemons",new Map);ze(this,"activeSessions",[]);ze(this,"delivered",new Set);ze(this,"subRetryTimer",null);ze(this,"subRetryDelay");ze(this,"subRetryInitialMs");ze(this,"subRetryMaxMs");ze(this,"started",!1);ze(this,"stopped",!1);var s,r;this.deps=t,this.subRetryInitialMs=((s=t.subRetrySchedule)==null?void 0:s.initialMs)??_D,this.subRetryMaxMs=((r=t.subRetrySchedule)==null?void 0:r.maxMs)??AD,this.subRetryDelay=this.subRetryInitialMs}start(){var t,s;this.started||this.stopped||(this.started=!0,this.unsubscribeInterest=this.deps.subscribeInterest(()=>this.syncInterest()),this.unsubscribeTopicsAvailable=((s=(t=this.deps).subscribeTopicsAvailable)==null?void 0:s.call(t,r=>this.handleTopicsAvailable(r)))??null,this.syncInterest(),this.connect())}stop(){var s,r;if(this.stopped)return;this.stopped=!0,(s=this.unsubscribeInterest)==null||s.call(this),this.unsubscribeInterest=null,(r=this.unsubscribeTopicsAvailable)==null||r.call(this),this.unsubscribeTopicsAvailable=null,this.reconnectTimer!==null&&this.deps.clearTimer(this.reconnectTimer),this.reconnectTimer=null;const t=this.socket;this.socket=null,this.stopHost();try{t==null||t.close()}catch{}}isHostRunning(){return this.host!==null}currentReconnectDelay(){return this.reconnectDelay}connect(){var s,r;if(this.stopped)return;let t;try{t=this.deps.createSocket()}catch(o){(r=(s=this.deps).log)==null||r.call(s,`[Transcript] standalone lane socket failed: ${o instanceof Error?o.message:String(o)}`),this.scheduleReconnect();return}this.socket=t,t.addEventListener("open",()=>this.handleOpen(t)),t.addEventListener("close",()=>this.handleClose(t))}handleOpen(t){var r,o;if(this.stopped||t!==this.socket)return;this.openedAt=this.deps.now(),this.stopHost();const s=this.deps.startHost(t,a=>this.deliver(a),a=>this.requestBase(a));if(!s){(o=(r=this.deps).log)==null||o.call(r,"[Transcript] standalone lane: transcript worker unavailable — live chat cannot be shown"),this.stopped=!0,this.socket=null;try{t.close()}catch{}return}this.host=s,this.activeSessions.length>0&&s.activateSessions(this.activeSessions),this.armSubRetry(!0)}handleClose(t){if(t!==this.socket)return;this.socket=null;const s=this.openedAt===null?0:this.deps.now()-this.openedAt;this.openedAt=null,s>=CD&&(this.reconnectDelay=lp),this.stopHost(),this.scheduleReconnect()}scheduleReconnect(){if(this.stopped||this.reconnectTimer!==null)return;const t=this.reconnectDelay;this.reconnectDelay=Math.min(Math.round(this.reconnectDelay*1.5),ND),this.reconnectTimer=this.deps.setTimer(()=>{this.reconnectTimer=null,this.connect()},t,"reconnect")}stopHost(){const t=this.host;t&&(this.host=null,this.delivered.clear(),this.subRetryTimer!==null&&this.deps.clearTimer(this.subRetryTimer),this.subRetryTimer=null,t.stop())}syncInterest(){var r;const t=new Map;for(const[o,a]of this.deps.collectInterest())for(const i of a){const l=t.get(i);l?l.includes(o)||l.push(o):t.set(i,[o])}this.sessionDaemons=t;const s=[...t.keys()].sort();if(!(s.length===this.activeSessions.length&&s.every((o,a)=>o===this.activeSessions[a]))){this.activeSessions=s;for(const o of[...this.delivered])t.has(o)||this.delivered.delete(o);(r=this.host)==null||r.activateSessions(s),this.armSubRetry(!0)}}armSubRetry(t){if(t&&(this.subRetryDelay=this.subRetryInitialMs),!this.host||this.subRetryTimer!==null||!this.activeSessions.some(r=>!this.delivered.has(r)))return;const s=this.subRetryDelay;this.subRetryTimer=this.deps.setTimer(()=>{this.subRetryTimer=null,this.rearmUndelivered()},s,"sub-retry")}handleTopicsAvailable(t){const s=this.host;if(!s||this.stopped||!this.deps.selectResubscribe)return;const r=this.deps.selectResubscribe(this.activeSessions,this.delivered,t);if(r.length===0)return;const o=new Set(r);s.activateSessions(this.activeSessions.filter(a=>!o.has(a))),s.activateSessions(this.activeSessions)}rearmUndelivered(){const t=this.host;if(!t||this.stopped)return;const s=this.activeSessions.filter(r=>!this.delivered.has(r));if(s.length!==0){for(const r of s)this.requestBase(r);t.activateSessions(this.activeSessions.filter(r=>this.delivered.has(r))),t.activateSessions(this.activeSessions),this.subRetryDelay=Math.min(this.subRetryDelay*2,this.subRetryMaxMs),this.armSubRetry(!1)}}deliver(t){const s=this.sessionDaemons.get(t.sessionId);if(s){this.delivered.add(t.sessionId);for(const r of s)this.deps.applyView(r,t.sessionId,t.view)}}requestBase(t){for(const s of this.sessionDaemons.get(t)??[])if(this.deps.requestBase(s,t))return}}function tl(e){return{kind:"transcript-bridge-control",event:e}}function LD(e){return typeof e=="object"&&e!==null&&e.kind==="transcript-bridge-frame"&&Array.isArray(e.upserts)&&Array.isArray(e.deletes)}function DD(e){return typeof e=="object"&&e!==null&&e.kind==="transcript-bridge-base-request"&&typeof e.sessionId=="string"}function OD(e,t){return{kind:"transcript-session-activation",sessionIds:[...e],...t?{ownerDaemonId:t}:{}}}var $D=Object.create,Wx=Object.defineProperty,FD=Object.getOwnPropertyDescriptor,Ux=Object.getOwnPropertyNames,HD=Object.getPrototypeOf,BD=Object.prototype.hasOwnProperty,WD=(e,t)=>function(){return t||(0,e[Ux(e)[0]])((t={exports:{}}).exports,t),t.exports},UD=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ux(t))!BD.call(e,o)&&o!==s&&Wx(e,o,{get:()=>t[o],enumerable:!(r=FD(t,o))||r.enumerable});return e},KD=(e,t,s)=>(s=e!=null?$D(HD(e)):{},UD(Wx(s,"default",{value:e,enumerable:!0}),e)),qD=WD({"../../node_modules/canonicalize/lib/canonicalize.js"(e,t){t.exports=function s(r){if(typeof r=="number"&&isNaN(r))throw new Error("NaN is not allowed");if(typeof r=="number"&&!isFinite(r))throw new Error("Infinity is not allowed");return r===null||typeof r!="object"?JSON.stringify(r):r.toJSON instanceof Function?s(r.toJSON()):Array.isArray(r)?`[${r.reduce((i,l,d)=>`${i}${d===0?"":","}${s(l===void 0||typeof l=="symbol"?null:l)}`,"")}]`:`{${Object.keys(r).sort().reduce((a,i)=>{if(r[i]===void 0||typeof r[i]=="symbol")return a;const l=a.length===0?"":",";return`${a}${l}${s(i)}:${s(r[i])}`},"")}}`}}});function on(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var Kx=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress"];on(Kx);var zD=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];on(zD);var VD=["p2p_offer","p2p_ice"];on(VD);var GD=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];on(GD);var YD=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","daemon_mesh_command","p2p_offer","p2p_ice"];on(YD);var QD=["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"];on(QD);var JD=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],XD=[...Kx,...JD];on(XD);var ZD=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];on(ZD);var e5=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];on(e5);var t5=["p2p_ready","p2p_answer","p2p_ice"];on(t5);var n5=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];on(n5);var s5=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];on(s5);var qx=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];on(qx);var zx=["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"];on(zx);[...new Set([...qx,...zx])];var Vx=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"];new Set(Vx);var r5=["pending","assigned","completed","failed","cancelled"],o5=["completed","failed","cancelled"],a5=["code_change","validation","live_debug_readonly","launch_app","convergence"],i5=["low","normal","high"],c5=["when_idle","interrupt"],Gx=["completed","blocked","failed"],l5=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function Er(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Er(r5);Er(o5);Er(a5);Er(i5);Er(c5);Er(Gx);var d5=["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"],u5=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(u5);var m5=["projects","project_status","project_send","project_read","project_add","discover_repos","memory","skill_view","skill_manage","project_note"];new Set(m5);var h5=["mesh_queue","mesh_direct","plain"],p5=["delivered","queued"],f5=["local","p2p"],b5=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],g5=["default","native_source"],x5=["restart","live_holder"],y5=["approval","choice"],v5=["approved","rejected","answered"],w5=["modal_button","auto_approve","prompt_answer"],S5=["genuine","weak"],k5=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],j5=["completed","aborted"],N5=["alive","unknown","read_failed","dead"],dp=["auth_failed","billing_failed"],C5=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],_5=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],A5=["completed","failed"],T5=["operator_update","refine_terminal","validation_terminal"],I5=["delivered","queued","duplicate"],M5=[...Vx,"unknown"],R5=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],P5=["completed","failed","cancelled"],E5=["genuine","weak","tool_report","operator"],L5=["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"],Yx=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],rr={t:"id"},or={t:"id",optional:!0},ds={t:"bool"},fa={t:"bool",optional:!0},up={t:"ms"},D5={t:"ms",optional:!0},ba={t:"int",optional:!0},Et=e=>({t:"enum",values:e}),ar=e=>({t:"enum",values:e,optional:!0}),O5={dispatch_accepted:{scope:Et(h5),messageId:rr,meshId:or,nodeId:or,providerType:or,attemptNo:ba,dispatchNonce:ba,consumeProfile:ar(g5),maxTaskRetries:ba,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:rr,outcome:Et(p5),via:Et(f5)},delivery_refused:{messageId:rr,reason:Et(d5)},dispatch_failed:{workerAbsent:ds,reason:Et(b5),refusalCode:or},duplicate_dispatch_refusal:{holderSessionId:rr,holderAttemptId:or},session_rebound:{toSessionId:rr,reason:Et(x5)},turn_started:{retro:ds},suspension:{modal:Et(y5),modalKey:or},suspension_resolved:{resolution:Et(v5),via:Et(w5)},turn_end:{strength:Et(S5),afterFinalizationTimeout:fa,hollow:fa,summary:{t:"summary_ref",optional:!0},blockReason:ar(k5),releasedByHardCap:fa,nativeOutcome:ar(j5),live:{t:"live",optional:!0},reportExpected:fa,providerFailure:ar(dp)},transcript_final:{selfAttributing:ds,nativeRead:ds,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:D5},transcript_activity:{newestActivityAt:up},no_progress:{stalledMs:up,observedStatus:Et(M5),finalAssistantPresent:ds},liveness:{result:Et(N5)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:ar(dp)},session_error:{reason:Et(C5)},worker_report:{outcome:Et(Gx),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:ds,branchState:ar(l5),touchedFileCount:ba},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:ds,commitsSinceDispatch:{t:"int"},attributable:ds},cancel:{reason:Et(_5)},operator_status:{status:Et(A5),reason:Et(T5)},coordinator_ack:{notify:Et(Yx),outcome:Et(I5)},hold_expired:{holdId:rr,reason:Et(R5)}},$5=Object.keys(O5);function Oo(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Oo($5);Oo(L5);Oo(Yx);Oo(P5);Oo(E5);function ns(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var F5=["applied","recorded","rejected"];ns(F5);var H5=["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(H5);var B5=["completed","failed"];ns(B5);var W5=["operator_update","refine_terminal","validation_terminal"];ns(W5);var U5=["own","fleet"];ns(U5);var K5=["active","paused","completed","abandoned"];ns(K5);var q5=["provider_quirk","pattern_to_avoid","recovery_lesson"];ns(q5);var z5=["coordinator","unknown"];ns(z5);var V5=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];ns(V5);var G5=["turn_observe","mesh_record","turn_cancel","operator_status","turn_query","mesh_index_query","mission_upsert","mission_query","note_upsert","note_forget","tool_call_record","ledger_query","mission_list_query","record_local","queue_query","queue_enqueue","queue_enqueue_batch","queue_cancel","queue_requeue","direct_dispatch_record","active_work_query","recovery_context_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];ns(G5);var Y5=KD(qD());Y5.default;new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;var Qx="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Uint8Array.from(Qx,e=>e.charCodeAt(0));var Q5=new Uint8Array(256);for(let e=0;e<64;e++)Q5[Qx.charCodeAt(e)]=e;new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;new globalThis.TextDecoder;/*! Bundled license information:
|
|
117
|
+
|
|
118
|
+
@noble/hashes/esm/utils.js:
|
|
119
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
120
|
+
*/const J5=/[^a-z0-9_-]+/g;function X5(e,t){const s=e.toLowerCase().replace(J5,"_").replace(/^_+|_+$/g,"");return s.length>0?s.slice(0,64):t}function Z5(e){return X5(e,"unknown_session")}function eO(e){return`session.${Z5(e)}.chat`}function mp(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 hp(e){const t=new Map;return e.forEach((s,r)=>t.set(s.messageId,r)),t}function nl(e){const t=e.ordered.length;return{...e.meta,coverage:{...e.meta.coverage,totalMessageCount:t,returnedMessageCount:t},messages:e.ordered}}class tO{constructor(){ze(this,"sessions",new Map)}apply(t){if(t.reset){if(!t.meta)return null;const o=[...t.upserts].sort(mp),a={meta:t.meta,byId:new Map(o.map(i=>[i.messageId,i])),ordered:o,indexOf:hp(o)};return this.sessions.set(t.sessionId,a),{sessionId:t.sessionId,view:nl(a),reset:!0}}const s=this.sessions.get(t.sessionId);if(!s)return null;if(s.meta=t.meta??{...s.meta,epoch:t.epoch,frame:t.frame},t.deletes.length===0&&t.upserts.every(o=>{const a=s.byId.get(o.messageId);return a!==void 0&&a.ord===o.ord})){if(t.upserts.length>0){const o=s.ordered.slice();for(const a of t.upserts)s.byId.set(a.messageId,a),o[s.indexOf.get(a.messageId)]=a;s.ordered=o}}else{for(const o of t.deletes)s.byId.delete(o);for(const o of t.upserts)s.byId.set(o.messageId,o);s.ordered=Array.from(s.byId.values()).sort(mp),s.indexOf=hp(s.ordered)}return{sessionId:t.sessionId,view:nl(s),reset:!1}}view(t){const s=this.sessions.get(t);return s?nl(s):null}retain(t){const s=new Set(t);for(const r of[...this.sessions.keys()])s.has(r)||this.sessions.delete(r)}clear(){this.sessions.clear()}}const nO="transcript_topics_available",sO=256;function rO(e){if(!e||typeof e!="object")return null;const t=e;if(t.type!==nO||!Array.isArray(t.topics)||t.topics.length>sO)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 oO(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(eO(o)))}const aO=4096;function iO(e){return typeof e.isOpen=="function"?e.isOpen():e.readyState===1||e.readyState==="open"}function cO(e,t,s={}){const r=s.preOpenQueueCap??aO,o=[];let a=!1;const i=()=>{for(const d of o.splice(0))e.send(d)},l=()=>{var d;o.length=0,a=!0,t.onmessage=null,(d=s.onOverflow)==null||d.call(s,"pre_open_queue_full"),t.postMessage(tl("queue_overflow"))};return t.onmessage=d=>{if(a)return;const u=d.data;typeof u=="string"&&(iO(e)?(o.length>0&&i(),e.send(u)):o.length<r?o.push(u):l())},e.addEventListener("message",d=>{if(a)return;const u=d.data;typeof u=="string"&&t.postMessage(u)}),e.addEventListener("open",()=>{a||(i(),t.postMessage(tl("transport_open")))}),e.addEventListener("close",()=>{a||(a=!0,o.length=0,t.postMessage(tl("transport_closed")))}),{pendingCount(){return o.length},close(){a||(a=!0,o.length=0,t.onmessage=null)}}}function lO(e,t){var u,m,h,p;const s=t.createChannel??(()=>new MessageChannel),r=s(),o=s(),a=t.createWorker();a.postMessage({sessionKey:t.sessionKey,writerId:t.writerId},[r.port2,o.port2]),(m=(u=r.port1).start)==null||m.call(u),(p=(h=o.port1).start)==null||p.call(h);const i=new tO;o.port1.onmessage=b=>{var f,x;if(LD(b.data)){const g=i.apply(b.data);g&&((f=t.onView)==null||f.call(t,g));return}DD(b.data)&&((x=t.onBaseRequest)==null||x.call(t,b.data.sessionId))};let l=cO(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(OD(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 Jx="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Uint8Array.from(Jx,e=>e.charCodeAt(0));const dO=new Uint8Array(256);for(let e=0;e<64;e++)dO[Jx.charCodeAt(e)]=e;new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;new globalThis.TextDecoder;function uO(){if(typeof window>"u"||typeof Worker>"u"||typeof WebSocket>"u")return()=>{};const e=TD(window.location,Gi()),t=new ED({createSocket:()=>new WebSocket(e),startHost:(s,r,o)=>lO(s,{writerId:jD,sessionKey:"transcript",onView:r,onBaseRequest:o,createWorker:()=>new Worker(new URL("/assets/transcript-worker-entry-DW88VYRp.js",import.meta.url),{type:"module"}),onOverflow:()=>console.warn("[Transcript] standalone lane pre-open queue overflow — channel reset")}),collectInterest:E_,subscribeInterest:L_,applyView:(s,r,o)=>M_(s,r,o),requestBase:R_,subscribeTopicsAvailable:PD,selectResubscribe:oO,setTimer:(s,r)=>setTimeout(s,r),clearTimer:s=>clearTimeout(s),now:()=>Date.now(),log:s=>console.warn(s)});return t.start(),()=>t.stop()}function mO(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,s=Gi();return s?`${t}?token=${encodeURIComponent(s)}`:t}const ga=mO(),pp=3e3,hO=3e4;let kn=null,pO=0;const mi=new Map;let Is=null,po=null,fp=null;const fO="standalone_hello";function bO(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Zr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function gO(e){return e==="connected"?"connected":e}async function fo(e,t,s){const r=yg(e,s||{}),o=kn;if(o&&o.readyState===WebSocket.OPEN){const a=`req_${++pO}_${Date.now()}`;return new Promise((i,l)=>{const d=setTimeout(()=>{mi.delete(a),l(new Error(`WS command timeout: ${t}`))},3e4);mi.set(a,{resolve:u=>{clearTimeout(d),i(u)},reject:u=>{clearTimeout(d),l(u)}}),o.send(JSON.stringify({type:"command",requestId:a,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function hi(e,t){const s=kn;if(!s||s.readyState!==WebSocket.OPEN||!MD(t))return!1;try{return s.send(JSON.stringify(t)),!0}catch{return!1}}function Xx(e,t,s){const r=kn;if(!r||r.readyState!==WebSocket.OPEN)return!1;const o=yg(e,{sessionId:t,targetSessionId:t,data:s});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:o.payload}})),!0}catch{return!1}}Ln.registerPtyInputSender(Xx);Ln.registerDataSender((e,t)=>hi(e,t));class xO{constructor(t){ze(this,"daemonId");ze(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(kn==null?void 0:kn.readyState)===WebSocket.OPEN}get connectionState(){return(kn==null?void 0:kn.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,s){return fo(this.daemonId,t,s)}async sendInput(t,s){return fo(this.daemonId,"cdp_remote_action",{action:t,params:s,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Is&&(clearInterval(Is),Is=null);const s=async()=>{if(this.hasCommandChannel)try{const r=await fo(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(r!=null&&r.success&&(r!=null&&r.base64)){const o=await fetch(`data:image/jpeg;base64,${r.base64}`).then(a=>a.blob());Ln.emitScreenshot(this.daemonId,o)}}catch{}};s(),Is=setInterval(s,2e3)}stopScreenshots(t){Is&&(clearInterval(Is),Is=null)}}let xn=null;function yO(e){return(!xn||xn.daemonId!==e)&&(xn=new xO(e)),xn}function vO({children:e}){const t=c.useRef(br()),s=br();t.current=s;const{setUserName:r}=gw(),o=c.useRef(r);o.current=r;const a=c.useRef(null),i=c.useRef(null),[,l]=c.useState("disconnected"),d=c.useCallback((x,g)=>{l(x),po==null||po(x,g)},[]),u=c.useRef(null),m=c.useRef(),h=c.useRef(pp),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 A,k;if(!p.current||((A=u.current)==null?void 0:A.readyState)===WebSocket.OPEN||((k=u.current)==null?void 0:k.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${ga}...`),Zr("connect_attempt",{url:ga,reason:f.current,delayMs:h.current});let S;try{S=new WebSocket(ga)}catch(w){console.error("[Standalone WS] Failed to create WebSocket:",w),g();return}u.current=S,S.onopen=()=>{if(!p.current){S.close();return}d("connected"),h.current=pp,Zr("open",{url:ga,reason:f.current}),Fn.resubscribeAll({sendData:hi}),console.log("[Standalone WS] Connected")},kn=S,S.onmessage=w=>{var y,N;try{const j=JSON.parse(w.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const E=mi.get(j.requestId);E&&(mi.delete(j.requestId),j.type==="error"?E.reject(new Error(((y=j.data)==null?void 0:y.message)||"Command failed")):E.resolve(j.data));return}if(j.type==="session_output"){const E=j.sessionId||j.cliId||j.cliType;E&&Ln.emitSessionOutput(E,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Ln.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated,typeof j.cols=="number"?j.cols:void 0,typeof j.rows=="number"?j.rows:void 0);return}const C=rO(j);if(C){RD(C);return}if(SD(j,fp,nt,P_))return;if(j.type==="topic_update"){const E=j.update;E&&Fn.publish(E);return}if(j.type===fO&&typeof j.daemonId=="string"&&j.daemonId){const E=j.daemonId;fp=E,Rl(E,typeof j.wireVersion=="number"?j.wireVersion:null);const P=yO(E);Ln.register(E,P),Ln.setState(E,"connected"),d("connected",E),i.current!==E&&((N=a.current)==null||N.call(a),i.current=E,a.current=Fn.subscribe({sendData:hi},E,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${E}`,params:{includeSessions:!0}},T=>{const M=t.current.getIdes(),_=M.find(D=>D.id===E),I=pb(T.status,{daemonId:E,existingDaemon:_,existingEntries:M,timestamp:T.timestamp});bO("metadata",{daemonId:E,seq:T.seq,sessions:(T.status.sessions||[]).map(D=>({id:D.id,providerType:D.providerType,status:D.status,unread:D.unread,inboxBucket:D.inboxBucket}))}),I.length>0&&t.current.injectEntries(I,{authoritativeDaemonIds:[E]}),t.current.markLoaded(),T.userName&&o.current&&o.current(T.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},S.onclose=w=>{p.current&&(xn==null||xn.stopScreenshots(),xn&&Ln.setState(xn.daemonId,"disconnected"),d("disconnected"),u.current=null,f.current=`close:${w.code}${w.wasClean?":clean":":unclean"}`,Zr("close",{code:w.code,reason:w.reason||"",wasClean:w.wasClean}),g())},S.onerror=w=>{b.current||!p.current||(f.current="error",Zr("error",{message:w instanceof Event?"event":String(w),readyState:S.readyState}),console.warn("[Standalone WS] Error, will reconnect:",w))}}function g(){if(!p.current)return;clearTimeout(m.current);const S=h.current;console.log(`[Standalone WS] Reconnecting in ${S}ms...`),Zr("schedule_reconnect",{reason:f.current,delayMs:S}),m.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,hO),x()},S)}x();const v=uO();return()=>{var S;v(),p.current=!1,b.current=!0,(S=a.current)==null||S.call(a),a.current=null,i.current=null,clearTimeout(m.current),u.current&&(u.current.onerror=null,u.current.onclose=null,u.current.close(),u.current=null,kn=null),xn&&(xn.stopScreenshots(),Ln.unregister(xn.daemonId))}},[]),n.jsx(n.Fragment,{children:e})}function wO({children:e}){const[t,s]=c.useState("disconnected"),[r,o]=c.useState(null);c.useEffect(()=>(po=(i,l)=>{s(i),l&&o(l)},()=>{po=null}),[]);const a=c.useMemo(()=>{const i=t==="connected",l=gO(t),d={};return r&&(d[r]=l),d.standalone=l,{wsStatus:t,isConnected:i,connectionStates:d,usesP2P:!1}},[t,r]);return n.jsx(bw,{connectionOverrides:a,children:n.jsx(vO,{children:e})})}const Zx="adhdev_standalone_font_preferences",Bs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Yi=[{id:"default",label:"Default",labelKey:"standalone.fonts.presets.default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",labelKey:null,family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",labelKey:null,family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",labelKey:null,family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",labelKey:null,family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",labelKey:"standalone.fonts.presets.serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",labelKey:"standalone.fonts.presets.custom",family:"",description:"Enter any CSS font-family stack"}],jo=[{id:"default",label:"Default mono",labelKey:"standalone.fonts.presets.defaultMono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", "D2Coding", "Noto Sans Mono CJK KR", "Apple SD Gothic Neo", "Malgun Gothic", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",labelKey:null,family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",labelKey:null,family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",labelKey:null,family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",labelKey:null,family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",labelKey:"standalone.fonts.presets.custom",family:"",description:"Enter any CSS monospace stack"}],SO=new Set(Yi.map(e=>e.id)),kO=new Set(jo.map(e=>e.id));function Dn(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Ea("chat",t.chat),code:Ea("code",t.code),terminal:Ea("terminal",t.terminal)}}function Ea(e,t){const s=Bs[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},o=typeof r.preset=="string"?r.preset.trim():"",a=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?SO:kO).has(o)?o==="custom"?a?{preset:"custom",customFamily:a}:s:{preset:o}:s}function La(e,t){var o;const s=Ea(e,t);if(s.preset==="custom"&&s.customFamily)return s.customFamily;const r=e==="chat"?Yi:jo;return((o=r.find(a=>a.id===s.preset))==null?void 0:o.family)||r[0].family}function jO(e){const t=Dn(e),s=La("chat",t.chat),r=La("code",t.code),o=La("terminal",t.terminal);return{"--chat-font-family":s,"--chat-code-font-family":r,"--chat-terminal-font-family":o,"--chat-tool-font-family":o}}function Ps(e,t=document.documentElement){const s=Dn(e),r=jO(s);t.setAttribute("data-standalone-fonts","custom");for(const[o,a]of Object.entries(r))t.style.setProperty(o,a);return s}function id(e){const t=Dn(e);try{localStorage.setItem(Zx,JSON.stringify(t))}catch{}return t}function NO(){try{const e=localStorage.getItem(Zx);if(e)return Dn(JSON.parse(e))}catch{}return Bs}function CO(){return Ps(NO())}function eo(e,t,s){const r=e==="chat"?Yi:jo,o=r.find(a=>a.id===t)||r[0];return o.labelKey&&s?s(o.labelKey,o.label):o.label}function _O({children:e}){const t=Vs(),s=pi(),{t:r}=he("common"),o=c.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:n.jsx(Hp,{}),label:r("nav.dashboard"),active:s.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:n.jsx(gr,{}),label:r("nav.machines"),active:s.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:n.jsx(On,{}),label:r("nav.mesh"),active:s.pathname.startsWith("/mesh")||s.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"notifications",path:"/notifications",icon:n.jsx(Jn,{}),label:r("nav.notifications"),active:s.pathname.startsWith("/notifications"),onSelect:()=>t("/notifications")},{id:"settings",path:"/settings",icon:n.jsx(_r,{}),label:r("nav.settings"),active:s.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[s.pathname,t,r]),a=c.useMemo(()=>[{id:"docs",label:n.jsxs(n.Fragment,{children:[n.jsx("span",{children:r("nav.docs")}),n.jsx("span",{className:"ml-auto text-4xs text-text-muted",children:"↗"})]}),icon:n.jsx(hd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("nav.docs")},{id:"about",label:r("nav.about"),icon:n.jsx(Co,{}),active:s.pathname==="/about",onSelect:()=>t("/about"),title:r("nav.about")}],[s.pathname,t,r]);return n.jsx(GT,{brand:({collapsed:i})=>n.jsxs(n.Fragment,{children:[n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&n.jsx("span",{children:"ADHDev"})]}),navItems:o,footerItems:a,footerInfo:({collapsed:i})=>i?null:n.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.75"]}),footerActions:({collapsed:i,toggleCollapsed:l})=>n.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:l,title:r(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[n.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&n.jsx("span",{className:"text-xs",children:r("standalone.layout.collapse")})]}),children:e})}function AO(){const e=Vs(),{sendCommand:t}=wt(),{ides:s}=yn(),r=c.useMemo(()=>s.filter(o=>o.daemonMode||o.type==="adhdev-daemon").map(o=>o),[s]);return n.jsx(yD,{daemons:r,features:Ax,sendCommand:t,unwrapResult:o=>o,normalizeMesh:o=>o,onClose:()=>e("/mesh")})}const TO=[{icon:n.jsx(gr,{size:16}),key:"localFirst"},{icon:n.jsx(Cn,{size:16}),key:"chatRelay"},{icon:n.jsx(pd,{size:16}),key:"screenshots"},{icon:n.jsx(Bn,{size:16}),key:"remoteControl"},{icon:n.jsx(xr,{size:16}),key:"multiIde"},{icon:n.jsx(hd,{size:16}),key:"cli"}],IO=[{icon:n.jsx(yi,{size:16}),key:"anywhere"},{icon:n.jsx(Hp,{size:16}),key:"p2pStream"},{icon:n.jsx(Jn,{size:16}),key:"mobileNotifications"},{icon:n.jsx(_w,{size:16}),key:"restApi"},{icon:n.jsx(Tw,{size:16}),key:"enterpriseControls"}],MO=[{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 RO(){const{t:e}=he("common");return n.jsxs(Lo,{icon:n.jsx(Co,{className:"text-text-primary"}),title:e("standalone.about.title"),subtitle:e("standalone.about.subtitle"),widthClassName:"max-w-5xl",actions:n.jsxs("div",{className:"px-3 py-1 text-2xs font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","1.0.75"]}),children:[n.jsx(vt,{children:n.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[n.jsxs("div",{className:"max-w-2xl",children:[n.jsx("div",{className:"text-2xs font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),n.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),n.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),n.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[n.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),n.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),n.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),n.jsx(vt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:n.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:TO.map(t=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[n.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[n.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),e("standalone.about.features."+t.key+".title")]}),n.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.features."+t.key+".desc")})]},t.key))})}),n.jsx(vt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:n.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:PT.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:LT.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:ET.map(t=>`${t.icon} ${t.name}`)}].map(t=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[n.jsx("div",{className:"text-2xs font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),n.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(s=>n.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-xs text-text-secondary",children:s},s))})]},t.label))})}),n.jsx(vt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:n.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:IO.map(t=>n.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[n.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[n.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),e("standalone.about.extras."+t.key+".title")]}),n.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.extras."+t.key+".desc")})]},t.key))})}),n.jsx(vt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:n.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:n.jsxs("table",{className:"w-full text-xxs",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"bg-bg-secondary",children:[n.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-2xs uppercase tracking-wider",children:e("standalone.about.featureHeader")}),n.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-2xs uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),n.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-2xs uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),n.jsx("tbody",{children:MO.map((t,s)=>n.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[n.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e("standalone.about.comparison."+t.key)}),n.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?n.jsx("span",{className:"text-emerald-500",children:"✓"}):n.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),n.jsx("td",{className:"px-4 py-2.5 text-center",children:n.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.key))})]})})}),n.jsx(Bi,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:n.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[n.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),n.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[n.jsx(Ow,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function sl(e,t,s){return{...e,[t]:s}}function rl({surface:e,title:t,description:s,value:r,options:o,onChange:a}){const{t:i}=he("common");return n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[n.jsxs("div",{className:"flex items-center gap-1 text-sm font-medium text-text-primary",children:[t,n.jsx(rt,{content:s,size:12})]}),n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(XT,{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:La(e,r)})]})]})]})}function PO({value:e,savedValue:t,saving:s=!1,error:r,notice:o,onChange:a,onSave:i,onResetToSaved:l,onResetToDefaults:d}){const{t:u}=he("common"),m=JSON.stringify(e)!==JSON.stringify(t);return n.jsxs("div",{className:"flex flex-col gap-4",children:[r&&n.jsx(Bt,{variant:"error",children:r}),o&&n.jsx(Bt,{variant:"success",children:o}),n.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[n.jsx(rl,{surface:"chat",title:u("standalone.fonts.chat"),description:u("standalone.fonts.chatDescription"),value:e.chat,options:Yi,onChange:h=>a(sl(e,"chat",h))}),n.jsx(rl,{surface:"code",title:u("standalone.fonts.code"),description:u("standalone.fonts.codeDescription"),value:e.code,options:jo,onChange:h=>a(sl(e,"code",h))}),n.jsx(rl,{surface:"terminal",title:u("standalone.fonts.terminal"),description:u("standalone.fonts.terminalDescription"),value:e.terminal,options:jo,onChange:h=>a(sl(e,"terminal",h))})]}),n.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[n.jsx("div",{className:"flex items-center justify-between gap-3",children:n.jsxs("div",{className:"flex items-center gap-1 text-sm font-medium text-text-primary",children:[u("standalone.fonts.livePreview"),n.jsx(rt,{size:12,content:[u("standalone.fonts.previewSummary",{chat:eo("chat",e.chat.preset,u),code:eo("code",e.code.preset,u),terminal:eo("terminal",e.terminal.preset,u)}),u("standalone.fonts.defaultsSummary",{chat:eo("chat",Bs.chat.preset,u),code:eo("code",Bs.code.preset,u)}),u("standalone.fonts.fontOverridesNotice")].join(`
|
|
121
|
+
|
|
122
|
+
`)})]})}),n.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:n.jsxs("div",{className:"chat-container-content",children:[n.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:n.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[n.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[n.jsx("span",{className:"chat-sender",children:"Claude"}),n.jsx("span",{className:"chat-time",children:u("standalone.fonts.previewNow")})]}),n.jsxs("div",{className:"chat-markdown",children:[n.jsx("p",{children:n.jsx(Da,{i18nKey:"standalone.fonts.previewProse",ns:"common",components:{strong:n.jsx("strong",{}),code:n.jsx("code",{})}})}),n.jsx("pre",{children:n.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),n.jsxs("div",{className:"chat-msg-tool",children:[n.jsx("span",{className:"tool-icon",children:"▸"}),n.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),n.jsxs("div",{className:"chat-msg-terminal",children:[n.jsx("div",{className:"chat-msg-header",children:u("standalone.fonts.terminal")}),n.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx(Qn,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:s||!m,children:u(s?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),n.jsx(Qn,{type:"button",variant:"secondary",size:"sm",onClick:l,disabled:s||!m,children:u("standalone.fonts.revertToSaved")}),n.jsx(Qn,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:s,children:u("standalone.fonts.resetToDefaults")})]})]})}function EO(){const{t:e}=he("common"),{ides:t}=yn(),s=t.find(U=>U.type==="adhdev-daemon"),{sendCommand:r}=wt(),{userName:o}=yn(),[a,i]=c.useState(o||""),[l,d]=c.useState(null),[u,m]=c.useState(null),[h,p]=c.useState(Bs),[b,f]=c.useState(!1),[x,g]=c.useState(""),[v,S]=c.useState(""),[A,k]=c.useState("127.0.0.1"),[w,y]=c.useState(""),[N,j]=c.useState(""),[C,E]=c.useState(""),[P,T]=c.useState(""),[M,_]=c.useState(""),[I,D]=c.useState(!1),L=async()=>{const K=await(await En("/auth/session")).json();d(K)},$=async()=>{const K=await(await En("/api/v1/standalone/preferences")).json();m(K),k(K.standaloneBindHost);const oe=Dn(K.standaloneFontPreferences);p(oe),Ps(oe),id(oe)};c.useEffect(()=>{o!==void 0&&i(o)},[o]),c.useEffect(()=>{Promise.all([L(),$()]).catch(U=>{T(U instanceof Error?U.message:String(U))})},[]),c.useEffect(()=>{Ps(h)},[h]);const q=U=>{const K=U.target.value.trim();s!=null&&s.id&&K!==o&&r(s.id,"set_user_name",{userName:K}).catch(console.error)},G=async()=>{g(""),S(""),f(!0);try{const U=Dn(h),K=await En("/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 ge=Dn(oe.standaloneFontPreferences);m(oe),p(ge),Ps(ge),id(ge),S(e("standalone.settings.fontsSaved"))}catch(U){g(U instanceof Error?U.message:String(U))}finally{f(!1)}},W=()=>{const U=Dn(u==null?void 0:u.standaloneFontPreferences);g(""),S(""),p(U),Ps(U)},R=()=>{g(""),S(""),p(Bs),Ps(Bs)},O=async()=>{T(""),_(""),D(!0);try{const U=await En("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:A})}),K=await U.json();if(!U.ok)throw new Error((K==null?void 0:K.error)||"Failed to save standalone network preference");m(K),k(K.standaloneBindHost),_(K.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(U){T(U instanceof Error?U.message:String(U))}finally{D(!1)}},B=async()=>{if(T(""),_(""),N.trim().length<4){T(e("standalone.settings.passwordTooShort"));return}if(N!==C){T(e("standalone.settings.passwordMismatch"));return}D(!0);try{const U=await En("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:N})}),K=await U.json();if(!U.ok)throw new Error((K==null?void 0:K.error)||"Failed to save password");d(K),await $(),y(""),j(""),E(""),_(l!=null&&l.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),Bx()}catch(U){T(U instanceof Error?U.message:String(U))}finally{D(!1)}},H=async()=>{T(""),_(""),D(!0);try{const U=await En("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,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 $(),y(""),j(""),E(""),_(e("standalone.settings.passwordDisabled"))}catch(U){T(U instanceof Error?U.message:String(U))}finally{D(!1)}};return n.jsxs(Lo,{icon:n.jsx(_r,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[(l==null?void 0:l.publicHostWarning)&&n.jsx(Bt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),n.jsx(vt,{title:e("standalone.settings.daemonSection"),children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[n.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.versionLabel")}),n.jsxs("span",{className:"font-mono text-xs text-text-primary",children:["v","1.0.75"]})]}),n.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[n.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.statusLabel")}),n.jsx("span",{className:`text-xs font-medium ${s?"text-green-400":"text-yellow-400"}`,children:e(s?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")})]}),n.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[n.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.authLabel")}),n.jsx("span",{className:"text-xs text-text-primary",children:l!=null&&l.hasPasswordAuth?e("standalone.settings.authPassword"):l!=null&&l.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]}),(s==null?void 0:s.id)&&n.jsxs("div",{className:"px-1 pt-1 text-xs text-text-muted","data-testid":"standalone-providers-link",children:[e("standalone.settings.providersIntro")," ",n.jsx(xp,{to:`/machines/${s.id}`,state:{initialMachineTab:"providers"},className:"text-accent-primary hover:underline",children:e("standalone.settings.providersLink")})]})]})}),n.jsx(vt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkHint"),children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsx("div",{className:"grid gap-3 md:grid-cols-2",role:"radiogroup","aria-label":e("standalone.settings.networkSection"),children:[{host:"127.0.0.1",label:e("standalone.settings.localhostLabel"),hint:e("standalone.settings.localhostHint")},{host:"0.0.0.0",label:e("standalone.settings.allInterfacesLabel"),hint:e("standalone.settings.allInterfacesHint")}].map(U=>n.jsxs("label",{className:`rounded-xl border px-4 py-3 text-sm flex gap-3 items-center cursor-pointer ${A===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:A===U.host,onChange:()=>k(U.host)}),n.jsx("span",{className:"font-medium text-text-primary",children:U.label}),n.jsx(rt,{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:()=>{O()},disabled:I,children:e(I?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),(u==null?void 0:u.standaloneBindHost)&&(u.currentBindHost||(l==null?void 0:l.boundHost))&&u.standaloneBindHost!==(u.currentBindHost||(l==null?void 0:l.boundHost))&&n.jsx(Qt,{content:e("standalone.settings.networkRestartHint",{host:u.currentBindHost||(l==null?void 0:l.boundHost)||"127.0.0.1"}),children:n.jsx("span",{className:"inline-flex items-center rounded-full border border-amber-500/25 bg-amber-500/10 px-2 py-0.5 text-3xs font-semibold text-amber-400","data-testid":"standalone-restart-chip",children:e("standalone.settings.restartToApply")})})]})]})}),n.jsx(vt,{title:e("standalone.settings.securitySection"),children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),P&&n.jsx(Bt,{variant:"error",children:P}),M&&n.jsx(Bt,{variant:"success",children:M}),n.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[n.jsx(Nn,{type:"password",placeholder:l!=null&&l.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:w,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:N,onChange:U=>j(U.target.value)}),n.jsx(Nn,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:C,onChange:U=>E(U.target.value)})]}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsx(Qn,{type:"button",variant:"primary",size:"sm",onClick:()=>{B()},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:()=>{H()},disabled:I,children:e("standalone.settings.disablePassword")})]})]})}),n.jsx(vt,{title:e("standalone.settings.appearanceSection"),children:n.jsx(j2,{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(rt,{content:e("standalone.settings.fontsDescription"),size:12})]}),n.jsx(PO,{value:h,savedValue:Dn(u==null?void 0:u.standaloneFontPreferences),saving:b,error:x,notice:v,onChange:p,onSave:()=>{G()},onResetToSaved:W,onResetToDefaults:R})]})})}),n.jsx(vt,{title:e("standalone.settings.profileSection"),children:n.jsx("div",{className:"flex flex-col gap-3",children:n.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[n.jsx("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:n.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[n.jsx(Cw,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel"),n.jsx(rt,{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:q,onKeyDown:U=>{U.key==="Enter"&&U.currentTarget.blur()}})]})})}),n.jsxs(vt,{title:e("settings.advancedTitle"),collapsible:!0,defaultOpen:!1,children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1 text-xs font-medium text-text-secondary",children:[e("settings.coordinatorPrompts.sectionTitle"),n.jsx(rt,{content:e("settings.coordinatorPrompts.sectionDescription"),size:12})]}),n.jsx(l2,{daemonId:s==null?void 0:s.id,embedded:!0})]})]})}const LO=["claude-cli","codex-cli","antigravity-cli"],oo="adhdev_onboarding_done",DO=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"}],OO={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions"};function $O({onDone:e}){const{t}=he("common"),[s,r]=c.useState([]),[o,a]=c.useState(new Set(LO)),[i,l]=c.useState(!0),[d,u]=c.useState(null),[m,h]=c.useState(!1),[p,b]=c.useState(null),[f,x]=c.useState("all");c.useEffect(()=>{let y=!1;return fetch("/api/v1/providers/catalog?sort=popular&limit=100").then(async N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);const j=await N.text();try{return JSON.parse(j)}catch{throw new Error(`unexpected non-JSON response (${N.headers.get("content-type")??"unknown content type"})`)}}).then(N=>{y||r(N.providers??[])}).catch(N=>{y||u(N instanceof Error?N.message:String(N))}).finally(()=>{y||l(!1)}),()=>{y=!0}},[]);const g=s.filter(y=>f==="all"||y.category===f),v=["cli","ide","extension"].map(y=>({category:y,items:g.filter(N=>N.category===y)})).filter(y=>y.items.length>0),S=c.useCallback(y=>{a(N=>{const j=new Set(N);return j.has(y)?j.delete(y):j.add(y),j})},[]),A=c.useCallback(async()=>{if(o.size===0){localStorage.setItem(oo,"1"),e();return}h(!0);const y=[];for(const N of o)try{const C=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:N})})).json().catch(()=>({}));y.push({type:N,ok:!!C.success,error:C.error})}catch(j){y.push({type:N,ok:!1,error:j instanceof Error?j.message:String(j)})}b(y),h(!1),y.every(N=>N.ok)&&localStorage.setItem(oo,"1")},[o,e]),k=c.useCallback(()=>{localStorage.setItem(oo,"1"),e()},[e]),w=c.useCallback(()=>{p&&p.every(y=>y.ok)?e():m||k()},[p,m,e,k]);return n.jsx(ag,{open:!0,onClose:w,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:m,children:t("standalone.onboarding.skip")}),n.jsx(Qn,{variant:"primary",size:"sm",onClick:()=>{p?(localStorage.setItem(oo,"1"),e()):A()},disabled:m||!p&&o.size===0,children:m?t("standalone.onboarding.installing"):p?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:o.size})})]})]}),children:n.jsxs("div",{className:"flex flex-col gap-5",children:[n.jsx("div",{className:"text-xs text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&s.length>0&&n.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:DO.map(y=>{const N=y.key==="all"?s.length:s.filter(j=>j.category===y.key).length;return N===0&&y.key!=="all"?null:n.jsxs("button",{onClick:()=>x(y.key),className:`machine-btn text-3xs px-2 py-0.5 ${f===y.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[y.label," ",n.jsxs("span",{className:"opacity-60",children:["(",N,")"]})]},y.key)})}),i&&n.jsx("div",{className:"text-text-muted text-xs py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&n.jsx(Bt,{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:v.map(y=>n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:OO[y.category]??y.category}),n.jsx("div",{className:"grid gap-1.5",children:y.items.map(N=>{var P;const j=o.has(N.type),C=p==null?void 0:p.find(T=>T.type===N.type),E=((P=N.manifest)==null?void 0:P.details)??"";return n.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${j?"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:j,onChange:()=>S(N.type),disabled:m,className:"shrink-0"}),n.jsx(Fi,{type:N.type,label:N.displayName??N.type,size:18,className:"shrink-0"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-xxs font-medium text-text-primary truncate",children:N.displayName}),E&&n.jsx("div",{className:"text-3xs text-text-muted truncate",children:E})]}),C&&n.jsx("span",{className:`text-3xs font-semibold ${C.ok?"text-status-online":"text-status-error"}`,children:C.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:C.error??"failed"})})]},N.type)})})]},y.category))})]})})}function FO(){try{return localStorage.getItem(oo)==="1"}catch{return!1}}const HO="/dashboard";function BO(e,t){const s=typeof t=="string"?t.trim():"";return{suppressed:e.startsWith(HO),sessionId:s||null}}OT();g2();Mf();CO();const WO=Gw({baseUrl:"",getToken:Gi});function UO({children:e}){const{t}=he("common"),[s,r]=c.useState(null),[o,a]=c.useState(!0),[i,l]=c.useState(""),[d,u]=c.useState(""),[m,h]=c.useState(!1),p=async()=>{a(!0),u("");try{const g=await En("/auth/session");if(!g.ok)throw new Error(`HTTP ${g.status}`);const v=await g.json();r(v)}catch(g){u(g instanceof Error?g.message:String(g))}finally{a(!1)}},[b,f]=c.useState(0);c.useEffect(()=>{p()},[]),c.useEffect(()=>{if(!d||s)return;const g=Math.min(5e3,500*2**b),v=window.setTimeout(()=>{f(S=>S+1),p()},g);return()=>window.clearTimeout(v)},[d,s,b]),c.useEffect(()=>{s&&f(0)},[s]),c.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let g=!1;return(async()=>{try{const v=await En("/api/v1/standalone/preferences");if(!v.ok)return;const S=await v.json();if(g)return;const A=Dn(S.standaloneFontPreferences);Ps(A),id(A)}catch{}})(),()=>{g=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const x=async g=>{g.preventDefault(),h(!0),u("");try{const v=await En("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),S=await v.json();if(!v.ok)throw new Error((S==null?void 0:S.error)||"Login failed");r(S),l(""),Bx()}catch(v){u(v instanceof Error?v.message:String(v))}finally{h(!1)}};return o||!s&&b<3?n.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):s?!s.required||s.authenticated?n.jsx(n.Fragment,{children:e}):n.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:n.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),n.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),s.hasPasswordAuth?n.jsxs("form",{className:"flex flex-col gap-3",onSubmit:x,children:[n.jsx(Nn,{type:"password",value:i,onChange:g=>l(g.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),n.jsx(Qn,{type:"submit",variant:"primary",disabled:m||!i,className:"justify-center",children:t(m?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):n.jsx(Bt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&n.jsx(Bt,{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 KO(){const{ides:e,initialLoaded:t}=yn(),s=e.filter(r=>r.type==="adhdev-daemon").map(r=>({id:r.id,machineId:r.machineId||r.id,nickname:Lf(r)||void 0,hostname:Ad(r,{fallbackId:r.id}),status:r.status,providers:(r.availableProviders||[]).map(o=>({type:o.type,displayName:o.displayName,icon:o.icon,category:o.category}))}));return n.jsx(VE,{machines:s,initialLoaded:t??!0})}function bp(){const{t:e}=he("common"),{ides:t,initialLoaded:s}=yn();if(!s)return n.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(o=>o.daemonMode||o.type==="adhdev-daemon");return r?n.jsx(il,{to:`/machines/${r.id}`,replace:!0}):n.jsx(il,{to:"/dashboard",replace:!0})}function qO(){const[e,t]=c.useState(!1);return c.useEffect(()=>{let s=!1;if(!FO())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{s||(r.providers??[]).length===0&&(window.dispatchEvent(new Event(Yl)),t(!0))}).catch(()=>{}),()=>{s=!0}},[]),e?n.jsx($O,{onDone:()=>t(!1)}):null}function zO(){const{t:e}=he("common"),t=pi(),[s]=gp(),{suppressed:r,sessionId:o}=BO(t.pathname,s.get("activeTab")),{promptSession:a,hasActivePrompt:i,responseError:l,isSubmitting:d,submit:u,cancel:m,reopen:h}=Ci(o);return r||!i?null:n.jsxs("div",{className:"relative",children:[!a&&n.jsx("button",{type:"button",onClick:h,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),n.jsx(Nd,{promptSession:a,isSubmitting:d,error:l,onSubmit:u,onCancel:m})]})}function VO(){const e=c.useMemo(()=>({sendCommand:fo,sendData:hi,sendPtyInput:Xx}),[]);return n.jsx(my,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:n.jsx(vw,{client:WO,children:n.jsx(UO,{children:n.jsx(wO,{children:n.jsx(Sw,{value:e,children:n.jsxs(Vw,{sendDaemonCommand:fo,children:[n.jsx(zO,{}),n.jsx(F1,{}),n.jsxs(_O,{children:[n.jsx(qO,{}),n.jsxs(hy,{children:[n.jsx(Pn,{path:"/dashboard",element:n.jsx(xP,{})}),n.jsx(Pn,{path:"/machine",element:n.jsx(bp,{})}),n.jsx(Pn,{path:"/machines/:id",element:n.jsx(BE,{})}),n.jsx(Pn,{path:"/machines",element:n.jsx(bp,{})}),n.jsx(Pn,{path:"/notifications",element:n.jsx(KO,{})}),n.jsx(Pn,{path:"/about",element:n.jsx(RO,{})}),n.jsx(Pn,{path:"/settings",element:n.jsx(EO,{})}),n.jsx(Pn,{path:"/mesh",element:n.jsx(fD,{children:n.jsx(hD,{})})}),n.jsx(Pn,{path:"/setup",element:n.jsx(AO,{})}),n.jsx(Pn,{path:"*",element:n.jsx(il,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}iC({connectionManager:Ln});function GO(){return n.jsx(N2,{fallback:n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",background:"var(--bg-primary)"},children:n.jsx(nn,{})}),children:n.jsx(VO,{})})}py(document.getElementById("root")).render(n.jsx(ZT,{children:n.jsx(GO,{})}));export{a2 as $,Ud as A,Xr as B,h3 as C,jg as D,b3 as E,Wd as F,nh as G,m3 as H,tn as I,M3 as J,_3 as K,JO as L,C3 as M,Ha as N,C0 as O,Un as P,$x as Q,Hd as R,f3 as S,Qt as T,bf as U,Yd as V,Qn as W,Nn as X,Ay as Y,gw as Z,n2 as _,yr as a,Ar as a0,Lt as a1,XO as a2,N3 as a3,j3 as a4,o3 as a5,g3 as a6,k3 as a7,n3 as a8,w3 as a9,y3 as aa,nt as ab,v3 as ac,qp as ad,e3 as ae,S3 as af,x3 as ag,I3 as ah,i3 as ai,Hp as aj,Iw as ak,On as al,Bd as am,wt as an,R3 as ao,tL as ap,To as aq,Sr as ar,kt as as,fi as at,Nx as au,Cx as av,eL as aw,ZE as ax,Zu as b,t3 as c,Fa as d,d3 as e,u3 as f,Ox as g,OA as h,wl as i,ZO as j,Si as k,c3 as l,A3 as m,p3 as n,T3 as o,ki as p,Vi as q,tg as r,l3 as s,r3 as t,Hi as u,rt as v,s3 as w,kr as x,cl as y,a3 as z};
|