tide-commander 1.110.2 → 1.110.3

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 (43) hide show
  1. package/dist/assets/{BossLogsModal-DBeMak5-.js → BossLogsModal-Dub95BCo.js} +1 -1
  2. package/dist/assets/{BossSpawnModal-DDl6qgnq.js → BossSpawnModal-BXIZWAzn.js} +1 -1
  3. package/dist/assets/{ControlsModal-BBUukX-p.js → ControlsModal-MclobOaO.js} +1 -1
  4. package/dist/assets/{DockerLogsModal-BWf3XDEI.js → DockerLogsModal-DRQ6YsEB.js} +1 -1
  5. package/dist/assets/{EmbeddedEditor-CIOdhnaW.js → EmbeddedEditor-B9iQHzhz.js} +1 -1
  6. package/dist/assets/{GmailOAuthSetup-qG-_WeOb.js → GmailOAuthSetup-wEezv-Vt.js} +1 -1
  7. package/dist/assets/{GoogleOAuthSetup-BK3lzU4n.js → GoogleOAuthSetup-P_teBMn2.js} +1 -1
  8. package/dist/assets/{IframeModal-D_NEs_Ld.js → IframeModal-DEXm0UTA.js} +1 -1
  9. package/dist/assets/{IntegrationsPanel-yphWX1ZD.js → IntegrationsPanel-CgFuLL4S.js} +2 -2
  10. package/dist/assets/{LogViewerModal-B0h9NNRk.js → LogViewerModal-CSpbNMTp.js} +1 -1
  11. package/dist/assets/{MonitoringModal-Ciw7KnXH.js → MonitoringModal-Dv1lWqtZ.js} +1 -1
  12. package/dist/assets/{PM2LogsModal-C1dYQaff.js → PM2LogsModal-qpjByXs_.js} +1 -1
  13. package/dist/assets/{RestoreArchivedAreaModal-DOwzfu-D.js → RestoreArchivedAreaModal-2O5SPxwQ.js} +1 -1
  14. package/dist/assets/{Scene2DCanvas-MHfv4Rzg.js → Scene2DCanvas-BJiXSOxB.js} +1 -1
  15. package/dist/assets/{SceneManager-cm1Kj0YD.js → SceneManager-D9NtdKQ1.js} +1 -1
  16. package/dist/assets/{SkillsPanel-DLwMkORc.js → SkillsPanel-B8_RPJzS.js} +1 -1
  17. package/dist/assets/{SlackMultiInstanceSetup-Dql_wPMX.js → SlackMultiInstanceSetup-VcCJhIhV.js} +1 -1
  18. package/dist/assets/{SpawnModal-DzPTSOKV.js → SpawnModal-gn1VV_xv.js} +1 -1
  19. package/dist/assets/StatisticsModal-DRvS2yB_.js +1 -0
  20. package/dist/assets/{SubordinateAssignmentModal-CoLzD3z2.js → SubordinateAssignmentModal-D9gpXqIB.js} +1 -1
  21. package/dist/assets/{TriggerManagerPanel-BOi2zr7N.js → TriggerManagerPanel-bBguUZCE.js} +1 -1
  22. package/dist/assets/{WorkflowEditorPanel-DB1ygPDS.js → WorkflowEditorPanel-BGcpM6uO.js} +1 -1
  23. package/dist/assets/{index-BZsQOteM.js → index-2NGIIydL.js} +1 -1
  24. package/dist/assets/{index-DKASWGtq.js → index-BLw57j0y.js} +1 -1
  25. package/dist/assets/index-Bg0YBtj9.js +11 -0
  26. package/dist/assets/{index-DKdZI-Ar.js → index-Bgcnlnvz.js} +1 -1
  27. package/dist/assets/{index-6Wak7CPm.js → index-BrdAbMM1.js} +1 -1
  28. package/dist/assets/{index-BXJSMT4a.js → index-CTfxfQqV.js} +3 -3
  29. package/dist/assets/{index-ThbMNdRp.js → index-Cy72l2Qo.js} +1 -1
  30. package/dist/assets/{index-D4XW6MSF.js → index-GpT5NHsq.js} +2 -2
  31. package/dist/assets/{index-C6EHHgC0.js → index-VYch6p3A.js} +1 -1
  32. package/dist/assets/{main-BxA3Bhkv.js → main-Brpf2Evy.js} +94 -94
  33. package/dist/assets/{main-BLrGoeQ_.css → main-VciFPjA1.css} +1 -1
  34. package/dist/assets/{web-BskC98UQ.js → web-DUdLOxoB.js} +1 -1
  35. package/dist/assets/{web-CSRmX8Ge.js → web-DjzK5qYd.js} +1 -1
  36. package/dist/assets/{web-zdygXcYu.js → web-IMi3bHab.js} +1 -1
  37. package/dist/index.html +2 -2
  38. package/dist/src/packages/server/data/builtin-skills/send-message-to-agent.js +31 -1
  39. package/dist/src/packages/server/routes/agents.js +30 -0
  40. package/dist/src/packages/server/services/runtime-service.js +24 -0
  41. package/dist/src/packages/server/websocket/handlers/agent-handler.js +18 -12
  42. package/package.json +1 -1
  43. package/dist/assets/index-BP6ukiYG.js +0 -11
@@ -1 +1 @@
1
- import{cl as a}from"./main-BxA3Bhkv.js";import{ImpactStyle as i,NotificationType as r}from"./index-D4XW6MSF.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";class h extends a{constructor(){super(...arguments),this.selectionStarted=!1}async impact(t){const e=this.patternForImpact(t==null?void 0:t.style);this.vibrateWithPattern(e)}async notification(t){const e=this.patternForNotification(t==null?void 0:t.type);this.vibrateWithPattern(e)}async vibrate(t){const e=(t==null?void 0:t.duration)||300;this.vibrateWithPattern([e])}async selectionStart(){this.selectionStarted=!0}async selectionChanged(){this.selectionStarted&&this.vibrateWithPattern([70])}async selectionEnd(){this.selectionStarted=!1}patternForImpact(t=i.Heavy){return t===i.Medium?[43]:t===i.Light?[20]:[61]}patternForNotification(t=r.Success){return t===r.Warning?[30,40,30,50,60]:t===r.Error?[27,45,50]:[35,65,21]}vibrateWithPattern(t){if(navigator.vibrate)navigator.vibrate(t);else throw this.unavailable("Browser does not support the vibrate API")}}export{h as HapticsWeb};
1
+ import{cm as a}from"./main-Brpf2Evy.js";import{ImpactStyle as i,NotificationType as r}from"./index-GpT5NHsq.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";class h extends a{constructor(){super(...arguments),this.selectionStarted=!1}async impact(t){const e=this.patternForImpact(t==null?void 0:t.style);this.vibrateWithPattern(e)}async notification(t){const e=this.patternForNotification(t==null?void 0:t.type);this.vibrateWithPattern(e)}async vibrate(t){const e=(t==null?void 0:t.duration)||300;this.vibrateWithPattern([e])}async selectionStart(){this.selectionStarted=!0}async selectionChanged(){this.selectionStarted&&this.vibrateWithPattern([70])}async selectionEnd(){this.selectionStarted=!1}patternForImpact(t=i.Heavy){return t===i.Medium?[43]:t===i.Light?[20]:[61]}patternForNotification(t=r.Success){return t===r.Warning?[30,40,30,50,60]:t===r.Error?[27,45,50]:[35,65,21]}vibrateWithPattern(t){if(navigator.vibrate)navigator.vibrate(t);else throw this.unavailable("Browser does not support the vibrate API")}}export{h as HapticsWeb};
@@ -1 +1 @@
1
- import{cl as t}from"./main-BxA3Bhkv.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";class o extends t{constructor(){super(),this.handleVisibilityChange=()=>{const e={isActive:document.hidden!==!0};this.notifyListeners("appStateChange",e),document.hidden?this.notifyListeners("pause",null):this.notifyListeners("resume",null)},document.addEventListener("visibilitychange",this.handleVisibilityChange,!1)}exitApp(){throw this.unimplemented("Not implemented on web.")}async getInfo(){throw this.unimplemented("Not implemented on web.")}async getLaunchUrl(){return{url:""}}async getState(){return{isActive:document.hidden!==!0}}async minimizeApp(){throw this.unimplemented("Not implemented on web.")}async toggleBackButtonHandler(){throw this.unimplemented("Not implemented on web.")}async getAppLanguage(){return{value:navigator.language.split("-")[0].toLowerCase()}}}export{o as AppWeb};
1
+ import{cm as t}from"./main-Brpf2Evy.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";class o extends t{constructor(){super(),this.handleVisibilityChange=()=>{const e={isActive:document.hidden!==!0};this.notifyListeners("appStateChange",e),document.hidden?this.notifyListeners("pause",null):this.notifyListeners("resume",null)},document.addEventListener("visibilitychange",this.handleVisibilityChange,!1)}exitApp(){throw this.unimplemented("Not implemented on web.")}async getInfo(){throw this.unimplemented("Not implemented on web.")}async getLaunchUrl(){return{url:""}}async getState(){return{isActive:document.hidden!==!0}}async minimizeApp(){throw this.unimplemented("Not implemented on web.")}async toggleBackButtonHandler(){throw this.unimplemented("Not implemented on web.")}async getAppLanguage(){return{value:navigator.language.split("-")[0].toLowerCase()}}}export{o as AppWeb};
@@ -1 +1 @@
1
- import{cl as s}from"./main-BxA3Bhkv.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";class l extends s{constructor(){super(...arguments),this.pending=[],this.deliveredNotifications=[],this.hasNotificationSupport=()=>{if(!("Notification"in window)||!Notification.requestPermission)return!1;if(Notification.permission!=="granted")try{new Notification("")}catch(i){if(i instanceof Error&&i.name==="TypeError")return!1}return!0}}async getDeliveredNotifications(){const i=[];for(const t of this.deliveredNotifications){const e={title:t.title,id:parseInt(t.tag),body:t.body};i.push(e)}return{notifications:i}}async removeDeliveredNotifications(i){for(const t of i.notifications){const e=this.deliveredNotifications.find(n=>n.tag===String(t.id));e==null||e.close(),this.deliveredNotifications=this.deliveredNotifications.filter(()=>!e)}}async removeAllDeliveredNotifications(){for(const i of this.deliveredNotifications)i.close();this.deliveredNotifications=[]}async createChannel(){throw this.unimplemented("Not implemented on web.")}async deleteChannel(){throw this.unimplemented("Not implemented on web.")}async listChannels(){throw this.unimplemented("Not implemented on web.")}async schedule(i){if(!this.hasNotificationSupport())throw this.unavailable("Notifications not supported in this browser.");for(const t of i.notifications)this.sendNotification(t);return{notifications:i.notifications.map(t=>({id:t.id}))}}async getPending(){return{notifications:this.pending}}async registerActionTypes(){throw this.unimplemented("Not implemented on web.")}async cancel(i){this.pending=this.pending.filter(t=>!i.notifications.find(e=>e.id===t.id))}async areEnabled(){const{display:i}=await this.checkPermissions();return{value:i==="granted"}}async changeExactNotificationSetting(){throw this.unimplemented("Not implemented on web.")}async checkExactNotificationSetting(){throw this.unimplemented("Not implemented on web.")}async requestPermissions(){if(!this.hasNotificationSupport())throw this.unavailable("Notifications not supported in this browser.");return{display:this.transformNotificationPermission(await Notification.requestPermission())}}async checkPermissions(){if(!this.hasNotificationSupport())throw this.unavailable("Notifications not supported in this browser.");return{display:this.transformNotificationPermission(Notification.permission)}}transformNotificationPermission(i){switch(i){case"granted":return"granted";case"denied":return"denied";default:return"prompt"}}sendPending(){var i;const t=[],e=new Date().getTime();for(const n of this.pending)!((i=n.schedule)===null||i===void 0)&&i.at&&n.schedule.at.getTime()<=e&&(this.buildNotification(n),t.push(n));this.pending=this.pending.filter(n=>!t.find(o=>o===n))}sendNotification(i){var t;if(!((t=i.schedule)===null||t===void 0)&&t.at){const e=i.schedule.at.getTime()-new Date().getTime();this.pending.push(i),setTimeout(()=>{this.sendPending()},e);return}this.buildNotification(i)}buildNotification(i){const t=new Notification(i.title,{body:i.body,tag:String(i.id)});return t.addEventListener("click",this.onClick.bind(this,i),!1),t.addEventListener("show",this.onShow.bind(this,i),!1),t.addEventListener("close",()=>{this.deliveredNotifications=this.deliveredNotifications.filter(()=>!this)},!1),this.deliveredNotifications.push(t),t}onClick(i){const t={actionId:"tap",notification:i};this.notifyListeners("localNotificationActionPerformed",t)}onShow(i){this.notifyListeners("localNotificationReceived",i)}}export{l as LocalNotificationsWeb};
1
+ import{cm as s}from"./main-Brpf2Evy.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";class l extends s{constructor(){super(...arguments),this.pending=[],this.deliveredNotifications=[],this.hasNotificationSupport=()=>{if(!("Notification"in window)||!Notification.requestPermission)return!1;if(Notification.permission!=="granted")try{new Notification("")}catch(i){if(i instanceof Error&&i.name==="TypeError")return!1}return!0}}async getDeliveredNotifications(){const i=[];for(const t of this.deliveredNotifications){const e={title:t.title,id:parseInt(t.tag),body:t.body};i.push(e)}return{notifications:i}}async removeDeliveredNotifications(i){for(const t of i.notifications){const e=this.deliveredNotifications.find(n=>n.tag===String(t.id));e==null||e.close(),this.deliveredNotifications=this.deliveredNotifications.filter(()=>!e)}}async removeAllDeliveredNotifications(){for(const i of this.deliveredNotifications)i.close();this.deliveredNotifications=[]}async createChannel(){throw this.unimplemented("Not implemented on web.")}async deleteChannel(){throw this.unimplemented("Not implemented on web.")}async listChannels(){throw this.unimplemented("Not implemented on web.")}async schedule(i){if(!this.hasNotificationSupport())throw this.unavailable("Notifications not supported in this browser.");for(const t of i.notifications)this.sendNotification(t);return{notifications:i.notifications.map(t=>({id:t.id}))}}async getPending(){return{notifications:this.pending}}async registerActionTypes(){throw this.unimplemented("Not implemented on web.")}async cancel(i){this.pending=this.pending.filter(t=>!i.notifications.find(e=>e.id===t.id))}async areEnabled(){const{display:i}=await this.checkPermissions();return{value:i==="granted"}}async changeExactNotificationSetting(){throw this.unimplemented("Not implemented on web.")}async checkExactNotificationSetting(){throw this.unimplemented("Not implemented on web.")}async requestPermissions(){if(!this.hasNotificationSupport())throw this.unavailable("Notifications not supported in this browser.");return{display:this.transformNotificationPermission(await Notification.requestPermission())}}async checkPermissions(){if(!this.hasNotificationSupport())throw this.unavailable("Notifications not supported in this browser.");return{display:this.transformNotificationPermission(Notification.permission)}}transformNotificationPermission(i){switch(i){case"granted":return"granted";case"denied":return"denied";default:return"prompt"}}sendPending(){var i;const t=[],e=new Date().getTime();for(const n of this.pending)!((i=n.schedule)===null||i===void 0)&&i.at&&n.schedule.at.getTime()<=e&&(this.buildNotification(n),t.push(n));this.pending=this.pending.filter(n=>!t.find(o=>o===n))}sendNotification(i){var t;if(!((t=i.schedule)===null||t===void 0)&&t.at){const e=i.schedule.at.getTime()-new Date().getTime();this.pending.push(i),setTimeout(()=>{this.sendPending()},e);return}this.buildNotification(i)}buildNotification(i){const t=new Notification(i.title,{body:i.body,tag:String(i.id)});return t.addEventListener("click",this.onClick.bind(this,i),!1),t.addEventListener("show",this.onShow.bind(this,i),!1),t.addEventListener("close",()=>{this.deliveredNotifications=this.deliveredNotifications.filter(()=>!this)},!1),this.deliveredNotifications.push(t),t}onClick(i){const t={actionId:"tap",notification:i};this.notifyListeners("localNotificationActionPerformed",t)}onShow(i){this.notifyListeners("localNotificationReceived",i)}}export{l as LocalNotificationsWeb};
package/dist/index.html CHANGED
@@ -22,10 +22,10 @@
22
22
  <link rel="icon" type="image/png" sizes="16x16" href="/assets/icons/favicon-16x16.png" />
23
23
  <link rel="apple-touch-icon" sizes="180x180" href="/assets/icons/apple-touch-icon.png" />
24
24
  <title>Tide Commander</title>
25
- <script type="module" crossorigin src="/assets/main-BxA3Bhkv.js"></script>
25
+ <script type="module" crossorigin src="/assets/main-Brpf2Evy.js"></script>
26
26
  <link rel="modulepreload" crossorigin href="/assets/vendor-react--Eh9ivFN.js">
27
27
  <link rel="modulepreload" crossorigin href="/assets/vendor-three-Chj50gSY.js">
28
- <link rel="stylesheet" crossorigin href="/assets/main-BLrGoeQ_.css">
28
+ <link rel="stylesheet" crossorigin href="/assets/main-VciFPjA1.css">
29
29
  </head>
30
30
  <body>
31
31
  <div id="app"></div>
@@ -47,5 +47,35 @@ EOF
47
47
  - Always prefix messages with your identity so the receiver knows who sent it
48
48
  - Use heredoc syntax (\`-d @- <<'EOF'\`) to avoid JSON escaping problems
49
49
  - Keep messages simple - avoid special characters like backslashes or nested quotes
50
- - Works with all agent types including boss agents`,
50
+ - Works with all agent types including boss agents
51
+
52
+ ## Collapsing an Agent's Context (\`/compact\`)
53
+
54
+ \`POST /api/agents/AGENT_ID/message\` cannot deliver Claude Code slash commands —
55
+ the slash is passed through as message body instead of being intercepted by the
56
+ CLI. For that, use the dedicated endpoint:
57
+
58
+ \`\`\`bash
59
+ curl -s -X POST http://localhost:5174/api/agents/AGENT_ID/collapse-context
60
+ \`\`\`
61
+
62
+ This sends Claude Code's \`/compact\` slash command to the agent's runner, which
63
+ compresses its conversation history. Works for ANY agent including yourself
64
+ (auto-collapse from a cron or end-of-flow step).
65
+
66
+ Response shape:
67
+
68
+ \`\`\`json
69
+ { "success": true, "agentId": "AGENT_ID", "status": "collapse-initiated" }
70
+ \`\`\`
71
+
72
+ Status codes:
73
+ - \`200\` + \`status: "collapse-initiated"\` — \`/compact\` dispatched
74
+ - \`404\` + \`status: "not-found"\` — agent id doesn't exist
75
+ - \`409\` + \`status: "busy"\` + \`currentStatus\` — agent isn't idle (Claude rejects slash commands mid-turn); retry once it goes idle
76
+ - \`500\` + \`status: "error"\` — runtime error sending the command
77
+
78
+ **When to use which endpoint:**
79
+ - \`/message\` — deliver content / instructions to an agent (what you usually want)
80
+ - \`/collapse-context\` — trigger the \`/compact\` slash command (the only path that works for slash commands; \`/message\` will not)`,
51
81
  };
