tide-commander 1.129.2 → 1.131.0

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.
Files changed (55) hide show
  1. package/dist/assets/{BossLogsModal-BMJsPBdB.js → BossLogsModal-CWI0TeXV.js} +1 -1
  2. package/dist/assets/{BossSpawnModal-DuDDNuE-.js → BossSpawnModal-CxiQJasU.js} +1 -1
  3. package/dist/assets/{ControlsModal-Cn3pkMIT.js → ControlsModal-BrPnWWpS.js} +1 -1
  4. package/dist/assets/{DockerLogsModal-D5XQ6zSr.js → DockerLogsModal-D1oIAzfZ.js} +1 -1
  5. package/dist/assets/{EmbeddedEditor-Ct4fmYRC.js → EmbeddedEditor-CHP_HStx.js} +1 -1
  6. package/dist/assets/{GmailOAuthSetup-Cfxh0FZm.js → GmailOAuthSetup-DCn-EXjO.js} +1 -1
  7. package/dist/assets/{GoogleOAuthSetup-Z-Yv0mbQ.js → GoogleOAuthSetup-D26zofAR.js} +1 -1
  8. package/dist/assets/{IframeModal-eyoeBSzE.js → IframeModal-CSN8ck7s.js} +1 -1
  9. package/dist/assets/{IntegrationsPanel-DzdEuC2w.js → IntegrationsPanel-BU_xwMMT.js} +2 -2
  10. package/dist/assets/{LogViewerModal-fhtTos_b.js → LogViewerModal-Amod9PlS.js} +1 -1
  11. package/dist/assets/{MonitoringModal-D_QNY_Zh.js → MonitoringModal-D-2zR9Oi.js} +1 -1
  12. package/dist/assets/{PM2LogsModal-DulkKfnA.js → PM2LogsModal-B48puyEY.js} +1 -1
  13. package/dist/assets/{RestoreArchivedAreaModal-BkpEL2dc.js → RestoreArchivedAreaModal-C4IVaTMA.js} +1 -1
  14. package/dist/assets/{Scene2DCanvas-C5E1mERA.js → Scene2DCanvas-BYdgkm1n.js} +1 -1
  15. package/dist/assets/{SceneManager-BA7KiD3q.js → SceneManager-DVL0xQVk.js} +1 -1
  16. package/dist/assets/{SkillsPanel-uotqhq5s.js → SkillsPanel-BwCe6nFB.js} +1 -1
  17. package/dist/assets/{SlackMultiInstanceSetup-B1QA0scY.js → SlackMultiInstanceSetup-nSiRoxLD.js} +1 -1
  18. package/dist/assets/{SpawnModal-B1d-vt6c.js → SpawnModal-DXvcL-cq.js} +1 -1
  19. package/dist/assets/{StatisticsModal-CpMdoPSG.js → StatisticsModal-Dgq-n8L6.js} +1 -1
  20. package/dist/assets/{SubordinateAssignmentModal-ALjpv2DP.js → SubordinateAssignmentModal-DflOgTr1.js} +1 -1
  21. package/dist/assets/{TriggerManagerPanel-rrDTH1Oq.js → TriggerManagerPanel-wzVna9Th.js} +1 -1
  22. package/dist/assets/{WorkflowEditorPanel-BcuM9e70.js → WorkflowEditorPanel-Cv1Bb_0g.js} +1 -1
  23. package/dist/assets/{area-logos-BkmhbXfG.js → area-logos-6NdoVnoc.js} +1 -1
  24. package/dist/assets/{index-CfEgfolW.js → index-1_kNHqvQ.js} +1 -1
  25. package/dist/assets/index-Bsf5hZbp.js +11 -0
  26. package/dist/assets/{index-DI7bDj0E.js → index-CoGlYrB7.js} +5 -5
  27. package/dist/assets/{index-BiXjxgpq.js → index-CqwyKXtm.js} +1 -1
  28. package/dist/assets/index-D8cfBFRC.js +2 -0
  29. package/dist/assets/{index-DMCGsQg5.js → index-DZcn4bXn.js} +1 -1
  30. package/dist/assets/{index-BNoB11BS.js → index-SaaO8V1I.js} +2 -2
  31. package/dist/assets/{index-BoN1bGyV.js → index-Tn-mXnAH.js} +3 -3
  32. package/dist/assets/{index-C9NJLW6A.js → index-sLCEQwTe.js} +3 -3
  33. package/dist/assets/main-BPim_cvM.css +1 -0
  34. package/dist/assets/{main-CEKV7I4r.js → main-DffU4pm2.js} +110 -110
  35. package/dist/assets/{web-DTb2MfHS.js → web-BzTFbp-p.js} +1 -1
  36. package/dist/assets/{web-CvCmCymz.js → web-CNVP9dOO.js} +1 -1
  37. package/dist/assets/{web-jSBoGXkW.js → web-SdWeOa6A.js} +1 -1
  38. package/dist/index.html +2 -2
  39. package/dist/locales/de/config.json +20 -13
  40. package/dist/locales/en/config.json +11 -6
  41. package/dist/locales/es/config.json +20 -13
  42. package/dist/locales/fr/config.json +20 -13
  43. package/dist/locales/hi/config.json +20 -13
  44. package/dist/locales/it/config.json +20 -13
  45. package/dist/locales/ja/config.json +20 -13
  46. package/dist/locales/pt/config.json +20 -13
  47. package/dist/locales/ru/config.json +20 -13
  48. package/dist/locales/zh-CN/config.json +20 -13
  49. package/dist/src/packages/server/claude/backend.js +10 -3
  50. package/dist/src/packages/server/claude/session-loader.js +56 -13
  51. package/dist/src/packages/server/codex/backend.js +6 -1
  52. package/package.json +1 -1
  53. package/dist/assets/index-ZQNyoovC.js +0 -2
  54. package/dist/assets/index-dfuoBomr.js +0 -11
  55. package/dist/assets/main-D086vUF0.css +0 -1
@@ -1428,6 +1428,58 @@ async function parseSessionMessages(resolved) {
1428
1428
  lastMessageTimestamp: last?.timestamp ? new Date(last.timestamp) : null,
1429
1429
  };
1430
1430
  }
