@adhdev/daemon-standalone 1.0.60-rc.63 → 1.0.60-rc.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +4 -4
- package/package.json +2 -2
- package/public/assets/{DashboardMeshGraphDialog-DtFpO2PQ.js → DashboardMeshGraphDialog-zKlWvAFM.js} +1 -1
- package/public/assets/common-CMA7YhWW.js +1 -0
- package/public/assets/common-Cw-N7oC7.js +1 -0
- package/public/assets/common-DMhfgNQ0.js +1 -0
- package/public/assets/common-d2kkUuhU.js +1 -0
- package/public/assets/index-BfRUbeFT.js +115 -0
- package/public/assets/index-CKh2UwjR.css +1 -0
- package/public/index.html +2 -2
- package/vendor/mcp-server/index.js +1 -1
- package/public/assets/common-BPFzWFQt.js +0 -1
- package/public/assets/common-D3xpMHz6.js +0 -1
- package/public/assets/common-D8_bJv3R.js +0 -1
- package/public/assets/common-DepW94Rn.js +0 -1
- package/public/assets/index-BYZgs8N1.js +0 -115
- package/public/assets/index-CpFTgx9d.css +0 -1
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-COe_yvHR.js","assets/vendor-CgFxQ3Rd.js","assets/terminal-6GBZ9nXN.css","assets/DashboardMeshGraphDialog-DtFpO2PQ.js","assets/mesh-graph-7mv6fb91.js","assets/DashboardMeshGraphDialog-Cf4jCsgG.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var Ix=Object.defineProperty;var Mx=(e,t,s)=>t in e?Ix(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var qe=(e,t,s)=>Mx(e,typeof t!="symbol"?t+"":t,s);import{r as l,j as n,u as ve,i as at,M as Yc,b as Rx,d as Px,e as Lx,t as Ex,f as Dx,a as Qn,h as Ox,R as It,T as $a,k as rr,l as zl,m as Gl,D as Fx,n as ui,o as cp,p as $x,q as Hx,L as dp,B as Bx,v as Wx,w as Un,N as Vl,x as Ux}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 Kx(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),s=[];return{record(r){const o={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...r,payload:r.payload?{...r.payload}:{}};return s.push(o),s.length>t&&s.splice(0,s.length-t),o},list(r={}){const o=Math.max(1,Math.floor(r.limit||100));return s.filter(a=>!r.interactionId||a.interactionId===r.interactionId).filter(a=>!r.topic||a.topic===r.topic).filter(a=>!r.kind||a.kind===r.kind).slice(-o).map(a=>({...a,payload:a.payload?{...a.payload}:{}}))},clear(){s.splice(0,s.length)}}}const Xs=Kx();function du(e){const t={};for(const s of e)s.transport&&(t[s.transport]=(t[s.transport]||0)+1);return{count:e.length,ids:e.map(s=>s.id),statuses:e.map(s=>String(s.status||"unknown")),transports:t}}function qx(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function uu(e){return Array.isArray(e)?[...e]:[]}function up(e,t){if(!e)return t??null;const s=Object.prototype.hasOwnProperty.call(e,"messages"),r=Object.prototype.hasOwnProperty.call(e,"activeModal"),o=typeof e.id=="string"?e.id.trim():"",a=typeof(t==null?void 0:t.id)=="string"?t.id.trim():"",i=!!o&&!!a&&o!==a;return t?{...t,...e,messages:s?uu(e.messages):i?[]:t.messages,activeModal:r?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...s?{messages:uu(e.messages)}:{},...r?{activeModal:e.activeModal??null}:{}}}function io(e,t){const s=qx(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:up(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 mp(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?io(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 ft(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ae(...e){for(const t of e){if(typeof t!="string")continue;const s=t.trim();if(s)return s}}function xn(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Qt(...e){for(const t of e)if(typeof t=="boolean")return t}function Qi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function zx(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 Qc(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 Gx(e,t){if(!Array.isArray(e))return;const s=e.map(r=>{const o=ft(r),a=Ae(o.path),i=Ae(o.commit),c=Ae(o.repoPath,o.repo_root)??zx(t,a);if(!a||!i)return null;const d={path:a,commit:i,dirty:Qt(o.dirty)??!1,outOfSync:Qt(o.outOfSync,o.out_of_sync)??!1},u=xn(o.lastCheckedAt,o.last_checked_at);u!==void 0&&(d.lastCheckedAt=u),c&&(d.repoPath=c);const m=Ae(o.error);return m&&(d.error=m),d}).filter(r=>r!==null);return s.length>0?s:void 0}function Vx(e){return Qt(e.isGitRepo)!==void 0||!!Ae(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!Ae(e.repoRoot,e.repo_root,e.workspace)||xn(e.ahead,e.behind,e.staged,e.modified,e.untracked,e.deleted,e.renamed,e.lastCheckedAt,e.last_checked_at)!==void 0||Array.isArray(e.submodules)&&e.submodules.length>0}function ka(e,t,s){const r=Qt(e.isGitRepo);if(!Object.keys(e).length||!Vx(e))return;const o=r??!0,a=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(C=>typeof C=="string"):[],i=xn(e.conflicts)??a.length,c=Qt(e.hasConflicts)??i>0,d=Ae(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,u=Gx(e.submodules,d),m=Ae(e.upstreamStatus,e.upstream_status),h=xn(e.upstreamFetchedAt,e.upstream_fetched_at),p=Ae(e.upstreamFetchError,e.upstream_fetch_error),g=Ae(e.error),f=xn(e.staged)??0,y=xn(e.modified)??0,b=xn(e.untracked)??0,k=xn(e.deleted)??0,j=xn(e.renamed)??0,v=xn(e.lastCheckedAt,e.last_checked_at);return{workspace:Ae(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:o,branch:Ae(e.branch)??null,headCommit:Ae(e.headCommit)??null,headMessage:Ae(e.headMessage)??null,upstream:Ae(e.upstream)??null,upstreamStatus:m??"unchecked",...h!==void 0?{upstreamFetchedAt:h}:{},...p?{upstreamFetchError:p}:{},ahead:xn(e.ahead)??0,behind:xn(e.behind)??0,staged:f,modified:y,untracked:b,deleted:k,renamed:j,dirty:Qt(e.dirty,e.isDirty,e.is_dirty)??(f+y+b+k+j>0||c),hasConflicts:c,conflictFiles:a,stashCount:xn(e.stashCount,e.stash_count)??0,...v!==void 0?{lastCheckedAt:v}:{},...u?{submodules:u}:{},...e.daemonBuildBehind&&typeof e.daemonBuildBehind=="object"?{daemonBuildBehind:e.daemonBuildBehind}:{},...g?{error:g}:{}}}function Yx(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+=Qc(e.upstreamStatus),typeof e.ahead=="number"&&(t+=2),typeof e.behind=="number"&&(t+=2),Array.isArray(e.submodules)&&e.submodules.length>0&&(t+=4+e.submodules.length),e.error&&(t-=20),t}function Qx(e,t){const s=ft(e.lastGit??e.last_git),r=ft(s.result),o=ft(s.status),a=ft(r.status),i=ft(e.lastProbe??e.last_probe),c=ft(i.git),d=ft(c.result),u=ft(c.status),m=ft(d.status);let h=null;for(const p of[o,a,u,m]){const g=ka(p,e);if(!g)continue;const f=Yx(g);(!h||f>h.score)&&(h={git:g,score:f})}return h==null?void 0:h.git}function Jx(e){const t=[Ae(e.workspace),Ae(e.providerType,e.provider),Ae(e.role),Ae(e.state,e.status),Ae(e.title),Ae(e.createdAt,e.created_at),Ae(e.startedAt,e.started_at)].filter(s=>!!s);if(t.length!==0)return`synthetic:${t.join("|")}`}function Ha(e){const t=ft(e),s=Ae(t.sessionId,t.session_id,t.id)??Jx(t);return s?{sessionId:s,...Ae(t.providerType,t.provider)?{providerType:Ae(t.providerType,t.provider)}:{},...Ae(t.state,t.status)?{state:Ae(t.state,t.status)}:{},...Ae(t.chatStatus,t.chat_status)?{chatStatus:Ae(t.chatStatus,t.chat_status)}:{},...Ae(t.lifecycle)?{lifecycle:Ae(t.lifecycle)}:{},...Ae(t.surfaceKind,t.surface_kind)?{surfaceKind:Ae(t.surfaceKind,t.surface_kind)}:{},...Ae(t.recoveryState,t.recovery_state)?{recoveryState:Ae(t.recoveryState,t.recovery_state)}:{},...Ae(t.workspace)?{workspace:Ae(t.workspace)}:{},...Ae(t.title)?{title:Ae(t.title)}:{},...Ae(t.role)?{role:Ae(t.role)}:{},...Qt(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:Qt(t.isSelfCoordinator,t.is_self_coordinator)}:{},...Ae(t.statusNote,t.status_note)?{statusNote:Ae(t.statusNote,t.status_note)}:{},...Ae(t.createdAt,t.created_at)?{createdAt:Ae(t.createdAt,t.created_at)}:{},...Ae(t.startedAt,t.started_at)?{startedAt:Ae(t.startedAt,t.started_at)}:{},...Ae(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:Ae(t.lastActivityAt,t.last_activity_at)}:{},...Qt(t.isCached,t.is_cached)!==void 0?{isCached:Qt(t.isCached,t.is_cached)}:{}}:null}function Xx(e){const t=e&&typeof e=="object"?e:{};return Ae(t.id,t.nodeId,t.node_id)}function Zx(e,t){if(!t)return!1;const s=t.trim();return s?Xx(e)===s:!1}var ey=["antigravity-cli","claude-cli","codex-cli","cursor-cli","grok-cli","kimi","opencode"];function Yl(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 ty=["daemon_","standalone_"];function ny(e){const t=Ae(e);return!!t&&/^[0-9a-f]{64}$/i.test(t)}function hp(e){var s,r;return!e||!ny(e.id)?!1:!!!(Ae(e.machineNickname)||Ae(e.nickname)||Ae(e.hostname)||Ae(e.platform)||Ae((s=e.machine)==null?void 0:s.hostname)||Ae((r=e.machine)==null?void 0:r.platform)||Ae(e.machineId)||Array.isArray(e.sessions)&&e.sessions.length>0)}function Ql(e){const t=Ae(e);if(t){for(const s of ty)if(t.startsWith(s))return t.slice(s.length).trim()||void 0;return t}}function sy(e){const t=Ql(e);if(t)return t.startsWith("mach_")?`daemon_${t}`:t}function on(e,t){const s=Ql(e),r=Ql(t);return!s||!r?!1:s===r}var pp=["easy","medium","difficult","freeform"];function ry(e){return typeof e=="string"&&pp.includes(e)}function oy(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(ry):[],i=Array.isArray(t.capability)?t.capability.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[],c=Number(t.maxParallel),d=Number.isFinite(c)&&c>0?Math.floor(c):void 0;return{provider:s,...r?{model:r}:{},...o?{thinkingLevel:o}:{},...a.length?{difficulty:a}:{},...i.length?{capability:i}:{},...d!==void 0?{maxParallel:d}:{}}}function fp(e){if(!Array.isArray(e))return[];const t=[];for(const s of e){const r=oy(s);r&&t.push(r)}return t}function ay(e){const t=new Set,s=[];for(const r of fp(e))t.has(r.provider)||(t.add(r.provider),s.push(r.provider));return s}function cn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var gp=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress","monitor:long_generating"];cn(gp);var iy=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];cn(iy);var ly=["p2p_offer","p2p_ice"];cn(ly);var cy=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];cn(cy);var dy=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","beacon_vectors","daemon_mesh_command","p2p_offer","p2p_ice"];cn(dy);var uy=["auth_ok","auth_error","machine_evicted","force_disconnect","token_revoked","version_mismatch","force_update_required","command","agent_command","resolve_action","beacon_vectors_result","daemon_mesh_result","p2p_ready","p2p_offer","p2p_answer","p2p_ice","mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];cn(uy);var my=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],hy=[...gp,...my];cn(hy);var py=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];cn(py);var fy=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];cn(fy);var gy=["p2p_ready","p2p_answer","p2p_ice"];cn(gy);var by=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];cn(by);var xy=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];cn(xy);var bp=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];cn(bp);var xp=["ping","pong","p2p_evicted","status_report","status_event","topic_update","topic_update_chunk","session_output","session_output_chunk","session_io_error","command_result","command_result_chunk","response"];cn(xp);[...new Set([...bp,...xp])];var yy="Claude TUI review page is not focused",vy="Claude TUI answer delivered but not confirmed",Jc=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"],yp={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"},vp={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"},wy=new Set(Jc);function mi(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return wy.has(t)?t:vp[t]??null}function Xc(e){const t=mi(e);return t?yp[t]:"unknown"}function hi(e){return Xc(e)==="working"}function Sy(e){return Xc(e)==="dead"}function wp(e){const t=Xc(e);return t==="working"||t==="blocked"}function mu(e){return Jc.filter(t=>yp[t]===e)}var ky=["pending","assigned","completed","failed","cancelled"],jy=["completed","failed","cancelled"],Ny=["code_change","validation","live_debug_readonly","launch_app","convergence"],Cy=["low","normal","high"],_y=["low","medium","high"],Ay=["when_idle","interrupt"],Ty=["preserve","stop","delete_stopped","stop_and_delete"],Sp=["completed","blocked","failed"],kp=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function ls(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}ls(ky);ls(jy);ls(Ny);ls(Cy);ls(_y);ls(Ay);ls(Ty);ls(Sp);ls(kp);var Iy=["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"],My=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(My);var Ry=["fsm_edge","short_gen_inline","completion_flush_genuine","completion_flush_weak","monitor_final_summary","pre_cleanup_transcript","stall_transcript","startup_grace_collapse","acp_prompt_response","cdp_state","approval_gate","modal_button","mesh_stall_watchdog","status_monitor","pty_exit","provider_error","coordinator_probe","mcp_probe","worker_tool","dispatch","input_service","operator","intentional_cleanup","scheduler","git_probe","session_registry"],Py=["mesh_queue","mesh_direct","plain"],Ly=["delivered","queued"],Ey=["local","p2p"],Dy=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],Oy=["default","native_source"],Fy=["restart","live_holder"],$y=["approval","choice"],Hy=["approved","rejected","answered"],By=["modal_button","auto_approve","prompt_answer"],Wy=["genuine","weak"],Uy=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],Ky=["completed","aborted"],qy=["alive","unknown","read_failed","dead"],zy=["auth_failed","billing_failed"],Gy=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],Vy=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],Yy=["completed","failed"],Qy=["operator_update","refine_terminal","validation_terminal"],Jy=["delivered","queued","duplicate"],Xy=[...Jc,"unknown"],jp=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],Zy=["completed","failed","cancelled"],ev=["genuine","weak","tool_report","operator"],tv=["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"],Np=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],ar={t:"id"},ir={t:"id",optional:!0},hs={t:"bool"},Yo={t:"bool",optional:!0},hu={t:"ms"},nv={t:"ms",optional:!0},Qo={t:"int",optional:!0},Ft=e=>({t:"enum",values:e}),Kr=e=>({t:"enum",values:e,optional:!0}),sv={dispatch_accepted:{scope:Ft(Py),messageId:ar,meshId:ir,nodeId:ir,providerType:ir,attemptNo:Qo,dispatchNonce:Qo,consumeProfile:Kr(Oy),maxTaskRetries:Qo,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:ar,outcome:Ft(Ly),via:Ft(Ey)},delivery_refused:{messageId:ar,reason:Ft(Iy)},dispatch_failed:{workerAbsent:hs,reason:Ft(Dy),refusalCode:ir},duplicate_dispatch_refusal:{holderSessionId:ar,holderAttemptId:ir},session_rebound:{toSessionId:ar,reason:Ft(Fy)},turn_started:{retro:hs},suspension:{modal:Ft($y),modalKey:ir},suspension_resolved:{resolution:Ft(Hy),via:Ft(By)},turn_end:{strength:Ft(Wy),afterFinalizationTimeout:Yo,hollow:Yo,summary:{t:"summary_ref",optional:!0},blockReason:Kr(Uy),releasedByHardCap:Yo,nativeOutcome:Kr(Ky),live:{t:"live",optional:!0},reportExpected:Yo},transcript_final:{selfAttributing:hs,nativeRead:hs,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:nv},transcript_activity:{newestActivityAt:hu},no_progress:{stalledMs:hu,observedStatus:Ft(Xy),finalAssistantPresent:hs},liveness:{result:Ft(qy)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:Kr(zy)},session_error:{reason:Ft(Gy)},worker_report:{outcome:Ft(Sp),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:hs,branchState:Kr(kp),touchedFileCount:Qo},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:hs,commitsSinceDispatch:{t:"int"},attributable:hs},cancel:{reason:Ft(Vy)},operator_status:{status:Ft(Yy),reason:Ft(Qy)},coordinator_ack:{notify:Ft(Np),outcome:Ft(Jy)},hold_expired:{holdId:ar,reason:Ft(jp)}},rv=Object.keys(sv);function _s(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}_s(Ry);_s(rv);_s(tv);_s(Np);_s(jp);_s(Zy);_s(ev);var ov=["turn.evidence","turn.committed","turn.notify","mesh.record"];_s(ov);var av=["user","remembered","mesh_slot","task_override","provider_default","unspecified"];function Zc(e){return typeof e=="string"&&av.includes(e)}var iv=["dashboard","mesh","cli","api","restore"];function lv(e){return typeof e=="string"&&iv.includes(e)}function cv(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??Cp(e)}function Cp(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 dv(e){const t=cv(e);if(!e||!t)return;const s=Cp(e);return{value:t,...s&&s!==t?{changedFrom:s}:{},source:Zc(e.source)?e.source:"unspecified"}}function Pn(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Jl(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function pu(e){if(!e||typeof e!="object")return;const t=e,s=[];if(Array.isArray(t.history))for(const u of t.history){if(!u||typeof u!="object")continue;const m=u,h=Pn(m.value),p=Jl(m.at),g=m.via==="launch"||m.via==="change_model"||m.via==="observed"?m.via:void 0;h&&p!==void 0&&g&&s.push({at:p,value:h,via:g})}const r=Pn(t.requested),o=Pn(t.launchValue),a=Pn(t.resolvedDefault),i=Pn(t.current),c=Pn(t.observed),d=Jl(t.observedAt);return{source:Zc(t.source)?t.source:"unspecified",...r?{requested:r}:{},...o?{launchValue:o}:{},...a?{resolvedDefault:a}:{},...i?{current:i}:{},...c?{observed:c}:{},...d!==void 0?{observedAt:d}:{},history:s.slice(-20)}}function uv(e){if(!e||typeof e!="object")return;const t=e,s=Pn(t.sessionId),r=Pn(t.providerType),o=Jl(t.launchedAt),a=pu(t.model),i=pu(t.thinkingLevel);if(!s||!r||o===void 0||!a||!i)return;const c=Pn(t.providerVersion),d=Pn(t.workspace),u=Pn(t.autoApproveModeId);return{sessionId:s,providerType:r,...c?{providerVersion:c}:{},...t.providerChannel==="stable"||t.providerChannel==="preview"?{providerChannel:t.providerChannel}:{},launchedBy:lv(t.launchedBy)?t.launchedBy:"api",launchedAt:o,...d?{workspace:d}:{},model:a,thinkingLevel:i,...u?{autoApproveModeId:u}:{}}}var mv=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];function Fn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Fn(mv);var hv=["applied","recorded","rejected"];Fn(hv);var pv=["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(pv);var fv=["completed","failed"];Fn(fv);var gv=["operator_update","refine_terminal","validation_terminal"];Fn(gv);var bv=["own","fleet"];Fn(bv);var xv=["active","paused","completed","abandoned"];Fn(xv);var yv=["magi","coordinator"];Fn(yv);var vv=["provider_quirk","pattern_to_avoid","recovery_lesson"];Fn(vv);var wv=["coordinator","unknown"];Fn(wv);var Sv=["gate_claimed","gate_released","gate_abandoned","node_patched"];Fn(Sv);var kv=["turn_observe","mesh_record","turn_cancel","operator_status","turn_query","mesh_index_query","mission_upsert","mission_query","note_upsert","note_forget","tool_call_record","ledger_query","mission_list_query","record_local","queue_query","queue_enqueue","queue_enqueue_graph","queue_cancel","queue_requeue","direct_dispatch_record","graph_audit_record","active_work_query","recovery_context_query","graph_gate_claim","graph_gate_release","graph_gate_abandon","graph_node_patch","graph_view_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];Fn(kv);const jv=new Set(["no_progress","long_generating"]);function fu(e){return!e||jv.has(e)?e:mi(e)??e}function gu(e){return!!e&&typeof e=="object"&&"text"in e}function ed(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:gu(a)?String(a.text||""):"").join(s):gu(e)?o=String(e.text||""):o=String(e||""),r?o.replace(/\s+/g," ").trim():o}function _r(e){return ed(e,{normalizeWhitespace:!0})}function Nv(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 bu(e){var s,r;let t=0;return e.activeChat!==void 0&&(t+=4),e.activeInteractivePrompt!==void 0&&(t+=2),(s=e.childSessions)!=null&&s.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(r=e.agents)!=null&&r.length&&(t+=1),t}function _p(e,t,s){if(s.type!=="adhdev-daemon")return s;const r={...s},o=t.version??s.version??e.version,a=t.serverVersion??e.serverVersion??s.serverVersion,i=t.versionMismatch===!0||e.versionMismatch===!0,c=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??s.versionUpdateReason;return o&&(r.version=o),a&&(r.serverVersion=a),d&&(r.versionUpdateReason=d),o&&a&&o===a?(delete r.versionMismatch,delete r.serverVersion,delete r.versionUpdateRequired,delete r.versionUpdateReason,r):((t.versionMismatch===!0||i&&o&&a&&o!==a)&&(r.versionMismatch=!0),c&&(r.versionUpdateRequired=!0),r)}function Cv(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 Ji(e){if(!e||typeof e!="object")return"";const t=e,s=Cv(_r(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),s].join(":")}function _v(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=Ji(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:Ji(e[0]),last:Ji(e[e.length-1])}}function Xl(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Zl(e,t,s){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Xl(e)&&Xl(t)){const i=e.messages;Array.isArray(i)&&i===t.messages&&s.add(i)}if(Array.isArray(e)&&Array.isArray(t)){const i=Math.min(e.length,t.length);for(let c=0;c<i;c+=1)Zl(e[c],t[c],s);return}const r=e,o=t,a=new Set([...Object.keys(r),...Object.keys(o)]);for(const i of a)i!=="messages"&&Zl(r[i],o[i],s)}function fo(e,t){return Array.isArray(e)?e.map(s=>fo(s,t)):!e||typeof e!="object"?e:Xl(e)?Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>[r,r==="messages"?_v(o,t):fo(o,t)])):Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,fo(r,t)]))}function Av(e,t){try{const s=new WeakSet;return Zl(e,t,s),JSON.stringify(fo(e,s))===JSON.stringify(fo(t,s))}catch{return!1}}function ec(e,t,s){return Av(e,t)?(e._lastUpdate=s,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Ap(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Tv(e,t,s){t[s]!==void 0&&(e[s]=t[s])}function xu(e,t,s,r){var d;const o=(d=t.chats)!=null&&d.length?t.chats:e.chats,a=mp(e.childSessions,t.childSessions,{preserveMissing:r}),i=up(t.activeChat,e.activeChat),c=t.workspace||e.workspace;return _p(e,t,{...e,...t,chats:o,childSessions:a,activeChat:i,workspace:c,_lastUpdate:s})}function Iv(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=mp(e.childSessions,t.childSessions,{preserveMissing:s})),(o=t.chats)!=null&&o.length&&!((a=e.chats)!=null&&a.length)&&(r.chats=t.chats),t.workspace&&(r.workspace=t.workspace);for(const i of["title","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","muted","model","modelSource","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])Tv(r,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(r.machineNickname=t.machineNickname),t.versionMismatch===!0&&(r.versionMismatch=!0),r}function Mv(e,t,s,r){const o=Iv(e,t,r),a=Object.keys(o).length>0?_p(e,t,{...e,...o,_lastUpdate:s}):{...e,_lastUpdate:s};return ec(e,a,s)}function Rv(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=Ap(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 Pv(e,t,s,r,o,a){return!o.has(t)||!a.has(t)||r.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?s>1e4:e.transport==="cdp-page"?s>3e4:!1}function Lv(e,t,s,r,o){return e.transport?s.has(t)&&!r.has(t)?!0:o.has(t):!1}function Ev(e,t,s){var m,h;const r=Date.now(),o=new Set((s==null?void 0:s.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(p=>({...p,_lastUpdate:r}));const a=new Map;for(const p of t)a.set(p.id,p);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:u}=Rv(e);for(const p of e){const g=a.get(p.id);if(!g){a.set(p.id,{...p,_lastUpdate:r});continue}const f=bu(p),y=bu(g),b=Ap(p),k=!o.has(b);if(f>y){const S=xu(g,p,r,k);a.set(p.id,ec(g,S,r));continue}if(f<y){a.set(p.id,Mv(g,p,r,k));continue}const j=S=>typeof S=="number"&&Number.isFinite(S),v=j(p.timestamp)&&j(g.timestamp),C=v?p.timestamp:p.timestamp||r,x=v?g.timestamp:g._lastUpdate||g.timestamp||0;if(C>=x){const S=xu(g,p,r,k);a.set(p.id,ec(g,S,r));continue}(m=p.chats)!=null&&m.length&&!((h=g.chats)!=null&&h.length)&&a.set(p.id,{...g,chats:p.chats})}for(const[p,g]of a){const f=g.daemonId||p.split(":")[0];if(!c.has(f))continue;if(o.has(f)&&u.has(f)&&!i.has(p)){a.delete(p);continue}const y=r-(g._lastUpdate||g.timestamp||0);Pv(g,f,y,i,o,d)&&a.delete(p)}for(const[p,g]of a){const f=g.daemonId||p.split(":")[0];if(Lv(g,f,c,d,a))continue;r-(g._lastUpdate||g.timestamp||0)>3e5&&g.status!=="online"&&a.delete(p)}return Array.from(a.values())}function Dv(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 Ov(e,t){return e.id===t||e.sessionId===t||e.instanceId===t}function Fv(e,t,s){const r=t.trim();if(!r)return e;let o=!1;const a=e.map(i=>{if(!Ov(i,r))return i;const c=i.activeInteractivePrompt;return c&&c.promptId===s.promptId?i:(o=!0,{...i,activeInteractivePrompt:s})});return o?a:e}const Tp=l.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},usesP2P:!0,userRole:void 0,connectionRetryStatuses:void 0}),Ip=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[],hydrateInteractivePrompt:()=>{}}),Mp=l.createContext({userName:void 0,setUserName:()=>{},userRole:void 0,usesP2P:!0});function $v({children:e,connectionOverrides:t}){const[s,r]=l.useState([]),[o,a]=l.useState(!1),[i,c]=l.useState([]),[d,u]=l.useState(void 0),m=l.useRef(s);l.useEffect(()=>{m.current=s},[s]);const h=l.useCallback((v,C)=>{r(x=>{let S=!1;const w=x.map(_=>_.id!==v||_.chats===C?_:(S=!0,{..._,chats:C}));return S?w:x})},[]),p=l.useCallback((v,C)=>{r(x=>{const S=x.length===0?v:Ev(v,x,C),w=!Dv(x,S);return w&&Xs.record({kind:"dashboard.entries_applied",payload:{incoming:du(v),next:du(S)}}),w?S:x})},[]),g=l.useCallback(()=>a(!0),[]),f=l.useCallback((v,C)=>{r(x=>Fv(x,v,C))},[]),y=l.useMemo(()=>({injectEntries:p,markLoaded:g,getIdes:()=>m.current,hydrateInteractivePrompt:f}),[p,g,f]),b=t,k=l.useMemo(()=>({ides:s,updateRouteChats:h,initialLoaded:o,toasts:i,setToasts:c,wsStatus:(b==null?void 0:b.wsStatus)??"connected",isConnected:(b==null?void 0:b.isConnected)??!0,connectionStates:(b==null?void 0:b.connectionStates)??{},connectionTransports:(b==null?void 0:b.connectionTransports)??{},showReconnected:(b==null?void 0:b.showReconnected)??!1,retryConnection:b==null?void 0:b.retryConnection,retryServerConnection:b==null?void 0:b.retryServerConnection,connectionLoginUrl:b==null?void 0:b.connectionLoginUrl,isP2PActive:(b==null?void 0:b.isP2PActive)??!1,p2pStates:(b==null?void 0:b.p2pStates)??{},usesP2P:(b==null?void 0:b.usesP2P)??!0,userRole:b==null?void 0:b.userRole,connectionRetryStatuses:b==null?void 0:b.connectionRetryStatuses,userName:d,setUserName:u}),[s,h,o,i,b==null?void 0:b.wsStatus,b==null?void 0:b.isConnected,b==null?void 0:b.connectionStates,b==null?void 0:b.connectionTransports,b==null?void 0:b.showReconnected,b==null?void 0:b.retryConnection,b==null?void 0:b.retryServerConnection,b==null?void 0:b.connectionLoginUrl,b==null?void 0:b.isP2PActive,b==null?void 0:b.p2pStates,b==null?void 0:b.usesP2P,b==null?void 0:b.userRole,b==null?void 0:b.connectionRetryStatuses,d]),j=l.useMemo(()=>({userName:d,setUserName:u,userRole:b==null?void 0:b.userRole,usesP2P:(b==null?void 0:b.usesP2P)??!0}),[d,u,b==null?void 0:b.userRole,b==null?void 0:b.usesP2P]);return n.jsx(Ip.Provider,{value:y,children:n.jsx(Mp.Provider,{value:j,children:n.jsx(Tp.Provider,{value:k,children:e})})})}function An(){return l.useContext(Tp)}function Hv(){return l.useContext(Mp)}function Ar(){return l.useContext(Ip)}const Bv=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={...}>.`)}}}),Wv=l.createContext(Bv);function Uv({client:e,children:t}){return n.jsx(Wv.Provider,{value:e,children:t})}const Kv={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Rp=l.createContext(Kv);function qv({value:e,children:t}){return n.jsx(Rp.Provider,{value:e,children:t})}function _t(){return l.useContext(Rp)}function Pp(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function zv(e){const t=Pp(e);if(!t||t.error!=="untrusted_external_provider")return null;const s=t.provider&&typeof t.provider=="object"?t.provider:null;return{providerType:typeof(s==null?void 0:s.type)=="string"?s.type:null,sourceName:typeof(s==null?void 0:s.sourceName)=="string"?s.sourceName:null,description:typeof t.hint=="string"?t.hint:void 0}}function Gv(e){const[t,s]=l.useState(null),r=l.useCallback(async(i,c)=>{const d=h=>e(i,"launch_cli",{...c,...h}),u=await d({}),m=zv(u);return m?new Promise(h=>{s({providerType:m.providerType||String(c.cliType??"?"),sourceName:m.sourceName,description:m.description,retry:()=>d({confirmExternalUntrusted:!0}),resolve:p=>{p.cancelled?h({success:!1,error:"user_cancelled_untrusted_launch"}):h(p.response)}})}):u},[e]),o=l.useCallback(async()=>{const i=t;if(i){s(null);try{const c=await i.retry(),d=Pp(c);d!=null&&d.success?i.resolve({ok:!0,response:c}):i.resolve({ok:!1,error:(d==null?void 0:d.error)||"launch failed after confirm",response:c})}catch(c){i.resolve({ok:!1,error:(c==null?void 0:c.message)||String(c)})}}},[t]),a=l.useCallback(()=>{const i=t;i&&(s(null),i.resolve({ok:!1,cancelled:!0}))},[t]);return{launchCli:r,pending:t,confirm:o,cancel:a}}const Xe={size:18};function Lp({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),n.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),n.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),n.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function td({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Ks({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),n.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),n.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),n.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),n.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),n.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Vv({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"9",cy:"7",r:"4"}),n.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),n.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Yv({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Qv({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Ep({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),n.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),n.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),n.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function nd({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),n.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),n.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),n.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),n.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Er({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("polyline",{points:"20 6 9 17 4 12"})})}function Jv({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"}),n.jsx("path",{d:"m15 5 4 4"})]})}function Dr({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Io({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),n.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function y5({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),n.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Xv({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Jn({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Xn({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),n.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Dp({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"}),n.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),n.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Zs({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function Or({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polyline",{points:"23 4 23 10 17 10"}),n.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function an({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),n.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),n.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Tr({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("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 Gn({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"5",r:"2"}),n.jsx("circle",{cx:"5",cy:"19",r:"2"}),n.jsx("circle",{cx:"19",cy:"19",r:"2"}),n.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),n.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),n.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function Zv({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),n.jsx("polyline",{points:"2 12 12 17 22 12"}),n.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function sd({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function pi({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),n.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),n.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),n.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function rd({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function ew({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),n.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),n.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function od({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polyline",{points:"4 17 10 11 4 5"}),n.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function tw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Op({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function jo({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function nw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}),n.jsx("line",{x1:"10",y1:"11",x2:"10",y2:"17"}),n.jsx("line",{x1:"14",y1:"11",x2:"14",y2:"17"})]})}function Bt({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Fp({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",className:t,children:[n.jsx("circle",{cx:"5",cy:"12",r:"1.9"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.9"}),n.jsx("circle",{cx:"19",cy:"12",r:"1.9"})]})}function fi({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),n.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),n.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),n.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function sw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),n.jsx("path",{d:"M12 2v6"}),n.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),n.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function rw({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function $p({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})})}function ow({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),n.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function js({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),n.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function tc({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M8.7 3A6 6 0 0 1 18 8c0 3 .6 5 1.4 6.5"}),n.jsx("path",{d:"M17 17H3s3-2 3-9a5.98 5.98 0 0 1 .6-2.6"}),n.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"}),n.jsx("line",{x1:"2",y1:"2",x2:"22",y2:"22"})]})}function Hp({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"5"}),n.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),n.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),n.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),n.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),n.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),n.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),n.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),n.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Bp({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Wp({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),n.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),n.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function gi({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),n.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function yu({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function aw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),n.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function iw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),n.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),n.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function lw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),n.jsx("path",{d:"M13 2h9v9"}),n.jsx("path",{d:"M22 2L13 11"})]})}function cw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("polyline",{points:"9 14 4 9 9 4"}),n.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Up({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),n.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),n.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),n.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),n.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),n.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),n.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),n.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),n.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),n.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function dw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),n.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function uw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),n.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),n.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function Kp({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),n.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}function Ir({size:e=Xe.size,className:t}){return n.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`animate-spin ${t??""}`,children:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.22-8.56"})})}function qp({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"}),n.jsx("path",{d:"M13 13l6 6"})]})}function mw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M18 11V6a2 2 0 0 0-4 0v5"}),n.jsx("path",{d:"M14 10V4a2 2 0 0 0-4 0v6"}),n.jsx("path",{d:"M10 10.5V6a2 2 0 0 0-4 0v8"}),n.jsx("path",{d:"M18 8a2 2 0 0 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15"})]})}function hw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"16.5",y1:"9.4",x2:"7.5",y2:"4.21"}),n.jsx("path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"}),n.jsx("polyline",{points:"3.27 6.96 12 12.01 20.73 6.96"}),n.jsx("line",{x1:"12",y1:"22.08",x2:"12",y2:"12"})]})}function pw({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("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 nc({size:e=Xe.size,className:t}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),n.jsx("circle",{cx:"18",cy:"6",r:"3"}),n.jsx("circle",{cx:"6",cy:"18",r:"3"}),n.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function fw({providerType:e,sourceName:t,description:s,onConfirm:r,onCancel:o}){const{t:a}=ve("common"),i=l.useRef(null);return l.useEffect(()=>{var c;(c=i.current)==null||c.focus()},[]),l.useEffect(()=>{const c=d=>{d.key==="Escape"&&o()};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[o]),n.jsx("div",{role:"dialog","aria-modal":"true","aria-label":a("machine.confirmExternal.dialogAria"),className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:o,style:{pointerEvents:"auto"},children:n.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-amber-500/40 rounded-lg shadow-xl max-w-lg w-full",onClick:c=>c.stopPropagation(),children:[n.jsxs("div",{className:"px-4 py-3 border-b border-border-subtle flex items-center gap-2",children:[n.jsx("span",{"aria-hidden":!0,className:"text-amber-400",children:n.jsx(an,{size:16})}),n.jsx("h2",{className:"text-sm font-semibold",children:a("machine.confirmExternal.title")})]}),n.jsxs("div",{className:"px-4 py-3 text-xs flex flex-col gap-3",children:[n.jsx("p",{children:t?a("machine.confirmExternal.aboutToActivateFrom",{provider:e,source:t}):a("machine.confirmExternal.aboutToActivate",{provider:e})}),n.jsx("p",{className:"text-text-secondary",children:s??a("machine.confirmExternal.description")}),n.jsx("p",{className:"text-text-secondary",children:a("machine.confirmExternal.proceedWarning")})]}),n.jsxs("div",{className:"px-4 py-2 border-t border-border-subtle flex justify-end gap-2",children:[n.jsx("button",{ref:i,type:"button",onClick:o,className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:a("machine.confirmExternal.cancel")}),n.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-amber-500 text-black font-semibold hover:opacity-90",children:a("machine.confirmExternal.activate")})]})]})})}const zp=l.createContext(null);function gw({sendDaemonCommand:e,children:t}){const s=Gv(e),r=l.useMemo(()=>({launchCli:s.launchCli}),[s.launchCli]);return n.jsxs(zp.Provider,{value:r,children:[t,s.pending&&n.jsx(fw,{providerType:s.pending.providerType,sourceName:s.pending.sourceName,description:s.pending.description,onConfirm:s.confirm,onCancel:s.cancel})]})}function bi(){const e=l.useContext(zp);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function bw(e){const{baseUrl:t,getToken:s,onUnauthorized:r}=e;function o(c){return c.startsWith("http")?c:`${t}${c.startsWith("/")?"":"/"}${c}`}function a(c){const d=s==null?void 0:s(),u=o(c),m=c.startsWith("http")?new URL(u):new URL(u,typeof window<"u"?window.location.origin:"http://localhost");return d&&m.searchParams.set("token",d),!c.startsWith("http")&&!t?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function i(c,d={}){const u={"Content-Type":"application/json",...d.headers||{}},m=s==null?void 0:s();m&&(u.Authorization=`Bearer ${m}`);const h=o(c),p=new AbortController,g=setTimeout(()=>p.abort(),15e3);try{const f=await fetch(h,{...d,headers:u,signal:p.signal});if(f.status===401)throw r==null||r(),new Error("Unauthorized");if(!f.ok){const y=await f.json().catch(()=>({error:f.statusText}));throw new Error(y.error||`API Error: ${f.status}`)}return f.json()}finally{clearTimeout(g)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,u={})=>i(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:u})}),execTerminal:(c,d,u)=>i(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:u})}),sendAgentMessage:(c,d,u)=>i(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:u})}),getAgentStatus:c=>i(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,u)=>i(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:u?"approve":"reject"})}),getMuxState:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,d,u={})=>i(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:u})}),getMuxEventsUrl:c=>a(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>a(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:i}}function xi(e,t={}){if(!e)return"";const{suffix:s="",nowLabel:r="now",nowThreshold:o=60}=t,a=Date.now()-e,i=Math.floor(a/1e3);if(i<o)return r;const c=Math.floor(i/60);if(c<60)return`${c}m${s}`;const d=Math.floor(c/60);if(d<24)return`${d}h${s}`;const u=Math.floor(d/24);return u<7?`${u}d${s}`:new Date(e).toLocaleDateString()}const Gp=e=>xi(e);function Mo(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 Ro(e){var s,r;if(e)return e;const t=((s=at)==null?void 0:s.resolvedLanguage)||((r=at)==null?void 0:r.language);return t&&t!=="cimode"?t:void 0}function Ba(e,t={}){const s=Mo(e);if(s===null)return"";const r=Ro(t.locale),o=t.now??Date.now(),a=Math.round((s-o)/1e3),i=Math.abs(a);let c;try{c=new Intl.RelativeTimeFormat(r,{numeric:"auto",style:"short"})}catch{c=new Intl.RelativeTimeFormat(void 0,{numeric:"auto",style:"short"})}return i<45?c.format(0,"second"):i<3600?c.format(Math.round(a/60),"minute"):i<86400?c.format(Math.round(a/3600),"hour"):i<7*86400?c.format(Math.round(a/86400),"day"):id(s,{locale:r})}function ad(e,t){try{return new Intl.DateTimeFormat(e,t)}catch{return new Intl.DateTimeFormat(void 0,t)}}function Po(e,t={}){const s=Mo(e);return s===null?"":ad(Ro(t.locale),{dateStyle:"medium",timeStyle:t.seconds?"medium":"short"}).format(s)}function id(e,t={}){const s=Mo(e);return s===null?"":ad(Ro(t.locale),{dateStyle:"medium"}).format(s)}function yi(e,t={}){const s=Mo(e);return s===null?"":ad(Ro(t.locale),{timeStyle:t.seconds?"medium":"short"}).format(s)}function v5(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const s=Math.floor(t/60);if(s<60)return`${s}m`;const r=Math.floor(s/60);return r<48?`${r}h ${s%60}m`:`${Math.floor(r/24)}d ${r%24}h`}function ps(e,t,s){try{return new Intl.NumberFormat(s,{style:"unit",unit:t,unitDisplay:"short"}).format(e)}catch{return`${e}${t[0]}`}}function xw(e,t={}){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";const s=Ro(t.locale),r=Math.round(e/1e3);if(r<60)return ps(r,"second",s);const o=Math.floor(r/60);if(o<60)return ps(o,"minute",s);const a=Math.floor(o/60);if(a<48){const d=o%60;return d?`${ps(a,"hour",s)} ${ps(d,"minute",s)}`:ps(a,"hour",s)}const i=Math.floor(a/24),c=a%24;return c?`${ps(i,"day",s)} ${ps(c,"hour",s)}`:ps(i,"day",s)}function sc(e){return e?yi(e):""}function yw(e,t,s){return Number(e.receivedAt||s[vi(e)]||0)||0}function Vp(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function vw(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}const ww=new Set(["https:","http:","mailto:","file:"]);function vu(e){if(e)try{const t=new URL(e);return ww.has(t.protocol)?e:void 0}catch{return}}function qr(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 Xi(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 wu(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t^e.charCodeAt(s),t|=0;return(t>>>0).toString(36)}function Sw(e){const t=e.toolBlockRef;if(!t||typeof t!="object")return null;const{recordIndex:s,blockIndex:r}=t;return!Number.isInteger(s)||!Number.isInteger(r)?null:`toolblock:${s}:${r}`}function vi(e,t){const s=e,r=ed(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:${wu(r)}`,...d?[`ts:${d}`]:[]].join("|")}return a.join("|")}const i=e.receivedAt||e.timestamp||0;return[e.role?`role:${e.role}`:"role:",`chash:${wu(r)}`,i?`ts:${i}`:""].filter(Boolean).join("|")}function kw(e){const t=e.map((o,a)=>vi(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 jw(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 Nw(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Yp(e){return e?jw([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Nw(e.content)]):""}const ld=200,Cw=80,Su=650,zr=new Map;function Wa(e,t){if(!e)return!1;const s=String(e.messageFingerprint||"");return s?s===String(t||""):!0}function _w(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}:${Yp(r)}`}function Aw(e,t,s,r){return e||!t?!1:Wa(s,r)}function Tw({scrollTop:e,scrollHeight:t,clientHeight:s,topThresholdPx:r=Cw,bottomThresholdPx:o=ld}){const a=Math.max(0,Number(e)||0),i=Math.max(0,Number(t)||0),c=Math.max(0,Number(s)||0);return Math.max(0,i-c)<=0?{showTop:!1,showBottom:!1}:{showTop:a>r,showBottom:Math.max(0,i-a-c)>o}}function Iw(e){return Tw({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function lo(e,t=ld){return!!e&&e.fromBottom>=t}function Mw(e,t){return Wa(e,t)?!lo(e):!0}function Rw({hasSelection:e,userScrolledUp:t,hasChatContentChanged:s=!0}){return!(e||t||!s)}function Pw({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:s}){return e?!1:s||!t}function Zi(e,t){const s=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(s)?s:t.top}const cd="adhdev_chat_activity_visible",ku=new Set(["hidden","debug","internal"]),ju=new Set(["visible","user","chat"]),Lw=new Set(["debug","trace","internal"]),Ew=new Set(["tool_call","terminal_command","runtime_activity"]),Dw=new Set(["runtime_status","provider_chrome","control"]),Ow=new Set(["thought","tool","terminal"]);function Qp(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function xr(e){return typeof e=="string"?e.trim().toLowerCase():""}function el(e,t,s){return e[s]??(t==null?void 0:t[s])}function Nu(e,t,s){const r=e;return s.some(o=>r[o]===!0||(t==null?void 0:t[o])===!0)}function Fw(e,t){const s=xr(e.kind);return s||(t==="tool"?"tool":"standard")}function tl(e,t,s){const r=Qp(e),o=typeof(r==null?void 0:r.label)=="string"?r.label.trim():"";return o||(t==="terminal"||s==="terminal_command"?"Terminal":t==="tool"||s==="tool_call"?"Tool":t==="thought"?"Thought":s==="runtime_activity"?"Runtime":"Activity")}function $w(e){const t=e.content;return Array.isArray(t)&&t.some(s=>!!s&&typeof s=="object"&&s.type!=="text")}function wi(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=Qp(e),s=xr(e.role),r=Fw(e,s),o=xr(el(e,t,"visibility")),a=xr(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??o),i=xr(el(e,t,"audience")),c=xr(el(e,t,"source")),d=ku.has(o)||ku.has(a)||Lw.has(i)||Nu(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),u=ju.has(o)||ju.has(a)||i==="chat"||Nu(e,t,["userFacing"]),m=Ow.has(r)||Ew.has(c);if(d)return{surface:m?"activity":"internal",isUserFacing:!1,isActivityFacing:m,isInternal:!m,role:s,kind:r,label:tl(e,r,c)};if(u)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:s,kind:r,label:tl(e,r,c)};if((s==="system"||r==="system")&&$w(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:s,kind:r,label:"Chat"};if(Dw.has(c)||s==="system"||r==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:s,kind:r,label:"Internal"};if(m)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:s,kind:r,label:tl(e,r,c)};const h=(s==="user"||s==="human"||s==="assistant")&&(r==="standard"||r==="");return{surface:h?"chat":"internal",isUserFacing:h,isActivityFacing:!1,isInternal:!h,role:s,kind:r,label:h?"Chat":"Internal"}}function Hw(e){return(Array.isArray(e)?e:[]).filter(t=>wi(t).isActivityFacing)}const Cu=new WeakMap;function Jp(e){const t=Cu.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 Cu.set(e,r),r}function Bw(e){return`${String(e.role||"")}::${Jp(e)}`}function Ww(e){if(e.length<2)return e;const t=[];let s="";for(const r of e){const o=Bw(r);Jp(r).trim().length>0&&o===s||(t.push(r),s=o)}return t}function Uw(e,t,s){return!s||t.length===0?e:[...e,...t].sort((r,o)=>{const a=Number(r.receivedAt??r.timestamp??0)||0,i=Number(o.receivedAt??o.timestamp??0)||0;if(a!==i)return a-i;const c=Number(r.index??0)||0,d=Number(o.index??0)||0;return c-d})}function qs(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(cd))!=="0"}catch{return!0}}function Kw(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(cd,e?"1":"0")}catch{}}const rc="adhdev:chat-activity-visibility-change";function Xp(e){Kw(e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(rc,{detail:e}))}function dd(e){if(typeof window>"u")return()=>{};const t=r=>{const o=r.detail;e(typeof o=="boolean"?o:qs())},s=r=>{r.key&&r.key!==cd||e(qs())};return window.addEventListener(rc,t),window.addEventListener("storage",s),()=>{window.removeEventListener(rc,t),window.removeEventListener("storage",s)}}const _u=100,Au=600;function Tu({text:e}){const{t}=ve("common"),[s,r]=l.useState(!1),o=l.useCallback(()=>{navigator.clipboard.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)}).catch(()=>{})},[e]);return n.jsx("button",{type:"button",onClick:o,"aria-label":t("chat.copyMessage"),className:"chat-copy-btn",children:s?n.jsx(Er,{size:11}):n.jsx(nd,{size:11})})}function qw({text:e}){const{t}=ve("common"),[s,r]=l.useState(!1),o=l.useCallback(a=>{a.preventDefault(),a.stopPropagation(),navigator.clipboard.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)}).catch(()=>{})},[e]);return n.jsx("button",{type:"button",onClick:o,"aria-label":t("chat.copyCode"),title:t("chat.copyCode"),className:"chat-code-copy-btn",children:s?n.jsx(Er,{size:12}):n.jsx(nd,{size:12})})}function zw(e){const t=oc(e.children);return n.jsxs("pre",{...e,children:[e.children,n.jsx(qw,{text:t})]})}function oc(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(oc).join("");if(l.isValidElement(e)){const s=(t=e.props)==null?void 0:t.children;return oc(s)}return""}const Zp={pre:zw},ef=[Rx,{singleTilde:!1}],tf=[ef,Px,Lx],Gw=[ef];function Jo(e,t,s){return n.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[n.jsx("span",{className:"font-medium",children:e}),t?n.jsx("span",{className:"ml-1 break-all",children:t}):null,s?n.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:s}):null]})}function Iu(e,t){return e?t?n.jsx("pre",{className:"chat-preformatted",children:e}):Vp(e)?n.jsx(Yc,{remarkPlugins:tf,components:Zp,children:e}):n.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const Vw=l.memo(function({content:t,renderAsPreformatted:s,renderAsMarkdown:r}){return s?n.jsx("pre",{className:"chat-preformatted",children:t}):r?n.jsx(Yc,{remarkPlugins:tf,components:Zp,children:t}):n.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function Gr({parts:e,renderAsPreformatted:t}){return n.jsx("div",{className:"flex flex-col gap-2",children:e.map((s,r)=>{if(s.type==="text")return n.jsx("div",{children:Iu(String(s.text||""),t)},`text-${r}`);if(s.type==="image"){const o=Xi(s),a=s.alt||s.description||qr(s.uri,"image");return o?n.jsx("img",{src:o,alt:a,className:"max-w-full rounded-md border border-border-subtle"},`image-${r}`):n.jsx("div",{children:Jo("Image",a,s.mimeType)},`image-fallback-${r}`)}if(s.type==="audio"){const o=Xi(s);return o?n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("audio",{controls:!0,src:o,className:"max-w-full"}),s.transcript?n.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:s.transcript}):null]},`audio-${r}`):n.jsx("div",{children:Jo("Audio",qr(s.uri,"audio"),s.transcript||s.mimeType)},`audio-fallback-${r}`)}if(s.type==="video"){const o=Xi(s),a=s.title||s.name||s.alt||qr(s.uri,"video"),i=[s.transcript,s.description,s.mimeType].filter(Boolean).join(`
|
|
6
|
-
`);return n.jsxs("div",{className:"flex flex-col gap-1",children:[o?n.jsx("video",{controls:!0,src:o,poster:s.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):Jo("Video",a,i),o&&i?n.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:i}):null]},`video-${r}`)}if(s.type==="resource_link"){const o=s.title||s.name||qr(s.uri,"resource"),a=[s.description,s.mimeType].filter(Boolean).join(`
|
|
7
|
-
`),i=vu(s.uri);return n.jsxs("div",{className:"flex flex-col gap-1",children:[i?n.jsx("a",{href:i,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:o}):Jo("Resource",o,a),i&&a?n.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:a}):null]},`resource-link-${r}`)}if(s.type==="resource"&&s.resource){const o=qr(s.resource.uri,"resource");if(s.resource.text)return n.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[n.jsx("div",{className:"text-2xs opacity-70 mb-1",children:o}),Iu(s.resource.text,!0)]},`resource-${r}`);const a=vu(s.resource.uri);if(a)return n.jsx("a",{href:a,target:"_blank",rel:"noreferrer",className:"underline break-all",children:o},`resource-uri-${r}`)}return null})})}const Yw=l.memo(function({log:t}){return n.jsxs("div",{className:"self-center chat-msg-action",children:[n.jsx(Yc,{remarkPlugins:Gw,children:t.text}),n.jsx("span",{className:"action-time",children:sc(t.timestamp)})]})},(e,t)=>e.log===t.log);function Mu({state:e,onExpand:t,onCollapse:s}){const{t:r}=ve("common");if((e==null?void 0:e.status)==="loading")return n.jsx("div",{className:"chat-msg-tool-expand","aria-live":"polite",children:r("chat.toolExpandLoading")});if((e==null?void 0:e.status)==="error"){const o=e.error==="source_changed";return n.jsx("div",{className:"chat-msg-tool-expand chat-msg-tool-expand-error",role:"status","data-expand-error-reason":e.error??"unknown",children:r(o?"chat.toolExpandStale":"chat.toolExpandUnavailable")})}return(e==null?void 0:e.status)==="expanded"?n.jsx("button",{type:"button",className:"chat-msg-tool-expand",onClick:s,children:r("chat.toolCollapse")}):n.jsx("button",{type:"button",className:"chat-msg-tool-expand",onClick:t,children:r("chat.toolExpand")})}function Qw(e){const t=e.meta,s=t==null?void 0:t.pendingId;return typeof s=="string"?s:""}function Jw(e){const t=e.meta;return(t==null?void 0:t.pendingLocal)===!0&&(t==null?void 0:t.queued)===!0}const Ru=new WeakMap;function Pu(e){const t=Ru.get(e);if(t!==void 0)return t;const s=Xw(e);return Ru.set(e,s),s}function Xw(e){const t=e.meta;return[Yp(e),e.kind||"",e.senderName||"",e.bubbleId||"",e.bubbleState||"",e.visibility||"",e.transcriptVisibility||"",e.audience||"",e.source||"",e.userFacing===void 0?"":String(e.userFacing),e.internal===void 0?"":String(e.internal),e.isInternal===void 0?"":String(e.isInternal),e.debug===void 0?"":String(e.debug),t?String(t.label??""):"",t?String(t.isRunning??""):"",t?String(t.renderMode??""):"",t?String(t.pendingLocal??""):"",t?String(t.queued??""):"",t?String(t.pendingId??""):""].join("")}const Zw=l.memo(function({message:t,receivedAt:s,agentName:r,userName:o,isCliMode:a,isTextExpanded:i,onToggleTextExpanded:c,onSendNow:d,isSendingNow:u,onCancelQueued:m,onExpandToolBlock:h,onCollapseToolBlock:p,toolExpand:g}){var T,H,q,J;const{t:f}=ve("common"),y=Jw(t),b=Qw(t),k=(t.role||"").toLowerCase(),j=k==="user"||k==="human",v=t.kind||(k==="tool"?"tool":"standard"),C=wi(t),x=vw(t.content)?t.content:null,S=!!(x!=null&&x.some(K=>K.type!=="text")),w=ed(t.content,{joiner:`
|
|
8
|
-
`});if(C.isActivityFacing&&v!=="thought"&&v!=="tool"&&v!=="terminal"){const K=C.label||f("chat.activityFallback");return n.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[n.jsxs("div",{className:"chat-msg-activity-meta","aria-label":f("chat.activityMessageAria"),children:[n.jsx("span",{className:"activity-dot"}),n.jsx("span",{children:K})]}),S&&x?n.jsx("div",{className:"chat-msg-activity-body",children:n.jsx(Gr,{parts:x,renderAsPreformatted:!1})}):n.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:w})]})}if(v==="thought"){const K=typeof((T=t.meta)==null?void 0:T.label)=="string"?t.meta.label:f("chat.thought");return n.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":C.isActivityFacing?"true":void 0,children:[n.jsxs("div",{className:"chat-msg-header",children:[n.jsx(rw,{size:13}),n.jsx("span",{children:K})]}),n.jsx("div",{className:"chat-msg-body",children:w})]})}if(v==="tool"){const K=t.toolBlockRef,M=typeof((H=t.meta)==null?void 0:H.label)=="string"&&t.meta.label?t.meta.label:typeof t.toolName=="string"&&t.toolName?t.toolName:"Tool",D=(g==null?void 0:g.text)??w,P=!K&&!S&&D.length>Au,W=P&&!i&&(g==null?void 0:g.status)!=="expanded"?`${D.slice(0,Au-1)}…`:D;return n.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":C.isActivityFacing?"true":void 0,children:[n.jsxs("span",{className:"chat-bubble-header-end chat-msg-tool-header-end",children:[n.jsx(Tu,{text:w}),s!=null&&n.jsx("span",{className:"chat-time",children:sc(s)})]}),n.jsxs("div",{className:"chat-msg-tool-meta","aria-label":f("chat.toolMessageAria"),children:[n.jsx("span",{className:"tool-icon","aria-hidden":"true"}),n.jsx("span",{className:"tool-label",children:M})]}),S&&x?n.jsx("div",{className:"tool-text w-full",children:n.jsx(Gr,{parts:x,renderAsPreformatted:!1})}):n.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:W}),K&&h?n.jsx(Mu,{state:g,onExpand:()=>h(K),onCollapse:p}):P?n.jsx(Mu,{state:i||(g==null?void 0:g.status)==="expanded"?{status:"expanded"}:void 0,onExpand:c,onCollapse:c}):null]})}if(v==="terminal"){const K=typeof((q=t.meta)==null?void 0:q.label)=="string"?t.meta.label:"Ran command";return n.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":C.isActivityFacing?"true":void 0,children:[n.jsxs("div",{className:"chat-msg-header",children:[n.jsx("span",{children:(J=t.meta)!=null&&J.isRunning?n.jsx(Ir,{size:12}):n.jsx(Er,{size:12})}),n.jsx("span",{children:K})]}),S&&x?n.jsx("div",{className:"chat-msg-body",children:n.jsx(Gr,{parts:x,renderAsPreformatted:!0})}):n.jsx("pre",{className:"chat-msg-body",children:w})]})}if(v==="system"){const K=w.length>_u,M=i||!K?w:`${w.slice(0,_u)}…`;return n.jsx("div",{className:"self-center chat-msg-system",title:w,children:S&&x?n.jsx(Gr,{parts:x,renderAsPreformatted:!1}):n.jsxs(n.Fragment,{children:[M,K&&c&&n.jsx("button",{type:"button",onClick:c,className:"chat-msg-system-expand ml-1.5 text-3xs font-semibold underline opacity-70 hover:opacity-100",children:f(i?"chat.showLess":"chat.showMore")})]})})}const _=t.meta,O=(typeof(_==null?void 0:_.renderMode)=="string"?_.renderMode.trim():"")==="preformatted",L=w,R=!1,F=L,N=O,I=!j&&!N&&Vp(F),B=["chat-message-row",j?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return n.jsx("div",{className:B,children:(L||S||j)&&n.jsxs("div",{className:`chat-bubble ${j?"chat-bubble-user":"chat-bubble-assistant"}`,children:[n.jsxs("div",{className:`chat-bubble-header ${L||S?"mb-1.5":"mb-0"}`,children:[n.jsx("span",{className:"chat-sender",children:j?o||f("chat.you"):t.senderName||r}),n.jsxs("span",{className:"chat-bubble-header-end",children:[(L||S)&&n.jsx(Tu,{text:w}),s!=null&&n.jsx("span",{className:"chat-time",children:sc(s)})]})]}),(L||S)&&n.jsx("div",{className:"chat-markdown",children:S&&x?n.jsx(Gr,{parts:x,renderAsPreformatted:N}):n.jsx(Vw,{content:F,renderAsPreformatted:N,renderAsMarkdown:I})}),R,y&&n.jsxs("div",{className:"chat-bubble-queued","data-chat-queued-row":"true",children:[n.jsx("span",{className:"chat-bubble-queued-label","aria-label":f("chat.waitingToSendAria"),children:f("chat.waitingToSend")}),d&&n.jsx("button",{type:"button",onClick:()=>d(b||void 0),disabled:u,className:"chat-bubble-send-now","aria-label":f("chat.sendNowAria"),title:f("chat.sendNowTitle"),children:f(u?"chat.sending":"chat.sendNow")}),m&&b&&n.jsx("button",{type:"button",onClick:()=>m(b),disabled:u,className:"chat-bubble-cancel-queued","aria-label":f("chat.cancelQueuedAria"),title:f("chat.cancelQueuedTitle"),children:f("chat.cancelQueued")})]})]})})},(e,t)=>(e.message===t.message||Pu(e.message)===Pu(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded&&e.isSendingNow===t.isSendingNow&&e.onSendNow===t.onSendNow&&e.onCancelQueued===t.onCancelQueued&&e.toolExpand===t.toolExpand),e0=l.forwardRef(function({messages:t,actionLogs:s,agentName:r="Agent",userName:o,isCliMode:a=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:u,showActivityMessages:m=!1,emptyState:h,onLoadMore:p,isLoadingMore:g,hasMoreHistory:f,hiddenLiveCount:y=0,loadError:b,scrollToBottomRequestNonce:k,isVisible:j=!0,onSendNow:v,isSendingNow:C,onCancelQueued:x,onExpandToolBlock:S,onCollapseToolBlock:w,toolExpansions:_},A){const{t:O}=ve("common"),L=l.useRef(null),R=l.useRef(null),F=l.useRef(null),N=l.useRef(0),I=l.useRef(""),B=l.useRef(""),T=l.useRef(!1),H=l.useRef(null),q=l.useRef(!1),J=l.useRef(null),K=l.useRef(!1),[M,D]=l.useState(new Set),[P,$]=l.useState({showTop:!1,showBottom:!1}),W=l.useRef(!1),U=l.useRef(!1),ae=l.useRef(j),be=l.useRef(j),V=l.useRef(null);be.current=j;const we=()=>{const Y=L.current;return Y?Y.scrollHeight-Y.scrollTop-Y.clientHeight<ld:!0},ce=l.useCallback(()=>{const Y=L.current,me=Y?Iw(Y):{showTop:!1,showBottom:!1};$(fe=>fe.showTop===me.showTop&&fe.showBottom===me.showBottom?fe:me)},[]),de=l.useCallback((Y="auto")=>{var fe;const me=L.current;me&&(me.scrollTo({top:me.scrollHeight,behavior:Y}),(fe=me.ownerDocument.defaultView)==null||fe.requestAnimationFrame(()=>ce()))},[ce]),ne=l.useCallback((Y="auto")=>{var fe;const me=L.current;me&&(me.scrollTo({top:0,behavior:Y}),(fe=me.ownerDocument.defaultView)==null||fe.requestAnimationFrame(()=>ce()))},[ce]),ee=l.useCallback(()=>{var oe;const Y=L.current,me=(oe=window.getSelection)==null?void 0:oe.call(window);if(!Y||!me||me.rangeCount===0||me.isCollapsed){K.current=!1;return}const fe=me.anchorNode,E=me.focusNode;K.current=!!(fe&&E&&Y.contains(fe)&&Y.contains(E))},[]),ue=l.useMemo(()=>{const Y=[],me=[];for(const fe of Array.isArray(t)?t:[]){const E=wi(fe);E.isUserFacing?Y.push(fe):E.isActivityFacing&&me.push(fe)}return Ww(Uw(Y,me,m))},[t,m]),je=ue.length===t.length?u:void 0,X=_w(ue,je),G=l.useCallback(()=>{const Y=L.current;if(!Y||!c||!be.current)return;const me={top:Y.scrollTop,fromBottom:Math.max(0,Y.scrollHeight-Y.scrollTop-Y.clientHeight),messageFingerprint:X};V.current={contextKey:c,snapshot:me},zr.set(c,me)},[c,X]),z=l.useCallback((Y="auto")=>{H.current!=null&&cancelAnimationFrame(H.current),H.current=requestAnimationFrame(()=>{H.current=null,de(Y)})},[de]),ie=l.useCallback(()=>{W.current=!1,q.current=!0,U.current=!0,J.current!=null&&window.clearTimeout(J.current),J.current=window.setTimeout(()=>{q.current=!1,J.current=null},Su)},[]);l.useEffect(()=>{const Y=!T.current,me=B.current!==c;if(B.current=c,Y||me){T.current=!0;const E=c?zr.get(c):null,oe=!!E&&Wa(E,X);W.current=oe?lo(E):!1,q.current=Mw(E,X),K.current||(oe?requestAnimationFrame(()=>{const Ie=L.current;Ie&&(Zi(Ie,E),W.current=lo(E),ce(),U.current=!0)}):z("auto")),N.current=ue.length,I.current=X;return}ue.length>N.current;const fe=X!==I.current;Rw({hasSelection:K.current,userScrolledUp:W.current,hasChatContentChanged:fe})&&z("auto"),N.current=ue.length,I.current=X},[X,c,ue.length,z,ce]),l.useEffect(()=>{k&&(ie(),K.current||z("auto"))},[ie,z,k]),l.useEffect(()=>{const Y=ae.current;Y&&!j&&G(),be.current=j,ae.current=j;const me=c?zr.get(c):null;if(Aw(Y,j,me,X)){if(!me)return;W.current=lo(me),q.current=!1,K.current||requestAnimationFrame(()=>{const fe=L.current;fe&&(Zi(fe,me),ce())});return}},[j,c,X,ie,G,z,ce]),l.useEffect(()=>()=>{const Y=V.current;Y&&zr.set(Y.contextKey,Y.snapshot),H.current!=null&&cancelAnimationFrame(H.current),J.current!=null&&window.clearTimeout(J.current)},[]),l.useEffect(()=>{const Y=R.current,me=L.current;if(!Y||!me)return;const fe=()=>{J.current!=null&&window.clearTimeout(J.current),J.current=window.setTimeout(()=>{q.current=!1,J.current=null},Su)},E=new ResizeObserver(()=>{ce();const oe=q.current;Pw({hasSelection:K.current,userScrolledUp:W.current,contextAutoScrollActive:oe})&&(z("auto"),oe&&fe())});return E.observe(Y),me!==Y&&E.observe(me),()=>{E.disconnect(),J.current!=null&&(window.clearTimeout(J.current),J.current=null)}},[z,c,ce]),l.useImperativeHandle(A,()=>({scrollToBottom:(Y="smooth")=>{de(Y)}}),[de]),l.useEffect(()=>{const Y=L.current;if(!Y)return;let me;const fe=()=>{G(),clearTimeout(me),me=setTimeout(()=>{W.current=!we(),ce()},50)};return Y.addEventListener("scroll",fe,{passive:!0}),()=>{Y.removeEventListener("scroll",fe),clearTimeout(me)}},[G,ce]),l.useEffect(()=>(document.addEventListener("selectionchange",ee),()=>document.removeEventListener("selectionchange",ee)),[ee]);const Ne=l.useRef(0),Be=l.useRef(!1);l.useEffect(()=>{const Y=L.current;if(!Y||!Be.current||Ne.current===0)return;const me=Y.scrollHeight-Ne.current;me>0&&(Y.scrollTop=me),ce(),G(),Ne.current=0,Be.current=!1},[ue.length,G,ce]),l.useEffect(()=>{if(U.current||!c)return;const Y=zr.get(c),me=L.current;if(!(!Y||!me)){if(!Wa(Y,X)){de("auto"),U.current=!0;return}Zi(me,Y),W.current=lo(Y),ce(),U.current=!0}},[c,X,ue.length,de,ce]);const Le=()=>{const Y=L.current;Y&&(Ne.current=Y.scrollHeight),Be.current=!0,p==null||p()},Je=()=>{W.current=!0,ne("smooth"),G()},Se=()=>{ie(),de("smooth"),G()},he=l.useMemo(()=>{const Y=kw(ue),me=ue.map((Ie,Z)=>({type:"message",data:Ie,index:Z,ts:yw(Ie,Z,d),stableKey:Y[Z]}));if(!s||s.length===0)return me;const fe=[...s].sort((Ie,Z)=>Ie.timestamp-Z.timestamp).map((Ie,Z)=>({type:"action",data:Ie,index:Z,ts:Ie.timestamp})),E=[];let oe=0;for(const Ie of me){for(;oe<fe.length&&Ie.ts>0&&fe[oe].ts<Ie.ts;)E.push(fe[oe++]);E.push(Ie)}for(;oe<fe.length;)E.push(fe[oe++]);return E},[ue,s,d]),pe=y>0||!!f,Ee=y>0?y>80?O("chatList.showEarlierMessagesHidden",{count:Math.min(y,80),total:y}):O("chatList.showEarlierMessages",{count:Math.min(y,80)}):b?O("chatList.loadErrorRetry",{error:b}):O("chatList.loadOlderMessages");return n.jsxs("div",{className:"chat-scroll-frame",children:[n.jsx("div",{ref:L,"data-chat-scroll":!0,className:"chat-container",children:n.jsxs("div",{ref:R,className:"chat-container-content",children:[g&&n.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:O("chatList.loadingOlderMessages")}),pe&&!g&&n.jsx("div",{className:"text-center py-2",children:n.jsx("button",{type:"button",onClick:Le,className:`text-2xs rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${b&&y===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:Ee})}),he.length===0&&!pe&&(h||n.jsx("div",{className:"text-center mt-16 opacity-20 text-xxs",children:O("chatList.waitingForMessages")})),he.map(Y=>{if(Y.type==="action"){const se=Y.data;return n.jsx(Yw,{log:se},`action-${Y.index}`)}const me=Y.data;Y.index;const fe=Y.stableKey,E=me.receivedAt||d[vi(me)],oe=`${c}-${fe}`,Ie=M.has(oe),Z=Sw(me)??fe;return n.jsx(Zw,{message:me,receivedAt:E,agentName:r,userName:o,isCliMode:a,isTextExpanded:Ie,onSendNow:v,isSendingNow:C,onCancelQueued:x,toolExpand:_==null?void 0:_[Z],onExpandToolBlock:S?se=>S(Z,se):void 0,onCollapseToolBlock:w?()=>w(Z):void 0,onToggleTextExpanded:()=>D(se=>{const ye=new Set(se);return Ie?ye.delete(oe):ye.add(oe),ye})},`msg-${fe}`)}),i&&n.jsx("div",{className:"self-start chat-typing-wrapper",children:n.jsxs("div",{className:"typing-indicator",children:[n.jsx("div",{className:"dot"}),n.jsx("div",{className:"dot"}),n.jsx("div",{className:"dot"}),n.jsx("span",{className:"text-2xs text-text-muted ml-1",children:O("chatList.agentGenerating")})]})}),n.jsx("div",{className:"min-h-10",ref:F})]})}),(P.showTop||P.showBottom)&&n.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":O("chatList.jumpToTop"),children:[P.showTop&&n.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:Je,"aria-label":O("chatList.jumpToOldestMessages"),title:O("chatList.jumpToTop"),children:O("chatList.top")}),P.showBottom&&n.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:Se,"aria-label":O("chatList.jumpToLatestMessages"),title:O("chatList.jumpToBottom"),children:O("chatList.latest")})]})]})}),t0=l.memo(e0,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.showActivityMessages===t.showActivityMessages&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible&&e.onSendNow===t.onSendNow&&e.isSendingNow===t.isSendingNow&&e.onCancelQueued===t.onCancelQueued&&e.toolExpansions===t.toolExpansions&&e.onExpandToolBlock===t.onExpandToolBlock&&e.onCollapseToolBlock===t.onCollapseToolBlock),n0="modulepreload",s0=function(e){return"/"+e},Lu={},kr=function(t,s,r){let o=Promise.resolve();if(s&&s.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));o=Promise.allSettled(s.map(d=>{if(d=s0(d),d in Lu)return;Lu[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":n0,u||(h.as="script"),h.crossOrigin="",h.href=d,c&&h.setAttribute("nonce",c),document.head.appendChild(h),u)return new Promise((p,g)=>{h.addEventListener("load",p),h.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function a(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return o.then(i=>{for(const c of i||[])c.status==="rejected"&&a(c.reason);return t().catch(a)})};let Eu=!1;const nf=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:s,fontSize:r=13,readOnly:o=!1,sizingMode:a="measured"},i)=>{const c=l.useRef(null),[d,u]=l.useState(null),m=l.useRef([]),h=l.useRef(!1),p=l.useRef(!1),g=l.useRef(!1),f=l.useRef(!1),y=()=>{const b=c.current;if(b){h.current&&(b.clear(),h.current=!1);for(const k of m.current)b.write(k.data,k.onProcessed);m.current=[],p.current&&(b.fit(),p.current=!1),g.current&&(b.bumpResize(),g.current=!1),f.current&&(b.scrollToTop(),f.current=!1)}};return l.useImperativeHandle(i,()=>({write:(b,k)=>{c.current?c.current.write(b,k):m.current.push({data:b,onProcessed:k})},clear:()=>{c.current?c.current.clear():(m.current=[],h.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(m.current=[],h.current=!0)},resize:(b,k)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(b,k)},fit:()=>{c.current?c.current.fit():p.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():g.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():f.current=!0},getSelection:()=>{var b,k;return((k=(b=c.current)==null?void 0:b.getSelection)==null?void 0:k.call(b))||""},getVisibleText:()=>{var b,k;return((k=(b=c.current)==null?void 0:b.getVisibleText)==null?void 0:k.call(b))||""}}),[]),l.useEffect(()=>{d&&y()},[d]),l.useEffect(()=>{let b=!1;return kr(()=>import("./terminal-COe_yvHR.js"),__vite__mapDeps([0,1,2])).then(k=>{Eu||(Eu=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),b||u(()=>k.GhosttyTerminalView)}).catch(k=>{console.error("[CliTerminal] failed to load terminal renderer",k)}),()=>{b=!0}},[]),d?n.jsx(d,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:s,fontSize:r,readOnly:o,sizingMode:a,className:"w-full h-full rounded-lg overflow-hidden"}):n.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});nf.displayName="CliTerminal";function xt(...e){return Ex(Dx(e))}const r0={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},o0={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},wn=l.forwardRef(function({radius:t="xl",padding:s="md",className:r,...o},a){return n.jsx("div",{ref:a,className:xt("border border-border-subtle bg-bg-secondary",r0[t],o0[s],r),...o})});function Xo({label:e,value:t,sub:s,icon:r}){return n.jsxs(wn,{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsx("span",{className:"text-base flex items-center",children:r}),n.jsx("span",{className:"text-3xs text-text-muted uppercase tracking-wide font-semibold",children:e})]}),n.jsx("div",{className:"text-[22px] leading-[30px] font-bold text-text-primary tracking-tight",children:t}),s&&n.jsx("div",{className:"text-2xs text-text-muted mt-0.5",children:s})]})}function sf({title:e,description:t,confirmLabel:s,cancelLabel:r,tone:o="default",busy:a=!1,onConfirm:i,onCancel:c}){const{t:d}=ve("common");l.useEffect(()=>{const m=h=>{h.key==="Escape"&&c()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[c]);const u=n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 backdrop-blur-[2px] p-4",role:"dialog","aria-modal":"true","aria-labelledby":"confirm-dialog-title",onClick:m=>{m.target===m.currentTarget&&c()},children:n.jsxs("div",{className:"w-full max-w-sm rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden",children:[n.jsxs("div",{className:"px-5 py-4",children:[n.jsx("div",{id:"confirm-dialog-title",className:"text-sm font-semibold text-text-primary",children:e}),t&&n.jsx("div",{className:"mt-1.5 text-xs text-text-secondary whitespace-pre-line break-words",children:t})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-border-subtle",children:[n.jsx("button",{type:"button",className:"btn btn-secondary h-9 px-4 text-sm",disabled:a,onClick:c,children:r??d("common.cancel")}),n.jsx("button",{type:"button",autoFocus:!0,className:`btn ${o==="danger"?"btn-danger":"btn-primary"} h-9 px-4 text-sm font-semibold`,disabled:a,onClick:i,children:s})]})]})});return Qn.createPortal(u,document.body)}function ud(e){if(!e||typeof e!="object")return;const t=e;return"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Fr(){const[e,t]=l.useState(null),s=l.useRef(null),r=l.useCallback(i=>{t(null);const c=s.current;s.current=null,c==null||c(i)},[]),o=l.useCallback(i=>new Promise(c=>{var d;(d=s.current)==null||d.call(s,!1),s.current=c,t(i)}),[]);l.useEffect(()=>()=>{var i;(i=s.current)==null||i.call(s,!1)},[]);const a=e?n.jsx(sf,{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 Du({value:e,max:t,label:s,color:r="#8b5cf6",detail:o,compact:a=!1}){const i=t>0?Math.min(Math.round(e/t*100),100):0,c=i>85?"#ef4444":i>60?"var(--status-warning)":r;return a?n.jsxs("div",{className:"flex-1",children:[n.jsxs("div",{className:"flex justify-between mb-0.5",children:[n.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide font-semibold",children:s}),n.jsxs("span",{className:"text-3xs text-text-secondary font-semibold",children:[i,"%"]})]}),n.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:n.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${i}%`,background:c}})})]}):n.jsxs("div",{className:"flex-1",children:[n.jsxs("div",{className:"flex justify-between mb-1.5",children:[n.jsx("span",{className:"text-2xs text-text-secondary font-medium",children:s}),n.jsxs("span",{className:"text-xxs text-text-primary font-bold",children:[i,"%"]})]}),n.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:n.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${i}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),o&&n.jsx("div",{className:"text-3xs text-text-muted mt-0.5",children:o})]})}function a0({cursorPos:e,viewportRef:t,imgRef:s}){var j;if(!e||!s.current)return null;const r=s.current,o=r.getBoundingClientRect(),a=(j=t.current)==null?void 0:j.getBoundingClientRect();if(!a)return null;const i=r.naturalWidth||o.width,c=r.naturalHeight||o.height,d=i/c,u=o.width/o.height;let m,h,p,g;d>u?(m=o.width,h=o.width/d,p=0,g=(o.height-h)/2):(h=o.height,m=o.height*d,p=(o.width-m)/2,g=0);const f=o.left-a.left+p+m*e.nx,y=o.top-a.top+g+h*e.ny,b=Math.max(8,Math.min(a.width-8,f)),k=Math.max(8,Math.min(a.height-8,y));return n.jsxs("div",{style:{position:"absolute",left:b-8,top:k-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[n.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),n.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),n.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function nl(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function i0({inputMode:e,onToggleInputMode:t,isImeOpen:s,setIsImeOpen:r,isMenuOpen:o,setIsMenuOpen:a,imeText:i,setImeText:c,handleImeSubmit:d,isConnActive:u,zoom:m,isMobile:h,mobileFillZoom:p,onZoomOut:g,onZoomReset:f,onZoomIn:y,transportType:b,screenshotUsage:k,lastActionStatus:j}){const{t:v}=ve("common");return n.jsxs(n.Fragment,{children:[n.jsxs("div",{onTouchStart:C=>C.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:nl(t),className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[n.jsx("span",{className:"text-sm",children:e==="mouse"?n.jsx(qp,{size:14}):n.jsx(mw,{size:14})}),n.jsx("span",{className:`text-3xs font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:v(e==="mouse"?"remote.mouse":"remote.touch")})]}),n.jsxs("div",{className:"relative",children:[n.jsx("div",{role:"button",tabIndex:0,onClick:()=>{r(C=>!C),a(!1)},onKeyDown:nl(()=>{r(C=>!C),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(Up,{size:14})})}),s&&n.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:n.jsx("input",{type:"text",placeholder:v("remote.typeAndEnter"),value:i,autoFocus:!0,onTouchStart:C=>C.stopPropagation(),onChange:C=>c(C.target.value),onKeyDown:C=>{d(C)},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(C=>!C),r(!1)},onKeyDown:nl(()=>{a(C=>!C),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(Dr,{size:14})})})}),n.jsx("div",{className:"w-px h-[18px] bg-white/10"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:u?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[n.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:u?"#22c55e":"#eab308",boxShadow:u?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),n.jsx("span",{className:"text-5xs font-extrabold",style:{color:u?"#22c55e":"#eab308"},children:v(u?"remote.connected":"remote.ws")})]}),m>1&&n.jsxs("span",{className:"text-5xs font-bold text-indigo-400",children:[Math.round(m*100),"%"]}),b==="direct"&&n.jsx("span",{className:"text-5xs font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:v("remote.directP2PTitle"),children:v("remote.direct")}),b==="relay"&&n.jsx("span",{className:"text-5xs font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:v("remote.turnRelayTitle"),children:v("remote.relay")}),k&&k.dailyBudgetMinutes>0&&n.jsx("span",{className:"text-5xs font-bold px-1 py-0.5 rounded",style:{color:k.budgetExhausted?"#ef4444":"#c4b5fd",background:k.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:v("remote.dailyTurnTitle"),children:k.budgetExhausted?v("remote.turnBlocked"):v("remote.turnUsage",{used:k.dailyUsedMinutes,budget:k.dailyBudgetMinutes})}),j&&n.jsx("span",{className:"text-5xs text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:j})]})]}),o&&n.jsxs("div",{onTouchStart:C=>C.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[n.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:v("remote.settings")}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[n.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:[v("remote.zoom")," ",m<=(h?p:1)+.01?v(h?"remote.fill":"remote.fit"):`${Math.round(m*100)}%`]}),n.jsxs("div",{style:{display:"flex",gap:4},children:[n.jsx("button",{onClick:C=>{C.stopPropagation(),g()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),n.jsx("button",{onClick:C=>{C.stopPropagation(),f()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:v(h?"remote.fill":"remote.fit")}),n.jsx("button",{onClick:C=>{C.stopPropagation(),y()},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 l0({waitingLabel:e,waitingHint:t,transportType:s}){const{t:r}=ve("common");return n.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[n.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:n.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),n.jsx("div",{className:"text-white/85 text-xxs font-semibold tracking-wide",children:e}),n.jsx("div",{className:"text-2xs text-white/40",children:t}),s==="relay"&&n.jsx("div",{className:"text-3xs font-medium",style:{color:"var(--status-warning)",opacity:.8},children:r("remote.waitingState.turnRelayActive")})]})}function c0({connState:e,onRetry:t}){const{t:s}=ve("common"),r=e==="failed"?"remote.error.reasonFailed":"remote.error.reasonDisconnected";return n.jsxs("div",{"data-testid":"remote-error-state",className:"text-center flex flex-col items-center gap-3 px-6",children:[n.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-red-500/25 bg-red-500/10 shadow-[0_10px_30px_rgba(0,0,0,0.35)]",children:n.jsx(an,{size:22,className:"text-red-400"})}),n.jsx("div",{className:"text-white/90 text-[13px] leading-[1.45] font-semibold tracking-wide",children:s("remote.error.title")}),n.jsx("div",{className:"text-2xs text-white/50 max-w-[260px]",children:s(r)}),t&&n.jsxs("button",{type:"button",onClick:t,className:"mt-1 h-8 px-3.5 rounded-lg flex items-center gap-1.5 bg-white/[0.08] border border-white/15 text-white/90 text-2xs font-bold hover:bg-white/[0.14] transition-colors",children:[n.jsx(Or,{size:13}),s("remote.error.retry")]})]})}function d0(){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 Ou(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 Lo(e,t){const s=l.useRef(null),r=l.useRef(0);l.useEffect(()=>{if(!d0())return;r.current+=1;const o=s.current;if(!o){console.debug(`[render-trace] ${e}#${r.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,c])=>[i,Ou(c)]))}),s.current=t;return}const a=Object.keys({...o,...t}).filter(i=>!Object.is(o[i],t[i]));a.length>0&&console.debug(`[render-trace] ${e}#${r.current}`,{changed:a,snapshot:Object.fromEntries(a.map(i=>[i,Ou(t[i])]))}),s.current=t})}function u0({containerRef:e,viewportRef:t,imgRef:s,inputMode:r,setInputMode:o,minZoom:a,zoomRef:i,panXRef:c,panYRef:d,setPanX:u,setPanY:m,setZoom:h,lastWheelTimeRef:p,onAction:g,setLastActionStatus:f,spawnRippleFromNormalized:y,clampPan:b,isMobile:k,mobileFillZoom:j}){const[v,C]=l.useState(null),x=l.useRef(null),S=l.useRef(null),w=l.useRef(null),_=l.useRef(!1),A=l.useRef(null),O=l.useRef(0),L=l.useRef(null),R=l.useRef(1),F=l.useRef({x:0,y:0}),N=l.useRef(!1),I=l.useRef(r),B=l.useRef(g),T=30,H=550,q=18,J=60,K=400,M=12,D=()=>{if(x.current)return;const W={nx:.5,ny:.5};x.current=W,C(W)};return l.useEffect(()=>{I.current=r,r==="mouse"&&D()},[r]),l.useEffect(()=>{B.current=g},[g]),l.useEffect(()=>{const W=e.current;if(!W)return;const U=de=>{if(!s.current)return null;const ne=s.current.getBoundingClientRect();return!ne.width||!ne.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-ne.left)/ne.width)),ny:Math.max(0,Math.min(1,(de.clientY-ne.top)/ne.height))}},ae=(de,ne)=>{if(!s.current)return{dnx:0,dny:0};const ee=s.current,ue=ee.getBoundingClientRect(),je=ee.naturalWidth||ue.width,X=ee.naturalHeight||ue.height,G=je/X,z=ue.width/ue.height;let ie,Ne;return G>z?(ie=ue.width,Ne=ue.width/G):(Ne=ue.height,ie=ue.height*G),{dnx:de/ie,dny:ne/Ne}},be=(de,ne,ee)=>{if(ee<=1.05)return;const ue=-(de-.5)*100,je=-(ne-.5)*100,X=b(ue,je,ee);(Math.abs(X.x-c.current)>.1||Math.abs(X.y-d.current)>.1)&&(u(X.x),m(X.y),c.current=X.x,d.current=X.y)},V=de=>{const ne=t.current;if(ne&&de.target instanceof Node&&ne.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const ee=de.touches[0];S.current={x:ee.clientX,y:ee.clientY,time:Date.now()},w.current={x:ee.clientX,y:ee.clientY},N.current||(_.current=!1),A.current=setTimeout(()=>{if(!_.current&&!N.current)if(_.current=!0,I.current==="mouse"){const ue=x.current||{nx:.5,ny:.5};f("Right Click"),y(ue.nx,ue.ny,"right"),B.current("input_click",{...ue,button:"right"}).catch(()=>{})}else{const ue=U(ee);ue&&(f("Right Click"),y(ue.nx,ue.ny,"right"),B.current("input_click",{...ue,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){A.current&&clearTimeout(A.current),_.current=!0,N.current=!0;const ee=de.touches[1].clientX-de.touches[0].clientX,ue=de.touches[1].clientY-de.touches[0].clientY;L.current=Math.sqrt(ee*ee+ue*ue),R.current=i.current,F.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},we=de=>{const ne=t.current;if(ne&&de.target instanceof Node&&ne.contains(de.target)&&de.preventDefault(),de.touches.length===1&&w.current){const ee=de.touches[0],ue=ee.clientX-w.current.x,je=ee.clientY-w.current.y;if(!_.current&&S.current){const X=ee.clientX-S.current.x,G=ee.clientY-S.current.y;Math.sqrt(X*X+G*G)>8&&(_.current=!0,A.current&&clearTimeout(A.current))}if(_.current)if(I.current==="mouse"){const X=ae(ue,je),G=x.current||{nx:.5,ny:.5},z=Math.max(0,Math.min(1,G.nx+X.dnx)),ie=Math.max(0,Math.min(1,G.ny+X.dny));x.current={nx:z,ny:ie},C({nx:z,ny:ie}),f(`Cursor: ${Math.round(z*100)}%, ${Math.round(ie*100)}%`),be(z,ie,i.current);const Ne=Date.now();Ne-p.current>=30&&(p.current=Ne,B.current("input_mouseMoved",{nx:z,ny:ie}).catch(()=>{}))}else if(i.current>1){const X=t.current;if(X){const G=X.clientWidth,z=X.clientHeight,ie=c.current+ue/G*100,Ne=d.current+je/z*100,Be=b(ie,Ne,i.current);u(Be.x),m(Be.y),c.current=Be.x,d.current=Be.y}}else{const X=U(ee);if(X){const G=Date.now();G-p.current>=40&&(p.current=G,f("Scroll"),B.current("input_wheel",{nx:X.nx,ny:X.ny,deltaX:Math.round(-ue*2.5),deltaY:Math.round(-je*2.5)}).catch(()=>{}))}}w.current={x:ee.clientX,y:ee.clientY};return}if(de.touches.length===2&&L.current!==null){const ee=de.touches[1].clientX-de.touches[0].clientX,ue=de.touches[1].clientY-de.touches[0].clientY,X=Math.sqrt(ee*ee+ue*ue)/L.current,G=(de.touches[0].clientX+de.touches[1].clientX)/2,z=(de.touches[0].clientY+de.touches[1].clientY)/2,ie=G-F.current.x,Ne=z-F.current.y,Be=Math.abs(X-1)>.03;if(I.current==="mouse"){if(Be){const Le=Math.max(a,Math.min(5,R.current*X));h(Le),i.current=Le}else if(Math.abs(ie)>2||Math.abs(Ne)>2){const Le=x.current||{nx:.5,ny:.5},Je=Date.now();Je-p.current>=30&&(p.current=Je,f("Scroll"),B.current("input_wheel",{nx:Le.nx,ny:Le.ny,deltaX:Math.round(-ie*3),deltaY:Math.round(-Ne*3)}).catch(()=>{}))}}else{const Le=Math.max(a,Math.min(5,R.current*X));h(Le),i.current=Le;const Je=t.current;if(Je&&Le>1){const Se=Je.clientWidth,he=Je.clientHeight,pe=c.current+ie/Se*100,Ee=d.current+Ne/he*100,Y=b(pe,Ee,Le);u(Y.x),m(Y.y),c.current=Y.x,d.current=Y.y}}F.current={x:G,y:z}}},ce=de=>{var ne;if(A.current&&clearTimeout(A.current),L.current=null,de.touches.length===1&&N.current){const ee=de.touches[0];S.current={x:ee.clientX,y:ee.clientY,time:Date.now()},w.current={x:ee.clientX,y:ee.clientY},_.current=!0;return}if(de.touches.length===0){if(N.current){N.current=!1,_.current=!1;return}if(de.changedTouches.length===1){const ee=de.changedTouches[0],ue=Date.now(),je=ue-(((ne=S.current)==null?void 0:ne.time)||0),X=S.current?ee.clientX-S.current.x:0,G=S.current?ee.clientY-S.current.y:0,z=Math.sqrt(X*X+G*G);if(I.current==="mouse"){if(je<T||je>H||z>q){_.current=!1;return}const ie=x.current||U(ee);ie&&(f(`Click: ${Math.round(ie.nx*100)}%, ${Math.round(ie.ny*100)}%`),y(ie.nx,ie.ny,"left"),B.current("input_click",{...ie}).catch(()=>{}))}else{if(_.current){_.current=!1;return}if(je<J||je>K||z>M){_.current=!1;return}const ie=U(ee);if(!ie)return;ue-O.current<300?(f("Double tap"),y(ie.nx,ie.ny,"double"),B.current("input_click",{...ie,clickCount:2}).catch(()=>{}),O.current=0):(f(`Tap: ${Math.round(ie.nx*100)}%, ${Math.round(ie.ny*100)}%`),y(ie.nx,ie.ny,"left"),B.current("input_click",{...ie}).catch(()=>{}),O.current=ue)}}_.current=!1}};return W.addEventListener("touchstart",V,{passive:!1}),W.addEventListener("touchmove",we,{passive:!1}),W.addEventListener("touchend",ce,{passive:!1}),()=>{W.removeEventListener("touchstart",V),W.removeEventListener("touchmove",we),W.removeEventListener("touchend",ce),A.current&&clearTimeout(A.current)}},[e,t,s,a,i,c,d,u,m,h,p,f,y,b]),{cursorPos:v,cursorPosRef:x,handleToggleInputMode:()=>{o(W=>{const U=W==="touch"?"mouse":"touch";return U==="mouse"&&D(),U})},handleZoomReset:()=>{const W=k?j:1;h(W),i.current=W,u(0),m(0),c.current=0,d.current=0}}}const m0=15e3;function rf({onAction:e,addLog:t,connState:s,connScreenshot:r,screenshotUsage:o,transportType:a,onRetry:i}){const{t:c}=ve("common"),d=l.useRef(null),u=l.useRef(null),m=l.useRef(null),[h,p]=l.useState(null),[g,f]=l.useState(""),[,y]=l.useState(!1),[b,k]=l.useState(!1),[j,v]=l.useState(!1),[C,x]=l.useState([]),S=l.useRef(0),w=l.useRef(new Set),[_,A]=l.useState(!1),[O,L]=l.useState(!1),R=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[F,N]=l.useState(R?"mouse":"touch"),[I,B]=l.useState(1),T=l.useRef(!1),[H,q]=l.useState(1),[J,K]=l.useState(0),[M,D]=l.useState(0);Lo("RemoteView",{connState:s,hasScreenshot:!!r,inputMode:F,zoom:H,panX:J,panY:M,isMenuOpen:_,isImeOpen:O});const P=l.useRef(0),$=l.useRef(H),W=l.useRef(J),U=l.useRef(M);l.useEffect(()=>{$.current=H},[H]),l.useEffect(()=>{W.current=J},[J]),l.useEffect(()=>{U.current=M},[M]),l.useEffect(()=>{var Se;(Se=d.current)==null||Se.focus()},[]),l.useEffect(()=>{s!=="connected"&&k(!1)},[s]),l.useEffect(()=>{if(s==="connected"){v(!1);return}v(!1);const Se=setTimeout(()=>v(!0),m0);return()=>clearTimeout(Se)},[s]);const ae=s==="connected",be=r,V=s==="failed"||s==="disconnected"&&j,we=c(ae?"remote.waiting.connectedLabel":s==="connecting"?"remote.waiting.connectingLabel":"remote.waiting.reconnectingLabel"),ce=c(ae?"remote.waiting.connectedHint":"remote.waiting.reconnectingHint");l.useEffect(()=>{if(!R||T.current||!be)return;const Se=m.current,he=u.current;if(!Se||!he)return;const pe=()=>{const Ee=he.clientWidth,Y=he.clientHeight,me=Se.naturalWidth,fe=Se.naturalHeight;if(!me||!fe||!Ee||!Y)return;const E=Math.min(Ee/me,Y/fe),Ie=Math.max(Ee/me,Y/fe)/E;Ie>1.01&&(B(Ie),q(Ie),$.current=Ie),T.current=!0};if(Se.complete&&Se.naturalWidth){pe();return}return Se.addEventListener("load",pe,{once:!0}),()=>Se.removeEventListener("load",pe)},[be,R]);const de=.5;l.useEffect(()=>{H<=de&&(K(0),D(0))},[H,de]);const ne=(Se,he,pe)=>{if(pe<=de)return{x:0,y:0};const Ee=(pe-1)/(2*pe)*100,Y=(pe-1)/(2*pe)*100;return{x:Math.max(-Ee,Math.min(Ee,Se)),y:Math.max(-Y,Math.min(Y,he))}},ee=(Se,he)=>{if(!m.current)return null;const pe=m.current.getBoundingClientRect();return!pe.width||!pe.height?null:{nx:Math.max(0,Math.min(1,(Se-pe.left)/pe.width)),ny:Math.max(0,Math.min(1,(he-pe.top)/pe.height))}},ue=Se=>{const he=setTimeout(()=>{w.current.delete(he),x(pe=>pe.filter(Ee=>Ee.id!==Se))},600);w.current.add(he)};l.useEffect(()=>{const Se=w.current;return()=>{for(const he of Se)clearTimeout(he);Se.clear()}},[]);const je=(Se,he,pe)=>{const Ee=u.current;if(!Ee)return;const Y=Ee.getBoundingClientRect(),me=++S.current;x(fe=>[...fe,{id:me,x:Se-Y.left,y:he-Y.top,type:pe}]),ue(me)},X=(Se,he,pe)=>{const Ee=m.current,Y=u.current;if(!Ee||!Y)return;const me=Ee.getBoundingClientRect(),fe=Y.getBoundingClientRect(),E=Ee.naturalWidth||me.width,oe=Ee.naturalHeight||me.height,Ie=E/oe,Z=me.width/me.height;let se,ye,Fe,Me;Ie>Z?(se=me.width,ye=me.width/Ie,Fe=0,Me=(me.height-ye)/2):(ye=me.height,se=me.height*Ie,Fe=(me.width-se)/2,Me=0);const De=me.left-fe.left+Fe+se*Se,Te=me.top-fe.top+Me+ye*he,He=++S.current;x(tt=>[...tt,{id:He,x:De,y:Te,type:pe}]),ue(He)},G=async Se=>{var pe;const he=ee(Se.clientX,Se.clientY);if(he){p(`Click: ${Math.round(he.nx*100)}%, ${Math.round(he.ny*100)}%`),(pe=d.current)==null||pe.focus(),k(!0);try{const Ee=await e("input_click",{nx:he.nx,ny:he.ny});if(!(Ee!=null&&Ee.success)){t(`❌ Click failed: ${Ee==null?void 0:Ee.error}`);return}je(Se.clientX,Se.clientY,"left")}catch(Ee){t(`❌ Click error: ${Ee.message||Ee}`)}}},z=async(Se,he,pe,Ee=0)=>{try{await e("input_key",{type:pe?"char":"keyDown",key:Se,code:he,text:pe?Se:void 0,unmodifiedText:pe?Se:void 0,modifiers:Ee})}catch(Y){t(`❌ Key error: ${Y.message||Y}`)}},ie=async Se=>{if(Se.target.tagName==="INPUT"||!b||Se.key==="Escape")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter"].includes(Se.key)&&Se.preventDefault();let pe=0;Se.altKey&&(pe|=1),Se.ctrlKey&&(pe|=2),Se.metaKey&&(pe|=4),Se.shiftKey&&(pe|=8),p(`Key: ${Se.key}`),await z(Se.key,Se.code,Se.key.length===1,pe)},Ne=async Se=>{if(Se.key==="Enter"){if(Se.nativeEvent.isComposing)return;if(g){const he=g;f(""),p(`IME Sent: ${he}`);try{const pe=await e("input_type",{text:he});pe!=null&&pe.success||t(`❌ IME error: ${pe==null?void 0:pe.error}`)}catch(pe){t(`❌ IME error: ${pe.message}`)}}else p("Key: Enter"),await z("Enter","Enter",!1)}};l.useEffect(()=>{const Se=d.current;if(!Se)return;const he=pe=>{var Ee;if((Ee=m.current)!=null&&Ee.contains(pe.target)){pe.preventDefault();const Y=Date.now();if(Y-P.current<40)return;P.current=Y;const me=ee(pe.clientX,pe.clientY);if(!me)return;p(`Scroll: ${Math.round(pe.deltaY)}`),e("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(pe.deltaX),deltaY:Math.round(pe.deltaY)}).catch(()=>{})}};return Se.addEventListener("wheel",he,{passive:!1}),()=>Se.removeEventListener("wheel",he)},[e]);const{cursorPos:Be,handleToggleInputMode:Le,handleZoomReset:Je}=u0({containerRef:d,viewportRef:u,imgRef:m,inputMode:F,setInputMode:N,minZoom:de,zoomRef:$,panXRef:W,panYRef:U,setPanX:K,setPanY:D,setZoom:q,lastWheelTimeRef:P,onAction:e,setLastActionStatus:p,spawnRippleFromNormalized:X,clampPan:ne,isMobile:R,mobileFillZoom:I});return n.jsxs("div",{ref:d,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ie,onContextMenu:Se=>Se.preventDefault(),onFocus:()=>y(!0),onBlur:()=>y(!1),tabIndex:0,children:[n.jsxs("div",{ref:u,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[V?n.jsx(c0,{connState:s,onRetry:i}):be?n.jsx("img",{ref:m,src:be,alt:c("remote.screenshotAlt"),style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${H}) translate(${J}%, ${M}%)`,transformOrigin:"center center",cursor:F==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:G,onContextMenu:Se=>Se.preventDefault(),onDragStart:Se=>Se.preventDefault()}):n.jsx(l0,{waitingLabel:we,waitingHint:ce,transportType:a}),F==="mouse"&&!V&&be&&n.jsx(a0,{cursorPos:Be,viewportRef:u,imgRef:m}),C.map(Se=>{const pe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[Se.type];return n.jsxs("div",{style:{position:"absolute",left:Se.x,top:Se.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[n.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${pe}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),n.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${pe}, 0.9)`,boxShadow:`0 0 12px rgba(${pe}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},Se.id)})]}),n.jsx(i0,{inputMode:F,onToggleInputMode:Le,isImeOpen:O,setIsImeOpen:L,isMenuOpen:_,setIsMenuOpen:A,imeText:g,setImeText:f,handleImeSubmit:Ne,isConnActive:ae,zoom:H,isMobile:R,mobileFillZoom:I,onZoomOut:()=>q(Se=>Math.max(.5,Se-.25)),onZoomReset:Je,onZoomIn:()=>q(Se=>Math.min(5,Se+.25)),transportType:a,screenshotUsage:o,lastActionStatus:h}),n.jsx("style",{children:`
|
|
9
|
-
@keyframes slideUp {
|
|
10
|
-
from { opacity: 0; transform: translateY(6px); }
|
|
11
|
-
to { opacity: 1; transform: translateY(0); }
|
|
12
|
-
}
|
|
13
|
-
@keyframes slideUpSidebar {
|
|
14
|
-
from { opacity: 0; transform: translateY(6px); }
|
|
15
|
-
to { opacity: 1; transform: translateY(0); }
|
|
16
|
-
}
|
|
17
|
-
@keyframes click-ripple-ring {
|
|
18
|
-
0% { transform: scale(0.3); opacity: 1; }
|
|
19
|
-
100% { transform: scale(2.2); opacity: 0; }
|
|
20
|
-
}
|
|
21
|
-
@keyframes click-ripple-dot {
|
|
22
|
-
0% { transform: scale(1); opacity: 0.9; }
|
|
23
|
-
50% { transform: scale(1.8); opacity: 0.6; }
|
|
24
|
-
100% { transform: scale(0.5); opacity: 0; }
|
|
25
|
-
}
|
|
26
|
-
@keyframes remote-float {
|
|
27
|
-
0% { transform: translateY(0px); }
|
|
28
|
-
50% { transform: translateY(-7px); }
|
|
29
|
-
100% { transform: translateY(0px); }
|
|
30
|
-
}
|
|
31
|
-
`})]})}function ac(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 h0(e){var t;return ac(e.activeInteractivePrompt)||ac((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function p0(e){return e.sessionId||e.instanceId||e.id}function f0(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=h0(a);if(!i)continue;const c=p0(a);if(r&&r!==c&&r!==a.id||!o&&a.surfaceHidden===!0)continue;return{daemonId:a.daemonId||a.id.split(":")[0]||a.id,sessionId:c,routeId:a.id,providerType:a.type,title:a.title||a.cliName||a.type,prompt:i}}return null}function of(e,t){var r;const s={};for(const o of e.questions){const a=t[o.questionId]||{},i=Array.from(new Set((a.selectedLabels||[]).map(d=>d.trim()).filter(Boolean))),c=(r=a.freeformText)==null?void 0:r.trim();s[o.questionId]={selectedLabels:i,...c?{freeformText:c}:{}}}return{promptId:e.promptId,answers:s}}function es({children:e}){return typeof document>"u"?n.jsx(n.Fragment,{children:e}):Qn.createPortal(e,document.body)}function g0(e,t){const s=r=>{r.key==="Escape"&&(r.stopPropagation(),t())};return e.addEventListener("keydown",s,!0),()=>e.removeEventListener("keydown",s,!0)}const Fu='a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',b0=200;function $u(e){const t={};for(const s of(e==null?void 0:e.prompt.questions)||[])t[s.questionId]={selectedLabels:[],freeformText:""};return t}function Hu(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 x0({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(gi,{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 md({promptSession:e,isSubmitting:t=!1,error:s,onSubmit:r,onCancel:o}){const{t:a}=ve("common"),[i,c]=l.useState(()=>$u(e)),[d,u]=l.useState(!1),m=l.useRef(!1),h=l.useRef(null),p="interactive-prompt-title";l.useEffect(()=>{if(c($u(e)),u(!1),m.current=!1,!(e==null?void 0:e.prompt.promptId))return;const A=setTimeout(()=>{m.current=!0,u(!0)},b0);return()=>clearTimeout(A)},[e==null?void 0:e.prompt.promptId]),l.useEffect(()=>{if(e)return g0(window,o)},[e,o]);const g=e==null?void 0:e.prompt.promptId,f=e==null?void 0:e.sessionId,y=e==null?void 0:e.daemonId;l.useEffect(()=>{if(!g)return;const _=h.current;if(!_)return;const A=()=>Array.from(_.querySelectorAll(Fu)),O=L=>{if(L.key!=="Tab")return;const R=A();if(R.length===0)return;const F=R[0],N=R[R.length-1],I=document.activeElement;L.shiftKey?(I===F||!_.contains(I))&&(L.preventDefault(),N.focus()):(I===N||!_.contains(I))&&(L.preventDefault(),F.focus())};return _.addEventListener("keydown",O),()=>_.removeEventListener("keydown",O)},[g,f,y]),l.useEffect(()=>{if(!g)return;const _=h.current;if(!_)return;const A=document.activeElement;if(A instanceof Node&&_.contains(A))return;(Array.from(_.querySelectorAll(Fu))[0]||_).focus()},[g,f,y]);const b=(e==null?void 0:e.prompt.questions)||[],k=b.length===1,j=l.useMemo(()=>e?e.prompt.questions.every(_=>Hu(_,i[_.questionId])):!1,[e,i]),v=l.useMemo(()=>b.filter(_=>!Hu(_,i[_.questionId])).length,[b,i]);if(!e)return null;const C=(_,A)=>{c(O=>{const L=O[_.questionId]||{selectedLabels:[]},R=L.selectedLabels||[],F=_.multiSelect?R.includes(A)?R.filter(N=>N!==A):[...R,A]:[A];return{...O,[_.questionId]:{...L,selectedLabels:F}}})},x=(_,A)=>{c(O=>({...O,[_]:{...O[_]||{selectedLabels:[]},freeformText:A}}))},S=()=>{!j||t||!m.current||r(i)},w=of(e.prompt,i);return n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50 px-4 pt-[calc(24px+env(safe-area-inset-top,0px))] pb-[calc(24px+env(safe-area-inset-bottom,0px))]",children:n.jsxs("div",{ref:h,role:"dialog","aria-modal":"true","aria-labelledby":p,tabIndex:-1,className:"flex max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-48px)] w-full max-w-2xl flex-col overflow-hidden rounded-lg border border-border-default bg-surface-primary shadow-2xl outline-none",children:[n.jsxs("div",{className:"flex shrink-0 items-start justify-between gap-4 border-b border-border-default px-5 py-4",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-normal text-status-warning",children:[n.jsx(an,{size:15})," ",a("interactivePrompt.actionRequired")]}),n.jsx("h2",{id:p,className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("button",{type:"button",onClick:o,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":a("interactivePrompt.cancelAria"),children:n.jsx(Bt,{size:16})})})]}),n.jsxs("div",{className:"interactive-prompt-question-list min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-4",children:[b.map((_,A)=>{var R,F;const O=((R=w.answers[_.questionId])==null?void 0:R.selectedLabels)||[],L=_.multiSelect?a("interactivePrompt.multipleChoice"):a("interactivePrompt.singleChoice");return n.jsxs("section",{className:A>0?"space-y-3 border-t border-border-default pt-5":"space-y-3",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[_.header&&n.jsx("span",{className:"text-xs font-semibold uppercase tracking-normal text-text-muted",children:_.header}),n.jsx("span",{className:"rounded-full border border-border-subtle px-2 py-0.5 text-3xs font-semibold uppercase tracking-normal text-text-muted",children:L})]}),n.jsxs("div",{className:"mt-1 text-sm font-semibold text-text-primary",children:[k?"":`${A+1}. `,_.question]}),_.multiSelect&&_.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:_.multiSelect?"group":"radiogroup","aria-label":_.question,children:_.options.map(N=>n.jsx(x0,{label:N.label,description:N.description||N.preview,selected:O.includes(N.label),multiSelect:_.multiSelect,disabled:t,onClick:()=>C(_,N.label)},N.label))}),_.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:((F=i[_.questionId])==null?void 0:F.freeformText)||"",disabled:t,onChange:N=>x(_.questionId,N.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-default bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]},_.questionId)}),s&&n.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:s})]}),n.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border-default px-5 pt-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))]",children:[!j&&v>0&&n.jsx("span",{className:"mr-auto text-xs text-text-muted",children:a("interactivePrompt.answersRequired",{count:v})}),n.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:o,disabled:t,children:a("common.cancel")}),n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:S,disabled:!j||t||!d,children:a(t?"interactivePrompt.submitting":"interactivePrompt.submit")})]})]})})})}function dn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var af=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress","monitor:long_generating"];dn(af);var y0=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];dn(y0);var v0=["p2p_offer","p2p_ice"];dn(v0);var w0=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];dn(w0);var S0=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","beacon_vectors","daemon_mesh_command","p2p_offer","p2p_ice"];dn(S0);var k0=["auth_ok","auth_error","machine_evicted","force_disconnect","token_revoked","version_mismatch","force_update_required","command","agent_command","resolve_action","beacon_vectors_result","daemon_mesh_result","p2p_ready","p2p_offer","p2p_answer","p2p_ice","mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];dn(k0);var j0=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],N0=[...af,...j0];dn(N0);var C0=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];dn(C0);var _0=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];dn(_0);var A0=["p2p_ready","p2p_answer","p2p_ice"];dn(A0);var T0=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];dn(T0);var I0=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];dn(I0);var lf=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];dn(lf);var cf=["ping","pong","p2p_evicted","status_report","status_event","topic_update","topic_update_chunk","session_output","session_output_chunk","session_io_error","command_result","command_result_chunk","response"];dn(cf);[...new Set([...lf,...cf])];var df=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"],M0={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"},R0=new Set(df);function P0(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return R0.has(t)?t:M0[t]??null}var L0=["pending","assigned","completed","failed","cancelled"],E0=["completed","failed","cancelled"],D0=["code_change","validation","live_debug_readonly","launch_app","convergence"],O0=["low","normal","high"],F0=["low","medium","high"],$0=["when_idle","interrupt"],H0=["preserve","stop","delete_stopped","stop_and_delete"],uf=["completed","blocked","failed"],mf=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function cs(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}cs(L0);cs(E0);cs(D0);cs(O0);cs(F0);cs($0);cs(H0);cs(uf);cs(mf);var B0=["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"],W0=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(W0);var U0=["fsm_edge","short_gen_inline","completion_flush_genuine","completion_flush_weak","monitor_final_summary","pre_cleanup_transcript","stall_transcript","startup_grace_collapse","acp_prompt_response","cdp_state","approval_gate","modal_button","mesh_stall_watchdog","status_monitor","pty_exit","provider_error","coordinator_probe","mcp_probe","worker_tool","dispatch","input_service","operator","intentional_cleanup","scheduler","git_probe","session_registry"],K0=["mesh_queue","mesh_direct","plain"],q0=["delivered","queued"],z0=["local","p2p"],G0=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],V0=["default","native_source"],Y0=["restart","live_holder"],Q0=["approval","choice"],J0=["approved","rejected","answered"],X0=["modal_button","auto_approve","prompt_answer"],Z0=["genuine","weak"],eS=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],tS=["completed","aborted"],nS=["alive","unknown","read_failed","dead"],sS=["auth_failed","billing_failed"],rS=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],oS=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],aS=["completed","failed"],iS=["operator_update","refine_terminal","validation_terminal"],lS=["delivered","queued","duplicate"],cS=[...df,"unknown"],hf=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],dS=["completed","failed","cancelled"],uS=["genuine","weak","tool_report","operator"],mS=["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"],pf=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],lr={t:"id"},cr={t:"id",optional:!0},fs={t:"bool"},Zo={t:"bool",optional:!0},Bu={t:"ms"},hS={t:"ms",optional:!0},ea={t:"int",optional:!0},$t=e=>({t:"enum",values:e}),Vr=e=>({t:"enum",values:e,optional:!0}),pS={dispatch_accepted:{scope:$t(K0),messageId:lr,meshId:cr,nodeId:cr,providerType:cr,attemptNo:ea,dispatchNonce:ea,consumeProfile:Vr(V0),maxTaskRetries:ea,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:lr,outcome:$t(q0),via:$t(z0)},delivery_refused:{messageId:lr,reason:$t(B0)},dispatch_failed:{workerAbsent:fs,reason:$t(G0),refusalCode:cr},duplicate_dispatch_refusal:{holderSessionId:lr,holderAttemptId:cr},session_rebound:{toSessionId:lr,reason:$t(Y0)},turn_started:{retro:fs},suspension:{modal:$t(Q0),modalKey:cr},suspension_resolved:{resolution:$t(J0),via:$t(X0)},turn_end:{strength:$t(Z0),afterFinalizationTimeout:Zo,hollow:Zo,summary:{t:"summary_ref",optional:!0},blockReason:Vr(eS),releasedByHardCap:Zo,nativeOutcome:Vr(tS),live:{t:"live",optional:!0},reportExpected:Zo},transcript_final:{selfAttributing:fs,nativeRead:fs,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:hS},transcript_activity:{newestActivityAt:Bu},no_progress:{stalledMs:Bu,observedStatus:$t(cS),finalAssistantPresent:fs},liveness:{result:$t(nS)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:Vr(sS)},session_error:{reason:$t(rS)},worker_report:{outcome:$t(uf),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:fs,branchState:Vr(mf),touchedFileCount:ea},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:fs,commitsSinceDispatch:{t:"int"},attributable:fs},cancel:{reason:$t(oS)},operator_status:{status:$t(aS),reason:$t(iS)},coordinator_ack:{notify:$t(pf),outcome:$t(lS)},hold_expired:{holdId:lr,reason:$t(hf)}},fS=Object.keys(pS);function As(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}As(U0);As(fS);As(mS);As(pf);As(hf);As(dS);As(uS);var gS=["turn.evidence","turn.committed","turn.notify","mesh.record"];As(gS);var bS=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];function $n(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}$n(bS);var xS=["applied","recorded","rejected"];$n(xS);var yS=["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(yS);var vS=["completed","failed"];$n(vS);var wS=["operator_update","refine_terminal","validation_terminal"];$n(wS);var SS=["own","fleet"];$n(SS);var kS=["active","paused","completed","abandoned"];$n(kS);var jS=["magi","coordinator"];$n(jS);var NS=["provider_quirk","pattern_to_avoid","recovery_lesson"];$n(NS);var CS=["coordinator","unknown"];$n(CS);var _S=["gate_claimed","gate_released","gate_abandoned","node_patched"];$n(_S);var AS=["turn_observe","mesh_record","turn_cancel","operator_status","turn_query","mesh_index_query","mission_upsert","mission_query","note_upsert","note_forget","tool_call_record","ledger_query","mission_list_query","record_local","queue_query","queue_enqueue","queue_enqueue_graph","queue_cancel","queue_requeue","direct_dispatch_record","graph_audit_record","active_work_query","recovery_context_query","graph_gate_claim","graph_gate_release","graph_gate_abandon","graph_node_patch","graph_view_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];$n(AS);function TS(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function vn(e,t){return TS(t==null?void 0:t.activeModal)?"waiting_approval":P0(e)??"idle"}function ic(e){return vn(e)==="generating"}function Wu(e,t){return vn(e,t)==="waiting_approval"}function IS(e){return(e==null?void 0:e.surfaceHidden)===!0}function MS(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function or(e){const t=e.connectionState==="failed"||e.connectionState==="closed",s=e.connectionState==="connecting"||e.connectionState==="new",r=hi(e.status),o=vn(e.status),a=o==="waiting_approval",i=o==="waiting_choice",c=Sy(o);return{isReconnecting:t,isConnecting:s,isGenerating:r,isWaiting:a,isWaitingChoice:i,isErrored:c}}function er(e){return or(e).isGenerating}function RS(e){let t=0;for(const s of e)er(s)&&t++;return t}function Uu(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 PS(e,t){const s=e.lastUpdated||0,r=t.lastUpdated||0;if(r!==s)return r>s;const o=Uu(e),a=Uu(t);return a!==o?a>o:!1}function Ku(e,t,s){return e===void 0?t:t===void 0?e:s?t:e}function ff(e){const t=new Map,s=new Map,r=(o,a)=>{if(!o)return;const i=s.get(o),c=t.get(o),d=(a.lastUpdated||0)>((i==null?void 0:i.lastUpdated)||0),u=Ku(c==null?void 0:c.surfaceHidden,typeof a.surfaceHidden=="boolean"?a.surfaceHidden:void 0,d),m=Ku(c==null?void 0:c.muted,typeof a.muted=="boolean"?a.muted:void 0,d);if(i&&!PS(i,a)){c&&t.set(o,{...c,surfaceHidden:u,muted:m});return}s.set(o,a),t.set(o,{sessionId:o,...MS(a),surfaceHidden:u,muted:m})};for(const o of e)if(o.type!=="adhdev-daemon"){r(o.sessionId,o);for(const a of o.childSessions||[])r(a.id,a)}return t}function Ns(e,t){if(e.sessionId){const s=t.get(e.sessionId);if(s)return s}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:void 0,muted:void 0,completionMarker:"",seenCompletionMarker:""}}function Si(e,t,s){const r=Ns(e,t),o=or(e),a=o.isReconnecting,i=o.isConnecting,c=o.isGenerating,d=o.isWaiting,u=o.isWaitingChoice,m=r.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d||u,h=r.inboxBucket==="working"||c,g=!!(r.inboxBucket==="task_complete"&&r.unread&&!(s!=null&&s.hideOpenTaskCompleteUnread&&(s!=null&&s.isOpenConversation)));return{unread:g,requiresAction:m,isWorking:h,isReconnecting:a,isConnecting:i,isGenerating:c,isWaiting:d,inboxBucket:m?"needs_attention":h?"working":g?"task_complete":"idle"}}function LS(e,t,s){return Si(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:s==null?void 0:s.isOpenConversation}).unread}function ES(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function DS(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 OS(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 FS({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(!ES(a))throw new Error(DS(a));return}await OS(e.sessionId,t,o)}let lc=null;const cc=new Set;function $S(e){return cc.add(e),()=>{cc.delete(e)}}function qu(){return lc}function ta(e){if(lc!==e){lc=e;for(const t of cc)t()}}function ki(e,t){const{t:s}=ve("common"),{ides:r,isP2PActive:o,p2pStates:a}=An(),{sendCommand:i}=_t(),c=l.useSyncExternalStore($S,qu,qu),[d,u]=l.useState(!1),[m,h]=l.useState(null),p=l.useRef(!1),g=(t==null?void 0:t.includeHidden)===!0,f=l.useMemo(()=>f0(r,{sessionId:e,includeHidden:g}),[r,e,g]),y=!!f,b=l.useMemo(()=>f?f.prompt.promptId===c?null:f:null,[c,f]),k=(f==null?void 0:f.prompt.promptId)??null;l.useEffect(()=>{h(null)},[k]);const j=l.useCallback(async x=>{if(!b||p.current)return;p.current=!0;const S=of(b.prompt,x);u(!0),h(null);try{const w=(a==null?void 0:a[b.daemonId])==="connected"||o===!0;await FS({promptSession:b,response:S,useP2PCommand:w,sendCommand:i}),ta(b.prompt.promptId)}catch(w){let _=w instanceof Error?w.message:String(w);throw _.includes(vy)?(ta(b.prompt.promptId),h(s("interactivePrompt.errorReviewUnconfirmed",{defaultValue:"The answer keys reached the terminal, but the question is still on screen — the answer may not have been submitted. Check the terminal: if it was not submitted, answer there; resending from here could submit it twice."})),w):(_.includes(yy)&&(_=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(_),w)}finally{u(!1),p.current=!1}},[o,a,b,i]),v=l.useCallback(()=>{b&&ta(b.prompt.promptId)},[b]),C=l.useCallback(()=>{if(ta(null),!f){h(s("interactivePrompt.errorUnavailable",{defaultValue:"Could not load the question — answer it in the terminal view instead."}));return}h(null)},[f,s]);return{promptSession:b,hasActivePrompt:y,responseError:m,isSubmitting:d,submit:j,cancel:v,reopen:C}}function gf(e){return e.sessionId??e.routeId}const sl=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(),HS=12e3;function bf({activeConv:e,onModalButton:t}){const{t:s}=ve(),[r,o]=l.useState(null),{hasActivePrompt:a,promptSession:i,reopen:c}=ki(gf(e));l.useEffect(()=>{o(null)},[e.modalMessage,e.status,e.connectionState]),l.useEffect(()=>{if(!r)return;const h=setTimeout(()=>o(null),HS);return()=>clearTimeout(h)},[r]);const d=or(e);if(!d.isWaiting&&!d.isWaitingChoice||!e.modalButtons)return null;const u=h=>{r||(o(h),t(h))},m=()=>n.jsx("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:n.jsx("div",{className:"flex items-center gap-2",children:n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(an,{size:14}),s("approval.questionUnavailable",{defaultValue:"Question waiting — could not load it here. Answer it in the terminal view."})]})})});return a&&!i?m():a?n.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&n.jsx("div",{className:"text-2xs opacity-85 mb-1.5 line-clamp-3 max-w-full whitespace-pre-wrap break-words",title:e.modalMessage,children:e.modalMessage}),n.jsxs("div",{className:"flex justify-between items-center gap-2",children:[n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(an,{size:14})," ",s("approval.questionPending",{defaultValue:"Question waiting"})]}),n.jsx("button",{onClick:c,className:"btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold cursor-pointer whitespace-nowrap shrink-0",style:{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"},children:s("approval.answerQuestion",{defaultValue:"Answer the question"})})]})]}):d.isWaitingChoice?m():n.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&n.jsx("div",{className:"text-2xs opacity-85 mb-1.5 line-clamp-3 max-w-full whitespace-pre-wrap break-words",title:e.modalMessage,children:e.modalMessage}),n.jsxs("div",{className:"flex justify-between items-center",children:[n.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[n.jsx(an,{size:14})," ",s(r?"approval.processing":"approval.actionRequired")]}),n.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((h,p)=>{const g=sl(h).toLowerCase(),f=/^always\b/.test(g),y=!f&&/^(run|approve|accept|yes|allow|always)/.test(g),b=/^(reject|deny|delete|remove|abort)/.test(g),k=r===h,j=r!==null;return n.jsx("button",{onClick:()=>u(h),disabled:j,title:f?s("approval.alwaysAllowWarning"):void 0,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${y?"font-extrabold":b?"bg-red-500/30 text-white font-semibold":f?"text-white/90 font-semibold":"text-white font-semibold"} ${j&&!k?"opacity-40":"opacity-100"} ${j?"cursor-not-allowed":"cursor-pointer"}`,style:y?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:f?{background:"transparent",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 55%, transparent)"}:b?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:k?n.jsx(Ir,{size:12}):f?n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(an,{size:11}),sl(h)]}):sl(h)},p)})})]})]})}const hd="adhdev_controls_bar_visible",dc="adhdev:controlsbarvisibilitychange";function rl(e){if(!e)return!1;try{return e.getItem(hd)==="1"}catch{return!1}}function BS(e,t){if(t)try{t.setItem(hd,e?"1":"0")}catch{}}function WS(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(dc,{detail:{visible:e}}))}function pd(){const[e,t]=l.useState(()=>typeof window>"u"?!1:rl(window.localStorage)),s=l.useRef(e),r=l.useCallback((i,c=!0)=>{s.current=i,t(i),typeof window<"u"&&BS(i,window.localStorage),c&&WS(i)},[]);l.useEffect(()=>{const i=d=>{const u=d.detail,m=typeof(u==null?void 0:u.visible)=="boolean"?u.visible:rl(window.localStorage);s.current=m,t(m)},c=d=>{if(d.key!==hd)return;const u=rl(window.localStorage);s.current=u,t(u)};return window.addEventListener(dc,i),window.addEventListener("storage",c),()=>{window.removeEventListener(dc,i),window.removeEventListener("storage",c)}},[]);const o=l.useCallback(i=>{r(i)},[r]),a=l.useCallback(()=>{r(!s.current)},[r]);return{isVisible:e,setVisibility:o,toggleVisibility:a}}const xf=["en","ko","ja","zh-CN","es"],zs="en",Rs=[{code:"en",label:"English"},{code:"ko",label:"한국어"},{code:"ja",label:"日本語"},{code:"zh-CN",label:"中文(简体)"},{code:"es",label:"Español"}];function Ws(e){return typeof e=="string"&&xf.includes(e)}function US(e){if(!e)return zs;const t=e.trim().toLowerCase();if(!t)return zs;if(t==="zh"||t.startsWith("zh-")||t.startsWith("zh_"))return"zh-CN";const s=t.split(/[-_]/)[0];return s==="en"?"en":s==="ko"?"ko":s==="ja"?"ja":s==="es"?"es":zs}const KS={runFailed:"Couldn't run {{label}}",updateFailed:"Couldn't update {{label}}",loadOptionsFailed:"Couldn't load {{label}} options"},qS={unknown:"Unknown",starting:"Starting",stopped:"Stopped",failed:"Failed",idle:"Idle",generating:"Working",awaitingApproval:"Needs approval"},zS={label:"Language",select:"Select language"},GS={copy:"Copy",no:"No",yes:"Yes",diagnostics:"Diagnostics",done:"Done",edit:"Edit",copied:"Copied",copyId:"Copy ID",technicalDetails:"Technical details",saveFailed:"Couldn't save: {{error}}",saved:"Saved",refresh:"Refresh",moreInfo:"More info",closeDialog:"Close dialog",noRecords:"No records found.",close:"Close",back:"Back",cancel:"Cancel",confirm:"Confirm",confirmTitle:"Are you sure?"},VS={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"},YS={details:"Details",label:{success:"Done",warning:"Attention",info:"Update"},dismiss:"Dismiss"},QS={actionNeeded:"Action needed",taskComplete:"Task complete",markRead:"Mark read",markUnread:"Mark unread",delete:"Delete"},JS={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"},XS={header:{moreActions:"More actions",title:"Dashboard",guide:"Dashboard guide",guideOpen:"Open dashboard guide",guideShort:"Guide",openGitStatus:"Open git status",meshGraph:"Mesh graph",stopAcpSession:"Stop ACP session",stopCliProcess:"Stop CLI process",chatHistory:"Chat History",remoteControl:"Remote Control",generating:"generating",activityInbox:"Notifications"},hidden:{title:"Hidden tabs",dragHint:"Drag a tab here to hide it.",resetPanels:"Reset panels",restoreAll:"Restore all",hideCurrentTab:"Hide current tab",empty:"No hidden tabs.",resetPanelsConfirm:"Move every floating or popout panel back into the main dashboard grid?"},inbox:{unread:"Unread",read:"Read",empty:"No pending activity."},metaChips:{queuePending:"{{count}} waiting",queueTooltip:"Queue: {{pending}} waiting, {{assigned}} assigned, {{completed}} completed, {{failed}} failed",meshNode:"Mesh Node"},versionBanner:{restarting:"restarting",upgrading:"updating…",unknownVersion:"unknown",updateAvailable:"Update available",required:"required",retry:"retry"},remoteDialog:{liveRemoteView:"Live remote view",remoteUnavailable:"Remote view unavailable",remoteOnly:"Remote only",splitView:"Split view",remoteFallback:"Remote",history:"History"},guide:{title:"Dashboard guide",subtitle:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune.",close:"Close dashboard guide",tabs:{overview:"Overview",quickstart:"Quick start",shortcuts:"Shortcuts"},overview:{whatLivesWhere:{title:"What lives where",tabsLabel:"Tabs:",tabsText:"active sessions across IDE, CLI, and ACP agents.",hiddenLabel:"Hidden tabs:",hiddenText:"stash sessions you do not want in the main strip but still want to keep around.",inboxLabel:"Activity inbox:",inboxText:"sessions waiting for approval or finished tasks you have not reviewed yet.",cliToggleLabel:"CLI view toggle:",cliToggleText:"switch a PTY session between terminal and chat rendering without relaunching it."},usefulFlows:{title:"Useful flows",reviewLabel:"Review notifications:",reviewText:"open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane.",clutterLabel:"Reduce clutter:",clutterText:"hide less important sessions instead of closing them, then restore from hidden tabs when needed.",splitLabel:"Split work:",splitText:"keep one pane active for input and let secondary panes stay read-only until you focus them.",detachedLabel:"Detached views:",detachedText:"float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor.",dockingLabel:"Docking:",dockingText:"use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard.",perTabLabel:"Per-tab shortcuts:",perTabText:"right-click a Dockview tab to assign a direct shortcut for that specific session.",approvalLabel:"Approval buttons:",approvalText:"use {{keys}} for the first three visible approval actions on the active session."}},quickstart:{desktop:{title:"Desktop quick start",step1:"Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions.",step2:"Keep the main strip focused on active work and push overflow into Hidden tabs.",step3:"Use the inbox for approval-required or completed sessions instead of scanning every tab.",step4:"Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."},mobile:{title:"Mobile quick start",step1:"Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions.",step2:"Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there.",step3:"Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."}},shortcuts:{sections:{all:"All",workspace:"Workspace",panes:"Panes",approvals:"Approvals"},disableAll:"Disable all",resetToDefaults:"Reset to defaults",default:"Default:",listening:"Listening...",set:"Set",disable:"Disable",off:"Off",footer:"Use modifier shortcuts like {{keys}}, or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs.",resetConfirm:"Reset all dashboard shortcuts back to their default values?",setListening:"Listening"}},shortcutDefs:{openShortcutHelp:{label:"Open shortcuts",description:"Show the keyboard shortcuts panel."},openNewSession:{label:"New session",description:"Open the new session launcher."},hideCurrentTab:{label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs."},toggleHiddenTabs:{label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover."},openHistoryForActiveTab:{label:"Open history",description:"Open history for the active session."},openRemoteForActiveTab:{label:"Open remote",description:"Open remote control for the active session when available."},floatActiveTab:{label:"Float active tab",description:"Move the active tab into a floating panel."},popoutActiveTab:{label:"Open active tab in new window",description:"Move the active tab into a detached popout window."},dockActiveTab:{label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window."},splitActiveTabRight:{label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it."},splitActiveTabDown:{label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it."},focusLeftPane:{label:"Focus left pane",description:"Move focus to the pane on the left."},focusRightPane:{label:"Focus right pane",description:"Move focus to the pane on the right."},focusUpPane:{label:"Focus upper pane",description:"Move focus to the pane above."},focusDownPane:{label:"Focus lower pane",description:"Move focus to the pane below."},moveActiveTabToLeftPane:{label:"Move active tab left",description:"Move the active tab into the pane on the left."},moveActiveTabToRightPane:{label:"Move active tab right",description:"Move the active tab into the pane on the right."},moveActiveTabToUpPane:{label:"Move active tab up",description:"Move the active tab into the pane above."},moveActiveTabToDownPane:{label:"Move active tab down",description:"Move the active tab into the pane below."},triggerPrimaryApprovalAction:{label:"Approval action 1",description:"Press the first approval/action button for the active session."},triggerSecondaryApprovalAction:{label:"Approval action 2",description:"Press the second approval/action button for the active session."},triggerTertiaryApprovalAction:{label:"Approval action 3",description:"Press the third approval/action button for the active session."},setActiveTabShortcut:{label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab."},selectPreviousGroupTab:{label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group."},selectNextGroupTab:{label:"Next tab in group",description:"Move to the next tab inside the active Dockview group."},toggleCliView:{label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view."}}},ZS={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"},ek={processing:"PROCESSING...",actionRequired:"ACTION REQUIRED",alwaysAllowWarning:"Grants this permission permanently — future runs will not ask again",questionPending:"QUESTION WAITING",answerQuestion:"Answer the question"},tk={loading:"Loading…",launchModelChanged:"{{from}} → {{to}} (changed)",launchModelSource:{user:"chosen",remembered:"remembered",mesh_slot:"mesh slot",task_override:"task override",provider_default:"default"}},nk={noMeshesShort:"No meshes on this machine",noProvidersShort:"No agents available",advancedOptions:"Advanced options",agent:"Agent",defaultResolvesTo:"Default resolves to {{model}}",title:"Start session",close:"Close new session dialog",detectedLocally:"Detected locally",availableToOpen:"Available to open",machine:"Machine",selectMachine:"Select machine {{name}}",workspace:"Workspace",browse:"Browse…",launchTargetType:"Launch target type",modeWorkspace:"Workspace",modeWorkspaceDesc:"Normal session",modeMesh:"Mesh",modeMeshDesc:"Coordinator session",homeDirectory:"Home directory",customFolder:"Custom folder…",launchWithoutWorkspace:"Launch without a workspace.",selectWorkspaceFolder:"Select a workspace folder.",selectFolder:"Select folder",saving:"Saving…",saveWorkspace:"Save workspace",loadingMeshes:"Loading meshes…",noMeshes:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker.",mesh:"Mesh",repoMesh:"Repo mesh",nodeCount_one:"{{count}} node",nodeCount_other:"{{count}} nodes",coordinatorWorkspace:"Coordinator workspace: {{path}}",noProviders:"Nothing usable on the selected machine. If an agent is installed outside the default location, set its executable path in Machine → Providers.",startupArguments:"Startup arguments",optionalFlags:"Optional flags...",autoApproveMode:"Auto-approve mode",autoApproveModeDescription:"Choose how this session handles approval prompts.",autoApproveLegacy:"Auto approve",autoApproveLegacyDescription:"Automatically accept supported approval prompts for this session.",autoApproveRisk:{safe:"Safe",caution:"Caution",dangerous:"Dangerous"},dangerousModeTitle:"Confirm dangerous auto-approve mode",dangerousModeFallbackWarning:"This mode can bypass approval or sandbox protections. Use it only in a trusted workspace.",dangerousModeRisk:"Risk",dangerousModeLaunchArgs:"Injected launch arguments",dangerousModeConfirm:"Use dangerous mode",modelAndThinking:"Model & thinking (optional)",model:"Model",providerDefault:"(provider default)",custom:"Custom…",typeModelName:"Type a model name",backToModelList:"← Back to model list",thinkingLevel:"Thinking level",selectWorkspaceTitle:"Select workspace",start:"Start",starting:"Starting…",startMeshCoordinator:"Start mesh coordinator",startingCoordinator:"Starting coordinator…",startIde:"Start IDE",startingIde:"Starting IDE…",startAcpSession:"Start ACP session",startingAcpSession:"Starting ACP session…",startFresh:"Start fresh",startingFresh:"Starting fresh…",resumeSavedHistory:"Resume saved history",resumingSavedHistory:"Resuming saved history…",errorLoadMeshes:"Could not load meshes",errorLoadFolder:"Could not load folder",errorLoadSavedSessions:"Could not load saved sessions",errorSaveWorkspace:"Could not save workspace",workspaceSaved:"Workspace saved. It will appear in the list once the machine state refreshes.",errorManualMcpSetup:"Manual MCP setup required before this provider can act as mesh coordinator.",errorStartMeshCoordinator:"Could not start mesh coordinator",errorStartSession:"Could not start session",errorResumeSession:"Could not resume session",errorWorkspaceContextRequired:"Choose a workspace — a directory, a saved/default workspace, or your home directory — before launching.",defaultWorkspace:"Default workspace"},sk={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)"},rk={hint:{daemon:{followUp:"Needs follow-up",merged:"Merged",notMergeable:"Can't merge yet — changes or conflicts",cleanup:"Merged — worktree can be cleaned up",needsMerge:"Pushed — ready to merge",blockedReview:"Needs review before merging"},anchorEmpty:"No workspace on the default branch",anchorWorkspaces:"{{count}} workspace(s) on {{branch}}",anchorNeedsFollowUp:"{{count}} on {{branch}} need follow-up",submoduleSynced:"{{path}} is in sync",submoduleChanged:"{{path}} has local changes",submoduleOutOfSync:"{{path}} is out of sync with its parent",gitAgeUnknown:"Git status age unknown",staleGit:"Git status is over 5 min old",missingSubmodule:"Submodule not reported: {{paths}}",noGitYet:"No git status received yet",noGitYetOnline:"Online — git status not received yet",waitingForGit:"Waiting for git status…",nodeError:"Node reported an error",upstreamUnverified:"Upstream not verified yet",noUpstream:"Push {{branch}} to set its upstream",mergeConflicts:"Resolve merge conflicts",detachedHead:"Detached HEAD — check out a branch",notGitRepo:"Not a git repository",noGitStatus:"No git status yet"},sessionCleanup:{stopAndDeleteHint:"Stop matching sessions, then remove their chat records.",stopAndDelete:"Stop and delete sessions",deleteStoppedHint:"Clear finished or stopped chats without stopping running sessions.",deleteStopped:"Delete stopped sessions only",stopHint:"Stop running session processes but keep their chat records.",stop:"Stop running sessions only",preserveHint:"Keep finished chat history and leave running sessions alone.",preserve:"Keep history and running sessions"},nodeHealth:{failed:"Failed",completed:"Completed",assigned:"Assigned",pending:"Pending",enabled:"Enabled",unknown:"Connecting…",wrongBranch:"Other branch",degradedHint:"The connection to this machine is down or timed out — often temporary. Wait a moment or reconnect the machine.",degraded:"Unreachable",offline:"Offline",dirty:"Uncommitted changes",online:"Online"},activity:{noKeyEvents:"No recent key events",rawData:"Raw data",showKey:"Show key events only",showAll:"Show all activity",nodeChanged:"Machine joined or left",sessionStarted:"Agent started",needsInput:"Needs your input",taskFailed:"Task failed",taskFinished:"Task finished",taskStarted:"Task started"},drift:{clean:"Clean",conflicts:"conflicts",submoduleOutOfSync_other:"{{count}} submodules out of sync",submoduleOutOfSync_one:"{{count}} submodule out of sync",submoduleChanged_other:"{{count}} submodules changed",submoduleChanged_one:"{{count}} submodule changed",changed_other:"{{count}} changed",changed_one:"{{count}} changed",upstreamUnverified:"upstream unverified",noGit:"No git info",probePending:"Checking git…"},graph:{slowLinkChip:"Slow link",observationUnreachableChip:"Unreachable",observationStaleChip:"Stale",remoteBadge:"remote",activeSessionAria:"active session",observationAsOf:"as of {{age}} ago",observationRefreshing:"as of {{age}} ago · refreshing",observationFetching:"fetching state…",observationUnreachable:"unreachable · last known {{age}} ago",observationUnreachableNoState:"unreachable · no state yet"},statusTab:{v2ScopeHint:"Pending events by scope",providerSkewHint:"Providers running different versions on different nodes",providerSkew:"{{count}} provider version mismatch",v2RatioHint:"Share of pending coordinator events in the current message format",daemonBuildHint:"Exact daemon build (version@commit) running on this node",quotaFailedHint:"This machine couldn't read this provider's usage",quotaOkNoWindowHint:"Read successfully — this provider has no percentage limit to show",nodeCountHint:"Mesh nodes (workspaces/worktrees) on this machine — they share one plan quota",nodeCount_other:"{{count}} nodes",nodeCount_one:"{{count}} node",daemonVersionHint:"Daemon version running on this machine",blockedReasonHint:"Why this node can't take a new code-changing task right now",providerCapHint:"Active tasks per provider on this node vs its declared limit",priorityHint:"Scheduling preference (higher is preferred)",priority:"priority {{value}}",loadHint:"Active tasks assigned to this node",load:"load {{count}}",readonlyCapHint:"Active read-only investigation tasks vs their limit (2× the write limit)",readonlyCap:"read-only {{active}}/{{max}}",writeCapHint:"Active tasks that change code vs the mesh-wide parallel limit",writeCap:"write {{active}}/{{max}}"},manualSetup:{restartHint:"Start a fresh CLI session after editing config.",configPath:"Config path:",format:"Format:",server:"Server:",titleFor:"Manual MCP setup required for {{provider}}",title:"Manual MCP setup required"},help:{toggleAria:"Mesh help",toggleTitle:"Mesh concept help",regionAria:"Mesh concept help",kicker:"Help",title:"Mesh concepts at a glance",close:"Close help",sections:{node:{term:"Node",summary:"A workspace participating in the mesh — a repo checkout or an isolated git worktree.",details:["Base node vs worktree clone node — a clone isolates parallel work without conflicts.","Shows health (online/offline) alongside git state (branch · ahead/behind · dirty).","Multiple nodes can share the same daemon."]},p2p:{term:"P2P connection",summary:"How the selected coordinator reaches each remote node over WebRTC.",details:["direct — a direct host/STUN path; lowest latency.","relay — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed — no live P2P link from the coordinator right now.","P2P connectivity is shown as transport and RTT chips on each node card (and in the node detail panel), not as a graph edge."]},session:{term:"Session",summary:"An agent CLI session running on a node.",details:["status = idle / generating / waiting_approval.","Distinguishes coordinator sessions (which dispatch and collect work) from delegated worker sessions (which do the work)."]},task:{term:"Task",summary:"A single unit of work handled by the queue-based pull model.",details:["States: pending → assigned → completed / failed / cancelled.","Idle nodes claim from the queue automatically; direct dispatch targets a specific session."]},mission:{term:"Mission",summary:"A multi-task batch aimed at one goal, and the durable record of that effort.",details:["States: active / paused / completed / abandoned.","Progress is derived from the states of its member tasks."]},refinery:{term:"Refinery (refine)",summary:"The process of safely converging and merging a worktree branch into the base.",details:["Config-driven (.adhdev/refine.*) — guarded by a patch-equivalence preflight and a no-op guard.","ff-only by principle; no force-push.","If a submodule commit is unreachable from origin it must be published → classified as blocked_review."]},completion:{term:"Completion model",summary:"Completion of delegated work is persisted to the queue (pending-events).",details:["The coordinator learns of completion via periodic polling or events.","Because it is persisted to the queue, completion signals are never lost."]},magi:{term:"MAGI",summary:"Cross-verification: several independent AI agents answer the same question in parallel.",details:["Confidence comes from independence — different AIs on different machines fail in different ways.","When the agents disagree, the disagreement itself flags what to double-check.","The synthesis weighs agreement against source coupling."]},magiPanel:{term:"MAGI panel",summary:"A saved, reusable team of (machine × AI) members you invoke by name across investigations.",details:["Each member is one provider (AI) optionally pinned to a node (machine), with a replica count.","independent — spans ≥2 providers AND ≥2 machines, so agreement adds real confidence.","coupled — collapses to one AI or one machine; repeated members repeat the same mistakes.","Managed machine-locally from the Panels tab; defined in ~/.adhdev/meshes.json."]},convergence:{term:"Branch convergence states",summary:"After worktree work, each branch is classified into exactly one final state.",details:["merged_to_main — merged into the base.","pushed_feature_branch_needs_merge — pushed, awaiting merge.","blocked_review — held back by review/reachability issues.","cleanup_candidate — ready to clean up.","not_mergeable — cannot be merged."]},graph:{term:"Orchestration graph",summary:"A batch of tasks enqueued together with declared dependencies, conditions and gates.",details:["Created by mesh_enqueue_batch; each graph is one executable plan inside a mission.","Settled graphs collapse to a single chip on the blueprint — click to expand in place."]},gate:{term:"Coordinator gate",summary:"A step that holds the graph until a human-directed coordinator acts.",details:["States: declared → awaiting_coordinator → claimed → released (or expired).","The blueprint draws a waiting gate at full card width with its instructions and deadline.","Acting on a gate is done by instructing the coordinator; the dashboard is read-only here."]},condition:{term:"Condition (run_if)",summary:"A declarative predicate deciding whether a planned step runs at all.",details:["Grammar is a closed set: all / any / not over exists, ==, != and in.","The blueprint renders it as a card wired into the edge, e.g. review.outcome == rejected.","A step whose condition never holds is skipped, not failed."]},blueprint:{term:"Blueprint",summary:"The plan view: live queue work, graph gates and planned steps on one canvas.",details:["One axis — dependency depth, left to right. Root tasks are ordered newest first.","Cards carry their own time, so position never has to encode it.","Finished graphs sit below the live work as a collapsed archive."]},routingPreview:{term:"Routing preview",summary:"A read-only forecast of where a hypothetical task would land.",details:["Shown per difficulty; a task pinned to a node gets its own pinned preview (📌).","It is a prediction, not the owner — a card that already ran shows its real node below."]},worktree:{term:"Worktree node",summary:"A node backed by a git worktree rather than the main checkout.",details:["Labelled by its branch (⎇). Lets several tasks run on one machine without sharing a branch.","Orphan worktrees are reported as cleanup candidates and are never deleted automatically."]}}},approvals:{title:"PENDING APPROVALS",empty:"No sessions are awaiting an approval decision.",sessionFallback:"session {{id}}",approve:"Approve",reject:"Reject",waitingFor:"Waiting for {{duration}}"},difficulty:{intro:"Map each task difficulty to a brain. The coordinator classifies a task's difficulty; easy work then runs on a cheaper model at low effort, hard work on a stronger model at high effort. Leave a field blank to keep the routed default.",connectPrompt:"Connect to a coordinator daemon to edit brain presets.",errorLoad:"Failed to load brain presets",errorSave:"Failed to save brain presets",provider:"Provider",model:"Model",thinking:"Thinking",routedDefault:"(routed default)",defaultOption:"(default)",modelPlaceholder:"e.g. haiku, sonnet, opus",savePresets:"Save presets",saving:"Saving…",reset:"Reset",loading:"Loading…",easy:"Easy",easyHint:"trivial fixes, renames, docs — save tokens",medium:"Medium",mediumHint:"ordinary feature / bugfix work",difficult:"Difficult",difficultHint:"architecture, tricky debugging, hard reasoning",freeform:"Freeform",freeformHint:"no fixed shape"},magiKind:{refresh:"Refresh",loading:"Loading…",connectPrompt:"Connect to a coordinator daemon to manage kind → panel bindings.",errorLoad:"Failed to load kind panels",errorSave:"Failed to save kind binding",errorRemove:"Failed to remove kind binding",errorSlotProvider:"Slot {{slot}}: provider is required",errorSlotReplica:"Slot {{slot}}: replica count must be ≥ 1",errorNoSlot:"A kind binding needs at least one slot",removeConfirm:'Remove the MAGI panel binding for "{{kind}}"?',kindRca:"Root-cause analysis",kindDesign:"Design / approach review",kindClaimAudit:"Verify specific claims",kindFreeform:"Freeform review",agentCount_one:"{{count}} agent",agentCount_other:"{{count}} agents",off:"off",noAgents:"No agents yet — add one to enable this review type.",machine:"Machine",machineTitle:'Which machine runs this agent. Leave on "any" to let the coordinator route by tags.',anyMachine:"Any machine",offlineSuffix:"{{label}} (offline)",worktreeSuffix:"{{label}} — worktree ({{branch}})",worktreeUnknownBranch:"unknown branch",worktreeDisabledTitle:"Ephemeral worktree nodes can't be newly assigned to a MAGI slot — they can disappear on cleanup. An existing assignment stays visible here so it can be reviewed or cleared.",provider:"Provider",providerTitle:"The AI agent this slot runs.",selectProvider:"Select provider…",model:"Model",modelTitle:"Optional model override (best-effort). Blank uses the provider default.",modelDefault:"default",modelCustom:"Custom…",backToModelList:"← Back to model list",copies:"Copies",copiesTitle:"How many parallel copies of this agent to run. Blank = 1.",removeAgent:"Remove agent",addAgent:"+ Add agent",save:"Save",saving:"Saving…",removeBinding:"Remove binding",removeBindingTitle:"Clear this kind binding",removeBindingDisabledTitle:"Nothing to remove — this kind is unconfigured"},synthesis:{rawUnavailable:"Raw answers unavailable",empty:"No cross-verification results for this mesh yet.",synthesized:"synthesized",running:"running",answered:"{{answered}}/{{total}} answered",needsVerificationCount:"{{count}} needs verification",agreedCount:"{{count}} agreed",staleCount:"{{count}} stale",gitSkewLabel:"Git skew: ",gitSkewNote_one:"{{count}} branch ({{branches}}) — evidence compares different code.",gitSkewNote_other:"{{count}} branches ({{branches}}) — evidence compares different code.",needsVerification:"Needs verification",openQuestions:"Open questions",rawReplicaAnswers:"Raw replica answers",rawTitleLive:"Best-effort: raw replica text is not persisted — recoverable only from a live coordinator with the replica sessions still reachable.",rawTitleOffline:"A live coordinator daemon is required to fetch raw replica answers.",loading:"Loading…",reloadRaw:"Reload raw answers",loadRaw:"Load raw answers",rawNotice:"Raw per-replica text is not persisted (only this synthesis summary is). It is fetched live from the coordinator and is unavailable once the replica sessions age out or no live session exists.",errorLoadRaw:"Failed to load raw answers",rawEmpty:"No raw answers were returned — the replica transcripts are not retained (raw not persisted), aged out, or no live session is reachable for this group.",truncated:"truncated"},panel:{selectNode:"Select a node to view details.",submoduleBadge:"Submodule",dirtyBadge:"Dirty",outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",orphanBadge:"Orphan",fieldWorkspace:"Workspace",fieldBranch:"Branch",fieldUpstream:"Upstream",fieldUpstreamState:"Upstream state",fieldHead:"HEAD",fieldSubmodulePath:"Submodule path",fieldSubmoduleCommit:"Submodule commit",fieldParentNode:"Parent node",fieldAhead:"Ahead",fieldBehind:"Behind",fieldDirtyFiles:"Dirty files",fieldActiveSessions:"Active sessions",fieldProviders:"Providers",fieldConnection:"Connection",fieldError:"Error",orphanReasons:"Orphan reasons",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusCoordinator:"coordinator",statusWorker:"worker",upstreamVerified:"verified",upstreamUnverifiedFetch:"unverified (fetch failed)",upstreamUnverified:"unverified",upstreamUnavailable:"unavailable",needsFollowUp:"needs follow-up",refined:"refined",tooltipLocalChanges:"Local changes",tooltipHasConflicts:"Has conflicts",tooltipOutOfSync:"Out of sync",tooltipNeedsFollowUp:"Needs follow-up",tooltipUpstreamUnverified:"Upstream unverified",tooltipRefineCompleted:"refine completed",tooltipRefinedBranch:"refined {{branch}}",tooltipP2PRelayed:"P2P link relayed through TURN (slower path)",tooltipPrefixStatus:"Status:",tooltipPrefixBranch:"Branch:",tooltipPrefixNote:"Note:",defaultBranch:"default branch",submoduleSynced:"synced",moreChats_one:"+{{count}} more chat",moreChats_other:"+{{count}} more chats",remote:"remote",chats_one:"{{count}} chat",chats_other:"{{count}} chats",generatingCount:"{{count}} generating",coordinatorAttached:"coordinator attached",coordinators:"{{count}} coordinators",workers_one:"{{count}} worker",workers_other:"{{count}} workers",sampledStatus:"sampled status"},legendEdge:{parentBranch:"default branch",cloneLink:"worktree clone",worktreeLink:"same branch",submoduleLink:"submodule",sessionLink:"session",orphanLink:"needs follow-up"},attention:{submoduleDrift:"submodule drift",submoduleDirty:"submodule dirty",conflictsPresent:"conflicts present",dirtyWorkspace:"dirty workspace",upstreamUnverified:"upstream unverified",pushBranch:"push branch",blockedReview:"blocked review",refineFailed:"refine failed",refining:"refining…",needsMerge:"needs merge",refineWorktree:"refine worktree",needsFollowUp:"needs follow-up",offline:"offline",ahead:"ahead {{count}}",behind:"behind {{count}}",aheadBehind:"ahead {{ahead}} / behind {{behind}}"},summary:{anchor:"Default branch anchor",parent:"parent {{label}}",localChanges:"local changes",sessions_one:"{{count}} session",sessions_other:"{{count}} sessions",conflicts:"conflicts",clean:"Clean and even with upstream"},taskDag:{plan:{depsFailed_one:"{{count}} upstream failed",depsFailed_other:"{{count}} upstream failed",openTask:"Open this task"},gate:{holding_one:"holding {{count}} step",holding_other:"holding {{count}} steps",converged:"commits on main",notConverged_one:"{{count}} commits not on main",notConverged_other:"{{count}} commits not on main",deadline:"due {{time}} · then {{onTimeout}}",needsYou:"Needs you"},edge:{conditionMore:"+ more",conditional:"if condition"},time:{now:"just now",minutes_one:"{{count}}m ago",minutes_other:"{{count}}m ago",hours_one:"{{count}}h ago",hours_other:"{{count}}h ago",days_one:"{{count}}d ago",days_other:"{{count}}d ago"},collapsed:{expand:"Click to expand this finished graph",counts:"{{nodes}} steps · {{gates}} gates"},empty:"No tasks yet",waitsOn_one:"waits on {{count}}",waitsOn_other:"waits on {{count}}",blocked:"blocked",missingDeps_one:"{{count}} unknown dep",missingDeps_other:"{{count}} unknown deps",selectedTask:"Selected task",finalSummary:"Final summary",finalSummaryFull:"Show full report",finalSummaryLoading:"Loading final summary…",finalSummaryUnavailable:"Final summary unavailable",statsTasks_one:"{{count}} task",statsTasks_other:"{{count}} tasks",statsEdges_one:"{{count}} dependency",statsEdges_other:"{{count}} dependencies",statsMissions_one:"{{count}} mission",statsMissions_other:"{{count}} missions",statsWaiting_one:"{{count}} waiting",statsWaiting_other:"{{count}} waiting",statsBlocked_one:"{{count}} blocked",statsBlocked_other:"{{count}} blocked",legend:{satisfied:"done",waiting:"waiting",failed:"failed"},hiddenTasks_one:"{{count}} older task hidden",hiddenTasks_other:"{{count}} older tasks hidden",loadMore_one:"Load {{count}} more task",loadMore_other:"Load {{count}} more tasks",predictedSlot:"Predicted next routing slot",predictedSlotPinned:"Pinned to a target node — predicted slot on that node",statsPending:"{{count}} queued",statsAssigned:"{{count}} assigned",jumpToState:"Click to jump to the next card in this state"},obs:{fieldEdgeId:"Link ID",fieldHealthRaw:"Health",fieldNodeId:"Node ID",machineSection:"Machine",behindCount:"{{count}} behind",aheadCount:"{{count}} ahead",healUnavailableHint:"Only a clean checkout that is strictly behind a verified upstream can be updated here.",healHint:"Fast-forward this checkout to its upstream. It has no local changes, so nothing can be lost.",healFailed:"Couldn't update {{label}}: {{reason}}",healDone:"{{label}} is up to date",directionTBShort:"↓",directionLRShort:"→",tabMap:"Map",closeDetailAria:"Close detail panel",layoutDirectionAria:"Graph layout direction",viewAria:"Mesh view",tabOverview:"Overview",tabTasks:"Tasks",planeNeedsDaemon:"Connect to the daemon to view graphs and gates.",panHint:"drag or scroll to pan",headlineFollowUp_one:"{{count}} needs attention",headlineFollowUp_other:"{{count}} need attention",headlineIncomplete:"Some machines not visible",headlineConverged:"All synced",badgeBlocked:"{{count}} blocked",badgeBlockedTitle:"{{count}} blocked review",badgeNotMergeable:"{{count}} not mergeable",badgeNeedMerge_one:"{{count}} needs merge",badgeNeedMerge_other:"{{count}} need merge",badgeCleanupTitle:"{{count}} refine/cleanup",badgeOffline:"{{count}} offline",badgeIncompleteTitle:"{{count}} incomplete peer snapshot",badgeNoGitTitle:"{{count}} no git snapshot",badgeNoSubmodTitle:"{{count}} missing submodule visibility",badgeStaleTitle:"{{count}} stale peer snapshot",badgeActiveQueue:"{{count}} active queue",badgeNodes_one:"{{count}} node",badgeNodes_other:"{{count}} nodes",badgeAttachedChats_one:"{{count}} attached chat",badgeAttachedChats_other:"{{count}} attached chats",legendDirty:"{{count}} dirty",legendOrphan:"{{count}} orphan",legendRecentFailures_one:"{{count}} recent failure",legendRecentFailures_other:"{{count}} recent failures",legendAnchor:"Anchor = default branch",legendPeerLink:"Peer link = same-branch worktree",legendSubmoduleLink:"Submodule link = child checkout",healthRefineFailed:"{{count}} refine failed",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedEdge:"Selected edge",activeSessions:"Active Sessions",queueTasks:"Queue tasks",keyWarning:"Key warning",noResultCode:"No result code returned.",legend:"Legend",checking:"Updating…",heal:"Update",loadingGraph:"Loading graph…",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",connecting:"connecting...",providerUnknown:"provider unknown",directionLRTitle:"Left to right",directionTBTitle:"Top to bottom"},notes:{sectionHint:"Lessons the coordinator keeps between sessions — provider quirks, patterns to avoid, recovery steps.",expired:"expired",neverExpires:"never expires",durable:"durable",expiresIn:"expires {{when}}",tab:"Notes",addTitle:"Add operating note",listTitle:"Operating notes",textPlaceholder:"Record a provider quirk, a pattern to avoid, or a recovery lesson...",categoryLabel:"Category",categoryUncategorized:"Uncategorized",categoryProviderQuirk:"Provider quirk",categoryPatternToAvoid:"Pattern to avoid",categoryRecoveryLesson:"Recovery lesson",add:"Add",edit:"Edit",delete:"Delete",save:"Save",cancel:"Cancel",refresh:"Refresh",loading:"Loading notes...",empty:"No operating notes recorded yet.",unavailable:"Operating notes are unavailable — the coordinator is not reachable over P2P.",loadFailed:"Failed to load operating notes.",saveFailed:"Failed to save the operating note.",deleteFailed:"Failed to delete the operating note.",editFailed:"Failed to update the operating note.",showMore:"Show more",showLess:"Show less",pinned:"pinned"},dialog:{liveUpdatesOn:"Live updates on",liveUpdatesPaused:"Live updates paused — showing the last loaded state",refreshedAt:"Refreshed {{time}}",refreshFailedQuiet:"refresh failed · showing last loaded",refreshTitle:"Refresh live mesh graph",refresh:"Refresh",refreshing:"Refreshing…",loadingStatus:"Loading live mesh status…",noGraph:"No live mesh graph is available for this coordinator yet. Tap the ? above to learn what a Repo Mesh does.",errorNoMeshId:"This coordinator does not expose a live mesh id.",errorUnexpectedPayload:"Couldn't load graph data. Please try again shortly."},health:{statFailed:"Failed",statPending:"Waiting"},blueprint:{schedPrediction:"Prediction",gateActsViaCoordinatorHint:"The coordinator claims and releases this gate — ask it in the coordinator chat.",gateFallback:"gate",readonlyBadge:"read-only",liveQueue:"Live queue",scheduling:"Scheduling preview",schedObservedAt:"as of {{time}}",schedNoNodes:"No routable nodes.",schedQuotaButton:"Quota",schedQuotaButtonTitle:"Per-machine plan quota at a glance",schedNoWinner:"no eligible slot",leaseExpired:"lease expired",emptyGraph:"This graph has no nodes.",gateActsViaCoordinator:"Coordinator-managed",schedNext:"Next up",schedWaiting:"Ready",schedFull:"At capacity",schedFloorExcluded:"Below difficulty",schedQuotaGated:"Quota-gated",schedCapFree:"Free",schedColSlot:"Slot",schedColScore:"Score",schedColQuota:"Quota",schedColParallel:"Parallel",schedColStatus:"Status",schedColMachine:"Machine",schedNextTitle:"Dispatch a task of this difficulty now and this slot takes it",schedTargetWorktreeTitle:"The task would run in this worktree checkout",schedUnpinned:"no pin",schedUnpinnedTitle:"Hypothetical dispatch with no target pin — tasks pinned to a node show their own forecast on their cards",schedPointInTime:"Point-in-time prediction, not a settled assignment: slot capacity can go stale as soon as a slot is claimed or released",schedulingShort:"Scheduling",gate:{release:"Release",abandon:"Abandon",extend24h:"Extend 24h",outcomePassed:"Passed",outcomeFailed:"Failed",evidencePlaceholder:"Evidence (optional)",reasonPlaceholder:"Reason for abandoning this gate",abandonReasonRequired:"A reason is required to abandon a gate.",submitRelease:"Submit release",submitAbandon:"Submit abandon",extendConfirmTitle:'Extend "{{ref}}" by 24 hours?',expiredBadge:"Expired · {{age}} ago",commandUnavailable:"No daemon connection to send this command."},list:{barActive:"Active {{count}}",barBlocked:"Blocked {{count}}",barRecent:"Recent {{count}}",barMissions_one:"{{count}} mission",barMissions_other:"{{count}} missions",sectionRunning:"Running",sectionBlocked:"Blocked",sectionRecent:"Recent",sectionHistory:"History",generating:"generating",approvalNeeded:"approval needed",choiceNeeded:"choice needed",planShow:"plan",planHide:"hide",planTitle:"Show this task's dependency plan",noMission:"No mission",loadMore_one:"Show {{count}} more",loadMore_other:"Show {{count}} more",emptyActive:"Nothing running",blockedByGate:"blocked by: {{ref}}, {{age}}",waitingOn:"waiting on:",waitingOnMore:"+{{count}} more",blockedByDeadDependency:"blocked by failed/cancelled dependency:",chainGroup:"Chain: {{title}}"},graph:{viewSwitchLabel:"Blueprint view",viewList:"List",viewGraph:"Graph",activeOnly:"Active only",activeOnlyTitle:"Hide lanes where everything has finished",hiddenLanes_one:"{{count}} finished lane hidden",hiddenLanes_other:"{{count}} finished lanes hidden",emptyActive:"Nothing running",showFinished:"Show finished lanes",layoutFailed:"Graph layout failed: {{error}}",laneGraph:"Graph {{id}}",laneAdhoc:"Independent tasks",laneCollapse:"Collapse",laneExpand:"Expand",foldCompleted:"Fold completed",unfoldCompleted:"Show completed",foldNode_one:"{{count}} completed",foldNode_other:"{{count}} completed",countRunning_one:"{{count}} running",countRunning_other:"{{count}} running",countGates_one:"{{count}} gate waiting",countGates_other:"{{count}} gates waiting",countDead_one:"{{count}} stuck",countDead_other:"{{count}} stuck",countWaiting_one:"{{count}} waiting",countWaiting_other:"{{count}} waiting",countFailed_one:"{{count}} failed",countFailed_other:"{{count}} failed",countDone_one:"{{count}} done",countDone_other:"{{count}} done",timeRunning:"running {{age}}",timeFinished:"ended {{time}}",timeQueued:"queued {{age}}",deadlineIn:"due in {{age}}",deadlineOverdue:"overdue {{age}}",tooltipTask:"Task: {{id}}",tooltipMission:"Mission: {{id}}",tooltipGraph:"Graph: {{id}} · {{ref}}",tooltipGate:"Gate: {{id}}",tooltipStatus:"Status: {{status}}",deadDirect:"A dependency failed or was cancelled — this task will not start on its own.",deadTransitive:"Something upstream failed or was cancelled — this task will not start on its own.",legendDepends:"depends on",legendGate:"gate",legendRunning:"running",legendDead:"can never start",heldUntil:"until {{time}}",gateDetails:"Open gate details",tone:{pending:"pending",running:"running",completed:"completed",failed:"failed",cancelled:"cancelled",dead:"stuck",plan:"planned",held:"held"},gateTone:{declared:"declared",awaiting:"awaiting",claimed:"claimed",expired:"expired",released:"released",abandoned:"abandoned"}}},page:{title:"Repo Mesh",subtitle:"Multi-workspace orchestration",waitingForDaemon:"Waiting for daemon connection...",observabilitySecondary:"Mesh observability"},list:{nodeCount_other:"{{count}} nodes",nodeCount_one:"{{count}} node",machinesOnline:"{{online}}/{{total}} machines online",settings:"Settings",open:"Open",title:"Repo Meshes",count_one:"{{count}} mesh",count_other:"{{count}} meshes",createMesh:"+ Create Mesh",createTitle:"Create Repo Mesh",createOnMachine:"Create on machine",noConnectedDaemon:"No connected daemon",workspace:"Workspace",workspaceHint:"Choose from workspaces registered by the selected daemon.",selectMachineFirst:"Select a machine first",noRegisteredWorkspaces:"No registered workspaces",name:"Name",remoteUrl:"Repo remote URL (recommended)",remoteUrlHint:"Paste your repo URL — the identity (github.com/user/repo) is filled in automatically.",repoIdentity:"Repo identity",repoIdentityHint:"For a repo with no remote, or when the URL differs per machine. e.g. github.com/user/repo",advancedIdentityToggle:"Advanced: set identity manually",create:"Create",creating:"Creating…",cancel:"Cancel",loading:"Loading meshes...",emptyTitle:"No Repo Meshes",emptyWithDaemons:"Run several coding agents on one repo across your machines.",emptyNoDaemons:"Connect a machine first.",createFirst:"Create First Mesh",noRepoIdentity:"No repo identity",repoMeshFallback:"Repo Mesh"},detail:{useFromCli:"Use from CLI",optionNo:"No",optionYes:"Yes",distributionInOrderSummary:"First available node, in the order added",distributionSmartSummary:"Best-fit node for each task, spread by load",tabGeneral:"General",back:"← Back",delete:"Delete",observabilityOpenTitle:"Open the live view (overview, tasks, map)",observabilityDisabledTitle:"The host machine must be connected first",observabilityOpen:"Open",tabsAriaLabel:"Mesh settings sections",tabAdvanced:"Advanced",quotaBusyFallback:"Quota fallback when busy",quotaBusyFallbackHint:"When the best provider by quota has no free slot, try the next provider with quota on the same node instead of waiting. Never falls back to a provider that is low on quota, and never moves the task to another node.",distribution:"Distribution",distributionSmart:"Smart",distributionSmartDescription:"Match each task to the node whose capability slot fits it best (difficulty + capability tags), then spread by priority and load. Without slots it still spreads work evenly. Recommended when any node has slots.",distributionInOrder:"In order",distributionInOrderDescription:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading.",recommended:"Recommended",saving:"Saving…",visibilityTitle:"Dashboard visibility",visibilityLabel:"Coordinator-spawned worker sessions",visibilityHint:"Hidden = keep the inbox quiet and mute their notifications; you interact through the coordinator session. Visible = show every spawned worker as its own conversation.",visibilityHidden:"Hidden",visibilityVisible:"Visible",magiTitle:"Cross-check reviewers",magiDescription:"MAGI (Multi-Agent Ground-truth Insight) runs a panel of AI agents that cross-check each other's work to surface the ground truth. Choose which agents handle each review type.",coordinatorPromptTitle:"Coordinator prompt",thisMeshHint:"Applies only to coordinator sessions for {{name}}. Leave empty to keep the daemon default.",overrideLabel:"Override (replaces default)",overrideHint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",overridePlaceholder:"(empty — daemon default applies)",appendLabel:"Append (added after the base)",appendHint:"Always added after whichever base prompt wins.",appendPlaceholder:"(empty — nothing appended)",availablePlaceholders:"Available placeholders",placeholdersIntro:"These tokens are replaced when rendering an override or append prompt:",saveCoordinatorPrompt:"Save coordinator prompt",clear:"Clear",clearTitle:"Clear both fields. Click Save to commit.",safetyTitle:"Safety & Git",safetyDescription:"Checkpointing, approval gates, and git safety behavior for coordinator-driven tasks.",checkpointBefore:"Auto-commit a checkpoint before each task",checkpointAfter:"Auto-commit a checkpoint after each task",pushApproval:"Push approval",requireApprovalBeforePush:"Require approval before push",doNotRequireApproval:"Do not require approval",destructiveGitApproval:"Destructive git approval",requireApproval:"Require approval",uncommittedChanges:"When the workspace has uncommitted changes",warnAndContinue:"Warn and continue",blockTask:"Block task",checkpointThenContinue:"Checkpoint then continue",autoPublishSubmodule:"Auto-publish submodule commits (advanced)",requireExplicitApproval:"Require explicit approval",allowRefineryPublish:"Allow Refinery non-force publish",autoFastForward:"Auto fast-forward idle nodes",ffEnabled:"Enabled (catch up online, clean, behind nodes)",ffDisabled:"Disabled",includeRemoteNodes:"Include remote nodes",includeRemoteNodesHint:"Off = only the coordinator's local workspace is auto fast-forwarded.",remoteNo:"No (local workspace only)",remoteYes:"Yes (delegate to remote owning daemons)",detectionMode:"Detection mode",detectionModeHint:"Idle = on a node's idle edge. Continuous = also scan periodically (base nodes only).",idleEdgeOnly:"Idle edge only",continuousScan:"Continuous (periodic scan)",sessionCleanupLabel:"When removing a node, its sessions…",sessionCleanupHint:"Separate transcript cleanup from runtime/process cleanup.",mcpDescription:"· The mesh MCP server can be used directly from your CLI agent.",repoMeshJsonTitle:"From repo file (read-only)",repoMeshJsonHint:"This repo commits coordinator prompt text that stacks with the fields above. Edit it in the repo file, not here:",repoMeshJsonOverrideLabel:"Repo override",repoMeshJsonAppendLabel:"Repo append",repoMeshJsonInvalid:"This repo's .adhdev/mesh.json could not be parsed, so its prompt layer is ignored."},nodeList:{advanced:"Advanced",launchBlockedChip:"No provider detected",usesTools:"Uses {{tools}}",addingIsExplicit:"Adding it is still up to you.",compatibleWorkspace:"Compatible Git workspace detected.",inspectingRepo:"Inspecting the Git repository (read-only)…",title:"Nodes & Providers ({{count}})",descriptionCloud:"Workspaces in this mesh and their preferred AI tools.",descriptionStandalone:"Workspaces participating in this mesh and their preferred AI tools.",daemonCandidates:"Machine daemon candidates",available:"{{count}} available",noDaemonsAvailable:"No connected machine daemons are currently available.",allDaemonsAttached:"All connected machine daemons are already attached.",selectedHost:"selected host",attachMachine:"Attach machine",addNode:"Add node",attachMachineTitle:"Attach Machine Daemon",addNodeTitle:"Add Node",machine:"Machine",selectMachine:"Select a machine...",workspacePath:"Workspace Path",enterCustomPath:"Or enter a custom path →",preferredTools:"Preferred AI tools (in order)",preferredToolsHint:"Order used when launching without an explicit provider.",add:"Add",cancel:"Cancel",emptyTitle:"No nodes",emptyDescription:"Add a workspace to this mesh.",slotsLabel:"Preferred AI tools (capability slots)",slotsHint:"Each slot = provider + model + thinking + the task difficulty/capability it handles + a per-slot parallel cap. Tasks are matched to the best-fit slot (order = preference). With no slots, this node uses its legacy provider order.",nodeInstruction:"Node instruction (optional)",nodeInstructionHint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",nodeInstructionPlaceholder:"e.g. 'Run only smoke tests here', 'Use opus on this node'",saveInstruction:"Save instruction",saving:"Saving…",removeNode:"Remove node",nodeId:"Node ID:",repoRoot:"Repo root:",activeSessionsLabel:"Active sessions:",added:"Added:",activeQueueAssignments:"Active queue assignments",noActiveAssignment:"No active assigned queue task for this node.",activeSessions:"Active sessions",launchBlocked:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)",titleNoCount:"Nodes & Providers",workspacesDetected:"{{count}} workspace(s) detected",pickFromSaved:"← Pick from saved workspaces",ownerMachine:"Owner: {{owner}} · Machine: {{machine}}",machineTabsLabel:"Machines in this mesh",machineTabCounts:"{{nodes}} node(s) · {{slots}} slot(s)"},host:{setHostConfirmTitle:"Set {{name}} as the host?",setupNode:"setup node",willHostOn:"Will host on",coordinatorProvider:"Coordinator CLI provider",coordinatorProviderHint:"Tool launched for the host coordinator session.",useNodePriority:"Use node provider priority",title:"Host machine",descriptionSet:"The machine that runs this mesh's coordinator. It is set once and not changed here.",descriptionUnset:"Choose the machine that will run this mesh's coordinator.",hostLabel:"Host:",hostNode:"Host node:",unknown:"Unknown",hostOffline:"Host offline",hostOfflineText:"Live status won't load until the host reconnects. Meanwhile you can send commands through another connected machine — this doesn't change the host.",reconnectToCommand:"Reconnect to command",reconnectToCommandHint:"Route commands through this connected daemon until the host is back. Does not change the mesh host.",waitForHost:"Wait for host to reconnect",noDaemonsToRoute:"No connected daemons available to route commands through. Bring the host (or another daemon) online.",launching:"Launching...",launchHost:"Launch Host Coordinator",setHostBanner:"Choose a host machine",hostDaemon:"Host daemon",hostDaemonHint:'Pick the daemon that will host this mesh, then confirm with "Set as host".',resolvingHost:"Resolving host… (or pick a daemon to host)",launchHostSetsHost:"Launch Host Coordinator",noDaemonsToHost:"No connected daemons. Bring a daemon online to host this mesh.",online:"online",offline:"offline",noCommandTarget:"No command target available — bring the host or a daemon online.",pickHostFirst:"Pick a host daemon (or wait for the host pin to resolve) first.",attachNodeFirst:"Attach a workspace from this daemon as a node first.",setHostAction:"Set as host",settingHost:"Setting host…",setHostActionHint:"Pins this daemon as the mesh host. Effectively permanent — it is not reassigned from here afterwards.",confirmSetsHost:"Confirm below to set it as the mesh host.",attachNodeThenSetHost:"Attach one of its workspaces as a node first, then set it as the host."},slotEditor:{emptyHint:"Without slots this node still runs tasks using its provider order. Add a slot to send specific task difficulties or capabilities to a specific tool.",empty:"No slots (optional)",moveUp:"Move up",moveDown:"Move down",removeSlot:"Remove slot",provider:"Provider",select:"(select)",model:"Model",providerDefault:"(provider default)",custom:"Custom…",modelPlaceholder:"model",backToModelList:"← Back to model list",thinking:"Thinking",thinkingDefault:"(default)",difficulty:"Difficulty (blank = freeform tasks only)",capabilityTags:"Capability tags (comma-separated)",maxParallel:"Max parallel (per slot)",maxParallelPlaceholder:"unlimited",addSlot:"Add slot",saving:"Saving…",saveSlots:"Save slots"},tagEditor:{emptyHint:"Tasks can run here without matching any specific tag. Add tags to target this node from a task's required tags.",noSpaces:"Tags cannot contain spaces.",reservedPrefix:"That prefix is auto-derived — pick a different tag.",alreadyAdded:"Already added.",routingTags:"Routing tags",autoDerivedTitle:"Auto-derived — can't be edited",customTagTitle:"Custom tag",remove:"Remove {{tag}}",addPlaceholder:"add a custom tag (e.g. test-runner)",add:"Add",saving:"Saving…",saveTags:"Save tags",empty:"No tags (optional)"},queue:{title:"Queue",description:"Inspect active queue work separately from historical completed, failed, and cancelled task records.",statActive:"Active",statPending:"Pending",statAssigned:"Assigned",statStale:"Stale",statHistorical:"Historical",statCompleted:"Completed",statFailed:"Failed",loading:"Loading...",refresh:"Refresh Queue",refreshHint:"Refresh the queue to view host-owned task counts and recent assignments.",empty:"Queue is empty.",staleBadge:"stale",staleTitle:"Stale assignment",waitingOnTitle:"Waiting on: {{tasks}}",waitsOn_one:"waits on {{count}} task",waitsOn_other:"waits on {{count}} tasks",blocked:"blocked",durationTitle:"Dispatched → terminal wall clock",retry_one:" · {{count}} retry",retry_other:" · {{count}} retries",node:"node {{id}}",session:"session {{id}}"},promptPreview:{connectPrompt:"Connect a daemon to preview the default.",errorRender:"Failed to render the default prompt",hide:"Hide the default prompt",view:"View the default prompt",rendering:"Rendering…",retry:"Retry",info:"This is what a coordinator session gets when Override is empty.",launchScopeNote:"Mission, recent activity and operating notes are added at launch and are not shown here."},hermesMcp:{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",fallbackProvider:"Hermes CLI"},providerAutoApprove:{partialInventoryChip_other:"{{count}} nodes pending",partialInventoryChip_one:"{{count}} node pending",title:"Provider auto-approve defaults",loading:"Loading provider defaults…",loadError:"Failed to load provider auto-approve defaults.",noProviders:"No CLI providers with auto-approve modes detected on this mesh's machines.",awaitingNodes:"Waiting for {{count}} node(s) to report their installed providers…",partialInventory:"Provider list may be incomplete — {{count}} node(s) have not reported yet.",noHostDaemon:"Connect the mesh host daemon to configure provider auto-approve defaults.",repoSection:{chip:"Shared with team",title:"Repository default",hint:"Committed to .adhdev/mesh.json — shared with the whole team. Sets which mode a delegated worker requests; it does not grant permission to run it.",usesProviderDefault:"Uses provider default",clear:"Use provider default"},machineSection:{chip:"This machine only",title:"This machine authorization",hint:"Local only (meshes.json) — never committed. Controls whether workers on THIS machine auto-approve at all, and whether dangerous modes are allowed.",autoApproveToggleLabel:"Delegated worker auto-approve",autoApproveToggleHint:"When off, workers delegated to this machine stop at every approval prompt.",dangerousToggleLabel:"Allow dangerous modes on this machine",dangerousToggleHint:"Opt-in: workers on this machine may run dangerous modes that execute tools with no approval at all.",dangerousDisabledHint:"No effect while auto-approve above is off.",confirmTitle:"Opt in to dangerous modes",confirmDescription:"This allows delegated workers on this machine to run dangerous provider modes. In a dangerous mode the agent executes tools and commands with no approval prompts at all.",confirmScopeLabel:"Scope",confirmScopeValue:"This machine only (local meshes.json — never committed)",confirmEffectLabel:"Effect",confirmEffectValue:"Repo-requested dangerous modes (e.g. Force, fully autonomous) are no longer downgraded to a safer interactive mode on this machine.",confirmConfirm:"Opt in"},effectiveSection:{statusDowngradedHint:"{{requested}} was requested, but this machine hasn't allowed dangerous modes, so it runs {{mode}}.",statusRequested:"Runs: {{mode}}",statusInvalidFallback:"Requested mode not found → runs provider default: {{mode}}",statusDowngraded:"{{mode}} (downgraded)",statusDisabled:"Auto-approve disabled on this machine — worker will ask for approval.",statusNone:"No usable auto-approve mode — worker will ask for approval."},dangerous:{sharedWarningDetail:"Saved in .adhdev/mesh.json. Each machine runs it only after opting in (delegatedWorkerDangerousModeAllow).",sharedWarningTitle:"This is committed to the repository",sharedWarning:"Committed to the repo and shared with your team. Machines that haven't allowed dangerous modes run a safer mode instead."},saving:"Saving…",saved:"Saved to .adhdev/mesh.json",saveError:"Failed to save provider defaults."},graphs:{includeTerminal:"Include finished",loading:"Loading graphs…",shown_one:"{{count}} graph shown",shown_other:"{{count}} graphs shown",loadMore_one:"Load {{count}} more graph",loadMore_other:"Load {{count}} more graphs",serverLimitHidden_one:"{{count}} older graph hidden · maximum 100",serverLimitHidden_other:"{{count}} older graphs hidden · maximum 100",serverLimitReached:"The daemon returns at most 100 graphs."},status:{healthErrorChip:"Error",offlineMachinesTitle:"Not reporting: {{machines}}",badgeBootstrap:"Setting up",badgeUpdatePending:"Update pending",quotaClaudeRefreshChip:"Needs refresh",quotaClaudeSetupChip:"Set up",machineNotReportingHint:"We haven't heard from this machine, so its plan quota is unknown.",quotaNotCollectedHint:"A machine reports its plan quota after its first refresh (about 15 minutes) and only while an agent has been active.",schedulingNotReportedHint:"This machine runs an older version that doesn't report scheduling details.",schedulingNotReported:"Update the daemon to see scheduling",schedulingTitle:"Scheduling",distributionTitle:"Distribution decides how work without a target is spread across nodes. Per-node load and limits are listed below.",protocolTitle:"Protocol & provider versions",noNodesReporting:"No nodes reporting runtime yet.",quotaNotCollected:"No quota yet",quotaFreshnessHint:"Last updated",machineNotReporting:"Offline · quota unknown",quotaClaudeSetupHint:"Set up Claude quota with `adhdev quota claude:install`.",quotaClaudeRefreshHint:"Open a Claude Code session once to refresh quota.",quotaAccountHint:"The signed-in account this quota belongs to, as reported by the provider CLI",quotaOkNoWindows:"No limit",healthNotGitRepo:"Not a git repo",healthProbePending:"Checking…",healthPeerConnection:"Connection {{state}}",healthNoLiveReport:"No report yet",badgeWorktree:"worktree",badgeWorktreeTitle:"Local worktree node",badgeWorktreeBranchTitle:"Worktree branch {{branch}}",badgeBootstrapTitle:"Worktree bootstrap is still in progress",badgeConnectionTitle:"Mesh peer connection state",badgeSessions_one:"{{count}} session",badgeSessions_other:"{{count}} sessions",badgeFastForwardReady:"fast-forward ready",badgeFastForwardReadyTitle:"Clean, behind upstream — safe for fast-forward",badgeStaleBuildTitle:"Live daemon was built behind workspace HEAD — merged fixes may not be live",badgeDeployLagTitle:"Running daemon build commit differs from origin/main — deploy + restart pending for this node",machinesNotReporting_one:"{{count}} offline",machinesNotReporting_other:"{{count}} offline",machinesSection:"Machines — plan · nodes",versionSkewTitle:"Version differs from this machine’s consensus (stale report or partial install)",machineVersionsTitle:"Provider CLI versions installed on this machine — shared by all its nodes"},overview:{tasksCount_other:"{{count}} tasks",tasksCount_one:"{{count}} task",sessionCount_other:"{{count}} sessions",sessionCount_one:"{{count}} session",leaseExpired:"lease expired",providerUnknown:"provider unknown",truncated:"(truncated)",missionCard:"Missions",ledgerCard:"Activity",queueCard:"Queue",nodesCard:"Nodes",sessionsCard:"Active sessions",refineCard:"Refine jobs",recentActivity:"Recent activity",recentTasks:"Recent tasks",missionTasksHeading:"Mission tasks",showFewer:"Show fewer",showMore:"+{{count}} more",noActiveMissions:"No active missions",missionDataUnavailable:"Update the daemon to see missions",completedHistory:"Completed / abandoned history",noQueueActivity:"No queue activity.",noNodes:"No nodes in this mesh yet.",noActiveSessions:"No active sessions.",noRefineJobs:"No refine jobs.",closeDetail:"Close detail",loadingGoal:"Loading…",showFullGoal:"Show full goal",statCompleted:"Completed",statAssigned:"Assigned",statPending:"Pending",statFailed:"Failed",statBlocked:"Blocked",statCancelled:"Cancelled",statWallClock:"Wall clock",statTotalRuntime:"Total runtime",statRetries:"Retries",statDispatched:"Dispatched",statStalled:"Stalled",statSessions:"Sessions",statCheckpoints:"Checkpoints",statActive:"Active",statPaused:"Paused",statAbandoned:"Abandoned",recentFailures:"{{count}} recent failures",activeCount:"{{count}} active",failedCount:"{{count}} failed",detailKickerMission:"Mission",detailKickerLedger:"Ledger entry",detailKickerQueue:"Queue task",detailKickerSession:"Session",detailKickerGate:"Gate",detailLabelGraph:"Graph",detailLabelRef:"Step",detailLabelOutcome:"Outcome",detailLabelMissionId:"Mission id",detailLabelCreated:"Created",detailLabelUpdated:"Updated",detailLabelElapsed:"Elapsed",detailLabelFullInstruction:"Show full instruction",detailLabelLastActivity:"Last task activity",detailLabelIncompleteEvidence:"Incomplete evidence",incompleteTaskCount_one:"{{count}} task",incompleteTaskCount_other:"{{count}} tasks",detailLabelEntryId:"Entry id",detailLabelWhen:"When",detailLabelNode:"Node",detailLabelDependsOn:"Depends on",detailLabelSession:"Session",detailLabelProvider:"Provider",detailLabelPayload:"Show raw payload",detailLabelTaskId:"Task id",detailLabelFinalSummary:"Final summary",detailLabelFullFinalSummary:"Show full report",detailFinalSummaryLoading:"Loading final summary…",detailFinalSummaryUnavailable:"Final summary unavailable",detailLabelAutoLaunch:"Auto launch",detailLabelCancelReason:"Cancel reason",detailLabelRequeueReason:"Requeue reason",detailLabelRequeued:"requeued {{count}}",detailLabelSessionId:"Session id",detailLabelBranch:"Branch",detailLabelRole:"Role",detailLabelStarted:"Started",detailLabelWorkspace:"Workspace",routingHeading:"Routing",routingDevice:"Device",routingDaemon:"Daemon",routingExecution:"Execution",routingVia:"Via",routingDifficulty:"Difficulty",routingFitness:"Fitness",routingReason:"Reason",routingRequiredTags:"Required tags",routingTagsUnsatisfied:"unsatisfied",routingSkipped:"Skipped candidates",routingSkippedMore:"+{{count}} more",pausedMissions:"Paused missions",ledgerAllTime:"all-time totals",detailLabelGateAfter:"After",detailLabelGateUnlocks:"Unlocks",sessionTasksHeading:"Tasks in this session",showOnCanvas:"Show on canvas"}},ok={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."},ak={debugBundleFailed:"Couldn't collect debug info",replicaDegradedShort:"Sync degraded",connectingToMachine:"Connecting to your machine",establishingP2P:"Establishing P2P connection",agentNotMonitored:"Agent not monitored",clickToSwitchMonitoring:"Click to switch monitoring to this agent",agentPanelHidden:"Agent panel is not visible yet",openPanelHint:"Open the chat in your IDE",noMessagesYet:"No messages yet",loadingChat:"Loading chat...",openPanel:"Open {{label}} Panel",switchingPanel:"Switching...",openingPanel:"Opening...",replicaDegraded:"Live sync is having trouble — showing messages the previous way",busyNoProgress:"Agent shows no progress.",busyGenerating:"Agent is generating.",busyWaitingApproval:"Waiting for approval",activityToggleLabel:"Tool steps",activityToggleTitle:"Show tool, terminal and thinking steps",reconnectMachine:"Reconnect",reconnectingMachine:"Reconnecting…",reconnectMachineTitle:"Automatic reconnection gave up on this machine — reconnect now"},ik={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"},lk={cdpDisconnectedShort:"IDE disconnected",hideFromDashboard:"Hide from dashboard",removeShortcut:"Remove shortcut",changeShortcut:"Change shortcut ({{shortcut}})",meshChat:"Mesh chat",dropSplitRight:"Split right",dropMoveHere:"Move here",dropSplitLeft:"Split left",relaunchWithCdp:"Relaunch with connection",cdpDisconnected:"Not connected to the IDE — chat history and screenshots are unavailable.",resizeHandleHint:"Drag to resize · Double-click to merge",shortcutListening:"Listening…",shortcutPressCombo:"Press a key combination (e.g. {{example1}}, {{example2}})",shortcutSetTitle:"Set shortcut",loadingSessions:"Loading sessions...",noConversations:"No conversations yet",waitingForDaemon:"Waiting for your daemon",connectYourMachines:"Connect your machines",daemonDescription:"Start the ADHDev daemon to connect.",installDescription:"Install ADHDev on a machine and sign in.",newSession:"New session",newSessionDescription:"Start a session with any installed agent.",noTabsInGroup:"No tabs in this group",pressEscToCancel:"Press Esc to cancel",noActiveAgent:"No active agent",moveTabHere:"Move a tab here to view"},ck={growViewport:"Enlarge terminal view",shrinkViewport:"Shrink terminal view",sendInterrupt:"Send interrupt (Ctrl-C)",arrowRight:"Arrow right",arrowDown:"Arrow down",arrowLeft:"Arrow left",arrowUp:"Arrow up",keysPanelTitle:"Terminal keys",keysButton:"Keys",copyHint:"Copy the selected terminal text, or the visible screen if nothing is selected",specDebugHint:"Spec debug — inspect current state, sections, and transition history",replayScrollbackHint:"Load earlier terminal output so you can scroll farther up",loadOlderOutput:"Load older terminal output",loadingOlder:"Loading older...",debug:"Debug",copy:"Copy",openControlKeys:"Open terminal control keys",closeControlKeys:"Close terminal control keys"},dk={muteThis:"Mute this chat",unmuteThis:"Unmute this chat"},uk={switchToTerminal:"Switch to Terminal view",switchToChat:"Switch to Chat view"},mk={updatedAt:"Updated {{time}}",messageCountShort_other:"{{count}} msgs",messageCountShort_one:"{{count}} msg",workspaceUnknown:"Workspace unknown",clearSelection:"Clear",selectedSavedHistory:"Selected saved history",loadingShort:"Loading…",savedHistoryNoneYet:"No saved history",savedHistoryLoadedCount_other:"{{count}} saved histories loaded. Open saved history to choose one.",savedHistoryLoadedCount_one:"{{count}} saved history loaded. Open saved history to choose one.",savedHistoryBadge:"Saved history",resumeSavedHistory:"Resume saved history",startFresh:"Start fresh",resumingSavedHistory:"Resuming saved history…",startingFresh:"Starting fresh…",startIde:"Start IDE",startingIde:"Starting IDE…",startAcpSession:"Start ACP session",startingAcpSession:"Starting ACP session…",recoverHostedRuntime:"Recover hosted runtime",hostedRuntimeRecoveryDescription:"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead.",openSavedHistory:"Open saved history",savedHistoryTitle:"Saved History",savedHistoryHelper:"Use saved history when you want continuity in the same provider conversation.",savedHistoryEmpty:"No saved history found yet.",refreshSavedHistory:"Refresh saved history",refreshingSavedHistory:"Refreshing saved history…",startFreshWith:"Start fresh with {{label}}?",restart:"Restart {{label}}?",startFreshReview:"Review the provider and target folder before starting fresh.",restartIdeReview:"Review or change the target workspace before restarting this IDE.",restartStoppedReview:"Review or change the target workspace before restarting this stopped session.",confirmStartFresh:"Start fresh",confirmRestart:"Restart",confirmStartingFresh:"Starting fresh…",confirmRestarting:"Restarting…",resumeWith:"Resume saved history with {{label}}?",resumeReview:"Review or change the target workspace before resuming saved history."},hk={layout:{expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse"},auth:{loading:"Loading standalone dashboard…",loadError:"Failed to load standalone auth status: {{error}}",signInTitle:"Standalone sign-in",passwordProtected:"This self-hosted dashboard is protected by a local password.",tokenProtected:"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session.",passwordPlaceholder:"Enter standalone password",unlock:"Unlock dashboard",signingIn:"Signing in…",noPasswordEnabled:"Password login is not enabled on this server."},machine:{loading:"Loading machine...",awaitingInput:"Awaiting your input ↑"},settings:{restartToApply:"Restart to apply",providersLink:"Providers",providersIntro:"IDEs and agents on this machine:",title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",publicHostWarning:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token.",daemonSection:"Daemon",versionLabel:"Version",statusLabel:"Status",statusRunning:"● Running",statusNotConnected:"○ Not connected",authLabel:"Auth",authPassword:"Password enabled",authToken:"Token enabled",authNone:"No auth configured",networkSection:"Network Access",networkHint:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token.",localhostLabel:"Localhost only",localhostHint:"Bind to 127.0.0.1. Best when only this machine should open the dashboard.",allInterfacesLabel:"All interfaces",allInterfacesHint:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points.",saveNetworkMode:"Save default network mode",saving:"Saving…",networkRestartHint:"Applies on next standalone restart. Current run stays bound to {{host}}.",networkSavedAll:"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.",networkSavedLocal:"Default standalone network mode set to localhost only. Restart standalone to apply it.",securitySection:"Dashboard Security",passwordSet:"A local password is currently required for browser access. Existing sessions are rotated when you change it.",passwordNotSet:"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended.",currentPasswordPlaceholder:"Current password",currentPasswordFirstTimePlaceholder:"Current password (not needed for first setup)",newPasswordPlaceholder:"New password",newPasswordFirstTimePlaceholder:"New standalone password",confirmPasswordPlaceholder:"Confirm new password",updatePassword:"Update password",enablePassword:"Enable password",disablePassword:"Disable password",passwordUpdated:"Standalone password updated.",passwordEnabled:"Standalone password enabled.",passwordDisabled:"Standalone password disabled.",passwordTooShort:"Password must be at least 4 characters.",passwordMismatch:"New password and confirmation do not match.",appearanceSection:"Appearance",fontsLabel:"Fonts",fontsDescription:"Standalone-only typography overrides for chat text, markdown code, and terminal output.",fontsSaved:"Standalone chat fonts saved for this self-hosted dashboard.",profileSection:"Profile",displayNameLabel:"Display Name",displayNameHint:"Your name shown in chat threads and on the team dashboard.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Welcome to ADHDev",selectedCount_one:"{{count}} provider selected",selectedCount_other:"{{count}} providers selected",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",intro:"Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from Machines → Providers.",loadingRegistry:"Loading registry…",loadError:"Failed to load registry: {{error}}",noProviders:"No providers in this category.",installed:"✓ installed",installFailed:"✗ {{error}}"},about:{title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",selfHostedEdition:"Self-hosted edition",headline:"Keep the same dashboard experience, with the runtime fully on-device.",description:"Standalone keeps the browser, daemon, screenshots, and control path entirely on your own machine. Aside from multi-machine connectivity and mobile notifications, it is the same core product experience as Cloud.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Try Cloud ↗",includedSection:"Included in standalone",includedDescription:"The local-first feature set available without the cloud control plane.",inventorySection:"Built-in inventory",inventoryDescription:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",cloudExtrasSection:"Cloud-only extras",cloudExtrasDescription:"Capabilities that need the hosted control plane or team infrastructure.",comparisonSection:"Self-hosted vs Cloud",comparisonDescription:"The product split at a glance.",featureHeader:"Feature",selfhostHeader:"Selfhost",cloudHeader:"Cloud",cloudOptional:"Cloud is optional, not required",cloudOptionalDescription:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",compareCloud:"Compare Cloud ↗",discord:"Discord ↗",features:{localFirst:{title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},chatRelay:{title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},screenshots:{title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},remoteControl:{title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},multiIde:{title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},cliAcp:{title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}},extras:{anywhere:{title:"Access from anywhere",desc:"Reach your machines from another laptop or phone without opening local ports."},p2pStream:{title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},mobileNotifications:{title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},restApi:{title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},teamWorkspace:{title:"Team workspace",desc:"Share machines, activity views, and policies across a team workspace."},enterpriseControls:{title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}},comparison:{chatRelay:"Agent chat relay",screenshots:"Live IDE screenshots",remoteControl:"Remote IDE control",multiIde:"Multi-IDE monitoring",extensionCli:"Extension and CLI agents",anyNetwork:"Access from any network",webrtc:"WebRTC P2P streaming",mobilePush:"Mobile push notifications",restApi:"REST API and webhooks",teamCollaboration:"Team collaboration",multiMachineDashboards:"Multi-machine dashboards",ssoRbacAuditLogs:"SSO, RBAC, audit logs"}},fonts:{fontOverridesNotice:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below.",chat:"Chat text",chatDescription:"Assistant/user prose, markdown text, thought cards, and system notes.",code:"Code blocks",codeDescription:"Markdown code fences, inline code, and preformatted command output.",terminal:"Terminal",terminalDescription:"Terminal transcript cards and tool/command rows in chat mode.",livePreview:"Live preview",resolvedStack:"Resolved stack:",saveFontSettings:"Save font settings",revertToSaved:"Revert to saved",resetToDefaults:"Reset to defaults",saving:"Saving…",customFamilyPlaceholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',previewSummary:"Chat: {{chat}} · Code: {{code}} · Terminal: {{terminal}}",defaultsSummary:"Defaults: {{chat}} / {{code}}",previewNow:"now",previewProse:"Readable prose, <strong>bold text</strong>, and <code>inline code</code> should all follow your standalone font choices.",presets:{default:"Default",defaultMono:"Default mono",custom:"Custom…",serif:"Serif"}}},pk={login:{eyebrow:"Cloud sign-in",title:"Sign in to ADHDev",subtitle:"Connect your machines, get approval and completion notifications, and keep your coding agents moving when you are away from your desk.",continueWith:"Continue with {{provider}}",connecting:"Connecting...",devDivider:"dev",devLogin:"Dev Login (test_jwt_token)",providerNote:"GitHub and Google are used only for authentication.",errorUnverifiedEmail:"This login provider did not return a verified email, so we could not safely sign you in.",termsPrefix:"By continuing, you agree to our ",termsLink:"Terms of Service",termsAnd:" and ",privacyLink:"Privacy Policy",termsSuffix:"."},account:{openMachines:"Open Machines",machinesSummaryShort:"{{count}} of {{limit}}",title:"Account",subtitle:"Profile, plan & activity",tabAccount:"Account",tabBilling:"Billing",tabActivity:"Activity",profile:"Profile",noName:"No name",displayName:"Display Name",displayNameDesc:"Your name shown in the dashboard and team workspaces.",nicknamePlaceholder:"Nickname",save:"Save",saving:"...",cancel:"Cancel",saved:"Saved",edit:"Edit",failedToSave:"Failed to save",userId:"User ID",loadingProfile:"Loading profile...",planLimits:"Plan limits",limitMachines:"Machines",limitP2P:"Connected machines",limitPushNotifications:"Daily Push Notifications",limitTurnRelay:"Relay fallback",enabled:"Enabled",disabled:"Disabled",frozen:"Frozen",session:"Session",logout:"Logout",logoutDesc:"Sign out of your ADHDev account on this device.",dangerZone:"Danger zone",dangerZoneDesc:"Permanently delete your account and all associated data. This action cannot be undone.",deleteAccount:"Delete account",deleteWillRemove:"This will permanently delete:",deleteItemProfile:"Your profile and login credentials",deleteItemKeys:"All API keys and connection tokens",deleteItemWebhooks:"Webhooks and delivery history",deleteItemPush:"Push notification subscriptions",deleteItemSessions:"Shared sessions and audit logs",deleteTypeConfirm:"Type {{keyword}} to confirm:",deleting:"Deleting...",permanentlyDelete:"Permanently delete",failedToDeleteAccount:"Failed to delete account",registeredMachines:"Registered Machines",machinesSummary:"{{count}} registered · {{online}} online",machinesLimit:"(limit: {{limit}})",loadingMachines:"Loading machines...",noMachinesRegistered:"No machines registered",runSetupPrefix:"Run ",runSetupMiddle:", then start ",runSetupSuffix:" on a machine to register it here.",removeMachineConfirm:"Remove this machine? It will need to run `adhdev setup` again to reconnect.",failedToDeleteMachine:"Failed to delete machine",failedToUpdate:"Failed to update",rename:"Rename",online:"Online",connecting:"Connecting",removeMachine:"Remove machine",never:"Never",frozenFeatureTitle:"Frozen — this feature is paused and not available."},billing:{currentPlan:"Current Plan:",statusTrial:"Trial",statusActive:"Active",statusPastDue:"Past Due",statusCanceled:"Canceled",nextBilling:"Next billing: {{date}}",trialEnds:"Trial ends: {{date}}",accessUntil:"Access until: {{date}}",updatePayment:"Please update your payment method",managePayment:"Manage Payment & Invoices",couldNotOpenPortal:"Could not open billing portal",checkoutSuccess:"Your subscription is active. Thanks for upgrading!",statMachines:"Machines",statSharedSessions:"Shared Sessions",statTurnRelay:"TURN Relay",statTurnOn:"On",resetsDailyUtc:"Resets daily at 00:00 UTC",resetsInHours_one:"~{{count}}h left",resetsInHours_other:"~{{count}}h left",resetsInMinutes_one:"~{{count}}m left",resetsInMinutes_other:"~{{count}}m left",resetsDailyUtcWithLeft:"Resets daily at 00:00 UTC · {{left}}",monthly:"Monthly",yearly:"Yearly",savePercent:"Save up to {{pct}}% yearly",pricesInUsd:"All prices in USD",paddleLoading:"Paddle is loading, please try again.",cancelConfirm:"Are you sure you want to cancel your subscription? You will retain access until the end of your billing period.",cancelSubscription:"Cancel Subscription",cancelRetainAccess:"You will retain access to {{plan}} features until the end of your current billing period.",cancelTeamDowngrade:" All team members will be downgraded to their personal plans.",cancelFailed:"Failed to cancel subscription"},about:{title:"About",subtitle:"Cloud overview, supported surfaces, and plan-level capabilities",cloudEdition:"Cloud edition",heroTitle:"Control your local CLI agents from anywhere — web or mobile.",heroDesc:"ADHDev Cloud surfaces the agents running on your machines in your browser: send prompts, approve actions, orchestrate work across machines, and get notified on your phone — code flows P2P directly to your daemon, never through the server.",openDashboard:"Open Dashboard",viewMachines:"View Machines",docs:"Docs ↗",whyTitle:"Why ADHDev Cloud",whyDesc:"Core capabilities available when your machines are connected through the cloud control plane.",howTitle:"How it works",howDesc:"The cloud onboarding path from install to remote control.",repoMeshTitle:"Repo Mesh",repoMeshDesc:"Orchestrate agents across machines — cloud only.",meshCard1Title:"One coordinator, many agents",meshCard1Desc:"Enqueue tasks against a mission and let idle nodes claim work from a local-first, pull-based queue. Fan out across machines and providers — Claude Code on one, Codex on another — then converge the results from a single coordinator session.",meshCard2Title:"Same repo, many machines at once",meshCard2Desc:"Each node is a checkout or an isolated git worktree, so parallel agents never collide. The refinery converges every branch — validate, merge, push, clean up — with safe submodule handling. Runs over a direct daemon-to-daemon P2P channel; the server only signals and authorizes same-account peers.",worksWith:"Works with",worksWithDesc:"Supported CLI agents, IDEs, and AI extensions.",groupCli:"CLI Agents",groupIdes:"IDEs",groupExtensions:"AI Agents",pricingTitle:"Pricing",pricingDesc:"Current cloud plans and machine capacity by tier.",planPopular:"Popular",readyTitle:"Ready to connect a machine",readyDesc:"Jump into your dashboard, inspect your connected machines, or continue in the docs if you are still setting up.",dashboard:"Dashboard",machines:"Machines",discord:"Discord ↗",github:"GitHub ↗",features:{webControlTitle:"Web control of local CLI agents",webControlDesc:"Drive any local CLI agent — Claude Code, Codex, Cursor CLI — from your browser: send prompts, approve actions, and steer sessions without touching the terminal.",chatRelayTitle:"Agent chat relay",chatRelayDesc:"Read and respond to agent conversations from anywhere, including mobile surfaces.",liveViewTitle:"Live session view",liveViewDesc:"Watch agent activity in real time; for IDE sessions, view and control the screen over P2P without switching windows.",mobileTitle:"Mobile-ready",mobileDesc:"Receive approvals and check progress while away from your development machine.",secureTitle:"Secure by default",secureDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC — the cloud handles auth and signaling metadata only. Your code never routes through the server."},steps:{step1Title:"One-line Install",step1Desc:"Run a single command on any machine you want to drive. It installs the ADHDev daemon plus the adhdev CLI.",step2Title:"Sign In",step2Desc:"Sign in with GitHub or Google and the daemon pairs itself to your account — no token to copy.",step3Title:"Drive Your Agents from Anywhere",step3Desc:"The machine appears in your dashboard instantly. Launch and control Claude Code, Codex, Cursor CLI, and other CLI agents from the web — IDE sessions too."},plans:{freeName:"Free",proName:"Pro",ultraName:"Ultra",freePer:"/mo",proPer:"/mo",ultraPer:"/mo",freeFeature1:"1 machine",freeFeature2:"Real-time chat relay",freeFeature3:"Web control for your local agents",proFeature1:"2 machines",proFeature2:"Unlimited AI agents",proFeature3:"P2P remote view",ultraFeature1:"5 machines — flat, not per-seat",ultraFeature2:"Everything in Pro",ultraFeature3:"Higher concurrency & usage limits",ultraFeature4:"Unlimited daily screenshot minutes"}},layout:{adminSection:"Admin",adminOverview:"Overview",adminUsers:"Users",adminAuditLogs:"Audit Logs",adminSystem:"System",adminTokens:"Admin Tokens",adminEntry:"Admin",footerPlanTitle:"Current plan: {{plan}} — manage or upgrade",expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse",logout:"Logout",machineLimitBadge:"Machines full",machineLimitBadgeTitle:"You've reached your plan limit of {{count}} machine{{plural}} — open billing to upgrade",pushBudget:"Daily notifications {{used}}/{{limit}}"},settings:{title:"Settings",subtitle:"Appearance & preferences",appearanceTitle:"Appearance"},planCard:{unlimited:"Unlimited",machineSingular:"{{count}} machine",machinePlural:"{{count}} machines",sharedSessionSingular:"{{count}} shared session",sharedSessionPlural:"{{count}} shared sessions",teamMemberSingular:"{{count}} team member",teamMemberPlural:"{{count}} team members",turnIncluded:"TURN relay included",recommended:"Recommended",currentPlan:"Current Plan",contactUs:"Contact Us",freeForever:"Free Forever",startTrial:"Start 7-day free trial",upgradeTo:"Upgrade to {{name}}",noChargeCancel:"No charge for 7 days. Cancel anytime.",periodSeatMo:"seat/mo",periodMo:"mo",yearlyNote:"${{yearly}}/year — Save ${{saved}}",pricingCustom:"Custom"},activity:{origin:{ide:"IDE",extension:"Extension",admin:"Admin",webhook:"Webhook",web:"Dashboard",user:"User",terminal:"Terminal",system:"System",registry:"Registry",mesh:"Mesh",machine:"Machine",daemon:"Daemon",connection:"Connection",cli:"CLI",auth:"Sign-in",api_key:"API key",api:"API",agent:"Agent"},filterPlaceholder:"Filter by action, resource, or source...",refresh:"Refresh",loading:"Loading...",noLogs:"No logs",noMatchingLogs:"No matching logs found.",logsWillAppear:"Actions will appear here as they happen.",colAction:"Action",colResource:"Resource",colSource:"Source",colTime:"Time",logCount:"{{count}} logs",logCountFiltered:" (filtered from {{total}})",action:{login:"Logged in",logout:"Logged out",api_key_create:"Created API key",api_key_revoke:"Revoked API key",agent_command:"Sent agent command",terminal_exec:"Ran terminal command",ide_command:"Sent IDE command",daemon_command:"Sent daemon command",daemon_disconnect:"Disconnected daemon",daemon_revoke:"Revoked daemon",webhook_create:"Created webhook",webhook_delete:"Deleted webhook",webhook_toggle:"Toggled webhook",registry_publish:"Published provider",registry_promote:"Promoted provider",registry_yank:"Yanked provider",registry_publish_token_issued:"Issued registry publish token",machine_registered:"Registered machine",machine_secret_rotated:"Rotated machine secret",shortcut_launch:"Launched session",shortcut_stop:"Stopped session",shortcut_chat:"Sent chat message",shortcut_chat_debug_bundle:"Exported chat debug bundle",shortcut_approve:"Approved agent action",shortcut_reject:"Rejected agent action",shortcut_git_push:"Pushed git changes",shortcut_git_checkpoint:"Created git checkpoint",shortcut_mesh_clone_node:"Cloned mesh node",shortcut_mesh_remove_node:"Removed mesh node",shortcut_mesh_refine_node:"Refined mesh node",admin_plan_change:"Changed user plan",admin_role_change:"Changed user role",admin_user_suspend:"Suspended user",admin_user_unsuspend:"Unsuspended user",admin_machine_delete:"Deleted machine",admin_token_create:"Created admin token",admin_apikey_rate_limit:"Changed API key rate limit",admin_apikey_scopes:"Changed API key scopes",admin_apikey_revoke:"Revoked API key",admin_plan_limits_update:"Updated plan limits",admin_plan_limits_reset:"Reset plan limits",admin_config_update:"Updated system config",admin_announcement:"Posted system announcement",admin_disconnect:"Disconnected connection"}},webhooks:{title:"Webhooks",subtitle:"Real-time event notifications",addWebhook:"+ Add Webhook",eventDaemonConnect:"Daemon Connected",eventDaemonDisconnect:"Daemon Disconnected",eventAgentStatus:"Agent Status Change",eventApprovalRequired:"Approval Required",failed:"Failed",deleteConfirm:"Delete this webhook?",testFailed:"Test failed",secretTitle:"Webhook Secret",secretShownOncePrefix:"Shown ",secretShownOnce:"only once",secretShownOnceSuffix:". Use to verify ",copy:"Copy",done:"Done",newWebhook:"New Webhook",labelUrl:"URL",urlPlaceholder:"https://your-service.com/webhook",labelEvents:"Events",allEvents:"All Events (*)",creating:"Creating...",create:"Create",cancel:"Cancel",loading:"Loading...",noWebhooks:"No webhooks",noWebhooksDesc:"Receive real-time notifications about events.",setupFirst:"Set up first webhook",off:"OFF",autoDisabled:"Auto-disabled",autoDisabledTitle:"Auto-disabled after 10 consecutive failures",failuresWarning:"{{count}} failures",failuresTitle:"{{count}} consecutive failures — will auto-disable at 10",all:"ALL",history:"History",test:"Test",delete:"Delete",deleting:"...",recentDeliveries:"Recent Deliveries",refresh:"Refresh",noDeliveries:"No deliveries yet. Send a test to verify the endpoint.",request:"REQUEST",response:"RESPONSE",securityTitle:"Security",securityVerifyPrefix:"Verify ",securityVerifySuffix:" with your secret",securityHttps:"Use HTTPS endpoints only",securityAsync:"Return 2xx immediately, process async",securityAutoDisable:"Auto-disabled after 10 consecutive failures"},apiKeys:{title:"API Keys",keyCount:"{{count}} keys",playground:"Playground",create:"+ Create",scopeDaemonRead:"Daemon Read",scopeDaemonReadDesc:"List daemons & status",scopeDaemonControl:"Daemon Control",scopeDaemonControlDesc:"Commands, launch/stop, disconnect",scopeAgentRead:"Agent Read",scopeAgentReadDesc:"Status & chat history",scopeAgentControl:"Agent Control",scopeAgentControlDesc:"Send, approve/reject",scopeTerminal:"Terminal",scopeTerminalDesc:"Execute commands",scopeWebhooks:"Webhooks",scopeWebhooksDesc:"Manage hooks & deliveries",frozen:"Frozen",revokeConfirm:"Revoke this API key? This cannot be undone.",failedToLoad:"Failed to load",failed:"Failed",upgradePlan:"Upgrade your plan →",keyCreated:"Key Created!",copyNow:"Copy now — shown only once.",copied:"Copied",copy:"Copy",testKey:"Test",dismiss:"Dismiss",playgroundTitle:"API Playground",enterKeyToTest:"Enter an API key to test.",open:"Open",createKeyTitle:"Create API Key",labelName:"Name",namePlaceholder:"e.g. Production Bot",permissions:"Permissions ({{count}})",createBtn:"Create",cancel:"Cancel",loading:"Loading...",noKeys:"No API Keys",noKeysDesc:"Create a key to integrate with external services.",createFirstKey:"Create First Key",usedDate:"Used {{date}}",neverUsed:"Never used",revoke:"Revoke",usageLabel:"Usage:",apiReference:"API Reference →",frozenFeatureTitle:"Frozen — this feature is paused."},shareModal:{title:"Share Session",chatLabel:"Chat",chatDesc:"AI conversation only",remoteLabel:"Remote",remoteDesc:"Screenshot + desktop",permissionLabel:"Permission Level",authRequired:"Account required",expiresAfter:"Expires After",maxViewers:"Max Viewers",hide:"Hide",activeShares:"Active Shares",creating:"Creating...",createChatLink:"Create Chat Link",createRemoteLink:"Create Remote Link",expires:"expires",revoke:"Revoke",shareLinkCreated:"Share link created!",viewerMustLogin:"Viewer must be logged in to use this link",copy:"Copy",copied:"Copied!",expiresAt:"Expires:",done:"Done",failedToCreate:"Failed to create share link",expiry1h:"1 hour",expiry6h:"6 hours",expiry24h:"24 hours",expiry7d:"7 days",chatView:{label:"View Only",desc:"Read AI conversation in real-time"},chatControl:{label:"Control",desc:"Read + send messages + approve/reject actions"},remoteView:{label:"View Only",desc:"Watch screenshots + chat in real-time"},remoteControl:{label:"Control",desc:"Screenshots + send messages + approve/reject"},remoteFull:{label:"Full Access",desc:"Full remote control including desktop input"}},onboarding:{title:"Connect your first machine",subtitle:"Install ADHDev on a machine and sign in — it pairs itself and shows up here. Then drive every agent on it from this dashboard.",platformMac:"macOS / Linux",platformWindows:"Windows",copyTitle:"Click to copy",copiedLabel:"✓ Copied",copyLabel:"Copy",listeningLabel:"Listening for your daemon — keep this page open, it will appear automatically.",connectingLabel:"Connecting to ADHDev…",step1Title:"Install the daemon",step1Desc:"Run the command above on any machine you want to drive. It installs the daemon plus the adhdev CLI.",step2Title:"Sign in — the machine pairs itself",step2Desc:"The daemon links to this account automatically. No token to copy; it appears here the moment it connects.",step3Title:"Launch your first session",step3Desc:"Once a machine is online, start Claude Code, Codex, Cursor, and other agents straight from the dashboard.",readDocs:"Read the documentation →",reconnectingLabel:"Connection lost — reconnecting… Check your network if this persists.",offlineLabel:"You're offline. Reconnect to the internet and this page will resume automatically.",authFailedLabel:"Session expired — sign in again to continue.",machineLimitLabel:"Machine limit reached — your plan allows up to {{limit}}. Remove a machine or upgrade your plan to connect this one.",machineLimitManage:"Manage machines →",machineLimitUpgrade:"Upgrade plan →",setupWizardLink:"Prefer a guided setup? Open the Setup Wizard →"},legal:{navHome:"Home",navDashboard:"Dashboard",footerHome:"Home",footerTerms:"Terms",footerPrivacy:"Privacy",footerRefund:"Refund Policy",footerCopyright:"© 2026 RacoLab. All rights reserved."},authCallback:{authFailed:"Authentication Failed",backToLogin:"Back to Login",completing:"Completing authentication...",noTokenError:"No access token received"},cliAuth:{title:"ADHDev CLI Authentication",verifying:"Verifying...",authorizeAs:"Authorize CLI as {{name}}?",noCodeError:"No authentication code provided.",approve:"✓ Approve",signInFirst:"Please sign in first to authorize the CLI.",signIn:"Sign In →",failed:"Failed",successMessage:"CLI authentication complete!",returnToTerminal:"You can return to the terminal.",registryPublishTitle:"Authorize Registry Publishing",authorizeRegistryPublishAs:"Grant provider registry publishing access as {{name}}?",registryPublishWarning:"This grants a short-lived token (15 minutes) that can publish, promote and yank provider packages in the registry. It is not a daemon registration. Only approve this if you started a registry publish yourself. Requires an admin account.",signInFirstRegistryPublish:"Please sign in with an admin account to authorize registry publishing.",approving:"Approving…",errorFriendly:"Couldn't complete CLI authorization.",tryAgain:"Try again"},privacy:{title:"Privacy Policy",lastUpdated:"Last updated: September 27, 2026",intro:'This Privacy Policy describes how RacoLab ("we", "us", "our") collects, uses, and protects your information when you use the ADHDev service ("Service") at',s1Title:"1. Information We Collect",s1h1:"1.1 Account Information",s1p1:"When you create an account, we collect information provided by your authentication provider (GitHub or Google), including your name, email address, and profile picture.",s1h2:"1.2 IDE & Agent Data",s1p2:"When you connect your development environment to the Service, the local daemon may transmit:",s1l1:'IDE type and version (e.g., "Cursor 0.49.1")',s1l2:"Active AI agent information (name, status, current model)",s1l3:"Chat messages between you and AI agents",s1l4:"IDE screenshots (transmitted via P2P, not stored on our servers)",s1l5:"Workspace paths and open file names",s1l6:"Machine information (hostname, OS, memory usage)",s1h3:"1.3 Usage Data",s1p3:"We automatically collect usage information including API calls, feature usage patterns, and connection logs for service improvement and debugging purposes.",s1p3Attribution:"We also count visits by traffic source in aggregate only (campaign tags such as utm_source, the referring website's domain and the landing page, kept in your browser's local storage — no IP address, device identifier or cookie), and when you create an account we record the source of your first visit so we can see which channels bring new users.",s1h4:"1.4 Payment Information",s1p4:"Payment processing is handled entirely by our Merchant of Record, Paddle (Paddle.com Market Limited). We do not directly collect or store credit card numbers, bank account details, or other financial information. Please refer to",s1p4PaddleLink:"Paddle's Privacy Policy",s1p4Suffix:"for their data handling practices.",s2Title:"2. How We Use Your Information",s2p1:"We use collected information to:",s2l1:"Provide and maintain the Service",s2l2:"Authenticate your identity and manage your account",s2l3:"Route commands and data between your dashboard and connected machines",s2l4:"Send notifications (browser and push) about agent status changes",s2l5:"Process billing and subscription management (via Paddle)",s2l6:"Detect and prevent abuse or unauthorized access",s2l7:"Improve the Service and develop new features",s2l8:"Respond to support requests",s3Title:"3. Data Storage & Security",s3h1:"3.1 Infrastructure",s3p1:"Our Service runs on Cloudflare's global network using Cloudflare Workers, Durable Objects, and D1 Database. Data is stored in Cloudflare's infrastructure and is subject to",s3p1CloudflareLink:"Cloudflare's Privacy Policy",s3h2:"3.2 P2P Data",s3p2:"IDE screenshots and real-time terminal data are transmitted directly between your browser and your machine via WebRTC peer-to-peer connections. This data does not pass through or get stored on our servers.",s3h3:"3.3 Security Measures",s3p3:"We implement the following security measures:",s3l1:"JWT-based authentication with short-lived access tokens and refresh token rotation",s3l2:"Encrypted WebSocket connections (WSS/TLS)",s3l3:"Per-connection tokens for daemon authentication",s3l4:"Rate limiting on all API endpoints",s3l5:"Audit logging for security-sensitive operations",s4Title:"4. Data Sharing",s4p1:"We do not sell your personal data to third parties. We may share data with:",s4l1:"Payment processing as Merchant of Record",s4l2:"Infrastructure provider (hosting, CDN, database)",s4l3Label:"Authentication providers",s4l3:"GitHub/Google for OAuth login",s4p2:"We may disclose data if required by law, legal process, or to protect our rights and the safety of our users.",s5Title:"5. Data Retention",s5p1:"We retain your account data for the duration of your active account. Chat messages and agent activity data are retained for up to 90 days for service functionality.",s5p2:"Upon account deletion, we will remove your personal data within 30 days. Some anonymized usage data may be retained for analytical purposes.",s6Title:"6. Your Rights",s6p1:"You have the right to:",s6l1Label:"Access",s6l1:"Request a copy of your personal data",s6l2Label:"Correction",s6l2:"Update or correct your personal information",s6l3Label:"Deletion",s6l3:"Request deletion of your account and associated data",s6l4Label:"Export",s6l4:"Download your data in a portable format",s6l5Label:"Object",s6l5:"Object to certain data processing activities",s6p2:"To exercise these rights, contact us at",s7Title:"7. Cookies",s7p1:"We use essential cookies only for authentication (session tokens) and user preferences (theme, notification settings). We do not use advertising or tracking cookies.",s8Title:"8. Children's Privacy",s8p1:"The Service is not intended for users under the age of 16. We do not knowingly collect personal information from children under 16.",s9Title:"9. International Data Transfers",s9p1:"Your data may be processed in various locations through Cloudflare's global network. By using the Service, you consent to the transfer and processing of your data in these locations.",s10Title:"10. Changes to This Policy",s10p1:"We may update this Privacy Policy from time to time. We will notify you of any material changes by email or through the Service. Your continued use after changes constitutes acceptance of the updated policy.",s11Title:"11. Contact",s11p1:"For questions about this Privacy Policy or data practices:",s11l1Prefix:"Email:",s11l2Prefix:"Website:"},terms:{title:"Terms of Service",lastUpdated:"Last updated: April 11, 2026",intro:'Welcome to ADHDev ("Service"), operated by RacoLab ("we", "us", "our"). By accessing or using our Service at',introSuffix:'you agree to be bound by these Terms of Service ("Terms"). If you do not agree, do not use the Service.',s1Title:"1. Service Description",s1p1:"ADHDev is a cloud developer tool that provides remote monitoring and control of AI coding agents (such as Cursor, VS Code, Antigravity, Claude Code, and others) through web and mobile dashboard surfaces. The Service includes a local daemon, remote dashboards, REST API access, and browser and push notifications.",s2Title:"2. Account Registration",s2p1:"You must create an account to use the Service. You are responsible for maintaining the confidentiality of your account credentials. You agree to provide accurate and complete information during registration and to keep your account information up to date.",s2p2:"You must be at least 16 years old to use the Service. By creating an account, you represent that you meet this age requirement.",s3Title:"3. Subscription Plans & Billing",s3p1:"The Service offers the following plans:",s3l1:"Limited features, 1 connected machine",s3l2:"2 connected machines, unlimited agents, P2P remote view, 7-day free trial",s3l3:"5 connected machines, everything in Pro plus higher concurrency and usage limits (flat price, not per-seat)",s3p2:"Paid subscriptions are billed in advance on a monthly or yearly basis. All payments are processed by our payment partner, Paddle (Paddle.com Market Limited), who acts as the Merchant of Record for all transactions.",s4Title:"4. Refund Policy",s4p1:"We offer a 14-day money-back guarantee for all paid plans. If you are not satisfied with the Service, you may request a full refund within 14 days of your initial purchase by contacting us at",s4p2:"Refunds for renewals are handled on a case-by-case basis. Paddle's refund policies also apply as they are the Merchant of Record.",s5Title:"5. Acceptable Use",s5p1:"You agree not to:",s5l1:"Use the Service for any unlawful purpose or in violation of any applicable laws",s5l2:"Attempt to gain unauthorized access to other users' accounts or data",s5l3:"Reverse-engineer, decompile, or attempt to extract the source code of the Service's server components",s5l4:"Use the Service to transmit malware, spam, or other harmful content",s5l5:"Resell or redistribute the Service without our written consent",s5l6:"Interfere with or disrupt the integrity or performance of the Service",s6Title:"6. Intellectual Property",s6p1:"The Service, including its original content, features, and functionality, is owned by RacoLab and is protected by applicable intellectual property laws. The local daemon component is available under an open-source license as specified in the project repository.",s6p2:"You retain ownership of all data and content you transmit through the Service.",s7Title:"7. Data & Privacy",s7p1:"Your use of the Service is also governed by our",s7PrivacyLink:"Privacy Policy",s7p1Suffix:"The Service processes IDE interactions, chat messages, and screenshots for the purpose of remote monitoring and control. We do not sell your data to third parties.",s8Title:"8. Service Availability",s8p1:"We strive to maintain high availability but do not guarantee uninterrupted access. The Service may be temporarily unavailable due to maintenance, updates, or circumstances beyond our control. We are not liable for any losses resulting from service interruptions.",s9Title:"9. Limitation of Liability",s9p1:"TO THE MAXIMUM EXTENT PERMITTED BY LAW, RacoLab SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR ANY LOSS OF PROFITS OR REVENUES, WHETHER INCURRED DIRECTLY OR INDIRECTLY, ARISING OUT OF YOUR USE OF THE SERVICE.",s9p2:"Our total liability for any claim arising from the Service shall not exceed the amount you paid us in the 12 months preceding the claim.",s10Title:"10. Termination",s10p1:"We may suspend or terminate your access to the Service at any time for violations of these Terms or for any other reason at our sole discretion. You may cancel your account at any time through the Settings page. Upon cancellation, your data will be deleted within 30 days.",s11Title:"11. Changes to Terms",s11p1:"We reserve the right to modify these Terms at any time. We will notify you of material changes via email or through the Service. Your continued use after changes constitutes acceptance of the modified Terms.",s12Title:"12. Governing Law",s12p1:"These Terms shall be governed by and construed in accordance with the laws of the Republic of Korea, without regard to conflict of law provisions.",s13Title:"13. Contact",s13p1:"If you have any questions about these Terms, please contact us:",s13l1Prefix:"Email:",s13l2Prefix:"Website:"},refund:{title:"Refund Policy",lastUpdated:"Last updated: March 24, 2026",intro:"ADHDev is operated by RacoLab. All payments are processed by our Merchant of Record,",introSuffix:"who manages billing, invoicing, and refunds on our behalf.",s1Title:"1. 14-Day Money-Back Guarantee",s1p1:"We offer a 14-day money-back guarantee on all paid plans (Pro). If you are not satisfied with the Service for any reason, you may request a full refund within 14 days of your initial subscription purchase.",s1p2:"To request a refund, contact us at",s1p2Suffix:"with your account email and order details. We will process your request within 3 business days.",s2Title:"2. Renewal Refunds",s2p1:"Refunds for subscription renewals (monthly or yearly) are handled on a case-by-case basis. If you were charged for a renewal you did not intend, please contact us within 7 days of the charge at",s3Title:"3. Non-Refundable Cases",s3p1:"Refunds will not be issued for:",s3l1:"Requests made after the 14-day guarantee period for initial purchases",s3l2Prefix:"Accounts suspended or terminated due to violations of our",s3l2Link:"Terms of Service",s3l3:"Partial months of service already used beyond the refund window",s4Title:"4. How Refunds Are Processed",s4p1:"Approved refunds are processed through Paddle and returned to the original payment method. Depending on your bank or card issuer, refunds may take 5–10 business days to appear. Paddle's own",s4p1RefundLink:"refund terms",s4p1Suffix:"also apply.",s5Title:"5. Cancellation",s5p1Prefix:"You may cancel your subscription at any time from the",s5p1BillingLink:"Billing",s5p1Suffix:"page in your dashboard. Cancellation stops future charges. You retain access to your plan's features until the end of the current billing period. Cancellation alone does not trigger a refund.",s6Title:"6. Contact",s6p1:"For refund requests or billing questions:",s6l1Prefix:"Email:",s6l2Prefix:"Website:"},sessionShare:{loading:"Loading session...",sessionNotFound:"Session Not Found",noLongerAvailable:"This session is no longer available",homeBtn:"← ADHDev Home",sharedSession:"Shared Session",host:"Host",mode:"Mode",permission:"Permission",auth:"Auth",authRequired:"Account required",viewers:"Viewers",joinChat:"Join Chat",joinSession:"Join Session",expires:"Expires: {{date}}",chatLabel:"Chat",remoteLabel:"Remote",waitingMessages:"Waiting for messages...",connecting:"Connecting... ({{state}})",sendMessageAs:"Send message as {{name}}...",sendAs:"Send as {{name}}...",ownerChat:"{{name}}'s Chat",ownerSession:"{{name}}'s Session",agentName:"{{name}}'s Agent",fullControlBadge:"Full Control Active",failedToJoin:"Failed to join session",sessionRevoked:"Session has been revoked by the host",sessionExpired:"Session has expired",authRequired2:"Authentication required for control share",unknownError:"Unknown error"},apiPlayground:{title:"API Playground",history:"History ({{count}})",apiRelayWarning:"Daemon API relay is opt-in. REST command/chat proxy routes stay disabled unless that daemon explicitly enables them with `adhdev daemon:api enable`.",authBearer:"Authorization: Bearer {{key}}",copyAsCurl:"cURL",copied:"Copied",targetDaemon:"Target Daemon",quickActions:"Quick Actions",requestBody:"Request Body (JSON)",recentRequests:"Recent Requests",clearHistory:"Clear",noDaemonsWarning:"No daemons connected. Start a daemon first or replace {daemonId} manually.",send:"▶ Send",sending:"⏳"},announcementBanner:{visibleUntil:"Visible until {{time}}",dismiss:"Dismiss"},push:{budgetResetsShort:"Resets at {{time}}",budgetRemainingShort:"{{count}} left on your plan today",budgetShort:"{{used}}/{{limit}} today",title:"Push Notifications",descUnsupported:"Not supported in this browser",descDenied:"Blocked — enable in browser settings",descEnabled:"On",descDefault:"Alerts even when the tab is closed",docsLink:"Push Notifications docs",sent:"Sent",test:"Test",iosHint:"On iPhone and iPad, push only works from the installed Safari PWA. A normal Safari tab cannot receive ADHDev push notifications.",unsupportedWarning:"This browser does not support Web Push here. Use Safari PWA on iPhone/iPad or a Chromium browser on desktop/Android.",deniedWarning:"Notifications are blocked in browser or site settings. Re-enable them there, then turn Push Notifications on again.",registeredDevices:"Registered devices: {{count}}",noDevices:"No active push devices found.",deviceLabel:"Device {{number}}",thisDevice:"This device",lastActive:"Last active",removing:"Removing...",removeHere:"Remove here",remove:"Remove"},mesh:{manualMcpSetup:"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",couldNotLoadMeshes:"Could not load meshes",untitledMesh:"Untitled mesh",chooseMachineFirst:"Choose a machine first.",launchFailed:"Launch failed",coordinatorLaunchFailed:"Coordinator launch failed",coordinatorLaunched:"Coordinator launched ({{sessionId}})",coordinatorLaunchSent:"Coordinator launch command sent"},plans:{free:"Free",pro:"Pro",ultra:"Ultra",team:"Team",enterprise:"Enterprise"},adminAudit:{title:"Global Audit",subtitle:"System-wide event tracking",allActions:"All Actions",allSources:"All Sources",filter:"Filter",noLogs:"No logs found",loading:"Loading...",loadMore:"Load More ↓"},adminDashboard:{failedToLoad:"Failed to load admin data",title:"Admin Dashboard",subtitle:"Service overview & management",accessDenied:"Admin access denied",backToDashboard:"Back to Dashboard",loading:"Loading admin dashboard",loadingDesc:"Collecting service stats and recent audit activity.",totalUsers:"Total Users",todayCommands:"Today Commands",activeApiKeys:"Active API Keys",todayLogins:"Today Logins",planDistribution:"Plan Distribution",quickActions:"Quick Actions",manageUsers:"Manage Users",apiKeys:"API Keys",auditLogs:"Audit Logs",systemConfig:"System Config",recentActivity:"Recent Activity",viewAll:"View All",noRecentActivity:"No recent activity"},adminTokens:{title:"Admin Tokens",subtitle:"Issue admin-scoped API tokens for deploy automation",superAdminOnly:"Super admin only",superAdminOnlyDesc:"Only a super admin can issue admin tokens. Ask a super admin if you need one.",issueTitle:"Issue a new token",nameLabel:"Name",namePlaceholder:"e.g. deploy-ci",scopesLabel:"Scopes",scopesHint:"admin covers most admin APIs. super_admin also allows issuing tokens and changing roles — grant it only when required.",expiryLabel:"Expires in",expiryDays:"{{count}} days",expiryHint:"Admin tokens always expire. The server caps the lifetime at 90 days.",issue:"Issue token",issuing:"Issuing...",issuedTitle:"Copy your token now",issuedWarning:"This is the only time the token is shown. Store it somewhere safe — you cannot retrieve it again.",issuedMeta:"Scopes: {{scopes}} · Expires: {{expiresAt}}",copy:"Copy",copied:"Copied",copyFailed:"Copy failed — select the token and copy it manually",dismiss:"Dismiss",expiryClamped:"Expiry was shortened to the 90-day maximum",existingTitle:"Active admin tokens",emptyTitle:"No admin tokens",emptyDesc:"Issue one above to authenticate deploys without the browser login.",expiresAt:"Expires: {{time}}",lastUsed:"Last used {{time}}",neverUsed:"Never used",noExpiry:"No expiry",expired:"Expired",revoke:"Revoke",revokeConfirm:'Revoke the token "{{name}}"? Anything using it will stop working immediately.',revoked:"Token revoked",loading:"Loading...",error:"Error: {{message}}"},adminSystem:{error:"Error: {{message}}",announcementSent:"Announcement sent",announcementCleared:"Announcement cleared",title:"System Settings",subtitle:"Announcements & system configuration",loading:"Loading system settings",loadingDesc:"Fetching current announcement state.",announcement:"Announcement",current:"Current:",untilTime:"(until {{time}})",untilCleared:"(until cleared)",announcementPlaceholder:"Enter announcement message...",severityInfo:"Info",severityWarning:"Warning",severityCritical:"Critical",duration1h:"1 hour",duration6h:"6 hours",duration24h:"24 hours",duration7d:"7 days",durationUntilCleared:"Until cleared",send:"Send"},adminUsers:{error:"Error: {{message}}",roleUpdated:"Role updated",planUpdated:"Plan updated",suspensionReasonPrompt:"Enter suspension reason:",userSuspended:"User suspended",userUnsuspended:"User unsuspended",title:"User Management",subtitle:"Manage users, roles, and suspension",usersTotal:"users total",searchPlaceholder:"Search email or name...",allRoles:"All Roles",roleUser:"User",roleAdmin:"Admin",roleSuperAdmin:"Super Admin",allPlans:"All Plans",search:"Search",colUser:"User",colRole:"Role",colPlan:"Plan",colStatus:"Status",colCreated:"Created",colActions:"Actions",noName:"No name",statusSuspended:"Suspended",statusActive:"Active",unsuspend:"Unsuspend",suspend:"Suspend",loading:"Loading...",prev:"← Prev",next:"Next →"}},fk={onboardingTour:{next:"Next",getStarted:"Get started",learnMore:"Learn more in the docs",closeAria:"Close onboarding",allSetStandalone:{desc:"This dashboard is already connected to your local daemon. Start a session from the Dashboard tab, or add more providers under Machines → Providers.",title:"You're all set"},getStartedCloud:{desc:"Run this on any machine you want to drive, then sign in — the daemon pairs itself to your dashboard automatically.",title:"Get started"},orchestrate:{desc:"Repo Mesh (Cloud Pro) lets one coordinator hand work to agents across many machines — parallel git worktrees, automatic branch convergence, and cross-checking the same repo from several angles.",title:"Orchestrate your agents"},watchAndSteer:{desc:"Follow each agent's session in real time and steer it as it works — switch sessions, take screenshots, and (for IDE sessions) view and control the screen over a direct connection.",title:"Watch and steer, live"},realtimeChat:{desc:"See what your AI agent is doing in real time. Send messages, approve or reject actions — all from your browser or phone.",title:"Real-time chat"},welcome:{desc:"Drive any local CLI coding agent — Claude Code, Codex, Antigravity CLI — straight from your browser or phone. The agents keep running on your machine; you control them from the web.",title:"Welcome to ADHDev"}},installCommand:{orViaNpm:"Or via npm:",clickToCopy:"Click to copy"},errorBoundary:{reload:"Reload page",description:"An unexpected error occurred. Please reload the page to continue.",title:"Something went wrong"},shellFreshness:{dismissAria:"Dismiss update notice",later:"Later",reload:"Reload",message:"A new version of ADHDev is available."},openMenu:"Open menu",closeMenu:"Close menu"},gk={loadingOlderMessages:"Loading older messages...",waitingForMessages:"Waiting for messages...",agentGenerating:"Agent generating...",jumpToTop:"Jump to top",jumpToOldestMessages:"Jump to oldest messages",top:"↑ Top",latest:"↓ Latest",jumpToLatestMessages:"Jump to latest messages",jumpToBottom:"Jump to bottom",showEarlierMessages:"↑ Show {{count}} earlier messages...",showEarlierMessagesHidden:"↑ Show {{count}} earlier messages... ({{total}} hidden)",loadOlderMessages:"↑ Load older messages",loadErrorRetry:"↻ {{error}}"},bk={zoomOut:"Zoom Out",zoomIn:"Zoom In",resetZoom:"Reset Zoom",toggleFullscreen:"Toggle Fullscreen"},xk={screenshotAlt:"Remote View",mouse:"Mouse",touch:"Touch",connected:"Connected",ws:"Reconnecting",direct:"Direct",relay:"Relay",turnBlocked:"Relay limit reached",turnUsage:"TURN {{used}}/{{budget}}m",typeAndEnter:"Type & Enter...",settings:"SETTINGS",zoom:"ZOOM:",fill:"FILL",fit:"FIT",directP2PTitle:"Direct P2P connection",turnRelayTitle:"TURN relay in use",dailyTurnTitle:"Daily TURN relay usage",waitingState:{turnRelayActive:"TURN relay active"},waiting:{connectedLabel:"Connected. Waiting for first frame...",connectingLabel:"Connecting to Host...",reconnectingLabel:"Reconnecting to Host...",connectedHint:"The remote stream is warming up",reconnectingHint:"Waiting for the remote stream to catch up"},error:{title:"Remote connection lost",reasonFailed:"The connection to this host failed. Check that the daemon is running and try again.",reasonDisconnected:"Lost connection to the host and could not reconnect after 15 seconds.",retry:"Retry"},screenshotViewer:{altText:"IDE Screenshot",waitingForStream:"Waiting for screenshot stream...",p2pStatus:"P2P: {{state}}"}},yk={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"},vk={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"},wk={mobile:{noHistoryMatches:"No saved history matches these filters.",workspaceMissing:"(workspace missing)",resumableOnly:"Only ones that can be resumed",sortMessages:"Most messages",sortOldest:"Oldest first",sortRecent:"Most recent",filterModel:"Filter by model",filterWorkspace:"Filter by workspace",searchHistory:"Search title or preview",useThisFolder:"Use this folder",browseDescription:"Move through folders like a normal file browser, then use the current folder for this machine.",browseTitle:"Select workspace",machineDetails:"Machine details",inspect:"Inspect",createFolder:"Create folder",showMore:"Show {{count}} more",showFewer:"Show fewer",recentLaunches:"Recent launches",currentChats:"Current chats",machineFallback:"machine"},daemonUpdate:{previewUnknownDescription:"The app is connected to preview, but the server hasn't reported a preview target version yet.",previewUpToDateDescription:"This machine already runs the current preview daemon.",previewUnknownTitle:"Preview update status unknown",previewUpToDateTitle:"Preview daemon is up to date",mismatchDescription:"This machine runs a different daemon version than the current app. Update it before starting more sessions.",previewUpgradeDescription:"This machine can be updated to the current preview daemon without opening a remote shell.",requiredDescription:"This machine is on an incompatible daemon version. Update it before starting more sessions.",mismatchTitle:"Version mismatch detected",requiredTitle:"Daemon update required",upgrade:"Update",updateNow:"Update now"},launchPick:{empty:"No saved workspaces yet. Add one in the Workspace tab or type a path above.",description:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path.",title:"Where should this run?"},workspacePicker:{noneSelected:"No workspace selected. This starts in the home folder.",selectedWorkspace:"Selected workspace",defaultWorkspace:"Default workspace",enterPathFirst:"Enter a full folder path to start there.",browseFirst:"Browse to a folder before starting there.",enterPath:"Enter a full folder path…",customPath:"Custom path…",selectWorkspace:"Select workspace…",noneSaved:"(no saved workspaces — add one in the Workspace tab)",noWorkspaceHome:"(no workspace — start in home folder)"},trustBadge:{externalUntrustedHint:"From a source you added, and it includes code that ADHDev will run. Review the source before enabling.",externalSafeHint:"From a source you added. Settings only — ADHDev never runs code from it.",trustedWithScriptsHint:"Provided officially by ADHDev. Includes scripts that ADHDev runs.",trustedHint:"Provided officially by ADHDev. Settings only — no provider code runs.",userCustomHint:"You wrote this provider in your own providers folder. It runs your own code.",externalUntrusted:"External · runs code",externalSafe:"External",trustedWithScripts:"Official · scripts",trusted:"Official",userCustom:"Custom"},providerSettings:{option:{high:"High",medium:"Medium",low:"Low"},notifications:{description:"Show notifications when {{provider}} changes state.",label:"Notifications"},showCoordinatorSystemPrompt:{description:"Show the injected system prompt as a message in the chat. Off by default — you can always see it in the chat header's Session Info (ⓘ).",label:"Show system prompt message"},showTerminal:{description:"Show terminal commands and their output in the chat.",label:"Show terminal"},showToolCalls:{description:"Show short summaries of tool calls (searched, edited, …) in the chat.",label:"Show tool calls"},showThinking:{description:"Show the agent's reasoning in the chat.",label:"Show thinking"},longGeneratingThresholdSec:{description:"How long a reply can run before the long-running alert fires.",label:"Long-running threshold (seconds)"},longGeneratingAlert:{description:"Notify you when a reply takes unusually long.",label:"Long-running alert"},approvalAlert:{description:"Notify you when {{provider}} is waiting for your approval.",label:"Approval notifications"},appPathOverride:{description:"Optional full path to the IDE app. Leave blank to look in the usual install locations.",label:"App path"},cliPathOverride:{description:"Optional full path to the IDE command-line launcher. Leave blank to use the detected one.",label:"CLI launcher path"},executableArgs:{description:"Optional arguments that replace the default ones when {{provider}} starts. Leave blank to use the defaults.",label:"Launch arguments"},executablePath:{description:"Optional full path to the {{provider}} program. Leave blank to find it on your PATH.",label:"Executable path"},autoApprove:{description:"Approve {{provider}} tool calls and prompts automatically, without asking you first.",label:"Auto approve"},enabled:{description:"Turn this on before ADHDev detects, launches, or checks {{provider}} on this machine.",label:"Enabled on this machine"},thisProvider:"this provider"},launchConfirm:{workspace:"Workspace",languageModel:"Language Model (Optional)",autoDetect:"Auto-detect or default",cliArgs:"CLI Arguments (Optional)",cliArgsPlaceholder:"e.g. --experimental",cancel:"Cancel",closeAria:"Close launch confirmation",launch:"Launch",launching:"Launching…"},confirmExternal:{aboutToActivateFrom:"You're about to turn on {{provider}} from {{source}}.",aboutToActivate:"You're about to turn on {{provider}}.",dialogAria:"Confirm untrusted external provider",title:"Activate untrusted external provider?",description:"This manifest ships JavaScript that the daemon will execute. Treat as untrusted code — review the source before enabling.",proceedWarning:"Only proceed if you trust the source URL you added and have reviewed the manifest.",cancel:"Cancel",activate:"Activate"},providers:{advancedHint:"Sources, load paths and provider details",filter:"Filter",sourceConfigTitle:"Provider source config",sourceConfigDesc:"Where the daemon looks for provider manifests. Affects resolution and reloads.",sourceMode:"Source mode",explicitProviderDir:"Explicit providerDir",providerDirPlaceholder:"Leave blank to use ~/.adhdev/providers",applying:"Applying…",applyReload:"Apply + Reload",userRoot:"User root:",upstreamRoot:"Upstream root:",providerRoots:"Provider roots:",loadingSettings:"Loading provider settings…",noProviders:"No providers installed yet — use Install above, or add a source under Advanced.",noFilteredProviders:"No {{filter}} providers installed.",refresh:"Refresh",updateAll:"Update all",advanced:"Advanced",newChannelTypesTitle:"Available to install",newChannelTypesDesc:"Published to the verified channel but never installed on this machine. Install activates the digest-verified bundle.",installNewType:"Install",modelListTitle:"Model lists",modelListStaleDesc:"Could not read the model list from these CLIs (signed out, offline, or unsupported output). The provider manifest's list is being used and may be out of date.",modelListStaleBadge:"unverified",installFailedTitle:"Install failed",installFailedDigestMismatch:"Install failed — try later",loadFailed:"Failed to load provider settings: {{error}}",quotaToggleFailed:"Failed to update quota probe for {{provider}}: {{error}}"},sourcesPanel:{title:"External sources",description:"3rd-party git URLs you've added. Providers here may ship JavaScript the daemon will execute — activation requires a confirmation.",addSource:"+ Add source",empty:'No external sources registered. Use "+ Add source" to register a 3rd-party provider git URL.',remove:"Remove",removing:"…",removeConfirmTitle:"Remove provider source {{name}}?",removeConfirmDescription:"This deletes the cloned manifests and clears any active-source entries that pointed here.",removeConfirmLabel:"Remove",conflictsTitle:"Conflicts",conflictsDescription:"Multiple sources expose the same provider type. Pick which source's copy should be active.",active:"Active",switchActiveTo:"Switch active to {{name}}",addTitle:"Add external source",gitUrl:"Git URL",ref:"Ref (branch/tag)",name:"Name (optional, auto-derived from URL)",cancel:"Cancel",cloning:"Cloning…",cloneAndRegister:"Clone + register",loadFailed:"Failed to load sources",addFailed:"Failed to add source",removeFailed:"Failed to remove source",setActiveFailed:"Failed to set active source"},providerRow:{detectDisabledHint:"Turn the provider on before checking it",detectHint:"Check that the configured program can be found and run",lifecycleDeprecated:"No longer supported",lifecycleExperimental:"Experimental",lifecycleBeta:"Beta",lifecycleStable:"Stable",checkFailed:"Failed",checkOk:"OK",statusDetected:"Detected",statusNotDetected:"Not detected",statusEnabledUnchecked:"Enabled (unchecked)",statusDisabled:"Disabled",labelType:"Type:",labelVersion:"Version:",labelBinary:"Binary:",labelStatus:"Status:",labelDetails:"Details:",labelSource:"Source:",labelTrust:"Trust:",labelLinks:"Links:",labelDetection:"Detection:",labelVerification:"Verification:",saving:"saving…",disable:"Disable",enable:"Enable",detect:"Detect",resetCommand:"Reset command",quotaAccountLabel:"Show account on quota",quotaAccountLabelHint:"Label this provider's plan quota with the signed-in account. Off means the account is never fetched, not just hidden.",quotaAccountLabelOn:"On",quotaAccountLabelOff:"Off",quotaTracking:"Quota tracking",quotaTrackingHint:"Periodically read this provider's plan quota for the dashboards. Off stops the reads entirely.",quotaTrackingOn:"On",quotaTrackingOff:"Off",quotaClaudeConfirmTitle:"Enable Claude quota tracking?",quotaClaudeConfirmBody:"Claude Code has no quota API, so ADHDev reads usage through its statusLine — the only path available. Enabling replaces the statusLine command in ~/.claude/settings.json with the ADHDev wrapper. Your existing command keeps running inside the wrapper and its output is passed through unchanged, so your prompt looks the same. No other setting in the file is modified. The current value is backed up first and can be restored with `adhdev quota claude:uninstall`.",quotaClaudeConfirmOk:"Enable and install",quotaClaudeConfirmCancel:"Cancel",labelSpecPin:"Spec pin:",labelActivatedAt:"Activated:",labelPreviousPin:"Previous pin:",labelDigest:"Digest:",specPinStale:"update {{latest}}",specPinStaleHint:"This machine loads an older spec. Channel offers {{latest}}.",updateInline:"Update",updateInlineHint:"Channel offers {{latest}}. Download, verify and activate it on this machine.",specPinUpdating:"Updating…",specPinRollback:"Roll back",specPinRollbackHint:"Return to spec {{version}} (local, no download).",specPinRollingBack:"Rolling back…"},installOptions:{title:"Set up {{provider}}",quotaLabel:"Track plan usage",quotaHint:"Periodically read this provider's plan quota so the dashboards and `adhdev quota` can show what's left. Off stops the reads entirely — nothing is collected.",quotaClaudeNote:"Claude Code has no quota API, so this installs the ADHDev statusLine wrapper into ~/.claude/settings.json. Your existing command keeps running inside it, and the original is backed up.",autoApproveLabel:"Approve tool calls automatically",autoApproveHint:"When this agent asks permission to run a command, edit a file or use a tool, ADHDev answers yes for you. You will not see the approval prompt, and the action runs without waiting.",autoApproveWarning:"The agent can run commands on this machine without asking you first. Turn this off to approve each one yourself.",cancel:"Cancel",confirm:"Enable provider"},card:{status:{offline:"Offline",failed:"Connection failed",connecting:"Connecting…",attention:"Online · sync delayed",online:"Online"},slowLink:"Slow link",coresCount_other:"{{count}} cores",coresCount_one:"{{count}} core",onMachine:"on {{machine}}",sectionIDEs:"IDEs",sectionCLIs:"CLIs",sectionACPAgents:"ACP Agents",cpu:"CPU",mem:"MEM",loading:"Loading your machines…",emptyHeadline:"Welcome to ADHDev",emptyBody:"Connect your first machine to the dashboard. Install ADHDev on that machine and sign in — it pairs automatically and appears here:",emptyDocsLink:"Read the documentation →",hidden:"Hidden",pageTitle:"Machines",burrowCount_one:"{{count}} machine",burrowCount_other:"{{count}} machines",onlineCount_one:"{{count}} online",onlineCount_other:"{{count}} online",agentsActive_one:"{{count}} agent active",agentsActive_other:"{{count}} agents active",activeNow:"Active Now",generating:"generating",connectionFailed:"Connection failed",reconnect:"Reconnect",transportRelay:"Connected through a relay server — slower than a direct link. Usually a firewall or NAT blocks the direct path.",transportDirect:"Direct connection",beacon:{lastSyncedBehindPart_other:", {{count}} records still to receive",lastSyncedBehindPart_one:", {{count}} record still to receive",soleCopyTooltip_other:"{{entries}} records on this machine are not yet backed up on another machine. Keep it online until another machine has synced.",soleCopyTooltip_one:"{{entries}} record on this machine is not yet backed up on another machine. Keep it online until another machine has synced.",soleCopyLabel_other:"{{count}} records not backed up",soleCopyLabel_one:"{{count}} record not backed up",behindTooltip_other:"This machine hasn't received {{count}} recent records from your other machines yet. It usually catches up on its own.",behindTooltip_one:"This machine hasn't received {{count}} recent record from your other machines yet. It usually catches up on its own.",behindLabel:"Sync delayed",deferredLabel:"Backup unconfirmed",deferredTooltip:"Couldn't confirm that everything on this machine is backed up: only some of your machines could be compared. This is not an error.",lastSyncedTooltip:"Last synced {{minutes}} min ago{{behindPart}}."},fleetPeer:{stateOffline:"offline",stateOnline:"online",divergedLabel:"Sync delayed",tooltip:"The server sees this machine as {{wsState}} with {{wsCount}} sessions, but another of your machines saw {{peerState}} with {{peerCount}} sessions ({{age}}s ago). This usually settles within a few seconds."},noAgentsRunning:"No agents running yet",launchCta:"Launch →"},detail:{relaunchFailed:"Couldn't relaunch",launchProvider:"Provider",launchType:"Type",tabsAriaLabel:"Machine sections",tabSessions:"Sessions",notFound:"Machine not found",save:"Save",cancel:"Cancel",loading:"Loading machine...",offlineHint:"The machine may be offline or not yet connected.",back:"← Back",tabHostedRuntimes:"Hosted Runtimes",tabProviders:"Providers",tabSystem:"System",tabLogs:"Logs",clickToSetNickname:"Click to set nickname",nicknamePlaceholder:"Machine nickname...",reconnect:"Reconnect",p2pConnected:"connected",providerUpdatesAvailable:"Provider updates available",providerSyncSuccess:"Provider channel synced — {{count}} updated",providerSyncAlreadyCurrent:"Provider channel is already current",providerSyncFailed:"Provider update failed"},commandCenter:{updateStatusUnknown:"Update status unknown",upToDate:"Up to date",updateDaemon:"Update daemon",updateToVersion:"Update to v{{version}}",updateChannel:{preview:"preview",stable:"stable"},updateTargetWithChannel:"Target: v{{version}} ({{channel}})",updateTarget:"Target: v{{version}}",currentChats:"Current Chats",recentLaunches:"Recent Launches",daemonUpdate:"Daemon Update"},workspaceBrowse:{currentFolder:"Current folder",parent:"Parent",go:"Go",pathPlaceholder:"Type a folder path",loading:"Loading folders…",noSubfolders:"No subfolders here.",useThisFolder:"Use this folder"},managedWorkspaces:{setDefaultHint:"Set as default workspace",unsetDefaultHint:"Default workspace — click to unset",title:"Workspaces",addWorkspace:"Add workspace",empty:'No saved workspaces yet. Click "{{button}}" to pick a folder.',addDialogDescription:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",remove:"Remove",newSession:"Start a new session in this workspace",newSessionShort:"Session",newMeshSession:"Start a mesh coordinator session in this workspace",newMeshSessionShort:"Mesh",removeConfirmTitle:"Remove workspace",removeConfirmDescription:'Remove "{{label}}" from the list? The folder itself is not deleted.',rename:"Rename",renamePlaceholder:"Workspace name",saveName:"Save",cancelRename:"Cancel",renameFailed:"Could not update workspace name"},overview:{diagnostics:"Diagnostics",p2p:"P2P",daemonVersion:"Daemon version",cores:"CPU cores",platform:"Platform",hostname:"Hostname",aboutMachine:"This machine",approx:"(approx.)",memory:"Memory",cpuDetail:"{{load}} avg / {{cores}} cores",cpuLoad:"CPU load",resourceUsage:"Resource usage",waiting:"Waiting…",uptime:"Uptime",waitingForStats:"Waiting for live stats…",waitingForStatsWithTotal:"Waiting for live stats… · {{total}} total"},quota:{text:{failureKind:{unknown:"unknown error","no-data":"no reading yet","setup-required":"setup required",unsupported:"not supported","cli-unavailable":"program not found",parse:"unreadable response",server:"provider server error",network:"network error","rate-limited":"rate limited","quota-exhausted":"plan limit reached",unauthorized:"access denied","expired-token":"sign-in expired","missing-credentials":"not signed in"},agoDays:"{{days}}d {{hours}}h ago",agoHours:"{{hours}}h {{minutes}}m ago",agoMinutes:"{{minutes}}m ago",justNow:"just now",unreadable:"could not read quota",unavailable:"not available on this machine",pool:"pool",usageSessions:"{{count}} sess",usageTokens:"{{count}} tok",windowReset:"reset · awaiting refresh",cue:{stale:"stale",refreshing:"refreshing"},resetsInDays:"resets in {{days}}d {{hours}}h",resetsInHours:"resets in {{hours}}h {{minutes}}m",resetsInMinutes:"resets in {{minutes}}m",resetsNow:"resets now",used:"{{percent}}% used"},title:"Plan quota",sessionHint:"Rolling 5-hour plan window reported by this machine",weeklyHint:"Rolling 7-day plan window reported by this machine",monthlyHint:"Rolling 30-day billing window reported by this machine",bucketHint:"Per-pool quota bucket reported by this machine — pools on one plan reset independently",failureHint:"This machine reported that it could not read this provider's quota",okNoWindows:"No limit",okNoWindowsHint:"The quota fetch succeeded; this provider reports no percentage window (e.g. included-usage plans).",accountHint:"The signed-in account this quota belongs to, as reported by the provider CLI",usageHint:"Absolute usage over the trailing window — this provider routes to your own upstream accounts, so there is no plan limit to show a percentage against."},actions:{nicknameSyncFailed:"Nickname updated on the machine, but account sync failed",nicknameFailed:"Couldn't save nickname",nicknameSaved:"Nickname saved",pathMissing:"The path may be missing on disk",workspaceActionFailed:"Workspace update failed",workspaceAdded:"Workspace added",detectFailed:"IDE detection failed",usingDefaultWorkspace:"Using the default workspace",runningInHome:"Running in the home directory",launchPending:"{{name}} is starting — it will appear shortly",launchFailed:"Couldn't launch {{name}}",launching:"Launching {{name}}…",stopCliConfirmDescription:"This will terminate the process.",stopIdeConfirmDescription:"This will disconnect CDP and optionally kill the process.",stopped:"{{name}} stopped",launched:"{{name}} launched",stopFailed:"Couldn't stop",restartInitiated:"{{name}} restart initiated",restartFailed:"Couldn't restart",selectProviderFirst:"Select a CLI or ACP provider first",selectProvider:"Select a provider",workspaceRemoved:"Workspace removed",workspaceLabelUpdated:"Workspace name updated",defaultWorkspaceUpdated:"Default workspace updated",defaultWorkspaceCleared:"Default workspace cleared",idesFound_one:"Found {{count}} IDE",idesFound_other:"Found {{count}} IDEs"},logsTabSections:{view:"View",filterInfo:"Info+ ({{count}})",filterIssues:"Issues ({{count}})",filterAll:"All ({{count}})",searchPlaceholder:"Search diagnostics…",copyDiagnostics:"Copy diagnostics",copyVisible:"Copy visible",pause:"Pause",resume:"Resume",refresh:"↻ Refresh",clear:"Clear",advancedSourceScope:"Advanced source scope",daemonLevelPlus:"Daemon {{level}}+",diagnosticsTimeline:"Diagnostics timeline",visibleEventsIssues:"{{events}} visible event(s) · {{issues}} issue signal(s)",filteredBy:"Filtered by “{{query}}”",mergedByTime:"Daemon, trace, and browser signals merged by time",latestIssue:"Latest issue",noVisibleIssue:"No visible warn/error signal",sourceStatus:"Source status",needsAttention:"Needs attention",livePolling:"Live polling every 3s",paused:"Paused",lastUpdate:"Last update: {{time}}",notYetLoaded:"Not yet loaded",rawFile:"raw file",sourceDaemon:"daemon",sourceTrace:"trace",sourceBrowser:"browser",repeatedIssuePatterns:"Repeated issue patterns",unifiedTimeline:"Unified timeline",visibleDiagnosticEvents:"{{count}} visible diagnostic event(s)",hide:"Hide",show:"Show",loadingDiagnostics:"Loading diagnostics…",daemonLogsError:"Daemon logs: {{error}}",daemonTraceError:"Daemon trace: {{error}}",noDiagnosticsMatch:"No diagnostics match the current view.",rawSourceDaemonLogs:"Raw source · daemon logs",visibleRawLinesFallback:"{{count}} visible raw line(s) from file fallback",visibleStructuredLines:"{{count}} visible structured line(s)",loadingDaemonLogs:"Loading daemon logs…",noDaemonLogsYet:"No daemon logs captured yet for this machine.",noRawLinesMatchSearch:"No raw daemon log lines match the current search.",rawFallbackOnlyInAll:"Raw file-fallback logs are available only in All view.",noStructuredLogsMatch:"No structured daemon logs match the current view.",rawSourceDaemonTrace:"Raw source · daemon trace",sessionHostOnly:"session_host only",visibleTraceEvents:"{{count}} visible trace event(s)",loadingDaemonTrace:"Loading daemon trace…",noTraceEntriesMatchSearch:"No trace entries match the current search.",noSessionHostTraceYet:"No session host trace entries yet.",noTraceEntriesYet:"No trace entries yet.",noPayload:"No payload",rawSourceBrowserEvents:"Raw source · browser debug events",visibleBrowserEvents:"{{count}} visible browser event(s)",noBrowserEventsMatchSearch:"No browser debug events match the current search.",noBrowserEventsYet:"No browser debug events captured yet."}},Sk={transition:{recover:"Recovered",detach:"Detached",attach:"Attached",start:"Started",stop:"Stopped",restart:"Restarted",resume:"Resumed"},lastErrorLabel:"Last error",endpointLabel:"Endpoint",activeAgo:"active {{time}}",title:"Hosted Runtime Recovery",stopConfirmTitle:"Stop {{name}}?",stopConfirmDescription:"This will terminate the hosted runtime.",pruneConfirmTitle:"Prune duplicate hosted runtimes?",pruneConfirmDescription:"The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.",prune:"Prune",pruning:"Pruning…",pruneDuplicatesCount:"Prune duplicates ({{count}})",toastResumed:"Session host resumed: {{name}}",toastRestarted:"Session host restarted: {{name}}",toastStopped:"Session host stopped: {{name}}",toastPruned:"Pruned {{pruned}} duplicate runtime(s) across {{groups}} group(s)",actionFailed:"Session host action failed",pruneFailed:"Duplicate prune failed",diagnosticsFailed:"Could not load hosted runtime diagnostics",diagnosticsAttention:"Hosted runtime diagnostics need attention",stop:"Stop",stopping:"Stopping…",restart:"Restart",restarting:"Restarting…",resume:"Resume",resuming:"Resuming…",recover:"Recover",recovering:"Recovering…",refresh:"Refresh",refreshing:"Refreshing…",noWorkspace:"No workspace",clientsCount_one:"{{count}} client",clientsCount_other:"{{count}} clients",dashboardSessions_one:"{{count}} dashboard session",dashboardSessions_other:"{{count}} dashboard sessions",statLive:"Live runtimes",statRecovery:"Recovery",statRequests:"Requests",statStarted:"Started",latestWarning:"Latest host warning",liveTitle:"Live Hosted Runtimes",recoveryTitle:"Recovery Snapshots",inactiveTitle:"Inactive Records",recentActivity:"Recent Host Activity",liveEmpty:"No live hosted runtimes on this machine right now.",recoveryEmpty:"No recovery snapshots currently need attention.",transitionsEmpty:"No recent runtime transitions yet.",nextAction:"Next: {{action}}"},kk={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"},jk={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."}},Nk={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"},Ck={gallery:{next:"Next view",previous:"Previous view"},nav:{home:"ADHDev Home",mesh:"Mesh",what:"What",agents:"Agents",pricing:"Pricing",install:"Install",github:"GitHub",docs:"Docs",getStarted:"Get started",toggleMenu:"Toggle menu",mainNavigation:"Main navigation"},hero:{badge:"Multi-vendor, multi-machine agent control plane",title:"Manage the coding agents running on your computer — from anywhere.",subtitleInstall:"Install ADHDev on your <os></os>.",subtitlePlace:"use your <device></device>",subtitleAsk:"to ask <coordinator></coordinator> to send <worker></worker> to <verb></verb> your repo.",subtitleFrom:"from <place></place>",anywhere:"anywhere",subtitleLand:"Ten agents at once — none of them step on each other.",axes:{os:["Mac","Windows","Linux"],place:["the subway","a cafe","your parents' place","bed","the couch","the garden","the passenger seat","the ferry","the toilet","inside a container","the moon","a server rack"],device:["desktop","laptop","tablet","mobile phone"],verb:["debug","build","test","review"]},copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",getStarted:"Get started free",orInstall:"Or install the CLI",openSource:"Open source on GitHub",joinDiscord:"Join Discord",selfHost:"Self-host it",demoDesktop:"ADHDev command center driving live agent sessions across multiple machines",demoPush:"ADHDev mobile push notification and one-tap approval"},mesh:{sectionTitle:"Parallel agents that don't step on each other.",sectionSubtitle:"Running agents in parallel is the easy part — every tool does it now. The hard part is what comes after: a pile of branches that still have to be checked and merged. ADHDev does that for you, so finished work arrives on main instead of in your review queue.",refineryHighlight:"Automatic landing",refineryTitle:"Finished work merges to main on its own",refineryDesc:"Anyone can run ten agents at once. ADHDev then checks each branch against your project's own tests and lint, merges the ones that pass cleanly into main, and tidies up — automatically, and never with a force-push. Anything unclear is held back for you to review instead of merged.",asyncHighlight:"One place to drive it",asyncTitle:"You talk to one place. It runs the rest.",asyncDesc:"You hand work to a single coordinator, and it runs every agent across every machine for you. It only pings you when something needs approval or finishes — so there's no queue of agent windows to watch and nothing to sit in front of.",crossPlatformHighlight:"Every OS at once",crossPlatformTitle:"Mac, Windows, Linux — all at once",crossPlatformDesc:"Send a task to a specific operating system with one tag. A single prompt can build, test, or verify across Mac, Windows, and Linux machines you already own — in parallel, with no SSH setup and no virtual machines.",monoHighlight:"Works with real repos",monoTitle:"Safe even with git submodules",monoDesc:"Real production repos nest submodules — exactly where naive auto-merge breaks. ADHDev handles them safely: it makes sure submodule changes are published and pointed at correctly before it touches main. This project is itself a repo with two submodules, merged this way every day.",crossHighlight:"Second opinion",crossTitle:"Consensus over a single opinion",crossSubtitle:"MAGI — Multi-Agent Ground-truth Insight",crossDesc:"Ask the same read-only question to several machines and models at once, then see where they agree and disagree (MAGI) — more trustworthy than one agent's answer.",tryMesh:"Try Repo Mesh →",seePlans:"See plans",availableOn:"Connect a machine and open the <strong>Repo Mesh</strong> page to get started.",readGuide:"Read the guide"},compare:{sectionTitle:"Everyone runs agents in parallel. Not everyone keeps them out of each other's way.",sectionSubtitle:"A fair question. Local CLIs spawn subagents; desktop orchestrators fan work across worktrees with a slick native UI. Both stop at the branch. Here's the honest line — including where each of them beats us — with no hand-waving.",colLocalCli:"Local CLI + subagents",colDesktop:"Desktop orchestrator",colAdhdev:"ADHDev Repo Mesh",rowLandsMain:"Lands finished work on main",rowLandsMainLocalCli:"You run the gates and merge by hand",rowLandsMainDesktop:"Parallelizes the work, then hands you the branches to review",rowLandsMainAdhdev:"The Refinery runs your repo's gates, checks patch equivalence, and fast-forwards main — unattended, no force-push",rowSubmodules:"Safe with git submodules",rowSubmodulesLocalCli:"No merge automation to be aware of them",rowSubmodulesDesktop:"Worktree parallelism, but the merge is yours to get right",rowSubmodulesAdhdev:"Submodule-aware convergence: reachability gate, patch-equivalence check, atomic pointer bump — dogfooded on this monorepo daily",rowAsync:"Talk to one place, async",rowAsyncLocalCli:"One session at a time, synchronously",rowAsyncDesktop:"You supervise each agent window yourself",rowAsyncAdhdev:"One coordinator drives every worker on an event loop — it waits on completion/approval events, you don't poll or babysit",rowMultiMachine:"Multiple physical machines",rowMultiMachineLocalCli:"One host's processes only",rowMultiMachineDesktop:"Bound to the one machine it runs on",rowMultiMachineAdhdev:"Remote daemons over P2P — Mac, Windows, and Linux nodes in one mesh, no SSH plumbing",rowParallelBranch:"Parallel isolated-branch work",rowParallelBranchLocalCli:"Subagents share one working tree — concurrent writes collide",rowParallelBranchDesktop:"One git worktree per task — a core strength",rowParallelBranchAdhdev:"One git worktree per node — parallel across machines, not just cores",rowBrowser:"Drive it from a browser or phone",rowBrowserLocalCli:"You have to be at the terminal",rowBrowserDesktop:"Native desktop app — you're at that desk",rowBrowserAdhdev:"Web-first: control sessions and approve from any browser or phone",rowNativeApp:"Native desktop app",rowNativeAppLocalCli:"Terminal only",rowNativeAppDesktop:"Polished native window — genuinely nicer to sit in front of",rowNativeAppAdhdev:"We're web-first — a browser tab, not a native app",rowRestarts:"Survives restarts & context loss",rowRestartsLocalCli:"State lives in a session — close it and it's gone",rowRestartsDesktop:"State tied to the app process",rowRestartsAdhdev:"Missions persist to disk and resume after a coordinator or daemon restart — append-only, tamper-evident audit trail",rowCrossCheck:"Cross-check the answer",rowCrossCheckLocalCli:"One agent's take, no second opinion",rowCrossCheckDesktop:"Parallel work, single verdict",rowCrossCheckAdhdev:"MAGI fans the same read-only question to independent machine × provider agents and surfaces where they diverge",footnote:"For a single machine, a single branch, a one-shot task — a local CLI with subagents is lighter and works great, and a native desktop orchestrator is a nicer place to sit. Repo Mesh earns its keep when work fans out across machines and branches, needs to survive restarts, and should land on main automatically — controlled from wherever you are."},what:{sectionTitle:"Any agent, mixed freely",sectionSubtitle:"Vendor-neutral by design. Run Claude Code on the Mac, Codex on the Windows GPU box, Cursor CLI for review passes — in the same mesh, under the same policies. Switch vendors without switching platforms.",cliHighlight:"CLI agents",cliTitle:"Drive any terminal agent from the web",cliDesc:"Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Grok, Hermes, Kimi, and OpenCode — attached on your machine through a PTY adapter with proper resume and reconnect, driven from your browser. Send prompts and provide visual context instantly (paste, drag & drop, or upload multiple images at once, up to 5 images / 10MB each). Aider, Goose, and other ACP agents connect over stdio.",uiHighlight:"One UI",uiTitle:"Same dashboard, any device",uiDesc:"Cloud-hosted at adhf.dev — drive every agent from a laptop or phone, whether you're at your desk or away from it.",ideHighlight:"IDE agents",ideTitle:"Also: attach to running editors",ideDesc:"Cursor, VS Code, VSCodium, Windsurf, Antigravity, Kiro, PearAI, Trae. Read live chat, send prompts, switch sessions, capture screenshots.",p2pHighlight:"Yours, end to end",p2pTitle:"P2P-first: your data stays yours",p2pDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC. The cloud sees auth and signaling metadata, nothing else — your code never routes through the server."},oss:{sectionTitle:"Open source & self-hostable",sectionSubtitle:"The daemon and dashboard are AGPL-3.0 and available on GitHub. Run them yourself on any machine or server — no account required.",github:"GitHub",selfHostDocs:"Self-hosting docs"},agents:{sectionTitle:"Supported agents",sectionSubtitle:"{{ides}} built-in IDE integrations, {{clis}} built-in CLI agents, {{extensions}} IDE-resident extension agents, and {{acp}}+ ACP (stdio MCP) agents. Provider scripts live in <code>adhdev-providers/</code> — add your own under <code>~/.adhdev/providers/</code>.",tierTested:"Tested",tierTestedDesc:"validated against a real app + version",tierCommunity:"Community",tierCommunityDesc:"built-in and community-supported",groupIdes:"IDEs",hintIdes:"Attached via Chrome DevTools Protocol. Read chat, send prompts, switch sessions, screenshot.",groupCli:"CLI agents",hintCli:"Driven through a PTY adapter with resume and reconnect.",groupExtensions:"In-IDE extension agents",hintExtensions:"CDP webview attachment for agents that live inside another IDE.",acpFootnote:"Plus {{count}}+ ACP agents over stdio (Agent Client Protocol): Codex, Claude Agent, Goose, Cline, OpenHands, and more."},pricing:{sectionTitle:"Simple pricing as your agents grow",sectionSubtitle:"Start free on one machine. Go Pro for two, or Ultra for five. No per-seat math, no enterprise sales call — just the plans below.",mostPopular:"Most popular",upgradeToPro:"Upgrade to Pro",footnote:"Simple, transparent pricing — the prices above are what you'll pay. Prefer to self-host? The daemon and dashboard are open source. Prices in USD.",plans:{free:{period:"forever",tagline:"Everything you need to drive one machine from anywhere.",cta:"Start free",features:{machine:"One machine, paired in a single command",p2p:"P2P chat, commands, screenshots, remote input",providers:"Every provider — CLI, IDE, and ACP agents",push:"Push notifications for approvals & completions",share:"One shared session link"}},pro:{period:"/mo",tagline:"Two machines, more concurrent sessions, and TURN for restrictive networks — plus Repo Mesh to orchestrate agents across both.",cta:"Start 7-day Pro trial",features:{machines:"2 machines — run agents on both",p2p:"More concurrent P2P sessions",push:"Unlimited push notifications",turn:"TURN relay for restrictive networks",share:"More shared sessions"}},ultra:{period:"/mo",tagline:"Everything in Pro, scaled up — more machines and higher limits for heavy parallel work.",cta:"Go Ultra",features:{machines:"5 machines — flat price, not per-seat",everything:"Everything in Pro",p2p:"Highest concurrent P2P sessions",screenshots:"Unlimited daily screenshot minutes",webhooks:"Higher API call limits",share:"More shared sessions"}}}},install:{sectionTitle:"Three steps to a working dashboard",sectionSubtitle:"No configuration files. No API keys to wire up. ADHDev does not manage agent auth — each tool keeps its own login.",selectOs:"Select OS",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",platformNote:"macOS and Windows are the validated install paths. Linux runs the same Unix script and is community-tested.",arrow:"→",steps:{step1:{title:"Install the daemon",desc:"One curl command installs the daemon plus the adhdev CLI — the launcher you run to pair machines and start the daemon (not to be confused with the CLI agents it drives, like Claude Code or Codex). Same binary powers cloud and standalone."},step2:{title:"Link a machine",desc:"Sign in once with GitHub or Google and the daemon pairs itself — no token to copy."},step3:{title:"Drive your agents",desc:"Launch Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi, and other agents from the dashboard. Read chat, send prompts, provide visual context (paste, drag & drop, or upload multiple images at once), approve actions, and switch sessions."}}},cta:{headline:"Stop juggling tabs. Drive every agent from one dashboard.",subtitle:"One curl command, one daemon, every agent you already use. Drive them all from the web — Cloud is live.",getStarted:"Get started →",github:"GitHub",discord:"Discord"},footer:{docs:"Docs",github:"GitHub",discord:"Discord",dashboard:"Dashboard",terms:"Terms",privacy:"Privacy",contact:"Contact",copyright:"© {{year}} RacoLab. All rights reserved."},imagePaste:{sectionTitle:"Paste a screenshot. A terminal agent on another machine sees it instantly.",sectionSubtitle:"Grab a screenshot on your laptop or phone, paste it into the chat, and a CLI agent running in a terminal on a different machine gets it as visual context — no file juggling, no SSH. Paste, drag & drop, or upload up to 5 images (10MB each) at once.",point1:"Paste from clipboard, drag & drop, or upload",point2:"Up to 5 images, 10MB each",point3:"Lands in a PTY terminal agent on any of your machines",step1Label:"Paste the image, type a question",step2Label:"Sent — the agent picks it up",step3Label:"It saw the image and answered"},mobile:{sectionTitle:"Leave your desk. Your agents keep going.",sectionSubtitle:"A push notification hits your phone when an agent needs approval or finishes. Tap it, approve or reject, then follow up in chat — all from the mobile dashboard, wherever you are.",point1:"Push notification on approval or completion",point2:"One tap to approve or reject",point3:"Follow up with a chat instruction, then put your phone away",notificationLabel:"Mobile push notification for an agent approval",resumeLabel:"Approving and following up from the mobile dashboard",deviceShotLabel:"Real iOS lock-screen notifications showing grouped ADHDev push alerts for agent completions and approvals",deviceShotCaption:"Real device — actual push notifications on a phone",point4:"No port forwarding, no VPN, no DMZ — P2P with TURN relay connects from cafés, hotspots, desktop or laptop, anywhere with internet"},brain:{sectionTitle:"Cheap models for easy work. Expensive ones only when it's hard.",sectionSubtitle:"Tag a task easy, medium, or difficult and the mesh applies a matching preset — provider, model, and thinking budget. Routine work runs on a cheap fast model; only the hard tasks reach for the expensive one. You spend tokens where they matter.",point1:"Difficulty-based presets: easy / medium / difficult",point2:"Each preset picks provider, model, and thinking level",point3:"Save tokens without hand-tuning every task"},scenario:{sectionTitle:"One prompt. Mac builds, Windows tests, main lands.",sectionSubtitle:"A real session in three steps: you describe the work once, agents run in parallel across your machines, and finished code arrives on main — without you sitting at the terminal.",step1Label:"Describe the work",step1Desc:"Tell it what to build, in one sentence. No config, no setup per machine.",step2Label:"Agents run in parallel",step2Desc:"The work splits across your Mac and Windows machines at once — each on its own branch, each running your project's tests and checks.",step3Label:"Finished code lands on main",step3Desc:"When the checks pass, the work merges into main automatically and safely. Anything unclear is held back for you to review — never force-pushed.",caveat:"Mac and Windows are the verified daily-driver machines. Linux is also supported."}},_k={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."},Ak={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"}},Tk={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"},Ik={pageTitle:"Approvals",pageSubtitle:"Sessions waiting on your decision.",pending:"Pending",loading:"Loading approvals…",emptyHint:"Approvals from any connected machine will appear here automatically."},Mk={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"},Rk={dashboard:"Dashboard",machines:"Machines",notifications:"Notifications",mesh:"Mesh",marketplace:"Marketplace",api:"API",webhooks:"Webhooks",account:"Account",settings:"Settings",docs:"Docs",about:"About",chats:"Chats"},Pk={controls:KS,sessionStatus:qS,language:zS,common:GS,connection:VS,toast:YS,notification:QS,event:JS,dashboard:XS,cliStop:ZS,approval:ek,chatControls:tk,newSession:nk,mobileInbox:sk,mesh:rk,chat:ok,chatPane:ak,chatInput:ik,paneGroup:lk,terminal:ck,conversation:dk,cliView:uk,launch:mk,standalone:hk,cloud:pk,app:fk,chatList:gk,screenshot:bk,remote:xk,sessionNav:yk,sessionInfo:vk,machine:wk,sessionHost:Sk,sessionHostSurface:kk,settings:jk,historyModal:Nk,landing:Ck,interactivePrompt:_k,git:Ak,notifications:Tk,approvals:Ik,setupWizard:Mk,nav:Rk},uc="lang",go="common",Lk={ko:()=>kr(()=>import("./common-BPFzWFQt.js"),[]),ja:()=>kr(()=>import("./common-D8_bJv3R.js"),[]),"zh-CN":()=>kr(()=>import("./common-D3xpMHz6.js"),[]),es:()=>kr(()=>import("./common-DepW94Rn.js"),[])};async function Ek(e){return!Ws(e)||e===zs?null:(await Lk[e]()).default}const Dk={type:"backend",init(){},read(e,t,s){if(t!==go){s(null,{});return}Ek(e).then(r=>s(null,r??{}),r=>s(r instanceof Error?r:new Error(String(r)),!1))}};function Ok(e){return{resources:{[zs]:{[go]:Pk}},partialBundledLanguages:!0,lng:e,fallbackLng:zs,supportedLngs:xf,ns:[go],defaultNS:go,interpolation:{escapeValue:!1},returnEmptyString:!1,react:{transKeepBasicHtmlNodesFor:["br","strong","i","p","em"]}}}function Fk(){try{const e=localStorage.getItem(uc);if(Ws(e))return e}catch{}return null}function yf(){const e=Fk();return e||(typeof navigator<"u"?US(navigator.language):zs)}function mc(e){typeof document>"u"||document.documentElement.setAttribute("lang",e)}let No=null,vf=!1;function wf(){if(No)return at;const e=yf();return No=at.use(Dk).use(Ox).init(Ok(e)).then(()=>{},()=>{}).finally(()=>{vf=!0}),mc(e),at}function $k(){return vf?!0:!!No&&at.isInitialized&&at.hasLoadedNamespace(go)}function Hk(){return No||wf(),No}function Gt(e){return(typeof e=="string"?e.trim():"")||void 0}function rs(e,t){const s=Gt(t);return s?`${e}:${s}`:void 0}function ys(e,t,s){const r=rs(t,s),o=Gt(s);r&&e.push(r),o&&e.push(o)}function jr(e){const t=[],s=new Set;for(const r of e)!r||s.has(r)||(s.add(r),t.push(r));return t}function Sf(e){return Gt(e.providerSessionId)||Gt(e.sessionId)||Gt(e.tabKey)||Gt(e.routeId)}function ji(e){return jr([Gt(e.historySessionId),Gt(e.providerSessionId),Gt(e.sessionId)])}function bo(e){const t=[];return ys(t,"provider",e.providerSessionId),ys(t,"session",e.sessionId),ys(t,"tab",e.tabKey),ys(t,"route",e.routeId),jr(t)}function Bk(e){const t=[];return Gt(e.providerSessionId)?(ys(t,"provider",e.providerSessionId),jr(t)):Gt(e.sessionId)?(ys(t,"session",e.sessionId),jr(t)):Gt(e.tabKey)?(ys(t,"tab",e.tabKey),jr(t)):Gt(e.routeId)?(ys(t,"route",e.routeId),jr(t)):[]}function kf(e){return rs("provider",e.providerSessionId)||rs("session",e.sessionId)||rs("tab",e.tabKey)||rs("route",e.routeId)||"unknown:"}function Ni(e){return ji(e)[0]}function Ci(e){const t=Gt(e.sessionId),s=Ni(e);if(s&&!(t&&s===t))return s}function Wk(e){const t=Gt(e.providerSessionId),s=Gt(e.sessionId),r=Gt(e.tabKey),o=Gt(e.routeId),a=[rs("provider",t),rs("session",s),rs("tab",r),rs("route",o)].filter(d=>typeof d=="string"),i=bo({providerSessionId:t,sessionId:s,tabKey:r,routeId:o}),c=kf({providerSessionId:t,sessionId:s,tabKey:r,routeId:o});return{providerSessionId:t,sessionId:s,tabKey:r,routeId:o,canonicalKey:c,targetKey:c,targetValue:Sf({providerSessionId:t,sessionId:s,tabKey:r,routeId:o}),historySessionId:Ni({providerSessionId:t,sessionId:s}),runtimeSessionId:s,allKeys:a,lookupKeys:i}}function co(e,t){const s=Wk(e);return Bk(t).some(r=>s.lookupKeys.includes(r))}function jf(e){const t=String(e.daemonId||"").trim(),s=String(e.id||"").trim();return t&&s.startsWith(`${t}:`)?s.slice(t.length+1):s}function hc(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 Uk(e,t){const s=String(e.daemonId||"").trim(),r=String(e.id||"").trim(),o=jf(e);if(o&&t.has(o))return`mesh:${o}`;const a=String(e.ownerDaemonId||"").trim()||s;return a?o?`${a}:${o}`:a:r}function ol(e,t){return t||e||"unknown"}function Kk(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 qk={vscode:"VS Code",pearai:"PearAI"};function Kt(e){return e?e.split("-").map(t=>qk[t.toLowerCase()]||t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function zk(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 al(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function ja(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 Gk(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),s=t[t.length-1];return s.length>12?`Machine-${s.substring(0,8)}`:s}return e}function Vk(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Yk(e){return Gk(e.trim().replace(/\.local$/i,""))}function Nf(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function fd(e,t={}){var o,a;const s=[e.hostname,(o=e.machine)==null?void 0:o.hostname,(a=e.system)==null?void 0:a.hostname].find(i=>typeof i=="string"&&i.trim().length>0&&!Vk(i));if(s&&s!=="Unknown")return Yk(s);const r=t.fallbackId||e.id;return r?`Machine-${r.substring(0,8)}`:t.fallbackLabel||"Machine"}function Tn(e,t={}){return Nf(e)||fd(e,t)}function Cf(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 _f(e,t,s={}){const r=String(t).trim();if(!e||!Array.isArray(e.items)||!r)return"";const o=e.items.find(a=>String((a==null?void 0:a.id)||"").trim()===r);return o?String(s.preferShortValue?o.shortValue||o.value||"":o.value||o.shortValue||"").trim():""}function tr(e,t){return Cf(e).join(" · ")}function Co(e){return e.transport==="pty"}function Nr(e){return e.transport==="acp"}const Af={darwin:"macOS",linux:"Linux",win32:"Windows"};function Qk(e,t){var s,r;return(s=t==null?void 0:t.providerLabels)!=null&&s[e]?t.providerLabels[e]:(r=t==null?void 0:t.providerLabels)!=null&&r[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:Kt(e)}function zu(e,t,s){const r=(e||"").trim().toLowerCase();if(!r)return!0;const o=(t||"").trim().toLowerCase(),a=(s||"").trim().toLowerCase(),i=Kt(s||"").trim().toLowerCase();return r===o||r===a||r===i}function Jk(e,t=[],s=[]){var d,u,m,h;const r=vn(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(r==="waiting_approval")return"waiting_approval";if(r==="waiting_choice")return"waiting_choice";if(r==="generating")return"generating";const o=t.find(p=>Wu(p.status,{activeModal:p.activeModal})||ic(p.status));if(o)return vn(o.status,{activeModal:o.activeModal});const a=s.find(p=>Wu(p.status,{activeModal:p.activeModal})||ic(p.status));if(a)return vn(a.status,{activeModal:a.activeModal});if(r&&r!=="idle")return r;const i=vn((d=t[0])==null?void 0:d.status,{activeModal:(u=t[0])==null?void 0:u.activeModal});if(i!=="idle")return i;const c=vn((m=s[0])==null?void 0:m.status,{activeModal:(h=s[0])==null?void 0:h.activeModal});return c!=="idle"?c:"idle"}function Xk(e){return vn(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Zk(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,s=["generating","finalizing","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const r of e){const o=(r.name||r.id||"").toLowerCase().replace(/\s+/g,"-"),a=t.get(o),i=vn(r.status);if(!a){t.set(o,{...r,status:i});continue}const c=s.indexOf(a.status||"idle"),d=s.indexOf(i||"idle");d>=0&&(c<0||d<c)&&t.set(o,{...r,status:i})}return Array.from(t.values())}function ej(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 tj(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&&ej(t.receivedAt)||0}function nj(e){return(e.recentLaunches||[]).reduce((s,r)=>Math.max(s,r.lastLaunchedAt||0),0)}function pc(e){return Math.max(nj(e),tj(e.activeChat))}function sj(e,t,s,r,o,a){const i=t-e;if(i!==0)return i;const c=s.localeCompare(r);return c!==0?c:o.localeCompare(a)}function Ua(e,t){return sj(pc(e),pc(t),Tn(e,{fallbackId:e.id}),Tn(t,{fallbackId:t.id}),e.id,t.id)}const Tf="adhdev_notification_prefs",Gu={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function rj(){try{const e=localStorage.getItem(Tf);if(e){const t=JSON.parse(e);return{...Gu,...t}}}catch{}return{...Gu}}function oj(e){try{localStorage.setItem(Tf,JSON.stringify(e))}catch{}}let ss=rj(),Na=[];function aj(){Na.forEach(e=>e())}function ij(e){ss={...ss,...e},oj(ss),aj()}function lj(){const[,e]=l.useState(0);l.useEffect(()=>{const s=()=>e(r=>r+1);return Na.push(s),()=>{Na=Na.filter(r=>r!==s)}},[]);const t=l.useCallback(s=>{ij(s)},[]);return[{...ss},t]}function xo(e){if(!ss.globalEnabled)return!1;switch(e){case"disconnect":return ss.disconnectAlert;case"completion":return ss.completionAlert;case"approval":return ss.approvalAlert;case"browser":return ss.browserNotifications;default:return!0}}const cj={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function If(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Mf(){return"Notification"in window&&Notification.permission==="granted"}function dj(e,t,s){return e?!(s==="waiting_choice"&&t!=="waiting_choice"):!1}let Ps=null;function uj(e){return e!==!1}async function mj(){if(Ps!==null)return Ps;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Ps=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Ps=!!await e.pushManager.getSubscription(),Ps):(Ps=!1,!1)}catch{return Ps=!1,!1}}function fc(e,t,s){if(Mf())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 hj(e){const{name:t,prev:s,curr:r,questionEntered:o}=e,a=String(e.modalMessage||"").replace(/\s+/g," ").trim().slice(0,120);return o&&e.onApproval?{kind:"question",title:t,body:a?at.t("event.browser.questionWithMessage",{message:a}):at.t("event.browser.question")}:e.onApproval&&r==="waiting_approval"&&s!=="waiting_approval"?{kind:"approval",title:t,body:a?at.t("event.browser.approvalWithMessage",{message:a}):at.t("event.browser.approval")}:e.onComplete&&ic(s)&&r==="idle"?{kind:"complete",title:t,body:at.t("event.browser.finished")}:e.onError&&r==="error"&&s!=="error"?{kind:"error",title:t,body:at.t("event.browser.error")}:null}function pj(e,t={}){const s={...cj,...t},r=l.useRef(new Map),o=l.useRef(0),[a,i]=l.useState(null);l.useEffect(()=>{let d=!1;return mj().then(u=>{d||i(u)}),()=>{d=!0}},[]);const c=l.useCallback((d,u,m)=>{const h=Date.now();h-o.current<s.throttleMs||(o.current=h,fc(d,u,m))},[s.throttleMs]);l.useEffect(()=>{var d;if(!(!s.enabled||!Mf())&&xo("browser")&&!uj(a)){if(document.hasFocus()){for(const u of e)r.current.set(u.id,vn(u.status,{activeModal:u.activeModal}));return}for(const u of e){const m=r.current.get(u.id),h=vn(u.status,{activeModal:u.activeModal}),p=u.name||u.id,g=h==="waiting_choice"&&m!=="waiting_choice";if(dj(u.muted,m,h)){r.current.set(u.id,h);continue}const f=hj({name:p,prev:m,curr:h,modalMessage:(d=u.activeModal)==null?void 0:d.message,questionEntered:g,onApproval:s.onApproval&&xo("approval"),onComplete:s.onComplete&&xo("completion"),onError:s.onError});f&&c(f.title,f.body,`${f.kind}-${u.id}`),r.current.set(u.id,h)}}},[e,s.enabled,s.onApproval,s.onComplete,s.onError,a,c])}const fj=/^(run|approve|accept|yes|allow|always)/,gj=/^(run|approve|accept|yes|allow|always|proceed|save)/,bj=/^(reject|deny|delete|remove|abort|cancel|no)/;function gd(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function xj(e){const t=gd(e).toLowerCase();return fj.test(t)?"primary":bj.test(t)?"danger":"default"}function yj(e){return gj.test(gd(e).toLowerCase())?"approve":"reject"}function vj(e){return e.map((t,s)=>({label:gd(t),variant:xj(t),action:yj(t),button:t,buttonIndex:s}))}function wj(e,t,s){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:s}function Sj(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 bd(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 bd(s);try{return JSON.stringify(e)}catch{return}}return String(e)}}class kj{constructor(){qe(this,"dedupMap",new Map);qe(this,"DEDUP_WINDOW_MS",5e3);qe(this,"DEDUP_MAX_SIZE",50);qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);qe(this,"toastCallbacks",[]);qe(this,"statusEventCallbacks",[]);qe(this,"resolveActionFn",null);qe(this,"viewRequestRespondFn",null);qe(this,"hydrateInteractivePromptFn",null);qe(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(s=>s!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(s=>s!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}setHydrateInteractivePrompt(t){this.hydrateInteractivePromptFn=t}hydrateInteractivePromptFromEvent(t){const s=this.hydrateInteractivePromptFn;if(!s)return;const r=t.targetSessionId;if(!r)return;const o=ac(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=bd(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 y;const r=this.resolveConversationKey(t),o=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),a=r||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(o),c=`${a}:${t.event}:${i}`;if(t.event==="agent:waiting_choice"&&this.hydrateInteractivePromptFromEvent(t),this.isDuplicate(c))return;for(const b of this.statusEventCallbacks)b(t);const d=this.isConversationEventMuted(t),u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let h=Kt(m);const p=this.resolveOwningDaemon(t);if(p){const b=Tn(p,{fallbackId:p.id});b&&(h=!m||m==="adhdev-daemon"?b:`${b}/${h}`)}let g="",f="info";if(t.event==="agent:generating_completed"){if(g=t.duration?`✅ ${at.t("event.taskCompletedWithDuration",{label:h,duration:xw(Number(t.duration)*1e3)})}`:`✅ ${at.t("event.taskCompleted",{label:h})}`,f="success",!d)try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started"){if(t.event==="agent:waiting_approval"){if(g=`⚡ ${at.t("event.approvalNeeded",{label:h})}`,f="warning",d)g="";else if((y=t.modalButtons)!=null&&y.length&&this.resolveActionFn){const b=this.resolveActionRouteTarget(t);if(!b)return;const k=this.resolveActionFn,j=vj(t.modalButtons).map(x=>({label:x.label,variant:x.variant,onClick:()=>{k(b,"resolve_action",{action:x.action,button:x.button,buttonIndex:x.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),v=wj(h,t.modalMessage,g),C=Date.now();this.emitToast({id:C,message:v,type:f,timestamp:C,targetKey:r||b,actions:j,duration:15e3}),g=""}}else if(t.event==="agent:waiting_choice"){g=`❓ ${at.t("event.questionNeeded",{label:h})}`,f="warning";const b=typeof t.modalMessage=="string"&&t.modalMessage.trim()?t.modalMessage.replace(/[\n\r]+/g," ").slice(0,120):"";b&&(g=`${g} — ${b}`);const k=Date.now();this.emitToast({id:k,message:g,type:f,timestamp:k,targetKey:r||t.daemonId,duration:1e4}),g=""}else if(t.event==="monitor:no_progress"||t.event==="monitor:long_generating"){const b=t.elapsedSec?Math.round(t.elapsedSec/60):0;g=b?`⚠️ ${at.t("event.noProgressWithDuration",{label:h,minutes:b})}`:`⚠️ ${at.t("event.noProgress",{label:h})}`,f="warning",!d&&xo("browser")&&!document.hasFocus()&&fc(`⚠️ ${at.t("event.noProgressTitle",{label:h})}`,at.t("event.noProgressBody",{duration:b?`${b}m`:""}),`no-progress-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const b=t.requesterName||at.t("event.someoneRequester"),k=t.requestId,j=t.orgId;if(g=`${at.t("event.viewRequest",{requester:b})}`,f="warning",k&&j&&this.viewRequestRespondFn){const v=Date.now(),C=Sj(j,k,this.viewRequestRespondFn,(x,S)=>console.error(`[EventManager] ${x} view request failed:`,S));this.emitToast({id:v,message:g,type:f,timestamp:v,actions:C,duration:3e4}),g=""}xo("browser")&&!document.hasFocus()&&fc(`${at.t("event.viewRequestTitle")}`,at.t("event.viewRequest",{requester:b}),`view-request-${k}`)}else if(t.event==="team:view_request_approved")g=`✅ ${at.t("event.viewRequestApproved")}`,f="success";else if(t.event==="team:view_request_rejected"){const b=t.targetName||at.t("event.someoneTarget");g=`❌ ${at.t("event.viewRequestDeclined",{target:b})}`,f="warning"}}if(g&&!d){const b=Date.now();this.emitToast({id:b,message:g,type:f,timestamp:b,targetKey:r||t.daemonId,duration:5e3})}}}const ct=new kj,Vu=new Map;function Rf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Cr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function _i(e){return ud(e)??null}function jj(e){const t=_i(e);return!t||!Rf(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function na(e){const t=_i(e);return!t||!Rf(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Yr(e){const t=_i(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function sa(e){const t=_i(e);return!!t&&t.success===!1}function Nj(e){var t,s;for(const r of e||[]){if(r.type==="toast"&&((t=r.toast)!=null&&t.message)){const o=r.toast.level==="warning"?"warning":r.toast.level==="success"?"success":"info";ct.showToast(r.toast.message,o);continue}if(r.type==="notification"&&((s=r.notification)!=null&&s.body)){const o=r.notification.level==="warning"?"warning":r.notification.level==="success"?"success":"info";ct.showToast(r.notification.body,o)}}}function Cj(e,t){return e&&Cr(e.currentValue)?e.currentValue:t}function _j(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 Aj(e,t){return Cr(t)?Cr(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Tj(e,t){var a,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Cr(c))return c}const r=(a=t.controlValues)==null?void 0:a[e];if(Cr(r))return r;const o=(i=t.defaultValues)==null?void 0:i[e];return Cr(o)?o:void 0}function Ca(e,t){return e.options||t[e.id]||[]}const Ij={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 Mj(e,t,s){var r;return((r=Ij[t])==null?void 0:r.has(s.id))===!0}function Rj(e){if(e){if(hi(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 Pj(e,t){const s=e.visibleWhenState;if(!s||s.length===0)return!0;const r=Rj(t);return r?r.some(o=>s.includes(o)):!0}function xd(e,t){return(e||[]).filter(s=>s.placement==="bar"&&s.hidden!==!0&&!Mj(t.hostIdeType,t.providerType,s)&&Pj(s,t.currentStatus)).sort((s,r)=>(s.order??50)-(r.order??50))}function il(e,t){return{value:t}}function Lj(e,t,s){var o;return s?((o=Ca(e,t).find(a=>a.value===s))==null?void 0:o.label)||s:""}const Ej={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Dj({routeId:e,sessionId:t,hostIdeType:s,providerType:r,displayLabel:o,controls:a,controlValues:i,currentStatus:c,coordinatorHint:d}){const{t:u}=ve("common"),{sendCommand:m}=_t(),{confirm:h,confirmDialog:p}=Fr(),g=`${e}:${t||r}`,f=Ej[r]||"#94a3b8",[y,b]=l.useState({}),k=l.useRef({}),j=l.useRef(i);k.current=y,j.current=i;const v=l.useRef(0),C={};for(const M of a||[])M.defaultValue!==void 0&&(C[M.id]=M.defaultValue);const x={...C,...i||{},...Date.now()<v.current?y:{}};l.useEffect(()=>{i&&Date.now()>v.current&&b(M=>_j(M,i))},[i]);const[S,w]=l.useState(Vu.get(g)||{}),[_,A]=l.useState(null),[O,L]=l.useState(null),R=l.useCallback(async(M,D={})=>{const P={...D,...t&&{targetSessionId:t},...d??{}};return await m(e,M,P)},[e,t,m,d]),F=l.useCallback(async(M,D={})=>{const P=t?{targetSessionId:t}:{agentType:r,...s?{ideType:s}:{}};return await R("invoke_provider_script",{...P,scriptName:M,...D})},[R,r,s,t]),N=l.useCallback((M,D,P)=>{const $=Cj(P,D);b(W=>({...W,[M.id]:$})),Nj(P==null?void 0:P.effects)},[]),I=l.useCallback((M,D)=>{b(P=>{const $={...P};return D===void 0?delete $[M.id]:$[M.id]=D,$}),v.current=0},[]);if(!a||a.length===0)return null;const B=xd(a,{hostIdeType:s,providerType:r,currentStatus:c});if(B.length===0)return null;const T=async M=>{if(_===M.id){A(null);return}if(Ca(M,S).length>0){A(M.id);return}if(M.dynamic&&M.listScript){L(M.id);try{const P=await F(M.listScript,{}),$=jj(P);if(!$){const ae=Yr(P);ae&&ct.showErrorToast(u("controls.loadOptionsFailed",{label:M.label}),ae);return}const W=$.options;w(ae=>{const be={...ae,[M.id]:W};return Vu.set(g,be),be});const U=Tj(M.id,{localOverrideUntil:v.current,localValues:k.current,controlValues:j.current,defaultValues:C});if(Aj(U,$.currentValue)){const ae=$.currentValue;b(be=>({...be,[M.id]:ae}))}A(M.id)}catch(P){ct.showErrorToast(u("controls.loadOptionsFailed",{label:M.label}),P)}finally{L(null)}}},H=async(M,D)=>{A(null);const P=(i==null?void 0:i[M.id])??C[M.id];b($=>({...$,[M.id]:D})),v.current=Date.now()+5e3;try{if(!M.setScript)return;const $=await F(M.setScript,il(M,D)),W=na($);if(W&&!W.ok||sa($))throw new Error((W==null?void 0:W.error)||Yr($)||`Could not update ${M.label}`);N(M,D,W)}catch($){I(M,P),ct.showErrorToast(u("controls.updateFailed",{label:M.label}),$)}},q=async M=>{const D=Ca(M,S).map(be=>be.value);if(D.length===0)return;const P=String(x[M.id]||""),W=(D.indexOf(P)+1)%D.length,U=D[W];if(typeof U!="string")return;const ae=(i==null?void 0:i[M.id])??C[M.id];b(be=>({...be,[M.id]:U})),v.current=Date.now()+5e3;try{if(!M.setScript)return;const be=await F(M.setScript,il(M,U)),V=na(be);if(V&&!V.ok||sa(be))throw new Error((V==null?void 0:V.error)||Yr(be)||`Could not update ${M.label}`);N(M,U,V)}catch(be){I(M,ae),ct.showErrorToast(u("controls.updateFailed",{label:M.label}),be)}},J=async M=>{const P=!x[M.id],$=(i==null?void 0:i[M.id])??C[M.id];b(W=>({...W,[M.id]:P})),v.current=Date.now()+5e3;try{if(!M.setScript)return;const W=await F(M.setScript,il(M,P)),U=na(W);if(U&&!U.ok||sa(W))throw new Error((U==null?void 0:U.error)||Yr(W)||`Could not update ${M.label}`);N(M,P,U)}catch(W){I(M,$),ct.showErrorToast(u("controls.updateFailed",{label:M.label}),W)}},K=async M=>{var P,$,W;if(!M.invokeScript||M.confirmMessage&&!await h({title:((P=M.confirmTitle)==null?void 0:P.trim())||M.confirmMessage,description:($=M.confirmTitle)!=null&&$.trim()?M.confirmMessage:void 0,confirmLabel:((W=M.confirmLabel)==null?void 0:W.trim())||u("common.confirm")}))return;const D=(i==null?void 0:i[M.id])??C[M.id];try{const U=await F(M.invokeScript),ae=na(U);if(ae&&!ae.ok||sa(U))throw new Error((ae==null?void 0:ae.error)||Yr(U)||`Could not run ${M.label}`);ae&&N(M,D??!0,ae)}catch(U){I(M,D),ct.showErrorToast(u("controls.runFailed",{label:M.label}),U)}};return n.jsxs("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-2xs font-semibold tracking-[0.02em]",style:{borderColor:`${f}33`,background:`${f}12`,color:f},children:o}),B.map(M=>{const D=String(x[M.id]||""),P=Lj(M,S,D),$=_===M.id,W=O===M.id,U=Ca(M,S),ae="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-xs font-medium transition-colors whitespace-nowrap";switch(M.type){case"select":return n.jsxs("div",{className:"relative max-w-full",children:[n.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${f}55`:"var(--border-default)",background:$?`${f}10`:"var(--surface-tertiary)",color:D?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(M),title:M.label,children:[M.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:M.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?u("chatControls.loading"):P||M.label}),n.jsx("span",{className:"text-4xs opacity-55",children:"▼"})]}),$&&U.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-[var(--z-dropdown)]",onClick:()=>A(null)}),n.jsxs("div",{className:"absolute bottom-full left-0 z-[var(--z-dropdown)] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[n.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-3xs font-semibold uppercase tracking-[0.08em] text-text-muted",children:M.label}),U.map(be=>n.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-xs transition-colors",style:{background:be.value===D?`${f}14`:"transparent",color:be.value===D?"var(--text-primary)":"var(--text-secondary)",borderLeft:be.value===D?`2px solid ${f}`:"2px solid transparent"},title:be.description||be.label,onMouseEnter:V=>{V.currentTarget.style.background=`${f}10`},onMouseLeave:V=>{V.currentTarget.style.background=be.value===D?`${f}14`:"transparent"},onClick:()=>void H(M,be.value),children:[n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:be.label}),be.value===D&&n.jsx("span",{className:"shrink-0 text-2xs font-semibold",style:{color:f},children:"✓"})]},be.value))]})]})]},M.id);case"cycle":return n.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:D?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void q(M),title:`Click to cycle: ${U.map(be=>be.label).join(" → ")}`,children:[M.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:M.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P||M.label}),n.jsx("span",{className:"text-3xs opacity-55",children:"⟳"})]},M.id);case"toggle":return n.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:D?`${f}44`:"var(--border-default)",background:D?`${f}14`:"var(--surface-tertiary)",color:D?f:"var(--text-muted)"},onClick:()=>void J(M),"aria-pressed":!!D,children:[M.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:M.icon}),M.label]},M.id);case"action":return n.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void K(M),children:[M.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:M.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:M.resultDisplay==="inline"&&D?`${M.label}: ${D}`:M.label})]},M.id);case"display":return n.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-xs font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:D?"var(--text-primary)":"var(--text-muted)"},children:[M.icon&&n.jsx("span",{className:"text-2xs opacity-70",children:M.icon}),n.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:D?`${M.label}: ${D}`:M.label})]},M.id);default:return null}})]}),p]})}function Oj(e){if(!e||typeof e!="object")return{};const t=e,s=uv(t.launch);return{...s?{launch:s}:{},...typeof t.model=="string"&&t.model.trim()?{model:t.model.trim()}:{},...Zc(t.modelSource)?{modelSource:t.modelSource}:{}}}const Yu={user:"chosen",remembered:"remembered",mesh_slot:"mesh slot",task_override:"task",provider_default:"default",unspecified:""};function Fj(e,t){return String(t.defaultValue??"").replace(/\{\{(\w+)\}\}/g,(s,r)=>String(t[r]??""))}function Pf(e,t=Fj){const s=e.launch?dv(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=Yu[o]?t(`chatControls.launchModelSource.${o}`,{defaultValue:Yu[o]}):"";return{text:a?`${r} · ${a}`:r,source:o}}function $j({surface:e}){const{t}=ve("common"),s=Pf(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 Hj({isActive:e=!0,isCliTerminal:t=!1,routeId:s,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:c,controlValues:d,currentStatus:u,coordinatorHint:m,launchSurface:h}){const{isVisible:p}=pd(),g=xd(c,{hostIdeType:o,providerType:a,currentStatus:u}),f=g.length>0&&p,y=!!h&&!!Pf(h);return!e||t||!f&&!y?null:n.jsxs("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:[y&&h&&n.jsx("div",{className:"flex justify-end px-3 pt-1",children:n.jsx($j,{surface:h})}),f&&n.jsx(Dj,{routeId:s,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:g,controlValues:d,currentStatus:u,coordinatorHint:m})]})}const Qr=5,Lf=10*1024*1024;function Bj({hasDraft:e,isBusy:t=!1}){return!e||t}function Wj(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 Uj(e){if(e.size>Lf)return null;const t=await Wj(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 Kj(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}function qj(e){return/[\u1100-\u11FF\u3130-\u318F\uAC00-\uD7A3]/.test(e)}const Ef=l.memo(function({contextKey:t,panelLabel:s,isSending:r,isBusy:o=!1,statusMessage:a=null,inlineStatusMessage:i=null,onSend:c,isActive:d=!0,showControlsToggle:u=!1,animateVisibility:m=!0,onControlsToggle:h,messageInput:p}){const{t:g}=ve("common"),f=l.useRef(null),y=l.useRef(null),[b,k]=l.useState(""),[j,v]=l.useState([]),[C,x]=l.useState(null),[S,w]=l.useState(!1),_=l.useRef(!1),A=l.useRef(0),O=50,L=l.useRef(""),R=l.useRef(!1),F=l.useRef(null),N=30,{isVisible:I,toggleVisibility:B}=pd(),T=Kj(p),H=!!b.trim()||j.length>0;l.useEffect(()=>{k(""),v([]),x(null)},[t]),l.useEffect(()=>{var U;d&&((U=f.current)==null||U.focus({preventScroll:!0}))},[t,d]),l.useEffect(()=>{const U=f.current;U&&(U.style.height="auto",b&&(U.style.height=`${Math.min(U.scrollHeight,160)}px`))},[b]);const q=l.useCallback(async U=>{x(null);const ae=Array.from(U).filter(ne=>ne.type.startsWith("image/"));if(ae.length===0)return;const be=Qr-j.length;if(be<=0){x(`Max ${Qr} images`);return}const V=ae.slice(0,be);if(V.filter(ne=>ne.size>Lf).length>0){x("Image too large (max 10 MB)");return}const de=(await Promise.all(V.map(Uj))).filter(ne=>ne!==null);v(ne=>[...ne,...de])},[j.length]),J=l.useCallback(U=>{v(ae=>ae.filter((be,V)=>V!==U))},[]),K=l.useCallback(async()=>{const U=b.trim();if(!U&&j.length===0||o||_.current)return;_.current=!0;const ae=j.length>0?[...j]:void 0;try{await c(U,ae)!==!1&&(k(""),v([]),x(null))}finally{_.current=!1}},[b,j,o,c]),M=l.useRef(K);M.current=K;const D=l.useCallback(()=>{R.current&&(R.current=!1,F.current&&(clearTimeout(F.current),F.current=null),setTimeout(()=>{M.current()},0))},[]);l.useEffect(()=>()=>{F.current&&clearTimeout(F.current)},[]);const P=l.useCallback(U=>{T&&(U.preventDefault(),w(!0))},[T]),$=l.useCallback(()=>w(!1),[]),W=l.useCallback(U=>{T&&(U.preventDefault(),w(!1),U.dataTransfer.files.length>0&&q(U.dataTransfer.files))},[T,q]);return n.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",S?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:d?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:d?200:0,opacity:d?1:0,transform:d?"translateY(0)":"translateY(10px)",padding:d?"10px 12px":"0 12px",pointerEvents:d?"auto":"none"},"aria-hidden":!d,onDragOver:P,onDragLeave:$,onDrop:W,children:[j.length>0&&n.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:j.map((U,ae)=>n.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[n.jsx("img",{src:U.previewUrl,alt:U.name,className:"w-full h-full object-cover"}),n.jsx("button",{type:"button",onClick:()=>J(ae),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-3xs leading-none","aria-label":`Remove ${U.name}`,children:"✕"})]},ae))}),n.jsxs("div",{className:"flex gap-2 items-center",title:d?g("chatInput.sendTo",{panel:s}):void 0,children:[u&&n.jsx("button",{type:"button",onClick:()=>{B(),h==null||h()},"aria-label":g(I?"chatInput.hideControls":"chatInput.showControls"),"aria-pressed":I,title:g(I?"chatInput.hideControls":"chatInput.showControls"),className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:n.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[n.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),n.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),n.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),T&&n.jsxs(n.Fragment,{children:[n.jsx("input",{ref:y,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:U=>{U.target.files&&q(U.target.files),U.target.value=""}}),n.jsx("button",{type:"button",onClick:()=>{var U;return(U=y.current)==null?void 0:U.click()},disabled:j.length>=Qr,title:j.length>=Qr?`Max ${Qr} images`:g("chatInput.attachImage"),className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":g("chatInput.attachImage"),children:n.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),n.jsx("div",{className:"flex-1 relative",children:n.jsx("textarea",{ref:f,rows:1,placeholder:a||(T&&j.length>0?g("chatInput.addMessageOptional"):g("chatInput.placeholder",{panel:s})),value:b,onChange:U=>k(U.target.value),onPaste:U=>{if(T&&U.clipboardData.files.length>0&&Array.from(U.clipboardData.files).some(ue=>ue.type.startsWith("image/"))){U.preventDefault(),q(U.clipboardData.files);return}const ae=U.clipboardData.getData("text/plain"),be=Nv(ae);if(be===ae)return;U.preventDefault();const V=f.current,we=(V==null?void 0:V.selectionStart)??b.length,ce=(V==null?void 0:V.selectionEnd)??b.length,de=b.slice(0,we)+be+b.slice(ce);k(de);const ne=we+be.length;requestAnimationFrame(()=>{V==null||V.setSelectionRange(ne,ne)})},onCompositionUpdate:U=>{L.current=U.data||""},onCompositionEnd:U=>{A.current=Date.now(),U.data&&(L.current=U.data),D()},onKeyDown:U=>{if(U.key!=="Enter"||U.shiftKey)return;if(U.nativeEvent.isComposing||U.keyCode===229||Date.now()-A.current<O){U.preventDefault(),qj(L.current)&&!R.current&&(R.current=!0,F.current=setTimeout(D,N));return}U.preventDefault(),K()},className:"w-full rounded-[20px] px-4 py-2 bg-bg-secondary text-sm text-text-primary resize-none leading-[1.4] block",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))",minHeight:40,maxHeight:160,overflowY:"auto",whiteSpace:"pre-wrap"}})}),n.jsx("button",{onClick:()=>{K()},disabled:Bj({hasDraft:H,isBusy:o}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${H&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:H&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":g("chatInput.sendMessage"),children:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:H?"text-white":"text-text-muted",children:n.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(C||T&&S)&&n.jsx("div",{className:`pt-1.5 px-1 text-2xs ${C?"text-red-400":"text-[var(--accent-primary)]"}`,children:C||g("chatInput.dropImage")}),i&&!C&&n.jsx("div",{className:"pt-2 px-1 text-2xs text-text-muted opacity-80",children:i})]})});function zj({entries:e,onSendNow:t,onCancelQueued:s,isSendingNow:r}){const{t:o}=ve(),a=e.filter(d=>d.queued===!0&&!!d.id);if(a.length===0)return null;const i=a.some(d=>d.stale!==!0),c=o(i?"chat.waitingToSendAria":"chat.notDeliveredAria");return n.jsx("div",{className:"chat-pending-queue-strip","data-testid":"pending-queue-strip","data-pending-queue-count":a.length,role:"region","aria-label":c,children:a.map(d=>n.jsxs("div",{className:"chat-pending-queue-row","data-chat-queued-row":"true","data-chat-queued-stale":d.stale===!0?"true":void 0,children:[n.jsxs("div",{className:"chat-bubble chat-bubble-user chat-pending-queue-bubble",title:d.content,children:[n.jsx("div",{className:"chat-pending-queue-body",children:d.content}),n.jsx("span",{className:d.stale===!0?"chat-pending-queue-clock chat-pending-queue-stale":"chat-pending-queue-clock",role:"img","aria-label":d.stale===!0?o("chat.notDeliveredAria"):o("chat.waitingToSendAria"),title:d.stale===!0?o("chat.notDelivered"):o("chat.waitingToSendAria"),children:d.stale===!0?"⚠":"⏱"})]}),t&&n.jsx("button",{type:"button",onClick:()=>t(d.id),disabled:r,className:"chat-pending-queue-send","aria-label":o("chat.sendNowAria"),title:o("chat.sendNowTitle"),children:"↑"}),s&&n.jsx("button",{type:"button",onClick:()=>s(d.id),disabled:r,className:"chat-pending-queue-cancel","aria-label":o("chat.cancelQueuedAria"),title:o("chat.cancelQueuedTitle"),children:"✕"})]},d.id))})}const Gj=l.memo(zj,(e,t)=>e.onSendNow===t.onSendNow&&e.onCancelQueued===t.onCancelQueued&&e.isSendingNow===t.isSendingNow&&e.entries.length===t.entries.length&&e.entries.every((s,r)=>{const o=t.entries[r];return!!o&&s.id===o.id&&s.content===o.content&&s.queued===o.queued&&s.stale===o.stale})),Vj={accent:{track:"--accent-primary",head:"--accent-primary-light"},success:{track:"--status-online",head:"--status-online"},muted:{track:"--text-muted",head:"--text-muted"}};function ln({size:e=28,thickness:t=2.5,color:s="accent",className:r,label:o}){const a=Vj[s],i={width:e,height:e,border:`${t}px solid color-mix(in srgb, var(${a.track}) 20%, transparent)`,borderTopColor:`var(${a.head})`};return n.jsx("span",{className:xt("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 Yj=1e4;function Qj({machineId:e,blocked:t,retryConnection:s}){const{t:r}=ve("common"),[o,a]=l.useState(!1),i=l.useRef(null);if(l.useEffect(()=>{t||a(!1)},[t]),l.useEffect(()=>{if(!o)return;const d=setTimeout(()=>a(!1),Yj);return()=>clearTimeout(d)},[o]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),!e||!t||!s)return null;const c=()=>{o||(a(!0),s(e))};return n.jsxs("button",{type:"button","data-testid":"chat-machine-reconnect",onClick:c,disabled:o,"aria-label":r("chatPane.reconnectMachine"),title:r("chatPane.reconnectMachineTitle"),className:"inline-flex items-center justify-center gap-1 h-6 px-2 rounded-full leading-none text-3xs font-bold transition-colors bg-red-500/10 border border-red-500/25 text-red-400 hover:bg-red-500/20 disabled:opacity-60 disabled:cursor-not-allowed",style:{pointerEvents:"auto"},children:[o?n.jsx(ln,{size:11,thickness:2,color:"muted"}):n.jsx(Tr,{size:12}),n.jsx("span",{children:r(o?"chatPane.reconnectingMachine":"chatPane.reconnectMachine")})]})}let Df=An;function yd(){return Df()}class Jj{constructor(){qe(this,"listeners",new Map)}send(t,s){return!1}isConnected(){return!1}on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>{var r;(r=this.listeners.get(t))==null||r.delete(s)}}emit(t,...s){var r;(r=this.listeners.get(t))==null||r.forEach(o=>o(...s))}}let Of=new Jj;class Xj{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 Lt=new Xj;function Zj(e){e.dashboardWS&&(Of=e.dashboardWS),e.connectionManager&&(Lt=e.connectionManager),e.useDaemonsHook&&(Df=e.useDaemonsHook)}function _a(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Ff="adhdev-pending-queued-messages-v1",eN=256*1024,tN=24*60*60*1e3,$f=10*60*1e3;function Hf(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Ff)||"{}");return{byKey:e.byKey&&typeof e.byKey=="object"?e.byKey:{}}}catch{return{byKey:{}}}}function nN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ff,JSON.stringify(e))}catch{}}function sN(e,t){if(!e||typeof e!="object")return;const s=e;if(!Array.isArray(s.parts))return;let r=0;const o=new Set(s.omitted&&typeof s.omitted=="object"&&Array.isArray(s.omitted.partTypes)?s.omitted.partTypes.filter(c=>typeof c=="string"):[]),a=[];for(const c of s.parts){if(!c||typeof c!="object")continue;const d=c,u=typeof d.type=="string"?d.type:"";if(!u)continue;if(u==="text"){a.push({type:"text",text:typeof d.text=="string"?d.text:""});continue}const m=typeof d.data=="string"?d.data:void 0,h=m?m.length:0;if(m&&r+h<=eN){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 Bf(e,t){if(!Array.isArray(e))return[];const s=new Set,r=[];let o=0;for(const a of e){if(!a||typeof a!="object")continue;const i=a,c=typeof i.content=="string"?i.content:"",d=typeof i.sentAt=="number"&&Number.isFinite(i.sentAt)?i.sentAt:0,u=typeof i.id=="string"&&i.id?i.id:"";if(!c.trim()||!d||!u||t-d>tN||s.has(u))continue;s.add(u);const m=i.stale===!0||t-d>$f,h=sN(i.input,c);r.push({entry:{id:u,content:c,sentAt:d,queued:i.queued===!0,settled:!0,stale:m,...h?{input:h}:{}},index:o}),o+=1}return r.sort((a,i)=>a.entry.sentAt-i.entry.sentAt||a.index-i.index),r.map(a=>a.entry).slice(-20)}let Qu=0;function rN(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 Qu+=1,`pq-${e}-${Qu}`}function oN(e,t=Date.now()){const s=String(e||"").trim();return s?Bf(Hf().byKey[s],t):[]}function aN(e,t,s=Date.now()){const r=String(e||"").trim();if(!r)return;const o=Hf(),a=Bf(t,s);a.length>0?o.byKey[r]=a:delete o.byKey[r],nN(o)}function Wf(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}const iN=12e4;function lN(e){if(typeof e=="string")return e.trim();if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}const cN=/^(?:\s*(?:\[Image #\d+\]|\[image: [^\]\n]{1,100}\]))+\s*/;function dN(e,t){const s=lN(e);if(s===t)return!0;const r=s.replace(cN,"").trim();return r!==s&&r.length>0&&r===t}function uN(e,t){if(!t)return!1;const s=e.meta;return typeof(s==null?void 0:s.sourceMessageId)=="string"&&s.sourceMessageId===t}function Ju(e){const t=e.meta;return typeof(t==null?void 0:t.sourceMessageId)=="string"&&t.sourceMessageId.length>0}function Uf(e,t){if(!t)return 0;let s=0;for(const r of e)String(r.role||"").toLowerCase()==="user"&&dN(r.content,t)&&(s+=1);return s}function mN(e,t,s=Date.now(),r=$f){if(!e||e.length===0)return{entries:[],changed:!1,retiredByEcho:0,markedStale:0};const o=new Map,a=[];let i=0,c=0,d=!1;const u=t.some(m=>Ju(m))?t.filter(m=>!Ju(m)):t;for(const m of e){const h=m.content.trim();if(!h){d=!0;continue}if(t.some(f=>uN(f,m.id))){i+=1,d=!0;continue}o.has(h)||o.set(h,Uf(u,h));const p=o.get(h)||0;if(p>0){o.set(h,p-1),i+=1,d=!0;continue}if(s-m.sentAt>r&&m.stale!==!0){c+=1,d=!0,a.push({...m,stale:!0});continue}a.push(m)}return d?{entries:a,changed:!0,retiredByEcho:i,markedStale:c}:{entries:e,changed:!1,retiredByEcho:0,markedStale:0}}function hN(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 pN(e,t,s=Date.now(),r={}){if(!t||t.length===0)return e;const o=new Map,a=[];for(const i of t){const c=i.content.trim();if(!c||s-i.sentAt>iN)continue;o.has(c)||o.set(c,Uf(e,c));const d=o.get(c)||0;if(d>0){o.set(c,d-1);continue}r.excludeQueued&&i.queued===!0&&i.id||a.push(hN(i))}return a.length===0?e:[...e,...a]}function fN(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 ll(e){return fN(e)?String(e.role||"").toLowerCase():""}const gN=4;function bN(e,t){if(e.length===0)return[];for(let a=t.length-1;a>=0;a-=1)if(ll(t[a])==="assistant")return[];const s=t.some(a=>ll(a)==="user"),r=[];let o=!1;for(let a=e.length-1;a>=0&&r.length<gN;a-=1){const i=e[a],c=ll(i);if(c){if(!o&&c==="assistant"){r.unshift(i),o=!0;continue}if(o&&c==="user"){s||r.unshift(i);break}}}return r}function xN(e){let t=!0;for(let s=1;s<e.length;s+=1)if(_a(e[s-1])>_a(e[s])){t=!1;break}return t?e:e.map((s,r)=>({message:s,index:r,ts:_a(s)})).sort((s,r)=>s.ts-r.ts||s.index-r.index).map(s=>s.message)}function yN(e){const{historyMessages:t,liveMessages:s,visibleLiveCount:r}=e,o=Math.max(0,s.length-r),a=o>0?s.slice(0,o):[],i=o>0?s.slice(-r):s,c=bN(a,i),d=c.length>0?[...c,...i]:i,u=t.length===0?d:[...t,...d];return xN(u)}const St=e=>e.transport==="pty",$r=(e,t)=>St(e)&&e.mode||"chat",Kf=(e,t)=>St(e)&&$r(e)==="terminal",vt=e=>e.transport==="acp",vN=180;function Ss(e){return e.streamSource!=="agent-stream"}function as(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Ai(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 qf(e){return e.machineName||""}function Cs(e){return as(e)}function Vn(e){return e.agentType||""}function Ka(e){return e.hostIdeType||""}function vd(e){return e.displayPrimary||e.agentName||"Agent"}function zf(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function wN(e,t){const s=Wf(e,t),r=[...s].reverse();return r.find(o=>!(o!=null&&o._localId)&&wi(o).isUserFacing)||r.find(o=>!(o!=null&&o._localId))||s[s.length-1]}function Gf(e,t){const s=wN(e,t),r=_r(s==null?void 0:s.content),o=_r(e.lastMessagePreview);return o&&e.lastMessageRole==="assistant"&&(s==null?void 0:s.role)==="user"?o:r||o||""}function SN(e,t=vN){const s=_r(e);if(!s||t<=0)return"";const r=Array.from(s);return r.length<=t?s:`${r.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function kN(e){return SN(Gf(e)||e.displaySecondary||"")}function Vf(e){return[e.displaySecondary,qf(e)].filter(Boolean)}function Mr(e){return e.agentName||Kt(Vn(e))}function jN(e){var t,s;if(!Ss(e)){const r=(s=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:s.trim();if(r)return r}return Kt(Ka(e)||Vn(e))}function Yf(e){return Ss(e)?e.sessionId:e.nativeSessionId}function Xu(e){return Ss(e)?"native":e.tabKey}function NN(e){return e.sessionId}function Qf(e,t){if(t)return Ss(e)||!t.childSessions?t:t.childSessions.find(s=>s.id===e.sessionId||s.providerType===e.agentType)||t}function CN(e,t){const s=Vn(e),r=Ss(e),o=St(e)||vt(e),a=r?o?Mr(e)||(t==null?void 0:t.cliName)||Kt(Ka(e)||s):t!=null&&t.type?Kt(t.type):Kt(Ka(e)||s):Mr(e);return{isNativeConversation:r,isCli:St(e),isAcp:vt(e),isCliTerminal:Kf(e),providerType:s,displayLabel:a,targetEntry:Qf(e,t)}}function ks(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:St(e)||vt(e)?{agentType:Vn(e)}:e.streamSource==="agent-stream"?{agentType:Vn(e)}:t}function vs(e){return e?Cs(e):""}function yr(e,t){e(s=>[...s,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}const _N="Waiting for approval…",AN="Waiting for your answer…";function Ti(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 Jf(e){return Ti(e)?(e==null?void 0:e.status)==="waiting_choice"?AN:_N:null}function ra(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 Xf(){return"select_session"}function TN(){return"open_panel"}function IN({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function MN(e,t,s=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<s:!1}function Zu(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Us(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}const uo="Waiting to send — the agent is still working.",RN="Too late to cancel — this message was already sent to the agent.";function em(e){return!e||typeof e!="object"?!1:e.queued===!0}function PN({feedbackMessage:e,lastSendQueued:t,isGenerating:s}){return!t||e!==uo?!1:!s}function wd(e){return e instanceof Error?e.message:String(e||"")}function tm(e){const t=wd(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function nm(e,t){const s=wd(t);return s?s.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${s}`:`⚠️ **${e}** unavailable`}const LN=5e3;function EN(e,t,s=LN){const r=e.get(t);if(!r)return Promise.resolve("unknown");let o;const a=new Promise(i=>{o=setTimeout(()=>i("unknown"),s)});return Promise.race([r,a]).finally(()=>{o&&clearTimeout(o)})}function DN(e,t){if(!t||t.length===0)return;const s=t.map(r=>({type:"image",mimeType:r.mimeType,data:r.data,alt:r.name}));return e&&s.push({type:"text",text:e}),{parts:s,textFallback:e}}function sm(e,t,s,r,o={mode:"queue"}){const a=s?{parts:s.parts,textFallback:s.textFallback}:{parts:[{type:"text",text:t}],textFallback:t};return{messageId:e,input:a,policy:o,...ks(r)}}function Ii({sendDaemonCommand:e,activeConv:t,setActionLogs:s,isStandalone:r}){const[o,a]=l.useState(!1),[i,c]=l.useState(!1),[d,u]=l.useState(null),[m,h]=l.useState(!1),[p,g]=l.useState([]),f=l.useRef(!1),y=l.useRef(null),b=l.useRef([]);b.current=p;const k=l.useRef(new Map),j=(t==null?void 0:t.tabKey)||"",v=l.useRef(j);v.current=j;const C=l.useCallback(N=>{g(I=>{const B=N(I);return B===I?I:(aN(v.current,B),B)})},[]),x=l.useCallback(N=>{C(I=>{const B=mN(I,N);return B.changed?B.entries:I})},[C]);l.useEffect(()=>{u(null),h(!1),g(j?oN(j):[])},[t==null?void 0:t.tabKey,j]);const S=t?er(t):!1;l.useEffect(()=>{u(N=>PN({feedbackMessage:N,lastSendQueued:m,isGenerating:S})?null:N),!S&&m&&h(!1)},[S,m]);const w=l.useCallback(async(N,I)=>{if(!t||f.current)return!1;const B=N.trim(),T=Ti(t);if(IN({hasMessage:!!B,blockedMessage:T,sendInFlight:f.current}))return T&&u(T),!1;const H=Date.now(),q={tabKey:t.tabKey,message:B,timestamp:H};if(MN(y.current,q))return u(null),!0;f.current=!0,c(!0),u(null),h(!1),y.current=q;const J=rN(H),K=DN(B,I);let M=()=>{};k.current.set(J,new Promise(P=>{M=P}));let D="not-parked";C(P=>[...P,{id:J,content:B,sentAt:H,...K?{input:K}:{}}].slice(-20));try{const P=vs(t);if(!P)return y.current=Zu(y.current,q),C(U=>U.filter(ae=>ae.id!==J)),u("Unable to send message right now."),!1;const $=await e(P,"send_chat",sm(J,B,K,t)),W=Us($);if(W!=null&&W.deduplicated)return u(null),!0;if(em(W))return D="parked",h(!0),C(U=>U.map(ae=>ae.id===J?{...ae,queued:!0}:ae)),u(uo),!0;if((W==null?void 0:W.sent)===!1)throw new Error((W==null?void 0:W.error)||"Send failed");if((W==null?void 0:W.success)===!1)throw new Error((W==null?void 0:W.error)||"Send failed");return h(!1),u(null),!0}catch(P){const $=wd(P);return $.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",$):console.warn("Send blocked/failed",P),y.current=Zu(y.current,q),C(W=>W.filter(U=>U.id!==J)),u(ra(P)),!1}finally{k.current.delete(J),M(D),C(P=>P.map($=>$.id===J?{...$,settled:!0}:$)),f.current=!1,c(!1)}},[t,e,C]),_=l.useCallback(async N=>{if(!t||f.current)return!1;const I=b.current,B=N?I.find(q=>q.id===N):I.find(q=>q.queued===!0);if(!B||!B.queued)return!1;const T=B.content.trim();if(!T)return!1;const H=B.id;f.current=!0,c(!0),u(null);try{const q=vs(t);if(!q)return u("Unable to send message right now."),!1;const J=await e(q,"send_chat",sm(H,T,B.input,t,{mode:"send_now"})),K=Us(J);return(K==null?void 0:K.success)===!1?(u(ra(new Error((K==null?void 0:K.error)||"Send now failed"))),!1):(K==null?void 0:K.queuedWithAgent)===!0?(h(!1),C(M=>M.map(D=>D.id===H?{...D,queued:!1}:D)),u(null),!0):em(K)?(h(!0),C(M=>M.map(D=>D.id===H?{...D,queued:!0}:D)),u(uo),!0):(h(!1),C(M=>M.map(D=>D.id===H?{...D,queued:!1}:D)),u(null),!0)}catch(q){return console.warn("Send now blocked/failed",q),u(ra(q)),!1}finally{f.current=!1,c(!1)}},[t,e,C]),A=l.useCallback(async N=>{if(!t||!N)return!1;const I=b.current.find(T=>T.id===N);if(!I)return!1;const B=I.content.trim();if(I.settled&&!I.queued)return C(T=>T.filter(H=>H.id!==N)),!0;if(!I.settled&&await EN(k.current,N)==="not-parked")return C(H=>H.filter(q=>q.id!==N)),!0;try{const T=vs(t);if(!T)return u("Unable to cancel this message right now."),!1;const H=await e(T,"cancel_queued_chat",{messageId:N,message:B,...ks(t)}),q=Us(H),J=typeof(q==null?void 0:q.cancelled)=="number"&&q.cancelled===0;return J&&I.stale===!0?(C(K=>K.filter(M=>M.id!==N)),u(K=>K===uo?null:K),!0):(q==null?void 0:q.success)===!1||J?(u(RN),!1):(C(K=>K.filter(M=>M.id!==N)),u(K=>K===uo?null:K),!0)}catch(T){return console.warn("Cancel queued send failed",T),u(ra(T)),!1}},[t,e,C]),O=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(N){console.error("Relaunch failed",N)}},[t,e]),L=l.useCallback(async N=>{if(t)try{const B=(t.modalButtons||[]).indexOf(N),T=N.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),H=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(T),q=vs(t);if(!q)return;const J=await e(q,"resolve_action",{button:N,action:H?"approve":"reject",...B>=0&&{buttonIndex:B},...ks(t),...Ai(t)}),K=Us(J);K.success||s(M=>[...M,{routeId:t.tabKey,text:nm(N,K==null?void 0:K.error),timestamp:Date.now()}])}catch(I){tm(I)||console.error("[ModalButton] Error:",I),s(B=>[...B,{routeId:t.tabKey,text:tm(I)?nm(N,I):`❌ **${N}** error`,timestamp:Date.now()}])}},[t,e,s]),R=l.useCallback(async()=>{if(!(!t||o)){a(!0);try{await e(t.routeId,TN(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(N){console.error("Focus agent failed",N)}finally{a(!1)}}},[t,o,e]),F=p.length>0?p[p.length-1]:null;return l.useMemo(()=>({isSendingChat:i,sendFeedbackMessage:d,lastSendQueued:m,pendingLocalMessage:F,pendingLocalMessages:p,isFocusingAgent:o,handleSendChat:w,handleSendNowQueued:_,handleCancelQueued:A,retireEchoedPendingMessages:x,handleRelaunch:O,handleModalButton:L,handleFocusAgent:R}),[i,d,m,F,p,o,w,_,A,x,O,L,R])}const ON=10,FN=8e3,$N=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function HN(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 gc(e,t="",s=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if($N.test(t)&&e.trim())return"[REDACTED:secret-field]";const r=HN(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=>gc(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,gc(o,r,s+1)]))}function Jr(e,t){return Array.isArray(e)?e.slice(-t):[]}function BN(e,t=Date.now()){const s=e&&t-e.firstAt<=FN,r=s?e.count+1:1;return r>=ON?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:r,firstAt:s?e.firstAt:t},shouldCollect:!1}}function Zf(e){var r,o;const{activeConv:t}=e,s={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((r=e.chatTailState.liveMessages)==null?void 0:r.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((o=e.chatTailState.historyMessages)==null?void 0:o.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Jr(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:Jr(t.messages,10),visibleMessagesTail:Jr(e.visibleMessages,5),historyMessagesTail:Jr(e.chatTailState.historyMessages,5),actionLogsTail:Jr(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{hasLiveSnapshot:!!e.chatTailState.hasLiveSnapshot,hasMoreHistory:!!e.chatTailState.hasMoreHistory,historyError:e.chatTailState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return gc(s)}function eg(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 tg(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 ng(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const s=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&s.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&s.push("","warnings:",...t.warnings.map(r=>`- ${String(r)}`)),s.join(`
|
|
32
|
-
`)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
|
|
33
|
-
|
|
34
|
-
\`\`\`json
|
|
35
|
-
${JSON.stringify(t.bundle,null,2)}
|
|
36
|
-
\`\`\``:`# ADHDev Chat Debug Bundle
|
|
37
|
-
|
|
38
|
-
\`\`\`json
|
|
39
|
-
${JSON.stringify(t,null,2)}
|
|
40
|
-
\`\`\``}function cl(e,t){return`${e}:${t}`}const WN=new Set(["intervalMs"]);function rm(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]=WN.has(r)?Math.min(a,o):Math.max(a,o):t[r]=o}return t}function om(e){const t=e.params;return t&&typeof t=="object"?{...t}:{}}function am(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function UN(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function dr(e,t){UN()&&console.debug(`[subscription-manager] ${e}`,t)}class KN{constructor(){qe(this,"active",new Map);qe(this,"retryTimers",new Map)}subscribe(t,s,r,o,a){var h,p;const i=cl(r.topic,r.key),c=this.active.get(i);let d=!0;if(c){c.handlers.add(o),c.handlerParams.set(o,om(r));const g={...r,params:rm(c.handlerParams.values())};(!am(c.request,g)||c.daemonId!==s)&&(c.daemonId=s,c.request=g,d=((h=t.sendData)==null?void 0:h.call(t,s,g))??!1,!d&&(a!=null&&a.retryIntervalMs)?this.scheduleRetry(i,t,a.retryIntervalMs):d&&this.clearRetry(i),dr("subscribe_update",{daemonId:s,topic:r.topic,key:r.key,accepted:d})),c.lastUpdate&&o(c.lastUpdate)}else{const g={daemonId:s,request:r,handlers:new Set([o]),handlerParams:new Map([[o,om(r)]])};this.active.set(i,g),dr("subscribe",{daemonId:s,topic:r.topic,key:r.key}),d=((p=t.sendData)==null?void 0:p.call(t,s,r))??!1,!d&&(a!=null&&a.retryIntervalMs)&&this.scheduleRetry(i,t,a.retryIntervalMs)}let u=!1;const m=()=>{var b,k;if(u)return;u=!0,this.clearRetry(i);const g=this.active.get(i);if(!g)return;if(g.handlers.delete(o),g.handlerParams.delete(o),g.handlers.size>0){const j={...g.request,params:rm(g.handlerParams.values())};am(g.request,j)||(g.request=j,(b=t.sendData)==null||b.call(t,g.daemonId,j));return}this.active.delete(i);const f=g.daemonId,y={type:"unsubscribe",topic:r.topic,key:r.key};dr("unsubscribe",{daemonId:f,topic:r.topic,key:r.key}),(k=t.sendData)==null||k.call(t,f,y)};return m.initialSendAccepted=d,m}publish(t){const s=cl(t.topic,t.key),r=this.active.get(s);r&&(this.clearRetry(s),r.lastUpdate=t,Xs.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),r.handlers.forEach(o=>{o(t),Xs.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,s,r){const o=cl(t,s),a=this.active.get(o);if(a){a.request={...a.request,params:{...a.request.params,...r}};for(const[i,c]of a.handlerParams)a.handlerParams.set(i,{...c,...r})}}resubscribeAll(t){var s;dr("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(r=>({daemonId:r.daemonId,topic:r.request.topic,key:r.request.key}))});for(const r of this.active.values())(s=t.sendData)==null||s.call(t,r.daemonId,r.request)}resubscribeForDaemon(t,s){var o;const r=Array.from(this.active.values()).filter(a=>a.daemonId===t);dr("resubscribe_daemon",{daemonId:t,count:r.length,subscriptions:r.map(a=>({topic:a.request.topic,key:a.request.key}))});for(const a of r)(o=s.sendData)==null||o.call(s,a.daemonId,a.request)}scheduleRetry(t,s,r){if(this.retryTimers.has(t))return;const o=setTimeout(()=>{var c;this.retryTimers.delete(t);const a=this.active.get(t);if(!a)return;const i=((c=s.sendData)==null?void 0:c.call(s,a.daemonId,a.request))??!1;dr("subscribe_retry",{id:t,accepted:i,topic:a.request.topic,key:a.request.key}),i||this.scheduleRetry(t,s,r)},r);this.retryTimers.set(t,o)}clearRetry(t){const s=this.retryTimers.get(t);s!==void 0&&(clearTimeout(s),this.retryTimers.delete(t))}}const _n=new KN;function qN(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 zN(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 dl(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function GN(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function VN(e){GN()&&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 qa(e,t){const s=[],{daemonId:r,existingDaemon:o,existingEntries:a,timestamp:i}=t,c=i||e.timestamp||Date.now(),d=e.sessions||[],u=on(r,e.instanceId),{topLevel:m,childrenByParent:h}=zN(d),p=qN(a,r),g=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,f=m.filter(k=>k.kind==="workspace"&&k.transport==="cdp-page"),y=m.filter(k=>k.kind==="agent"&&k.transport==="pty"),b=m.filter(k=>k.kind==="agent"&&k.transport==="acp");s.push({...o||{},id:r,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...g&&{machine:g,platform:g.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},...e.beacon&&{beacon:u?e.beacon:void 0},...e.fleetStatusPeerView&&{fleetStatusPeerView:e.fleetStatusPeerView},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:f.some(k=>!!k.cdpConnected)});for(const k of f){const j=p.get(k.id),v=io(k,j),C=(h.get(k.id)||[]).map(x=>io(x,p.get(x.id)));s.push({id:`${r}:ide:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:v.parentId,sessionKind:v.kind,transport:v.transport,sessionCapabilities:v.capabilities,type:v.providerType,status:v.cdpConnected?"online":"detected",daemonId:r,instanceId:dl(r,k.id),workspace:v.workspace,terminals:0,childSessions:C,agents:C.map(x=>({id:x.id,name:x.providerName||x.providerType,type:x.providerType,status:x.status})),activeChat:v.activeChat,...v.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:v.activeInteractivePrompt},chats:[],cdpConnected:v.cdpConnected,...v.lastMessagePreview!==void 0&&{lastMessagePreview:v.lastMessagePreview},...v.lastMessageRole!==void 0&&{lastMessageRole:v.lastMessageRole},...v.lastMessageAt!==void 0&&{lastMessageAt:v.lastMessageAt},...v.lastMessageHash!==void 0&&{lastMessageHash:v.lastMessageHash},lastUpdated:v.lastUpdated,unread:v.unread,lastSeenAt:v.lastSeenAt,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,seenCompletionMarker:v.seenCompletionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,...v.controlValues!==void 0&&{controlValues:v.controlValues},...v.providerControls!==void 0&&{providerControls:v.providerControls},...v.summaryMetadata!==void 0&&{summaryMetadata:v.summaryMetadata},...v.settings!==void 0&&{settings:v.settings},...v.messageInput!==void 0&&{messageInput:v.messageInput},timestamp:c})}for(const k of y){const j=p.get(k.id),v=io(k,j);s.push({id:`${r}:cli:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:v.parentId,sessionKind:v.kind,transport:v.transport,sessionCapabilities:v.capabilities,type:v.providerType,agentType:v.providerType,status:fu(v.status)||"generating",daemonId:r,instanceId:dl(r,k.id),cliName:v.providerName||v.providerType,mode:v.mode||(j==null?void 0:j.mode)||"terminal",workspace:v.workspace||"",...k.ownerDaemonId&&{ownerDaemonId:k.ownerDaemonId},...k.ownerMachineName&&{ownerMachineName:k.ownerMachineName},activeChat:v.activeChat,...v.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:v.activeInteractivePrompt},...v.resume!==void 0&&{resume:v.resume},...v.runtimeKey!==void 0&&{runtimeKey:v.runtimeKey},...v.runtimeDisplayName!==void 0&&{runtimeDisplayName:v.runtimeDisplayName},...v.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:v.runtimeWorkspaceLabel},...v.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:v.runtimeWriteOwner},...v.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:v.runtimeAttachedClients},...v.lastMessagePreview!==void 0&&{lastMessagePreview:v.lastMessagePreview},...v.lastMessageRole!==void 0&&{lastMessageRole:v.lastMessageRole},...v.lastMessageAt!==void 0&&{lastMessageAt:v.lastMessageAt},...v.lastMessageHash!==void 0&&{lastMessageHash:v.lastMessageHash},lastUpdated:v.lastUpdated,unread:v.unread,lastSeenAt:v.lastSeenAt,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,seenCompletionMarker:v.seenCompletionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,...v.controlValues!==void 0&&{controlValues:v.controlValues},...v.providerControls!==void 0&&{providerControls:v.providerControls},...v.summaryMetadata!==void 0&&{summaryMetadata:v.summaryMetadata},...v.settings!==void 0&&{settings:v.settings},...v.messageInput!==void 0&&{messageInput:v.messageInput},timestamp:c,_isCli:!0})}for(const k of b){const j=p.get(k.id),v=io(k,j);s.push({id:`${r}:acp:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:v.parentId,sessionKind:v.kind,transport:v.transport,sessionCapabilities:v.capabilities,type:v.providerType,agentType:v.providerType,status:fu(v.status)||"generating",daemonId:r,instanceId:dl(r,k.id),cliName:v.providerName||v.providerType,mode:"chat",workspace:v.workspace||"",...k.ownerDaemonId&&{ownerDaemonId:k.ownerDaemonId},...k.ownerMachineName&&{ownerMachineName:k.ownerMachineName},activeChat:v.activeChat,...v.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:v.activeInteractivePrompt},...v.runtimeKey!==void 0&&{runtimeKey:v.runtimeKey},...v.runtimeDisplayName!==void 0&&{runtimeDisplayName:v.runtimeDisplayName},...v.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:v.runtimeWorkspaceLabel},...v.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:v.runtimeWriteOwner},...v.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:v.runtimeAttachedClients},...v.lastMessagePreview!==void 0&&{lastMessagePreview:v.lastMessagePreview},...v.lastMessageRole!==void 0&&{lastMessageRole:v.lastMessageRole},...v.lastMessageAt!==void 0&&{lastMessageAt:v.lastMessageAt},...v.lastMessageHash!==void 0&&{lastMessageHash:v.lastMessageHash},lastUpdated:v.lastUpdated,unread:v.unread,lastSeenAt:v.lastSeenAt,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,seenCompletionMarker:v.seenCompletionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,...v.controlValues!==void 0&&{controlValues:v.controlValues},...v.providerControls!==void 0&&{providerControls:v.providerControls},...v.summaryMetadata!==void 0&&{summaryMetadata:v.summaryMetadata},...v.settings!==void 0&&{settings:v.settings},...v.messageInput!==void 0&&{messageInput:v.messageInput},timestamp:c,_isAcp:!0})}return VN(s),s}const YN=15e3,QN=15e3,JN=6e4,im=12,XN=8e3,ZN=4e3;function eC(e){const{force:t,hasSubscription:s,loadedAt:r,now:o,minFreshMs:a}=e;return t||r<=0?!0:s?!1:o-r>=a}const ul=new Map,ml=new Map,Xr=new Set;function tC(e){if(!e||typeof e!="object")return null;const t=e,s=t.status;if(s&&typeof s=="object")return s;const r=t.result;if(r&&typeof r=="object"&&"status"in r){const o=r.status;if(o&&typeof o=="object")return o}return t}function Hr(){const{sendCommand:e,sendData:t}=_t(),{injectEntries:s,getIdes:r}=Ar(),o=l.useRef(new Map);return l.useEffect(()=>{const a=o.current;return()=>{for(const[i,c]of a)c(),Xr.delete(i);a.clear()}},[]),l.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??JN;if(!eC({force:i==null?void 0:i.force,hasSubscription:Xr.has(a),loadedAt:ml.get(a)||0,now:Date.now(),minFreshMs:c}))return;const d=ul.get(a);if(d)return d;const u=(async()=>{var y;if(t&&!Xr.has(a)){const b=_n.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},k=>{const j=r(),v=j.find(x=>x.id===a),C=qa(k.status,{daemonId:a,existingDaemon:v,existingEntries:j,timestamp:k.timestamp});C.length>0&&s(C),ml.set(a,Date.now())});(y=o.current.get(a))==null||y(),o.current.set(a,b),b.initialSendAccepted?Xr.add(a):Xr.delete(a)}const m=await e(a,"get_status_metadata"),h=tC(m);if(!h)return;const p=r(),g=p.find(b=>b.id===a),f=qa(h,{daemonId:a,existingDaemon:g,existingEntries:p,timestamp:h.timestamp||Date.now()});f.length>0&&s(f,{authoritativeDaemonIds:[a]}),ml.set(a,Date.now())})().finally(()=>{ul.delete(a)});return ul.set(a,u),u},[r,s,e,t])}const Ls=8,lm=6;function nC(e,t,s){const r=Math.max(Ls,s.width-t.width-Ls),o=e.left+e.width/2-t.width/2,a=Math.min(Math.max(Ls,o),r),i=e.bottom+lm,c=i+t.height<=s.height-Ls,d=e.top-lm-t.height;return!c&&d>=Ls?{top:d,left:a,placement:"above"}:{top:Math.max(Ls,Math.min(i,s.height-t.height-Ls)),left:a,placement:"below"}}function Sd(){const e=l.useRef(null),t=l.useRef(null),[s,r]=l.useState({pinned:!1,peeking:!1}),[o,a]=l.useState(null),i=s.pinned||s.peeking,c=l.useCallback(()=>r({pinned:!1,peeking:!1}),[]),d=l.useCallback(()=>r(h=>h.pinned?{pinned:!1,peeking:!1}:{pinned:!0,peeking:!1}),[]),u=l.useCallback(h=>r(p=>p.peeking===h?p:{...p,peeking:h}),[]),m=l.useCallback(()=>{const h=e.current,p=t.current;if(!h||!p||typeof window>"u")return;const g=h.getBoundingClientRect(),f=p.getBoundingClientRect();a(nC({top:g.top,bottom:g.bottom,left:g.left,width:g.width},{width:f.width,height:f.height},{width:window.innerWidth,height:window.innerHeight}))},[]);return l.useLayoutEffect(()=>{if(!i){a(null);return}m()},[i,m]),l.useEffect(()=>{if(!i||typeof window>"u")return;const h=f=>{var y,b;f.key==="Escape"&&(f.stopPropagation(),f.preventDefault(),c(),(b=(y=e.current)==null?void 0:y.focus)==null||b.call(y))},p=f=>{var b,k;const y=f.target;y&&((b=e.current)!=null&&b.contains(y)||(k=t.current)!=null&&k.contains(y)||c())},g=()=>m();return window.addEventListener("keydown",h,!0),document.addEventListener("pointerdown",p,!0),document.addEventListener("mousedown",p,!0),window.addEventListener("resize",g),window.addEventListener("scroll",g,!0),()=>{window.removeEventListener("keydown",h,!0),document.removeEventListener("pointerdown",p,!0),document.removeEventListener("mousedown",p,!0),window.removeEventListener("resize",g),window.removeEventListener("scroll",g,!0)}},[c,i,m]),{anchorRef:e,popoverRef:t,open:i,pinned:s.pinned,position:o,close:c,togglePinned:d,setPeeking:u}}function kd({id:e,popoverRef:t,position:s,children:r,className:o,role:a="tooltip",ariaLabel:i}){return typeof document>"u"?null:Qn.createPortal(n.jsx("div",{ref:t,id:e,role:a,"aria-label":i,"data-placement":(s==null?void 0:s.placement)??"below",className:xt("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 sg(e){return e==null||e===!1||e===""}function dt({content:e,label:t,size:s=13,className:r,popoverClassName:o}){const{t:a}=ve("common"),i=l.useId(),c=`${i}-pop`,d=`${i}-desc`,{anchorRef:u,popoverRef:m,open:h,position:p,togglePinned:g,setPeeking:f}=Sd();return sg(e)?null:n.jsxs("span",{className:"inline-flex items-center align-middle",children:[n.jsx("button",{ref:y=>{u.current=y},type:"button","data-infotip":"","aria-label":t??a("common.moreInfo"),"aria-expanded":h,"aria-controls":h?c:void 0,"aria-describedby":d,onClick:y=>{y.preventDefault(),y.stopPropagation(),g()},onPointerEnter:y=>{y.pointerType==="mouse"&&f(!0)},onPointerLeave:y=>{y.pointerType==="mouse"&&f(!1)},className:xt("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(Io,{size:s})}),n.jsx("span",{id:d,className:"sr-only",children:e}),h&&n.jsx(kd,{id:c,popoverRef:m,position:p,className:o,children:e})]})}function tn({content:e,children:t,className:s,popoverClassName:r}){const o=l.useId(),a=`${o}-pop`,i=`${o}-desc`,{anchorRef:c,popoverRef:d,open:u,position:m,togglePinned:h,setPeeking:p}=Sd();if(sg(e))return n.jsx(n.Fragment,{children:t});const g=n.jsx("span",{ref:f=>{c.current=f},"data-tooltip":"",tabIndex:0,"aria-describedby":i,className:xt("inline-flex max-w-full cursor-default items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-accent/60",s),onPointerEnter:f=>{f.pointerType==="mouse"&&p(!0)},onPointerLeave:f=>{f.pointerType==="mouse"&&p(!1)},onPointerUp:f=>{f.pointerType!=="mouse"&&h()},onFocus:()=>p(!0),onBlur:()=>p(!1),onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),h())},children:t});return n.jsxs(n.Fragment,{children:[g,n.jsx("span",{id:i,className:"sr-only",children:e}),u&&n.jsx(kd,{id:a,popoverRef:d,position:m,className:r,children:e})]})}function w5({children:e,content:t,label:s,className:r,popoverClassName:o}){const i=`${l.useId()}-pop`,{anchorRef:c,popoverRef:d,open:u,position:m,togglePinned:h}=Sd();return n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:p=>{c.current=p},type:"button","aria-label":s,"aria-expanded":u,"aria-haspopup":"dialog","aria-controls":u?i:void 0,onClick:p=>{p.preventDefault(),p.stopPropagation(),h()},className:r,children:e}),u&&n.jsx(kd,{id:i,popoverRef:d,position:m,role:"dialog",ariaLabel:s,className:xt("whitespace-normal",o),children:t})]})}const sC=60,rC=50;function rg(e={}){return e.isCliLike?rC:sC}function oC(e={}){return rg(e)}const og=new Map;function cm(e,t){if(!e)return t;const s=og.get(e);return typeof s=="number"&&s>t?s:t}function aC(e,t){e&&og.set(e,t)}function iC(e){return{"data-transcript-read-source":e.transcriptReadSource,...e.transcriptFallbackReason?{"data-transcript-fallback-reason":e.transcriptFallbackReason}:{},...e.stale?{"data-transcript-stale":"true"}:{},...e.omittedBefore?{"data-transcript-omitted-before":"true"}:{},...e.transcriptReplicaDegraded?{"data-transcript-replica-degraded":"true"}:{}}}function lC(e){const t={role:e.role,kind:e.kind,content:e.content};return e.receivedAt!==null&&(t.receivedAt=e.receivedAt),e.timestamp!==null&&(t.timestamp=e.timestamp),e.bubbleState!==null&&(t.bubbleState=e.bubbleState),e.senderName!==null&&(t.senderName=e.senderName),e.toolName!==null&&e.toolName&&(t.toolName=e.toolName,t.meta={...t.meta??{},label:e.toolName}),e.toolBlockRef!==null&&(t.toolBlockRef=e.toolBlockRef),e.turnKey!==null&&(t._turnKey=e.turnKey),typeof e.sequence=="number"&&(t.sequence=e.sequence),t}function cC(e){if(e.messageSource)return{selected:e.messageSource}}function ag(e){if(!e||typeof e!="object")return!1;const t=e;if(typeof t.sessionId!="string"||!t.sessionId||typeof t.status!="string"||!t.status||!Array.isArray(t.messages)||!t.provenance||typeof t.provenance!="object"||!("activeModal"in t))return!1;const s=t.activeModal;if(s!==null){if(!s||typeof s!="object")return!1;const r=s;if(typeof r.message!="string"||!Array.isArray(r.buttons))return!1}return!0}function ig(e,t){const s=cC(e.provenance);return{topic:"session.chat_tail",key:t.subscriptionKey,sessionId:e.sessionId,...e.historySessionId?{historySessionId:e.historySessionId}:{},seq:e.revision,timestamp:0,messages:e.messages.map(lC),status:e.status,...e.title?{title:e.title}:{},activeModal:e.activeModal?{message:e.activeModal.message,buttons:[...e.activeModal.buttons]}:null,activeInteractivePrompt:null,...s?{messageSource:s}:{},omittedBefore:t.omittedBefore,stale:t.stale,transcriptReadSource:"replica"}}const dC=new Set([...mu("working"),...mu("blocked"),...Object.keys(vp).filter(e=>wp(e))]);function mo(e){return hi(e)}const uC=new Set(["agent:generating_completed","agent:stopped","agent:waiting_approval","agent:waiting_choice"]);function lg(e){return typeof e=="string"&&uC.has(e)}function bc(e){return wp(e)}const Eo=60;function mC(e,t=Eo){return{tailLimit:t}}function dm(e,t){const s=e[e.length-1];if(!s)return"empty:";let r="";try{r=JSON.stringify(s.content??"")}catch{r=String(s.content??"")}return["",e.length,String(s.id||""),String(s.index??""),String(s.receivedAt??s.timestamp??""),r].join("|")}function za(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(za).join(`
|
|
41
|
-
`);if(typeof e=="object"){const t=e;return za(t.text??t.content??t.value??"")}return String(e)}function jd(e){return za(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function hC(e){return e.length===0||e.every(jd)}function um(e){for(let t=e.length-1;t>=0;t-=1){const s=e[t],r=typeof(s==null?void 0:s.role)=="string"?s.role:"",o=typeof(s==null?void 0:s.kind)=="string"?s.kind:"";if(!(r==="system"||o==="system")&&!(o==="tool"||o==="thought"||o==="terminal"||o==="activity")&&!jd(e[t]))return r}return""}function mm(e){for(let t=e.length-1;t>=0;t-=1){const s=e[t],r=typeof(s==null?void 0:s.role)=="string"?s.role:"",o=typeof(s==null?void 0:s.kind)=="string"?s.kind:"";if(r==="system"||o==="system"||o==="tool"||o==="thought"||o==="terminal"||o==="activity"||jd(e[t]))continue;if(r!=="assistant")return"";const a=e[t];return`${String(a.bubbleId??a.providerUnitKey??a.id??"")}#${za(a.content).length}`}return""}function cg(e,t){if(um(t)!=="assistant")return!1;const s=Array.isArray(e.liveMessages)?e.liveMessages:[];return um(s)!=="assistant"}function Mi(e){return typeof e=="string"?{selected:e}:e}function pC(e){const t=Mi(e);return!!t&&t.selected==="native-history"}function fC(e,t,s){return pC(s)?cg(e,t):!1}function dg(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function gC(e,t,s,r,o,a,i){const c=bc(r)||mo(r),d=a&&e.hasLiveSnapshot;if(!c&&!d)return!1;const u=c?dg(e,t):Array.isArray(e.liveMessages)?e.liveMessages.length:0;if(u<=0)return!1;if(hC(s))return!0;if(d&&!c&&cg(e,s))return!1;const m=Mi(o);if(m){const h=m.selected,p=m.fallbackReason;if(h==="native-history"||typeof p=="string"&&p!==""&&!p.startsWith("native_history_"))return!1}return i==="replica"?!1:s.length<u}function bC(e,t,s,r){if(s.length!==0||dg(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0)return!1;const a=Mi(r);if(!a)return!1;const i=a.selected,c=a.fallbackReason,d=a.nativeSource;return i==="native-history"?c==="native_history_transient_gap_held":d==="native-unavailable"?!0:typeof c=="string"&&c.startsWith("native_history_")}function xC(e,t,s,r,o,a,i){return gC(e,t,s,r,o,a,i)?"defer-busy-shrink":bC(e,t,s,o)?"skip-transient-empty":"apply"}function yC(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function hm(e,t){const s=e[t];return typeof s=="string"?s:""}function pm(e){return e.transcriptReadSource==="replica"?"replica":"legacy"}function fm(e,t){return e[t]===!0}function gm(e,t){const s=e[t];return typeof s=="string"&&s.length>0?s:void 0}function vC(e,t){const{sendData:s,sendCommand:r,isConnected:o}=_t(),a=(t==null?void 0:t.enabled)!==!1,i=(t==null?void 0:t.refreshEnabled)!==!1,c=Cs(e),d=e.sessionId||"",u=Ci(e),m=`daemon:${c}:session:${d}`,h=Math.max(0,(t==null?void 0:t.tailLimit)??Eo),p=e.messages.length,g=l.useMemo(()=>!a||!c||!d?null:pg({daemonId:c,sessionId:d,historySessionId:u,subscriptionKey:m,sendData:s,tailLimit:h,fallbackRecentCount:p,includeActivity:qs()}),[c,a,u,s,d,m,h]);l.useEffect(()=>{g==null||g.updateOptions({fallbackRecentCount:p})},[g,p]);const[f,y]=l.useState(()=>(g==null?void 0:g.getSnapshot())||Ga(h));l.useEffect(()=>{if(!g){y(Ga(h));return}g.retain(),y(g.getSnapshot());const v=g.subscribe(C=>{y(C)});return()=>{v(),g.release()}},[g,h]);const b=l.useCallback(async()=>{!g||!c||!d||await g.loadHistoryPage(async({offset:v,excludeRecentCount:C,excludeFromIdentity:x})=>{const S=e.agentType,w=await r(c,"chat_history",{agentType:S,offset:v,limit:30,targetSessionId:d,historySessionId:u,excludeRecentCount:C,...x?{excludeFromIdentity:x}:{},...qs()?{includeActivity:!0}:{}}),_=w&&typeof w=="object"&&"result"in w?w.result||{}:w||{};return{messages:Array.isArray(_.messages)?_.messages:[],hasMore:_.hasMore===!0}})},[e.agentType,g,c,u,r,d]),k=l.useCallback((v=!1)=>!g||!c||!d?Promise.resolve():g.refreshAuthoritativeTail(async()=>{const C=await r(c,"read_chat",{agentType:e.agentType,targetSessionId:d,historySessionId:u,...h>0?{tailLimit:h}:{},...qs()?{includeActivity:!0}:{}}),x=C&&typeof C=="object"&&"result"in C?C.result:C;if(!x||typeof x!="object"||x.success===!1)return null;const S=Array.isArray(x.messages)?x.messages:Array.isArray(x.messagesTail)?x.messagesTail:[];return{topic:"session.chat_tail",key:m,sessionId:d,historySessionId:u,seq:0,timestamp:0,messages:S,status:typeof x.status=="string"?x.status:"idle",...x.messageSource&&typeof x.messageSource=="object"?{messageSource:x.messageSource}:{}}},{force:v}),[e.agentType,g,c,u,r,d,m,h]);l.useEffect(()=>{if(g)return dd(v=>{g.updateOptions({includeActivity:v}),v&&k(!0)})},[g,c,d,u]),l.useEffect(()=>{if(!g||!a||!i||!c||!d)return;k(!0);const v=()=>{typeof document<"u"&&document.visibilityState==="visible"&&k()},C=w=>{w.persisted&&k()};typeof document<"u"&&document.addEventListener("visibilitychange",v),typeof window<"u"&&window.addEventListener("pageshow",C);let x=o?o(c):!0;const S=setInterval(()=>{if(!o)return;const w=o(c);w&&!x&&k(),x=w},2e3);return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",v),typeof window<"u"&&window.removeEventListener("pageshow",C),clearInterval(S)}},[g,c,a,i,d,u]);const j=BC({hasController:!!g,enabled:a,daemonId:c,sessionId:d,refreshEnabled:i});return l.useEffect(()=>{if(!g||!j.armed)return;const v=setInterval(()=>{g.shouldRefreshForLiveness({visible:j.visible})&&k()},CC),C=()=>{typeof document>"u"||g.noteVisibilityChange(document.hidden)},x=()=>{g.noteVisibilityChange(!0)},S=()=>{g.noteVisibilityChange(!1)};return C(),typeof document<"u"&&document.addEventListener("visibilitychange",C),typeof window<"u"&&(window.addEventListener("pagehide",x),window.addEventListener("pageshow",S)),()=>{clearInterval(v),typeof document<"u"&&document.removeEventListener("visibilitychange",C),typeof window<"u"&&(window.removeEventListener("pagehide",x),window.removeEventListener("pageshow",S))}},[g,j.armed,j.visible,d,u]),l.useMemo(()=>DC(f,b),[b,f])}function wC(e,t){const{sendData:s}=_t(),r=(t==null?void 0:t.enabled)!==!1,o=Math.max(0,(t==null?void 0:t.tailLimit)??Eo),a=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Ri)),i=$C(a),[c,d]=l.useState(0);l.useEffect(()=>{if(!r||e.length===0)return;const m=setInterval(()=>{d(h=>h+1)},i);return()=>{clearInterval(m)}},[e.length,r,i]);const u=l.useMemo(()=>HC(e,{recentActivityMs:a}),[e,a,c]);l.useEffect(()=>{if(!r||!s||u.descriptors.length===0)return;const m=u.descriptors.map(h=>pg({...h,sendData:s,tailLimit:o}));return m.forEach(h=>{h.retain()}),()=>{m.forEach(h=>h.release())}},[u.signature,r,s,o])}function SC(e){const[t,s]=l.useState(0),r=l.useMemo(()=>{const i=[];for(const c of e){const d=Cs(c),u=c.sessionId||"";if(!d||!u)continue;const m=Ci(c);i.push(Do(d,u,m||u))}return i},[e]),o=r.join("|"),a=l.useSyncExternalStore(hg,xm,xm);return l.useEffect(()=>{if(r.length===0)return;const i=[];for(const c of r){const d=is.get(c);if(!d)continue;let u=!1;i.push(d.subscribe(()=>{if(!u){u=!0;return}s(m=>m+1)}))}return()=>{for(const c of i)c()}},[o,a]),t}function kC(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 jC=1e3,NC=750,CC=5e3,ug=2e4,_C=12e4,AC=6e4,hl=ug,bm=500,Ri=12e4,is=new Map;let mg=0;const xc=new Set;function yc(){mg+=1;for(const e of xc)e()}function hg(e){return xc.add(e),()=>{xc.delete(e)}}function xm(){return mg}function Do(e,t,s){return`${e}::${t}::${s||t}`}function Ga(e=Eo){return{liveMessages:[],hasLiveSnapshot:!1,cursor:mC([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null,transcriptReadSource:"legacy",omittedBefore:!1,stale:!1,transcriptReplicaDegraded:!1}}class TC{constructor(t){qe(this,"manager");qe(this,"sendData");qe(this,"daemonId");qe(this,"sessionId");qe(this,"historySessionId");qe(this,"subscriptionKey");qe(this,"fallbackRecentCount");qe(this,"includeActivity");qe(this,"snapshot");qe(this,"transportSubscription",null);qe(this,"listeners",new Set);qe(this,"retainCount",0);qe(this,"loadHistoryPromise",null);qe(this,"pendingDisconnectTimer",null);qe(this,"authoritativeRefreshPromise",null);qe(this,"lastAuthoritativeRefreshAt",0);qe(this,"now");qe(this,"lastActiveStatusAt",0);qe(this,"lastAppliedAt",0);qe(this,"lastInboundAt",0);qe(this,"lastKnownStatus");qe(this,"lastMappedRevisionSnapshot",null);qe(this,"lastMappedOmittedBefore",!1);qe(this,"lastMappedStale",!1);qe(this,"terminalStatusRefreshPending",!1);qe(this,"lastLivenessAttemptAt",0);qe(this,"replicaHealthy",!1);qe(this,"lastReportedTransportSelection",null);qe(this,"everHadHealthyReplica",!1);qe(this,"lastReplicaAdvanceAt",0);qe(this,"lastReplicaRevision",0);qe(this,"lastReplicaBusyAt",0);qe(this,"hiddenSinceAt",0);qe(this,"hiddenElapsedMs",0);this.manager=t.manager||_n,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.includeActivity=t.includeActivity===!0,this.now=t.now??(()=>Date.now()),this.snapshot=Ga(Math.max(0,t.tailLimit??Eo))}updateOptions(t){const s=this.sendData,r=this.daemonId,o=this.sessionId;if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.now&&(this.now=t.now),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const a=Math.max(0,t.tailLimit);a!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:a}},this.transportSubscription&&(this.disconnect(),this.connect()))}t.includeActivity!==void 0&&t.includeActivity!==this.includeActivity&&(this.includeActivity=t.includeActivity,this.transportSubscription&&(this.disconnect(),this.connect())),this.retainCount>0&&(s!==this.sendData||r!==this.daemonId||o!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...Ga(this.snapshot.cursor.tailLimit),hasLiveSnapshot:!0},this.lastMappedRevisionSnapshot=null,this.emit()}reportTranscriptReplicaFallback(t){const s=this.replicaHealthy;this.replicaHealthy=!1,(s||!this.transportSubscription)&&this.syncLegacySubscription();const r=this.everHadHealthyReplica;this.snapshot.transcriptReadSource==="legacy"&&this.snapshot.transcriptFallbackReason===t&&this.snapshot.transcriptReplicaDegraded===r||(this.snapshot={...this.snapshot,transcriptReadSource:"legacy",transcriptFallbackReason:t,transcriptReplicaDegraded:r},this.emit())}applyTranscriptReplicaSnapshot(t,s){if(!ag(t)){this.reportTranscriptReplicaFallback("revision_invalid");return}const r=this.lastMappedRevisionSnapshot===t&&this.lastMappedOmittedBefore===s.omittedBefore&&this.lastMappedStale===(s.stale===!0);let o;if(r){const c=this.now();this.lastInboundAt=c,this.lastKnownStatus=t.status,(bc(t.status)||mo(t.status))&&(this.lastActiveStatusAt=c),o="noop"}else o=this.handleUpdate(s.mapped??ig(t,{subscriptionKey:this.subscriptionKey,omittedBefore:s.omittedBefore,stale:s.stale===!0})),o==="noop"?(this.lastMappedRevisionSnapshot=t,this.lastMappedOmittedBefore=s.omittedBefore,this.lastMappedStale=s.stale===!0):this.lastMappedRevisionSnapshot=null;const a=typeof t.revision=="number"?t.revision:0;a>this.lastReplicaRevision&&(this.lastReplicaRevision=a,this.lastReplicaAdvanceAt=this.now(),this.hiddenElapsedMs=0),mo(t.status)&&(this.lastReplicaBusyAt=this.now()),!this.replicaHealthy&&o==="applied"&&(this.replicaHealthy=!0,this.everHadHealthyReplica=!0,this.lastReplicaAdvanceAt===0&&(this.lastReplicaAdvanceAt=this.now()),this.syncLegacySubscription()),this.snapshot.transcriptReplicaDegraded&&(this.snapshot={...this.snapshot,transcriptReplicaDegraded:!1},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.syncLegacySubscription(),this.retainCount===1&&yc()}isRetained(){return this.retainCount>0}getIdentity(){return{daemonId:this.daemonId,sessionId:this.sessionId}}release(){const t=this.retainCount>0;this.retainCount=Math.max(0,this.retainCount-1),t&&this.retainCount===0&&yc(),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const s=(async()=>{try{const r=this.snapshot.hasLiveSnapshot,o=r?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),a=await t({offset:this.snapshot.historyOffset,excludeRecentCount:o,excludeFromIdentity:kC(this.snapshot.liveMessages[0])}),i=Array.isArray(a.messages)?a.messages:[],c=!r&&i.length===0&&a.hasMore!==!0&&this.fallbackRecentCount>0,d=[...i,...this.snapshot.historyMessages],u=d.length>bm?d.slice(d.length-bm):d;this.snapshot={...this.snapshot,historyMessages:u,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:a.hasMore===!0,historyError:null}}catch(r){this.snapshot={...this.snapshot,historyError:r instanceof Error?r.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=s,s}expireStaleReplicaLease(){if(!this.replicaHealthy||this.lastReplicaBusyAt===0)return;const t=this.now(),s=this.hiddenElapsedMs+(this.hiddenSinceAt>0?Math.max(0,t-this.hiddenSinceAt):0);if(t-this.lastReplicaBusyAt-s>hl)return;const r=t-this.lastReplicaAdvanceAt-s>=hl,o=this.lastAppliedAt>0&&t-this.lastAppliedAt-s>=hl;!r&&!o||this.reportTranscriptReplicaFallback(r?"replica_lease_expired":"replica_screen_stalled")}noteTerminalStatusEvent(t){lg(t)&&(this.terminalStatusRefreshPending=!0)}noteVisibilityChange(t){const s=this.now();if(t){this.hiddenSinceAt===0&&(this.hiddenSinceAt=s);return}this.hiddenSinceAt!==0&&(this.hiddenElapsedMs+=Math.max(0,s-this.hiddenSinceAt),this.hiddenSinceAt=0)}shouldRefreshForLiveness(t={}){if(this.expireStaleReplicaLease(),this.lastInboundAt===0||this.authoritativeRefreshPromise)return!1;if(this.terminalStatusRefreshPending)return this.terminalStatusRefreshPending=!1,!0;if(this.replicaHealthy)return!1;const s=Math.max(this.lastAppliedAt,this.lastLivenessAttemptAt),r=this.now()-s,o=mo(this.lastKnownStatus)?ug:_C,a=t.visible===!0?o:Math.max(o,AC);return r>=a}getLivenessStateForTest(){return{lastInboundAt:this.lastInboundAt,lastAppliedAt:this.lastAppliedAt,lastKnownStatus:this.lastKnownStatus}}refreshAuthoritativeTail(t,s={}){if(this.authoritativeRefreshPromise)return this.authoritativeRefreshPromise;const r=this.now();if(!s.force&&this.lastAuthoritativeRefreshAt>0&&r-this.lastAuthoritativeRefreshAt<NC)return Promise.resolve();this.lastAuthoritativeRefreshAt=r;const o=(async()=>{try{const a=await t();a&&this.handleUpdate(a),this.lastInboundAt=this.now(),this.lastLivenessAttemptAt=this.now()}catch{this.lastInboundAt=this.now(),this.lastLivenessAttemptAt=this.now()}})().finally(()=>{this.authoritativeRefreshPromise=null});return this.authoritativeRefreshPromise=o,o}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{},...this.includeActivity?{includeActivity:!0}:{}}}}shouldRunLegacySubscription(){return!this.replicaHealthy}syncLegacySubscription(){this.retainCount<=0||(this.shouldRunLegacySubscription()?this.connect():this.disconnect(),this.reportTransportSelection())}reportTransportSelection(){if(!this.sendData||!this.daemonId)return;const t=this.replicaHealthy?"replica":"legacy";if(this.lastReportedTransportSelection!==t){this.lastReportedTransportSelection=t;try{this.sendData(this.daemonId,{type:"command",commandType:"report_transcript_transport",data:{selection:t}})}catch{}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||this.shouldRunLegacySubscription()&&(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:jC}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null,this.replicaHealthy=!1,this.lastReportedTransportSelection=null,this.everHadHealthyReplica=!1,this.lastReplicaAdvanceAt=0,this.lastReplicaRevision=0,this.lastReplicaBusyAt=0,this.hiddenSinceAt=0,this.hiddenElapsedMs=0,this.lastMappedRevisionSnapshot=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return"rejected";const s=hm(t,"sessionId");if(s&&s!==this.sessionId)return"rejected";const r=hm(t,"historySessionId");if(r&&this.historySessionId&&r!==this.historySessionId)return"rejected";const o=yC(t),a=t.messageSource,i=this.now();this.lastInboundAt=i,this.lastKnownStatus=t.status;const c=this.lastActiveStatusAt>0&&i-this.lastActiveStatusAt<=Ri;(bc(t.status)||mo(t.status))&&(this.lastActiveStatusAt=i);const d=fC(this.snapshot,o,a);if(!d&&xC(this.snapshot,this.fallbackRecentCount,o,t.status,a,c,pm(t))!=="apply")return"deferred";const u={tailLimit:this.snapshot.cursor.tailLimit};return!d&&dm(this.snapshot.liveMessages)===dm(o)&&mm(this.snapshot.liveMessages)===mm(o)&&this.snapshot.cursor.tailLimit===u.tailLimit?"noop":(this.lastAppliedAt=i,this.hiddenElapsedMs=0,this.snapshot={...this.snapshot,liveMessages:o,hasLiveSnapshot:!0,cursor:u,messageSource:Mi(a),transcriptReadSource:pm(t),omittedBefore:fm(t,"omittedBefore"),stale:fm(t,"stale"),...gm(t,"transcriptFallbackReason")!==void 0?{transcriptFallbackReason:gm(t,"transcriptFallbackReason")}:{}},this.emit(),"applied")}}function pg(e){const t=Do(e.daemonId,e.sessionId,e.historySessionId),s=is.get(t);if(s)return s.updateOptions(e),s;const r=new TC(e);return is.set(t,r),yc(),r}function IC(e,t,s){if(!e||!t)return;const r=`${e}::${t}::`,o=Do(e,t,s);for(const[a,i]of is.entries())(a===o||a.startsWith(r))&&i.clearLiveSnapshot()}function fg(e){const t=Cs(e),s=e.sessionId||"";if(!t||!s)return;const r=Ci(e),o=Do(t,s,r||s),a=is.get(o);if(!a)return;const i=a.getSnapshot();return i.hasLiveSnapshot?i:void 0}function MC(e,t,s,r){if(!e||!t)return 0;const o=`${e}::${t}::`;let a,i=0;for(const[c,d]of is.entries())c.startsWith(o)&&(!a&&ag(s)&&(a=ig(s,{subscriptionKey:`daemon:${e}:session:${t}`,omittedBefore:r.omittedBefore,stale:r.stale===!0})),d.applyTranscriptReplicaSnapshot(s,{...r,mapped:a}),i+=1);return i}function RC(e,t,s){if(!e||!t||!lg(s))return 0;const r=`${e}::${t}::`;let o=0;for(const[a,i]of is.entries())a.startsWith(r)&&(i.noteTerminalStatusEvent(s),o+=1);return o}function PC(e,t,s){if(!e||!t)return;const r=`${e}::${t}::`;for(const[o,a]of is.entries())o.startsWith(r)&&a.reportTranscriptReplicaFallback(s)}function LC(){const e=new Map;for(const s of is.values()){if(!s.isRetained())continue;const{daemonId:r,sessionId:o}=s.getIdentity();if(!r||!o)continue;const a=e.get(r);a?a.add(o):e.set(r,new Set([o]))}const t=new Map;for(const[s,r]of e.entries())t.set(s,[...r].sort());return t}function EC(e){return hg(e)}function DC(e,t){return{...e,loadHistoryPage:t}}function OC(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function FC(e,t={}){const s=String(e.status||"").trim().toLowerCase();if(dC.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??Ri)),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 $C(e=Ri){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function HC(e,t={}){const s=new Set,r=[];for(const o of e){if(!FC(o,t))continue;const a=Cs(o),i=o.sessionId||"";if(!a||!i)continue;const c=Ci(o),d=Do(a,i,c||i);s.has(d)||(s.add(d),r.push({daemonId:a,sessionId:i,historySessionId:c,subscriptionKey:`daemon:${a}:session:${i}`}))}return r.sort(OC),{descriptors:r,signature:r.map(o=>`${o.subscriptionKey}|${o.historySessionId}`).join("||")}}function BC(e){return{armed:!!(e.hasController&&e.enabled&&e.daemonId&&e.sessionId),visible:e.refreshEnabled}}const WC=5e3;function UC(e,t,s=WC){const[r,o]=l.useState(!1);return l.useEffect(()=>{if(!e){o(!1);return}o(!1);const a=setTimeout(()=>{o(!0)},s);return()=>clearTimeout(a)},[e,t,s]),r}const vc="https://adhf.dev",gg="https://dev.adhf.dev";function bg(e){return e==="adhf.dev"||e==="adhdev-web.pages.dev"||e==="localhost"||e==="127.0.0.1"?vc:gg}function KC(){return typeof window>"u"?vc:bg(window.location.hostname)}function qC(){const e=KC();return{unix:{cmd:`curl -fsSL ${e}/install | sh`,shell:"Terminal",prompt:"$ "},powershell:{cmd:`irm ${e}/install.ps1 | iex`,shell:"PowerShell",prompt:"PS> "},cmd:{cmd:`curl -fsSL ${e}/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd`,shell:"CMD",prompt:"> "}}}function zC(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function GC(e){return zC(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Aa=new Map,wc=new Set;function ym(e,t){!e||Aa.get(e)===t||(t?Aa.set(e,!0):Aa.delete(e),wc.forEach(r=>r(e,t)))}function VC(e){return e?Aa.get(e)===!0:!1}function YC(e){return wc.add(e),()=>{wc.delete(e)}}function QC(e,t,s=`${t}s`){return`${e} ${e===1?t:s}`}function JC(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function XC(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function xg(e){return hi(e.status)||e.inboxBucket==="working"}function yg(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 ZC(e){return xg(e)?!1:e.inboxBucket==="task_complete"&&yg(e).length>0}function vm(e){return e.branch||"detached HEAD"}function e_(e){if(e.error)return`${vm(e)} · Git error: ${e.error}`;const t=[vm(e)];return e.changedFiles>0?t.push(QC(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 t_(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${e_(t)}`}function n_(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function s_(e,t={}){if(t.enabled===!1)return[];if(!XC(e))return[];const s=xg(e)?"working":ZC(e)?"complete":null;if(!s)return[];const r=s==="complete"?yg(e):"";return[{id:s==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${JC(r)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:t_(s,e.git),timestamp:n_(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 r_=60,o_=3e4;function a_(e){return{enabled:!!e.sessionId,refreshEnabled:e.isVisible,tailLimit:e.tailLimit}}function i_(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 l_=["unsupported_source","source_unavailable","source_changed","block_not_found","not_a_tool_block"];function c_(e){return l_.find(t=>t===e)}function d_(){return typeof window>"u"?!1:bg(window.location.hostname)===gg}function u_(e,t){return!t||!e?"":` (${e})`}function vg({activeConv:e,ideEntry:t,handleSendChat:s,handleSendNowQueued:r,handleCancelQueued:o,isSendingChat:a=!1,sendFeedbackMessage:i=null,pendingLocalMessage:c=null,pendingLocalMessages:d=null,retireEchoedPendingMessages:u,handleFocusAgent:m,isFocusingAgent:h,actionLogs:p,userName:g,scrollToBottomRequestNonce:f,isInputActive:y=!0,isVisible:b=!0}){var E,oe,Ie,Z,se,ye,Fe;const{t:k}=ve("common"),j=l.useRef(new Map),v=l.useRef(void 0),C=Hr(),{sendCommand:x}=_t(),{isVisible:S}=pd(),w=yd(),_=Cs(e),A=It.useMemo(()=>{const Me=w.connectionRetryStatuses;if(!Me||!_)return;const De=Me[_];if(De)return De;const Te=Object.keys(Me).find(He=>on(He,_));return Te?Me[Te]:void 0},[w.connectionRetryStatuses,_]);Lo("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:p.length,isSendingChat:a});const O=It.useMemo(()=>or(e),[e.status,e.connectionState]);It.useEffect(()=>{const Me=e.sessionId;if(Me)return ym(Me,O.isGenerating),()=>{ym(Me,!1)}},[e.sessionId,O.isGenerating]);const L=l.useMemo(()=>CN(e,t),[e,t]),R=l.useMemo(()=>Oj(L.targetEntry),[L.targetEntry]),F=l.useMemo(()=>{var Me;return xd((Me=L.targetEntry)==null?void 0:Me.providerControls,{hostIdeType:e.hostIdeType,providerType:L.providerType})},[e.hostIdeType,L.providerType,(E=L.targetEntry)==null?void 0:E.providerControls]),N=rg({isCliLike:L.isCli||L.isAcp}),I=oC({isCliLike:L.isCli||L.isAcp}),B=vC(e,a_({sessionId:e.sessionId,isVisible:b,tailLimit:I})),T=UC(B.transcriptReplicaDegraded,e.tabKey),[H,q]=l.useState(()=>cm(e.tabKey,N)),[J,K]=l.useState(()=>qs()),M=e.tabKey,D=B.historyMessages,P=B.hasMoreHistory,$=B.historyError,W=Wf(e,B),U=pN(W,d??(c?[c]:null),void 0,{excludeQueued:!0}),ae=((d==null?void 0:d.length)??0)>0;l.useEffect(()=>{if(!u||(u(W),!ae))return;const Me=setInterval(()=>u(W),o_);return()=>clearInterval(Me)},[u,W,ae]);const be=l.useMemo(()=>Hw(U).length,[U]);l.useEffect(()=>{q(cm(M,N))},[N,M]);const V=Math.max(0,U.length-H),we=vd(e),ce=Cs(e),de=GC(e),ne=Ti(e),ee=i_(e,k),ue=i||null,je=Jf(e)||i||ee,X=!!ne,[G,z]=l.useState(!1);l.useEffect(()=>{const Me=L.targetEntry;ce&&(!Me||Me.providerControls===void 0||Me.controlValues===void 0)&&C(ce,{minFreshMs:3e4}).catch(()=>{})},[ce,L.isAcp,(oe=L.targetEntry)==null?void 0:oe.providerControls,(Ie=L.targetEntry)==null?void 0:Ie.controlValues,C]);const ie=l.useCallback(async()=>{if(!G){if(U.length>H){q(Me=>{const De=Math.min(U.length,Me+r_);return aC(M,De),De});return}z(!0);try{await B.loadHistoryPage()}finally{z(!1)}}},[B,G,U.length,M,H]),{allMessages:Ne,receivedAtMap:Be}=l.useMemo(()=>{const Me=yN({historyMessages:D,liveMessages:U,visibleLiveCount:H}),De=s_(e),Te=De.length>0?[...Me,...De]:Me,He={};return Te.forEach((tt,Ct)=>{const Q=vi(tt),re=`${e.tabKey}:${Q}`;let le=_a(tt)||j.current.get(re)||0;le||(le=Date.now(),j.current.set(re,le)),He[Q]=le}),{allMessages:Te,receivedAtMap:He}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,V,D,U,H]),Le=l.useMemo(()=>p.filter(Me=>Me.routeId===e.tabKey).sort((Me,De)=>Me.timestamp-De.timestamp),[p,e.tabKey]),[Je,Se]=l.useState({});l.useEffect(()=>{Se({})},[e.tabKey]);const he=l.useCallback(async(Me,De)=>{if(ce){Se(Te=>({...Te,[Me]:{status:"loading"}}));try{const Te=await x(ce,"expand_tool_block",{targetSessionId:e.sessionId,agentType:L.providerType||e.agentType,toolBlockRef:De}),He=Us(Te),tt=He!=null&&He.success?He.callArgs!==void 0?`${He.toolName?`${He.toolName}: `:""}${He.callArgs}`:He.result:void 0;Se(Ct=>({...Ct,[Me]:tt!==void 0?{status:"expanded",text:tt}:{status:"error",error:c_(He==null?void 0:He.reason)}}))}catch{Se(Te=>({...Te,[Me]:{status:"error"}}))}}},[e.agentType,e.sessionId,L.providerType,ce,x]),pe=l.useCallback(Me=>{Se(De=>{if(!De[Me])return De;const Te={...De};return delete Te[Me],Te})},[]),Ee=l.useCallback(async()=>{var Ct,Q;if(!ce)return;const Me=Zf({activeConv:e,visibleMessages:Ne,actionLogs:p,controls:(Ct=L.targetEntry)==null?void 0:Ct.providerControls,controlValues:(Q=L.targetEntry)==null?void 0:Q.controlValues,visibleBarControlCount:F.length,chatTailState:{liveMessages:B.liveMessages,hasLiveSnapshot:B.hasLiveSnapshot,hasMoreHistory:P,historyError:$,historyMessages:D},ui:{controlsVisible:S,visibleLiveCount:H,activityVisible:J,activityCount:be,hiddenLiveCount:V,isInputActive:y,isVisible:b}}),De=await x(ce,"get_chat_debug_bundle",{agentType:L.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:Me}),Te=Us(De),He=ng(Te),tt=await tg(He);tt==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ct.showToast(eg(Te,{locatorCopyStatus:tt}),tt==="failed"?"warning":"success")},[e,p,be,Ne,S,B.hasLiveSnapshot,B.liveMessages,L.providerType,(Z=L.targetEntry)==null?void 0:Z.controlValues,(se=L.targetEntry)==null?void 0:se.providerControls,ce,P,V,D,y,b,$,x,J,F.length,H]);l.useEffect(()=>dd(K),[]);const Y=l.useCallback(()=>{K(Me=>{const De=!Me;return Xp(De),De})},[]),me=l.useCallback(()=>{const Me=BN(v.current);v.current=Me.state,Me.shouldCollect&&Ee().catch(De=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",De),ct.showErrorToast(k("chatPane.debugBundleFailed"),De)})},[Ee,k]),fe=l.useMemo(()=>{if(U.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[n.jsx("div",{className:"connecting-logo-float",children:n.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),n.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[n.jsxs("div",{className:"text-xxs text-blue-400 font-medium",children:[k("chatPane.connectingToMachine"),n.jsx("span",{className:"connecting-dots"})]}),n.jsx("div",{className:"text-2xs opacity-35",children:k("chatPane.establishingP2P")})]})]});if(O.isGenerating&&z(!1),e.status==="not_monitored"&&de)return n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[n.jsx("div",{className:"text-3xl opacity-60",children:n.jsx(Tr,{size:28})}),n.jsx("div",{className:"text-xxs opacity-50",children:k("chatPane.agentNotMonitored")}),n.jsx("button",{onClick:m,disabled:h,className:"btn btn-primary",children:h?n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(Ir,{size:12}),k("chatPane.switchingPanel")]}):n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Zs,{size:14})," ",k("chatPane.openPanel",{label:we})]})}),n.jsx("div",{className:"text-2xs opacity-35 max-w-[280px]",children:k("chatPane.clickToSwitchMonitoring")})]});if(e.status==="panel_hidden"&&de)return n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[n.jsx("div",{className:"text-3xl opacity-60",children:n.jsx(sd,{size:28})}),n.jsx("div",{className:"text-xxs opacity-50",children:k("chatPane.agentPanelHidden")}),n.jsx("button",{onClick:m,disabled:h,className:"btn btn-primary",children:h?n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(Ir,{size:12}),k("chatPane.openingPanel")]}):n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Zs,{size:14})," ",k("chatPane.openPanel",{label:we})]})}),n.jsx("div",{className:"text-2xs opacity-35 max-w-[280px]",children:k("chatPane.openPanelHint")})]});if(e.status==="idle"&&!G)return!P&&D.length===0?n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[n.jsx("div",{className:"opacity-40",children:n.jsx(Jn,{size:26})}),n.jsx("div",{className:"text-xxs opacity-40",children:k("chatPane.noMessagesYet")})]}):n.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[n.jsx("div",{className:"opacity-40 animate-pulse",children:n.jsx(Jn,{size:26})}),n.jsx("div",{className:"text-xxs opacity-40",children:k("chatPane.loadingChat")})]})}},[e.connectionState,e.status,de,m,P,D.length,h,G,U.length,we,O.isGenerating]);return n.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",...iC(B),children:[n.jsxs("div",{className:"chat-activity-toggle-bar",children:[n.jsxs("button",{type:"button",className:`chat-activity-toggle ${J?"chat-activity-toggle-active":""}`,onClick:Y,"aria-pressed":J,title:k("chatPane.activityToggleTitle"),children:[n.jsx("span",{className:"chat-activity-toggle-dot"}),k("chatPane.activityToggleLabel"),be>0&&n.jsx("span",{className:"chat-activity-toggle-count",children:be})]}),n.jsx("div",{className:"ml-auto flex items-center gap-1",children:n.jsx(Qj,{machineId:_,blocked:!!(A!=null&&A.blocked),retryConnection:w.retryConnection})})]}),T&&n.jsxs("div",{className:"flex items-center gap-1 px-3 py-1 text-2xs text-amber-400/90 bg-amber-500/10 border-b border-amber-500/20",role:"status","data-testid":"transcript-replica-degraded-notice",children:[n.jsx("span",{className:"font-semibold",children:k("chatPane.replicaDegradedShort")}),n.jsx(dt,{content:k("chatPane.replicaDegraded"),size:12}),u_(B.transcriptFallbackReason,d_())]}),n.jsx(t0,{messages:Ne,actionLogs:Le,agentName:Mr(e)||we||"Agent",userName:g,isCliMode:L.isCli||L.isAcp,isWorking:O.isGenerating,contextKey:e.tabKey,receivedAtMap:Be,lastMessageHash:e.lastMessageHash,showActivityMessages:J,onLoadMore:ie,isLoadingMore:G,hasMoreHistory:P,hiddenLiveCount:V,loadError:$??void 0,emptyState:fe,scrollToBottomRequestNonce:f,isVisible:b,onSendNow:r,isSendingNow:a,onCancelQueued:o,toolExpansions:Je,onExpandToolBlock:he,onCollapseToolBlock:pe}),n.jsx(Gj,{entries:d??(c?[c]:[]),onSendNow:r,onCancelQueued:o,isSendingNow:a}),n.jsx(Hj,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:L.providerType,displayLabel:L.displayLabel,controls:(ye=L.targetEntry)==null?void 0:ye.providerControls,controlValues:(Fe=L.targetEntry)==null?void 0:Fe.controlValues,currentStatus:e.status,coordinatorHint:Ai(e),isActive:y,isCliTerminal:L.isCliTerminal,launchSurface:R}),!L.isCliTerminal&&n.jsx(Ef,{contextKey:e.tabKey,panelLabel:we,isSending:a,isBusy:X,statusMessage:je,inlineStatusMessage:ue,onSend:s,isActive:y,showControlsToggle:F.length>0,onControlsToggle:me,messageInput:e.messageInput})]})}const m_=.5,h_=1.25,Mn="\x1B",wm={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function p_(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function Sm(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 f_(e,t){if(t in wm){const r=wm[t],o=p_(e);return o===1?`${Mn}[${r}`:`${Mn}[1;${o}${r}`}switch(t){case"Enter":return e.alt?`${Mn}\r`:"\r";case"Escape":return e.alt?`${Mn}${Mn}`:Mn;case"Backspace":{const r=e.ctrl?"\b":"";return e.alt?`${Mn}${r}`:r}case"Tab":{const r=e.shift?`${Mn}[Z`:" ";return e.alt&&!e.shift?`${Mn} `:r}case"Space":{const r=Sm(" ",e);return e.alt?`${Mn}${r}`:r}}const s=Sm(t,e);return e.alt?`${Mn}${s}`:s}function Ot(e){return vd(e)}function Oo(e){return Vf(e).join(" · ")}function wg(e){var t,s;return!!e.daemonId&&!!((t=e.coordinator)!=null&&t.meshId||typeof((s=e.settings)==null?void 0:s.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0)}function g_(e){var o,a,i;const t=[],s=typeof((o=e.settings)==null?void 0:o.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0,r=!!((a=e.coordinator)!=null&&a.meshId)||typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0;return s&&t.push("Mesh node"),r&&t.push("Coordinator"),t}function b_(e){var i,c,d;const t=[],s=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",r=typeof((c=e.coordinator)==null?void 0:c.meshId)=="string"?e.coordinator.meshId.trim():"",o=typeof((d=e.settings)==null?void 0:d.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",a=r||o;if(s&&t.push(`Mesh node: ${s}`),a&&t.push(`Coordinator: ${a}`),e.meshQueueStats){const{pending:u,assigned:m,completed:h,failed:p}=e.meshQueueStats;t.push(`Queue: ${u} pending, ${m} assigned, ${h} completed, ${p} failed`)}return t.join(" · ")}function Sg(e,t){const s=Gf(e,t);return s||(e.title?e.title:Oo(e)||"No messages yet")}function kg(e,t){const{isReconnecting:s,isConnecting:r,isErrored:o}=or(e);return s?"Reconnecting…":r?"Connecting…":t!=null&&t.requiresAction?"Action needed":o?"Needs attention":null}function x_(e,t){const s=["Chat",...Vf(e)];return t!=null&&t.timestampLabel&&s.push(t.timestampLabel),s.filter(Boolean).join(" · ")}function Gs(e){return kg(e)||Oo(e)}function y_(e,t){return`${Ot(e)} · ${Sg(e,t)}`}function v_(e){const t=Ka(e),s=t?Kt(t):Mr(e);return`${Ot(e)} — ${s||"Agent"}`}function w_(e){return Mr(e)||"CLI"}function jg(e){return zf(e)}function Ng(e){return e?`Remote · ${Ot(e)||e.workspaceName||"Session"}`:"Remote"}const km=[{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:""}})}],S_=[{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 k_(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 Nd({cond:e,path:t,sections:s,onChange:r,onRemove:o,onPreview:a,preview:i}){const c=k_(e),d=i[t],u=m=>{const h=km.find(p=>p.kind===m);h&&r(h.make(s))};return n.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-1.5 space-y-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("select",{value:c,onChange:m=>u(m.target.value),className:"bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1 py-0.5",children:km.map(m=>n.jsx("option",{value:m.kind,children:m.label},m.kind))}),(c==="regex"||c==="stable"||c==="changed"||c==="elapsed")&&n.jsx("button",{type:"button",className:"text-3xs text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>a(t,e),children:"test"}),d&&d!=="loading"&&n.jsx("span",{className:`text-3xs font-mono px-1.5 py-0.5 rounded ${d.result?"text-status-online bg-status-online/20":"text-text-secondary bg-bg-glass"}`,children:d.result?"match ✓":"no match"}),d==="loading"&&n.jsx("span",{className:"text-3xs text-text-muted",children:"testing…"}),o&&n.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-xs px-1",onClick:o,children:"×"})]}),c==="regex"&&n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsxs("select",{value:e.section??"",onChange:m=>r({...e,section:m.target.value||void 0}),className:"bg-bg-secondary text-accent-primary text-3xs font-mono rounded border border-border-default px-1 py-0.5",children:[n.jsx("option",{value:"",children:"(whole screen)"}),s.map(m=>n.jsx("option",{value:m,children:m},m))]}),n.jsx("input",{value:e.matches??"",onChange:m=>r({...e,matches:m.target.value}),placeholder:"regex",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),c==="elapsed"&&n.jsx(ws,{label:"elapsed_ms",value:e.elapsed_ms,onChange:m=>r({elapsed_ms:m})}),c==="stable"&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ws,{label:"stable_ms",value:e.stable_ms,onChange:m=>r({...e,stable_ms:m})}),n.jsx(ws,{label:"cursor_above",value:e.cursor_above??0,onChange:m=>r({...e,cursor_above:m||void 0})})]}),c==="changed"&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ws,{label:"cursor_above",value:e.cursor_above,onChange:m=>r({...e,cursor_above:m})}),n.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:[n.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:m=>r({...e,changed:m.target.checked}),className:"accent-[var(--accent-primary)]"}),"changed"]})]}),(c==="all"||c==="any")&&n.jsx(j_,{kind:c,cond:e,path:t,sections:s,onChange:r,onPreview:a,preview:i}),c==="not"&&n.jsx("div",{className:"pl-2 border-l border-border-default",children:n.jsx(Nd,{cond:e.not,path:`${t}.not`,sections:s,onChange:m=>r({not:m}),onPreview:a,preview:i})})]})}function j_({kind:e,cond:t,path:s,sections:r,onChange:o,onPreview:a,preview:i}){const c=(e==="all"?t.all:t.any)??[],d=u=>o(e==="all"?{all:u}:{any:u});return n.jsxs("div",{className:"pl-2 border-l border-border-default space-y-1",children:[c.map((u,m)=>n.jsx(Nd,{cond:u,path:`${s}.${e}[${m}]`,sections:r,onChange:h=>d(c.map((p,g)=>g===m?h:p)),onRemove:()=>d(c.filter((h,p)=>p!==m)),onPreview:a,preview:i},m)),n.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d([...c,{section:r[0],matches:""}]),children:"+ condition"}),S_.map(u=>n.jsxs("button",{type:"button",className:"text-3xs text-accent-primary/80 hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>d([...c,JSON.parse(JSON.stringify(u.cond))]),title:"insert verified pattern",children:["+ ",u.label]},u.label))]})]})}function ws({label:e,value:t,onChange:s}){return n.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary font-mono",children:[e,n.jsx("input",{type:"number",value:Number.isFinite(t)?t:0,onChange:r=>s(Number(r.target.value)),className:"w-20 bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5 outline-none focus:border-accent"})]})}function N_({sections:e,otherSectionIds:t,onChange:s,onTest:r,testResult:o}){const a=Object.keys(e),i=o&&o!=="loading"&&!("error"in o)?Object.fromEntries(o.sections.map(h=>[h.id,h])):{},c=(h,p)=>{if(!p||p===h||e[p])return;const g={};for(const[f,y]of Object.entries(e))g[f===h?p:f]=y;s(g)},d=(h,p)=>s({...e,[h]:p}),u=h=>{const p={...e};delete p[h],s(p)},m=()=>{let h="section",p=1;for(;e[h];)h=`section${p++}`;s({...e,[h]:{from_top:0}})};return n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"Sections"}),n.jsx("span",{className:"text-text-muted text-3xs",children:"— how the screen is split; conditions match against these"}),n.jsx("button",{type:"button",className:"ml-auto text-3xs text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:r,title:"Resolve all sections against the live session screen",children:o==="loading"?"testing…":"test on live screen"}),n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:m,children:"+ section"})]}),o&&o!=="loading"&&"error"in o&&n.jsx("div",{className:"text-status-error bg-status-error/15 border border-status-error/40 rounded p-1.5 text-3xs mb-1",children:o.error}),n.jsx("div",{className:"space-y-1.5",children:a.map(h=>{var y;const p=e[h],g=p.anchor!=null?"anchor":"positional",f=b=>{b==="anchor"?d(h,{anchor:p.anchor??"^",anchor_last:p.anchor_last,until:p.until}):d(h,{from_top:p.from_top??0,until:p.until})};return n.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{value:h,onChange:b=>c(h,b.target.value.trim()),className:"w-28 bg-bg-secondary text-accent-primary font-mono text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),n.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-3xs",children:[n.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="positional"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>f("positional"),children:"positional"}),n.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="anchor"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>f("anchor"),children:"anchor"})]}),n.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-sm px-1",onClick:()=>u(h),children:"×"})]}),g==="positional"?n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx(ws,{label:"from_top",value:typeof p.from_top=="number"?p.from_top:0,onChange:b=>d(h,{...p,from_top:b,from_bottom:void 0})}),n.jsx(ws,{label:"from_bottom",value:typeof p.from_bottom=="number"?p.from_bottom:0,onChange:b=>d(h,{...p,from_bottom:b||void 0})}),n.jsx(jm,{def:p,otherIds:t(h),onChange:b=>d(h,b)})]}):n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"text-3xs text-text-muted w-16",children:"anchor"}),n.jsx("input",{value:p.anchor??"",onChange:b=>d(h,{...p,anchor:b.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),n.jsxs("label",{className:"flex items-center gap-1 text-3xs text-text-secondary",children:[n.jsx("input",{type:"checkbox",checked:!!p.anchor_last,onChange:b=>d(h,{...p,anchor_last:b.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"last"]})]}),n.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:n.jsx(jm,{def:p,otherIds:t(h),onChange:b=>d(h,b)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"text-3xs text-text-muted w-16",children:"ctx next"}),n.jsx("input",{value:((y=p.anchor_context)==null?void 0:y.next)??"",onChange:b=>d(h,{...p,anchor_context:{...p.anchor_context,next:b.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-secondary text-3xs font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})]}),i[h]&&n.jsxs("div",{className:"border-t border-border-subtle pt-1",children:[n.jsxs("div",{className:"text-4xs text-text-muted mb-0.5",children:["captured lines ",i[h].fromLine,"–",i[h].toLine,i[h].text.trim()===""&&n.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),n.jsx("pre",{className:"font-mono text-3xs text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary rounded border border-border-subtle px-2 py-1 max-h-28 overflow-y-auto",children:i[h].text||"(empty)"})]})]},h)})})]})}function jm({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 C_({model:e,onChange:t,onPreview:s,preview:r,onTestSections:o,sectionPreview:a}){const i=e.states.map(h=>h.id),c=Object.keys(e.sections??{}),d=l.useCallback(h=>t({...e,...h}),[e,t]),u=(h,p)=>d({states:e.states.map((g,f)=>f===h?{...g,...p}:g)}),m=(h,p)=>d({transitions:e.transitions.map((g,f)=>f===h?{...g,...p}:g)});return n.jsxs("div",{className:"space-y-3",children:[n.jsx(N_,{sections:e.sections??{},otherSectionIds:h=>c.filter(p=>p!==h),onChange:h=>d({sections:h}),onTest:()=>o(e.sections??{}),testResult:a}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"States"}),n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),n.jsx("div",{className:"space-y-1.5",children:e.states.map((h,p)=>n.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1",children:[n.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[n.jsxs("label",{className:"flex flex-col gap-0.5",children:[n.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide",children:"id (used by transitions)"}),n.jsx("input",{value:h.id,onChange:g=>u(p,{id:g.target.value}),placeholder:"idle",className:"w-32 bg-bg-secondary text-accent-primary font-mono text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),n.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[n.jsx("span",{className:"text-4xs text-text-muted uppercase tracking-wide",children:"label (shown in dashboard)"}),n.jsx("input",{value:h.label,onChange:g=>u(p,{label:g.target.value}),placeholder:"Ready",className:"w-full bg-bg-secondary text-text-primary text-2xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),n.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1 pb-0.5",onClick:()=>d({states:e.states.filter((g,f)=>f!==p)}),children:"×"})]}),n.jsxs("div",{className:"flex items-center gap-3 text-3xs text-text-secondary flex-wrap",children:[n.jsxs("label",{className:"flex items-center gap-1",children:[n.jsx("input",{type:"radio",name:"initial",checked:!!h.initial,onChange:()=>d({states:e.states.map((g,f)=>({...g,initial:f===p}))}),className:"accent-[var(--accent-primary)]"}),"initial"]}),n.jsxs("label",{className:"flex items-center gap-1",children:[n.jsx("input",{type:"checkbox",checked:!!h.modal,onChange:g=>u(p,{modal:g.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"modal"]}),n.jsxs("label",{className:"flex items-center gap-1",children:["status",n.jsxs("select",{value:h.status??"",onChange:g=>u(p,{status:g.target.value||void 0}),className:"bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5",children:[n.jsx("option",{value:"",children:"(auto)"}),n.jsx("option",{value:"idle",children:"idle"}),n.jsx("option",{value:"generating",children:"generating"}),n.jsx("option",{value:"approval",children:"approval"})]})]})]})]},p))})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold",children:"Transitions"}),n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d({transitions:[...e.transitions,{from:i[0]??"",to:i[0]??""}]}),children:"+ transition"})]}),n.jsx("div",{className:"space-y-1.5",children:e.transitions.map((h,p)=>n.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:"text-3xs text-text-muted",children:"from"}),n.jsx(__,{value:h.from,states:i,onChange:g=>m(p,{from:g})}),n.jsx("span",{className:"text-3xs text-text-muted",children:"→"}),n.jsx("select",{value:h.to,onChange:g=>m(p,{to:g.target.value}),className:"bg-bg-secondary text-status-online font-mono text-3xs rounded border border-border-default px-1 py-0.5",children:i.map(g=>n.jsx("option",{value:g,children:g},g))}),n.jsx("span",{className:"text-3xs text-text-muted ml-1",children:"label"}),n.jsx("input",{value:h.label??"",onChange:g=>m(p,{label:g.target.value||void 0}),placeholder:"debug name only (optional)",title:"Display name shown in the debug history/transition table. Does not affect behaviour.",className:"flex-1 min-w-[120px] bg-bg-secondary text-text-secondary text-3xs rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),n.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1",onClick:()=>d({transitions:e.transitions.filter((g,f)=>f!==p)}),children:"×"})]}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(ws,{label:"min_hold_ms",value:h.min_hold_ms??0,onChange:g=>m(p,{min_hold_ms:g||void 0})}),n.jsx(ws,{label:"priority",value:h.priority??0,onChange:g=>m(p,{priority:g||void 0})})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-3xs text-text-muted",children:"when"}),!h.when&&n.jsx("button",{type:"button",className:"text-3xs text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>m(p,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),h.when&&n.jsx("button",{type:"button",className:"text-3xs text-text-muted hover:text-status-error",onClick:()=>m(p,{when:void 0}),children:"remove guard"})]}),h.when&&n.jsx(Nd,{cond:h.when,path:`t${p}`,sections:c,onChange:g=>m(p,{when:g}),onPreview:s,preview:r})]})]},p))})]})]})}function __({value:e,states:t,onChange:s}){const r=new Set(Array.isArray(e)?e:e==="*"?t:[e]),o=e==="*",a=i=>{const c=new Set(r);c.has(i)?c.delete(i):c.add(i);const d=t.filter(u=>c.has(u));s(d.length===1?d[0]:d)};return n.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>n.jsx("button",{type:"button",onClick:()=>a(i),className:`font-mono text-3xs px-1 py-0.5 rounded border ${o||r.has(i)?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-muted border-border-default hover:border-border-default"}`,children:i},i))})}function Cn(e){return e&&typeof e=="object"?e:{}}function At(e){return typeof e=="string"?e:""}function A_(e){const t=Cn(e);return!!(typeof t.spec_id=="string"&&t.spec_id.length>0||"current_state"in t||Array.isArray(t.stateHistory))}function T_(e){const t=Cn(e.parser),s=Cn(t.parsedStatusCache),r=Cn(e.activeModal).buttons!=null?Cn(e.activeModal):Cn(s.activeModal),o=Array.isArray(r.buttons)?r.buttons:null;if(!o||o.length===0){const a=At(r.message)||At(r.title);return a?{title:a,buttons:[]}:null}return{title:At(r.message)||At(r.title)||null,buttons:o.map((a,i)=>({index:i,label:typeof a=="string"?a:String(a)}))}}function I_(e){const t=Array.isArray(e.messages)?e.messages:null;return t?t.map(s=>Cn(s)).filter(s=>typeof s.role=="string").map(s=>({role:At(s.role),content:At(s.content),receivedAt:typeof s.receivedAt=="number"?s.receivedAt:void 0})):[]}function Nm(e){if(e==null||typeof e!="object")return null;const t=e;if(A_(e))return{cliType:At(t.cliType),spec_id:At(t.spec_id),specPath:typeof t.specPath=="string"?t.specPath:void 0,current_state:t.current_state??null,current_modal:t.current_modal??null,activeInteractivePrompt:t.activeInteractivePrompt,exited:t.exited===!0,screen:At(t.screen),sections:t.sections??void 0,stateHistory:Array.isArray(t.stateHistory)?t.stateHistory:[],statusHistory:[],idleHoldPending:t.idleHoldPending===!0,lastBusyAt:typeof t.lastBusyAt=="number"?t.lastBusyAt:0,cursorPosition:t.cursorPosition??null,completionIdleDebounce:t.completionIdleDebounce??null,fsm:t.fsm??null,name:typeof t.name=="string"?t.name:void 0,status:typeof t.status=="string"?t.status:void 0,workingDir:typeof t.workingDir=="string"?t.workingDir:void 0,spawnedAtMs:typeof t.spawnedAtMs=="number"?t.spawnedAtMs:void 0,providerSessionId:t.providerSessionId??null,messages:t.messages??void 0,committedMessages:t.committedMessages??void 0,nativeSource:!1,transcriptAuthority:void 0};const s=Cn(t.terminal),r=Cn(t.parser),o=Cn(r.parsedStatusCache),a=Cn(t.runtimeMetadata),i=At(s.screenText)||At(s.lastScreenText)||At(t.screenText),c=At(o.status)||At(t.currentStatus)||At(t.status),d=At(o.providerSessionId)||At(a.providerSessionId)||null,u=At(o.transcriptAuthority)||At(t.transcriptAuthority)||void 0,m=(Array.isArray(t.statusHistory)?t.statusHistory:[]).map(h=>Cn(h)).filter(h=>typeof h.status=="string"&&typeof h.at=="number").map(h=>({status:h.status,at:h.at,trigger:typeof h.trigger=="string"?h.trigger:null}));return{cliType:At(t.cliType)||At(t.type),spec_id:At(t.cliType)||At(t.type)||"native-source",specPath:typeof t.specPath=="string"?t.specPath:void 0,current_state:c?{id:c,label:c,title:null}:null,current_modal:T_(t),activeInteractivePrompt:t.activeInteractivePrompt??null,exited:t.exited===!0,screen:i,sections:void 0,stateHistory:[],statusHistory:m,idleHoldPending:!1,lastBusyAt:typeof t.lastBusyAt=="number"?t.lastBusyAt:0,cursorPosition:null,completionIdleDebounce:null,fsm:null,name:At(t.cliName)||At(t.name)||void 0,status:c||void 0,workingDir:typeof t.workingDir=="string"?t.workingDir:void 0,spawnedAtMs:typeof a.spawnedAtMs=="number"?a.spawnedAtMs:typeof t.spawnAt=="number"?t.spawnAt:void 0,providerSessionId:d,messages:I_(t),committedMessages:void 0,nativeSource:!0,transcriptAuthority:u}}function ur(e){const t=Date.now()-e;return t<0?Ba(e):t<2e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:Ba(e)}function Cm(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const M_={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"},R_={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 oa(e){return R_[e]??"text-text-primary bg-bg-glass border border-border-default"}function mr({children:e}){return n.jsx("div",{className:"text-text-secondary text-3xs uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function aa(){return n.jsx("div",{className:"border-t border-white/8 my-2"})}function Cg({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(Cg,{node:a,depth:t+1},i))]})}function P_({t:e}){const[t,s]=l.useState(!1),r=e.fires?"text-status-online bg-status-online/20 border-status-online/40":e.holdSatisfied?"text-text-secondary bg-bg-glass border-border-default":"text-status-warning bg-status-warning/20 border-status-warning/40";return n.jsxs("div",{className:"border border-border-default rounded bg-surface-secondary overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-bg-glass-hover text-left",onClick:()=>s(o=>!o),children:[n.jsx("span",{className:"text-3xs text-text-muted w-3",children:e.cond?t?"▾":"▸":" "}),n.jsxs("span",{className:`font-mono text-2xs px-1.5 py-0.5 rounded border ${r}`,children:["→ ",e.to]}),n.jsx("span",{className:"text-text-secondary font-mono text-3xs truncate",children:e.label}),n.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.fires&&n.jsx("span",{className:"text-status-online text-3xs font-mono",children:"FIRES"}),!e.holdSatisfied&&n.jsxs("span",{className:"text-status-warning text-3xs font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),n.jsx("span",{className:`text-3xs font-mono ${e.condResult?"text-status-online":"text-text-muted"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&n.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-bg-secondary border-t border-border-default",children:n.jsx(Cg,{node:e.cond})})]})}function L_({activeConv:e,onClose:t}){var de,ne,ee,ue,je;const{sendCommand:s}=_t(),[r,o]=l.useState(!0),[a,i]=l.useState(null),[c,d]=l.useState(null),[u,m]=l.useState(!1),[h,p]=l.useState(new Set(["footer"])),[g,f]=l.useState("Snapshot"),[y,b]=l.useState(!1),[k,j]=l.useState(null),[v,C]=l.useState(!1),[x,S]=l.useState(""),[w,_]=l.useState(!1),[A,O]=l.useState("idle"),[L,R]=l.useState(null),[F,N]=l.useState([]),[I,B]=l.useState({}),[T,H]=l.useState(null),[q,J]=l.useState(!1),K=e.daemonId||((de=e.routeId)==null?void 0:de.split(":")[0])||e.routeId||"",M=e.sessionId||"",D=l.useCallback(async()=>{o(!0),d(null);try{const X=await s(K,"get_spec_debug",{targetSessionId:M}),G=X&&typeof X=="object"?X:{},z=G.result&&typeof G.result=="object"?G.result:G;z!=null&&z.success?i(z):(d((z==null?void 0:z.error)||"Failed to load spec debug"),i(null))}catch(X){d((X==null?void 0:X.message)||String(X)),i(null)}finally{o(!1)}},[s,K,M]);l.useEffect(()=>{D()},[D]),l.useEffect(()=>{if(!q)return;const X=setInterval(()=>{D()},1e3);return()=>clearInterval(X)},[q,D]),l.useEffect(()=>{const X=G=>{G.key==="Escape"&&!y&&t()};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[t,y]);const P=l.useCallback(async X=>{try{const G=await s(K,"validate_spec",{content:JSON.stringify(X)}),z=G&&typeof G=="object"?G:{},ie=z.result&&typeof z.result=="object"?z.result:z;N(ie!=null&&ie.valid?[]:(ie==null?void 0:ie.errors)??["validation failed"])}catch(G){N([(G==null?void 0:G.message)||String(G)])}},[s,K]),$=l.useCallback(async()=>{R(null),O("idle"),B({});try{const X=await s(K,"get_spec_source",{targetSessionId:M}),G=X&&typeof X=="object"?X:{},z=G.result&&typeof G.result=="object"?G.result:G;if(!(z!=null&&z.success)||typeof z.content!="string"){R((z==null?void 0:z.error)||"Failed to load spec source");return}S(z.content);let ie=null;try{ie=JSON.parse(z.content)}catch{}ie&&ie.$schema==="adhdev:cli/spec@4"?(j(ie),C(!1),P(ie)):(j(null),C(!0)),_(!1),b(!0)}catch(X){R((X==null?void 0:X.message)||String(X))}},[s,K,M,P]),W=l.useCallback(X=>{j(X),S(JSON.stringify(X,null,2)),_(!0),O("idle"),P(X)},[P]),U=l.useCallback(async(X,G)=>{B(z=>({...z,[X]:"loading"}));try{const z=await s(K,"eval_condition_preview",{targetSessionId:M,condition:G}),ie=z&&typeof z=="object"?z:{},Ne=ie.result&&typeof ie.result=="object"?ie.result:ie;!(Ne!=null&&Ne.success)||!Ne.result?B(Be=>({...Be,[X]:{result:!1,detail:Ne==null?void 0:Ne.error}})):B(Be=>({...Be,[X]:{result:Ne.result.result,detail:Ne.result.detail}}))}catch(z){B(ie=>({...ie,[X]:{result:!1,detail:z==null?void 0:z.message}}))}},[s,K,M]),ae=l.useCallback(async X=>{H("loading");try{const G=await s(K,"resolve_section_preview",{targetSessionId:M,sections:X}),z=G&&typeof G=="object"?G:{},ie=z.result&&typeof z.result=="object"?z.result:z;!(ie!=null&&ie.success)||!Array.isArray(ie.sections)?H({error:(ie==null?void 0:ie.error)||"resolve failed"}):H({sections:ie.sections,screenLineCount:ie.screenLineCount??0})}catch(G){H({error:(G==null?void 0:G.message)||String(G)})}},[s,K,M]),be=l.useCallback(async()=>{var z,ie;const X=(z=a==null?void 0:a.snapshot)==null?void 0:z.specPath;if(!X){R("No spec path on this session");return}if(!v&&F.length>0){R("Fix validation errors before saving");return}const G=!v&&k?JSON.stringify(k,null,2):x;O("saving"),R(null);try{const Ne=await s(K,"write_spec_source",{specPath:X,content:G}),Be=Ne&&typeof Ne=="object"?Ne:{},Le=Be.result&&typeof Be.result=="object"?Be.result:Be;if(!(Le!=null&&Le.success)){O("error"),R(((ie=Le==null?void 0:Le.validationErrors)==null?void 0:ie.join(`
|
|
42
|
-
`))||(Le==null?void 0:Le.error)||"Save failed");return}O("saved"),_(!1),setTimeout(()=>{D()},400),setTimeout(()=>O("idle"),1500)}catch(Ne){O("error"),R((Ne==null?void 0:Ne.message)||String(Ne))}},[s,K,(ne=a==null?void 0:a.snapshot)==null?void 0:ne.specPath,x,k,v,F,D]),V=Nm(a==null?void 0:a.snapshot),we=async()=>{var Je,Se,he;let X=a;X||(await D(),X=a);const G=Nm(X==null?void 0:X.snapshot),z=[],ie=(G==null?void 0:G.nativeSource)===!0;if(z.push("# Spec Debug Snapshot"),z.push(`Generated: ${new Date().toISOString()}`),z.push(`Session: ${(X==null?void 0:X.sessionId)??""} (${(X==null?void 0:X.providerType)??""})`),ie&&(z.push("Provider kind: native-source (no state-machine spec — State History / FSM / Sections are N/A)"),G!=null&&G.transcriptAuthority&&z.push(`transcriptAuthority: ${G.transcriptAuthority}`)),z.push(`Spec: ${(G==null?void 0:G.spec_id)??""} (${(G==null?void 0:G.specPath)??""})`),z.push(`Provider: ${(G==null?void 0:G.name)??""} (${(G==null?void 0:G.cliType)??""})`),z.push(`Working dir: ${(G==null?void 0:G.workingDir)??""}`),z.push(`Spawned: ${G!=null&&G.spawnedAtMs?new Date(G.spawnedAtMs).toISOString():""}`),z.push(""),z.push("## Current State"),z.push(`State: ${((Je=G==null?void 0:G.current_state)==null?void 0:Je.id)??"none"} (${((Se=G==null?void 0:G.current_state)==null?void 0:Se.label)??""})`),z.push(`Status: ${(G==null?void 0:G.status)??""}`),z.push(`Idle hold pending: ${(G==null?void 0:G.idleHoldPending)??!1}`),z.push(`Exited: ${(G==null?void 0:G.exited)??!1}`),z.push(`Last busy: ${G!=null&&G.lastBusyAt?ur(G.lastBusyAt):""}`),z.push(`Cursor: ${(G==null?void 0:G.cursorPosition)!=null?`(${G.cursorPosition.row},${G.cursorPosition.col})`:"n/a"}`),(he=G==null?void 0:G.completionIdleDebounce)!=null&&he.active){const pe=G.completionIdleDebounce;z.push(`completion_idle_after: age=${pe.ageMs}ms hold=${pe.holdMs}ms force=${pe.forceAfterMs}ms remaining=${Math.max(0,pe.holdMs-pe.ageMs)}ms`)}if(z.push(""),z.push("## Modal"),G!=null&&G.current_modal){const pe=G.current_modal.buttons.map(Ee=>Ee.label).join(" / ");z.push(`${G.current_modal.title??""} [${pe}]`)}else z.push("none");if(z.push(""),z.push("## State History (last 20)"),ie&&!(G!=null&&G.statusHistory&&G.statusHistory.length>0)&&z.push("N/A (native-source provider — no state-machine rules)"),ie&&(G!=null&&G.statusHistory)&&G.statusHistory.length>0){z.push("(legacy engine status transitions — native-source provider has no state-machine rules)");for(const pe of[...G.statusHistory].reverse().slice(0,20))z.push(`- ${pe.status} @ ${new Date(pe.at).toISOString()}${pe.trigger?` | trigger: ${pe.trigger}`:""}`)}const Ne=G!=null&&G.stateHistory?[...G.stateHistory].reverse().slice(0,20):[];for(const pe of Ne){const Ee=pe.reason!=null?typeof pe.reason=="string"?pe.reason:JSON.stringify(pe.reason):"",Y=pe.debounceKind!=null?typeof pe.debounceKind=="string"?pe.debounceKind:JSON.stringify(pe.debounceKind):"",me=pe.matchedStateId!=null?String(pe.matchedStateId):"",fe=(pe.matchedRules??[]).map(E=>typeof E=="string"?E:JSON.stringify(E)).join(", ");z.push(`- ${pe.stateId} @ ${new Date(pe.at).toISOString()} held ${pe.durationMs}ms | reason: ${Ee} | debounce: ${Y} | eval→${me} | rules: ${fe}`)}if(z.push(""),z.push("## Sections"),ie)z.push("N/A (native-source provider — no state-machine sections)");else if(G!=null&&G.sections)for(const[pe,Ee]of Object.entries(G.sections)){const Y=Ee.split(`
|
|
43
|
-
`).slice(0,3).join(`
|
|
44
|
-
`);z.push(`${pe}: ${Y}`)}z.push(""),z.push("## Last Assistant Message");const Le=[...(G==null?void 0:G.messages)??(G==null?void 0:G.committedMessages)??[]].reverse().find(pe=>pe.role==="assistant");z.push(Le?Le.content.slice(0,400):""),z.push(""),z.push("## Screen (first 50 lines)"),z.push(G!=null&&G.screen?G.screen.split(`
|
|
45
|
-
`).slice(0,50).join(`
|
|
46
|
-
`):"");try{await navigator.clipboard.writeText(z.join(`
|
|
47
|
-
`)),f("Copied!"),setTimeout(()=>f("Snapshot"),1500)}catch(pe){console.error("[SpecDebugPanel] clipboard write failed",pe)}},ce=X=>{p(G=>{const z=new Set(G);return z.has(X)?z.delete(X):z.add(X),z})};return n.jsx(es,{children:n.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Spec debug",className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center bg-black/60 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] px-0 sm:items-center sm:p-4",onClick:t,style:{pointerEvents:"auto"},children:n.jsxs("div",{className:"bg-bg-secondary text-text-primary border border-border-default rounded-t-xl sm:rounded-lg shadow-2xl max-w-2xl w-full max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[88vh] flex flex-col",onClick:X=>X.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-border-default px-4 py-2.5 shrink-0 gap-2 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 overflow-hidden",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary shrink-0",children:"Spec Debug"}),V&&n.jsx("span",{className:"text-2xs text-text-secondary font-mono bg-surface-secondary px-1.5 py-0.5 rounded truncate",children:V.spec_id})]}),n.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(V==null?void 0:V.specPath)&&n.jsx("button",{type:"button",className:`text-2xs transition-colors px-2 py-1 rounded border ${y?"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:()=>{y?b(!1):$()},disabled:r,children:y?"Close Editor":"Edit Spec"}),n.jsx("button",{type:"button",className:"text-2xs text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{we()},disabled:r,children:g}),n.jsx("button",{type:"button",className:"text-2xs text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{D()},disabled:r,children:r?"Loading…":"Refresh"}),n.jsx("button",{type:"button",className:"text-text-secondary hover:text-text-primary transition-colors text-xl leading-none w-7 h-7 flex items-center justify-center rounded hover:bg-bg-glass-hover",onClick:t,"aria-label":"Close",children:"×"})]})]}),y&&n.jsxs("div",{className:"flex-1 flex flex-col min-h-0 px-4 py-3 gap-2",children:[n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[n.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-3xs",children:[n.jsx("button",{type:"button",className:`px-2 py-0.5 ${v?"text-text-secondary hover:bg-bg-glass-hover":"bg-accent-primary/20 text-accent-primary"}`,onClick:()=>{if(v)try{const X=JSON.parse(x);j(X),P(X)}catch{return}C(!1)},disabled:!k&&v,children:"Form"}),n.jsx("button",{type:"button",className:`px-2 py-0.5 ${v?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>{k&&S(JSON.stringify(k,null,2)),C(!0)},children:"JSON"})]}),n.jsx("span",{className:"text-3xs text-text-muted font-mono truncate flex-1",title:V==null?void 0:V.specPath,children:((V==null?void 0:V.specPath)??"").split("/").slice(-3).join("/")}),w&&n.jsx("span",{className:"text-status-warning text-3xs",children:"unsaved"}),!v&&F.length>0&&n.jsxs("span",{className:"text-status-error text-3xs",children:[F.length," error",F.length>1?"s":""]}),n.jsx("button",{type:"button",className:`text-2xs px-2.5 py-1 rounded border transition-colors ${A==="saving"||!v&&F.length>0?"text-text-muted border-border-default cursor-not-allowed":"text-status-online bg-status-online/20 border-status-online/40 hover:bg-status-online/20"}`,onClick:()=>{be()},disabled:A==="saving"||!v&&F.length>0,children:A==="saving"?"Saving…":A==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),L&&n.jsx("pre",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2 text-3xs whitespace-pre-wrap shrink-0 max-h-28 overflow-y-auto",children:L}),!v&&F.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:F.map((X,G)=>n.jsx("div",{className:"font-mono",children:X},G))}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:v||!k?n.jsx("textarea",{value:x,onChange:X=>{S(X.target.value),_(!0),O("idle")},spellCheck:!1,className:"w-full h-full min-h-[300px] font-mono text-2xs leading-relaxed bg-bg-secondary text-text-primary border border-border-default rounded p-3 resize-none outline-none focus:border-accent"}):n.jsx(C_,{model:k,onChange:W,onPreview:U,preview:I,onTestSections:ae,sectionPreview:T})}),n.jsx("div",{className:"text-3xs text-text-muted shrink-0",children:v?"Raw JSON — validated on save.":'Build the FSM; from/to are constrained to existing states. "test" evaluates a condition against the live screen. Save hot-reloads the session.'})]}),!y&&n.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))] space-y-3 text-xs",children:[c&&n.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2",children:c}),r&&!a&&n.jsx("div",{className:"text-text-muted text-center py-6",children:"Loading…"}),a&&!a.isSpecProvider&&n.jsxs("div",{className:"text-text-muted text-center py-6",children:["Not a spec-driven provider (",a.providerType||"unknown",")."]}),V&&n.jsxs(n.Fragment,{children:[V.nativeSource&&n.jsxs("div",{className:"text-2xs text-text-secondary bg-surface-secondary border border-border-default rounded-md px-3 py-2",children:[n.jsx("span",{className:"text-accent-primary font-semibold",children:"Native-source provider"}),n.jsx("span",{className:"text-text-muted",children:" — no state-machine spec."}),n.jsx("span",{className:"text-text-muted",children:" State History, FSM transitions, and Sections are "}),n.jsx("span",{className:"text-text-secondary font-mono",children:"N/A"}),n.jsx("span",{className:"text-text-muted",children:". Status, screen, modal, and transcript below are live."}),V.transcriptAuthority&&n.jsxs("span",{className:"text-text-muted font-mono",children:[" (transcriptAuthority: ",V.transcriptAuthority,")"]})]}),n.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-2xs bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[V.name&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-text-muted",children:"Provider"}),n.jsxs("span",{className:"font-mono text-text-primary",children:[V.name," ",n.jsxs("span",{className:"text-text-muted",children:["(",V.cliType,")"]})]})]}),V.workingDir&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-text-muted",children:"Dir"}),n.jsx("span",{className:"font-mono text-text-secondary truncate min-w-0",title:V.workingDir,children:V.workingDir})]}),V.spawnedAtMs?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-text-muted",children:"Spawned"}),n.jsx("span",{className:"text-text-secondary",children:ur(V.spawnedAtMs)})]}):null,V.providerSessionId&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-text-muted",children:"Session"}),n.jsx("span",{className:"font-mono text-text-muted text-3xs truncate min-w-0",title:V.providerSessionId,children:V.providerSessionId})]})]}),n.jsxs("div",{className:"flex items-center gap-2 flex-wrap bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[n.jsx("span",{className:`font-semibold font-mono text-xs px-2 py-0.5 rounded ${V.current_state?oa(V.current_state.id):"text-text-muted"}`,children:V.current_state?V.current_state.id:"none"}),((ee=V.current_state)==null?void 0:ee.label)&&V.current_state.label!==V.current_state.id&&n.jsx("span",{className:"text-text-secondary text-2xs",children:V.current_state.label}),V.status&&V.status!==((ue=V.current_state)==null?void 0:ue.id)&&n.jsxs("span",{className:"text-text-muted text-2xs",children:["engine: ",n.jsx("span",{className:`font-mono ${oa(V.status)} px-1 py-0.5 rounded text-3xs`,children:V.status})]}),V.idleHoldPending&&n.jsx("span",{className:"text-yellow-200 text-3xs bg-yellow-600/25 border border-yellow-500/35 px-1.5 py-0.5 rounded font-mono",children:"idle hold pending"}),V.exited&&n.jsx("span",{className:"text-status-error text-3xs bg-status-error/20 border border-status-error/40 px-1.5 py-0.5 rounded font-mono",children:"exited"}),V.cursorPosition!=null&&n.jsxs("span",{className:"text-text-muted text-2xs font-mono",children:["cursor: ",n.jsxs("span",{className:"text-text-secondary",children:[V.cursorPosition.row,",",V.cursorPosition.col]})]}),V.lastBusyAt>0&&n.jsxs("span",{className:"text-text-muted text-2xs ml-auto",children:["last busy: ",n.jsx("span",{className:"text-text-secondary",children:ur(V.lastBusyAt)})]})]}),((je=V.completionIdleDebounce)==null?void 0:je.active)&&n.jsxs("div",{className:"flex items-center gap-2 text-2xs bg-accent-primary/20 border border-accent rounded-md px-3 py-1.5 font-mono",children:[n.jsx("span",{className:"text-accent-primary",children:"completion_idle_after"}),n.jsxs("span",{className:"text-text-secondary",children:["age: ",n.jsxs("span",{className:"text-accent-primary",children:[V.completionIdleDebounce.ageMs,"ms"]})]}),n.jsx("span",{className:"text-text-muted",children:"/"}),n.jsxs("span",{className:"text-text-secondary",children:["hold: ",n.jsxs("span",{className:"text-text-secondary",children:[V.completionIdleDebounce.holdMs,"ms"]})]}),n.jsxs("span",{className:"text-text-secondary",children:["force: ",n.jsxs("span",{className:"text-text-secondary",children:[V.completionIdleDebounce.forceAfterMs,"ms"]})]}),n.jsx("span",{className:"text-text-muted ml-auto",children:V.completionIdleDebounce.ageMs<V.completionIdleDebounce.holdMs?n.jsxs("span",{className:"text-status-warning",children:["hold remaining: ",V.completionIdleDebounce.holdMs-V.completionIdleDebounce.ageMs,"ms"]}):V.completionIdleDebounce.ageMs<V.completionIdleDebounce.forceAfterMs?n.jsxs("span",{className:"text-orange-300",children:["force in: ",V.completionIdleDebounce.forceAfterMs-V.completionIdleDebounce.ageMs,"ms"]}):n.jsx("span",{className:"text-status-error",children:"overdue"})})]}),V.current_modal&&n.jsxs("div",{className:"bg-orange-900/30 border border-orange-600/40 rounded-md p-2.5",children:[n.jsx("span",{className:"text-orange-200 font-semibold",children:"Modal: "}),n.jsx("span",{className:"text-text-secondary",children:V.current_modal.title||""}),V.current_modal.buttons.length>0&&n.jsxs("span",{className:"text-text-secondary ml-2",children:["[",V.current_modal.buttons.map(X=>X.label).join(" / "),"]"]})]}),V.fsm&&n.jsxs(n.Fragment,{children:[n.jsx(aa,{}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsxs(mr,{children:["FSM — outgoing from ",n.jsx("span",{className:"text-accent-primary font-mono normal-case",children:V.fsm.currentState})," (held ",Cm(V.fsm.stateAgeMs),")"]}),n.jsxs("label",{className:"ml-auto flex items-center gap-1 text-3xs text-text-muted cursor-pointer select-none mb-1.5",children:[n.jsx("input",{type:"checkbox",checked:q,onChange:X=>J(X.target.checked),className:"accent-[var(--accent-primary)]"}),"live"]})]}),n.jsxs("div",{className:"space-y-1",children:[V.fsm.transitions.length===0&&n.jsx("div",{className:"text-text-muted text-2xs italic px-1",children:"no outgoing transitions (terminal state)"}),V.fsm.transitions.map((X,G)=>n.jsx(P_,{t:X},G))]})]})]}),n.jsx(aa,{}),V.nativeSource&&n.jsxs("div",{children:[n.jsx(mr,{children:"Sections"}),n.jsx("div",{className:"text-text-muted text-2xs italic px-1",children:"N/A (native-source provider)"})]}),!V.nativeSource&&V.sections&&Object.keys(V.sections).length>0&&n.jsxs("div",{children:[n.jsx(mr,{children:"Sections"}),n.jsx("div",{className:"space-y-1",children:Object.entries(V.sections).map(([X,G])=>{var Be;const z=h.has(X),ie=G.split(`
|
|
48
|
-
`),Ne=((Be=ie[0])==null?void 0:Be.slice(0,80))||"(empty)";return n.jsxs("div",{className:"border border-border-default rounded overflow-hidden bg-surface-secondary",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-bg-glass-hover transition-colors text-left",onClick:()=>ce(X),children:[n.jsx("span",{className:"text-3xs text-text-muted w-3",children:z?"▾":"▸"}),n.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-2xs",children:X}),!z&&n.jsx("span",{className:"text-text-secondary truncate font-mono text-2xs",children:Ne}),n.jsxs("span",{className:"ml-auto text-text-muted text-3xs shrink-0",children:[ie.length,"L"]})]}),z&&n.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-2xs text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary max-h-40 overflow-y-auto border-t border-border-default",children:G||"(empty)"})]},X)})})]}),n.jsx(aa,{}),V.nativeSource&&n.jsxs("div",{children:[n.jsxs(mr,{children:["Status History",V.statusHistory&&V.statusHistory.length>0?` (${V.statusHistory.length})`:""]}),V.statusHistory&&V.statusHistory.length>0?n.jsx("div",{className:"space-y-px",children:[...V.statusHistory].reverse().slice(0,20).map((X,G)=>n.jsx("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:`font-mono text-2xs font-semibold px-1.5 py-0.5 rounded shrink-0 ${oa(X.status)}`,children:X.status}),n.jsx("span",{className:"text-text-secondary text-2xs shrink-0 tabular-nums",children:ur(X.at)}),X.trigger&&n.jsx("span",{className:"text-3xs px-1.5 py-0.5 rounded font-mono shrink-0 text-text-secondary bg-bg-glass border border-border-default",children:X.trigger})]})},G))}):n.jsx("div",{className:"text-text-muted text-2xs italic px-1",children:"N/A (native-source provider — no state-machine rules)"})]}),!V.nativeSource&&V.stateHistory&&V.stateHistory.length>0&&n.jsxs("div",{children:[n.jsxs(mr,{children:["State History (",V.stateHistory.length,")"]}),n.jsx("div",{className:"space-y-px",children:[...V.stateHistory].reverse().slice(0,20).map((X,G)=>n.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:`font-mono text-2xs font-semibold px-1.5 py-0.5 rounded shrink-0 ${oa(X.stateId)}`,children:X.stateId}),n.jsx("span",{className:"text-text-secondary text-2xs shrink-0 tabular-nums",children:ur(X.at)}),X.durationMs>0&&n.jsxs("span",{className:"text-text-muted text-2xs",children:["held ",n.jsx("span",{className:"text-text-secondary",children:Cm(X.durationMs)})]}),X.reason&&n.jsx("span",{className:`text-3xs px-1.5 py-0.5 rounded font-mono shrink-0 ${M_[String(X.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(X.reason)}),X.debounceKind&&String(X.debounceKind)!=="none"&&n.jsxs("span",{className:"text-text-muted text-3xs font-mono",children:["debounce:",String(X.debounceKind)]}),X.matchedStateId&&String(X.matchedStateId)!==X.stateId&&n.jsxs("span",{className:"text-text-muted text-3xs font-mono",children:["eval→",n.jsx("span",{className:"text-text-secondary",children:String(X.matchedStateId)})]})]}),X.matchedRules&&X.matchedRules.length>0&&n.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-border-default",children:[X.matchedRules.slice(0,3).map((z,ie)=>n.jsx("span",{className:"font-mono text-3xs text-accent-primary bg-accent-primary/20 border border-accent px-1.5 py-0.5 rounded break-all",children:typeof z=="string"?z:JSON.stringify(z)},ie)),X.matchedRules.length>3&&n.jsxs("span",{className:"text-3xs text-text-muted",children:["+",X.matchedRules.length-3," more"]})]})]},G))})]}),n.jsx(aa,{}),(()=>{const X=V.messages??V.committedMessages??[];if(X.length===0)return null;const G=X.filter(Ne=>Ne.role==="user").length,z=X.filter(Ne=>Ne.role==="assistant").length,ie=[...X].reverse().find(Ne=>Ne.role==="assistant");return n.jsxs("div",{children:[n.jsxs(mr,{children:["Transcript (",X.length," — ",G,"u / ",z,"a)"]}),ie&&n.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-md p-2.5 text-2xs",children:[n.jsxs("div",{className:"text-text-muted mb-1 text-3xs",children:["Last assistant ",ie.receivedAt?ur(ie.receivedAt):""]}),n.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[ie.content.slice(0,400),ie.content.length>400?"…":""]})]})]})})(),V.specPath&&n.jsx("div",{className:"text-3xs text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:V.specPath,children:V.specPath}),n.jsxs("div",{children:[n.jsxs("button",{type:"button",className:"text-2xs text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>m(X=>!X),children:[n.jsx("span",{className:"text-text-muted",children:u?"▾":"▸"}),n.jsxs("span",{children:["Raw screen (",V.screen?V.screen.split(`
|
|
49
|
-
`).length:0," lines)"]})]}),u&&n.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-2xs text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:V.screen||"(empty)"})]})]})]})]})})})}function _g(e,t){if(typeof window>"u")return!1;try{return window[e]===!0||window.localStorage.getItem(t)==="1"}catch{return window[e]===!0}}function E_(){return _g("__ADHDEV_DEBUG_SPEC__","adhdev_debug_spec")}function D_(){return _g("__ADHDEV_DEBUG_MOBILE_BUNDLE__","adhdev_debug_mobile_bundle")}function O_({activeConv:e,clearToken:t=0,terminalRef:s,handleSendChat:r,isSendingChat:o=!1,sendFeedbackMessage:a=null,isVisible:i=!0,isInputActive:c=!0}){var Qe;const{t:d}=ve("common");An();const{sendPtyInput:u}=_t(),[m,h]=l.useState(!1),p=l.useRef(!1);p.current=m;const[g,f]=l.useState("Runtime terminal unavailable"),[y,b]=l.useState(!1),[k,j]=l.useState(null),[v,C]=l.useState(!1),[x,S]=l.useState(!1),[w,_]=l.useState(1),[A,O]=l.useState(!1),[L,R]=l.useState(!1),[F,N]=l.useState(!1),[I,B]=l.useState(!1),[T,H]=l.useState(!1),q=E_(),[J,K]=l.useState({width:0,height:0}),[M,D]=l.useState({width:0,height:0}),[P,$]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[W,U]=l.useState(null),ae=l.useRef(null),be=l.useRef(null),V=l.useRef(!1),we=l.useRef(!1),ce=l.useRef(i),de=l.useRef(0),ne=l.useRef(!1),ee=l.useRef(""),ue=l.useRef(null),je=l.useRef(!1),X=l.useRef(!1),G=l.useRef(null),z=l.useRef(null),ie=l.useRef(null),Ne=32*1024,Be=()=>{var ge,_e,Pe,nt;return((_e=(ge=ae.current)==null?void 0:ge.ownerDocument)==null?void 0:_e.defaultView)||((nt=(Pe=be.current)==null?void 0:Pe.ownerDocument)==null?void 0:nt.defaultView)||window},Le=ge=>{const _e=Be();return{ownerWindow:_e,frameId:_e.requestAnimationFrame(ge)}},Je=()=>{const ge=G.current;if(ge){try{ge.ownerWindow.cancelAnimationFrame(ge.frameId)}catch{}G.current=null}},Se=()=>{const ge=z.current;if(ge){try{ge.ownerWindow.clearTimeout(ge.timeoutId)}catch{}z.current=null}},he=()=>{const ge=ie.current;if(ge){try{ge.ownerWindow.clearTimeout(ge.timeoutId)}catch{}ie.current=null}},pe=()=>{i&&G.current===null&&(G.current=Le(()=>{re()}))},Ee=e.tabKey,Y=e.sessionId||"",me=e.daemonId||((Qe=e.routeId)==null?void 0:Qe.split(":")[0])||e.routeId||"",fe=Ti(e),E=m?Jf(e)||a:g,oe=m&&a||null,Ie=m_,Z=h_,se=.05,ye=()=>{const ge=M.width,_e=M.height;if(!Number.isFinite(J.width)||J.width<=0||!Number.isFinite(J.height)||J.height<=0||!Number.isFinite(ge)||ge<=0||!Number.isFinite(_e)||_e<=0)return 1;const Pe=J.width/ge,nt=J.height/_e;return Number(Math.min(Z,Math.max(Ie,Math.min(Pe,nt))).toFixed(2))},Fe=ye(),Me=V.current&&w>Fe,De=Number.isFinite(M.width)&&M.width>0?Math.max(J.width,Math.round(M.width*w)):J.width,Te=Number.isFinite(M.height)&&M.height>0?Math.max(J.height,Math.round(M.height*w)):J.height,He=()=>{Le(()=>{const ge=be.current;ge&&(ge.scrollLeft=0,ge.scrollTop=ge.scrollHeight-ge.clientHeight)})},tt=()=>{var ge,_e;de.current=0,ne.current=!1,ee.current="",ue.current=null,je.current=!1,X.current=!1,V.current||(we.current=!1,_(1)),G.current!==null&&Je(),h(!1),f("Runtime terminal unavailable"),he(),Se(),j(null),U(null),O(!1),b(!1),C(!1),S(!1),(_e=(ge=s.current)==null?void 0:ge.reset)==null||_e.call(ge)},Ct=()=>{var ge,_e;de.current=0,ne.current=!1,ee.current="",ue.current=null,je.current=!1,X.current=!1,G.current!==null&&Je(),h(!0),f(""),he(),Se(),j(null),U(null),O(!1),b(!1),C(!1),S(!1),(_e=(ge=s.current)==null?void 0:ge.reset)==null||_e.call(ge)},Q=()=>{X.current&&(X.current=!1,Le(()=>{var ge,_e;(_e=(ge=s.current)==null?void 0:ge.scrollToTop)==null||_e.call(ge)}))},re=()=>{if(G.current=null,!i)return;const ge=ee.current;if(!ge)return;const _e=ge.slice(0,Ne);ee.current=ge.slice(_e.length);const Pe=s.current;if(!Pe){ee.current=_e+ee.current,pe();return}Pe.write(_e,()=>{if(ee.current.length>0){pe();return}Q()})},le=ge=>{ge&&(ee.current+=ge,pe())},xe=(ge,_e=0,Pe,nt,ze={})=>{var Ge,gt,Mt,Rt;const ut=!!ze.force;!ut&&_e>0&&de.current>=_e||!ut&&_e===0&&ne.current||(de.current=_e,_e>0&&C(!0),h(!0),f(""),typeof Pe=="number"&&typeof nt=="number"&&Pe>0&&nt>0&&((gt=(Ge=s.current)==null?void 0:Ge.resize)==null||gt.call(Ge,Pe,nt)),ee.current="",(Rt=(Mt=s.current)==null?void 0:Mt.reset)==null||Rt.call(Mt),ge?le(ge):Q())};l.useEffect(()=>{tt()},[Y]),l.useEffect(()=>{var _e;if(!Y)return;const ge=((_e=Lt.onRuntimeEvent)==null?void 0:_e.call(Lt,Y,Pe=>{if(!(!Pe||Pe.sessionId!==Y)){if(Pe.type==="runtime_snapshot"){if(!i){ue.current={text:Pe.text||"",seq:Pe.seq||0,cols:Pe.cols,rows:Pe.rows,force:!!Pe.force};return}xe(Pe.text||"",Pe.seq||0,Pe.cols,Pe.rows,{force:!!Pe.force});return}if(Pe.type==="session_output"){ne.current=!0,typeof Pe.seq=="number"&&(de.current=Math.max(de.current,Pe.seq),Pe.seq>0&&C(!0)),p.current||h(!0),p.current||f(""),typeof Pe.data=="string"&&le(Pe.data);return}if(Pe.type==="session_cleared"){if(!i){je.current=!0,ee.current="",ue.current=null;return}Ct();return}if(Pe.type==="session_io_error"){const nt=typeof Pe.error=="string"&&Pe.error?Pe.error:typeof Pe.reason=="string"&&Pe.reason?Pe.reason:"unknown error";h(!1),f(`Runtime input failed: ${nt}`);return}}},me))||(()=>{});return()=>{ge()}},[me,Y,s,i]);const Ce=async(ge={})=>{var _e;if(!me||!Y)return{success:!1,error:"daemonId and sessionId are required"};ge.preserveStatus||f(ge.loadingMessage||"Loading runtime terminal...");try{const Pe=await((_e=Lt.requestRuntimeSnapshot)==null?void 0:_e.call(Lt,me,Y,{sinceSeq:ge.sinceSeq,force:ge.force}));return Pe&&Pe.success===!1?(ge.preserveStatus||(h(!1),f(`Runtime terminal unavailable: ${Pe.error}`)),Pe):Pe||{success:!0}}catch(Pe){const nt=(Pe==null?void 0:Pe.message)||String(Pe);return ge.preserveStatus||(h(!1),f(`Runtime terminal unavailable: ${nt}`)),{success:!1,error:nt}}},Re=async ge=>{var ut,Ge;const _e=((ut=ae.current)==null?void 0:ut.ownerDocument)||document,Pe=_e.defaultView||window,nt=(Ge=Pe.navigator)==null?void 0:Ge.clipboard;if(nt!=null&&nt.writeText&&Pe.isSecureContext)try{return await nt.writeText(ge),!0}catch{}let ze=null;try{return ze=_e.createElement("textarea"),ze.value=ge,ze.setAttribute("readonly","true"),ze.style.position="fixed",ze.style.left="-9999px",ze.style.top="0",_e.body.appendChild(ze),ze.focus(),ze.select(),_e.execCommand("copy")}catch{return!1}finally{ze==null||ze.remove()}},Ue=ge=>{Se(),U(ge);const _e=Be();z.current={ownerWindow:_e,timeoutId:_e.setTimeout(()=>{z.current=null,U(Pe=>Pe===ge?null:Pe)},2200)}},$e=ge=>{he(),j(ge);const _e=Be();ie.current={ownerWindow:_e,timeoutId:_e.setTimeout(()=>{ie.current=null,j(Pe=>Pe===ge?null:Pe)},2200)}},ke=async()=>{var ze,ut,Ge,gt;const ge=((ut=(ze=s.current)==null?void 0:ze.getSelection)==null?void 0:ut.call(ze))||"",_e=((gt=(Ge=s.current)==null?void 0:Ge.getVisibleText)==null?void 0:gt.call(Ge))||"",Pe=ge.trimEnd()||_e.trimEnd();if(!Pe){Ue("Nothing to copy");return}if(!await Re(Pe)){Ue("Copy failed");return}Ue(ge.trimEnd()?"Copied selection":"Copied visible terminal")},Ze=ge=>{if(!m||!i)return;((u==null?void 0:u(me,Y,ge))??!1)||Ue("Terminal input failed")},et=ge=>{Ze(f_({ctrl:L,alt:F,shift:I},ge)),R(!1),N(!1),B(!1)},Ve=async()=>{if(y)return;b(!0),j("Loading older terminal output..."),X.current=!0;const ge=await Ce({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(b(!1),(ge==null?void 0:ge.success)===!1){X.current=!1,j(`Older terminal output unavailable: ${ge.error}`);return}S(!0),$e("Older terminal output loaded"),Le(()=>{var _e;(_e=s.current)==null||_e.bumpResize()})};l.useEffect(()=>{var _e,Pe;if(!Y)return;me&&((_e=Lt.getState)==null?void 0:_e.call(Lt,me))==="connected"&&Ce();const ge=(Pe=Lt.onStateChange)==null?void 0:Pe.call(Lt,(nt,ze)=>{nt!==me||ze!=="connected"||Ce()});return()=>{ge==null||ge()}},[me,Y,s]),l.useEffect(()=>{t&&tt()},[t,Ee,s]),l.useEffect(()=>{var nt,ze;const ge=ae.current,_e=(ze=(nt=ge==null?void 0:ge.ownerDocument)==null?void 0:nt.defaultView)==null?void 0:ze.ResizeObserver;if(!ge||!_e)return;const Pe=new _e(ut=>{const Ge=ut[0];if(!Ge)return;const{width:gt,height:Mt}=Ge.contentRect;K(Rt=>{const mn=Math.round(gt),nn=Math.round(Mt);return Rt.width===mn&&Rt.height===nn?Rt:{width:mn,height:nn}})});return Pe.observe(ge),()=>Pe.disconnect()},[]),l.useEffect(()=>{if(V.current)return;const ge=ye();!Number.isFinite(ge)||ge<=0||_(_e=>we.current?ge<_e-se?ge:_e:(we.current=!0,ge))},[M.height,M.width,J.height,J.width]),l.useEffect(()=>{Me&&He()},[Me,Te,De]),l.useEffect(()=>{var Pe;const ge=ce.current;if(ce.current=i,!i)return;ge||S(!1),je.current&&(je.current=!1,Ct());const _e=ue.current;_e&&(ue.current=null,xe(_e.text,_e.seq,_e.cols,_e.rows,{force:!!_e.force})),me&&Y&&((Pe=Lt.getState)==null?void 0:Pe.call(Lt,me))==="connected"&&Ce(),ee.current&&G.current===null&&pe(),Le(()=>{var nt;(nt=s.current)==null||nt.bumpResize()})},[me,i,Y]),l.useEffect(()=>()=>{G.current!==null&&Je(),Se(),he()},[]),l.useEffect(()=>{const ge=nt=>{var ut;const ze=nt.detail;ze!=null&&ze.sessionId&&ze.sessionId!==Y||m&&((ut=s.current)==null||ut.bumpResize())},_e=Be(),Pe=_e===window?[window]:[window,_e];for(const nt of Pe)nt.addEventListener("adhdev:fit-cli-terminal",ge);return()=>{for(const nt of Pe)nt.removeEventListener("adhdev:fit-cli-terminal",ge)}},[m,Y,s]);const lt=m&&v&&!x&&(P.atTop||!P.canScroll)||y||!!k;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{ref:ae,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[lt&&n.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[n.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-2xs font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ve()},disabled:!Y||y,title:d("terminal.replayScrollbackHint"),children:d(y?"terminal.loadingOlder":"terminal.loadOlderOutput")}),k&&n.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-3xs text-white/70 backdrop-blur-sm",children:k})]}),n.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[W&&n.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-3xs text-white/70 backdrop-blur-sm",children:W}),q&&n.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-2xs font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>H(ge=>!ge),title:d("terminal.specDebugHint"),children:d("terminal.debug")}),n.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-2xs font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{ke()},disabled:!m,title:d("terminal.copyHint"),children:d("terminal.copy")}),n.jsxs("div",{className:"relative",children:[n.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-2xs font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>O(ge=>!ge),disabled:!m,"aria-label":d(A?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":A,"aria-controls":"terminal-control-keys-popover",title:d("terminal.openControlKeys"),children:d("terminal.keysButton")}),A&&n.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":d("terminal.openControlKeys"),className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-3xs font-semibold uppercase tracking-[0.14em] text-white/45",children:d("terminal.keysPanelTitle")}),n.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-2xs text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>O(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),n.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",L,R],["Alt",F,N],["Shift",I,B]].map(([ge,_e,Pe])=>n.jsx("button",{type:"button","aria-pressed":_e,className:`h-9 rounded-lg border text-xs font-semibold transition-colors ${_e?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>Pe(nt=>!nt),children:ge},ge))}),n.jsx("div",{className:"my-2 h-px bg-white/10"}),n.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>et("Escape"),children:"Esc"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>et("Tab"),children:"Tab"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>et("Enter"),children:"Enter"}),n.jsx("span",{"aria-hidden":"true"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] leading-[22px] font-semibold hover:bg-white/[0.12]",onClick:()=>et("ArrowUp"),"aria-label":d("terminal.arrowUp"),children:"↑"}),n.jsx("span",{"aria-hidden":"true"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] leading-[22px] font-semibold hover:bg-white/[0.12]",onClick:()=>et("ArrowLeft"),"aria-label":d("terminal.arrowLeft"),children:"←"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] leading-[22px] font-semibold hover:bg-white/[0.12]",onClick:()=>et("ArrowDown"),"aria-label":d("terminal.arrowDown"),children:"↓"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] leading-[22px] font-semibold hover:bg-white/[0.12]",onClick:()=>et("ArrowRight"),"aria-label":d("terminal.arrowRight"),children:"→"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>Ze(""),title:d("terminal.sendInterrupt"),children:"Ctrl-C"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>et("Space"),children:"Space"}),n.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-xs font-semibold hover:bg-white/[0.12]",onClick:()=>et("Backspace"),children:"Bksp"})]})]})]}),n.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{V.current=!0,_(ge=>{const _e=Math.max(Fe,Number((ge-.1).toFixed(2)));return _e>Fe&&He(),_e})},title:d("terminal.shrinkViewport"),children:"-"}),n.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{V.current=!0,_(ge=>{const _e=Math.min(Z,Number((ge+.1).toFixed(2)));return _e>Fe&&He(),_e})},title:d("terminal.growViewport"),children:"+"})]}),n.jsx("div",{ref:be,className:Me?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:n.jsx("div",{style:{width:De>0?`${De}px`:"100%",height:Te>0?`${Te}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:n.jsx("div",{style:{width:M.width>0?`${M.width}px`:"100%",height:M.height>0?`${M.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:w},children:n.jsx(nf,{ref:s,readOnly:!m||!i,sizingMode:"measured",onViewportMetrics:D,onScrollMetrics:$,onInput:ge=>{!m||(u==null||u(me,Y,ge))}})})})}),!m&&n.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-2xs text-red-300 pointer-events-none",children:g})]}),n.jsx(Ef,{contextKey:e.tabKey,panelLabel:Ot(e),isSending:o,isBusy:!!fe,statusMessage:E,inlineStatusMessage:oe,onSend:async ge=>fe?!1:r(ge),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),T&&n.jsx(L_,{activeConv:e,onClose:()=>H(!1)})]})}const F_=5e3,$_=12e3,H_=15e3;function B_(e){return e==="disconnected"||e==="reconnecting"}function W_({wsStatus:e,showReconnected:t,loginUrl:s,onReconnect:r,reconnectDelayMs:o=F_,reconnectActionDelayMs:a=$_}){const{t:i}=ve(),c=B_(e),[d,u]=l.useState(()=>!c||o<=0),[m,h]=l.useState(()=>!c||a<=0),p=l.useRef(!1),[g,f]=l.useState(!1);l.useEffect(()=>{if(!c){u(!1);return}if(p.current=!1,o<=0){p.current=!0,u(!0);return}u(!1);const A=setTimeout(()=>{p.current=!0,u(!0)},o);return()=>clearTimeout(A)},[o,c]),l.useEffect(()=>{if(!c){h(!1);return}if(a<=0){h(!0);return}h(!1);const A=setTimeout(()=>{h(!0)},a);return()=>clearTimeout(A)},[a,c]),l.useEffect(()=>{e!=="reconnecting"&&f(!1)},[e]),l.useEffect(()=>{if(!g)return;const A=setTimeout(()=>f(!1),H_);return()=>clearTimeout(A)},[g]);const y=()=>{f(!0),r==null||r()},b=c?d:e==="offline"||e==="auth_failed",k=!!(r&&e!=="auth_failed"&&(!c||m)),j=l.useMemo(()=>!t||e!=="connected"?!1:o<=0||p.current,[o,t,e]),v=e==="auth_failed"?"red":e==="offline"?"orange":"accent",C={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))"},x={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)"},S={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},w="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",_={transform:"translateX(-50%)"};return n.jsxs(n.Fragment,{children:[b&&n.jsx("div",{className:w,style:_,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:C[v],border:x[v],color:S[v]},children:[n.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),n.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(s?n.jsxs(n.Fragment,{children:[i("connection.sessionExpired")," ",n.jsx("a",{href:s,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),k&&n.jsxs("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-xs font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center gap-1.5",onClick:y,disabled:e==="offline"||g,children:[g&&n.jsx(ln,{size:11,thickness:2,color:"muted"}),i(g?"connection.reconnecting":"connection.reconnectNow")]})]})}),j&&n.jsx("div",{className:w,style:_,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 Ag({mode:e,onChange:t,compact:s=!1}){const{t:r}=ve("common"),o=s?14:15;return n.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:r(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?n.jsx(od,{size:o}):n.jsx(Jn,{size:o})})}function U_(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 K_(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 q_(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 Cd({git:e,className:t="",compact:s=!1}){const r=U_(e),o=K_(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 ${q_(o)} ${t}`.trim(),title:a.join(" · ")||r,"data-git-tone":o,children:[n.jsx("span",{"aria-hidden":"true",children:"⑂"}),n.jsx("span",{className:"truncate",children:r})]})}function Tg({value:e,live:t=!0,fallback:s="",className:r}){const{i18n:o}=ve("common"),[,a]=l.useState(0),i=Mo(e);if(l.useEffect(()=>{if(!t||i===null||typeof window>"u")return;const d=window.setInterval(()=>a(u=>u+1),3e4);return()=>window.clearInterval(d)},[t,i]),i===null)return s?n.jsx("span",{className:r,children:s}):null;const c=(o==null?void 0:o.resolvedLanguage)||(o==null?void 0:o.language);return n.jsx(tn,{content:Po(i,{locale:c,seconds:!0}),children:n.jsx("time",{dateTime:new Date(i).toISOString(),className:r,children:Ba(i,{locale:c})})})}async function Ig(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 Mg({value:e,label:t,className:s}){const{t:r}=ve("common"),[o,a]=l.useState(!1),i=l.useRef(null);return l.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),n.jsx("button",{type:"button",onClick:async c=>{c.stopPropagation(),await Ig(e)&&(a(!0),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500))},title:e,"aria-label":`${t??r("common.copyId")}: ${e}`,className:xt("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 _d({rows:e=[],children:t,summary:s,className:r,summaryClassName:o}){const{t:a}=ve("common"),i=e.filter(c=>typeof c.value=="string"&&c.value);return i.length===0&&!t?null:n.jsxs("details",{className:xt("group text-xs",r),"data-technical-details":"",children:[n.jsxs("summary",{className:xt("cursor-pointer select-none list-none text-3xs font-medium uppercase tracking-wide text-text-muted [&::-webkit-details-marker]:hidden",o),children:[n.jsx("span",{className:"mr-1 inline-block transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),s??a("common.technicalDetails")]}),n.jsxs("div",{className:"mt-2 flex flex-col gap-1.5",children:[i.map(c=>n.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[n.jsx("span",{className:"shrink-0 text-3xs text-text-muted",children:c.label}),n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx("span",{className:"min-w-0 truncate font-mono text-3xs text-text-secondary",title:c.value,children:c.value}),c.copyable!==!1&&n.jsx(Mg,{value:c.value})]})]},c.label)),t]})]})}function Rg(e){const t=e.replace(/[\\/]+$/,""),s=t.split(/[\\/]/);return s[s.length-1]||t||e}const z_=l.createContext(null);function Ad(){return l.useContext(z_)}function G_(e){const t=e.replace(/^(daemon_|standalone_)/,"");return t.length<=20?t:`${t.slice(0,17)}…`}function V_(e){return Qx(e)}function Y_(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 Q_(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 Va(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=Y_(e);return t.outOfSync?"degraded":t.dirty||Q_(e)?"dirty":"online"}function J_(e,t){const s=t?Va(t):void 0;return!e||e==="unknown"?s:e}function X_(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(Ha).filter(i=>i!==null);if(a.length>0)return a}const s=ft(e.activeSession??e.active_session),r={...s,sessionId:Ae(s.sessionId,s.id,s.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id)},o=Ha(r);return o?[o]:void 0}function Z_(e){const t=ft(e.connection);return Object.keys(t).length>0?t:void 0}function e1(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 Pg(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 _m(e){var r,o,a,i,c,d;let t=0;const s=e.git;return Pg(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+=Qc(s==null?void 0:s.upstreamStatus),typeof(s==null?void 0:s.lastCheckedAt)=="number"&&(t+=6),t+=(((r=s==null?void 0:s.submodules)==null?void 0:r.length)??0)*6),(o=e.branchConvergence)!=null&&o.status&&(t+=12),(((a=e.connection)==null?void 0:a.state)==="connected"||((i=e.connection)==null?void 0:i.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((d=e.connection)==null?void 0:d.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function t1(e,t){var f,y,b,k;const s=_m(e),o=_m(t)>s?t:e,a=o===t?e:t,i=o.git??a.git,c=(((f=o.providers)==null?void 0:f.length)??0)>0?o.providers:a.providers,d=(((y=o.activeSessions)==null?void 0:y.length)??0)>0?o.activeSessions:a.activeSessions,u=(((b=o.activeSessionDetails)==null?void 0:b.length)??0)>0?o.activeSessionDetails:a.activeSessionDetails,m=(((k=o.providerPriority)==null?void 0:k.length)??0)>0?o.providerPriority:a.providerPriority,h=o.connection??a.connection,p={...a,...o,machineLabel:o.machineLabel||a.machineLabel,workspace:o.workspace||a.workspace,...o.repoRoot||a.repoRoot?{repoRoot:o.repoRoot||a.repoRoot}:{},...o.daemonId||a.daemonId?{daemonId:o.daemonId||a.daemonId}:{},...o.machineId||a.machineId?{machineId:o.machineId||a.machineId}:{},...o.machineStatus||a.machineStatus?{machineStatus:o.machineStatus||a.machineStatus}:{},health:i&&(!o.health||o.health==="unknown")?Va(i):o.health,providers:c??[],activeSessions:d??[],...u&&u.length>0?{activeSessionDetails:u}:{},...m&&m.length>0?{providerPriority:m}:{},...h?{connection:h}:{},...i?{git:i}:{}},g=ft(o.branchConvergence);return Object.keys(g).length>0?Object.assign(p,{branchConvergence:g}):delete p.branchConvergence,i&&(delete p.gitProbePending,delete p.error),p}const n1=new Set(["self","local","member_push","coordinator_probe","none"]);function Sc(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Am(e){const t=ft(e),s=Ae(t.source);if(!s||!n1.has(s))return null;const r=Ae(t.lastRefreshError);return{source:s,observedAt:Sc(t.observedAt),refreshing:t.refreshing===!0,unreachableSince:Sc(t.unreachableSince),...r?{lastRefreshError:r}:{}}}function Lg(e){const t=ft(e),s=Ae(t.nodeId,t.id);if(!s)return null;const r=ft(t.cachedStatus),o=V_(t),a=o?void 0:ka(ft(t.git),t)??ka(t,t),i=o??a,c=i?void 0:ka(ft(r.git),t),d=i??c,u=Ae(t.machineStatus,t.machine_status,r.machineStatus,r.machine_status),m=Ae(t.health),h=o?Va(d):J_(m,i)||(d?Va(d):void 0)||Ae(r.health)||u||Ae(t.status)||"unknown",g=(o?void 0:Ae(t.error))??(i?void 0:Ae(r.error)),f=X_(t),y=Qi(t.activeSessions),b=(f==null?void 0:f.map(_=>_.sessionId))??[],k=Qi(t.providerPriority),j=Qt(t.gitProbePending,t.git_probe_pending),v=i?void 0:j,C=Z_(t),x=ft(t.branchConvergence??t.branch_convergence),S=C==null?void 0:C.state,w=o&&(!(C!=null&&C.reported)||S==="unknown")?e1(C):C;return{nodeId:s,machineLabel:Ae(t.machineLabel,t.machine_label,t.hostname)||G_(Ae(t.daemonId,t.daemon_id,t.machineId,t.machine_id,s)||s),workspace:Ae(t.workspace,d==null?void 0:d.workspace)||"",...Ae(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Ae(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Ae(t.daemonId,t.daemon_id)?{daemonId:Ae(t.daemonId,t.daemon_id)}:{},...Ae(t.machineId,t.machine_id)?{machineId:Ae(t.machineId,t.machine_id)}:{},...u?{machineStatus:u}:{},...Qt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Qt(t.isLocalWorktree,t.is_local_worktree)}:{},...Ae(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Ae(t.worktreeBranch,t.worktree_branch)}:{},...Ae(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:Ae(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:h,...d?{git:d}:{},...v!==void 0?{gitProbePending:v}:{},providers:Qi(t.providers),activeSessions:y.length>0?y:b,...f&&f.length>0?{activeSessionDetails:f}:{},...k.length>0?{providerPriority:k}:{},...Qt(t.launchReady)!==void 0?{launchReady:Qt(t.launchReady)}:o?{launchReady:!0}:{},...Ae(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)?{lastSeenAt:Ae(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)}:{},...Ae(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)?{updatedAt:Ae(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)}:{},...w?{connection:w}:{},...Object.keys(x).length>0?{branchConvergence:x}:{},...t.scheduling&&typeof t.scheduling=="object"?{scheduling:t.scheduling}:{},...Qt(t.autoFastForwardEligible,t.auto_fast_forward_eligible)===!0?{autoFastForwardEligible:!0}:{},...t.worktreeBootstrap&&typeof t.worktreeBootstrap=="object"?{worktreeBootstrap:t.worktreeBootstrap}:{},...t.staleDaemonBuild&&typeof t.staleDaemonBuild=="object"?{staleDaemonBuild:t.staleDaemonBuild}:{},...t.providerVersions&&typeof t.providerVersions=="object"&&!Array.isArray(t.providerVersions)?{providerVersions:t.providerVersions}:{},...Ae(t.daemonBuildVersion,t.daemon_build_version)?{daemonBuildVersion:Ae(t.daemonBuildVersion,t.daemon_build_version)}:{},...t.nodeFacts&&typeof t.nodeFacts=="object"&&!Array.isArray(t.nodeFacts)?{nodeFacts:t.nodeFacts}:{},...Am(t.gitObservation)?{gitObservation:Am(t.gitObservation)}:{},...Tm(t.heldRuntime??t.held_runtime)?{heldRuntime:Tm(t.heldRuntime??t.held_runtime)}:{},...Ae(t.role)?{role:Ae(t.role)}:{},...Ae(t.nodeLabel,t.node_label)?{nodeLabel:Ae(t.nodeLabel,t.node_label)}:{},...g?{error:g}:{}}}const s1=new Set(["member_push","coordinator_probe","none"]);function Tm(e){const t=ft(e);if(Object.keys(t).length===0)return null;const s=Ae(t.source)||"none";if(!s1.has(s))return null;const r=Array.isArray(t.sessions)?t.sessions.filter(o=>Object.keys(ft(o)).length>0):[];return{...t,source:s,observedAt:Sc(t.observedAt),refreshing:t.refreshing===!0,sessions:r}}function r1(e,t,s){const r=ft(e),o=ft(r.settings),a=ft(r.activeChat),i=Ae(ft(r.coordinator).meshId,o.meshCoordinatorFor),c=t&&i===t?"coordinator":t&&Ae(o.meshNodeFor)===t?"worker":void 0,d=Ha({sessionId:Ae(r.instanceId,r.id,r.sessionId),providerType:Ae(r.providerType),state:Ae(r.status),chatStatus:Ae(a.status),...c?{role:c}:{},...s?{workspace:s}:{}});return d?{...d,isSelfCoordinator:!1}:null}function o1(e,t,s,r){const o=ft(e),a=ft(o.settings),i=Ae(a.meshNodeId);return i?i===s.nodeId:!r||!t?!1:Ae(ft(o.coordinator).meshId,a.meshCoordinatorFor)===t||Ae(a.meshNodeFor)===t}function Eg(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=>o1(d,e,r,a)).map(d=>r1(d,e,r.workspace||void 0)).filter(d=>d!==null);if(i.length===0)return r;const c=Ya([...r.activeSessionDetails??[],...i]);return{...r,activeSessionDetails:c,activeSessions:Ya([...c,...(r.activeSessions??[]).map(d=>({sessionId:d}))]).map(d=>d.sessionId)}})}function Ya(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 Dg(e,t){const s=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],r=s.map(Ha).filter(o=>o!==null);return r.length===0?t:t.map(o=>{const a=r.filter(c=>{const d=ft(s.find(p=>{const g=ft(p);return Ae(g.sessionId,g.session_id,g.id)===c.sessionId})),u=Ae(d.nodeId,d.node_id),m=Ae(d.daemonId,d.daemon_id),h=Ae(d.workspace);return u&&u===o.nodeId?!0:on(m,o.daemonId)?!h||!o.workspace||h===o.workspace:!!(h&&o.workspace&&h===o.workspace)});if(a.length===0)return o;const i=Ya([...o.activeSessionDetails??[],...a]);return{...o,activeSessionDetails:i,activeSessions:Ya([...o.activeSessionDetails??[],...a,...(o.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function a1(e){const t=ft(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||Ae(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||Qt(t.is_local_worktree)!==void 0}function Og(e){const t=new Map,s=[];for(const r of e){const o=a1(r)?Lg(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=t1(a,o);t.set(o.nodeId,i);const c=s.findIndex(d=>d.nodeId===o.nodeId);c>=0&&(s[c]=i)}return s}function S5(e){const t=e??{},s=Og(t.nodes??[]);return{...t,nodes:Eg(Ae(t.meshId)||"",Dg(t,s))}}function k5(e){var s;const t=e==null?void 0:e.git;return{nodeId:(e==null?void 0:e.nodeId)??null,chosenSource:t?"live_git":e!=null&&e.gitProbePending?"pending_git":"no_git",hasLiveGit:Pg(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 i1(e){const t=Ae(e.meshId,e.mesh_id,e.id),s=e.nodes,r=Array.isArray(s)?s.map(d=>Lg(d)).filter(d=>d!==null):null;if(!t||!r)return null;const o=Eg(t,Dg(e,Og(r))),a=Ae(e.meshName,e.mesh_name,e.name),i=Ae(e.repoIdentity,e.repo_identity),c=Ae(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!a||!i||!c?null:{...e,meshId:t,meshName:a,repoIdentity:i,refreshedAt:c,nodes:o}}function l1(e){var a;let t=0;const s=ft(e.sourceOfTruth),r=ft(s.directPeerTruth);Ae(s.currentStatus)==="live_git_and_session_probes"&&(t+=100),s.coordinatorOwnsLiveTruth===!0&&(t+=25),r.satisfied===!0&&(t+=15);for(const i of e.nodes){const c=i.git;if(!c){i.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=Qc(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((a=c.submodules)==null?void 0:a.length)??0)*2}return t}function c1(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 d1=20;function Im(e){let t=null;for(const s of e){const r=i1(ft(s));if(!r)continue;const o=l1(r),a=c1(r);if(!t){t={status:r,score:o,refreshedAt:a};continue}(Math.abs(o-t.score)<=d1?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 Td(e){const s=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,r=Im([s==null?void 0:s.status,s]);return r||Im([e==null?void 0:e.status,e])}function u1(e){var c;const t=typeof e.heldCoordinatorDaemonId=="string"?e.heldCoordinatorDaemonId.trim():"";if(t)return t;const s=e.conv,r=(s==null?void 0:s.settings)||{};if((typeof((c=s==null?void 0:s.coordinator)==null?void 0:c.meshId)=="string"&&s.coordinator.meshId.trim()||typeof r.meshCoordinatorFor=="string"&&r.meshCoordinatorFor.trim()||"")&&e.sessionDaemonId)return e.sessionDaemonId;const a=typeof r.meshCoordinatorDaemonId=="string"?r.meshCoordinatorDaemonId.trim():"";return a||(typeof e.reportedCoordinatorDaemonId=="string"?e.reportedCoordinatorDaemonId.trim():"")||null}function m1(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 h1(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 p1(e,t){var o,a;if(!t)return null;const s=Td(e),r=(o=s==null?void 0:s.nodes)==null?void 0:o.find(i=>Zx(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 f1={sm:"max-w-md",md:"max-w-lg",lg:"max-w-3xl"},Mm={center:"items-center justify-center",sheet:"items-end justify-center sm:items-center",stretch:"items-stretch justify-center md:items-center"};function Rr({open:e=!0,onClose:t,align:s="center",size:r="md",chrome:o=!0,closeOnBackdrop:a=!0,closeOnEsc:i=!0,ariaLabel:c,ariaLabelledBy:d,overlayClassName:u,surfaceClassName:m,children:h}){l.useEffect(()=>{if(!e||!i)return;const b=k=>{k.key==="Escape"&&t()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[e,i,t]);const p=l.useCallback(b=>{a&&b.target===b.currentTarget&&t()},[a,t]);if(!e)return null;const g=o?xt("fixed inset-0 flex",Mm[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):xt("fixed inset-0 flex",Mm[s],u),f=o?xt("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",f1[r],m):xt(m),y=n.jsx("div",{className:g,style:o?{zIndex:"var(--z-modal-backdrop)"}:void 0,onClick:p,children:n.jsx("div",{role:"dialog","aria-modal":"true","aria-label":c,"aria-labelledby":d,className:f,style:o?{zIndex:"var(--z-modal)"}:void 0,onClick:b=>b.stopPropagation(),children:h})});return typeof document>"u"?y:Qn.createPortal(y,document.body)}function Fg({open:e,onClose:t,size:s="md",title:r,footer:o,children:a,showClose:i=!0,closeOnBackdrop:c=!0,closeOnEsc:d=!0,ariaLabel:u,className:m,contentClassName:h}){const p=r!=null||i;return n.jsxs(Rr,{open:e,onClose:t,size:s,closeOnBackdrop:c,closeOnEsc:d,ariaLabel:r==null?u:void 0,overlayClassName:m,surfaceClassName:h,children:[p&&n.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-4 border-b border-border-default px-5 py-4",children:[n.jsx("div",{className:"min-w-0",children:typeof r=="string"||typeof r=="number"?n.jsx("h2",{className:"truncate text-lg font-bold text-text-primary",children:r}):r}),i&&n.jsx("button",{type:"button",onClick:t,className:"-m-1.5 inline-flex h-11 w-11 shrink-0 items-center justify-center","aria-label":at.t("common.closeDialog"),children:n.jsx("span",{className:"btn btn-ghost btn-sm inline-flex h-8 w-8 items-center justify-center p-0",children:n.jsx(Bt,{size:16})})})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-5 py-4",children:a}),o!=null&&n.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border-default px-5 py-4",children:o})]})}const kc=new Map;function g1(e){return{meshId:e,daemonId:null,status:null,response:null,loadedAt:null,loading:!1,refreshing:!1,error:null}}function Id(e){let t=kc.get(e);return t||(t={snapshot:g1(e),inFlight:null,queuedRefresh:null,listeners:new Set},kc.set(e,t)),t}function vr(e,t){const s=Id(e);s.snapshot={...s.snapshot,...t};for(const r of[...s.listeners])try{r()}catch{}}function yo(e){var t;return e?((t=kc.get(e))==null?void 0:t.snapshot)??null:null}function b1(e,t){const s=Id(e);return s.listeners.add(t),()=>{s.listeners.delete(t)}}function x1(e,t,s=null){vr(e,{status:t,daemonId:s,loadedAt:t?Date.now():null,error:null})}function y1(e){return e instanceof Error?e.message:typeof e=="string"?e:"Failed to load mesh status"}function Pi(e){const{meshId:t,daemonId:s,load:r}=e,o=e.refresh===!0,a=e.extract??(m=>Td(m));if(!t||!s)return Promise.resolve(null);const i=Id(t),c=i.inFlight;if(c&&c.daemonId===s)return!o||c.refresh?c.promise:(i.queuedRefresh||(i.queuedRefresh=c.promise.then(()=>(i.queuedRefresh=null,Pi(e)))),i.queuedRefresh);const d=i.snapshot.status!==null;vr(t,{loading:!d,refreshing:d,error:null});const u=(async()=>{var m;await null;try{const h=await r(s,t,{refresh:o}),p=a(h);return p?(vr(t,{status:p,response:h,daemonId:s,loadedAt:Date.now(),error:null}),p):(vr(t,{error:"mesh_status returned an unexpected payload."}),null)}catch(h){return vr(t,{error:y1(h)}),null}finally{((m=i.inFlight)==null?void 0:m.promise)===u&&(i.inFlight=null),vr(t,{loading:!1,refreshing:!1})}})();return i.inFlight={daemonId:s,refresh:o,promise:u},u}const Qa=new Set;function v1(e){if(Qa.size===0)return!1;for(const t of[...Qa])try{t(e)}catch{}return!0}function w1(e){return Qa.add(e),()=>Qa.delete(e)}const Ts={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`},S1=new Set(["missing-credentials","expired-token","unauthorized","quota-exhausted","rate-limited","network","server","parse","cli-unavailable","unsupported","setup-required","no-data","unknown"]);function Md(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)=>S1.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 k1={"antigravity-cli":"Antigravity CLI","claude-cli":"Claude Code","codex-cli":"Codex CLI","cursor-cli":"Cursor CLI","grok-cli":"Grok CLI","hermes-cli":"Hermes CLI",kimi:"Kimi Code",opencode:"opencode"};function j1(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 N1(e,t=Ts){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(j1((o??0)+(a??0)))),typeof s.sessions=="number"&&r.push(t.usageSessions(s.sessions)),r.length===0?null:`${s.days}d ${r.join(" · ")}`}function Pr(e){return k1[e]??e}function Rm(e){return Number.isFinite(e)?e>=90?"danger":e>=70?"warn":"good":"default"}function C1(e,t=Date.now(),s=Ts){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 Ta(e,t=Date.now()){const s=e==null?void 0:e.resetsAt;return typeof s=="number"&&Number.isFinite(s)&&s>0&&s<=t}Ts.windowReset();function Pm(e){return!!e&&typeof e.usedPercent=="number"&&Number.isFinite(e.usedPercent)}function _1(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 A1(e){return Pm(e.session)||Pm(e.weekly)?!0:Array.isArray(e.buckets)&&e.buckets.some(t=>!!t&&typeof t.usedPercent=="number"&&Number.isFinite(t.usedPercent))}function T1(e){var t;if(!_1(e)&&A1(e))return"stale";if(((t=e.metadata)==null?void 0:t.lastGoodWindows)===!0)return"refreshing"}function Lm(e,t=Date.now(),s=!1,r=Ts){if(!e||typeof e.usedPercent!="number"||!Number.isFinite(e.usedPercent))return null;if(Ta(e,t))return r.windowReset();const o=r.used(e.usedPercent.toFixed(1)),a=C1(e.resetsAt,t,r),i=a?`${o} · ${a}`:o,c=s===!0||s==="refreshing"?"refreshing":s==="stale"?"stale":null;return c?`${i} · ${r.cue(c)}`:i}function I1(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 M1(e,t=Ts){var o;const s=e.buckets;if(!Array.isArray(s)||s.length<2)return[];const r=[];for(const a of s){if(!a||typeof a!="object")continue;const i=Number(a.usedPercent),c=Number(a.windowMinutes);if(!Number.isFinite(i)||!Number.isFinite(c)||c<=0)continue;const u=(o=(typeof a.name=="string"?a.name:"").split("·")[0])==null?void 0:o.trim().replace(/\s+(Models?|Bundled Models?)$/i,"").trim();r.push({label:`${u||t.pool()} ${I1(c)}`,usedPercent:i,window:{usedPercent:i,windowMinutes:c,resetsAt:typeof a.resetsAt=="number"?a.resetsAt:null}})}return r.sort((a,i)=>a.label.localeCompare(i.label))}function R1(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 P1(e,t=Ts){var c;const s=typeof e.error=="string"?e.error.trim():"",r=(c=e.metadata)==null?void 0:c.failureKind,o=typeof r=="string"?r.trim():"",a=o?o.replace(/[_-]+/g," "):"",i=o?t.failureKind(o,a):"";return s&&a&&!s.toLowerCase().includes(a.toLowerCase())?`${s} (${i})`:s||i||(e.status==="unavailable"?t.unavailable():t.unreadable())}function L1(e,t=Date.now(),s=Ts){const r=T1(e),o=(g,f,y)=>{const b=Lm(g,t,r,s);if(!b)return null;const k=g.usedPercent,j=Ta(g,t);return{key:f,label:`${y} ${b}`,usedPercent:j?null:k,hint:f,tone:j?"default":Rm(k)}},a=o(e.session,"session","5h"),i=o(e.weekly,"weekly","7d"),c=o(e.monthly,"monthly","30d"),d=M1(e,s).map(g=>({key:g.label,label:`${g.label} ${Lm(g.window,t,r,s)}`,usedPercent:Ta(g.window,t)?null:g.usedPercent,hint:"bucket",tone:Ta(g.window,t)?"default":Rm(g.usedPercent)})),u=d.length>0?d:[a,i,c].filter(g=>g!==null),m=N1(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:R1(e),compactChip:null}:{kind:"failure",cue:r,chips:[],usageLabel:null,message:P1(e,s),compactChip:null}}function Rd(e){return(t,s=Date.now())=>L1(t,s,e)}function j5(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 $g(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)=>Pr(s.provider).localeCompare(Pr(r.provider)))}function N5(e,t=Date.now(),s=Ts){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 Em(e){return Po(e,{seconds:!0})||"—"}function E1({sessionId:e,daemonId:t,conv:s,onClose:r}){var T;const{t:o}=ve("common"),a=Rd(Md(o)),{sendCommand:i}=_t(),c=Ad(),[d,u]=l.useState(!0),[m,h]=l.useState(null),[p,g]=l.useState(null),[f,y]=l.useState(null),[b,k]=l.useState(null),j=l.useMemo(()=>m1(s),[s]),v=l.useMemo(()=>h1(s),[s]),C=l.useCallback(async()=>{u(!0),g(null);try{const H=await i(t,"get_session_info",{targetSessionId:e}),q=H&&typeof H=="object"?H:{},J=q.result&&typeof q.result=="object"?q.result:q;J!=null&&J.success?h(J):(g((J==null?void 0:J.error)||o("sessionInfo.failedToLoad")),h(null))}catch(H){g((H==null?void 0:H.message)||String(H)),h(null)}finally{u(!1)}},[i,t,e,o]);l.useEffect(()=>{C()},[C]);const x=l.useMemo(()=>{var H,q;return u1({conv:s,sessionDaemonId:t,heldCoordinatorDaemonId:j?(H=yo(j))==null?void 0:H.daemonId:null,reportedCoordinatorDaemonId:(q=m==null?void 0:m.meshWorker)==null?void 0:q.coordinatorDaemonId})},[s,t,j,(T=m==null?void 0:m.meshWorker)==null?void 0:T.coordinatorDaemonId]),S=l.useCallback(async()=>{var K,M;if(y(null),k(null),!j||!v||!x)return;const q=((K=yo(j))==null?void 0:K.status)??null??await Pi({meshId:j,daemonId:x,refresh:!1,load:(D,P,$)=>c!=null&&c.loadMeshStatus?c.loadMeshStatus(D,P,{refresh:$.refresh}):i(D,"mesh_status",{meshId:P})});if(!q){k(((M=yo(j))==null?void 0:M.error)||o("sessionInfo.meshNodeUnavailable"));return}const J=p1(q,v);if(!J){k(o("sessionInfo.stampedToNode"));return}y(J)},[c,i,x,j,v,o]);l.useEffect(()=>{S()},[S]);const[w,_]=l.useState(!1),A=l.useCallback(async()=>{await Ig(D1({sessionId:e,daemonId:t,conv:s,data:m,meshNode:f,meshNodeError:b}))&&(_(!0),setTimeout(()=>_(!1),1500))},[s,t,m,f,b,e]),O=n.jsxs(n.Fragment,{children:[(m||p)&&n.jsx("button",{type:"button",onClick:()=>void A(),"data-testid":"session-info-copy-diagnostics",className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:n.jsx("span",{"aria-live":"polite",children:o(w?"common.copied":"sessionInfo.copyDiagnostics")})}),n.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:o("sessionInfo.close")})]}),L=H=>o(H?"common.yes":"common.no"),R=m==null?void 0:m.session,F=(R==null?void 0:R.workspace)||(s==null?void 0:s.workspacePath)||"",N=(s==null?void 0:s.machineName)||(m==null?void 0:m.machineNickname)||"",I=m==null?void 0:m.meshWorker,B=$g((f==null?void 0:f.quota)??(m==null?void 0:m.quota));return n.jsx(Fg,{open:!0,onClose:r,title:o("sessionInfo.title"),size:"lg",footer:O,children:n.jsxs("div",{className:"text-sm space-y-4",children:[d&&n.jsx("div",{className:"text-text-secondary",children:o("sessionInfo.loading")}),p&&n.jsx("div",{className:"text-red-500",children:o("sessionInfo.failedToLoad")}),R&&n.jsxs("div",{className:"space-y-1.5","data-testid":"session-info-summary",children:[n.jsx(it,{k:o("sessionInfo.rowProvider"),v:R.providerName||R.providerType}),F&&n.jsx(it,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(tn,{content:F,children:n.jsx("span",{className:"truncate",children:Rg(F)})})}),N&&n.jsx(it,{k:o("sessionInfo.rowMachine"),v:N}),R.spawnedAtMs?n.jsx(it,{k:o("sessionInfo.rowStarted"),v:n.jsx(Tg,{value:R.spawnedAtMs})}):null,(s==null?void 0:s.git)&&n.jsx(it,{k:o("sessionInfo.rowGit"),v:n.jsxs("span",{children:[s.git.branch||o("sessionInfo.gitDetached"),s.git.ahead?` ↑${s.git.ahead}`:"",s.git.behind?` ↓${s.git.behind}`:"",s.git.dirty?` · ${o("sessionInfo.gitDirty")}`:` · ${o("sessionInfo.gitClean")}`]})}),(m==null?void 0:m.coordinator)&&n.jsx(it,{k:o("sessionInfo.rowRole"),v:o("sessionInfo.roleCoordinator")}),B.map(({provider:H,quota:q})=>{const J=a(q);return n.jsx(it,{k:[Pr(H),Yl(q)].filter(Boolean).join(" · "),v:J.kind==="chips"?n.jsx("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:J.chips.map(K=>n.jsx(Dm,{label:K.label,tone:K.tone},K.key))}):J.kind==="usage"?n.jsx(Dm,{label:J.usageLabel,tone:"info"}):J.kind==="okNoWindows"?n.jsx("span",{className:"text-text-secondary",children:J.message??o("sessionInfo.quotaOkNoWindows")}):n.jsx("span",{className:"text-text-secondary",children:J.message})},H)}),(I==null?void 0:I.coordinatorSessionId)&&n.jsx(it,{k:o("sessionInfo.sectionMeshWorker"),v:n.jsxs("span",{className:"inline-flex flex-wrap items-center gap-2",children:[I.coordinatorCliType&&n.jsx("span",{className:"text-text-secondary",children:I.coordinatorCliType}),I.coordinatorAlive===!1?n.jsx("span",{className:"text-text-secondary",children:o("sessionNav.coordinatorGone")}):n.jsx("button",{type:"button",className:"rounded border border-border-default px-2 py-0.5 text-xs hover:bg-surface-secondary",onClick:()=>{v1({sessionId:I.coordinatorSessionId,source:"session-info-dialog"}),r()},children:o("sessionNav.openCoordinatorChat")})]})})]}),(R||f||(m==null?void 0:m.coordinator)||b&&(j||v))&&n.jsxs("details",{className:"group rounded-lg border border-border-subtle px-3 py-2","data-testid":"session-info-technical-details",children:[n.jsxs("summary",{className:"cursor-pointer select-none list-none text-xs font-medium text-text-secondary [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"mr-1 inline-block transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),o("common.technicalDetails")]}),n.jsxs("div",{className:"mt-3 space-y-4",children:[R&&n.jsxs(Fs,{title:o("sessionInfo.sectionSession"),children:[n.jsx(it,{k:o("sessionInfo.rowSessionId"),v:n.jsx(Pt,{children:R.sessionId})}),n.jsx(it,{k:o("sessionInfo.rowProviderType"),v:n.jsx(Pt,{children:R.providerType})}),R.transport&&n.jsx(it,{k:o("sessionInfo.rowTransport"),v:R.transport}),F&&n.jsx(it,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(Pt,{children:F})}),R.spawnedAtMs?n.jsx(it,{k:o("sessionInfo.rowSpawnedAt"),v:Em(R.spawnedAtMs)}):null,R.providerSessionId&&n.jsx(it,{k:o("sessionInfo.rowProviderSessionId"),v:n.jsx(Pt,{children:R.providerSessionId})}),(s==null?void 0:s.connectionState)&&n.jsx(it,{k:o("sessionInfo.rowConnection"),v:s.connectionState})]}),I&&(I.meshId||I.taskId||I.coordinatorSessionId)&&n.jsxs(Fs,{title:o("sessionInfo.sectionMeshWorker"),children:[I.meshId&&n.jsx(it,{k:o("sessionInfo.rowMeshId"),v:n.jsx(Pt,{children:I.meshId})}),I.taskId&&n.jsx(it,{k:o("sessionInfo.rowTaskId"),v:n.jsx(Pt,{children:I.taskId})}),I.coordinatorSessionId&&n.jsx(it,{k:o("sessionInfo.rowCoordinator"),v:n.jsx(Pt,{children:I.coordinatorSessionId})})]}),(R==null?void 0:R.launch)&&n.jsxs(Fs,{title:o("sessionInfo.sectionLaunch"),children:[R.launch.command&&n.jsx(it,{k:o("sessionInfo.rowCommand"),v:n.jsx(Pt,{children:R.launch.command})}),R.launch.cwd&&n.jsx(it,{k:o("sessionInfo.rowWorkingDirectory"),v:n.jsx(Pt,{children:R.launch.cwd})}),Array.isArray(R.launch.args)&&R.launch.args.length>0&&n.jsx(it,{k:o("sessionInfo.rowArgs"),v:n.jsx(Pt,{children:R.launch.args.join(" ")})}),Array.isArray(R.launch.extraArgs)&&R.launch.extraArgs.length>0&&n.jsx(it,{k:o("sessionInfo.rowExtraArgs"),v:n.jsx(Pt,{children:R.launch.extraArgs.join(" ")})}),Array.isArray(R.launch.extraEnvKeys)&&R.launch.extraEnvKeys.length>0&&n.jsx(it,{k:o("sessionInfo.rowExtraEnv"),v:n.jsx(Pt,{children:R.launch.extraEnvKeys.join(", ")})})]}),f&&n.jsxs(Fs,{title:o("sessionInfo.sectionMeshNode"),children:[f.nodeId&&n.jsx(it,{k:o("sessionInfo.rowNodeId"),v:n.jsx(Pt,{children:f.nodeId})}),f.workspace&&n.jsx(it,{k:o("sessionInfo.rowWorkspace"),v:n.jsx(Pt,{children:f.workspace})}),f.repoRoot&&f.repoRoot!==f.workspace&&n.jsx(it,{k:o("sessionInfo.rowRepoRoot"),v:n.jsx(Pt,{children:f.repoRoot})}),f.daemonId&&n.jsx(it,{k:o("sessionInfo.rowDaemonId"),v:n.jsx(Pt,{children:f.daemonId})}),f.role&&n.jsx(it,{k:o("sessionInfo.rowRole"),v:f.role}),f.machineStatus&&n.jsx(it,{k:o("sessionInfo.rowMachineStatus"),v:f.machineStatus}),f.health&&n.jsx(it,{k:o("sessionInfo.rowHealth"),v:f.health}),f.isLocalWorktree&&n.jsx(it,{k:o("sessionInfo.rowWorktree"),v:f.worktreeBranch?n.jsx(Pt,{children:f.worktreeBranch}):o("common.yes")}),typeof f.launchReady=="boolean"&&n.jsx(it,{k:o("sessionInfo.rowLaunchReady"),v:L(f.launchReady)}),f.git&&n.jsx(it,{k:o("sessionInfo.rowGit"),v:n.jsxs("span",{children:[f.git.branch||o("sessionInfo.gitDetached"),f.git.headCommit?` @ ${String(f.git.headCommit).slice(0,10)}`:"",f.git.ahead?` ↑${f.git.ahead}`:"",f.git.behind?` ↓${f.git.behind}`:"",f.git.dirty?` · ${o("sessionInfo.gitDirty")}`:` · ${o("sessionInfo.gitClean")}`,f.git.upstream?` · ${f.git.upstream}`:""]})}),f.connection&&n.jsx(it,{k:o("sessionInfo.rowConnection"),v:n.jsxs("span",{children:[f.connection.transport||"—",f.connection.state?` · ${f.connection.state}`:"",typeof f.connection.rttMs=="number"?` · RTT ${f.connection.rttMs}ms`:""]})}),Array.isArray(f.providers)&&f.providers.length>0&&n.jsx(it,{k:o("sessionInfo.rowProviders"),v:n.jsx(Pt,{children:f.providers.join(", ")})}),Array.isArray(f.providerPriority)&&f.providerPriority.length>0&&n.jsx(it,{k:o("sessionInfo.rowProviderPriority"),v:n.jsx(Pt,{children:f.providerPriority.join(" › ")})})]}),!f&&b&&(j||v)&&n.jsx(Fs,{title:o("sessionInfo.sectionMeshNode"),children:n.jsx("div",{className:"text-text-secondary italic",children:b})}),(m==null?void 0:m.coordinator)&&n.jsxs(Fs,{title:o("sessionInfo.sectionMeshCoordinator"),children:[n.jsx(it,{k:o("sessionInfo.rowMeshId"),v:n.jsx(Pt,{children:m.coordinator.meshId})}),m.coordinator.cliType&&n.jsx(it,{k:o("sessionInfo.rowCoordinatorCli"),v:m.coordinator.cliType}),m.coordinator.startedAt?n.jsx(it,{k:o("sessionInfo.rowStartedAt"),v:Em(m.coordinator.startedAt)}):null,m.coordinator.injection&&n.jsx(it,{k:o("sessionInfo.rowPromptInjection"),v:`${m.coordinator.injection.mode}${m.coordinator.injection.target?` → ${m.coordinator.injection.target}`:""}`}),m.coordinator.mcpConfigPath&&n.jsx(it,{k:o("sessionInfo.rowMcpConfig"),v:n.jsx(Pt,{children:m.coordinator.mcpConfigPath})}),m.coordinator.extraSystemPrompt&&n.jsx(jc,{title:o("sessionInfo.blockExtraPrompt"),body:m.coordinator.extraSystemPrompt}),m.coordinator.systemPrompt&&n.jsx(jc,{title:o("sessionInfo.blockFinalPrompt"),body:m.coordinator.systemPrompt})]}),(R==null?void 0:R.runtimeMetadata)!=null&&n.jsx(O1,{meta:R.runtimeMetadata}),p&&n.jsx("div",{className:"font-mono text-xs text-text-secondary break-all",children:p})]})]})]})})}function D1(e){const{sessionId:t,daemonId:s,conv:r,data:o,meshNode:a,meshNodeError:i}=e,c={sessionId:t,daemonId:s,machine:(r==null?void 0:r.machineName)||(o==null?void 0:o.machineNickname)||null,connectionState:(r==null?void 0:r.connectionState)??null,git:(r==null?void 0:r.git)??null,session:(o==null?void 0:o.session)??null,meshWorker:(o==null?void 0:o.meshWorker)??null,coordinator:(o==null?void 0:o.coordinator)??null,meshNode:a??null,meshNodeError:i??null,error:(o==null?void 0:o.error)??null};try{return JSON.stringify(c,null,2)}catch{return String(c)}}function Fs({title:e,children:t}){return n.jsxs("div",{children:[n.jsx("h3",{className:"text-xs uppercase tracking-wide text-text-secondary mb-1",children:e}),n.jsx("div",{className:"space-y-1",children:t})]})}function it({k:e,v:t}){return n.jsxs("div",{className:"flex flex-col sm:flex-row gap-1 sm:gap-3",children:[n.jsx("div",{className:"w-full sm:w-36 sm:shrink-0 text-text-secondary font-medium sm:font-normal",children:e}),n.jsx("div",{className:"min-w-0 break-all",children:t})]})}function Pt({children:e}){return n.jsx("code",{className:"font-mono text-xs",children:e})}function Dm({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 O1({meta:e}){const{t}=ve("common");if(!e||typeof e!="object")return null;const s=e,r=u=>typeof u=="string"&&u.trim()?u:null,o=r(s.runtimeId),a=r(s.lifecycle),i=r(s.surfaceKind),c=r(s.recoveryState),d=Array.isArray(s.attachedClients)?s.attachedClients.length:null;return n.jsxs(Fs,{title:t("sessionInfo.sectionRuntime"),children:[o&&n.jsx(it,{k:t("sessionInfo.rowRuntimeId"),v:n.jsx(Pt,{children:o})}),a&&n.jsx(it,{k:t("sessionInfo.rowLifecycle"),v:a}),i&&n.jsx(it,{k:t("sessionInfo.rowSurface"),v:i}),c&&n.jsx(it,{k:t("sessionInfo.rowRecoveryState"),v:c}),typeof s.restoredFromStorage=="boolean"&&n.jsx(it,{k:t("sessionInfo.rowRestoredFromStorage"),v:s.restoredFromStorage?t("common.yes"):t("common.no")}),d!=null&&n.jsx(it,{k:t("sessionInfo.rowAttachedClients"),v:String(d)}),n.jsx(jc,{title:t("sessionInfo.blockRawMetadata"),body:F1(e)})]})}function F1(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function jc({title:e,body:t,defaultOpen:s=!1}){const[r,o]=l.useState(s);return n.jsxs("div",{className:"mt-2",children:[n.jsxs("button",{type:"button",onClick:()=>o(a=>!a),className:"text-xs uppercase tracking-wide text-text-secondary hover:text-text-primary",style:{pointerEvents:"auto"},children:[r?"▾":"▸"," ",e]}),r&&n.jsx("pre",{className:"mt-1 p-2 bg-[var(--surface-secondary)] border border-border-subtle rounded text-xs whitespace-pre-wrap overflow-x-auto max-h-96 overflow-y-auto",children:t})]})}function Hg(){return kr(()=>import("./DashboardMeshGraphDialog-DtFpO2PQ.js"),__vite__mapDeps([3,1,4,5]))}const $1=l.lazy(Hg);function H1({onClose:e}){const{t}=ve(),s=t("connection.loadingShort");return n.jsx(Rr,{onClose:e,size:"sm",ariaLabel:s,children:n.jsx("div",{className:"flex items-center justify-center p-8","data-testid":"mesh-graph-dialog-loading",children:n.jsx(ln,{label:s})})})}function Pd(e){return n.jsx(l.Suspense,{fallback:n.jsx(H1,{onClose:e.onClose}),children:n.jsx($1,{...e})})}const B1=8e3;function W1({sessionId:e,daemonId:t,muted:s,sendDaemonCommand:r}){const[o,a]=l.useState(null),i=l.useRef(null);l.useEffect(()=>{o!==null&&s===o&&a(null)},[s,o]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]);const c=o!==null?o:s,d=!!e&&!!t,u=l.useCallback(()=>{if(!e||!t)return;const m=!c;a(m),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(null),B1),r(t,"set_conversation_prefs",{sessionId:e,muted:m}).catch(h=>{console.warn("[conversation-prefs] toggle mute failed",h),a(null)})},[t,c,r,e]);return{available:d,muted:c,toggle:u}}const ia=220;function Om(e){var t,s;return!!e.daemonId&&!!((t=e.coordinator)!=null&&t.meshId||(s=e.settings)!=null&&s.meshCoordinatorFor)}function Bg({conversation:e,onOpenHistory:t,onOpenRemote:s,onOpenGit:r,onOpenMeshGraph:o,className:a,iconSize:i=16}){const{t:c}=ve("common"),{ides:d}=An(),{sendCommand:u}=_t(),[m,h]=l.useState(!1),[p,g]=l.useState(!1),[f,y]=l.useState(null),b=l.useRef(null),k=l.useRef(null),j=St(e)&&!vt(e),v=vt(e),C=l.useMemo(()=>{const A=d.find(O=>O.id===e.routeId);return Qf(e,A)},[e,d]),x=W1({sessionId:e.sessionId,daemonId:e.daemonId,muted:!!(C!=null&&C.muted),sendDaemonCommand:u}),S=[];if(t&&!v&&S.push({key:"history",label:c("dashboard.header.chatHistory"),icon:n.jsx(Dp,{size:15}),onSelect:()=>t(e)}),s&&!j&&!v&&S.push({key:"remote",label:c("dashboard.header.remoteControl"),icon:n.jsx(Xn,{size:15}),onSelect:()=>s(e)}),o&&Om(e)&&S.push({key:"mesh",label:c("dashboard.header.meshGraph"),icon:n.jsx(Gn,{size:15}),onSelect:()=>o(e)}),r&&e.git&&e.daemonId&&e.workspacePath){const A=e.daemonId,O=e.workspacePath;S.push({key:"git",label:c("dashboard.header.openGitStatus"),icon:n.jsx(nc,{size:15}),onSelect:()=>r(A,O)})}x.available&&S.push({key:"mute",label:x.muted?c("conversation.unmuteThis"):c("conversation.muteThis"),icon:x.muted?n.jsx(tc,{size:15}):n.jsx(js,{size:15}),onSelect:x.toggle,pressed:x.muted}),e.sessionId&&e.daemonId&&S.push({key:"info",label:c("sessionInfo.title"),icon:n.jsx(Io,{size:15}),onSelect:()=>g(!0)});const w=l.useCallback((A=!1)=>{var O;h(!1),A&&((O=b.current)==null||O.focus())},[]);if(l.useLayoutEffect(()=>{var L;if(!m||typeof window>"u"){y(null);return}const A=(L=b.current)==null?void 0:L.getBoundingClientRect();if(!A)return;const O=Math.min(Math.max(8,A.right-ia),window.innerWidth-ia-8);y({top:A.bottom+6,left:O})},[m]),l.useEffect(()=>{if(!m||typeof window>"u")return;const A=R=>{R.key==="Escape"&&(R.stopPropagation(),w(!0))},O=R=>{var N,I;const F=R.target;F&&((N=b.current)!=null&&N.contains(F)||(I=k.current)!=null&&I.contains(F)||w())},L=()=>w();return window.addEventListener("keydown",A,!0),document.addEventListener("mousedown",O,!0),window.addEventListener("resize",L),()=>{window.removeEventListener("keydown",A,!0),document.removeEventListener("mousedown",O,!0),window.removeEventListener("resize",L)}},[w,m]),l.useEffect(()=>{var A,O;m&&((O=(A=k.current)==null?void 0:A.querySelector('[role="menuitem"]'))==null||O.focus())},[m,f]),S.length===0)return null;const _=A=>{var F;if(A.key!=="ArrowDown"&&A.key!=="ArrowUp")return;A.preventDefault();const O=Array.from(((F=k.current)==null?void 0:F.querySelectorAll('[role="menuitem"]'))??[]),L=O.indexOf(document.activeElement),R=O[(L+(A.key==="ArrowDown"?1:-1)+O.length)%O.length];R==null||R.focus()};return n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:b,type:"button","data-testid":"conversation-actions-menu","aria-label":c("dashboard.header.moreActions"),title:c("dashboard.header.moreActions"),"aria-haspopup":"menu","aria-expanded":m,onClick:()=>h(A=>!A),onPointerEnter:()=>{o&&Om(e)&&Hg()},className:a??"btn btn-secondary btn-sm",style:{pointerEvents:"auto"},children:n.jsx(Fp,{size:i})}),m&&typeof document<"u"&&Qn.createPortal(n.jsx("div",{ref:k,role:"menu","aria-label":c("dashboard.header.moreActions"),onKeyDown:_,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:f?{top:f.top,left:f.left,width:ia}:{top:-9999,left:-9999,width:ia,visibility:"hidden"},children:S.map(A=>n.jsxs("button",{type:"button",role:"menuitem","data-menu-item":A.key,"aria-pressed":A.pressed,onClick:()=>{w(),A.onSelect()},className:xt("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",A.pressed&&"text-amber-500"),children:[n.jsx("span",{className:"flex w-4 shrink-0 justify-center","aria-hidden":!0,children:A.icon}),n.jsx("span",{className:"min-w-0 truncate",children:A.label})]},A.key))}),document.body),p&&e.sessionId&&e.daemonId&&n.jsx(E1,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e,onClose:()=>g(!1)})]})}function U1({wsStatus:e,isConnected:t,daemonCount:s,p2pStates:r={},usesP2P:o=!0}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};if(s>0&&!o)return t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null};const i=Object.values(r).filter(c=>c==="connected").length;return s>0?i>=s?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.machinesConnectedCount",subtitleParams:{connected:i,total:s}}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function Fm({value:e}){return e?n.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function $m({notification:e,shortcutIndex:t,onOpen:s,onMarkRead:r,onMarkUnread:o,onDelete:a}){const{t:i}=ve(),c=xi(e.updatedAt),d=!e.readAt;return n.jsxs("div",{className:`dashboard-header-inbox-item ${d?"is-attention":""}`.trim(),children:[n.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:s,children:[n.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),n.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?n.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?i("notification.actionNeeded"):i("notification.taskComplete"),c].filter(Boolean).join(" · ")]}),e.preview?n.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),n.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[d?n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),r()},children:i("notification.markRead")}):n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),o()},children:i("notification.markUnread")}),n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:i("notification.delete")})]})]})}function K1({activeConv:e,wsStatus:t,isConnected:s,conversations:r,onOpenHistory:o,onOpenRemote:a,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:u,hiddenConversations:m=[],onShowConversation:h,onShowAllHidden:p,onResetPanelsToMain:g,inboxOpen:f,onInboxOpenChange:y,hiddenOpen:b,onHiddenOpenChange:k,onOpenNewSession:j,onOpenDashboardGuide:v,guideNudgeVisible:C=!1,actionShortcuts:x,notifications:S,notificationUnreadCount:w,onOpenNotification:_,onMarkNotificationRead:A,onMarkNotificationUnread:O,onDeleteNotification:L,onOpenGitDialog:R,onOpenMeshGraph:F}){const{t:N}=ve(),{ides:I,p2pStates:B={},usesP2P:T=!0}=An(),H=!!e&&St(e)&&!vt(e),q=!!e&&vt(e),J=c||(e?Kf(e)?"terminal":"chat":null),[K,M]=l.useState(!1),[D,P]=l.useState(!1),$=l.useRef(null),W=l.useRef(null),U=l.useRef(null),ae=I.filter(z=>z.type==="adhdev-daemon"),be=U1({wsStatus:t,isConnected:s,daemonCount:ae.length,p2pStates:B,usesP2P:T}),V=N(be.titleKey),we=be.subtitleKey?N(be.subtitleKey,be.subtitleParams):null,ce=be.tone==="connected"?"#22c55e":be.tone==="limited"?"#eab308":"#ef4444",de=be.tone==="connected"?"0 0 4px #22c55e80":be.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",ne=l.useMemo(()=>S.filter(z=>!z.readAt),[S]),ee=l.useMemo(()=>S.filter(z=>!!z.readAt),[S]),ue=l.useMemo(()=>ne.slice(0,9),[ne]),je=w;l.useEffect(()=>{if(!f)return;const z=ie=>{var Ne;(Ne=W.current)!=null&&Ne.contains(ie.target)||y(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[f,y]),l.useEffect(()=>{if(!b)return;const z=ie=>{var Ne;(Ne=U.current)!=null&&Ne.contains(ie.target)||k(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[b,k]),l.useEffect(()=>{if(!b&&!f)return;const z=ie=>{if(!ie.altKey)return;const Ne=ie.code.match(/^Digit([1-9])$/);if(!Ne)return;const Be=Number(Ne[1])-1,Le=b?m[Be]:void 0,Je=f?ue[Be]:void 0;if(!(!Le&&!Je)){if(ie.preventDefault(),ie.stopPropagation(),Le){h==null||h(Le),k(!1);return}Je&&(_(Je),y(!1))}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[m,b,f,ue,k,y,_,h]),l.useEffect(()=>{const z=m.length;if($.current===null){$.current=z;return}z>$.current&&P(!0),$.current=z},[m.length]);const X=()=>P(!1),G=z=>{if(!z)return;const ie=r.find(Ne=>Ne.tabKey===z);ie&&(u==null||u(ie))};return n.jsxs("div",{className:"dashboard-header",children:[n.jsx("div",{className:"flex items-center gap-3",children:n.jsx("div",{className:"header-title-block",children:n.jsxs("div",{className:"header-title-row",children:[n.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[n.jsx(Jn,{size:18}),n.jsx("span",{className:"header-title-desktop",children:N("dashboard.header.title")}),n.jsx("span",{className:"header-title-mobile",children:e?Ot(e):N("dashboard.header.title")}),n.jsx(tn,{content:we?`${V} · ${we}`:V,className:"ml-0.5",children:n.jsx("span",{role:"img","aria-label":V,"data-connection-tone":be.tone,className:"header-title-status-dot",style:{background:ce,boxShadow:de}})})]}),n.jsx("div",{className:"header-subtitle flex items-center",children:j&&n.jsx("button",{type:"button",onClick:j,className:"btn btn-secondary btn-sm ml-2",title:`${N("paneGroup.newSession")}${x!=null&&x.openNewSession?` (${x.openNewSession})`:""}`,"aria-label":N("paneGroup.newSession"),children:n.jsx(jo,{size:14})})})]})})}),n.jsxs("div",{className:"flex gap-2 items-center",children:[v&&n.jsxs("button",{type:"button",onClick:v,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:N("dashboard.header.guide"),"aria-label":N("dashboard.header.guideOpen"),children:[n.jsx("span",{className:"font-semibold leading-none",children:"?"}),C&&n.jsx("span",{children:N("dashboard.header.guideShort")})]}),e&&n.jsxs("div",{className:"dashboard-header-actions-group","data-testid":"dashboard-pane-toolbar",children:[n.jsx(Cd,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),H&&d&&J&&n.jsx(Ag,{mode:J,onChange:d,compact:!0}),(H||q)&&i&&n.jsx("button",{type:"button",onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:N(q?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),"aria-label":N(q?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),"data-testid":"dashboard-pane-stop",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:n.jsx(Bt,{size:14})}),n.jsx(Bg,{conversation:e,onOpenHistory:o,onOpenRemote:a?()=>a():void 0,onOpenGit:R,onOpenMeshGraph:F,iconSize:14})]}),n.jsxs("div",{className:"dashboard-header-inbox",ref:W,children:[n.jsxs("div",{className:`dashboard-header-hidden${K?" is-drop-target":""}${D?" hidden-spawn-flash":""}${(m??[]).some(er)?" hidden-generating-spin":""}`,onAnimationEnd:X,ref:U,onDragEnter:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),M(!0))},onDragOver:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),z.dataTransfer.dropEffect="move",M(!0))},onDragLeave:z=>{z.currentTarget.contains(z.relatedTarget)||M(!1)},onDrop:z=>{const ie=z.dataTransfer.getData("text/tab-key");z.preventDefault(),M(!1),G(ie)},children:[n.jsxs("button",{type:"button",onClick:()=>k(!b),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${N("dashboard.hidden.title")}${x!=null&&x.toggleHiddenTabs?` (${x.toggleHiddenTabs})`:""}. ${N("dashboard.hidden.dragHint")}`,children:[n.jsx(pi,{size:16}),m.length>0&&n.jsx("span",{className:`dashboard-header-hidden-badge${D?" hidden-badge-pop":""}`,children:m.length})]}),b&&n.jsxs("div",{className:"dashboard-header-hidden-popover",children:[n.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:N("dashboard.hidden.title")}),n.jsx(Fm,{value:x==null?void 0:x.toggleHiddenTabs})]}),n.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&n.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:N("dashboard.hidden.resetPanels")}),m.length>0&&p&&n.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{p(),k(!1)},children:N("dashboard.hidden.restoreAll")})]})]}),e&&u&&n.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>u(e),children:[n.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[n.jsx("span",{className:"dashboard-header-hidden-current-label",children:N("dashboard.hidden.hideCurrentTab")}),n.jsx(Fm,{value:x==null?void 0:x.hideCurrentTab})]}),n.jsx("span",{className:"dashboard-header-hidden-current-title",children:Ot(e)})]}),m.length>0?n.jsx("div",{className:"dashboard-header-hidden-list",children:m.map(z=>n.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(z),k(!1)},children:[n.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[er(z)&&n.jsx(ln,{size:12,thickness:2,color:"success",label:N("dashboard.header.generating")}),Ot(z)]}),n.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[m.indexOf(z)<9?n.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",m.indexOf(z)+1]}):null,Oo(z)]})]},z.tabKey))}):n.jsx("div",{className:"dashboard-header-inbox-empty",children:N("dashboard.hidden.empty")})]})]}),n.jsxs("button",{type:"button",onClick:()=>y(!f),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:N("dashboard.header.activityInbox"),children:[n.jsx(js,{size:16}),je>0&&n.jsx("span",{className:"dashboard-header-inbox-badge",children:je})]}),f&&n.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ne.length>0&&n.jsxs("div",{className:"dashboard-header-inbox-section",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title",children:N("dashboard.inbox.unread")}),ne.map(z=>n.jsx($m,{notification:z,shortcutIndex:ue.indexOf(z)>=0?ue.indexOf(z)+1:void 0,onOpen:()=>_(z),onMarkRead:()=>A(z.id),onMarkUnread:()=>O(z.id),onDelete:()=>L(z.id)},z.id))]}),ee.length>0&&n.jsxs("div",{className:"dashboard-header-inbox-section",children:[n.jsx("div",{className:"dashboard-header-inbox-section-title",children:N("dashboard.inbox.read")}),ee.map(z=>n.jsx($m,{notification:z,onOpen:()=>_(z),onMarkRead:()=>A(z.id),onMarkUnread:()=>O(z.id),onDelete:()=>L(z.id)},z.id))]}),S.length===0&&n.jsx("div",{className:"dashboard-header-inbox-empty",children:N("dashboard.inbox.empty")})]})]})]})]})}function yn(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function q1(e,t){return String(e||"")!==String(t||"")}function z1(e,t={}){const s=String(t.textQuery||"").trim().toLowerCase(),r=String(t.workspaceQuery||"").trim().toLowerCase(),o=String(t.modelQuery||"").trim().toLowerCase(),a=!!t.resumableOnly;return!s&&!r&&!o&&!a?e:e.filter(i=>!(a&&!i.canResume||s&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
50
|
-
`).includes(s)||r&&!String(i.workspace||"").toLowerCase().includes(r)||o&&!Cf(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
51
|
-
`).includes(o)))}function G1(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 Ld(e,t={}){return G1(z1(e,t),t.sortMode||"recent")}function Nc(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function Wg(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function V1(e){return e?e("launch.startFresh"):"Start fresh"}function Y1(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Q1(e){return e?e("launch.openSavedHistory"):"Open saved history"}function Cc(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function Ed(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function Ug(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function J1(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function X1(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function Ja(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 Xa(e,t){if(typeof e=="function"){const r=t;return e(r==="start-fresh"?"launch.startFreshReview":r==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const s=e;return s==="start-fresh"?"Review the provider and target folder before starting fresh.":s==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Za(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function ei(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function Kg(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function qg(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function Hm(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 Z1({activeConv:e,ides:t,isCreatingChat:s,isRefreshingHistory:r,savedSessions:o=[],isSavedSessionsLoading:a=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:u,onClose:m,onNewChat:h,onSwitchSession:p,onRefreshHistory:g,onResumeSavedSession:f}){var F;const{t:y}=ve("common"),b=t.find(N=>N.id===e.routeId),k=(b==null?void 0:b.chats)||[],j=(F=b==null?void 0:b.activeChat)==null?void 0:F.id,v=St(e)&&!vt(e),[C,x]=l.useState(()=>yn()),[S,w]=l.useState(null),_=c||C,A=String(d||"").trim(),O=N=>{if(u){u(N);return}x(N)},L=l.useMemo(()=>o.map(N=>{const I=String(N.workspace||"").trim();return N.canResume||I||!A?N:{...N,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,o]),R=l.useMemo(()=>Ld(L,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[L,_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.workspaceQuery]);return n.jsxs(n.Fragment,{children:[n.jsxs(Rr,{chrome:!1,onClose:m,closeOnEsc:!S,ariaLabel:v?Cc(y):y("historyModal.chatHistory"),overlayClassName:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4 bg-black/60 backdrop-blur-sm",surfaceClassName:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[n.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"m-0 text-lg font-extrabold",children:v?Cc(y):y("historyModal.chatHistory")}),n.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:v_(e)}),v&&n.jsx("div",{className:"text-2xs text-text-muted mt-1",children:Ed(y)})]}),n.jsx("button",{onClick:m,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:n.jsx(Bt,{size:16})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!v&&n.jsx("button",{onClick:h,disabled:s,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:y(s?"historyModal.creating":"historyModal.startNewChat")}),v?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[n.jsx("input",{type:"text",value:_.textQuery,onChange:N=>O({..._,textQuery:N.target.value}),placeholder:y("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:_.workspaceQuery,onChange:N=>O({..._,workspaceQuery:N.target.value}),placeholder:y("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:_.modelQuery,onChange:N=>O({..._,modelQuery:N.target.value}),placeholder:y("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:_.sortMode,onChange:N=>O({..._,sortMode:N.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[n.jsx("option",{value:"recent",children:y("historyModal.sortRecent")}),n.jsx("option",{value:"oldest",children:y("historyModal.sortOldest")}),n.jsx("option",{value:"messages",children:y("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:_.resumableOnly,onChange:N=>O({..._,resumableOnly:N.target.checked})}),y("historyModal.resumeReadyOnly")]})]}),R.map(N=>{const I=e.providerSessionId===N.providerSessionId,B=I||!N.canResume||!!i,T=N.workspaceFallbackSource==="selected-workspace";return n.jsxs("button",{type:"button",onClick:()=>{B||!f||w({kind:"saved",session:N})},disabled:B,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${I?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${B?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:`font-bold text-sm mb-1 truncate ${I?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:N.title||y("historyModal.untitledSession")}),n.jsx("div",{className:"text-2xs text-text-muted font-mono truncate",children:N.providerSessionId})]}),n.jsx("div",{className:"text-2xs text-text-muted shrink-0",children:Hm(N.lastMessageAt)})]}),n.jsx("div",{className:"mt-2 text-xs text-text-muted line-clamp-2",children:N.preview||y("historyModal.noSavedPreview")}),n.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-2xs text-text-muted",children:[n.jsxs("div",{className:"truncate",children:[N.workspace||y("historyModal.workspaceUnknown"),T?y("historyModal.selectedWorkspaceSuffix"):"",tr(N.summaryMetadata)?` · ${tr(N.summaryMetadata)}`:"",N.messageCount>0?` · ${y("historyModal.msgCount",{count:N.messageCount})}`:""]}),n.jsx("div",{className:"shrink-0",children:I?y("historyModal.statusActive"):N.canResume?T?y("historyModal.statusResumeSelectedWorkspace"):i===N.providerSessionId?y("historyModal.statusResuming"):y("historyModal.statusResume"):y("historyModal.statusMissingWorkspace")})]})]},N.id)})]}):k.map(N=>n.jsxs("div",{onClick:()=>{N.id!==j&&w({kind:"chat",id:N.id,title:N.title||y("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${j===N.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[n.jsx("div",{className:`font-bold text-sm mb-1 ${j===N.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:N.title||y("historyModal.untitledSession")}),n.jsxs("div",{className:"flex justify-between items-center",children:[n.jsxs("div",{className:"text-2xs text-text-muted font-mono",children:[N.id.substring(0,12),"..."]}),j===N.id&&n.jsx("span",{className:"text-3xs bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:y("historyModal.statusActive")})]})]},N.id)),(v&&!a&&R.length===0||!v&&k.length===0)&&n.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[n.jsx("div",{className:"text-3xl mb-3 opacity-60",children:n.jsx(ow,{size:32})}),n.jsx("div",{className:"text-xxs",children:v?o.length>0?y("historyModal.noMatchingHistory"):Ug(y):y("historyModal.noRecentChats")})]}),v&&a&&n.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:n.jsx("div",{className:"text-xxs",children:X1(y)})})]}),n.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:n.jsx("button",{onClick:g,disabled:r||a,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||a?y("historyModal.refreshing"):n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Or,{size:13})," ",v?J1(y):y("historyModal.refreshHistory")]})})})]}),S&&n.jsxs(Rr,{chrome:!1,onClose:()=>w(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:y("historyModal.confirmSwitchTitle")}),n.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:y("historyModal.confirmSwitchDescription",{target:S.kind==="chat"?S.title:S.session.title||y("historyModal.untitledSession")})}),S.kind==="saved"&&n.jsxs("div",{className:"mt-2 text-2xs text-text-muted font-mono truncate",children:[S.session.workspace||y("historyModal.workspaceUnknown"),S.session.lastMessageAt?` · ${Hm(S.session.lastMessageAt)}`:""]})]}),n.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[n.jsx("button",{onClick:()=>{const N=S;w(null),N.kind==="chat"?(p(e.routeId,N.id),m()):f&&f(N.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:y("historyModal.confirmSwitchAction")}),n.jsx("button",{onClick:()=>w(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:y("common.cancel")})]})]})]})}const Bm={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 eA({toast:e}){const{t}=ve(),{setToasts:s}=An(),[r,o]=l.useState(!1);return e.details?n.jsxs("div",{className:"mt-2","data-toast-details":"",children:[n.jsxs("button",{type:"button",className:"bg-transparent border-none p-0 text-xs font-semibold text-text-muted hover:text-text-primary cursor-pointer","aria-expanded":r,onClick:a=>{a.stopPropagation();const i=!r;o(i),i&&s(c=>c.map(d=>d.id===e.id?{...d,pinned:!0}:d))},children:[n.jsx("span",{className:"mr-1 inline-block transition-transform",style:{transform:r?"rotate(90deg)":void 0},"aria-hidden":!0,children:"▸"}),t("toast.details")]}),r&&n.jsx("pre",{className:"mt-1.5 max-h-40 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-border-subtle bg-bg-secondary/60 px-2.5 py-2 font-mono text-3xs leading-relaxed text-text-secondary",children:e.details})]}):null}function zg({toasts:e,onDismiss:t,onClickToast:s}){const{t:r}=ve();return n.jsx("div",{className:"fixed right-4 top-[calc(env(safe-area-inset-top,0px)+64px)] z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none sm:top-[calc(env(safe-area-inset-top,0px)+16px)]",children:e.map(o=>{const a=Bm[o.type]||Bm.info;return n.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=o.actions)!=null&&i.length||s&&s(o)},children:[n.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),n.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(o.id)},"aria-label":r("toast.dismiss"),children:n.jsx(Bt,{size:14})}),n.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[n.jsx("div",{className:"flex items-center gap-2 pr-8",children:n.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-3xs font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:r(a.labelKey)})}),n.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:o.message}),n.jsx(eA,{toast:o}),o.actions&&o.actions.length>0&&n.jsx("div",{className:"flex gap-2 mt-3",children:o.actions.map((i,c)=>n.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),t(o.id)},children:i.label},c))})]})]},o.id)})})}const tA=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function nA(e){const t=e.workspace||"";if(!t)return"";const s=t.split(/[/\\]/).filter(Boolean);return s.length>0?s[s.length-1]:t}function sA(e,t){return Gg(e)||t}function Gg(e){var o,a,i;const t=(a=(o=e.summaryMetadata)==null?void 0:o.items)==null?void 0:a.find(c=>(c==null?void 0:c.id)==="model"),s=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(s)return s;const r=(i=e.controlValues)==null?void 0:i.model;return typeof r=="string"&&r.trim()?r.trim():""}function rA(e){return Gg(e)||void 0}function oA(e){return e.sessionId||e.instanceId||e.agentType}function Vg(e=[]){const t={};for(const s of e)s.type==="adhdev-daemon"&&(t[s.id]=Tn(s,{fallbackId:s.id}));return t}function Yg(e,t={}){var r;const s=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:Kk(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[s]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Dd(e,t={}){return aA(e,Yg(e,t))}function aA(e,t={}){var p,g,f,y,b,k,j,v,C;const s=[],r=t.machineName,o=t.connectionState,a=nA(e),i=e.workspace||"",c=Qk(e.type,{agentName:e.cliName}),d=St(e)||vt(e)?c:Kt(e.type),u=sA(e,d),m=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var S,w,_;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,activeChatId:(S=x.activeChat)==null?void 0:S.id,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||Kt(x.providerType),model:rA(x),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((w=x.activeChat)==null?void 0:w.messages)||[],activeModal:((_=x.activeChat)==null?void 0:_.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,surfaceHidden:x.surfaceHidden,muted:x.muted,git:x.git,settings:x.settings,coordinator:x.coordinator,messageInput:x.messageInput}}):[],h=tA(e);if(h){const x=e.sessionId||e.instanceId,S=(p=e.settings)==null?void 0:p.meshCoordinatorFor,w=((g=e.settings)==null?void 0:g.meshNodeFor)||!((f=e.settings)!=null&&f.meshCoordinatorFor)&&((y=e.settings)==null?void 0:y.launchedByCoordinator),_=S?" (Coordinator)":w?" (Mesh Node)":"",A=c+_,O=(b=e.activeChat)==null?void 0:b.activeModal,L=O&&Array.isArray(O.buttons)&&O.buttons.length>0,R=Jk(e.activeChat,[{status:e.status,activeModal:(k=e.activeChat)==null?void 0:k.activeModal}],e.agents||[]),F=e.activeChat||{title:"",messages:[]};let N=F.title&&String(F.title).trim()?String(F.title).trim():"";const I=(j=e.activeChat)==null?void 0:j.id,B=e.chats;if(I&&Array.isArray(B)&&B.length>0){const P=B.find($=>$.id===I||$.id&&String($.id)===String(I));P!=null&&P.title&&String(P.title).trim()&&(N=String(P.title).trim())}const T=(St(e)||vt(e),e.type),H=(St(e)||vt(e))&&zu(N,A,T)?"":N,q=F.messages||[],J=typeof I=="string"?I.trim():"",K=(St(e)||vt(e))&&J===String(e.type||"").trim(),M=J&&!K?J:e.providerSessionId,D=e.coordinator||(typeof((v=e.settings)==null?void 0:v.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);s.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,historySessionId:M,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:St(e)&&e.mode||"chat",agentName:A,agentType:T,status:R,title:H,messages:q,resume:e.resume,hostIdeType:!St(e)&&!vt(e)?e.type:void 0,workspaceName:a,workspacePath:i,git:e.git,displayPrimary:a||H||(St(e)?e.mode==="chat"?A:`Terminal${_}`:A),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:L?O.buttons:void 0,modalMessage:L?O.message:void 0,streamSource:"native",tabKey:ol(x,e.id),machineName:r,connectionState:o,settings:e.settings,coordinator:D,messageInput:e.messageInput})}if(h&&(St(e)||vt(e)))return s;for(const x of m){const S=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,w=Xk(x),_=oA(x),A=`${e.id}:${_}`,O=x.title&&String(x.title).trim()||"",L=zu(O,x.agentName,x.agentType)?"":O,R=x.messages||[];if(!(x.transport==="cdp-webview"||!!x.sessionId||!!x.providerSessionId||R.length>0||S||!!L||!["idle","panel_hidden","disconnected","not_monitored"].includes(w)))continue;const N=x.coordinator||(typeof((C=x.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&x.settings.meshCoordinatorFor?{meshId:x.settings.meshCoordinatorFor,role:"coordinator"}:void 0);s.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,historySessionId:x.activeChatId||x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:w,title:L,messages:R,hostIdeType:e.type,workspaceName:a,workspacePath:i,git:x.git||e.git,displayPrimary:a||L||x.agentName||d,displaySecondary:x.model&&x.model.trim()?x.model.trim():`${d} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,modalButtons:S?x.activeModal.buttons:void 0,modalMessage:S?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:ol(x.sessionId||x.instanceId,A),machineName:r,connectionState:o,settings:x.settings,coordinator:N,messageInput:x.messageInput})}return s.length===0&&s.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:a,workspacePath:i,git:e.git,displayPrimary:a||d,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:ol(e.sessionId||e.instanceId,e.id),connectionState:o,settings:e.settings,messageInput:e.messageInput}),s}function Qg(e){return String(e.type||e.id||"").trim()}function ti(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function iA(e,t){const s=(t||"").trim();if(!s)return[];const r=(e||[]).find(o=>o.type===s);return ti(r==null?void 0:r.modelOptions)}function lA(e,t){const s=(t||"").trim();if(!s)return[];const r=(e||[]).find(o=>o.type===s);return ti(r==null?void 0:r.thinkingLevelOptions)}function Jg(e){const t=new Map;for(const s of e||[])s!=null&&s.type&&t.set(s.type,{models:ti(s.modelOptions),thinking:ti(s.thinkingLevelOptions)});return t}function cA(e){var t;return e.category!=="cli"||!Qg(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function Zn(e){var r;const t=new Set,s=[];for(const o of e||[]){if(!cA(o))continue;const a=Qg(o);if(!a||t.has(a))continue;t.add(a);const i=String(o.displayName||o.name||a),c=o.detectedPath||((r=o.lastDetection)==null?void 0:r.path)||null;s.push({type:a,label:i,icon:o.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(o.modelOptions)&&o.modelOptions.length?{modelOptions:o.modelOptions}:{},...Array.isArray(o.thinkingLevelOptions)&&o.thinkingLevelOptions.length?{thinkingLevelOptions:o.thinkingLevelOptions}:{}})}return s}function Fo(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],s=new Set,r=[];for(const o of t){const a=typeof o=="string"?o.trim():"";!a||s.has(a)||(s.add(a),r.push(a))}return r}function nr(e){return e.map(t=>t.type)}function dA(e,t){const s=Fo(e),r=t.trim();return!r||s.includes(r)?s:[...s,r]}function uA(e,t){return Fo(e).filter(s=>s!==t)}function Wm(e,t,s){const r=Fo(e),o=r.indexOf(t);if(o<0)return r;const a=r.filter(c=>c!==t);if(s==="top")return[t,...a];if(s==="bottom")return[...a,t];const i=s==="up"?Math.max(0,o-1):Math.min(a.length,o+1);return a.splice(i,0,t),a}const mA={"claude-cli":{monogram:"CL",hue:"#D97757"},"codex-cli":{monogram:"CX",hue:"#10A37F"},"gemini-cli":{monogram:"GM",hue:"#4285F4"},"kimi-cli":{monogram:"KM",hue:"#6366F1"},"antigravity-cli":{monogram:"AG",hue:"#8B5CF6"},"cursor-cli":{monogram:"CU",hue:"#64748B"},"opencode-cli":{monogram:"OC",hue:"#CA8A04"},"hermes-cli":{monogram:"HM",hue:"#14B8A6"},"grok-cli":{monogram:"GK",hue:"#475569"},antigravity:{monogram:"AG",hue:"#8B5CF6"},cursor:{monogram:"CU",hue:"#64748B"},kiro:{monogram:"KI",hue:"#F59E0B"},pearai:{monogram:"PA",hue:"#22C55E"},trae:{monogram:"TR",hue:"#EF4444"},vscode:{monogram:"VS",hue:"#3B82F6"},vscodium:{monogram:"VC",hue:"#2DD4BF"},windsurf:{monogram:"WS",hue:"#0EA5E9"},cline:{monogram:"CN",hue:"#0284C7"},"roo-code":{monogram:"RC",hue:"#F97316"}},Um=["#0EA5E9","#8B5CF6","#10B981","#F59E0B","#EF4444","#14B8A6","#6366F1","#EC4899","#84CC16","#F97316","#06B6D4","#A855F7"];function hA(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 pA(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 Li({type:e,label:t,size:s=16,className:r}){const o=(e||"").trim().toLowerCase(),a=(t==null?void 0:t.trim())||o;if(!a)return n.jsx(hw,{size:s,className:r});const i=mA[o],c=(i==null?void 0:i.monogram)??pA((t==null?void 0:t.trim())||o.replace(/-cli$/,"")),d=(i==null?void 0:i.hue)??Um[hA(o||a)%Um.length];return n.jsx("span",{"aria-hidden":!0,className:`inline-flex shrink-0 select-none items-center justify-center font-semibold ${r??""}`,style:{width:s,height:s,borderRadius:Math.max(4,Math.round(s*.3)),backgroundColor:`${d}21`,border:`1px solid ${d}4D`,color:d,fontSize:Math.max(7,Math.round(s*.42)),letterSpacing:"0.02em",lineHeight:1},children:c})}function Km({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 fA({value:e,availableProviders:t,onChange:s,disabled:r=!1,saveButton:o}){const{t:a}=ve("common"),[i,c]=l.useState(""),d=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),u=l.useMemo(()=>Fo(e),[e]),m=u.filter(g=>!d.has(g)).length,h=t.filter(g=>!u.includes(g.type)),p=()=>{i&&(s(dA(u,i)),c(""))};return n.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[n.jsx("div",{className:"flex flex-col gap-2",children:u.length===0?n.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-300",children:a("settings.providerPriority.emptyWarning")}):u.map((g,f)=>{const y=d.get(g),b=!!y;return n.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${b?"bg-bg-primary":"bg-bg-primary/40"}`,children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsxs("span",{className:"text-3xs font-semibold text-text-muted",children:["#",f+1]}),n.jsx(Li,{type:g,label:y==null?void 0:y.label,size:14}),n.jsx("span",{className:`font-mono text-xs ${b?"text-text-primary":"text-text-muted"}`,children:g}),b?n.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-4xs font-semibold text-green-400",children:a("settings.providerPriority.available")}):n.jsx(tn,{content:a("settings.providerPriority.keptUntilDetected"),children:n.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-4xs font-semibold text-amber-400",children:a("settings.providerPriority.notOnMachine")})})]}),y&&n.jsx("div",{className:"mt-1 text-3xs text-text-muted",children:`${y.label} · ${y.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(Wm(u,g,"up")),children:n.jsx(Km,{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(Wm(u,g,"down")),children:n.jsx(Km,{direction:"down"})}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>s(uA(u,g)),children:a("settings.providerPriority.remove")})]})]},g)})}),n.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[n.jsxs("label",{className:"flex-1 text-2xs text-text-secondary",children:[n.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:a("settings.providerPriority.addCliLabel")}),n.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:g=>c(g.target.value),disabled:r||h.length===0,children:[n.jsx("option",{value:"",children:h.length?a("settings.providerPriority.selectProvider"):a("settings.providerPriority.noMoreProviders")}),h.map(g=>n.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:r||!i,onClick:p,children:a("settings.providerPriority.addProvider")}),o]}),n.jsx("div",{className:"mt-2 flex items-center gap-1 text-2xs text-text-muted",children:n.jsx(dt,{content:[a("settings.providerPriority.orderHint"),m>0?a("settings.providerPriority.undetectedHint",{count:m}):""].filter(Boolean).join(`
|
|
52
|
-
|
|
53
|
-
`)})})]})}function gA(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function Xg(e,t){const s=gA(e);return{daemonId:s.daemonId,payload:{...t,...s.targetSessionId&&!t.targetSessionId?{targetSessionId:s.targetSessionId}:{}}}}const bA=[{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:"🏄"}],xA=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"grok-cli",name:"Grok",icon:"🛰️"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],yA=[{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 Zg({icon:e,title:t,subtitle:s,subtitleInline:r=!1,badge:o,actions:a,className:i}){return n.jsxs("div",{className:xt("dashboard-header",i),children:[n.jsxs("div",{children:[n.jsxs("h1",{className:"header-title flex items-center gap-2",children:[n.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,s&&!r&&n.jsx(dt,{content:s}),o&&n.jsxs("span",{className:"text-3xs font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[o.count!==void 0?o.count:""," ",o.text]})]}),s&&r&&n.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:s})]}),a&&n.jsx("div",{className:"flex gap-2",children:a})]})}function $o({icon:e,title:t,subtitle:s,subtitleInline:r,badge:o,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:d}){return n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsx(Zg,{icon:e,title:t,subtitle:s,subtitleInline:r,badge:o,actions:a}),n.jsx("div",{className:"page-content",children:n.jsx("div",{className:xt("mx-auto flex w-full flex-col gap-4",i,c),children:d})})]})}const _c="adhdev:themechange";function vA(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function wr(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Sr(e){return e==="system"?vA():e}function eb(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Ia(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(_c,{detail:{preference:e,theme:t}}))}function wA(){const e=wr(),t=Sr(e);eb(t),Ia(e,t)}function Ho(){const[e,t]=l.useState(wr),[s,r]=l.useState(()=>Sr(wr()));l.useEffect(()=>{eb(s)},[s]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const u=d.matches?"light":"dark";r(u),Ia("system",u)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const u=d.detail||{},m=u.preference,h=u.theme;t(m==="dark"||m==="light"||m==="system"?m:wr()),r(h==="dark"||h==="light"?h:Sr(wr()))},c=d=>{if(d.key!=="theme")return;const u=wr(),m=Sr(u);t(u),r(m)};return window.addEventListener(_c,i),window.addEventListener("storage",c),()=>{window.removeEventListener(_c,i),window.removeEventListener("storage",c)}},[]);const o=l.useCallback(i=>{const c=Sr(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}Ia(i,c)},[]),a=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=Sr(c);r(d);try{localStorage.setItem("theme",c)}catch{}return Ia(c,d),c})},[]);return{theme:s,preference:e,setPreference:o,cycleTheme:a,isDark:s==="dark"}}const qm={dark:"Dark",light:"Light",system:"System"};function SA({collapsed:e}){const{preference:t,cycleTheme:s}=Ho(),r=t==="dark"?n.jsx(Bp,{size:16}):t==="light"?n.jsx(Hp,{size:16}):n.jsx(Wp,{size:16});return n.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:s,title:`Theme: ${qm[t]} (click to cycle)`,children:[n.jsx("span",{className:"nav-icon",children:r}),!e&&n.jsx("span",{className:"text-xs",children:qm[t]})]})}const Ac="adhdev:langchange";function kA(){const e=at.language;return Ws(e)?e:yf()}function jA(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Ac,{detail:{language:e}}))}function NA(){const[e,t]=l.useState(kA);l.useEffect(()=>{const r=i=>{Ws(i)&&t(i)},o=i=>{const c=i.detail||{};Ws(c.language)&&t(c.language)},a=i=>{if(i.key!==uc)return;const c=i.newValue;Ws(c)&&c!==at.language&&(at.changeLanguage(c),mc(c))};return at.on("languageChanged",r),window.addEventListener(Ac,o),window.addEventListener("storage",a),()=>{at.off("languageChanged",r),window.removeEventListener(Ac,o),window.removeEventListener("storage",a)}},[]);const s=l.useCallback(r=>{if(Ws(r)){t(r);try{localStorage.setItem(uc,r)}catch{}at.changeLanguage(r),mc(r),jA(r)}},[]);return{language:e,setLanguage:s}}function CA({trigger:e,viewport:t,menu:s,variant:r,gap:o=6,margin:a=8}){const i=e.top-a,c=t.height-e.bottom-a,d=r==="sidebar";let u=d;d&&i<s.height&&c>i&&(u=!1),!d&&c<s.height&&i>c&&(u=!0);const m=u?i:c,h=Math.max(80,Math.min(s.height,m));let p;u?p=e.top-o-h:p=e.bottom+o,p=zm(p,a,Math.max(a,t.height-h-a));const g=zm(e.left,a,Math.max(a,t.width-s.width-a));return{top:p,left:g,maxHeight:h}}function zm(e,t,s){return Math.min(Math.max(e,t),s)}function _A({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 AA({collapsed:e,variant:t="sidebar"}){const{language:s,setLanguage:r}=NA(),{t:o}=ve("common"),[a,i]=l.useState(!1),[c,d]=l.useState(0),u=l.useRef(null),m=l.useRef(null),h=l.useRef(null),p=l.useId(),[g,f]=l.useState(null),y=l.useCallback(()=>{const R=m.current;if(!R)return;const F=R.getBoundingClientRect(),N=h.current,I=Math.max((N==null?void 0:N.offsetWidth)??0,168),B=(N==null?void 0:N.scrollHeight)??Rs.length*36+12;f(CA({trigger:{top:F.top,left:F.left,right:F.right,bottom:F.bottom,width:F.width,height:F.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:I,height:B},variant:t}))},[t]),b=Math.max(0,Rs.findIndex(R=>R.code===s)),k=Rs[b]??Rs[0],j=o("language.label",{defaultValue:"Language"}),v=o("language.select",{defaultValue:"Select language"}),C=R=>`${p}-opt-${R}`,x=l.useCallback(()=>{d(b),i(!0)},[b]),S=l.useCallback((R=!0)=>{var F;i(!1),R&&((F=m.current)==null||F.focus())},[]),w=l.useCallback(R=>{const F=Rs[R];F&&r(F.code),S()},[r,S]);l.useEffect(()=>{if(!a)return;const R=I=>{var B,T;return!!((B=u.current)!=null&&B.contains(I)||(T=h.current)!=null&&T.contains(I))},F=I=>{R(I.target)||i(!1)},N=I=>{R(I.target)||i(!1)};return document.addEventListener("pointerdown",F,!0),document.addEventListener("focusin",N,!0),()=>{document.removeEventListener("pointerdown",F,!0),document.removeEventListener("focusin",N,!0)}},[a]),l.useLayoutEffect(()=>{if(!a){f(null);return}y();const R=()=>y();return window.addEventListener("resize",R),window.addEventListener("scroll",R,!0),()=>{window.removeEventListener("resize",R),window.removeEventListener("scroll",R,!0)}},[a,y]),l.useEffect(()=>{var R;a&&g&&((R=h.current)==null||R.focus())},[a,g]);const _=R=>{const F=Rs.length-1;switch(R.key){case"ArrowDown":R.preventDefault(),d(N=>N>=F?0:N+1);break;case"ArrowUp":R.preventDefault(),d(N=>N<=0?F:N-1);break;case"Home":R.preventDefault(),d(0);break;case"End":R.preventDefault(),d(F);break;case"Enter":case" ":R.preventDefault(),w(c);break;case"Escape":R.preventDefault(),S();break;case"Tab":i(!1);break}},A=R=>{a||(R.key==="ArrowDown"||R.key==="ArrowUp"||R.key==="Enter"||R.key===" ")&&(R.preventDefault(),x())},O=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,L=t==="landing"||!e;return n.jsxs("div",{ref:u,className:"lang-switch",children:[n.jsxs("button",{ref:m,type:"button",className:O,"aria-haspopup":"listbox","aria-expanded":a,"aria-label":`${j}: ${k.label}`,title:`${j}: ${k.label}`,onClick:()=>a?S(!1):x(),onKeyDown:A,children:[n.jsx("span",{className:"nav-icon lang-switch-icon",children:n.jsx(Kp,{size:16})}),L&&n.jsx("span",{className:"lang-switch-label text-xs",children:k.label}),L&&n.jsx(_A,{open:a})]}),a&&typeof document<"u"&&Qn.createPortal(n.jsx("ul",{ref:h,role:"listbox",tabIndex:-1,"aria-label":v,"aria-activedescendant":C(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:_,children:Rs.map((R,F)=>{const N=R.code===k.code,I=F===c;return n.jsxs("li",{id:C(F),role:"option","aria-selected":N,className:`lang-switch-option${I?" is-active":""}${N?" is-selected":""}`,onMouseEnter:()=>d(F),onClick:()=>w(F),children:[n.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:N?n.jsx(Er,{size:14}):null}),n.jsx("span",{className:"lang-switch-option-label",children:R.label})]},R.code)})}),document.body)]})}const TA=[],IA=[];function pl(e,t){return e?typeof e=="function"?e(t):e:null}const MA=l.memo(function({renderState:t,brand:s,navItems:r,sidebarSections:o,footerItems:a,footerInfo:i,footerActions:c,closeMobileMenu:d}){const{t:u}=ve("common"),{collapsed:m,mobileMenuOpen:h}=t,p=f=>`nav-item${f.active?" active":""} cursor-pointer ${m?"justify-center py-2.5 px-0":""}${f.className?` ${f.className}`:""}`,g=f=>n.jsxs("div",{className:p(f),id:`nav-${f.id}`,onClick:()=>{f.onSelect(),d()},title:m?f.title??(typeof f.label=="string"?f.label:void 0):f.title,children:[n.jsx("span",{className:"nav-icon",children:f.icon}),!m&&f.label]},f.id);return n.jsxs("aside",{className:`sidebar ${h?"sidebar-open":""}`,children:[n.jsxs("div",{className:"sidebar-header",children:[n.jsx("div",{className:`sidebar-logo ${m?"justify-center gap-0":""}`,children:pl(s,t)}),n.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":u("app.closeMenu"),onClick:d,children:n.jsx(Bt,{size:16})})]}),n.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),o.map(f=>n.jsxs("div",{className:f.className??"border-t border-border-subtle pt-2 mt-2",children:[!m&&f.title?n.jsx("div",{className:"px-3 py-1 text-3xs text-text-muted uppercase tracking-widest",children:f.title}):null,f.items.map(g)]},f.key)),n.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(g),pl(i,t),n.jsx(SA,{collapsed:m}),n.jsx(AA,{collapsed:m}),pl(c,t)]})]})});function RA({children:e,brand:t,navItems:s,sidebarSections:r=TA,footerItems:o=IA,footerInfo:a,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const{t:u}=ve("common"),[m,h]=l.useState(!1),[p,g]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),f=l.useCallback(()=>h(!0),[]),y=l.useCallback(()=>h(!1),[]),b=l.useCallback(()=>{g(j=>{const v=!j;try{localStorage.setItem(d,v?"1":"0")}catch{}return v})},[d]),k=l.useMemo(()=>({collapsed:p,mobileMenuOpen:m,openMobileMenu:f,closeMobileMenu:y,toggleCollapsed:b}),[p,m,f,y,b]);return n.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${p?" sidebar-collapsed":""}`,children:[n.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":u("app.openMenu"),onClick:f,children:[n.jsx("span",{className:"mobile-menu-icon"}),n.jsx("span",{className:"mobile-menu-icon"}),n.jsx("span",{className:"mobile-menu-icon"})]}),m&&n.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":u("app.closeMenu"),onClick:y,onKeyDown:j=>j.key==="Escape"&&y()}),n.jsx(MA,{renderState:k,brand:t,navItems:s,sidebarSections:r,footerItems:o,footerInfo:a,footerActions:i,closeMobileMenu:y}),n.jsx("main",{className:"main-content relative",children:n.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function Nt({title:e,icon:t,description:s,descriptionInline:r=!1,accentColor:o,className:a,collapsible:i,defaultOpen:c=!0,badge:d,action:u,children:m}){const[h,p]=l.useState(c),g=i?h:!0,f=()=>p(k=>!k),y=n.jsxs(n.Fragment,{children:[t&&n.jsx("span",{children:t}),n.jsx("span",{children:e})]}),b=(e||s||u)&&n.jsxs("div",{className:xt("flex items-start justify-between gap-3",g&&"mb-4",i&&"cursor-pointer"),onClick:i?f:void 0,children:[n.jsxs("div",{className:"min-w-0",children:[e&&n.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[i?n.jsx("button",{type:"button",className:"inline-flex items-center gap-1.5 bg-transparent border-none p-0 text-left font-semibold text-text-primary cursor-pointer",onClick:k=>{k.stopPropagation(),f()},"aria-expanded":g,children:y}):y,s&&!r&&n.jsx("span",{onClick:k=>k.stopPropagation(),className:"inline-flex",children:n.jsx(dt,{content:s})}),d]}),s&&(r||!e)&&n.jsx("p",{className:"text-xxs text-text-muted mt-1",children:s})]}),u&&n.jsx("div",{className:"flex shrink-0 items-center gap-2",onClick:k=>k.stopPropagation(),children:u}),i&&n.jsx("span",{className:xt("mt-0.5 shrink-0 text-text-muted transition-transform select-none",g?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return n.jsxs("div",{className:xt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",o&&"border-l-[3px]",a),style:o?{borderLeftColor:o}:void 0,children:[b,g&&m]})}function Ei({icon:e,title:t,description:s,action:r,className:o,variant:a="default"}){return a==="compact"?n.jsxs("div",{className:xt("flex flex-wrap items-center justify-center gap-2 rounded-xl border border-dashed border-border-subtle px-4 py-5 text-center text-xs text-text-muted",o),children:[e&&n.jsx("span",{className:"flex items-center opacity-60","aria-hidden":!0,children:e}),n.jsx("span",{className:"font-medium text-text-secondary",children:t}),s?n.jsx(dt,{content:s}):null,r]}):n.jsxs("div",{className:xt("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 PA={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"},LA={error:an,warning:an,success:gi,info:Io};function zt({variant:e,children:t,onDismiss:s,className:r}){return n.jsxs("div",{className:xt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-xxs",PA[e],r),children:[n.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const o=LA[e];return n.jsx(o,{size:14})})(),n.jsx("span",{children:t})]}),s&&n.jsx("button",{onClick:s,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function qt({label:e,hint:t,hintInline:s=!1,children:r,className:o}){return n.jsxs("div",{className:xt("mb-5",o),children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1",children:[n.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider",children:e}),t&&!s&&n.jsx(dt,{content:t})]}),r,t&&s&&n.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function Dn(e){const{className:t,...s}=e;return n.jsx("input",{...s,className:xt("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 EA={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},os=l.forwardRef(function({variant:t="secondary",size:s="md",type:r,className:o,...a},i){return n.jsx("button",{ref:i,type:r??"button",className:xt("btn",EA[t],s==="sm"&&"btn-sm",o),...a})}),DA=l.forwardRef(function({options:t,children:s,className:r,...o},a){return n.jsx("select",{ref:a,className:xt("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 Od({tabs:e,activeKey:t,onSelect:s,variant:r="pill",ariaLabel:o,className:a,tabIdPrefix:i,panelIdPrefix:c}){const d=r==="underline",u=m=>{var y;if(m.key!=="ArrowRight"&&m.key!=="ArrowLeft"&&m.key!=="Home"&&m.key!=="End")return;const h=Math.max(0,e.findIndex(b=>b.key===t)),p=m.key==="Home"?0:m.key==="End"?e.length-1:(h+(m.key==="ArrowRight"?1:-1)+e.length)%e.length,g=e[p];if(!g)return;m.preventDefault(),s(g.key),(y=m.currentTarget.querySelectorAll('[role="tab"]')[p])==null||y.focus()};return n.jsx("div",{className:xt(d?"flex shrink-0 items-center gap-1 overflow-x-auto border-b border-border-subtle px-4 md:px-6 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden":"mb-5 inline-flex w-full flex-wrap items-center gap-1 rounded-xl border border-border-subtle bg-bg-secondary/60 p-1 sm:w-fit",a),role:"tablist","aria-label":o,onKeyDown:u,children:e.map(m=>{const h=m.key===t;return n.jsxs("button",{id:i?`${i}-${m.key}`:void 0,type:"button",role:"tab","aria-selected":h,"aria-controls":c?`${c}-${m.key}`:void 0,tabIndex:h?0:-1,className:xt(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 tb({tabs:e,defaultTabKey:t,activeKey:s,onTabChange:r,variant:o="pill",ariaLabel:a,className:i,tabListClassName:c,panelClassName:d,tabIdPrefix:u,unmountInactivePanels:m=!1}){var b;const[h,p]=l.useState(t??((b=e[0])==null?void 0:b.key)),g=s!==void 0,f=g?s:h,y=k=>{g||p(k),r==null||r(k)};return n.jsxs("div",{className:i,children:[n.jsx(Od,{tabs:e,activeKey:f,onSelect:y,variant:o,ariaLabel:a,className:c,tabIdPrefix:u}),e.map(k=>{const j=k.key===f;return m&&!j?null:n.jsx("div",{role:"tabpanel","aria-labelledby":u?`${u}-${k.key}`:void 0,className:j?xt("flex flex-col gap-4",d):"hidden",children:k.content},k.key)})]})}class OA extends l.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,s){console.error("[ErrorBoundary] Uncaught error:",t,s)}render(){return this.state.hasError?n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",background:"var(--bg-primary, #0a0e1a)",color:"var(--text-secondary, #c4c9d4)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:n.jsxs("div",{style:{textAlign:"center",maxWidth:420,padding:24},children:[n.jsx("div",{style:{display:"flex",justifyContent:"center",marginBottom:16},children:n.jsx(an,{size:44,className:"text-status-warning"})}),n.jsx("h2",{style:{margin:"0 0 8px",fontSize:18,fontWeight:600,color:"var(--text-primary, #eee)"},children:at.t("app.errorBoundary.title")}),n.jsx("p",{style:{margin:"0 0 20px",fontSize:14,opacity:.7,lineHeight:1.5},children:at.t("app.errorBoundary.description")}),n.jsx("button",{onClick:()=>window.location.reload(),style:{padding:"10px 24px",borderRadius:8,border:"1px solid rgba(99, 102, 241, 0.4)",background:"rgba(99, 102, 241, 0.1)",color:"#a5b4fc",fontSize:14,fontWeight:500,cursor:"pointer"},children:at.t("app.errorBoundary.reload")})]})}):this.props.children}}const FA={sm:"w-[34px] h-[19px]",md:"w-[40px] h-[22px]"},Gm={sm:{base:"w-[16px] h-[16px]",on:"translate-x-[15px]"},md:{base:"w-[19px] h-[19px]",on:"translate-x-[18px]"}};function Br({checked:e,onChange:t,disabled:s=!1,busy:r=!1,size:o="md",id:a,title:i,className:c,as:d="button",...u}){const m=s||r,h=f=>{f.stopPropagation(),!m&&t(!e)},p={id:a,title:i,role:"switch","aria-checked":e,"aria-disabled":s||void 0,"aria-busy":r||void 0,"aria-label":u["aria-label"],"aria-labelledby":u["aria-labelledby"],"aria-describedby":u["aria-describedby"],"data-state":e?"on":"off",className:xt("relative inline-flex shrink-0 items-center rounded-full border-none bg-transparent p-0 outline-none","focus-visible:ring-2 focus-visible:ring-accent/60 focus-visible:ring-offset-1 focus-visible:ring-offset-bg-primary",s?"cursor-not-allowed opacity-50":r?"cursor-wait opacity-60":"cursor-pointer",c)},g=n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,className:xt("inline-block rounded-full transition-colors duration-200 ease-in-out",FA[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:xt("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",Gm[o].base,e?Gm[o].on:"translate-x-0")})]});return d==="span"?n.jsx("span",{...p,tabIndex:s?-1:0,onClick:h,onKeyDown:f=>{(f.key===" "||f.key==="Enter")&&(f.preventDefault(),h(f))},children:g}):n.jsx("button",{type:"button",...p,disabled:s,onClick:h,children:g})}function Di({onClick:e,refreshing:t=!1,disabled:s=!1,label:r,size:o=14,showLabel:a=!1,className:i}){const{t:c}=ve("common"),d=r??c("common.refresh");return n.jsxs("button",{type:"button",onClick:e,disabled:s||t,"aria-label":a?void 0:d,"aria-busy":t||void 0,title:d,className:xt("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(Or,{size:o,className:t?"animate-spin":void 0}),a&&n.jsx("span",{children:d})]})}const C5={recentFailures:0};function _5(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 $A={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 HA(e,t){const s=$A[(e||"unknown").toLowerCase()];return s?t(s):String(e)}function A5(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 nb(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return{bucket:"other",normalized:""};const r=mi(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 T5(e){const{bucket:t,normalized:s}=nb(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 I5(e,t){const{bucket:s,normalized:r}=nb(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 M5(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 BA(e){return e.startedAt||e.createdAt||null}function R5(e){const t=BA(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 P5(e,t){const s=(d,u,m)=>t?t(d,m):u,r=e.git;if(!r)return e.gitProbePending?s("mesh.drift.probePending","Git probe pending"):s("mesh.drift.noGit","No git probe");const o=(r.staged??0)+(r.modified??0)+(r.untracked??0)+(r.deleted??0)+(r.renamed??0),a=[];r.branch&&a.push(r.branch),r.upstream&&r.upstreamStatus!=="fresh"&&a.push(s("mesh.drift.upstreamUnverified","upstream unverified")),r.upstreamStatus==="fresh"&&((r.ahead??0)>0||(r.behind??0)>0)&&a.push(`↑${r.ahead??0}/↓${r.behind??0}`),o>0&&a.push(s("mesh.drift.changed",`${o} dirty`,{count:o}));const i=(r.submodules??[]).filter(d=>d.dirty),c=(r.submodules??[]).filter(d=>d.outOfSync||d.error);return i.length>0&&a.push(s("mesh.drift.submoduleChanged",`${i.length} submodule dirty`,{count:i.length})),c.length>0&&a.push(s("mesh.drift.submoduleOutOfSync",`${c.length} submodule drift`,{count:c.length})),r.hasConflicts&&a.push(s("mesh.drift.conflicts","conflicts")),a.join(" · ")||s("mesh.drift.clean","Clean")}function WA(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)=>Pr(o.provider).localeCompare(Pr(a.provider)))}function sb(e){return sy(e.daemonId)||e.machineId||e.nodeId}function L5(e){var s;const t=new Map;for(const r of e.nodes){const o=r.nodeFacts,a=sb(r);if(!a)continue;let i=t.get(a);i||(i={machineKey:a,label:"",nodeCount:0,hasReported:!1,quota:[]},t.set(a,i)),i.nodeCount+=1;const c=typeof(o==null?void 0:o.reportedAt)=="number"&&Number.isFinite(o.reportedAt)?o.reportedAt:void 0,d=c!==void 0&&(i.reportedAt===void 0||c>i.reportedAt);d&&(i.reportedAt=c),o&&(i.hasReported=!0);const u=WA(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=qA(e,r.machineKey);return[...t.values()].sort((r,o)=>r.label.localeCompare(o.label)||r.machineKey.localeCompare(o.machineKey))}function UA(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 KA(e){const t=UA(e),s=typeof e.machineLabel=="string"?e.machineLabel.trim():"";return!s||s===t?t:`${t} · ${s}`}function qA(e,t){var i,c,d;const s=[],r=[],o=[];for(const u of e.nodes){if(sb(u)!==t)continue;const h=(i=u.nodeFacts)==null?void 0:i.machineNickname;typeof h=="string"&&h.trim()&&s.push(h.trim());const p=u.machine,g=(p!=null&&p.sameMachine?p.coordinatorHostname:void 0)??((d=(c=p==null?void 0:p.identityEvidence)==null?void 0:c.find(y=>((y==null?void 0:y.label)==="hostname"||(y==null?void 0:y.label)==="machineName")&&typeof y.value=="string"&&y.value.trim()))==null?void 0:d.value);typeof g=="string"&&g.trim()&&r.push(g.trim().replace(/\.local$/i,""));const f=typeof u.machineLabel=="string"?u.machineLabel.trim():"";f&&f!==u.nodeId&&f!==u.daemonId&&f!==t&&o.push(f)}const a=u=>u.length===0?void 0:[...u].sort((m,h)=>m.localeCompare(h))[0];return a(s)??a(r)??a(o)??rb(t)}function rb(e){const t=e.replace(/^(daemon_|standalone_)/,"");return t.length<=20?t:`${t.slice(0,17)}…`}const E5={first_eligible:"In order",fitness:"Smart",least_loaded:"Smart",round_robin:"Smart (round-robin)",priority_only:"Smart (priority)"};function D5(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 O5(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 F5(e){return e.assignedNodeId||e.targetNodeId||null}function Vm(e){return e?e.slice(0,7):null}function zA(e,t){var a,i,c;const s=Vm((a=e==null?void 0:e.git)==null?void 0:a.headCommit),r=((c=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:c.trim())||"";if(s||r)return[s,r].filter(Boolean).join(" · ");const o=t[0];return o?[Vm(o.commit),o.message].filter(Boolean).join(" · "):null}function $5(e,t){const s=zA(e,t);return s||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function H5(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 B5(e){var o,a,i,c,d,u,m;const t=((o=e.selectedSessionEntry)==null?void 0:o.session.workspace)||((a=e.selectedSessionEntry)==null?void 0:a.workspace)||((c=(i=e.selectedNodeStatus)==null?void 0:i.git)==null?void 0:c.workspace)||((d=e.selectedNodeStatus)==null?void 0:d.workspace)||null;if(!t||!e.selectedSessionEntry&&!e.selectedNodeStatus)return null;const s=((u=e.selectedNodeStatus)==null?void 0:u.nodeId)||((m=e.selectedSessionEntry)==null?void 0:m.nodeId)||null,r=e.coordinatorDaemonId||null;return r&&s?{daemonId:r,workspace:t,nodeId:s}:null}function W5(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 U5(e,t){return t?e.nodes.find(s=>s.id===t)??null:null}function K5(e){var t,s,r,o;return[e.meshId,e.refreshedAt,e.nodes.length,((s=(t=e.queue)==null?void 0:t.summary)==null?void 0:s.active)??"",((o=(r=e.ledger)==null?void 0:r.summary)==null?void 0:o.recentFailures)??"",...e.nodes.map(a=>{var i,c,d,u,m,h,p,g,f,y,b,k,j,v,C,x,S,w,_,A,O,L;return[a.nodeId,a.daemonId??"",a.machineId??"",a.machineLabel,a.machineStatus??"",((i=a.connection)==null?void 0:i.state)??"",((c=a.connection)==null?void 0:c.transport)??"",((d=a.connection)==null?void 0:d.source)??"",a.health,a.gitProbePending?1:0,((u=a.git)==null?void 0:u.branch)??"",((m=a.git)==null?void 0:m.upstream)??"",((h=a.git)==null?void 0:h.upstreamStatus)??"",((p=a.git)==null?void 0:p.ahead)??"",((g=a.git)==null?void 0:g.behind)??"",((f=a.git)==null?void 0:f.headCommit)??"",((y=a.git)==null?void 0:y.staged)??"",((b=a.git)==null?void 0:b.modified)??"",((k=a.git)==null?void 0:k.untracked)??"",((j=a.git)==null?void 0:j.deleted)??"",((v=a.git)==null?void 0:v.renamed)??"",(C=a.git)!=null&&C.hasConflicts?1:0,((x=a.git)==null?void 0:x.lastCheckedAt)??"",((S=a.activeSessions)==null?void 0:S.join(","))??"",((w=a.activeSessionDetails)==null?void 0:w.length)??"",((_=a.activeSessionDetails)==null?void 0:_.map(R=>[R.sessionId,R.providerType??"",R.state??"",R.chatStatus??"",R.lifecycle??"",R.role??"",R.isSelfCoordinator?1:0,R.statusNote??"",R.startedAt??"",R.createdAt??""].join("/")).join(","))??"",((A=a.providers)==null?void 0:A.join(","))??"",((O=a.providerPriority)==null?void 0:O.join(","))??"",a.error??"",(((L=a.git)==null?void 0:L.submodules)??[]).map(R=>[R.path,R.commit,R.dirty?1:0,R.outOfSync?1:0,R.error??""].join("/")).join(",")].join("|")})].join("::")}function q5(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function ns({label:e,description:t,descriptionInline:s=!1,checked:r,disabled:o,onChange:a,extra:i}){const c=l.useId();return n.jsxs("div",{className:`flex justify-between items-center ${o?"opacity-60":""}`,children:[n.jsxs("div",{className:"pr-4 min-w-0",children:[n.jsxs("div",{className:"font-medium text-sm flex items-center gap-1",children:[n.jsx("span",{id:c,children:e}),t&&!s&&n.jsx(dt,{content:t})]}),t&&s&&n.jsx("div",{className:"text-2xs text-text-muted mt-0.5",children:t})]}),n.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,n.jsx(Br,{checked:r,disabled:o,onChange:a,"aria-labelledby":c})]})]})}const GA=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli"];function VA({daemonId:e,knownCliTypes:t=GA,embedded:s=!1}){const{t:r}=ve("common"),{sendCommand:o}=_t(),[a,i]=l.useState({}),[c,d]=l.useState({}),[u,m]=l.useState(!0),[h,p]=l.useState(null),[g,f]=l.useState(null),[y,b]=l.useState(""),[k,j]=l.useState(!1),v=s||k,[C,x]=l.useState(null),S=l.useCallback(async()=>{if(e){m(!0),f(null);try{const N=await o(e,"list_coordinator_prompts",{}),I=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(I!=null&&I.success)){f((I==null?void 0:I.error)||r("settings.coordinatorPrompts.loadFailed"));return}const B=I.entries||{};b(I.dir||"");const T={};for(const H of t)T[H]=B[H]||{override:"",append:""};for(const H of Object.keys(B))T[H]||(T[H]=B[H]);i(T),d(JSON.parse(JSON.stringify(T)))}catch(N){f((N==null?void 0:N.message)||String(N))}finally{m(!1)}}},[o,e,t,r]);l.useEffect(()=>{S()},[S]);const w=l.useCallback(async(N,I)=>{var B;if(e){p(`${N}:${I}`),f(null);try{const T=((B=a[N])==null?void 0:B[I])||"",H=await o(e,"write_coordinator_prompt",{key:N,kind:I,content:T}),q=H!=null&&H.result&&typeof H.result=="object"?H.result:H;if(!(q!=null&&q.success)){f((q==null?void 0:q.error)||r("settings.coordinatorPrompts.saveFailed"));return}d(J=>({...J,[N]:{...J[N]||{override:"",append:""},[I]:T}}))}catch(T){f((T==null?void 0:T.message)||String(T))}finally{p(null)}}},[o,e,a,r]),_=l.useMemo(()=>(N,I)=>{var B,T;return(((B=a[N])==null?void 0:B[I])||"")!==(((T=c[N])==null?void 0:T[I])||"")},[a,c]),A=l.useCallback(async N=>{_(N,"override")&&await w(N,"override"),_(N,"append")&&await w(N,"append")},[_,w]),O=l.useCallback(N=>{const I=c[N];return!!(I&&((I.override||"").trim()||(I.append||"").trim()))},[c]),L=Object.keys(a),R=L.filter(O),F=C&&a[C]?C:L[0];return e?v?n.jsxs("div",{className:"flex flex-col gap-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1 text-xs text-text-muted",children:[n.jsx("span",{className:"truncate font-mono text-2xs",children:y||"~/.adhdev/coordinator-prompts/"}),n.jsx(dt,{content:n.jsxs("span",{children:[r("settings.coordinatorPrompts.intro")," ",y||"~/.adhdev/coordinator-prompts/",`
|
|
54
|
-
|
|
55
|
-
`,n.jsx($a,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:n.jsx("strong",{})}})," ",n.jsx($a,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:n.jsx("strong",{})}}),`
|
|
56
|
-
|
|
57
|
-
`,r("settings.coordinatorPrompts.resetHint")," ",r("settings.coordinatorPrompts.placeholdersHint")," ",n.jsxs("span",{className:"font-mono",children:["{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}"]}),"…"]})})]}),!s&&n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>j(!1),children:r("settings.coordinatorPrompts.collapseLabel")})]}),g&&n.jsx("div",{className:"text-xs text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:g}),u&&n.jsx("div",{className:"text-xs text-text-muted",children:r("settings.coordinatorPrompts.loading")}),L.length>0&&n.jsx(tb,{activeKey:F,onTabChange:x,ariaLabel:r("settings.coordinatorPrompts.tabsAriaLabel"),tabIdPrefix:"coordinator-prompt-tab",tabs:L.map(N=>{const I=a[N],B=_(N,"override")||_(N,"append");return{key:N,label:n.jsxs("span",{className:"flex items-center gap-1.5 font-mono text-xs",children:[N,O(N)&&n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-accent-primary",title:r("settings.coordinatorPrompts.customizedBadge")}),B&&n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:"var(--status-warning)"},"aria-hidden":!0})]}),content:n.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[n.jsx("label",{className:"block text-2xs uppercase tracking-wide text-text-muted mb-1",children:r("settings.coordinatorPrompts.overrideLabel")}),n.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-xs font-mono text-text-primary",rows:4,value:I.override,onChange:T=>i(H=>({...H,[N]:{...H[N],override:T.target.value}})),placeholder:r("settings.coordinatorPrompts.overridePlaceholder"),disabled:h===`${N}:override`}),n.jsx("div",{className:"mb-3"}),n.jsx("label",{className:"block text-2xs uppercase tracking-wide text-text-muted mb-1",children:r("settings.coordinatorPrompts.appendLabel")}),n.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-xs font-mono text-text-primary",rows:3,value:I.append,onChange:T=>i(H=>({...H,[N]:{...H[N],append:T.target.value}})),placeholder:r("settings.coordinatorPrompts.appendPlaceholder"),disabled:h===`${N}:append`}),n.jsx("div",{className:"mt-2 flex justify-end",children:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm","data-testid":"coordinator-prompt-save",onClick:()=>void A(N),disabled:!!(h!=null&&h.startsWith(`${N}:`))||!B,children:h!=null&&h.startsWith(`${N}:`)?r("settings.coordinatorPrompts.saving"):r(B?"settings.coordinatorPrompts.save":"settings.coordinatorPrompts.saved")})})]})}})})]}):n.jsxs("div",{className:"flex flex-col gap-3",children:[g&&n.jsx("div",{className:"text-xs text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:g}),n.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[n.jsx("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5 text-xs text-text-muted",children:u?n.jsx("span",{children:r("settings.coordinatorPrompts.loading")}):R.length===0?n.jsx("span",{children:r("settings.coordinatorPrompts.collapsedNone")}):n.jsxs(n.Fragment,{children:[n.jsxs("span",{children:[r("settings.coordinatorPrompts.customizedBadge"),":"]}),R.map(N=>n.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-accent-primary/10 px-1.5 py-0.5 font-mono text-2xs text-accent-primary",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-accent-primary","aria-hidden":!0}),N]},N))]})}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>j(!0),children:r("settings.coordinatorPrompts.expandLabel")})]})]}):n.jsx("div",{className:"text-xs text-text-muted",children:r("settings.coordinatorPrompts.connectDaemon")})}const YA=[{id:"dark",labelKey:"settings.appearance.modeDark",icon:Bp},{id:"light",labelKey:"settings.appearance.modeLight",icon:Hp},{id:"system",labelKey:"settings.appearance.modeSystem",icon:Wp}];function QA(){const{preference:e,setPreference:t}=Ho(),{t:s}=ve("common");return n.jsx("div",{className:"flex gap-2",children:YA.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 JA(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 XA(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function fl(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Ym(e){const{r:t,g:s,b:r}=XA(e);return .2126*fl(t)+.7152*fl(s)+.0722*fl(r)}function Qm(e,t){const s=Ym(e),r=Ym(t),o=Math.max(s,r),a=Math.min(s,r);return(o+.05)/(a+.05)}function ob(e){const t=JA(e);if(!t)return"#111827";const s="#111827",r="#ffffff";return Qm(t,s)>=Qm(t,r)?s:r}const Tc={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},Ic={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},ZA=[{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"}}}],ab="adhdev-chat-theme",ib="adhdev-chat-theme-custom";function Ma(){if(typeof window>"u")return"ember";try{return localStorage.getItem(ab)||"ember"}catch{return"ember"}}function En(e){try{const t=localStorage.getItem(ib);if(t){const s=JSON.parse(t);return{...e==="dark"?Tc:Ic,...s[e]}}}catch{}return e==="dark"?Tc:Ic}function la(e,t){try{localStorage.setItem(ib,JSON.stringify({dark:e,light:t}))}catch{}}function jn(e,t){const s=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16);return`rgba(${s}, ${r}, ${o}, ${t})`}function ni(e,t){const s=Math.min(255,parseInt(e.slice(1,3),16)+t),r=Math.min(255,parseInt(e.slice(3,5),16)+t),o=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${s.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}const eT={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function vo(e,t){var o;const s=(o=eT[e])==null?void 0:o[t];if(!s)return;const r=document.documentElement;r.style.setProperty("--accent-primary",s),r.style.setProperty("--accent-primary-light",ni(s,24)),r.style.setProperty("--accent-on-primary",ob(s)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${s}, ${ni(s,18)})`),r.style.setProperty("--border-accent",jn(s,.35)),r.style.setProperty("--nav-active-bg",jn(s,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${s}, 0 0 12px ${jn(s,.06)}`)}function Vs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",jn(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",jn(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",jn(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",jn(e.borderSubtle,.5)),t.style.setProperty("--border-default",jn(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",ni(e.accentColor,30)),t.style.setProperty("--accent-on-primary",ob(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${ni(e.accentColor,40)})`),t.style.setProperty("--border-accent",jn(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",jn(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${jn(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${jn(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Fd(){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 tT(e){try{localStorage.setItem(ab,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Ys()?"dark":"light";Vs(En(t))}else Fd(),vo(e,Ys()?"dark":"light")}function nT(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Ma();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Ys()?"dark":"light";Vs(En(t))}else Fd(),vo(e,Ys()?"dark":"light")}function Ys(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Xt({label:e,value:t,onChange:s}){return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[n.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[n.jsx("input",{type:"color",value:t,onChange:r=>s(r.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),n.jsx("input",{type:"text",value:t,onChange:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&s(r.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Zr({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 sT({dark:e,onColorsChange:t}){const{t:s}=ve("common"),r=e?"dark":"light",[o,a]=l.useState(()=>En(r));l.useEffect(()=>{a(En(r))},[r]);const i=l.useCallback((c,d)=>{a(u=>{const m={...u,[c]:d},p=En(r==="dark"?"light":"dark");return r==="dark"?la(m,p):la(p,m),Vs(m),t(m),m})},[r,t]);return n.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[n.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[s("settings.theme.customEditorTitle"),n.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:s(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[n.jsxs("div",{children:[n.jsxs(Zr,{title:s("settings.theme.sectionAppBackground"),children:[n.jsx(Xt,{label:s("settings.theme.colorBackground"),value:o.bgPrimary,onChange:c=>i("bgPrimary",c)}),n.jsx(Xt,{label:s("settings.theme.colorSurface"),value:o.bgSecondary,onChange:c=>i("bgSecondary",c)}),n.jsx(Xt,{label:s("settings.theme.colorCard"),value:o.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),n.jsxs(Zr,{title:s("settings.theme.sectionAppText"),children:[n.jsx(Xt,{label:s("settings.theme.colorPrimary"),value:o.textPrimary,onChange:c=>i("textPrimary",c)}),n.jsx(Xt,{label:s("settings.theme.colorSecondary"),value:o.textSecondary,onChange:c=>i("textSecondary",c)}),n.jsx(Xt,{label:s("settings.theme.colorMuted"),value:o.textMuted,onChange:c=>i("textMuted",c)})]}),n.jsxs(Zr,{title:s("settings.theme.sectionBordersAccent"),children:[n.jsx(Xt,{label:s("settings.theme.colorBorderSubtle"),value:o.borderSubtle,onChange:c=>i("borderSubtle",c)}),n.jsx(Xt,{label:s("settings.theme.colorBorderDefault"),value:o.borderDefault,onChange:c=>i("borderDefault",c)}),n.jsx(Xt,{label:s("settings.theme.colorAccent"),value:o.accentColor,onChange:c=>i("accentColor",c)})]})]}),n.jsxs("div",{children:[n.jsxs(Zr,{title:s("settings.theme.sectionChatBubbles"),children:[n.jsx(Xt,{label:s("settings.theme.colorUserBubble"),value:o.userBubble,onChange:c=>i("userBubble",c)}),n.jsx(Xt,{label:s("settings.theme.colorUserText"),value:o.userText,onChange:c=>i("userText",c)}),n.jsx(Xt,{label:s("settings.theme.colorAgentBubble"),value:o.assistantBubble,onChange:c=>i("assistantBubble",c)}),n.jsx(Xt,{label:s("settings.theme.colorAgentText"),value:o.assistantText,onChange:c=>i("assistantText",c)})]}),n.jsxs(Zr,{title:s("settings.theme.sectionChatLayout"),children:[n.jsx(Xt,{label:s("settings.theme.colorChatBg"),value:o.containerBg,onChange:c=>i("containerBg",c)}),n.jsx(Xt,{label:s("settings.theme.colorSendButton"),value:o.sendButton,onChange:c=>i("sendButton",c)}),n.jsx(Xt,{label:s("settings.theme.colorInputBorder"),value:o.inputBorder,onChange:c=>i("inputBorder",c)}),n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[n.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:s("settings.theme.labelBubbleRadius")}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[n.jsx("input",{type:"range",min:4,max:24,value:o.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),n.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[o.bubbleRadius,"px"]})]})]})]})]})]}),n.jsx("button",{onClick:()=>{const c=e?Tc:Ic,u=En(e?"light":"dark");e?la(c,u):la(u,c),a(c),Vs(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:s("settings.theme.resetToDefaults")})]})}function rT(){const{t:e}=ve("common"),[t,s]=l.useState(Ma),[r,o]=l.useState(!0),[a,i]=l.useState(()=>En("dark"));l.useEffect(()=>{o(Ys());const u=new MutationObserver(()=>{const p=Ys();o(p);const g=Ma();g==="custom"?Vs(En(p?"dark":"light")):vo(g,p?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),h=()=>{const p=Ys();o(p);const g=Ma();g==="custom"?Vs(En(p?"dark":"light")):vo(g,p?"dark":"light")};return m.addEventListener("change",h),()=>{u.disconnect(),m.removeEventListener("change",h)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Vs(En(r?"dark":"light")):(Fd(),vo(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(En(r?"dark":"light"))},[r]);const c=u=>{s(u),tT(u)},d=[...ZA,{id:"custom",name:"Custom",description:e("settings.theme.presetCustomDescription"),preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return n.jsxs("div",{children:[n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(u=>{const m=t===u.id,h=r?u.preview.dark:u.preview.light,p=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return n.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[n.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:h.containerBg},children:[n.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-3xs max-w-[75%]",style:{background:h.assistantBubble,border:h.assistantBorder,color:h.textColor},children:e("settings.theme.helloHelp")}),n.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-3xs max-w-[75%]",style:{background:h.userBubble,color:p},children:e("settings.theme.fixBug")}),n.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-3xs max-w-[75%]",style:{background:h.assistantBubble,border:h.assistantBorder,color:h.textColor},children:e("settings.theme.onIt")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[m&&n.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?e("settings.theme.customLabel"):u.name}),n.jsx("div",{className:"text-3xs text-text-muted",children:u.id==="custom"?u.description:e(`settings.theme.preset.${u.id}`,{defaultValue:u.description})})]})]})]},u.id)})}),t==="custom"&&n.jsx(sT,{dark:r,onColorsChange:u=>i(u)})]})}const $d="adhdev_mobileDashboardMode_v1",Mc="adhdev:mobile-dashboard-mode-change";function Hd(){try{return localStorage.getItem($d)==="workspace"?"workspace":"chat"}catch{return"chat"}}function oT(e){if(typeof window>"u")return()=>{};const t=o=>{e(o??Hd())},s=o=>{const a=o.detail;t(a)},r=o=>{o.key&&o.key!==$d||t()};return window.addEventListener(Mc,s),window.addEventListener("storage",r),()=>{window.removeEventListener(Mc,s),window.removeEventListener("storage",r)}}function aT(e){try{localStorage.setItem($d,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Mc,{detail:e}))}function iT(){const{t:e}=ve("common"),[t,s]=l.useState(!0);return l.useEffect(()=>{s(Hd()==="chat")},[]),n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Jn,{size:15})," ",e("settings.mobileMode.label")]}),description:e(t?"settings.mobileMode.descriptionChat":"settings.mobileMode.descriptionWorkspace"),checked:t,onChange:r=>{s(r),aT(r?"chat":"workspace")},extra:n.jsx("span",{className:"text-2xs text-text-muted",children:e(t?"settings.mobileMode.chatMode":"settings.mobileMode.workspaceMode")})})}function lT(){const{t:e}=ve("common"),[t,s]=l.useState(()=>qs());return l.useEffect(()=>dd(s),[]),n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx($p,{size:15})," ",e("settings.chatActivity.rowLabel")]}),description:e(t?"settings.chatActivity.descriptionOn":"settings.chatActivity.descriptionOff"),checked:t,onChange:r=>{s(r),Xp(r)}})}function cT({fontsSlot:e}){const{t}=ve("common");return n.jsxs("div",{className:"flex flex-col gap-5",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:t("settings.appearance.modeLabel")}),n.jsx(QA,{})]}),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(rT,{})]}),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(lT,{})]}),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(iT,{})]})]})}function dT({children:e,fallback:t=null}){const[s,r]=l.useState($k);return l.useEffect(()=>{if(s)return;let o=!0;return Hk().then(()=>{o&&r(!0)}),()=>{o=!1}},[s]),n.jsx(n.Fragment,{children:s?e:t})}const gl=new Map,Jm=new Map;function uT(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 mT(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 lb(){const{sendCommand:e}=_t(),{injectEntries:t,getIdes:s}=Ar();return l.useCallback(async(r,o)=>{if(!r)return;const a=(o==null?void 0:o.minFreshMs)??QN,i=Jm.get(r)||0;if(!(o!=null&&o.force)&&i>0&&Date.now()-i<a)return;const c=gl.get(r);if(c)return c;const d=(async()=>{const u=await e(r,"get_machine_runtime_stats"),m=uT(u);if(!m)return;const h=s().find(g=>g.id===r),p=mT(h,r,m.machine,m.timestamp||Date.now());t([p]),Jm.set(r,Date.now())})().finally(()=>{gl.delete(r)});return gl.set(r,d),d},[s,t,e])}function hT(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 pT(e,t){const{sendData:s}=_t(),{injectEntries:r,getIdes:o}=Ar(),a=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!s)return;const i=a?a.split("|"):[];if(i.length===0)return;const c=i.map(d=>_n.subscribe({sendData:s},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},m=>{const h=o().find(g=>g.id===d),p=hT(h,d,m);r([p])}));return()=>{c.forEach(d=>d())}},[a,o,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,s])}function fT(e,t){const{sendData:s}=_t(),[r,o]=l.useState(null),[a,i]=l.useState(!1);return l.useEffect(()=>{if(!e){o(null),i(!1);return}if(!(t!=null&&t.enabled)||!s){i(!1);return}o(null),i(!0);let c=null;const d=_n.subscribe({sendData:s},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},u=>{c&&(clearTimeout(c),c=null),o(u.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},ZN):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,s]),{diagnostics:r,loading:a,applyDiagnostics:o}}function Xm(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function cb(e){const{sendData:t,isConnected:s}=_t(),[r,o]=l.useState({}),a=l.useRef(null);return l.useEffect(()=>{const i=Xm(e);if(!i||!e.sessionId||!t){o({});return}const c=_n.subscribe({sendData:t},i,{type:"subscribe",topic:"session.modal",key:`daemon:${i}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},d=>{o({status:d.status,modalMessage:d.modalMessage,modalButtons:d.modalButtons}),Xs.record({interactionId:d.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:d.status,modalButtonCount:Array.isArray(d.modalButtons)?d.modalButtons.length:0}})});return c.initialSendAccepted||o({}),a.current=()=>{_n.resubscribeForDaemon(i,{sendData:t}),Xs.record({kind:"dashboard.session_modal_resync",topic:"session.modal",payload:{sessionId:e.sessionId}})},()=>{a.current=null,c()}},[e.daemonId,e.routeId,e.sessionId,t]),l.useEffect(()=>{const i=Xm(e);if(!i||!e.sessionId||!t)return;const c=()=>{var p;return(p=a.current)==null?void 0:p.call(a)},d=()=>{typeof document>"u"||document.visibilityState==="visible"&&c()},u=p=>{p.persisted&&c()};typeof document<"u"&&document.addEventListener("visibilitychange",d),typeof window<"u"&&window.addEventListener("pageshow",u);let m=s?s(i):!0;const h=()=>{if(!s)return;const p=s(i);p&&!m&&c(),m=p};return typeof document<"u"&&document.addEventListener("visibilitychange",h),typeof window<"u"&&window.addEventListener("online",h),()=>{typeof document<"u"&&(document.removeEventListener("visibilitychange",d),document.removeEventListener("visibilitychange",h)),typeof window<"u"&&(window.removeEventListener("pageshow",u),window.removeEventListener("online",h))}},[e.daemonId,e.routeId,e.sessionId,t,s]),r}function db(e){return e instanceof Error?e.message:String(e||"")}function gT(e){const t=db(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 bT(e){const t=db(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function ub({conversation:e,mode:t,ides:s,sendDaemonCommand:r,setCliViewModeOverrides:o}){if(!e||!St(e)||vt(e))return;const a=$r(e);if(a===t)return;const i=e.sessionId;i&&o(c=>({...c,[i]:t}));try{await r(as(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Vn(e),mode:t})}catch(c){const d=bT(c);i&&!d&&o(u=>{const m={...u};return a===yT(s,i)?delete m[i]:m[i]=a,m}),gT(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function Zm(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 xT(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=Zm(o,t),i=Array.isArray(o.childSessions)?o.childSessions.map(d=>Zm(d,t)):o.childSessions,c=i!==o.childSessions;return a!==o||c?(s=!0,{...a,...c?{childSessions:i}:{}}):o});return s?r:e}function yT(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 vT({visibleConversations:e,clearedTabs:t,setClearedTabs:s,setActionLogs:r,isConversationMuted:o}){l.useEffect(()=>{If()},[]);const a=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:jg(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 pj(a),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{s(d=>{const u=Date.now(),m={};for(const[h,p]of Object.entries(d))u-p<5e3&&(m[h]=p);return Object.keys(m).length===Object.keys(d).length?d:m})},5500);return()=>clearTimeout(c)},[t,s]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;r(d=>{const u=d.filter(m=>m.timestamp>c).slice(-100);return u.length===d.length?d:u})},6e4);return()=>clearInterval(i)},[r]),null}function eh(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Qs(e){const t=[...e.messages].reverse().find(o=>!(o!=null&&o._localId))||e.messages[e.messages.length-1],s=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=eh(t==null?void 0:t.receivedAt)||eh(t==null?void 0:t.timestamp)||0;return Math.max(s,r)}function Rc(e,t=0){return Qs(e)||e.lastUpdated||t||0}function mb(e){return Qs(e)||e.lastUpdated||0}function hb(e,t,s=mb){const r=s(t)-s(e);if(r!==0)return r;const o=(e.machineName||"").localeCompare(t.machineName||"");if(o!==0)return o;const a=e.displayPrimary.localeCompare(t.displayPrimary);if(a!==0)return a;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function Pc(e){var s;const t=vn(e.status,{activeModal:(s=e.modalButtons)!=null&&s.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function wT(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Pc(e)&&!e.title.trim()}function ST(e){return e.length===0?null:[...e].sort((t,s)=>{const r=Number(Pc(s))-Number(Pc(t));if(r!==0)return r;const o=s.messages.length-t.messages.length;return o!==0?o:hb(t,s)})[0]||null}function On(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=ST(o);return r?a&&wT(r)?a:r:a||s[0]||null}function kT(e){const t=e.filter(o=>o.type!=="adhdev-daemon"),s=new Set;for(const o of t){if(!hc(o))continue;const a=jf(o);a&&s.add(a)}const r=new Map;for(const o of t){const a=Uk(o,s),i=r.get(a);if(!i){r.set(a,o);continue}const c=h=>(h.workspace?1:0)+(h.activeChat?1:0)+(h.lastMessagePreview?1:0),d=c(i),u=c(o),m=u>d||u===d&&(o.timestamp||0)>(i.timestamp||0)?o:i;r.set(a,jT(m,m===o?i:o))}return Array.from(r.values())}function jT(e,t){const s=hc(t),r=hc(e);if(!s&&!r)return e;const o=r?s?void 0:t:e,a=r?e:s?t:void 0,i=o&&String(o.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=a==null?void 0:a.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!r&&{settings:{...d,...e.settings??{}}}}}function bl(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 NT(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 th(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],s=t[t.length-1],r=s?NT(_r(s.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((s==null?void 0:s.id)||""),String((s==null?void 0:s.index)??""),String((s==null?void 0:s.receivedAt)??(s==null?void 0:s.timestamp)??""),r].join(":")}function CT(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||""),th(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||""),th(s.activeChat)].join(":"))].join("|")}function _T(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 AT(e,t){const s=new Map;for(const r of e){const o=t.get(r.routeId)||r;for(const a of bo({routeId:r.routeId}))s.set(a,o);for(const a of bo({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))s.set(a,r.streamSource==="native"?o:r);for(const a of bo({tabKey:r.tabKey}))s.set(a,r)}return s}function TT(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function IT(e){const t=TT(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const s=String(t.role||""),r=_r(t.content).slice(0,240);return`${e.messages.length}:${s}:${r}`}function MT({ides:e,connectionStates:t,clearedTabs:s}){const r=l.useMemo(()=>kT(e),[e]),o=l.useMemo(()=>ff(e),[e]),a=l.useMemo(()=>Vg(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),u=l.useRef(new Map),m=l.useRef(new Map),h=l.useMemo(()=>{const C=new Map,x=[];for(const A of r){const{connectionState:O="new",machineName:L}=Yg(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),R=CT(A),F=u.current.get(A.id);if(F&&F.ide===A&&F.sourceSignature===R&&F.connectionState===O&&F.machineName===L){C.set(A.id,F),x.push(...F.conversations);continue}const N=Dd(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),I={ide:A,sourceSignature:R,connectionState:O,machineName:L,conversations:N};C.set(A.id,I),x.push(...N)}u.current=C;const S=new Map,w=A=>{const O=IT(A),L=m.current.get(A.tabKey);if(L&&L.signature===O)return S.set(A.tabKey,L),L.timestamp;const R={signature:O,timestamp:mb(A)||(L==null?void 0:L.timestamp)||0};return S.set(A.tabKey,R),R.timestamp},_=[...x].sort((A,O)=>hb(A,O,w));return m.current=S,_},[r,t,a]),p=l.useMemo(()=>{const C=_T(h,s);return bl(i.current,C)?i.current:(i.current=C,C)},[h,s]),g=l.useMemo(()=>{const C=new Map,x=Array.from(new Set(p.map(S=>S.routeId)));for(const S of x){const w=On(p,S);w&&C.set(S,w)}return C},[p]),f=l.useMemo(()=>{const C=new Map;for(const x of p){const S=g.get(x.routeId),w=x.streamSource==="native"&&S?S:x;for(const _ of bo({providerSessionId:x.providerSessionId,sessionId:x.sessionId,tabKey:x.tabKey}))C.set(_,w)}return C},[p,g]),y=l.useMemo(()=>AT(p,g),[p,g]),b=l.useCallback(C=>{if(C)return f.get(C)},[f]),k=l.useCallback(C=>{if(C)return y.get(C)},[y]),j=l.useMemo(()=>{const C=p.filter(x=>!Ns(x,o).surfaceHidden);return bl(c.current,C)?c.current:(c.current=C,C)},[p,o]),v=l.useMemo(()=>{const C=j.map(x=>x.tabKey);return bl(d.current,C)?d.current:(d.current=C,C)},[j]);return{chatIdes:r,conversations:p,visibleConversations:j,visibleTabKeys:v,resolveConversationBySessionId:b,resolveConversationByTarget:k}}function RT({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:s,setSearchParams:r}){const o=l.useMemo(()=>{var c;return e||!t?null:((c=s(t))==null?void 0:c.tabKey)??null},[e,s,t]),a=l.useMemo(()=>{var c;return!e||!t?null:((c=s(t))==null?void 0:c.tabKey)??null},[e,s,t]),i=l.useCallback(()=>{t&&r(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[r,t]);return{requestedDesktopTabKey:o,requestedMobileTabKey:a,consumeRequestedActiveTab:i}}function PT({ides:e,sendDaemonCommand:t,setToasts:s,resolveConversationByTarget:r,hydrateInteractivePrompt:o}){l.useEffect(()=>{ct.setIdes(e)},[e]),l.useEffect(()=>{ct.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),l.useEffect(()=>{ct.setHydrateInteractivePrompt(o)},[o]),l.useEffect(()=>{const a=ct.onToast(i=>{s(d=>d.some(m=>m.message===i.message&&i.timestamp-m.timestamp<3e3)?d:[...d.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions,details:i.details}]);const c=i.duration||5e3;setTimeout(()=>s(d=>d.filter(u=>u.id!==i.id||u.pinned)),c)});return()=>{a()}},[s]),l.useEffect(()=>{const a=Of.on("status_event",i=>{ct.handleRawEvent(i,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var i;const a=c=>{var b;const d=c.data;if((d==null?void 0:d.type)!=="notification_action"||typeof d.action!="string"||!d.action.startsWith("approval_")||!(d.daemonId||d.targetSessionId||d.targetKey))return;const u=d.targetSessionId||d.targetKey||d.daemonId,m=r(u),h=(m==null?void 0:m.routeId)||d.daemonId;if(!h)return;const p=Number(d.buttonIndex),g=d.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[p])||"Approve",f=String(g).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),y=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(f);t(h,"resolve_action",{action:y?"approve":"reject",button:g,...Number.isFinite(p)&&{buttonIndex:p},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...d.targetSessionId&&{targetSessionId:d.targetSessionId}}).catch(k=>console.error("[SW Action] approval failed:",k))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[r,t])}const LT="adhdev_dashboardLayout_v1",ET="adhdev_dashboardDockview_v1",DT="adhdev_dashboardDockviewHiddenRestore_v1",eo={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Bd(e,t){try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}}function OT(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function pb(e){return`${LT}:${e}`}function FT(e){const t=pb(e);return Bd(t,null)}function $T(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=pb(e);if(s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function fb(e){return`${ET}:${e}`}function HT(e){const t=fb(e);return Bd(t,null)}function BT(e,t){try{const s=fb(e);if(!t){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function gb(e){return`${DT}:${e}`}function WT(e){const t=gb(e);return Bd(t,{})}function UT(e,t){try{const s=gb(e);if(Object.keys(t).length===0){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function KT(){return{groupAssignments:[...eo.groupAssignments],focusedGroup:eo.focusedGroup,groupActiveTabIds:{...eo.groupActiveTabIds},groupTabOrders:{...eo.groupTabOrders},groupSizes:[...eo.groupSizes]}}function qT(e,t){return e?e.length===t.length&&e.every((s,r)=>s===t[r]):t.length===0}function zT(){const[e]=l.useState(()=>OT(typeof window<"u"?window.innerWidth:1280)),[t,s]=l.useState(()=>new Map),[r,o]=l.useState(0),[a,i]=l.useState({}),[c,d]=l.useState({}),[u,m]=l.useState([]),[h,p]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,f]=l.useState(!1),y=l.useCallback(()=>{if(g)return;const A=FT(e)??KT();s(new Map(A.groupAssignments)),o(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),m(A.groupSizes),f(!0)},[g,e]);l.useEffect(()=>{g&&$T(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:a,groupTabOrders:c,groupSizes:u})},[g,e,t,r,a,c,u]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),O=L=>p(L.matches);return A.addEventListener("change",O),()=>A.removeEventListener("change",O)},[]);const b=l.useCallback(A=>{s(A)},[]),k=l.useCallback(A=>{o(A)},[]),j=l.useCallback(A=>{i(A)},[]),v=l.useCallback(A=>{d(A)},[]),C=l.useCallback(A=>{m(A)},[]),x=l.useCallback(A=>{k(A)},[k]),S=l.useCallback((A,O)=>{i(L=>(L[A]??null)===(O??null)?L:{...L,[A]:O})},[]),w=l.useCallback((A,O)=>{d(L=>{const R=L[A];return qT(R,O)?L:{...L,[A]:O}})},[]),_=l.useCallback((A,O)=>{const L=O.get(A)??0;return S(L,A),x(L),L},[x,S]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:b,focusedGroup:r,updateFocusedGroup:k,focusGroup:x,groupActiveTabIds:a,updateGroupActiveTabIds:j,setGroupActiveTab:S,groupTabOrders:c,updateGroupTabOrders:v,setGroupTabOrder:w,groupSizes:u,updateGroupSizes:C,isMobile:h,hasHydratedStoredLayout:g,hydrateStoredLayout:y,focusConversationTab:_}}function GT(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const s=e[0],r=ji(t);return typeof(s==null?void 0:s.id)=="string"&&r.includes(s.id)}function VT({urlActiveTab:e,conversations:t,resolveConversationBySessionId:s,normalizedGroupAssignments:r,hasHydratedStoredLayout:o,hydrateStoredLayout:a,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:u,isRefreshingHistory:m,ides:h,handleRefreshHistory:p}){const g=l.useRef(!1),f=l.useRef(!1),y=l.useRef(null),b=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!o){a();return}const k=s(e);k&&(i(k.tabKey,r),g.current=!0,f.current=!0,y.current!=null&&(window.clearTimeout(y.current),y.current=null),c(j=>{const v=new URLSearchParams(j);return v.delete("activeTab"),v},{replace:!0}))},[e,t,s,r,o,a,i,c]),l.useEffect(()=>{if(!(f.current||o)&&t.length!==0){if(!e){a(),f.current=!0;return}if(g.current){f.current=!0;return}if(y.current==null)return y.current=window.setTimeout(()=>{y.current=null,!(f.current||o)&&(a(),f.current=!0)},1500),()=>{y.current!=null&&(window.clearTimeout(y.current),y.current=null)}}},[e,t.length,o,a]),l.useEffect(()=>{if(!d){b.current=!1;return}if(!u||b.current||m)return;const k=h.find(j=>j.id===u.routeId);k&&(!k.chats||k.chats.length===0||GT(k.chats,u))&&(b.current=!0,p())},[d,u,m,h,p])}function xl(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=ji(t);return typeof(s==null?void 0:s.id)=="string"&&r.includes(s.id)}function bb({sendDaemonCommand:e,activeConv:t,chats:s,updateRouteChats:r,setToasts:o,setClearedTabs:a}){const[i,c]=l.useState(!1),[d,u]=l.useState(!1),m=l.useCallback(async f=>{try{await e("standalone","launch_ide",{ideType:f,enableCdp:!0})}catch(y){console.error("Launch failed",y)}},[e]),h=l.useCallback(async(f,y)=>{try{const b=f||(t==null?void 0:t.daemonId)||"",k=await e(b,"switch_chat",{id:y,sessionId:y,...ks(t)}),j=k==null?void 0:k.result;if((k==null?void 0:k.success)===!0||j==="switched"||j==="switched-by-title")return;j===!1||j==="not_found"?yr(o,"⚠️ Session tab not found — try refreshing history"):typeof j=="string"&&j.startsWith("error:")?yr(o,`⚠️ Switch error: ${j}`):yr(o,"⚠️ Session switch failed")}catch(b){console.error("Switch failed",b),yr(o,`❌ Switch failed: ${b.message||"connection error"}`)}},[t,e,o]),p=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const f=vs(t);await e(f,"new_chat",{...ks(t)}),IC(f,t.sessionId,ji(t)[0]),a(y=>({...y,[t.tabKey]:Date.now()}))}catch(f){console.error("New chat failed",f)}finally{c(!1)}}},[t,i,e,a]),g=l.useCallback(async()=>{var f,y;if(!(!t||d)){u(!0);try{const b=vs(t),k=async()=>e(b,"list_chats",{forceExpand:!0,...ks(t)});let j=await k(),v=(j==null?void 0:j.chats)||((f=j==null?void 0:j.result)==null?void 0:f.chats);xl(v,t)&&(await new Promise(C=>setTimeout(C,450)),j=await k(),v=(j==null?void 0:j.chats)||((y=j==null?void 0:j.result)==null?void 0:y.chats)),j!=null&&j.success&&Array.isArray(v)&&(r(t.routeId,v),xl(v,t)&&!xl(s,t)&&yr(o,"⚠️ History dialog did not fully open — try once more"))}catch(b){console.error("Refresh history failed",b)}finally{u(!1)}}},[t,s,d,e,r,o]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:m,handleSwitchSession:h,handleNewChat:p,handleRefreshHistory:g}}function YT(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 QT(e,t){return e.length!==t.length?!1:e.every((s,r)=>s===t[r])}function nh(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 ca(e,t){const s=new Set(t),r=t.length>0?[0]:[];for(const[i,c]of e)!s.has(i)||c<=0||r.includes(c)||r.push(c);r.sort((i,c)=>i-c);const o={};r.forEach((i,c)=>{o[i]=c}),r.length===0&&(o[0]=0);const a=new Map;for(const[i,c]of e){if(!s.has(i)||c<=0)continue;const d=o[c];typeof d=="number"&&d>0&&a.set(i,d)}return{assignments:a,groupCount:Math.max(1,r.length),mapping:o,usedGroups:r}}function sh(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 JT(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 XT(e,t,s){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),o=r.length===t.length?r:Array(s).fill(100/s),a=o.reduce((i,c)=>i+c,0);return a>0?o.map(i=>i/a*100):Array(s).fill(100/s)}function rh(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 oh(e){return Array(e).fill(100/e)}function ZT({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:s,updateGroupActiveTabIds:r,updateGroupTabOrders:o,groupSizes:a,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:u}){const m=l.useRef(null),h=l.useMemo(()=>ca(e,u),[e,u]),p=h.assignments,g=l.useMemo(()=>c?1:h.groupCount,[h.groupCount,c]),f=g>1,y=l.useCallback((x,S)=>{t(w=>{const _=new Map(ca(w,u).assignments);return S===0?_.delete(x):_.set(x,S),_}),r(w=>({...w,[S]:x})),s(S)},[t,u,r,s]),b=l.useCallback(x=>{t(S=>{const w=ca(S,u).assignments,_=new Map;for(const[A,O]of w)O!==x&&(O>x?_.set(A,O-1):_.set(A,O));return _}),i(S=>{if(S.length<=1)return[];const w=[...S];w.splice(x,1);const _=w.reduce((A,O)=>A+O,0);return _>0?w.map(A=>A/_*100):[]}),s(0)},[t,u,i,s]),k=l.useCallback((x,S)=>{S.preventDefault();const w=m.current;if(!w)return;const _=S.clientX,A=w.offsetWidth,O=a.length===g?[...a]:oh(g),L=F=>{const I=(F.clientX-_)/A*100,B=[...O];B[x]=Math.max(15,O[x]+I),B[x+1]=Math.max(15,O[x+1]-I),i(B)},R=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",R),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",R)},[a,g,i]),j=l.useCallback((x,S,w)=>{if(g>=4)return;const _=w==="left"?S:S+1;t(A=>{const O=ca(A,u).assignments,L=new Map;for(const R of d){const F=O.get(R.tabKey)??0,N=F>=_?F+1:F;N>0&&L.set(R.tabKey,N)}return _>0&&L.set(x,_),L}),i(A=>{const O=A.length===g?[...A]:oh(g),L=O[S]??100/g,R=Math.max(15,L/2),F=Math.max(15,L/2),N=[...O];N[S]=R,N.splice(_,0,F);const I=N.reduce((B,T)=>B+T,0);return N.map(B=>B/I*100)}),r(A=>{const O=rh(A,_);return O[_]=x,O}),o(A=>{const O=rh(A,_);return O[_]=[x],O}),s(_)},[g,t,u,d,i,r,o,s]);l.useEffect(()=>{YT(e,p)||t(p)},[e,p,t]),l.useEffect(()=>{const{mapping:x,usedGroups:S}=h;r(w=>{const _=sh(w,x);return nh(w,_)?w:_}),o(w=>{const _=sh(w,x);return nh(w,_)?w:_}),s(w=>{const _=c?0:JT(w,S,x);return w===_?w:_}),i(w=>{const _=c?[]:XT(w,S,h.groupCount);return QT(w,_)?w:_})},[h,c,r,o,s,i]);const v=l.useMemo(()=>{const x=Array.from({length:g},()=>[]);for(const S of d){const w=p.get(S.tabKey)??0,_=Math.min(w,g-1);x[_].push(S)}return x},[d,p,g]),C=l.useCallback(()=>{t(new Map),s(0)},[t,s]);return{containerRef:m,normalizedGroupAssignments:p,numGroups:g,isSplitMode:f,groupedConvs:v,moveTabToGroup:y,closeGroup:b,handleResizeStart:k,splitTabRelative:j,clearAllSplits:C}}function yl(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 e2(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 ho(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Wd(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},s=yl(t.channel)||yl(e.updateChannel)||yl(e.releaseChannel)||void 0,r=e2(t.npmTag)||(s==="preview"?"next":s==="stable"?"latest":void 0),o=ho(t.targetVersion)||ho(e.serverVersion)||void 0,a=ho(t.minVersion)||void 0,i=ho(t.updateCommand)||(s?"adhdev update":void 0);return{...s?{channel:s}:{},...r?{npmTag:r}:{},...o?{targetVersion:o}:{},...a?{minVersion:a}:{},...i?{updateCommand:i}:{}}}function Hs(e,t=null){return Wd(e).targetVersion||t}function t2(e){return Wd(e).channel||null}function Ud(e){return!e||!Wd(e).channel?null:{}}function xb(e,t={},s){const r=ho(t.targetVersion);return r?s?s("machine.commandCenter.updateToVersion",{version:r}):`Update to v${r}`:t.fallback?t.fallback:s?t.required?s("machine.daemonUpdate.updateNow"):s("machine.daemonUpdate.upgrade"):t.required?"Update now":"Upgrade"}function si(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const s=t[4]??null;let r=null;if(s){const o=s.match(/(?:^|\.)(\d+)$/);r=o?Number(o[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:s!==null}}function ah(e){var t;return((t=si(e))==null?void 0:t.base)??null}function yb(e,t){const s=si(e),r=si(t);if(!s||!r)return e!==t;for(let o=0;o<3;o+=1){if(s.base[o]<r.base[o])return!0;if(s.base[o]>r.base[o])return!1}return s.isPrerelease&&r.isPrerelease?s.prereleaseNumber===null||r.prereleaseNumber===null?!1:s.prereleaseNumber<r.prereleaseNumber:!1}function Kd(e,t){const s=e.version||null;return!s||!t||e.versionMismatch===!0&&!si(t)?!1:yb(s,t)}function Ra(e,t){if(e.versionUpdateRequired===!0)return!0;const s=e.version||null;if(!s||!t||!yb(s,t))return!1;const r=ah(s),o=ah(t);return!r||!o?!1:r[0]!==o[0]||r[1]!==o[1]}function n2({ides:e,sendDaemonCommand:t}){const s="1.0.59",r=l.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:Kd(h,Hs(h,s))).sort((h,p)=>Number(Ra(p,Hs(p,s)))-Number(Ra(h,Hs(h,s)))),[s,e]),o=l.useMemo(()=>r.some(h=>Ra(h,Hs(h,s))),[s,r]),a=l.useMemo(()=>r.map(h=>Hs(h,s)).find(h=>typeof h=="string"&&h.trim().length>0)||s,[s,r]),[i,c]=l.useState(!1),[d,u]=l.useState({}),m=l.useCallback(async h=>{var f,y;const p=e.find(b=>b.id===h);if(!p)return;u(b=>({...b,[h]:"upgrading"}));const g=Ud(p);if(!g){u(b=>({...b,[h]:"error"}));return}try{const b=await t(h,"daemon_upgrade",g);(f=b==null?void 0:b.result)!=null&&f.upgraded||(y=b==null?void 0:b.result)!=null&&y.success?u(k=>({...k,[h]:"done"})):u(k=>({...k,[h]:"error"}))}catch{u(b=>({...b,[h]:"error"}))}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:o,targetVersion:a,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:m}}const vb=80;function Pa(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function s2(e){return{...e,createdAt:Pa(e.createdAt),updatedAt:Pa(e.updatedAt,e.createdAt),lastEventAt:Pa(e.lastEventAt,e.updatedAt||e.createdAt)}}function r2(e){const t=kf(e);return t==="unknown:"?e.id:t}function o2(e){return[e.type,Sf(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function a2(e,t=vb){const s=new Map;for(const r of e){if(r.deletedAt)continue;const o=r2(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 i2(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=Si(o,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=Pa(o.lastMessageAt||(a==null?void 0:a.lastUpdated)||o.lastUpdated,s),u=o2({type:c,sessionId:o.sessionId,providerSessionId:o.providerSessionId,tabKey:o.tabKey,lastMessageHash:o.lastMessageHash,lastMessageAt:o.lastMessageAt,lastUpdated:(a==null?void 0:a.lastUpdated)||o.lastUpdated});r.push(s2({id:u,dedupKey:u,type:c,routeId:o.routeId,machineId:o.daemonId||o.routeId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,tabKey:o.tabKey,title:zf(o),preview:kN(o),createdAt:d,updatedAt:d,lastEventAt:d}))}return a2(r)}function l2(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function c2(e){const{conversations:t,liveSessionInboxState:s,maxItems:r=vb}=e,o=l.useMemo(()=>i2(t,s).slice(0,Math.max(0,r)),[t,s,r]),a=l.useMemo(()=>l2(o),[o]);return{notifications:o,unreadCount:a}}function d2({notifications:e,sendDaemonCommand:t}){const s=l.useCallback(a=>{const i=e.find(d=>d.id===a),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),r=l.useCallback(a=>{const i=e.find(c=>c.id===a);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),o=l.useCallback(a=>{const i=e.find(c=>c.id===a);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:s,handleMarkDashboardNotificationUnread:r,handleDeleteDashboardNotification:o}}function qd(...e){const t=new Set,s=[],r=o=>{const a=typeof o=="string"?o.trim():"";if(!a)return;const i=a.toLowerCase();t.has(i)||(t.add(i),s.push(a))};for(const o of e){if(Array.isArray(o)){for(const a of o)r(a);continue}r(o)}return s}function u2(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const s=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(s){const r=s[1].toUpperCase(),o=(s[2]||"").replace(/[\\/]+/g,"\\");return o?`${r}:\\${o}`:`${r}:\\`}return null}function zd(e,t=[]){if(e==="win32"){for(const s of t){if(typeof s!="string")continue;const r=u2(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 m2(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 h2(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Gd(e,t,s){const r=await e(t,"file_list_browse",{path:s}),o=h2(r);if(!(o!=null&&o.success))throw new Error((o==null?void 0:o.error)||(r==null?void 0:r.error)||"Could not browse folder");const a=typeof(o==null?void 0:o.path)=="string"?o.path:s,i=a.includes("\\")?"\\":"/",c=(u,m)=>/^[A-Za-z]:\\?$/.test(u)?`${u.replace(/\\?$/,"\\")}${m}`:u==="/"||u==="\\"?`${i}${m}`:`${u.replace(/[\\/]+$/,"")}${i}${m}`,d=Array.isArray(o==null?void 0:o.files)?o.files.filter(u=>(u==null?void 0:u.type)==="directory"&&typeof(u==null?void 0:u.name)=="string").map(u=>({name:u.name,path:typeof(u==null?void 0:u.path)=="string"&&u.path.trim()?u.path:c(a,u.name)})).sort((u,m)=>u.name.localeCompare(m.name)):[];return{path:a,directories:d}}function ih(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 wb(e,t={}){const s=e==null?void 0:e.mcpConfig;if((s==null?void 0:s.mode)!=="manual")return null;const o=ih(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"}).trim();return!o.includes(`
|
|
58
|
-
`)&&!o.startsWith("{")?null:{serverName:s.serverName||"adhdev-mesh",configFormat:s.format,configPathCommand:s.configPathCommand,requiresRestart:s.requiresRestart===!0,instructions:s.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:ih(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"})}}function p2(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 _o(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Sb(e){return Ni(e)||e.tabKey||e.routeId||null}function kb(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",s=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",o=e.conversations.find(a=>{if(r&&a.routeId!==r)return!1;const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||s&&i.includes(s)||r&&a.routeId===r)});if(o!=null&&o.tabKey)return o.tabKey;if(r){const a=On(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(a!=null&&a.tabKey)return a.tabKey}return t||s||r||null}function xs(e){return String(e||"").trim()}function jb(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ri(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function f2(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function g2(e,t){const s=xs(e.providerSessionId),r=xs(e.targetSessionId),o=t.find(a=>{const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey,a.routeId].map(xs).filter(Boolean);return!!(s&&i.includes(s)||r&&i.includes(r))});return o?o.tabKey:r||s||null}function b2(e,t,s){if(t.event!=="agent:generating_completed")return null;const r=jb(t.daemonId);if(r&&r!==e.machineId)return null;const o=xs(t.providerType);if(e.providerType&&o!==e.providerType)return null;const a=xs(e.resumeSessionId),i=xs(e.launchedSessionId),c=xs(t.providerSessionId),d=xs(t.targetSessionId);if(a&&a!==c&&a!==d||i&&i!==c&&i!==d)return null;const u=ri(e.workspacePath);if(u){const m=ri(t.workspaceName);if(m&&!f2(m,u))return null}return g2(t,s)}function lh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function x2({ides:e,conversations:t,onOpenSession:s}){const[r,o]=l.useState(null),a=l.useRef(null),i=l.useCallback(()=>{a.current=null,o(null)},[]),c=l.useCallback(d=>{a.current=d,o(d)},[]);return l.useEffect(()=>{if(!r)return;const d=ri(r.workspacePath),u=e.find(h=>{var b,k,j,v;if(!h||h.type==="adhdev-daemon"||jb(h.daemonId||h.id)!==r.machineId||(Co(h)?"cli":Nr(h)?"acp":"ide")!==r.kind)return!1;const f=String(h.agentType||h.type||"");if(r.providerType&&f!==r.providerType)return!1;if(r.resumeSessionId)return String(h.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const C=String(r.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(S=>String(S||"")).filter(Boolean).includes(C)}if(d){const C=ri(h.workspace||h.runtimeWorkspaceLabel);return C?C===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((v=(j=(k=(b=h.activeChat)==null?void 0:b.messages)==null?void 0:k.at)==null?void 0:j.call(k,-1))==null?void 0:v.timestamp)||0)>=r.startedAt-5e3});if(!u)return;const m=kb({entrySessionId:u.sessionId,entryInstanceId:u.instanceId,entryRouteId:u.id,conversations:t});m&&(i(),s(m))},[i,t,e,s,r]),l.useEffect(()=>ct.onStatusEvent(d=>{const u=a.current;if(!u)return;const m=b2(u,d,t);m&&(i(),s(m))}),[i,t,s]),l.useEffect(()=>{if(!r)return;const d=window.setTimeout(()=>{o(u=>!u||u.startedAt!==r.startedAt?u:(a.current=null,null))},45e3);return()=>window.clearTimeout(d)},[r]),{trackPendingLaunch:c}}function y2(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 v2(e,t,s){var i,c,d,u;const r={meshId:e.trim()};t.trim()&&(r.cliType=t.trim());const o=(i=s==null?void 0:s.initialModel)==null?void 0:i.trim(),a=(c=s==null?void 0:s.initialThinkingLevel)==null?void 0:c.trim();return o&&(r.initialModel=o),a&&(r.initialThinkingLevel=a),o&&(s!=null&&s.modelSource)&&(r.modelSource=s.modelSource),a&&(s!=null&&s.thinkingLevelSource)&&(r.thinkingLevelSource=s.thinkingLevelSource),(d=s==null?void 0:s.settings)!=null&&d.autoApproveMode?r.autoApproveMode=s.settings.autoApproveMode:typeof((u=s==null?void 0:s.settings)==null?void 0:u.autoApprove)=="boolean"&&(r.autoApprove=s.settings.autoApprove),r}function w2({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:s,activeConv:r,ides:o,setCliViewModeOverrides:a}){const i=Ad(),{launchCli:c}=bi(),d=l.useCallback(async(b,k)=>Gd(e,b,k),[e]),u=l.useCallback(async(b,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const j=await e(b,"workspace_add",{path:k.trim()});return j!=null&&j.success?{ok:!0}:{ok:!1,error:(j==null?void 0:j.error)||"Could not save workspace"}}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not save workspace"}}},[e]),m=l.useCallback(async(b,k,j)=>{var v;try{const C={ideType:k,enableCdp:!0};(v=j==null?void 0:j.workspacePath)!=null&&v.trim()&&(C.workspace=j.workspacePath.trim());const x=await e(b,"launch_ide",C);return!(x!=null&&x.success)&&(x==null?void 0:x.success)!==void 0?{ok:!1,error:(x==null?void 0:x.error)||"Could not launch IDE"}:(t({machineId:b,kind:"ide",providerType:k,workspacePath:(j==null?void 0:j.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),h=l.useCallback(async(b,k,j,v)=>{const C=Date.now();try{const x=y2(j,v),S=await c(b,x),w=(S==null?void 0:S.result)||S,_=(w==null?void 0:w.sessionId)||(w==null?void 0:w.id);return S!=null&&S.success&&_?(t({machineId:b,kind:k,providerType:j,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,launchedSessionId:_,startedAt:C}),{ok:!0}):S!=null&&S.success?(t({machineId:b,kind:k,providerType:j,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(S==null?void 0:S.error)||(w==null?void 0:w.error)||`Could not launch ${k.toUpperCase()} session`,code:(S==null?void 0:S.code)||(w==null?void 0:w.code)||void 0}}catch(x){return lh(x)?(t({machineId:b,kind:k,providerType:j,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:x instanceof Error?x.message:`Could not launch ${k.toUpperCase()} session`}}},[c,e,t]),p=l.useCallback(async b=>{var k;if(i!=null&&i.listMeshes)return i.listMeshes(b);if(!b)return[];try{const j=await e(b,"list_meshes",{}),v=(j==null?void 0:j.result)??j;if((v==null?void 0:v.success)===!1)throw new Error((v==null?void 0:v.error)||"Could not load meshes");return(Array.isArray(v==null?void 0:v.meshes)?v.meshes:Array.isArray((k=v==null?void 0:v.result)==null?void 0:k.meshes)?v.result.meshes:[]).map(x=>{var S;return{id:String((x==null?void 0:x.id)||""),name:String((x==null?void 0:x.name)||(x==null?void 0:x.id)||"Untitled mesh"),repoIdentity:(x==null?void 0:x.repoIdentity)||(x==null?void 0:x.repo_identity)||null,workspace:Array.isArray(x==null?void 0:x.nodes)&&x.nodes.length>0?String(((S=x.nodes[0])==null?void 0:S.workspace)||""):null,nodesCount:Array.isArray(x==null?void 0:x.nodes)?x.nodes.length:void 0,status:(x==null?void 0:x.status)||null}}).filter(x=>x.id)}catch(j){throw console.error("List meshes failed",j),j}},[i,e]),g=l.useCallback(async(b,k,j,v)=>{if(!k.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(b,k,j,v);const C=Date.now();try{const x=v2(k,j,v),S=await e(b,"launch_mesh_coordinator",x),w=(S==null?void 0:S.result)??S;if((w==null?void 0:w.success)===!1||(S==null?void 0:S.success)===!1){const A=String((w==null?void 0:w.code)||(S==null?void 0:S.code)||""),O=p2((w==null?void 0:w.meshCoordinatorSetup)||(w==null?void 0:w.manualSetup)||(S==null?void 0:S.meshCoordinatorSetup)||(S==null?void 0:S.manualSetup));return{ok:!1,error:(w==null?void 0:w.error)||(S==null?void 0:S.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:O}}const _=(w==null?void 0:w.sessionId)||(w==null?void 0:w.id);return _?s(_):t({machineId:b,kind:"cli",providerType:(w==null?void 0:w.cliType)||j.trim()||void 0,workspacePath:(w==null?void 0:w.workspace)||null,startedAt:C}),{ok:!0}}catch(x){return lh(x)?(t({machineId:b,kind:"cli",providerType:j.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:x instanceof Error?x.message:"Could not launch mesh coordinator"}}},[i,s,e,t]),f=l.useCallback(async(b,k)=>{if(!b||!k)return[];try{const j=await e(b,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),v=(j==null?void 0:j.result)??j;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(j){return console.error("List saved sessions failed",j),[]}},[e]),y=l.useCallback(async b=>{await ub({conversation:r,mode:b,ides:o,sendDaemonCommand:e,setCliViewModeOverrides:a})},[r,o,e,a]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:u,handleLaunchMachineIde:m,handleLaunchMachineProvider:h,handleListMachineMeshes:p,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:f,setActiveCliViewMode:y}}function S2(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function k2(e,t,s=Date.now()){return!e||!S2(t)?null:{tabKey:e,nonce:s}}function j2({isMobile:e,conversations:t,visibleConversations:s,groupActiveTabIds:r,focusedGroup:o,groupedConvs:a,setSearchParams:i}){const[c,d]=l.useState(null),[u,m]=l.useState(null),h=l.useMemo(()=>{var b,k;if(!e){if(c){const j=t.find(v=>v.tabKey===c);if(j)return j}return s[0]}const y=r[o];if(y){const j=t.find(v=>v.tabKey===y);if(j)return j}return((b=a[o])==null?void 0:b[0])||((k=a[0])==null?void 0:k[0])},[t,c,o,r,a,e,s]),p=l.useCallback(y=>{d(y)},[]),g=l.useCallback(y=>{d(y.tabKey),i(b=>{const k=new URLSearchParams(b),j=NN(y);return j?k.set("activeTab",j):k.delete("activeTab"),k},{replace:!0})},[i]),f=l.useCallback((y,b)=>{const k=k2(y,b);k&&m(k)},[]);return{activeConv:h,openDesktopConversation:g,requestScrollToBottom:f,scrollToBottomRequest:u,setDesktopActiveTab:p}}function N2(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 C2(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 _2({activeConv:e,isMobile:t,liveSessionInboxState:s,sendDaemonCommand:r}){const o=l.useRef(null),a=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),a.current=null};if(t){u(),o.current=null;return}if(!(e!=null&&e.sessionId)){u(),o.current=null;return}const m=Ns(e,s),h=C2({tabKey:e.tabKey,historySessionId:Ni(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Qs(e),liveState:m}),p=h.autoReadKey,g=N2({autoReadKey:p,shouldMarkSeen:h.shouldMarkSeen,completedKey:o.current,pendingKey:a.current});if(!h.shouldMarkSeen){g.shouldCancelPending&&u(),o.current=p;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&u();const f=()=>{if(document.visibilityState!=="visible"||o.current===p)return;o.current=p,a.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const b=h.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:b,completionMarker:h.completionMarker}).catch(()=>{})};if(a.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(f,1500);const b=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=b,document.addEventListener("visibilitychange",b);return}const y=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(f,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=y,document.addEventListener("visibilitychange",y)},[e,t,s,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function vl(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 A2({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:s,ides:r,sendDaemonCommand:o,updateRouteChats:a,setToasts:i,setClearedTabs:c,setSearchParams:d}){var H;const{launchCli:u}=bi(),[m,h]=l.useState(!1),[p,g]=l.useState([]),[f,y]=l.useState(()=>yn()),[b,k]=l.useState(!1),[j,v]=l.useState(null),C=l.useRef(null),x=l.useMemo(()=>s||t||e,[e,s,t]),S=!!x&&St(x)&&!vt(x),w=l.useMemo(()=>{if(!x||!S)return null;const q=x.daemonId||x.routeId||"",J=Vn(x),K=vl(x);return`${q}:${J}:${x.providerSessionId||""}:${K}`},[x,S]),_=l.useMemo(()=>!x||!S?"":vl(x),[x,S]),{isCreatingChat:A,isRefreshingHistory:O,handleSwitchSession:L,handleNewChat:R,handleRefreshHistory:F}=bb({sendDaemonCommand:o,activeConv:x,chats:(H=r.find(q=>q.id===(x==null?void 0:x.routeId)))==null?void 0:H.chats,updateRouteChats:a,setToasts:i,setClearedTabs:c}),N=l.useCallback(()=>{h(!0)},[]),I=l.useCallback(()=>{h(!1)},[]),B=l.useCallback(async()=>{if(!(!x||!S||b)){k(!0);try{const q=x.daemonId||x.routeId,J=Vn(x),K=vl(x),M=await o(q,"list_saved_sessions",{agentType:J,providerType:J,kind:"cli",limit:50,...x.providerSessionId?{providerSessionId:x.providerSessionId}:{},...K?{workspace:K}:{}}),D=(M==null?void 0:M.result)??M;g(Array.isArray(D==null?void 0:D.sessions)?D.sessions:[])}catch(q){console.error("Refresh saved sessions failed",q),g([])}finally{k(!1)}}},[x,b,S,o]);l.useEffect(()=>{if(!m){C.current=null;return}if(!S){C.current=null,g([]),k(!1);return}!w||b||C.current!==w&&(C.current=w,B())},[B,m,b,S,w]);const T=l.useCallback(async q=>{if(!x||!S||!q.providerSessionId||!q.workspace)return;const J=x.daemonId||x.routeId,K=Vn(x);try{v(q.providerSessionId);const M=_f(q.summaryMetadata,"model",{preferShortValue:!0})||void 0,D=await u(J,{cliType:K,dir:q.workspace,resumeSessionId:q.providerSessionId,initialModel:M,...M?{modelSource:"remembered"}:{}}),P=(D==null?void 0:D.result)??D,$=typeof(P==null?void 0:P.sessionId)=="string"?P.sessionId:typeof(P==null?void 0:P.id)=="string"?P.id:"";$&&d(W=>{const U=new URLSearchParams(W);return U.set("activeTab",$),U},{replace:!0}),I()}catch(M){console.error("Resume saved session failed",M)}finally{v(null)}},[I,x,S,o,d]);return{historyModalOpen:m,openHistoryModal:N,closeHistoryModal:I,historyTargetConv:x,isSavedSessionHistoryTarget:S,isHistoryCreatingChat:A,isHistoryRefreshingHistory:O,handleHistorySwitchSession:L,handleHistoryNewChat:R,handleHistoryRefresh:F,savedHistorySessions:p,savedHistoryFilters:f,setSavedHistoryFilters:y,missingWorkspaceResumePath:_,isSavedHistoryLoading:b,resumingSavedHistorySessionId:j,handleRefreshSavedHistory:B,handleResumeSavedHistorySession:T}}function T2({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c}){const[d,u]=l.useState(null),[m,h]=l.useState(null),p=l.useMemo(()=>{if(e||!r)return null;const k=c(r);return k&&!St(k)&&!vt(k)?k:null},[e,r,c]),g=l.useMemo(()=>{const k=d==null?void 0:d.routeId;if(!k)return null;const j=d!=null&&d.tabKey?a.find(v=>v.tabKey===d.tabKey):o?a.find(v=>v.tabKey===o):null;return(j==null?void 0:j.routeId)===k?j:On(a,k)},[a,d,o]),f=l.useMemo(()=>{if(g)return i.find(k=>k.id===g.routeId)},[i,g]);l.useEffect(()=>{p&&(u({routeId:p.routeId,tabKey:Xu(p)}),h(p),s({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,s,p]);const y=l.useCallback(k=>{k&&(u({routeId:k.routeId,tabKey:Xu(k)}),h(k))},[]),b=l.useCallback(()=>{u(null),h(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:f,remoteDialogActiveConv:m,setRemoteDialogActiveConv:h,openRemoteDialog:y,closeRemoteDialog:b}}function I2({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:u}){const{remoteDialogConv:m,remoteDialogIdeEntry:h,remoteDialogActiveConv:p,setRemoteDialogActiveConv:g,openRemoteDialog:f,closeRemoteDialog:y}=T2({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c}),[b,k]=l.useState(!1),[j,v]=l.useState(null),C=l.useCallback(async w=>{const _=w||d;!_||!St(_)&&!vt(_)||(v(_),k(!0))},[d]),x=l.useCallback(()=>{k(!1),v(null)},[]),S=l.useCallback(async w=>{const _=j||d;if(!_||!St(_)&&!vt(_)){x();return}k(!1);try{const A=Vn(_),O=_.routeId||_.daemonId||"";await u(O,"stop_cli",{cliType:A,targetSessionId:_.sessionId,mode:w,...Ai(_)})}catch(A){console.error("Stop CLI failed:",A)}finally{v(null)}},[d,x,j,u]);return{remoteDialogConv:m,remoteDialogIdeEntry:h,remoteDialogActiveConv:p,setRemoteDialogActiveConv:g,openRemoteDialog:f,closeRemoteDialog:y,cliStopDialogOpen:b,cliStopTargetConv:j,requestCliStop:C,cancelCliStop:x,confirmCliStop:S}}function wl(e,t=!0){return(e??!0)&&t}const Vd=l.memo(function({activeConv:t,clearToken:s,isCliTerminal:r,ideEntry:o,terminalRef:a,commands:i,actionLogs:c,userName:d,scrollToBottomRequestNonce:u,isInputActive:m=!0,isVisible:h=!0}){const{handleModalButton:p,handleRelaunch:g,handleSendChat:f,handleSendNowQueued:y,handleCancelQueued:b,isSendingChat:k,sendFeedbackMessage:j,pendingLocalMessage:v,pendingLocalMessages:C,retireEchoedPendingMessages:x,handleFocusAgent:S,isFocusingAgent:w}=i,_=r,A=!r,O=wl(h,_),L=wl(h,A),R=wl(h),F=cb(t),{t:N}=ve("common"),I=F.status||F.modalMessage||F.modalButtons?{...t,...F.status?{status:F.status}:{},...F.modalMessage!==void 0?{modalMessage:F.modalMessage}:{},...F.modalButtons!==void 0?{modalButtons:F.modalButtons}:{}}:t,B=T=>n.jsx(vg,{activeConv:I,ideEntry:o,handleSendChat:f,handleSendNowQueued:y,handleCancelQueued:b,isSendingChat:k,sendFeedbackMessage:j,pendingLocalMessage:v,pendingLocalMessages:C,retireEchoedPendingMessages:x,handleFocusAgent:S,isFocusingAgent:w,actionLogs:c,userName:d,scrollToBottomRequestNonce:u,isInputActive:m&&T,isVisible:T});return n.jsxs(n.Fragment,{children:[n.jsx(bf,{activeConv:I,onModalButton:p}),I.transport!=="pty"&&I.transport!=="acp"&&I.cdpConnected===!1?n.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:n.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[n.jsx("span",{className:"text-sm",children:n.jsx(an,{size:14})}),n.jsxs("span",{className:"flex flex-1 items-center gap-1",children:[n.jsx("span",{className:"font-semibold",children:N("paneGroup.cdpDisconnectedShort")}),n.jsx(dt,{content:N("paneGroup.cdpDisconnected"),size:12})]}),n.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-3xs whitespace-nowrap shrink-0",onClick:g,children:N("paneGroup.relaunchWithCdp")})]})}):null,I.transport==="pty"?n.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[n.jsx("div",{"aria-hidden":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:_?"visible":"hidden",pointerEvents:_?"auto":"none"},children:n.jsx(O_,{activeConv:I,clearToken:s,terminalRef:a,handleSendChat:f,isSendingChat:k,sendFeedbackMessage:j,isVisible:O,isInputActive:m&&O})}),n.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:A?"visible":"hidden",pointerEvents:A?"auto":"none"},children:B(L)})]}):B(R)]})},(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 M2({conversation:e,className:t="",onOpenNativeConversation:s,onOpenMachine:r,interactive:o=!0,meshOnly:a=!1}){var C,x,S;const{t:i}=ve("common"),c=rr(),d=as(e),u=a?null:qf(e),m=!a&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),h=!a&&e.streamSource==="agent-stream"&&!!e.agentName,p=!a&&!h&&(e.transport==="pty"||e.transport==="acp"),g=Mr(e),f=jN(e),y=(C=e.settings)==null?void 0:C.meshNodeFor,b=e.meshQueueStats,k=((x=e.coordinator)==null?void 0:x.meshId)||((S=e.settings)==null?void 0:S.meshCoordinatorFor),j=l.useCallback(()=>{if(r){r();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,r]),v=l.useCallback(()=>{if(s){s();return}const w=Sb(e);w&&c(_o(w))},[e,c,s]);return!m&&!h&&!p&&!u&&!y&&!b?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:v,title:f,children:[n.jsx(Xn,{size:12}),n.jsx("span",{children:f})]}):n.jsxs("span",{className:"conversation-meta-chip",title:f,children:[n.jsx(Xn,{size:12}),n.jsx("span",{children:f})]})),h&&n.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[n.jsx(Tr,{size:12}),n.jsx("span",{children:g})]}),p&&n.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[n.jsx(Tr,{size:12}),n.jsx("span",{children:g})]}),u&&(o?n.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:u,children:[n.jsx(Ks,{size:12}),n.jsx("span",{children:u})]}):n.jsxs("span",{className:"conversation-meta-chip",title:u,children:[n.jsx(Ks,{size:12}),n.jsx("span",{children:u})]})),y&&n.jsxs("span",{className:"conversation-meta-chip",title:i("dashboard.metaChips.meshNode"),children:[n.jsx(Ks,{size:12}),n.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),k&&b&&n.jsxs("span",{className:`conversation-meta-chip ${b.pending>0?"is-active":""}`,style:b.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:i("dashboard.metaChips.queueTooltip",{pending:b.pending,assigned:b.assigned,completed:b.completed,failed:b.failed}),children:[n.jsx(Zv,{size:12}),n.jsx("span",{children:i("dashboard.metaChips.queuePending",{count:b.pending})})]})]})}function R2({selectedConversation:e,isAcp:t,isStandalone:s,selectedIdeEntry:r,actionLogs:o,userName:a,commands:i,onBack:c,onOpenNativeConversation:d,onOpenMachine:u,onOpenHistory:m,onOpenRemote:h,onOpenMeshGraph:p,onStopCli:g,cliViewMode:f,onSetCliViewMode:y}){const{t:b}=ve("common"),k=l.useRef(null),j=ki(gf(e)),v=St(e)&&!t,C=v&&f==="terminal",x=s?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:`flex items-center justify-between gap-3 ${x} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[n.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[n.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:c,type:"button","aria-label":b("common.back"),children:n.jsx(td,{size:18})}),n.jsxs("div",{className:"min-w-0 flex-1 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:Ot(e)}),n.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:n.jsx(M2,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>u(e)})})]})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[v&&f&&n.jsx(Ag,{mode:f,onChange:y,compact:!0}),v&&g&&n.jsx("button",{onClick:()=>{g(e)},className:"btn btn-secondary btn-sm",title:b("cliStop.stopProcess"),"aria-label":b("cliStop.stopProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:n.jsx(Bt,{size:14})}),n.jsx(Bg,{conversation:e,onOpenHistory:m,onOpenRemote:h,onOpenMeshGraph:p,iconSize:14})]})]}),n.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:n.jsx(Vd,{activeConv:e,clearToken:0,isCliTerminal:C,ideEntry:r,terminalRef:k,commands:i,actionLogs:o,userName:a})}),n.jsx(md,{promptSession:j.promptSession,isSubmitting:j.isSubmitting,error:j.responseError,onSubmit:j.submit,onCancel:j.cancel})]})}function P2(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Nb({isStandalone:e=!1}={}){const{t}=ve("common"),[s,r]=l.useState("unix"),[o,a]=l.useState("powershell"),[i,c]=l.useState(!1),d=s==="unix"?"unix":o,u=l.useMemo(()=>qC(),[]);l.useEffect(()=>{r(P2())},[]);const m=l.useCallback(()=>{navigator.clipboard.writeText(u[d].cmd).catch(()=>{}),c(!0),setTimeout(()=>c(!1),2e3)},[d]);return n.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[n.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[n.jsx("button",{className:`text-3xs px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${s==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>r("unix"),children:"macOS / Linux"}),n.jsx("button",{className:`text-3xs px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${s==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>r("windows"),children:"Windows"})]}),s==="windows"&&n.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[n.jsx("button",{className:`text-4xs px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${o==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("powershell"),children:"PowerShell"}),n.jsx("button",{className:`text-4xs px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${o==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("cmd"),children:">_ CMD"})]}),n.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:m,title:t("app.installCommand.clickToCopy"),children:[n.jsx("span",{className:"text-text-muted select-none",children:u[d].prompt}),n.jsx("span",{className:"flex-1 break-all",children:u[d].cmd}),n.jsx("span",{className:"text-4xs font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:i?n.jsx(Er,{size:12}):n.jsx(nd,{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 Cb({section:e,onSectionChange:t}){const{t:s}=ve("common"),r=[{key:"machines",label:s("nav.machines"),icon:Xn},{key:"chats",label:s("nav.chats"),icon:Jn}];return n.jsx("div",{className:"px-3 py-2.5 pb-[calc(20px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:n.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:o,label:a,icon:i})=>{const c=e===o;return n.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-xxs font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(o),type:"button","aria-pressed":c,children:[n.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:n.jsx(i,{size:15})}),n.jsx("span",{children:a})]},o)})})})}function da({title:e,className:t=""}){return n.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:n.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function hr({children:e,className:t=""}){return n.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function Es({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 L2({title:e,isMuted:t,onToggleMute:s,onHide:r,onStop:o}){const{t:a}=ve(),[i,c]=l.useState(!1),d=l.useRef(null);if(l.useEffect(()=>{if(!i)return;const h=g=>{var f;(f=d.current)!=null&&f.contains(g.target)||c(!1)},p=g=>{g.key==="Escape"&&c(!1)};return document.addEventListener("pointerdown",h,!0),document.addEventListener("mousedown",h,!0),window.addEventListener("keydown",p),()=>{document.removeEventListener("pointerdown",h,!0),document.removeEventListener("mousedown",h,!0),window.removeEventListener("keydown",p)}},[i]),!s&&!r&&!o)return null;const u="flex w-full items-center gap-2.5 rounded-lg border-none bg-transparent px-3 py-2.5 text-left text-sm font-medium text-text-secondary hover:bg-bg-secondary hover:text-text-primary",m=h=>p=>{p.preventDefault(),p.stopPropagation(),c(!1),h()};return n.jsxs("div",{ref:d,className:"relative",children:[n.jsx("button",{type:"button",className:`mobile-inbox-row-menu-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${t?"border-amber-500/60 bg-amber-500/15 text-amber-500":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:h=>{h.preventDefault(),h.stopPropagation(),c(p=>!p)},"aria-haspopup":"menu","aria-expanded":i,"aria-label":a("mobileInbox.moreActionsFor",{title:e}),title:a("dashboard.header.moreActions"),children:t?n.jsx(tc,{size:13}):n.jsx(Fp,{size:14})}),i&&n.jsxs("div",{role:"menu",className:"absolute right-0 top-full z-[var(--z-popover)] mt-1 flex w-48 flex-col rounded-xl border border-border-default bg-bg-card p-1 shadow-xl",children:[s&&n.jsxs("button",{type:"button",role:"menuitem",className:`mobile-inbox-mute-button ${u}`,onClick:m(s),children:[t?n.jsx(js,{size:15}):n.jsx(tc,{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(pi,{size:15}),a("mobileInbox.hide")]}),o&&n.jsxs("button",{type:"button",role:"menuitem",className:`mobile-inbox-stop-button ${u} !text-status-error`,onClick:m(o),children:[n.jsx(Bt,{size:15}),a("mobileInbox.stopSessionTitle")]})]})]})}function ua({item:e,type:t,getAvatarText:s,onOpenConversation:r,onRequestHideConversation:o,onRequestStopCli:a,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:u}){const{t:m}=ve(),h=t==="needs_attention"||t==="task_complete",p=t==="working",g=t==="earlier",f=t==="task_complete",{isReconnecting:y,isConnecting:b,isErrored:k}=or(e.conversation),j=Ot(e.conversation),v=Oo(e.conversation),C=kg(e.conversation,{requiresAction:t==="needs_attention"}),x=h?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":p?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",S=h?"bg-accent-primary shadow-glow":p?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",w=g?"text-text-secondary":"text-text-primary",_=g?"text-text-muted":"text-text-secondary",A=g?"text-text-secondary opacity-80":"text-text-muted",O=g?"text-text-muted opacity-80":"text-text-muted",L=!p&&!f,R=wg(e.conversation),F="text-[color:var(--status-warning)]",N=I=>{if(!c||!D_())return;I.preventDefault(),I.stopPropagation();const B=c==null?void 0:c(e.conversation);Promise.resolve(B).catch(T=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",T)})};return n.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${x}`,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 ${S}`,style:h?{color:"var(--accent-on-primary)"}:void 0,children:s(j)}),R&&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-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:I=>{I.preventDefault(),I.stopPropagation(),i(e.conversation)},"aria-label":m("mobileInbox.openMeshGraphFor",{title:j}),title:m("mobileInbox.openLiveMeshGraph"),children:n.jsx(Gn,{size:13})})]}),n.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>r(e.conversation),onContextMenu:N,type:"button",children:[n.jsx("div",{className:"flex items-center gap-2 pr-[92px]",children:n.jsx("span",{className:`text-[15px] leading-[22px] font-bold truncate tracking-tight ${w}`,children:j})}),n.jsxs("div",{className:`text-xs font-medium truncate flex items-center ${_}`,children:[n.jsx("span",{className:"truncate",children:v}),n.jsx(Cd,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),y?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:`${F} animate-pulse`,children:m("mobileInbox.reconnectingItem")})]}):b?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:"text-text-muted",children:m("mobileInbox.connectingItem")})]}):C==="Action needed"?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:F,children:m("mobileInbox.actionNeeded")})]}):k&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 opacity-50",children:"·"}),n.jsx("span",{className:"text-[color:var(--status-error)]",children:m("mobileInbox.needsAttention")})]})]}),n.jsx("div",{className:`mt-0.5 truncate text-xxs ${A}`,children:e.preview})]}),n.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[L&&n.jsx("span",{className:`mr-0.5 text-2xs font-medium shrink-0 ${O}`,children:Gp(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(L2,{title:j,isMuted:d,onToggleMute:u,onHide:o,onStop:a})]})]})},e.conversation.tabKey)}function ch({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 E2({section:e,attentionItems:t,unreadItems:s,workingItems:r,completedItems:o,hiddenConversations:a,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:u,onOpenConversation:m,onShowAllHidden:h,onHideConversation:p,onShowHiddenConversation:g,onOpenMeshGraph:f,onStopCli:y,onOpenNewSession:b,onOpenMachine:k,onOpenSettings:j,onSectionChange:v,wsStatus:C="connected",initialDataLoaded:x=!0,conversationsLoaded:S,isStandalone:w=!1,onCollectChatDebugBundle:_,isConversationMuted:A,onToggleMuteConversation:O}){const{t:L}=ve(),R=C==="disconnected"||C==="reconnecting"||C==="offline"||C==="auth_failed",F=!R&&!x,N=!R&&!(S??x),I=i.length>0,B=t.length>0||s.length>0||r.length>0||o.length>0,T=L(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),H=w?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",q=w?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",J=l.useCallback(async D=>{const P=vs(D);if(!P)return;const $=Array.isArray(D.messages)?D.messages:[],W=Zf({activeConv:D,visibleMessages:$,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:$.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),U=await u(P,"get_chat_debug_bundle",{...ks(D),delivery:"daemon_file",frontendSnapshot:W}),ae=Us(U),be=ng(ae),V=await tg(be);V==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ct.showToast(eg(ae,{locatorCopyStatus:V}),V==="failed"?"warning":"success")},[d,u]),K=_||J,M=l.useCallback(D=>{p&&(p(D),ct.showToast(L("mobileInbox.hiddenToast",{title:Ot(D)}),"info",{duration:6e3,actions:[{label:L("mobileInbox.undo"),variant:"primary",onClick:()=>{g?g(D):h()}}]}))},[p,h,g,L]);return n.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[n.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${H}`,children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:T}),n.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||s.length>0)&&n.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-2xs font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[n.jsx(js,{size:13}),n.jsx("span",{children:t.length+s.length})]}),n.jsx("button",{onClick:j,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:n.jsx(Dr,{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:R?n.jsx(Es,{icon:n.jsx(ln,{size:32}),title:L(C==="offline"?"mobileInbox.networkOffline":C==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:L(C==="offline"?"mobileInbox.waitingForNetwork":C==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):F?n.jsx(Es,{icon:n.jsx(ln,{size:32}),title:L("mobileInbox.loading"),subtitle:L("mobileInbox.loadingSubtitle")}):i.length===0?n.jsx(Es,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:L(w?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:L(w?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!w&&n.jsx("div",{className:"w-full max-w-[360px] mt-4",children:n.jsx(Nb,{})})}):n.jsx(hr,{children:i.map((D,P)=>n.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${P>0?"border-t border-border-subtle/70":""}`,onClick:()=>k(D.id),type:"button",children:[n.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(D.label)}),n.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-[15px] leading-[22px] font-bold text-text-primary truncate tracking-tight",children:D.label}),n.jsxs("span",{className:"flex items-center gap-2 text-2xs font-medium text-text-muted shrink-0",children:[n.jsx(ch,{count:D.generatingCount,label:L("mobileInbox.generatingCount",{count:D.generatingCount})}),D.unread>0?n.jsx("span",{className:"text-accent-primary",children:L("mobileInbox.newCount",{count:D.unread})}):D.total>0?L("mobileInbox.chatCount",{count:D.total}):L("mobileInbox.idle")]})]}),n.jsx("div",{className:"text-xs font-medium text-text-secondary truncate",children:D.subtitle}),D.total>0?n.jsxs("div",{className:"text-xxs text-text-muted mt-0.5",children:[L("mobileInbox.chatCount",{count:D.total}),D.unread>0?L("mobileInbox.unreadSuffix",{count:D.unread}):"",D.generatingCount>0?L("mobileInbox.collapsedGeneratingSuffix",{count:D.generatingCount}):""]}):D.generatingCount>0?n.jsx("div",{className:"text-xxs text-accent-primary mt-0.5 font-medium",children:L("mobileInbox.generatingCount",{count:D.generatingCount})}):n.jsx("div",{className:"text-xxs text-text-muted mt-0.5 italic opacity-70",children:L("mobileInbox.noActiveChats")})]})]},D.id))})}),e==="chats"&&t.length>0&&n.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[n.jsx(da,{title:L("mobileInbox.needsAttention"),className:"mb-0"}),n.jsx(hr,{children:t.map((D,P)=>n.jsx("div",{className:P>0?"border-t border-border-subtle/70":"",children:n.jsx(ua,{item:D,type:"needs_attention",getAvatarText:c,onOpenConversation:m,onRequestHideConversation:p?()=>M(D.conversation):void 0,onRequestStopCli:y?()=>y(D.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:K,isMuted:A==null?void 0:A(D.conversation),onToggleMute:O?()=>O(D.conversation):void 0})},D.conversation.tabKey))})]}),e==="chats"&&s.length>0&&n.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[n.jsx(da,{title:L("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),n.jsx(hr,{children:s.map((D,P)=>n.jsx("div",{className:P>0?"border-t border-border-subtle/70":"",children:n.jsx(ua,{item:D,type:"task_complete",getAvatarText:c,onOpenConversation:m,onRequestHideConversation:p?()=>M(D.conversation):void 0,onRequestStopCli:y?()=>y(D.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:K,isMuted:A==null?void 0:A(D.conversation),onToggleMute:O?()=>O(D.conversation):void 0})},D.conversation.tabKey))})]}),e==="chats"&&r.length>0&&n.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[n.jsx(da,{title:L("mobileInbox.workingNow"),className:"mb-0 mt-2"}),n.jsx(hr,{children:r.map((D,P)=>n.jsx("div",{className:P>0?"border-t border-border-subtle/70":"",children:n.jsx(ua,{item:D,type:"working",getAvatarText:c,onOpenConversation:m,onRequestHideConversation:p?()=>M(D.conversation):void 0,onRequestStopCli:y?()=>y(D.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:K,isMuted:A==null?void 0:A(D.conversation),onToggleMute:O?()=>O(D.conversation):void 0})},D.conversation.tabKey))})]}),e==="chats"&&n.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&n.jsx(da,{title:L("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?n.jsx(hr,{children:o.map((D,P)=>n.jsx("div",{className:P>0?"border-t border-border-subtle/70":"",children:n.jsx(ua,{item:D,type:"earlier",getAvatarText:c,onOpenConversation:m,onRequestHideConversation:p?()=>M(D.conversation):void 0,onRequestStopCli:y?()=>y(D.conversation):void 0,onOpenMeshGraph:f,onCollectChatDebugBundle:K,isMuted:A==null?void 0:A(D.conversation),onToggleMute:O?()=>O(D.conversation):void 0})},D.conversation.tabKey))}):B?n.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:L("mobileInbox.allCaughtUp")}):R?n.jsx(Es,{icon:n.jsx(ln,{size:28}),title:L("mobileInbox.connecting"),subtitle:L("mobileInbox.connectingSubtitle")}):N?n.jsx(Es,{icon:n.jsx(ln,{size:28}),title:L("mobileInbox.loading"),subtitle:L("mobileInbox.loadingSubtitle")}):I?n.jsx(Es,{icon:n.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:n.jsx(Jn,{size:20})}),title:L("mobileInbox.noConversations"),subtitle:L("paneGroup.newSessionDescription"),children:b&&n.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:b,"aria-label":L("paneGroup.newSession"),title:L("paneGroup.newSession"),children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),n.jsx("span",{children:L("paneGroup.newSession")})]})}):n.jsx(Es,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:L("mobileInbox.noMachinesConnected"),subtitle:L("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&a.length>0&&(()=>{const D=RS(a);return n.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:n.jsx(hr,{className:"mt-4 border-dashed bg-bg-secondary/20",children:n.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-xs font-bold uppercase tracking-wider text-text-secondary",children:L("mobileInbox.hiddenTabs")}),n.jsx(ch,{count:D,label:L("mobileInbox.generatingCount",{count:D})})]}),n.jsxs("div",{className:"mt-0.5 text-xxs text-text-muted",children:[L("mobileInbox.collapsedCount",{count:a.length}),D>0?L("mobileInbox.collapsedGeneratingSuffix",{count:D}):""]})]}),n.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-xs font-semibold text-accent-primary hover:border-border-default",onClick:h,children:L("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&b&&B&&n.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:b,"aria-label":L("paneGroup.newSession"),title:L("paneGroup.newSession"),children:n.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),n.jsx(Cb,{section:e,onSectionChange:v})]})}function D2(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 _b(e,t){const s=[e.workspace||(t?t("launch.workspaceUnknown"):"Workspace unknown")],r=tr(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(t?t("launch.messageCountShort",{count:e.messageCount}):`${e.messageCount} msgs`);const o=D2(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:o?t?t("launch.updatedAt",{time:o}):`Updated ${o}`:"",preview:(e.preview||"").trim()}}function Yd({title:e,description:t,currentPath:s,directories:r,busy:o=!1,error:a="",confirmLabel:i,inline:c=!1,onClose:d,onNavigate:u,onConfirm:m}){const[h,p]=l.useState(s),{t:g}=ve("common"),f=i??g("machine.workspaceBrowse.useThisFolder");l.useEffect(()=>{p(s)},[s]);const y=m2(s),b=h.trim(),k=n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t&&!c&&n.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),n.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:d,"aria-label":g("common.close"),children:n.jsx(Bt,{size:16})})]}),n.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[n.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!y||o||u(y)},disabled:!y||o,children:[n.jsx(td,{size:15}),g("machine.workspaceBrowse.parent")]}),n.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:g("machine.workspaceBrowse.currentFolder")}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"text",value:h,onChange:j=>p(j.target.value),onKeyDown:j=>{j.key!=="Enter"||!b||o||(j.preventDefault(),u(b))},placeholder:g("machine.workspaceBrowse.pathPlaceholder"),className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),n.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!b||o||u(b)},disabled:!b||o,children:g("machine.workspaceBrowse.go")})]})]})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?n.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:g("machine.workspaceBrowse.loading")}):a?n.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:a}):r.length===0?n.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:g("machine.workspaceBrowse.noSubfolders")}):n.jsx("div",{className:"p-3",children:r.map(j=>n.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(j.path),children:[n.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:n.jsx(Zs,{size:17})}),n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:j.name}),n.jsx("span",{className:"block text-2xs text-text-muted truncate",children:j.path})]})]},j.path))})}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[n.jsx("button",{type:"button",className:"btn btn-secondary h-9 px-4 text-sm",onClick:d,children:g("common.cancel")}),n.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(b||s),disabled:!b&&!s||o,children:f})]})]});return c?n.jsx("div",{className:"mt-3 flex max-h-[min(60vh,440px)] flex-col overflow-hidden rounded-xl border border-border-subtle bg-bg-secondary",role:"region","aria-labelledby":"workspace-browse-title","data-testid":"workspace-browse-inline",children:k}):n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:n.jsx("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:k})})})}function Oi({title:e,description:t,details:s,workspaceOptions:r,selectedWorkspaceKey:o,onWorkspaceChange:a,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:u,argsValue:m,onArgsChange:h,showModelInput:p,modelValue:g,onModelChange:f,historyProviderNode:y,onConfirm:b,onCancel:k}){const{t:j}=ve("common"),v=i??j("machine.launchConfirm.launch"),C=c??j("machine.launchConfirm.launching"),x=r==null?void 0:r.find(w=>w.key===o),S=n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:n.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),n.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),n.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:k,"aria-label":j("machine.launchConfirm.closeAria"),children:n.jsx(Bt,{size:16})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[r&&r.length>0&&a&&n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:j("machine.launchConfirm.workspace")}),n.jsx("select",{value:o||"",onChange:w=>a(w.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(w=>n.jsx("option",{value:w.key,children:w.label},w.key))}),(x==null?void 0:x.description)&&n.jsx("div",{className:"mt-2 text-2xs text-text-muted break-all",children:x.description})]}),y,s.map((w,_)=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:w.label}),n.jsx("div",{className:"text-sm text-text-primary break-all",children:w.value})]},`${w.label}:${_}`)),p&&f&&n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:j("machine.launchConfirm.languageModel")}),n.jsx("input",{type:"text",value:g||"",onChange:w=>f(w.target.value),placeholder:j("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),u&&h&&n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted mb-1",children:j("machine.launchConfirm.cliArgs")}),n.jsx("input",{type:"text",value:m||"",onChange:w=>h(w.target.value),placeholder:j("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[n.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:k,disabled:d,children:j("machine.launchConfirm.cancel")}),n.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:d,children:[n.jsx(Op,{size:14}),d?C:v]})]})]})});return typeof document>"u"?S:Qn.createPortal(S,document.body)}function dh(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Ab(e){const{machine:t,currentWorkspacePath:s,currentWorkspaceId:r,includeHome:o=!0,homeLabel:a="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];o&&c.push({key:"__home__",label:a,description:i,workspaceId:null,workspacePath:null});for(const m of t.workspaces||[])c.push({key:`saved:${m.id}`,label:`${m.id===t.defaultWorkspaceId?"⭐ ":""}${dh(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const d=(s==null?void 0:s.trim())||"",u=d?(t.workspaces||[]).find(m=>m.path===d):null;if(d&&!u&&c.push({key:`custom:${d}`,label:dh(d),description:d,workspaceId:null,workspacePath:d}),r){const m=`saved:${r}`;if(c.some(h=>h.key===m))return{options:c,selectedKey:m}}return u?{options:c,selectedKey:`saved:${u.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function O2(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function F2(e,t){return[O2(e.kind),e.subtitle||"",e.providerSessionId?t?t("launch.savedHistoryBadge"):"Saved history":""].filter(Boolean).join(" · ")}function $2(e){return e.lastLaunchedAt?xi(e.lastLaunchedAt):""}function Tb(e,t){return{metaText:F2(e,t),updatedLabel:$2(e)}}function Sl(e,t,s){return e?"ide":t>0?"cli":s>0?"acp":null}function H2({selectedMachineEntry:e,cliProviders:t,acpProviders:s,machineAction:r,onBrowseDirectory:o,onListSavedSessions:a}){var ye,Fe,Me,De;const i=Hr(),[c,d]=l.useState(!1),u=(((ye=e.detectedIdes)==null?void 0:ye.length)||0)>0,m=l.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),h=e.defaultWorkspaceId||null,[p,g]=l.useState(h||((Fe=m[0])==null?void 0:Fe.id)||""),[f,y]=l.useState(""),[b,k]=l.useState(""),[j,v]=l.useState([]),[C,x]=l.useState(!1),[S,w]=l.useState(""),[_,A]=l.useState(!1),[O,L]=l.useState(Sl(u,t.length,s.length)),R=l.useRef(null),[F,N]=l.useState(null),I=l.useRef("__home__"),[B,T]=l.useState("__home__"),[H,q]=l.useState(""),[J,K]=l.useState(""),[M,D]=l.useState(""),[P,$]=l.useState([]),[W,U]=l.useState(()=>yn().textQuery),[ae,be]=l.useState(()=>yn().workspaceQuery),[V,we]=l.useState(()=>yn().modelQuery),[ce,de]=l.useState(()=>yn().resumableOnly),[ne,ee]=l.useState(()=>yn().sortMode),[ue,je]=l.useState(!1),[X,G]=l.useState(!1),z=l.useRef(0),ie=l.useRef(0),Ne=l.useRef(null),Be=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const Le=p==="__custom__"?f.trim():((Me=m.find(Te=>Te.id===p))==null?void 0:Me.path)||"",Je=p==="__custom__"&&!!Le&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),Se=p!=="__custom__"&&((De=m.find(Te=>Te.id===p))==null?void 0:De.path)||"",he=l.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),pe=l.useCallback(async Te=>{const He=z.current+1;z.current=He,x(!0),w("");try{const tt=await o(Te);if(z.current!==He)return;k(tt.path),y(tt.path),v(tt.directories)}catch(tt){if(z.current!==He)return;w(tt instanceof Error?tt.message:"Could not load folder")}finally{z.current===He&&x(!1)}},[o]),Ee=l.useCallback(()=>{var He;g("__custom__"),A(!0);const Te=zd(e.platform,qd(f.trim(),Se,he,e.defaultWorkspacePath,(He=m.find(tt=>tt.id===h))==null?void 0:He.path,m.map(tt=>tt.path)));pe(Te)},[f,h,pe,he,Se,e.platform,m]),Y=l.useCallback(Te=>{if(Te!=null&&Te.workspaceId){g(Te.workspaceId),y("");return}if(Te!=null&&Te.workspacePath){g("__custom__"),y(Te.workspacePath);return}g(""),y("")},[]),me=l.useCallback(Te=>{if(g(Te),Te==="__custom__"){Ee();return}y("")},[Ee]),fe=l.useCallback(Te=>{g("__custom__"),y(Te)},[]),E=l.useCallback((Te,He)=>{const tt=ie.current+1;ie.current=tt,R.current=He,I.current=Te.selectedWorkspaceKey||"__home__",T(Te.selectedWorkspaceKey||"__home__"),q(Te.initialArgs||""),K(Te.initialModel||""),D(""),$([]);const Ct=Te.providerType?`${e.id}:${Te.providerType}`:null;if(q1(Be.current,Ct)){const Q=yn();U(Q.textQuery),be(Q.workspaceQuery),we(Q.modelQuery),de(Q.resumableOnly),ee(Q.sortMode)}Be.current=Ct,N(Te),Te.providerType&&a?(je(!0),a(Te.providerType).then(Q=>{ie.current===tt&&$(Q||[])}).catch(Q=>{ie.current===tt&&console.warn("Failed to load saved sessions",Q)}).finally(()=>{ie.current===tt&&je(!1)})):je(!1)},[a,e.id]),oe=l.useMemo(()=>Ld(P,{textQuery:W,workspaceQuery:ae,modelQuery:V,resumableOnly:ce,sortMode:ne}),[V,ce,P,ne,W,ae]);l.useEffect(()=>{M&&(oe.some(Te=>Te.providerSessionId===M)||D(""))},[oe,M]);const Ie=l.useCallback(()=>{R.current&&(G(!0),R.current().finally(()=>{R.current=null,G(!1),N(null)}))},[]),Z=l.useCallback(()=>{ie.current+=1,R.current=null,je(!1),N(null)},[]),se=l.useCallback(Te=>{I.current=Te,T(Te)},[]);return l.useEffect(()=>{var Te;Ne.current!==e.id&&(z.current+=1,ie.current+=1,Ne.current=e.id,g(h||((Te=m[0])==null?void 0:Te.id)||"__custom__"),y(""),k(""),v([]),x(!1),w(""),A(!1),R.current=null,N(null),$([]),je(!1),G(!1),U(yn().textQuery),be(yn().workspaceQuery),we(yn().modelQuery),de(yn().resumableOnly),ee(yn().sortMode),Be.current=null,L(Sl(u,t.length,s.length)))},[s.length,t.length,h,u,e.id,m]),l.useEffect(()=>{var Te;p!=="__custom__"&&(p&&m.some(He=>He.id===p)||g(h||((Te=m[0])==null?void 0:Te.id)||"__custom__"))},[h,p,m]),l.useEffect(()=>{O==="ide"&&u||O==="cli"&&t.length>0||O==="acp"&&s.length>0||L(Sl(u,t.length,s.length))},[O,s.length,t.length,u]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:u,workspaceRows:m,defaultWorkspaceId:h,workspaceChoice:p,customWorkspacePath:f,browseCurrentPath:b,browseDirectories:j,browseBusy:C,browseError:S,browseDialogOpen:_,activeLauncherKind:O,launchConfirm:F,launchConfirmWorkspaceKeyRef:I,launchConfirmWorkspaceKey:B,launchConfirmArgs:H,launchConfirmModel:J,launchConfirmResumeId:M,launchConfirmSavedSessions:P,launchConfirmTextFilter:W,launchConfirmWorkspaceFilter:ae,launchConfirmModelFilter:V,launchConfirmResumableOnly:ce,launchConfirmSortMode:ne,filteredLaunchConfirmSavedSessions:oe,launchConfirmSessionsLoading:ue,launchConfirmBusy:X,resolvedWorkspacePath:Le,canCreateMissingWorkspace:Je,openBrowseDialog:Ee,loadBrowsePath:pe,handleWorkspaceChoiceChange:me,chooseCustomWorkspacePath:fe,setCustomWorkspacePath:y,setBrowseDialogOpen:A,setActiveLauncherKind:L,openLaunchConfirm:E,handleConfirmLaunch:Ie,closeLaunchConfirm:Z,setWorkspaceSelectionFromOption:Y,setLaunchConfirmWorkspaceKeyAndSync:se,setLaunchConfirmArgs:q,setLaunchConfirmModel:K,setLaunchConfirmResumeId:D,setLaunchConfirmTextFilter:U,setLaunchConfirmWorkspaceFilter:be,setLaunchConfirmModelFilter:we,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:ee}}function B2({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:s,cliProviders:r,acpProviders:o,selectedMachineNeedsUpgrade:a,appVersion:i,machineAction:c,isStandalone:d,section:u,showBottomNav:m,onBack:h,onSectionChange:p,onOpenConversation:g,onOpenRecent:f,onOpenMachineDetails:y,onMachineUpgrade:b,onBrowseDirectory:k,onListSavedSessions:j}){const{t:v}=ve("common"),C=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",x=s.slice(0,4),S=t.slice(0,3),w=H2({selectedMachineEntry:e,cliProviders:r,acpProviders:o,machineAction:c,onBrowseDirectory:k,onListSavedSessions:j}),_=l.useMemo(()=>x.map(N=>{const{metaText:I,updatedLabel:B}=Tb(N,v);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:I,updatedLabel:B,onClick:()=>{const{options:T,selectedKey:H}=Ab({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:N.workspace,homeLabel:v("newSession.homeDirectory"),homeDescription:v("newSession.launchWithoutWorkspace")});w.openLaunchConfirm({title:N.kind==="ide"?Ja(v,"restart-ide",N.label):N.providerSessionId?Kg(v,N.label):Ja(v,"start-fresh",N.label),description:N.kind==="ide"?Xa(v,"restart-ide"):N.providerSessionId?qg(v):Xa(v,"start-fresh"),confirmLabel:N.kind==="ide"?Za(v,"restart-ide"):N.providerSessionId?Nc(v,!0):Za(v,"start-fresh"),busyLabel:N.kind==="ide"?ei(v,"restart-ide"):N.providerSessionId?Wg(v,!0):ei(v,"start-fresh"),workspaceOptions:T,selectedWorkspaceKey:H,details:[{label:"Mode",value:C(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const q=T.find(J=>J.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(q),await f({...N,workspace:(q==null?void 0:q.workspacePath)??null})})}}}),[w,f,x,v]),A=l.useMemo(()=>S.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:Ot(N.conversation),secondary:x_(N.conversation,{timestampLabel:N.timestamp?Gp(N.timestamp):null}),unread:N.unread,onClick:()=>g(N.conversation)})),[g,S]),O=w.showAllRecent?_:_.slice(0,4),L=_.length>0,R=A.length>0,F=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`flex items-center justify-between gap-3 ${F} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:n.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[n.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":v("common.back"),children:n.jsx(td,{size:18})}),n.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[n.jsx("div",{className:"flex items-center gap-2 text-[17px] leading-[26px] font-extrabold tracking-tight text-text-primary truncate",children:Tn(e,{fallbackId:e.id})}),n.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||v("machine.mobile.machineFallback"),e.version?` · v${e.version}`:""]})]})]})}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[R&&n.jsxs("section",{className:"flex flex-col gap-0",children:[n.jsx("div",{className:"text-2xs font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:v("machine.mobile.currentChats")}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(N=>n.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${N.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:N.onClick,children:[n.jsx("span",{className:"text-sm font-bold text-text-primary",children:N.primary}),n.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))})]}),L&&n.jsxs("section",{className:"flex flex-col gap-0",children:[n.jsx("div",{className:"text-2xs font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:v("machine.mobile.recentLaunches")}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:O.map(N=>n.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:N.onClick,children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[n.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:N.primary}),N.updatedLabel&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:N.updatedLabel})]}),n.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))}),_.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:()=>w.setShowAllRecent(N=>!N),children:w.showAllRecent?v("machine.mobile.showFewer"):v("machine.mobile.showMore",{count:_.length-4})})})]}),n.jsxs("section",{className:"flex flex-col gap-0",children:[n.jsx("div",{className:"text-2xs font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:v("machine.mobile.inspect")}),n.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[a&&n.jsx("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:b,children:n.jsx("span",{className:"text-sm font-bold text-text-primary",children:v("machine.commandCenter.updateToVersion",{version:i})})}),n.jsx("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:y,children:n.jsx("span",{className:"text-sm font-bold text-text-primary",children:v("machine.mobile.machineDetails")})})]})]})]}),w.browseDialogOpen&&n.jsx(Yd,{title:v("machine.mobile.browseTitle"),description:v("machine.mobile.browseDescription"),currentPath:w.browseCurrentPath,directories:w.browseDirectories,busy:w.browseBusy,error:w.browseError,confirmLabel:v("machine.mobile.useThisFolder"),onClose:()=>w.setBrowseDialogOpen(!1),onNavigate:N=>{w.loadBrowsePath(N)},onConfirm:N=>{w.chooseCustomWorkspacePath(N),w.setBrowseDialogOpen(!1)}}),w.launchConfirm&&n.jsx(Oi,{title:w.launchConfirm.title,description:w.launchConfirm.description,details:w.launchConfirm.details,workspaceOptions:w.launchConfirm.workspaceOptions,selectedWorkspaceKey:w.launchConfirmWorkspaceKey,onWorkspaceChange:w.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:w.launchConfirm.providerType?Nc(v,!!w.launchConfirmResumeId):w.launchConfirm.confirmLabel,busyLabel:w.launchConfirm.providerType?void 0:w.launchConfirm.busyLabel,busy:w.launchConfirmBusy,showArgsInput:w.launchConfirm.showArgsInput,argsValue:w.launchConfirmArgs,onArgsChange:w.setLaunchConfirmArgs,showModelInput:w.launchConfirm.showModelInput,modelValue:w.launchConfirmModel,onModelChange:w.setLaunchConfirmModel,historyProviderNode:w.launchConfirm.providerType&&(w.launchConfirmSessionsLoading||w.launchConfirmSavedSessions.length>0)&&n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[n.jsxs("div",{className:"flex items-center justify-between mb-1",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted",children:v("launch.resumeSavedHistory")}),w.launchConfirmSessionsLoading&&n.jsx("div",{className:"text-3xs text-text-secondary font-medium",children:v("launch.loadingShort")})]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2",children:Ed(v)}),n.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[n.jsx("input",{type:"text",value:w.launchConfirmTextFilter,onChange:N=>w.setLaunchConfirmTextFilter(N.target.value),placeholder:v("machine.mobile.searchHistory"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),n.jsx("input",{type:"text",value:w.launchConfirmWorkspaceFilter,onChange:N=>w.setLaunchConfirmWorkspaceFilter(N.target.value),placeholder:v("machine.mobile.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),n.jsx("input",{type:"text",value:w.launchConfirmModelFilter,onChange:N=>w.setLaunchConfirmModelFilter(N.target.value),placeholder:v("machine.mobile.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),n.jsxs("select",{value:w.launchConfirmSortMode,onChange:N=>w.setLaunchConfirmSortMode(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[n.jsx("option",{value:"recent",children:v("machine.mobile.sortRecent")}),n.jsx("option",{value:"oldest",children:v("machine.mobile.sortOldest")}),n.jsx("option",{value:"messages",children:v("machine.mobile.sortMessages")})]})]}),n.jsxs("label",{className:"mb-2 flex items-center gap-2 text-2xs text-text-muted",children:[n.jsx("input",{type:"checkbox",checked:w.launchConfirmResumableOnly,onChange:N=>w.setLaunchConfirmResumableOnly(N.target.checked),disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),v("machine.mobile.resumableOnly")]}),n.jsxs("select",{value:w.launchConfirmResumeId,onChange:N=>w.setLaunchConfirmResumeId(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[n.jsx("option",{value:"",children:V1(v)}),w.filteredLaunchConfirmSavedSessions.map(N=>n.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":v("machine.mobile.workspaceMissing")]},N.providerSessionId))]}),!w.launchConfirmSessionsLoading&&w.launchConfirmSavedSessions.length>0&&w.filteredLaunchConfirmSavedSessions.length===0&&n.jsx("div",{className:"mt-2 text-2xs text-text-muted",children:v("machine.mobile.noHistoryMatches")}),w.launchConfirmResumeId&&(()=>{const N=w.filteredLaunchConfirmSavedSessions.find(B=>B.providerSessionId===w.launchConfirmResumeId);if(!N)return null;const I=_b(N,v);return n.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-2xs text-text-muted leading-relaxed",children:[n.jsx("div",{className:"font-semibold text-text-primary truncate",children:I.title}),n.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),n.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&n.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&n.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:w.handleConfirmLaunch,onCancel:w.closeLaunchConfirm}),m&&n.jsx(Cb,{section:u,onSectionChange:p})]})}const uh=8e3;function W2(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 Ib(e,t,s){const r=l.useRef(new Map),[,o]=l.useState(0),a=l.useCallback(()=>o(g=>g+1),[]);l.useEffect(()=>{const g=r.current;if(g.size===0)return;const f=Date.now();let y=!1;for(const[b,k]of g){const j=e.get(b),v=k.muted===void 0||(j?j.muted===k.muted:!1),C=k.hidden===void 0||(j?j.surfaceHidden===k.hidden:!1),x=f-k.at>uh;(v&&C||x)&&(g.delete(b),y=!0)}y&&a()},[e,a]),l.useEffect(()=>{if(r.current.size===0)return;const g=setInterval(()=>{const f=r.current,y=Date.now();let b=!1;for(const[k,j]of f)y-j.at>uh&&(f.delete(k),b=!0);b&&a(),f.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,f)=>{const y=r.current.get(g);r.current.set(g,{...y,...f,at:Date.now()}),a()},[a]),c=l.useCallback(g=>{const f=g.sessionId,y=f?r.current.get(f):void 0;return(y==null?void 0:y.muted)!==void 0?y.muted:Ns(g,e).muted??!1},[e]),d=l.useCallback(g=>{const f=g.sessionId,y=f?r.current.get(f):void 0;return(y==null?void 0:y.hidden)!==void 0?y.hidden:Ns(g,e).surfaceHidden??!1},[e]),u=l.useCallback((g,f)=>{const y=as(g),b=g.sessionId;!y||!b||(i(b,f),t(y,"set_conversation_prefs",{sessionId:b,...f,...Ai(g)}).then(k=>{const j=W2(k);j.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",j.reason),r.current.delete(b),a(),s==null||s(`Couldn't update conversation — ${j.reason}`))}).catch(k=>{console.warn("[conversation-prefs] set_conversation_prefs failed",k),r.current.delete(b),a();const j=k instanceof Error?k.message:String(k??"the daemon is unreachable");s==null||s(`Couldn't update conversation — ${j}`)}))},[t,i,a,s]),m=l.useCallback(g=>{u(g,{muted:!c(g)})},[u,c]),h=l.useCallback((g,f)=>{u(g,{hidden:f})},[u]),p=l.useCallback(g=>{u(g,{hidden:!d(g)})},[u,d]);return{isMuted:c,isHidden:d,toggleMute:m,setHidden:h,toggleHidden:p}}function La(e){return[...e].sort((t,s)=>{const r=s.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(s.conversation.tabKey)})}function U2(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:La(e)}function K2(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:La(s),unreadItems:La(r),workingItems:U2(o,t),completedItems:La(a)}}function Fi(e,t){if(!t)return!1;const s=e.filter(r=>r.type==="adhdev-daemon"&&Mb(r)==="Connected");return s.length===0?!0:s.every(r=>r._sessionListAuthoritative===!0)}function Mb(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 q2(e,t){if(!e)return[];const s=e.recentLaunches||[];return s.length>0?s.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:tr(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var i;const o=Co(r)?"cli":Nr(r)?"acp":"ide",a=tr(r.summaryMetadata);return{id:`${o}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(Co(r)?r.cliName||r.type:Nr(r)&&r.cliName||r.type),kind:o,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:Nr(r)?a||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,o)=>o.timestamp-r.timestamp).map(({timestamp:r,...o})=>o)}function z2(e,t,s=[]){const r=new Map;for(const a of t){const i=as(a.conversation),c=r.get(i);c?c.push(a):r.set(i,[a])}const o=new Map;for(const a of s){const i=as(a),c=o.get(i);c?c.push(a):o.set(i,[a])}return e.map(a=>{const i=r.get(a.id)||[],c=o.get(a.id)||[],d=[...i].sort((y,b)=>b.timestamp-y.timestamp)[0]||null,u=(d==null?void 0:d.conversation)||null,m=pc(a),h=i.filter(y=>y.unread||y.requiresAction).length,p=i.filter(y=>er(y.conversation)).length+c.filter(er).length,g=Mb(a),f=[a.platform||"machine",g].filter(Boolean);return{id:a.id,label:Tn(a,{fallbackId:a.id}),subtitle:f.join(" · "),unread:h,total:i.length,generatingCount:p,latestConversation:u,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:m,preview:u?y_(u,fg(u)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((a,i)=>{const c=a.latestTimestamp||a.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==c?d-c:a.label.localeCompare(i.label)})}function G2(e){return e==="chat"}function ma(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 V2({conversations:e,machineEntries:t,items:s,selectedConversation:r,selectedTabKey:o,screen:a,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:g,setSelectedTabKey:f,setScreen:y,setSelectedMachineId:b,setSection:k,setMachineBackTarget:j,resetMachineAction:v}){const C=l.useRef(null),x=l.useCallback(S=>{if(!(S!=null&&S.sessionId))return;const w=Ns(S,i),_=Math.max(Date.now(),Qs(S),w.lastUpdated||0);ma("mark_read:start",{tabKey:S.tabKey,sessionId:S.sessionId,displayPrimary:Ot(S),inboxBucket:w.inboxBucket,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:Qs(S),readAt:_}),c(as(S)||S.routeId,"mark_session_seen",{sessionId:S.sessionId,providerSessionId:S.providerSessionId,seenAt:_,completionMarker:w.completionMarker}).then(A=>{ma("mark_read:result",{tabKey:S.tabKey,sessionId:S.sessionId,result:A})}).catch(A=>{ma("mark_read:error",{tabKey:S.tabKey,sessionId:S.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var w;if(!r){G2(a)&&y("inbox"),f(((w=e[0])==null?void 0:w.tabKey)||null),C.current=null;return}if(a!=="chat"){C.current=null;return}const S=`${r.tabKey}:${r.sessionId||""}`;C.current!==S&&(C.current=S,x(r))},[e,x,a,r,y,f]),l.useEffect(()=>{if(!d)return;const S=e.find(w=>w.tabKey===d);S&&(f(S.tabKey),y("chat"),u==null||u())},[e,u,d,y,f]),l.useEffect(()=>{if(!m)return;const S=t.find(w=>w.id===m);S&&(b(S.id),v(),k("machines"),j("inbox"),y("machine"),h==null||h())},[t,h,m,v,j,y,k,b]),l.useEffect(()=>{p&&(k(p),y("inbox"),g==null||g())},[g,p,y,k]),l.useEffect(()=>{const S=s.filter(w=>w.inboxBucket==="task_complete"||w.unread);S.length!==0&&ma("inbox_state",{screen:a,selectedTabKey:o,items:S.map(w=>{const _=Ns(w.conversation,i);return{liveState:_,tabKey:w.conversation.tabKey,sessionId:w.conversation.sessionId,displayPrimary:Ot(w.conversation),serverBucket:_.inboxBucket,computedBucket:w.inboxBucket,serverUnread:_.unread,computedUnread:w.unread,lastSeenAt:_.lastSeenAt,lastUpdated:_.lastUpdated,activityAt:Qs(w.conversation)}})})},[s,i,a,o]),{markConversationRead:x}}const Y2="Cannot update: node update policy unavailable; refresh and try again";async function Q2(e,t,s){var o,a,i,c,d,u;const r=Ud(s);if(!r)return{state:"error",message:Y2};try{const m=await e(t,"daemon_upgrade",r);return(o=m==null?void 0:m.result)!=null&&o.alreadyLatest?{state:"done",message:`Already on v${((a=m==null?void 0:m.result)==null?void 0:a.version)||"latest"}.`}:(i=m==null?void 0:m.result)!=null&&i.upgraded||(c=m==null?void 0:m.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((d=m==null?void 0:m.result)==null?void 0:d.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((u=m==null?void 0:m.result)==null?void 0:u.error)||"Upgrade failed"}}catch(m){return{state:"error",message:m instanceof Error?m.message:"Upgrade failed"}}}function J2(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function mh(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function X2(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Z2({sendDaemonCommand:e,navigate:t,ides:s,conversations:r}){const{launchCli:o}=bi(),[a,i]=l.useState("idle"),[c,d]=l.useState(""),[u,m]=l.useState(null),h=l.useCallback(()=>{i("idle"),d(""),m(null)},[]),p=l.useCallback(async(v,C,x)=>{var S;try{i("loading"),d(`Launching ${C}…`);const w={ideType:C,enableCdp:!0};(S=x==null?void 0:x.workspacePath)!=null&&S.trim()&&(w.workspace=x.workspacePath.trim()),await e(v,"launch_ide",w),i("done"),d(`${C} launch requested`)}catch(w){i("error"),d(w instanceof Error?w.message:"Launch IDE failed"),console.error("Launch IDE failed",w)}},[e]),g=l.useCallback(async(v,C,x)=>{if(C.trim())try{i("loading"),d(x!=null&&x.createIfMissing?"Creating folder…":"Saving workspace…");const S=await e(v,"workspace_add",{path:C.trim(),createIfMissing:(x==null?void 0:x.createIfMissing)===!0});if(S!=null&&S.success){i("done"),d(x!=null&&x.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((S==null?void 0:S.error)||"Could not save workspace")}catch(S){i("error"),d(S instanceof Error?S.message:"Could not save workspace")}},[e]),f=l.useCallback(async v=>{i("loading"),d("Starting daemon upgrade…");const C=s.find(S=>S.id===v||S.daemonId===v),x=await Q2(e,v,C);i(x.state),d(x.message)},[s,e]),y=l.useCallback(async(v,C,x,S)=>{var A,O,L;const w=Date.now(),_={machineId:v,kind:C,providerType:x,workspaceId:(S==null?void 0:S.workspaceId)||null,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:w};try{i("loading"),d(`Launching ${x}…`),m(_);const R={cliType:x};(A=S==null?void 0:S.workspacePath)!=null&&A.trim()?R.dir=S.workspacePath.trim():S!=null&&S.workspaceId?R.workspaceId=S.workspaceId:S!=null&&S.useHome&&(R.useHome=!0),S!=null&&S.resumeSessionId&&(R.resumeSessionId=S.resumeSessionId),(O=S==null?void 0:S.args)!=null&&O.trim()&&(R.cliArgs=S.args.trim().split(/\s+/).filter(Boolean)),(L=S==null?void 0:S.model)!=null&&L.trim()&&(R.initialModel=S.model.trim());const F=await o(v,R),N=(F==null?void 0:F.result)||F,I=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);if(F!=null&&F.success&&I){m(null),i("done"),d(`${x} launched`),t(_o(I));return}if(F!=null&&F.success){i("loading"),d(`${x} launch requested — waiting for session…`);return}m(null),i("error"),d((F==null?void 0:F.error)||(N==null?void 0:N.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(R){if(X2(R)){i("loading"),d(`${x} launch requested — waiting for session…`);return}m(null),i("error"),d(R instanceof Error?R.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),b=l.useCallback(async(v,C)=>{try{const x=await e(v,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),S=(x==null?void 0:x.result)??x;return Array.isArray(S==null?void 0:S.sessions)?S.sessions:[]}catch(x){return console.error("Failed to list saved sessions on mobile:",x),[]}},[e]),k=l.useCallback(async(v,C)=>Gd(e,v,C),[e]);l.useEffect(()=>{if(!u)return;const v=mh(u.workspacePath),C=s.find(S=>{var R,F,N,I;if(!S||S.type==="adhdev-daemon"||J2(S.daemonId||S.id)!==u.machineId||(S.transport==="acp"?"acp":S.transport==="pty"?"cli":null)!==u.kind||String(S.agentType||S.type||"")!==u.providerType)return!1;const O=String(S.providerSessionId||"");if(u.resumeSessionId&&O)return O===u.resumeSessionId;if(v){const B=mh(S.workspace||S.runtimeWorkspaceLabel);return B?B===v:!1}return Number(S.lastUpdated||S._lastUpdate||S.timestamp||((I=(N=(F=(R=S.activeChat)==null?void 0:R.messages)==null?void 0:F.at)==null?void 0:N.call(F,-1))==null?void 0:I.timestamp)||0)>=u.startedAt-5e3});if(!C)return;const x=kb({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:r});x&&(m(null),i("done"),d(`${u.providerType} launched`),t(_o(x)))},[r,s,t,u]),l.useEffect(()=>{if(!u)return;const v=window.setTimeout(()=>{m(C=>!C||C.startedAt!==u.startedAt?C:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(v)},[u]);const j=l.useCallback(async(v,C)=>{var x;if(C.kind==="ide"&&C.providerType){await p(v,C.providerType,{workspacePath:C.workspace||null});return}if((C.kind==="cli"||C.kind==="acp")&&C.providerType){const S=((x=C.workspace)==null?void 0:x.trim())||"";await y(v,C.kind,C.providerType,{workspacePath:S||null,useHome:!S,resumeSessionId:C.providerSessionId||null})}},[p,y]);return{machineAction:{state:a,message:c},resetMachineAction:h,handleLaunchDetectedIde:p,handleAddWorkspace:g,handleMachineUpgrade:f,handleLaunchWorkspaceProvider:y,handleListSavedSessions:b,handleBrowseDirectory:k,handleOpenRecent:j}}function eI({conversations:e,selectedConversation:t,machineBackTarget:s,markConversationRead:r,resetMachineAction:o,setSelectedTabKey:a,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:u}){const m=l.useCallback(k=>{a(k.tabKey),i("chat"),r(k)},[r,i,a]),h=l.useCallback(k=>{const j=e.find(v=>v.routeId===k.routeId&&v.streamSource==="native");j&&(a(j.tabKey),i("chat"),r(j))},[e,r,i,a]),p=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),g=l.useCallback((k,j="inbox")=>{c(k),o(),d("machines"),u(j),i("machine")},[o,u,i,d,c]),f=l.useCallback(k=>{const j=as(k);j&&g(j,"chat")},[g]),y=l.useCallback(()=>{o(),i(s)},[s,o,i]),b=l.useCallback(k=>{d(k),i("inbox")},[i,d]);return{openConversation:m,openNativeConversation:h,backFromConversation:p,openMachine:g,openConversationMachine:f,backFromMachine:y,changeMachineSection:b}}function Ao(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function tI(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function nI({conversations:e,hiddenConversations:t,ides:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:g,onOpenHistory:f,onOpenRemote:y,onStopCli:b,wsStatus:k,isConnected:j,initialDataLoaded:v=!0,onShowAllHiddenConversations:C,onHideConversation:x,onShowHiddenConversation:S,onOpenMeshGraph:w,onOpenNewSession:_,liveSessionInboxState:A,setCliViewModeOverrides:O}){const[L,R]=l.useState(()=>{var Y;return((Y=e[0])==null?void 0:Y.tabKey)||null}),[F,N]=l.useState(()=>e[0]?"chat":"inbox"),[I,B]=l.useState("chats"),[T,H]=l.useState(null),[q,J]=l.useState("inbox"),K=l.useRef([]),M=rr(),D="1.0.59",P=l.useMemo(()=>e.find(Y=>Y.tabKey===L)||e[0]||null,[e,L]),$=l.useMemo(()=>P?s.find(Y=>Y.id===P.routeId):void 0,[s,P]),W=l.useMemo(()=>!P||vt(P)||!St(P)?null:$r(P),[P]),U=l.useMemo(()=>s.filter(Y=>Y.type==="adhdev-daemon").sort(Ua),[s]),ae=l.useMemo(()=>U.find(Y=>Y.id===T)||null,[U,T]),be=Ii({sendDaemonCommand:o,activeConv:P||void 0,setActionLogs:a,isStandalone:i}),V=Z2({sendDaemonCommand:o,navigate:M,ides:s,conversations:e}),we=SC(e),ce=l.useMemo(()=>e.map(Y=>{const me=F==="chat"&&(P==null?void 0:P.tabKey)===Y.tabKey,fe=Si(Y,A,{hideOpenTaskCompleteUnread:!0,isOpenConversation:me}),E=Qs(Y),oe=fg(Y),Ie=Sg(Y,oe);return{conversation:Y,timestamp:E,preview:Ie,unread:fe.unread,requiresAction:fe.requiresAction,isWorking:fe.isWorking,inboxBucket:fe.inboxBucket}}),[e,A,F,P,we]),{markConversationRead:de}=V2({conversations:e,machineEntries:U,items:ce,selectedConversation:P,selectedTabKey:L,screen:F,liveSessionInboxState:A,sendDaemonCommand:o,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:g,setSelectedTabKey:R,setScreen:N,setSelectedMachineId:H,setSection:B,setMachineBackTarget:J,resetMachineAction:V.resetMachineAction}),ne=eI({conversations:e,selectedConversation:P,machineBackTarget:q,markConversationRead:de,resetMachineAction:V.resetMachineAction,setSelectedTabKey:R,setScreen:N,setSelectedMachineId:H,setSection:B,setMachineBackTarget:J}),{isMuted:ee,toggleMute:ue}=Ib(A,o),{attentionItems:je,unreadItems:X,workingItems:G,completedItems:z}=l.useMemo(()=>K2(ce,K.current),[ce]);l.useEffect(()=>{K.current=G.map(Y=>Y.conversation.tabKey)},[G]);const ie=l.useMemo(()=>ae?ce.filter(Y=>as(Y.conversation)===ae.id):[],[ce,ae]),Ne=l.useMemo(()=>q2(ae,s),[s,ae]),Be=!!ae&&Kd(ae,Hs(ae,D)),Le=l.useMemo(()=>(ae==null?void 0:ae.availableProviders)||[],[ae]),Je=l.useMemo(()=>Le.filter(Y=>Ao(Y,"cli")).map(Y=>({type:Y.type,displayName:Y.displayName||Y.type,icon:Y.icon})),[Le]),Se=l.useMemo(()=>Le.filter(Y=>Ao(Y,"acp")).map(Y=>({type:Y.type,displayName:Y.displayName||Y.type,icon:Y.icon})),[Le]),he=l.useMemo(()=>z2(U,ce,t),[ce,U,t]),pe=l.useMemo(()=>Fi(s,v),[s,v]),Ee=l.useCallback(async Y=>{ae&&await V.handleOpenRecent(ae.id,Y)},[V,ae]);return n.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:F==="chat"&&P?n.jsx(R2,{selectedConversation:P,isAcp:vt(P),isStandalone:i,selectedIdeEntry:$,actionLogs:r,userName:c,commands:be,onBack:ne.backFromConversation,onOpenNativeConversation:ne.openNativeConversation,onOpenMachine:ne.openConversationMachine,onOpenHistory:f,onOpenRemote:y,onOpenMeshGraph:w,onStopCli:b,cliViewMode:W,onSetCliViewMode:async Y=>{await ub({conversation:P,mode:Y,ides:s,sendDaemonCommand:o,setCliViewModeOverrides:O})}}):F==="machine"&&ae?n.jsx(B2,{selectedMachineEntry:ae,selectedMachineConversations:ie,selectedMachineRecentLaunches:Ne,cliProviders:Je,acpProviders:Se,selectedMachineNeedsUpgrade:Be,appVersion:D,machineAction:V.machineAction,isStandalone:i,section:I,showBottomNav:q==="inbox",onBack:ne.backFromMachine,onSectionChange:ne.changeMachineSection,onOpenConversation:ne.openConversation,onOpenRecent:Ee,onOpenMachineDetails:()=>M(`/machines/${ae.id}`),onMachineUpgrade:()=>V.handleMachineUpgrade(ae.id),onBrowseDirectory:Y=>V.handleBrowseDirectory(ae.id,Y),onListSavedSessions:Y=>V.handleListSavedSessions(ae.id,Y)}):n.jsx(E2,{section:I,attentionItems:je,unreadItems:X,workingItems:G,completedItems:z,hiddenConversations:t,machineCards:he,getAvatarText:tI,actionLogs:r,sendDaemonCommand:o,onOpenConversation:ne.openConversation,onShowAllHidden:C,onHideConversation:x,onShowHiddenConversation:S,onOpenMeshGraph:w,onStopCli:b,onOpenNewSession:_,onOpenMachine:ne.openMachine,onOpenSettings:()=>M("/settings"),onSectionChange:B,wsStatus:k,isConnected:j,initialDataLoaded:v,conversationsLoaded:pe,isStandalone:i,isConversationMuted:ee,onToggleMuteConversation:ue})})}function kl(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function sI({conversations:e,numGroups:t,onMoveTab:s,onReceiveTab:r,onOwnTabDrop:o,onClearPreviewOrder:a}){const i=l.useRef(0),[c,d]=l.useState(!1),[u,m]=l.useState(null),h=l.useCallback(()=>{i.current=0,d(!1),m(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const p=l.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!kl(t,s)){m("merge");return}const k=b.currentTarget.getBoundingClientRect(),j=b.clientX-k.left,v=k.width/3;j<v?m("split-left"):j>v*2?m("split-right"):m("merge")},[t,s]),f=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),m(null))},[]),y=l.useCallback(b=>{i.current=0,d(!1);const k=b.dataTransfer.getData("text/tab-key"),j=k?e.some(C=>C.tabKey===k):!1,v=u;if(m(null),a(),!!k){if(b.preventDefault(),v==="split-left"&&kl(t,s)){s==null||s(k,"split-left");return}if(v==="split-right"&&kl(t,s)){s==null||s(k,"split-right");return}if(j){o(k);return}r==null||r(k)}},[e,u,t,s,r,o,a]);return{dragOver:c,dropAction:u,resetDragState:h,handleDragEnter:p,handleDragOver:g,handleDragLeave:f,handleDrop:y}}function rI(e,t){const s=new Set(t.map(a=>a.tabKey)),r=e.filter(a=>s.has(a)),o=t.filter(a=>!e.includes(a.tabKey)).map(a=>a.tabKey);return[...r,...o]}function oI({conversations:e,initialActiveTabId:t,initialTabOrder:s,onActiveTabChange:r,onTabOrderChange:o}){const[a,i]=l.useState(t??null),[c,d]=l.useState(s??[]),[u,m]=l.useState(null),h=l.useRef(null),p=l.useRef(null),g=l.useRef(r),f=l.useRef(o);l.useEffect(()=>{g.current=r},[r]),l.useEffect(()=>{f.current=o},[o]),l.useEffect(()=>{t&&t!==a&&i(t)},[t,a]),l.useEffect(()=>{d(w=>{const _=rI(w,e);return _.length===w.length&&_.every((A,O)=>A===w[O])?w:_})},[e]);const y=l.useMemo(()=>{const w=u??c;if(w.length===0)return e;const _=new Map(w.map((A,O)=>[A,O]));return[...e].sort((A,O)=>{const L=_.get(A.tabKey)??999,R=_.get(O.tabKey)??999;return L-R})},[e,u,c]);l.useEffect(()=>{var _,A;if(y.length===0){a!==null&&(i(null),(_=g.current)==null||_.call(g,null));return}if(a&&y.some(O=>O.tabKey===a))return;const w=y[0].tabKey;w!==a&&(i(w),(A=g.current)==null||A.call(g,w))},[y,a]);const b=l.useMemo(()=>y.find(w=>w.tabKey===a),[y,a]),k=l.useCallback(w=>{var _;i(w),(_=g.current)==null||_.call(g,w)},[]),j=l.useCallback((w,_,A)=>{d(O=>{var N;const L=O.filter(I=>I!==w),R=L.indexOf(_);if(R<0)return O;const F=A==="left"?R:R+1;return L.splice(F,0,w),(N=f.current)==null||N.call(f,L),L}),m(null)},[]),v=l.useCallback((w,_,A)=>{const L=(c.length>0?c:e.map(N=>N.tabKey)).filter(N=>N!==w),R=L.indexOf(_);if(R<0)return;const F=A==="left"?R:R+1;L.splice(F,0,w),h.current=L,m(L)},[c,e]),C=l.useCallback(()=>{var _;const w=h.current;w&&(d(w),(_=f.current)==null||_.call(f,w))},[]),x=l.useCallback(()=>{h.current=null,m(null)},[]),S=l.useCallback(w=>{d(_=>{var O;const A=_.filter(L=>L!==w);return A.push(w),(O=f.current)==null||O.call(f,A),A})},[]);return{activeTabId:a,activeConv:b,sortedConversations:y,previewOrderRef:h,draggingTabRef:p,selectTab:k,handleTabReorder:j,updatePreviewOrder:v,commitPreviewOrder:C,clearPreviewOrder:x,moveTabToEnd:S,setDraggingTabKey:w=>{p.current=w}}}function aI({dropAction:e,canSplit:t}){const{t:s}=ve("common");return n.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[n.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:n.jsx("div",{className:"px-3 py-1.5 rounded-full text-2xs font-semibold text-white bg-black/45 backdrop-blur-sm",children:s("paneGroup.dropSplitLeft")})}),n.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:n.jsx("div",{className:"px-3 py-1.5 rounded-full text-2xs font-semibold text-white bg-black/45 backdrop-blur-sm",children:s("paneGroup.dropMoveHere")})}),n.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:n.jsx("div",{className:"px-3 py-1.5 rounded-full text-2xs font-semibold text-white bg-black/45 backdrop-blur-sm",children:s("paneGroup.dropSplitRight")})})]})}function Qd({conversationsCount:e,isSplitMode:t,isStandalone:s,hasRegisteredMachines:r=!1,suppressGuide:o=!1,onOpenNewSession:a,isLoading:i=!1}){const{t:c}=ve("common");if(o)return n.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:c("paneGroup.noActiveAgent")});if(i)return n.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center gap-3 -mt-8 text-text-muted",children:[n.jsx(ln,{}),n.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const d=!s&&!r,u=r&&!!a,m=c(r?"paneGroup.noConversations":s?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),h=c(r?"paneGroup.newSessionDescription":s?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?n.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[n.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),n.jsxs("div",{className:"text-center max-w-lg",children:[n.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:m}),n.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:h}),u&&n.jsx("div",{className:"flex items-center justify-center mb-4",children:n.jsxs("button",{type:"button",onClick:a,className:"btn btn-primary btn-sm inline-flex items-center gap-2",title:c("paneGroup.newSession"),"aria-label":c("paneGroup.newSession"),children:[n.jsx(jo,{size:14}),n.jsx("span",{children:c("paneGroup.newSession")})]})}),d&&n.jsx(Nb,{}),d&&n.jsx("div",{className:"mt-8",children:n.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:c("machine.card.emptyDocsLink")})})]})]}):n.jsx("div",{className:"text-sm text-text-muted opacity-50",children:c(t?"paneGroup.moveTabHere":"paneGroup.noActiveAgent")})}const Rb="adhdev-tab-shortcuts";function Pb(){try{return JSON.parse(localStorage.getItem(Rb)||"{}")}catch{return{}}}function Lb({enabled:e=!0,sortedTabKeys:t,onFocus:s,onSelectTab:r}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[a,i]=l.useState(()=>Pb()),[c,d]=l.useState(null),u=l.useCallback(h=>{const p=[];return h.metaKey&&p.push(o?"⌘":"Meta"),h.ctrlKey&&p.push("Ctrl"),h.altKey&&p.push(o?"⌥":"Alt"),h.shiftKey&&p.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(p.push(h.key.length===1?h.key.toUpperCase():h.key),p.join("+"))},[o]),m=l.useCallback(h=>{i(h);try{localStorage.setItem(Rb,JSON.stringify(h))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const h=p=>{if(p.preventDefault(),p.stopPropagation(),p.key==="Escape"){d(null);return}const g=u(p);if(!g)return;const f={...a};for(const[y,b]of Object.entries(f))b===g&&delete f[y];f[c]=g,m(f),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,c,a,m,u]),l.useEffect(()=>{if(!e)return;const h=p=>{if(!(!p.ctrlKey&&!p.metaKey&&!p.altKey)){for(const[g,f]of Object.entries(a))if(t.includes(g)&&u(p)===f){p.preventDefault(),s(),r(g);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,a,t,s,r,u]),{isMac:o,tabShortcuts:a,shortcutListening:c,setShortcutListening:d,saveShortcuts:m}}const jl=e=>{e.preventDefault()},iI=l.memo(function({conv:t,isActive:s,isDraggedTab:r,isTaskCompleteUnread:o,shortcut:a,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:u,onConversationActivated:m,onPreviewReorder:h,onReorderTab:p,onCommitPreviewOrder:g,onClearPreviewOrder:f,onDragStateReset:y,onDragTabKeyChange:b,onReceiveTab:k,onOpenContextMenu:j,longPressTimer:v,isGroupActive:C}){const{t:x}=ve("common"),S=or(t),w=S.isGenerating?"agent-tab-generating":S.isWaiting?"agent-tab-waiting":"",_=S.isReconnecting,A=g_(t),O=b_(t),L=wg(t),R=l.useCallback(K=>{c.current=t.tabKey,b(t.tabKey),K.dataTransfer.setData("text/tab-key",t.tabKey),K.dataTransfer.effectAllowed="move"},[t.tabKey,c,b]),F=l.useCallback(()=>{c.current=null,b(null),g(),f(),y()},[c,b,g,f,y]),N=l.useCallback(K=>{const M=c.current;if(!(!M||M===t.tabKey)&&K.dataTransfer.types.includes("text/tab-key")){K.preventDefault(),K.stopPropagation();const D=K.currentTarget.getBoundingClientRect(),P=K.clientX<D.left+D.width/2?"left":"right";h(M,t.tabKey,P)}},[t.tabKey,c,h]),I=l.useCallback(K=>{K.preventDefault(),K.stopPropagation();const M=K.dataTransfer.getData("text/tab-key");if(M&&M!==t.tabKey){const D=K.currentTarget.getBoundingClientRect(),P=K.clientX<D.left+D.width/2?"left":"right";i.includes(M)?p(M,t.tabKey,P):k&&k(M)}f()},[t.tabKey,i,p,k,f]),B=l.useCallback(K=>{K.stopPropagation(),d(),u(t.tabKey),m(t)},[t,m,d,u]),T=l.useCallback(K=>{K.preventDefault(),j(K.clientX,K.clientY,t.tabKey)},[t.tabKey,j]),H=l.useCallback(K=>{const M=K.touches[0];v.current=setTimeout(()=>{j(M.clientX,M.clientY,t.tabKey)},600)},[t.tabKey,v,j]),q=l.useCallback(()=>{v.current&&clearTimeout(v.current)},[v]),J=["adhdev-dockview-tab",w,s&&"is-active",C&&"is-group-active",_&&"is-reconnecting"].filter(Boolean).join(" ");return n.jsxs("div",{"data-tabkey":t.tabKey,className:J,draggable:!0,onDragStart:R,onDragEnd:F,onDragOver:N,onDrop:I,onClick:B,onContextMenu:T,onTouchStart:H,onTouchEnd:q,onTouchMove:q,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[L&&n.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:x("paneGroup.meshChat"),"aria-label":x("paneGroup.meshChat"),children:n.jsx(Gn,{size:11})}),o&&n.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),n.jsx("div",{className:"adhdev-dockview-tab-status",children:S.isGenerating?n.jsx(ln,{size:12,thickness:2,color:"success"}):S.isWaiting?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):_?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):S.isConnecting?n.jsx(ln,{size:12,thickness:2}):t.connectionState==="connected"?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):n.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),A.length>0&&n.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:O,"aria-label":O||A.join(" · "),children:A.join(" · ")}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("span",{className:"adhdev-dockview-tab-primary",title:Ot(t),children:Ot(t)}),n.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[_?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Gs(t)}):S.isConnecting?n.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Gs(t),n.jsx("span",{className:"connecting-dots"})]}):n.jsx("span",{className:"truncate",children:Gs(t)}),n.jsx(Cd,{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 lI({conversations:e,activeTabId:t,groupIndex:s,unreadTabKeys:r,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:u,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:g,onReceiveTab:f,onHideTab:y,isGroupActive:b,allowTabShortcuts:k=!0}){const{t:j}=ve("common"),[v,C]=l.useState(null),x=l.useRef(null),S=l.useRef(null),w=l.useMemo(()=>e.map(N=>N.tabKey),[e]);Lo("PaneGroupTabBar",{groupIndex:s,activeTabId:t,tabCount:e.length,ctxMenuTab:(v==null?void 0:v.tabKey)||null});const{isMac:_,tabShortcuts:A,shortcutListening:O,setShortcutListening:L,saveShortcuts:R}=Lb({enabled:k,sortedTabKeys:e.map(N=>N.tabKey),onFocus:a,onSelectTab:i});l.useEffect(()=>{if(!v)return;const N=I=>{const B=document.querySelector("[data-pane-context-menu]");B&&B.contains(I.target)||C(null)};return window.addEventListener("mousedown",N,!0),()=>window.removeEventListener("mousedown",N,!0)},[v]),l.useEffect(()=>{const N=S.current;if(!N)return;const I=B=>{Math.abs(B.deltaY)<=Math.abs(B.deltaX)||(B.preventDefault(),N.scrollLeft+=B.deltaY)};return N.addEventListener("wheel",I,{passive:!1}),()=>N.removeEventListener("wheel",I)},[]);const F=l.useCallback((N,I,B)=>{C({x:N,y:I,tabKey:B})},[]);return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:n.jsxs("div",{ref:S,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(N=>n.jsx(iI,{conv:N,isActive:t===N.tabKey,isDraggedTab:o.current===N.tabKey,isTaskCompleteUnread:r.has(N.tabKey),shortcut:k?A[N.tabKey]:void 0,conversationKeys:w,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:u,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:g,onReceiveTab:f,onOpenContextMenu:F,longPressTimer:x,isGroupActive:b},N.tabKey)),e.length===0&&n.jsx("div",{className:"p-2 text-xs opacity-40",children:j("paneGroup.noTabsInGroup")})]})}),v&&n.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:v.x,top:v.y},children:[k&&n.jsxs(n.Fragment,{children:[n.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:jl,onClick:N=>{N.stopPropagation(),L(v.tabKey),C(null)},children:["⌨ ",A[v.tabKey]?j("paneGroup.changeShortcut",{shortcut:A[v.tabKey]}):j("paneGroup.shortcutSetTitle")]}),A[v.tabKey]&&n.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:jl,onClick:()=>{const N={...A};delete N[v.tabKey],R(N),C(null)},children:["✕ ",j("paneGroup.removeShortcut")]})]}),y&&n.jsxs(n.Fragment,{children:[k&&n.jsx("div",{className:"border-t border-border-subtle my-1"}),n.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:jl,onClick:()=>{y(v.tabKey),C(null)},children:n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(pi,{size:12}),j("paneGroup.hideFromDashboard")]})})]})]}),k&&O&&n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>L(null),children:n.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:N=>N.stopPropagation(),children:[n.jsxs("div",{className:"text-sm font-bold text-text-primary mb-2",children:["⌨ ",j("paneGroup.shortcutSetTitle")]}),n.jsx("div",{className:"text-xs text-text-secondary mb-4",children:j("paneGroup.shortcutPressCombo",{example1:_?"⌘+1":"Ctrl+1",example2:_?"⌥+A":"Alt+A"})}),n.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:j("paneGroup.shortcutListening")}),n.jsx("div",{className:"text-3xs text-text-muted mt-3",children:j("paneGroup.pressEscToCancel")})]})})})]})}function cI({conversations:e,ides:t,clearedTabs:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d=!0,userName:u,groupIndex:m,onFocus:h,isSplitMode:p,numGroups:g,onMoveTab:f,onReceiveTab:y,style:b,onActiveTabChange:k,initialActiveTabId:j,initialTabOrder:v,onTabOrderChange:C,onHideTab:x,isFocused:S,allowTabShortcuts:w=!0,onOpenNewSession:_,liveSessionInboxState:A}){const{sendCommand:O}=_t(),L=l.useRef(null),{activeTabId:R,activeConv:F,sortedConversations:N,draggingTabRef:I,selectTab:B,handleTabReorder:T,updatePreviewOrder:H,commitPreviewOrder:q,clearPreviewOrder:J,moveTabToEnd:K,setDraggingTabKey:M}=oI({conversations:e,initialActiveTabId:j,initialTabOrder:v,onActiveTabChange:k,onTabOrderChange:C}),D=Ii({sendDaemonCommand:o,activeConv:F,setActionLogs:a,isStandalone:i}),{dragOver:P,dropAction:$,resetDragState:W,handleDragEnter:U,handleDragOver:ae,handleDragLeave:be,handleDrop:V}=sI({conversations:e,numGroups:g,onMoveTab:f,onReceiveTab:y,onOwnTabDrop:K,onClearPreviewOrder:J}),we=F&&!vt(F)&&$r(F)==="terminal",ce=l.useMemo(()=>F?t.find(ue=>ue.id===F.routeId):void 0,[t,F]),de=l.useMemo(()=>F?r.filter(ue=>ue.routeId===F.tabKey):[],[r,F]),ne=l.useMemo(()=>new Set(N.filter(ue=>LS(ue,A,{isOpenConversation:ue.tabKey===R})).map(ue=>ue.tabKey)),[R,A,N]);Lo("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:R,dragOver:P});const ee=l.useCallback(ue=>{ue.streamSource==="agent-stream"&&ue.agentType&&O(ue.routeId,Xf(),{agentType:ue.agentType,...ue.sessionId&&{targetSessionId:ue.sessionId}}).catch(()=>{})},[O]);return n.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...b,outline:P?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[n.jsx(lI,{conversations:N,activeTabId:R,groupIndex:m,numGroups:g,unreadTabKeys:ne,draggingTabRef:I,onFocus:h,onSelectTab:B,onConversationActivated:ee,onPreviewReorder:H,onReorderTab:T,onCommitPreviewOrder:q,onClearPreviewOrder:J,onDragStateReset:W,onDragTabKeyChange:M,onMoveTab:f,onReceiveTab:y,onHideTab:x,isGroupActive:S??!1,allowTabShortcuts:w}),n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:U,onDragOver:ae,onDragLeave:be,onDrop:V,children:[P&&n.jsx(aI,{dropAction:$,canSplit:!!(g<4&&f)}),F?n.jsx(Vd,{activeConv:F,clearToken:s[F.tabKey]||0,isCliTerminal:!!we,ideEntry:ce,terminalRef:L,commands:D,actionLogs:de,userName:u,isInputActive:!p||!!S}):n.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:n.jsx(Qd,{conversationsCount:e.length,isSplitMode:p,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:_,isLoading:!Fi(t,d)})})]})]})}function dI({containerRef:e,isSplitMode:t,numGroups:s,groupSizes:r,groupedConvs:o,clearedTabs:a,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:u,isStandalone:m,hasRegisteredMachines:h,initialDataLoaded:p,userName:g,focusedGroup:f,focusGroup:y,moveTabToGroup:b,splitTabRelative:k,closeGroup:j,handleResizeStart:v,groupActiveTabIds:C,setGroupActiveTab:x,groupTabOrders:S,setGroupTabOrder:w,toggleHiddenTab:_,onOpenNewSession:A,allowTabShortcuts:O=!0,liveSessionInboxState:L}){const{t:R}=ve("common");return n.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:o.map((F,N)=>{const I=t&&r.length===s?`${r[N]}%`:void 0;return n.jsxs(It.Fragment,{children:[t&&N>0&&n.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:B=>v(N-1,B),onDoubleClick:()=>j(N),title:R("paneGroup.resizeHandleHint"),children:n.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),n.jsx(cI,{style:t?{flexBasis:I??`${100/s}%`,flexGrow:I?0:1,flexShrink:I?0:1}:void 0,conversations:F,clearedTabs:a,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:u,isStandalone:m,hasRegisteredMachines:h,initialDataLoaded:p,userName:g,groupIndex:N,isFocused:t&&f===N,onFocus:()=>y(N),isSplitMode:t,numGroups:s,onMoveTab:(B,T)=>{T==="left"&&N>0?b(B,N-1):T==="right"&&N<s-1?b(B,N+1):T==="split-left"&&s<4?k(B,N,"left"):T==="split-right"&&s<4&&k(B,N,"right")},onReceiveTab:B=>b(B,N),onActiveTabChange:B=>x(N,B),initialActiveTabId:C[N],initialTabOrder:S[N],onTabOrderChange:B=>w(N,B),onHideTab:_,onOpenNewSession:A,allowTabShortcuts:O,liveSessionInboxState:L})]},N)})})}const Eb="adhdev-dashboard-action-shortcuts",uI=1200,mI=[["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 hI(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function wt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Db(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:wt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:wt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:wt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:wt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:wt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:wt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:wt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:wt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:wt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:wt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:wt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:wt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:wt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:wt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:wt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:wt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:wt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:wt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:wt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:wt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:wt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:wt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:wt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:wt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:wt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:wt("toggleCliView",e)}]}function Lc(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function oi(e){const t=Object.fromEntries(Db(e).map(s=>[s.id,s.defaultShortcut]));try{const s=JSON.parse(localStorage.getItem(Eb)||"{}"),r={...t,...s};for(const[o,a]of mI)r[o]===a&&(r[o]=t[o]);return r}catch{return t}}function Ob(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function pI({enabled:e=!0,onTrigger:t}){const s=hI(),[r,o]=l.useState(()=>oi(s)),[a,i]=l.useState(null),[c,d]=l.useState([]),u=l.useRef({parts:[],timer:null}),m=l.useCallback(y=>{const b=[];return y.metaKey&&b.push(s?"⌘":"Meta"),y.ctrlKey&&b.push("Ctrl"),y.altKey&&b.push(s?"⌥":"Alt"),y.shiftKey&&y.key.length!==1&&b.push(s?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(y.key)?null:(b.push(Ob(y.key)),b.join("+"))},[s]),h=l.useCallback(y=>{o(y);try{localStorage.setItem(Eb,JSON.stringify(y))}catch{}},[]);l.useEffect(()=>{const y=oi(s),b=Object.entries(r),k=Object.entries(y);b.length===k.length&&b.every(([j,v])=>y[j]===v)||h(y)},[r,s,h]);const p=l.useCallback(()=>{typeof window<"u"&&u.current.timer!=null&&window.clearTimeout(u.current.timer),u.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(u.current.timer!=null&&window.clearTimeout(u.current.timer),u.current.timer=window.setTimeout(()=>{u.current={parts:[],timer:null}},uI))},[]);l.useEffect(()=>{if(!a)return;const y=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){i(null),d([]);return}const k=m(b);if(!k)return;const v=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(k);if(c.length===0&&v){d([k]);return}const x=[...c,k].slice(0,2).join(" "),S={...r};for(const[w,_]of Object.entries(S))_===x&&delete S[w];S[a]=x,h(S),i(null),d([])};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[r,m,h,a,c]),l.useEffect(()=>{if(!e||a)return;const y=b=>{if(b.defaultPrevented)return;const k=m(b);if(!k)return;const j=b.metaKey||b.ctrlKey||b.altKey;if(Lc(b.target))return;const v=u.current.parts,C=j?[k]:[...v.slice(-1),k].slice(-2),x=C.join(" "),S=C[C.length-1],w=Object.entries(r).filter(([,R])=>!!R),_=w.find(([,R])=>R===x);if(_){b.preventDefault(),p(),t(_[0]);return}if(w.some(([,R])=>R.startsWith(`${x} `))){b.preventDefault(),u.current.parts=C,g();return}const O=w.find(([,R])=>R===S);if(O){b.preventDefault(),p(),t(O[0]);return}if(w.some(([,R])=>R.startsWith(`${S} `))){b.preventDefault(),u.current.parts=[S],g();return}p()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[r,g,e,m,t,p,a]),l.useEffect(()=>()=>p(),[p]);const f=l.useMemo(()=>Db(s),[s]);return{isMac:s,actionDefinitions:f,actionShortcuts:r,shortcutListening:a,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:h}}function fI({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 Fb(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function hh({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:s,ides:r}){return!e||s>0?!1:t?!Fb(r):!0}function gI({previousVisibleConversationCount:e,visibleConversationCount:t,ides:s}){return t>0||e<=0?!1:Fb(s)}const $b=1e3,bI=4;function ph(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function fh(e,t,s){return Math.abs(t.clientX-e.clientX)>s||Math.abs(t.clientY-e.clientY)>s}function xI({detachDelayMs:e=$b,stillnessThresholdPx:t=bI,onDetach:s,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:o=globalThis.clearTimeout.bind(globalThis)}){let a=null,i=null,c=null,d=null,u=null,m=!1;const h=()=>{u!=null&&(o(u),u=null)},p=()=>{h(),c=null},g=()=>{h(),a=null,i=null,c=null,d=null,m=!1},f=()=>{!a||!c||!d||m||u!=null||(u=r(()=>{u=null,!(!a||!c||!d||m)&&ph(d,i)&&(fh(c,d,t)||(m=!0,s({panelId:a,clientX:d.clientX,clientY:d.clientY})))},e))},y=k=>{if(!(!a||m)){if(!ph(k,i)){d={clientX:k.clientX,clientY:k.clientY},p();return}(!c||fh(c,k,t))&&(h(),c={clientX:k.clientX,clientY:k.clientY}),d={clientX:k.clientX,clientY:k.clientY},f()}},b=k=>{!a||m||(k&&(d={clientX:k.clientX,clientY:k.clientY}),p())};return{startDrag:k=>{h(),a=k.panelId,i=k.selfPanelBounds??null,c=null,d={clientX:k.clientX,clientY:k.clientY},m=!1},markSelfPanel:y,markNonSelfPanel:b,markNoDropTarget:b,markDockTarget:b,endDrag:g,isDragging:()=>a!=null,hasDetached:()=>m,dispose:g}}function yI(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Ea(e){return Ot(e)||e.tabKey}function vI(e){return`remote:${e}`}function Rn(e){return e.startsWith("remote:")}function gh(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Nl(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 Cl(e,t){e.classList.remove(zl.className,Gl.className),e.classList.add(t==="light"?zl.className:Gl.className)}function bh(e){return e?Array.from(new Set(e.groups.map(t=>{var s,r;return(r=(s=t.element)==null?void 0:s.ownerDocument)==null?void 0:r.defaultView}).filter(t=>!!t&&t!==window))):[]}function wI(e,t,s){var i;const r=[t];let o;for(const c of r){let d;for(const u of c){const m=e.addPanel({id:u.tabKey,component:"conversation",title:Ea(u),params:{kind:"conversation",tabKey:u.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});d||(d=m.id)}o=d??o}return s??((i=t[0])==null?void 0:i.tabKey)??null}function xh(e,t){const s=new Set(t.map(o=>o.tabKey)),r=new Map;for(const o of t)r.set(o.tabKey,(r.get(o.tabKey)||0)+1);for(const o of[...e.panels])Rn(o.id)||s.has(o.id)||e.removePanel(o);for(const o of t){const a=e.getPanel(o.tabKey);if(a){(r.get(o.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:o.tabKey,daemonId:o.daemonId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,panelId:a.id}),a.update({params:{tabKey:o.tabKey}}),a.title!==Ea(o)&&a.api.setTitle(Ea(o));continue}e.addPanel({id:o.tabKey,component:"conversation",title:Ea(o),params:{kind:"conversation",tabKey:o.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function yh(e,t,s){var d,u;const r=s?vI(s):null;for(const m of[...e.panels])Rn(m.id)&&(!r||m.id!==r)&&e.removePanel(m);if(!s||!r)return;const o=On(t,s);if(!o&&e.totalPanels===0)return;const a=e.getPanel(r),i=Ng(o);if(a){a.title!==i&&a.api.setTitle(i);return}const c=(o==null?void 0:o.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((u=e.panels.find(m=>!Rn(m.id)))==null?void 0:u.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:s},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function Hb({doId:e,targetSessionId:t,connState:s,viewMode:r}){const[o,a]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?Lt.onScreenshot("ide-page",(m,h)=>{if(m!==e)return;const p=new FileReader;p.onload=()=>a(p.result),p.readAsDataURL(h)}):void 0,[e]),l.useEffect(()=>{s!=="connected"&&a(null)},[s]),l.useEffect(()=>{var m;return e?((m=Lt.onStatus)==null?void 0:m.call(Lt,(h,p)=>{h===e&&p!=null&&p.screenshotUsage&&c(p.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{a(null)},[e,t]),l.useEffect(()=>{const u=e?Lt.get(e):null;if(!(!u||s!=="connected"))return r!=="chat"&&t?u.startScreenshots(t):u.stopScreenshots(t),()=>{u.stopScreenshots(t)}},[r,s,t,e]);const d=l.useCallback(async(u,m)=>{const h=e?Lt.get(e):null;return!h||s!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(u,m,t)},[e,s,t]);return{connScreenshot:o,screenshotUsage:i,handleRemoteAction:d}}const Bb=l.createContext(null);function $i(){const e=l.useContext(Bb);if(!e)throw new Error("DashboardDockviewContext missing");return e}function SI(e){const[,t]=l.useState(0);l.useEffect(()=>{const s=()=>t(o=>o+1),r=[e.api.onDidActiveGroupChange(s),e.api.onDidTitleChange(s),e.api.onDidGroupChange(s),e.containerApi.onDidActivePanelChange(s)];return()=>{for(const o of r)o.dispose()}},[e.api,e.containerApi])}function kI({params:e}){var u;const t=$i(),{t:s}=ve("common"),r=l.useMemo(()=>On([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),o=l.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:d}=Hb({doId:a,targetSessionId:r?Yf(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(rf,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:d})}):n.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:s("dashboard.remoteDialog.remoteUnavailable")})}function jI(){const e=$i();return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:n.jsx(Qd,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!Fi(e.ides,e.initialDataLoaded)})})}function NI(e){var v,C;SI(e);const t=$i(),{t:s}=ve("common"),r=l.useCallback(x=>{"button"in x&&x.button!==0||e.api.setActive()},[e.api]),o=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=o==null?void 0:o.sessionId,i=l.useCallback(x=>YC(x),[]),c=l.useCallback(()=>VC(a),[a]),d=l.useSyncExternalStore(i,c,c);if(e.params.kind==="remote"){const x=On([...t.conversationsByTabKey.values()],e.params.routeId),S=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,w=e.api.isGroupActive;return n.jsxs("div",{className:`adhdev-dockview-tab${S?" is-active":""}${w?" is-group-active":""}`,title:e.api.title||s("dashboard.remoteDialog.remoteFallback"),"data-tab-key":(x==null?void 0:x.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:x!=null&&x.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:x.machineName})]}):n.jsx("span",{children:s("dashboard.remoteDialog.liveRemoteView")})})]})]})}const u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)return n.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:n.jsx("div",{className:"adhdev-dockview-tab-copy",children:n.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const m=((C=e.api.group.activePanel)==null?void 0:C.id)===e.api.id,h=e.api.isGroupActive,p=Si(u,t.liveSessionInboxState,{isOpenConversation:m}),g=p.isReconnecting,f=p.isConnecting,y=p.isGenerating||d,b=p.isWaiting,k=p.unread,j=t.tabShortcuts[u.tabKey];return n.jsxs("div",{className:`adhdev-dockview-tab${m?" is-active":""}${h?" is-group-active":""}${g?" is-reconnecting":""}`,title:Ot(u),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:x=>{var S;x.preventDefault(),r(x),t.openTabContextMenu({x:x.clientX,y:x.clientY,tabKey:u.tabKey,sourceDocument:((S=x.target)==null?void 0:S.ownerDocument)??document})},children:[k&&n.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),n.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:y?n.jsx(ln,{size:12,thickness:2,color:"success"}):b?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):g?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):f?n.jsx(ln,{size:12,thickness:2}):u.connectionState==="connected"?n.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):n.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),n.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[n.jsx("div",{className:"adhdev-dockview-tab-primary",children:Ot(u)}),n.jsx("div",{className:"adhdev-dockview-tab-meta",children:g?n.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Gs(u)}):f?n.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Gs(u)}):n.jsx("span",{children:Gs(u)})})]}),j&&n.jsx("span",{className:"text-4xs opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:j,children:j})]})}const CI=[];function ha(e){return e.isActive}function vh(e){return e.isVisible}function _I(e){e.preventDefault()}function AI({params:e,api:t}){var f;const s=$i(),r=l.useRef(null),[o,a]=l.useState(()=>ha(t)),[i,c]=l.useState(()=>vh(t)),d=s.conversationsByTabKey.get(e.tabKey),u=Ii({sendDaemonCommand:s.sendDaemonCommand,activeConv:d,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone});l.useEffect(()=>{a(ha(t)),c(vh(t));const y=[t.onDidActiveChange(b=>a(b.isActive)),t.onDidActiveGroupChange(b=>{if(!ha(t)&&!b.isActive){a(!1);return}a(ha(t))}),t.onDidVisibilityChange(b=>c(b.isVisible))];return()=>{for(const b of y)b.dispose()}},[t]);const m=l.useMemo(()=>d?s.ides.find(y=>y.id===d.routeId):void 0,[s.ides,d]),h=d==null?void 0:d.tabKey,p=l.useMemo(()=>h?s.actionLogs.filter(y=>y.routeId===h):CI,[s.actionLogs,h]);if(!d)return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:n.jsx(Qd,{conversationsCount:0,isSplitMode:!1,isStandalone:s.isStandalone,hasRegisteredMachines:s.hasRegisteredMachines,onOpenNewSession:s.onOpenNewSession,suppressGuide:s.hasDetachedConversationPanels,isLoading:!Fi(s.ides,s.initialDataLoaded)})});const g=!vt(d)&&$r(d)==="terminal";return n.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:n.jsx(Vd,{activeConv:d,clearToken:s.clearedTabs[d.tabKey]||0,isCliTerminal:g,ideEntry:m,terminalRef:r,commands:u,actionLogs:p,userName:s.userName,scrollToBottomRequestNonce:((f=s.scrollToBottomRequest)==null?void 0:f.tabKey)===d.tabKey?s.scrollToBottomRequest.nonce:void 0,isInputActive:o,isVisible:i})})}function TI({visibleConversations:e,clearedTabs:t,ides:s,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:u,toggleHiddenTab:m,actionShortcuts:h,registerActionHandlers:p,onActiveTabChange:g,onOpenNewSession:f,onRequestScrollToBottom:y,requestedActiveTabKey:b,requestedRemoteIdeId:k,onRequestedActiveTabConsumed:j,scrollToBottomRequest:v,liveSessionInboxState:C,layoutProfile:x}){var He,tt,Ct;const{t:S}=ve("common"),{theme:w}=Ho(),{sendCommand:_}=_t(),A=l.useRef(null),O=l.useRef(null),L=l.useRef(null),R=l.useRef(!1),F=l.useRef(!1),N=l.useRef(!1),I=l.useRef(null),B=l.useRef([]),[T,H]=l.useState(null),[q,J]=l.useState(0),K=l.useRef(typeof window>"u"?{}:WT(x)),M=l.useMemo(()=>new Map(e.map(Q=>[Q.tabKey,Q])),[e]),D=l.useMemo(()=>{const Q=A.current;return Q?Q.groups.some(re=>{try{const le=re.model.location.type;return le!=="floating"&&le!=="popout"?!1:re.panels.some(xe=>M.has(xe.id))}catch{return!1}}):!1},[M,q,e]),P=l.useCallback(()=>{var Q;(Q=A.current)==null||Q.focus()},[]),$=l.useCallback((Q,re)=>{y==null||y(Q,re)},[y]),W=l.useCallback(Q=>{const re=document,le=Q.document;for(const $e of re.querySelectorAll('link[rel="stylesheet"]')){const ke=le.createElement("link");ke.rel="stylesheet",ke.href=$e.href,$e.crossOrigin&&(ke.crossOrigin=$e.crossOrigin),le.head.appendChild(ke)}for(const $e of re.querySelectorAll("style")){const ke=le.createElement("style");ke.textContent=$e.textContent,le.head.appendChild(ke)}const xe=[];for(const $e of re.styleSheets)try{for(const ke of $e.cssRules)ke instanceof CSSStyleRule&&(ke.selectorText===":root"||ke.selectorText==="html")&&xe.push(ke.cssText)}catch{}if(xe.length>0){const $e=le.createElement("style");$e.textContent=xe.join(`
|
|
59
|
-
`),le.head.appendChild($e)}const Ce=re.documentElement.getAttribute("data-theme");Ce&&le.documentElement.setAttribute("data-theme",Ce),le.documentElement.style.colorScheme=Ce==="light"?"light":"dark",le.body.className=re.body.className;const Re=re.documentElement.getAttribute("style");Re&&le.documentElement.setAttribute("style",Re);const Ue=le.getElementById("dv-popout-window");Ue instanceof HTMLElement&&(Ue.classList.add("adhdev-dockview"),Cl(Ue,w))},[w]),U=l.useCallback(()=>{var re;const Q=A.current;if(Q)for(const le of Q.groups)try{const xe=(re=le.element)==null?void 0:re.ownerDocument;if(!xe||xe===document)continue;const Ce=xe.getElementById("dv-popout-window");Ce instanceof HTMLElement&&(Ce.classList.add("adhdev-dockview"),Cl(Ce,w));const Re=document.documentElement.getAttribute("data-theme");Re&&xe.documentElement.setAttribute("data-theme",Re),xe.documentElement.style.colorScheme=Re==="light"?"light":"dark",xe.body.className=document.body.className;const Ue=document.documentElement.getAttribute("style");Ue?xe.documentElement.setAttribute("style",Ue):xe.documentElement.removeAttribute("style")}catch{}},[w]),ae=l.useCallback(Q=>{const re=A.current;if(!re)return;const le=re.getPanel(Q);le&&re.addPopoutGroup(le,{popoutUrl:"/popout.html",onDidOpen:({window:xe})=>{W(xe),je();const Ce=M.get(Q);xe.document.title=Ce?`${Ot(Ce)} — ADHDev`:"ADHDev — Popout"}})},[M,W]),be=l.useCallback(Q=>{const re=A.current,le=re==null?void 0:re.getPanel(Q);if(!re||!le)return;const xe=re.groups.filter(Ce=>{var Re;try{return((Re=Ce.element)==null?void 0:Re.ownerDocument)===document}catch{return!0}});xe.length>0?le.api.moveTo({group:xe[0],position:"center"}):le.api.moveTo({position:"center"}),le.api.setActive()},[]),V=l.useCallback(Q=>{var xe;const re=A.current;if(!re)return!1;const le=re.getPanel(Q);if(!le)return!1;try{return((xe=le.group.element)==null?void 0:xe.ownerDocument)!==document}catch{return!1}},[]),we=l.useCallback(Q=>{V(Q)&&be(Q),m(Q)},[V,be,m]),ce=l.useCallback(Q=>{const re=A.current,le=re==null?void 0:re.getPanel(Q);!re||!le||re.addFloatingGroup(le,{width:600,height:500})},[]),de=l.useCallback(Q=>{var le;const re=(le=A.current)==null?void 0:le.getPanel(Q);if(!re)return!1;try{return re.group.model.location.type==="floating"}catch{return!1}},[]),ne=l.useCallback(()=>{var re,le;const Q=(le=(re=A.current)==null?void 0:re.activePanel)==null?void 0:le.id;return!Q||Rn(Q)?null:M.has(Q)?Q:null},[M]),ee=l.useCallback(Q=>{const re=A.current,le=re==null?void 0:re.getPanel(Q);if(!re||!le)return;const xe=re.groups.filter(Ce=>{try{return Ce.model.location.type==="grid"}catch{return!0}});xe.length>0?le.api.moveTo({group:xe[0],position:"center"}):le.api.moveTo({position:"center"}),le.api.setActive()},[]),ue=l.useCallback(()=>{var Re;const Q=A.current;if(!Q)return;const le=Q.groups.filter(Ue=>{var $e;try{return(($e=Ue.element)==null?void 0:$e.ownerDocument)===document&&Ue.model.location.type==="grid"}catch{return!1}})[0]||null,xe=[...Q.panels];for(const Ue of xe){const $e=(Re=Ue.group.element)==null?void 0:Re.ownerDocument,ke=Ue.group.model.location.type;$e===document&&ke==="grid"||(le&&le.id!==Ue.group.id?Ue.api.moveTo({group:le,position:"center"}):Ue.api.moveTo({position:"center"}))}const Ce=Q.activePanel;Ce&&(Ce.group.model.openPanel(Ce),Ce.api.setActive()),Nl(document)},[]),je=l.useCallback(()=>{var re,le;const Q=A.current;if(Q)for(const xe of Q.groups){const Ce=(re=xe.element)==null?void 0:re.ownerDocument;if(!Ce||Ce===document)continue;const Re=Ce.getElementById("dv-popout-window");if(!(Re instanceof HTMLElement))continue;let Ue=null,$e=Ce.title||"ADHDev",ke="Popout workspace";const Ze=xe.activePanel;if(Ze)if(Ue=Ze.id,Rn(Ze.id)){const Qe=((le=Ze.params)==null?void 0:le.routeId)||Ze.id.slice(7),ge=On([...M.values()],Qe);$e=Ng(ge),ke=ge!=null&&ge.machineName?`Remote view · ${ge.machineName}`:"Remote view"}else{const Qe=M.get(Ze.id);$e=Qe?Ot(Qe):Ze.title||Ze.id,ke=Qe?Gs(Qe):"Dockview panel"}Ce.title=`${$e} — ADHDev`;const et=Array.from(Ce.querySelectorAll("#adhdev-popout-header"));for(const Qe of et)Qe.remove();const Ve=Ce.createElement("div");Ve.id="adhdev-popout-header",Ce.body.appendChild(Ve),Ve.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Ve.innerHTML=`
|
|
60
|
-
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
61
|
-
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
62
|
-
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${gh($e)}</div>
|
|
63
|
-
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${gh(ke)}</div>
|
|
64
|
-
</div>
|
|
65
|
-
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
66
|
-
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
67
|
-
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
68
|
-
</div>
|
|
69
|
-
`,Re.style.top="52px",Re.style.height="calc(100% - 52px)";const st=Ve.querySelector("[data-adhdev-popout-focus]");st&&(st.onclick=()=>{window.focus()});const lt=Ve.querySelector("[data-adhdev-popout-dock]");lt&&(lt.disabled=!Ue,lt.style.opacity=Ue?"1":"0.5",lt.style.cursor=Ue?"pointer":"default",lt.onclick=()=>{var Qe;Ue&&be(Ue),(Qe=Ce.defaultView)==null||Qe.focus()})}},[M,be]),X=l.useCallback(Q=>{var xe;const re=A.current,le=re==null?void 0:re.getPanel(Q);if(!(!re||!le)){le.group.model.openPanel(le),le.api.setActive(),$(Q,"dockview-shortcut");try{const Ce=le.group.model.location;Ce.type==="popout"?Ce.getWindow().focus():Nl((xe=le.group.element)==null?void 0:xe.ownerDocument)}catch{}}},[$]),G=l.useCallback(Q=>{const re=A.current,le=re==null?void 0:re.activePanel,xe=(re==null?void 0:re.activeGroup)||(le==null?void 0:le.group);if(!re||!le||!xe)return;const Ce=xe.panels||[];if(Ce.length<=1)return;const Re=Ce.findIndex(ke=>ke.id===le.id);if(Re<0)return;const Ue=(Re+Q+Ce.length)%Ce.length,$e=Ce[Ue];$e&&($e.group.model.openPanel($e),$e.api.setActive(),Rn($e.id)||$($e.id,"dockview-shortcut"))},[$]),z=l.useCallback(Q=>{var st;const re=A.current,le=(re==null?void 0:re.activeGroup)||((st=re==null?void 0:re.activePanel)==null?void 0:st.group);if(!re||!le)return;const xe=re.groups||[],Ce=xe.find(lt=>lt.id===le.id);if(!Ce)return;const Re=Ce.element.getBoundingClientRect(),Ue=Re.left+Re.width/2,$e=Re.top+Re.height/2,ke=(lt,Qe,ge,_e)=>Math.max(0,Math.min(Qe,_e)-Math.max(lt,ge)),Ze=lt=>{const Qe=lt.element.getBoundingClientRect(),ge=Qe.left+Qe.width/2,_e=Qe.top+Qe.height/2;let Pe=0,nt=0,ze=0,ut=!1;if(Q==="left"?(ut=ge<Ue,Pe=Math.max(0,Re.left-Qe.right),nt=Math.abs(_e-$e),ze=ke(Re.top,Re.bottom,Qe.top,Qe.bottom)):Q==="right"?(ut=ge>Ue,Pe=Math.max(0,Qe.left-Re.right),nt=Math.abs(_e-$e),ze=ke(Re.top,Re.bottom,Qe.top,Qe.bottom)):Q==="above"?(ut=_e<$e,Pe=Math.max(0,Re.top-Qe.bottom),nt=Math.abs(ge-Ue),ze=ke(Re.left,Re.right,Qe.left,Qe.right)):(ut=_e>$e,Pe=Math.max(0,Qe.top-Re.bottom),nt=Math.abs(ge-Ue),ze=ke(Re.left,Re.right,Qe.left,Qe.right)),!ut)return Number.POSITIVE_INFINITY;const Ge=ze>0?0:120;return Pe*3+nt+Ge};let et=null,Ve=Number.POSITIVE_INFINITY;for(const lt of xe){if(lt.id===Ce.id)continue;const Qe=Ze(lt);Number.isFinite(Qe)&&(Qe>=Ve||(Ve=Qe,et=lt))}return et||void 0},[]),ie=l.useCallback(Q=>{var xe;const re=z(Q);if(!re)return;const le=re.activePanel||re.panels[0];le&&(re.model.openPanel(le),le.api.setActive(),Rn(le.id)||$(le.id,"dockview-focus"),Nl((xe=re.element)==null?void 0:xe.ownerDocument))},[z,$]),Ne=l.useCallback((Q,re)=>{const le=A.current,xe=le==null?void 0:le.activePanel,Ce=(le==null?void 0:le.activeGroup)||(xe==null?void 0:xe.group);if(!le||!xe||!Ce)return;let Re=z(Q);!Re&&(re!=null&&re.createGroupIfMissing)&&(Re=le.addGroup({referenceGroup:Ce,direction:Q})),Re&&(xe.api.moveTo({group:Re,position:"center"}),xe.group.model.openPanel(xe),xe.api.setActive(),Rn(xe.id)||$(xe.id,re!=null&&re.createGroupIfMissing?"dockview-split":"dockview-move"))},[z,$]),{isMac:Be,tabShortcuts:Le,shortcutListening:Je,setShortcutListening:Se,saveShortcuts:he}=Lb({sortedTabKeys:e.map(Q=>Q.tabKey),onFocus:P,onSelectTab:X}),pe=l.useCallback(()=>{var le;const Q=A.current;if(!Q)return;const re=Q.activePanel;if(re){if(Rn(re.id)){const xe=((le=re.params)==null?void 0:le.routeId)||re.id.slice(7),Ce=On(e,xe);Ce!=null&&Ce.tabKey&&Se(Ce.tabKey);return}M.has(re.id)&&Se(re.id)}},[M,X,Se,e]),Ee=l.useCallback(Q=>{const re=[];return Q.metaKey&&re.push(Be?"⌘":"Meta"),Q.ctrlKey&&re.push("Ctrl"),Q.altKey&&re.push(Be?"⌥":"Alt"),Q.shiftKey&&Q.key.length!==1&&re.push(Be?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(Q.key)?null:(re.push(Ob(Q.key)),re.join("+"))},[Be]),Y=l.useCallback(Q=>{var re,le;switch(Q){case"splitActiveTabRight":Ne("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Ne("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const xe=ne();xe&&ce(xe);return}case"popoutActiveTab":{const xe=ne();xe&&ae(xe);return}case"dockActiveTab":{const xe=ne();if(!xe)return;V(xe)?be(xe):de(xe)&&ee(xe);return}case"focusLeftPane":ie("left");return;case"focusRightPane":ie("right");return;case"focusUpPane":ie("above");return;case"focusDownPane":ie("below");return;case"moveActiveTabToLeftPane":Ne("left");return;case"moveActiveTabToRightPane":Ne("right");return;case"moveActiveTabToUpPane":Ne("above");return;case"moveActiveTabToDownPane":Ne("below");return;case"selectPreviousGroupTab":G(-1);return;case"selectNextGroupTab":G(1);return;case"setActiveTabShortcut":pe();return;case"hideCurrentTab":{const xe=(le=(re=A.current)==null?void 0:re.activePanel)==null?void 0:le.id;xe&&!Rn(xe)&&we(xe);return}default:return}},[G,ee,ie,ce,ne,we,de,V,be,Ne,ae,pe]);l.useEffect(()=>{if(!T)return;const Q=T.sourceDocument,re=Q.defaultView??window,le=xe=>{const Ce=Q.querySelector("[data-dockview-tab-context-menu]");Ce&&Ce.contains(xe.target)||H(null)};return re.addEventListener("mousedown",le,!0),re!==window&&window.addEventListener("mousedown",()=>H(null),!0),()=>{re.removeEventListener("mousedown",le,!0),re!==window&&window.removeEventListener("mousedown",()=>H(null),!0)}},[T]);const me=l.useMemo(()=>({actionLogs:r,clearedTabs:t,conversationsByTabKey:M,hasDetachedConversationPanels:D,ides:s,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,onOpenNewSession:f,liveSessionInboxState:C,sendDaemonCommand:o,setActionLogs:a,toggleHiddenTab:we,userName:u,scrollToBottomRequest:v,tabShortcuts:Le,openTabContextMenu:({x:Q,y:re,tabKey:le,sourceDocument:xe})=>H({x:Q,y:re,tabKey:le,sourceDocument:xe??document}),popoutTab:ae,moveTabBackToMain:be,isTabInPopout:V,floatTab:ce,isTabFloating:de}),[r,t,M,D,s,i,c,d,f,C,o,a,we,u,v,Le,ae,be,V,ce,de]),fe=T?fI({isTabInPopout:V(T.tabKey),isTabFloating:de(T.tabKey),tabShortcut:Le[T.tabKey],actionShortcuts:h}):[],E=l.useCallback(Q=>{var xe;const re=A.current;if((((xe=re==null?void 0:re.activePanel)==null?void 0:xe.id)??null)===Q.id){Q.group.model.openPanel(Q);return}Q.group.model.openPanel(Q),Q.api.setActive()},[]),oe=l.useCallback((Q,re="requested-tab")=>{if(!Q)return!1;const le=A.current;if(!le)return!1;const xe=le.getPanel(Q);return xe?(E(xe),$(Q,re),j==null||j(),!0):!1},[E,j,$]),Ie=l.useCallback(()=>{if(N.current)return!1;const Q=oe(I.current,"stored-layout-restore");return Q&&(N.current=!0),Q},[oe]),Z=l.useCallback(()=>{var re;const Q=A.current;Q&&BT(x,{activeTabId:((re=Q.activePanel)==null?void 0:re.id)??null,layout:Q.toJSON()})},[x]),se=l.useCallback(()=>{UT(x,K.current)},[x]),ye=l.useCallback(Q=>{var xe,Ce,Re,Ue;const re=A.current;if(!re)return{kind:"grid"};const le=re.toJSON();for(const $e of le.floatingGroups||[])if((Ce=(xe=$e.data)==null?void 0:xe.views)!=null&&Ce.includes(Q)&&$e.position)return{kind:"floating",position:$e.position};for(const $e of le.popoutGroups||[])if((Ue=(Re=$e.data)==null?void 0:Re.views)!=null&&Ue.includes(Q))return{kind:"popout",position:$e.position,popoutUrl:$e.url};return{kind:"grid"}},[]),Fe=l.useCallback(Q=>{const re=A.current;if(!re)return;const le=re.getPanel(Q),xe=K.current[Q];if(!le||!xe||xe.kind==="grid")return;if(le.group.model.location.type===xe.kind){delete K.current[Q],se();return}if(xe.kind==="floating"){re.addFloatingGroup(le,{x:xe.position.left??24,y:xe.position.top??24,width:xe.position.width,height:xe.position.height}),delete K.current[Q],se();return}delete K.current[Q],se()},[se]);l.useEffect(()=>(p==null||p({setShortcutForActiveTab:pe,restoreHiddenTabToSavedLocation:Fe,activateConversationTab:X,resetAllPanelsToMain:ue,activatePreviousTabInGroup:()=>G(-1),activateNextTabInGroup:()=>G(1),floatActiveTab:()=>{const Q=ne();Q&&ce(Q)},popoutActiveTab:()=>{const Q=ne();Q&&ae(Q)},dockActiveTab:()=>{const Q=ne();Q&&(V(Q)?be(Q):de(Q)&&ee(Q))},splitActiveTabRight:()=>Ne("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Ne("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ie("left"),focusRightPane:()=>ie("right"),focusUpPane:()=>ie("above"),focusDownPane:()=>ie("below"),moveActiveTabToLeftPane:()=>Ne("left"),moveActiveTabToRightPane:()=>Ne("right"),moveActiveTabToUpPane:()=>Ne("above"),moveActiveTabToDownPane:()=>Ne("below")}),()=>p==null?void 0:p(null)),[G,ee,ce,ie,ne,de,V,Ne,be,ae,p,ue,Fe,X,pe]),l.useEffect(()=>()=>{var Q;(Q=L.current)==null||Q.call(L),L.current=null},[]);const Me=l.useCallback(Q=>{var le,xe;A.current=Q.api,(le=L.current)==null||le.call(L),L.current=null;const re=HT(x);if(I.current=(re==null?void 0:re.activeTabId)??null,re!=null&&re.layout&&Q.api.fromJSON(re.layout,{reuseExistingPanels:!1}),F.current=hh({hasStoredLayout:!!(re!=null&&re.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:s}),F.current||(xh(Q.api,e),yh(Q.api,e,k)),Q.api.totalPanels===0&&e.length>0){const Ce=wI(Q.api,e,b);if(Ce){const Re=Q.api.getPanel(Ce);Re&&E(Re)}}else!F.current&&!oe(b)&&Ie();if(R.current=!0,Q.api.onDidActivePanelChange(Ce=>{var Ue;if(I.current=(Ce==null?void 0:Ce.id)??null,N.current=!0,je(),Ce&&Rn(Ce.id)){const $e=((Ue=Ce.params)==null?void 0:Ue.routeId)||Ce.id.slice(7),ke=On(e,$e);g((ke==null?void 0:ke.tabKey)??null),Z();return}if(g((Ce==null?void 0:Ce.id)??null),Z(),!Ce)return;const Re=M.get(Ce.id);(Re==null?void 0:Re.streamSource)==="agent-stream"&&Re.agentType&&_(Re.routeId,Xf(),{agentType:Re.agentType,...Re.sessionId&&{targetSessionId:Re.sessionId}}).catch(()=>{})}),Q.api.onDidLayoutChange(()=>{Z(),je(),J(Ce=>Ce+1)}),yI()){const Ce=Ve=>({clientX:Ve.clientX,clientY:Ve.clientY}),Re=Ve=>{const st=Ve==null?void 0:Ve.getBoundingClientRect();return st?{left:st.left,right:st.right,top:st.top,bottom:st.bottom}:null},Ue=Ve=>{var lt;const st=(lt=O.current)==null?void 0:lt.getBoundingClientRect();return st?Ve.clientX<st.left||Ve.clientX>st.right||Ve.clientY<st.top||Ve.clientY>st.bottom:!1},$e=xI({detachDelayMs:$b,onDetach:({panelId:Ve,clientX:st,clientY:lt})=>{var ze,ut;const Qe=Q.api.getPanel(Ve);if(!Qe)return;try{if(Qe.group.model.location.type!=="grid")return}catch{return}const ge=(ze=O.current)==null?void 0:ze.getBoundingClientRect(),_e=(ut=Qe.group.element)==null?void 0:ut.getBoundingClientRect(),Pe=Math.round(Math.min(Math.max((_e==null?void 0:_e.width)??600,360),720)),nt=Math.round(Math.min(Math.max((_e==null?void 0:_e.height)??500,260),640));Q.api.addFloatingGroup(Qe,{x:ge?Math.max(0,st-ge.left-32):void 0,y:ge?Math.max(0,lt-ge.top-18):void 0,width:Pe,height:nt}),Qe.api.setActive(),Z(),je(),J(Ge=>Ge+1)}}),ke=[Q.api.onWillDragPanel(Ve=>{if(!(Ve.nativeEvent.defaultPrevented||Ve.nativeEvent.shiftKey)){try{if(Ve.panel.group.model.location.type!=="grid")return}catch{return}$e.startDrag({panelId:Ve.panel.id,selfPanelBounds:Re(Ve.panel.group.element),...Ce(Ve.nativeEvent)})}}),Q.api.onWillShowOverlay(Ve=>{if($e.hasDetached()){Ve.preventDefault();return}$e.markDockTarget(Ce(Ve.nativeEvent))}),Q.api.onWillDrop(Ve=>{if($e.hasDetached()){Ve.preventDefault(),$e.endDrag();return}$e.markDockTarget(Ce(Ve.nativeEvent))}),Q.api.onDidDrop(()=>$e.endDrag()),Q.api.onUnhandledDragOverEvent(Ve=>{$e.isDragging()&&$e.markSelfPanel(Ce(Ve.nativeEvent))})],Ze=Ve=>{if(!$e.isDragging())return;const st=Ce(Ve);Ue(st)&&$e.markNonSelfPanel(st)},et=()=>$e.endDrag();window.addEventListener("dragover",Ze,!0),window.addEventListener("drop",et,!0),window.addEventListener("dragend",et,!0),L.current=()=>{$e.dispose();for(const Ve of ke)Ve.dispose();window.removeEventListener("dragover",Ze,!0),window.removeEventListener("drop",et,!0),window.removeEventListener("dragend",et,!0)}}Q.api.onDidAddGroup(Ce=>{requestAnimationFrame(()=>{var Re,Ue;try{const $e=(Re=Ce.element)==null?void 0:Re.ownerDocument;if(!$e||$e===document)return;(Ue=$e.getElementById("dv-popout-window"))==null||Ue.classList.add("adhdev-dockview");const ke=document.documentElement.getAttribute("data-theme");ke&&$e.documentElement.setAttribute("data-theme",ke),$e.body.className=document.body.className;const Ze=document.documentElement.getAttribute("style");Ze&&$e.documentElement.setAttribute("style",Ze)}catch{}je(),J($e=>$e+1)})}),g(((xe=Q.api.activePanel)==null?void 0:xe.id)??null)},[E,oe,M,s,d,x,g,Z,b,k,_,je,e]);l.useLayoutEffect(()=>{const Q=A.current;if(!Q||!R.current||F.current&&hh({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:s}))return;F.current&&(F.current=!1);const re=B.current,le=new Set(re),xe=e.map(et=>et.tabKey),Ce=new Set(xe),Re=gI({previousVisibleConversationCount:re.length,visibleConversationCount:e.length,ides:s});let Ue=!1;for(const et of re)Ce.has(et)||Re||(K.current[et]=ye(et),Ue=!0);Ue&&se(),Re||(xh(Q,e),yh(Q,e,k));const $e=xe.filter(et=>!le.has(et));let ke=!1;for(const et of $e){const Ve=Q.getPanel(et),st=K.current[et];if(!Ve||!st||st.kind==="grid")continue;if(Ve.group.model.location.type===st.kind){delete K.current[et],ke=!0;continue}if(st.kind==="floating"){Q.addFloatingGroup(Ve,{x:st.position.left??24,y:st.position.top??24,width:st.position.width,height:st.position.height}),delete K.current[et],ke=!0;continue}}if(ke&&se(),B.current=xe,b&&oe(b))return;!Q.activePanel&&Q.panels[0]&&E(Q.panels[0]),!!(Q.activePanel&&Q.getPanel(Q.activePanel.id))||Ie()},[E,oe,Ie,s,d,se,ye,b,k,e]),l.useEffect(()=>{R.current&&oe(b)},[oe,b]),l.useEffect(()=>{const Q=le=>{const xe=le.target;if(!xe)return;const Ce=xe.querySelector("[data-tab-key]")||xe.closest("[data-tab-key]");if(Ce){const Re=Ce.getAttribute("data-tab-key");if(Re&&le.dataTransfer){const Ue=xe.closest(".dv-tab")||Ce.closest(".dv-tab")||Ce;le.dataTransfer.effectAllowed="move",le.dataTransfer.setData("text/tab-key",Re),Ue instanceof HTMLElement&&le.dataTransfer.setDragImage(Ue,Math.max(12,Math.round(Ue.clientWidth/2)),Math.max(10,Math.round(Ue.clientHeight/2)))}}};window.addEventListener("dragstart",Q);const re=bh(A.current);for(const le of re)le.addEventListener("dragstart",Q);return()=>{window.removeEventListener("dragstart",Q);for(const le of re)le.removeEventListener("dragstart",Q)}},[q]),l.useEffect(()=>{var re;const Q=(re=O.current)==null?void 0:re.querySelector(".adhdev-dockview");Q instanceof HTMLElement&&Cl(Q,w),U(),je()},[je,U,w]),l.useEffect(()=>{je()},[je]),l.useEffect(()=>{const Q=re=>{if(re.defaultPrevented||Je)return;const le=Ee(re);if(!le)return;const xe=re.metaKey||re.ctrlKey||re.altKey;Lc(re.target)&&!xe||oi(Be).setActiveTabShortcut!==le||(re.preventDefault(),re.stopPropagation(),pe())};return window.addEventListener("keydown",Q,!0),()=>window.removeEventListener("keydown",Q,!0)},[Ee,Be,Je,pe]),l.useEffect(()=>{const Q=O.current;if(!Q)return;const re=le=>{var $e,ke;if(!le.isTrusted)return;const xe=(ke=($e=le.target)==null?void 0:$e.closest)==null?void 0:ke.call($e,".dv-scrollable");if(!xe)return;le.preventDefault(),le.stopPropagation();const Ce=Math.abs(le.deltaX),Re=Math.abs(le.deltaY),Ue=Ce>Re?le.deltaX:le.deltaY;xe.dispatchEvent(new WheelEvent("wheel",{deltaY:Ue,deltaMode:le.deltaMode,bubbles:!1,cancelable:!0}))};return Q.addEventListener("wheel",re,{passive:!1,capture:!0}),()=>Q.removeEventListener("wheel",re,{capture:!0})},[]),l.useEffect(()=>{const Q=bh(A.current);if(Q.length===0)return;const re=Q.map(le=>{let xe=[],Ce=null;const Re=()=>{Ce!=null&&le.clearTimeout(Ce),Ce=null,xe=[]},Ue=()=>{Ce!=null&&le.clearTimeout(Ce),Ce=le.setTimeout(()=>{Ce=null,xe=[]},1200)},$e=Ze=>{if(!Ze.ctrlKey&&!Ze.metaKey&&!Ze.altKey)return;const et=Ee(Ze);if(!et)return;const Ve=Pb();for(const[st,lt]of Object.entries(Ve))if(e.some(Qe=>Qe.tabKey===st)&<===et){Ze.preventDefault(),X(st);return}},ke=Ze=>{if(Ze.defaultPrevented||Je)return;const et=Ee(Ze);if(!et)return;const Ve=Ze.metaKey||Ze.ctrlKey||Ze.altKey;if(Lc(Ze.target))return;const st=oi(Be),lt=Object.entries(st).filter(([Ge,gt])=>!!gt&&(Ge==="splitActiveTabRight"||Ge==="splitActiveTabDown"||Ge==="floatActiveTab"||Ge==="popoutActiveTab"||Ge==="dockActiveTab"||Ge==="focusLeftPane"||Ge==="focusRightPane"||Ge==="focusUpPane"||Ge==="focusDownPane"||Ge==="moveActiveTabToLeftPane"||Ge==="moveActiveTabToRightPane"||Ge==="moveActiveTabToUpPane"||Ge==="moveActiveTabToDownPane"||Ge==="selectPreviousGroupTab"||Ge==="selectNextGroupTab"||Ge==="setActiveTabShortcut"||Ge==="hideCurrentTab")),Qe=Ve?[et]:[...xe.slice(-1),et].slice(-2),ge=Qe.join(" "),_e=Qe[Qe.length-1],Pe=lt.find(([,Ge])=>Ge===ge);if(Pe){Ze.preventDefault(),Re(),Y(Pe[0]);return}if(lt.some(([,Ge])=>Ge.startsWith(`${ge} `))){Ze.preventDefault(),xe=Qe,Ue();return}const ze=lt.find(([,Ge])=>Ge===_e);if(ze){Ze.preventDefault(),Re(),Y(ze[0]);return}if(lt.some(([,Ge])=>Ge.startsWith(`${_e} `))){Ze.preventDefault(),xe=[_e],Ue();return}Re()};return le.addEventListener("keydown",$e),le.addEventListener("keydown",ke),()=>{Re(),le.removeEventListener("keydown",$e),le.removeEventListener("keydown",ke)}});return()=>{for(const le of re)le()}},[Ee,Be,q,X,Je,Y,e]);const De=w==="light"?zl:Gl,Te=((Ct=(tt=(He=A.current)==null?void 0:He.activePanel)==null?void 0:tt.group.element)==null?void 0:Ct.ownerDocument)??document;return n.jsxs(Bb.Provider,{value:me,children:[n.jsx("div",{ref:O,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:n.jsx(Fx,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:AI,remote:kI},defaultTabComponent:NI,watermarkComponent:jI,onReady:Me,singleTabMode:"default",tabAnimation:"smooth",theme:De,popoutUrl:"/popout.html"})}),T&&Qn.createPortal(n.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[var(--z-popover)] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:T.x,top:T.y},children:fe.map(Q=>{if(Q.type==="separator")return n.jsx("div",{className:"border-t border-border-subtle my-1"},Q.id);let re=n.jsx(Up,{size:13,className:"shrink-0 opacity-70"}),le=()=>{};switch(Q.id){case"dockInWindow":case"dockBackToGrid":re=n.jsx(uw,{size:13,className:"shrink-0 opacity-70"}),le=()=>{ee(T.tabKey),H(null)};break;case"moveBackToMain":re=n.jsx(cw,{size:13,className:"shrink-0 opacity-70"}),le=()=>{be(T.tabKey),H(null)};break;case"floatAsPanel":re=n.jsx(dw,{size:13,className:"shrink-0 opacity-70"}),le=()=>{ce(T.tabKey),H(null)};break;case"openInNewWindow":re=n.jsx(lw,{size:13,className:"shrink-0 opacity-70"}),le=()=>{ae(T.tabKey),H(null)};break;case"setShortcut":le=xe=>{xe.stopPropagation(),Se(T.tabKey),H(null)};break;case"removeShortcut":re=n.jsx(Bt,{size:13,className:"shrink-0 opacity-70"}),le=()=>{const xe={...Le};delete xe[T.tabKey],he(xe),H(null)};break;case"hideTab":re=n.jsx(pi,{size:13,className:"shrink-0 opacity-70"}),le=()=>{we(T.tabKey),H(null)};break}return n.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${Q.tone==="muted"?"text-text-muted":""}`,onMouseDown:_I,onClick:le,children:[re,n.jsx("span",{className:"flex-1 min-w-0",children:Q.label}),Q.shortcut?n.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:Q.shortcut}):null]},Q.id)})}),T.sourceDocument.body),Je&&Qn.createPortal(n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>Se(null),children:n.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:Q=>Q.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:Be?"⌘+1":"Ctrl+1",example2:Be?"⌥+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")})]})}),Te.body)]})}const Wb="adhdev-recent-launch-args-v1",II=8;function MI(e){return String(e||"").trim().replace(/\s+/g," ")}function Ub(e,t){return`${e.trim()}::${t.trim()}`}function Kb(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Wb)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function RI(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Wb,JSON.stringify(e))}catch{}}function PI(e,t){var a;const s=String(e||"").trim(),r=String(t||"").trim();return!s||!r?[]:((a=Kb().byKey[Ub(s,r)])==null?void 0:a.items)||[]}function LI(e,t,s){var m;const r=String(e||"").trim(),o=String(t||"").trim(),a=MI(s);if(!r||!o||!a)return;const i=Kb(),c=Ub(r,o),d=((m=i.byKey[c])==null?void 0:m.items)||[],u=[a,...d.filter(h=>h!==a)].slice(0,II);i.byKey[c]={items:u},RI(i)}const EI="adhdev.remember.";function Ec(e){return`${EI}${e.trim()}`}function _l(e){if(typeof window>"u"||!e.trim())return null;try{const t=window.localStorage.getItem(Ec(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 pa(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(Ec(e));return}window.localStorage.setItem(Ec(e),JSON.stringify(s))}catch{}}function DI({sessions:e,loading:t,busy:s=!1,resumingSessionId:r=null,fallbackWorkspacePath:o,onResume:a,onRefresh:i,onClose:c}){const{t:d}=ve("common"),[u,m]=l.useState(""),h=String(o||"").trim(),p=l.useMemo(()=>{const g=e.map(f=>f.canResume||String(f.workspace||"").trim()||!h?f:{...f,workspace:h,canResume:!0,workspaceFallbackSource:"selected-workspace"});return Ld(g,{textQuery:u,sortMode:"recent"})},[h,u,e]);return n.jsxs("div",{className:"mt-3 flex max-h-[min(55vh,420px)] flex-col overflow-hidden rounded-xl border border-border-subtle bg-bg-secondary",role:"region","aria-label":Cc(d),"data-testid":"saved-history-inline",children:[n.jsxs("div",{className:"flex items-center gap-2 border-b border-border-subtle px-3 py-2",children:[n.jsx("input",{type:"search",value:u,onChange:g=>m(g.target.value),placeholder:d("historyModal.searchPlaceholder"),"aria-label":d("historyModal.searchPlaceholder"),className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-1.5 text-sm text-text-primary"}),n.jsx(Di,{onClick:i,refreshing:t,className:"h-8 w-8"}),n.jsx("button",{type:"button",onClick:c,"aria-label":d("common.close"),className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border-subtle bg-transparent text-text-muted hover:text-text-primary",children:n.jsx(Bt,{size:14})})]}),n.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-2",children:[p.map(g=>{const f=r===g.providerSessionId,y=String(g.workspace||"").trim();return n.jsxs("div",{className:"flex items-center gap-3 rounded-lg px-2.5 py-2 hover:bg-bg-primary/60",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"truncate text-sm font-semibold text-text-primary",children:g.title||d("historyModal.untitledSession")}),n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-2xs text-text-muted",children:[n.jsx(Tg,{value:g.lastMessageAt}),y&&n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx(tn,{content:y,children:n.jsx("span",{className:"truncate",children:Rg(y)})})]}),g.messageCount>0&&n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:"shrink-0",children:d("historyModal.msgCount",{count:g.messageCount})})]})]})]}),g.canResume?n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",disabled:s||!!r,onClick:()=>a(g),children:d(f?"historyModal.statusResuming":"historyModal.statusResume")}):n.jsx("span",{className:"shrink-0 text-2xs text-text-muted",children:d("historyModal.statusMissingWorkspace")})]},g.id)}),!t&&p.length===0&&n.jsx("div",{className:"px-3 py-6 text-center text-xs text-text-muted",children:e.length>0?d("historyModal.noMatchingHistory"):Ug(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 OI(e){return!e.hasLoadedInitialResults&&!e.isLoading}function $s({title:e,description:t,action:s,children:r,className:o="",contentClassName:a=""}){return n.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${o}`.trim(),children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[n.jsx("div",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted",children:e}),t&&n.jsx(dt,{content:t,size:12})]}),s?n.jsx("div",{className:"flex items-center gap-2",children:s}):null]}),r?n.jsx("div",{className:s?`mt-3 ${a}`.trim():`mt-2 ${a}`.trim(),children:r}):null]})}function FI(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 $I({busy:e,savedSessionsLoading:t,savedSessionsError:s,savedSessionsLoaded:r,savedSessionsCount:o=0,selectedSession:a,historyOpen:i=!1,onOpenHistory:c,onClearSelection:d}){const{t:u}=ve("common"),m=a?_b(a,u):null,h=FI(u,{savedSessionsLoading:t,savedSessionsLoaded:r,savedSessionsCount:o}),p=!!m||!!h||!!s;return n.jsx($s,{title:u("launch.savedHistoryBadge"),description:Ed(u),action:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,"aria-expanded":i,onClick:c,children:Q1(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 qb({setup:e,providerName:t,className:s=""}){const{t:r}=ve("common");return e?n.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${s}`,children:[n.jsx("div",{className:"font-semibold",children:t?r("mesh.manualSetup.titleFor",{provider:t}):r("mesh.manualSetup.title")}),e.instructions&&n.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-2xs text-text-muted",children:[e.serverName&&n.jsxs("span",{children:[r("mesh.manualSetup.server")," ",n.jsx("code",{children:e.serverName})]}),e.configFormat&&n.jsxs("span",{children:[r("mesh.manualSetup.format")," ",n.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&n.jsxs("span",{children:[r("mesh.manualSetup.configPath")," ",n.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&n.jsx("span",{children:r("mesh.manualSetup.restartHint")})]}),e.template&&n.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}const HI={cli:"CLI",ide:"IDE",acp:"ACP"},BI=new Set(["--dangerously-skip-permissions","--dangerously-bypass-approvals-and-sandbox","bypassPermissions","sandbox_mode=danger-full-access","approval_policy=never"]);function WI(e){const t=e.trim();return BI.has(t)||t.startsWith("--dangerously-skip-permissions=")||t.startsWith("--dangerously-bypass-approvals-and-sandbox=")}function Yn(e){var t;return(t=e.launchArgs)!=null&&t.some(WI)?"dangerous":e.risk}function UI(e){var s,r;if(!e)return"";const t=e.modes.find(o=>o.id===e.default);return t&&Yn(t)!=="dangerous"?t.id:((s=e.modes.find(o=>o.strategy==="pty-parse-default"&&Yn(o)!=="dangerous"))==null?void 0:s.id)||((r=e.modes.find(o=>Yn(o)!=="dangerous"))==null?void 0:r.id)||""}function KI(e,t,s){return e?t?{autoApproveMode:t}:{autoApprove:!1}:{autoApprove:s}}const qI={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 zb({risk:e}){const{t}=ve();return n.jsx("span",{className:`rounded-full border px-2 py-0.5 text-3xs font-semibold uppercase tracking-wide ${qI[e]}`,children:t(`newSession.autoApproveRisk.${e}`)})}function Gb({config:e,selectedModeId:t,disabled:s=!1,onSelectMode:r}){const{t:o}=ve();return n.jsx("div",{className:"space-y-2",children:n.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":o("newSession.autoApproveMode"),children:e.modes.map(a=>{const i=Yn(a),c=t===a.id;return n.jsxs("button",{type:"button",role:"radio","aria-checked":c,className:`flex w-full items-center justify-between gap-3 rounded-xl border px-3.5 py-3 text-left transition-colors ${c?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>r(a),disabled:s,children:[n.jsx("span",{className:"min-w-0 text-sm font-semibold text-text-primary",children:a.label}),n.jsx(zb,{risk:i})]},a.id)})})})}function zI({checked:e,disabled:t=!1,onChange:s}){const{t:r}=ve();return n.jsxs("div",{className:"flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-secondary/40 px-3.5 py-3",children:[n.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[n.jsx("span",{id:"legacy-auto-approve-label",className:"text-sm font-semibold text-text-primary",children:r("newSession.autoApproveLegacy")}),n.jsx(dt,{content:r("newSession.autoApproveLegacyDescription")})]}),n.jsx(Br,{checked:e,onChange:s,disabled:t,"aria-labelledby":"legacy-auto-approve-label"})]})}function Vb({mode:e,onConfirm:t,onCancel:s}){const{t:r}=ve();return n.jsx(Oi,{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 wo(e,t){var s;return e?t==="ide"?(((s=e.detectedIdes)==null?void 0:s.length)||0)>0:(e.availableProviders||[]).some(r=>Ao(r,t)):!1}function Al(e){return e?wo(e,"cli")?"cli":wo(e,"ide")?"ide":wo(e,"acp")?"acp":null:null}const Tl="new-session-dialog",wh="new-session-workspace",Sh="new-session-mesh",Dc={value:"",source:null};function kh(e,t){return e?{value:e,source:t}:Dc}function jh(e,t){return{...e.value.trim()&&e.source?{modelSource:e.source}:{},...t.value.trim()&&t.source?{thinkingLevelSource:t.source}:{}}}function GI(e){return e==="cli"||e==="ide"||e==="acp"}function pr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function VI({machines:e,ides:t,onClose:s,onBrowseDirectory:r,onSaveWorkspace:o,onLaunchIde:a,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:u,initialMachineId:m,initialWorkspaceId:h,initialLaunchMode:p,initialMeshWorkspacePath:g}){var Yt,us,su,ru,ou,au,iu,lu,cu;const{t:f}=ve(),y=Hr(),b=l.useMemo(()=>[...e].sort(Ua),[e]),[k]=l.useState(()=>({dialog:_l(Tl),workspace:_l(wh),mesh:_l(Sh)})),[j,v]=l.useState(()=>{var Ke,We;if(m&&e.some(ot=>ot.id===m))return m;const te=(Ke=k.dialog)==null?void 0:Ke.machineId;return te&&e.some(ot=>ot.id===te)?te:((We=[...e].sort(Ua)[0])==null?void 0:We.id)||""}),C=l.useMemo(()=>b.find(te=>te.id===j)||b[0],[j,b]),x=l.useMemo(()=>((C==null?void 0:C.workspaces)||[]).map(te=>({id:te.id,path:te.path,label:te.label})),[C]),S=(C==null?void 0:C.defaultWorkspaceId)||null,[w,_]=l.useState("workspace"),[A,O]=l.useState(""),[L,R]=l.useState(""),[F,N]=l.useState([]),[I,B]=l.useState(""),[T,H]=l.useState(!1),[q,J]=l.useState(null),[K,M]=l.useState(""),[D,P]=l.useState(Al(b[0])),[$,W]=l.useState(""),[U,ae]=l.useState(""),[be,V]=l.useState(!1),[we,ce]=l.useState(""),[de,ne]=l.useState(null),[ee,ue]=l.useState(Dc),[je,X]=l.useState(Dc),G=ee.value,z=je.value,ie=l.useCallback((te,Ke)=>{ue(kh(te,Ke))},[]),Ne=l.useCallback((te,Ke)=>{X(kh(te,Ke))},[]),[Be,Le]=l.useState(!1),[Je,Se]=l.useState([]),[he,pe]=l.useState(""),[Ee,Y]=l.useState([]),[me,fe]=l.useState(!1),[E,oe]=l.useState(!1),[Ie,Z]=l.useState(""),[se,ye]=l.useState(!1),[Fe,Me]=l.useState(null),[De,Te]=l.useState(!1),[He,tt]=l.useState(""),[Ct,Q]=l.useState("error"),[re,le]=l.useState(null),[xe,Ce]=l.useState(!1),[Re,Ue]=l.useState(""),[$e,ke]=l.useState([]),[Ze,et]=l.useState(!1),[Ve,st]=l.useState(""),[lt,Qe]=l.useState(!1),ge=l.useRef(null),_e=l.useRef(h||null),Pe=l.useRef(p||(((Yt=k.dialog)==null?void 0:Yt.mode)==="mesh"||((us=k.dialog)==null?void 0:us.mode)==="workspace"?k.dialog.mode:null)),nt=l.useRef(g||null),ze=l.useRef(h?null:((su=k.workspace)==null?void 0:su.workspaceChoice)||null),ut=(ru=k.workspace)==null?void 0:ru.kind,Ge=l.useRef(GI(ut)?ut:null),gt=l.useRef(((ou=k.workspace)==null?void 0:ou.target)||null),Mt=l.useRef(((au=k.mesh)==null?void 0:au.meshId)||null),Rt=l.useRef(((iu=k.mesh)==null?void 0:iu.cliType)||null),mn=l.useRef(!0),nn=l.useRef(!0),Jt=l.useRef(0),Et=l.useRef(0),hn=l.useRef(0);l.useEffect(()=>{var te,Ke;if(!j&&((te=b[0])!=null&&te.id)){const We=(Ke=k.dialog)==null?void 0:Ke.machineId,ot=m&&b.some(bn=>bn.id===m)?m:We&&b.some(bn=>bn.id===We)?We:b[0].id;v(ot)}},[m,k,j,b]),l.useEffect(()=>{!C||!(!C.workspaces||!C.availableProviders||!C.detectedIdes||!C.recentLaunches)||y(C.id,{minFreshMs:3e4}).catch(()=>{})},[y,C]);const Bn=l.useCallback(te=>{te&&y(te,{minFreshMs:3e4}).catch(()=>{})},[y]),Tt=l.useMemo(()=>((C==null?void 0:C.availableProviders)||[]).filter(te=>Ao(te,"cli")),[C]),Vt=l.useMemo(()=>((C==null?void 0:C.availableProviders)||[]).filter(te=>Ao(te,"acp")),[C]),pn=l.useMemo(()=>((C==null?void 0:C.detectedIdes)||[]).map(te=>({id:te.type,label:te.name||te.type,meta:te.running?f("newSession.detectedLocally"):f("newSession.availableToOpen")})),[C,f]),Oe=l.useMemo(()=>D==="cli"?Tt.map(te=>({id:te.type,label:te.displayName||te.type,meta:""})):D==="acp"?Vt.map(te=>({id:te.type,label:te.displayName||te.type,meta:""})):pn,[Vt,D,Tt,pn]),rt=l.useMemo(()=>{const te=Tt.map(ot=>({kind:"cli",id:ot.type,label:ot.displayName||ot.type,meta:""}));if(w==="mesh")return te;const Ke=Vt.map(ot=>({kind:"acp",id:ot.type,label:ot.displayName||ot.type,meta:""})),We=pn.map(ot=>({kind:"ide",...ot}));return[...te,...Ke,...We]},[Vt,Tt,pn,w]),pt=l.useMemo(()=>F.find(te=>te.id===I)||null,[F,I]),bt=l.useMemo(()=>Tt.find(te=>te.type===$)||null,[Tt,$]),yt=l.useMemo(()=>[...Tt,...Vt].find(te=>te.type===$),[Tt,Vt,$]),kt=D==="cli"?yt==null?void 0:yt.autoApproveModes:void 0,fn=JSON.stringify(kt||null),Ye=UI(kt),mt=l.useMemo(()=>iA(yt?[yt]:[],yt==null?void 0:yt.type),[yt]),Zt=l.useMemo(()=>{const te=lA(yt?[yt]:[],yt==null?void 0:yt.type);return te.length?te:["low","medium","high"]},[yt]),Sn=l.useMemo(()=>wb(bt==null?void 0:bt.meshCoordinator,{meshId:(pt==null?void 0:pt.id)||"",workspace:(pt==null?void 0:pt.workspace)||""}),[bt,pt]),sn=re||Sn,rn=l.useCallback(async te=>{const Ke=hn.current+1;hn.current=Ke,H(!0),M("");try{const We=await c(te);if(hn.current!==Ke)return;N(We),B(ot=>{var bn;return We.some(ms=>ms.id===ot)?ot:((bn=We[0])==null?void 0:bn.id)||""}),J(te)}catch(We){if(hn.current!==Ke)return;N([]),B(""),J(te),M(We instanceof Error?We.message:f("newSession.errorLoadMeshes"))}finally{hn.current===Ke&&H(!1)}},[c,f]);l.useEffect(()=>{var bn,ms;if(!C)return;if(ge.current!==C.id){Et.current+=1,hn.current+=1,ge.current!==null&&(_e.current=null,Pe.current=null,nt.current=null,ze.current=null,Ge.current=null,gt.current=null,Mt.current=null,Rt.current=null,mn.current=!1,nn.current=!1),ge.current=C.id;const Dt=Pe.current;Pe.current=null,_(Dt||"workspace");const Wn=_e.current,ts=ze.current;R(""),Ce(!1),Ue(""),ke([]),et(!1),st(""),Wn&&x.some(Yi=>Yi.id===Wn)?(_e.current=null,O(Wn)):ts==="__home__"?(ze.current=null,O("__home__")):ts==="__custom__"&&((bn=k.workspace)!=null&&bn.customWorkspacePath)?(ze.current=null,O("__custom__"),R(k.workspace.customWorkspacePath)):ts&&x.some(Yi=>Yi.id===ts)?(ze.current=null,O(ts)):O(S||((ms=x[0])==null?void 0:ms.id)||"__home__"),N([]),B(""),H(!1),J(null),M("");const Vi=Ge.current;Vi&&wo(C,Vi)?(Ge.current=null,P(Vi)):P(Al(C)),W(""),ae(""),V(!1),ce(""),ne(null),ie("","user"),Ne("","user"),Le(!1),pe(""),Y([]),oe(!1),Z(""),ye(!1),tt(""),le(null);return}const Ke=_e.current,We=ze.current;Ke&&x.some(Dt=>Dt.id===Ke)?(_e.current=null,O(Ke)):We&&x.some(Dt=>Dt.id===We)?(ze.current=null,O(We)):O(Dt=>{var Wn;return Dt==="__custom__"||Dt==="__home__"||x.some(ts=>ts.id===Dt)?Dt:S||((Wn=x[0])==null?void 0:Wn.id)||"__home__"});const ot=Ge.current;ot&&wo(C,ot)?(Ge.current=null,P(ot)):P(Dt=>Dt==="ide"&&pn.length>0||Dt==="cli"&&Tt.length>0||Dt==="acp"&&Vt.length>0?Dt:Al(C))},[Vt.length,Tt.length,S,pn.length,k,C,x]),l.useEffect(()=>{!C||w!=="mesh"||q===C.id||T||rn(C.id)},[rn,q,T,C,w]),l.useEffect(()=>{if(F.length===0)return;const te=nt.current;if(te){nt.current=null,Mt.current=null;const We=F.find(ot=>pr(ot.workspace)===pr(te));We&&B(We.id);return}const Ke=Mt.current;Ke&&(Mt.current=null,F.some(We=>We.id===Ke)&&B(Ke))},[F]),l.useEffect(()=>{w==="mesh"&&D!=="cli"&&Tt.length>0&&P("cli")},[D,Tt.length,w]),l.useEffect(()=>{var We;if(!D||Oe.some(ot=>ot.id===$))return;let te=((We=Oe[0])==null?void 0:We.id)||"";const Ke=gt.current;w!=="mesh"&&Ke&&Oe.length>0&&D===ut&&(gt.current=null,Oe.some(ot=>ot.id===Ke)&&(te=Ke)),W(te)},[D,Oe,ut,$,w]),l.useEffect(()=>{if(w!=="mesh")return;const te=Rt.current;!te||Tt.length===0||(Rt.current=null,Tt.some(Ke=>Ke.type===te)&&W(te))},[Tt,w]),l.useEffect(()=>{le(null)},[C==null?void 0:C.id,I,$,w]),l.useEffect(()=>{ie("","user"),Ne("","user"),Le(!1)},[$,ie,Ne]),l.useEffect(()=>{ce(Ye),V(!1),ne(null)},[fn,Ye,C==null?void 0:C.id,$]),l.useEffect(()=>{if(!$)return;const te=w==="mesh",Ke=te?nn:mn;if(!Ke.current)return;const We=te?k.mesh:k.workspace,ot=te?We==null?void 0:We.cliType:We==null?void 0:We.target;if(!We||ot!==$)return;Ke.current=!1;const bn=We.model||"";bn&&(mt.length>0&&!mt.includes(bn)&&Le(!0),ie(bn,"remembered"));const ms=We.thinkingLevel||"";ms&&Zt.includes(ms)&&Ne(ms,"remembered");const Dt=We.autoApproveModeId||"";if(Dt&&kt){const Wn=kt.modes.find(ts=>ts.id===Dt);Wn&&Yn(Wn)!=="dangerous"&&ce(Wn.id)}},[kt,fn,mt,k,$,ie,Ne,Zt,w]);const In=l.useCallback(te=>{if(Yn(te)==="dangerous"){ne(te);return}ce(te.id)},[]),jt=l.useMemo(()=>KI(kt,we,be),[kt,be,we]),en=l.useCallback(async(te,Ke)=>{const We=Jt.current+1;return Jt.current=We,fe(!0),Z(""),u(te,Ke).then(ot=>{Jt.current===We&&Y(ot)}).catch(ot=>{Jt.current===We&&(Y([]),Z(ot instanceof Error?ot.message:f("newSession.errorLoadSavedSessions")))}).finally(()=>{Jt.current===We&&(fe(!1),oe(!0))})},[u,f]),gn=l.useCallback((te,Ke)=>{Se(PI(te,Ke))},[]);l.useEffect(()=>{Jt.current+=1,pe(""),ye(!1),!C||!$||D==="ide"?Se([]):gn(C.id,$),oe(!1),Y([]),Z(""),fe(!1)},[D,gn,en,C,$]),l.useEffect(()=>{if(!he)return;const te=Ee.find(Ke=>Ke.providerSessionId===he);te!=null&&te.canResume||pe("")},[Ee,he]);const Wt=A==="__custom__"?L.trim():A==="__home__"?"":((lu=x.find(te=>te.id===A))==null?void 0:lu.path)||"",Ms=l.useMemo(()=>C?t.filter(te=>te.id!==C.id&&te.daemonId===C.id).map(te=>te.workspace):[],[t,C]),kn=l.useMemo(()=>((C==null?void 0:C.recentLaunches)||[]).map(te=>te.workspace),[C]),Bo=l.useCallback(te=>{const Ke=String(te.workspace||"").trim();if(!Ke)return;const We=x.find(ot=>pr(ot.path)===pr(Ke));if(We){O(We.id),R("");return}O("__custom__"),R(Ke)},[x]),Wo=l.useCallback(te=>{const Ke=String(te.workspace||"").trim();if(!Ke)return{workspaceId:null,workspacePath:null,useHome:!0};const We=x.find(ot=>pr(ot.path)===pr(Ke));return We?{workspaceId:We.id,workspacePath:null,useHome:!1}:{workspaceId:null,workspacePath:Ke,useHome:!1}},[x]),qi=l.useMemo(()=>Ee.find(te=>te.providerSessionId===he)||null,[Ee,he]),zi=l.useCallback(te=>{if(!C||!$||Fe||!te.canResume)return;const Ke=Wo(te);pe(te.providerSessionId),Bo(te),Me(te.providerSessionId),ye(!1),Te(!0),tt(""),i(C.id,"cli",$,{workspaceId:Ke.workspaceId,workspacePath:Ke.workspacePath,useHome:Ke.useHome,resumeSessionId:te.providerSessionId,settings:jt}).then(We=>{if(!We.ok){Q("error"),tt(We.code==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"?f("newSession.errorWorkspaceContextRequired"):We.error||f("newSession.errorResumeSession"));return}s()}).finally(()=>{Te(!1),Me(We=>We===te.providerSessionId?null:We)})},[Bo,jt,s,i,Wo,Fe,C,$,f]),Uo=((cu=kt==null?void 0:kt.modes.find(te=>te.id===we))==null?void 0:cu.label)||"",Ko=[U.trim(),G.trim(),z.trim(),D==="cli"||w==="mesh"?kt?Uo:be?f("newSession.autoApproveLegacy"):"":""].filter(Boolean).join(" · "),Wr=l.useCallback(()=>{var We;if(!C)return;const te=Et.current+1;Et.current=te,O("__custom__"),Ce(!0),st("");const Ke=zd(C.platform,qd(L.trim(),Wt,Ms,kn,C.defaultWorkspacePath,(We=x.find(ot=>ot.id===S))==null?void 0:We.path,x.map(ot=>ot.path)));et(!0),r(C.id,Ke).then(ot=>{Et.current===te&&(Ue(ot.path),R(ot.path),ke(ot.directories))}).catch(ot=>{Et.current===te&&st(ot instanceof Error?ot.message:f("newSession.errorLoadFolder"))}).finally(()=>{Et.current===te&&et(!1)})},[L,S,kn,Ms,r,Wt,C,x]),Gi=l.useCallback(te=>{if(!C)return;const Ke=Et.current+1;Et.current=Ke,et(!0),st(""),r(C.id,te).then(We=>{Et.current===Ke&&(Ue(We.path),R(We.path),ke(We.directories))}).catch(We=>{Et.current===Ke&&st(We instanceof Error?We.message:f("newSession.errorLoadFolder"))}).finally(()=>{Et.current===Ke&&et(!1)})},[r,C]),qo=l.useCallback(async()=>{if(!C||!Wt)return;Qe(!0),tt("");const te=await o(C.id,Wt);if(Qe(!1),!te.ok){Q("error"),tt(te.error||f("newSession.errorSaveWorkspace"));return}Q("info"),tt(f("newSession.workspaceSaved"))},[o,Wt,C,f]),zo=l.useCallback(async()=>{if(!C)return;if(w==="mesh"){if(!I||!$)return;Te(!0),tt(""),le(null);const We=await d(C.id,I,$,{initialModel:G.trim()?G.trim():null,initialThinkingLevel:z.trim()?z.trim():null,...jh(ee,je),settings:jt});if(Te(!1),!We.ok){if(We.code==="mesh_coordinator_manual_mcp_setup_required"&&We.manualSetup){le(We.manualSetup),Q("info"),tt(f("newSession.errorManualMcpSetup"));return}Q("error"),tt(We.error||f("newSession.errorStartMeshCoordinator"));return}pa(Tl,{machineId:C.id,mode:"mesh"}),pa(Sh,{meshId:I,cliType:$,model:G.trim(),thinkingLevel:z.trim(),autoApproveModeId:we}),s();return}if(!D||!$)return;Te(!0),tt("");const te=U.trim()?U.trim().split(/\s+/).filter(Boolean):[],Ke=D==="ide"?await a(C.id,$,{workspacePath:Wt||null}):await i(C.id,D,$,{workspaceId:A!=="__home__"&&A!=="__custom__"?A:null,workspacePath:A==="__custom__"&&Wt||null,useHome:A==="__home__",resumeSessionId:D==="cli"&&he?he:null,cliArgs:te,initialModel:G.trim()?G.trim():null,initialThinkingLevel:z.trim()?z.trim():null,...jh(ee,je),settings:jt});if(Te(!1),!Ke.ok){Q("error"),tt(Ke.code==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"?f("newSession.errorWorkspaceContextRequired"):Ke.error||f("newSession.errorStartSession"));return}D!=="ide"&&U.trim()&&(LI(C.id,$,U),gn(C.id,$)),pa(Tl,{machineId:C.id,mode:"workspace"}),pa(wh,{workspaceChoice:A,customWorkspacePath:A==="__custom__"?Wt:"",kind:D,target:$,model:D==="ide"?"":G.trim(),thinkingLevel:D==="ide"?"":z.trim(),autoApproveModeId:D==="cli"?we:""}),s()},[D,U,G,z,ee,je,jt,gn,s,a,d,i,Wt,we,C,I,he,$,A,w,f]),Ur=D==="cli"&&!!he,Go=f(w==="mesh"?"newSession.startMeshCoordinator":D==="cli"?Ur?"newSession.resumeSavedHistory":"newSession.startFresh":D==="ide"?"newSession.startIde":D==="acp"?"newSession.startAcpSession":"newSession.start"),Vo=f(w==="mesh"?"newSession.startingCoordinator":D==="cli"?Ur?"newSession.resumingSavedHistory":"newSession.startingFresh":D==="ide"?"newSession.startingIde":D==="acp"?"newSession.startingAcpSession":"newSession.starting"),ht=b.length>5;return C?n.jsxs(n.Fragment,{children:[n.jsxs(Rr,{chrome:!1,onClose:s,closeOnBackdrop:!1,closeOnEsc:!1,ariaLabelledBy:"dashboard-new-title",overlayClassName:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",surfaceClassName:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[n.jsx("div",{className:"min-w-0",children:n.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:f("newSession.title")})}),n.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:s,"aria-label":f("newSession.close"),children:n.jsx(Bt,{size:16})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[b.length>1&&n.jsx($s,{title:f("newSession.machine"),children:ht?n.jsx("select",{"aria-label":f("newSession.machine"),value:C.id,onChange:te=>v(te.target.value),onFocus:()=>b.forEach(te=>Bn(te.id)),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:De,children:b.map(te=>n.jsx("option",{value:te.id,children:Tn(te,{fallbackId:te.id})},te.id))}):n.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":f("newSession.machine"),children:b.map(te=>{const Ke=Tn(te,{fallbackId:te.id}),We=C.id===te.id;return n.jsxs("button",{type:"button","aria-label":f("newSession.selectMachine",{name:Ke}),"aria-pressed":We,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${We?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>v(te.id),onMouseEnter:()=>Bn(te.id),onFocus:()=>Bn(te.id),disabled:De,title:Ke,children:[n.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${te.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),n.jsx("span",{className:"truncate",children:Ke})]},te.id)})})}),n.jsxs($s,{title:f("newSession.workspace"),action:w==="workspace"?n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Wr,disabled:De,children:f("newSession.browse")}):void 0,children:[n.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":f("newSession.launchTargetType"),children:[{id:"workspace",label:f("newSession.modeWorkspace"),desc:f("newSession.modeWorkspaceDesc")},{id:"mesh",label:f("newSession.modeMesh"),desc:f("newSession.modeMeshDesc")}].map(te=>n.jsxs("button",{type:"button",role:"radio","aria-checked":w===te.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${w===te.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{_(te.id),tt(""),te.id==="mesh"&&C&&q!==C.id&&!T&&rn(C.id)},disabled:De,children:[n.jsx("div",{className:"text-sm font-semibold",children:te.label}),n.jsx("div",{className:"mt-0.5 text-2xs opacity-80",children:te.desc})]},te.id))}),w==="workspace"?n.jsxs(n.Fragment,{children:[n.jsxs("select",{value:A,onChange:te=>{const Ke=te.target.value;ze.current=null,O(Ke),Ke==="__custom__"?Wr():tt("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:De,children:[n.jsx("option",{value:"__home__",children:f("newSession.homeDirectory")}),x.map(te=>n.jsxs("option",{value:te.id,children:[te.id===S?"★ ":"",ja(te.path,te.label)||te.path]},te.id)),n.jsx("option",{value:"__custom__",children:f("newSession.customFolder")})]}),n.jsx("div",{className:"mt-2 text-2xs text-text-muted break-all",children:A==="__home__"?f("newSession.launchWithoutWorkspace"):Wt||f("newSession.selectWorkspaceFolder")}),xe&&n.jsx(Yd,{inline:!0,title:f("newSession.selectWorkspaceTitle"),description:"",currentPath:Re,directories:$e,busy:Ze,error:Ve,onClose:()=>Ce(!1),onNavigate:Gi,onConfirm:te=>{R(te),Ue(te),O("__custom__"),Ce(!1)}}),!xe&&A==="__custom__"&&Wt&&n.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[n.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Wr,disabled:De,children:[n.jsx(Zs,{size:14}),f("newSession.selectFolder")]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:qo,disabled:De||lt,children:f(lt?"newSession.saving":"newSession.saveWorkspace")})]})]}):n.jsxs("div",{className:"space-y-3",children:[T&&n.jsx("div",{className:"text-sm text-text-muted",children:f("newSession.loadingMeshes")}),!T&&K&&n.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:K}),!T&&!K&&F.length===0&&n.jsxs("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:[f("newSession.noMeshesShort"),n.jsx(dt,{content:f("newSession.noMeshes")})]}),F.length>0&&n.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":f("newSession.mesh"),children:F.map(te=>n.jsxs("button",{type:"button",role:"radio","aria-checked":I===te.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${I===te.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>{Mt.current=null,B(te.id)},disabled:De,children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:te.name}),n.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[te.repoIdentity||f("newSession.repoMesh"),typeof te.nodesCount=="number"?` · ${f("newSession.nodeCount",{count:te.nodesCount})}`:""]}),te.workspace&&n.jsx("div",{className:"mt-1 text-2xs text-text-muted break-all",children:f("newSession.coordinatorWorkspace",{path:te.workspace})})]},te.id))})]})]}),n.jsx($s,{title:f("newSession.agent"),children:n.jsxs("div",{className:"grid grid-cols-1 gap-1.5",role:"radiogroup","aria-label":f("newSession.agent"),children:[rt.map(te=>{const Ke=D===te.kind&&$===te.id;return n.jsxs("button",{type:"button",role:"radio","aria-checked":Ke,"data-launch-kind":te.kind,className:`flex w-full items-center justify-between gap-3 rounded-xl border px-3.5 py-2.5 text-left transition-colors ${Ke?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>{Ge.current=null,gt.current=null,Rt.current=null,P(te.kind),W(te.id)},disabled:De,children:[n.jsx("span",{className:"min-w-0 truncate text-sm font-semibold text-text-primary",children:te.label}),n.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[te.meta&&n.jsx("span",{className:"text-2xs text-text-muted",children:te.meta}),w!=="mesh"&&n.jsx("span",{className:"rounded-full border border-border-subtle px-1.5 py-px text-3xs font-semibold uppercase tracking-wide text-text-muted",children:HI[te.kind]})]})]},`${te.kind}:${te.id}`)}),rt.length===0&&n.jsxs("div",{className:"flex items-center gap-1 text-sm text-text-muted",children:[f("newSession.noProvidersShort"),n.jsx(dt,{content:f("newSession.noProviders")})]})]})}),w==="mesh"&&sn&&n.jsx(qb,{setup:sn,providerName:(bt==null?void 0:bt.displayName)||(bt==null?void 0:bt.name)||$}),(w==="mesh"&&!!$||w!=="mesh"&&D!=="ide")&&n.jsxs("details",{className:"group rounded-xl border border-border-subtle bg-bg-primary","data-testid":"new-session-advanced",children:[n.jsxs("summary",{className:"flex cursor-pointer select-none list-none items-center gap-2 px-4 py-3 [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"inline-block text-text-muted transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),n.jsx("span",{className:"text-3xs uppercase tracking-[0.08em] text-text-muted",children:f("newSession.advancedOptions")}),Ko&&n.jsx("span",{className:"ml-auto min-w-0 truncate text-2xs text-text-secondary","data-testid":"new-session-advanced-summary",children:Ko})]}),n.jsxs("div",{className:"space-y-3 px-3 pb-3",children:[w!=="mesh"&&D!=="ide"&&n.jsxs($s,{title:f("newSession.startupArguments"),children:[n.jsx("input",{type:"text",value:U,onChange:te=>ae(te.target.value),placeholder:f("newSession.optionalFlags"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:De}),Je.length>0&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Je.map(te=>n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>ae(te),disabled:De,title:te,children:te},te))})]}),(w==="mesh"&&!!$||w!=="mesh"&&D==="cli")&&n.jsx($s,{title:f("newSession.autoApproveMode"),description:kt?f("newSession.autoApproveModeDescription"):void 0,children:kt?n.jsx(Gb,{config:kt,selectedModeId:we,disabled:De,onSelectMode:In}):n.jsx(zI,{checked:be,disabled:De,onChange:V})}),(w==="mesh"&&!!$||w!=="mesh"&&D!=="ide")&&n.jsx($s,{title:f("newSession.modelAndThinking"),children:n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:f("newSession.model")}),mt.length>0&&!Be?n.jsxs(n.Fragment,{children:[n.jsxs("select",{value:mt.includes(G)?G:"",onChange:te=>{te.target.value==="__custom__"?(Le(!0),ie("","user")):ie(te.target.value,"user")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:De,children:[n.jsx("option",{value:"",children:f("newSession.providerDefault")}),mt.map(te=>n.jsx("option",{value:te,children:te},te)),n.jsx("option",{value:"__custom__",children:f("newSession.custom")})]}),!G.trim()&&n.jsx("span",{className:"text-2xs text-text-muted","data-testid":"new-session-default-model",children:f("newSession.defaultResolvesTo",{model:mt[0],defaultValue:"Default resolves to {{model}}"})})]}):n.jsxs(n.Fragment,{children:[n.jsx("input",{type:"text",value:G,onChange:te=>ie(te.target.value,"user"),placeholder:f("newSession.typeModelName"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:De,autoFocus:Be}),mt.length>0&&n.jsx("button",{type:"button",className:"self-start text-2xs text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{Le(!1),ie("","user")},disabled:De,children:f("newSession.backToModelList")})]})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:f("newSession.thinkingLevel")}),n.jsxs("select",{value:z,onChange:te=>Ne(te.target.value,"user"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:De,children:[n.jsx("option",{value:"",children:f("newSession.providerDefault")}),Zt.map(te=>n.jsx("option",{value:te,children:te},te))]})]})]})})]})]}),w!=="mesh"&&D==="cli"&&n.jsx($I,{busy:De,savedSessionsLoading:me,savedSessionsError:Ie,savedSessionsLoaded:E,savedSessionsCount:Ee.length,selectedSession:qi,historyOpen:se,onOpenHistory:()=>{if(!(!C||!$)){if(se){ye(!1);return}ye(!0),OI({hasLoadedInitialResults:E,isLoading:me})&&en(C.id,$)}},onClearSelection:()=>pe("")}),w!=="mesh"&&D==="cli"&&se&&n.jsx(DI,{sessions:Ee,loading:me,busy:De,resumingSessionId:Fe,fallbackWorkspacePath:Wt||null,onRefresh:()=>{!C||!$||en(C.id,$)},onClose:()=>ye(!1),onResume:zi}),He&&n.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${Ct==="info"?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:He})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[n.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:s,disabled:De,children:f("common.cancel")}),n.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:zo,disabled:De||(w==="mesh"?!I||!$||D!=="cli"||T:!D||!$||A==="__custom__"&&!Wt),children:[n.jsx(Op,{size:14}),De?Vo:Go]})]})]}),de&&n.jsx(Vb,{mode:de,onConfirm:()=>{ce(de.id),ne(null)},onCancel:()=>ne(null)})]}):null}function YI(e,t){const{sendCommand:s}=_t(),[r,o]=l.useState(null),[a,i]=l.useState(!1),c=l.useRef(0);l.useEffect(()=>{const u=c.current+1;if(c.current=u,o(null),!e||!t){i(!1);return}return i(!0),s(e,"git_remote_url",{workspace:t}).then(m=>{if(c.current!==u)return;const h=(m==null?void 0:m.result)??m;o(typeof(h==null?void 0:h.remoteUrl)=="string"?h.remoteUrl:null)}).catch(()=>{c.current===u&&o(null)}).finally(()=>{c.current===u&&i(!1)}),()=>{c.current+=1}},[e,t,s]);const d=QI(r);return{remoteUrl:r,githubUrl:d,loading:a}}function QI(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 Yb=5e3;function JI(e,t){return t?`git:${t}:${e}`:`git:${e}`}function XI({workspace:e,daemonId:t,includeDiffSummary:s=!1,intervalMs:r=Yb}){return{type:"subscribe",topic:"workspace.git",key:JI(e,t),params:{workspace:e,includeDiffSummary:s,intervalMs:r}}}function Jd(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function sr(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const s=e;if(typeof s.error=="string"&&s.error.trim())return s.error;if(typeof s.message=="string"&&s.message.trim())return s.message}return t}function ZI(e){const t=Jd(e);return(t==null?void 0:t.success)===!1?{status:null,error:sr(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:sr(t,"Git status response did not include status")}}function eM(e){const t=Jd(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:sr(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:sr(t,"Git diff summary response did not include diffSummary")}}function Il(e){return e===void 0||typeof e=="boolean"}function tM(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Il(t.binary)&&Il(t.truncated)&&Il(t.staged)}function nM(e){const t=Jd(e);return(t==null?void 0:t.success)===!1?{diff:null,error:sr(t,"Git file diff request failed")}:tM(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:sr(t,"Git file diff response did not include a valid diff object")}}function sM({daemonId:e,workspace:t,enabled:s=!0,includeDiffSummary:r=!1,intervalMs:o=Yb}){const{sendCommand:a,sendData:i}=_t(),c=typeof t=="string"?t.trim():"",d=!!(s&&e&&c),[u,m]=l.useState(null),[h,p]=l.useState(null),[g,f]=l.useState(!1),[y,b]=l.useState(null),k=l.useRef(0),j=l.useCallback(async()=>{if(!d||!e||!c)return;const C=k.current+1;k.current=C,f(!0),b(null);try{const x=ZI(await a(e,"git_status",{workspace:c}));if(k.current!==C)return;if(x.error){m(null),p(null),b(x.error);return}if(m(x.status),!r){p(null);return}const S=eM(await a(e,"git_diff_summary",{workspace:c}));if(k.current!==C)return;if(S.error){p(null),b(S.error);return}p(S.diffSummary)}catch(x){if(k.current!==C)return;b(sr(x,"Git status request failed"))}finally{k.current===C&&f(!1)}},[d,e,r,a,c]),v=l.useMemo(()=>c?XI({workspace:c,daemonId:e,includeDiffSummary:r,intervalMs:o}):null,[e,r,o,c]);return l.useEffect(()=>{if(k.current+=1,m(null),p(null),f(!1),b(null),!d||!e||!c||!v)return;const C=i?_n.subscribe({sendData:i},e,v,x=>{var S,w;x.workspace===c&&(m(x.status),p(x.diffSummary??null),b(((S=x.status)==null?void 0:S.error)||((w=x.diffSummary)==null?void 0:w.error)||null),f(!1))},{retryIntervalMs:1e3}):null;return j(),()=>{k.current+=1,C==null||C()}},[d,e,j,v,i,c]),{status:u,diffSummary:h,loading:g,error:y,refresh:j}}const rM={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},oM={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 Nh(e){return e.split("/").pop()??e}function aM(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function iM({files:e,truncated:t,onFileClick:s,selectedPath:r,className:o=""}){const{t:a}=ve("common");return e.length===0?n.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:a("git.changeList.noChanges")}):n.jsxs("div",{className:`flex flex-col ${o}`,children:[n.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(i=>{const c=r===i.path,d=rM[i.status]??"?",u=oM[i.status]??"text-text-muted",m=aM(i.path),h=Nh(i.path),p=i.staged?n.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-status-online align-middle",title:a("git.changeList.stagedHint")}):null;return n.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${c?"bg-surface-elevated":""}`,onClick:()=>s==null?void 0:s(i),children:[n.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${u}`,title:i.status,children:d}),n.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&n.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),n.jsx("span",{className:"text-text-primary",children:h}),i.oldPath&&n.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Nh(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($a,{i18nKey:"git.changeList.truncatedNote",ns:"common",components:{code:n.jsx("code",{className:"font-mono"})}})})]})}function lM(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 cM({diff:e,binary:t,truncated:s,loading:r,error:o,className:a=""}){const{t:i}=ve("common"),c=l.useRef(null);if(l.useEffect(()=>{c.current&&(c.current.scrollTop=0)},[e]),r)return n.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${a}`,children:i("git.diffPreview.loading")});if(o)return n.jsx("div",{className:`px-3 py-4 text-xs text-status-error ${a}`,children:o});if(t)return n.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${a}`,children:i("git.diffPreview.binary")});if(!e)return n.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${a}`,children:i("git.diffPreview.empty")});const d=e.split(`
|
|
70
|
-
`);return n.jsxs("div",{ref:c,className:`overflow-auto ${a}`,children:[n.jsx("div",{className:"py-1",children:d.map((u,m)=>lM(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 dM(e,t){const s=[`Branch: ${e||"unknown"}`];s.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const r={};for(const o of t.files)r[o.status]||(r[o.status]=[]),r[o.status].push(o.path);for(const[o,a]of Object.entries(r))s.push(`${o}: ${a.slice(0,5).join(", ")}${a.length>5?` (+${a.length-5} more)`:""}`);return s.join(`
|
|
71
|
-
`)}function Qb({daemonId:e,workspace:t,onClose:s}){const{t:r}=ve("common"),{sendCommand:o}=_t(),{status:a,diffSummary:i,loading:c,error:d,refresh:u}=sM({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,h]=l.useState(null),[p,g]=l.useState(null),[f,y]=l.useState(""),[b,k]=l.useState(!1),[j,v]=l.useState(!1),[C,x]=l.useState(null),[S,w]=l.useState(null),{githubUrl:_}=YI(e,t),A=l.useCallback(async I=>{if(!((m==null?void 0:m.path)===I.path&&!m.loading)){h({path:I.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const B=await o(e,"git_diff_file",{workspace:t,path:I.path,staged:I.staged}),T=nM(B);if(T.error||!T.diff){h({path:I.path,diff:"",binary:!1,truncated:!1,loading:!1,error:T.error??"Failed to load diff"});return}h({path:I.path,diff:T.diff.diff,binary:T.diff.binary??!1,truncated:T.diff.truncated??!1,loading:!1,error:null})}catch(B){const T=B instanceof Error?B.message:"Failed to load diff";h({path:I.path,diff:"",binary:!1,truncated:!1,loading:!1,error:T})}}},[e,o,m,t]),O=l.useCallback(I=>{y(""),k(!1),x(null),w(null),g(I)},[]),L=l.useCallback(()=>{g(null),x(null),v(!1)},[]),R=l.useCallback(async()=>{var I,B,T;if(p){v(!0),x(null);try{let H;p==="checkpoint"?H=await o(e,"git_checkpoint",{workspace:t,message:f,includeUntracked:b}):p==="stash"?H=await o(e,"git_stash_push",{workspace:t,message:f,includeUntracked:b}):p==="stash_pop"?H=await o(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&m&&(H=await o(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const q=(H==null?void 0:H.result)??H;if((q==null?void 0:q.success)===!1||q!=null&&q.error){x((q==null?void 0:q.error)??"Action failed"),v(!1);return}p==="checkpoint"?w(`Checkpoint created: ${((B=(I=q==null?void 0:q.checkpoint)==null?void 0:I.commit)==null?void 0:B.slice(0,7))??"done"}`):p==="stash"?w(`Stashed as ${((T=q==null?void 0:q.stash)==null?void 0:T.stashRef)??"stash@{0}"}`):p==="stash_pop"?w("Stash restored"):(w("File reverted"),h(null)),g(null),await u()}catch(H){x(H instanceof Error?H.message:"Action failed")}finally{v(!1)}}},[p,o,e,t,f,b,m,u]),F=!!(a!=null&&a.hasConflicts);l.useEffect(()=>{const I=B=>{B.key==="Escape"&&(p?L():s())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[p,L,s]);const N=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",onClick:I=>{I.target===I.currentTarget&&s()},children:n.jsxs("div",{className:"relative flex h-[80dvh] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-2rem)] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[n.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[n.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??r("git.statusDialog.title")}),n.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),_&&n.jsx("a",{href:`${_}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-3xs text-text-secondary hover:text-accent-primary underline",title:r("git.statusDialog.openOnGithub"),children:"GitHub ↗"})]}),n.jsx("button",{onClick:u,disabled:c,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:r("git.statusDialog.refresh"),children:"↺"}),n.jsx("button",{type:"button",onClick:s,className:"-m-1.5 flex h-11 w-11 shrink-0 items-center justify-center rounded text-text-secondary hover:text-text-primary","aria-label":r("common.close"),children:n.jsx(Bt,{className:"h-4 w-4"})})]}),a&&n.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&n.jsxs("span",{title:a.headMessage??void 0,children:[n.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&n.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&n.jsxs("span",{className:"text-orange-400",children:["↑",r("git.statusDialog.ahead",{count:a.ahead})]}),a.behind>0&&n.jsxs("span",{className:"text-orange-400",children:["↓",r("git.statusDialog.behind",{count:a.behind})]}),a.staged>0&&n.jsx("span",{className:"text-status-online",children:r("git.statusDialog.staged",{count:a.staged})}),a.modified>0&&n.jsx("span",{children:r("git.statusDialog.modified",{count:a.modified})}),a.untracked>0&&n.jsx("span",{children:r("git.statusDialog.untracked",{count:a.untracked})}),a.deleted>0&&n.jsx("span",{className:"text-status-error",children:r("git.statusDialog.deleted",{count:a.deleted})}),a.stashCount>0&&n.jsx("span",{children:r("git.statusDialog.stashed",{count:a.stashCount})}),a.hasConflicts&&n.jsx("span",{className:"font-bold text-status-error",children:r("git.statusDialog.conflicts")}),N===0&&!a.error&&n.jsx("span",{className:"text-status-online",children:r("git.statusDialog.clean")}),i&&i.files.length>0&&n.jsxs("span",{className:"text-text-secondary",children:[r("git.statusDialog.fileCount",{count:i.files.length}),i.totalInsertions>0&&n.jsxs("span",{className:"text-status-online",children:[" +",i.totalInsertions]}),i.totalDeletions>0&&n.jsxs("span",{className:"text-status-error",children:[" -",i.totalDeletions]})]})]}),d&&n.jsx("div",{className:"shrink-0 border-b border-border/50 bg-status-error/10 px-4 py-2 text-xs text-status-error",children:d}),n.jsxs("div",{className:"flex min-h-0 flex-1",children:[n.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[c&&!i&&n.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:r("git.statusDialog.loading")}),i&&n.jsx(iM,{files:i.files,truncated:i.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:A}),!c&&!i&&!d&&n.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:r("git.statusDialog.noDiffData")})]}),n.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?n.jsx(cM,{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")})})]}),S&&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:S}),n.jsx("button",{onClick:()=>w(null),className:"ml-2 text-status-online hover:text-text-primary",children:"×"})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[n.jsx("button",{onClick:()=>O("checkpoint"),disabled:F,title:r(F?"git.statusDialog.resolveBeforeCheckpoint":"git.statusDialog.checkpointHint"),className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:r("git.statusDialog.checkpoint")}),n.jsx("button",{onClick:()=>O("stash"),disabled:F,title:r(F?"git.statusDialog.resolveBeforeStash":"git.statusDialog.stashHint"),className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:r("git.statusDialog.stash")}),n.jsx("button",{onClick:()=>O("stash_pop"),disabled:F||!(a!=null&&a.stashCount),title:F?r("git.statusDialog.resolveBeforePop"):a!=null&&a.stashCount?r("git.statusDialog.popHint"):r("git.statusDialog.noStashes"),className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:r("git.statusDialog.popStash")}),n.jsx("button",{onClick:()=>O("checkout_files"),disabled:!m,title:m?r("git.statusDialog.revertFile",{path:m.path}):r("git.statusDialog.selectFileToRevert"),className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:r("git.statusDialog.checkoutSelected")}),i&&i.files.length>0&&n.jsx("button",{onClick:()=>{const I=dM((a==null?void 0:a.branch)??null,i);navigator.clipboard.writeText(I),w(r("git.statusDialog.copied")),setTimeout(()=>w(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=>y(I.target.value),maxLength:200,placeholder:r("git.statusDialog.messageRequired"),className:"rounded border border-border bg-surface-secondary px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),n.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:b,onChange:I=>k(I.target.checked)}),r("git.statusDialog.includeUntracked")]})]}),C&&n.jsx("p",{className:"text-xs text-status-error",children:C}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{onClick:L,disabled:j,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:r("common.cancel")}),n.jsx("button",{onClick:R,disabled:j||(p==="checkpoint"||p==="stash")&&!f.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:r(j?"git.statusDialog.working":"common.confirm")})]})]})})]})})})}function uM({isMobile:e,showMobileChatMode:t,visibleConversationCount:s}){const[r,o]=l.useState(!1),[a,i]=l.useState(!1),[c,d]=l.useState(!1),[u,m]=l.useState(!1),[h,p]=l.useState(!1),[g,f]=l.useState("quickstart"),[y,b]=l.useState("workspace"),k=l.useMemo(()=>!t&&!e,[t,e]),j=l.useCallback(_=>{o(_),_&&i(!1)},[]),v=l.useCallback(_=>{i(_),_&&o(!1)},[]),C=l.useCallback(()=>{f(s===0?"quickstart":"shortcuts"),b("workspace"),d(!0),o(!1),i(!1)},[s]),x=l.useCallback(()=>{d(!1)},[]),S=l.useCallback(()=>{m(!0)},[]),w=l.useCallback(()=>{m(!1)},[]);return l.useEffect(()=>{if(!k){p(!1);return}p(!0);const _=window.setTimeout(()=>{p(!1)},1e4);return()=>window.clearTimeout(_)},[k]),{inboxOpen:r,hiddenOpen:a,shortcutHelpOpen:c,newSessionOpen:u,guideNudgeVisible:h,guideTab:g,shortcutSection:y,isDesktopDashboard:k,setGuideTab:f,setShortcutSection:b,handleInboxOpenChange:j,handleHiddenOpenChange:v,handleOpenShortcutHelp:C,closeShortcutHelp:x,openNewSession:S,closeNewSession:w}}function mM(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 hM(e){return e instanceof Error?e.message:String(e||"")}function pM(e){const t=hM(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function fM({showMobileChatMode:e,isMobile:t,activeConv:s,wsStatus:r,isConnected:o,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:u,mobileChatConversations:m,hiddenConversations:h,ides:p,actionLogs:g,sendDaemonCommand:f,setActionLogs:y,setCliViewModeOverrides:b,isStandalone:k,initialDataLoaded:j,userName:v,requestedMobileTabKey:C,onRequestedMobileTabConsumed:x,requestedMachineId:S,onRequestedMachineConsumed:w,requestedNewSessionLaunch:_,onRequestedNewSessionLaunchConsumed:A,requestedMobileSection:O,onRequestedMobileSectionConsumed:L,containerRef:R,isSplitMode:F,numGroups:N,groupSizes:I,groupedConvs:B,clearedTabs:T,focusedGroup:H,focusGroup:q,moveTabToGroup:J,splitTabRelative:K,closeGroup:M,handleResizeStart:D,groupActiveTabIds:P,setGroupActiveTab:$,groupTabOrders:W,setGroupTabOrder:U,toggleHiddenTab:ae,visibleConversations:be,requestedDesktopTabKey:V,onRequestedDesktopTabConsumed:we,onDesktopActiveTabChange:ce,onRequestScrollToBottom:de,onHideConversation:ne,onShowHiddenConversation:ee,onShowAllHiddenConversations:ue,scrollToBottomRequest:je,machineEntries:X,layoutProfile:G,onBrowseMachineDirectory:z,onSaveMachineWorkspace:ie,onLaunchMachineIde:Ne,onLaunchMachineProvider:Be,onListMachineMeshes:Le,onLaunchMeshCoordinator:Je,onListMachineSavedSessions:Se,notifications:he,notificationUnreadCount:pe,liveSessionInboxState:Ee,onMarkNotificationRead:Y,onMarkNotificationUnread:me,onDeleteNotification:fe}){const{t:E}=ve(),oe=It.useRef(null),{inboxOpen:Ie,hiddenOpen:Z,shortcutHelpOpen:se,newSessionOpen:ye,guideNudgeVisible:Fe,guideTab:Me,shortcutSection:De,isDesktopDashboard:Te,setGuideTab:He,setShortcutSection:tt,handleInboxOpenChange:Ct,handleHiddenOpenChange:Q,handleOpenShortcutHelp:re,closeShortcutHelp:le,openNewSession:xe,closeNewSession:Ce}=uM({isMobile:t,showMobileChatMode:e,visibleConversationCount:be.length}),[Re,Ue]=It.useState(null);It.useEffect(()=>{_&&(Ue({machineId:_.machineId,workspaceId:_.workspaceId??null,mode:_.mode||"workspace",meshWorkspacePath:_.meshWorkspacePath??null}),xe(),A==null||A())},[_,xe,A]);const $e=It.useCallback(()=>{Ue(null),Ce()},[Ce]),{confirm:ke,confirmDialog:Ze}=Fr(),[et,Ve]=It.useState(null),[st,lt]=It.useState(null),Qe=It.useCallback((Oe,rt)=>{Ve({daemonId:Oe,workspace:rt})},[]),ge=It.useCallback(Oe=>{lt(Oe)},[]),_e=It.useCallback(Oe=>{var rt;Qn.flushSync(()=>{ee(Oe)}),(rt=oe.current)==null||rt.restoreHiddenTabToSavedLocation(Oe.tabKey)},[ee]),Pe=It.useCallback(Oe=>{var pt;const rt=m.find(bt=>co(bt,Oe))||h.find(bt=>co(bt,Oe));rt&&(h.some(bt=>bt.tabKey===rt.tabKey)&&_e(rt),ce(rt.tabKey),(pt=oe.current)==null||pt.activateConversationTab(rt.tabKey),de(rt.tabKey,"notification-open")),Y(Oe.id),Ct(!1)},[_e,h,m,ce,Y,de]);It.useEffect(()=>w1(Oe=>{var bt;const rt=[{sessionId:Oe.sessionId},...Oe.providerSessionId?[{providerSessionId:Oe.providerSessionId}]:[]];let pt;for(const yt of rt)if(pt=m.find(kt=>co(kt,yt))||h.find(kt=>co(kt,yt)),pt)break;if(!pt){ct.showToast(E("sessionNav.chatNotFound"),"info");return}h.some(yt=>yt.tabKey===pt.tabKey)&&_e(pt),lt(null),ce(pt.tabKey),(bt=oe.current)==null||bt.activateConversationTab(pt.tabKey),de(pt.tabKey,"conversation-open")}),[_e,h,m,ce,de,E]);const nt=It.useCallback(async()=>{var rt;await ke({title:E("common.confirmTitle"),description:E("dashboard.hidden.resetPanelsConfirm"),confirmLabel:E("common.confirm")})&&((rt=oe.current)==null||rt.resetAllPanelsToMain(),Q(!1))},[ke,Q,E]),ze=It.useCallback(async Oe=>{var kt;if(!s)return;const rt=(kt=s.modalButtons)==null?void 0:kt[Oe];if(!rt)return;const pt=vs(s);if(!pt)return;const bt=rt.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),yt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(bt);try{await f(pt,"resolve_action",{button:rt,action:yt?"approve":"reject",buttonIndex:Oe,...ks(s)})}catch(fn){pM(fn)||console.error("[Shortcut approval] Failed:",fn)}},[s,f]),{isMac:ut,actionDefinitions:Ge,actionShortcuts:gt,shortcutListening:Mt,shortcutListeningDraft:Rt,setShortcutListening:mn,setShortcutListeningDraft:nn,saveShortcuts:Jt}=pI({enabled:Te&&!se,onTrigger:Oe=>{var rt,pt,bt,yt,kt,fn,Ye,mt,Zt,Sn,sn,rn,In,jt,en,gn;if(Oe==="openShortcutHelp"){re();return}if(Oe==="openNewSession"){xe();return}if(Oe==="hideCurrentTab"){s&&ne(s);return}if(Oe==="toggleHiddenTabs"){Q(!Z);return}if(Oe==="openHistoryForActiveTab"){s&&!vt(s)&&a(s);return}if(Oe==="openRemoteForActiveTab"){s&&!St(s)&&!vt(s)&&i(s);return}if(Oe==="splitActiveTabRight"){(rt=oe.current)==null||rt.splitActiveTabRight();return}if(Oe==="splitActiveTabDown"){(pt=oe.current)==null||pt.splitActiveTabDown();return}if(Oe==="floatActiveTab"){(bt=oe.current)==null||bt.floatActiveTab();return}if(Oe==="popoutActiveTab"){(yt=oe.current)==null||yt.popoutActiveTab();return}if(Oe==="dockActiveTab"){(kt=oe.current)==null||kt.dockActiveTab();return}if(Oe==="focusLeftPane"){(fn=oe.current)==null||fn.focusLeftPane();return}if(Oe==="focusRightPane"){(Ye=oe.current)==null||Ye.focusRightPane();return}if(Oe==="focusUpPane"){(mt=oe.current)==null||mt.focusUpPane();return}if(Oe==="focusDownPane"){(Zt=oe.current)==null||Zt.focusDownPane();return}if(Oe==="moveActiveTabToLeftPane"){(Sn=oe.current)==null||Sn.moveActiveTabToLeftPane();return}if(Oe==="moveActiveTabToRightPane"){(sn=oe.current)==null||sn.moveActiveTabToRightPane();return}if(Oe==="moveActiveTabToUpPane"){(rn=oe.current)==null||rn.moveActiveTabToUpPane();return}if(Oe==="moveActiveTabToDownPane"){(In=oe.current)==null||In.moveActiveTabToDownPane();return}if(Oe==="triggerPrimaryApprovalAction"){ze(0);return}if(Oe==="triggerSecondaryApprovalAction"){ze(1);return}if(Oe==="triggerTertiaryApprovalAction"){ze(2);return}if(Oe==="setActiveTabShortcut"){(jt=oe.current)==null||jt.setShortcutForActiveTab();return}if(Oe==="selectPreviousGroupTab"){(en=oe.current)==null||en.activatePreviousTabInGroup();return}if(Oe==="selectNextGroupTab"){(gn=oe.current)==null||gn.activateNextTabInGroup();return}!s||!St(s)||vt(s)||Oe==="toggleCliView"&&u(d==="chat"?"terminal":"chat")}}),Et=It.useCallback(()=>{le(),mn(null),nn([])},[le,mn,nn]),hn=It.useMemo(()=>De==="all"?Ge:Ge.filter(Oe=>mM(Oe)===De),[Ge,De]),Bn=It.useMemo(()=>[wt("triggerPrimaryApprovalAction",ut),wt("triggerSecondaryApprovalAction",ut),wt("triggerTertiaryApprovalAction",ut)].filter(Boolean).join(" / "),[ut]),Tt=ut?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",Vt=It.useCallback(()=>{const Oe=Object.fromEntries(Ge.map(rt=>[rt.id,""]));Jt(Oe)},[Ge,Jt]),pn=It.useCallback(async()=>{if(!await ke({title:E("common.confirmTitle"),description:E("dashboard.guide.shortcuts.resetConfirm"),confirmLabel:E("common.confirm")}))return;const rt=Object.fromEntries(Ge.map(pt=>[pt.id,pt.defaultShortcut]));Jt(rt)},[Ge,ke,Jt,E]);return It.useEffect(()=>{const Oe=rt=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?rt.metaKey&&rt.key.toLowerCase()==="w":rt.ctrlKey&&rt.key.toLowerCase()==="w")&&(rt.preventDefault(),s&&ne&&ne(s))};return window.addEventListener("keydown",Oe),()=>window.removeEventListener("keydown",Oe)},[s,ne]),It.useEffect(()=>{if(!se||Mt)return;const Oe=rt=>{rt.key==="Escape"&&(rt.preventDefault(),Et())};return window.addEventListener("keydown",Oe,!0),()=>window.removeEventListener("keydown",Oe,!0)},[Et,se,Mt]),n.jsxs(n.Fragment,{children:[!e&&n.jsx(K1,{activeConv:s,wsStatus:r,isConnected:o,conversations:be,hiddenConversations:h,onOpenHistory:a,onHideConversation:ne,onShowConversation:_e,onShowAllHidden:ue,onResetPanelsToMain:nt,notifications:he,notificationUnreadCount:pe,onOpenNotification:Pe,onMarkNotificationRead:Y,onMarkNotificationUnread:me,onDeleteNotification:fe,inboxOpen:Ie,onInboxOpenChange:Ct,hiddenOpen:Z,onHiddenOpenChange:Q,onOpenNewSession:t?void 0:xe,onOpenDashboardGuide:re,guideNudgeVisible:Fe,actionShortcuts:gt,onOpenRemote:()=>{!s||St(s)||vt(s)||i(s)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:u,onOpenGitDialog:Qe,onOpenMeshGraph:ge}),e?n.jsx(nI,{conversations:m,hiddenConversations:h,ides:p,actionLogs:g,sendDaemonCommand:f,setActionLogs:y,setCliViewModeOverrides:b,isStandalone:k,userName:v,requestedActiveTabKey:C,onRequestedActiveTabConsumed:x,requestedMachineId:S,onRequestedMachineConsumed:w,requestedMobileSection:O,onRequestedMobileSectionConsumed:L,onOpenHistory:a,onOpenRemote:i,onStopCli:c,wsStatus:r,isConnected:o,initialDataLoaded:j,onShowAllHiddenConversations:ue,onHideConversation:ne,onShowHiddenConversation:_e,onOpenMeshGraph:ge,onOpenNewSession:xe,liveSessionInboxState:Ee}):t?n.jsx(dI,{containerRef:R,isSplitMode:F,numGroups:N,groupSizes:I,groupedConvs:B,clearedTabs:T,ides:p,actionLogs:g,sendDaemonCommand:f,setActionLogs:y,isStandalone:k,hasRegisteredMachines:X.length>0,initialDataLoaded:j,userName:v,focusedGroup:H,focusGroup:q,moveTabToGroup:J,splitTabRelative:K,closeGroup:M,handleResizeStart:D,groupActiveTabIds:P,setGroupActiveTab:$,groupTabOrders:W,setGroupTabOrder:U,toggleHiddenTab:ae,onOpenNewSession:xe,allowTabShortcuts:!1,liveSessionInboxState:Ee}):n.jsx(TI,{visibleConversations:be,clearedTabs:T,ides:p,actionLogs:g,sendDaemonCommand:f,setActionLogs:y,isStandalone:k,hasRegisteredMachines:X.length>0,initialDataLoaded:j,userName:v,toggleHiddenTab:ae,actionShortcuts:gt,registerActionHandlers:Oe=>{oe.current=Oe},onActiveTabChange:ce,requestedActiveTabKey:V,onRequestedActiveTabConsumed:we,onRequestScrollToBottom:de,scrollToBottomRequest:je,onOpenNewSession:xe,liveSessionInboxState:Ee,layoutProfile:G}),ye&&n.jsx(VI,{machines:X,ides:p,initialMachineId:(Re==null?void 0:Re.machineId)||null,initialWorkspaceId:(Re==null?void 0:Re.workspaceId)||null,initialLaunchMode:(Re==null?void 0:Re.mode)||null,initialMeshWorkspacePath:(Re==null?void 0:Re.meshWorkspacePath)||null,onClose:$e,onBrowseDirectory:z,onSaveWorkspace:ie,onLaunchIde:Ne,onLaunchProvider:Be,onListMeshes:Le,onLaunchMeshCoordinator:Je,onListSavedSessions:Se},Re?`${Re.machineId}:${Re.workspaceId||""}:${Re.mode||""}:${Re.meshWorkspacePath||""}`:"default"),st&&n.jsx(Pd,{activeConv:st,sendDaemonCommand:f,onClose:()=>lt(null)}),Ze,et&&n.jsx(Qb,{daemonId:et.daemonId,workspace:et.workspace,onClose:()=>Ve(null)}),se&&n.jsxs(Rr,{chrome:!1,onClose:Et,closeOnEsc:!1,ariaLabel:E("dashboard.guide.title"),overlayClassName:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50 backdrop-blur-[2px]",surfaceClassName:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",children:[n.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-bold text-text-primary",children:E("dashboard.guide.title")}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:E("dashboard.guide.subtitle")})]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Et,"aria-label":E("dashboard.guide.close"),children:n.jsx(Bt,{size:14})})]}),n.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:E("dashboard.guide.tabs.overview")},{id:"quickstart",label:E("dashboard.guide.tabs.quickstart")},{id:"shortcuts",label:E("dashboard.guide.tabs.shortcuts")}].map(Oe=>n.jsx("button",{type:"button",className:`btn btn-sm ${Me===Oe.id?"btn-primary":"btn-secondary"}`,onClick:()=>He(Oe.id),children:Oe.label},Oe.id))}),Me==="overview"&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E("dashboard.guide.overview.whatLivesWhere.title")}),n.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.whatLivesWhere.tabsLabel")})," ",E("dashboard.guide.overview.whatLivesWhere.tabsText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.whatLivesWhere.hiddenLabel")})," ",E("dashboard.guide.overview.whatLivesWhere.hiddenText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.whatLivesWhere.inboxLabel")})," ",E("dashboard.guide.overview.whatLivesWhere.inboxText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.whatLivesWhere.cliToggleLabel")})," ",E("dashboard.guide.overview.whatLivesWhere.cliToggleText")]})]})]}),n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.title")}),n.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.reviewLabel")})," ",E("dashboard.guide.overview.usefulFlows.reviewText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.clutterLabel")})," ",E("dashboard.guide.overview.usefulFlows.clutterText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.splitLabel")})," ",E("dashboard.guide.overview.usefulFlows.splitText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.detachedLabel")})," ",E("dashboard.guide.overview.usefulFlows.detachedText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.dockingLabel")})," ",E("dashboard.guide.overview.usefulFlows.dockingText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.perTabLabel")})," ",E("dashboard.guide.overview.usefulFlows.perTabText")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:E("dashboard.guide.overview.usefulFlows.approvalLabel")})," ",E("dashboard.guide.overview.usefulFlows.approvalText",{keys:Bn})]})]})]})]}),Me==="quickstart"&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E("dashboard.guide.quickstart.desktop.title")}),n.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," ",E("dashboard.guide.quickstart.desktop.step1")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," ",E("dashboard.guide.quickstart.desktop.step2")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," ",E("dashboard.guide.quickstart.desktop.step3")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," ",E("dashboard.guide.quickstart.desktop.step4")]})]})]}),n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E("dashboard.guide.quickstart.mobile.title")}),n.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," ",E("dashboard.guide.quickstart.mobile.step1")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," ",E("dashboard.guide.quickstart.mobile.step2")]}),n.jsxs("div",{children:[n.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," ",E("dashboard.guide.quickstart.mobile.step3")]})]})]})]}),Me==="shortcuts"&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[n.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:E("dashboard.guide.shortcuts.sections.all")},{id:"workspace",label:E("dashboard.guide.shortcuts.sections.workspace")},{id:"panes",label:E("dashboard.guide.shortcuts.sections.panes")},{id:"approvals",label:E("dashboard.guide.shortcuts.sections.approvals")}].map(Oe=>n.jsx("button",{type:"button",className:`btn btn-sm ${De===Oe.id?"btn-primary":"btn-secondary"}`,onClick:()=>tt(Oe.id),children:Oe.label},Oe.id))}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Vt,children:E("dashboard.guide.shortcuts.disableAll")}),n.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:pn,children:E("dashboard.guide.shortcuts.resetToDefaults")})]})]}),n.jsx("div",{className:"space-y-2",children:hn.map(Oe=>n.jsx("div",{className:`rounded-xl border px-4 py-3 ${Mt===Oe.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E(`dashboard.shortcutDefs.${Oe.id}.label`,Oe.label)}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:E(`dashboard.shortcutDefs.${Oe.id}.description`,Oe.description)}),n.jsxs("div",{className:"text-2xs text-text-muted mt-2",children:[E("dashboard.guide.shortcuts.default")," ",n.jsx("span",{className:"font-mono",children:Oe.defaultShortcut})]})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[n.jsx("span",{className:"text-2xs font-mono px-2 py-1 rounded bg-surface-secondary border border-border-subtle min-w-[72px] text-center",children:Mt===Oe.id?Rt.length>0?`${Rt.join(" ")} ...`:E("dashboard.guide.shortcuts.listening"):gt[Oe.id]||E("dashboard.guide.shortcuts.off")}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{mn(Oe.id),nn([])},children:Mt===Oe.id?E("dashboard.guide.shortcuts.setListening"):E("dashboard.guide.shortcuts.set")}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const rt={...gt};rt[Oe.id]="",Jt(rt)},children:E("dashboard.guide.shortcuts.disable")})]})]})},Oe.id))}),n.jsx("div",{className:"text-2xs text-text-muted mt-4",children:E("dashboard.guide.shortcuts.footer",{keys:Tt})})]})]})]})}const gM=[{icon:fi,key:"welcome",visual:Kp},{icon:Jn,key:"realtimeChat",visual:pw},{icon:sd,key:"watchAndSteer",visual:qp},{icon:nc,key:"orchestrate",visual:nc}],bM={icon:fi,key:"getStartedCloud",code:"curl -fsSL https://adhf.dev/install | sh"},xM={icon:fi,key:"allSetStandalone",visual:gi};function yM({onClose:e,standalone:t=!1}){const[s,r]=l.useState(0),{t:o}=ve("common"),a=[...gM,t?xM:bM],i=a[s],c=s===a.length-1;return l.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]),n.jsx(es,{children:n.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:"var(--z-modal)",background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",padding:"calc(16px + env(safe-area-inset-top, 0px)) 16px calc(16px + env(safe-area-inset-bottom, 0px))",animation:"fadeIn 0.3s ease-out"},onClick:d=>{d.stopPropagation()},children:[n.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",maxHeight:"calc(100dvh - env(safe-area-inset-top, 0px) - env(safe-area-inset-bottom, 0px) - 32px)",overflowY:"auto",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[n.jsx("button",{onClick:e,"aria-label":o("app.onboardingTour.closeAria"),className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",style:{minWidth:44,minHeight:44,margin:-6,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:n.jsx(Bt,{size:20})}),n.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:a.map((d,u)=>n.jsx("div",{style:{width:u===s?24:8,height:8,borderRadius:4,background:u===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},u))}),n.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:(()=>{const d=i.visual||i.icon;return n.jsx(d,{size:44})})()}),n.jsxs("div",{style:{textAlign:"center"},children:[n.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[n.jsx(i.icon,{size:18})," ",o(`app.onboardingTour.${i.key}.title`)]}),n.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:o(`app.onboardingTour.${i.key}.desc`)}),i.code&&n.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[n.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),i.code]}),c&&n.jsxs("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:[o("app.onboardingTour.learnMore")," →"]})]}),n.jsx("div",{className:"flex justify-end items-center mt-6",children:n.jsx("button",{onClick:()=>c?e():r(d=>d+1),className:"btn btn-primary",children:c?`${o("app.onboardingTour.getStarted")} →`:`${o("app.onboardingTour.next")} →`})})]}),n.jsx("style",{children:`
|
|
72
|
-
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
73
|
-
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
74
|
-
`})]})})}function vM({hasExtensions:e,ideName:t,activeChatTab:s,extensionTabs:r,onSelectTab:o}){return e?n.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[n.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-2xs font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${s==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o("native"),children:t}),r.map(a=>{const i=s===a.tabKey,c=a.status==="waiting_approval",d=er(a);return n.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-2xs font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${i?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o(a.tabKey),children:[n.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),a.title,c&&n.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-3xs font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},a.tabKey)})]}):null}function wM({ideData:e,allIdes:t,connectionStates:s,ideName:r,preferredTabKey:o}){const[a,i]=l.useState(()=>o||"native"),c=l.useMemo(()=>Vg(t),[t]),d=l.useMemo(()=>e?Dd(e,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}):[],[e,c,s]),u=l.useMemo(()=>d.find(y=>y.streamSource==="native"),[d]),m=l.useMemo(()=>d.filter(y=>y.streamSource==="agent-stream"),[d]),h=l.useMemo(()=>e?On(d,e.id):null,[d,e]);l.useEffect(()=>{o&&i(o)},[o]),l.useEffect(()=>{if(o||!h)return;const y=h.streamSource==="native"?"native":h.tabKey;!y||a===y||a==="native"&&i(y)},[a,h,o]),l.useEffect(()=>{var y;a!=="native"&&(m.some(b=>b.tabKey===a)||i(((y=m[0])==null?void 0:y.tabKey)||"native"))},[a,m]),l.useEffect(()=>{a==="native"&&(u||m[0]&&i(m[0].tabKey))},[a,u,m]);const p=l.useMemo(()=>a==="native"&&u?u:m.find(y=>y.tabKey===a)||h||u||m[0],[a,u,h,m]),g=l.useMemo(()=>m.map(y=>({tabKey:y.tabKey,title:jg(y)||r,status:y.status})),[m,r]),f=l.useCallback(y=>{if(y)return d.find(b=>co(b,{sessionId:y,routeId:y,tabKey:y,providerSessionId:y}))},[d]);return{activeChatTab:a,setActiveChatTab:i,activeConv:p,conversations:d,extensionTabs:g,hasExtensions:g.length>0,resolveConversationByTarget:f}}function SM({activeConv:e,ideEntry:t,ides:s,connectionStates:r,actionLogs:o,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:d,onOpenHistory:u,onConversationChange:m,onClose:h,onRetryConnection:p}){const{t:g}=ve("common"),[f,y]=l.useState("split"),[b,k]=l.useState(()=>Ss(e)?"native":e.tabKey),j=l.useRef(null),v=l.useMemo(()=>t||s.find(D=>D.id===e.routeId),[e.routeId,t,s]),C=l.useMemo(()=>Kt((v==null?void 0:v.type)||""),[v==null?void 0:v.type]),{conversations:x,extensionTabs:S,hasExtensions:w}=wM({ideData:v,allIdes:s,connectionStates:r,ideName:C||"IDE",preferredTabKey:Ss(e)?void 0:e.tabKey}),_=l.useMemo(()=>v?On(x,v.id):null,[v,x]);l.useEffect(()=>{const D=j.current,P={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(j.current=P,!(D&&D.routeId===P.routeId&&D.tabKey===P.tabKey&&D.streamSource===P.streamSource)){if(Ss(e)){k("native");return}k(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(b==="native"){if(x.some(D=>D.streamSource==="native"))return;(_==null?void 0:_.streamSource)==="agent-stream"&&k(_.tabKey);return}if(!x.some(D=>D.tabKey===b)){if((_==null?void 0:_.streamSource)==="agent-stream"){k(_.tabKey);return}k("native")}},[x,b,_]);const A=l.useMemo(()=>b==="native"?x.find(D=>D.streamSource==="native")||e:x.find(D=>D.tabKey===b)||e,[e,x,b]),O=cb(A),L=l.useMemo(()=>O.status||O.modalMessage||O.modalButtons?{...A,...O.status?{status:O.status}:{},...O.modalMessage!==void 0?{modalMessage:O.modalMessage}:{},...O.modalButtons!==void 0?{modalButtons:O.modalButtons}:{}}:A,[A,O]),R=Cs(L),F=Ii({sendDaemonCommand:a,activeConv:L,setActionLogs:i,isStandalone:c}),{connScreenshot:N,screenshotUsage:I,handleRemoteAction:B}=Hb({doId:R,targetSessionId:Yf(L),connState:L.connectionState||"new",viewMode:f}),T=l.useMemo(()=>o.filter(D=>D.routeId===L.tabKey),[o,L.tabKey]),H=L.tabKey,q=l.useCallback(D=>{i(P=>[...P,{routeId:H,text:D,timestamp:Date.now()}])},[H,i]),J=v==null?void 0:v.machineId,K=l.useMemo(()=>{if(!(!p||!J))return()=>p(J)},[p,J]);l.useEffect(()=>{m==null||m(L)},[L,m]),l.useEffect(()=>{const D=P=>{P.key==="Escape"&&h()};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[h]);const M=l.useCallback(D=>{D.stopPropagation()},[]);return n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center p-0 md:p-3 bg-black/60 backdrop-blur-md",onClick:h,children:n.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:M,children:[n.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[n.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:n.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-lg md:text-xl tracking-tight text-text-primary",children:[n.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:n.jsx(Xn,{size:16})}),n.jsx("span",{className:"truncate",children:vd(A)||g("dashboard.remoteDialog.remoteFallback")})]})}),n.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:g("common.close")})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[n.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(D=>{const P=f===D;return n.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${P?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>y(D),title:g(D==="split"?"dashboard.remoteDialog.splitView":"dashboard.remoteDialog.remoteOnly"),children:D==="split"?n.jsx(tw,{size:15}):n.jsx(Xn,{size:15})},D)})}),n.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),n.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>u(A),title:g("dashboard.remoteDialog.history"),children:[n.jsx(Dp,{size:14,className:"md:mr-1.5"}),n.jsx("span",{className:"hidden md:inline",children:g("dashboard.remoteDialog.history")})]}),n.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:g("common.close")})]})]}),n.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[f!=="remote"&&n.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[n.jsx(vM,{hasExtensions:w,ideName:C||"IDE",activeChatTab:b,extensionTabs:S,onSelectTab:k}),n.jsx(bf,{activeConv:L,onModalButton:F.handleModalButton}),n.jsx(vg,{activeConv:L,ideEntry:v,showMetaChips:!1,handleSendChat:F.handleSendChat,handleSendNowQueued:F.handleSendNowQueued,handleCancelQueued:F.handleCancelQueued,isSendingChat:F.isSendingChat,sendFeedbackMessage:F.sendFeedbackMessage,pendingLocalMessage:F.pendingLocalMessage,pendingLocalMessages:F.pendingLocalMessages,retireEchoedPendingMessages:F.retireEchoedPendingMessages,handleFocusAgent:F.handleFocusAgent,isFocusingAgent:F.isFocusingAgent,actionLogs:T,userName:d})]}),n.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-1 md:order-2":""}`,children:n.jsx(rf,{addLog:q,connState:L.connectionState||"new",connScreenshot:N,screenshotUsage:I,transportType:L.transport,onAction:B,onRetry:K})})]})]})})})}function kM({activeConv:e,canSaveAndStop:t=!1,onCancel:s,onStopNow:r,onSaveAndStop:o}){const{t:a}=ve(),i=w_(e);return n.jsx(es,{children:n.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[n.jsx("div",{onClick:s,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),n.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[n.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[n.jsx("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:a("cliStop.title",{agent:i})}),n.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a(t?"cliStop.gracefulDescription":"cliStop.forceOnlyDescription")})]}),n.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&n.jsx("button",{onClick:o,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("cliStop.stop")}),n.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:a("cliStop.forceStop")}),n.jsx("button",{onClick:s,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})})}function jM({historyModal:e,remoteDialog:t,cliStopDialog:s,connectionBanner:r,toastOverlay:o,onboarding:a,interactivePrompt:i,suppressInteractivePrompt:c=!1}){var d;return n.jsxs(n.Fragment,{children:[!r.suppress&&n.jsx(W_,{wsStatus:r.wsStatus,showReconnected:r.showReconnected,loginUrl:r.loginUrl,onReconnect:r.onReconnect}),e.open&&e.targetConv&&n.jsx(Z1,{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(SM,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose,onRetryConnection:t.onRetryConnection}),s.open&&s.targetConv&&(St(s.targetConv)||vt(s.targetConv))&&n.jsx(kM,{activeConv:s.targetConv,canSaveAndStop:St(s.targetConv)&&!vt(s.targetConv)&&!!((d=s.targetConv.resume)!=null&&d.supported),onCancel:s.onCancel,onStopNow:s.onStopNow,onSaveAndStop:s.onSaveAndStop}),n.jsx(zg,{toasts:o.toasts,onDismiss:o.onDismiss,onClickToast:o.onClick}),!c&&n.jsx(md,{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(yM,{onClose:a.onClose,standalone:a.standalone})]})}function NM({daemons:e,targetVersion:t,required:s=!1,upgradingDaemons:r,onUpgrade:o,onDismiss:a}){const{t:i}=ve("common");return e.length===0?null:n.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:s?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:s?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[n.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:s?"var(--status-danger)":"var(--status-warning)"},children:n.jsx(Or,{size:14})}),n.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[n.jsxs("span",{children:[i(s?"machine.daemonUpdate.requiredTitle":"dashboard.versionBanner.updateAvailable"),t?n.jsxs(n.Fragment,{children:[": ",n.jsxs("strong",{children:["v",t]})]}):null]}),e.map(c=>{const d=Tn(c,{fallbackId:c.id}),u=r[c.id],m=c.version||c.daemonVersion||i("dashboard.versionBanner.unknownVersion"),h=c.versionUpdateRequired===!0,p=xb(c,{targetVersion:t,required:h},i);return n.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:h?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${h?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[n.jsx("span",{className:"font-medium text-text-primary",children:d}),n.jsxs("span",{className:"text-3xs text-text-muted",children:["v",m]}),h&&n.jsx("span",{className:"text-3xs",style:{color:"var(--status-danger)"},children:i("dashboard.versionBanner.required")}),u==="upgrading"?n.jsx("span",{className:"text-3xs animate-pulse",style:{color:h?"var(--status-danger)":"var(--status-warning)"},children:i("dashboard.versionBanner.upgrading")}):u==="done"?n.jsxs("span",{className:"text-3xs text-green-400",children:["✓ ",i("dashboard.versionBanner.restarting")]}):u==="error"?n.jsx("button",{className:"text-3xs text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>o(c.id),children:i("dashboard.versionBanner.retry")}):n.jsx("button",{className:"text-3xs font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:h?"var(--status-danger)":"var(--status-warning)",background:h?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${h?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(c.id),children:p})]},c.id)})]}),!s&&n.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:a,title:i("toast.dismiss"),children:n.jsx(Bt,{size:16})})]})}function CM(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function _M(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 AM(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>_M(t)).map(t=>t.id)}}function TM({suppressConnectionBanner:e=!1}={}){var qo,zo,Ur,Go,Vo;const{sendCommand:t}=_t(),s=Hr(),r=lb(),o=ui(),a=rr(),[i,c]=cp(),d=i.get("activeTab"),u=((qo=o.state)==null?void 0:qo.openRemoteForTabKey)||null,m=((zo=o.state)==null?void 0:zo.openMachineId)||null,h=((Ur=o.state)==null?void 0:Ur.openNewSession)||null,p=((Go=o.state)==null?void 0:Go.mobileSection)||null,g=yd(),f=g.ides||[],y=g.initialLoaded??!0,{updateRouteChats:b,setToasts:k}=g,{hydrateInteractivePrompt:j}=Ar(),[v,C]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),x=g.toasts||[],S=g.wsStatus||"connected",w=g.isConnected??!0,_=g.connectionStates||{},A=g.showReconnected||!1,{layoutProfile:O,groupAssignments:L,updateGroupAssignments:R,focusedGroup:F,updateFocusedGroup:N,focusGroup:I,groupActiveTabIds:B,updateGroupActiveTabIds:T,setGroupActiveTab:H,groupTabOrders:q,updateGroupTabOrders:J,setGroupTabOrder:K,groupSizes:M,updateGroupSizes:D,isMobile:P,hasHydratedStoredLayout:$,hydrateStoredLayout:W,focusConversationTab:U}=zT(),[ae,be]=l.useState(()=>Hd());l.useEffect(()=>oT(be),[]);const V=l.useMemo(()=>CM({isMobile:P,mobileViewMode:ae}),[P,ae]),[we,ce]=l.useState([]),[de,ne]=l.useState({}),[ee,ue]=l.useState({});Lo("Dashboard",{ideCount:f.length,toastCount:x.length,focusedGroup:F,groupCount:Object.keys(L).length,actionLogCount:we.length});const je=l.useMemo(()=>f.filter(ht=>ht.type==="adhdev-daemon").sort(Ua),[f]),G=!!je[0];l.useEffect(()=>{const{metadataDaemonIds:ht,runtimeDaemonIds:Yt}=AM(je);for(const us of ht)s(us,{minFreshMs:3e4}).catch(()=>{});for(const us of Yt)r(us,{minFreshMs:3e4}).catch(()=>{})},[s,r,je]);const z=l.useMemo(()=>xT(f,de),[f,de]),{conversations:ie,visibleConversations:Ne,visibleTabKeys:Be,resolveConversationBySessionId:Le,resolveConversationByTarget:Je}=MT({ides:z,connectionStates:_,clearedTabs:ee}),Se=l.useMemo(()=>new Map(ie.map(ht=>[ht.tabKey,ht])),[ie]);wC(Ne,V);const he=l.useMemo(()=>ff(f),[f]),pe=Ib(he,t,l.useCallback(ht=>yr(k,ht),[k])),{notifications:Ee,unreadCount:Y}=c2({conversations:ie,liveSessionInboxState:he}),{handleMarkDashboardNotificationRead:me,handleMarkDashboardNotificationUnread:fe,handleDeleteDashboardNotification:E}=d2({notifications:Ee,sendDaemonCommand:t}),{containerRef:oe,normalizedGroupAssignments:Ie,numGroups:Z,isSplitMode:se,groupedConvs:ye,moveTabToGroup:Fe,closeGroup:Me,handleResizeStart:De,splitTabRelative:Te}=ZT({groupAssignments:L,updateGroupAssignments:R,updateFocusedGroup:N,updateGroupActiveTabIds:T,updateGroupTabOrders:J,groupSizes:M,updateGroupSizes:D,isMobile:P,visibleConversations:Ne,visibleTabKeys:Be}),{activeConv:He,openDesktopConversation:tt,requestScrollToBottom:Ct,scrollToBottomRequest:Q,setDesktopActiveTab:re}=j2({isMobile:P,conversations:ie,visibleConversations:Ne,groupActiveTabIds:B,focusedGroup:F,groupedConvs:ye,setSearchParams:c});_2({activeConv:He,isMobile:P,liveSessionInboxState:he,sendDaemonCommand:t});const{requestedDesktopTabKey:le,requestedMobileTabKey:xe,consumeRequestedActiveTab:Ce}=RT({isMobile:P,urlActiveTab:d,resolveConversationBySessionId:Le,setSearchParams:c}),{remoteDialogConv:Re,remoteDialogIdeEntry:Ue,remoteDialogActiveConv:$e,setRemoteDialogActiveConv:ke,openRemoteDialog:Ze,closeRemoteDialog:et,cliStopDialogOpen:Ve,cliStopTargetConv:st,requestCliStop:lt,cancelCliStop:Qe,confirmCliStop:ge}=I2({isMobile:P,location:o,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:le,conversations:ie,ides:f,resolveConversationByTarget:Je,activeConv:He,sendDaemonCommand:t}),{historyModalOpen:_e,openHistoryModal:Pe,closeHistoryModal:nt,historyTargetConv:ze,isSavedSessionHistoryTarget:ut,isHistoryCreatingChat:Ge,isHistoryRefreshingHistory:gt,handleHistorySwitchSession:Mt,handleHistoryNewChat:Rt,handleHistoryRefresh:mn,savedHistorySessions:nn,savedHistoryFilters:Jt,setSavedHistoryFilters:Et,missingWorkspaceResumePath:hn,isSavedHistoryLoading:Bn,resumingSavedHistorySessionId:Tt,handleRefreshSavedHistory:Vt,handleResumeSavedHistorySession:pn}=A2({activeConv:He,remoteDialogConv:Re,remoteDialogActiveConv:$e,ides:f,sendDaemonCommand:t,updateRouteChats:b,setToasts:k,setClearedTabs:ue,setSearchParams:c}),Oe=l.useMemo(()=>Ne,[Ne]),rt=P&&ae==="chat",pt=l.useMemo(()=>ie.filter(ht=>IS(Ns(ht,he))),[ie,he]),bt=l.useCallback(ht=>{const Yt=new URLSearchParams(i);Yt.set("activeTab",ht),c(Yt,{replace:!0})},[i,c]),{trackPendingLaunch:yt}=x2({ides:f,conversations:ie,onOpenSession:bt}),{handleBrowseMachineDirectory:kt,handleSaveMachineWorkspace:fn,handleLaunchMachineIde:Ye,handleLaunchMachineProvider:mt,handleListMachineMeshes:Zt,handleLaunchMeshCoordinator:Sn,handleListMachineSavedSessions:sn,setActiveCliViewMode:rn}=w2({sendDaemonCommand:t,trackPendingLaunch:yt,onOpenSession:bt,activeConv:He,ides:f,setCliViewModeOverrides:ne});vT({visibleConversations:Ne,clearedTabs:ee,setClearedTabs:ue,setActionLogs:ce,isConversationMuted:pe.isMuted}),PT({ides:f,sendDaemonCommand:t,setToasts:k,resolveConversationByTarget:Je,hydrateInteractivePrompt:j});const In=ki((He==null?void 0:He.sessionId)??(He==null?void 0:He.routeId)??null),{isRefreshingHistory:jt,handleRefreshHistory:en}=bb({sendDaemonCommand:t,activeConv:He,chats:(Vo=f.find(ht=>ht.id===(He==null?void 0:He.routeId)))==null?void 0:Vo.chats,updateRouteChats:b,setToasts:k,setClearedTabs:ue});VT({urlActiveTab:P&&!rt?d:null,conversations:ie,resolveConversationBySessionId:Le,normalizedGroupAssignments:Ie,hasHydratedStoredLayout:P&&!rt?$:!0,hydrateStoredLayout:P&&!rt?W:()=>{},focusConversationTab:U,setSearchParams:c,historyModalOpen:_e,activeConv:He,isRefreshingHistory:jt,ides:f,handleRefreshHistory:en});const gn=l.useMemo(()=>!He||!St(He)||vt(He)?null:$r(He),[He]),{versionMismatchDaemons:Wt,hasRequiredVersionDaemons:Ms,targetVersion:kn,versionBannerDismissed:Bo,setVersionBannerDismissed:Wo,upgradingDaemons:qi,handleBannerUpgrade:zi}=n2({ides:f,sendDaemonCommand:t}),Uo=l.useCallback(ht=>{pe.setHidden(ht,!1),tt(ht)},[tt,pe]),Ko=l.useCallback(()=>{for(const ht of pt)pe.setHidden(ht,!1)},[pt,pe]),Wr=l.useCallback(ht=>{pe.setHidden(ht,!0)},[pe]),Gi=l.useCallback(ht=>{pe.toggleHidden(ht)},[pe]);return n.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!Bo||Ms)&&n.jsx(NM,{daemons:Wt,targetVersion:kn,required:Ms,upgradingDaemons:qi,onUpgrade:zi,onDismiss:()=>Wo(!0)}),n.jsx(fM,{showMobileChatMode:rt,isMobile:P,activeConv:He,wsStatus:S,isConnected:w,onOpenHistory:ht=>{ht&&ke(ht),Pe()},onOpenRemote:Ze,onStopCli:lt,activeCliViewMode:gn,onSetActiveCliViewMode:rn,mobileChatConversations:Oe,ides:f,actionLogs:we,sendDaemonCommand:t,setActionLogs:ce,setCliViewModeOverrides:ne,isStandalone:G,initialDataLoaded:y,userName:g.userName,requestedMobileTabKey:xe,onRequestedMobileTabConsumed:Ce,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(o.pathname+o.search,{replace:!0,state:null})},requestedNewSessionLaunch:h,onRequestedNewSessionLaunchConsumed:()=>{a(o.pathname+o.search,{replace:!0,state:null})},requestedMobileSection:p,onRequestedMobileSectionConsumed:()=>{a(o.pathname+o.search,{replace:!0,state:null})},containerRef:oe,isSplitMode:se,numGroups:Z,groupSizes:M,groupedConvs:ye,clearedTabs:ee,focusedGroup:F,focusGroup:I,moveTabToGroup:Fe,splitTabRelative:Te,closeGroup:Me,handleResizeStart:De,groupActiveTabIds:B,setGroupActiveTab:H,groupTabOrders:q,setGroupTabOrder:K,toggleHiddenTab:ht=>{const Yt=Se.get(ht);Yt&&Gi(Yt)},visibleConversations:Ne,hiddenConversations:pt,requestedDesktopTabKey:le,onRequestedDesktopTabConsumed:Ce,onDesktopActiveTabChange:re,onRequestScrollToBottom:Ct,onHideConversation:Wr,onShowHiddenConversation:Uo,onShowAllHiddenConversations:Ko,scrollToBottomRequest:Q,machineEntries:je,layoutProfile:O,onBrowseMachineDirectory:kt,onSaveMachineWorkspace:fn,onLaunchMachineIde:Ye,onLaunchMachineProvider:mt,onListMachineMeshes:Zt,onLaunchMeshCoordinator:Sn,onListMachineSavedSessions:sn,notifications:Ee,notificationUnreadCount:Y,liveSessionInboxState:he,onMarkNotificationRead:me,onMarkNotificationUnread:fe,onDeleteNotification:E}),n.jsx("style",{children:`
|
|
75
|
-
body { overflow: hidden; overscroll-behavior: none; }
|
|
76
|
-
`}),n.jsx(jM,{historyModal:{open:_e,targetConv:ze,ides:f,isCreatingChat:Ge,isRefreshingHistory:ut?!1:gt,savedSessions:nn,savedHistoryFilters:Jt,missingWorkspaceResumePath:hn||null,onSavedHistoryFiltersChange:Et,isSavedSessionsLoading:Bn,isResumingSavedSessionId:Tt,onClose:nt,onNewChat:Rt,onSwitchSession:Mt,onRefreshHistory:ut?Vt:mn,onResumeSavedSession:pn},remoteDialog:{conversation:Re,ideEntry:Ue,ides:f,connectionStates:_,actionLogs:we,sendDaemonCommand:t,setActionLogs:ce,isStandalone:G,userName:g.userName,onOpenHistory:ht=>{ht&&ke(ht),Pe()},onConversationChange:ke,onClose:et,onRetryConnection:g.retryConnection},cliStopDialog:{open:Ve,targetConv:st,onCancel:Qe,onStopNow:async()=>{await ge("hard")},onSaveAndStop:async()=>{await ge("save")}},connectionBanner:{wsStatus:S,showReconnected:A,loginUrl:g.connectionLoginUrl,onReconnect:g.retryServerConnection,suppress:e},toastOverlay:{toasts:x,onDismiss:ht=>k(Yt=>Yt.filter(us=>us.id!==ht)),onClick:ht=>{if(ht.targetKey){const Yt=Je(ht.targetKey);Yt&&(U(Yt.tabKey,Ie),Uo(Yt),Ct(Yt.tabKey,"toast-open"))}}},onboarding:{open:v,standalone:G,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}C(!1)}},interactivePrompt:In,suppressInteractivePrompt:rt})]})}function IM({machineId:e,registeredMachineId:t,sendDaemonCommand:s,onNicknameSynced:r,logsEndRef:o}){const{t:a}=ve("common"),{launchCli:i}=bi(),{confirm:c,confirmDialog:d}=Fr(),[u,m]=l.useState([]),[h,p]=l.useState(null),[g,f]=l.useState(null),[y,b]=l.useState(!1),[k,j]=l.useState(null),[v,C]=l.useState(!1),[x,S]=l.useState(""),w=l.useRef(null),_=l.useCallback(P=>{w.current=P},[]),A=l.useCallback((P,$,W=!1,U)=>{const ae=bd(U),be=ae&&ae!==$?`${$} — ${ae}`:$;m(V=>[...V.slice(-100),{timestamp:Date.now(),level:P,message:be}]),setTimeout(()=>{var V;return(V=o.current)==null?void 0:V.scrollIntoView({behavior:"smooth"})},100),W&&(P==="error"||P==="warn"?ct.showErrorToast($,U):ct.showToast($,"success"))},[o]),O=l.useCallback(P=>{const $=P instanceof Error?P.message:String(P||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),L=l.useCallback(async(P,$)=>{var W;if(!e||h)return!1;p(P),A("info",a("machine.actions.launching",{name:Kt(P)}));try{const U={ideType:P,enableCdp:!0};(W=$==null?void 0:$.workspace)!=null&&W.trim()?U.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(U.useDefaultWorkspace=!0);const ae=await s(e,"launch_ide",U);return ae!=null&&ae.success?A("info",a("machine.actions.launched",{name:Kt(P)}),!0):A("error",a("machine.actions.launchFailed",{name:Kt(P)}),!0,ae==null?void 0:ae.error),!!(ae!=null&&ae.success)}catch(U){return A("error",a("machine.actions.launchFailed",{name:Kt(P)}),!0,U),!1}finally{p(null)}},[e,h,A,s,a]),R=l.useCallback(async P=>{if(!e)return{success:!1};const{cliType:$,dir:W,workspaceId:U,useDefaultWorkspace:ae,useHome:be,argsStr:V,model:we,resumeSessionId:ce}=P;if(!$)return A("warn",a("machine.actions.selectProviderFirst"),!0),{success:!1};const de=V?V.split(/\s+/).filter(Boolean):void 0,ne=(W==null?void 0:W.trim())||(U?"(saved id)":ae?"(default workspace)":be?"(home)":"");A("info",a("machine.actions.launching",{name:$}),!1,[ne,we].filter(Boolean).join(" · ")||void 0),f($);try{const ee={cliType:$,cliArgs:de,initialModel:we||void 0};W!=null&&W.trim()?ee.dir=W.trim():U?ee.workspaceId=U:ae?ee.useDefaultWorkspace=!0:be&&(ee.useHome=!0),ce&&(ee.resumeSessionId=ce);const ue=await i(e,ee),je=(ue==null?void 0:ue.result)||ue;return ue!=null&&ue.success?(A("info",a("machine.actions.launched",{name:$}),!0),(je==null?void 0:je.launchSource)==="home"?A("info",a("machine.actions.runningInHome")):(je==null?void 0:je.launchSource)==="defaultWorkspace"&&A("info",a("machine.actions.usingDefaultWorkspace")),{success:!0,sessionId:je==null?void 0:je.sessionId}):(A("error",a("machine.actions.launchFailed",{name:$}),!0,(ue==null?void 0:ue.error)||(je==null?void 0:je.error)),(ue==null?void 0:ue.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&j({cliType:$,argsStr:V,model:we}),{success:!1,sessionId:je==null?void 0:je.sessionId})}catch(ee){return O(ee)?(A("warn",a("machine.actions.launchPending",{name:$}),!0),{success:!1,pending:!0}):(A("error",a("machine.actions.launchFailed",{name:$}),!0,ee),{success:!1})}finally{f(null)}},[e,A,O,s,a]),F=l.useCallback(async(P,$,W,U)=>e?P?$.trim()?R({cliType:P,dir:$,argsStr:W,model:U}):(j({cliType:P,argsStr:W,model:U}),{success:!1}):(A("warn",a("machine.actions.selectProvider"),!0),{success:!1}):{success:!1},[e,A,R,a]),N=l.useCallback(async(P,$,W)=>{if(e&&await c({title:a("cliStop.title",{agent:P}),description:a("machine.actions.stopCliConfirmDescription"),confirmLabel:a("cliStop.stop"),tone:"danger"}))try{const U=await s(e,"stop_cli",{cliType:P,dir:$,targetSessionId:W});U!=null&&U.success?A("info",a("machine.actions.stopped",{name:P}),!0):A("error",a("machine.actions.stopFailed"),!0,U==null?void 0:U.error)}catch(U){A("error",a("machine.actions.stopFailed"),!0,U)}},[e,A,c,s,a]),I=l.useCallback(async P=>{try{await s(P.daemonId,"restart_ide",{ideType:P.type}),A("info",a("machine.actions.restartInitiated",{name:Kt(P.type)}),!0)}catch($){A("error",a("machine.actions.restartFailed"),!0,$)}},[A,s,a]),B=l.useCallback(async P=>{if(await c({title:a("cliStop.title",{agent:Kt(P.type)}),description:a("machine.actions.stopIdeConfirmDescription"),confirmLabel:a("cliStop.stop"),tone:"danger"}))try{const $=await s(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});$!=null&&$.success?A("info",a("machine.actions.stopped",{name:Kt(P.type)}),!0):A("error",a("machine.actions.stopFailed"),!0,$==null?void 0:$.error)}catch($){A("error",a("machine.actions.stopFailed"),!0,$)}},[A,c,s,a]),T=l.useCallback(async()=>{if(e)try{const P=await s(e,"detect_ides",{});A("info",a("machine.actions.idesFound",{count:((P==null?void 0:P.result)||[]).length}),!0)}catch(P){A("error",a("machine.actions.detectFailed"),!0,P)}},[e,A,s,a]),H=l.useCallback(async P=>{if(!e||!P.trim())return!1;b(!0);try{const $=await s(e,"workspace_add",{path:P.trim()});return $!=null&&$.success?(A("info",a("machine.actions.workspaceAdded"),!1,P.trim()),!0):(A("error",a("machine.actions.workspaceActionFailed"),!1,$==null?void 0:$.error),!1)}catch($){return A("error",a("machine.actions.workspaceActionFailed"),!1,$),!1}finally{b(!1)}},[e,A,s,a]),q=l.useCallback(async P=>{if(e){b(!0);try{const $=await s(e,"workspace_remove",{id:P});$!=null&&$.success?A("info",a("machine.actions.workspaceRemoved"),!0):A("error",a("machine.actions.workspaceActionFailed"),!0,$==null?void 0:$.error)}catch($){A("error",a("machine.actions.workspaceActionFailed"),!0,$)}finally{b(!1)}}},[e,A,s,a]),J=l.useCallback(async P=>{var $;if(e){b(!0);try{const W=await s(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(W!=null&&W.success){A("info",a(P?"machine.actions.defaultWorkspaceUpdated":"machine.actions.defaultWorkspaceCleared"),!0);const U=typeof W.defaultWorkspacePath=="string"?W.defaultWorkspacePath:"";U&&(($=w.current)==null||$.call(w,U))}else A("error",a("machine.actions.workspaceActionFailed"),!0,W==null?void 0:W.error)}catch(W){A("error",a("machine.actions.workspaceActionFailed"),!0,W)}finally{b(!1)}}},[e,A,s,a]),K=l.useCallback(async(P,$)=>{if(!e||!P.trim())return!1;b(!0);try{const W=await s(e,"workspace_set_label",{path:P.trim(),label:$});return W!=null&&W.success?(await s(e,"workspace_list",{}),A("info",a("machine.actions.workspaceLabelUpdated"),!0),!0):(A("error",a("machine.managedWorkspaces.renameFailed"),!0,W==null?void 0:W.error),!1)}catch(W){return A("error",a("machine.managedWorkspaces.renameFailed"),!0,W),!1}finally{b(!1)}},[e,A,s,a]),M=l.useCallback(async P=>{var W;if(!e||!P.trim())return;const $=P.trim();b(!0);try{const U=await s(e,"workspace_set_default",{path:$});U!=null&&U.success?(A("info",a("machine.actions.defaultWorkspaceUpdated")),(W=w.current)==null||W.call(w,$)):A("error",a("machine.actions.workspaceActionFailed"),!1,(U==null?void 0:U.error)||a("machine.actions.pathMissing"))}catch(U){A("error",a("machine.actions.workspaceActionFailed"),!1,U)}finally{b(!1)}},[e,A,s,a]),D=l.useCallback(async()=>{if(e)try{if(await s(e,"set_machine_nickname",{nickname:x}),r)try{await r({machineRuntimeId:e,registeredMachineId:t,nickname:x})}catch(P){A("warn",a("machine.actions.nicknameSyncFailed"),!1,P)}A("info",a("machine.actions.nicknameSaved")),C(!1)}catch(P){A("error",a("machine.actions.nicknameFailed"),!0,P)}},[e,x,t,A,r,s,a]);return{logs:u,launchingIde:h,launchingAgentType:g,workspaceBusy:y,launchPick:k,setLaunchPick:j,editingNickname:v,setEditingNickname:C,nicknameInput:x,setNicknameInput:S,addLog:A,handleLaunchIde:L,runLaunchCliCore:R,handleLaunchCli:F,handleStopCli:N,handleRestartIde:I,handleStopIde:B,handleDetectIdes:T,handleWorkspaceAdd:H,handleWorkspaceRemove:q,handleWorkspaceSetDefault:J,handleWorkspaceSetLabel:K,handleWorkspaceResumePath:M,handleSaveNickname:D,confirmDialog:d,setOnDefaultWorkspaceChanged:_}}const Ch={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"},MM={bucket:"machine.quota.bucketHint",session:"machine.quota.sessionHint",weekly:"machine.quota.weeklyHint",monthly:"machine.quota.monthlyHint",usage:"machine.quota.usageHint"};function _h({label:e,tone:t,title:s}){return n.jsx("span",{title:s,className:`rounded-full px-2 py-0.5 text-3xs font-medium ${Ch[t]??Ch.default}`,children:e})}function RM({machine:e}){const{t}=ve("common"),s=Rd(Md(t)),r=$g(e.quota);return r.length===0?null:n.jsxs(wn,{padding:"lg",className:"mb-5",children:[n.jsx("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mb-3",children:t("machine.quota.title")}),n.jsx("div",{className:"flex flex-col gap-2",children:r.map(({provider:o,quota:a})=>{const i=s(a);return n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"text-xs text-text-primary min-w-[92px]",children:Pr(o)}),Yl(a)&&n.jsx("span",{className:"text-3xs text-text-secondary",title:t("machine.quota.accountHint"),children:Yl(a)}),i.kind==="chips"&&i.chips.map(c=>n.jsx(_h,{label:c.label,tone:c.tone,title:t(MM[c.hint])},c.key)),i.kind==="usage"&&n.jsx(_h,{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 Ah({title:e,defaultOpen:t=!1,testId:s,children:r}){const[o,a]=l.useState(t),[i,c]=l.useState(t);return n.jsxs("details",{className:"group rounded-xl border border-border-subtle bg-bg-glass",open:o,"data-testid":s,onToggle:d=>{const u=d.currentTarget.open;a(u),u&&c(!0)},children:[n.jsxs("summary",{className:"flex cursor-pointer select-none list-none items-center gap-2 px-4 py-3 text-sm font-semibold text-text-primary [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"inline-block text-text-muted transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),e]}),i&&n.jsx("div",{className:"px-4 pb-4",children:r()})]})}function PM({machine:e,ideSessions:t,cliSessions:s,acpSessions:r,daemonVersion:o,renderHostedRuntimes:a,renderLogs:i,initialDiagnostics:c=null}){var g,f;const{t:d}=ve("common"),u=typeof e.uptime=="number"||typeof e.freeMem=="number"||typeof e.availableMem=="number"||Array.isArray(e.loadavg)&&e.loadavg.length>0,m=e.availableMem??e.freeMem??e.totalMem,h=u&&e.totalMem>0?Math.min(100,Math.max(0,Math.round((e.totalMem-m)/e.totalMem*100))):0,p=((g=e.loadavg)==null?void 0:g[0])||0;return n.jsxs("div",{children:[n.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[n.jsx(Xo,{icon:n.jsx(rd,{size:16}),label:d("machine.overview.uptime"),value:typeof e.uptime=="number"?zk(e.uptime):d("machine.overview.waiting")}),n.jsx(Xo,{icon:n.jsx(Xn,{size:16}),label:"IDEs",value:`${t.length}`}),n.jsx(Xo,{icon:n.jsx(od,{size:16}),label:"CLIs",value:`${s.length}`}),n.jsx(Xo,{icon:n.jsx(sw,{size:16}),label:"ACPs",value:`${r.length}`})]}),n.jsxs(wn,{padding:"lg",className:"mb-5",children:[n.jsx("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mb-3",children:d("machine.overview.resourceUsage")}),n.jsxs("div",{className:"flex gap-6",children:[n.jsx(Du,{value:u?Math.min(Math.round(p/e.cpus*100),100):0,max:100,label:d("machine.overview.cpuLoad"),color:"#8b5cf6",detail:u?d("machine.overview.cpuDetail",{load:p.toFixed(2),cores:e.cpus}):d("machine.overview.waitingForStats")}),n.jsx(Du,{value:h,max:100,label:d("machine.overview.memory"),color:"#3b82f6",detail:u?`${al(e.totalMem-m)} / ${al(e.totalMem)}${e.platform==="darwin"?` ${d("machine.overview.approx")}`:""}`:d("machine.overview.waitingForStatsWithTotal",{total:al(e.totalMem)})})]})]}),n.jsx(RM,{machine:e}),n.jsxs(wn,{padding:"lg",className:"mb-5",children:[n.jsx("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mb-3",children:d("machine.overview.aboutMachine")}),n.jsxs("dl",{className:"grid grid-cols-1 gap-x-6 gap-y-2 text-xs sm:grid-cols-2","data-testid":"machine-about",children:[n.jsx(to,{label:d("machine.overview.hostname"),value:e.hostname}),n.jsx(to,{label:d("machine.overview.platform"),value:[Af[e.platform]||e.platform,e.arch].filter(Boolean).join(" · ")}),e.cpus>0&&n.jsx(to,{label:d("machine.overview.cores"),value:String(e.cpus)}),o&&n.jsx(to,{label:d("machine.overview.daemonVersion"),value:`v${o}`}),((f=e.p2p)==null?void 0:f.available)&&n.jsx(to,{label:d("machine.overview.p2p"),value:e.p2p.state==="connected"?d("machine.detail.p2pConnected"):e.p2p.state})]})]}),(a||i)&&n.jsxs("details",{className:"group mb-5","data-testid":"machine-diagnostics",open:c?!0:void 0,children:[n.jsxs("summary",{className:"mb-3 flex cursor-pointer select-none list-none items-center gap-2 text-2xs font-semibold uppercase tracking-wider text-text-muted [&::-webkit-details-marker]:hidden",children:[n.jsx("span",{className:"inline-block transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"}),d("machine.overview.diagnostics")]}),n.jsxs("div",{className:"flex flex-col gap-3",children:[a&&n.jsx(Ah,{title:d("machine.detail.tabHostedRuntimes"),defaultOpen:c==="hosted-runtimes",testId:"machine-diagnostics-hosted-runtimes",children:a}),i&&n.jsx(Ah,{title:d("machine.detail.tabLogs"),defaultOpen:c==="logs",testId:"machine-diagnostics-logs",children:i})]})]})]})}function to({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 Jb(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 Xb(e,t,s){const r=[];for(const[o,a]of Object.entries(e.settings)){const i=s!=null&&s.filterSchema?s.filterSchema(a):a;if(i.length===0)continue;const c=t.find(d=>d.type===o);r.push({type:o,displayName:(c==null?void 0:c.displayName)||o,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:i,values:e.values[o]||{}})}return r}function Ml(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 Th(e){if(!e||typeof e!="object")return null;if(Ml(e))return e;const t=e,s=t.result;return Ml(s)?s:Ml(t.sourceConfig)?t.sourceConfig:null}function LM(e){const t=e.trim();return t||null}function EM({providerType:e,displayName:t,supportsQuota:s,quotaInstallsClaudeStatusline:r,onCancel:o,onConfirm:a}){const{t:i}=ve("common"),[c,d]=l.useState(!0),[u,m]=l.useState(!0);return n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:o,children:n.jsxs("div",{className:"w-[min(520px,92vw)] rounded-xl border border-border-default bg-surface-primary p-5 shadow-2xl",onClick:h=>h.stopPropagation(),role:"dialog","aria-modal":"true",children:[n.jsx("div",{className:"text-xxs font-semibold text-text-primary",children:i("machine.installOptions.title",{provider:t})}),n.jsxs("div",{className:"mt-4 flex flex-col gap-3",children:[s&&n.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5",children:[n.jsx("input",{type:"checkbox",checked:c,onChange:h=>d(h.target.checked),className:"mt-0.5 h-3.5 w-3.5 shrink-0 accent-accent-primary"}),n.jsx("span",{className:"min-w-0",children:n.jsxs("span",{className:"flex items-center gap-1 text-xs font-medium text-text-primary",children:[i("machine.installOptions.quotaLabel"),n.jsx(dt,{content:[i("machine.installOptions.quotaHint"),r&&c?i("machine.installOptions.quotaClaudeNote"):""].filter(Boolean).join(`
|
|
77
|
-
|
|
78
|
-
`),size:12})]})})]}),n.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5",children:[n.jsx("input",{type:"checkbox",checked:u,onChange:h=>m(h.target.checked),className:"mt-0.5 h-3.5 w-3.5 shrink-0 accent-accent-primary"}),n.jsxs("span",{className:"min-w-0",children:[n.jsx("span",{className:"block text-xs font-medium text-text-primary",children:i("machine.installOptions.autoApproveLabel")}),n.jsx("span",{className:"mt-0.5 block text-2xs text-text-muted",children:i("machine.installOptions.autoApproveHint")}),u&&n.jsx("span",{className:"mt-1 block text-2xs text-amber-400",children:i("machine.installOptions.autoApproveWarning")})]})]})]}),n.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[n.jsx("button",{onClick:o,className:"machine-btn text-2xs px-3 py-1",children:i("machine.installOptions.cancel")}),n.jsx("button",{onClick:()=>a({quotaEnabled:s?c:void 0,autoApprove:u}),className:"machine-btn text-2xs px-3 py-1 border-accent-primary/30 bg-accent-primary/15 text-accent-primary","data-provider-type":e,children:i("machine.installOptions.confirm")})]})]})})})}const Ih={"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"},Mh={"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"},DM={"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 OM({trust:e,sourceName:t,description:s}){const{t:r}=ve("common"),o=Ih[e]?r(Ih[e]):e,a=t&&(e==="external-safe"||e==="external-untrusted")?`${o} · ${t}`:o,i=Mh[e]?r(Mh[e]):s;return n.jsx("span",{className:`text-3xs px-1.5 py-0.5 rounded border whitespace-nowrap ${DM[e]??""}`,title:i,children:a})}const FM={ide:{badge:"bg-blue-500/10 text-blue-300 border-blue-500/20",accent:"border-blue-500/[0.12]"},cli:{badge:"bg-indigo-500/10 text-indigo-300 border-indigo-500/20",accent:"border-indigo-500/[0.12]"},acp:{badge:"bg-fuchsia-500/10 text-fuchsia-300 border-fuchsia-500/20",accent:"border-fuchsia-500/[0.12]"},extension:{badge:"bg-teal-500/10 text-teal-300 border-teal-500/20",accent:"border-teal-500/[0.12]"}},$M=["enabled","autoApprove","executablePath","executableArgs","cliPathOverride","appPathOverride","approvalAlert","longGeneratingAlert","longGeneratingThresholdSec","showThinking","showToolCalls","showTerminal","showCoordinatorSystemPrompt","notifications"],HM=new Set($M);function BM(e,t,s){if(!HM.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 WM(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 UM(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 Rh={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"},KM={bucket:"machine.quota.bucketHint",session:"machine.quota.sessionHint",weekly:"machine.quota.weeklyHint",monthly:"machine.quota.monthlyHint",usage:"machine.quota.usageHint"},qM={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 Ph(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 Lh={Stable:"machine.providerRow.lifecycleStable",Beta:"machine.providerRow.lifecycleBeta",Experimental:"machine.providerRow.lifecycleExperimental",Deprecated:"machine.providerRow.lifecycleDeprecated"};function zM(e){return e==="cli"||e==="acp"}function Rl({checked:e,busy:t,label:s,onToggle:r}){return n.jsx(Br,{as:"span",size:"sm",checked:e,busy:t,"aria-label":s,onChange:()=>r()})}function GM({prov:e,quota:t,providerInfo:s,savingKey:r,onSetSetting:o,onEnableToggle:a,onDetect:i,onResetCommand:c,quotaAccountLabelEnabled:d,onQuotaAccountLabelToggle:u,quotaEnabled:m,onQuotaToggle:h,pin:p,onUpdate:g,updating:f,onRollbackUpdate:y,showAdvanced:b=!1}){var N;const[k,j]=l.useState(null),[v,C]=l.useState(!1),{t:x}=ve("common"),S={detected:x("machine.providerRow.statusDetected"),not_detected:x("machine.providerRow.statusNotDetected"),enabled_unchecked:x("machine.providerRow.statusEnabledUnchecked"),disabled:x("machine.providerRow.statusDisabled")},[w,_]=l.useState(!1),A=(s==null?void 0:s.enabled)===!0||e.values.enabled===!0,O=s==null?void 0:s.machineStatus,L=A&&O==="disabled"?"enabled_unchecked":O||(A?"enabled_unchecked":"disabled"),R=zM(e.category),F=(()=>{if(!t)return null;const B=Rd(Md(x))(t).compactChip;return B?{label:B.label,tone:qM[B.tone],title:x(KM[B.hint])}:null})();return n.jsxs(wn,{padding:"none",children:[n.jsxs("button",{onClick:()=>_(I=>!I),className:"w-full px-4 py-2.5 flex items-center gap-3 text-left",children:[n.jsx(Li,{type:e.type,label:e.displayName,size:20,className:"shrink-0"}),n.jsx("span",{className:"text-xxs font-semibold text-text-primary truncate",children:e.displayName}),n.jsx("span",{className:`text-4xs font-semibold px-1.5 py-px rounded border ${((N=FM[e.category])==null?void 0:N.badge)??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(s==null?void 0:s.trust)&&n.jsx(OM,{trust:s.trust,sourceName:s.sourceName??null,description:s.trustDescription}),R&&n.jsx("span",{className:`text-4xs font-semibold px-1.5 py-px rounded border ${Rh[L]??Rh.disabled}`,children:S[L]??L}),n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[g&&(p==null?void 0:p.stale)&&p.latestVersion&&n.jsx("span",{role:"button",tabIndex:0,"aria-disabled":f?!0:void 0,title:x("machine.providerRow.updateInlineHint",{latest:p.latestVersion}),onClick:I=>{I.stopPropagation(),!f&&g()},onKeyDown:I=>{I.key!=="Enter"&&I.key!==" "||(I.preventDefault(),I.stopPropagation(),!f&&g())},className:`text-3xs font-semibold px-2 py-0.5 rounded-md border border-amber-500/30 text-amber-400 shrink-0 ${f?"opacity-60 cursor-wait":"cursor-pointer hover:bg-amber-500/15"}`,children:x(f?"machine.providerRow.specPinUpdating":"machine.providerRow.updateInline")}),F&&n.jsx("span",{className:`text-4xs font-semibold px-1.5 py-px rounded border shrink-0 ${F.tone}`,title:F.title,children:F.label}),R&&n.jsx(Rl,{checked:A,busy:r===`${e.type}.enabled`,label:x(A?"machine.providerRow.disable":"machine.providerRow.enable"),onToggle:()=>{a(e.type,!A)}}),n.jsx("span",{className:"text-text-muted text-xs",children:w?"▾":"▸"})]})]}),w&&n.jsxs("div",{className:"border-t border-border-subtle px-4 py-3 flex flex-col gap-3",children:[e.schema.length>0&&n.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(I=>{const B=BM(x,I,e.displayName);return n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("div",{className:"flex-1 min-w-0",children:n.jsxs("div",{className:"flex items-center gap-1 text-2xs font-medium text-text-primary",children:[B.label,B.description&&n.jsx(dt,{content:B.description,size:11}),r===`${e.type}.${I.key}`&&n.jsx("span",{className:"ml-1.5 text-4xs text-accent-primary",children:x("machine.providerRow.saving")})]})}),n.jsx("div",{className:"shrink-0",children:I.type==="boolean"?n.jsx(Br,{checked:!!(e.values[I.key]??I.default),busy:r===`${e.type}.${I.key}`,"aria-label":B.label,onChange:T=>void o(e.type,I.key,T)}):I.type==="number"?n.jsx("input",{type:"number",value:Number(e.values[I.key]??I.default??0)||0,min:I.min,max:I.max,onChange:T=>{const H=parseInt(T.target.value)||0;I.min!==void 0&&H<I.min||I.max!==void 0&&H>I.max||o(e.type,I.key,H)},className:"machine-input w-20 text-center text-2xs"}):I.type==="select"&&I.options?n.jsx("select",{value:String(e.values[I.key]??I.default??""),onChange:T=>void o(e.type,I.key,T.target.value),className:"machine-input text-2xs",children:I.options.map(T=>n.jsx("option",{value:T,children:WM(x,T)},T))}):n.jsx("input",{type:"text",defaultValue:String(e.values[I.key]??I.default??""),onBlur:T=>void o(e.type,I.key,T.target.value),className:"machine-input w-[180px] text-2xs"})})]},I.key)})}),h&&m!==void 0&&n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1 text-2xs text-text-secondary font-medium",children:[x("machine.providerRow.quotaTracking"),n.jsx(dt,{content:x("machine.providerRow.quotaTrackingHint"),size:11})]}),v?n.jsxs("div",{className:"flex flex-col items-end gap-1.5 shrink-0",children:[n.jsx("div",{className:"text-2xs font-medium text-amber-400",children:x("machine.providerRow.quotaClaudeConfirmTitle")}),n.jsx("div",{className:"text-3xs text-text-muted max-w-[420px] text-right",children:x("machine.providerRow.quotaClaudeConfirmBody")}),n.jsxs("div",{className:"flex gap-1.5",children:[n.jsx("button",{onClick:I=>{I.stopPropagation(),C(!1),h(e.type,!0)},className:"machine-btn text-3xs px-2 py-0.5 text-amber-400 border-amber-500/25",children:x("machine.providerRow.quotaClaudeConfirmOk")}),n.jsx("button",{onClick:I=>{I.stopPropagation(),C(!1)},className:"machine-btn text-3xs px-2 py-0.5",children:x("machine.providerRow.quotaClaudeConfirmCancel")})]})]}):n.jsx(Rl,{checked:m,label:x("machine.providerRow.quotaTracking"),onToggle:()=>{e.type==="claude-cli"&&!m?C(!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:[x("machine.providerRow.quotaAccountLabel"),n.jsx(dt,{content:x("machine.providerRow.quotaAccountLabelHint"),size:11})]}),n.jsx(Rl,{checked:d,label:x("machine.providerRow.quotaAccountLabel"),onToggle:()=>{u(!d)}})]}),b&&n.jsxs("div",{className:"grid gap-1 text-3xs text-text-muted","data-testid":"provider-row-metadata",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:x("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:x("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:x("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:x("machine.providerRow.specPinStaleHint",{latest:p.latestVersion}),children:x("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:x("machine.providerRow.labelActivatedAt")})," ",Po(p.activatedAt)]}),(p==null?void 0:p.previousVersion)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:x("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:x("machine.providerRow.labelDigest")})," ",n.jsx("span",{className:"font-mono",children:p.digest.replace(/^sha256:/,"").slice(0,12)})]}),b&&(s==null?void 0:s.binary)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:x("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:x("machine.providerRow.labelStatus")})," ",Lh[s.status]?x(Lh[s.status]):s.status]}),b&&(s==null?void 0:s.details)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:x("machine.providerRow.labelDetails")})," ",s.details]}),b&&(s==null?void 0:s.sourceLayer)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:x("machine.providerRow.labelSource")})," ",n.jsx("span",{className:"font-mono",children:s.sourceLayer}),s.sourceName?` · ${s.sourceName}`:""]}),b&&(s==null?void 0:s.trust)&&(s==null?void 0:s.trustDescription)&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:x("machine.providerRow.labelTrust")})," ",n.jsx("span",{className:"font-mono",children:s.trust})," — ",s.trustDescription]}),(()=>{const I=s==null?void 0:s.links;if(!I)return null;const B=Object.entries(I).map(([T,H])=>({k:T,href:UM(H)})).filter(T=>T.href!==null);return B.length===0?null:n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:x("machine.providerRow.labelLinks")})," ",B.map(({k:T,href:H})=>n.jsx("a",{href:H,target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary hover:underline mr-2",children:T},T))]})})()]}),R&&(b||(s==null?void 0:s.lastDetection)||(s==null?void 0:s.lastVerification))&&n.jsxs("div",{className:"grid gap-1 text-3xs text-text-muted",children:[(b||(s==null?void 0:s.lastDetection))&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:x("machine.providerRow.labelDetection")})," ",Ph(x,s==null?void 0:s.lastDetection)]}),(b||(s==null?void 0:s.lastVerification))&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary font-medium",children:x("machine.providerRow.labelVerification")})," ",Ph(x,s==null?void 0:s.lastVerification)]})]}),n.jsxs("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:[R&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>void i(e.type),disabled:!A||r===`${e.type}.detect`,className:`machine-btn text-3xs px-2 py-0.5 text-blue-400 border-blue-500/25 ${A?"":"opacity-40 cursor-not-allowed"}`,title:x(A?"machine.providerRow.detectHint":"machine.providerRow.detectDisabledHint"),children:x("machine.providerRow.detect")}),n.jsx("button",{onClick:()=>void c(e.type),className:"machine-btn text-3xs px-2 py-0.5",children:x("machine.providerRow.resetCommand")})]}),y&&(p==null?void 0:p.previousVersion)&&n.jsx("button",{onClick:()=>{j("rollback"),y().finally(()=>j(null))},disabled:k!==null||f===!0,className:"machine-btn text-3xs px-2 py-0.5",title:x("machine.providerRow.specPinRollbackHint",{version:p.previousVersion}),children:x(k==="rollback"?"machine.providerRow.specPinRollingBack":"machine.providerRow.specPinRollback")})]})]})]})}function VM(e){if(!e||typeof e!="object")return null;const t=e,s=t.result;return s&&typeof s=="object"?s:t}function Eh(e){const t=VM(e);if(!t)return[];const s=[];t.success===!1&&typeof t.error=="string"&&t.error.trim()&&s.push({code:"COMMAND_FAILED",message:t.error});const r=t.channelSync,o=r&&typeof r=="object"?r.errors:void 0;if(Array.isArray(o))for(const a of o){if(!a||typeof a!="object")continue;const i=a,c=typeof i.code=="string"?i.code:"UNKNOWN",d=typeof i.message=="string"?i.message:"";s.push({code:c,message:d,...typeof i.providerType=="string"?{providerType:i.providerType}:{}})}return s}function YM(e){return e.some(t=>t.code==="DIGEST_MISMATCH")}function fa(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function QM({machineId:e,sendDaemonCommand:t,onChange:s,reloadToken:r=0}){const{t:o}=ve("common"),{confirm:a,confirmDialog:i}=Fr(),[c,d]=l.useState([]),[u,m]=l.useState([]),[h,p]=l.useState(!1),[g,f]=l.useState(null),[y,b]=l.useState(!1),[k,j]=l.useState(""),[v,C]=l.useState("main"),[x,S]=l.useState(""),[w,_]=l.useState(!1),[A,O]=l.useState(null),[L,R]=l.useState(null),F=l.useCallback(async()=>{if(e){p(!0),f(null);try{const T=fa(await t(e,"list_provider_sources",{}));if(!(T!=null&&T.success)){f((T==null?void 0:T.error)||o("machine.sourcesPanel.loadFailed"));return}d(T.sources||[]),m(T.conflicts||[])}catch(T){f((T==null?void 0:T.message)||o("machine.sourcesPanel.loadFailed"))}finally{p(!1)}}},[e,t,o]);l.useEffect(()=>{F()},[F,r]);const N=async()=>{if(k.trim()){_(!0),f(null);try{const T=fa(await t(e,"add_provider_source",{url:k.trim(),ref:v.trim()||"main",...x.trim()?{name:x.trim()}:{}}));T!=null&&T.success?(b(!1),j(""),C("main"),S(""),await F(),s==null||s()):f((T==null?void 0:T.error)||o("machine.sourcesPanel.addFailed"))}catch(T){f((T==null?void 0:T.message)||o("machine.sourcesPanel.addFailed"))}finally{_(!1)}}},I=async T=>{if(await a({title:o("machine.sourcesPanel.removeConfirmTitle",{name:T}),description:o("machine.sourcesPanel.removeConfirmDescription"),confirmLabel:o("machine.sourcesPanel.removeConfirmLabel"),cancelLabel:o("machine.sourcesPanel.cancel"),tone:"danger"})){O(T),f(null);try{const q=fa(await t(e,"remove_provider_source",{name:T}));q!=null&&q.success?(await F(),s==null||s()):f((q==null?void 0:q.error)||o("machine.sourcesPanel.removeFailed"))}catch(q){f((q==null?void 0:q.message)||o("machine.sourcesPanel.removeFailed"))}finally{O(null)}}},B=async(T,H)=>{R(`${T}:${H}`),f(null);try{const q=fa(await t(e,"set_active_provider_source",{type:T,sourceName:H}));q!=null&&q.success?(await F(),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{R(null)}};return n.jsxs(wn,{padding:"none",className:"px-4.5 py-3.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[n.jsxs("div",{className:"flex items-center gap-1 text-2xs font-semibold uppercase tracking-wider text-sky-400",children:[o("machine.sourcesPanel.title"),n.jsx(dt,{content:o("machine.sourcesPanel.description"),size:12}),h&&n.jsx("span",{className:"ml-1 normal-case tracking-normal font-normal text-text-muted",children:"…"})]}),n.jsx("div",{className:"flex gap-1.5",children:n.jsx("button",{onClick:()=>b(!0),className:"machine-btn text-3xs bg-sky-500/[0.08] border-sky-500/20 text-sky-300 hover:bg-sky-500/[0.14]",children:o("machine.sourcesPanel.addSource")})})]}),g&&n.jsx("div",{className:"mb-2 text-2xs text-red-400 bg-red-500/10 border border-red-500/20 rounded px-2 py-1",children:g}),c.length===0?n.jsx("div",{className:"text-2xs text-text-muted italic",children:o("machine.sourcesPanel.empty")}):n.jsx("ul",{className:"flex flex-col gap-2",children:c.map(T=>n.jsxs("li",{className:"rounded border border-border-subtle bg-bg-primary/40 px-3 py-2",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"font-mono text-xs text-text-primary",children:T.name}),n.jsxs("div",{className:"text-3xs text-text-muted truncate",children:[T.url," ",n.jsxs("span",{className:"opacity-60",children:["@ ",T.ref]})]})]}),n.jsx("button",{type:"button",onClick:()=>void I(T.name),disabled:A===T.name,className:"machine-btn text-3xs text-red-400 hover:bg-red-500/[0.10]",children:A===T.name?o("machine.sourcesPanel.removing"):o("machine.sourcesPanel.remove")})]}),n.jsx("div",{className:"mt-1.5 text-3xs text-text-muted",children:Object.entries(T.providers).map(([H,q])=>n.jsxs("span",{className:"mr-3",children:[n.jsxs("span",{className:"text-text-secondary",children:[H,":"]})," ",q.length]},H))})]},T.name))}),u.length>0&&n.jsxs("div",{className:"mt-3 rounded border border-amber-500/30 bg-amber-500/[0.06] px-3 py-2",children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1 text-2xs font-semibold text-amber-300",children:[o("machine.sourcesPanel.conflictsTitle"),n.jsx(dt,{content:o("machine.sourcesPanel.conflictsDescription"),size:12})]}),n.jsx("ul",{className:"flex flex-col gap-1.5",children:u.map(T=>n.jsxs("li",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"font-mono text-2xs",children:[T.type," ",n.jsxs("span",{className:"text-text-muted",children:["(",T.category,")"]})]}),n.jsx("div",{className:"flex gap-1.5 flex-wrap",children:T.candidates.map(H=>n.jsxs("button",{type:"button",onClick:()=>void B(T.type,H),disabled:L===`${T.type}:${H}`,className:`text-3xs px-2 py-0.5 rounded border ${T.active===H?"bg-amber-500/[0.18] border-amber-500/40 text-amber-200":"border-border-subtle text-text-secondary hover:bg-amber-500/[0.06]"}`,title:T.active===H?o("machine.sourcesPanel.active"):o("machine.sourcesPanel.switchActiveTo",{name:H}),children:[T.active===H?"● ":"",H]},H))})]},T.type))})]}),y&&n.jsxs("div",{className:"mt-3 rounded border border-sky-500/30 bg-sky-500/[0.06] px-3 py-3",children:[n.jsx("div",{className:"text-2xs font-semibold text-sky-300 mb-2",children:o("machine.sourcesPanel.addTitle")}),n.jsxs("div",{className:"grid md:grid-cols-3 gap-2",children:[n.jsxs("label",{className:"flex flex-col gap-1 text-3xs text-text-secondary md:col-span-3",children:[n.jsx("span",{children:o("machine.sourcesPanel.gitUrl")}),n.jsx("input",{type:"text",value:k,onChange:T=>j(T.target.value),placeholder:"https://github.com/vendor/extra-providers",className:"machine-input text-2xs font-mono"})]}),n.jsxs("label",{className:"flex flex-col gap-1 text-3xs text-text-secondary",children:[n.jsx("span",{children:o("machine.sourcesPanel.ref")}),n.jsx("input",{type:"text",value:v,onChange:T=>C(T.target.value),placeholder:"main",className:"machine-input text-2xs"})]}),n.jsxs("label",{className:"flex flex-col gap-1 text-3xs text-text-secondary md:col-span-2",children:[n.jsx("span",{children:o("machine.sourcesPanel.name")}),n.jsx("input",{type:"text",value:x,onChange:T=>S(T.target.value),placeholder:"@vendor-extra-providers",className:"machine-input text-2xs font-mono"})]})]}),n.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>b(!1),className:"machine-btn text-3xs",children:o("machine.sourcesPanel.cancel")}),n.jsx("button",{type:"button",onClick:()=>void N(),disabled:w||!k.trim(),className:"machine-btn text-3xs bg-sky-500/[0.10] border-sky-500/30 text-sky-200 hover:bg-sky-500/[0.18]",children:o(w?"machine.sourcesPanel.cloning":"machine.sourcesPanel.cloneAndRegister")})]})]}),i]})}function Dh(e){var o;const t=ud(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 Oh=new Set(["codex-cli"]),ga=new Set(ey);function JM({machineId:e,providers:t,sendDaemonCommand:s,quota:r,onChannelStaleness:o}){var oe,Ie;const{t:a}=ve("common"),[i,c]=l.useState(null),[d,u]=l.useState(void 0),[m,h]=l.useState({}),[p,g]=l.useState({}),[f,y]=l.useState([]),[b,k]=l.useState([]),[j,v]=l.useState(null),[C,x]=l.useState({}),[S,w]=l.useState(!1),[_,A]=l.useState({}),[O,L]=l.useState(!1),[R,F]=l.useState(null),[N,I]=l.useState(null),[B,T]=l.useState("cli"),[H,q]=l.useState(null),[J,K]=l.useState(!1),[M,D]=l.useState(0),[P,$]=l.useState(null),[W,U]=l.useState("normal"),[ae,be]=l.useState(""),[V,we]=l.useState(!1),ce=l.useCallback(async()=>{if(e)try{const Z=await s(e,"get_provider_source_config",{}),se=Th(Z);se&&($(se),U(se.sourceMode),be(se.explicitProviderDir||""))}catch(Z){F(a("machine.providers.loadFailed",{error:(Z==null?void 0:Z.message)||String(Z)}))}},[e,s,a]),de=l.useCallback(async Z=>{if(e){Z!=null&&Z.explicit&&L(!0);try{const se=await s(e,"get_provider_settings",{}),ye=Jb(se);ye&&(c(ye),F(null))}catch(se){F(a("machine.providers.loadFailed",{error:(se==null?void 0:se.message)||String(se)}))}finally{Z!=null&&Z.explicit&&L(!1)}}},[e,s,a]),ne=l.useMemo(()=>{if(!i)return[];const Z=Xb(i,t,{filterSchema:se=>se.filter(ye=>ye.key!=="enabled")});return Z.sort((se,ye)=>se.category.localeCompare(ye.category)||se.displayName.localeCompare(ye.displayName)),Z},[i,t]),ee=l.useCallback((Z,se,ye)=>{c(Fe=>Fe&&{...Fe,values:{...Fe.values,[Z]:{...Fe.values[Z]||{},[se]:ye}}})},[]),ue=l.useCallback(async()=>{if(e)try{const Z=await s(e,"get_quota_account_label",{}),se=Z&&typeof Z=="object"&&"result"in Z?Z.result:Z;typeof(se==null?void 0:se.enabled)=="boolean"&&u(se.enabled)}catch{}},[e,s]),je=l.useCallback(async Z=>{if(e){u(Z);try{const se=await s(e,"set_quota_account_label",{enabled:Z}),ye=se&&typeof se=="object"&&"result"in se?se.result:se;(ye==null?void 0:ye.success)===!1&&await ue()}catch{await ue()}}},[e,s,ue]),X=l.useCallback(async Z=>{if(e)try{const se=await s(e,"get_quota_provider_enabled",{providerType:Z}),ye=se&&typeof se=="object"&&"result"in se?se.result:se;typeof(ye==null?void 0:ye.enabled)=="boolean"&&h(Fe=>({...Fe,[Z]:ye.enabled}))}catch{}},[e,s]),G=l.useCallback(async()=>{await Promise.all([...ga].map(Z=>X(Z)))},[X]),z=l.useCallback(async(Z,se)=>{if(e){h(ye=>({...ye,[Z]:se}));try{const ye=await s(e,"set_quota_provider_enabled",{providerType:Z,enabled:se}),Fe=ye&&typeof ye=="object"&&"result"in ye?ye.result:ye;(Fe==null?void 0:Fe.success)===!1&&(F(a("machine.providers.quotaToggleFailed",{provider:Z,error:typeof Fe.error=="string"?Fe.error:"unknown error"})),await X(Z))}catch(ye){F(a("machine.providers.quotaToggleFailed",{provider:Z,error:(ye==null?void 0:ye.message)||String(ye)})),await X(Z)}}},[e,s,X,a]),ie=l.useCallback(async()=>{var Z,se;if(e)try{const ye=await s(e,"check_provider_updates",{}),Fe=ye&&typeof ye=="object"&&"result"in ye?ye.result:ye,Me={};for(const Te of(Fe==null?void 0:Fe.providers)??[])typeof(Te==null?void 0:Te.type)=="string"&&(Me[Te.type]={activeVersion:Te.activeVersion??null,latestVersion:Te.latestVersion??null,stale:Te.stale===!0,digest:Te.digest??null,activatedAt:Te.activatedAt??null,previousVersion:Te.previousVersion??null});g(Me),y(Array.isArray((Z=Fe==null?void 0:Fe.channelStaleness)==null?void 0:Z.newTypes)?Fe.channelStaleness.newTypes:[]);const De=Fe==null?void 0:Fe.channelStaleness;o&&De&&!De.error&&o({staleTypes:Array.isArray(De.staleTypes)?De.staleTypes:[],newTypes:Array.isArray(De.newTypes)?De.newTypes:[]}),k(Array.isArray((se=Fe==null?void 0:Fe.modelStaleness)==null?void 0:se.staleTypes)?Fe.modelStaleness.staleTypes:[])}catch{}},[e,s,o]),Ne=l.useCallback(async Z=>{if(e){v(Z),A(se=>{if(!(Z in se))return se;const ye={...se};return delete ye[Z],ye});try{const se=await s(e,"activate_provider_updates",{types:[Z]}),ye=Eh(se);ye.length>0&&A(Fe=>({...Fe,[Z]:ye}))}catch(se){A(ye=>({...ye,[Z]:[{code:"COMMAND_FAILED",message:se instanceof Error?se.message:String(se)}]}))}finally{v(null),await ie(),de()}}},[e,s,ie,de]),Be=l.useCallback(async()=>{if(e){w(!0);try{const Z=await s(e,"activate_provider_updates",{}),se=Dh(Z);"error"in se?ct.showErrorToast(a("machine.detail.providerSyncFailed"),se.error):ct.showToast(se.activatedCount>0?a("machine.detail.providerSyncSuccess",{count:se.activatedCount}):a("machine.detail.providerSyncAlreadyCurrent"),"success")}catch(Z){ct.showErrorToast(a("machine.detail.providerSyncFailed"),Z)}finally{w(!1),await ie(),de()}}},[e,s,ie,de,a]),Le=l.useCallback(async Z=>{if(e)try{await s(e,"rollback_provider_update",{providerType:Z})}finally{await ie(),de()}},[e,s,ie,de]),Je=l.useCallback(async Z=>{if(e){x(se=>({...se,[Z]:!0}));try{const se=await s(e,"activate_provider_updates",{types:[Z],only:!0}),ye=Dh(se),Fe=Eh(se);if("error"in ye||Fe.length>0){const Me="error"in ye?ye.error:Fe.map(De=>De.message||De.code).join("; ");ct.showErrorToast(a("machine.detail.providerSyncFailed"),Me)}else ct.showToast(ye.activatedCount>0?a("machine.detail.providerSyncSuccess",{count:ye.activatedCount}):a("machine.detail.providerSyncAlreadyCurrent"),"success")}catch(se){ct.showErrorToast(a("machine.detail.providerSyncFailed"),se)}finally{x(se=>{const ye={...se};return delete ye[Z],ye}),await ie(),de()}}},[e,s,ie,de,a]);l.useEffect(()=>{i||de({explicit:!0}),P||ce(),d===void 0&&ue(),G(),ie()},[]);const Se=async(Z,se,ye)=>{I(`${Z}.${se}`),ee(Z,se,ye);try{const Fe=await s(e,"set_provider_setting",{providerType:Z,key:se,value:ye});Fe!=null&&Fe.success||de()}catch{de()}I(null)},he=async(Z,se)=>{if(se){q(Z);return}await Se(Z,"enabled",!1)},pe=l.useCallback(async(Z,se)=>{q(null),I(`${Z}.enabled`);try{se.quotaEnabled!==void 0&&await s(e,"set_quota_provider_enabled",{providerType:Z,enabled:se.quotaEnabled});const ye=await s(e,"set_provider_setting",{providerType:Z,key:"autoApprove",value:se.autoApprove}),Fe=await s(e,"set_provider_setting",{providerType:Z,key:"enabled",value:!0});if((ye==null?void 0:ye.success)===!1||(Fe==null?void 0:Fe.success)===!1)throw new Error("set_provider_setting refused");ee(Z,"autoApprove",se.autoApprove),ee(Z,"enabled",!0),se.quotaEnabled!==void 0&&h(Me=>({...Me,[Z]:se.quotaEnabled}))}catch{de(),X(Z)}finally{I(null)}},[e,s,de,X,ee]),Ee=async Z=>{I(`${Z}.detect`);try{const se=await s(e,"detect_provider",{providerType:Z}),ye=se&&typeof se=="object"&&"result"in se?se.result:se;(ye==null?void 0:ye.success)===!1&&F(a("machine.providers.loadFailed",{error:typeof ye.error=="string"?ye.error:"detect failed"}))}catch(se){F(a("machine.providers.loadFailed",{error:(se==null?void 0:se.message)||String(se)}))}finally{I(null)}},Y=async Z=>{await Se(Z,"executablePath",""),await Se(Z,"executableArgs","")},me=async()=>{we(!0);try{const Z=await s(e,"set_provider_source_config",{providerSourceMode:W,providerDir:LM(ae)}),se=Th(Z);se?($(se),U(se.sourceMode),be(se.explicitProviderDir||"")):await ce(),de()}catch{await ce()}we(!1)},fe=ne.filter(Z=>B==="all"||Z.category===B),E=Object.values(p).filter(Z=>Z.stale).length;return n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[n.jsxs("div",{className:"flex gap-1 items-center",children:[n.jsx("span",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mr-2",children:a("machine.providers.filter")}),["cli","ide","acp","extension","all"].map(Z=>n.jsx("button",{onClick:()=>T(Z),className:`machine-btn text-3xs px-2 py-0.5 ${B===Z?"bg-accent-primary/15 border-accent-primary/40 text-accent-primary":""}`,children:Z.toUpperCase()},Z))]}),n.jsxs("div",{className:"flex gap-1.5 items-center",children:[E>=2&&n.jsxs("button",{onClick:()=>{Be()},disabled:S,className:"machine-btn text-3xs text-amber-400 border-amber-500/25",children:[S?n.jsx(Ir,{size:11}):null," ",a("machine.providers.updateAll")]}),n.jsx(Di,{onClick:()=>{de({explicit:!0}),ie(),J&&(ce(),D(Z=>Z+1))},refreshing:O,label:a("machine.providers.refresh"),size:12,className:"h-7 w-7"}),n.jsx("button",{onClick:()=>K(Z=>!Z),"aria-expanded":J,className:`machine-btn text-3xs ${J?"bg-accent-primary/10 border-accent-primary/30 text-accent-primary":""}`,title:a("machine.providers.advancedHint"),children:a("machine.providers.advanced")})]})]}),R&&n.jsx(zt,{variant:"error",onDismiss:()=>F(null),children:R}),f.length>0&&n.jsxs(wn,{padding:"none",className:"px-4.5 py-3.5",children:[n.jsxs("div",{className:"mb-2.5 flex items-center gap-1 text-2xs font-semibold uppercase tracking-wider text-accent-primary",children:[a("machine.providers.newChannelTypesTitle"),n.jsx(dt,{content:a("machine.providers.newChannelTypesDesc"),size:12})]}),n.jsx("div",{className:"flex flex-col gap-1.5",children:f.map(Z=>{const se=_[Z]??[];return n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 text-xxs",children:[n.jsx("span",{className:"font-mono text-text-primary",children:Z}),n.jsx("button",{onClick:()=>{Ne(Z)},disabled:j!==null,className:"px-2.5 py-1 rounded-md text-xs font-medium bg-accent-primary/15 text-accent-primary hover:bg-accent-primary/25 disabled:opacity-50",children:j===Z?n.jsx(Ir,{size:11}):a("machine.providers.installNewType")})]}),se.length>0&&n.jsxs("div",{className:"rounded-md border border-red-500/30 bg-red-500/[0.07] px-2.5 py-1.5",children:[n.jsx("div",{className:"text-3xs font-semibold text-red-300",children:YM(se)?a("machine.providers.installFailedDigestMismatch"):a("machine.providers.installFailedTitle")}),n.jsx(_d,{summary:a("toast.details"),className:"mt-1",children:n.jsx("ul",{className:"flex flex-col gap-0.5",children:se.map((ye,Fe)=>n.jsxs("li",{className:"text-3xs text-text-muted font-mono break-all",children:[n.jsx("span",{className:"text-red-300/90",children:ye.code}),ye.providerType?` [${ye.providerType}]`:"",ye.message?`: ${ye.message}`:""]},`${ye.code}-${Fe}`))})})]})]},Z)})})]}),b.length>0&&n.jsxs(wn,{padding:"none",className:"px-4.5 py-3.5",children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1 text-2xs font-semibold uppercase tracking-wider text-text-secondary",children:[a("machine.providers.modelListTitle"),n.jsx(dt,{content:a("machine.providers.modelListStaleDesc"),size:12})]}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:b.map(Z=>n.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-amber-500/30 bg-amber-500/[0.07] px-2 py-0.5",children:[n.jsx("span",{className:"font-mono text-xxs text-text-primary",children:Z}),n.jsx("span",{className:"text-3xs uppercase tracking-wider text-amber-300/90",children:a("machine.providers.modelListStaleBadge")})]},Z))})]}),J&&n.jsx(QM,{machineId:e,sendDaemonCommand:s,onChange:()=>{de()},reloadToken:M}),J&&n.jsxs(wn,{padding:"none",className:"px-4.5 py-3.5",children:[n.jsx("div",{className:"flex items-center justify-between gap-3 mb-3",children:n.jsxs("div",{className:"flex items-center gap-1 text-2xs font-semibold uppercase tracking-wider text-accent-primary",children:[a("machine.providers.sourceConfigTitle"),n.jsx(dt,{content:a("machine.providers.sourceConfigDesc"),size:12})]})}),n.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[n.jsxs("label",{className:"flex flex-col gap-1 text-2xs text-text-secondary",children:[n.jsx("span",{className:"font-medium text-text-primary",children:a("machine.providers.sourceMode")}),n.jsxs("select",{value:W,onChange:Z=>U(Z.target.value),className:"machine-input text-2xs",children:[n.jsx("option",{value:"normal",children:"normal"}),n.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),n.jsxs("label",{className:"flex flex-col gap-1 text-2xs text-text-secondary",children:[n.jsx("span",{className:"font-medium text-text-primary",children:a("machine.providers.explicitProviderDir")}),n.jsx("input",{type:"text",value:ae,onChange:Z=>be(Z.target.value),placeholder:a("machine.providers.providerDirPlaceholder"),className:"machine-input text-2xs"})]}),n.jsx("button",{onClick:()=>void me(),disabled:V,className:"machine-btn text-3xs bg-accent-primary/[0.08] border-accent-primary/20 text-accent-primary hover:bg-accent-primary/[0.14]",children:a(V?"machine.providers.applying":"machine.providers.applyReload")})]}),n.jsx("div",{className:"mt-3 flex flex-col gap-1.5","data-testid":"provider-source-paths",children:[{label:a("machine.providers.userRoot"),value:P==null?void 0:P.userDir},{label:a("machine.providers.upstreamRoot"),value:P==null?void 0:P.upstreamDir},{label:a("machine.providers.providerRoots"),value:(oe=P==null?void 0:P.providerRoots)==null?void 0:oe.join(" → ")}].map(Z=>n.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 text-3xs",children:[n.jsx("span",{className:"shrink-0 font-medium text-text-secondary",children:Z.label}),n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx("span",{className:"min-w-0 truncate font-mono text-text-muted",title:Z.value||void 0,children:Z.value||"—"}),Z.value&&n.jsx(Mg,{value:Z.value,label:a("common.copy")})]})]},Z.label))})]}),O&&ne.length===0?n.jsx("div",{className:"p-10 text-center text-text-muted",children:a("machine.providers.loadingSettings")}):fe.length===0?n.jsx(wn,{padding:"none",className:"px-4.5 py-8 text-center",children:n.jsx("div",{className:"text-xs text-text-muted",children:B==="all"?a("machine.providers.noProviders"):a("machine.providers.noFilteredProviders",{filter:B.toUpperCase()})})}):n.jsx("div",{className:"flex flex-col gap-1.5",children:fe.map(Z=>n.jsx(GM,{quota:r==null?void 0:r[Z.type],prov:Z,providerInfo:t.find(se=>se.type===Z.type),savingKey:N,onSetSetting:Se,onEnableToggle:he,onDetect:Ee,onResetCommand:Y,quotaAccountLabelEnabled:Oh.has(Z.type)?d:void 0,onQuotaAccountLabelToggle:Oh.has(Z.type)?je:void 0,quotaEnabled:ga.has(Z.type)?m[Z.type]??!0:void 0,onQuotaToggle:ga.has(Z.type)?z:void 0,pin:p[Z.type],onUpdate:()=>Je(Z.type),updating:C[Z.type]===!0,onRollbackUpdate:()=>Le(Z.type),showAdvanced:J},Z.type))}),H&&n.jsx(EM,{providerType:H,displayName:((Ie=ne.find(Z=>Z.type===H))==null?void 0:Ie.displayName)||H,supportsQuota:ga.has(H),quotaInstallsClaudeStatusline:H==="claude-cli",onCancel:()=>q(null),onConfirm:Z=>{pe(H,Z)}})]})}const XM=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function ZM({count:e,since:t,category:s}){return{count:e,since:t,...s==="all"?{}:{category:s}}}function eR(e,t){return t==="all"?e:e.filter(s=>s.category===t)}function tR(e){return e.trim().toLowerCase()}function Hi(e,t){const s=tR(t);return s?e.some(r=>String(r??"").toLowerCase().includes(s)):!0}function Xd(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Lr(e,t=220){const s=Xd(e);return s?s.length>t?`${s.slice(0,t)}…`:s:""}function nR(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 sR(e,t){return e.filter(s=>Hi([s.level,s.message],t))}function Fh(e){return`${e.timestamp}:${e.level}:${e.message}`}function rR(e,t,s=300){if(t.entries.length>0){const r=new Map;for(const i of e.entries)r.set(Fh(i),i);for(const i of t.entries)r.set(Fh(i),i);const o=Array.from(r.values()).sort((i,c)=>i.timestamp-c.timestamp).slice(-s),a=o.reduce((i,c)=>Math.max(i,Number(c.timestamp||0)),e.lastTs);return{entries:o,kind:"structured",rawText:"",lastTs:a}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function oR(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 aR(e,t){return e.split(`
|
|
79
|
-
`).map(s=>s.trimEnd()).filter(Boolean).filter(s=>Hi([s],t))}function iR(e,t){return e.filter(s=>Hi([s.level,s.category,s.stage,s.interactionId,Xd(s.payload)],t))}function lR(e,t){return e.filter(s=>Hi([s.kind,s.topic,s.interactionId,Xd(s.payload)],t))}function $h(e){return e==="warn"||e==="error"}function cR({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=>$h(o.level)).length+s.filter(o=>$h(o.level)).length}}function dR({daemonLogs:e,daemonRawLines:t,trace:s,webEvents:r}){const o=[];return e.length>0?o.push(["[daemon logs]",...e.map(a=>`${new Date(a.timestamp).toISOString()} ${a.level.toUpperCase()} ${a.message}`)].join(`
|
|
80
|
-
`)):t.length>0&&o.push(["[daemon logs]",...t].join(`
|
|
81
|
-
`)),s.length>0&&o.push(["[trace]",...s.map(a=>`${new Date(a.ts).toISOString()} ${a.level.toUpperCase()} ${a.category}.${a.stage} ${Lr(a.payload,500)}`.trim())].join(`
|
|
82
|
-
`)),r.length>0&&o.push(["[browser events]",...r.map(a=>`${new Date(a.ts).toISOString()} ${a.kind}${a.topic?` topic=${a.topic}`:""} ${Lr(a.payload,500)}`.trim())].join(`
|
|
83
|
-
`)),o.join(`
|
|
84
|
-
|
|
85
|
-
`)}function uR({machineId:e,sendDaemonCommand:t}){const[s,r]=l.useState([]),[o,a]=l.useState("empty"),[i,c]=l.useState(""),[d,u]=l.useState([]),[m,h]=l.useState([]),[p,g]=l.useState(null),[f,y]=l.useState(!0),[b,k]=l.useState("info"),[j,v]=l.useState("all"),[C,x]=l.useState(!0),[S,w]=l.useState(!0),[_,A]=l.useState(""),[O,L]=l.useState(""),[R,F]=l.useState(0),N=l.useRef(0),I=l.useRef(0),B=l.useRef(0),T=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),H=l.useRef([]),q=l.useCallback(()=>{const W={entries:[],kind:"empty",rawText:"",lastTs:0};T.current=W,I.current=0,r([]),c(""),a("empty"),x(!0)},[]),J=l.useCallback(()=>{H.current=[],B.current=0,u([]),w(!0)},[]),K=l.useCallback(W=>{W!==b&&(q(),k(W))},[b,q]),M=l.useCallback(W=>{v(U=>U===W?U:W)},[]),D=l.useCallback(()=>{q(),J(),h([]),g(null),A(""),L(""),Xs.clear()},[q,J]),P=l.useCallback(()=>{F(W=>W+1)},[]),$=l.useCallback(async()=>{if(!e)return;const W=N.current+1;N.current=W;const U=I.current,ae=B.current,[be,V]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:b,since:U}),t(e,"get_debug_trace",ZM({count:120,since:ae,category:j}))]);if(N.current===W){if(be.status==="fulfilled"){const we=be.value,ce=(we==null?void 0:we.result)||we,de=nR(ce),ne=rR(T.current,de,300);T.current=ne,I.current=ne.lastTs,x(!1),A((we==null?void 0:we.success)===!1?String((we==null?void 0:we.error)||"Could not load daemon logs"):""),a(ne.kind),c(ne.rawText),r(ne.entries)}else x(!1),A(be.reason instanceof Error?be.reason.message:"Could not load daemon logs");if(V.status==="fulfilled"){const we=V.value,ce=(we==null?void 0:we.result)||we;if((we==null?void 0:we.success)===!1)L(String((we==null?void 0:we.error)||"Could not load daemon trace"));else if(Array.isArray(ce==null?void 0:ce.trace)){const de=ce.trace,ne=oR(H.current,de,120),ee=de.reduce((ue,je)=>Math.max(ue,Number(je.ts||0)),ae);H.current=ne,ee>ae&&(B.current=ee),L(""),u(ne)}else L("");w(!1)}else w(!1),L(V.reason instanceof Error?V.reason.message:"Could not load daemon trace");h(Xs.list({limit:120})),g(Date.now())}},[b,e,t,j]);return l.useEffect(()=>{J()},[J,j]),l.useEffect(()=>{N.current+=1,q(),J(),h([]),g(null),A(""),L("")},[e,q,J]),l.useEffect(()=>{if(!e)return;if($(),!f)return()=>{N.current+=1};const W=setInterval(()=>{$()},3e3);return()=>{N.current+=1,clearInterval(W)}},[f,$,e,R]),{daemonLogs:s,daemonLogKind:o,daemonRawText:i,debugTrace:d,webEvents:m,lastUpdatedAt:p,autoRefresh:f,logLevel:b,traceCategory:j,daemonLoading:C,traceLoading:S,daemonFetchError:_,traceFetchError:O,setAutoRefresh:y,setLogLevel:K,setTraceCategory:M,refresh:P,clear:D}}function mR({daemonLoading:e,traceLoading:t,daemonFetchError:s,traceFetchError:r,daemonLogKind:o,daemonLogsCount:a,daemonRawLineCount:i,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:s?"error":e?"loading":a>0||i>0?"ok":"empty",detail:s||(o==="text"?`${i} raw file-fallback line(s)`:`${a} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:r?"error":t?"loading":c>0?"ok":"empty",detail:r||`${c} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function Hh(e){return e==="warn"||e==="error"}function hR(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 pR(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 Bh(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function fR(e){const t=Lr(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function gR(e){const t=Lr(e.payload,320),s=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${s} ${t}`:`${e.kind}${s}`}function bR({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:gR(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:fR(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:pR(a,i),severity:hR(a),message:a,raw:a})}),o.sort((a,i)=>a.ts!==i.ts?a.ts-i.ts:Bh(a.source)-Bh(i.source))}function xR(e){return`${e.source}:${e.severity}:${e.message}`}function yR(e){const t=e.filter(r=>Hh(r.severity)).sort((r,o)=>o.ts-r.ts),s=new Map;for(const r of e){if(!Hh(r.severity))continue;const o=xR(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 vR(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Wh(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",s=e.interactionId?` ix=${e.interactionId}`:"";return`${vR(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${s} ${e.message}`.trim()}function wR({events:e,summary:t,sources:s,maxTimelineEvents:r=80}){const o=[];o.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
86
|
-
`)),o.push(["[source status]",...s.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
|
|
87
|
-
`)),t.latestIssue&&o.push(["[latest issue]",Wh(t.latestIssue)].join(`
|
|
88
|
-
`)),t.repeatedPatterns.length>0&&o.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
|
|
89
|
-
`));const a=e.slice(-r);return o.push(["[timeline]",...a.length>0?a.map(Wh):["No diagnostic events captured."]].join(`
|
|
90
|
-
`)),o.join(`
|
|
91
|
-
|
|
92
|
-
`)}function SR(e,t){return t==="issues"?e.filter(s=>s.level==="warn"||s.level==="error"):t==="info"?e.filter(s=>s.level!=="debug"):e}function kR(e,t){return t==="issues"?e.filter(s=>s.level==="warn"||s.level==="error"):t==="info"?e.filter(s=>s.level!=="debug"):e}function jR({daemonLogs:e,daemonRawText:t,daemonLogKind:s,debugTrace:r,webEvents:o,traceCategory:a,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:u,daemonFetchError:m,traceFetchError:h}){const p=eR(r,a),g=sR(e,c),f=aR(t,c),y=iR(p,c),b=lR(o,c),k=SR(g,i),j=i==="all"?f:[],v=kR(y,i),C=i==="issues"?[]:b,x=cR({daemonLogs:g,daemonRawLines:f,trace:y,webEvents:b}),S=bR({daemonLogs:k,daemonRawLines:j,trace:v,webEvents:C}),w=yR(S),_=mR({daemonLoading:d,traceLoading:u,daemonFetchError:m,traceFetchError:h,daemonLogKind:s,daemonLogsCount:g.length,daemonRawLineCount:f.length,traceCount:y.length,webEventCount:b.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:f,filteredTraceEntries:y,filteredWebEvents:b,visibleDaemonLogs:k,visibleDaemonRawLines:j,visibleTraceEntries:v,visibleWebEvents:C,quickFilterCounts:x,diagnosticEvents:S,diagnosticsSummary:w,sourceStates:_}}function NR(e,t){return e?yi(e,{seconds:!0}):t("machine.logsTabSections.notYetLoaded")}function Zb(e,t){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?t("machine.logsTabSections.rawFile"):yi(e,{seconds:!0})}function Oc(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 Pl(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 Zd(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 CR({event:e}){const{t}=ve("common");return n.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Oc(e.severity)}`,children:[n.jsxs("div",{className:"flex gap-2 text-3xs text-text-muted flex-wrap",children:[n.jsx("span",{children:Zb(e.ts,t)}),n.jsx("span",{children:e.severity.toUpperCase()}),n.jsx("span",{children:Zd(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 _R({quickFilter:e,quickFilterCounts:t,searchQuery:s,autoRefresh:r,onQuickFilterChange:o,onSearchQueryChange:a,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:u,onClear:m}){const{t:h}=ve("common");return n.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx("span",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider mr-1",children:h("machine.logsTabSections.view")}),n.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:h("machine.logsTabSections.filterInfo",{count:t.info})},{id:"issues",label:h("machine.logsTabSections.filterIssues",{count:t.issues})},{id:"all",label:h("machine.logsTabSections.filterAll",{count:t.all})}].map(p=>n.jsx("button",{type:"button",onClick:()=>o(p.id),className:`rounded-md px-2.5 py-1 text-2xs transition-colors ${e===p.id?"bg-accent-primary/15 text-accent-primary border border-accent-primary/30":"text-text-secondary hover:text-text-primary"}`,children:p.label},p.id))}),n.jsx("input",{value:s,onChange:p=>a(p.target.value),placeholder:h("machine.logsTabSections.searchPlaceholder"),className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-primary placeholder:text-text-muted"})]}),n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx("button",{onClick:i,className:"machine-btn",children:h("machine.logsTabSections.copyDiagnostics")}),n.jsx("button",{onClick:c,className:"machine-btn",children:h("machine.logsTabSections.copyVisible")}),n.jsx("button",{onClick:d,className:`machine-btn ${r?"text-green-500 border-green-500/30":""}`,children:h(r?"machine.logsTabSections.pause":"machine.logsTabSections.resume")}),n.jsx("button",{onClick:u,className:"machine-btn",children:h("machine.logsTabSections.refresh")}),n.jsx("button",{onClick:m,className:"machine-btn",children:h("machine.logsTabSections.clear")})]})]})}function AR({logLevel:e,traceCategory:t,onLogLevelChange:s,onTraceCategoryChange:r}){const{t:o}=ve("common");return n.jsx(wn,{padding:"sm",children:n.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx("span",{className:"text-3xs uppercase tracking-wider text-text-muted font-semibold",children:o("machine.logsTabSections.advancedSourceScope")}),["debug","info","warn","error"].map(a=>n.jsx("button",{onClick:()=>s(a),className:`machine-btn text-3xs px-2 py-0.5 ${e===a?"bg-accent-primary/15 border-accent-primary/40 text-accent-primary":""}`,children:o("machine.logsTabSections.daemonLevelPlus",{level:a.toUpperCase()})},a))]}),n.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:XM.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 TR({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:s,searchQuery:r,lastUpdatedAt:o,autoRefresh:a,daemonFetchError:i,traceFetchError:c}){var h,p;const{t:d}=ve("common"),u=((h=e.latestIssue)==null?void 0:h.severity)==="error"?"danger":((p=e.latestIssue)==null?void 0:p.severity)==="warn"?"warning":"good",m=i||c?"danger":a?"good":"neutral";return n.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[n.jsxs("div",{className:`rounded-xl border p-3 ${Pl(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 ${Pl(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:[Zd(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:Zb(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 ${Pl(m)}`,children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted mb-2",children:d("machine.logsTabSections.sourceStatus")}),n.jsx("div",{className:"text-xxs text-text-primary font-medium",children:d(i||c?"machine.logsTabSections.needsAttention":a?"machine.logsTabSections.livePolling":"machine.logsTabSections.paused")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:d("machine.logsTabSections.lastUpdate",{time:NR(o,d)})}),n.jsx("div",{className:"text-3xs text-text-muted mt-2 space-y-1",children:s.map(g=>n.jsxs("div",{children:[g.label,": ",g.status]},g.id))})]})]})}function IR({patterns:e}){const{t}=ve("common");return e.length===0?null:n.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted mb-2",children:t("machine.logsTabSections.repeatedIssuePatterns")}),n.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(s=>n.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[n.jsxs("div",{className:"text-xs text-text-primary font-medium",children:[s.count,"× ",s.severity.toUpperCase()," · ",Zd(s.source,t)]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1 line-clamp-2",children:s.message})]},s.key))})]})}function MR({streams:e,sectionsOpen:t,setSectionsOpen:s,diagnosticEvents:r,visibleDaemonLogs:o,visibleDaemonRawLines:a,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:d,searchQuery:u}){const{t:m}=ve("common");return n.jsxs("div",{className:"grid gap-3",children:[n.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(h=>({...h,timeline:!h.timeline})),children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted",children:m("machine.logsTabSections.unifiedTimeline")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:m("machine.logsTabSections.visibleDiagnosticEvents",{count:r.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.timeline?m("machine.logsTabSections.hide"):m("machine.logsTabSections.show")})]}),t.timeline&&n.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-2xs leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.loadingDiagnostics")}),(e.daemonFetchError||e.traceFetchError)&&r.length===0&&n.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&n.jsx("div",{children:m("machine.logsTabSections.daemonLogsError",{error:e.daemonFetchError})}),e.traceFetchError&&n.jsx("div",{children:m("machine.logsTabSections.daemonTraceError",{error:e.traceFetchError})})]}),!e.daemonLoading&&!e.traceLoading&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:m("machine.logsTabSections.noDiagnosticsMatch")}),r.map(h=>n.jsx(CR,{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 ${Oc(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 ${Oc(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:Lr(h.payload,360)||m("machine.logsTabSections.noPayload")})]},h.id))]})]}),n.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[n.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(h=>({...h,web:!h.web})),children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-muted",children:m("machine.logsTabSections.rawSourceBrowserEvents")}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1",children:m("machine.logsTabSections.visibleBrowserEvents",{count:c.length})})]}),n.jsx("div",{className:"text-2xs text-text-muted",children:t.web?m("machine.logsTabSections.hide"):m("machine.logsTabSections.show")})]}),t.web&&n.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-2xs leading-relaxed",children:[c.length===0&&n.jsx("div",{className:"p-6 text-center text-text-muted",children:u.trim()?m("machine.logsTabSections.noBrowserEventsMatchSearch"):m("machine.logsTabSections.noBrowserEventsYet")}),c.map(h=>n.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[n.jsxs("div",{className:"flex gap-2 text-3xs text-text-muted flex-wrap",children:[n.jsx("span",{children:new Date(h.ts).toLocaleTimeString()}),n.jsx("span",{children:h.kind}),h.topic&&n.jsxs("span",{children:["topic=",h.topic]}),h.interactionId&&n.jsxs("span",{children:["ix=",h.interactionId]})]}),n.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Lr(h.payload,360)||m("machine.logsTabSections.noPayload")})]},h.id))]})]})]})}function RR({machineId:e,sendDaemonCommand:t}){const s=uR({machineId:e,sendDaemonCommand:t}),[r,o]=l.useState("info"),[a,i]=l.useState(""),[c,d]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),u=l.useRef(null),m=l.useRef(!1),h=l.useMemo(()=>jR({daemonLogs:s.daemonLogs,daemonRawText:s.daemonRawText,daemonLogKind:s.daemonLogKind,debugTrace:s.debugTrace,webEvents:s.webEvents,traceCategory:s.traceCategory,quickFilter:r,searchQuery:a,daemonLoading:s.daemonLoading,traceLoading:s.traceLoading,daemonFetchError:s.daemonFetchError,traceFetchError:s.traceFetchError}),[r,a,s.daemonFetchError,s.daemonLoading,s.daemonLogKind,s.daemonLogs,s.daemonRawText,s.debugTrace,s.traceCategory,s.traceFetchError,s.traceLoading,s.webEvents]);l.useEffect(()=>{if(s.autoRefresh&&h.diagnosticEvents.length>0){const f=m.current?"smooth":"instant";setTimeout(()=>{var y;(y=u.current)==null||y.scrollIntoView({behavior:f}),m.current=!0},50)}},[h.diagnosticEvents.length,s.autoRefresh]);const p=l.useCallback(async()=>{var y;const f=dR({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!f.trim()){ct.showToast("No visible logs to copy.","info");return}try{await((y=navigator.clipboard)==null?void 0:y.writeText(f)),ct.showToast("Copied visible logs to clipboard.","success")}catch(b){ct.showToast(b instanceof Error?b.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),g=l.useCallback(async()=>{var y;const f=wR({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((y=navigator.clipboard)==null?void 0:y.writeText(f)),ct.showToast("Copied diagnostic bundle to clipboard.","success")}catch(b){ct.showToast(b instanceof Error?b.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return n.jsxs("div",{className:"space-y-4",children:[n.jsx(_R,{quickFilter:r,quickFilterCounts:h.quickFilterCounts,searchQuery:a,autoRefresh:s.autoRefresh,onQuickFilterChange:o,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{p()},onToggleAutoRefresh:()=>s.setAutoRefresh(f=>!f),onRefresh:s.refresh,onClear:s.clear}),n.jsx(AR,{logLevel:s.logLevel,traceCategory:s.traceCategory,onLogLevelChange:s.setLogLevel,onTraceCategoryChange:s.setTraceCategory}),n.jsx(TR,{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(IR,{patterns:h.diagnosticsSummary.repeatedPatterns}),n.jsx(MR,{streams:s,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:r,searchQuery:a}),n.jsx("div",{ref:u})]})}function PR(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 ex(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 LR(e){var o;const t=[],s=[],r=[];for(const a of e||[]){const i=String((a==null?void 0:a.lifecycle)||"").trim(),c=ex((a==null?void 0:a.meta)||void 0),d=((o=a==null?void 0:a.meta)==null?void 0:o.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(a):(i==="stopped"||i==="failed")&&(d||c)?s.push(a):r.push(a)}return{liveRuntimes:t,recoverySnapshots:s,inactiveRecords:r}}function ER(e,t){return e==="live"?t?t("sessionHostSurface.attach"):"Attach":e==="recovery"?t?t("sessionHostSurface.recover"):"Recover":t?t("sessionHostSurface.restart"):"Restart"}function Ll(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 DR={starting:"sessionHostSurface.lifecycleStarting",running:"sessionHostSurface.lifecycleRunning",stopping:"sessionHostSurface.lifecycleStopping",stopped:"sessionHostSurface.lifecycleStopped",failed:"sessionHostSurface.lifecycleFailed",interrupted:"sessionHostSurface.lifecycleInterrupted"},OR={starting:"Starting",running:"Running",stopping:"Stopping",stopped:"Stopped",failed:"Failed",interrupted:"Interrupted"};function Uh(e,t){const s=DR[e];return s?t?t(s):OR[e]??e:e}function El(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Dl(e){return yi(e,{seconds:!0})||"—"}function Kh(e){return Ba(e)||"—"}function FR(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 $R(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function HR(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 BR(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 WR({machineId:e,cliSessions:t,sendDaemonCommand:s}){const{t:r}=ve("common"),[o,a]=l.useState(""),[i,c]=l.useState(null),{confirm:d,confirmDialog:u}=Fr(),[m,h]=l.useState(!1),p=fT(e,{enabled:!!e,includeSessions:!0,limit:im,intervalMs:XN}),g=p.diagnostics,f=p.loading,y=p.applyDiagnostics,b=l.useMemo(()=>PR({diagnostics:g,loading:f,refreshing:m,error:o,t:r}),[g,f,m,o,r]),k=l.useMemo(()=>new Map(t.map(N=>[N.sessionId||N.id,N])),[t]),j=l.useCallback(async()=>{if(e){h(!0);try{const N=await s(e,"session_host_get_diagnostics",{includeSessions:!0,limit:im}),I=El(N);if(!(I!=null&&I.success))throw new Error((I==null?void 0:I.error)||r("sessionHost.diagnosticsFailed"));y(I.diagnostics||I.result||null),a("")}catch(N){const I=N instanceof Error?N.message:r("sessionHost.diagnosticsFailed");a(I)}finally{h(!1)}}},[y,e,s,r]);l.useEffect(()=>{!e||g||f||m||j()},[g,f,e,j,m]);const v=l.useCallback(async(N,I)=>{const B=`${N}:${I.sessionId}`;if(!(N==="session_host_stop_session"&&!await d({title:r("sessionHost.stopConfirmTitle",{name:I.displayName}),description:r("sessionHost.stopConfirmDescription"),confirmLabel:r("sessionHost.stop"),tone:"danger"}))){c(B);try{const T=await s(e,N,{sessionId:I.sessionId}),H=El(T);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||r("sessionHost.actionFailed"));const q=N==="session_host_resume_session"?"sessionHost.toastResumed":N==="session_host_restart_session"?"sessionHost.toastRestarted":"sessionHost.toastStopped";ct.showToast(r(q,{name:I.displayName}),"success"),await j()}catch(T){const H=T instanceof Error?T.message:r("sessionHost.actionFailed");ct.showToast(H,"warning"),a(H)}finally{c(T=>T===B?null:T)}}},[d,e,j,s,r]),C=l.useCallback(async()=>{if(await d({title:r("sessionHost.pruneConfirmTitle"),description:r("sessionHost.pruneConfirmDescription"),confirmLabel:r("sessionHost.prune"),tone:"danger"})){c("session_host_prune_duplicate_sessions");try{const I=await s(e,"session_host_prune_duplicate_sessions",{}),B=El(I);if(!(B!=null&&B.success))throw new Error((B==null?void 0:B.error)||r("sessionHost.pruneFailed"));const T=B.result||{},H=Array.isArray(T.prunedSessionIds)?T.prunedSessionIds.length:0,q=typeof T.duplicateGroupCount=="number"?T.duplicateGroupCount:0;ct.showToast(r("sessionHost.toastPruned",{pruned:H,groups:q}),"success"),await j()}catch(I){const B=I instanceof Error?I.message:r("sessionHost.pruneFailed");ct.showToast(B,"warning"),a(B)}finally{c(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[d,e,j,s,r]),x=l.useMemo(()=>[...(g==null?void 0:g.sessions)||[]].sort((N,I)=>(I.lastActivityAt||0)-(N.lastActivityAt||0)),[g==null?void 0:g.sessions]),S=l.useMemo(()=>g!=null&&g.liveRuntimes||g!=null&&g.recoverySnapshots||g!=null&&g.inactiveRecords?{liveRuntimes:(g==null?void 0:g.liveRuntimes)||[],recoverySnapshots:(g==null?void 0:g.recoverySnapshots)||[],inactiveRecords:(g==null?void 0:g.inactiveRecords)||[]}:LR(x),[g==null?void 0:g.inactiveRecords,g==null?void 0:g.liveRuntimes,g==null?void 0:g.recoverySnapshots,x]),w=S.liveRuntimes,_=S.recoverySnapshots,A=S.inactiveRecords,O=l.useMemo(()=>BR(w),[w]),L=l.useMemo(()=>[...(g==null?void 0:g.recentTransitions)||[]].slice(-6).reverse(),[g==null?void 0:g.recentTransitions]),R=l.useMemo(()=>[...(g==null?void 0:g.recentLogs)||[]].reverse().find(N=>N.level==="warn"||N.level==="error")||null,[g==null?void 0:g.recentLogs]),F=(N,I)=>{var W;const B=i===`session_host_resume_session:${N.sessionId}`,T=i===`session_host_restart_session:${N.sessionId}`,H=i===`session_host_stop_session:${N.sessionId}`,q=ex(N.meta,r),J=k.get(N.sessionId),K=r("sessionHost.clientsCount",{count:N.attachedClients.length}),M=r(I==="recovery"?"sessionHost.recover":"sessionHost.resume"),D=r(I==="recovery"?"sessionHost.recovering":"sessionHost.resuming"),P=ER(I,r),$=Uh(N.lifecycle,r);return n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("div",{className:"font-medium text-xxs text-text-primary",children:N.displayName||(J==null?void 0:J.cliName)||N.providerType}),n.jsx("span",{className:`px-2 py-0.5 rounded-md text-3xs font-semibold ${HR(N.lifecycle)}`,children:$}),q&&n.jsx("span",{className:"px-2 py-0.5 rounded-md text-3xs font-semibold bg-sky-500/[0.08] text-sky-300",children:q})]}),n.jsx("div",{className:"text-2xs text-text-secondary mt-1 flex flex-wrap gap-2",children:n.jsx(tn,{content:[N.runtimeKey,N.osPid?`pid ${N.osPid}`:""].filter(Boolean).join(" · "),children:n.jsx("span",{className:"text-text-primary/90",children:N.workspaceLabel||(J==null?void 0:J.runtimeWorkspaceLabel)||N.workspace||r("sessionHost.noWorkspace")})})}),n.jsxs("div",{className:"text-3xs text-text-secondary mt-1 flex flex-wrap gap-2",children:[n.jsx("span",{className:((W=N.writeOwner)==null?void 0:W.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:$R(N.writeOwner)}),n.jsx("span",{className:"text-text-muted",children:"·"}),n.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[n.jsx(Vv,{size:11})," ",K]}),n.jsx("span",{className:"text-text-muted",children:"·"}),n.jsx("span",{className:"text-text-primary/85",children:r("sessionHost.activeAgo",{time:Kh(N.lastActivityAt)})}),n.jsx("span",{className:"text-text-muted",children:"·"}),n.jsx("span",{className:"text-sky-200",children:r("sessionHost.nextAction",{action:P})})]})]}),n.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[I==="recovery"&&(N.lifecycle==="interrupted"||N.lifecycle==="failed"||N.lifecycle==="stopped")&&n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1",disabled:!!i,onClick:()=>{v("session_host_resume_session",N)},children:B?D:M}),n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1",disabled:!!i,onClick:()=>{v("session_host_restart_session",N)},children:r(T?"sessionHost.restarting":"sessionHost.restart")}),I==="live"&&(N.lifecycle==="running"||N.lifecycle==="starting"||N.lifecycle==="interrupted")&&n.jsx("button",{type:"button",className:"machine-btn text-3xs px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{v("session_host_stop_session",N)},children:r(H?"sessionHost.stopping":"sessionHost.stop")})]})]})},N.sessionId)};return n.jsxs(wn,{padding:"lg",className:"mb-5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[n.jsx(Ks,{size:14})," ",r("sessionHost.title")]}),n.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Y1()})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[O>0&&n.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{C()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?r("sessionHost.pruning"):r("sessionHost.pruneDuplicatesCount",{count:O})}),n.jsx("span",{className:`px-2 py-1 rounded-md text-3xs font-semibold ${b.toneClass}`,children:b.label}),n.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{j()},disabled:f||m,children:[n.jsx(Or,{size:13}),r(f||m?"sessionHost.refreshing":"sessionHost.refresh")]})]})]}),o&&!g&&n.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-xs text-amber-200 mb-3",children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(an,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),n.jsxs("div",{children:[n.jsx("div",{className:"font-medium text-amber-100",children:r("sessionHost.diagnosticsAttention")}),n.jsx("div",{className:"text-amber-200/90 mt-1",children:o})]})]})}),g&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-secondary",children:r("sessionHost.statLive")}),n.jsx("div",{className:"text-lg font-semibold text-text-primary mt-1",children:g.runtimeCount})]}),n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-secondary",children:r("sessionHost.statRecovery")}),n.jsx("div",{className:"text-lg font-semibold text-text-primary mt-1",children:_.length})]}),n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-secondary",children:r("sessionHost.statRequests")}),n.jsx("div",{className:"text-lg font-semibold text-text-primary mt-1",children:g.recentRequests.length})]}),n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[n.jsx("div",{className:"text-3xs uppercase tracking-wider text-text-secondary",children:r("sessionHost.statStarted")}),n.jsx("div",{className:"text-xs font-medium text-text-primary mt-1",children:Kh(g.hostStartedAt)}),n.jsx("div",{className:"text-3xs text-text-secondary mt-0.5",children:Dl(g.hostStartedAt)})]})]}),R&&n.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-2xs text-text-secondary mb-4",children:[n.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[n.jsx(an,{size:13})," ",r("sessionHost.latestWarning")]}),n.jsx("div",{className:"text-text-primary leading-relaxed",children:R.message}),n.jsxs("div",{className:"text-3xs text-text-secondary mt-1",children:[Dl(R.timestamp),R.sessionId?` · ${R.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(od,{size:14})," ",r("sessionHost.liveTitle")]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2.5",children:Ll("live",r)}),w.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:w.map(N=>F(N,"live"))})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[n.jsx(Ks,{size:14})," ",r("sessionHost.recoveryTitle")]}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2.5",children:Ll("recovery",r)}),_.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:_.map(N=>F(N,"recovery"))})]}),A.length>0&&n.jsxs("div",{children:[n.jsx("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:r("sessionHost.inactiveTitle")}),n.jsx("div",{className:"text-2xs text-text-secondary mb-2.5",children:Ll("inactive",r)}),n.jsx("div",{className:"space-y-2 opacity-85",children:A.map(N=>F(N,"inactive"))})]})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-2xs text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:r("sessionHost.recentActivity")}),L.length===0?n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-xs text-text-secondary",children:r("sessionHost.transitionsEmpty")}):n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:L.map(N=>{var B;const I=x.find(T=>T.sessionId===N.sessionId);return n.jsxs("div",{className:"px-3.5 py-2.5 text-2xs flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-text-primary font-medium",children:(I==null?void 0:I.displayName)||((B=k.get(N.sessionId))==null?void 0:B.cliName)||N.sessionId}),n.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[FR(N.action,r),N.lifecycle?` · ${Uh(N.lifecycle,r)}`:"",(N.detail||N.error)&&n.jsx(dt,{content:[N.detail,N.error].filter(Boolean).join(`
|
|
93
|
-
`),size:11,className:"ml-1"})]})]}),n.jsx("div",{className:`shrink-0 text-3xs ${N.success===!1?"text-red-300":"text-text-secondary"}`,children:Dl(N.timestamp)})]},`${N.sessionId}:${N.timestamp}:${N.action}`)})})]}),n.jsx(_d,{className:"mt-3",rows:[{label:r("sessionHost.endpointLabel"),value:g.endpoint||null},{label:r("sessionHost.lastErrorLabel"),value:o||null,copyable:!1}]})]}),u]})}function UR({machine:e,launchPick:t,actions:s}){const{t:r}=ve("common"),{runLaunchCliCore:o,setLaunchPick:a}=s;return l.useEffect(()=>{const i=c=>{c.key==="Escape"&&a(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[a]),n.jsx(es,{children:n.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",onClick:()=>a(null),children:n.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",onClick:i=>i.stopPropagation(),children:[n.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:r("machine.launchPick.title")}),n.jsx("p",{className:"text-2xs text-text-muted m-0 mb-4",children:r("machine.launchPick.description")}),n.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?n.jsx("span",{className:"text-2xs text-text-muted",children:r("machine.launchPick.empty")}):(e.workspaces||[]).map(i=>n.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-accent-primary/10 transition-colors",onClick:()=>{a(null),o({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[n.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),n.jsx("span",{className:"text-3xs text-text-muted font-mono truncate block",children:i.path})]},i.id))}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsx("button",{type:"button",className:"machine-btn text-2xs flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),o({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.defaultWorkspace")}),n.jsx("button",{type:"button",className:"machine-btn text-2xs flex-1 min-w-[120px]",onClick:()=>{a(null),o({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.homeDirectory")}),n.jsx("button",{type:"button",className:"machine-btn text-2xs flex-1 min-w-[80px]",onClick:()=>a(null),children:r("common.cancel")})]})]})})})}function KR(e,t){const s=t2(e),r=Hs(e,t),o=Kd(e,r),a=Ra(e,r),i=xb(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 Ol({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 Fl({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 qR({machineEntry:e,providers:t,recentLaunches:s,currentConversations:r,onUpgradeDaemon:o,onOpenRecent:a,onOpenConversation:i}){const{t:c}=ve("common"),d=r.slice(0,6),u=s.slice(0,4),h=KR(e,"1.0.59"),p=h.visible?[c(h.descriptionKey),h.targetVersion?h.channel?c("machine.commandCenter.updateTargetWithChannel",{version:h.targetVersion,channel:c(`machine.commandCenter.updateChannel.${h.channel}`)}):c("machine.commandCenter.updateTarget",{version:h.targetVersion}):""].filter(Boolean).join(`
|
|
94
|
-
`):"";return n.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(Ol,{icon:n.jsx(Jn,{size:13}),children:c("machine.commandCenter.currentChats")}),n.jsx(Fl,{children:n.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(g=>{const f=Rc(g);return n.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(g),children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:Ot(g)}),f>0&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:xi(f)})]}),n.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Oo(g)})]},g.tabKey)})})})]}),u.length>0&&n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(Ol,{icon:n.jsx(rd,{size:13}),children:c("machine.commandCenter.recentLaunches")}),n.jsx(Fl,{children:n.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(g=>{const{metaText:f,updatedLabel:y}=Tb(g,c);return n.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>a(g),children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:g.label}),y&&n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:y})]}),n.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:f})]},g.id)})})})]}),h.visible&&h.showButton&&n.jsxs("div",{className:"flex flex-col gap-2","data-testid":"daemon-update-card",children:[n.jsx(Ol,{icon:n.jsx(an,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),n.jsx(Fl,{className:"border-amber-500/20 bg-amber-500/5",children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsxs("div",{className:"flex items-center gap-1 text-sm font-semibold text-text-primary",children:[c(h.titleKey),n.jsx(dt,{content:p})]}),n.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:o,children:[n.jsx(Or,{size:13}),n.jsx("span",{className:"text-sm font-medium",children:h.targetVersion?c("machine.commandCenter.updateToVersion",{version:h.targetVersion}):c("machine.commandCenter.updateDaemon")})]})]})})]}),h.visible&&!h.showButton&&n.jsx("div",{"data-testid":"daemon-update-chip",children:n.jsx(tn,{content:p,children:n.jsx("span",{className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-2xs font-medium ${h.tone==="good"?"border-emerald-500/20 bg-emerald-500/5 text-emerald-400":"border-border-subtle bg-bg-glass text-text-secondary"}`,children:h.tone==="good"?c("machine.commandCenter.upToDate"):c("machine.commandCenter.updateStatusUnknown")})})})]})}function Fc(e){return e.trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function zR(e,t){return t.has(Fc(e))}function GR({displayLabel:e,path:t,busy:s,onSave:r}){const{t:o}=ve("common"),[a,i]=l.useState(!1),[c,d]=l.useState(e),[u,m]=l.useState(!1),h=l.useRef(null);l.useEffect(()=>{var y,b;a&&((y=h.current)==null||y.focus(),(b=h.current)==null||b.select())},[a]);const p=()=>{d(e),i(!0)},g=()=>{i(!1),d(e)},f=async()=>{m(!0);try{await r(t,c)&&i(!1)}finally{m(!1)}};return a?n.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[n.jsx("input",{ref:h,autoFocus:!0,value:c,maxLength:64,disabled:s||u,onChange:y=>d(y.target.value),onKeyDown:y=>{y.key==="Enter"&&f(),y.key==="Escape"&&g()},placeholder:o("machine.managedWorkspaces.renamePlaceholder"),"aria-label":o("machine.managedWorkspaces.rename"),className:"min-w-0 flex-1 px-1.5 py-0.5 rounded border border-accent/30 bg-bg-secondary text-text-primary text-2xs font-medium"}),n.jsx("button",{type:"button",title:o("machine.managedWorkspaces.saveName"),"aria-label":o("machine.managedWorkspaces.saveName"),className:"shrink-0 p-0.5 rounded text-green-400 hover:bg-green-500/15 transition-colors",disabled:s||u,onClick:()=>{f()},children:n.jsx(Er,{size:12})}),n.jsx("button",{type:"button",title:o("machine.managedWorkspaces.cancelRename"),"aria-label":o("machine.managedWorkspaces.cancelRename"),className:"shrink-0 p-0.5 rounded text-text-muted/60 hover:text-text-primary hover:bg-bg-glass-hover transition-colors",disabled:u,onClick:g,children:n.jsx(Bt,{size:12})})]}):n.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[n.jsx("div",{className:"font-medium text-text-primary truncate",children:e}),n.jsx("button",{type:"button",title:o("machine.managedWorkspaces.rename"),"aria-label":o("machine.managedWorkspaces.rename"),className:"shrink-0 p-0.5 rounded text-text-muted/60 hover:text-text-primary hover:bg-bg-glass-hover transition-colors",disabled:s,onClick:p,children:n.jsx(Jv,{size:12})})]})}function VR({machineId:e,machine:t,ideSessions:s,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:u,handleWorkspaceSetDefault:m,handleWorkspaceSetLabel:h}=a,{t:p}=ve("common"),g=rr(),f=Ad(),[y,b]=l.useState(!1),[k,j]=l.useState(()=>new Set),[v,C]=l.useState(null);l.useEffect(()=>{let T=!1;return(async()=>{try{let H=[];if(f!=null&&f.listMeshes)H=(await f.listMeshes(e)).map(q=>q.workspace);else{const q=await i(e,"list_meshes",{}),J=(q==null?void 0:q.result)??q;H=(Array.isArray(J==null?void 0:J.meshes)?J.meshes:[]).map(M=>{var D;return Array.isArray(M==null?void 0:M.nodes)&&M.nodes.length>0?String(((D=M.nodes[0])==null?void 0:D.workspace)||""):null})}if(T)return;j(new Set(H.filter(q=>!!q).map(Fc)))}catch{}})(),()=>{T=!0}},[e,f,i]);const x=l.useCallback(T=>{g("/dashboard",{state:{openNewSession:{machineId:e,workspaceId:T}}})},[e,g]),S=l.useCallback((T,H)=>{g("/dashboard",{state:{openNewSession:{machineId:e,workspaceId:T,mode:"mesh",meshWorkspacePath:H}}})},[e,g]),[w,_]=l.useState(""),[A,O]=l.useState([]),[L,R]=l.useState(!1),[F,N]=l.useState(""),I=l.useCallback(async T=>{R(!0),N("");try{const H=await Gd(i,e,T);_(H.path),O(H.directories)}catch(H){N(H instanceof Error?H.message:"Could not load folder")}finally{R(!1)}},[e,i]),B=l.useCallback(()=>{b(!0);const T=[...s.map(q=>q.workspace),...r.map(q=>q.workspace),...o.map(q=>q.workspace)],H=zd(t.platform,qd(T,t.defaultWorkspacePath,(t.workspaces||[]).map(q=>q.path)));I(H)},[o,r,s,I,t.defaultWorkspacePath,t.platform,t.workspaces]);return n.jsxs(n.Fragment,{children:[n.jsxs(wn,{padding:"lg",className:"mb-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[n.jsxs("div",{className:"text-2xs text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[n.jsx(Zs,{size:14})," ",p("machine.managedWorkspaces.title")]}),n.jsxs("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:B,children:["+ ",p("machine.managedWorkspaces.addWorkspace")]})]}),(t.workspaces||[]).length===0?n.jsx("div",{className:"text-2xs text-text-muted py-4 text-center",children:p("machine.managedWorkspaces.empty",{button:p("machine.managedWorkspaces.addWorkspace")})}):n.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(T=>{const H=T.id===t.defaultWorkspaceId;return n.jsxs("li",{className:`flex items-start gap-2 text-2xs rounded-lg border px-2.5 py-2 transition-colors ${H?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[n.jsx("button",{type:"button",title:p(H?"machine.managedWorkspaces.unsetDefaultHint":"machine.managedWorkspaces.setDefaultHint"),disabled:c,onClick:()=>void m(H?null:T.id),className:`text-base leading-none shrink-0 transition-colors ${H?"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:[zR(T.path,k)?n.jsx(GR,{displayLabel:ja(T.path,T.label),path:T.path,busy:c,onSave:h}):n.jsx("div",{className:"font-medium text-text-primary truncate",children:ja(T.path,T.label)}),n.jsx("div",{className:"font-mono text-text-muted truncate text-3xs",title:T.path,children:T.path})]}),n.jsxs("button",{type:"button",title:p("machine.managedWorkspaces.newSession"),className:"btn shrink-0 flex items-center gap-1 bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-2 py-1 rounded transition-colors text-3xs",disabled:c,onClick:()=>x(T.id),children:[n.jsx(jo,{size:11}),p("machine.managedWorkspaces.newSessionShort")]}),k.has(Fc(T.path))&&n.jsxs("button",{type:"button",title:p("machine.managedWorkspaces.newMeshSession"),className:"btn shrink-0 flex items-center gap-1 bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-2 py-1 rounded transition-colors text-3xs",disabled:c,onClick:()=>S(T.id,T.path),children:[n.jsx(jo,{size:11}),p("machine.managedWorkspaces.newMeshSessionShort")]}),n.jsx("button",{type:"button",title:p("machine.managedWorkspaces.remove"),"aria-label":p("machine.managedWorkspaces.remove"),className:"shrink-0 p-1 rounded text-text-muted/60 hover:text-red-400 hover:bg-red-500/10 transition-colors",disabled:c,onClick:()=>C({id:T.id,label:ja(T.path,T.label)}),children:n.jsx(nw,{size:13})})]},T.id)})})]}),y&&n.jsx(Yd,{title:p("machine.managedWorkspaces.addWorkspace"),description:p("machine.managedWorkspaces.addDialogDescription"),currentPath:w,directories:A,busy:L,error:F,confirmLabel:p("machine.managedWorkspaces.addWorkspace"),onClose:()=>b(!1),onNavigate:T=>{I(T)},onConfirm:T=>{(async()=>{if(!T)return;await d(T)&&b(!1)})()}}),v&&n.jsx(sf,{title:p("machine.managedWorkspaces.removeConfirmTitle"),description:p("machine.managedWorkspaces.removeConfirmDescription",{label:v.label}),confirmLabel:p("machine.managedWorkspaces.remove"),tone:"danger",busy:c,onCancel:()=>C(null),onConfirm:()=>{const T=v;C(null),T&&u(T.id)}})]})}function YR({machine:e,machineId:t,ideSessions:s,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i}){const{t:c}=ve("common");return n.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[n.jsx("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:n.jsx("div",{className:"text-lg font-semibold text-text-primary",children:c("machine.managedWorkspaces.title")})}),i&&n.jsx(VR,{machineId:t,machine:e,ideSessions:s,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i})]})}function QR({onNicknameSynced:e}={}){var Ne,Be,Le,Je,Se,he,pe,Ee,Y,me,fe;const{t}=ve("common"),{id:s}=$x(),r=rr(),o=ui(),{sendCommand:a}=_t(),i=Hr(),c=lb(),d=yd(),u=d.ides||[],m=d.initialLoaded??!0,h=u.find(E=>E.id===s&&E.type==="adhdev-daemon"),p=u.some(E=>E.type==="adhdev-daemon"),g=s?(Ne=d.connectionRetryStatuses)==null?void 0:Ne[s]:void 0,f=!!(g!=null&&g.blocked),[y,b]=l.useState("workspace"),[k,j]=l.useState(null),[v,C]=l.useState(null),[,x]=l.useState("ide"),S=l.useRef(null),[w,_]=l.useState(null),A=l.useRef("__home__"),[O,L]=l.useState("__home__"),[R,F]=l.useState(!1),N=l.useRef(null);l.useEffect(()=>{!s||!h||!(!h.workspaces||!h.availableProviders||!h.detectedIdes||!h.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,h,s]);const I=l.useCallback(E=>{const oe=ud(E),Ie=oe==null?void 0:oe.providerChannelStaleness;Ie&&!Ie.error&&j({staleTypes:Array.isArray(Ie.staleTypes)?Ie.staleTypes:[],newTypes:Array.isArray(Ie.newTypes)?Ie.newTypes:[]})},[]);l.useEffect(()=>{if(!s||!h)return;let E=!1;return(async()=>{try{const oe=await a(s,"get_status_metadata");E||I(oe)}catch{}})(),()=>{E=!0}},[I,s,h==null?void 0:h.id,a]),l.useEffect(()=>{if(!s||!h||y!=="overview"&&y!=="providers")return;const E=h.machine;(typeof(E==null?void 0:E.cpus)!="number"||typeof(E==null?void 0:E.totalMem)!="number"||typeof(E==null?void 0:E.arch)!="string"||typeof(E==null?void 0:E.release)!="string"||!(E!=null&&E.quota))&&c(s,{minFreshMs:3e4}).catch(()=>{})},[y,c,h,s]),pT(s&&y==="overview"?[s]:[],{enabled:y==="overview",intervalMs:YN});const B=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},T=IM({machineId:s,registeredMachineId:(h==null?void 0:h.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:N});l.useEffect(()=>ct.onToast(oe=>{d.setToasts(Z=>{if(Z.some(Fe=>Fe.message===oe.message&&oe.timestamp-Fe.timestamp<3e3))return Z;const ye={id:oe.id,message:oe.message,type:oe.type,timestamp:oe.timestamp,targetKey:oe.targetKey,actions:oe.actions,details:oe.details};return[...Z.slice(-4),ye]});const Ie=oe.duration||5e3;setTimeout(()=>d.setToasts(Z=>Z.filter(se=>se.id!==oe.id||se.pinned)),Ie)}),[d]);const H=(h==null?void 0:h.availableProviders)||[],q={};for(const E of H)q[E.type]=E.icon;const J=h?{id:h.id,hostname:fd(h,{fallbackId:h.id}),platform:((Be=h.machine)==null?void 0:Be.platform)||"unknown",arch:((Le=h.machine)==null?void 0:Le.arch)||"",cpus:((Je=h.machine)==null?void 0:Je.cpus)||0,totalMem:((Se=h.machine)==null?void 0:Se.totalMem)||0,freeMem:(he=h.machine)==null?void 0:he.freeMem,availableMem:(pe=h.machine)==null?void 0:pe.availableMem,loadavg:(Ee=h.machine)==null?void 0:Ee.loadavg,uptime:(Y=h.machine)==null?void 0:Y.uptime,release:((me=h.machine)==null?void 0:me.release)||"",cdpConnected:!!h.cdpConnected,machineNickname:h.machineNickname||null,...(fe=h.machine)!=null&&fe.quota?{quota:h.machine.quota}:{},p2p:h.p2p?{screenshotActive:!1,...h.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:h.detectedIdes||[],workspaces:h.workspaces||[],defaultWorkspaceId:h.defaultWorkspaceId??h.activeWorkspaceId??null,defaultWorkspacePath:h.defaultWorkspacePath??h.activeWorkspacePath??null}:null,K=u.filter(E=>E.daemonId===s&&E.type!=="adhdev-daemon").filter(E=>!Co(E)&&!Nr(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,version:E.version||"",instanceId:E.instanceId||"",status:E.status,workspace:E.workspace||null,terminals:E.terminals||0,aiAgents:Zk(E.aiAgents||(E.agents||[]).map(oe=>({id:oe.name,name:oe.name,status:oe.status,version:oe.version}))),activeChat:E.activeChat||null,chats:E.chats||[],childSessions:E.childSessions||[],cdpConnected:E.cdpConnected||!1,daemonId:s,lastMessageAt:E.lastMessageAt})),M=u.filter(E=>E.daemonId===s&&Co(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,cliName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,mode:E.mode,runtimeKey:E.runtimeKey,runtimeDisplayName:E.runtimeDisplayName,runtimeWorkspaceLabel:E.runtimeWorkspaceLabel,runtimeWriteOwner:E.runtimeWriteOwner||null,runtimeAttachedClients:E.runtimeAttachedClients||[],daemonId:s,lastMessageAt:E.lastMessageAt})),D=u.filter(E=>E.daemonId===s&&Nr(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,acpName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,daemonId:s,lastMessageAt:E.lastMessageAt})),P=h?Tn(h,{fallbackId:s}):"",$="workspace",W=o.state,U=W==null?void 0:W.initialMachineTab,ae=W==null?void 0:W.initialWorkspaceCategory;W==null||W.initialWorkspaceId,W==null||W.initialWorkspacePath;const be=U==="session-host"?"hosted-runtimes":U==="logs"?"logs":null,V=U==="ides"||U==="clis"||U==="acps"?"workspace":be?"overview":U||$,we=U==="ides"?"ide":U==="clis"?"cli":U==="acps"?"acp":ae,ce=[...K.map(E=>{var oe;return{id:`ide:${E.type}:${E.workspace||""}`,label:((oe=E.activeChat)==null?void 0:oe.title)||E.type,kind:"ide",providerType:E.type,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:E.lastMessageAt||0}}),...M.map(E=>{var oe;return{id:`cli:${E.type}:${E.workspace||""}`,label:((oe=E.activeChat)==null?void 0:oe.title)||E.cliName,kind:"cli",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:E.lastMessageAt||0}}),...D.map(E=>{var oe;return{id:`acp:${E.type}:${E.workspace||""}`,label:((oe=E.activeChat)==null?void 0:oe.title)||E.acpName,kind:"acp",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:tr(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:E.lastMessageAt||0}})].sort((E,oe)=>(oe.lastLaunchedAt||0)-(E.lastLaunchedAt||0)),de=((h==null?void 0:h.recentLaunches)||[]).length>0?((h==null?void 0:h.recentLaunches)||[]).map(E=>({id:E.id,label:E.title||E.providerName||E.providerType,kind:E.kind,providerType:E.providerType,providerSessionId:E.providerSessionId,subtitle:tr(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace,summaryMetadata:E.summaryMetadata,lastLaunchedAt:E.lastLaunchedAt})):ce,ne=l.useMemo(()=>{var oe;const E=((oe=d.connectionStates)==null?void 0:oe[s||""])||void 0;return u.filter(Ie=>Ie.daemonId===s&&Ie.type!=="adhdev-daemon").flatMap(Ie=>Dd(Ie,{connectionStates:s&&E?{[s]:E}:void 0,defaultConnectionState:E})).filter(Ie=>!(Ie.transport==="pty"&&Ie.mode==="terminal")).sort((Ie,Z)=>Rc(Z)-Rc(Ie))},[u,d.connectionStates,s]),ee=l.useCallback(E=>{const oe=Sb(E);oe&&r(_o(oe))},[r]),ue=l.useCallback(()=>{S.current&&(F(!0),S.current().finally(()=>{S.current=null,F(!1),_(null)}))},[]),je=l.useCallback(E=>{if(!J)return;const{options:oe,selectedKey:Ie}=Ab({machine:J,currentWorkspacePath:E.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),Z=async()=>{x(E.kind),b("workspace")};if(S.current=async()=>{const se=oe.find(Me=>Me.key===A.current),ye=(se==null?void 0:se.workspacePath)??null,Fe=(se==null?void 0:se.workspaceId)??null;if(E.kind==="ide"&&E.providerType){await T.handleLaunchIde(E.providerType,ye?{workspace:ye}:void 0);return}if((E.kind==="cli"||E.kind==="acp")&&E.providerType){await T.runLaunchCliCore({cliType:E.providerType,dir:Fe?void 0:ye||"",workspaceId:Fe||void 0,model:E.kind==="acp"&&_f(E.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:E.providerSessionId});return}await Z()},A.current=Ie,oe.length<=1){const se=S.current;S.current=null,se==null||se().catch(ye=>ct.showErrorToast(t("machine.detail.relaunchFailed"),ye));return}L(Ie),_({title:E.kind==="ide"?Ja(t,"restart-ide",E.label):E.providerSessionId?Kg(t,E.label):Ja(t,"start-fresh",E.label),description:E.kind==="ide"?Xa(t,"restart-ide"):E.providerSessionId?qg(t):Xa(t,"start-fresh"),confirmLabel:E.kind==="ide"?Za(t,"restart-ide"):E.providerSessionId?Nc(t,!0):Za(t,"start-fresh"),busyLabel:E.kind==="ide"?ei(t,"restart-ide"):E.providerSessionId?Wg(t,!0):ei(t,"start-fresh"),workspaceOptions:oe,details:[{label:t("machine.detail.launchType"),value:E.kind.toUpperCase()},...E.providerType?[{label:t("machine.detail.launchProvider"),value:(()=>{const se=H.find(Fe=>Fe.type===E.providerType),ye=(se==null?void 0:se.displayName)||E.providerType;return n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Li,{type:E.providerType,label:ye,size:14}),ye]})})()}]:[]]})},[T,J,H,t]);if(l.useEffect(()=>{b(V)},[$,V,s]),l.useEffect(()=>{we&&x(we)},[we,s]),!J)return m?n.jsxs("div",{className:"p-10 text-center text-text-muted",children:[n.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),n.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),n.jsx("button",{onClick:B,className:"machine-btn-back",children:t("machine.detail.back")})]}):n.jsx("div",{className:"p-10 text-center text-text-muted",children:n.jsx("p",{children:t("machine.detail.loading")})});const X=!!k&&k.staleTypes.length+k.newTypes.length>0,G=K.length+M.length+D.length,z=[{key:"workspace",icon:n.jsx(Xn,{size:14}),label:t("machine.detail.tabSessions"),trailing:G>0?n.jsx("span",{className:`px-1.5 py-px rounded-full text-3xs ${y==="workspace"?"bg-accent-primary/20 text-accent-primary":"bg-bg-glass-hover text-text-muted"}`,children:G}):void 0},{key:"providers",icon:n.jsx(Dr,{size:14}),label:t("machine.detail.tabProviders"),trailing:X?n.jsx("span",{title:t("machine.detail.providerUpdatesAvailable"),"aria-label":t("machine.detail.providerUpdatesAvailable"),"data-testid":"providers-update-dot",className:"w-1.5 h-1.5 rounded-full bg-amber-400 ml-0.5 shrink-0"}):void 0},{key:"overview",icon:n.jsx(ew,{size:14}),label:t("machine.detail.tabSystem")}],ie=Af[J.platform]||J.platform;return n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-border-subtle",children:[n.jsx("div",{className:"flex items-center justify-between w-full",children:n.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[n.jsx("button",{onClick:B,className:"flex items-center justify-center w-8 h-8 rounded-full bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),n.jsxs("div",{className:"flex flex-col min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[T.editingNickname?n.jsxs("div",{className:"flex gap-1.5 items-center",children:[n.jsx("input",{autoFocus:!0,value:T.nicknameInput,onChange:E=>T.setNicknameInput(E.target.value),onKeyDown:E=>{E.key==="Enter"&&T.handleSaveNickname(),E.key==="Escape"&&T.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-accent/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),n.jsx("button",{onClick:T.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:t("machine.detail.save")}),n.jsx("button",{onClick:()=>T.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-bg-glass text-text-muted hover:bg-bg-glass-hover hover:text-text-primary text-sm font-medium transition-colors",children:t("machine.detail.cancel")})]}):n.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{T.setEditingNickname(!0),T.setNicknameInput(J.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:P}),f?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),d.retryConnection&&s&&n.jsx("button",{onClick:()=>d.retryConnection(s),className:"px-2.5 py-0.5 rounded text-2xs font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):null]}),n.jsx("div",{className:"mt-1 text-xs text-text-secondary","data-testid":"machine-detail-subtitle",children:[t(f?"machine.card.status.failed":"machine.card.status.online"),ie].filter(Boolean).join(" · ")})]})]})}),n.jsx(Od,{variant:"underline",tabs:z,activeKey:y,onSelect:E=>b(E),ariaLabel:t("machine.detail.tabsAriaLabel"),className:"mt-4 -mx-1 border-b-0 px-0 md:px-0",tabIdPrefix:"machine-tab"})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:n.jsx("div",{className:"max-w-7xl mx-auto h-full",children:n.jsxs("div",{className:"h-full",children:[y==="workspace"&&n.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[n.jsx(qR,{machineEntry:h,providers:H,recentLaunches:de,currentConversations:ne,onUpgradeDaemon:async()=>{const E=Ud(h);if(E)try{await a(s,"daemon_upgrade",E)}catch{}},onOpenRecent:je,onOpenConversation:ee}),n.jsx(YR,{machine:J,machineId:s,ideSessions:K,cliSessions:M,acpSessions:D,actions:T,sendDaemonCommand:a})]}),y==="providers"&&n.jsx(JM,{machineId:s,providers:H,sendDaemonCommand:a,quota:J.quota,onChannelStaleness:j}),y==="overview"&&n.jsx(PM,{machine:J,ideSessions:K,cliSessions:M,acpSessions:D,daemonVersion:h==null?void 0:h.version,initialDiagnostics:be,renderHostedRuntimes:()=>n.jsx(WR,{machineId:s,cliSessions:M,sendDaemonCommand:a}),renderLogs:()=>n.jsx(RR,{machineId:s,sendDaemonCommand:a})})]})})}),T.launchPick&&J&&n.jsx(UR,{machine:J,launchPick:T.launchPick,actions:T}),w&&n.jsx(Oi,{title:w.title,description:w.description,details:w.details,workspaceOptions:w.workspaceOptions,selectedWorkspaceKey:O,onWorkspaceChange:E=>{A.current=E,L(E)},confirmLabel:w.confirmLabel,busyLabel:w.busyLabel,busy:R,onConfirm:ue,onCancel:()=>{S.current=null,_(null)}}),v&&n.jsx(Qb,{daemonId:v.daemonId,workspace:v.workspace,onClose:()=>C(null)}),T.confirmDialog,n.jsx(zg,{toasts:d.toasts||[],onDismiss:E=>d.setToasts(oe=>oe.filter(Ie=>Ie.id!==E)),onClickToast:E=>{E.targetKey&&r(_o(E.targetKey))}}),n.jsx("style",{children:`
|
|
95
|
-
@keyframes toast-in {
|
|
96
|
-
from { opacity: 0; transform: translateX(40px); }
|
|
97
|
-
to { opacity: 1; transform: translateX(0); }
|
|
98
|
-
}
|
|
99
|
-
`})]})}const JR=new Set(["approvalAlert","noProgressAlert","noProgressThresholdSec","longGeneratingAlert","longGeneratingThresholdSec"]),XR=[{id:"approval",keys:["approvalAlert"]},{id:"noProgress",keys:["noProgressAlert","longGeneratingAlert"]}];function ZR(e){return e.filter(t=>JR.has(t.key))}function eP({machineId:e,children:t}){return n.jsx(dp,{to:`/machines/${e}`,state:{initialMachineTab:"providers"},className:"text-accent-primary hover:underline",children:t})}function tP({machineId:e,children:t}){return Hx()?n.jsx(eP,{machineId:e,children:t}):n.jsx("a",{href:`/machines/${e}`,className:"text-accent-primary hover:underline",children:t})}function nP({machines:e,onBrowserPrefChange:t,renderPushSection:s,initialLoaded:r=!0}){const{t:o}=ve("common"),[a,i]=lj(),{sendCommand:c}=_t(),[d,u]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission),[m,h]=l.useState({}),[p,g]=l.useState(!1),f=l.useMemo(()=>e.filter(x=>x.status==="online"),[e]);l.useEffect(()=>{const x=()=>{if(typeof window>"u"||!("Notification"in window)){u("unsupported");return}u(Notification.permission)};return x(),window.addEventListener("focus",x),document.addEventListener("visibilitychange",x),()=>{window.removeEventListener("focus",x),document.removeEventListener("visibilitychange",x)}},[]);const y=l.useCallback(async()=>{g(!0);const x={};for(const S of f)try{const w=await c(S.id,"get_provider_settings",{}),_=Jb(w);if(_){const A=Xb(_,S.providers||[],{filterSchema:ZR});A.length>0&&(x[S.id]=A)}}catch(w){console.warn("[Notifications] Failed to fetch settings from",S.id,w)}h(x),g(!1)},[f,c]);l.useEffect(()=>{f.length>0&&y()},[f.length]);const b=l.useMemo(()=>{const x=[];for(const[S,w]of Object.entries(m)){const _=f.find(O=>O.id===S),A=_?Tn(_,{fallbackId:S}):S.slice(0,8);for(const O of w)x.push({...O,machineId:S,machineLabel:A})}return x},[m,f]),k=l.useCallback(async(x,S,w,_)=>{h(A=>{const O={...A};return O[x]=(O[x]||[]).map(L=>L.type===S?{...L,values:{...L.values,[w]:_}}:L),O});try{await c(x,"set_provider_setting",{providerType:S,key:w,value:_})}catch{}},[c]),j=l.useMemo(()=>XR.map(x=>{const S=b.map(_=>({entry:_,key:x.keys.find(A=>_.schema.some(O=>O.key===A))})).filter(_=>!!_.key),w=S.filter(({entry:_,key:A})=>{var O;return!!(_.values[A]??((O=_.schema.find(L=>L.key===A))==null?void 0:O.default))}).length;return{id:x.id,targets:S,total:S.length,onCount:w}}).filter(x=>x.total>0),[b]),v=l.useCallback(async(x,S)=>{const w=j.find(_=>_.id===x);if(w)for(const{entry:_,key:A}of w.targets)await k(_.machineId,_.type,A,S)},[j,k]),C=(x,S)=>{i({[x]:S}),t==null||t(x,S)};return n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsx(Zg,{icon:n.jsx(js,{className:"text-text-primary"}),title:o("notifications.title"),subtitle:o("notifications.subtitle")}),n.jsxs("div",{className:"page-content",children:[n.jsx(Nt,{title:o("notifications.sectionBrowserAlerts"),className:"mb-4",children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(js,{size:15})," ",o("notifications.masterToggleLabel")]}),description:o("notifications.masterToggleDesc"),checked:a.globalEnabled,onChange:x=>C("globalEnabled",x)}),a.globalEnabled&&n.jsx("div",{className:"border-t border-border-subtle my-0.5"}),a.globalEnabled&&n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Xn,{size:15})," ",o("notifications.browserNotificationsLabel")]}),description:o("notifications.browserNotificationsDesc"),checked:a.browserNotifications,onChange:x=>C("browserNotifications",x)}),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:()=>{If().then(u)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-2xs text-text-secondary hover:text-text-primary transition-colors",children:o("notifications.allowNotifications")})]}),d==="denied"&&n.jsx("span",{className:"inline-flex items-center rounded-full border border-amber-500/25 bg-amber-500/10 px-2 py-0.5 text-3xs font-semibold text-amber-400",children:o("notifications.permissionBlockedChip")}),d==="unsupported"&&n.jsx("span",{className:"inline-flex items-center rounded-full border border-border-subtle bg-bg-glass px-2 py-0.5 text-3xs font-semibold text-text-muted",children:o("notifications.permissionUnsupportedChip")}),n.jsx(dt,{content:[o(s?"notifications.browserBackgroundInfoWithPush":"notifications.browserBackgroundInfo"),d==="default"?o("notifications.permissionDefault"):d==="denied"?o("notifications.permissionDenied"):d==="unsupported"?o("notifications.permissionUnsupported"):""].filter(Boolean).join(`
|
|
100
|
-
|
|
101
|
-
`)})]}),a.globalEnabled&&a.browserNotifications&&n.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(gi,{size:15})," ",o("notifications.completionAlertsLabel")]}),description:o("notifications.completionAlertsDesc"),checked:a.completionAlert,onChange:x=>C("completionAlert",x)}),n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(yu,{size:15})," ",o("notifications.approvalAlertsLabel")]}),description:o("notifications.approvalAlertsDesc"),checked:a.approvalAlert,onChange:x=>C("approvalAlert",x)}),n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Tr,{size:15})," ",o("notifications.connectionAlertsLabel")]}),description:o("notifications.connectionAlertsDesc"),checked:a.disconnectAlert,onChange:x=>C("disconnectAlert",x)})]}),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(sP,{})]}),!a.globalEnabled&&n.jsx("p",{className:"text-2xs text-text-muted italic",children:o("notifications.allDisabled")})]})}),n.jsx(Nt,{title:o("notifications.sectionProviderAlerts"),description:o("notifications.agentAlertsDesc"),action:n.jsx(Di,{onClick:()=>{y()},refreshing:p,label:o("notifications.refresh")}),className:"mb-4",children:r?f.length===0?n.jsx("p",{className:"text-sm text-text-muted py-6 text-center",children:o("notifications.noOnlineMachines")}):p&&b.length===0?n.jsx("p",{className:"text-sm text-text-muted py-6 text-center",children:o("notifications.loadingProviderSettings")}):n.jsxs("div",{className:"flex flex-col gap-3","data-testid":"agent-alert-toggles",children:[j.map(({id:x,total:S,onCount:w})=>n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[x==="approval"?n.jsx(yu,{size:15}):n.jsx(rd,{size:15}),n.jsx("span",{children:o(`notifications.agentAlert.${x}`)}),w>0&&w<S&&n.jsx("span",{className:"text-3xs text-text-muted",children:o("notifications.mixed")})]}),description:o(`notifications.agentAlert.${x}Desc`),checked:w===S,onChange:_=>void v(x,_)},x)),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((x,S)=>n.jsxs("span",{children:[S>0?", ":"",n.jsx(tP,{machineId:x.id,children:f.length>1?Tn(x,{fallbackId:x.id}):o("notifications.machineProviders")})]},x.id))]})]}):n.jsx("p",{className:"text-sm text-text-muted py-6 text-center",children:o("notifications.loading")})})]})]})}function sP(){const{t:e}=ve("common"),[t,s]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),r=o=>{s(o);try{localStorage.setItem("adhdev_sound",o?"1":"0")}catch{}};return n.jsx(ns,{label:n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(aw,{size:15})," ",e("notifications.soundEffectsLabel")]}),description:e("notifications.soundEffectsDesc"),checked:t,onChange:r})}const $l=[];function Ut(e){return typeof e=="string"?e.trim():""}function $c(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function tx(...e){const t=new Set;for(const s of e){const r=Ut(s);r&&t.add(r)}return[...t]}function rP(e,t){var h,p;const s=$c(e==null?void 0:e.settings),r=Ut((h=e==null?void 0:e.coordinator)==null?void 0:h.meshId)||Ut(s.meshCoordinatorFor),o=Ut(s.meshNodeFor),a=!!r||!!o,i=r===t||o===t;if(a&&!i)return null;const c=$c(e==null?void 0:e.activeChat),d=tx(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),u=d[0]||"";if(!u)return null;const m=r===t?Ut((p=e==null?void 0:e.coordinator)==null?void 0:p.role)||"coordinator":o===t?Ut(s.meshNodeRole)||"worker":Ut(e==null?void 0:e.role)||Ut(s.meshNodeRole)||void 0;return{sessionId:u,aliases:d,meshId:t,nodeId:i&&Ut(s.meshNodeId)||null,providerType:Ut(e==null?void 0:e.providerType)||void 0,state:mi(e==null?void 0:e.status)??void 0,chatStatus:Ut(c.status)||void 0,lifecycle:Ut(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:Ut(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:Ut(e==null?void 0:e.runtimeRecoveryState)||void 0,...m?{role:m}:{},...i?{isSelfCoordinator:r===t}:{},workspace:Ut(e==null?void 0:e.workspace)||null}}function nx(e,t){var r;return t?(Array.isArray((r=e.status)==null?void 0:r.sessions)?e.status.sessions:[]).map(o=>rP(o,t)).filter(o=>o!==null):[]}function ai(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function oP(e,t){const s=new Set(ai(t));return ai(e).some(r=>s.has(r))}function aP(e,t){const s=t.filter(o=>!!o);return s.length===0?e:[...e.filter(o=>!s.some(a=>oP(o,a))),...s]}function iP(e,t){const s=e.nodes??[],r=s.filter(c=>{var d;return((d=c.connection)==null?void 0:d.state)==="self"}),o=r.length>0?r:t?s.filter(c=>on(String(c.daemonId||""),t)):[];if(o.length===1)return o[0].nodeId;const a=o.filter(c=>c.role==="host");if(a.length===1)return a[0].nodeId;const i=o.filter(c=>!c.isLocalWorktree);return i.length===1?i[0].nodeId:null}function lP(e,t,s){if(t.length===0)return e;const r=t.some(d=>d.isSelfCoordinator&&!d.nodeId)?iP(e,s):null,o=new Map;for(const d of t)for(const u of ai(d))o.set(u,d);let a=!1;const c=(e.nodes??[]).map(d=>{const u=Array.isArray(d.activeSessionDetails)?d.activeSessionDetails:Array.isArray(d.sessions)?d.sessions:[],m=new Map;for(const p of u){const g=tx(p==null?void 0:p.sessionId,p==null?void 0:p.session_id,p==null?void 0:p.id,p==null?void 0:p.providerSessionId,p==null?void 0:p.provider_session_id),f=g[0]||"";if(!f)continue;const y=g.map(b=>o.get(b)).find(Boolean);y&&(a=!0),m.set(f,y?{...p,sessionId:f,providerType:y.providerType||p.providerType,state:y.state||p.state,chatStatus:y.chatStatus||p.chatStatus,lifecycle:y.lifecycle||p.lifecycle,surfaceKind:y.surfaceKind||p.surfaceKind,recoveryState:y.recoveryState||p.recoveryState,role:y.role||p.role,isSelfCoordinator:y.isSelfCoordinator??p.isSelfCoordinator,workspace:y.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(ai(p).some(b=>m.has(b)))continue;const f=p.nodeId!=null&&p.nodeId===d.nodeId,y=p.isSelfCoordinator&&!p.nodeId&&r!==null&&r===d.nodeId;!f&&!y||(a=!0,m.set(p.sessionId,{sessionId:p.sessionId,providerType:p.providerType,state:p.state,chatStatus:p.chatStatus,lifecycle:p.lifecycle,surfaceKind:p.surfaceKind,recoveryState:p.recoveryState,role:p.role,isSelfCoordinator:p.isSelfCoordinator,workspace:p.workspace||d.workspace}))}const h=[...m.values()];return h.length===0?d:{...d,activeSessionDetails:h,activeSessions:h.map(p=>p.sessionId)}});return a?{...e,nodes:c}:e}function cP(e,t){const r=nx(e,t).map(o=>{var d;const a=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(u=>Ut(u==null?void 0:u.id)===o.sessionId),i=$c(a==null?void 0:a.activeInteractivePrompt),c=a!=null&&a.meshQueueStats&&typeof a.meshQueueStats=="object"?JSON.stringify(a.meshQueueStats):"";return[o.sessionId,o.providerType??"",o.state??"",o.chatStatus??"",o.lifecycle??"",o.surfaceKind??"",o.recoveryState??"",Ut(i.status)||Ut(i.kind)||Ut(i.type),o.nodeId??"",o.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(o=>!!o).sort();return r.length>0?r.join(`
|
|
102
|
-
`):null}function dP({status:e,daemonId:t,meshId:s,sendData:r,extraLiveSessions:o=$l}){const[a,i]=l.useState($l),c=l.useRef(null);l.useEffect(()=>{c.current=null,i($l)},[t,s]),l.useEffect(()=>{if(!s||!r||!t)return;const u=_n.subscribe({sendData:r},t,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${t}`,params:{includeSessions:!0}},m=>{if(m.topic!=="daemon.metadata")return;const h=cP(m,s);h!==c.current&&(c.current=h,i(nx(m,s)))});return()=>{u()}},[t,s,r]);const d=l.useMemo(()=>aP(a,o),[o,a]);return l.useMemo(()=>e?lP(e,d,t):null,[d,e,t])}function sx({daemonIds:e,meshId:t,sendData:s,onRevisionAdvance:r,onRevisionObserved:o}){const a=l.useRef(new Map),i=l.useRef(r);i.current=r;const c=l.useRef(o);c.current=o;const d=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{a.current=new Map},[d,t]),l.useEffect(()=>{if(!t||!s)return;const u=[...new Set(e.filter(Boolean))];if(u.length===0)return;const m=u.map(h=>_n.subscribe({sendData:s},h,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${h}`,params:{includeSessions:!0}},p=>{var b;if(p.topic!=="daemon.metadata")return;const g=p.meshStateRevisions;if(!g)return;const f=g[t]??g["*"];if(typeof f!="number")return;const y=a.current.get(h);a.current.set(h,f),(b=c.current)==null||b.call(c),y!==void 0&&f>y&&i.current()}));return()=>{for(const h of m)h()}},[d,t,s])}const rx={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},ox=l.createContext(null);function uP(){const e=l.useContext(ox);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function eu(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 ii="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function Hc({workspaces:e,value:t,onChange:s,autoFocus:r}){const{t:o}=ve("common"),[a,i]=l.useState(!1),c=new Set(e.map(u=>u.path)),d=a?"__custom":c.has(t)?t:"";return e.length===0||a?n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("input",{type:"text",className:ii,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:ii,value:d,onChange:u=>{u.target.value==="__custom"?(i(!0),s("")):s(u.target.value)},children:[n.jsx("option",{value:"",children:o("setupWizard.machines.workspaceSelectPlaceholder")}),e.map(u=>n.jsx("option",{value:u.path,children:u.label||u.path},u.path)),n.jsx("option",{value:"__custom",children:o("setupWizard.machines.workspaceCustom")})]})}function li(e){var t;return!!(e!=null&&e.success)&&((t=e==null?void 0:e.plan)==null?void 0:t.kind)!==void 0&&e.plan.kind!=="create_mesh_and_onboard"}function ax(e,t){const[s,r]=l.useState(!1),o=l.useRef(null);return l.useEffect(()=>(e?o.current=setTimeout(()=>r(!0),t):r(!1),()=>{o.current&&clearTimeout(o.current)}),[e,t]),e&&s}function ix({plan:e,loading:t}){var i,c,d;const{t:s}=ve("common"),r=ax(t,250);let o=null,a="text-2xs text-text-muted";return r?o=s("setupWizard.machines.planChecking"):(e==null?void 0:e.success)===!1?(a="text-2xs text-red-400",o=n.jsxs(n.Fragment,{children:[e.error,e.action?` ${e.action}`:""]})):li(e)?(a="text-2xs text-amber-400",o=((i=e.plan)==null?void 0:i.summary)||s("setupWizard.machines.planExists")):e&&(a="text-2xs text-emerald-400",o=s("setupWizard.machines.planOk",{identity:((c=e.discovery)==null?void 0:c.repoIdentity)||((d=e.discovery)==null?void 0:d.repoRoot)||""})),n.jsx("p",{className:`${a} min-h-[1.4em]`,children:o})}function mP(e){var t;return e.creating||e.planLoading||!e.name.trim()||e.showDaemonPicker&&!e.daemonId||((t=e.plan)==null?void 0:t.success)===!1||li(e.plan)?!0:e.workspace.trim()?!1:!e.repoRemoteUrl.trim()&&!e.repoIdentity.trim()}function lx(e){var N,I;const{variant:t="page",showDaemonPicker:s,daemons:r,daemonLabel:o,name:a,onNameChange:i,daemonId:c,onDaemonIdChange:d,workspace:u,onWorkspaceChange:m,workspaces:h,plan:p,planLoading:g,repoRemoteUrl:f,onRepoRemoteUrlChange:y,repoIdentity:b,onRepoIdentityChange:k,manualOpen:j,onManualOpenChange:v,creating:C,warning:x,onCreate:S,onCancel:w}=e,{t:_}=ve("common"),A=mP({creating:C,planLoading:g,plan:p,name:a,workspace:u,showDaemonPicker:s,daemonId:c,repoRemoteUrl:f,repoIdentity:b}),O=ax(g,250),L=j||!!f.trim()||!!b.trim(),R=s&&r.length>0&&n.jsxs("select",{className:t==="wizard"?ii:"input w-full",value:c,onChange:B=>d(B.target.value),children:[n.jsx("option",{value:"",children:_("setupWizard.machines.machineSelectPlaceholder")}),r.map(B=>n.jsx("option",{value:B.id,children:o(B)},B.id))]}),F=L?n.jsxs(n.Fragment,{children:[n.jsx(qt,{label:_("mesh.list.remoteUrl"),hint:_("mesh.list.remoteUrlHint"),children:n.jsx(Dn,{value:f,onChange:B=>y(B.target.value),placeholder:"https://github.com/user/repo"})}),n.jsx(qt,{label:_("mesh.list.repoIdentity"),hint:_("mesh.list.repoIdentityHint"),children:n.jsx(Dn,{value:b,onChange:B=>k(B.target.value),placeholder:"github.com/user/repo"})})]}):n.jsx("button",{type:"button",className:"self-start text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-3 bg-transparent border-none cursor-pointer p-0",onClick:()=>v(!0),children:_("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:_("setupWizard.machines.meshName")}),n.jsx("input",{type:"text",className:ii,value:a,onChange:B=>i(B.target.value)})]}),s&&r.length>1&&n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:_("setupWizard.machines.machine")}),R]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:_("setupWizard.machines.workspace")}),n.jsx(Hc,{workspaces:h,value:u,onChange:m})]}),n.jsx(ix,{plan:p,loading:g}),x&&n.jsx("p",{className:"text-2xs text-amber-400",children:x}),n.jsx("div",{className:"flex justify-end",children:n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:S,disabled:A,children:_(C?"setupWizard.machines.creating":"setupWizard.machines.create")})})]}):n.jsxs(n.Fragment,{children:[n.jsx("h3",{className:"text-base font-bold mb-4",children:_("mesh.list.createTitle")}),s&&n.jsx(qt,{label:_("mesh.list.createOnMachine"),children:r.length===0?n.jsx("select",{className:"input w-full",disabled:!0,children:n.jsx("option",{value:"",children:_("mesh.list.noConnectedDaemon")})}):R}),n.jsx(qt,{label:_("mesh.list.workspace"),hint:_("mesh.list.workspaceHint"),children:n.jsx(Hc,{workspaces:h,value:u,onChange:m})}),(O||p)&&n.jsx(zt,{variant:(p==null?void 0:p.success)===!1?"error":li(p)?"warning":"info",className:"mb-4",children:O?_("setupWizard.machines.planChecking"):(p==null?void 0:p.success)===!1?eu(p):li(p)?((N=p.plan)==null?void 0:N.summary)||_("setupWizard.machines.planExists"):`${((I=p.plan)==null?void 0:I.summary)||"Git repository detected."} No changes will be made until you click Create.`}),n.jsx(qt,{label:_("mesh.list.name"),children:n.jsx(Dn,{value:a,onChange:B=>i(B.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),n.jsx("div",{className:"flex flex-col",children:F}),n.jsxs("div",{className:"flex gap-2 mt-3",children:[n.jsx("button",{className:"btn btn-primary btn-sm",onClick:S,disabled:A,children:_(C?"mesh.list.creating":"mesh.list.create")}),w&&n.jsx("button",{className:"btn btn-secondary btn-sm",onClick:w,disabled:C,children:_("mesh.list.cancel")})]})]})}function hP({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 pP({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 fP({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 gP={online:"#22c55e",dirty:"#f59e0b",offline:"#6b7280",degraded:"#ef4444",enabled:"#22c55e",pending:"#a855f7",assigned:"#3b82f6",completed:"#22c55e",failed:"#ef4444",unknown:"#6b7280"};function bP({status:e}){const{t}=ve("common"),s=gP[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}}),HA(e,t)]});return r?n.jsx(tn,{content:r,children:o}):o}function cx(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 Bc(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function xP(e,t,s,r,o){if(!e.length)return"";const a=String(o||"");if(a){const d=e.find(u=>on(u.id,a));return d?d.id:a}const i=t.find(d=>d.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const d=e.find(u=>on(u.id,c));if(d)return d.id}return""}function Bi(e,t){var c;if(t.length===1&&((c=t[0])!=null&&c.id))return t[0].id;if(!e)return"";const s=Bc(e.meshHost),r=Array.isArray(e.nodes)?e.nodes:[],o=(s.hostNodeId?r.find(d=>String(d.id)===s.hostNodeId):void 0)??r.find(d=>d.role==="host"),a=s.hostDaemonId||String((o==null?void 0:o.daemon_id)||(o==null?void 0:o.daemonId)||"");if(!a)return"";const i=t.find(d=>on(d.id,a));return i?i.id:a}function yP(e){const t=new Map;for(const s of e)s!=null&&s.id&&t.set(s.id,Zn(s.availableProviders||[]));return t}function vP(e,t){const s=String(e.daemon_id||e.daemonId||"");return s&&t.has(s)?t.get(s):!s&&t.size===1?[...t.values()][0]:[]}function bs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function dx(e){if(!e)return null;const t=bs(e.nodeFacts).availableProviders;if(Array.isArray(t)&&t.length>0)return t;const s=bs(e.heldRuntime).availableProviders;return Array.isArray(s)&&s.length>0?s:null}function wP(e){if(!e)return[];const t=bs(e.nodeFacts),s=Object.keys(bs(e.providerVersions)).length>0?bs(e.providerVersions):bs(t.providerVersions),r=bs(t.providerEnablement);return Object.keys(s).map(o=>o.trim()).filter(o=>o&&bs(r[o]).enabled!==!1)}function SP(e,t,s){const r=dx(s);if(r)return Zn(r);const o=vP(e,t),a=wP(s);if(a.length===0)return o;if(o.length>0){const i=new Set(a);return o.filter(c=>i.has(c.type))}return Zn(a.map(i=>({type:i,category:"cli",installed:!0})))}function kP(e,t,s){const r=new Map;for(const d of t)d!=null&&d.id&&r.set(d.id,Array.isArray(d.availableProviders)?d.availableProviders:[]);const o=new Set,a=[];let i=0,c=0;for(const d of Array.isArray(e)?e:[]){const u=String((d==null?void 0:d.daemon_id)||(d==null?void 0:d.daemonId)||""),m=tu(d,s),h=dx(m)??(u?r.get(u):r.size===1?[...r.values()][0]:void 0);if(!h||h.length===0){c++;continue}i++;for(const p of h){const g=String((p==null?void 0:p.type)||(p==null?void 0:p.id)||"").trim();!g||o.has(g)||(o.add(g),a.push(p))}}return a.sort((d,u)=>String((d==null?void 0:d.type)||(d==null?void 0:d.id)||"").localeCompare(String((u==null?void 0:u.type)||(u==null?void 0:u.id)||""))),{providers:a,reportedNodeCount:i,unreportedNodeCount:c}}function tu(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 jP(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 fp(t.slots))o(a.provider);if(Array.isArray(t.providerPriority))for(const a of t.providerPriority)o(a);return r}function NP(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 jP(t.policy))s.push({tag:`provider=${m}`,custom:!1});const i=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";t.isLocalWorktree===!0&&i&&s.push({tag:`worktree=${i}`,custom:!1});const c=new Set;return s.filter(m=>c.has(m.tag)?!1:(c.add(m.tag),!0))}function CP(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 ux(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 _P(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 AP=["","low","medium","high"],TP={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function qh(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function zh(e){const t=e.provider.trim();if(!t)return null;const s=e.model.trim(),r=e.thinkingLevel.trim()||void 0,o=Number(e.maxParallel),a=Number.isFinite(o)&&o>0?Math.floor(o):void 0;return{provider:t,...s?{model:s}:{},...r?{thinkingLevel:r}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...a!==void 0?{maxParallel:a}:{}}}function IP(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const Ds="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function MP({slots:e,availableProviders:t,saving:s,onSave:r}){const{t:o}=ve("common"),[a,i]=l.useState(()=>e.map(qh)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(qh))},[c]);const d=l.useMemo(()=>[...new Set(t.map(j=>j.type).filter(Boolean))],[t]),u=l.useMemo(()=>Jg(t),[t]),m=l.useMemo(()=>{const j=a.map(zh).filter(Boolean);return JSON.stringify(j)!==JSON.stringify(e)},[a,e]),h=(j,v)=>i(C=>C.map((x,S)=>S===j?{...x,...v}:x)),p=(j,v)=>i(C=>C.map((x,S)=>{var A;if(S!==j)return x;const w=((A=u.get(v))==null?void 0:A.models)??[],_=!x.model||w.length===0||w.includes(x.model);return{...x,provider:v,..._?{}:{model:""}}})),g=j=>i(v=>v.filter((C,x)=>x!==j)),f=()=>i(j=>[...j,IP()]),y=(j,v)=>i(C=>{const x=j+v;if(x<0||x>=C.length)return C;const S=[...C];return[S[j],S[x]]=[S[x],S[j]],S}),b=(j,v)=>i(C=>C.map((x,S)=>{if(S!==j)return x;const w=x.difficulty.includes(v);return{...x,difficulty:w?x.difficulty.filter(_=>_!==v):[...x.difficulty,v]}})),k=()=>r(a.map(zh).filter(Boolean));return n.jsxs("div",{className:"flex flex-col gap-2",onClick:j=>j.stopPropagation(),children:[a.length===0&&n.jsxs("div",{className:"flex items-center gap-1 text-xs text-text-muted",children:[n.jsx("span",{children:o("mesh.slotEditor.empty")}),n.jsx(dt,{content:o("mesh.slotEditor.emptyHint"),size:12})]}),a.map((j,v)=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[n.jsxs("span",{className:"text-2xs font-semibold text-text-muted",children:["#",v+1]}),n.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[n.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:v===0,onClick:()=>y(v,-1),title:o("mesh.slotEditor.moveUp"),children:"↑"}),n.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:v===a.length-1,onClick:()=>y(v,1),title:o("mesh.slotEditor.moveDown"),children:"↓"}),n.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>g(v),"aria-label":o("mesh.slotEditor.removeSlot"),children:n.jsx(Bt,{size:12})})]})]}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.provider")}),d.length>0?n.jsxs("select",{className:Ds,value:j.provider,onChange:C=>p(v,C.target.value),children:[n.jsx("option",{value:"",children:o("mesh.slotEditor.select")}),d.map(C=>n.jsx("option",{value:C,children:C},C)),j.provider&&!d.includes(j.provider)&&n.jsx("option",{value:j.provider,children:j.provider})]}):n.jsx("input",{className:Ds,value:j.provider,placeholder:"claude-cli",onChange:C=>h(v,{provider:C.target.value})})]}),(()=>{var _;const C=u.get(j.provider),x=(C==null?void 0:C.models)??[],S=(_=C==null?void 0:C.thinking)!=null&&_.length?["",...C.thinking]:AP,w=!!j.model&&x.length>0&&!x.includes(j.model);return n.jsxs(n.Fragment,{children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.model")}),x.length>0&&!w?n.jsxs("select",{className:Ds,value:x.includes(j.model)?j.model:"",onChange:A=>h(v,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[n.jsx("option",{value:"",children:o("mesh.slotEditor.providerDefault")}),x.map(A=>n.jsx("option",{value:A,children:A},A)),n.jsx("option",{value:"__custom__",children:o("mesh.slotEditor.custom")})]}):n.jsxs(n.Fragment,{children:[n.jsx("input",{className:Ds,value:j.model.trim(),placeholder:j.provider?`${j.provider} model`:o("mesh.slotEditor.modelPlaceholder"),onChange:A=>h(v,{model:A.target.value})}),x.length>0&&n.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-3xs text-text-muted hover:underline",onClick:()=>h(v,{model:""}),children:o("mesh.slotEditor.backToModelList")})]})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.thinking")}),n.jsx("select",{className:Ds,value:j.thinkingLevel,onChange:A=>h(v,{thinkingLevel:A.target.value}),children:S.map(A=>n.jsx("option",{value:A,children:A||o("mesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),n.jsxs("div",{className:"mt-2",children:[n.jsx("span",{className:"text-2xs text-text-muted",children:o("mesh.slotEditor.difficulty")}),n.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:pp.map(C=>{const x=j.difficulty.includes(C);return n.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-2xs font-medium transition-colors ${x?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>b(v,C),children:TP[C]},C)})})]}),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:Ds,value:j.capability.join(", "),placeholder:"worktree, os=darwin",onChange:C=>h(v,{capability:C.target.value.split(",").map(x=>x.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:Ds,value:j.maxParallel,placeholder:o("mesh.slotEditor.maxParallelPlaceholder"),onChange:C=>h(v,{maxParallel:C.target.value})})]})]})]},v)),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:f,children:[n.jsx(jo,{size:13})," ",o("mesh.slotEditor.addSlot")]}),n.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:k,disabled:!!s||!m,children:o(s?"mesh.slotEditor.saving":"mesh.slotEditor.saveSlots")})]})]})}function RP(e){const t=e.capabilities;return Array.isArray(t)?t.map(s=>typeof s=="string"?s.trim():"").filter(Boolean):[]}const PP=["os=","arch=","provider=","worktree=","converge="];function LP({node:e,saving:t,onSave:s}){const{t:r}=ve("common"),o=l.useMemo(()=>NP(e).filter(y=>!y.custom),[e]),a=l.useMemo(()=>RP(e),[e]),[i,c]=l.useState(a),[d,u]=l.useState(""),m=JSON.stringify(i)!==JSON.stringify(a),p=(y=>{const b=y.trim();return b?/\s/.test(b)?r("mesh.tagEditor.noSpaces"):PP.some(k=>b.toLowerCase().startsWith(k))?r("mesh.tagEditor.reservedPrefix"):i.includes(b)?r("mesh.tagEditor.alreadyAdded"):null:null})(d);function g(){const y=d.trim();!y||p||(c(b=>[...b,y]),u(""))}function f(y){c(b=>b.filter(k=>k!==y))}return n.jsxs("div",{className:"mt-2",onClick:y=>y.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(y=>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:y.tag},y.tag)),i.map(y=>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:[y,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(y),disabled:t,"aria-label":r("mesh.tagEditor.remove",{tag:y}),children:"×"})]},y))]}),n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[n.jsx("input",{type:"text",value:d,onChange:y=>u(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),g())},placeholder:r("mesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-xs text-text-primary"}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:g,disabled:t||!d.trim()||!!p,children:r("mesh.tagEditor.add")}),m&&n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>s(i),disabled:t,children:r(t?"mesh.tagEditor.saving":"mesh.tagEditor.saveTags")})]}),p&&n.jsx("div",{className:"mt-1 text-2xs text-amber-400",children:p}),i.length===0&&o.length===0&&n.jsxs("div",{className:"mt-1 flex items-center gap-1 text-2xs text-text-muted",children:[n.jsx("span",{children:r("mesh.tagEditor.empty")}),n.jsx(dt,{content:r("mesh.tagEditor.emptyHint"),size:12})]})]})}function EP(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 Gh({nodes:e,statusNodes:t,meshQueue:s,daemons:r,userName:o,features:a,providersByDaemonId:i,savingNodeSlotsId:c,onUpdateNodeSlots:d,savingNodeCapabilitiesId:u,onUpdateNodeCapabilities:m,nodeSystemPromptDrafts:h,onNodeSystemPromptDraftChange:p,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:f,selectedNodeId:y,onSelectNode:b,onRemoveNode:k}){const{t:j}=ve("common"),[v,C]=l.useState(()=>new Set),x=S=>C(w=>{const _=new Set(w);return _.has(S)?_.delete(S):_.add(S),_});return e.length===0?n.jsx(Ei,{variant:"compact",icon:n.jsx(Zs,{size:14}),title:j("mesh.nodeList.emptyTitle"),description:j("mesh.nodeList.emptyDescription")}):n.jsx("div",{className:"flex flex-col gap-2",children:e.map(S=>{var T;const w=$P(S),_=DP(S,s),A=tu(S,t),O=CP(A),L=y===S.id,R=v.has(S.id),F=ux(A)||S.status||(_.length>0||O.length>0?"active":"enabled"),N=a.addNodeDaemonPicker?S.machine_label||S.machine_nickname||S.hostname||S.workspace:S.workspace.split("/").pop()||S.workspace,I=w.configured?w.label.split(" → "):[],B=a.addNodeDaemonPicker?j("mesh.nodeList.ownerMachine",{owner:EP(r.find(H=>H.id===String(S.daemon_id||"")),o),machine:S.machine_label||S.daemon_id||S.workspace}):null;return n.jsxs("div",{className:`rounded-xl border bg-bg-glass px-4 py-3 transition-colors ${a.addNodeDaemonPicker?"border-border-subtle":`cursor-pointer ${L?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:a.addNodeDaemonPicker?void 0:"button",tabIndex:a.addNodeDaemonPicker?void 0:0,onClick:a.addNodeDaemonPicker?void 0:()=>b(L?null:S.id),onKeyDown:a.addNodeDaemonPicker?void 0:H=>{H.target===H.currentTarget&&(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),b(L?null:S.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:S.workspace,children:N}),a.addNodeDaemonPicker&&n.jsx(bP,{status:F}),!w.configured&&n.jsx(tn,{content:j("mesh.nodeList.launchBlocked"),children:n.jsx("span",{className:"rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-3xs font-medium text-amber-400",children:j("mesh.nodeList.launchBlockedChip")})})]}),n.jsxs("div",{className:"mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 text-2xs text-text-muted",children:[I.length>0&&n.jsx("span",{className:"truncate",children:j("mesh.nodeList.usesTools",{tools:I.join(", ")})}),a.addNodeDaemonPicker&&n.jsx("span",{className:"truncate font-mono text-3xs",title:S.workspace,children:S.workspace.split("/").filter(Boolean).pop()||S.workspace})]})]}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0","aria-expanded":R,onClick:H=>{H.stopPropagation(),x(S.id)},children:j(R?"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:H=>{H.stopPropagation(),k(S.id)},"aria-label":j("mesh.nodeList.removeNode"),title:j("mesh.nodeList.removeNode"),children:n.jsx(pP,{size:14})})]}),R&&n.jsxs("div",{className:"mt-3 max-w-2xl cursor-default",onClick:H=>H.stopPropagation(),children:[n.jsx(qt,{label:j("mesh.nodeList.slotsLabel"),hint:j("mesh.nodeList.slotsHint"),children:n.jsx(MP,{slots:Array.isArray((T=S.policy)==null?void 0:T.slots)?S.policy.slots:[],availableProviders:SP(S,i,A),saving:c===S.id,onSave:H=>d(S,H)})}),n.jsxs("details",{className:"group",children:[n.jsxs("summary",{className:"cursor-pointer select-none text-xs text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[n.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",j("mesh.nodeList.advanced")]}),n.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[n.jsx(LP,{node:S,saving:u===S.id,onSave:H=>m(S,H)}),a.nodeInstruction&&n.jsxs(qt,{label:j("mesh.nodeList.nodeInstruction"),hint:j("mesh.nodeList.nodeInstructionHint"),className:"mb-0",children:[n.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:h[S.id]??"",onChange:H=>{const q=H.target.value;p(S.id,q)},disabled:g===S.id,placeholder:j("mesh.nodeList.nodeInstructionPlaceholder")}),n.jsx("div",{className:"mt-2 flex items-center gap-2",children:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>f(S),disabled:g===S.id,children:g===S.id?j("mesh.nodeList.saving"):j("mesh.nodeList.saveInstruction")})})]}),n.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-xs text-text-muted",children:[B&&n.jsx("div",{className:"mb-2",children:B}),n.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary",children:j("mesh.nodeList.repoRoot")})," ",n.jsx("span",{className:"font-mono break-all",children:S.repoRoot||S.workspace})]}),n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary",children:j("mesh.nodeList.activeSessionsLabel")})," ",O.length]}),a.addNodeDaemonPicker&&n.jsxs("div",{children:[n.jsx("span",{className:"text-text-secondary",children:j("mesh.nodeList.added")})," ",id(S.created_at||S.createdAt)||"—"]})]}),n.jsxs("div",{className:"mt-3",children:[n.jsx("div",{className:"text-text-secondary mb-1",children:j("mesh.nodeList.activeQueueAssignments")}),_.length===0?n.jsx("div",{children:j("mesh.nodeList.noActiveAssignment")}):n.jsx("ul",{className:"m-0 pl-4",children:_.map(H=>n.jsx("li",{className:"font-mono",children:OP(H)},H.id))})]}),O.length>0&&n.jsxs("div",{className:"mt-3",children:[n.jsx("div",{className:"text-text-secondary mb-1",children:j("mesh.nodeList.activeSessions")}),n.jsx("ul",{className:"m-0 pl-4",children:O.map(H=>n.jsxs("li",{className:"font-mono",children:[H.provider," / ",H.status]},H.id))})]}),n.jsx(_d,{className:"mt-3",rows:[{label:j("mesh.nodeList.nodeId"),value:S.id},...O.map(H=>({label:j("mesh.nodeList.activeSessions"),value:H.id}))]})]})]})]})]})]},S.id)})})}function DP(e,t){return t.filter(s=>s.status!=="assigned"?!1:(s.assignedNodeId||s.nodeId)===e.id)}function OP(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 FP(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:ay((a=e.policy)==null?void 0:a.slots)}function $P(e){const t=FP(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 Wc(e){return e.isLocalWorktree===!0}function ci(e){return e&&(e.machineNickname||e.nickname||e.hostname||(e.id?rb(e.id):void 0))||"Unknown"}function HP(e){return String(e.daemon_id||e.daemonId||"")}function mx(e,t,s){const r=new Map(t.map(i=>[i.id,i])),o=[],a=new Map;for(const i of e){const c=HP(i);a.has(c)||(a.set(c,[]),o.push(c)),a.get(c).push(i)}return o.map(i=>{const c=a.get(i),d=i?r.get(i):void 0,u=c[0],m=c.map(b=>tu(b,s)).filter(b=>!!b),h=m.map(b=>_P(b).machineNickname).find(Boolean),p=i?h||(d?ci(d):(u==null?void 0:u.machine_label)||(u==null?void 0:u.machine_nickname)||(u==null?void 0:u.hostname)||i):ci(d),g=m.map(b=>ux(b)).filter(b=>!!b),f=g.length>0?g.includes("online"):(d==null?void 0:d.status)==="online",y=c.reduce((b,k)=>{var j;return b+(Array.isArray((j=k.policy)==null?void 0:j.slots)?k.policy.slots.length:0)},0);return{key:i,label:p,online:f,nodes:c,slotCount:y}})}function BP({groups:e,activeKey:t,onChange:s}){const{t:r}=ve("common");return n.jsx(Od,{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 WP({nodes:e,statusNodes:t,meshQueue:s,activeDaemon:r,daemons:o,selectedMeshId:a,userName:i,features:c,coordinatorDaemonId:d,availableCliProviders:u,savingNodeSlotsId:m,onUpdateNodeSlots:h,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:g,nodeSystemPromptDrafts:f,onNodeSystemPromptDraftChange:y,savingNodeSystemPromptId:b,onSaveNodeSystemPrompt:k,selectedNodeId:j,onSelectNode:v,showAddNode:C,onShowAddNode:x,onCancelAddNode:S,nodeWorkspace:w,onNodeWorkspaceChange:_,nodeProviderPriority:A,onNodeProviderPriorityChange:O,nodeDaemonId:L,onNodeDaemonIdChange:R,nodeCustomPath:F,onNodeCustomPathChange:N,nodePickerWorkspaces:I,nodePickerProviders:B,nodeOnboardingPlan:T,nodePlanLoading:H,attachableDaemons:q,onAddNode:J,onRemoveNode:K}){var be,V,we;const{t:M}=ve("common"),D=l.useMemo(()=>yP(o),[o]),P=l.useMemo(()=>e.filter(ce=>!Wc(ce)),[e]),$=l.useMemo(()=>c.addNodeDaemonPicker?mx(P,o,t):[],[c.addNodeDaemonPicker,P,o,t]),[W,U]=l.useState(null),ae=$.some(ce=>ce.key===W)?W:((be=$[0])==null?void 0:be.key)??"";return n.jsxs(Nt,{title:c.addNodeDaemonPicker?M("mesh.nodeList.title",{count:P.length}):M("mesh.nodeList.titleNoCount"),description:c.addNodeDaemonPicker?M("mesh.nodeList.descriptionCloud"):M("mesh.nodeList.descriptionStandalone"),children:[c.addNodeDaemonPicker&&n.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[n.jsx("div",{className:"min-w-0 text-sm font-semibold text-text-primary",children:M("mesh.nodeList.daemonCandidates")}),n.jsx("span",{className:"text-2xs text-text-muted shrink-0",children:M("mesh.nodeList.available",{count:q.length})})]}),o.length===0?n.jsx("div",{className:"text-xs text-text-muted",children:M("mesh.nodeList.noDaemonsAvailable")}):q.length===0?n.jsx("div",{className:"text-xs text-text-muted",children:M("mesh.nodeList.allDaemonsAttached")}):n.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:q.map(ce=>n.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors min-w-0 ${ce.id===d?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{R(ce.id),_(""),N(!1),O(nr(Zn(ce.availableProviders||[]))),x()},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:ci(ce)}),ce.id===d&&n.jsx("span",{className:"text-3xs text-accent-primary shrink-0",children:M("mesh.nodeList.selectedHost")})]}),n.jsx("div",{className:"mt-1 text-2xs text-text-muted",children:M("mesh.nodeList.workspacesDetected",{count:(ce.workspaces||[]).length})})]},ce.id))})]}),!C&&n.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:x,children:[n.jsx(fP,{size:13})," ",c.addNodeDaemonPicker?M("mesh.nodeList.attachMachine"):M("mesh.nodeList.addNode")]}),C&&n.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[n.jsxs("div",{className:"flex justify-between items-center mb-3",children:[n.jsx("h4",{className:"text-sm font-bold",children:c.addNodeDaemonPicker?M("mesh.nodeList.attachMachineTitle"):M("mesh.nodeList.addNodeTitle")}),n.jsx("button",{onClick:()=>{S(),R(""),N(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:n.jsx(Bt,{size:16})})]}),c.addNodeDaemonPicker&&n.jsx(qt,{label:M("mesh.nodeList.machine"),children:n.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:L,onChange:ce=>{var de;R(ce.target.value),_(""),N(!1),O(nr(Zn(((de=o.find(ne=>ne.id===ce.target.value))==null?void 0:de.availableProviders)||[])))},children:[n.jsx("option",{value:"",children:M("mesh.nodeList.selectMachine")}),o.map(ce=>n.jsx("option",{value:ce.id,children:ci(ce)},ce.id))]})}),(c.addNodeDaemonPicker?L:!0)&&n.jsx(qt,{label:M("mesh.nodeList.workspacePath"),children:c.addNodeDaemonPicker&&!F&&I.length>0?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:I.map(ce=>n.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${w===ce.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>_(ce.path),children:[n.jsx("span",{className:"font-medium block truncate",children:ce.label||ce.path.split("/").pop()}),n.jsx("span",{className:"text-3xs text-text-muted font-mono truncate block",children:ce.path})]},ce.id||ce.path))}),n.jsx("button",{type:"button",className:"text-2xs text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{N(!0),_("")},children:M("mesh.nodeList.enterCustomPath")})]}):n.jsx(n.Fragment,{children:c.addNodeDaemonPicker?n.jsxs(n.Fragment,{children:[n.jsx(Dn,{value:w,onChange:ce=>_(ce.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:ce=>{ce.key==="Enter"&&J()}}),I.length>0&&n.jsx("button",{type:"button",className:"text-2xs text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{N(!1),_("")},children:M("mesh.nodeList.pickFromSaved")})]}):(()=>{var ne;const ce=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],de=`mesh-add-node-workspaces-${a||"new"}`;return n.jsxs(n.Fragment,{children:[n.jsx(Dn,{value:w,onChange:ee=>_(ee.target.value),placeholder:((ne=ce[0])==null?void 0:ne.path)||"/Users/dev/projects/myapp",list:ce.length>0?de:void 0,autoFocus:!0}),ce.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("datalist",{id:de,children:ce.map(ee=>n.jsx("option",{value:ee.path,children:ee.label||ee.path},ee.id||ee.path))}),n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ce.slice(0,6).map(ee=>n.jsx("button",{type:"button",onClick:()=>_(ee.path),className:"text-2xs px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:ee.path,children:ee.label||ee.path.split("/").filter(Boolean).pop()||ee.path},ee.id||ee.path))})]})]})})()})}),(H||T)&&n.jsx(zt,{variant:(T==null?void 0:T.success)===!1?"error":"info",className:"mb-4",children:H?M("mesh.nodeList.inspectingRepo"):T!=null&&T.success?`${((V=T.plan)==null?void 0:V.summary)||M("mesh.nodeList.compatibleWorkspace")} ${M("mesh.nodeList.addingIsExplicit")}`:eu(T)}),n.jsx(qt,{label:M("mesh.nodeList.preferredTools"),hint:M("mesh.nodeList.preferredToolsHint"),children:n.jsx(fA,{value:A,availableProviders:c.addNodeDaemonPicker?B:u,onChange:O})}),n.jsxs("div",{className:"flex gap-2 mt-3",children:[n.jsx("button",{onClick:J,disabled:H||(T==null?void 0:T.success)===!1||!w.trim()||c.addNodeDaemonPicker&&!L,className:"btn btn-primary btn-sm",children:M("mesh.nodeList.add")}),n.jsx("button",{onClick:()=>{S(),R(""),N(!1)},className:"btn btn-secondary btn-sm",children:M("mesh.nodeList.cancel")})]})]}),P.length===0?n.jsx(Ei,{icon:n.jsx(Zs,{}),title:M("mesh.nodeList.emptyTitle"),description:M("mesh.nodeList.emptyDescription")}):c.addNodeDaemonPicker?n.jsxs(n.Fragment,{children:[$.length>1&&n.jsx(BP,{groups:$,activeKey:ae,onChange:U}),n.jsx(Gh,{nodes:((we=$.find(ce=>ce.key===ae))==null?void 0:we.nodes)||P,statusNodes:t,meshQueue:s,daemons:o,userName:i,features:c,providersByDaemonId:D,savingNodeSlotsId:m,onUpdateNodeSlots:h,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:g,nodeSystemPromptDrafts:f,onNodeSystemPromptDraftChange:y,savingNodeSystemPromptId:b,onSaveNodeSystemPrompt:k,selectedNodeId:j,onSelectNode:v,onRemoveNode:K})]}):n.jsx(Gh,{nodes:P,statusNodes:t,meshQueue:s,daemons:o,userName:i,features:c,providersByDaemonId:D,savingNodeSlotsId:m,onUpdateNodeSlots:h,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:g,nodeSystemPromptDrafts:f,onNodeSystemPromptDraftChange:y,savingNodeSystemPromptId:b,onSaveNodeSystemPrompt:k,selectedNodeId:j,onSelectNode:v,onRemoveNode:K})]})}function UP(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function KP({meshes:e,loading:t,error:s,onDismissError:r,daemons:o,features:a,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:u,createRepoIdentity:m,onCreateRepoIdentityChange:h,createRepoRemoteUrl:p,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:f,onNewMeshDaemonIdChange:y,newMeshWorkspace:b,onNewMeshWorkspaceChange:k,createPickerWorkspaces:j,createOnboardingPlan:v,createPlanLoading:C,creating:x,createWarning:S,onDismissCreateWarning:w,onSelectMesh:_,onCreate:A,onCancelCreate:O,sendCommand:L}){const{t:R}=ve("common"),[F,N]=l.useState(!1),[I,B]=l.useState(null);return n.jsxs($o,{icon:n.jsx(Gn,{}),title:R("mesh.list.title"),subtitle:R("mesh.list.count",{count:e.length}),subtitleInline:!0,widthClassName:"max-w-5xl",actions:n.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,children:R("mesh.list.createMesh")}),children:[s&&n.jsx(zt,{variant:"error",onDismiss:r,className:"mb-4",children:s}),S&&n.jsx(zt,{variant:"warning",onDismiss:w,className:"mb-4",children:S}),i&&n.jsx(Nt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:n.jsx(lx,{variant:"page",showDaemonPicker:a.createDaemonPicker,daemons:o,daemonLabel:UP,name:d,onNameChange:u,daemonId:f,onDaemonIdChange:y,workspace:b,onWorkspaceChange:k,workspaces:j,plan:v,planLoading:C,repoRemoteUrl:p,onRepoRemoteUrlChange:g,repoIdentity:m,onRepoIdentityChange:h,manualOpen:F,onManualOpenChange:N,creating:x,onCreate:A,onCancel:O})}),t?n.jsx("div",{className:"text-sm text-text-muted p-4",children:R("mesh.list.loading")}):e.length===0?n.jsx(Ei,{icon:n.jsx(Gn,{}),title:R("mesh.list.emptyTitle"),description:o.length>0?R("mesh.list.emptyWithDaemons"):R("mesh.list.emptyNoDaemons"),action:n.jsx("button",{className:"btn btn-primary btn-sm",disabled:!o.length,onClick:c,children:R("mesh.list.createFirst")})}):n.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(T=>{const H=Array.isArray(T.nodes)?T.nodes:[],q=mx(H.filter($=>$.isLocalWorktree!==!0),o).filter($=>$.key),J=q.filter($=>$.online).length,K=Bi(T,o),M=!!K&&o.some($=>on($.id,K)&&($.status===void 0||$.status==="online")),D=T.createdAt||T.created_at,P=q.length===0?"bg-neutral-500":J===q.length?"bg-green-400":J===0?"bg-red-400":"bg-amber-400";return n.jsxs("div",{className:"flex w-full flex-col gap-3 rounded-xl border border-border-subtle bg-bg-glass px-4 py-3.5 transition-colors hover:border-border-default sm:flex-row sm:items-center",children:[n.jsxs("button",{type:"button",onClick:()=>_(T.id),className:"min-w-0 flex-1 cursor-pointer border-none bg-transparent p-0 text-left",children:[n.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[n.jsx(Gn,{size:16}),n.jsx("span",{className:"truncate text-sm font-bold text-text-primary",children:T.name})]}),n.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs text-text-muted",children:[n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx("span",{"aria-hidden":!0,className:`h-1.5 w-1.5 rounded-full ${P}`}),q.length>0?R("mesh.list.machinesOnline",{online:J,total:q.length}):R("mesh.list.nodeCount",{count:H.length||T.nodeCount||0})]}),n.jsx("span",{className:"truncate font-mono",children:T.repoIdentity||T.repo_identity||R("mesh.list.noRepoIdentity")}),(T.defaultBranch||T.default_branch)&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(hP,{size:11}),T.defaultBranch||T.default_branch]}),D&&n.jsx(tn,{content:Po(D),children:n.jsx("span",{children:id(D)})})]})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>_(T.id),children:R("mesh.list.settings")}),L&&n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",disabled:!M,title:M?void 0:R("mesh.detail.observabilityDisabledTitle"),onClick:()=>B({meshId:T.id,daemonId:K,meshName:T.name}),children:R("mesh.list.open")})]})]},T.id)})}),I&&L&&n.jsx(Pd,{activeConv:cx(I),sendDaemonCommand:L,onClose:()=>B(null)})]})}const qP={default:"border-white/10 bg-white/[0.04] text-slate-200",good:"border-emerald-400/20 bg-emerald-500/10 text-emerald-200",warn:"border-amber-400/20 bg-amber-500/10 text-amber-100",danger:"border-rose-400/20 bg-rose-500/10 text-rose-100",info:"border-sky-400/20 bg-sky-500/10 text-sky-100"},zP={default:"border-slate-300 bg-white/95 text-slate-700",good:"border-emerald-300 bg-emerald-50 text-emerald-700",warn:"border-amber-300 bg-amber-50 text-amber-700",danger:"border-rose-300 bg-rose-50 text-rose-700",info:"border-sky-300 bg-sky-50 text-sky-700"},GP={default:"border-white/10 bg-white/[0.04] text-slate-200 hover:bg-white/[0.08]",info:"border-sky-400/25 bg-sky-500/10 text-sky-100 hover:bg-sky-500/16",success:"border-emerald-400/25 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/16"},VP={default:"border-slate-300 bg-white text-slate-700 hover:bg-slate-50",info:"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"};function nu(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-3xs text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",blueprintShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-sky-200 bg-[radial-gradient(circle_at_top,_rgba(14,116,233,0.10),_rgba(240,247,255,0.98)_46%,_rgba(248,251,255,1))]",blueprintGridFineColor:"rgba(59, 130, 246, 0.10)",blueprintGridAccentColor:"rgba(59, 130, 246, 0.20)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center bg-[rgba(15,23,42,0.82)] px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",dialogShellClass:"flex shrink-0 h-[calc(100dvh-32px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-2rem)] w-full flex-col overflow-hidden rounded-[20px] border border-slate-200 bg-white shadow-[0_18px_60px_rgba(15,23,42,0.35)] md:h-[calc(100dvh-32px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-2 border-b border-slate-200 bg-white/96 px-4 pb-0 pt-4 backdrop-blur md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-2xs uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-500",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-slate-200/80 py-0.5 text-2xs",panelFieldLabelClass:"shrink-0 text-slate-500",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-3xs text-sky-700",badge:t=>zP[t],actionButton:t=>VP[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-3xs text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",blueprintShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-sky-400/15 bg-[radial-gradient(circle_at_top,_rgba(30,84,164,0.22),_rgba(6,17,38,0.99)_46%,_rgba(3,10,26,1))]",blueprintGridFineColor:"rgba(96, 165, 250, 0.10)",blueprintGridAccentColor:"rgba(96, 165, 250, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center bg-[#030617]/[0.92] px-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] pt-[calc(16px+env(safe-area-inset-top,0px))]",dialogShellClass:"flex shrink-0 h-[calc(100dvh-32px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-2rem)] w-full flex-col overflow-hidden rounded-[20px] border border-white/10 bg-slate-950 shadow-[0_18px_60px_rgba(2,6,23,0.6)] md:h-[calc(100dvh-32px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-2 border-b border-white/10 bg-slate-950/92 px-4 pb-0 pt-4 backdrop-blur md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-2xs uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-400",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-white/6 py-0.5 text-2xs",panelFieldLabelClass:"shrink-0 text-slate-400",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-3xs text-blue-300",badge:t=>qP[t],actionButton:t=>GP[t]}}const YP=["claude-cli","codex-cli","hermes-cli","antigravity-cli"],QP=[{kind:"rca",labelKey:"mesh.magiKind.kindRca",hint:"rca"},{kind:"design",labelKey:"mesh.magiKind.kindDesign",hint:"design"},{kind:"claim_audit",labelKey:"mesh.magiKind.kindClaimAudit",hint:"claim_audit"},{kind:"freeform",labelKey:"mesh.magiKind.kindFreeform",hint:"freeform"}];function JP(){return{nodeId:"",provider:"",model:"",n:""}}function Vh(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function XP(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function ZP(e){const t=[];for(let s=0;s<e.length;s++){const r=e[s],o=r.provider.trim();if(!o)return{error:{code:"provider_required",slot:s+1}};const a=r.nodeId.trim(),i=r.model.trim(),c=r.n.trim();let d;if(c){const u=Number(c);if(!Number.isFinite(u)||u<1)return{error:{code:"replica_min",slot:s+1}};d=Math.floor(u)}t.push({provider:o,...a?{nodeId:a}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function eL({status:e,daemonId:t,sendDaemonCommand:s,availableProviders:r,meshId:o}){const{t:a}=ve(),{theme:i}=Ho(),c=l.useMemo(()=>nu(i),[i]),d=l.useMemo(()=>Jg(r),[r]),[u,m]=l.useState({}),[h,p]=l.useState(!1),[g,f]=l.useState(null),[y,b]=l.useState({}),[k,j]=l.useState(null),v=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(P=>({nodeId:P.nodeId,machineLabel:P.machineLabel,providers:P.providers,providerPriority:P.providerPriority,isLocalWorktree:P.isLocalWorktree,worktreeBranch:P.worktreeBranch})),[e==null?void 0:e.nodes]),C=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(P=>P.nodeId),[e==null?void 0:e.nodes]),x=l.useMemo(()=>new Set(v.filter(Wc).map(P=>P.nodeId)),[v]),S=l.useMemo(()=>Object.fromEntries(v.filter(Wc).map(P=>[P.nodeId,P.worktreeBranch])),[v]),w=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(P=>[P.nodeId,KA(P)||P.nodeId])),[e==null?void 0:e.nodes]),_=l.useMemo(()=>{const P={};for(const $ of v)P[$.nodeId]=Vh($);return P},[v]),A=l.useMemo(()=>{const P=[...new Set(v.flatMap(Vh).filter(Boolean))];return[...new Set([...P,...YP])].sort()},[v]),O=!!t&&!!s,L=P=>P&&typeof P=="object"&&"result"in P?P.result:P,R=o??(e==null?void 0:e.meshId),F=l.useCallback(async()=>{if(!(!t||!s)){p(!0),f(null);try{const P=await s(t,"magi_kind_panel_list",{...R?{meshId:R}:{}}),$=L(P);if(($==null?void 0:$.success)===!1)throw new Error($.error||a("mesh.magiKind.errorLoad"));m($!=null&&$.kindPanels&&typeof $.kindPanels=="object"?$.kindPanels:{}),b({})}catch(P){f((P==null?void 0:P.message)||a("mesh.magiKind.errorLoad"))}finally{p(!1)}}},[t,s,R,a]);l.useEffect(()=>{F()},[F]);const N=l.useCallback(P=>{if(y[P])return y[P];const $=u[P];return $?$.map(XP):[]},[y,u]),I=(P,$)=>{b(W=>({...W,[P]:$}))},B=(P,$,W)=>{const U=N(P);I(P,U.map((ae,be)=>be===$?{...ae,...W}:ae))},T=P=>{I(P,[...N(P),JP()])},H=(P,$)=>{I(P,N(P).filter((W,U)=>U!==$))},q=l.useCallback(async P=>{if(!t||!s)return;const $=ZP(N(P));if("error"in $){const W=$.error,U=W.code==="provider_required"?a("mesh.magiKind.errorSlotProvider",{slot:W.slot}):W.code==="replica_min"?a("mesh.magiKind.errorSlotReplica",{slot:W.slot}):a("mesh.magiKind.errorNoSlot");f(`${P}: ${U}`);return}j(P),f(null);try{const W=await s(t,"magi_kind_panel_set",{kind:P,slots:$.slots,...R?{meshId:R}:{}}),U=L(W);if((U==null?void 0:U.success)===!1)throw new Error(U.error||a("mesh.magiKind.errorSave"));await F()}catch(W){f((W==null?void 0:W.message)||a("mesh.magiKind.errorSave"))}finally{j(null)}},[t,s,N,F,R,a]),J=l.useCallback(async P=>{if(!(!t||!s)&&confirm(a("mesh.magiKind.removeConfirm",{kind:P}))){j(P),f(null);try{const $=await s(t,"magi_kind_panel_remove",{kind:P,...R?{meshId:R}:{}}),W=L($);if((W==null?void 0:W.success)===!1)throw new Error(W.error||a("mesh.magiKind.errorRemove"));await F()}catch($){f(($==null?void 0:$.message)||a("mesh.magiKind.errorRemove"))}finally{j(null)}}},[t,s,F,R,a]),K=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${c.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,M="btn btn-primary btn-sm",D="btn btn-secondary btn-sm";return n.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[n.jsx("div",{className:"flex flex-wrap items-center gap-2",children:n.jsx("div",{className:"ml-auto flex items-center gap-2",children:n.jsx("button",{type:"button",className:D,onClick:()=>void F(),disabled:h||!O,children:a(h?"mesh.magiKind.loading":"mesh.magiKind.refresh")})})}),!O&&n.jsx("div",{className:`rounded-xl border p-3 text-xs ${c.textSecondary} ${c.isDark?"border-white/10":"border-slate-200"}`,children:a("mesh.magiKind.connectPrompt")}),g&&n.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-xs text-rose-300",children:g}),n.jsx("div",{className:"flex flex-col gap-3",children:QP.map(({kind:P,labelKey:$,hint:W})=>{const U=N(P),ae=!!u[P],be=k===P;return n.jsxs("div",{className:`${c.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:`text-xxs font-semibold ${c.textPrimary}`,children:a($)}),n.jsx("span",{className:`font-mono text-3xs ${c.textMuted}`,children:W}),n.jsx("span",{className:`rounded-full border px-2 py-0.5 text-3xs uppercase tracking-[0.14em] ${ae?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:ae?a("mesh.magiKind.agentCount",{count:u[P].length}):a("mesh.magiKind.off")})]}),n.jsxs("div",{className:"flex flex-col gap-2",children:[U.length===0&&n.jsx("div",{className:`rounded-xl border p-2.5 text-2xs ${c.textSecondary} ${c.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:a("mesh.magiKind.noAgents")}),U.map((V,we)=>{const ce=V.nodeId?_[V.nodeId]??[]:[],de=V.nodeId&&ce.length?ce:A;return n.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${c.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:`text-4xs uppercase tracking-wide ${c.textSecondary}`,children:a("mesh.magiKind.machine")}),n.jsxs("select",{className:K,value:V.nodeId,onChange:ne=>B(P,we,{nodeId:ne.target.value}),title:a("mesh.magiKind.machineTitle"),children:[n.jsx("option",{value:"",children:a("mesh.magiKind.anyMachine")}),C.map(ne=>{const ee=x.has(ne),ue=ee?a("mesh.magiKind.worktreeSuffix",{label:w[ne]??ne,branch:S[ne]||a("mesh.magiKind.worktreeUnknownBranch")}):w[ne]??ne;return n.jsx("option",{value:ne,disabled:ee,title:ee?a("mesh.magiKind.worktreeDisabledTitle"):void 0,children:ue},ne)}),V.nodeId&&!C.includes(V.nodeId)&&n.jsx("option",{value:V.nodeId,children:a("mesh.magiKind.offlineSuffix",{label:w[V.nodeId]??V.nodeId})})]})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsxs("span",{className:`text-4xs uppercase tracking-wide ${c.textSecondary}`,children:[a("mesh.magiKind.provider")," *"]}),n.jsxs("select",{className:K,value:V.provider,onChange:ne=>B(P,we,{provider:ne.target.value}),title:a("mesh.magiKind.providerTitle"),children:[n.jsx("option",{value:"",children:a("mesh.magiKind.selectProvider")}),de.map(ne=>n.jsx("option",{value:ne,children:ne},ne)),V.provider&&!de.includes(V.provider)&&n.jsx("option",{value:V.provider,children:V.provider})]})]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:`text-4xs uppercase tracking-wide ${c.textSecondary}`,children:a("mesh.magiKind.model")}),(()=>{var ue;const ne=(V.provider?(ue=d.get(V.provider))==null?void 0:ue.models:void 0)??[],ee=!!V.model&&ne.length>0&&!ne.includes(V.model);return ne.length>0&&!ee?n.jsxs("select",{className:K,value:ne.includes(V.model)?V.model:"",title:a("mesh.magiKind.modelTitle"),onChange:je=>B(P,we,{model:je.target.value==="__custom__"?" ":je.target.value}),children:[n.jsx("option",{value:"",children:a("mesh.magiKind.modelDefault")}),ne.map(je=>n.jsx("option",{value:je,children:je},je)),n.jsx("option",{value:"__custom__",children:a("mesh.magiKind.modelCustom")})]}):n.jsxs(n.Fragment,{children:[n.jsx("input",{className:K,value:V.model.trim(),placeholder:a("mesh.magiKind.modelDefault"),title:a("mesh.magiKind.modelTitle"),onChange:je=>B(P,we,{model:je.target.value})}),ne.length>0&&n.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-3xs ${c.textSecondary} hover:underline`,onClick:()=>B(P,we,{model:""}),children:a("mesh.magiKind.backToModelList")})]})})()]}),n.jsxs("label",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:`text-4xs uppercase tracking-wide ${c.textSecondary}`,children:a("mesh.magiKind.copies")}),n.jsx("input",{className:`${K} sm:w-16`,value:V.n,placeholder:"1",inputMode:"numeric",title:a("mesh.magiKind.copiesTitle"),onChange:ne=>B(P,we,{n:ne.target.value})})]}),n.jsx("button",{type:"button",className:`${D} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>H(P,we),"aria-label":a("mesh.magiKind.removeAgent"),title:a("mesh.magiKind.removeAgent"),children:"✕"})]},we)}),n.jsx("div",{children:n.jsx("button",{type:"button",className:D,onClick:()=>T(P),disabled:!O,children:a("mesh.magiKind.addAgent")})})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",className:M,onClick:()=>void q(P),disabled:be||!O,children:a(be?"mesh.magiKind.saving":"mesh.magiKind.save")}),n.jsx("button",{type:"button",className:D,onClick:()=>void J(P),disabled:be||!O||!ae,title:a(ae?"mesh.magiKind.removeBindingTitle":"mesh.magiKind.removeBindingDisabledTitle"),children:a("mesh.magiKind.removeBinding")})]})]},P)})})]})}const Wi=l.createContext(nu("dark"));function no({label:e,tone:t="default",className:s,title:r}){const o=l.useContext(Wi),a=n.jsx("span",{className:`rounded-full border pl-2 pr-[calc(0.5rem-0.16em)] py-0.5 text-[10px] leading-none align-middle uppercase tracking-[0.16em] ${o.badge(t)}${s?` ${s}`:""}`,children:e});return r?n.jsx(tn,{content:r,children:a}):a}function z5({label:e,value:t}){const s=l.useContext(Wi);return n.jsxs("div",{className:s.rowClass,children:[n.jsx("span",{className:s.rowLabelClass,children:e}),n.jsx("span",{className:s.rowValueClass,children:t})]})}const tL="You are one independent member of a multi-agent cross-verification quorum";function nL(e){var r,o;const t=(e??"").trim();if(!t)return"";if(!t.startsWith(tL))return t;const s=(o=(r=t.match(/\n## Question\n([\s\S]*?)(?:\n## |$)/))==null?void 0:r[1])==null?void 0:o.trim().replace(/\s+/g," ");return s?`MAGI cross-verify — ${s}`:"MAGI cross-verification task"}function hx(e){let t=e??"";return t?(t=t.replace(/^```[^\n]*\n?/gm,""),t=t.replace(/^#{1,6}\s+/gm,""),t=t.replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm,""),t=t.replace(/^>\s?/gm,""),t=t.replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"$2"),t=t.replace(/(^|\W)[*_](?=\S)([^*_\n]*\S)[*_](?=\W|$)/g,"$1$2"),t=t.replace(/`([^`\n]*)`/g,"$1"),t=t.replace(/[ \t]{2,}/g," "),t=t.replace(/\n{3,}/g,`
|
|
103
|
-
|
|
104
|
-
`),t.trim()):""}function G5(e){return hx(nL(e))}const ba=["provider_quirk","pattern_to_avoid","recovery_lesson"],Yh=240,sL={provider_quirk:"warn",pattern_to_avoid:"danger",recovery_lesson:"good"};function Hl(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 xa(e){return Po(e)}function rL({meshId:e,daemonId:t,sendDaemonCommand:s}){const{t:r}=ve("common"),o=l.useContext(Wi),[a,i]=l.useState([]),[c,d]=l.useState(!1),[u,m]=l.useState(null),[h,p]=l.useState(!1),[g,f]=l.useState(!1),[y,b]=l.useState(""),[k,j]=l.useState(""),[v,C]=l.useState(new Set),[x,S]=l.useState(null),[w,_]=l.useState(""),[A,O]=l.useState(""),L=!!(s&&t&&e),R=l.useCallback(async()=>{if(!(!s||!t||!e)){d(!0),m(null);try{const K=await s(t,"list_mesh_notes",{meshId:e,tail:100}),M=(K==null?void 0:K.result)??K;if(M&&M.success===!1){m(typeof M.error=="string"?M.error:r("mesh.notes.loadFailed")),i([]);return}const D=Array.isArray(M==null?void 0:M.notes)?M.notes:[];i([...D].reverse())}catch(K){m(K instanceof Error?K.message:r("mesh.notes.loadFailed")),i([])}finally{d(!1)}}},[s,t,e,r]);l.useEffect(()=>{R()},[R]);const F=l.useCallback(async()=>{if(!s||!t||!e)return;const K=y.trim();if(!(!K||h)){p(!0),m(null);try{const M=await s(t,"record_mesh_note",{meshId:e,text:K,...k?{category:k}:{}}),D=(M==null?void 0:M.result)??M;if(D&&D.success===!1){m(typeof D.error=="string"?D.error:r("mesh.notes.saveFailed"));return}b(""),j(""),f(!1),await R()}catch(M){m(M instanceof Error?M.message:r("mesh.notes.saveFailed"))}finally{p(!1)}}},[s,t,e,y,k,h,R,r]),N=l.useCallback(async K=>{if(!(!s||!t||!e||h)){p(!0),m(null);try{const M=await s(t,"forget_mesh_note",{meshId:e,noteId:K}),D=(M==null?void 0:M.result)??M;if(D&&D.success===!1){m(typeof D.error=="string"?D.error:r("mesh.notes.deleteFailed"));return}await R()}catch(M){m(M instanceof Error?M.message:r("mesh.notes.deleteFailed"))}finally{p(!1)}}},[s,t,e,h,R,r]),I=l.useCallback(K=>{S(K.id),_(K.text),O(ba.includes(K.category)?K.category:"")},[]),B=l.useCallback(()=>{S(null),_(""),O("")},[]),T=l.useCallback(async K=>{if(!s||!t||!e||h)return;const M=w.trim();if(M){p(!0),m(null);try{const D=await s(t,"forget_mesh_note",{meshId:e,noteId:K}),P=(D==null?void 0:D.result)??D;if(P&&P.success===!1){m(typeof P.error=="string"?P.error:r("mesh.notes.editFailed"));return}const $=await s(t,"record_mesh_note",{meshId:e,text:M,...A?{category:A}:{}}),W=($==null?void 0:$.result)??$;if(W&&W.success===!1){m(typeof W.error=="string"?W.error:r("mesh.notes.editFailed"));return}B(),await R()}catch(D){m(D instanceof Error?D.message:r("mesh.notes.editFailed"))}finally{p(!1)}}},[s,t,e,w,A,h,B,R,r]),H=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",J=K=>`rounded-lg border px-2.5 py-1 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-45 ${o.actionButton(K)}`;return L?n.jsxs("div",{className:"flex flex-col gap-3",children:[g?n.jsxs("div",{className:`${o.cardClass} rounded-2xl p-4`,children:[n.jsx("div",{className:`mb-2 text-sm font-semibold ${o.textPrimary}`,children:r("mesh.notes.addTitle")}),n.jsx("textarea",{value:y,onChange:K=>b(K.target.value),rows:2,placeholder:r("mesh.notes.textPlaceholder"),className:q,autoFocus:!0}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[n.jsxs("select",{value:k,onChange:K=>j(K.target.value),className:H,"aria-label":r("mesh.notes.categoryLabel"),children:[n.jsx("option",{value:"",children:r("mesh.notes.categoryUncategorized")}),ba.map(K=>n.jsx("option",{value:K,children:Hl(r,K)},K))]}),n.jsx("button",{type:"button",onClick:()=>{F()},disabled:h||!y.trim(),className:J("success"),children:r("mesh.notes.add")}),n.jsx("button",{type:"button",onClick:()=>f(!1),disabled:h,className:J("default"),children:r("mesh.notes.cancel")})]})]}):n.jsx("div",{children:n.jsxs("button",{type:"button",onClick:()=>f(!0),className:J("info"),children:["+ ",r("mesh.notes.addTitle")]})}),u&&n.jsx("div",{className:o.isDark?"rounded-xl border border-rose-400/20 bg-rose-500/10 px-3 py-2 text-xs text-rose-100":"rounded-xl border border-rose-300 bg-rose-50 px-3 py-2 text-xs text-rose-700",children:u}),n.jsxs("div",{className:`${o.cardClass} rounded-2xl p-4`,children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[n.jsx("div",{className:`text-sm font-semibold ${o.textPrimary}`,children:r("mesh.notes.listTitle")}),n.jsx(Di,{onClick:()=>{R()},refreshing:c,disabled:h,label:r("mesh.notes.refresh"),size:13,className:"h-7 w-7"})]}),c?n.jsx("div",{className:`py-6 text-center text-sm ${o.textMuted}`,children:r("mesh.notes.loading")}):a.length===0?n.jsx("div",{className:`py-6 text-center text-sm ${o.textMuted}`,children:r("mesh.notes.empty")}):n.jsx("div",{className:"flex flex-col gap-2",children:a.map(K=>n.jsx("div",{className:`rounded-xl border px-3 py-2.5 ${o.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:x===K.id?n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("textarea",{value:w,onChange:M=>_(M.target.value),rows:2,className:q}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsxs("select",{value:A,onChange:M=>O(M.target.value),className:H,"aria-label":r("mesh.notes.categoryLabel"),children:[n.jsx("option",{value:"",children:r("mesh.notes.categoryUncategorized")}),ba.map(M=>n.jsx("option",{value:M,children:Hl(r,M)},M))]}),n.jsx("button",{type:"button",onClick:()=>{T(K.id)},disabled:h||!w.trim(),className:J("success"),children:r("mesh.notes.save")}),n.jsx("button",{type:"button",onClick:B,disabled:h,className:J("default"),children:r("mesh.notes.cancel")})]})]}):n.jsxs(n.Fragment,{children:[(()=>{const M=hx(K.text),D=v.has(K.id),P=M.length>Yh,$=!P||D?M:`${M.slice(0,Yh).trimEnd()}…`;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`whitespace-pre-wrap break-words text-sm ${o.textPrimary}`,children:$}),P&&n.jsx("button",{type:"button",onClick:()=>C(W=>{const U=new Set(W);return U.has(K.id)?U.delete(K.id):U.add(K.id),U}),className:`mt-1 text-2xs font-medium ${o.isDark?"text-sky-300 hover:text-sky-200":"text-sky-600 hover:text-sky-700"}`,children:r(D?"mesh.notes.showLess":"mesh.notes.showMore")})]})})(),n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[n.jsx(no,{label:Hl(r,K.category),tone:ba.includes(K.category)?sL[K.category]:"default"}),K.pinned&&n.jsx(no,{label:r("mesh.notes.pinned"),tone:"info"}),K.expired?n.jsx(no,{label:r("mesh.notes.expired"),tone:"danger"}):K.pinned?n.jsx(no,{label:r("mesh.notes.neverExpires"),tone:"default"}):xa(K.effectiveExpiresAt)?n.jsx("span",{className:`text-2xs ${o.textMuted}`,title:K.effectiveExpiresAt,children:r("mesh.notes.expiresIn",{when:xa(K.effectiveExpiresAt)})}):n.jsx(no,{label:r("mesh.notes.durable"),tone:"default"}),xa(K.createdAt)&&n.jsx("span",{className:`text-2xs ${o.textMuted}`,children:xa(K.createdAt)}),n.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>I(K),disabled:h,className:J("info"),children:r("mesh.notes.edit")}),n.jsx("button",{type:"button",onClick:()=>{N(K.id)},disabled:h,className:J("default"),children:r("mesh.notes.delete")})]})]})]})},K.id))})]})]}):n.jsx("div",{className:`${o.cardClass} rounded-2xl p-4 text-xs ${o.textSecondary}`,children:r("mesh.notes.unavailable")})}const fr={sessionMinRemainingPercent:10,weeklyMinRemainingPercent:15,sessionResetImminentMinutes:5,staleAfterMinutes:30,spreadBonusMax:30,sessionAxisWeeklyHeadroomPercent:40},Uc=60*1e3;function Qh(e){return e===void 0||!Number.isFinite(e)?"":String(e/Uc)}function Da(e){const t=e??{};return{sessionMinRemainingPercent:t.sessionMinRemainingPercent!==void 0?String(t.sessionMinRemainingPercent):"",weeklyMinRemainingPercent:t.weeklyMinRemainingPercent!==void 0?String(t.weeklyMinRemainingPercent):"",sessionResetImminentMinutes:Qh(t.sessionResetImminentMs),staleAfterMinutes:Qh(t.staleAfterMs),spreadBonusMax:t.spreadBonusMax!==void 0?String(t.spreadBonusMax):"",sessionAxisWeeklyHeadroomPercent:t.sessionAxisWeeklyHeadroomPercent!==void 0?String(t.sessionAxisWeeklyHeadroomPercent):""}}function oL(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 Kc(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*Uc);const i=s(e.staleAfterMinutes);i!==void 0&&(t.staleAfterMs=i*Uc);const c=s(e.spreadBonusMax);c!==void 0&&(t.spreadBonusMax=c);const d=s(e.sessionAxisWeeklyHeadroomPercent);return d!==void 0&&(t.sessionAxisWeeklyHeadroomPercent=d),t}const aL="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs",iL="w-full rounded-lg border border-red-500/60 bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function lL({quotaRouting:e,saving:t,error:s,onSave:r,hideHeader:o=!1}){const{t:a}=ve("common"),[i,c]=l.useState(()=>Da(e)),d=l.useCallback((k,j)=>{c(v=>({...v,[k]:j}))},[]),u=l.useMemo(()=>{const k={};for(const j of Object.keys(i)){const v=oL(j,i[j]);v&&(k[j]=v)}return k},[i]),m=Object.keys(u).length>0,h=l.useMemo(()=>JSON.stringify(Kc(i))!==JSON.stringify(Jh(e)),[i,e]),p=l.useRef(!1),g=JSON.stringify(Jh(e));l.useEffect(()=>{p.current||c(Da(e))},[g]);const f=l.useCallback(()=>{p.current=!1,!(m||!h)&&r(Kc(i))},[h,i,m,r]),y=l.useCallback(()=>{c(Da(null)),r({})},[r]),b=[{key:"sessionMinRemainingPercent",label:a("setupWizard.quotaPolicy.sessionMin"),hint:a("setupWizard.quotaPolicy.sessionMinHint"),placeholder:fr.sessionMinRemainingPercent,unit:"%"},{key:"weeklyMinRemainingPercent",label:a("setupWizard.quotaPolicy.weeklyMin"),hint:a("setupWizard.quotaPolicy.weeklyMinHint"),placeholder:fr.weeklyMinRemainingPercent,unit:"%"},{key:"sessionResetImminentMinutes",label:a("setupWizard.quotaPolicy.resetImminent"),hint:a("setupWizard.quotaPolicy.resetImminentHint"),placeholder:fr.sessionResetImminentMinutes,unit:a("setupWizard.quotaPolicy.minutes")},{key:"staleAfterMinutes",label:a("setupWizard.quotaPolicy.staleAfter"),hint:a("setupWizard.quotaPolicy.staleAfterHint"),placeholder:fr.staleAfterMinutes,unit:a("setupWizard.quotaPolicy.minutes")},{key:"spreadBonusMax",label:a("setupWizard.quotaPolicy.spreadBonus"),hint:a("setupWizard.quotaPolicy.spreadBonusHint"),placeholder:fr.spreadBonusMax,unit:""},{key:"sessionAxisWeeklyHeadroomPercent",label:a("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroom"),hint:a("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroomHint"),placeholder:fr.sessionAxisWeeklyHeadroomPercent,unit:"%"}];return n.jsxs("div",{className:"flex flex-col gap-3",children:[!o&&n.jsxs("h3",{className:"flex items-center gap-1 text-sm font-semibold text-text-primary",children:[a("setupWizard.quotaPolicy.title"),n.jsx(dt,{content:a("setupWizard.quotaPolicy.description")})]}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-2",children:b.map(k=>{const j=u[k.key],v=`quota-policy-${k.key}`;return n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsxs("span",{className:"flex items-center gap-1 text-2xs text-text-muted",children:[n.jsxs("label",{htmlFor:v,children:[k.label,k.unit?` (${k.unit})`:""]}),n.jsx(dt,{content:k.hint,size:12})]}),n.jsx("input",{id:v,type:"number",inputMode:"decimal",className:j?iL:aL,value:i[k.key],placeholder:String(k.placeholder),"aria-invalid":j?!0:void 0,onChange:C=>{p.current=!0,d(k.key,C.target.value)},onBlur:f,onKeyDown:C=>{C.key==="Enter"&&f()}}),j&&n.jsx("span",{className:"text-3xs leading-snug text-red-400",children:a(`setupWizard.quotaPolicy.errors.${j}`)})]},k.key)})}),s?n.jsx("p",{className:"text-2xs text-red-400",children:s}):null,n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:y,disabled:!!t,children:a("setupWizard.quotaPolicy.useDefaults")}),n.jsxs("span",{className:"flex items-center gap-1 text-3xs text-text-muted",children:[a(t?"setupWizard.quotaPolicy.saving":"setupWizard.quotaPolicy.blankMeansDefaultShort"),!t&&n.jsx(dt,{content:a("setupWizard.quotaPolicy.blankMeansDefault"),size:12})]})]})]})}function Jh(e){return Kc(Da(e))}function cL(e,t,s,r){const{t:o}=ve(),[a,i]=l.useState(!1),[c,d]=l.useState(null),[u,m]=l.useState(null),[h,p]=l.useState(null),g=l.useCallback(async()=>{if(!e||!t){d(o("mesh.promptPreview.connectPrompt"));return}i(!0),d(null);try{const f=await r(e,"coordinator_prompt_preview",{meshId:t,cliType:s}),y=f!=null&&f.result&&typeof f.result=="object"?f.result:f;if(!(y!=null&&y.success))return d((y==null?void 0:y.error)||o("mesh.promptPreview.errorRender")),null;const b=typeof y.prompt=="string"?y.prompt:"";return m(b),p(typeof y.bytes=="number"?y.bytes:null),b}catch(f){return d((f==null?void 0:f.message)||String(f)),null}finally{i(!1)}},[e,t,s,r,o]);return{loading:a,error:c,prompt:u,bytes:h,load:g}}function dL({daemonId:e,meshId:t,cliType:s,sendCommand:r,defaultOpen:o=!1}){const{t:a}=ve(),[i,c]=l.useState(o),{loading:d,error:u,prompt:m,bytes:h,load:p}=cL(e,t,s,r),g=l.useRef(!1);l.useEffect(()=>{i&&!g.current&&(g.current=!0,p())},[i,p]);const f=l.useCallback(()=>{c(y=>!y)},[]);return n.jsxs("div",{className:"mt-2",children:[n.jsxs("button",{type:"button",onClick:f,className:"inline-flex items-center gap-1 text-xs text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[n.jsx("span",{className:`transition-transform ${i?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),a(i?"mesh.promptPreview.hide":"mesh.promptPreview.view"),n.jsxs("span",{className:"text-text-muted",children:["(",s,")"]})]}),i&&n.jsxs("div",{className:"mt-2",children:[d&&n.jsx("div",{className:"text-xs text-text-muted",children:a("mesh.promptPreview.rendering")}),u&&n.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-300",children:[u,n.jsx("button",{type:"button",onClick:()=>void p(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:a("mesh.promptPreview.retry")})]}),!d&&!u&&m!==null&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between text-2xs text-text-muted",children:[n.jsx(dt,{content:`${a("mesh.promptPreview.info")}
|
|
105
|
-
${a("mesh.promptPreview.launchScopeNote")}`,size:12}),h!==null&&n.jsxs("span",{children:[(h/1024).toFixed(1)," KB"]})]}),n.jsx("textarea",{readOnly:!0,value:m,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-xs text-text-secondary font-mono",onFocus:y=>y.currentTarget.select()})]})]})]})}function uL(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 mL({daemonId:e,workspace:t,sendCommand:s}){const{t:r}=ve(),[o,a]=l.useState(null),i=l.useCallback(async()=>{if(!e||!t){a(null);return}try{const c=await s(e,"read_mesh_json_config",{workspace:t});a(uL(c))}catch{a(null)}},[e,t,s]);return l.useEffect(()=>{i()},[i]),o?o.sourceType==="invalid"?n.jsxs("div",{className:"mt-3 rounded-lg border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-300",children:[r("mesh.detail.repoMeshJsonInvalid"),o.error&&n.jsx("span",{className:"ml-1 font-mono text-2xs opacity-80",children:o.error})]}):n.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[n.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-1",children:[n.jsx("span",{className:"text-[13px] leading-tight font-semibold",children:r("mesh.detail.repoMeshJsonTitle")}),n.jsx(dt,{content:`${r("mesh.detail.repoMeshJsonHint")}${o.path?`
|
|
106
|
-
${o.path}`:""}`,size:12})]}),o.override.trim()&&n.jsxs("div",{className:"mb-2",children:[n.jsx("label",{className:"mb-1 block text-2xs uppercase tracking-wide text-text-muted",children:r("mesh.detail.repoMeshJsonOverrideLabel")}),n.jsx("textarea",{readOnly:!0,value:o.override,rows:4,className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 font-mono text-xs text-text-secondary",onFocus:c=>c.currentTarget.select()})]}),o.append.trim()&&n.jsxs("div",{children:[n.jsx("label",{className:"mb-1 block text-2xs uppercase tracking-wide text-text-muted",children:r("mesh.detail.repoMeshJsonAppendLabel")}),n.jsx("textarea",{readOnly:!0,value:o.append,rows:4,className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 font-mono text-xs text-text-secondary",onFocus:c=>c.currentTarget.select()})]})]}):null}const hL=[{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 Xh(e,t){if(t)return e.modes.find(s=>s.id===t)}function pL(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&Yn(t)!=="dangerous")}function fL({config:e,requestedModeId:t,machineAutoApproveEnabled:s,machineDangerousAllowed:r}){const o=Xh(e,e.default),a=o==null?void 0:o.id,i=(t==null?void 0:t.trim())||void 0;if(!s)return{status:"disabled",requestedModeId:i,providerDefaultModeId:a,requestedModeUnknown:!1,downgraded:!1};const c=Xh(e,i),d=!!i&&!c,u=c??o;if(!u||u.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:a,requestedModeUnknown:d,downgraded:!1};if(Yn(u)==="dangerous"&&!r){const m=pL(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 gL(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 bL({hostDaemonId:e,hostOnline:t,hostWorkspace:s,meshProviders:r,unreportedNodeCount:o=0,machineAutoApproveEnabled:a,machineDangerousAllowed:i,onUpdatePolicy:c,savingPolicy:d,sendCommand:u}){const{t:m}=ve("common"),h=l.useMemo(()=>gL(r),[r]),[p,g]=l.useState({}),[f,y]=l.useState(!1),[b,k]=l.useState(null),[j,v]=l.useState(!1),[C,x]=l.useState(null),[S,w]=l.useState(!1),[_,A]=l.useState(null),[O,L]=l.useState(!1),R=!!e&&t&&!!s,F=!!c&&!d,N=l.useCallback(async()=>{var K,M,D;if(R){y(!0),k(null);try{const P=await u(e,"read_mesh_json_config",{workspace:s}),$=(P==null?void 0:P.result)??P,W=((K=$==null?void 0:$.providerDefaults)==null?void 0:K.autoApproveModes)||((D=(M=$==null?void 0:$.config)==null?void 0:M.providerDefaults)==null?void 0:D.autoApproveModes),U={};if(W&&typeof W=="object")for(const[ae,be]of Object.entries(W))typeof be=="string"&&be.trim()&&(U[ae]=be.trim());g(U)}catch(P){k((P==null?void 0:P.message)||m("mesh.providerAutoApprove.loadError"))}finally{y(!1)}}},[R,e,s,u,m]);l.useEffect(()=>{N()},[N]);const I=l.useRef(null),B=l.useRef(p);B.current=p;const T=l.useCallback((K,M)=>{var P;w(!1);const D={...B.current};M&&M.trim()?D[K]=M.trim():delete D[K],B.current=D,g(D),(P=I.current)==null||P.call(I,D)},[]),H=l.useCallback((K,M)=>{if(Yn(M)==="dangerous"){A({type:K,mode:M});return}T(K,M.id)},[T]),q=l.useCallback(()=>{_&&T(_.type,_.mode.id),A(null)},[T,_]),J=l.useCallback(async K=>{if(R){v(!0),x(null),w(!1);try{const M=await u(e,"set_mesh_provider_defaults",{workspace:s,autoApproveModes:K,merge:!1,write:!0}),D=(M==null?void 0:M.result)??M;if((D==null?void 0:D.success)===!1)throw new Error((D==null?void 0:D.error)||m("mesh.providerAutoApprove.saveError"));w(!0),ct.showToast(m("common.saved"),"success"),await N()}catch(M){x((M==null?void 0:M.message)||m("mesh.providerAutoApprove.saveError"))}finally{v(!1)}}},[R,e,s,N,u,m]);return I.current=J,n.jsxs(Nt,{title:m("mesh.providerAutoApprove.title"),collapsible:!0,defaultOpen:!1,children:[n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-3.5",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary",children:m("mesh.providerAutoApprove.machineSection.title")}),n.jsx(tn,{content:m("mesh.providerAutoApprove.machineSection.hint"),children:n.jsx("span",{className:"rounded-full border border-border-subtle bg-surface-secondary/40 px-2 py-0.5 text-3xs font-medium text-text-muted",children:m("mesh.providerAutoApprove.machineSection.chip")})})]}),n.jsxs("div",{className:"mt-3 space-y-2",children:[n.jsx(Zh,{label:m("mesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:m("mesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:a,disabled:!F,onChange:K=>c==null?void 0:c({delegatedWorkerAutoApprove:K})}),n.jsx(Zh,{label:m("mesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:m(a?"mesh.providerAutoApprove.machineSection.dangerousToggleHint":"mesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:i,disabled:!F||!a,onChange:K=>{K?L(!0):c==null||c({delegatedWorkerDangerousModeAllow:!1})}})]})]}),R?f?n.jsx("div",{className:"text-xxs text-text-muted",children:m("mesh.providerAutoApprove.loading")}):h.length===0?n.jsx("div",{className:"text-xxs text-text-muted",children:o>0?m("mesh.providerAutoApprove.awaitingNodes",{count:o}):m("mesh.providerAutoApprove.noProviders")}):n.jsxs("div",{className:"space-y-6",children:[b&&n.jsx(zt,{variant:"error",onDismiss:()=>k(null),children:b}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary",children:m("mesh.providerAutoApprove.repoSection.title")}),n.jsx(tn,{content:m("mesh.providerAutoApprove.repoSection.hint"),children:n.jsx("span",{className:"rounded-full border border-border-subtle bg-surface-secondary/40 px-2 py-0.5 text-3xs font-medium text-text-muted",children:m("mesh.providerAutoApprove.repoSection.chip")})}),o>0&&n.jsx(tn,{content:m("mesh.providerAutoApprove.partialInventory",{count:o}),children:n.jsx("span",{className:"rounded-full border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 text-3xs font-medium text-amber-400",children:m("mesh.providerAutoApprove.partialInventoryChip",{count:o})})}),j&&n.jsx("span",{className:"text-3xs text-text-muted",children:m("mesh.providerAutoApprove.saving")})]}),n.jsx("div",{className:"space-y-5",children:h.map(K=>{const M=p[K.type],D=fL({config:K.autoApproveModes,requestedModeId:M,machineAutoApproveEnabled:a,machineDangerousAllowed:i});return n.jsxs("div",{className:"rounded-xl border border-border-subtle p-3.5",children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[n.jsx("span",{className:"text-sm font-semibold text-text-primary",children:K.label}),n.jsx("button",{type:"button",className:"text-2xs text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>T(K.type,void 0),disabled:!M||j,children:m("mesh.providerAutoApprove.repoSection.clear")})]}),n.jsx(Gb,{config:K.autoApproveModes,selectedModeId:M||"",disabled:j,onSelectMode:P=>H(K.type,P)}),!M&&n.jsx("div",{className:"mt-1.5 text-2xs text-text-muted",children:m("mesh.providerAutoApprove.repoSection.usesProviderDefault")}),n.jsx(xL,{effective:D,config:K.autoApproveModes})]},K.type)})}),C&&n.jsx(zt,{variant:"error",onDismiss:()=>x(null),children:C}),S&&n.jsx("span",{className:"sr-only",role:"status",children:m("mesh.providerAutoApprove.saved")})]}):n.jsx("div",{className:"text-xxs text-text-muted",children:m("mesh.providerAutoApprove.noHostDaemon")}),O&&n.jsx(Oi,{title:m("mesh.providerAutoApprove.machineSection.confirmTitle"),description:m("mesh.providerAutoApprove.machineSection.confirmDescription"),details:[{label:m("mesh.providerAutoApprove.machineSection.confirmScopeLabel"),value:m("mesh.providerAutoApprove.machineSection.confirmScopeValue")},{label:m("mesh.providerAutoApprove.machineSection.confirmEffectLabel"),value:m("mesh.providerAutoApprove.machineSection.confirmEffectValue")}],confirmLabel:m("mesh.providerAutoApprove.machineSection.confirmConfirm"),onConfirm:()=>{L(!1),c==null||c({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>L(!1)}),_&&n.jsx(Vb,{mode:_.mode,onConfirm:q,onCancel:()=>A(null)}),_&&n.jsx("div",{className:"fixed inset-x-0 bottom-6 z-[60] mx-auto max-w-lg px-4",children:n.jsxs("div",{className:"rounded-xl border border-status-error/40 bg-bg-primary p-3.5 shadow-lg",children:[n.jsxs("div",{className:"flex items-center gap-1 text-sm font-semibold text-status-error",children:[m("mesh.providerAutoApprove.dangerous.sharedWarningTitle"),n.jsx(dt,{content:m("mesh.providerAutoApprove.dangerous.sharedWarningDetail")})]}),n.jsx("div",{className:"mt-1 text-xs text-text-muted",children:m("mesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function xL({effective:e,config:t}){var d,u,m,h;const{t:s}=ve("common"),r=p=>{var g;return(p?(g=t.modes.find(f=>f.id===p))==null?void 0:g.label:void 0)||p||""};let o,a=null,i="ok";switch(e.status){case"requested":o=s("mesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((d=e.effectiveMode)==null?void 0:d.label)||""});break;case"invalid_fallback":o=s("mesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((u=e.effectiveMode)==null?void 0:u.label)||""}),i="warn";break;case"downgraded":o=s("mesh.providerAutoApprove.effectiveSection.statusDowngraded",{mode:((m=e.effectiveMode)==null?void 0:m.label)||""}),a=s("mesh.providerAutoApprove.effectiveSection.statusDowngradedHint",{requested:r(e.requestedModeId)||r(e.providerDefaultModeId),mode:((h=e.effectiveMode)==null?void 0:h.label)||""}),i="warn";break;case"disabled":o=s("mesh.providerAutoApprove.effectiveSection.statusDisabled"),i="muted";break;default:o=s("mesh.providerAutoApprove.effectiveSection.statusNone"),i="muted"}const c=i==="ok"?"border-status-online/25 bg-status-online/5 text-text-secondary":i==="warn"?"border-status-warning/30 bg-status-warning/5 text-status-warning":"border-border-subtle bg-surface-secondary/30 text-text-muted";return n.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-lg border px-3 py-2 text-xs ${c}`,children:[e.effectiveMode&&n.jsx(zb,{risk:Yn(e.effectiveMode)}),n.jsx("span",{className:"min-w-0",children:o}),a&&n.jsx(dt,{content:a,size:12})]})}function Zh({label:e,hint:t,checked:s,disabled:r=!1,onChange:o}){const a=l.useId();return n.jsxs("div",{className:`flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-primary/60 px-3.5 py-2.5 ${r?"opacity-60":""}`,children:[n.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[n.jsx("span",{id:a,className:"text-xxs font-semibold text-text-primary",children:e}),n.jsx(dt,{content:t,size:12})]}),n.jsx(Br,{checked:s,disabled:r,onChange:o,"aria-labelledby":a})]})}function ya(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function yL({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:s,isHostNodeAttached:r,selectedHostNode:o,hostPinned:a,hostLabel:i,hostOnline:c,hostRebindDaemonId:d,onHostRebindDaemonIdChange:u,settingMeshHost:m,onSetMeshHost:h}){const{t:p}=ve("common");if(a)return n.jsxs(Nt,{title:p("mesh.host.title"),description:p("mesh.host.descriptionSet"),children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xxs text-text-primary ${c?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[n.jsx("span",{className:"text-text-muted",children:p("mesh.host.hostLabel")}),n.jsx("span",{className:"font-medium",children:i||p("mesh.host.unknown")}),n.jsxs("span",{className:c?"text-text-muted":"text-amber-400",children:["· ",p(c?"mesh.host.online":"mesh.host.offline")]})]}),(o==null?void 0:o.workspace)&&n.jsxs("span",{className:"text-xs text-text-muted",children:[p("mesh.host.hostNode")," ",n.jsx("span",{className:"font-mono text-text-secondary",children:o.workspace})]})]}),!c&&n.jsxs("div",{className:"mt-4",children:[n.jsx(zt,{variant:"warning",className:"mb-3",children:n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("strong",{children:p("mesh.host.hostOffline")}),n.jsx(dt,{content:p("mesh.host.hostOfflineText")})]})}),e.length>0?n.jsx(qt,{label:p("mesh.host.reconnectToCommand"),hint:p("mesh.host.reconnectToCommandHint"),children:n.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:d,onChange:y=>u(y.target.value),children:[n.jsx("option",{value:"",children:p("mesh.host.waitForHost")}),e.map(y=>n.jsx("option",{value:y.id,children:ya(y)},y.id))]})}):n.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-muted",children:p("mesh.host.noDaemonsToRoute")})]})]});const g=e.find(y=>y.id===t),f=h&&t?n.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>h(t),disabled:!!m,children:p(m?"mesh.host.settingHost":"mesh.host.setHostAction")}):null;return n.jsxs(Nt,{title:p("mesh.host.title"),description:p("mesh.host.descriptionUnset"),children:[n.jsx(zt,{variant:"info",className:"mb-4",children:n.jsx("strong",{children:p("mesh.host.setHostBanner")})}),e.length>0?n.jsxs(n.Fragment,{children:[t?n.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-muted",children:r?n.jsxs(n.Fragment,{children:[p("mesh.host.willHostOn")," ",n.jsx("span",{className:"font-medium text-text-primary",children:ya(g)}),o!=null&&o.workspace?n.jsxs(n.Fragment,{children:[" · ",p("mesh.host.setupNode")," ",n.jsx("span",{className:"font-mono text-text-secondary",children:o.workspace})]}):null,". ",p("mesh.host.confirmSetsHost")]}):n.jsxs(n.Fragment,{children:[p("mesh.host.willHostOn")," ",n.jsx("span",{className:"font-medium text-text-primary",children:ya(g)}),". ",p("mesh.host.attachNodeThenSetHost")]})}):n.jsx(qt,{label:p("mesh.host.hostDaemon"),hint:p("mesh.host.hostDaemonHint"),children:n.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:y=>s(y.target.value),children:[n.jsx("option",{value:"",children:p("mesh.host.resolvingHost")}),e.map(y=>n.jsx("option",{value:y.id,children:ya(y)},y.id))]})}),f&&n.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:f})]}):n.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-xs text-text-muted",children:p("mesh.host.noDaemonsToHost")})]})}function vL({meshId:e,availableCliAgents:t}){const{t:s}=ve(),r=t.find(a=>{const i=a.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||a.name.toLowerCase().includes("hermes")}),o=wb(r==null?void 0:r.meshCoordinator,{meshId:e});return o?n.jsx(Nt,{title:s("mesh.hermesMcp.title"),description:s("mesh.hermesMcp.description"),children:n.jsx(qb,{setup:o,providerName:(r==null?void 0:r.name)||s("mesh.hermesMcp.fallbackProvider")})}):null}const Bl=[{value:"preserve",labelKey:"mesh.sessionCleanup.preserve",descriptionKey:"mesh.sessionCleanup.preserveHint"},{value:"stop",labelKey:"mesh.sessionCleanup.stop",descriptionKey:"mesh.sessionCleanup.stopHint"},{value:"delete_stopped",labelKey:"mesh.sessionCleanup.deleteStopped",descriptionKey:"mesh.sessionCleanup.deleteStoppedHint"},{value:"stop_and_delete",labelKey:"mesh.sessionCleanup.stopAndDelete",descriptionKey:"mesh.sessionCleanup.stopAndDeleteHint"}],wL=[{value:"smart",labelKey:"mesh.detail.distributionSmart",summaryKey:"mesh.detail.distributionSmartSummary",descriptionKey:"mesh.detail.distributionSmartDescription"},{value:"in_order",labelKey:"mesh.detail.distributionInOrder",summaryKey:"mesh.detail.distributionInOrderSummary",descriptionKey:"mesh.detail.distributionInOrderDescription"}];function SL(e){return e==="smart"?"fitness":"first_eligible"}function kL(e,t){const s=e||"first_eligible";return s==="fitness"||s==="least_loaded"||s==="round_robin"||s==="priority_only"&&t!=null&&t.priorityConfigured?"smart":"in_order"}const jL={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function qc(e){return{...jL,...(e==null?void 0:e.policy)||{}}}function NL({selectedMesh:e,error:t,onDismissError:s,onBack:r,onDelete:o,displayedMeshStatus:a,graphError:i,onRefreshGraph:c,savingPolicy:d,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:h,savingCoordinatorPrompt:p,onSaveCoordinatorPrompt:g,daemons:f,coordinatorDaemonId:y,onCoordinatorDaemonIdChange:b,coordinatorCliType:k,isHostNodeAttached:j,selectedHostNode:v,hostPinned:C,hostLabel:x,hostOnline:S,hostRebindDaemonId:w,onHostRebindDaemonIdChange:_,settingMeshHost:A,onSetMeshHost:O,activeDaemon:L,activeDaemonId:R,meshQueue:F,userName:N,availableCliProviders:I,savingNodeSlotsId:B,onUpdateNodeSlots:T,savingNodeCapabilitiesId:H,onUpdateNodeCapabilities:q,nodeSystemPromptDrafts:J,onNodeSystemPromptDraftChange:K,savingNodeSystemPromptId:M,onSaveNodeSystemPrompt:D,selectedNodeId:P,onSelectNode:$,showAddNode:W,onShowAddNode:U,onCancelAddNode:ae,nodeWorkspace:be,onNodeWorkspaceChange:V,nodeProviderPriority:we,onNodeProviderPriorityChange:ce,nodeDaemonId:de,onNodeDaemonIdChange:ne,nodeCustomPath:ee,onNodeCustomPathChange:ue,nodePickerWorkspaces:je,nodePickerProviders:X,nodeOnboardingPlan:G,nodePlanLoading:z,attachableDaemons:ie,onAddNode:Ne,onRemoveNode:Be,availableCliAgents:Le,features:Je,sendCommand:Se}){const{t:he}=ve("common"),pe=qc(e),Ee=e.nodes||[],Y=(a==null?void 0:a.nodes)??null,me=l.useMemo(()=>kP(Ee,f,Y),[Ee,f,Y]),fe=Ee.some(ke=>{var et;const Ze=Number((et=ke.policy)==null?void 0:et.schedulingPriority);return Number.isFinite(Ze)&&Ze!==0}),E=!pe.schedulingStrategy,oe=l.useMemo(()=>Ee.some(ke=>{var Ze;return Array.isArray((Ze=ke.policy)==null?void 0:Ze.slots)&&ke.policy.slots.length>0}),[Ee]),Ie=E&&(oe||Ee.length>=2)?"smart":null,[Z,se]=l.useState(!1),ye=!!R&&!!e.id,{theme:Fe}=Ho(),Me=l.useMemo(()=>nu(Fe),[Fe]),De="w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",Te=pe.quotaRouting&&typeof pe.quotaRouting=="object"?pe.quotaRouting:{},He=Te.quotaBusyFallback!==!1,tt=kL(pe.schedulingStrategy,{priorityConfigured:fe}),Ct=n.jsxs(n.Fragment,{children:[Je.meshHostDaemonSection&&n.jsx(yL,{daemons:f,coordinatorDaemonId:y,onCoordinatorDaemonIdChange:b,isHostNodeAttached:j,selectedHostNode:v,hostPinned:C,hostLabel:x,hostOnline:S,hostRebindDaemonId:w,onHostRebindDaemonIdChange:ke=>{_(ke),c()},settingMeshHost:A,onSetMeshHost:O}),n.jsx(WP,{nodes:Ee,statusNodes:Y,meshQueue:F,activeDaemon:L,daemons:f,selectedMeshId:e.id,userName:N,features:{addNodeDaemonPicker:Je.addNodeDaemonPicker,nodeInstruction:Je.nodeInstruction},coordinatorDaemonId:y,availableCliProviders:I,savingNodeSlotsId:B,onUpdateNodeSlots:T,savingNodeCapabilitiesId:H,onUpdateNodeCapabilities:q,nodeSystemPromptDrafts:J,onNodeSystemPromptDraftChange:K,savingNodeSystemPromptId:M,onSaveNodeSystemPrompt:D,selectedNodeId:P,onSelectNode:$,showAddNode:W,onShowAddNode:U,onCancelAddNode:ae,nodeWorkspace:be,onNodeWorkspaceChange:V,nodeProviderPriority:we,onNodeProviderPriorityChange:ce,nodeDaemonId:de,onNodeDaemonIdChange:ne,nodeCustomPath:ee,onNodeCustomPathChange:ue,nodePickerWorkspaces:je,nodePickerProviders:X,nodeOnboardingPlan:G,nodePlanLoading:z,attachableDaemons:ie,onAddNode:Ne,onRemoveNode:Be}),n.jsx(Nt,{title:he("mesh.detail.distribution"),children:n.jsxs("fieldset",{className:"border-none p-0 m-0",children:[n.jsx("legend",{className:"sr-only",children:he("mesh.detail.distribution")}),n.jsx("div",{className:"flex flex-col gap-2",children:wL.map(ke=>{const Ze=tt===ke.value;return n.jsxs("label",{className:`flex items-center gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Ze?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[n.jsx("input",{type:"radio",name:"mesh-distribution",className:"accent-[var(--accent-primary)]",value:ke.value,checked:Ze,disabled:d,onChange:()=>u({schedulingStrategy:SL(ke.value)})}),n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[he(ke.labelKey),Ie===ke.value&&n.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-3xs font-medium text-accent-primary",children:he("mesh.detail.recommended")})]}),n.jsx("span",{className:"block truncate text-xs text-text-muted",children:he(ke.summaryKey)})]}),n.jsx(dt,{content:he(ke.descriptionKey)})]},ke.value)})})]})}),n.jsx(Nt,{title:he("mesh.detail.visibilityTitle"),description:he("mesh.detail.visibilityHint"),children:n.jsxs("select",{className:De,"aria-label":he("mesh.detail.visibilityLabel"),value:pe.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:ke=>u({spawnedSessionVisibility:ke.target.value==="visible"?"visible":"hidden"}),disabled:d,children:[n.jsx("option",{value:"hidden",children:he("mesh.detail.visibilityHidden")}),n.jsx("option",{value:"visible",children:he("mesh.detail.visibilityVisible")})]})}),n.jsx(bL,{hostDaemonId:y,hostOnline:S,hostWorkspace:(v==null?void 0:v.workspace)||"",meshProviders:me.providers,unreportedNodeCount:me.unreportedNodeCount,machineAutoApproveEnabled:pe.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:pe.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:u,savingPolicy:d,sendCommand:Se})]}),Q=pe.autoFastForward&&typeof pe.autoFastForward=="object"?pe.autoFastForward:{},re=Q.enabled!==!1,le=Q.remoteNodes===!0,xe=Q.mode==="continuous"?"continuous":"idle",Ce=ke=>u({autoFastForward:{...Q,...ke}}),Re=Bl.find(ke=>ke.value===pe.sessionCleanupOnNodeRemove)??Bl[0],Ue=n.jsxs(n.Fragment,{children:[n.jsxs(Nt,{title:he("setupWizard.quotaPolicy.title"),description:he("setupWizard.quotaPolicy.description"),collapsible:!0,defaultOpen:!1,children:[n.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[n.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-sm text-text-primary",children:[n.jsx("span",{id:"mesh-quota-busy-fallback-label",children:he("mesh.detail.quotaBusyFallback")}),n.jsx(dt,{content:he("mesh.detail.quotaBusyFallbackHint")})]}),n.jsx(Br,{checked:He,disabled:d,"aria-labelledby":"mesh-quota-busy-fallback-label",onChange:ke=>u({quotaRouting:{...Te,quotaBusyFallback:ke}})})]}),n.jsx(lL,{quotaRouting:pe.quotaRouting??null,saving:d,error:t,hideHeader:!0,onSave:ke=>u({quotaRouting:{...ke,...Te.quotaBusyFallback!==void 0?{quotaBusyFallback:Te.quotaBusyFallback}:{}}})})]}),n.jsx(Nt,{title:he("mesh.detail.magiTitle"),collapsible:!0,defaultOpen:!1,description:he("mesh.detail.magiDescription"),children:n.jsx(eL,{status:a,daemonId:R,meshId:e.id,sendDaemonCommand:Se,availableProviders:I})}),n.jsxs(Nt,{title:he("mesh.detail.safetyTitle"),collapsible:!0,defaultOpen:!1,description:he("mesh.detail.safetyDescription"),children:[n.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:he("mesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no",he("mesh.detail.optionNo")],["yes",he("mesh.detail.optionYes")]],val:ke=>ke?"yes":"no",parse:ke=>ke==="yes"},{label:he("mesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes",he("mesh.detail.optionYes")],["no",he("mesh.detail.optionNo")]],val:ke=>ke?"yes":"no",parse:ke=>ke==="yes"},{label:he("mesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",he("mesh.detail.requireApprovalBeforePush")],["not_required",he("mesh.detail.doNotRequireApproval")]],val:ke=>ke?"required":"not_required",parse:ke=>ke==="required"},{label:he("mesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",he("mesh.detail.warnAndContinue")],["block",he("mesh.detail.blockTask")],["checkpoint_then_continue",he("mesh.detail.checkpointThenContinue")]],val:ke=>ke||"warn",parse:ke=>ke},{label:he("mesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",he("mesh.detail.requireExplicitApproval")],["enabled",he("mesh.detail.allowRefineryPublish")]],val:ke=>ke?"enabled":"disabled",parse:ke=>ke==="enabled"}].map(({label:ke,key:Ze,opts:et,val:Ve,parse:st})=>n.jsx(qt,{label:ke,children:n.jsx("select",{className:De,value:Ve(pe[Ze]),onChange:lt=>u({[Ze]:st(lt.target.value)}),disabled:d,children:et.map(([lt,Qe])=>n.jsx("option",{value:lt,children:Qe},lt))})},Ze))}),n.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[n.jsx(qt,{label:he("mesh.detail.autoFastForward"),children:n.jsxs("select",{className:De,value:re?"enabled":"disabled",onChange:ke=>Ce({enabled:ke.target.value==="enabled"}),disabled:d,children:[n.jsx("option",{value:"enabled",children:he("mesh.detail.ffEnabled")}),n.jsx("option",{value:"disabled",children:he("mesh.detail.ffDisabled")})]})}),n.jsx(qt,{label:he("mesh.detail.includeRemoteNodes"),hint:he("mesh.detail.includeRemoteNodesHint"),children:n.jsxs("select",{className:De,value:le?"yes":"no",onChange:ke=>Ce({remoteNodes:ke.target.value==="yes"}),disabled:d||!re,children:[n.jsx("option",{value:"no",children:he("mesh.detail.remoteNo")}),n.jsx("option",{value:"yes",children:he("mesh.detail.remoteYes")})]})}),n.jsx(qt,{label:he("mesh.detail.detectionMode"),hint:he("mesh.detail.detectionModeHint"),children:n.jsxs("select",{className:De,value:xe,onChange:ke=>Ce({mode:ke.target.value==="continuous"?"continuous":"idle"}),disabled:d||!re||!le,children:[n.jsx("option",{value:"idle",children:he("mesh.detail.idleEdgeOnly")}),n.jsx("option",{value:"continuous",children:he("mesh.detail.continuousScan")})]})}),n.jsx(qt,{label:he("mesh.detail.sessionCleanupLabel"),hint:`${he("mesh.detail.sessionCleanupHint")}
|
|
107
|
-
${he(Re.descriptionKey)}`,children:n.jsx("select",{className:De,value:pe.sessionCleanupOnNodeRemove||"preserve",onChange:ke=>u({sessionCleanupOnNodeRemove:ke.target.value}),disabled:d,children:Bl.map(ke=>n.jsx("option",{value:ke.value,children:he(ke.labelKey)},ke.value))})})]})]}),Je.coordinatorPrompt&&n.jsxs(Nt,{title:he("mesh.detail.coordinatorPromptTitle"),collapsible:!0,defaultOpen:!1,description:he("mesh.detail.thisMeshHint",{name:e.name}),children:[n.jsx(dL,{daemonId:R,meshId:e.id,cliType:k,sendCommand:Se,defaultOpen:!0}),n.jsx(qt,{label:he("mesh.detail.overrideLabel"),hint:he("mesh.detail.overrideHint"),className:"mt-3",children:n.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:ke=>h({...m,override:ke.target.value}),disabled:p,placeholder:he("mesh.detail.overridePlaceholder")})}),n.jsx(qt,{label:he("mesh.detail.appendLabel"),hint:he("mesh.detail.appendHint"),children:n.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:ke=>h({...m,append:ke.target.value}),disabled:p,placeholder:he("mesh.detail.appendPlaceholder")})}),n.jsx(mL,{daemonId:y,workspace:(v==null?void 0:v.workspace)||"",sendCommand:Se}),n.jsxs("details",{className:"mt-2 text-xs text-text-muted",children:[n.jsxs("summary",{className:"cursor-pointer select-none inline-flex items-center gap-1",children:[he("mesh.detail.availablePlaceholders"),n.jsx(dt,{content:he("mesh.detail.placeholdersIntro"),size:12})]}),n.jsx("div",{className:"mt-2 overflow-x-auto",children:n.jsx("table",{className:"w-full text-left border-collapse",children:n.jsx("tbody",{children:hL.map(ke=>n.jsxs("tr",{className:"border-t border-border-subtle/60 align-top",children:[n.jsx("td",{className:"py-1 pr-3 font-mono whitespace-nowrap text-text-secondary",children:`{{${ke.token}}}`}),n.jsx("td",{className:"py-1 pr-3",children:ke.description}),n.jsx("td",{className:"py-1 font-mono text-text-muted/80",children:ke.example})]},ke.token))})})})]}),n.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[n.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:g,disabled:p,children:he(p?"mesh.detail.saving":"mesh.detail.saveCoordinatorPrompt")}),n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h({override:"",append:""}),disabled:p,title:he("mesh.detail.clearTitle"),children:he("mesh.detail.clear")})]})]}),n.jsx(Nt,{title:he("mesh.notes.tab"),collapsible:!0,defaultOpen:!1,description:he("mesh.notes.sectionHint"),children:n.jsx(Wi.Provider,{value:Me,children:n.jsx(rL,{meshId:e.id,daemonId:R,sendDaemonCommand:Se})})}),Je.hermesMcpConfig&&n.jsx(vL,{meshId:e.id,availableCliAgents:Le}),Je.meshHostDaemonSection&&n.jsx(Nt,{title:he("mesh.detail.useFromCli"),collapsible:!0,defaultOpen:!1,description:he("mesh.detail.mcpDescription"),children:n.jsxs("code",{className:"block overflow-x-auto rounded-lg bg-bg-secondary px-3 py-2 text-xs",children:["adhdev mcp --repo-mesh ",e.id]})})]}),$e=[{key:"general",icon:n.jsx(Dr,{size:14}),label:he("mesh.detail.tabGeneral"),content:Ct},{key:"advanced",icon:n.jsx($p,{size:14}),label:he("mesh.detail.tabAdvanced"),content:Ue}];return n.jsxs($o,{icon:n.jsx(Gn,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",subtitleInline:!0,widthClassName:"max-w-5xl",contentClassName:"gap-4",actions:n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{className:"btn btn-secondary btn-sm",onClick:r,children:he("mesh.detail.back")}),n.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>se(!0),disabled:!ye,title:he(ye?"mesh.detail.observabilityOpenTitle":"mesh.detail.observabilityDisabledTitle"),children:[n.jsx(Gn,{size:14}),he("mesh.detail.observabilityOpen")]}),n.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>o(e.id),children:he("mesh.detail.delete")})]}),children:[t&&n.jsx(zt,{variant:"error",onDismiss:s,children:t}),i&&n.jsx(zt,{variant:"warning",children:i}),n.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-subtle bg-bg-card/30",children:n.jsx(tb,{variant:"underline",tabs:$e,tabIdPrefix:"mesh-settings-tab",ariaLabel:he("mesh.detail.tabsAriaLabel"),panelClassName:"p-4 md:p-6"})}),Z&&ye&&n.jsx(Pd,{activeConv:cx({meshId:e.id,daemonId:R,meshName:e.name}),sendDaemonCommand:Se,onClose:()=>se(!1)})]})}function CL(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=>Bi(d.mesh,t)).find(Boolean)||"";return((i?a.find(d=>on(d.daemonId,i)):void 0)??a[0]).mesh})}async function _L(e,t,s){const r=new Array(e.length);let o=0;const a=()=>CL(r.filter(i=>!!i),e);return await Promise.all(e.map(async(i,c)=>{try{r[c]=await t(i)}catch{}o+=1,s==null||s({merged:a(),settled:o,total:e.length})})),a()}function AL(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 so=new Map;async function px(e){var o,a,i,c,d,u,m,h,p,g,f;const{sendCommand:t,unwrapResult:s}=e,r={meshCreated:!1,meshId:"",error:null,warning:null,plan:null};try{const y=e.reusablePlan??s(await t(e.targetDaemonId,"plan_mesh_onboarding",{workspace:e.workspace||void 0,operation:"auto",meshInventory:e.meshInventory}));if(r.plan=y,(y==null?void 0:y.success)===!1)return{...r,error:`${y.code||"onboarding_blocked"}: ${y.error}${y.action?` ${y.action}`:""}`};if(((o=y==null?void 0:y.plan)==null?void 0:o.kind)!=="create_mesh_and_onboard")return{...r,error:((a=y==null?void 0:y.plan)==null?void 0:a.summary)||"A compatible mesh already exists; add this workspace to it instead of creating a duplicate mesh."};const b={name:e.name.trim()};(e.repoRemoteUrl||(d=(c=(i=y==null?void 0:y.discovery)==null?void 0:i.origin)==null?void 0:c.urls)!=null&&d[0])&&(b.repoRemoteUrl=e.repoRemoteUrl||y.discovery.origin.urls[0]),(e.repoIdentity||(u=y==null?void 0:y.discovery)!=null&&u.repoIdentity)&&(b.repoIdentity=e.repoIdentity||y.discovery.repoIdentity),(m=y==null?void 0:y.discovery)!=null&&m.defaultBranch&&(b.defaultBranch=y.discovery.defaultBranch);const k=await t(e.targetDaemonId,"create_mesh",b),j=s(k);if((j==null?void 0:j.success)===!1)return{...r,error:j.error||"Create failed"};const v=typeof((h=j==null?void 0:j.mesh)==null?void 0:h.id)=="string"?j.mesh.id:"",C={...r,meshCreated:!0,meshId:v};if(!v||!e.attachWorkspace||!e.workspace)return C;try{const x=await t(e.targetDaemonId,"add_mesh_node",{meshId:v,daemonId:e.targetDaemonId,machineId:e.machineId,workspace:((p=y==null?void 0:y.discovery)==null?void 0:p.repoRoot)||e.workspace,repoRoot:(g=y==null?void 0:y.discovery)==null?void 0:g.repoRoot,isLocalWorktree:((f=y==null?void 0:y.discovery)==null?void 0:f.isLinkedWorktree)===!0,role:"host",providerPriority:e.providerPriority}),S=s(x);return(S==null?void 0:S.success)===!1?{...C,warning:ep(S.error||"add_mesh_node failed")}:C}catch(x){return{...C,warning:ep((x==null?void 0:x.message)||"add_mesh_node failed")}}}catch(y){return{...r,error:(y==null?void 0:y.message)||"Create failed"}}}function ep(e){return`Mesh created, but attaching the workspace failed: ${e}. Add the workspace from the mesh's node list.`}function Wl(e,t){return e===t?!0:e.length!==t.length?!1:JSON.stringify(e)===JSON.stringify(t)}function fx({daemons:e,primaryDaemonId:t,sendCommand:s,unwrapResult:r,normalizeMesh:o,features:a,loadDaemonMetadata:i,confirmAction:c}){const d=e.map(we=>we.id).filter(Boolean).sort().join(","),[u,m]=l.useState(()=>so.get(d)??[]),[h,p]=l.useState(null),[g,f]=l.useState(()=>!so.has(d)),[y,b]=l.useState(null),[k,j]=l.useState(!1),[v,C]=l.useState(!1),[x,S]=l.useState(null),[w,_]=l.useState(""),[A,O]=l.useState(""),[L,R]=l.useState(""),[F,N]=l.useState(""),[I,B]=l.useState(""),[T,H]=l.useState(null),[q,J]=l.useState(!1),K=a.createDaemonPicker?F:t,M=l.useMemo(()=>e.find(we=>we.id===K),[e,K]),D=(M==null?void 0:M.workspaces)||[],P=l.useMemo(()=>Zn((M==null?void 0:M.availableProviders)||[]),[M]);l.useEffect(()=>{!i||!K||!M||!(!M.workspaces||!M.availableProviders)||Promise.resolve(i(K,{minFreshMs:3e4})).catch(()=>{})},[i,K,M]),l.useEffect(()=>{if(!k||!K||!I){H(null),J(!1);return}let we=!1;return J(!0),s(K,"plan_mesh_onboarding",{workspace:I,operation:"auto",meshInventory:u}).then(ce=>{if(we)return;const de=r(ce);H(de),de!=null&&de.success&&(O(ne=>{var ee;return ne||((ee=de.discovery)==null?void 0:ee.repoIdentity)||""}),R(ne=>{var ee,ue,je,X,G,z;return ne||((je=(ue=(ee=de.discovery)==null?void 0:ee.origin)==null?void 0:ue.urls)==null?void 0:je[0])||((z=(G=(X=de.discovery)==null?void 0:X.upstream)==null?void 0:G.urls)==null?void 0:z[0])||""}),_(ne=>{var ee,ue;return ne||`${String(((ee=de.discovery)==null?void 0:ee.repoIdentity)||((ue=de.discovery)==null?void 0:ue.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(ce=>{we||H({success:!1,error:(ce==null?void 0:ce.message)||"Git discovery failed"})}).finally(()=>{we||J(!1)}),()=>{we=!0}},[k,K,I,u,s,r]);const $=l.useMemo(()=>e.map(we=>we.id).filter(Boolean).sort().join(","),[e]),W=l.useRef(0),U=l.useCallback(async(we=!1)=>{const ce=++W.current,de=()=>W.current===ce,ne=we||so.has($);f(ee=>ne?ee:!0);try{if(a.createDaemonPicker){const ee=await _L(e,async ue=>{if(!ue.id)return{daemonId:"",meshes:[]};const je=await s(ue.id,"list_meshes",{}),X=r(je);if((X==null?void 0:X.success)===!1)throw new Error(X.error||"Failed to load meshes");const G=(Array.isArray(X==null?void 0:X.meshes)?X.meshes:[]).map(z=>o(z,ue.id)).filter(z=>z.id);return{daemonId:ue.id,meshes:G}},({merged:ue,settled:je,total:X})=>{!de()||je>=X||ue.length!==0&&(m(G=>{const z=ne?AL(G,ue):ue;return Wl(G,z)?G:z}),f(!1))});if(!de())return;m(ue=>Wl(ue,ee)?ue:ee),so.set($,ee),b(null)}else{if(!t)return;const ee=await s(t,"list_meshes");if(!de())return;if(ee!=null&&ee.success){const ue=(ee.meshes||[]).map(je=>o(je,t));m(je=>Wl(je,ue)?je:ue),so.set($,ue),b(null)}else b((ee==null?void 0:ee.error)||"Failed to load meshes")}}catch(ee){de()&&b((ee==null?void 0:ee.message)||"Failed to load meshes")}finally{de()&&f(!1)}},[$,t,s,r,o,a.createDaemonPicker]);async function ae(){const we=a.createDaemonPicker?F:t;if(!we||!w.trim())return;const ce=L.trim(),de=A.trim(),ne=I.trim();if(!(!ne&&!ce&&!de)&&!v){C(!0),S(null);try{const ee=await px({targetDaemonId:we,name:w,repoRemoteUrl:ce,repoIdentity:de,workspace:ne,attachWorkspace:!!ne,machineId:M==null?void 0:M.machineId,providerPriority:nr(P),meshInventory:u,sendCommand:s,unwrapResult:r,reusablePlan:!q&&T?T:void 0});if(ee.plan!==null&&H(ee.plan),ee.warning&&S(ee.warning),!ee.meshCreated){b(ee.error||"Create failed");return}j(!1),_(""),O(""),R(""),B(""),await U(),ee.meshId&&p(ee.meshId)}finally{C(!1)}}}async function be(we){var ee;const ce=((ee=u.find(ue=>ue.id===we))==null?void 0:ee.name)||we;if(!(c?await c({title:"Delete this mesh?",description:`"${ce}" will be removed from this daemon. This cannot be undone.`,confirmLabel:"Delete",tone:"danger"}):confirm("Delete this mesh? This cannot be undone.")))return;const ne=Bi(u.find(ue=>ue.id===we),e)||(a.createDaemonPicker?"":t);if(!ne){b(at.t("mesh.host.noCommandTarget"));return}try{const ue=await s(ne,"delete_mesh",{meshId:we}),je=r(ue);if((je==null?void 0:je.success)===!1)throw new Error(je.error||"Failed to delete");h===we&&p(null),await U()}catch(ue){b((ue==null?void 0:ue.message)||"Delete failed")}}function V(){j(!1),_(""),O(""),R(""),B(""),H(null),S(null)}return{meshes:u,setMeshes:m,selectedMeshId:h,setSelectedMeshId:p,loading:g,error:y,setError:b,showCreate:k,setShowCreate:j,creating:v,createWarning:x,setCreateWarning:S,createName:w,setCreateName:_,createRepoIdentity:A,setCreateRepoIdentity:O,createRepoRemoteUrl:L,setCreateRepoRemoteUrl:R,newMeshDaemonId:F,setNewMeshDaemonId:N,newMeshWorkspace:I,setNewMeshWorkspace:B,createPickerWorkspaces:D,createPickerProviders:P,createOnboardingPlan:T,createPlanLoading:q,loadMeshes:U,handleCreate:ae,handleDelete:be,cancelCreate:V}}function TL({selectedMesh:e,selectedMeshId:t,activeDaemonId:s,daemons:r,sendCommand:o,unwrapResult:a,loadLiveMesh:i,resolveCommandTarget:c,launchCoordinator:d,features:u,loadMeshes:m,reloadMeshStatus:h,setError:p,confirmAction:g}){const f=s;function y(){return f||(p(at.t("mesh.host.noCommandTarget")),null)}const[b,k]=l.useState(null),[j,v]=l.useState(!1),[C,x]=l.useState(""),[S,w]=l.useState([]),[_,A]=l.useState(""),[O,L]=l.useState(!1),[R,F]=l.useState(null),[N,I]=l.useState(!1),[B,T]=l.useState(""),[H,q]=l.useState(!1),[J,K]=l.useState(!1),[M,D]=l.useState(null),[P,$]=l.useState(!1),[W,U]=l.useState({override:"",append:""}),[ae,be]=l.useState(!1),[V,we]=l.useState({}),[ce,de]=l.useState(null),ne=l.useMemo(()=>r.find(Y=>Y.id===_),[r,_]),ee=(ne==null?void 0:ne.workspaces)||[],ue=l.useMemo(()=>Zn((ne==null?void 0:ne.availableProviders)||[]),[ne]);l.useEffect(()=>{if(!j||!t||!C.trim()){F(null);return}const Y=u.addNodeDaemonPicker?_:f;if(!Y)return;let me=!1;return I(!0),o(Y,"plan_mesh_onboarding",{workspace:C.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(fe=>{me||F(a(fe))}).catch(fe=>{me||F({success:!1,error:(fe==null?void 0:fe.message)||"Git discovery failed"})}).finally(()=>{me||I(!1)}),()=>{me=!0}},[j,t,e,C,_,f,u.addNodeDaemonPicker,o,a]);async function je(){var fe,E,oe;if(!t)return;const Y=C.trim();if(!Y)return;const me=y();if(me)try{const Ie=u.addNodeDaemonPicker?_:me,Z=await o(Ie,"plan_mesh_onboarding",{workspace:Y,meshId:t,inlineMesh:e,operation:"add_existing"}),se=a(Z);if(F(se),(se==null?void 0:se.success)===!1)throw new Error(eu(se));const ye={meshId:t,workspace:((fe=se==null?void 0:se.discovery)==null?void 0:fe.repoRoot)||Y,repoRoot:(E=se==null?void 0:se.discovery)==null?void 0:E.repoRoot,isLocalWorktree:((oe=se==null?void 0:se.discovery)==null?void 0:oe.isLinkedWorktree)===!0};u.addNodeDaemonPicker&&_&&(ye.daemonId=_,ye.machineId=ne==null?void 0:ne.machineId),ye.providerPriority=Fo(S);const Fe=await o(me,"add_mesh_node",ye),Me=a(Fe);if((Me==null?void 0:Me.success)===!1)throw new Error(Me.error||"Add node failed");v(!1),x(""),w([]),A(""),L(!1),await m(),await h()}catch(Ie){p((Ie==null?void 0:Ie.message)||"Add node failed")}}async function X(Y){var Ie;if(!e)return;const me=qc(e),fe=((Ie=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(Z=>Z.value===me.sessionCleanupOnNodeRemove))==null?void 0:Ie.label)||"Preserve history and runtimes";if(!(g?await g({title:"Remove this node?",description:`Node removal cleanup policy: ${fe}`,confirmLabel:"Remove",tone:"danger"}):confirm(`Remove this node?
|
|
108
|
-
|
|
109
|
-
Node removal cleanup policy: ${fe}`)))return;const oe=y();if(oe)try{const Z=await o(oe,"remove_mesh_node",{meshId:e.id,nodeId:Y}),se=a(Z);if((se==null?void 0:se.success)===!1)throw new Error(se.error||"Remove failed");b===Y&&k(null),await m(),await h()}catch(Z){p((Z==null?void 0:Z.message)||"Remove node failed")}}async function G(Y){if(!e)return;const me={...qc(e),...Y},fe=y();if(fe)try{$(!0),p(null);const E=await o(fe,"update_mesh",{meshId:e.id,policy:me}),oe=a(E);if((oe==null?void 0:oe.success)===!1)throw new Error(oe.error||"Policy update failed");ct.showToast(at.t("common.saved"),"success"),await m()}catch(E){p((E==null?void 0:E.message)||"Policy update failed")}finally{$(!1)}}const[z,ie]=l.useState(null);async function Ne(Y,me){if(!t)return;const fe=y();if(fe)try{ie(Y.id),p(null);const E=await o(fe,"update_mesh_node",{meshId:t,nodeId:Y.id,policy:{slots:me}}),oe=a(E);if((oe==null?void 0:oe.success)===!1){p(oe.error||"Node slots update failed");return}ct.showToast(at.t("common.saved"),"success"),await m()}catch(E){p((E==null?void 0:E.message)||"Node slots update failed")}finally{ie(null)}}const[Be,Le]=l.useState(null);async function Je(Y,me){if(!t)return;const fe=y();if(!fe)return;const E=me.map(oe=>oe.trim()).filter(Boolean);try{Le(Y.id),p(null);const oe=await o(fe,"update_mesh_node",{meshId:t,nodeId:Y.id,capabilities:E}),Ie=a(oe);if((Ie==null?void 0:Ie.success)===!1){p(Ie.error||"Node tag update failed");return}ct.showToast(at.t("common.saved"),"success"),await m()}catch(oe){p((oe==null?void 0:oe.message)||"Node tag update failed")}finally{Le(null)}}async function Se(){if(!t)return;const Y=y();if(!Y)return;const fe={...(e==null?void 0:e.coordinator)||{}};W.override.trim()?fe.systemPromptOverride=W.override:delete fe.systemPromptOverride,W.append.trim()?fe.systemPromptAppend=W.append:delete fe.systemPromptAppend,delete fe.systemPromptSuffix;try{be(!0),p(null);const E=await o(Y,"update_mesh",{meshId:t,coordinator:fe}),oe=a(E);if((oe==null?void 0:oe.success)===!1){p(oe.error||"Coordinator prompt save failed");return}ct.showToast(at.t("common.saved"),"success"),await m()}catch(E){p((E==null?void 0:E.message)||"Coordinator prompt save failed")}finally{be(!1)}}async function he(Y){if(!t)return;const me=y();if(!me)return;const fe=(V[Y.id]||"").trim();try{de(Y.id),p(null);const E=await o(me,"update_mesh_node",{meshId:t,nodeId:Y.id,systemPrompt:fe}),oe=a(E);if((oe==null?void 0:oe.success)===!1){p(oe.error||"Node instruction save failed");return}ct.showToast(at.t("common.saved"),"success"),await m()}catch(E){p((E==null?void 0:E.message)||"Node instruction save failed")}finally{de(null)}}async function pe(Y){if(!(!e||!Y)){if(g){const me=r.find(oe=>oe.id===Y),fe=(me==null?void 0:me.machineNickname)||(me==null?void 0:me.nickname)||(me==null?void 0:me.hostname)||Y;if(!await g({title:at.t("mesh.host.setHostConfirmTitle",{name:fe}),description:at.t("mesh.host.setHostActionHint"),confirmLabel:at.t("mesh.host.setHostAction")}))return}p(null),D(null);try{K(!0);const me=(e.nodes||[]).find(oe=>on(String(oe.daemon_id||oe.daemonId||""),Y)),fe=await o(Y,"set_mesh_host",{meshId:e.id,hostDaemonId:Y,...me!=null&&me.id?{hostNodeId:me.id}:{}}),E=a(fe);if((E==null?void 0:E.success)===!1){p(E.error||"Setting the mesh host failed");return}await m()}catch(me){p((me==null?void 0:me.message)||"Setting the mesh host failed")}finally{K(!1)}}}async function Ee(){if(e){p(null),D(null);try{q(!0);const Y=i?await i(s,e.id,e):null,me=c(s,e.id,e,e.nodes||[],Y);if("error"in me)throw new Error(me.error);const fe=await d(me.targetDaemonId,{meshId:e.id,inlineMesh:me.inlineMesh,coordinatorNodeId:me.coordinatorNodeId,cliType:B.trim()||void 0});D(fe.message)}catch(Y){p((Y==null?void 0:Y.message)||"Coordinator launch failed")}finally{q(!1)}}}return{selectedNodeId:b,setSelectedNodeId:k,showAddNode:j,setShowAddNode:v,nodeWorkspace:C,setNodeWorkspace:x,nodeProviderPriority:S,setNodeProviderPriority:w,nodeDaemonId:_,setNodeDaemonId:A,nodeCustomPath:O,setNodeCustomPath:L,nodePickerWorkspaces:ee,nodePickerProviders:ue,nodeOnboardingPlan:R,nodePlanLoading:N,coordinatorCliType:B,setCoordinatorCliType:T,launchingCoordinator:H,launchResult:M,settingMeshHost:J,savingPolicy:P,coordinatorPromptDraft:W,setCoordinatorPromptDraft:U,savingCoordinatorPrompt:ae,nodeSystemPromptDrafts:V,setNodeSystemPromptDrafts:we,savingNodeSystemPromptId:ce,savingNodeSlotsId:z,savingNodeCapabilitiesId:Be,handleAddNode:je,handleRemoveNode:X,handleUpdatePolicy:G,handleUpdateNodeSlots:Ne,handleUpdateNodeCapabilities:Je,handleSaveCoordinatorPrompt:Se,handleSaveNodeSystemPrompt:he,handleLaunchCoordinator:Ee,handleSetMeshHost:pe}}const IL=[];function ML(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"):IL}function RL({status:e}){return{meshQueue:l.useMemo(()=>ML(e),[e])}}const PL=()=>()=>{};function gx(e){const t=l.useCallback(r=>e?b1(e,r):PL(),[e]),s=l.useCallback(()=>yo(e),[e]);return l.useSyncExternalStore(t,s,s)}const LL=6e4;function V5({meshId:e,daemonId:t,load:s,extract:r,sendData:o,backstopMs:a=LL}){const i=gx(e),c=l.useRef(s);c.current=s;const d=l.useRef(r);d.current=r;const u=l.useCallback(p=>{const g=c.current;return!e||!t||!g?Promise.resolve(null):Pi({meshId:e,daemonId:t,refresh:p,load:g,extract:d.current})},[e,t]);l.useEffect(()=>{u(!1)},[u]),sx({daemonIds:l.useMemo(()=>t?[t]:[],[t]),meshId:e,sendData:o,onRevisionAdvance:()=>{typeof document<"u"&&document.hidden||u(!1)}}),l.useEffect(()=>{if(!e||!t||a<=0)return;const p=setInterval(()=>{typeof document<"u"&&document.hidden||u(!1)},a);return()=>clearInterval(p)},[e,t,a,u]);const m=l.useCallback(()=>u(!0),[u]),h=l.useCallback(()=>u(!1),[u]);return{status:(i==null?void 0:i.status)??null,loading:(i==null?void 0:i.loading)??!1,refreshing:(i==null?void 0:i.refreshing)??!1,error:(i==null?void 0:i.error)??null,loadedAt:(i==null?void 0:i.loadedAt)??null,refresh:m,reload:h}}function EL(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}function DL({selectedMeshId:e,loadMeshStatus:t,extractStatus:s,normalizeNode:r}){const o=gx(e),[a,i]=l.useState(null),[c,d]=l.useState("idle"),u=(o==null?void 0:o.status)??null,m=l.useMemo(()=>!u||!r?u:{...u,nodes:(u.nodes??[]).map(g=>r(g,u.meshId??e??"",""))},[u,r,e]);function h(g){e&&x1(e,g,(o==null?void 0:o.daemonId)??null)}async function p(g,f=e,y=!1){var k;if(!g||!f)return;i(null),d(y?"settling":"first_paint"),await Pi({meshId:f,daemonId:g,refresh:y,load:(j,v,C)=>t(j,v,{refresh:C.refresh}),extract:j=>s(j)})?d("settled"):(i(((k=yo(f))==null?void 0:k.error)||"Failed to load mesh graph"),d("idle"))}return{meshGraphStatus:m,setMeshGraphStatus:h,graphLoading:!!(o!=null&&o.loading)&&!u,graphError:a??(u?null:(o==null?void 0:o.error)??null),setGraphError:i,graphProvenance:c,graphBootstrapFallback:EL(o==null?void 0:o.response),loadGraph:p}}function OL(e){var o;if(!e)return"null";const t=[...e.nodes??[]].map(a=>{var i,c,d,u,m,h;return[a.nodeId,a.health,((i=a.git)==null?void 0:i.branch)??"",((c=a.git)==null?void 0:c.headCommit)??"",(d=a.git)!=null&&d.dirty?"1":"0",((u=a.git)==null?void 0:u.ahead)??0,((m=a.git)==null?void 0:m.behind)??0,(h=a.git)!=null&&h.hasConflicts?"1":"0",[...a.activeSessions??[]].sort().join(",")].join("|")}).sort().join(";"),s=(o=e.queue)==null?void 0:o.summary,r=s?[s.pending,s.assigned,s.completed,s.failed,s.cancelled].join(","):"";return`${t}::${r}`}const FL=4,$L=3e4;function HL(){return{lastFingerprint:null,stableTicks:0,backedOff:!1}}function zc(e){e.stableTicks=0,e.backedOff=!1}function BL(e,t){const s=OL(t);return e.lastFingerprint===null?(e.lastFingerprint=s,e.backedOff):s!==e.lastFingerprint?(e.lastFingerprint=s,zc(e),!1):(e.stableTicks+=1,e.stableTicks>=FL&&(e.backedOff=!0),e.backedOff)}function WL(e,t){return e.backedOff?Math.max(t,$L):t}const UL=7e3,KL=45e3,tp=5*60*1e3;function qL(){const e=uP(),{t}=ve("common"),{confirm:s,confirmDialog:r}=Fr(),{sendCommand:o,sendData:a,daemons:i,userName:c,loadMeshStatus:d,launchCoordinator:u,loadLiveMesh:m,extractStatus:h,unwrapResult:p,normalizeMesh:g,normalizeNode:f,resolveCommandTarget:y,features:b}=e,k=Hr(),j=i[0],v=(j==null?void 0:j.id)||"",C=l.useMemo(()=>((j==null?void 0:j.availableProviders)||[]).filter(mt=>mt.category==="cli").map(mt=>({id:mt.type||mt.id,name:mt.displayName||mt.name||mt.type,meshCoordinator:mt.meshCoordinator})),[j]),x=l.useMemo(()=>Zn((j==null?void 0:j.availableProviders)||[]),[j]),{meshes:S,selectedMeshId:w,setSelectedMeshId:_,loading:A,error:O,setError:L,showCreate:R,setShowCreate:F,createName:N,setCreateName:I,createRepoIdentity:B,setCreateRepoIdentity:T,createRepoRemoteUrl:H,setCreateRepoRemoteUrl:q,newMeshDaemonId:J,setNewMeshDaemonId:K,newMeshWorkspace:M,setNewMeshWorkspace:D,createPickerWorkspaces:P,createOnboardingPlan:$,createPlanLoading:W,creating:U,createWarning:ae,setCreateWarning:be,loadMeshes:V,handleCreate:we,handleDelete:ce,cancelCreate:de}=fx({confirmAction:s,daemons:i,primaryDaemonId:v,sendCommand:o,unwrapResult:p,normalizeMesh:g,features:b,loadDaemonMetadata:k}),ne=S.find(Ye=>Ye.id===w)||null,{meshGraphStatus:ee,graphLoading:ue,graphError:je,setGraphError:X,loadGraph:G}=DL({selectedMeshId:w,loadMeshStatus:d,extractStatus:h,normalizeNode:f}),[z,ie]=l.useState(""),[Ne,Be]=l.useState(""),Le=b.meshHostDaemonSection?z:v,{meshQueue:Je}=RL({status:ee}),Se=async()=>{!w||!Le||await G(Le,w,!1)},{selectedNodeId:he,setSelectedNodeId:pe,showAddNode:Ee,setShowAddNode:Y,nodeWorkspace:me,setNodeWorkspace:fe,nodeProviderPriority:E,setNodeProviderPriority:oe,nodeDaemonId:Ie,setNodeDaemonId:Z,nodeCustomPath:se,setNodeCustomPath:ye,nodePickerWorkspaces:Fe,nodePickerProviders:Me,nodeOnboardingPlan:De,nodePlanLoading:Te,coordinatorCliType:He,savingPolicy:tt,coordinatorPromptDraft:Ct,setCoordinatorPromptDraft:Q,savingCoordinatorPrompt:re,nodeSystemPromptDrafts:le,setNodeSystemPromptDrafts:xe,savingNodeSystemPromptId:Ce,savingNodeSlotsId:Re,savingNodeCapabilitiesId:Ue,handleAddNode:$e,handleRemoveNode:ke,handleUpdatePolicy:Ze,handleUpdateNodeSlots:et,handleUpdateNodeCapabilities:Ve,handleSaveCoordinatorPrompt:st,handleSaveNodeSystemPrompt:lt,settingMeshHost:Qe,handleSetMeshHost:ge}=TL({confirmAction:s,selectedMesh:ne,selectedMeshId:w,activeDaemonId:Le,daemons:i,availableCliProviders:x,sendCommand:o,unwrapResult:p,loadLiveMesh:m,resolveCommandTarget:y,launchCoordinator:u,features:{addNodeDaemonPicker:b.addNodeDaemonPicker},loadMeshes:V,reloadMeshStatus:Se,setError:L}),_e=l.useMemo(()=>i.find(Ye=>Ye.id===Le)||j,[i,Le,j]),Pe=l.useMemo(()=>new Set(((ne==null?void 0:ne.nodes)||[]).map(Ye=>String(Ye.daemon_id||Ye.daemonId||""))),[ne]),nt=l.useMemo(()=>i.filter(Ye=>Ye.id&&!Pe.has(Ye.id)&&!hp(Ye)),[i,Pe]),ze=(ne==null?void 0:ne.nodes)||[],ut=l.useMemo(()=>ze.find(Ye=>on(String(Ye.daemon_id||Ye.daemonId||""),z)),[ze,z]),Ge=b.meshHostDaemonSection?!!ut:!0,gt=l.useMemo(()=>{if(!b.meshHostDaemonSection||!ne)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Ye=ne.meshHost,mt=ee!=null&&ee.meshId&&String(ee.meshId)===String(ne.id??"")?ee.meshHost:void 0,Zt=mt!=null&&mt.hostDaemonId?mt:Ye??mt,Sn=Bc(Zt),sn=Sn.hostDaemonId,rn=ze.find(kn=>kn.role==="host"),In=Sn.hostNodeId||String((rn==null?void 0:rn.id)||""),jt=In?ze.find(kn=>String(kn.id)===In):void 0,en=String((jt==null?void 0:jt.daemon_id)||(jt==null?void 0:jt.daemonId)||""),gn=sn||en;if(!gn)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Wt=i.find(kn=>sn&&on(kn.id,sn))||(en?i.find(kn=>on(kn.id,en)):void 0);if(Wt)return{pinned:!0,daemonId:Wt.id,label:zL(Wt),online:!0,hostNode:jt};const Ms=String((jt==null?void 0:jt.machineLabel)||"")||String((jt==null?void 0:jt.workspace)||"")||gn;return{pinned:!0,daemonId:gn,label:Ms,online:!1,hostNode:jt}},[ne,ze,i,ee,b.meshHostDaemonSection]),Mt=gt.daemonId,Rt=gt.online,mn=gt.pinned?gt.hostNode:ut,nn=l.useMemo(()=>!b.meshHostDaemonSection||!gt.pinned?"":!Rt&&Ne&&i.some(Ye=>Ye.id===Ne)?Ne:Mt,[b.meshHostDaemonSection,gt.pinned,Rt,Ne,i,Mt]),Jt=dP({status:ee,daemonId:Le||null,meshId:w,sendData:a});l.useEffect(()=>{const Ye=(ne==null?void 0:ne.coordinator)||{};Q({override:typeof Ye.systemPromptOverride=="string"?Ye.systemPromptOverride:"",append:typeof Ye.systemPromptAppend=="string"?Ye.systemPromptAppend:typeof Ye.systemPromptSuffix=="string"?Ye.systemPromptSuffix:""}),xe(Object.fromEntries(((ne==null?void 0:ne.nodes)||[]).map(mt=>[mt.id,typeof mt.systemPrompt=="string"?mt.systemPrompt:""])))},[ne]),l.useEffect(()=>{const Ye=b.addNodeDaemonPicker?nr(Me):nr(x);Ee&&E.length===0&&Ye.length>0&&oe(Ye)},[Ee,x,Me,E.length,b.addNodeDaemonPicker]),l.useEffect(()=>{const Ye=new Set(((ne==null?void 0:ne.nodes)||[]).map(mt=>mt.id));he&&!Ye.has(he)&&pe(null)},[ne,he]);const Et=l.useMemo(()=>{if(!(!(ee!=null&&ee.meshId)||String(ee.meshId)!==String((ne==null?void 0:ne.id)??"")))return Bc(ee.meshHost).hostDaemonId||void 0},[ee,ne]),hn=l.useMemo(()=>xP(i,ze,Le,v,Et),[i,ze,Le,v,Et]);l.useEffect(()=>{if(!b.meshHostDaemonSection)return;if(!i.length&&!gt.pinned){ie("");return}const Ye=gt.pinned?nn:hn;Ye&&!on(Ye,z)&&ie(Ye)},[i,z,gt.pinned,nn,hn,b.meshHostDaemonSection]),l.useEffect(()=>{Ne&&(Rt||!i.some(Ye=>Ye.id===Ne))&&Be("")},[Rt,Ne,i]),l.useEffect(()=>{if(b.createDaemonPicker){if(!i.length){K("");return}(!J||!i.some(Ye=>Ye.id===J))&&K(i[0].id)}},[i,J,b.createDaemonPicker]),l.useEffect(()=>{var Ye;if(b.createDaemonPicker){if(!J){D("");return}if(!P.length){D("");return}P.some(mt=>mt.path===M)||D(((Ye=P[0])==null?void 0:Ye.path)||"")}},[J,M,P,b.createDaemonPicker]);const Bn=l.useRef(null),Tt=l.useRef(HL()),Vt=b.meshStatePushRefresh?KL:UL,[pn,Oe]=l.useState(Vt);l.useEffect(()=>{if(!w)return;const Ye=Bn.current!==w;Bn.current=w,Ye&&(zc(Tt.current),Oe(Vt)),X(null),G(Le,w,!1)},[w,Le]);const rt=l.useRef(G);rt.current=G;const pt=l.useRef(!1),bt=l.useRef(()=>{});bt.current=()=>{pt.current||!w||!Le||(pt.current=!0,Promise.resolve(rt.current(Le,w,!1)).finally(()=>{pt.current=!1}))},l.useEffect(()=>{BL(Tt.current,ee),Oe(WL(Tt.current,Vt))},[ee,Vt]);const yt=l.useRef(null);l.useEffect(()=>{yt.current=null},[w,Le]),sx({daemonIds:l.useMemo(()=>[Le].filter(Boolean),[Le]),meshId:w,sendData:a,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||bt.current()},onRevisionObserved:()=>{yt.current=Date.now()}}),l.useEffect(()=>{if(!w||!Le||typeof document>"u")return;if(b.meshStatePushRefresh){const rn=w,In=setInterval(()=>{if(document.visibilityState!=="visible")return;const jt=yt.current,en=jt===null?1/0:Date.now()-jt;en<tp||(console.warn(`[repo-mesh] mesh_state push backstop firing for mesh ${rn}: no revision push observed in ${Math.round(en/1e3)}s — refreshing via poll fallback`),bt.current())},tp);return()=>clearInterval(In)}let Ye=null;const mt=()=>{document.visibilityState==="visible"&&bt.current()},Zt=()=>{Ye===null&&(Ye=setInterval(mt,pn))},Sn=()=>{Ye!==null&&(clearInterval(Ye),Ye=null)},sn=()=>{document.visibilityState==="visible"?Zt():Sn()};return document.visibilityState==="visible"&&Zt(),document.addEventListener("visibilitychange",sn),()=>{Sn(),document.removeEventListener("visibilitychange",sn)}},[w,Le,pn,b.meshStatePushRefresh]);const kt=l.useMemo(()=>i.map(Ye=>Ye.id).filter(Boolean).sort().join(","),[i]),fn=l.useRef(!1);return l.useEffect(()=>{V(fn.current),fn.current=!0},[kt]),v?ne?n.jsxs(n.Fragment,{children:[r,n.jsx(NL,{selectedMesh:ne,error:O,onDismissError:()=>L(null),onBack:()=>{_(null)},onDelete:ce,displayedMeshStatus:Jt,graphLoading:ue,graphError:je,onRefreshGraph:()=>{zc(Tt.current),G(Le,w,!0)},savingPolicy:tt,onUpdatePolicy:Ze,coordinatorPromptDraft:Ct,onCoordinatorPromptDraftChange:Q,savingCoordinatorPrompt:re,onSaveCoordinatorPrompt:st,daemons:i,coordinatorDaemonId:z,onCoordinatorDaemonIdChange:ie,coordinatorCliType:He,isHostNodeAttached:Ge,selectedHostNode:mn,hostPinned:gt.pinned,hostLabel:gt.label,hostOnline:Rt,hostRebindDaemonId:Ne,onHostRebindDaemonIdChange:Ye=>Be(Ye),settingMeshHost:Qe,onSetMeshHost:ge,activeDaemon:_e,activeDaemonId:Le,meshQueue:Je,userName:c,availableCliProviders:x,savingNodeSlotsId:Re,onUpdateNodeSlots:et,savingNodeCapabilitiesId:Ue,onUpdateNodeCapabilities:Ve,nodeSystemPromptDrafts:le,onNodeSystemPromptDraftChange:(Ye,mt)=>xe(Zt=>({...Zt,[Ye]:mt})),savingNodeSystemPromptId:Ce,onSaveNodeSystemPrompt:lt,selectedNodeId:he,onSelectNode:pe,showAddNode:Ee,onShowAddNode:()=>Y(!0),onCancelAddNode:()=>Y(!1),nodeWorkspace:me,onNodeWorkspaceChange:fe,nodeProviderPriority:E,onNodeProviderPriorityChange:oe,nodeDaemonId:Ie,onNodeDaemonIdChange:Z,nodeCustomPath:se,onNodeCustomPathChange:ye,nodePickerWorkspaces:Fe,nodePickerProviders:Me,nodeOnboardingPlan:De,nodePlanLoading:Te,attachableDaemons:nt,onAddNode:$e,onRemoveNode:ke,availableCliAgents:C,features:{coordinatorPrompt:b.coordinatorPrompt,meshHostDaemonSection:b.meshHostDaemonSection,hermesMcpConfig:b.hermesMcpConfig,addNodeDaemonPicker:b.addNodeDaemonPicker,nodeInstruction:b.nodeInstruction},sendCommand:o})]}):n.jsxs(n.Fragment,{children:[r,n.jsx(KP,{meshes:S,loading:A,error:O,onDismissError:()=>L(null),daemons:i,features:{createDaemonPicker:b.createDaemonPicker},showCreate:R,onToggleCreate:()=>F(!R),createName:N,onCreateNameChange:I,createRepoIdentity:B,onCreateRepoIdentityChange:T,createRepoRemoteUrl:H,onCreateRepoRemoteUrlChange:q,newMeshDaemonId:J,onNewMeshDaemonIdChange:K,newMeshWorkspace:M,onNewMeshWorkspaceChange:D,createPickerWorkspaces:P,createOnboardingPlan:$,createPlanLoading:W,creating:U,createWarning:ae,onDismissCreateWarning:()=>be(null),onSelectMesh:_,onCreate:we,onCancelCreate:de,sendCommand:o})]}):n.jsx($o,{icon:n.jsx(Gn,{}),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 zL(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function GL({children:e}){const{sendCommand:t,sendData:s}=_t(),{ides:r}=An(),o=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),a=l.useMemo(()=>({sendCommand:t,sendData:s,daemons:o,userName:void 0,loadMeshStatus:async(i,c,d)=>t(i,"mesh_status",(d==null?void 0:d.refresh)===!0?{meshId:c,refresh:!0}:{meshId:c}),launchCoordinator:async(i,c)=>{var p;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const u=await t(i,"launch_mesh_coordinator",d),m=(u==null?void 0:u.result)??u;if((m==null?void 0:m.success)===!1)throw new Error(m.error||"Coordinator launch failed");const h=(m==null?void 0:m.sessionId)||((p=m==null?void 0:m.session)==null?void 0:p.id)||(m==null?void 0:m.targetSessionId);return{sessionId:h,message:h?`Coordinator launched (${h})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Td,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:rx}),[t,s,o]);return n.jsx(ox.Provider,{value:a,children:e})}function VL(e){const{daemons:t,features:s,meshes:r,meshesLoading:o,selectedMeshId:a,onSelectMesh:i,createMode:c,onCreateModeChange:d,createName:u,onCreateNameChange:m,createDaemonId:h,onCreateDaemonIdChange:p,createWorkspace:g,onCreateWorkspaceChange:f,createPickerWorkspaces:y,createPlan:b,createPlanLoading:k,creating:j,createWarning:v,onCreate:C,createRepoRemoteUrl:x,onCreateRepoRemoteUrlChange:S,createRepoIdentity:w,onCreateRepoIdentityChange:_,createManualOpen:A,onCreateManualOpenChange:O,nodes:L,attachableDaemons:R,attachDaemonId:F,onAttachDaemonIdChange:N,attachWorkspace:I,onAttachWorkspaceChange:B,attachPickerWorkspaces:T,attachPlan:H,attachPlanLoading:q,attaching:J,onAttach:K,renderInstallOnboarding:M,nodeLabel:D,daemonLabel:P}=e,{t:$}=ve("common");if(t.length===0)return n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:$("setupWizard.machines.title")}),n.jsx("p",{className:"mt-1 text-2xs leading-relaxed text-text-muted",children:$("setupWizard.machines.noMachinesDescription")})]}),M?M():n.jsx("p",{className:"text-2xs text-text-muted",children:$("setupWizard.machines.noMachinesFallback")})]});const W=J||q||(H==null?void 0:H.success)===!1||!I.trim()||s.addNodeDaemonPicker&&!F;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:$("setupWizard.machines.title")}),n.jsx("p",{className:"mt-1 text-2xs leading-relaxed text-text-muted",children:$("setupWizard.machines.description")})]}),n.jsxs("div",{className:"flex flex-col gap-2",children:[r.map(U=>{const ae=!c&&a===U.id;return n.jsx("button",{type:"button",onClick:()=>{d(!1),i(U.id)},className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${ae?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:n.jsxs("span",{className:"min-w-0",children:[n.jsx("span",{className:"block truncate text-sm text-text-primary",children:U.name}),n.jsxs("span",{className:"block truncate text-2xs text-text-muted",children:[U.repoIdentity||U.repoRemoteUrl||""," · ",$("setupWizard.machines.nodeCount",{count:(U.nodes||[]).length})]})]})},U.id)}),n.jsx("button",{type:"button",onClick:()=>d(!0),className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${c?"border-accent-primary/60 bg-accent-primary/10":"border-dashed border-border-subtle bg-bg-secondary/40 hover:border-border-default"}`,children:n.jsxs("span",{className:"text-sm text-text-primary",children:["+ ",$("setupWizard.machines.createNew")]})}),o&&r.length===0&&n.jsx("p",{className:"text-2xs text-text-muted",children:$("setupWizard.machines.loadingMeshes")})]}),c&&n.jsx(lx,{variant:"wizard",showDaemonPicker:s.createDaemonPicker,daemons:t,daemonLabel:P,name:u,onNameChange:m,daemonId:h,onDaemonIdChange:p,workspace:g,onWorkspaceChange:f,workspaces:y,plan:b,planLoading:k,repoRemoteUrl:x,onRepoRemoteUrlChange:S,repoIdentity:w,onRepoIdentityChange:_,manualOpen:A,onManualOpenChange:O,creating:j,warning:v,onCreate:C}),!c&&a&&n.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[L.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1.5",children:L.map(U=>n.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-3xs text-text-secondary",children:D(U)},U.id))}),n.jsx("span",{className:"text-2xs font-medium text-text-secondary",children:$("setupWizard.machines.attachTitle")}),s.addNodeDaemonPicker&&(R.length>0?n.jsx("div",{className:"flex flex-wrap gap-1.5",children:R.map(U=>{const ae=F===U.id;return n.jsx("button",{type:"button",onClick:()=>N(U.id),className:`rounded-full border px-2.5 py-1 text-2xs transition-colors ${ae?"border-accent-primary/60 bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-secondary text-text-secondary hover:border-border-default"}`,children:P(U)},U.id)})}):n.jsx("p",{className:"text-2xs text-text-muted",children:$("setupWizard.machines.allMachinesAttached")})),(!s.addNodeDaemonPicker||F)&&n.jsxs(n.Fragment,{children:[n.jsx(Hc,{workspaces:T,value:I,onChange:B}),n.jsx(ix,{plan:H,loading:q}),n.jsx("div",{className:"flex justify-end",children:n.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:K,disabled:W,children:$(J?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function YL(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function QL(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function JL({daemons:e,features:t,sendCommand:s,unwrapResult:r,normalizeMesh:o,loadDaemonMetadata:a,initialMeshId:i,onClose:c,renderInstallOnboarding:d}){var Y,me;const{t:u}=ve("common"),m=((Y=e[0])==null?void 0:Y.id)||"",{meshes:h,loading:p,error:g,setError:f,loadMeshes:y,selectedMeshId:b,setSelectedMeshId:k}=fx({daemons:e,primaryDaemonId:m,sendCommand:s,unwrapResult:r,normalizeMesh:o,features:{createDaemonPicker:t.createDaemonPicker,addNodeDaemonPicker:t.addNodeDaemonPicker},loadDaemonMetadata:a});l.useEffect(()=>{y()},[y]);const j=l.useRef(h);j.current=h;const v=l.useMemo(()=>h.map(fe=>fe.id).sort().join(","),[h]),C=l.useRef(s);C.current=s;const x=l.useRef(r);x.current=r,l.useEffect(()=>{b||h.length===0||(i&&h.some(fe=>fe.id===i)?k(i):h.length===1&&k(h[0].id))},[h,b,i,k]);const S=l.useMemo(()=>h.find(fe=>fe.id===b)??null,[h,b]),w=l.useMemo(()=>(S==null?void 0:S.nodes)||[],[S]),_=l.useCallback(fe=>Bi(fe,e),[e]),[A,O]=l.useState(!1),[L,R]=l.useState(""),[F,N]=l.useState(""),[I,B]=l.useState(""),[T,H]=l.useState(null),[q,J]=l.useState(!1),[K,M]=l.useState(!1),[D,P]=l.useState(null),[$,W]=l.useState(""),[U,ae]=l.useState(""),[be,V]=l.useState(!1),we=t.createDaemonPicker&&F||m,ce=l.useMemo(()=>e.find(fe=>fe.id===we),[e,we]),de=(ce==null?void 0:ce.workspaces)||[];l.useEffect(()=>{if(!A||!we||!I.trim()){H(null),J(!1);return}let fe=!1;const E=setTimeout(()=>{fe||(J(!0),C.current(we,"plan_mesh_onboarding",{workspace:I.trim(),operation:"auto",meshInventory:j.current}).then(oe=>{if(fe)return;const Ie=x.current(oe);H(Ie),Ie!=null&&Ie.success&&(R(Z=>{var se,ye;return Z||`${String(((se=Ie.discovery)==null?void 0:se.repoIdentity)||((ye=Ie.discovery)==null?void 0:ye.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),ae(Z=>{var se;return Z||((se=Ie.discovery)==null?void 0:se.repoIdentity)||""}),W(Z=>{var se,ye,Fe,Me,De,Te;return Z||((Fe=(ye=(se=Ie.discovery)==null?void 0:se.origin)==null?void 0:ye.urls)==null?void 0:Fe[0])||((Te=(De=(Me=Ie.discovery)==null?void 0:Me.upstream)==null?void 0:De.urls)==null?void 0:Te[0])||""}))}).catch(oe=>{fe||H({success:!1,error:(oe==null?void 0:oe.message)||"Git discovery failed"})}).finally(()=>{fe||J(!1)}))},300);return()=>{fe=!0,clearTimeout(E)}},[A,we,I,v]);const ne=l.useCallback(async()=>{const fe=we,E=I.trim(),oe=$.trim(),Ie=U.trim();if(!(!fe||!L.trim()||K)&&!(!E&&!oe&&!Ie)){M(!0),P(null),f(null);try{const Z=await px({targetDaemonId:fe,name:L,repoRemoteUrl:oe,repoIdentity:Ie,workspace:E,attachWorkspace:!!E,machineId:ce==null?void 0:ce.machineId,providerPriority:nr(Zn((ce==null?void 0:ce.availableProviders)||[])),meshInventory:h,sendCommand:s,unwrapResult:r});if(Z.warning&&P(Z.warning),!Z.meshCreated){f(Z.error||u("setupWizard.machines.createFailed"));return}await y(!0),Z.meshId&&k(Z.meshId),O(!1)}finally{M(!1)}}},[we,L,I,$,U,K,ce,h,s,r,y,k,f,u]),[ee,ue]=l.useState(""),[je,X]=l.useState(""),[G,z]=l.useState(null),[ie,Ne]=l.useState(!1),[Be,Le]=l.useState(!1),Je=l.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const fe=new Set(w.map(E=>String(E.daemon_id||E.daemonId||"")));return e.filter(E=>E.id&&!fe.has(E.id)&&!hp(E))},[t.addNodeDaemonPicker,w,e]),Se=l.useMemo(()=>e.find(fe=>fe.id===ee),[e,ee]),he=t.addNodeDaemonPicker?(Se==null?void 0:Se.workspaces)||[]:((me=e.find(fe=>fe.id===m))==null?void 0:me.workspaces)||[];l.useEffect(()=>{if(A||!b||!je.trim()){z(null);return}const fe=t.addNodeDaemonPicker?ee:_(S);if(!fe)return;let E=!1;return Ne(!0),s(fe,"plan_mesh_onboarding",{workspace:je.trim(),meshId:b,inlineMesh:S,operation:"add_existing"}).then(oe=>{E||z(r(oe))}).catch(oe=>{E||z({success:!1,error:(oe==null?void 0:oe.message)||"Git discovery failed"})}).finally(()=>{E||Ne(!1)}),()=>{E=!0}},[A,b,S,je,ee,t.addNodeDaemonPicker,_,s,r]);const pe=l.useCallback(async()=>{var oe,Ie,Z,se;const fe=_(S);if(!b||Be)return;if(!fe){f(u("mesh.host.noCommandTarget"));return}const E=je.trim();if(E){Le(!0),f(null);try{const ye=t.addNodeDaemonPicker?ee:fe,Fe=await s(ye,"plan_mesh_onboarding",{workspace:E,meshId:b,inlineMesh:S,operation:"add_existing"}),Me=r(Fe);if(z(Me),(Me==null?void 0:Me.success)===!1)throw new Error(`${Me.code||"onboarding_blocked"}: ${Me.error}${Me.action?` ${Me.action}`:""}`);const De={meshId:b,workspace:((oe=Me==null?void 0:Me.discovery)==null?void 0:oe.repoRoot)||E,repoRoot:(Ie=Me==null?void 0:Me.discovery)==null?void 0:Ie.repoRoot,isLocalWorktree:((Z=Me==null?void 0:Me.discovery)==null?void 0:Z.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&ee&&(De.daemonId=ee,De.machineId=Se==null?void 0:Se.machineId),De.providerPriority=nr(Zn(((se=t.addNodeDaemonPicker?Se:e[0])==null?void 0:se.availableProviders)||[]));const Te=await s(fe,"add_mesh_node",De),He=r(Te);if((He==null?void 0:He.success)===!1)throw new Error(He.error||"Add node failed");X(""),z(null),await y(!0)}catch(ye){f((ye==null?void 0:ye.message)||"Add node failed")}finally{Le(!1)}}},[S,b,je,ee,Se,Be,t.addNodeDaemonPicker,_,e,s,r,y,f,u]),Ee=!A&&!!S&&w.length>0;return n.jsxs("div",{className:"mx-auto flex w-full max-w-2xl flex-col gap-4 p-4",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-base font-semibold text-text-primary",children:u("setupWizard.title")}),n.jsx("p",{className:"mt-1.5 text-2xs text-text-muted",children:u("setupWizard.machines.description")})]}),g&&n.jsx("p",{className:"text-2xs text-red-400",children:g}),n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary p-4",children:n.jsx(VL,{daemons:e,features:t,meshes:h,meshesLoading:p,selectedMeshId:b,onSelectMesh:fe=>{k(fe),X(""),ue("")},createMode:A,onCreateModeChange:O,createName:L,onCreateNameChange:R,createDaemonId:F,onCreateDaemonIdChange:N,createWorkspace:I,onCreateWorkspaceChange:B,createPickerWorkspaces:de,createPlan:T,createPlanLoading:q,creating:K,createWarning:D,onCreate:ne,createRepoRemoteUrl:$,onCreateRepoRemoteUrlChange:W,createRepoIdentity:U,onCreateRepoIdentityChange:ae,createManualOpen:be,onCreateManualOpenChange:V,nodes:w,attachableDaemons:Je,attachDaemonId:ee,onAttachDaemonIdChange:fe=>{ue(fe),X("")},attachWorkspace:je,onAttachWorkspaceChange:X,attachPickerWorkspaces:he,attachPlan:G,attachPlanLoading:ie,attaching:Be,onAttach:pe,renderInstallOnboarding:d,nodeLabel:QL,daemonLabel:YL})}),n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("div",{className:"ml-auto flex items-center gap-2",children:n.jsx("button",{type:"button",className:Ee?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:c,children:u(Ee?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function Ui(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function XL(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=Ui();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 qn(e,t){return await fetch(XL(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 ZL{constructor(){qe(this,"adapters",new Map);qe(this,"states",new Map);qe(this,"runtimeListeners",new Map);qe(this,"screenshotCallbacks",new Map);qe(this,"statusCallbacks",new Set);qe(this,"stateChangeCallbacks",new Set);qe(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const s of this.adapters.keys())if(s.startsWith("standalone"))return s}return null}register(t,s){this.adapters.set(t,s),this.states.set(t,s.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,s){this.states.set(t,s);const r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(o=>o(r,s))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const s=this.resolveDaemonId(t);return s?this.adapters.get(s):void 0}getState(t){const s=this.resolveDaemonId(t);return s&&this.states.get(s)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,s){return!1}sendPtyInput(t,s,r){return this.ptyInputSender?this.ptyInputSender(t,s,r):!1}onScreenshot(t,s){return this.screenshotCallbacks.set(t,s),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,s){this.screenshotCallbacks.forEach(r=>r(t,s))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,s){this.statusCallbacks.forEach(r=>r(t,s))}emitRuntimeSnapshot(t,s,r=0,o=!1,a,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:s,truncated:o,cols:a,rows:i})}emitSessionOutput(t,s,r){!t||typeof s!="string"||!s||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:s})}onRuntimeEvent(t,s){const r=this.runtimeListeners.get(t)||new Set;return r.add(s),this.runtimeListeners.set(t,r),()=>{const o=this.runtimeListeners.get(t);o&&(o.delete(s),o.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,s,r){if(!s)return{success:!1,error:"sessionId is required"};const o=new URL(`/api/v1/runtime/${encodeURIComponent(s)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&o.searchParams.set("sinceSeq",String(r.sinceSeq));const a=await qn(`${o.pathname}${o.search}`);if(!a.ok){let c=`Runtime snapshot unavailable (${a.status})`;try{const d=await a.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await a.json();return this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,s){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(o=>o(s))}}const Kn=new ZL;function eE(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 tE="/ws/seqscribe",nE="standalone_dashboard",np=3e3,sE=3e4,rE=3e4,sp=3e3,oE=6e4;function aE(e){const t=e==null?void 0:e.VITE_ADHDEV_TRANSCRIPT_WORKER;return!(typeof t=="string"&&t.trim().toLowerCase()==="off")}function iE(e,t){const r=`${e.protocol==="https:"?"wss":"ws"}://${e.host}${tE}`;return t?`${r}?token=${encodeURIComponent(t)}`:r}function lE(e){if(!e||typeof e!="object")return!1;const t=e;return t.type==="subscribe"||t.type==="unsubscribe"?!0:t.type==="command"&&t.commandType==="report_transcript_transport"}class cE{constructor(t){qe(this,"socket",null);qe(this,"host",null);qe(this,"openedAt",null);qe(this,"reconnectTimer",null);qe(this,"reconnectDelay",np);qe(this,"unsubscribeInterest",null);qe(this,"sessionDaemons",new Map);qe(this,"activeSessions",[]);qe(this,"delivered",new Set);qe(this,"subRetryTimer",null);qe(this,"subRetryDelay",sp);qe(this,"started",!1);qe(this,"stopped",!1);this.deps=t}start(){this.started||this.stopped||(this.started=!0,this.unsubscribeInterest=this.deps.subscribeInterest(()=>this.syncInterest()),this.syncInterest(),this.connect())}stop(){var s;if(this.stopped)return;this.stopped=!0,(s=this.unsubscribeInterest)==null||s.call(this),this.unsubscribeInterest=null,this.reconnectTimer!==null&&this.deps.clearTimer(this.reconnectTimer),this.reconnectTimer=null;const t=this.socket;this.socket=null,this.stopHost(!1);try{t==null||t.close()}catch{}}isHostRunning(){return this.host!==null}currentReconnectDelay(){return this.reconnectDelay}connect(){var s,r;if(this.stopped)return;let t;try{t=this.deps.createSocket()}catch(o){(r=(s=this.deps).log)==null||r.call(s,`[Transcript] standalone lane socket failed: ${o instanceof Error?o.message:String(o)}`),this.scheduleReconnect();return}this.socket=t,t.addEventListener("open",()=>this.handleOpen(t)),t.addEventListener("close",()=>this.handleClose(t))}handleOpen(t){var r,o;if(this.stopped||t!==this.socket)return;this.openedAt=this.deps.now(),this.stopHost(!1);const s=this.deps.startHost(t,a=>this.deliver(a));if(!s){(o=(r=this.deps).log)==null||o.call(r,"[Transcript] standalone lane: transcript worker unavailable — staying on legacy chat-tail"),this.stopped=!0,this.socket=null;try{t.close()}catch{}return}this.host=s,this.activeSessions.length>0&&s.activateSessions(this.activeSessions),this.armSubRetry(!0)}handleClose(t){if(t!==this.socket)return;this.socket=null;const s=this.openedAt===null?0:this.deps.now()-this.openedAt;this.openedAt=null,s>=rE&&(this.reconnectDelay=np),this.stopHost(!0),this.scheduleReconnect()}scheduleReconnect(){if(this.stopped||this.reconnectTimer!==null)return;const t=this.reconnectDelay;this.reconnectDelay=Math.min(Math.round(this.reconnectDelay*1.5),sE),this.reconnectTimer=this.deps.setTimer(()=>{this.reconnectTimer=null,this.connect()},t,"reconnect")}stopHost(t){const s=this.host;if(s&&(this.host=null,this.delivered.clear(),this.subRetryTimer!==null&&this.deps.clearTimer(this.subRetryTimer),this.subRetryTimer=null,s.stop(),!!t))for(const[r,o]of this.sessionDaemons)for(const a of o)console.warn(`[Transcript] standalone replica fallback — session=${r} reason=no_node`),this.deps.reportFallback(a,r,"no_node")}syncInterest(){var r;const t=new Map;for(const[o,a]of this.deps.collectInterest())for(const i of a){const c=t.get(i);c?c.includes(o)||c.push(o):t.set(i,[o])}this.sessionDaemons=t;const s=[...t.keys()].sort();if(!(s.length===this.activeSessions.length&&s.every((o,a)=>o===this.activeSessions[a]))){this.activeSessions=s;for(const o of[...this.delivered])t.has(o)||this.delivered.delete(o);(r=this.host)==null||r.activateSessions(s),this.armSubRetry(!0)}}armSubRetry(t){if(t&&(this.subRetryDelay=sp),!this.host||this.subRetryTimer!==null||!this.activeSessions.some(r=>!this.delivered.has(r)))return;const s=this.subRetryDelay;this.subRetryTimer=this.deps.setTimer(()=>{this.subRetryTimer=null,this.rearmUndelivered()},s,"sub-retry")}rearmUndelivered(){const t=this.host;!t||this.stopped||this.activeSessions.filter(r=>!this.delivered.has(r)).length===0||(t.activateSessions(this.activeSessions.filter(r=>this.delivered.has(r))),t.activateSessions(this.activeSessions),this.subRetryDelay=Math.min(this.subRetryDelay*2,oE),this.armSubRetry(!1))}deliver(t){const s=this.sessionDaemons.get(t.sessionId);if(s){this.delivered.add(t.sessionId);for(const r of s)this.deps.applySnapshot(r,t.sessionId,t.snapshot,{omittedBefore:t.omittedBefore})}}}function Ul(e){return{kind:"transcript-bridge-control",event:e}}function dE(e){return typeof e=="object"&&e!==null&&e.kind==="transcript-bridge-snapshot"}function uE(e,t){return{kind:"transcript-session-activation",sessionIds:[...e],...t?{ownerWriterId:t}:{}}}var mE=Object.create,xx=Object.defineProperty,hE=Object.getOwnPropertyDescriptor,yx=Object.getOwnPropertyNames,pE=Object.getPrototypeOf,fE=Object.prototype.hasOwnProperty,gE=(e,t)=>function(){return t||(0,e[yx(e)[0]])((t={exports:{}}).exports,t),t.exports},bE=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of yx(t))!fE.call(e,o)&&o!==s&&xx(e,o,{get:()=>t[o],enumerable:!(r=hE(t,o))||r.enumerable});return e},xE=(e,t,s)=>(s=e!=null?mE(pE(e)):{},bE(xx(s,"default",{value:e,enumerable:!0}),e)),yE=gE({"../../node_modules/canonicalize/lib/canonicalize.js"(e,t){t.exports=function s(r){if(typeof r=="number"&&isNaN(r))throw new Error("NaN is not allowed");if(typeof r=="number"&&!isFinite(r))throw new Error("Infinity is not allowed");return r===null||typeof r!="object"?JSON.stringify(r):r.toJSON instanceof Function?s(r.toJSON()):Array.isArray(r)?`[${r.reduce((i,c,d)=>`${i}${d===0?"":","}${s(c===void 0||typeof c=="symbol"?null:c)}`,"")}]`:`{${Object.keys(r).sort().reduce((a,i)=>{if(r[i]===void 0||typeof r[i]=="symbol")return a;const c=a.length===0?"":",";return`${a}${c}${s(i)}:${s(r[i])}`},"")}}`}}});function un(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}var vx=["agent:generating_started","agent:waiting_approval","agent:waiting_choice","agent:generating_completed","agent:stopped","monitor:no_progress","monitor:long_generating"];un(vx);var vE=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];un(vE);var wE=["p2p_offer","p2p_ice"];un(wE);var SE=["mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];un(SE);var kE=["auth","status_report","status_heartbeat","status_event","command_result","error","agent_event","beacon_vectors","daemon_mesh_command","p2p_offer","p2p_ice"];un(kE);var jE=["auth_ok","auth_error","machine_evicted","force_disconnect","token_revoked","version_mismatch","force_update_required","command","agent_command","resolve_action","beacon_vectors_result","daemon_mesh_result","p2p_ready","p2p_offer","p2p_answer","p2p_ice","mesh_p2p_ready","mesh_p2p_offer","mesh_p2p_answer","mesh_p2p_ice"];un(jE);var NE=["daemon:disconnect","team:session_viewed","team:view_request","team:view_request_approved","team:view_request_rejected"],CE=[...vx,...NE];un(CE);var _E=["connected","initial_state","daemon_status","status_event","system_announcement","auth_error","heartbeat","p2p_offer","p2p_ice"];un(_E);var AE=["heartbeat","refresh","p2p_ready","p2p_answer","p2p_ice"];un(AE);var TE=["p2p_ready","p2p_answer","p2p_ice"];un(TE);var IE=["share:connected","share:revoked","share:expired","share:error","share:viewer_count","p2p_offer","p2p_ice"];un(IE);var ME=["p2p_ready","p2p_offer","p2p_answer","p2p_ice"];un(ME);var wx=["ping","pong","command","input","pty_input","pty_resize","screenshot_start","screenshot_stop","subscribe","unsubscribe","seqscribe_session_interest","read","write","list"];un(wx);var Sx=["ping","pong","p2p_evicted","status_report","status_event","topic_update","topic_update_chunk","session_output","session_output_chunk","session_io_error","command_result","command_result_chunk","response"];un(Sx);[...new Set([...wx,...Sx])];var kx=["idle","generating","waiting_approval","waiting_choice","finalizing","error","stopped","starting","panel_hidden","not_monitored","disconnected"];new Set(kx);var RE=["pending","assigned","completed","failed","cancelled"],PE=["completed","failed","cancelled"],LE=["code_change","validation","live_debug_readonly","launch_app","convergence"],EE=["low","normal","high"],DE=["low","medium","high"],OE=["when_idle","interrupt"],FE=["preserve","stop","delete_stopped","stop_and_delete"],jx=["completed","blocked","failed"],Nx=["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"];function ds(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}ds(RE);ds(PE);ds(LE);ds(EE);ds(DE);ds(OE);ds(FE);ds(jx);ds(Nx);var $E=["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"],HE=["report_completion","progress_update","peer_context_pull","git_status","git_log","git_diff"];new Set(HE);var BE=["fsm_edge","short_gen_inline","completion_flush_genuine","completion_flush_weak","monitor_final_summary","pre_cleanup_transcript","stall_transcript","startup_grace_collapse","acp_prompt_response","cdp_state","approval_gate","modal_button","mesh_stall_watchdog","status_monitor","pty_exit","provider_error","coordinator_probe","mcp_probe","worker_tool","dispatch","input_service","operator","intentional_cleanup","scheduler","git_probe","session_registry"],WE=["mesh_queue","mesh_direct","plain"],UE=["delivered","queued"],KE=["local","p2p"],qE=["worker_absent","transport_error","spawn_failed","rejected_by_worker","timeout"],zE=["default","native_source"],GE=["restart","live_holder"],VE=["approval","choice"],YE=["approved","rejected","answered"],QE=["modal_button","auto_approve","prompt_answer"],JE=["genuine","weak"],XE=["missing_final_assistant","finalization_timeout","terminal_block_hard_cap","decoupled_completion"],ZE=["completed","aborted"],eD=["alive","unknown","read_failed","dead"],tD=["auth_failed","billing_failed"],nD=["provider_error","adapter_error","spawn_failed","auth_failed","billing_failed","unknown","daemon_restart"],sD=["operator_cancel","intentional_cleanup","task_removed","mission_abandoned","superseded"],rD=["completed","failed"],oD=["operator_update","refine_terminal","validation_terminal"],aD=["delivered","queued","duplicate"],iD=[...kx,"unknown"],Cx=["await_delivery","await_consume","await_turn","liveness","hard_ceiling","live_pending","transcript_quiet","weak_candidate","suspension_before_consumed","await_report","await_end"],lD=["completed","failed","cancelled"],cD=["genuine","weak","tool_report","operator"],dD=["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"],_x=["completed","failed","cancelled","stopped","approval","choice","approval_resolved","candidate","no_progress","progress","late_completion","mesh_event"],gr={t:"id"},br={t:"id",optional:!0},gs={t:"bool"},va={t:"bool",optional:!0},rp={t:"ms"},uD={t:"ms",optional:!0},wa={t:"int",optional:!0},Ht=e=>({t:"enum",values:e}),ro=e=>({t:"enum",values:e,optional:!0}),mD={dispatch_accepted:{scope:Ht(WE),messageId:gr,meshId:br,nodeId:br,providerType:br,attemptNo:wa,dispatchNonce:wa,consumeProfile:ro(zE),maxTaskRetries:wa,coordinator:{t:"coordinator",optional:!0}},delivered:{messageId:gr,outcome:Ht(UE),via:Ht(KE)},delivery_refused:{messageId:gr,reason:Ht($E)},dispatch_failed:{workerAbsent:gs,reason:Ht(qE),refusalCode:br},duplicate_dispatch_refusal:{holderSessionId:gr,holderAttemptId:br},session_rebound:{toSessionId:gr,reason:Ht(GE)},turn_started:{retro:gs},suspension:{modal:Ht(VE),modalKey:br},suspension_resolved:{resolution:Ht(YE),via:Ht(QE)},turn_end:{strength:Ht(JE),afterFinalizationTimeout:va,hollow:va,summary:{t:"summary_ref",optional:!0},blockReason:ro(XE),releasedByHardCap:va,nativeOutcome:ro(ZE),live:{t:"live",optional:!0},reportExpected:va},transcript_final:{selfAttributing:gs,nativeRead:gs,nativeMarker:{t:"native_marker",optional:!0},live:{t:"live"},summary:{t:"summary_ref",optional:!0},messageAt:uD},transcript_activity:{newestActivityAt:rp},no_progress:{stalledMs:rp,observedStatus:Ht(iD),finalAssistantPresent:gs},liveness:{result:Ht(eD)},process_exit:{exitCode:{t:"int",nullable:!0},providerFailure:ro(tD)},session_error:{reason:Ht(nD)},worker_report:{outcome:Ht(jx),summary:{t:"summary_ref",optional:!0},hasHandoffNotes:gs,branchState:ro(Nx),touchedFileCount:wa},worker_progress:{note:{t:"summary_ref",optional:!0}},git_side_effect:{dirty:gs,commitsSinceDispatch:{t:"int"},attributable:gs},cancel:{reason:Ht(sD)},operator_status:{status:Ht(rD),reason:Ht(oD)},coordinator_ack:{notify:Ht(_x),outcome:Ht(aD)},hold_expired:{holdId:gr,reason:Ht(Cx)}},hD=Object.keys(mD);function Is(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Is(BE);Is(hD);Is(dD);Is(_x);Is(Cx);Is(lD);Is(cD);var pD=["turn.evidence","turn.committed","turn.notify","mesh.record"];Is(pD);var fD=["daemon_required","turn_ledger_unavailable","ledger_not_owner"];function Hn(e){const t=new Set(e);return s=>typeof s=="string"&&t.has(s)}Hn(fD);var gD=["applied","recorded","rejected"];Hn(gD);var bD=["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(bD);var xD=["completed","failed"];Hn(xD);var yD=["operator_update","refine_terminal","validation_terminal"];Hn(yD);var vD=["own","fleet"];Hn(vD);var wD=["active","paused","completed","abandoned"];Hn(wD);var SD=["magi","coordinator"];Hn(SD);var kD=["provider_quirk","pattern_to_avoid","recovery_lesson"];Hn(kD);var jD=["coordinator","unknown"];Hn(jD);var ND=["gate_claimed","gate_released","gate_abandoned","node_patched"];Hn(ND);var CD=["turn_observe","mesh_record","turn_cancel","operator_status","turn_query","mesh_index_query","mission_upsert","mission_query","note_upsert","note_forget","tool_call_record","ledger_query","mission_list_query","record_local","queue_query","queue_enqueue","queue_enqueue_graph","queue_cancel","queue_requeue","direct_dispatch_record","graph_audit_record","active_work_query","recovery_context_query","graph_gate_claim","graph_gate_release","graph_gate_abandon","graph_node_patch","graph_view_query","task_stats_query","prune_stale_direct","orphaned_pin_notify"];Hn(CD);var _D=xE(yE());_D.default;new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;var AD="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";new Map([...AD].map((e,t)=>[e,t]));new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;new globalThis.TextDecoder;new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1});/*! Bundled license information:
|
|
110
|
-
|
|
111
|
-
@noble/hashes/esm/utils.js:
|
|
112
|
-
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
113
|
-
*/const TD=4096;function ID(e){return typeof e.isOpen=="function"?e.isOpen():e.readyState===1||e.readyState==="open"}function MD(e,t,s={}){const r=s.preOpenQueueCap??TD,o=[];let a=!1;const i=()=>{for(const d of o.splice(0))e.send(d)},c=()=>{var d;o.length=0,a=!0,t.onmessage=null,(d=s.onOverflow)==null||d.call(s,"pre_open_queue_full"),t.postMessage(Ul("queue_overflow"))};return t.onmessage=d=>{if(a)return;const u=d.data;typeof u=="string"&&(ID(e)?(o.length>0&&i(),e.send(u)):o.length<r?o.push(u):c())},e.addEventListener("message",d=>{if(a)return;const u=d.data;typeof u=="string"&&t.postMessage(u)}),e.addEventListener("open",()=>{a||(i(),t.postMessage(Ul("transport_open")))}),e.addEventListener("close",()=>{a||(a=!0,o.length=0,t.postMessage(Ul("transport_closed")))}),{pendingCount(){return o.length},close(){a||(a=!0,o.length=0,t.onmessage=null)}}}function RD(e,t){var d,u,m,h;const s=t.createChannel??(()=>new MessageChannel),r=s(),o=s(),a=t.createWorker();a.postMessage({sessionKey:t.sessionKey,writerId:t.writerId},[r.port2,o.port2]),(u=(d=r.port1).start)==null||u.call(d),(h=(m=o.port1).start)==null||h.call(m),o.port1.onmessage=p=>{var g;dE(p.data)&&((g=t.onSnapshot)==null||g.call(t,p.data))};let i=MD(e,r.port1,{...t.preOpenQueueCap!==void 0?{preOpenQueueCap:t.preOpenQueueCap}:{},onOverflow:()=>{var p;return(p=t.onOverflow)==null?void 0:p.call(t)}}),c=!1;return{pendingCount:()=>(i==null?void 0:i.pendingCount())??0,running:()=>!c,activateSessions(p,g){c||o.port1.postMessage(uE(p,g))},stop(){var p;if(!c){c=!0,i==null||i.close(),i=null,o.port1.onmessage=null;for(const g of[r.port1,o.port1])try{(p=g.close)==null||p.call(g)}catch{}a.terminate()}}}}new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;const PD="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";new Map([...PD].map((e,t)=>[e,t]));new globalThis.TextEncoder;new globalThis.TextDecoder;new globalThis.TextEncoder;new globalThis.TextDecoder;const LD={};function ED(){if(typeof window>"u"||typeof Worker>"u"||typeof WebSocket>"u")return()=>{};if(!aE(LD))return()=>{};const e=iE(window.location,Ui()),t=new cE({createSocket:()=>new WebSocket(e),startHost:(s,r)=>RD(s,{writerId:nE,sessionKey:"transcript",onSnapshot:r,createWorker:()=>new Worker(new URL("/assets/transcript-worker-entry-Dazh6WtK.js",import.meta.url),{type:"module"}),onOverflow:()=>console.warn("[Transcript] standalone lane pre-open queue overflow — channel reset")}),collectInterest:LC,subscribeInterest:EC,applySnapshot:MC,reportFallback:PC,setTimer:(s,r)=>setTimeout(s,r),clearTimer:s=>clearTimeout(s),now:()=>Date.now(),log:s=>console.warn(s)});return t.start(),()=>t.stop()}function DD(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,s=Ui();return s?`${t}?token=${encodeURIComponent(s)}`:t}const Sa=DD(),op=3e3,OD=3e4;let Ln=null,FD=0;const di=new Map;let Os=null,So=null,ap=null;function ip(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function oo(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function $D(e){return e==="connected"?"connected":e}async function ko(e,t,s){const r=Xg(e,s||{}),o=Ln;if(o&&o.readyState===WebSocket.OPEN){const a=`req_${++FD}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{di.delete(a),c(new Error(`WS command timeout: ${t}`))},3e4);di.set(a,{resolve:u=>{clearTimeout(d),i(u)},reject:u=>{clearTimeout(d),c(u)}}),o.send(JSON.stringify({type:"command",requestId:a,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Gc(e,t){const s=Ln;if(!s||s.readyState!==WebSocket.OPEN||!lE(t))return!1;try{return s.send(JSON.stringify(t)),!0}catch{return!1}}function Ax(e,t,s){const r=Ln;if(!r||r.readyState!==WebSocket.OPEN)return!1;const o=Xg(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}}Kn.registerPtyInputSender(Ax);class HD{constructor(t){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Ln==null?void 0:Ln.readyState)===WebSocket.OPEN}get connectionState(){return(Ln==null?void 0:Ln.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,s){return ko(this.daemonId,t,s)}async sendInput(t,s){return ko(this.daemonId,"cdp_remote_action",{action:t,params:s,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Os&&(clearInterval(Os),Os=null);const s=async()=>{if(this.hasCommandChannel)try{const r=await ko(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());Kn.emitScreenshot(this.daemonId,o)}}catch{}};s(),Os=setInterval(s,2e3)}stopScreenshots(t){Os&&(clearInterval(Os),Os=null)}}let Nn=null;function BD(e){return(!Nn||Nn.daemonId!==e)&&(Nn=new HD(e)),Nn}function WD({children:e}){const t=l.useRef(Ar()),s=Ar();t.current=s;const{setUserName:r}=Hv(),o=l.useRef(r);o.current=r;const a=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((y,b)=>{c(y),So==null||So(y,b)},[]),u=l.useRef(null),m=l.useRef(),h=l.useRef(op),p=l.useRef(!0),g=l.useRef(!1),f=l.useRef("initial_connect");return l.useEffect(()=>{p.current=!0,g.current=!1;function y(){var v,C;if(!p.current||((v=u.current)==null?void 0:v.readyState)===WebSocket.OPEN||((C=u.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Sa}...`),oo("connect_attempt",{url:Sa,reason:f.current,delayMs:h.current});let j;try{j=new WebSocket(Sa)}catch(x){console.error("[Standalone WS] Failed to create WebSocket:",x),b();return}u.current=j,j.onopen=()=>{if(!p.current){j.close();return}d("connected"),h.current=op,oo("open",{url:Sa,reason:f.current}),_n.resubscribeAll({sendData:Gc}),console.log("[Standalone WS] Connected")},Ln=j,j.onmessage=x=>{var S,w;try{const _=JSON.parse(x.data);if((_.type==="command_result"||_.type==="error")&&_.requestId){const A=di.get(_.requestId);A&&(di.delete(_.requestId),_.type==="error"?A.reject(new Error(((S=_.data)==null?void 0:S.message)||"Command failed")):A.resolve(_.data));return}if(_.type==="session_output"){const A=_.sessionId||_.cliId||_.cliType;A&&Kn.emitSessionOutput(A,typeof _.data=="string"?_.data:"",typeof _.seq=="number"?_.seq:void 0);return}if(_.type==="runtime_snapshot"){Kn.emitRuntimeSnapshot(_.sessionId,typeof _.text=="string"?_.text:"",typeof _.seq=="number"?_.seq:0,!!_.truncated,typeof _.cols=="number"?_.cols:void 0,typeof _.rows=="number"?_.rows:void 0);return}if(eE(_,ap,ct,RC))return;if(_.type==="topic_update"){const A=_.update;A&&_n.publish(A);return}if(_.type==="status"||_.type==="initial_state"){const A=_.data;if(!A)return;const{injectEntries:O,markLoaded:L,getIdes:R}=t.current,F=A.instanceId||"standalone";ap=F;const N=R().find(T=>T.id===F),I=BD(F);Kn.register(F,I),Kn.setState(F,"connected"),d("connected",F),Kn.emitStatus(F,A);const B=qa(A,{daemonId:F,existingDaemon:N,existingEntries:R()});ip("ws_status",{type:_.type,daemonId:F,sessions:(A.sessions||[]).map(T=>({id:T.id,parentId:T.parentId,providerType:T.providerType,kind:T.kind,transport:T.transport,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,title:T.title})),recentLaunches:(A.recentLaunches||[]).map(T=>({id:T.id,providerType:T.providerType,kind:T.kind,workspace:T.workspace,lastLaunchedAt:T.lastLaunchedAt}))}),ip("entries",{daemonId:F,entries:B.filter(T=>T.type!=="adhdev-daemon").map(T=>({id:T.id,type:T.type,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,sessionId:T.sessionId}))}),B.length>0&&O(B,{authoritativeDaemonIds:[F]}),L(),i.current!==F&&((w=a.current)==null||w.call(a),i.current=F,a.current=_n.subscribe({sendData:Gc},F,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${F}`,params:{includeSessions:!0}},T=>{if(T.topic!=="daemon.metadata")return;const H=t.current.getIdes(),q=H.find(K=>K.id===F),J=qa(T.status,{daemonId:F,existingDaemon:q,existingEntries:H,timestamp:T.timestamp});J.length>0&&t.current.injectEntries(J,{authoritativeDaemonIds:[F]}),T.userName&&o.current&&o.current(T.userName)}))}}catch(_){console.error("[Standalone WS] Parse error:",_)}},j.onclose=x=>{p.current&&(Nn==null||Nn.stopScreenshots(),Nn&&Kn.setState(Nn.daemonId,"disconnected"),d("disconnected"),u.current=null,f.current=`close:${x.code}${x.wasClean?":clean":":unclean"}`,oo("close",{code:x.code,reason:x.reason||"",wasClean:x.wasClean}),b())},j.onerror=x=>{g.current||!p.current||(f.current="error",oo("error",{message:x instanceof Event?"event":String(x),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",x))}}function b(){if(!p.current)return;clearTimeout(m.current);const j=h.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),oo("schedule_reconnect",{reason:f.current,delayMs:j}),m.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,OD),y()},j)}y();const k=ED();return()=>{var j;k(),p.current=!1,g.current=!0,(j=a.current)==null||j.call(a),a.current=null,i.current=null,clearTimeout(m.current),u.current&&(u.current.onerror=null,u.current.onclose=null,u.current.close(),u.current=null,Ln=null),Nn&&(Nn.stopScreenshots(),Kn.unregister(Nn.daemonId))}},[]),n.jsx(n.Fragment,{children:e})}function UD({children:e}){const[t,s]=l.useState("disconnected"),[r,o]=l.useState(null);l.useEffect(()=>(So=(i,c)=>{s(i),c&&o(c)},()=>{So=null}),[]);const a=l.useMemo(()=>{const i=t==="connected",c=$D(t),d={};return r&&(d[r]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d,usesP2P:!1}},[t,r]);return n.jsx($v,{connectionOverrides:a,children:n.jsx(WD,{children:e})})}const Tx="adhdev_standalone_font_preferences",Js={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Ki=[{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"}],To=[{id:"default",label:"Default mono",labelKey:"standalone.fonts.presets.defaultMono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",labelKey:null,family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",labelKey:null,family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",labelKey:null,family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",labelKey:null,family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",labelKey:"standalone.fonts.presets.custom",family:"",description:"Enter any CSS monospace stack"}],KD=new Set(Ki.map(e=>e.id)),qD=new Set(To.map(e=>e.id));function zn(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Oa("chat",t.chat),code:Oa("code",t.code),terminal:Oa("terminal",t.terminal)}}function Oa(e,t){const s=Js[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},o=typeof r.preset=="string"?r.preset.trim():"",a=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?KD:qD).has(o)?o==="custom"?a?{preset:"custom",customFamily:a}:s:{preset:o}:s}function Fa(e,t){var o;const s=Oa(e,t);if(s.preset==="custom"&&s.customFamily)return s.customFamily;const r=e==="chat"?Ki:To;return((o=r.find(a=>a.id===s.preset))==null?void 0:o.family)||r[0].family}function zD(e){const t=zn(e),s=Fa("chat",t.chat),r=Fa("code",t.code),o=Fa("terminal",t.terminal);return{"--chat-font-family":s,"--chat-code-font-family":r,"--chat-terminal-font-family":o,"--chat-tool-font-family":o}}function Bs(e,t=document.documentElement){const s=zn(e),r=zD(s);t.setAttribute("data-standalone-fonts","custom");for(const[o,a]of Object.entries(r))t.style.setProperty(o,a);return s}function Vc(e){const t=zn(e);try{localStorage.setItem(Tx,JSON.stringify(t))}catch{}return t}function GD(){try{const e=localStorage.getItem(Tx);if(e)return zn(JSON.parse(e))}catch{}return Js}function VD(){return Bs(GD())}function ao(e,t,s){const r=e==="chat"?Ki:To,o=r.find(a=>a.id===t)||r[0];return o.labelKey&&s?s(o.labelKey,o.label):o.label}function YD({children:e}){const t=rr(),s=ui(),{t:r}=ve("common"),o=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:n.jsx(Lp,{}),label:r("nav.dashboard"),active:s.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:n.jsx(Ks,{}),label:r("nav.machines"),active:s.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:n.jsx(Gn,{}),label:r("nav.mesh"),active:s.pathname.startsWith("/mesh")||s.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"notifications",path:"/notifications",icon:n.jsx(js,{}),label:r("nav.notifications"),active:s.pathname.startsWith("/notifications"),onSelect:()=>t("/notifications")},{id:"settings",path:"/settings",icon:n.jsx(Dr,{}),label:r("nav.settings"),active:s.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[s.pathname,t,r]),a=l.useMemo(()=>[{id:"docs",label:n.jsxs(n.Fragment,{children:[n.jsx("span",{children:r("nav.docs")}),n.jsx("span",{className:"ml-auto text-4xs text-text-muted",children:"↗"})]}),icon:n.jsx(Ep,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("nav.docs")},{id:"about",label:r("nav.about"),icon:n.jsx(Io,{}),active:s.pathname==="/about",onSelect:()=>t("/about"),title:r("nav.about")}],[s.pathname,t,r]);return n.jsx(RA,{brand:({collapsed:i})=>n.jsxs(n.Fragment,{children:[n.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&n.jsx("span",{children:"ADHDev"})]}),navItems:o,footerItems:a,footerInfo:({collapsed:i})=>i?null:n.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.59"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>n.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:r(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[n.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&n.jsx("span",{className:"text-xs",children:r("standalone.layout.collapse")})]}),children:e})}function QD(){const e=rr(),{sendCommand:t}=_t(),{ides:s}=An(),r=l.useMemo(()=>s.filter(o=>o.daemonMode||o.type==="adhdev-daemon").map(o=>o),[s]);return n.jsx(JL,{daemons:r,features:rx,sendCommand:t,unwrapResult:o=>o,normalizeMesh:o=>o,onClose:()=>e("/mesh")})}const JD=[{icon:n.jsx(Ks,{size:16}),key:"localFirst"},{icon:n.jsx(Jn,{size:16}),key:"chatRelay"},{icon:n.jsx(sd,{size:16}),key:"screenshots"},{icon:n.jsx(Xn,{size:16}),key:"remoteControl"},{icon:n.jsx(Tr,{size:16}),key:"multiIde"},{icon:n.jsx(Ep,{size:16}),key:"cliAcp"}],XD=[{icon:n.jsx(fi,{size:16}),key:"anywhere"},{icon:n.jsx(Lp,{size:16}),key:"p2pStream"},{icon:n.jsx(js,{size:16}),key:"mobileNotifications"},{icon:n.jsx(Qv,{size:16}),key:"restApi"},{icon:n.jsx(Xv,{size:16}),key:"enterpriseControls"}],ZD=[{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 e5(){const{t:e}=ve("common");return n.jsxs($o,{icon:n.jsx(Io,{className:"text-text-primary"}),title:e("standalone.about.title"),subtitle:e("standalone.about.subtitle"),widthClassName:"max-w-5xl",actions:n.jsxs("div",{className:"px-3 py-1 text-2xs font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","1.0.59"]}),children:[n.jsx(Nt,{children:n.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[n.jsxs("div",{className:"max-w-2xl",children:[n.jsx("div",{className:"text-2xs font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),n.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),n.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),n.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[n.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),n.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),n.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),n.jsx(Nt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:n.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:JD.map(t=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[n.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[n.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),e("standalone.about.features."+t.key+".title")]}),n.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.features."+t.key+".desc")})]},t.key))})}),n.jsx(Nt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:n.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:bA.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:yA.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:xA.map(t=>`${t.icon} ${t.name}`)}].map(t=>n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[n.jsx("div",{className:"text-2xs font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),n.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(s=>n.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-xs text-text-secondary",children:s},s))})]},t.label))})}),n.jsx(Nt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:n.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:XD.map(t=>n.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[n.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[n.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),e("standalone.about.extras."+t.key+".title")]}),n.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.extras."+t.key+".desc")})]},t.key))})}),n.jsx(Nt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:n.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:n.jsxs("table",{className:"w-full text-xxs",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"bg-bg-secondary",children:[n.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-2xs uppercase tracking-wider",children:e("standalone.about.featureHeader")}),n.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-2xs uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),n.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-2xs uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),n.jsx("tbody",{children:ZD.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(Ei,{icon:n.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:n.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[n.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),n.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[n.jsx(iw,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Kl(e,t,s){return{...e,[t]:s}}function ql({surface:e,title:t,description:s,value:r,options:o,onChange:a}){const{t:i}=ve("common");return n.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[n.jsxs("div",{className:"flex items-center gap-1 text-sm font-medium text-text-primary",children:[t,n.jsx(dt,{content:s,size:12})]}),n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx(DA,{value:r.preset,onChange:c=>{const d=c.target.value;a(d==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:d})},children:o.map(c=>n.jsx("option",{value:c.id,children:c.labelKey?i(c.labelKey,c.label):c.label},c.id))}),r.preset==="custom"&&n.jsx(Dn,{type:"text",className:"font-mono",placeholder:i("standalone.fonts.customFamilyPlaceholder"),value:r.customFamily||"",onChange:c=>a({preset:"custom",customFamily:c.target.value})}),n.jsxs("div",{className:"text-2xs text-text-muted",children:[n.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",n.jsx("span",{className:"font-mono break-all",children:Fa(e,r)})]})]})]})}function t5({value:e,savedValue:t,saving:s=!1,error:r,notice:o,onChange:a,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:u}=ve("common"),m=JSON.stringify(e)!==JSON.stringify(t);return n.jsxs("div",{className:"flex flex-col gap-4",children:[r&&n.jsx(zt,{variant:"error",children:r}),o&&n.jsx(zt,{variant:"success",children:o}),n.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[n.jsx(ql,{surface:"chat",title:u("standalone.fonts.chat"),description:u("standalone.fonts.chatDescription"),value:e.chat,options:Ki,onChange:h=>a(Kl(e,"chat",h))}),n.jsx(ql,{surface:"code",title:u("standalone.fonts.code"),description:u("standalone.fonts.codeDescription"),value:e.code,options:To,onChange:h=>a(Kl(e,"code",h))}),n.jsx(ql,{surface:"terminal",title:u("standalone.fonts.terminal"),description:u("standalone.fonts.terminalDescription"),value:e.terminal,options:To,onChange:h=>a(Kl(e,"terminal",h))})]}),n.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[n.jsx("div",{className:"flex items-center justify-between gap-3",children:n.jsxs("div",{className:"flex items-center gap-1 text-sm font-medium text-text-primary",children:[u("standalone.fonts.livePreview"),n.jsx(dt,{size:12,content:[u("standalone.fonts.previewSummary",{chat:ao("chat",e.chat.preset,u),code:ao("code",e.code.preset,u),terminal:ao("terminal",e.terminal.preset,u)}),u("standalone.fonts.defaultsSummary",{chat:ao("chat",Js.chat.preset,u),code:ao("code",Js.code.preset,u)}),u("standalone.fonts.fontOverridesNotice")].join(`
|
|
114
|
-
|
|
115
|
-
`)})]})}),n.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:n.jsxs("div",{className:"chat-container-content",children:[n.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:n.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[n.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[n.jsx("span",{className:"chat-sender",children:"Hermes"}),n.jsx("span",{className:"chat-time",children:u("standalone.fonts.previewNow")})]}),n.jsxs("div",{className:"chat-markdown",children:[n.jsx("p",{children:n.jsx($a,{i18nKey:"standalone.fonts.previewProse",ns:"common",components:{strong:n.jsx("strong",{}),code:n.jsx("code",{})}})}),n.jsx("pre",{children:n.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),n.jsxs("div",{className:"chat-msg-tool",children:[n.jsx("span",{className:"tool-icon",children:"▸"}),n.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),n.jsxs("div",{className:"chat-msg-terminal",children:[n.jsx("div",{className:"chat-msg-header",children:u("standalone.fonts.terminal")}),n.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx(os,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:s||!m,children:u(s?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),n.jsx(os,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:s||!m,children:u("standalone.fonts.revertToSaved")}),n.jsx(os,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:s,children:u("standalone.fonts.resetToDefaults")})]})]})}function n5(){const{t:e}=ve("common"),{ides:t}=An(),s=t.find(W=>W.type==="adhdev-daemon"),{sendCommand:r}=_t(),{userName:o}=An(),[a,i]=l.useState(o||""),[c,d]=l.useState(null),[u,m]=l.useState(null),[h,p]=l.useState(Js),[g,f]=l.useState(!1),[y,b]=l.useState(""),[k,j]=l.useState(""),[v,C]=l.useState("127.0.0.1"),[x,S]=l.useState(""),[w,_]=l.useState(""),[A,O]=l.useState(""),[L,R]=l.useState(""),[F,N]=l.useState(""),[I,B]=l.useState(!1),T=async()=>{const U=await(await qn("/auth/session")).json();d(U)},H=async()=>{const U=await(await qn("/api/v1/standalone/preferences")).json();m(U),C(U.standaloneBindHost);const ae=zn(U.standaloneFontPreferences);p(ae),Bs(ae),Vc(ae)};l.useEffect(()=>{o!==void 0&&i(o)},[o]),l.useEffect(()=>{Promise.all([T(),H()]).catch(W=>{R(W instanceof Error?W.message:String(W))})},[]),l.useEffect(()=>{Bs(h)},[h]);const q=W=>{const U=W.target.value.trim();s!=null&&s.id&&U!==o&&r(s.id,"set_user_name",{userName:U}).catch(console.error)},J=async()=>{b(""),j(""),f(!0);try{const W=zn(h),U=await qn("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:W})}),ae=await U.json();if(!U.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to save standalone font preferences");const be=zn(ae.standaloneFontPreferences);m(ae),p(be),Bs(be),Vc(be),j(e("standalone.settings.fontsSaved"))}catch(W){b(W instanceof Error?W.message:String(W))}finally{f(!1)}},K=()=>{const W=zn(u==null?void 0:u.standaloneFontPreferences);b(""),j(""),p(W),Bs(W)},M=()=>{b(""),j(""),p(Js),Bs(Js)},D=async()=>{R(""),N(""),B(!0);try{const W=await qn("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:v})}),U=await W.json();if(!W.ok)throw new Error((U==null?void 0:U.error)||"Failed to save standalone network preference");m(U),C(U.standaloneBindHost),N(U.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(W){R(W instanceof Error?W.message:String(W))}finally{B(!1)}},P=async()=>{if(R(""),N(""),w.trim().length<4){R(e("standalone.settings.passwordTooShort"));return}if(w!==A){R(e("standalone.settings.passwordMismatch"));return}B(!0);try{const W=await qn("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:x,newPassword:w})}),U=await W.json();if(!W.ok)throw new Error((U==null?void 0:U.error)||"Failed to save password");d(U),await H(),S(""),_(""),O(""),N(c!=null&&c.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),bx()}catch(W){R(W instanceof Error?W.message:String(W))}finally{B(!1)}},$=async()=>{R(""),N(""),B(!0);try{const W=await qn("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:x,clear:!0})}),U=await W.json();if(!W.ok)throw new Error((U==null?void 0:U.error)||"Failed to clear password");d(U),await H(),S(""),_(""),O(""),N(e("standalone.settings.passwordDisabled"))}catch(W){R(W instanceof Error?W.message:String(W))}finally{B(!1)}};return n.jsxs($o,{icon:n.jsx(Dr,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[(c==null?void 0:c.publicHostWarning)&&n.jsx(zt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),n.jsx(Nt,{title:e("standalone.settings.daemonSection"),children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[n.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.versionLabel")}),n.jsxs("span",{className:"font-mono text-xs text-text-primary",children:["v","1.0.59"]})]}),n.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[n.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.statusLabel")}),n.jsx("span",{className:`text-xs font-medium ${s?"text-green-400":"text-yellow-400"}`,children:e(s?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")})]}),n.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[n.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.authLabel")}),n.jsx("span",{className:"text-xs text-text-primary",children:c!=null&&c.hasPasswordAuth?e("standalone.settings.authPassword"):c!=null&&c.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]}),(s==null?void 0:s.id)&&n.jsxs("div",{className:"px-1 pt-1 text-xs text-text-muted","data-testid":"standalone-providers-link",children:[e("standalone.settings.providersIntro")," ",n.jsx(dp,{to:`/machines/${s.id}`,state:{initialMachineTab:"providers"},className:"text-accent-primary hover:underline",children:e("standalone.settings.providersLink")})]})]})}),n.jsx(Nt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkHint"),children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsx("div",{className:"grid gap-3 md:grid-cols-2",role:"radiogroup","aria-label":e("standalone.settings.networkSection"),children:[{host:"127.0.0.1",label:e("standalone.settings.localhostLabel"),hint:e("standalone.settings.localhostHint")},{host:"0.0.0.0",label:e("standalone.settings.allInterfacesLabel"),hint:e("standalone.settings.allInterfacesHint")}].map(W=>n.jsxs("label",{className:`rounded-xl border px-4 py-3 text-sm flex gap-3 items-center cursor-pointer ${v===W.host?"border-accent-primary/40 bg-accent-primary/5":"border-border-subtle bg-bg-glass"}`,children:[n.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v===W.host,onChange:()=>C(W.host)}),n.jsx("span",{className:"font-medium text-text-primary",children:W.label}),n.jsx(dt,{content:W.hint})]},W.host))}),n.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[n.jsx(os,{type:"button",variant:"primary",size:"sm",onClick:()=>{D()},disabled:I,children:e(I?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),(u==null?void 0:u.standaloneBindHost)&&(u.currentBindHost||(c==null?void 0:c.boundHost))&&u.standaloneBindHost!==(u.currentBindHost||(c==null?void 0:c.boundHost))&&n.jsx(tn,{content:e("standalone.settings.networkRestartHint",{host:u.currentBindHost||(c==null?void 0:c.boundHost)||"127.0.0.1"}),children:n.jsx("span",{className:"inline-flex items-center rounded-full border border-amber-500/25 bg-amber-500/10 px-2 py-0.5 text-3xs font-semibold text-amber-400","data-testid":"standalone-restart-chip",children:e("standalone.settings.restartToApply")})})]})]})}),n.jsx(Nt,{title:e("standalone.settings.securitySection"),children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:c!=null&&c.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),L&&n.jsx(zt,{variant:"error",children:L}),F&&n.jsx(zt,{variant:"success",children:F}),n.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[n.jsx(Dn,{type:"password",placeholder:c!=null&&c.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:x,onChange:W=>S(W.target.value)}),n.jsx(Dn,{type:"password",placeholder:c!=null&&c.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:w,onChange:W=>_(W.target.value)}),n.jsx(Dn,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:A,onChange:W=>O(W.target.value)})]}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsx(os,{type:"button",variant:"primary",size:"sm",onClick:()=>{P()},disabled:I,children:I?e("standalone.settings.saving"):c!=null&&c.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(c==null?void 0:c.hasPasswordAuth)&&n.jsx(os,{type:"button",variant:"danger",size:"sm",onClick:()=>{$()},disabled:I,children:e("standalone.settings.disablePassword")})]})]})}),n.jsx(Nt,{title:e("standalone.settings.appearanceSection"),children:n.jsx(cT,{fontsSlot:n.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[n.jsxs("div",{className:"text-xs text-text-muted mb-2 font-medium flex items-center gap-1",children:[e("standalone.settings.fontsLabel"),n.jsx(dt,{content:e("standalone.settings.fontsDescription"),size:12})]}),n.jsx(t5,{value:h,savedValue:zn(u==null?void 0:u.standaloneFontPreferences),saving:g,error:y,notice:k,onChange:p,onSave:()=>{J()},onResetToSaved:K,onResetToDefaults:M})]})})}),n.jsx(Nt,{title:e("standalone.settings.profileSection"),children:n.jsx("div",{className:"flex flex-col gap-3",children:n.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[n.jsx("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:n.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[n.jsx(Yv,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel"),n.jsx(dt,{content:e("standalone.settings.displayNameHint")})]})}),n.jsx(Dn,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:a,onChange:W=>i(W.target.value),onBlur:q,onKeyDown:W=>{W.key==="Enter"&&W.currentTarget.blur()}})]})})}),n.jsxs(Nt,{title:e("settings.advancedTitle"),collapsible:!0,defaultOpen:!1,children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1 text-xs font-medium text-text-secondary",children:[e("settings.coordinatorPrompts.sectionTitle"),n.jsx(dt,{content:e("settings.coordinatorPrompts.sectionDescription"),size:12})]}),n.jsx(VA,{daemonId:s==null?void 0:s.id,embedded:!0})]})]})}const s5=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],po="adhdev_onboarding_done",r5=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],o5={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function a5({onDone:e}){const{t}=ve("common"),[s,r]=l.useState([]),[o,a]=l.useState(new Set(s5)),[i,c]=l.useState(!0),[d,u]=l.useState(null),[m,h]=l.useState(!1),[p,g]=l.useState(null),[f,y]=l.useState("all");l.useEffect(()=>{let S=!1;return fetch("/api/v1/providers/catalog?sort=popular&limit=100").then(async w=>{if(!w.ok)throw new Error(`HTTP ${w.status}`);const _=await w.text();try{return JSON.parse(_)}catch{throw new Error(`unexpected non-JSON response (${w.headers.get("content-type")??"unknown content type"})`)}}).then(w=>{S||r(w.providers??[])}).catch(w=>{S||u(w instanceof Error?w.message:String(w))}).finally(()=>{S||c(!1)}),()=>{S=!0}},[]);const b=s.filter(S=>f==="all"||S.category===f),k=["cli","ide","extension","acp"].map(S=>({category:S,items:b.filter(w=>w.category===S)})).filter(S=>S.items.length>0),j=l.useCallback(S=>{a(w=>{const _=new Set(w);return _.has(S)?_.delete(S):_.add(S),_})},[]),v=l.useCallback(async()=>{if(o.size===0){localStorage.setItem(po,"1"),e();return}h(!0);const S=[];for(const w of o)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:w})})).json().catch(()=>({}));S.push({type:w,ok:!!A.success,error:A.error})}catch(_){S.push({type:w,ok:!1,error:_ instanceof Error?_.message:String(_)})}g(S),h(!1),S.every(w=>w.ok)&&localStorage.setItem(po,"1")},[o,e]),C=l.useCallback(()=>{localStorage.setItem(po,"1"),e()},[e]),x=l.useCallback(()=>{p&&p.every(S=>S.ok)?e():m||C()},[p,m,e,C]);return n.jsx(Fg,{open:!0,onClose:x,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:n.jsxs("div",{className:"flex w-full items-center gap-2",children:[n.jsx("div",{className:"text-2xs text-text-muted",children:t(o.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:o.size})}),n.jsxs("div",{className:"ml-auto flex gap-2",children:[n.jsx(os,{variant:"secondary",size:"sm",onClick:C,disabled:m,children:t("standalone.onboarding.skip")}),n.jsx(os,{variant:"primary",size:"sm",onClick:()=>{p?(localStorage.setItem(po,"1"),e()):v()},disabled:m||!p&&o.size===0,children:m?t("standalone.onboarding.installing"):p?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:o.size})})]})]}),children:n.jsxs("div",{className:"flex flex-col gap-5",children:[n.jsx("div",{className:"text-xs text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&s.length>0&&n.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:r5.map(S=>{const w=S.key==="all"?s.length:s.filter(_=>_.category===S.key).length;return w===0&&S.key!=="all"?null:n.jsxs("button",{onClick:()=>y(S.key),className:`machine-btn text-3xs px-2 py-0.5 ${f===S.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[S.label," ",n.jsxs("span",{className:"opacity-60",children:["(",w,")"]})]},S.key)})}),i&&n.jsx("div",{className:"text-text-muted text-xs py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&n.jsx(zt,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&b.length===0&&n.jsx("div",{className:"text-text-muted text-xs py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&b.length>0&&n.jsx("div",{className:"flex flex-col gap-4",children:k.map(S=>n.jsxs("div",{children:[n.jsx("div",{className:"text-3xs font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:o5[S.category]??S.category}),n.jsx("div",{className:"grid gap-1.5",children:S.items.map(w=>{var L;const _=o.has(w.type),A=p==null?void 0:p.find(R=>R.type===w.type),O=((L=w.manifest)==null?void 0:L.details)??"";return n.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${_?"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:_,onChange:()=>j(w.type),disabled:m,className:"shrink-0"}),n.jsx(Li,{type:w.type,label:w.displayName??w.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:w.displayName}),O&&n.jsx("div",{className:"text-3xs text-text-muted truncate",children:O})]}),A&&n.jsx("span",{className:`text-3xs font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},w.type)})})]},S.category))})]})})}function i5(){try{return localStorage.getItem(po)==="1"}catch{return!1}}const l5="/dashboard";function c5(e,t){const s=typeof t=="string"?t.trim():"";return{suppressed:e.startsWith(l5),sessionId:s||null}}wA();nT();wf();VD();const d5=bw({baseUrl:"",getToken:Ui});function u5({children:e}){const{t}=ve("common"),[s,r]=l.useState(null),[o,a]=l.useState(!0),[i,c]=l.useState(""),[d,u]=l.useState(""),[m,h]=l.useState(!1),p=async()=>{a(!0),u("");try{const y=await(await qn("/auth/session")).json();r(y)}catch(f){u(f instanceof Error?f.message:String(f))}finally{a(!1)}};l.useEffect(()=>{p()},[]),l.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let f=!1;return(async()=>{try{const y=await qn("/api/v1/standalone/preferences");if(!y.ok)return;const b=await y.json();if(f)return;const k=zn(b.standaloneFontPreferences);Bs(k),Vc(k)}catch{}})(),()=>{f=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const g=async f=>{f.preventDefault(),h(!0),u("");try{const y=await qn("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),b=await y.json();if(!y.ok)throw new Error((b==null?void 0:b.error)||"Login failed");r(b),c(""),bx()}catch(y){u(y instanceof Error?y.message:String(y))}finally{h(!1)}};return o?n.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):s?!s.required||s.authenticated?n.jsx(n.Fragment,{children:e}):n.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:n.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),n.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),s.hasPasswordAuth?n.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[n.jsx(Dn,{type:"password",value:i,onChange:f=>c(f.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),n.jsx(os,{type:"submit",variant:"primary",disabled:m||!i,className:"justify-center",children:t(m?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):n.jsx(zt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&n.jsx(zt,{variant:"error",children:d})]})}):n.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function m5(){const{ides:e,initialLoaded:t}=An(),s=e.filter(r=>r.type==="adhdev-daemon").map(r=>({id:r.id,machineId:r.machineId||r.id,nickname:Nf(r)||void 0,hostname:fd(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(nP,{machines:s,initialLoaded:t??!0})}function lp(){const{t:e}=ve("common"),{ides:t,initialLoaded:s}=An();if(!s)return n.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(o=>o.daemonMode||o.type==="adhdev-daemon");return r?n.jsx(Vl,{to:`/machines/${r.id}`,replace:!0}):n.jsx(Vl,{to:"/dashboard",replace:!0})}function h5(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let s=!1;if(!i5())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{s||(r.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{s=!0}},[]),e?n.jsx(a5,{onDone:()=>t(!1)}):null}function p5(){const{t:e}=ve("common"),t=ui(),[s]=cp(),{suppressed:r,sessionId:o}=c5(t.pathname,s.get("activeTab")),{promptSession:a,hasActivePrompt:i,responseError:c,isSubmitting:d,submit:u,cancel:m,reopen:h}=ki(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(md,{promptSession:a,isSubmitting:d,error:c,onSubmit:u,onCancel:m})]})}function f5(){const e=l.useMemo(()=>({sendCommand:ko,sendData:Gc,sendPtyInput:Ax}),[]);return n.jsx(Bx,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:n.jsx(Uv,{client:d5,children:n.jsx(u5,{children:n.jsx(UD,{children:n.jsx(qv,{value:e,children:n.jsxs(gw,{sendDaemonCommand:ko,children:[n.jsx(p5,{}),n.jsxs(YD,{children:[n.jsx(h5,{}),n.jsxs(Wx,{children:[n.jsx(Un,{path:"/dashboard",element:n.jsx(TM,{})}),n.jsx(Un,{path:"/machine",element:n.jsx(lp,{})}),n.jsx(Un,{path:"/machines/:id",element:n.jsx(QR,{})}),n.jsx(Un,{path:"/machines",element:n.jsx(lp,{})}),n.jsx(Un,{path:"/notifications",element:n.jsx(m5,{})}),n.jsx(Un,{path:"/about",element:n.jsx(e5,{})}),n.jsx(Un,{path:"/settings",element:n.jsx(n5,{})}),n.jsx(Un,{path:"/mesh",element:n.jsx(GL,{children:n.jsx(qL,{})})}),n.jsx(Un,{path:"/setup",element:n.jsx(QD,{})}),n.jsx(Un,{path:"*",element:n.jsx(Vl,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Zj({connectionManager:Kn});function g5(){return n.jsx(dT,{fallback:n.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",background:"var(--bg-primary)"},children:n.jsx(ln,{})}),children:n.jsx(f5,{})})}Ux(document.getElementById("root")).render(n.jsx(OA,{children:n.jsx(g5,{})}));export{$5 as $,Vm as A,no as B,P5 as C,G5 as D,Fr as E,ud as F,HA as G,g0 as H,an as I,es as J,Ba as K,hx as L,Wi as M,_d as N,qA as O,Or as P,Bt as Q,y5 as R,E5 as S,tn as T,q5 as U,K5 as V,C5 as W,O5 as X,U5 as Y,k5 as Z,B5 as _,Ir as a,ct as a0,H5 as a1,$p as a2,w5 as a3,W5 as a4,F5 as a5,z5 as a6,A5 as a7,Od as a8,Lp as a9,Zv as aa,Gn as ab,Ad as ac,_t as ad,V5 as ae,dP as af,Po as ag,Rr as ah,Ot as ai,mi as aj,tx as ak,nx as al,cP as am,lP as an,nc as b,S5 as c,M5 as d,R5 as e,v1 as f,nu as g,v5 as h,xi as i,T5 as j,yi as k,N5 as l,dt as m,KA as n,j5 as o,Yl as p,Pr as q,Pg as r,I5 as s,_5 as t,Ho as u,Rd as v,L5 as w,sb as x,D5 as y,Md as z};
|