@@ -1065,6 +1065,36 @@ router.post('/:id/message', async (req, res) => {
1065
1065
  res.status(500).json({ error: err.message });
1066
1066
  }
1067
1067
  });
1068
+ // POST /api/agents/:id/collapse-context — Send Claude Code's /compact slash command
1069
+ // to the agent's runner. Use case: any agent (including the same agent via a
1070
+ // scheduled cron) auto-collapsing its own context. Plain /message can't carry
1071
+ // slash commands; this is the only correct path.
1072
+ router.post('/:id/collapse-context', async (req, res) => {
1073
+ try {
1074
+ const agentId = req.params.id;
1075
+ const result = await runtimeService.collapseAgentContext(agentId);
1076
+ switch (result.status) {
1077
+ case 'collapse-initiated':
1078
+ log.log(`API collapse-context dispatched for agent ${agentId}`);
1079
+ res.status(200).json({ success: true, agentId, status: 'collapse-initiated' });
1080
+ return;
1081
+ case 'not-found':
1082
+ res.status(404).json({ success: false, agentId, status: 'not-found', error: `Agent not found: ${agentId}` });
1083
+ return;
1084
+ case 'busy':
1085
+ res.status(409).json({ success: false, agentId, status: 'busy', currentStatus: result.currentStatus, error: 'Cannot collapse context while agent is busy' });
1086
+ return;
1087
+ case 'error':
1088
+ log.error(` Failed to collapse context for ${agentId}: ${result.error}`);
1089
+ res.status(500).json({ success: false, agentId, status: 'error', error: result.error });
1090
+ return;
1091
+ }
1092
+ }
1093
+ catch (err) {
1094
+ log.error(' Failed to collapse context (route):', err);
1095
+ res.status(500).json({ error: err?.message || 'Failed to collapse context' });
1096
+ }
1097
+ });
1068
1098
  // POST /api/agents/:id/report-task - Subordinate reports task completion to its boss