1431
+ // Parsed-session cache keyed by file path, invalidated by (mtimeMs, size).
1432
+ // Every /history request previously re-parsed the full JSONL (and
1433
+ // getAgentHistory parses the SAME file twice when the page references
1434
+ // subagents) — with multi-MB sessions that parse dominated request latency.
1435
+ // Callers MUST treat the returned messages as immutable (all current callers
1436
+ // only read/slice them). Opencode sessions are excluded: their messages live
1437
+ // outside the resolved file (sqlite / part dirs), so a stat key on filePath
1438
+ // cannot see changes — and the sqlite path is cheap anyway.
1439
+ const parsedSessionCache = new Map();
1440
+ const PARSED_SESSION_CACHE_MAX = 8;
1441
+ // Only a file modified this recently may still be mid-write and warrant the
1442
+ // stability wait. The old unconditional waitForFileStable slept >=50ms on
1443
+ // EVERY request by construction (lastSize starts at -1, so the first check
1444
+ // can never match).
1445
+ const RECENT_WRITE_WINDOW_MS = 300;
1446
+ async function parseSessionMessagesCached(resolved) {
1447
+ if (resolved.provider === 'opencode') {
1448
+ return parseSessionMessages(resolved);
1449
+ }
1450
+ let stats;
1451
+ try {
1452
+ stats = fs.statSync(resolved.filePath);
1453
+ }
1454
+ catch {
1455
+ return parseSessionMessages(resolved);
1456
+ }
1457
+ const cached = parsedSessionCache.get(resolved.filePath);
1458
+ if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {
1459
+ // LRU touch: most recently used moves to the end of iteration order.
1460
+ parsedSessionCache.delete(resolved.filePath);
1461
+ parsedSessionCache.set(resolved.filePath, cached);
1462
+ return cached.parsed;
1463
+ }
1464
+ if (Date.now() - stats.mtimeMs < RECENT_WRITE_WINDOW_MS) {
1465
+ await waitForFileStable(resolved.filePath);
1466
+ try {
1467
+ stats = fs.statSync(resolved.filePath);
1468
+ }
1469
+ catch {
1470
+ return parseSessionMessages(resolved);
1471
+ }
1472
+ }
1473
+ const parsed = await parseSessionMessages(resolved);
1474
+ parsedSessionCache.set(resolved.filePath, { mtimeMs: stats.mtimeMs, size: stats.size, parsed });
1475
+ while (parsedSessionCache.size > PARSED_SESSION_CACHE_MAX) {
1476
+ const oldest = parsedSessionCache.keys().next().value;
1477
+ if (oldest === undefined)
1478
+ break;
1479
+ parsedSessionCache.delete(oldest);
1480
+ }
1481
+ return parsed;
1482
+ }
1431
1483
  /**
1432
1484
  * Load conversation history from a session file
1433
1485
  * @param cwd - Working directory
@@ -1441,10 +1493,7 @@ export async function loadSession(cwd, sessionId, limit = 50, offset = 0) {
1441
1493
  log.log(` Session file not found for session ${sessionId}`);
1442
1494
  return null;
1443
1495
  }
1444
- if (!resolved.opencodeDbSessionId) {
1445
- await waitForFileStable(resolved.filePath);
1446
- }
1447
- const { messages } = await parseSessionMessages(resolved);
1496
+ const { messages } = await parseSessionMessagesCached(resolved);
1448
1497
  const totalCount = messages.length;
1449
1498
  // Calculate slice indices from the end
1450
1499
  // offset 0, limit 50 -> slice(-50) = last 50 messages
@@ -1472,10 +1521,7 @@ export async function searchSession(cwd, sessionId, query, limit = 50) {
1472
1521
  if (!resolved) {
1473
1522
  return null;
1474
1523
  }
1475
- if (!resolved.opencodeDbSessionId) {
1476
- await waitForFileStable(resolved.filePath);
1477
- }
1478
- const { messages } = await parseSessionMessages(resolved);
1524
+ const { messages } = await parseSessionMessagesCached(resolved);
1479
1525
  const queryLower = query.toLowerCase();
1480
1526
  const matches = [];
1481
1527
  for (const message of messages) {
@@ -1614,7 +1660,7 @@ export async function getSessionActivityStatus(cwd, sessionId, activeThresholdSe
1614
1660
  const lastModified = await getResolvedSessionLastModified(resolved);
1615
1661
  const now = new Date();
1616
1662
  const secondsSinceModified = (now.getTime() - lastModified.getTime()) / 1000;
1617
- const { lastMessageType, lastMessageTimestamp } = await parseSessionMessages(resolved);
1663
+ const { lastMessageType, lastMessageTimestamp } = await parseSessionMessagesCached(resolved);
1618
1664
  // Determine if work is pending based on last message type:
1619
1665
  // - Last message was from user (Claude should be processing) OR
1620
1666
  // - Last message was tool_use (Claude is waiting for tool result) OR
@@ -1852,10 +1898,7 @@ export async function loadToolHistory(cwd, sessionId, agentId, agentName, limit
1852
1898
  if (!resolved) {
1853
1899
  return { toolExecutions, fileChanges };
1854
1900
  }
1855
- if (!resolved.opencodeDbSessionId) {
1856
- await waitForFileStable(resolved.filePath);
1857
- }
1858
- const { messages } = await parseSessionMessages(resolved);
1901
+ const { messages } = await parseSessionMessagesCached(resolved);
1859
1902
  for (const msg of messages) {
1860
1903
  if (msg.type !== 'tool_use' || !msg.toolName)
1861
1904
  continue;
@@ -3,7 +3,7 @@ import * as os from 'os';
3
3
  import * as path from 'path';
4
4
  import { CodexJsonEventParser } from './json-event-parser.js';
5
5
  import { TIDE_COMMANDER_APPENDED_PROMPT } from '../prompts/tide-commander.js';
6
- import { isEchoPromptEnabled, getCodexBinaryPath } from '../services/system-prompt-service.js';
6
+ import { isEchoPromptEnabled, getCodexBinaryPath, getSystemPrompt } from '../services/system-prompt-service.js';
7
7
  import { consumeInstructionsDirty, isBareSlashCommand } from '../services/instruction-refresh.js';
8
8
  import { loadAreas } from '../data/index.js';
9
9
  function shouldPassCodexModel(model) {
@@ -42,6 +42,11 @@ export function buildCodexPrompt(config) {
42
42
  return echoedUserPrompt;
43
43
  }
44
44
  const injectedSections = [];
45
+ // Global custom prompt — applies to every agent regardless of provider.
46
+ const systemLevelPrompt = getSystemPrompt().trim();
47
+ if (systemLevelPrompt) {
48
+ injectedSections.push(`## System-Level Custom Prompt\n${systemLevelPrompt}`);
49
+ }
45
50
  const customPrompt = config.customAgent?.definition?.prompt?.trim();
46
51
  if (customPrompt) {
47
52
  injectedSections.push(`## Agent Instructions\n${customPrompt}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tide-commander",
3
- "version": "1.129.2",
3
+ "version": "1.131.0",
4
4
  "description": "Visual multi-agent orchestrator and manager for Claude Code with 3D/2D interface",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,2 +0,0 @@
1
- import{r as a,B as pn,E as zt,G as qt,H as Yt,j as e,J as Kt,K as mn,u as Lt,L as fn,M as hn,N as gn,O as xn,V as bn,P as _n,U as wn,W as Ot,S,X as Bt,Y as Pt,Z as Ft,_ as mt,$ as oe,a0 as vn,s as _,a1 as Zt,a2 as Jt,a3 as Cn,w as Wt,x as Ht,I as p,a4 as jn,n as Nn,a5 as kn,a6 as Qt,a7 as en,a8 as yn,a9 as An,aa as Sn,ab as En,ac as Mn,ad as In,ae as Tn,af as Pn,ag as Ln,ah as Dn,ai as Rn,aj as $n,ak as Ut,C as zn,al as On,am as Bn,an as Fn,ao as Wn,ap as Hn,aq as Un,ar as Vn,as as Xn,at as Gn,au as qn,av as Yn,aw as Kn,ax as Zn,ay as Jn,az as Qn,aA as ea,aB as ta,aC as na,aD as aa}from"./main-CEKV7I4r.js";import{g as sa}from"./area-logos-BkmhbXfG.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function ia(u){const r=a.useRef(u);r.current=u,a.useEffect(()=>{if(!pn())return;let f=null,h=!1;return zt.addListener("backButton",()=>{r.current()==="exit"&&zt.exitApp()}).then(N=>{h?N.remove():f=N}),()=>{h=!0,f&&(f.remove(),f=null)}},[])}async function la(u){const r=qt(),f=await fetch(`${Yt()}/api/agents/${u}/terminal`,{method:"POST",headers:{Authorization:`Bearer ${r}`}});if(!f.ok){const h=await f.json().catch(()=>({}));throw new Error((h==null?void 0:h.error)||`Failed to start terminal (${f.status})`)}return f.json()}async function ra(u){const r=qt();await fetch(`${Yt()}/api/agents/${u}/terminal`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}const Ze=new Map;function oa({agentId:u}){const[r,f]=a.useState(null),[h,N]=a.useState(null);return a.useEffect(()=>{let L=!1;const M=Ze.get(u);return M&&(clearTimeout(M),Ze.delete(u)),f(null),N(null),la(u).then(R=>{L||f(R.url)}).catch(R=>{L||N(R instanceof Error?R.message:"Failed to start terminal")}),()=>{L=!0;const R=Ze.get(u);R&&clearTimeout(R),Ze.set(u,setTimeout(()=>{Ze.delete(u),ra(u)},2500))}},[u]),h?e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:h})}):r?e.jsx("div",{className:"flat-classic-terminal",children:e.jsx(Kt,{terminalUrl:r,visible:!0})}):e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:"Attaching to interactive session…"})})}const It=new Map,ca=6e4;function da({agentId:u,contextSummary:r}){const{t:f}=Lt(["terminal","common"]),[h,N]=a.useState(()=>{var I;return((I=It.get(u))==null?void 0:I.snapshot)??null}),[L,M]=a.useState(!1),[R,Z]=a.useState(null),w=a.useRef(0);a.useEffect(()=>{const I=It.get(u);if(I&&Date.now()-I.fetchedAt<ca){N(I.snapshot);return}const V=++w.current;M(!0),Z(null),fn(u).then(Y=>{V===w.current&&(It.set(u,{snapshot:Y,fetchedAt:Date.now()}),N(Y),M(!1))}).catch(Y=>{V===w.current&&(Z(Y.message||"Failed to load plan limits"),M(!1))})},[u]);const U=[];if(h!=null&&h.rateLimits){const I=[{key:"fiveHour",label:f("terminal:usage.currentSession"),window:h.rateLimits.fiveHour},{key:"sevenDay",label:f("terminal:usage.currentWeekAll"),window:h.rateLimits.sevenDay},{key:"sevenDayOpus",label:f("terminal:usage.currentWeekOpus"),window:h.rateLimits.sevenDayOpus},{key:"sevenDaySonnet",label:f("terminal:usage.currentWeekSonnet"),window:h.rateLimits.sevenDaySonnet}];for(const V of I)V.window&&U.push({...V,window:V.window})}return e.jsxs("div",{className:"plan-limits-tooltip",children:[r&&e.jsx("div",{className:"plan-limits-tooltip__context",children:r}),e.jsx("div",{className:"plan-limits-tooltip__title",children:f("terminal:usage.limits")}),L&&!h&&e.jsxs("div",{className:"plan-limits-tooltip__muted",children:[f("common:status.loading"),"…"]}),!L&&R&&!h&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:f("terminal:usage.limitsError",{message:R})}),U.length>0?e.jsx("div",{className:"plan-limits-tooltip__gauges",children:U.map(({key:I,label:V,window:Y})=>{const ce=Math.max(0,Math.min(100,Y.utilization)),te=gn(ce);return e.jsxs("div",{className:"plan-limits-tooltip__gauge",children:[e.jsxs("div",{className:"plan-limits-tooltip__gauge-head",children:[e.jsx("span",{className:"plan-limits-tooltip__gauge-label",children:V}),e.jsx("span",{className:"plan-limits-tooltip__gauge-percent",style:{color:te},children:f("terminal:usage.percentUsed",{percent:Math.round(ce)})})]}),e.jsx("div",{className:"plan-limits-tooltip__bar",children:e.jsx("div",{className:"plan-limits-tooltip__bar-fill",style:{width:`${ce}%`,background:te}})}),e.jsx("div",{className:"plan-limits-tooltip__reset",children:f("terminal:usage.resets",{time:hn(Y.resetsAt)})})]},I)})}):h&&!L&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:h.rateLimitsError?f("terminal:usage.limitsError",{message:h.rateLimitsError}):h.cliHint})]})}function ua({agentId:u,disabled:r,contextSummary:f,children:h}){return e.jsx(mn,{position:"top",maxWidth:320,disabled:r,className:"plan-limits-tooltip-wrapper",triggerStyle:{display:"inline-flex",alignItems:"center"},content:e.jsx(da,{agentId:u,contextSummary:f}),children:h})}const pa=a.memo(function({className:r=""}){const{t:f}=Lt(["common"]),[h,N]=xn(),L=a.useRef(null),[M,R]=a.useState(null);a.useLayoutEffect(()=>{const w=L.current;if(!w)return;const U=w.querySelector(".view-mode-toggle__btn--active");U&&R({left:U.offsetLeft,width:U.offsetWidth})},[h]);const Z=a.useCallback(w=>{if(w!==h){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:w}})),w==="3d"){requestAnimationFrame(()=>N(w));return}N(w)}},[h,N]);return e.jsxs("div",{className:`view-mode-toggle ${r}`,ref:L,children:[M&&e.jsx("div",{className:"view-mode-toggle__indicator",style:{left:M.left,width:M.width}}),bn.map(w=>e.jsxs("button",{className:`view-mode-toggle__btn ${h===w?"view-mode-toggle__btn--active":""}`,onClick:()=>Z(w),title:f(`common:viewMode.descriptions.${w}`),children:[e.jsxs("span",{className:"view-mode-toggle__icon",children:[w==="2d"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),e.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"})]}),w==="3d"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5z"}),e.jsx("path",{d:"M2 17l10 5 10-5"}),e.jsx("path",{d:"M2 12l10 5 10-5"})]}),w==="flat"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1"})]}),w==="dashboard"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"7",height:"9",rx:"1"}),e.jsx("rect",{x:"14",y:"3",width:"7",height:"5",rx:"1"}),e.jsx("rect",{x:"14",y:"12",width:"7",height:"9",rx:"1"}),e.jsx("rect",{x:"3",y:"16",width:"7",height:"5",rx:"1"})]})]}),e.jsx("span",{className:"view-mode-toggle__label",children:f(`common:viewMode.labels.${w}`)})]},w))]})}),ft=3,ht=280,Vt=320,Tt=240,Xt=64,ma=["simple","chat","advanced"],fa={simple:"Simple",chat:"Chat",advanced:"Advanced"},ha={simple:"○",chat:"◐",advanced:"◉"},ga={simple:"Simple view — clean messages only",chat:"Chat view — assistant replies (no tool calls)",advanced:"Advanced view — everything including tools"},Gt="flat-clear-context";function xa(u){const r=u.split("/").filter(Boolean);return r.length===0?u:r.slice(-2).join("/")}function ba(u){if(u.provider==="codex"){const L=u.codexModel||"gpt-5.3-codex",M=ta[L];return{model:(M==null?void 0:M.label)||L}}if(u.provider==="opencode")return{model:u.opencodeModel||"opencode"};const r=u.model||"sonnet",f=aa[r],h=u.effort,N=h?na[h]:void 0;return{model:(f==null?void 0:f.label)||r,effort:N==null?void 0:N.label}}function _a(u,r){if(r.type==="rectangle"&&r.width&&r.height){const f=r.width/2,h=r.height/2;return u.x>=r.center.x-f&&u.x<=r.center.x+f&&u.z>=r.center.z-h&&u.z<=r.center.z+h}if(r.type==="circle"&&r.radius){const f=u.x-r.center.x,h=u.z-r.center.z;return f*f+h*h<=r.radius*r.radius}return!1}const wa=On.memo(function({agentId:r,terminalViewMode:f,onTerminalViewModeChange:h,inspectorOpen:N,onToggleInspector:L,onImageClick:M,onFileClick:R,onBashClick:Z,onViewMarkdown:w,onRequestClearSubordinates:U,onOpenBuilding:I,keyboard:V,canNavigateBack:Y,canNavigateForward:ce,onNavigateBack:te,onNavigateForward:de,agentInfoOpen:we,onToggleAgentInfo:Je,onHeaderContextMenu:se,onBuildingContextMenu:ue}){var Ve,Ye,it,lt;const m=Bn(r),X=Jt(),pe=Fn(),ve=a.useRef(null),Le=a.useRef(null),me=!!pe.interactiveMode&&((m==null?void 0:m.provider)??"claude")==="claude"&&!!(m!=null&&m.sessionId),[ie,De]=a.useState(!1);a.useEffect(()=>{De(!1)},[r]),a.useEffect(()=>{!me&&ie&&De(!1)},[me,ie]),a.useEffect(()=>{const s=Le.current;if(!s)return;const l=d=>{d.button===3?(d.preventDefault(),d.stopPropagation(),te()):d.button===4&&(d.preventDefault(),d.stopPropagation(),de())},c=d=>{(d.button===3||d.button===4)&&d.preventDefault()};return s.addEventListener("mouseup",l),s.addEventListener("mousedown",c),()=>{s.removeEventListener("mouseup",l),s.removeEventListener("mousedown",c)}},[te,de]),a.useEffect(()=>{const s=Le.current;if(!s)return;let l=0,c=0,d=0;const _e=250,Ee=600,Me=80,yt=1.5,rt=T=>{let z=T instanceof HTMLElement?T:null;for(;z&&z!==s;){const Ie=window.getComputedStyle(z).overflowX;if((Ie==="auto"||Ie==="scroll")&&z.scrollWidth>z.clientWidth)return!0;z=z.parentElement}return!1},ot=T=>{const z=Date.now();if(z<d){T.preventDefault();return}if(Math.abs(T.deltaX)<=Math.abs(T.deltaY)*yt){l=0;return}if(rt(T.target)){l=0;return}z-c>_e&&(l=0),c=z,l+=T.deltaX,l<=-Me?(l=0,d=z+Ee,T.preventDefault(),te()):l>=Me&&(l=0,d=z+Ee,T.preventDefault(),de())};return s.addEventListener("wheel",ot,{passive:!1}),()=>s.removeEventListener("wheel",ot)},[te,de]);const Xe=Zt(),Re=a.useMemo(()=>{if(!m)return null;const s=new Set,l=[];for(const c of Xe.values())c.archived||c.directories.length===0||c.assignedAgentIds.includes(r)&&(s.add(c.id),l.push(c));for(const c of Xe.values())c.archived||c.directories.length===0||s.has(c.id)||_a({x:m.position.x,z:m.position.z},c)&&(s.add(c.id),l.push(c));return l.length===0?null:l.flatMap(c=>c.directories.filter(d=>d&&d.trim().length>0).map(d=>({areaId:c.id,areaName:c.name,dir:d})))},[m,r,Xe]),{branches:Qe,fetchRemote:Ce,fetchingDirs:fe}=Wn(Re),J=a.useMemo(()=>{var c;const s=_.getAreaForAgent(r);if(!s)return[];const l=[];for(const d of X.values())d.type==="terminal"&&_.isPositionInArea(d.position,s)&&l.push({id:d.id,name:d.name,hasUrl:!!((c=d.terminalStatus)!=null&&c.url)});return l},[r,X]),le=a.useMemo(()=>{var c;const s=_.getAreaForAgent(r);if(!s)return[];const l=[];for(const d of X.values())d.type==="server"&&((c=d.pm2)!=null&&c.enabled)&&_.isPositionInArea(d.position,s)&&l.push({id:d.id,name:d.name});return l},[r,X]),et=a.useMemo(()=>{const s=_.getAreaForAgent(r);if(!s)return[];const l=[];for(const c of X.values())c.type==="database"&&c.database&&_.isPositionInArea(c.position,s)&&l.push({id:c.id,name:c.name});return l},[r,X]),tt=Hn(),je=a.useMemo(()=>{const s=_.getAreaForAgent(r);if(!s)return[];const l=[];for(const c of X.values())if(c.type==="tests"&&_.isPositionInArea(c.position,s)){const d=!!c.folderPath&&tt.some(_e=>Un(_e,c.folderPath));l.push({id:c.id,name:c.name,working:d})}return l},[r,X,tt]),[,Ne]=a.useReducer(s=>s+1,0),ne=((Ve=ve.current)==null?void 0:Ve.search.searchMode)??!1,$e=a.useCallback(()=>{var s;(s=ve.current)==null||s.search.toggleSearch(),Ne()},[]),Q=Vn(),he=Q.isPending(Gt),[G,ee]=a.useState(null),ge=G?X.get(G):null,{height:gt,onResizeStart:nt}=Xn(),{sidePanelWidth:ze,handleSidePanelResizeStart:xt}=Gn(),[ke,xe]=a.useState(()=>Pt(S.GIT_PANEL_OPEN,!1)),[ye,Ge]=a.useState(()=>Pt(S.BUILDINGS_PANEL_OPEN,!1)),[Ae,Oe]=a.useState(!1),bt=a.useCallback(()=>{Oe(s=>{const l=!s;return l&&qn.setEnabled(!0),l})},[]),_t=a.useCallback(()=>Oe(!1),[]),wt=a.useCallback(()=>{xe(s=>{const l=!s;return oe(S.GIT_PANEL_OPEN,l),l})},[]),vt=a.useCallback(()=>{Ge(s=>{const l=!s;return oe(S.BUILDINGS_PANEL_OPEN,l),l})},[]),Ct=a.useCallback(()=>{xe(!1),oe(S.GIT_PANEL_OPEN,!1)},[]),jt=a.useCallback(()=>{Ge(!1),oe(S.BUILDINGS_PANEL_OPEN,!1)},[]),Be=Yn();a.useEffect(()=>{if(!G)return;J.some(l=>l.id===G)||ee(null)},[G,J]);const[b,B]=a.useState(!1),q=a.useRef(null);if(a.useEffect(()=>{if(!b)return;const s=l=>{q.current&&!q.current.contains(l.target)&&B(!1)};return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[b]),!m)return e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-chat__placeholder",children:[e.jsx("span",{className:"flat-chat__placeholder-icon",children:"💬"}),e.jsx("span",{className:"flat-chat__placeholder-text",children:"Select an agent to start chatting"})]})});const K=m.contextStats,Fe=!!K,at=K?K.totalTokens:m.contextUsed||0,st=K?K.contextWindow:m.contextLimit||2e5,Nt=K?K.usedPercent:Math.round(at/st*100),be=Math.max(0,Math.min(100,Nt)),We=Math.round(be*10)/10,Se=Math.round((100-be)*10)/10,He=be>=80?"#ff4a4a":be>=60?"#ff9e4a":be>=40?"#ffd700":"#4aff9e",ae=(at/1e3).toFixed(1),qe=(st/1e3).toFixed(1),D=m.cwd,re=D?xa(D):null,Ue=((Ye=m.subordinateIds)==null?void 0:Ye.length)||0,kt=Ue>0;return e.jsxs("div",{ref:Le,className:`flat-terminal-wrapper ${ke||ye||Ae?"flat-terminal-wrapper--with-side-panel":""}`,style:{"--guake-side-panel-width":`min(${ze}px, 70%)`},children:[e.jsxs("div",{className:"flat-terminal-wrapper__header",children:[e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__header-main ${we?"flat-terminal-wrapper__header-main--active":""}`,onClick:Je,onContextMenu:s=>{s.preventDefault(),s.stopPropagation(),se({x:s.clientX,y:s.clientY})},title:we?"Hide agent info":"Show agent info","aria-pressed":we,children:[e.jsx(Qt,{agent:m,size:28}),e.jsxs("span",{className:"flat-terminal-wrapper__header-info",children:[e.jsx("span",{className:"flat-terminal-wrapper__header-name",children:m.name}),e.jsx("span",{className:"flat-terminal-wrapper__header-status",style:{color:en(m.status)},children:m.status})]}),m.taskLabel&&e.jsxs("span",{className:"flat-terminal-wrapper__header-task",title:m.taskLabel,children:["📋 ",m.taskLabel]}),e.jsxs("span",{className:"flat-terminal-wrapper__header-model",children:[e.jsx("img",{src:m.provider==="codex"?"/assets/codex.png":m.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:m.provider,className:"flat-terminal-wrapper__header-provider-icon",title:m.provider==="codex"?"Codex Agent":m.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),(()=>{const{model:s,effort:l}=ba(m);return e.jsxs("span",{className:"flat-terminal-wrapper__header-model-chip",title:l?`Model: ${s} · Effort: ${l}`:`Model: ${s}`,children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-name",children:s}),l&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-sep","aria-hidden":"true",children:"·"}),e.jsx("span",{className:"flat-terminal-wrapper__header-model-effort",children:l})]})]})})()]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__header-meta",children:[e.jsxs("div",{className:"flat-terminal-wrapper__view-mode",role:"group","aria-label":"Message view mode",children:[ma.map(s=>e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${!ie&&f===s?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>{De(!1),h(s)},title:ga[s],"aria-pressed":!ie&&f===s,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:ha[s]}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:fa[s]})]},s)),me&&e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${ie?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>De(s=>!s),title:"Classic TUI — attach to the live interactive claude session in a terminal","aria-pressed":ie,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:e.jsx(p,{name:"terminal",size:13})}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:"Classic TUI"})]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__actions",role:"group","aria-label":"Terminal actions",children:[e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:te,disabled:!Y,title:"Back to previous agent","aria-label":"Back to previous agent",children:e.jsx(p,{name:"arrow-left",size:14})}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:de,disabled:!ce,title:"Forward to next agent","aria-label":"Forward to next agent",children:e.jsx(p,{name:"arrow-right",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ne?"flat-terminal-wrapper__action-btn--active":""}`,onClick:$e,title:ne?"Close search":"Search messages","aria-pressed":ne,children:e.jsx(p,{name:ne?"cross":"search",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn flat-terminal-wrapper__action-btn--danger ${he?"flat-terminal-wrapper__action-btn--confirm":""}`,onClick:()=>Q.handleClick(Gt,()=>{var s;_.clearContext(r),(s=ve.current)==null||s.historyLoader.clearHistory()}),title:he?"Click again to confirm clear context":"Clear context",children:e.jsx(p,{name:he?"question":"clear",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ke?"flat-terminal-wrapper__action-btn--active":""}`,onClick:wt,title:ke?"Hide git panel":"Show git changes","aria-pressed":ke,children:e.jsx(p,{name:"git-branch",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ye?"flat-terminal-wrapper__action-btn--active":""}`,onClick:vt,title:ye?"Hide buildings panel":"Show area buildings","aria-pressed":ye,children:e.jsx(p,{name:"buildings",size:14})}),e.jsxs("div",{className:"flat-terminal-wrapper__more",ref:q,children:[e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${b?"flat-terminal-wrapper__action-btn--active":""}`,onClick:()=>B(s=>!s),title:"More actions","aria-expanded":b,children:"⋮"}),b&&e.jsxs("div",{className:"flat-terminal-wrapper__more-menu",role:"menu",children:[e.jsxs("button",{type:"button",role:"menuitem",className:`flat-terminal-wrapper__more-item ${Ae?"flat-terminal-wrapper__more-item--active":""}`,onClick:()=>{bt(),B(!1)},title:Ae?"Hide Debug Panel":"Show Debug Panel",children:[e.jsx(p,{name:"bug",size:14}),e.jsx("span",{children:Ae?"Hide Debug Panel":"Show Debug Panel"})]}),e.jsx("div",{className:"flat-terminal-wrapper__more-divider"}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item",onClick:()=>{_.collapseContext(r),B(!1)},disabled:m.status!=="idle",title:m.status!=="idle"?"Agent must be idle to collapse context":"Collapse context",children:[e.jsx(p,{name:"package",size:14}),e.jsx("span",{children:"Collapse context"})]}),kt&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{U(r,Ue),B(!1)},children:[e.jsx(p,{name:"crown",size:14}),e.jsxs("span",{children:["Clear ",Ue," subordinate",Ue===1?"":"s"]})]}),e.jsx("div",{className:"flat-terminal-wrapper__more-divider"}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{_.killAgent(r),B(!1)},children:[e.jsx(p,{name:"cross",size:14}),e.jsx("span",{children:"Remove agent"})]})]})]})]}),e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__inspector-toggle ${N?"flat-terminal-wrapper__inspector-toggle--active":""}`,onClick:L,title:N?"Hide inspector panel":"Show inspector panel","aria-label":N?"Hide inspector panel":"Show inspector panel","aria-pressed":N,children:[e.jsx("span",{className:"flat-terminal-wrapper__inspector-icon","aria-hidden":"true",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"}),e.jsx("line",{x1:"10",y1:"2.5",x2:"10",y2:"13.5"})]})}),e.jsx("span",{className:"flat-terminal-wrapper__inspector-label",children:"Inspector"})]}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__close",onClick:()=>_.deselectAll(),title:"Close chat","aria-label":"Close chat",children:e.jsx(p,{name:"cross",size:14})})]})]}),ie&&me?e.jsx(oa,{agentId:r}):e.jsx(Kn,{ref:ve,agentId:r,agent:m,viewMode:f,isOpen:!0,onImageClick:M,onFileClick:R,onBashClick:Z,onViewMarkdown:w,keyboard:V,hasModalOpen:!1}),ge&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:nt,role:"separator","aria-orientation":"horizontal","aria-label":"Resize embedded terminal"}),e.jsxs("div",{className:"flat-bottom-panel",role:"region","aria-label":`Embedded terminal: ${ge.name}`,style:{height:gt},children:[e.jsxs("div",{className:"flat-bottom-panel__header",children:[e.jsxs("span",{className:"flat-bottom-panel__title",children:[e.jsx(p,{name:"terminal",size:12}),e.jsx("span",{children:ge.name}),!((it=ge.terminalStatus)!=null&&it.url)&&e.jsx("span",{className:"flat-bottom-panel__muted",children:"(starting...)"})]}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>ee(null),title:"Close embedded terminal","aria-label":"Close embedded terminal",children:e.jsx(p,{name:"cross",size:12})})]}),e.jsx("div",{className:"flat-bottom-panel__body",children:(lt=ge.terminalStatus)!=null&&lt.url?e.jsx(Kt,{terminalUrl:ge.terminalStatus.url,visible:!0}):e.jsx("div",{className:"flat-bottom-panel__placeholder",children:"Starting terminal..."})})]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__statusbar",role:"contentinfo",children:[m.isDetached&&e.jsxs("span",{className:"flat-terminal-wrapper__detached",title:"Reattaching session...",children:[e.jsx(p,{name:"refresh",size:12}),e.jsx("span",{children:"Reattaching"})]}),D&&re&&e.jsxs("span",{className:"flat-terminal-wrapper__cwd",title:`Open in file explorer: ${D}`,"aria-label":`Open ${D} in file explorer`,role:"button",tabIndex:0,onClick:()=>_.openFileExplorer(D),onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),_.openFileExplorer(D))},children:[e.jsx("span",{className:"flat-terminal-wrapper__cwd-icon",children:e.jsx(p,{name:"folder",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__cwd-text",children:re})]}),Re&&Re.map(({areaId:s,areaName:l,dir:c})=>{const d=Qe.get(c),_e=fe.has(c),Ee=c.split("/").filter(Boolean).pop()||c;return e.jsxs("span",{className:"flat-terminal-wrapper__area-dir",title:`${l}: ${c}${d?` (${d.branch}${d.ahead?` ↑${d.ahead}`:""}${d.behind?` ↓${d.behind}`:""})`:""}`,onClick:()=>_.openFileExplorerForAreaFolder(s,c),children:[e.jsx(p,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-terminal-wrapper__area-dir-name",children:Ee}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flat-terminal-wrapper__area-dir-branch",children:[e.jsx(p,{name:"git-branch",size:10})," ",d.branch]}),d.ahead>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-ahead",title:`${d.ahead} ahead`,children:[e.jsx(p,{name:"arrow-up",size:9}),d.ahead]}),d.behind>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-behind",title:`${d.behind} behind`,children:[e.jsx(p,{name:"arrow-down",size:9}),d.behind]}),e.jsx("span",{className:`flat-terminal-wrapper__area-fetch ${_e?"flat-terminal-wrapper__area-fetch--fetching":""}`,title:"Git fetch",onClick:Me=>{Me.stopPropagation(),Ce(c)},children:e.jsx(p,{name:_e?"hourglass":"download",size:12})})]})]},`${s}:${c}`)}),e.jsx(ua,{agentId:r,disabled:((m==null?void 0:m.provider)??"claude")!=="claude",contextSummary:Fe?`Context: ${ae}k / ${qe}k tokens (${We}% used)`:void 0,children:e.jsxs("span",{className:"flat-terminal-wrapper__context",tabIndex:0,role:"button",onClick:()=>_.setContextModalAgentId(r),onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),_.setContextModalAgentId(r))},title:((m==null?void 0:m.provider)??"claude")!=="claude"?Fe?`Context usage: ${ae}k / ${qe}k tokens (${We}% used). Click to view stats.`:"Click to fetch context stats":void 0,children:[e.jsx("span",{className:"flat-terminal-wrapper__context-icon",children:e.jsx(p,{name:"dashboard",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__context-label",children:"Ctx:"}),e.jsx("span",{className:"flat-terminal-wrapper__context-bar",children:e.jsx("span",{className:"flat-terminal-wrapper__context-bar-fill",style:{width:`${be}%`,backgroundColor:He}})}),e.jsxs("span",{className:"flat-terminal-wrapper__context-tokens",style:{color:He},children:[ae,"k/",qe,"k"]}),e.jsxs("span",{className:"flat-terminal-wrapper__context-free",children:["(",Se,"% free)"]}),!Fe&&e.jsx("span",{className:"flat-terminal-wrapper__context-warning",title:"No context stats yet",children:e.jsx(p,{name:"warn",size:12})})]})}),e.jsx("div",{className:"flat-terminal-wrapper__statusbar-spacer","aria-hidden":"true"}),J.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area terminals",children:J.map(s=>{const l=G===s.id;return e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${l?"flat-terminal-wrapper__building-btn--active":""} ${s.hasUrl?"":"flat-terminal-wrapper__building-btn--offline"}`,title:`${l?"Hide":"Show"} terminal: ${s.name}${s.hasUrl?"":" (starting...)"}`,onClick:()=>{if(l){ee(null);return}s.hasUrl||_.sendBuildingCommand(s.id,"start"),ee(s.id)},onContextMenu:c=>{c.preventDefault(),c.stopPropagation(),ue(s.id,{x:c.clientX,y:c.clientY})},children:e.jsx(p,{name:"terminal",size:14})},s.id)})}),le.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area PM2 logs",children:le.map(s=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open logs: ${s.name}`,onClick:()=>I(s.id),onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),ue(s.id,{x:l.clientX,y:l.clientY})},children:e.jsx(p,{name:"scroll",size:14})},s.id))}),et.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area databases",children:et.map(s=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open database: ${s.name}`,onClick:()=>I(s.id),onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),ue(s.id,{x:l.clientX,y:l.clientY})},children:e.jsx(p,{name:"hard-drives",size:14})},s.id))}),je.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area tests",children:je.map(s=>e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${s.working?"flat-terminal-wrapper__building-btn--tests-working":""}`,title:s.working?`Running tests: ${s.name}`:`Open tests: ${s.name}`,onClick:()=>I(s.id),onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),ue(s.id,{x:l.clientX,y:l.clientY})},children:e.jsx(p,{name:"flask",size:14})},s.id))}),e.jsx("div",{className:"flat-terminal-wrapper__theme",children:e.jsx(Zn,{})})]}),ke&&e.jsx(Jn,{agentId:r,agents:Be,onClose:Ct,branchInfoMap:Qe,fetchRemote:Ce,fetchingDirs:fe,onResizeStart:s=>xt(s,"right")}),ye&&e.jsx(Qn,{agentId:r,onClose:jt}),Ae&&e.jsx(ea,{agentId:r,onClose:_t})]})});function ka({onAgentClick:u,onBuildingClick:r,onBuildingDoubleClick:f,onBuildingPopup:h,onAreaContextMenu:N,onOpenSpawnModal:L,onOpenBossSpawnModal:M,onOpenAreaModal:R}){const{t:Z}=Lt(["common"]),w=_n(),U=wn(),[I,V]=a.useState(null),[Y,ce]=a.useState(null),[te,de]=a.useState(null),[we,Je]=a.useState(null),[se,ue]=a.useState(null),[m,X]=a.useState(null),[pe,ve]=a.useState(null),[Le,me]=a.useState(!1),ie=a.useCallback(()=>{me(t=>!t)},[]),De=a.useCallback(()=>{me(!1)},[]),[Xe,Re]=a.useState(()=>{const t=Ot(S.VIEW_MODE);return t==="simple"||t==="chat"||t==="advanced"?t:"simple"}),Qe=a.useCallback(t=>{Re(t),Bt(S.VIEW_MODE,t)},[]);a.useEffect(()=>{const t=n=>{if(n.key!==S.VIEW_MODE)return;const i=n.newValue;(i==="simple"||i==="chat"||i==="advanced")&&Re(i)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);const[Ce,fe]=a.useState(()=>Pt(S.FLAT_INSPECTOR_OPEN,!1)),[J,le]=a.useState(!1),et=a.useCallback(()=>le(t=>!t),[]),tt=a.useCallback(()=>le(!1),[]);a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-agents-drawer-state",{detail:{open:J}}))},[J]),a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-inspector-state",{detail:{open:Ce}}))},[Ce]),a.useEffect(()=>{const t=()=>le(C=>!C),n=()=>{fe(C=>{const k=!C;return oe(S.FLAT_INSPECTOR_OPEN,k),k})},i=()=>{le(!1),fe(!1),oe(S.FLAT_INSPECTOR_OPEN,!1)},g=()=>le(!1),x=()=>{fe(!1),oe(S.FLAT_INSPECTOR_OPEN,!1)};return window.addEventListener("tide-toggle-flat-agents-drawer",t),window.addEventListener("tide-toggle-flat-inspector",n),window.addEventListener("tide-close-flat-side-views",i),window.addEventListener("tide-close-flat-agents-drawer-only",g),window.addEventListener("tide-close-flat-inspector-only",x),()=>{window.removeEventListener("tide-toggle-flat-agents-drawer",t),window.removeEventListener("tide-toggle-flat-inspector",n),window.removeEventListener("tide-close-flat-side-views",i),window.removeEventListener("tide-close-flat-agents-drawer-only",g),window.removeEventListener("tide-close-flat-inspector-only",x)}},[]);const je=a.useRef(null),Ne=a.useRef(null),[ne,$e]=a.useState(()=>{const t=Ft(S.FLAT_MIDDLE_WIDTH,0);return t>=ht?t:null}),[Q,he]=a.useState(()=>{const t=Ft(S.FLAT_INSPECTOR_WIDTH,0);return t>=Tt?t:null}),G=a.useCallback(t=>{if(typeof window>"u")return t;const n=Q!==null?ft+Q:0,i=window.innerWidth-Xt-ft-Vt-n;return Math.max(ht,Math.min(Math.max(i,ht),t))},[Q]),ee=a.useCallback(t=>{var x;if(typeof window>"u")return t;const n=(x=je.current)==null?void 0:x.querySelector(".flat-middle"),i=(n==null?void 0:n.getBoundingClientRect().width)??ht,g=window.innerWidth-Xt-i-ft-Vt-ft;return Math.max(Tt,Math.min(Math.max(g,Tt),t))},[]);a.useEffect(()=>{if(ne===null&&Q===null)return;const t=()=>{$e(n=>{if(n===null)return n;const i=G(n);return i===n?n:i}),he(n=>{if(n===null)return n;const i=ee(n);return i===n?n:i})};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[ne,Q,G,ee]);const ge=a.useCallback(t=>{var i;if(t.button!==0)return;const n=(i=je.current)==null?void 0:i.querySelector(".flat-middle");n&&(t.currentTarget.setPointerCapture(t.pointerId),Ne.current={kind:"middle",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),gt=a.useCallback(t=>{var i;if(t.button!==0)return;const n=(i=je.current)==null?void 0:i.querySelector(".flat-inspector");n&&(t.currentTarget.setPointerCapture(t.pointerId),Ne.current={kind:"inspector",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),nt=a.useCallback(t=>{const n=Ne.current;if(!n||t.pointerId!==n.pointerId)return;const i=t.clientX-n.startX;n.kind==="middle"?$e(G(n.startWidth+i)):he(ee(n.startWidth-i))},[G,ee]),ze=a.useCallback(t=>{const n=Ne.current;if(!n||t.pointerId!==n.pointerId)return;try{t.currentTarget.releasePointerCapture(t.pointerId)}catch{}if(Ne.current=null,document.body.classList.remove("flat-splitter-dragging"),!(Math.abs(t.clientX-n.startX)>2))return;const g=t.clientX-n.startX;if(n.kind==="middle"){const x=G(n.startWidth+g);$e(x),mt(S.FLAT_MIDDLE_WIDTH,x)}else{const x=ee(n.startWidth-g);he(x),mt(S.FLAT_INSPECTOR_WIDTH,x)}},[G,ee]),xt=a.useCallback(()=>{$e(null),mt(S.FLAT_MIDDLE_WIDTH,0)},[]),ke=a.useCallback(()=>{he(null),mt(S.FLAT_INSPECTOR_WIDTH,0)},[]),[xe,ye]=a.useState(()=>Ot(S.FLAT_INSPECTOR_VIEW)==="tracking"?"tracking":"agent"),Ge=a.useCallback(t=>{ye(t),Bt(S.FLAT_INSPECTOR_VIEW,t)},[]),Ae=a.useCallback(()=>{fe(t=>{const n=!t;return oe(S.FLAT_INSPECTOR_OPEN,n),n})},[]),Oe=a.useCallback(()=>{fe(!1),oe(S.FLAT_INSPECTOR_OPEN,!1)},[]),bt=vn(),_t=a.useCallback((t,n)=>{V({url:t,name:n})},[]),wt=a.useCallback((t,n)=>{ce({command:t,output:n,isLive:!1})},[]),vt=a.useCallback((t,n)=>{_.setFileViewerPath(t,n)},[]),Ct=a.useCallback(t=>{de(t)},[]),jt=a.useCallback((t,n)=>{Je({agentId:t,count:n})},[]),Be=a.useCallback(t=>{f?f(t):r(t)},[r,f]),b=a.useMemo(()=>U.size>0?Array.from(U)[0]:null,[U]);a.useEffect(()=>{me(!1)},[b]);const B=a.useRef([]),q=a.useRef(-1),K=a.useRef(!1),Fe=a.useRef(null),[at,st]=a.useState(!1),[Nt,be]=a.useState(!1),We=a.useRef(!1),Se=a.useRef(null),He=a.useRef(!1),ae=a.useMemo(()=>new Set(w.map(t=>t.id)),[w]),qe=a.useMemo(()=>{const t=new Map(w.map(i=>[i.id,i])),n=new Map;for(const i of w)if((i.isBoss||i.class==="boss")&&i.subordinateIds&&i.subordinateIds.length>0){const g=i.subordinateIds.map(x=>t.get(x)).filter(x=>x!==void 0);g.length>0&&n.set(i.id,g)}return n},[w]),D=a.useCallback(()=>{const t=B.current,n=q.current;st(n>0),be(n>=0&&n<t.length-1)},[]),re=a.useCallback(t=>{const n=B.current;if(n.length===0)return;let i=q.current+t;for(;i>=0&&i<n.length;){const g=n[i];if(ae.has(g)){K.current=!0,q.current=i,D(),_.selectAgent(g);return}i+=t}},[ae,D]),Ue=a.useCallback(()=>re(-1),[re]),kt=a.useCallback(()=>re(1),[re]);ia(a.useCallback(()=>{const t=B.current,n=q.current;return t.length>0&&n>0?(re(-1),"handled"):"exit"},[re]));const Ve=a.useCallback((t,n)=>{if(typeof window>"u")return;const i=window.history.state,x={...typeof i=="object"&&i!==null?i:{},__flatAgentNav:{agentId:t}};n==="replace"?window.history.replaceState(x,"",window.location.href):window.history.pushState(x,"",window.location.href)},[]);a.useEffect(()=>{if(!b){We.current=!1,Se.current=null;return}if(!We.current){Ve(b,"replace"),We.current=!0,Se.current=b;return}if(He.current){He.current=!1,Se.current=b;return}Se.current!==b&&(Ve(b,"push"),Se.current=b)},[b,Ve]),a.useEffect(()=>{const t=n=>{var C,k;const i=(k=(C=n.state)==null?void 0:C.__flatAgentNav)==null?void 0:k.agentId;if(!i||typeof i!="string"||!ae.has(i)||i===b)return;He.current=!0,K.current=!0;const g=B.current,x=g.lastIndexOf(i);x>=0?q.current=x:(g.push(i),q.current=g.length-1),D(),_.selectAgent(i)};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[ae,b,D]),a.useEffect(()=>{if(!b){B.current=[],q.current=-1,D();return}if(Fe.current=b,K.current){K.current=!1,D();return}const t=B.current,n=q.current;if(n>=0&&t[n]===b){D();return}const i=n<t.length-1?t.slice(0,n+1):t.slice();i.push(b),i.length>100&&i.shift(),B.current=i,q.current=i.length-1,D()},[b,D]);const Ye=a.useCallback(t=>{u(t),le(!1)},[u]),it=b??"",lt=a.useCallback(()=>{},[]),s=a.useCallback(t=>{Ye(t)},[Ye]),l=Ce,[c,d]=a.useState(l),[_e,Ee]=a.useState(l);a.useEffect(()=>{if(l){d(!0);return}Ee(!1);const t=setTimeout(()=>d(!1),240);return()=>clearTimeout(t)},[l]),a.useEffect(()=>{if(!c||!l)return;let t=0;const n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>Ee(!0))});return()=>{cancelAnimationFrame(n),cancelAnimationFrame(t)}},[c,l]);const Me=a.useRef(null);a.useEffect(()=>{if(b)return;const t=n=>{if(n.key!==" "&&n.key!=="Backspace")return;const i=n.target;if(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.isContentEditable)return;const g=Fe.current;!g||!ae.has(g)||(n.preventDefault(),_.selectAgent(g))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[b,ae]);const[yt,rt]=a.useState(new Set),ot=a.useCallback(t=>{rt(n=>{const i=new Set(n);return i.has(t)?i.delete(t):i.add(t),i})},[]),[T,z]=a.useState(()=>typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches);a.useEffect(()=>{if(typeof window>"u")return;const t=window.matchMedia("(max-width: 768px)"),n=i=>z(i.matches);return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[]);const[Ie,tn]=a.useState(null),nn=a.useCallback(t=>{tn(n=>n===t?null:t)},[]),At=Zt(),ct=Jt(),[an]=Cn(),Te=a.useMemo(()=>{const t=new Map,n=[];for(const v of w){const A=_.getAreaForAgent(v.id);if(!Wt((A==null?void 0:A.id)??null))continue;if(!A||A.archived){n.push(v);continue}const E=t.get(A.id);E?E.push(v):t.set(A.id,[v])}const i=new Map,g=[];for(const v of ct.values()){let A=!1;for(const E of At.values())if(!E.archived&&Ht(E.id)&&_.isPositionInArea(v.position,E)){const F=i.get(E.id);F?F.push(v):i.set(E.id,[v]),A=!0;break}!A&&Wt(null)&&g.push(v)}const x=[];for(const[,v]of At){if(v.archived||!Ht(v.id))continue;const A=t.get(v.id),E=i.get(v.id)??[];(A&&A.length>0||E.length>0)&&x.push({area:v,agents:A??[],buildings:E})}(n.length>0||g.length>0)&&x.push({area:{id:"__unassigned__",name:"Unassigned",color:"#6272a4",center:{x:0,z:0},type:"circle",radius:0,directories:[],archived:!1,assignedAgentIds:[],zIndex:0},agents:n,buildings:g});const C=x.filter(v=>v.area.id!=="__unassigned__"),k=x.filter(v=>v.area.id==="__unassigned__");let o=1,y=1;const O=new Map;if(C.length>1){let v=1/0,A=-1/0,E=1/0,F=-1/0;for(const W of C)v=Math.min(v,W.area.center.x),A=Math.max(A,W.area.center.x),E=Math.min(E,W.area.center.z),F=Math.max(F,W.area.center.z);const dt=A-v||1,ut=F-E||1;if(C.length<=4){o=C.length,y=1;const W=[...C].sort((H,St)=>H.area.center.x-St.area.center.x);for(let H=0;H<W.length;H++)O.set(W[H].area.id,{row:1,col:H+1})}else{const W=[...C].sort((j,$)=>j.area.center.x-$.area.center.x),H=[];for(let j=1;j<W.length;j++)H.push(W[j].area.center.x-W[j-1].area.center.x);const St=H.reduce((j,$)=>j+$,0)/H.length||1;let Dt=1;for(const j of H)j>St*1.3&&Dt++;o=Math.max(2,Math.min(Dt,C.length));const Et=[...C].sort((j,$)=>j.area.center.z-$.area.center.z),pt=[];for(let j=1;j<Et.length;j++)pt.push(Et[j].area.center.z-Et[j-1].area.center.z);const on=pt.reduce((j,$)=>j+$,0)/pt.length||1;let Rt=1;for(const j of pt)j>on*1.3&&Rt++;y=Math.max(2,Math.min(Rt,C.length)),o=Math.max(o,Math.ceil(C.length/y)),y=Math.max(y,Math.ceil(C.length/o));const cn=dt/o,dn=ut/y,Mt=new Set;for(const j of C){let $=Math.min(o-1,Math.max(0,Math.floor((j.area.center.x-v)/cn))),Pe=Math.min(y-1,Math.max(0,Math.floor((j.area.center.z-E)/dn))),Ke=`${Pe},${$}`,$t=0;const un=y*o;for(;Mt.has(Ke)&&$t<un;)$++,$>=o&&($=0,Pe=(Pe+1)%y),Ke=`${Pe},${$}`,$t++;Mt.has(Ke)&&(Pe=y,$=0,Ke=`${Pe},${$}`,y++),Mt.add(Ke),O.set(j.area.id,{row:Pe+1,col:$+1})}}}const P=v=>{v.sort((A,E)=>{var dt,ut,W,H;const F=(((dt=A.position)==null?void 0:dt.z)??0)-(((ut=E.position)==null?void 0:ut.z)??0);return F!==0?F:(((W=A.position)==null?void 0:W.x)??0)-(((H=E.position)==null?void 0:H.x)??0)})};for(const v of C)P(v.agents);for(const v of k)P(v.agents);return{groups:[...C,...k],gridCols:o,gridRows:y,positions:O}},[w,At,ct,an]),sn=a.useMemo(()=>{if(!se)return[];const t=w.find(n=>n.id===se.agentId);return t?[{id:"edit-agent",label:"Edit Agent",icon:e.jsx(p,{name:"edit",size:14}),onClick:()=>{window.dispatchEvent(new CustomEvent("tide:open-agent-edit",{detail:{agentId:t.id}}))}},{id:"open-chat",label:"Open Chat",icon:e.jsx(p,{name:"chat",size:14}),onClick:()=>u(t.id)},{id:"clone-agent",label:"Clone Agent",icon:e.jsx(p,{name:"clipboard",size:14}),onClick:()=>_.cloneAgent(t.id)},{id:"fork-agent",label:"Fork Agent (with history)",icon:e.jsx(p,{name:"git-branch",size:14}),onClick:()=>_.forkAgent(t.id)},{id:"delete-agent",label:"Delete Agent",icon:e.jsx(p,{name:"trash",size:14}),danger:!0,onClick:()=>{ve({agentId:t.id,name:t.name})}}]:[]},[se,w,u]),ln=a.useMemo(()=>{var C;if(!m)return[];const t=ct.get(m.buildingId);if(!t)return[];const n=[],i=t.type==="server"||t.type==="docker"||t.type==="terminal",g=t.status==="running",x=t.type==="boss";if(n.push({id:"open",label:t.type==="database"?"Open Database":t.type==="folder"?"Open Folder":t.type==="tests"?"Open Tests":t.type==="boss"?"View Boss Logs":t.type==="terminal"?"Open Terminal":t.type==="server"&&((C=t.pm2)!=null&&C.enabled)?"View PM2 Logs":"Open",icon:e.jsx(p,{name:t.type==="database"?"database":t.type==="folder"?"folder":t.type==="tests"?"flask":t.type==="terminal"?"terminal":"eye",size:14}),onClick:()=>Be(t.id)}),i&&(g||n.push({id:"start",label:"Start",icon:e.jsx(p,{name:"play",size:14}),onClick:()=>_.sendBuildingCommand(t.id,"start")}),g&&(n.push({id:"restart",label:"Restart",icon:e.jsx(p,{name:"refresh",size:14}),onClick:()=>_.sendBuildingCommand(t.id,"restart")}),n.push({id:"stop",label:"Stop",icon:e.jsx(p,{name:"stop",size:14}),onClick:()=>_.sendBuildingCommand(t.id,"stop")}))),x&&t.subordinateBuildingIds&&t.subordinateBuildingIds.length>0&&(n.push({id:"start-all",label:"Start All Subordinates",icon:e.jsx(p,{name:"launch",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)_.sendBuildingCommand(k,"start")}}),n.push({id:"stop-all",label:"Stop All Subordinates",icon:e.jsx(p,{name:"pause",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)_.sendBuildingCommand(k,"stop")}}),n.push({id:"restart-all",label:"Restart All Subordinates",icon:e.jsx(p,{name:"restart",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)_.sendBuildingCommand(k,"restart")}})),i&&n.push({id:"health-check",label:"Health Check",icon:e.jsx(p,{name:"health",size:14}),onClick:()=>_.sendBuildingCommand(t.id,"healthCheck")}),n.push({id:"divider-edit",label:"",divider:!0,onClick:()=>{}}),n.push({id:"edit",label:"Edit Building",icon:e.jsx(p,{name:"edit",size:14}),onClick:()=>{window.dispatchEvent(new CustomEvent("tide:building-edit",{detail:{buildingId:t.id}}))}}),n.push({id:"clone",label:"Clone Building",icon:e.jsx(p,{name:"copy",size:14}),onClick:()=>{_.createBuilding({name:`${t.name} (Copy)`,type:t.type,style:t.style,color:t.color,scale:t.scale,position:{x:t.position.x+2,z:t.position.z+2},cwd:t.cwd,folderPath:t.folderPath,commands:t.commands,pm2:t.pm2,docker:t.docker,database:t.database,terminal:t.terminal,urls:t.urls,subordinateBuildingIds:t.subordinateBuildingIds})}}),t.urls&&t.urls.length>0)for(const k of t.urls)n.push({id:`url-${k.label}`,label:k.label,icon:e.jsx(p,{name:"link",size:14}),onClick:()=>window.open(k.url,"_blank","noopener,noreferrer")});return n.push({id:"divider-danger",label:"",divider:!0,onClick:()=>{}}),n.push({id:"delete",label:"Delete Building",icon:e.jsx(p,{name:"trash",size:14}),danger:!0,onClick:()=>_.deleteBuilding(t.id)}),n},[m,ct,Be]),rn=a.useCallback(t=>{const n=new Set(Te.groups.map(i=>i.area.id));n.delete(t),rt(n),requestAnimationFrame(()=>{const i=Me.current;if(!i)return;const g=i.querySelector(`[data-area-id="${t}"]`);if(!g)return;const x=i.getBoundingClientRect(),k=g.getBoundingClientRect().top-x.top+i.scrollTop-8;i.scrollTo({top:Math.max(0,k),behavior:"smooth"})})},[Te]);return e.jsxs("div",{ref:je,className:`flat-view ${l?"flat-view--with-inspector":""} ${b?"flat-view--has-chat":""} ${J?"flat-view--mobile-sidebar-open":""}`,style:(()=>{if(ne===null&&Q===null)return;const t={};return ne!==null&&(t["--flat-middle-width"]=`${ne}px`),Q!==null&&(t["--flat-inspector-width"]=`${Q}px`),t})(),children:[J&&e.jsx("div",{className:"flat-mobile-sidebar-backdrop",onClick:tt,"aria-hidden":"true"}),e.jsxs("div",{className:"flat-middle",children:[e.jsx("div",{className:"flat-middle__header",children:e.jsxs("div",{className:"flat-middle__actions",children:[e.jsx("button",{className:"flat-cta-btn flat-cta-btn--agent",onClick:L,title:"Create new agent",children:"+ Agent"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--boss",onClick:M,title:"Create new boss agent",children:"+ Boss"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--area",onClick:R,title:"Create new area",children:"+ Area"})]})}),e.jsx("div",{className:"flat-middle__content",children:e.jsx(jn,{activeAgentId:it,onClose:lt,onSelectAgent:s,collapsedAreas:yt,onToggleArea:ot,agentListRef:Me})})]}),e.jsx("div",{className:"flat-splitter flat-splitter--middle",role:"separator","aria-orientation":"vertical","aria-label":"Resize agents panel",title:"Drag to resize · Double-click to reset",onPointerDown:ge,onPointerMove:nt,onPointerUp:ze,onPointerCancel:ze,onDoubleClick:xt}),e.jsxs("div",{className:"flat-right",children:[e.jsxs("button",{type:"button",className:"flat-mobile-sidebar-toggle","aria-label":J?"Close agents sidebar":"Open agents sidebar","aria-expanded":J,onClick:et,children:[e.jsx(p,{name:"list",size:18}),e.jsx("span",{className:"flat-mobile-sidebar-toggle__label",children:"Agents"})]}),b?e.jsx(wa,{agentId:b,terminalViewMode:Xe,onTerminalViewModeChange:Qe,inspectorOpen:Ce,onToggleInspector:Ae,onImageClick:_t,onFileClick:vt,onBashClick:wt,onViewMarkdown:Ct,onRequestClearSubordinates:jt,onOpenBuilding:Be,keyboard:bt,canNavigateBack:at,canNavigateForward:Nt,onNavigateBack:Ue,onNavigateForward:kt,agentInfoOpen:Le,onToggleAgentInfo:ie,onHeaderContextMenu:t=>{b&&ue({agentId:b,position:t})},onBuildingContextMenu:(t,n)=>{X({buildingId:t,position:n})}}):e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-map",children:[e.jsxs("div",{className:"flat-map__header",children:[e.jsx("span",{className:"flat-map__title",children:"🗺️ Areas"}),e.jsx("span",{className:"flat-map__hint",children:"Click an area to focus it, or an agent to chat"}),e.jsx(pa,{className:"flat-map__view-mode"})]}),e.jsx("div",{className:"flat-map__grid",style:{gridTemplateColumns:`repeat(${Te.gridCols}, 1fr)`},children:Te.groups.length===0?e.jsx("div",{className:"flat-map__empty",children:e.jsx("span",{children:"No areas or agents yet"})}):(()=>{var n;const t=T&&Ie?((n=Te.positions.get(Ie))==null?void 0:n.row)??null:null;return Te.groups.map(i=>{var k;const g=i.area.id,x=Te.positions.get(g),C=T&&Ie!==g;return T&&t!=null&&(x==null?void 0:x.row)===t&&g!==Ie?null:e.jsxs("div",{className:`flat-map-area-card${C?" flat-map-area-card--collapsed":""}`,style:{"--area-color":i.area.color,gridRow:x==null?void 0:x.row,gridColumn:x==null?void 0:x.col},onContextMenu:o=>{N&&(o.preventDefault(),o.stopPropagation(),N(g,{x:o.clientX,y:o.clientY}))},children:[((k=i.area.logo)==null?void 0:k.filename)&&e.jsx("img",{className:"flat-map-area-card__logo",src:sa(i.area.logo.filename),alt:"","aria-hidden":"true",onError:o=>{o.currentTarget.style.display="none"}}),e.jsxs("button",{type:"button",className:"flat-map-area-card__header",onClick:()=>T?nn(g):rn(g),title:T?C?`Expand ${i.area.name}`:`Collapse ${i.area.name}`:`Focus ${i.area.name} in left panel`,"aria-expanded":T?!C:void 0,children:[e.jsx("span",{className:"flat-map-area-card__color",style:{background:i.area.color}}),e.jsx("span",{className:"flat-map-area-card__name",children:i.area.name}),e.jsx("span",{className:"flat-map-area-card__count",children:i.agents.length}),T&&e.jsx(p,{name:C?"caret-down":"caret-up",size:11,className:"flat-map-area-card__caret"})]}),e.jsx("div",{className:"flat-map-area-card__agents",children:i.agents.map(o=>{const y=o.isBoss||o.class==="boss",O=y?qe.get(o.id):void 0,P=Nn(o),v=P.usedPercent>=80?"#ff4a4a":P.usedPercent>=60?"#ff9e4a":P.usedPercent>=40?"#ffd700":"#4aff9e",A=`Context: ${(P.totalTokens/1e3).toFixed(1)}k / ${(P.contextWindow/1e3).toFixed(1)}k (${P.usedPercent}% used, ${P.freePercent}% free)`,E=o.latestTodos&&o.latestTodos.length>0||O&&O.length>0;return e.jsx(kn,{todos:o.latestTodos,subordinates:O,position:"top",children:e.jsxs("button",{type:"button",className:`flat-map-agent-chip ${o.status}`,onClick:()=>u(o.id),onContextMenu:F=>{F.preventDefault(),F.stopPropagation(),ue({agentId:o.id,position:{x:F.clientX,y:F.clientY}})},title:E?void 0:`${y?"Boss · ":""}Open chat with ${o.name}
2
- ${A}`,children:[e.jsx(Qt,{agent:o,size:16}),y&&e.jsx("span",{className:"flat-map-agent-chip__crown","aria-hidden":"true",children:e.jsx(p,{name:"crown",size:11,color:"#ffd700",weight:"fill"})}),e.jsx("span",{className:"flat-map-agent-chip__name",children:o.name}),e.jsx("img",{src:o.provider==="codex"?"/assets/codex.png":o.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:o.provider,className:"flat-map-agent-chip__provider-icon",title:o.provider==="codex"?"Codex Agent":o.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),e.jsx("span",{className:"flat-map-agent-chip__dot",style:{backgroundColor:en(o.status)}}),o.latestTodos&&o.latestTodos.length>0&&e.jsx(yn,{todos:o.latestTodos,maxDots:6}),y&&O&&O.length>0&&e.jsx(An,{subordinates:O,maxDots:6}),e.jsx("span",{className:"flat-map-agent-chip__context-bar","aria-hidden":"true",children:e.jsx("span",{className:"flat-map-agent-chip__context-bar-fill",style:{width:`${P.usedPercent}%`,backgroundColor:v}})})]})},o.id)})}),i.area.directories.length>0&&e.jsx("div",{className:"flat-map-area-card__folders",role:"group","aria-label":`${i.area.name} folders`,children:i.area.directories.map(o=>{const y=o.split("/").filter(Boolean).pop()||o;return e.jsxs("button",{type:"button",className:"flat-map-folder-chip",onClick:O=>{O.stopPropagation(),_.openFileExplorerForAreaFolder(g,o)},title:`Open in file explorer: ${o}`,children:[e.jsx(p,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-map-folder-chip__name",children:y})]},o)})}),i.buildings.length>0&&e.jsx("div",{className:"flat-map-area-card__buildings",children:i.buildings.map(o=>{var O;const y=(O=Sn[o.type])==null?void 0:O.color;return e.jsxs("button",{type:"button",className:`flat-map-building-chip flat-map-building-chip--${o.status}`,style:y?{"--building-type-color":y}:void 0,onClick:P=>{if(h){const v=P.currentTarget.getBoundingClientRect();h(o.id,{x:v.right,y:v.top+v.height/2})}else Be(o.id)},onContextMenu:P=>{P.preventDefault(),P.stopPropagation(),X({buildingId:o.id,position:{x:P.clientX,y:P.clientY}})},title:`${o.name} · ${o.type} · ${o.status}`,children:[e.jsx(p,{name:En(o.type),size:12,color:y}),e.jsx("span",{className:"flat-map-building-chip__name",children:o.name}),e.jsx("span",{className:"flat-map-building-chip__dot",style:{backgroundColor:Mn(o.status)}})]},o.id)})})]},g)})})()})]})})]}),l&&e.jsx("div",{className:"flat-splitter flat-splitter--inspector",role:"separator","aria-orientation":"vertical","aria-label":"Resize inspector panel",title:"Drag to resize · Double-click to reset",onPointerDown:gt,onPointerMove:nt,onPointerUp:ze,onPointerCancel:ze,onDoubleClick:ke}),c&&e.jsxs("aside",{className:`flat-inspector ${_e?"flat-inspector--open":"flat-inspector--closing"}`,"aria-label":"Inspector panel",children:[e.jsxs("div",{className:"flat-inspector__header",children:[e.jsxs("div",{className:"flat-inspector__tabs",role:"tablist","aria-label":"Inspector view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":xe==="agent",className:`flat-inspector__tab ${xe==="agent"?"flat-inspector__tab--active":""}`,onClick:()=>Ge("agent"),children:"Agent"}),e.jsx("button",{type:"button",role:"tab","aria-selected":xe==="tracking",className:`flat-inspector__tab ${xe==="tracking"?"flat-inspector__tab--active":""}`,onClick:()=>Ge("tracking"),children:"Tracking"})]}),e.jsx("button",{type:"button",className:"flat-inspector__close",onClick:Oe,title:"Close inspector","aria-label":"Close inspector",children:"✕"})]}),e.jsx("div",{className:"flat-inspector__body",children:xe==="tracking"?e.jsx(In,{activeAgentId:b??"",onSelectAgent:t=>{u(t),window.innerWidth<=768&&Oe()}}):(()=>{if(!b)return e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Select an agent to inspect"})});const t=w.find(n=>n.id===b);return t?e.jsx(Tn,{agent:t,onFocusAgent:n=>{u(n),window.innerWidth<=768&&Oe()},onKillAgent:n=>_.killAgent(n)}):e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Agent not found"})})})()})]}),I&&e.jsx(Pn,{url:I.url,name:I.name,onClose:()=>V(null)}),Y&&e.jsx(Ln,{state:Y,onClose:()=>ce(null)}),e.jsx(Dn,{agent:b?w.find(t=>t.id===b)??null:null,content:te,onClose:()=>de(null)}),we&&e.jsx(Rn,{action:"clear-subordinates",selectedAgentId:we.agentId,subordinateCount:we.count,onClose:()=>Je(null),onClearHistory:()=>{}}),e.jsx($n,{agent:b?w.find(t=>t.id===b)??null:null,isOpen:Le&&!!b,onClose:De}),e.jsx(Ut,{isOpen:se!==null,position:(se==null?void 0:se.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:sn,onClose:()=>ue(null)}),e.jsx(Ut,{isOpen:m!==null,position:(m==null?void 0:m.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:ln,onClose:()=>X(null)}),e.jsx(zn,{isOpen:pe!==null,title:Z("common:confirm.removeAgentTitle"),message:Z("common:confirm.removeAgentMessage",{name:(pe==null?void 0:pe.name)??""}),confirmLabel:Z("common:buttons.remove"),cancelLabel:Z("common:buttons.cancel"),variant:"danger",onConfirm:()=>{pe&&_.removeAgentFromServer(pe.agentId)},onClose:()=>ve(null)})]})}export{ka as FlatView};