1069
1099
  router.post('/:id/report-task', async (req, res) => {
1070
1100
  try {
@@ -187,6 +187,30 @@ export async function sendCommand(agentId, command, systemPrompt, forceNewSessio
187
187
  export async function sendSilentCommand(agentId, command) {
188
188
  await commandExecution.sendSilentCommand(agentId, command);
189
189
  }
190
+ /**
191
+ * Send Claude Code's `/compact` slash command to collapse an agent's context.
192
+ * Only fires when the agent exists AND is idle — the CLI rejects slash commands
193
+ * mid-turn, and we want a clean, predictable result instead of partial state.
194
+ *
195
+ * Callers: WS `collapse_context` handler, REST `POST /api/agents/:id/collapse-context`.
196
+ * Plain `/message` cannot carry slash commands (they're sent as message body, not
197
+ * intercepted by the CLI) — this helper is the only correct path.
198
+ */
199
+ export async function collapseAgentContext(agentId) {
200
+ const agent = agentService.getAgent(agentId);
201
+ if (!agent)
202
+ return { status: 'not-found' };
203
+ if (agent.status !== 'idle') {
204
+ return { status: 'busy', currentStatus: agent.status };
205
+ }
206
+ try {
207
+ await commandExecution.sendCommand(agentId, '/compact');
208
+ return { status: 'collapse-initiated' };
209
+ }
210
+ catch (err) {
211
+ return { status: 'error', error: err instanceof Error ? err.message : String(err) };
212
+ }
213
+ }
190
214
  export async function stopAgent(agentId) {
191
215
  await commandExecution.stopAgent(agentId);
192
216
  }
@@ -227,22 +227,28 @@ export function handleRequestSessionHistory(ctx, payload) {
227
227
  });
228
228
  }
229
229
  /**
230
- * Handle collapse_context message - sends /compact command to collapse context
230
+ * Handle collapse_context message - sends /compact command to collapse context.
231
+ * Thin wrapper around runtimeService.collapseAgentContext that maps each
232
+ * discriminated result back to the WS activity stream.
231
233
  */
232
234
  export async function handleCollapseContext(ctx, payload) {
233
- const agent = agentService.getAgent(payload.agentId);
234
- if (agent && agent.status === 'idle') {
235
- try {
236
- await runtimeService.sendCommand(payload.agentId, '/compact');
235
+ const result = await runtimeService.collapseAgentContext(payload.agentId);
236
+ switch (result.status) {
237
+ case 'collapse-initiated':
237
238
  ctx.sendActivity(payload.agentId, 'Context collapse initiated');
238
- }
239
- catch (err) {
240
- log.error(` Failed to collapse context: ${err}`);
239
+ return;
240
+ case 'busy':
241
+ ctx.sendActivity(payload.agentId, 'Cannot collapse context while agent is busy');
242
+ return;
243
+ case 'not-found':
244
+ // No agent → no activity stream to write to; quietly drop (the UI shouldn't
245
+ // be able to reach this state, and logging keeps the breadcrumb).
246
+ log.warn(`collapse_context for unknown agent ${payload.agentId}`);
247
+ return;
248
+ case 'error':
249
+ log.error(` Failed to collapse context: ${result.error}`);
241
250
  ctx.sendActivity(payload.agentId, 'Failed to collapse context');
242
- }
243
- }
244
- else {
245
- ctx.sendActivity(payload.agentId, 'Cannot collapse context while agent is busy');
251
+ return;
246
252
  }
247
253
  }
248
254
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tide-commander",
3
- "version": "1.110.2",
3
+ "version": "1.110.3",
4
4
  "description": "Visual multi-agent orchestrator and manager for Claude Code with 3D/2D interface",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,11 +0,0 @@
1
- import{r as l,aV as Re,aW as Ye,j as e,I as $,u as Y,aX as as,a3 as ns,f as Ve,s as E,aY as hs,k as is,l as me,aZ as X,a_ as ms,aO as gs,a$ as fs,C as ge,b0 as J,aL as we,b1 as xs,b2 as bs,b3 as js,b4 as ws,b5 as Se,b6 as os,b7 as ys,b8 as Me,b9 as Ns,ba as vs,bb as ks,bc as Ss,bd as Cs,be as Ts,bf as As,aH as _s,J as Es,S as ke,bg as Is,bh as Ps,aJ as $s,bi as Ue,K as Pe,aS as Ls,bj as ze,bk as Ds}from"./main-BxA3Bhkv.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const Ke="deivid11/tide-commander",Os=`https://api.github.com/repos/${Ke}/releases/latest`,Fs=`https://api.github.com/repos/${Ke}/releases?per_page=3`,Rs=3600*1e3,Je="app_update_dismissed_version",Ze="1.110.2";function Us(){var x,w;const[s,a]=l.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Ze}),t=((w=(x=Re)==null?void 0:x.getPlatform)==null?void 0:w.call(x))==="android"||!1,o=u=>u.replace(/^v/,"").split(".").map(m=>parseInt(m,10)||0),r=(u,g)=>{const m=o(u),j=o(g),b=Math.max(m.length,j.length);for(let h=0;h<b;h++){const S=m[h]||0,L=j[h]||0;if(S>L)return 1;if(S<L)return-1}return 0},d=async u=>{var m,j;if(Re&&Ye&&((j=(m=Re).isNativePlatform)==null?void 0:j.call(m))===!0){const b=await Ye.get({url:u,headers:{Accept:"application/vnd.github.v3+json"}});return{data:b.data,status:b.status}}else{const b=await fetch(u,{headers:{Accept:"application/vnd.github.v3+json"}});return b.ok?{data:await b.json(),status:b.status}:{data:null,status:b.status}}},c=l.useCallback(async(u=!1)=>{a(g=>({...g,isChecking:!0,error:null}));try{const[g,m]=await Promise.all([d(Os),d(Fs)]);if(g.status!==200)throw new Error(`GitHub API error: ${g.status}`);const j=g.data,b=j.tag_name;let h=[];m.status===200&&m.data&&(h=m.data.map(_=>({version:_.tag_name,name:_.name,publishedAt:_.published_at,releaseUrl:_.html_url})));const S=localStorage.getItem(Je);if(!u&&S===b)return a(_=>({..._,isChecking:!1,updateAvailable:!1,recentReleases:h})),null;if(!(r(b,Ze)>0))return a(_=>({..._,isChecking:!1,updateAvailable:!1,recentReleases:h})),null;const P=j.assets.find(_=>_.name.endsWith(".apk")&&_.content_type==="application/vnd.android.package-archive"),C={version:b,name:j.name,changelog:j.body,releaseUrl:j.html_url,apkUrl:(P==null?void 0:P.browser_download_url)||null,apkSize:(P==null?void 0:P.size)||null,publishedAt:j.published_at};return a(_=>({..._,isChecking:!1,updateAvailable:!0,updateInfo:C,recentReleases:h})),C}catch(g){const m=g instanceof Error?g.message:"Failed to check for updates";return a(j=>({...j,isChecking:!1,error:m})),null}},[]),n=l.useCallback(async()=>{var u,g,m;if(!((u=s.updateInfo)!=null&&u.apkUrl)){(g=s.updateInfo)!=null&&g.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(m=s.updateInfo)!=null&&m.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),a(j=>({...j,error:null}))}catch(j){const b=j instanceof Error?j.message:"Failed to open download";a(h=>({...h,error:b}))}},[s.updateInfo,t]),p=l.useCallback(()=>{s.updateInfo&&localStorage.setItem(Je,s.updateInfo.version),a(u=>({...u,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),y=l.useCallback(()=>{var u;(u=s.updateInfo)!=null&&u.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${Ke}/releases`,"_blank")},[s.updateInfo]);return l.useEffect(()=>{if(!t)return;const u=setTimeout(()=>{c()},5e3),g=setInterval(()=>{c()},Rs);return()=>{clearTimeout(u),clearInterval(g)}},[t,c]),{...s,isAndroid:t,checkForUpdate:c,downloadAndInstall:n,dismissUpdate:p,openReleasePage:y}}const ls="tide-toolbox-collapse";function zs(s,a){try{const t=localStorage.getItem(`${ls}-${s}`);if(t!==null)return t==="true"}catch{}return a}function Bs(s,a){try{localStorage.setItem(`${ls}-${s}`,String(a))}catch{}}function W({title:s,storageKey:a,defaultOpen:t=!1,forceOpen:o=!1,children:r,headerExtra:d}){const[c,n]=l.useState(()=>a?zs(a,t):t),p=()=>{const x=!c;n(x),a&&Bs(a,x)},y=o||c;return e.jsxs("div",{className:`collapsible-section ${y?"open":"collapsed"}`,children:[e.jsxs("button",{className:"collapsible-header",onClick:p,children:[e.jsx("span",{className:"collapsible-title",children:s}),e.jsxs("span",{className:"collapsible-header-right",children:[d,e.jsx("span",{className:"collapsible-arrow",children:e.jsx($,{name:y?"caret-down":"caret-right",size:10})})]})]}),y&&e.jsx("div",{className:"collapsible-content",children:r})]})}function Ms({area:s,isSelected:a,onClick:t,onDelete:o}){const{t:r}=Y(["config","common"]),d=s.assignedAgentIds.length,c=s.type==="rectangle"?r("config:areas.rect"):r("config:areas.circle");return e.jsxs("div",{className:`area-item ${a?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"area-color-dot",style:{backgroundColor:s.color}}),e.jsxs("div",{className:"area-info",children:[e.jsx("div",{className:"area-name",children:s.name}),e.jsxs("div",{className:"area-meta",children:[c," ",d>0&&`• ${d} ${d>1?r("common:labels.agents").toLowerCase():r("common:labels.agent").toLowerCase()}`]})]}),e.jsx("button",{className:"area-delete-btn",onClick:o,title:r("config:areas.deleteArea"),children:"×"})]})}function Vs({building:s,isSelected:a,onClick:t,onEdit:o}){var n;const{t:r}=Y(["config"]),d=((n=s.pm2Status)==null?void 0:n.ports)||[],c=(p,y)=>{p.stopPropagation(),window.open(`http://${window.location.hostname}:${y}`,"_blank")};return e.jsxs("div",{className:`building-item ${a?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"building-status-dot",style:{backgroundColor:as[s.status]},title:s.status}),e.jsx("div",{className:"building-icon",children:e.jsx($,{name:ns(s.type),size:16})}),e.jsxs("div",{className:"building-info",children:[e.jsx("div",{className:"building-name",children:s.name}),e.jsxs("div",{className:"building-meta",children:[s.type,d.length>0&&e.jsx("span",{className:"building-ports",children:d.map(p=>e.jsxs("a",{href:`http://${window.location.hostname}:${p}`,className:"building-port-link",onClick:y=>c(y,p),title:`Open :${p}`,children:[":",p]},p))})]})]}),e.jsx("button",{className:"building-edit-btn",onClick:p=>{p.stopPropagation(),o()},title:r("config:buildings.editBuilding"),children:e.jsx($,{name:"gear",size:14})})]})}function Ks({building:s,onClose:a,onOpenModal:t}){var y,x,w,u,g,m,j,b;const{t:o}=Y(["config","common"]),{buildingLogs:r}=Ve(),d=E.getBuildingLogs(s.id),c=hs[s.style||"server-rack"],n=h=>{E.sendBuildingCommand(s.id,h)},p=h=>{window.open(h,"_blank")};return e.jsxs("div",{className:"building-editor",children:[e.jsxs("div",{className:"building-editor-header",children:[e.jsxs("div",{className:"building-editor-title-row",children:[e.jsx("span",{className:"building-editor-icon",children:e.jsx($,{name:ns(s.type),size:18})}),e.jsx("span",{className:"building-editor-title",children:s.name}),e.jsx("span",{className:"building-editor-status",style:{backgroundColor:as[s.status]},children:s.status})]}),e.jsx("button",{className:"building-editor-close",onClick:a,children:"×"})]}),e.jsx("div",{className:"building-editor-section",children:e.jsxs("div",{className:"building-editor-info-grid",children:[e.jsxs("div",{className:"building-editor-info-item",children:[e.jsx("span",{className:"building-editor-info-label",children:o("common:labels.type")}),e.jsx("span",{className:"building-editor-info-value",children:s.type})]}),e.jsxs("div",{className:"building-editor-info-item",children:[e.jsx("span",{className:"building-editor-info-label",children:o("config:buildings.style")}),e.jsx("span",{className:"building-editor-info-value",children:c.label})]}),s.cwd&&e.jsxs("div",{className:"building-editor-info-item building-editor-info-wide",children:[e.jsx("span",{className:"building-editor-info-label",children:o("config:buildings.directory")}),e.jsx("span",{className:"building-editor-info-value building-editor-cwd",title:s.cwd,children:s.cwd.split("/").pop()||s.cwd})]})]})}),s.type==="server"&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:o("config:buildings.actions")}),e.jsxs("div",{className:"building-editor-actions",children:[e.jsxs("button",{className:"building-editor-action-btn start",onClick:()=>n("start"),disabled:!((y=s.commands)!=null&&y.start)||s.status==="running",title:((x=s.commands)==null?void 0:x.start)||o("config:buildings.noStartCommand"),children:[e.jsx($,{name:"play",size:12})," ",o("common:buttons.start")]}),e.jsxs("button",{className:"building-editor-action-btn stop",onClick:()=>n("stop"),disabled:!((w=s.commands)!=null&&w.stop)||s.status==="stopped",title:((u=s.commands)==null?void 0:u.stop)||o("config:buildings.noStopCommand"),children:[e.jsx($,{name:"stop",size:12,weight:"fill"})," ",o("common:buttons.stop")]}),e.jsxs("button",{className:"building-editor-action-btn restart",onClick:()=>n("restart"),disabled:!((g=s.commands)!=null&&g.restart),title:((m=s.commands)==null?void 0:m.restart)||o("config:buildings.noRestartCommand"),children:[e.jsx($,{name:"refresh",size:12})," ",o("common:buttons.retry")]}),e.jsxs("button",{className:"building-editor-action-btn health",onClick:()=>n("healthCheck"),disabled:!((j=s.commands)!=null&&j.healthCheck),title:((b=s.commands)==null?void 0:b.healthCheck)||o("config:buildings.noHealthCheck"),children:[e.jsx($,{name:"heart",size:12})," Health"]})]})]}),s.urls&&s.urls.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:o("config:buildings.links")}),e.jsx("div",{className:"building-editor-links",children:s.urls.map((h,S)=>e.jsxs("button",{className:"building-editor-link",onClick:()=>p(h.url),title:h.url,children:[e.jsx($,{name:"link",size:12})," ",h.label||h.url]},S))})]}),d.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsxs("div",{className:"building-editor-section-title",children:[o("config:buildings.recentLogs"),e.jsx("button",{className:"building-editor-clear-logs",onClick:()=>E.clearBuildingLogs(s.id),title:o("common:buttons.clear"),children:o("common:buttons.clear")})]}),e.jsx("div",{className:"building-editor-logs",children:d.slice(-5).map((h,S)=>e.jsx("div",{className:"building-editor-log-entry",children:h},S))})]}),e.jsx("div",{className:"building-editor-footer",children:e.jsxs("button",{className:"building-editor-edit-btn",onClick:t,children:[e.jsx($,{name:"gear",size:12})," ",o("config:buildings.fullSettings")]})})]})}async function Hs(s,a){const t=X(),o=await fetch(me(`/api/areas/${s}/logo`),{method:"POST",headers:{"Content-Type":a.type||"image/png","X-Filename":encodeURIComponent(a.name),...t?{Authorization:`Bearer ${t}`}:{}},body:a});if(!o.ok){const r=await o.json().catch(()=>({error:o.statusText}));throw new Error(r.error||`Upload failed: ${o.statusText}`)}return o.json()}async function Ws(s){const a=X(),t=await fetch(me(`/api/areas/${s}/logo`),{method:"DELETE",headers:{...a?{Authorization:`Bearer ${a}`}:{}}});if(!t.ok)throw new Error(`Failed to delete logo: ${t.statusText}`)}function qs(s){return is(me(`/api/areas/logos/${s}`))}const Gs=[{key:"center",labelKey:"posCenter"},{key:"top-left",labelKey:"posTopLeft"},{key:"top-right",labelKey:"posTopRight"},{key:"bottom-left",labelKey:"posBottomLeft"},{key:"bottom-right",labelKey:"posBottomRight"}];function Ys({area:s,onClose:a,onOpenFolder:t}){var ce;const{t:o}=Y(["config","common"]),[r,d]=l.useState(s.name),[c,n]=l.useState(s.prompt||""),[p,y]=l.useState(!1),[x,w]=l.useState(""),[u,g]=l.useState(!1),m=l.useRef(null);l.useEffect(()=>{d(s.name)},[s.id,s.name]),l.useEffect(()=>{n(s.prompt||"")},[s.id,s.prompt]);const j=N=>{const F=N.target.value;d(F),E.updateArea(s.id,{name:F})},b=N=>{E.updateArea(s.id,{color:N})},h=N=>{const F=N.target.value;n(F),E.updateArea(s.id,{prompt:F})},S=()=>{x.trim()&&(E.addDirectoryToArea(s.id,x.trim()),w(""),y(!1))},L=(N,F)=>{F.stopPropagation(),E.removeDirectoryFromArea(s.id,N)},P=()=>{E.bringAreaToFront(s.id)},C=()=>{E.sendAreaToBack(s.id)},_=l.useCallback(()=>{let N=2,F=2;s.type==="rectangle"&&s.width&&s.height?(N=s.width,F=s.height):s.type==="circle"&&s.radius&&(N=s.radius*1.414,F=s.radius*1.414);const M=Math.min(N,F)*.4;return{width:Math.round(M*10)/10,height:Math.round(M*10)/10}},[s.type,s.width,s.height,s.radius]),V=async N=>{var M;const F=(M=N.target.files)==null?void 0:M[0];if(F){g(!0);try{const v=await Hs(s.id,F),O=_();E.updateArea(s.id,{logo:{filename:v.filename,position:"center",width:O.width,height:O.height,keepAspectRatio:!0,opacity:.8}})}catch(v){console.error("Failed to upload logo:",v)}finally{g(!1),m.current&&(m.current.value="")}}},B=async()=>{try{await Ws(s.id),E.updateArea(s.id,{logo:void 0})}catch(N){console.error("Failed to remove logo:",N)}},K=N=>{s.logo&&E.updateArea(s.id,{logo:{...s.logo,position:N}})},k=N=>{if(!s.logo)return;const F=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.width>0){const M=s.logo.height/s.logo.width;E.updateArea(s.id,{logo:{...s.logo,width:F,height:Math.round(F*M*10)/10}})}else E.updateArea(s.id,{logo:{...s.logo,width:F}})},T=N=>{if(!s.logo)return;const F=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.height>0){const M=s.logo.width/s.logo.height;E.updateArea(s.id,{logo:{...s.logo,height:F,width:Math.round(F*M*10)/10}})}else E.updateArea(s.id,{logo:{...s.logo,height:F}})},H=()=>{s.logo&&E.updateArea(s.id,{logo:{...s.logo,keepAspectRatio:!s.logo.keepAspectRatio}})},Z=N=>{s.logo&&E.updateArea(s.id,{logo:{...s.logo,opacity:parseFloat(N.target.value)}})};return e.jsxs("div",{className:"area-editor",children:[e.jsxs("div",{className:"area-editor-header",children:[e.jsx("span",{className:"area-editor-title",children:o("config:areas.editArea")}),e.jsx("button",{className:"area-editor-close",onClick:a,children:"×"})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("common:labels.name")}),e.jsx("input",{type:"text",className:"area-editor-input",value:r,onChange:j,placeholder:o("config:areas.areaName")})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.color")}),e.jsx("div",{className:"color-picker-row",children:ms.map(N=>e.jsx("button",{type:"button",className:`color-swatch ${s.color===N?"selected":""}`,style:{backgroundColor:N},onClick:()=>b(N),"aria-label":`Set area color ${N}`,"aria-pressed":s.color===N,title:N},N))})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.layer")}),e.jsxs("div",{className:"area-layer-buttons",children:[e.jsxs("button",{className:"area-layer-btn",onClick:P,title:o("config:areas.bringToFront"),children:[e.jsx($,{name:"arrow-up",size:12})," ",o("config:areas.front")]}),e.jsxs("button",{className:"area-layer-btn",onClick:C,title:o("config:areas.sendToBack"),children:[e.jsx($,{name:"arrow-down",size:12})," ",o("config:areas.back")]})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.logo")}),e.jsxs("div",{className:"area-logo-section",children:[(ce=s.logo)!=null&&ce.filename?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"area-logo-preview",children:[e.jsx("img",{src:qs(s.logo.filename),alt:"Logo",className:"area-logo-thumbnail"}),e.jsx("button",{className:"area-logo-remove-btn",onClick:B,children:o("config:areas.removeLogo")}),e.jsx("button",{className:"area-logo-replace-btn",onClick:()=>{var N;return(N=m.current)==null?void 0:N.click()},disabled:u,children:u?"...":e.jsx($,{name:"refresh",size:12})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoPosition")}),e.jsx("div",{className:"area-logo-position-row",children:Gs.map(({key:N,labelKey:F})=>{var M;return e.jsx("button",{className:`area-logo-pos-btn ${((M=s.logo)==null?void 0:M.position)===N?"active":""}`,onClick:()=>K(N),children:o(`config:areas.${F}`)},N)})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoSize")}),e.jsxs("div",{className:"area-logo-size-row",children:[e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:o("config:areas.logoWidth")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.width,onChange:k,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:o("config:areas.logoHeight")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.height,onChange:T,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-aspect-label",title:o("config:areas.keepAspectRatio"),children:[e.jsx("input",{type:"checkbox",checked:s.logo.keepAspectRatio,onChange:H}),o("config:areas.keepAspectRatio")]})]})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoOpacity")}),e.jsxs("div",{className:"area-logo-opacity-row",children:[e.jsx("input",{type:"range",min:0,max:1,step:.05,value:s.logo.opacity??.8,onChange:Z,className:"area-logo-opacity-slider"}),e.jsxs("span",{className:"area-logo-opacity-value",children:[Math.round((s.logo.opacity??.8)*100),"%"]})]})]})]}):e.jsx("button",{className:"area-logo-upload-btn",onClick:()=>{var N;return(N=m.current)==null?void 0:N.click()},disabled:u,children:u?"...":o("config:areas.uploadLogo")}),e.jsx("input",{ref:m,type:"file",accept:"image/*",style:{display:"none"},onChange:V})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.folders",{count:s.directories.length})}),e.jsxs("div",{className:"area-folders-list",children:[s.directories.map(N=>e.jsxs("div",{className:"area-folder-item",title:N,children:[e.jsx("span",{className:"area-folder-icon clickable",onClick:()=>t==null?void 0:t(s.id),title:o("config:areas.openFolder"),children:e.jsx($,{name:"folder",size:14})}),e.jsx("span",{className:"area-folder-path",children:N.split("/").pop()||N}),e.jsx("button",{className:"area-folder-remove",onClick:F=>L(N,F),title:o("config:areas.removeFolder"),children:"×"})]},N)),p?e.jsxs("div",{className:"area-add-folder-inline",children:[e.jsx(gs,{value:x,onChange:w,onSubmit:S,placeholder:o("config:areas.folderPlaceholder"),className:"area-add-folder-input",directoriesOnly:!0,autoFocus:!0}),e.jsx("button",{className:"area-add-folder-confirm",onClick:S,children:"+"})]}):e.jsx("button",{className:"area-add-folder-btn",onClick:()=>y(!0),children:o("config:areas.addFolder")})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.prompt","Prompt")}),e.jsx("textarea",{className:"area-editor-input",value:c,onChange:h,placeholder:o("config:areas.promptPlaceholder","System prompt for agents in this area..."),rows:4,style:{resize:"vertical",fontFamily:"monospace",fontSize:12}}),e.jsx("div",{style:{fontSize:11,color:"var(--text-secondary)",marginTop:4},children:o("config:areas.promptHint","This prompt is injected into agents assigned to this area. Takes effect on next context refresh.")})]}),s.assignedAgentIds.length>0&&e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.assignedAgents",{count:s.assignedAgentIds.length})}),e.jsx("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:o("config:areas.rightClickUnassign")})]})]})}function Js(){const{t:s}=Y(["config","common"]),a=fs(),[t,o]=l.useState(!1),[r,d]=l.useState(null),[c,n]=l.useState({name:"",key:"",value:"",description:""}),[p,y]=l.useState(null),x=()=>{o(!0),d(null),n({name:"",key:"",value:"",description:""})},w=h=>{d(h.id),o(!1),n({name:h.name,key:h.key,value:h.value,description:h.description||""})},u=()=>{o(!1),d(null),n({name:"",key:"",value:"",description:""})},g=()=>{!c.name.trim()||!c.key.trim()||(r?E.updateSecret(r,{name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}):E.createSecret({name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}),u())},m=h=>{y(h)},j=()=>{p&&(E.deleteSecret(p),r===p&&u())},b=h=>{navigator.clipboard.writeText(`{{${h}}}`)};return e.jsxs("div",{className:"secrets-section",children:[e.jsx("div",{className:"secrets-description",children:s("config:secrets.description",{placeholder:"{{KEY}}"})}),e.jsx("div",{className:"secrets-list",children:a.length===0&&!t?e.jsx("div",{className:"secrets-empty",children:s("config:secrets.noSecrets")}):a.map(h=>e.jsxs("div",{className:`secret-item ${r===h.id?"editing":""}`,children:[e.jsxs("div",{className:"secret-item-header",children:[e.jsxs("div",{className:"secret-item-info",children:[e.jsx("span",{className:"secret-item-name",children:h.name}),e.jsx("code",{className:"secret-item-key",onClick:()=>b(h.key),title:s("config:secrets.copyPlaceholder"),children:`{{${h.key}}}`})]}),e.jsxs("div",{className:"secret-item-actions",children:[e.jsx("button",{className:"secret-item-btn edit",onClick:()=>w(h),title:s("common:buttons.edit"),children:e.jsx($,{name:"edit",size:12})}),e.jsx("button",{className:"secret-item-btn delete",onClick:()=>m(h.id),title:s("common:buttons.delete"),children:"×"})]})]}),h.description&&e.jsx("div",{className:"secret-item-description",children:h.description})]},h.id))}),(t||r)&&e.jsxs("div",{className:"secret-form",children:[e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("common:labels.name")}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.namePlaceholder"),value:c.name,onChange:h=>n({...c,name:h.target.value}),autoFocus:!0})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:"Key"}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.keyPlaceholder"),value:c.key,onChange:h=>n({...c,key:h.target.value.toUpperCase().replace(/[^A-Z0-9_]/g,"")})}),e.jsx("span",{className:"secret-form-hint",children:s("config:secrets.usedAs",{placeholder:`{{${c.key||"KEY"}}}`})})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("config:secrets.secretValue")}),e.jsx("input",{type:"password",className:"secret-form-input",placeholder:s("config:secrets.valuePlaceholder"),value:c.value,onChange:h=>n({...c,value:h.target.value})})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("common:labels.description")}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.descriptionPlaceholder"),value:c.description,onChange:h=>n({...c,description:h.target.value})})]}),e.jsxs("div",{className:"secret-form-actions",children:[e.jsx("button",{className:"secret-form-btn cancel",onClick:u,children:s("common:buttons.cancel")}),e.jsx("button",{className:"secret-form-btn save",onClick:g,disabled:!c.name.trim()||!c.key.trim(),children:s(r?"config:secrets.update":"common:buttons.add")})]})]}),!t&&!r&&e.jsx("button",{className:"secrets-add-btn",onClick:x,children:s("config:secrets.addSecret")}),e.jsx(ge,{isOpen:p!==null,title:s("common:buttons.delete"),message:s("config:secrets.deleteConfirm"),confirmLabel:s("common:buttons.delete"),cancelLabel:s("common:buttons.cancel"),variant:"danger",onConfirm:j,onClose:()=>y(null)})]})}async function Zs(){const s=X(),a=await fetch(`${J()}/api/agents/system-settings/prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch system prompt: ${a.statusText}`);return(await a.json()).prompt||""}async function Xs(s){const a=X(),t=await fetch(`${J()}/api/agents/system-settings/prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({prompt:s})});if(!t.ok)throw new Error(`Failed to update system prompt: ${t.statusText}`)}async function Qs(){const s=X(),a=await fetch(`${J()}/api/agents/system-settings/prompt`,{method:"DELETE",headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to clear system prompt: ${a.statusText}`)}async function et(){const s=X(),a=await fetch(`${J()}/api/agents/system-settings/echo-prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch echo prompt setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function st(s){const a=X(),t=await fetch(`${J()}/api/agents/system-settings/echo-prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update echo prompt setting: ${t.statusText}`)}async function tt(){const s=X(),a=await fetch(`${J()}/api/agents/system-settings/codex-binary`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch codex binary path: ${a.statusText}`);return(await a.json()).path||""}async function at(s){const a=X(),t=await fetch(`${J()}/api/agents/system-settings/codex-binary`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({path:s})});if(!t.ok)throw new Error(`Failed to update codex binary path: ${t.statusText}`)}async function nt(){const s=X(),a=await fetch(`${J()}/api/agents/system-settings/tmux-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch tmux mode setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function it(s){const a=X(),t=await fetch(`${J()}/api/agents/system-settings/tmux-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update tmux mode setting: ${t.statusText}`)}async function ot(){const s=X(),a=await fetch(`${J()}/api/agents/system-settings/backup`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch backup status: ${a.statusText}`);return a.json()}async function lt(s){const a=X(),t=await fetch(`${J()}/api/agents/system-settings/backup`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||`Failed to update backup setting: ${t.statusText}`)}return t.json()}function ct({checked:s,onChange:a,disabled:t}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,disabled:t,onChange:o=>a(o.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function rt(){const{t:s}=Y(["config","common"]),[a,t]=l.useState([]),[o,r]=l.useState(new Set),[d,c]=l.useState(new Set),[n,p]=l.useState(!1),[y,x]=l.useState(!1),[w,u]=l.useState(null),[g,m]=l.useState(null),[j,b]=l.useState(null),[h,S]=l.useState(null),[L,P]=l.useState(!1),[C,_]=l.useState(null);l.useEffect(()=>{we(me("/api/config/categories")).then(v=>v.json()).then(v=>{const O=Array.isArray(v)?v:[];t(O),r(new Set(O.map(R=>R.id)))}).catch(v=>console.error("Failed to fetch config categories:",v))},[]),l.useEffect(()=>{ot().then(S).catch(v=>{console.error("Failed to fetch backup status:",v),_(v.message||"Failed to fetch backup status")})},[]);const V=async v=>{if(!L){P(!0),_(null);try{const O=await lt(v);S(O)}catch(O){_(O.message||"Failed to update backup setting")}finally{P(!1)}}},B=v=>{r(O=>{const R=new Set(O);return R.has(v)?R.delete(v):R.add(v),R})},K=v=>{c(O=>{const R=new Set(O);return R.has(v)?R.delete(v):R.add(v),R})},k=()=>r(new Set(a.map(v=>v.id))),T=()=>r(new Set),H=()=>{g&&c(new Set(g.categories.map(v=>v.id)))},Z=()=>c(new Set),ce=async()=>{var v;if(o.size!==0){p(!0),b(null);try{const O=Array.from(o).join(","),R=await we(me(`/api/config/export?categories=${O}`));if(!R.ok)throw new Error("Export failed");const Q=await R.blob(),te=window.URL.createObjectURL(Q),ee=document.createElement("a");ee.href=te;const A=R.headers.get("Content-Disposition"),q=((v=A==null?void 0:A.match(/filename="(.+)"/))==null?void 0:v[1])||"tide-commander-config.zip";ee.download=q,document.body.appendChild(ee),ee.click(),document.body.removeChild(ee),window.URL.revokeObjectURL(te),b({type:"success",text:s("config:data.exportSuccess")})}catch(O){b({type:"error",text:O.message||"Export failed"})}finally{p(!1)}}},N=async v=>{var R;const O=(R=v.target.files)==null?void 0:R[0];if(O){u(O),b(null),m(null),c(new Set);try{const Q=await we(me("/api/config/preview"),{method:"POST",headers:{"Content-Type":"application/zip"},body:await O.arrayBuffer()});if(!Q.ok){const A=await Q.json();throw new Error(A.error||"Failed to preview config file")}const te=await Q.json(),ee=Array.isArray(te.categories)?te.categories:[];m({...te,categories:ee}),c(new Set(ee.map(A=>A.id)))}catch(Q){b({type:"error",text:Q.message||"Failed to read config file"}),u(null)}}},F=async()=>{if(!(!w||d.size===0)){x(!0),b(null);try{const v=Array.from(d).join(","),O=await we(me(`/api/config/import?categories=${v}`),{method:"POST",headers:{"Content-Type":"application/zip"},body:await w.arrayBuffer()}),R=await O.json();if(!O.ok)throw new Error(R.error||"Import failed");b({type:"success",text:R.message||s("config:data.importSuccess")}),u(null),m(null),c(new Set)}catch(v){b({type:"error",text:v.message||"Import failed"})}finally{x(!1)}}},M=()=>{u(null),m(null),c(new Set),b(null)};return e.jsxs("div",{className:"data-section",children:[j&&e.jsx("div",{className:`data-message data-message-${j.type}`,children:j.text}),e.jsxs("div",{className:"data-subsection",children:[e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-title",children:"Hourly Backups"}),e.jsx(ct,{checked:!!(h!=null&&h.enabled),disabled:L||!h,onChange:V})]}),e.jsxs("div",{className:"data-backup-info",children:[h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:["Saves a compressed snapshot of your data every hour to"," ",e.jsx("code",{children:h.backupDir}),". Identical snapshots are skipped. Keeps the 8 newest plus one from each of the 2 most recent prior days."]}),!h.scriptExists&&e.jsxs("div",{style:{marginTop:6,color:"var(--dracula-red, #ff5555)"},children:["Backup script not found at ",e.jsx("code",{children:h.scriptPath})]}),h.lastRunAt&&e.jsxs("div",{style:{marginTop:6},children:["Last run: ",new Date(h.lastRunAt).toLocaleString(),h.lastRunOk===!0&&" — ok",h.lastRunOk===!1&&h.lastRunError&&e.jsxs("span",{style:{color:"var(--dracula-red, #ff5555)"},children:[" — ",h.lastRunError]})]})]}):e.jsx("div",{children:"Loading backup status…"}),C&&e.jsx("div",{className:"data-message data-message-error",style:{marginTop:6},children:C})]})]}),e.jsxs("div",{className:"data-subsection",children:[e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-title",children:s("config:data.exportData")}),e.jsxs("div",{className:"data-select-controls",children:[e.jsx("button",{className:"data-select-btn",onClick:k,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:T,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:a.map(v=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:o.has(v.id),onChange:()=>B(v.id)}),e.jsx("span",{className:"data-category-name",children:v.name})]},v.id))}),e.jsx("button",{className:"data-action-btn export",onClick:ce,disabled:n||o.size===0,children:n?s("config:data.exporting"):s("config:data.exportCount",{count:o.size})})]}),e.jsxs("div",{className:"data-subsection",children:[e.jsx("div",{className:"data-subsection-header",children:e.jsx("span",{className:"data-subsection-title",children:s("config:data.importData")})}),w?g?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"data-import-info",children:[e.jsx("div",{className:"data-import-file",children:w.name}),e.jsxs("div",{className:"data-import-date",children:[s("config:data.exported"),": ",new Date(g.exportedAt).toLocaleDateString()]})]}),e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-subtitle",children:s("config:data.selectToImport")}),e.jsxs("div",{className:"data-select-controls",children:[e.jsx("button",{className:"data-select-btn",onClick:H,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:Z,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:g.categories.map(v=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:d.has(v.id),onChange:()=>K(v.id)}),e.jsx("span",{className:"data-category-name",children:v.name}),v.fileCount&&e.jsxs("span",{className:"data-category-count",children:["(",v.fileCount," ",s("config:data.files"),")"]})]},v.id))}),e.jsxs("div",{className:"data-import-actions",children:[e.jsx("button",{className:"data-action-btn cancel",onClick:M,children:s("common:buttons.cancel")}),e.jsx("button",{className:"data-action-btn import",onClick:F,disabled:y||d.size===0,children:y?s("config:data.importing"):s("config:data.importCount",{count:d.size})})]})]}):e.jsx("div",{className:"data-loading",children:s("config:data.readingFile")}):e.jsxs("label",{className:"data-file-input",children:[e.jsx("input",{type:"file",accept:".zip",onChange:N,style:{display:"none"}}),e.jsx("span",{className:"data-file-input-label",children:s("config:data.selectFile")})]})]})]})}async function dt(){const s=await we(`${J()}/api/system/install-info`);if(!s.ok)throw new Error(`Failed to fetch install info: ${s.statusText}`);return s.json()}function ut(s,a){const t=new AbortController;return(async()=>{try{const o=await fetch(is(`${J()}/api/system/self-update`),{method:"POST",signal:t.signal,headers:{Accept:"text/event-stream"}});if(!o.ok||!o.body){const n=await o.text().catch(()=>"");let p=null;try{p=JSON.parse(n)}catch{}const y=p&&typeof p=="object"&&"error"in p&&typeof p.error=="string"?p.error:`Self-update failed: ${o.status} ${o.statusText}`;s({type:"error",message:y}),a(new Error(y));return}const r=o.body.getReader(),d=new TextDecoder("utf-8");let c="";for(;;){const{value:n,done:p}=await r.read();if(p)break;c+=d.decode(n,{stream:!0});let y=c.indexOf(`
2
-
3
- `);for(;y!==-1;){const x=c.slice(0,y);c=c.slice(y+2);const w=x.split(`
4
- `);let u="message",g="";for(const m of w)m.startsWith(":")||(m.startsWith("event:")?u=m.slice(6).trim():m.startsWith("data:")&&(g+=(g?`
5
- `:"")+m.slice(5).trim()));if(g)try{const m=JSON.parse(g);s({type:u,...m})}catch{}y=c.indexOf(`
6
-
7
- `)}}a()}catch(o){if(o.name==="AbortError"){a();return}a(o)}})(),()=>t.abort()}function pt(){const[s,a]=l.useState(()=>xs()),t=o=>{a(o);const r=js(o);ws(r)};return e.jsx("div",{className:"theme-selector",children:e.jsx("div",{className:"theme-selector-grid",children:bs.map(o=>e.jsxs("button",{className:`theme-option ${s===o.id?"active":""}`,onClick:()=>t(o.id),title:o.description,children:[e.jsx("div",{className:"theme-preview",children:e.jsxs("div",{className:"theme-preview-bg",style:{backgroundColor:o.colors.bgPrimary},children:[e.jsx("div",{className:"theme-preview-accent",style:{backgroundColor:o.colors.accentBlue}}),e.jsx("div",{className:"theme-preview-claude",style:{backgroundColor:o.colors.accentClaude}})]})}),e.jsx("span",{className:"theme-name",children:o.name})]},o.id))})})}function ht(){const{t:s}=Y(["config"]),[a,t]=l.useState(null),[o,r]=l.useState("idle"),[d,c]=l.useState(""),[n,p]=l.useState(null),[y,x]=l.useState(null),w=l.useRef(null),u=l.useRef(null),g=l.useCallback(async()=>{try{const S=await dt();t(S)}catch{t(null)}},[]);l.useEffect(()=>{g()},[g]),l.useEffect(()=>{u.current&&(u.current.scrollTop=u.current.scrollHeight)},[d]);const m=l.useCallback(()=>{r("confirm")},[]),j=l.useCallback(()=>{r("idle")},[]),b=l.useCallback(()=>{r("running"),c(""),p(null),x(null);const S=ut(L=>{switch(L.type){case"start":c(P=>P+`${L.message}
8
- `);break;case"stdout":c(P=>P+L.chunk);break;case"stderr":c(P=>P+L.chunk);break;case"error":p(L.message),L.suggestedManualCommand&&c(P=>P+`
9
-
10
- Suggested manual command: ${L.suggestedManualCommand}
11
- `);break;case"done":L.success?(x(L.newVersion),r("success")):r("failed");break}},L=>{L&&p(P=>P??L.message),r(P=>P==="running"?n?"failed":"success":P)});w.current=S},[n]),h=l.useCallback(()=>{var S;(S=w.current)==null||S.call(w),w.current=null,r("idle"),g()},[g]);return a?a.isGlobalInstall?a.autoUpdateSupported?!a.updateAvailable&&o==="idle"?null:e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:s("config:about.autoUpdateTitle")}),o==="idle"&&a.updateAvailable&&e.jsxs("div",{className:"about-autoupdate-row",children:[e.jsxs("span",{className:"about-autoupdate-versions",children:[e.jsx("span",{className:"about-autoupdate-current",children:a.currentVersion}),e.jsx("span",{className:"about-autoupdate-arrow",children:"→"}),e.jsx("span",{className:"about-autoupdate-latest",children:a.latestVersion})]}),e.jsx("button",{className:"about-update-btn download",onClick:m,children:s("config:about.autoUpdateButton")})]}),o==="confirm"&&e.jsxs("div",{className:"about-autoupdate-confirm",children:[e.jsx("div",{className:"about-autoupdate-confirm-title",children:s("config:about.autoUpdateConfirmTitle")}),e.jsx("div",{className:"about-autoupdate-confirm-body",children:s("config:about.autoUpdateConfirmBody")}),e.jsxs("div",{className:"about-autoupdate-confirm-actions",children:[e.jsx("button",{className:"about-update-btn changelog",onClick:j,children:s("config:about.autoUpdateCancel")}),e.jsx("button",{className:"about-update-btn download",onClick:b,children:s("config:about.autoUpdateConfirm")})]})]}),(o==="running"||o==="success"||o==="failed")&&e.jsxs("div",{className:"about-autoupdate-stream",children:[e.jsxs("div",{className:"about-autoupdate-stream-title",children:[o==="running"&&s("config:about.autoUpdateRunning"),o==="success"&&s("config:about.autoUpdateSuccess"),o==="failed"&&s("config:about.autoUpdateFailed")]}),e.jsx("pre",{ref:u,className:"about-autoupdate-output",children:d||"..."}),o==="success"&&e.jsxs("div",{className:"about-autoupdate-success-hint",children:[y&&e.jsxs("div",{className:"about-autoupdate-newversion",children:["v",y]}),e.jsx("div",{children:s("config:about.autoUpdateRestartHint")})]}),o==="failed"&&n&&e.jsx("div",{className:"about-update-error",children:n}),(o==="success"||o==="failed")&&e.jsx("div",{className:"about-autoupdate-stream-actions",children:e.jsx("button",{className:"about-update-btn changelog",onClick:h,children:s("config:about.autoUpdateClose")})})]})]}):e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:s("config:about.autoUpdateTitle")}),e.jsx("div",{className:"about-autoupdate-devnote",children:s("config:about.autoUpdatePackageManagerNotice",{pm:a.packageManager})}),a.suggestedManualCommand&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"about-autoupdate-manualhint",children:s("config:about.autoUpdateManualCommand")}),e.jsx("pre",{className:"about-autoupdate-manualcmd",children:a.suggestedManualCommand})]})]}):e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:s("config:about.autoUpdateTitle")}),e.jsx("div",{className:"about-autoupdate-devnote",children:s("config:about.autoUpdateDevMode")})]}):null}function mt(){const{t:s}=Y(["config"]),{updateAvailable:a,updateInfo:t,recentReleases:o,isChecking:r,error:d,currentVersion:c,isAndroid:n,checkForUpdate:p,downloadAndInstall:y,openReleasePage:x}=Us(),w=g=>g?`${(g/(1024*1024)).toFixed(1)} MB`:"",u=g=>new Date(g).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"});return e.jsxs("div",{className:"about-section",children:[e.jsxs("div",{className:"about-logo",children:[e.jsx("span",{className:"about-logo-icon",children:e.jsx($,{name:"waves",size:24})}),e.jsx("span",{className:"about-logo-text",children:"Tide Commander"})]}),e.jsxs("div",{className:"about-version",children:[e.jsx("span",{className:"about-version-label",children:s("config:about.version")}),e.jsxs("div",{className:"about-version-info",children:[e.jsx("span",{className:"about-version-value",children:c}),a&&t?e.jsx("span",{className:"about-version-update-badge",onClick:x,title:`Update available: ${t.version}`,children:t.version}):e.jsxs("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"about-version-status",children:["(",s("config:about.updated"),")"]})]})]}),e.jsx(ht,{}),e.jsxs("div",{className:"about-update",children:[a&&t?e.jsxs("div",{className:"about-update-available",children:[e.jsxs("div",{className:"about-update-header",children:[e.jsx("span",{className:"about-update-badge",children:s("config:about.updateAvailable")}),e.jsx("span",{className:"about-update-version",children:t.version})]}),t.apkSize&&e.jsxs("div",{className:"about-update-size",children:[s("config:about.sizeLabel"),": ",w(t.apkSize)]}),d&&e.jsx("div",{className:"about-update-error",children:d}),e.jsxs("div",{className:"about-update-actions",children:[e.jsx("button",{className:"about-update-btn changelog",onClick:x,children:s("config:about.changelog")}),n&&t.apkUrl?e.jsx("button",{className:"about-update-btn download",onClick:y,children:s("config:about.downloadAPK")}):e.jsx("button",{className:"about-update-btn download",onClick:x,children:s("config:about.viewRelease")})]})]}):e.jsxs("div",{className:"about-update-check",children:[e.jsx("span",{className:"about-update-status",children:s(r?"config:about.checkingUpdates":"config:about.upToDate")}),e.jsx("button",{className:"about-update-btn check",onClick:()=>p(!0),disabled:r,children:r?"...":s("config:about.check")})]}),o.length>0&&e.jsxs("div",{className:"about-releases",children:[e.jsx("div",{className:"about-releases-title",children:s("config:about.recentReleases")}),e.jsx("div",{className:"about-releases-list",children:o.map(g=>e.jsxs("a",{href:g.releaseUrl,target:"_blank",rel:"noopener noreferrer",className:`about-release-item ${g.version===`v${c}`||g.version===c?"current":""}`,children:[e.jsx("span",{className:"about-release-version",children:g.version}),e.jsx("span",{className:"about-release-date",children:u(g.publishedAt)})]},g.version))})]})]}),e.jsx("div",{className:"about-description",children:s("config:about.tagline")}),e.jsxs("div",{className:"about-principles",children:[e.jsx("div",{className:"about-principles-title",children:s("config:about.corePrinciples")}),e.jsxs("ul",{className:"about-principles-list",children:[e.jsx("li",{children:s("config:about.principle1")}),e.jsx("li",{children:s("config:about.principle2")}),e.jsx("li",{children:s("config:about.principle3")}),e.jsx("li",{children:s("config:about.principle4")})]})]}),e.jsx("div",{className:"about-links",children:e.jsxs("a",{href:"https://github.com/deivid11/tide-commander",target:"_blank",rel:"noopener noreferrer",className:"about-link",children:[e.jsx("span",{className:"about-link-icon",children:e.jsx($,{name:"package",size:14})}),e.jsx("span",{children:s("config:about.repository")})]})}),e.jsxs("div",{className:"about-credits",children:[e.jsx("div",{className:"about-credits-title",children:s("config:about.specialThanks")}),e.jsxs("div",{className:"about-credit-item",children:[e.jsx("a",{href:"https://kenney.nl",target:"_blank",rel:"noopener noreferrer",className:"about-credit-link",children:"Kenney.nl"}),e.jsx("span",{className:"about-credit-desc",children:s("config:about.kenneyCredit")})]}),e.jsxs("div",{className:"about-credit-item",children:[e.jsx("a",{href:"https://claude.ai/code",target:"_blank",rel:"noopener noreferrer",className:"about-credit-link",children:"Claude Code"}),e.jsx("span",{className:"about-credit-desc",children:s("config:about.claudeCodeCredit")})]})]})]})}const gt={gmail:"✉️",slack:"💬",jira:"📋","google-calendar":"📅",docx:"📄",whatsapp:"📱"};function ft({onOpenModal:s}){const[a,t]=l.useState([]),[o,r]=l.useState(!0),d=l.useCallback(async()=>{try{const c=await we(me("/api/integrations"));if(!c.ok)return;const n=await c.json();t(n)}catch{}finally{r(!1)}},[]);return l.useEffect(()=>{d()},[d]),o?e.jsx("div",{style:{color:"var(--text-secondary, #a6adc8)",fontSize:12,padding:"4px 0"},children:"Loading..."}):a.length===0?e.jsx("div",{style:{color:"var(--text-secondary, #a6adc8)",fontSize:12,padding:"4px 0"},children:"No integrations available."}):e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[a.map(c=>{const n=gt[c.id]||"🔌",p=!!c.status.error,y=c.status.connected,x=p?"#f38ba8":y?"#a6e3a1":"#fab387",w=p?"Error":y?"Connected":"Setup Required",u=p?"✗":y?"✓":"⚠";return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"3px 8px",borderRadius:4,background:"var(--surface-1, #181825)",border:"1px solid var(--border, #313244)",fontSize:12,minHeight:26},children:[e.jsx("span",{style:{fontSize:13,flexShrink:0},children:n}),e.jsx("span",{style:{flex:1,minWidth:0,color:"var(--text-primary, #cdd6f4)",fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:c.name}),e.jsx("span",{style:{color:x,fontSize:10,fontWeight:500,whiteSpace:"nowrap"},title:w,children:u}),e.jsx("button",{onClick:()=>s(c.id),title:`Configure ${c.name}`,style:{background:"none",border:"none",cursor:"pointer",padding:"1px 3px",fontSize:12,color:"var(--text-secondary, #a6adc8)",borderRadius:3,flexShrink:0,lineHeight:1},onMouseEnter:g=>{g.target.style.color="var(--text-primary, #cdd6f4)"},onMouseLeave:g=>{g.target.style.color="var(--text-secondary, #a6adc8)"},children:"⚙️"})]},c.id)}),e.jsx("button",{onClick:()=>s(),style:{background:"none",border:"1px dashed var(--border, #313244)",borderRadius:4,padding:"3px 8px",cursor:"pointer",color:"var(--text-secondary, #a6adc8)",fontSize:11,textAlign:"center",marginTop:2},onMouseEnter:c=>{c.target.style.borderColor="var(--accent, #89b4fa)",c.target.style.color="var(--accent, #89b4fa)"},onMouseLeave:c=>{c.target.style.borderColor="var(--border, #313244)",c.target.style.color="var(--text-secondary, #a6adc8)"},children:"Manage All Integrations"})]})}function xt({isOpen:s,onClose:a}){const{t}=Y(["config"]),[o,r]=l.useState(""),[d,c]=l.useState(""),[n,p]=l.useState(!0),[y,x]=l.useState(null),[w,u]=l.useState(null),[g,m]=l.useState(!1),[j,b]=l.useState(!1),[h,S]=l.useState(!1);l.useEffect(()=>{s&&L()},[s]);const L=async()=>{try{p(!0),x(null),u(null);const T=await Zs();r(T),c(T),m(!1)}catch(T){x(T instanceof Error?T.message:"Failed to load system prompt")}finally{p(!1)}},P=T=>{const H=T.target.value;r(H),m(H!==d),x(null),u(null)},C=async()=>{try{x(null),u(null),await Xs(o),c(o),m(!1),u(t("config:systemPrompt.saved"))}catch(T){x(T instanceof Error?T.message:"Failed to save system prompt")}},_=()=>{b(!0)},V=async()=>{try{x(null),u(null),await Qs(),r(""),c(""),m(!1),u(t("config:systemPrompt.cleared"))}catch(T){x(T instanceof Error?T.message:"Failed to clear system prompt")}},B=()=>{r(d),m(!1),x(null),u(null)},K=()=>{if(g){S(!0);return}a()},k=T=>{T.key==="Escape"&&(T.preventDefault(),K())};return s?e.jsxs(Se,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:K,children:e.jsxs("div",{className:"system-prompt-modal",onClick:T=>T.stopPropagation(),onKeyDown:k,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:t("config:systemPrompt.title")}),e.jsx("button",{className:"modal-close",onClick:K,"aria-label":"Close",children:e.jsx($,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:n?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:"Loading system prompt..."})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:t("config:systemPrompt.description")}),y&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:"warn",size:14})}),y]}),w&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:"check",size:14})}),w]}),e.jsxs("div",{className:"editor-wrapper",children:[e.jsxs("div",{className:"editor-header",children:[e.jsx("label",{htmlFor:"prompt-input",className:"editor-label",children:t("config:systemPrompt.editPrompt")}),e.jsxs("span",{className:"char-count",children:[o.length," ",t("config:systemPrompt.characters")]})]}),e.jsx("textarea",{id:"prompt-input",className:"prompt-editor",value:o,onChange:P,placeholder:t("config:systemPrompt.placeholder"),rows:18,autoFocus:!0}),e.jsx("div",{className:"editor-hint",children:t("config:systemPrompt.hint")})]})]})}),e.jsxs("div",{className:"modal-footer",children:[e.jsx("div",{className:"footer-buttons-left",children:e.jsx("button",{className:"btn btn-danger",onClick:_,disabled:!o||n,children:t("config:systemPrompt.clear")})}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:K,children:"Close"}),e.jsx("button",{className:"btn btn-secondary",onClick:B,disabled:!g||n,children:t("config:systemPrompt.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:C,disabled:!g||n,children:t("config:systemPrompt.save")})]})]})]})}),e.jsx(ge,{isOpen:j,title:t("config:systemPrompt.clear"),message:t("config:systemPrompt.confirmClear"),confirmLabel:t("config:systemPrompt.clear"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{V()},onClose:()=>b(!1)}),e.jsx(ge,{isOpen:h,title:"Unsaved Changes",message:"You have unsaved changes. Close anyway?",confirmLabel:"Close anyway",cancelLabel:"Keep editing",variant:"danger",onConfirm:a,onClose:()=>S(!1)})]}):null}const Xe={enabled:!1,baseUrl:"",defaultSessionId:"",webhookVerifyToken:"",showIncomingToasts:!0},bt=2500,jt=12e4;function Qe(s){return{enabled:s.enabled??!1,baseUrl:s.baseUrl??"",defaultSessionId:s.defaultSessionId??"",webhookVerifyToken:s.webhookVerifyToken??"",showIncomingToasts:s.showIncomingToasts??!0}}function wt(s,a){return s.enabled===a.enabled&&s.baseUrl===a.baseUrl&&s.defaultSessionId===a.defaultSessionId&&s.webhookVerifyToken===a.webhookVerifyToken&&s.showIncomingToasts===a.showIncomingToasts}function yt({isOpen:s,onClose:a}){const{t}=Y(["config"]),[o,r]=l.useState(Xe),[d,c]=l.useState(Xe),[n,p]=l.useState(!1),[y,x]=l.useState([]),[w,u]=l.useState(!0),[g,m]=l.useState(null),[j,b]=l.useState(null),[h,S]=l.useState(""),[L,P]=l.useState(!1),[C,_]=l.useState(""),[V,B]=l.useState(null),[K,k]=l.useState(null),[T,H]=l.useState(null),Z=l.useRef(null),ce=l.useRef(0),[N,F]=l.useState(""),[M,v]=l.useState(""),[O,R]=l.useState(null),[Q,te]=l.useState(!1),[ee,A]=l.useState(!1),[q,ne]=l.useState(!1),[re,ae]=l.useState(!1),[pe,ye]=l.useState(null),Ne=!wt(o,d),ie=l.useCallback(()=>{Z.current&&(clearTimeout(Z.current),Z.current=null)},[]),D=l.useCallback(async()=>{try{u(!0),m(null),b(null);const[f,z]=await Promise.all([os(),ys()]),oe=Qe(f);if(r(oe),c(oe),p(!!z.configured),z.configured)try{const fe=await Me();x(Array.isArray(fe)?fe:[])}catch{x([])}else x([])}catch(f){m(f instanceof Error?f.message:t("config:whatsapp.errors.loadFailed"))}finally{u(!1)}},[t]),he=l.useCallback(async()=>{try{const f=await Me();x(Array.isArray(f)?f:[])}catch{}},[]);l.useEffect(()=>(s?D():(ie(),B(null),k(null),H(null),S(""),P(!1),R(null)),()=>{ie()}),[s,D,ie]);const se=(f,z)=>{r(oe=>({...oe,[f]:z})),m(null),b(null)},Le=async()=>{try{m(null),b(null);const f=await Cs({enabled:o.enabled,baseUrl:o.baseUrl.trim(),defaultSessionId:o.defaultSessionId.trim(),webhookVerifyToken:o.webhookVerifyToken,showIncomingToasts:o.showIncomingToasts});window.dispatchEvent(new CustomEvent("tide:whatsapp-config-updated"));const z=Qe(f);r(z),c(z),b(t("config:whatsapp.saved"))}catch(f){m(f instanceof Error?f.message:t("config:whatsapp.errors.saveFailed"))}},Ce=()=>{r(d),m(null),b(null)},be=()=>{if(Ne){A(!0);return}a()},De=f=>{f.key==="Escape"&&(f.preventDefault(),be())},Te=async()=>{const f=h.trim();if(f)try{m(null),b(null),await vs(f),S(""),P(!1),p(!0),b(t("config:whatsapp.apiKeySaved"))}catch(z){m(z instanceof Error?z.message:t("config:whatsapp.errors.apiKeySaveFailed"))}},Oe=()=>{ne(!0)},Ae=async()=>{try{m(null),b(null),await Ts(),p(!1),b(t("config:whatsapp.apiKeyCleared"))}catch(f){m(f instanceof Error?f.message:t("config:whatsapp.errors.apiKeyClearFailed"))}},_e=l.useCallback(async f=>{if(Date.now()>ce.current){H(t("config:whatsapp.pairingTimeout")),B(null),k(null),ie(),he();return}try{const z=await Ns(f);if(z.status&&["connected","paired","open","ready"].includes(z.status.toLowerCase())){H(t("config:whatsapp.pairingSuccess")),B(null),k(null),ie(),he();return}const fe=z.qrUrl??z.qr??null;fe&&k(fe)}catch(z){H(z instanceof Error?z.message:t("config:whatsapp.errors.qrFetchFailed"))}Z.current=setTimeout(()=>{_e(f)},bt)},[he,ie,t]),Ee=async()=>{const f=C.trim();if(f)try{m(null),b(null),H(null),k(null),ie(),await ks(f),_(""),B(f),ce.current=Date.now()+jt,_e(f),he()}catch(z){m(z instanceof Error?z.message:t("config:whatsapp.errors.sessionCreateFailed"))}},ve=()=>{ie(),B(null),k(null),H(null)},Fe=f=>{ye(f),ae(!0)},Ie=async()=>{if(pe)try{m(null),b(null),await As(pe),V===pe&&ve(),he(),b(t("config:whatsapp.sessionDeleted"))}catch(f){m(f instanceof Error?f.message:t("config:whatsapp.errors.sessionDeleteFailed"))}finally{ye(null)}},ue=async()=>{const f=N.trim(),z=M.trim();if(!(!f||!z))try{te(!0),R(null);const oe=o.defaultSessionId.trim()||void 0;await Ss(f,z,oe),R({kind:"success",text:t("config:whatsapp.testSent")})}catch(oe){R({kind:"error",text:oe instanceof Error?oe.message:t("config:whatsapp.errors.testSendFailed")})}finally{te(!1)}};return s?e.jsxs(Se,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:be,children:e.jsxs("div",{className:"whatsapp-config-modal",onClick:f=>f.stopPropagation(),onKeyDown:De,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:t("config:whatsapp.title")}),e.jsx("button",{className:"modal-close",onClick:be,"aria-label":"Close",children:e.jsx($,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:w?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:t("config:whatsapp.loading")})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:t("config:whatsapp.description")}),g&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:"warn",size:14})}),g]}),j&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:"check",size:14})}),j]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:t("config:whatsapp.sections.general")}),e.jsxs("div",{className:"wa-field wa-field-row",children:[e.jsx("label",{htmlFor:"wa-enabled",className:"wa-label",children:t("config:whatsapp.enabled")}),e.jsxs("label",{className:"wa-toggle",children:[e.jsx("input",{id:"wa-enabled",type:"checkbox",checked:o.enabled,onChange:f=>se("enabled",f.target.checked)}),e.jsx("span",{className:"wa-toggle-track",children:e.jsx("span",{className:"wa-toggle-thumb"})})]})]}),e.jsxs("div",{className:"wa-field wa-field-row",children:[e.jsx("label",{htmlFor:"wa-show-toasts",className:"wa-label",children:t("config:whatsapp.showIncomingToasts")}),e.jsxs("label",{className:"wa-toggle",children:[e.jsx("input",{id:"wa-show-toasts",type:"checkbox",checked:o.showIncomingToasts,onChange:f=>se("showIncomingToasts",f.target.checked)}),e.jsx("span",{className:"wa-toggle-track",children:e.jsx("span",{className:"wa-toggle-thumb"})})]})]}),e.jsx("span",{className:"wa-hint",children:t("config:whatsapp.showIncomingToastsHelp")}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-base-url",className:"wa-label",children:t("config:whatsapp.baseUrl")}),e.jsx("input",{id:"wa-base-url",type:"text",className:"wa-input",placeholder:"http://localhost:3007",value:o.baseUrl,onChange:f=>se("baseUrl",f.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-default-session",className:"wa-label",children:t("config:whatsapp.defaultSessionId")}),e.jsx("input",{id:"wa-default-session",type:"text",className:"wa-input",placeholder:t("config:whatsapp.defaultSessionIdPlaceholder"),value:o.defaultSessionId,onChange:f=>se("defaultSessionId",f.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-webhook-token",className:"wa-label",children:t("config:whatsapp.webhookVerifyToken")}),e.jsx("input",{id:"wa-webhook-token",type:"text",className:"wa-input",placeholder:t("config:whatsapp.webhookVerifyTokenPlaceholder"),value:o.webhookVerifyToken,onChange:f=>se("webhookVerifyToken",f.target.value)})]})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:t("config:whatsapp.sections.apiKey")}),e.jsx("div",{className:"wa-key-status",children:n?e.jsxs("span",{className:"wa-status wa-status-ok",children:[e.jsx($,{name:"check",size:12})," ",t("config:whatsapp.configured")]}):e.jsxs("span",{className:"wa-status wa-status-warn",children:[e.jsx($,{name:"warn",size:12})," ",t("config:whatsapp.notConfigured")]})}),e.jsxs("div",{className:"wa-field wa-field-inline",children:[e.jsx("input",{type:L?"text":"password",className:"wa-input",placeholder:t("config:whatsapp.apiKeyPlaceholder"),value:h,onChange:f=>S(f.target.value)}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>P(f=>!f),title:t(L?"config:whatsapp.hideKey":"config:whatsapp.showKey"),children:e.jsx($,{name:L?"eye-closed":"eye",size:14})}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Te,disabled:!h.trim(),children:t("config:whatsapp.saveKey")}),e.jsx("button",{type:"button",className:"btn btn-danger",onClick:Oe,disabled:!n,children:t("config:whatsapp.clearKey")})]}),e.jsx("span",{className:"wa-hint",children:t("config:whatsapp.apiKeyHint")})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:t("config:whatsapp.sections.sessions")}),e.jsx("div",{className:"wa-sessions-list",children:!Array.isArray(y)||y.length===0?e.jsx("div",{className:"wa-empty",children:t("config:whatsapp.noSessions")}):y.map(f=>e.jsxs("div",{className:"wa-session-row",children:[e.jsxs("div",{className:"wa-session-info",children:[e.jsx("span",{className:"wa-session-id",children:f.id}),e.jsx("span",{className:`wa-session-status status-${(f.status??"unknown").toLowerCase()}`,children:f.status||"—"}),f.pairedNumber&&e.jsx("span",{className:"wa-session-paired",children:f.pairedNumber})]}),e.jsx("button",{type:"button",className:"btn btn-danger btn-sm",onClick:()=>Fe(f.id),children:t("config:whatsapp.deleteSession")})]},f.id))}),e.jsxs("div",{className:"wa-field wa-field-inline",children:[e.jsx("input",{type:"text",className:"wa-input",placeholder:t("config:whatsapp.addSessionPlaceholder"),value:C,onChange:f=>_(f.target.value),onKeyDown:f=>{f.key==="Enter"&&Ee()}}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Ee,disabled:!C.trim()||V!==null,children:t("config:whatsapp.addSession")})]}),V&&e.jsxs("div",{className:"wa-qr-panel",children:[e.jsxs("div",{className:"wa-qr-header",children:[e.jsx("span",{children:t("config:whatsapp.qrPrompt",{id:V})}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ve,children:t("config:whatsapp.cancelPairing")})]}),K?e.jsx("div",{className:"wa-qr-image",children:e.jsx("img",{src:K,alt:"WhatsApp pairing QR code"})}):e.jsxs("div",{className:"wa-qr-loading",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:t("config:whatsapp.waitingForQr")})]})]}),T&&!V&&e.jsx("div",{className:"wa-pairing-message",children:T})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:t("config:whatsapp.sections.testMessage")}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-test-to",className:"wa-label",children:t("config:whatsapp.testTo")}),e.jsx("input",{id:"wa-test-to",type:"text",className:"wa-input",placeholder:t("config:whatsapp.testToPlaceholder"),value:N,onChange:f=>F(f.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-test-message",className:"wa-label",children:t("config:whatsapp.testMessageBody")}),e.jsx("textarea",{id:"wa-test-message",className:"wa-textarea",rows:4,placeholder:t("config:whatsapp.testMessageBodyPlaceholder"),value:M,onChange:f=>v(f.target.value)})]}),e.jsx("div",{className:"wa-field-inline wa-field-end",children:e.jsx("button",{type:"button",className:"btn btn-primary",onClick:ue,disabled:!N.trim()||!M.trim()||Q,children:t(Q?"config:whatsapp.sending":"config:whatsapp.sendTest")})}),O&&e.jsxs("div",{className:`alert ${O.kind==="success"?"alert-success":"alert-error"}`,children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:O.kind==="success"?"check":"warn",size:14})}),O.text]})]})]})}),e.jsxs("div",{className:"modal-footer",children:[e.jsx("div",{className:"footer-buttons-left"}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:be,children:t("config:whatsapp.close")}),e.jsx("button",{className:"btn btn-secondary",onClick:Ce,disabled:!Ne||w,children:t("config:whatsapp.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:Le,disabled:!Ne||w,children:t("config:whatsapp.save")})]})]})]})}),e.jsx(ge,{isOpen:ee,title:t("config:whatsapp.unsavedTitle"),message:t("config:whatsapp.unsavedMessage"),confirmLabel:t("config:whatsapp.closeAnyway"),cancelLabel:t("config:whatsapp.keepEditing"),variant:"danger",onConfirm:()=>{A(!1),a()},onClose:()=>A(!1)}),e.jsx(ge,{isOpen:q,title:t("config:whatsapp.clearKey"),message:t("config:whatsapp.confirmClearKey"),confirmLabel:t("config:whatsapp.clearKey"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{Ae()},onClose:()=>ne(!1)}),e.jsx(ge,{isOpen:re,title:t("config:whatsapp.deleteSession"),message:t("config:whatsapp.confirmDeleteSession",{id:pe??""}),confirmLabel:t("config:whatsapp.deleteSession"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{Ie()},onClose:()=>{ae(!1),ye(null)}})]}):null}const cs=["messages","statusChanges","taskComplete","errors","planReady","agentSpawned","agentStopped"];function He(s=!1){const a=X(),t={};return a&&(t.Authorization=`Bearer ${a}`),s&&(t["Content-Type"]="application/json"),t}async function We(s,a){try{const t=await s.json();if(t&&typeof t.error=="string")return t.error;if(t&&typeof t.message=="string")return t.message}catch{}return`${a}: ${s.statusText}`}async function Nt(){const s=await fetch(`${J()}/api/whatsapp/notification-config`,{headers:He()});if(!s.ok)throw new Error(await We(s,"Failed to fetch WhatsApp notification config"));return s.json()}async function vt(s){const a=await fetch(`${J()}/api/whatsapp/notification-config`,{method:"PATCH",headers:He(!0),body:JSON.stringify(s)});if(!a.ok)throw new Error(await We(a,"Failed to update WhatsApp notification config"));return a.json()}async function kt(){const s=await fetch(`${J()}/api/whatsapp/notification-config`,{method:"DELETE",headers:He()});if(!s.ok)throw new Error(await We(s,"Failed to reset WhatsApp notification config"));return s.json()}const $e={messages:!0,statusChanges:!0,taskComplete:!0,errors:!0,planReady:!0,agentSpawned:!0,agentStopped:!0},es={filter:{...$e},recipient:""};function St(s,a){if(s.recipient!==a.recipient)return!1;for(const t of cs)if(s.filter[t]!==a.filter[t])return!1;return!0}function Ct({isOpen:s,onClose:a}){const{t}=Y(["config"]),[o,r]=l.useState(es),[d,c]=l.useState(es),[n,p]=l.useState(!0),[y,x]=l.useState(null),[w,u]=l.useState(null),[g,m]=l.useState(!1),[j,b]=l.useState(!1),h=!St(o,d),S=l.useCallback(async()=>{try{p(!0),x(null),u(null);const k=await Nt(),T={filter:{...$e,...k.filter},recipient:k.recipient??""};r(T),c(T)}catch(k){x(k instanceof Error?k.message:t("config:whatsappNotifications.errors.loadFailed"))}finally{p(!1)}},[t]);l.useEffect(()=>{s&&S()},[s,S]);const L=(k,T)=>{r(H=>({...H,filter:{...H.filter,[k]:T}})),x(null),u(null)},P=k=>{r(T=>({...T,recipient:k})),x(null),u(null)},C=async()=>{try{x(null),u(null);const k=await vt({filter:o.filter,recipient:o.recipient.trim()}),T={filter:{...$e,...k.filter},recipient:k.recipient??""};r(T),c(T),u(t("config:whatsappNotifications.saved"))}catch(k){x(k instanceof Error?k.message:t("config:whatsappNotifications.errors.saveFailed"))}},_=()=>{r(d),x(null),u(null)},V=async()=>{try{x(null),u(null);const k=await kt(),T={filter:{...$e,...k.filter},recipient:k.recipient??""};r(T),c(T),u(t("config:whatsappNotifications.resetDone"))}catch(k){x(k instanceof Error?k.message:t("config:whatsappNotifications.errors.resetFailed"))}},B=()=>{if(h){m(!0);return}a()},K=k=>{k.key==="Escape"&&(k.preventDefault(),B())};return s?e.jsxs(Se,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:B,children:e.jsxs("div",{className:"whatsapp-notifications-modal",onClick:k=>k.stopPropagation(),onKeyDown:K,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:t("config:whatsappNotifications.title")}),e.jsx("button",{className:"modal-close",onClick:B,"aria-label":"Close",children:e.jsx($,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:n?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:t("config:whatsappNotifications.loading")})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:t("config:whatsappNotifications.description")}),y&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:"warn",size:14})}),y]}),w&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:"check",size:14})}),w]}),e.jsxs("section",{className:"wan-section",children:[e.jsx("h3",{className:"wan-section-title",children:t("config:whatsappNotifications.sections.recipient")}),e.jsxs("div",{className:"wan-field",children:[e.jsx("label",{htmlFor:"wan-recipient",className:"wan-label",children:t("config:whatsappNotifications.recipientLabel")}),e.jsx("input",{id:"wan-recipient",type:"text",className:"wan-input",placeholder:t("config:whatsappNotifications.recipientPlaceholder"),value:o.recipient,onChange:k=>P(k.target.value)}),e.jsx("span",{className:"wan-hint",children:t("config:whatsappNotifications.recipientHint")})]})]}),e.jsxs("section",{className:"wan-section",children:[e.jsx("h3",{className:"wan-section-title",children:t("config:whatsappNotifications.sections.events")}),e.jsx("p",{className:"wan-section-hint",children:t("config:whatsappNotifications.eventsHint")}),cs.map(k=>e.jsxs("div",{className:"wan-toggle-row",children:[e.jsxs("div",{className:"wan-toggle-info",children:[e.jsx("span",{className:"wan-toggle-title",children:t(`config:whatsappNotifications.events.${k}.title`)}),e.jsx("span",{className:"wan-toggle-help",children:t(`config:whatsappNotifications.events.${k}.help`)})]}),e.jsxs("label",{className:"wan-toggle",children:[e.jsx("input",{type:"checkbox",checked:o.filter[k],onChange:T=>L(k,T.target.checked)}),e.jsx("span",{className:"wan-toggle-track",children:e.jsx("span",{className:"wan-toggle-thumb"})})]})]},k))]})]})}),e.jsxs("div",{className:"modal-footer",children:[e.jsx("div",{className:"footer-buttons-left",children:e.jsx("button",{className:"btn btn-danger",onClick:()=>b(!0),disabled:n,children:t("config:whatsappNotifications.resetToDefaults")})}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:B,children:t("config:whatsappNotifications.close")}),e.jsx("button",{className:"btn btn-secondary",onClick:_,disabled:!h||n,children:t("config:whatsappNotifications.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:C,disabled:!h||n,children:t("config:whatsappNotifications.save")})]})]})]})}),e.jsx(ge,{isOpen:g,title:t("config:whatsappNotifications.unsavedTitle"),message:t("config:whatsappNotifications.unsavedMessage"),confirmLabel:t("config:whatsappNotifications.closeAnyway"),cancelLabel:t("config:whatsappNotifications.keepEditing"),variant:"danger",onConfirm:()=>{m(!1),a()},onClose:()=>m(!1)}),e.jsx(ge,{isOpen:j,title:t("config:whatsappNotifications.resetToDefaults"),message:t("config:whatsappNotifications.confirmReset"),confirmLabel:t("config:whatsappNotifications.resetToDefaults"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{V(),b(!1)},onClose:()=>b(!1)})]}):null}function rs(s){const a=s.replace(/@.*$/,"");return/^\d{10,15}$/.test(a)?a.startsWith("521")&&a.length===13?`+52 1 ${a.slice(3,5)} ${a.slice(5,9)} ${a.slice(9)}`:a.startsWith("52")&&a.length===12?`+52 ${a.slice(2,4)} ${a.slice(4,8)} ${a.slice(8)}`:a.startsWith("1")&&a.length===11?`+1 ${a.slice(1,4)} ${a.slice(4,7)} ${a.slice(7)}`:`+${a}`:s}function Tt(s,a=Date.now()){const t=s*1e3,o=a-t;if(o<0)return ss(t);const r=Math.floor(o/6e4);if(r<1)return"now";if(r<60)return`${r}m`;const d=Math.floor(r/60);if(d<24)return`${d}h`;const c=Math.floor(d/24);return c===1?"yesterday":c<7?`${c}d`:ss(t)}function ss(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function At(s){const a=s*1e3;return new Date(a).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}function ds(s){switch(s){case"image":return"📷";case"audio":return"🎤";case"video":return"📹";case"document":return"📎";case"location":return"📍";case"contact":return"👤";case"sticker":return"🌟";case"reaction":return"👍";case"unknown":return"❓";case"text":default:return null}}function _t(s,a){return s.length<=a?s:s.slice(0,Math.max(0,a-1)).trimEnd()+"…"}function Et({chats:s,selectedChatId:a,loading:t,error:o,onSelect:r,onRefresh:d,now:c}){const{t:n}=Y(["config","common"]);return e.jsxs("div",{className:"whatsapp-history-chatlist",children:[e.jsxs("div",{className:"whatsapp-history-chatlist__header",children:[e.jsx("span",{className:"whatsapp-history-chatlist__title",children:n("config:whatsappHistory.chats")}),e.jsx("button",{type:"button",className:"whatsapp-history-chatlist__refresh",onClick:d,disabled:t,"aria-label":n("config:whatsappHistory.refresh"),title:n("config:whatsappHistory.refresh"),children:"⟳"})]}),o&&e.jsx("div",{className:"whatsapp-history-chatlist__error",children:o}),t&&s.length===0&&e.jsxs("div",{className:"whatsapp-history-chatlist__loading",children:[e.jsx("span",{className:"spinner"}),e.jsx("span",{children:n("config:whatsappHistory.loadingChats")})]}),!t&&!o&&s.length===0&&e.jsx("div",{className:"whatsapp-history-chatlist__empty",children:n("config:whatsappHistory.emptyChats")}),e.jsx("ul",{className:"whatsapp-history-chatlist__items",children:s.map(p=>{const y=ds(p.lastMessageType),x=p.lastMessagePreview||`[${p.lastMessageType}]`,w=p.chatId===a,u=rs(p.chatId),g=p.isGroup?p.groupName:p.fromName,m=g||u,j=!!g&&g!==u;return e.jsx("li",{className:`whatsapp-history-chatlist__item ${w?"is-selected":""}`,children:e.jsxs("button",{type:"button",className:"whatsapp-history-chatlist__button",onClick:()=>r(p.chatId),children:[e.jsxs("div",{className:"whatsapp-history-chatlist__row",children:[e.jsx("span",{className:"whatsapp-history-chatlist__name",title:p.chatId,children:m}),e.jsx("span",{className:"whatsapp-history-chatlist__time",children:Tt(p.lastTimestamp,c)})]}),j&&e.jsx("div",{className:"whatsapp-history-chatlist__row whatsapp-history-chatlist__row--jid",children:e.jsx("span",{className:"whatsapp-history-chatlist__jid",children:u})}),e.jsxs("div",{className:"whatsapp-history-chatlist__row whatsapp-history-chatlist__row--secondary",children:[e.jsxs("span",{className:"whatsapp-history-chatlist__preview",children:[p.lastDirection==="outbound"&&e.jsx("span",{className:"whatsapp-history-chatlist__direction",children:"↗ "}),y&&e.jsxs("span",{className:"whatsapp-history-chatlist__preview-icon",children:[y," "]}),_t(x,40)]}),p.unreadCount>0&&e.jsx("span",{className:"whatsapp-history-chatlist__unread",children:p.unreadCount})]})]})},p.chatId)})})]})}function It({message:s}){const a=s.direction==="outbound"?"outbound":"inbound",t=ds(s.messageType),o=(s.body??"").trim(),r=o.length>0,d=r?null:`[${s.messageType}]`;return e.jsx("div",{className:`whatsapp-history-bubble whatsapp-history-bubble--${a}`,children:e.jsxs("div",{className:"whatsapp-history-bubble__inner",children:[t&&e.jsx("span",{className:"whatsapp-history-bubble__type-icon",title:s.messageType,children:t}),r?e.jsx("span",{className:"whatsapp-history-bubble__body",children:o}):e.jsx("span",{className:"whatsapp-history-bubble__placeholder",children:d}),s.audioTranscription&&e.jsxs("span",{className:"whatsapp-history-bubble__transcription",children:["“",s.audioTranscription,"”"]}),s.mediaPath&&e.jsx("a",{className:"whatsapp-history-bubble__media-link",href:s.mediaPath,target:"_blank",rel:"noopener noreferrer",children:s.mediaFilename||"open media"}),e.jsx("span",{className:"whatsapp-history-bubble__time",children:At(s.timestamp)})]})})}const Pt=["all","inbound","outbound"],$t=["all","text","image","audio","video","document","sticker","location","contact","reaction","unknown"];function Lt({direction:s,type:a,onDirectionChange:t,onTypeChange:o,disabled:r}){const{t:d}=Y(["config"]);return e.jsxs("div",{className:"whatsapp-history-filters",children:[e.jsxs("label",{className:"whatsapp-history-filters__field",children:[e.jsx("span",{children:d("config:whatsappHistory.direction")}),e.jsx("select",{value:s,onChange:c=>t(c.target.value),disabled:r,children:Pt.map(c=>e.jsx("option",{value:c,children:d(`config:whatsappHistory.directionValues.${c}`)},c))})]}),e.jsxs("label",{className:"whatsapp-history-filters__field",children:[e.jsx("span",{children:d("config:whatsappHistory.type")}),e.jsx("select",{value:a,onChange:c=>o(c.target.value),disabled:r,children:$t.map(c=>e.jsx("option",{value:c,children:d(`config:whatsappHistory.typeValues.${c}`)},c))})]})]})}const Dt=80;function Ot({chatId:s,messages:a,loading:t,loadingMore:o,error:r,hasMore:d,direction:c,type:n,onDirectionChange:p,onTypeChange:y,onLoadMore:x}){const{t:w}=Y(["config"]),u=l.useRef(null),g=l.useRef(null),m=l.useRef(!1),j=l.useRef(null);l.useEffect(()=>{g.current!==s&&(g.current=s,m.current=!1)},[s]),l.useLayoutEffect(()=>{u.current&&(m.current||a.length!==0&&(u.current.scrollTop=u.current.scrollHeight,m.current=!0))},[s,a.length]),l.useLayoutEffect(()=>{if(!u.current||j.current===null)return;const S=u.current.scrollHeight-j.current;j.current=null,S>0&&(u.current.scrollTop+=S)},[a.length]);const b=l.useCallback(()=>{!d||o||t||(u.current&&(j.current=u.current.scrollHeight),x())},[d,o,t,x]),h=l.useCallback(S=>{if(!m.current)return;S.currentTarget.scrollTop<=Dt&&b()},[b]);return s?e.jsxs("div",{className:"whatsapp-history-messages",children:[e.jsxs("div",{className:"whatsapp-history-messages__header",children:[e.jsx("div",{className:"whatsapp-history-messages__title",children:rs(s)}),e.jsx(Lt,{direction:c,type:n,onDirectionChange:p,onTypeChange:y,disabled:t})]}),e.jsxs("div",{className:"whatsapp-history-messages__scroll",ref:u,onScroll:h,children:[d&&e.jsx("div",{className:"whatsapp-history-messages__load-more-row",children:e.jsx("button",{type:"button",className:"whatsapp-history-messages__load-more",onClick:b,disabled:o||t,children:w(o?"config:whatsappHistory.loadingOlder":"config:whatsappHistory.loadOlder")})}),r&&e.jsx("div",{className:"whatsapp-history-messages__error",children:r}),t&&a.length===0&&e.jsxs("div",{className:"whatsapp-history-messages__loading",children:[e.jsx("span",{className:"spinner"}),e.jsx("span",{children:w("config:whatsappHistory.loadingMessages")})]}),!t&&!r&&a.length===0&&e.jsx("div",{className:"whatsapp-history-messages__empty",children:w("config:whatsappHistory.emptyMessages")}),a.map(S=>e.jsx(It,{message:S},Ft(S)))]})]}):e.jsx("div",{className:"whatsapp-history-messages whatsapp-history-messages--empty",children:e.jsx("div",{className:"whatsapp-history-messages__placeholder",children:w("config:whatsappHistory.selectChat")})})}function Ft(s){return typeof s.id=="number"?`id:${s.id}`:s.messageId?`mid:${s.messageId}`:`t:${s.timestamp}:${s.fromJid}:${(s.body??"").slice(0,16)}`}function us(){const s=X(),a={};return s&&(a.Authorization=`Bearer ${s}`),a}async function ps(s,a){try{const t=await s.json();if(t&&typeof t.error=="string")return t.error;if(t&&typeof t.message=="string")return t.message}catch{}return`${a}: ${s.statusText}`}async function Rt(s){const a=`${J()}/api/whatsapp/chats/${encodeURIComponent(s)}`,t=await fetch(a,{headers:us()});if(!t.ok)throw new Error(await ps(t,"Failed to fetch WhatsApp chats"));return t.json()}async function ts(s,a,t={}){const o=new URLSearchParams;t.cursor&&o.set("cursor",t.cursor),typeof t.limit=="number"&&o.set("limit",String(t.limit)),t.direction&&o.set("direction",t.direction),t.type&&o.set("type",t.type);const r=o.toString(),d=`${J()}/api/whatsapp/chats/${encodeURIComponent(s)}/${encodeURIComponent(a)}/messages${r?`?${r}`:""}`,c=await fetch(d,{headers:us()});if(!c.ok)throw new Error(await ps(c,"Failed to fetch WhatsApp messages"));return c.json()}const Ut=50;function zt({isOpen:s,onClose:a}){const{t}=Y(["config"]),[o,r]=l.useState([]),[d,c]=l.useState(null),[n,p]=l.useState(null),[y,x]=l.useState([]),[w,u]=l.useState(!1),[g,m]=l.useState(null),[j,b]=l.useState(null),[h,S]=l.useState([]),[L,P]=l.useState(!1),[C,_]=l.useState(!1),[V,B]=l.useState(null),[K,k]=l.useState(null),[T,H]=l.useState("all"),[Z,ce]=l.useState("all"),[N,F]=l.useState(()=>Date.now()),M=l.useRef(0);l.useEffect(()=>{if(!s)return;const A=window.setInterval(()=>F(Date.now()),6e4);return()=>window.clearInterval(A)},[s]),l.useEffect(()=>{if(!s)return;let A=!1;return(async()=>{var q;try{p(null);const[ne,re]=await Promise.all([Me().catch(()=>[]),os().catch(()=>null)]);if(A)return;r(ne);const ae=(re==null?void 0:re.defaultSessionId)||((q=ne[0])==null?void 0:q.id)||null;c(pe=>pe??ae)}catch(ne){if(A)return;p(ne instanceof Error?ne.message:String(ne))}})(),()=>{A=!0}},[s]);const v=l.useCallback(async A=>{u(!0),m(null);try{const q=await Rt(A);x(q.chats)}catch(q){m(q instanceof Error?q.message:String(q))}finally{u(!1)}},[]);l.useEffect(()=>{!s||!d||(b(null),S([]),k(null),v(d))},[s,d,v]);const O=l.useMemo(()=>{const A={limit:Ut};return T!=="all"&&(A.direction=T),Z!=="all"&&(A.type=Z),A},[T,Z]),R=l.useCallback(async(A,q,ne)=>{const re=++M.current;P(!0),B(null),S([]),k(null);try{const ae=await ts(A,q,ne);if(re!==M.current)return;S([...ae.messages].reverse()),k(ae.nextCursor)}catch(ae){if(re!==M.current)return;B(ae instanceof Error?ae.message:String(ae))}finally{re===M.current&&P(!1)}},[]);l.useEffect(()=>{!s||!d||!j||R(d,j,O)},[s,d,j,O,R]);const Q=l.useCallback(async()=>{if(!(!d||!j||!K)){_(!0),B(null);try{const A=await ts(d,j,{...O,cursor:K});S(q=>[...[...A.messages].reverse(),...q]),k(A.nextCursor)}catch(A){B(A instanceof Error?A.message:String(A))}finally{_(!1)}}},[d,j,K,O]),te=l.useCallback(()=>{d&&v(d)},[d,v]),ee=l.useCallback(A=>{A.key==="Escape"&&(A.preventDefault(),a())},[a]);return s?e.jsx(Se,{children:e.jsx("div",{className:"modal-overlay visible",onClick:a,children:e.jsxs("div",{className:"whatsapp-history-modal",onClick:A=>A.stopPropagation(),onKeyDown:ee,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:t("config:whatsappHistory.title")}),e.jsx("div",{className:"whatsapp-history-modal__session",children:e.jsxs("label",{children:[e.jsx("span",{children:t("config:whatsappHistory.session")}),e.jsxs("select",{value:d??"",onChange:A=>c(A.target.value||null),disabled:o.length===0,children:[o.length===0&&e.jsx("option",{value:"",children:t("config:whatsappHistory.noSessions")}),o.map(A=>e.jsxs("option",{value:A.id,children:[A.id,A.pairedNumber?` (${A.pairedNumber})`:""]},A.id))]})]})}),e.jsx("button",{className:"modal-close",onClick:a,"aria-label":"Close",children:e.jsx($,{name:"close",size:16})})]}),n&&e.jsx("div",{className:"whatsapp-history-modal__alert",children:n}),e.jsxs("div",{className:"whatsapp-history-modal__body",children:[e.jsx(Et,{chats:y,selectedChatId:j,loading:w,error:g,onSelect:b,onRefresh:te,now:N}),e.jsx(Ot,{chatId:j,messages:h,loading:L,loadingMore:C,error:V,hasMore:K!==null,direction:T,type:Z,onDirectionChange:H,onTypeChange:ce,onLoadMore:Q})]})]})})}):null}function Bt({isOpen:s,onClose:a,onOpenConfig:t,onOpenNotifications:o,onOpenHistory:r}){const{t:d}=Y(["config"]);if(l.useEffect(()=>{if(!s)return;const n=p=>{p.key==="Escape"&&(p.preventDefault(),a())};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[s,a]),!s)return null;const c=n=>{a(),n()};return e.jsx(Se,{children:e.jsx("div",{className:"modal-overlay visible",onClick:a,children:e.jsxs("div",{className:"whatsapp-hub-modal",onClick:n=>n.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("h2",{children:[e.jsx("span",{className:"whatsapp-hub-modal__icon",children:"📱"}),d("config:whatsappHub.title",{defaultValue:"WhatsApp"})]}),e.jsx("button",{className:"modal-close",onClick:a,"aria-label":"Close",children:e.jsx($,{name:"close",size:16})})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{className:"whatsapp-hub-modal__intro",children:d("config:whatsappHub.intro",{defaultValue:"Pick what you want to manage for the WhatsApp integration."})}),e.jsxs("div",{className:"whatsapp-hub-modal__options",children:[e.jsxs("button",{type:"button",className:"whatsapp-hub-modal__option",onClick:()=>c(t),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx($,{name:"gear",size:18})}),e.jsxs("span",{className:"whatsapp-hub-modal__option-text",children:[e.jsx("span",{className:"whatsapp-hub-modal__option-title",children:d("config:whatsappHub.config",{defaultValue:"Integration config"})}),e.jsx("span",{className:"whatsapp-hub-modal__option-desc",children:d("config:whatsappHub.configDesc",{defaultValue:"Server URL, API key, sessions and pairing."})})]})]}),e.jsxs("button",{type:"button",className:"whatsapp-hub-modal__option",onClick:()=>c(o),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx($,{name:"bell",size:18})}),e.jsxs("span",{className:"whatsapp-hub-modal__option-text",children:[e.jsx("span",{className:"whatsapp-hub-modal__option-title",children:d("config:whatsappHub.notifications",{defaultValue:"Notifications"})}),e.jsx("span",{className:"whatsapp-hub-modal__option-desc",children:d("config:whatsappHub.notificationsDesc",{defaultValue:"Which agent events get forwarded and to whom."})})]})]}),e.jsxs("button",{type:"button",className:"whatsapp-hub-modal__option",onClick:()=>c(r),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx($,{name:"hourglass",size:18})}),e.jsxs("span",{className:"whatsapp-hub-modal__option-text",children:[e.jsx("span",{className:"whatsapp-hub-modal__option-title",children:d("config:whatsappHub.history",{defaultValue:"History"})}),e.jsx("span",{className:"whatsapp-hub-modal__option-desc",children:d("config:whatsappHub.historyDesc",{defaultValue:"Browse persisted chats and messages."})})]})]})]})]})]})})})}const Mt=[{value:"auto",label:"Auto",icon:"🕐"},{value:"dawn",label:"Dawn",icon:"🌅"},{value:"day",label:"Day",icon:"☀️"},{value:"dusk",label:"Dusk",icon:"🌇"},{value:"night",label:"Night",icon:"🌙"}],Vt=[{value:"none",label:"Grass",icon:"🌱"},{value:"concrete",label:"Concrete",icon:"🏗️"},{value:"galactic",label:"Galactic",icon:"🌌"},{value:"metal",label:"Metal",icon:"⚙️"},{value:"hex",label:"Hex",icon:"⬡"},{value:"circuit",label:"Circuit",icon:"🔌"},{value:"pokemon-stadium",label:"Pokemon",icon:"🔴"}],Kt=[{value:"static",label:"Static",icon:"🧍"},{value:"idle",label:"Idle",icon:"🚶"},{value:"walk",label:"Walk",icon:"🚶‍♂️"},{value:"sprint",label:"Sprint",icon:"🏃"},{value:"jump",label:"Jump",icon:"⬆️"},{value:"fall",label:"Fall",icon:"⬇️"},{value:"crouch",label:"Crouch",icon:"🧎"},{value:"sit",label:"Sit",icon:"🪑"},{value:"die",label:"Die",icon:"💀"},{value:"emote-yes",label:"Yes",icon:"👍"},{value:"emote-no",label:"No",icon:"👎"}],Ht=[{value:"normal",label:"Normal",icon:"🎨"},{value:"bw",label:"B&W",icon:"⬛"},{value:"sepia",label:"Sepia",icon:"🟤"},{value:"cool",label:"Cool",icon:"❄️"},{value:"warm",label:"Warm",icon:"🔥"},{value:"neon",label:"Neon",icon:"💜"}],Wt=[{key:"showTrees",icon:"🌳",label:"Trees"},{key:"showBushes",icon:"🌿",label:"Bushes"},{key:"showHouse",icon:"🏠",label:"House"},{key:"showLamps",icon:"💡",label:"Lamps"},{key:"showGrass",icon:"🟩",label:"Grass"},{key:"showClouds",icon:"☁️",label:"Clouds"}],qt=[{value:null,label:"Auto",color:"linear-gradient(135deg, #4a90d9 0%, #0a1a2a 100%)"},{value:"#4a90d9",label:"Day Blue",color:"#4a90d9"},{value:"#0a1a2a",label:"Night",color:"#0a1a2a"},{value:"#ff6b35",label:"Sunset",color:"#ff6b35"},{value:"#1a0a2e",label:"Purple",color:"#1a0a2e"},{value:"#2d5a27",label:"Matrix",color:"#2d5a27"},{value:"#8b0000",label:"Blood",color:"#8b0000"},{value:"#000000",label:"Void",color:"#000000"}],Gt={showTrees:"trees",showBushes:"bushes",showHouse:"house",showLamps:"lamps",showGrass:"grass",showClouds:"clouds"},Yt={none:"grass","pokemon-stadium":"pokemon"},Jt={"emote-yes":"yes","emote-no":"no"},Zt={"":"auto","#4a90d9":"dayBlue","#0a1a2a":"night","#ff6b35":"sunset","#1a0a2e":"purple","#2d5a27":"matrix","#8b0000":"blood","#000000":"void"};function le({checked:s,onChange:a}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,onChange:t=>a(t.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function je({options:s,value:a,onChange:t,iconOnly:o=!1}){return e.jsx("div",{className:"chip-selector",children:s.map(r=>e.jsxs("button",{className:`chip ${a===r.value?"active":""}`,onClick:()=>t(r.value),title:r.label,children:[e.jsx("span",{className:"chip-icon",children:r.icon}),!o&&e.jsx("span",{className:"chip-label",children:r.label})]},r.value))})}function I({text:s,query:a}){if(!a.trim())return e.jsx(e.Fragment,{children:s});const t=s.toLowerCase(),o=a.toLowerCase(),r=t.indexOf(o);if(r===-1)return e.jsx(e.Fragment,{children:s});const d=s.slice(0,r),c=s.slice(r,r+a.length),n=s.slice(r+a.length);return e.jsxs(e.Fragment,{children:[d,e.jsx("mark",{className:"search-highlight",children:c}),n]})}const Xt=[{id:"general",title:"General",keywords:["history","hide costs","grid","fps","power saving","performance","limit","editor","external editor","language","idioma","语言","vibration","haptic","intensity","tab title","tmux","process persistence"]},{id:"agentNames",title:"Agent Names",keywords:["agent","names","custom","characters","rename"]},{id:"defaultClass",title:"Default Spawn Class",keywords:["default","class","spawn","agent","scout","builder","random"]},{id:"appearance",title:"Appearance",keywords:["theme","appearance","color","dark","light","style","look"]},{id:"connection",title:"Connection",keywords:["backend","url","auth","token","reconnect","server","api","connect","codex","opencode","binary","path"]},{id:"scene",title:"Scene",keywords:["character","size","indicator","scale","time","dawn","day","dusk","night","auto"]},{id:"terrain",title:"Terrain",keywords:["trees","bushes","house","lamps","grass","clouds","fog","brightness","floor","sky","color","environment","battlefield","size","grid","simple","minimal","dark","clean"]},{id:"modelStyle",title:"Agent Model Style",keywords:["saturation","roughness","metalness","glow","emissive","reflections","wireframe","color mode","material","shader"]},{id:"animations",title:"Animations",keywords:["idle","working","animation","walk","run","sprint","jump","sit","crouch"]},{id:"secrets",title:"Secrets",keywords:["secrets","api","key","password","credentials","env","environment"]},{id:"systemPrompt",title:"System Prompt",keywords:["system","prompt","global","instructions","ai","agent","rules","guidelines"]},{id:"data",title:"Data",keywords:["export","import","backup","restore","save","load","json"]},{id:"integrations",title:"Integrations",keywords:["integrations","integraciones","plugins","gmail","slack","jira","calendar","docx","email","whatsapp","notifications","notification","baileys","history","historial","chat","messages","inbox","config","setup"]},{id:"workflows",title:"Workflows",keywords:["workflow","automation","state machine","editor","actions","transitions","pipeline"]},{id:"triggers",title:"Triggers",keywords:["trigger","event","webhook","cron","slack","email","jira","matching","fire"]},{id:"monitoring",title:"Monitoring",keywords:["monitoring","logs","triggers","events","history","workflow","traces","audit","timeline"]},{id:"experimental",title:"Experimental",keywords:["experimental","2d","view","voice","assistant","speech","tts","text to speech","echo","prompt","duplicate"]},{id:"about",title:"About",keywords:["about","version","update","credits","github","releases"]}],Be=[{value:"auto",label:"Auto",icon:"🌐"},{value:"en",label:"English",icon:"🇺🇸"},{value:"zh-CN",label:"中文",icon:"🇨🇳"},{value:"es",label:"Español",icon:"🇪🇸"},{value:"hi",label:"हिन्दी",icon:"🇮🇳"},{value:"pt",label:"Português",icon:"🇧🇷"},{value:"ru",label:"Русский",icon:"🇷🇺"},{value:"ja",label:"日本語",icon:"🇯🇵"},{value:"de",label:"Deutsch",icon:"🇩🇪"},{value:"fr",label:"Français",icon:"🇫🇷"},{value:"it",label:"Italiano",icon:"🇮🇹"}];function Qt({config:s,onChange:a,searchQuery:t="",onOpenIntegrationsModal:o,onOpenMonitoringModal:r,onOpenWorkflowEditor:d,onOpenTriggerManager:c}){var qe;const{t:n}=Y(["config","common"]),p=Ve(),y=_s(),[x,w]=l.useState(()=>Es(ke.DEFAULT_AGENT_CLASS)||"scout"),[u,g]=l.useState(p.settings.historyLimit),[m,j]=l.useState(()=>Is()),[b,h]=l.useState(!1),[S,L]=l.useState(""),[P,C]=l.useState(()=>X()),[_,V]=l.useState(!1),[B,K]=l.useState(!1),[k,T]=l.useState(""),[H,Z]=l.useState(!1),[ce,N]=l.useState(!1),[F,M]=l.useState(!1),[v,O]=l.useState(!1),[R,Q]=l.useState(!1),[te,ee]=l.useState(""),[A,q]=l.useState(!1);l.useEffect(()=>{tt().then(ee).catch(()=>{})},[]),l.useEffect(()=>{et().then(i=>{i!==p.settings.experimentalEchoPrompt&&E.updateSettings({experimentalEchoPrompt:i})}).catch(()=>{})},[]),l.useEffect(()=>{nt().then(i=>{i!==p.settings.tmuxMode&&E.updateSettings({tmuxMode:i})}).catch(()=>{})},[]),l.useEffect(()=>Ps(i=>{j(i),h(!1)}),[]);const ne=Mt.map(i=>({...i,label:n(`config:time.${i.value}`)})),re=Vt.map(i=>({...i,label:n(`config:floor.${Yt[i.value]||i.value}`)})),ae=Kt.map(i=>({...i,label:n(`config:animation.${Jt[i.value]||i.value}`)})),pe=Ht.map(i=>({...i,label:n(`config:colorMode.${i.value}`)})),ye=Wt.map(i=>({...i,label:n(`config:terrain.${Gt[i.key]}`)})),Ne=qt.map(i=>({...i,label:n(`config:sky.${Zt[i.value??""]}`)})),ie=t.trim()?Xt.filter(i=>{const U=t.toLowerCase();return i.title.toLowerCase().includes(U)||i.keywords.some(de=>de.toLowerCase().includes(U))}).map(i=>i.id):null,D=i=>ie?ie.includes(i):!0,he=D("integrations"),se=p.settings.customAgentNames||[],Le=se.length>0?se:$s,Ce=()=>{const i=k.trim();i&&!se.includes(i)&&(E.updateSettings({customAgentNames:[...se,i]}),T(""))},be=i=>{E.updateSettings({customAgentNames:se.filter(U=>U!==i)})},De=()=>{E.updateSettings({customAgentNames:[]})},Te=()=>{const i=S.trim();if(i){if(m.includes(i)){L("");return}j([...m,i]),h(!0),L("")}},Oe=i=>{j(m.filter((U,de)=>de!==i)),h(!0)},Ae=(i,U)=>{const de=i+U;if(de<0||de>=m.length)return;const xe=m.slice();[xe[i],xe[de]]=[xe[de],xe[i]],j(xe),h(!0)},_e=()=>{Ds(m),h(!1),ze()},Ee=i=>{C(i),V(!0)},ve=()=>{Pe(ke.AUTH_TOKEN,P),V(!1),ze()},Fe=i=>{ee(i),q(!0)},Ie=()=>{at(te).catch(()=>{}),q(!1)},ue=i=>{a({...s,terrain:{...s.terrain,...i}})},f=i=>{a({...s,modelStyle:{...s.modelStyle,...i}})},z=i=>{a({...s,animations:{...s.animations,...i}})},oe=i=>{g(i),E.updateSettings({historyLimit:i})},fe=i=>{const U=s.terrain[i];typeof U=="boolean"&&ue({[i]:!U})},G=t.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-section",children:[ie&&ie.length===0&&e.jsx("div",{className:"config-no-results",children:n("config:noResults",{query:t})}),D("general")&&e.jsxs(W,{title:n("config:sections.general"),storageKey:"general",defaultOpen:!0,forceOpen:G&&D("general"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.history"),query:t})}),e.jsx("input",{type:"number",className:"config-input config-input-sm",value:u,onChange:i=>oe(parseInt(i.target.value)||100),min:50,max:2e3,step:50})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.hideCosts"),query:t})}),e.jsx(le,{checked:p.settings.hideCost,onChange:i=>E.updateSettings({hideCost:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.grid"),query:t})}),e.jsx(le,{checked:s.gridVisible,onChange:i=>a({...s,gridVisible:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.showFPS"),query:t})}),e.jsx(le,{checked:p.settings.showFPS,onChange:i=>E.updateSettings({showFPS:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.fpsLimit"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"120",step:"10",value:s.fpsLimit,onChange:i=>a({...s,fpsLimit:parseInt(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.fpsLimit===0?"∞":s.fpsLimit})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Experimental: Reduce FPS when idle to save power",children:[e.jsx(I,{text:n("config:general.powerSaving"),query:t})," ",e.jsx($,{name:"bolt",size:12})]}),e.jsx(le,{checked:p.settings.powerSaving,onChange:i=>E.updateSettings({powerSaving:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",title:"Wrap agent processes in tmux sessions so they survive server restarts (requires tmux installed)",children:e.jsx(I,{text:n("config:general.tmuxMode"),query:t})}),e.jsx(le,{checked:p.settings.tmuxMode,onChange:async i=>{E.updateSettings({tmuxMode:i});try{await it(i)}catch(U){console.error("Failed to sync tmux mode setting to server:",U)}}})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.vibrationIntensity"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"5",step:"1",value:p.settings.vibrationIntensity,onChange:i=>E.updateSettings({vibrationIntensity:parseInt(i.target.value)})}),e.jsx("span",{className:"config-value",children:p.settings.vibrationIntensity===0?n("config:vibrationValues.off"):p.settings.vibrationIntensity===1?n("config:vibrationValues.ultraLight"):p.settings.vibrationIntensity===2?n("config:vibrationValues.veryLight"):p.settings.vibrationIntensity===3?n("config:vibrationValues.light"):p.settings.vibrationIntensity===4?n("config:vibrationValues.medium"):n("config:vibrationValues.heavy")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.externalEditor"),query:t})}),e.jsx("input",{type:"text",className:"config-input",placeholder:n("config:general.externalEditorPlaceholder"),value:p.settings.externalEditorCommand||"",onChange:i=>E.updateSettings({externalEditorCommand:i.target.value})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.tabTitle"),query:t})}),e.jsx("input",{type:"text",className:"config-input",placeholder:n("config:general.tabTitlePlaceholder"),value:p.settings.tabTitle||"",onChange:i=>E.updateSettings({tabTitle:i.target.value})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.language"),query:t})}),e.jsx(je,{options:Be,value:localStorage.getItem("tide-commander-language-mode")==="manual"?((qe=Be.find(i=>i.value!=="auto"&&Ue.language.startsWith(i.value.split("-")[0])))==null?void 0:qe.value)||"en":"auto",onChange:i=>{var U;if(i==="auto"){localStorage.setItem("tide-commander-language-mode","auto");const de=navigator.language,xe=((U=Be.find(Ge=>Ge.value!=="auto"&&de.startsWith(Ge.value.split("-")[0])))==null?void 0:U.value)||"en";Ue.changeLanguage(xe)}else localStorage.setItem("tide-commander-language-mode","manual"),Ue.changeLanguage(i)}})]})]}),D("agentNames")&&e.jsx(W,{title:n("config:sections.agentNames"),storageKey:"agentNames",defaultOpen:!1,forceOpen:G&&D("agentNames"),children:e.jsxs("div",{className:"agent-names-section",children:[e.jsx("span",{className:"config-hint",children:se.length>0?n("config:agentNames.customConfigured",{count:se.length}):n("config:agentNames.usingDefaults")}),e.jsxs("div",{className:"agent-names-input-row",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",placeholder:n("config:agentNames.addPlaceholder"),value:k,onChange:i=>T(i.target.value),onKeyDown:i=>{i.key==="Enter"&&Ce()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:Ce,disabled:!k.trim(),title:n("config:agentNames.addName"),children:"+"})]}),e.jsx("div",{className:"agent-names-list",children:Le.map((i,U)=>e.jsxs("div",{className:"agent-name-chip",children:[e.jsx("span",{className:"agent-name-text",children:i}),se.length>0&&e.jsx("button",{className:"agent-name-remove",onClick:()=>be(i),title:n("common:buttons.remove"),children:"x"})]},`${i}-${U}`))}),se.length>0&&e.jsx("button",{className:"config-btn config-btn-link",onClick:De,children:n("common:buttons.resetToDefaults")})]})}),D("defaultClass")&&e.jsx(W,{title:"Default Spawn Class",storageKey:"defaultClass",defaultOpen:!1,forceOpen:G&&D("defaultClass"),children:e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-hint",children:'Class pre-selected when the spawn modal opens. "Random" picks a different class each time.'}),e.jsxs("div",{className:"agent-names-list",style:{flexWrap:"wrap",gap:"6px",marginTop:"8px"},children:[e.jsx("div",{className:`agent-name-chip${x==="random"?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{w("random"),Pe(ke.DEFAULT_AGENT_CLASS,"random")},children:e.jsx("span",{className:"agent-name-text",children:"🎲 Random"})}),Object.entries(Ls).map(([i,U])=>e.jsx("div",{className:`agent-name-chip${x===i?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{w(i),Pe(ke.DEFAULT_AGENT_CLASS,i)},children:e.jsxs("span",{className:"agent-name-text",children:[U.icon," ",i.charAt(0).toUpperCase()+i.slice(1)]})},i)),y.map(i=>e.jsx("div",{className:`agent-name-chip${x===i.id?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{w(i.id),Pe(ke.DEFAULT_AGENT_CLASS,i.id)},children:e.jsxs("span",{className:"agent-name-text",children:[i.icon," ",i.name]})},i.id))]})]})}),D("appearance")&&e.jsx(W,{title:n("config:sections.appearance"),storageKey:"appearance",defaultOpen:!1,forceOpen:G&&D("appearance"),children:e.jsx(pt,{})}),D("connection")&&e.jsxs(W,{title:n("config:sections.connection"),storageKey:"connection",defaultOpen:!1,forceOpen:G&&D("connection"),children:[e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:connection.backendUrl"),query:t})}),e.jsx("div",{className:"backend-urls-list",children:m.map((i,U)=>e.jsxs("div",{className:"backend-url-row",children:[e.jsx("span",{className:"backend-url-priority",title:n("config:connection.priorityLabel",{defaultValue:"Priority"}),children:U+1}),e.jsx("span",{className:"backend-url-text",title:i,children:i}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>Ae(U,-1),disabled:U===0,title:n("config:connection.moveUp",{defaultValue:"Move up"}),children:"↑"}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>Ae(U,1),disabled:U===m.length-1,title:n("config:connection.moveDown",{defaultValue:"Move down"}),children:"↓"}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>Oe(U),title:n("common:buttons.remove"),children:"x"})]},`${i}-${U}`))}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",value:S,onChange:i=>L(i.target.value),placeholder:n("config:connection.addUrlPlaceholder",{defaultValue:"http://host:port"}),onKeyDown:i=>{i.key==="Enter"&&Te()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:Te,disabled:!S.trim(),title:n("config:connection.addUrl",{defaultValue:"Add URL"}),children:"+"}),b&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:_e,title:n("config:connection.saveAndReconnect"),children:n("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:n("config:connection.urlsHint",{defaultValue:"Tried in order on connect; the first reachable host wins. Leave empty for auto-detect."})})]}),e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:connection.authToken"),query:t})}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:B?"text":"password",className:"config-input config-input-full",value:P,onChange:i=>Ee(i.target.value),placeholder:n("config:connection.tokenPlaceholder"),onKeyDown:i=>{i.key==="Enter"&&_&&ve()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>K(!B),title:n(B?"config:connection.hideToken":"config:connection.showToken"),children:e.jsx($,{name:B?"eye-closed":"eye",size:14})}),_&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:ve,title:n("config:connection.saveAndReconnect"),children:n("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:n("config:connection.tokenRequired")})]}),e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:connection.codexBinaryPath"),query:t})}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",value:te,onChange:i=>Fe(i.target.value),placeholder:n("config:connection.codexBinaryPathPlaceholder"),onKeyDown:i=>{i.key==="Enter"&&A&&Ie()}}),A&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:Ie,children:n("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:n("config:connection.codexBinaryPathHint")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("common:buttons.reconnect"),query:t})}),e.jsx("button",{className:"config-btn",onClick:()=>ze(),title:"Force reconnect to server",children:n("common:buttons.reconnect")})]})]}),D("scene")&&e.jsxs(W,{title:n("config:sections.scene"),storageKey:"scene",defaultOpen:!1,forceOpen:G&&D("scene"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:scene.characterSize"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"3.0",step:"0.1",value:s.characterScale,onChange:i=>a({...s,characterScale:parseFloat(i.target.value)})}),e.jsxs("span",{className:"config-value",children:[s.characterScale.toFixed(1),"x"]})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:scene.scale2d",{defaultValue:"2D Scale"}),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"2.0",step:"0.1",value:s.scale2d,onChange:i=>a({...s,scale2d:parseFloat(i.target.value)})}),e.jsxs("span",{className:"config-value",children:[s.scale2d.toFixed(1),"x"]})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:scene.scale3d",{defaultValue:"3D Scale"}),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"2.0",step:"0.1",value:s.scale3d,onChange:i=>a({...s,scale3d:parseFloat(i.target.value)})}),e.jsxs("span",{className:"config-value",children:[s.scale3d.toFixed(1),"x"]})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:scene.show2DTaskLabels",{defaultValue:"Show 2D task labels"}),query:t})}),e.jsx(le,{checked:s.show2DTaskLabels,onChange:i=>a({...s,show2DTaskLabels:i})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:scene.time"),query:t})}),e.jsx(je,{options:ne,value:s.timeMode,onChange:i=>a({...s,timeMode:i}),iconOnly:!0})]})]}),D("terrain")&&e.jsxs(W,{title:n("config:sections.terrain"),storageKey:"terrain",defaultOpen:!1,forceOpen:G&&D("terrain"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:terrainSettings.simpleMode",{defaultValue:"Simple Mode"}),query:t})}),e.jsx(le,{checked:s.terrain.simpleMode??!1,onChange:i=>ue({simpleMode:i})})]}),e.jsx("div",{className:"terrain-icons",style:{opacity:s.terrain.simpleMode?.4:1,pointerEvents:s.terrain.simpleMode?"none":"auto"},children:ye.map(i=>e.jsx("button",{className:`terrain-icon-btn ${s.terrain[i.key]?"active":""}`,onClick:()=>fe(i.key),title:i.label,children:i.icon},i.key))}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:terrainSettings.fog"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"2",step:"0.1",value:s.terrain.fogDensity,onChange:i=>ue({fogDensity:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.fogDensity===0?n("config:fogValues.off"):s.terrain.fogDensity<=1?n("config:fogValues.low"):n("config:fogValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:terrainSettings.brightness"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.2",max:"2",step:"0.1",value:s.terrain.brightness,onChange:i=>ue({brightness:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.brightness<=.5?n("config:brightnessValues.dark"):s.terrain.brightness<=1.2?n("config:brightnessValues.normal"):n("config:brightnessValues.bright")})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:terrainSettings.floor"),query:t})}),e.jsx(je,{options:re,value:s.terrain.floorStyle,onChange:i=>ue({floorStyle:i}),iconOnly:!0})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:terrainSettings.sky"),query:t})}),e.jsx("div",{className:"sky-color-selector",children:Ne.map(i=>e.jsx("button",{className:`sky-color-btn ${s.terrain.skyColor===i.value?"active":""}`,onClick:()=>ue({skyColor:i.value}),title:i.label,style:{background:i.color}},i.value??"auto"))})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:terrainSettings.battlefieldSize"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"30",max:"200",step:"10",value:s.terrain.battlefieldSize,onChange:i=>ue({battlefieldSize:parseInt(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.battlefieldSize})]})]}),D("modelStyle")&&e.jsxs(W,{title:n("config:sections.modelStyle"),storageKey:"modelStyle",defaultOpen:!1,forceOpen:G&&D("modelStyle"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:modelStyleSettings.saturation"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"2",step:"0.1",value:s.modelStyle.saturation,onChange:i=>f({saturation:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.saturation<=.3?n("config:saturationValues.gray"):s.modelStyle.saturation<=1.2?n("config:saturationValues.normal"):n("config:saturationValues.vivid")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:modelStyleSettings.roughness"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"1",step:"0.1",value:s.modelStyle.roughness,onChange:i=>f({roughness:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.roughness<0?n("config:roughnessValues.auto"):s.modelStyle.roughness<=.3?n("config:roughnessValues.glossy"):s.modelStyle.roughness<=.7?n("config:roughnessValues.normal"):n("config:roughnessValues.matte")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:modelStyleSettings.metalness"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"1",step:"0.1",value:s.modelStyle.metalness,onChange:i=>f({metalness:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.metalness<0?n("config:metalnessValues.auto"):s.modelStyle.metalness<=.3?n("config:metalnessValues.plastic"):s.modelStyle.metalness<=.7?n("config:metalnessValues.mixed"):n("config:metalnessValues.metal")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:modelStyleSettings.glow"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"1",step:"0.05",value:s.modelStyle.emissiveBoost,onChange:i=>f({emissiveBoost:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.emissiveBoost<=.1?n("config:glowValues.off"):s.modelStyle.emissiveBoost<=.4?n("config:glowValues.low"):s.modelStyle.emissiveBoost<=.7?n("config:glowValues.med"):n("config:glowValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:modelStyleSettings.reflections"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"2",step:"0.1",value:s.modelStyle.envMapIntensity,onChange:i=>f({envMapIntensity:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.envMapIntensity<0?n("config:reflectionValues.auto"):s.modelStyle.envMapIntensity<=.3?n("config:reflectionValues.low"):s.modelStyle.envMapIntensity<=1?n("config:reflectionValues.normal"):n("config:reflectionValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:modelStyleSettings.wireframe"),query:t})}),e.jsx(le,{checked:s.modelStyle.wireframe,onChange:i=>f({wireframe:i})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:modelStyleSettings.colorMode"),query:t})}),e.jsx(je,{options:pe,value:s.modelStyle.colorMode,onChange:i=>f({colorMode:i}),iconOnly:!0})]})]}),D("animations")&&e.jsxs(W,{title:n("config:sections.animations"),storageKey:"animations",defaultOpen:!1,forceOpen:G&&D("animations"),children:[e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:animationSettings.idle"),query:t})}),e.jsx(je,{options:ae,value:s.animations.idleAnimation,onChange:i=>z({idleAnimation:i}),iconOnly:!0})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:animationSettings.working"),query:t})}),e.jsx(je,{options:ae,value:s.animations.workingAnimation,onChange:i=>z({workingAnimation:i}),iconOnly:!0})]})]}),D("secrets")&&e.jsx(W,{title:n("config:sections.secrets"),storageKey:"secrets",defaultOpen:!1,forceOpen:G&&D("secrets"),children:e.jsx(Js,{})}),D("systemPrompt")&&e.jsx(W,{title:n("config:sections.systemPrompt"),storageKey:"systemPrompt",defaultOpen:!1,forceOpen:G&&D("systemPrompt"),children:e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:systemPrompt.title"),query:t})}),e.jsx("button",{className:"config-button",onClick:()=>Z(!0),children:n("config:systemPrompt.editPrompt")})]})}),D("data")&&e.jsx(W,{title:n("config:sections.data"),storageKey:"data",defaultOpen:!1,forceOpen:G&&D("data"),children:e.jsx(rt,{})}),he&&e.jsx(W,{title:n("config:sections.integrations"),storageKey:"integrations",defaultOpen:!1,forceOpen:G&&he,children:e.jsx(ft,{onOpenModal:i=>{i==="whatsapp"?Q(!0):o==null||o(i)}})}),D("workflows")&&e.jsxs(W,{title:"Workflows",storageKey:"workflows",defaultOpen:!1,forceOpen:G&&D("workflows"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(I,{text:"Create and manage automated workflow pipelines with visual state machine editor",query:t})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>d==null?void 0:d(),children:"Open Workflow Editor"})})]}),D("triggers")&&e.jsxs(W,{title:"Triggers",storageKey:"triggers",defaultOpen:!1,forceOpen:G&&D("triggers"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(I,{text:"Create and manage event-driven triggers that fire agents with templates",query:t})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>c==null?void 0:c(),children:"Open Trigger Manager"})})]}),D("monitoring")&&e.jsxs(W,{title:"Monitoring",storageKey:"monitoring",defaultOpen:!1,forceOpen:G&&D("monitoring"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(I,{text:"View event logs, trigger history, workflow traces, and system stats",query:t})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>r==null?void 0:r(),children:"Open Monitoring & Logs"})})]}),D("experimental")&&e.jsxs(W,{title:n("config:sections.experimental"),storageKey:"experimental",defaultOpen:!1,forceOpen:G&&D("experimental"),children:[e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Lightweight 2D top-down view for better performance",children:[e.jsx(I,{text:n("config:experimental.2dView"),query:t})," ",e.jsx($,{name:"map",size:12})]}),e.jsx(le,{checked:p.settings.experimental2DView,onChange:i=>E.updateSettings({experimental2DView:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Voice assistant for hands-free agent control",children:[e.jsx(I,{text:n("config:experimental.voiceAssistant"),query:t})," ",e.jsx($,{name:"microphone",size:12})]}),e.jsx(le,{checked:p.settings.experimentalVoiceAssistant,onChange:i=>E.updateSettings({experimentalVoiceAssistant:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Text-to-speech for reading agent responses",children:[e.jsx(I,{text:n("config:experimental.tts"),query:t})," ",e.jsx($,{name:"speaker-on",size:12})]}),e.jsx(le,{checked:p.settings.experimentalTTS,onChange:i=>E.updateSettings({experimentalTTS:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",title:"Duplicate system prompt for improved LLM attention coverage. Increases input token usage.",children:e.jsx(I,{text:n("config:experimental.echoPrompt"),query:t})}),e.jsx(le,{checked:p.settings.experimentalEchoPrompt,onChange:async i=>{E.updateSettings({experimentalEchoPrompt:i});try{await st(i)}catch(U){console.error("Failed to sync echo prompt setting to server:",U)}}})]}),e.jsx("span",{className:"config-hint",children:n("config:experimental.hint")})]}),D("about")&&e.jsx(W,{title:n("config:sections.about"),storageKey:"about",defaultOpen:!1,forceOpen:G&&D("about"),children:e.jsx(mt,{})})]}),e.jsx(xt,{isOpen:H,onClose:()=>Z(!1)}),e.jsx(yt,{isOpen:ce,onClose:()=>N(!1)}),e.jsx(Ct,{isOpen:F,onClose:()=>M(!1)}),e.jsx(zt,{isOpen:v,onClose:()=>O(!1)}),e.jsx(Bt,{isOpen:R,onClose:()=>Q(!1),onOpenConfig:()=>N(!0),onOpenNotifications:()=>M(!0),onOpenHistory:()=>O(!0)})]})}function aa({onConfigChange:s,onToolChange:a,config:t,isOpen:o,onClose:r,onOpenBuildingModal:d,onOpenAreaExplorer:c,onOpenIntegrationsModal:n,onOpenMonitoringModal:p,onOpenWorkflowEditor:y,onOpenTriggerManager:x}){const{t:w}=Y(["config","common"]),u=Ve(),g=Array.from(u.areas.values()),m=Array.from(u.buildings.values()),[j,b]=l.useState(""),h=l.useRef(null);if(l.useEffect(()=>{const C=_=>{_.key==="Escape"&&o&&r()};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[o,r]),l.useEffect(()=>{if(o&&h.current){if(typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches)return;const _=setTimeout(()=>{var V;(V=h.current)==null||V.focus()},50);return()=>clearTimeout(_)}},[o]),!o)return null;const S=C=>{const _=u.activeTool===C?null:C;a(_)},L=C=>{E.selectArea(u.selectedAreaId===C?null:C),a("select")},P=(C,_)=>{C.stopPropagation(),E.deleteArea(_)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"toolbox-backdrop",onClick:r}),e.jsxs("aside",{className:"toolbox",children:[e.jsxs("div",{className:"toolbox-header",children:[e.jsx("span",{children:w("config:title")}),e.jsx("button",{className:"toolbox-close-btn",onClick:r,title:w("common:buttons.close"),children:"×"})]}),e.jsxs("div",{className:"toolbox-search",children:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("path",{d:"M21 21l-4.35-4.35"})]}),e.jsx("input",{ref:h,type:"text",placeholder:w("config:searchPlaceholder"),value:j,onChange:C=>b(C.target.value),className:"toolbox-search-input"}),j&&e.jsx("button",{className:"toolbox-search-clear",onClick:()=>b(""),children:"×"})]}),e.jsxs("div",{className:"toolbox-content",children:[e.jsx("div",{className:"toolbox-section toolbox-section-collapsible",children:e.jsxs(W,{title:w("config:areas.title",{count:g.length}),storageKey:"areas",children:[e.jsxs("div",{className:"tool-buttons",children:[e.jsx("button",{className:`tool-btn ${u.activeTool==="select"?"active":""}`,onClick:()=>S("select"),title:w("config:tools.select"),children:e.jsx("span",{children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"})})})}),e.jsx("button",{className:`tool-btn ${u.activeTool==="rectangle"?"active":""}`,onClick:()=>S("rectangle"),title:w("config:tools.rectangle"),children:e.jsx("span",{children:e.jsx("svg",{width:"16",height:"16",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("button",{className:`tool-btn ${u.activeTool==="circle"?"active":""}`,onClick:()=>S("circle"),title:w("config:tools.circle"),children:e.jsx("span",{children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("circle",{cx:"12",cy:"12",r:"9"})})})})]}),e.jsx("div",{className:"areas-list",children:g.length===0?e.jsx("div",{className:"areas-empty",children:w("config:areas.drawToCreate")}):g.map(C=>e.jsx(Ms,{area:C,isSelected:u.selectedAreaId===C.id,onClick:()=>L(C.id),onDelete:_=>P(_,C.id)},C.id))})]})}),u.selectedAreaId&&e.jsx(Ys,{area:u.areas.get(u.selectedAreaId),onClose:()=>E.selectArea(null),onOpenFolder:c}),e.jsx("div",{className:"toolbox-section toolbox-section-collapsible",children:e.jsx(W,{title:w("config:buildings.title",{count:m.length}),storageKey:"buildings",headerExtra:e.jsx("button",{className:"add-building-btn",onClick:C=>{C.stopPropagation(),d==null||d()},title:w("config:buildings.addBuilding"),children:"+"}),children:e.jsx("div",{className:"buildings-list",children:m.length===0?e.jsx("div",{className:"buildings-empty",children:w("config:buildings.clickToAdd")}):m.map(C=>e.jsx(Vs,{building:C,isSelected:u.selectedBuildingIds.has(C.id),onClick:()=>{E.selectBuilding(u.selectedBuildingIds.has(C.id)?null:C.id)},onEdit:()=>d==null?void 0:d(C.id)},C.id))})})}),u.selectedBuildingIds.size===1&&(()=>{const C=Array.from(u.selectedBuildingIds)[0],_=u.buildings.get(C);return _?e.jsx(Ks,{building:_,onClose:()=>E.selectBuilding(null),onOpenModal:()=>d==null?void 0:d(C)}):null})(),e.jsx(Qt,{config:t,onChange:s,searchQuery:j,onOpenIntegrationsModal:n,onOpenMonitoringModal:p,onOpenWorkflowEditor:y,onOpenTriggerManager:x})]})]})]})}export{aa as Toolbox};