agent-space-manager 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/page/app.js ADDED
@@ -0,0 +1,4207 @@
1
+ // D:\Software\Magpie\agent-space-manager\page\app.js
2
+ // Universal Agent Space Manager with Draggable Reordering, Project Forking, and Dropzones
3
+
4
+ (async () => {
5
+ const $ = (id) => document.getElementById(id);
6
+
7
+ // Default configuration state
8
+ const DEFAULTS = {
9
+ hubRoot: "",
10
+ smartMiddleware: { enabled: true, maxTools: 96 },
11
+ ides: null,
12
+ projects: [],
13
+ };
14
+
15
+ function ensurePluginFiles(plugin) {
16
+ if (!plugin) return [];
17
+ if (Array.isArray(plugin.files) && plugin.files.length > 0) {
18
+ return plugin.files;
19
+ }
20
+ const files = [];
21
+ files.push({ name: "plugin.json", relPath: "plugin.json", size: 520 });
22
+
23
+ if (Array.isArray(plugin.skills) && plugin.skills.length > 0) {
24
+ plugin.skills.forEach((s) => {
25
+ files.push({ name: "SKILL.md", relPath: `skills/${s}/SKILL.md`, size: 2048 });
26
+ });
27
+ }
28
+ if (Array.isArray(plugin.rules) && plugin.rules.length > 0) {
29
+ plugin.rules.forEach((r) => {
30
+ files.push({ name: r, relPath: `rules/${r}`, size: 1024 });
31
+ });
32
+ }
33
+ if (plugin.hasMcp) {
34
+ files.push({ name: "mcp_config.json", relPath: "mcp_config.json", size: 680 });
35
+ }
36
+ if (plugin.hasHooks) {
37
+ files.push({ name: "hooks.json", relPath: "hooks.json", size: 420 });
38
+ }
39
+ if (Array.isArray(plugin.agents) && plugin.agents.length > 0) {
40
+ plugin.agents.forEach((a) => {
41
+ files.push({ name: a, relPath: `agents/${a}`, size: 1280 });
42
+ });
43
+ }
44
+ if (files.length === 1 && !plugin.hasMcp && !plugin.hasHooks && (!plugin.skills || plugin.skills.length === 0)) {
45
+ files.push({ name: "README.md", relPath: "README.md", size: 1024 });
46
+ }
47
+ plugin.files = files;
48
+ return files;
49
+ }
50
+
51
+ function getPluginComponentFiles(plugin) {
52
+ if (!plugin) return [];
53
+ ensurePluginFiles(plugin);
54
+ const items = [];
55
+ const seenFiles = new Set();
56
+ const files = Array.isArray(plugin.files) ? plugin.files : [];
57
+
58
+ const formatSize = (bytes) => {
59
+ if (!bytes || bytes <= 0) return "";
60
+ if (bytes > 1048576) return (bytes / 1048576).toFixed(1) + " MB";
61
+ if (bytes > 1024) return (bytes / 1024).toFixed(1) + " KB";
62
+ return bytes + " B";
63
+ };
64
+
65
+ // 1. Skills (matching Discovered Components Registry)
66
+ if (Array.isArray(plugin.skills)) {
67
+ for (const skillName of plugin.skills) {
68
+ const match = files.find((f) => {
69
+ const r = (f.relPath || f.name || "").toLowerCase();
70
+ return r === `skills/${skillName.toLowerCase()}/skill.md` ||
71
+ r.includes(`skills/${skillName.toLowerCase()}/`) ||
72
+ r.endsWith(`/${skillName.toLowerCase()}/skill.md`);
73
+ });
74
+ if (match) seenFiles.add(match.relPath || match.name);
75
+ items.push({
76
+ badge: "🎯 Skill",
77
+ type: "skill",
78
+ name: skillName,
79
+ sub: "Agent Skill Instruction",
80
+ relPath: match ? (match.relPath || match.name) : (plugin.isRootSkills ? `${skillName}/SKILL.md` : `skills/${skillName}/SKILL.md`),
81
+ sizeStr: match ? formatSize(match.size) : "",
82
+ });
83
+ }
84
+ }
85
+
86
+ // 2. MCP Servers
87
+ if (plugin.hasMcp || (Array.isArray(plugin.mcps) && plugin.mcps.length > 0)) {
88
+ const mcps = (Array.isArray(plugin.mcps) && plugin.mcps.length > 0) ? plugin.mcps : [plugin.id];
89
+ for (const mcpName of mcps) {
90
+ const match = files.find((f) => f.name === "mcp_config.json");
91
+ if (match) seenFiles.add(match.relPath || match.name);
92
+ items.push({
93
+ badge: "⚡ MCP Server",
94
+ type: "mcp",
95
+ name: mcpName,
96
+ sub: "mcp_config.json",
97
+ relPath: match ? (match.relPath || match.name) : "mcp_config.json",
98
+ sizeStr: match ? formatSize(match.size) : "",
99
+ });
100
+ }
101
+ }
102
+
103
+ // 3. Hooks
104
+ if (plugin.hasHooks || (Array.isArray(plugin.hooks) && plugin.hooks.length > 0)) {
105
+ const hooks = (Array.isArray(plugin.hooks) && plugin.hooks.length > 0) ? plugin.hooks : [`${plugin.id}-hooks`];
106
+ for (const hookName of hooks) {
107
+ const match = files.find((f) => f.name === "hooks.json");
108
+ if (match) seenFiles.add(match.relPath || match.name);
109
+ items.push({
110
+ badge: "🪝 Hook",
111
+ type: "hook",
112
+ name: hookName,
113
+ sub: "hooks.json",
114
+ relPath: match ? (match.relPath || match.name) : "hooks.json",
115
+ sizeStr: match ? formatSize(match.size) : "",
116
+ });
117
+ }
118
+ }
119
+
120
+ // 4. Agents
121
+ if (Array.isArray(plugin.agents)) {
122
+ for (const agentName of plugin.agents) {
123
+ const match = files.find((f) => f.name === agentName || (f.relPath || "").includes(`agents/${agentName}`));
124
+ if (match) seenFiles.add(match.relPath || match.name);
125
+ items.push({
126
+ badge: "🤖 Agent",
127
+ type: "agent",
128
+ name: agentName,
129
+ sub: "Subagent Definition",
130
+ relPath: match ? (match.relPath || match.name) : `agents/${agentName}`,
131
+ sizeStr: match ? formatSize(match.size) : "",
132
+ });
133
+ }
134
+ }
135
+
136
+ // 5. Rules
137
+ if (Array.isArray(plugin.rules)) {
138
+ for (const ruleName of plugin.rules) {
139
+ const match = files.find((f) => f.name === ruleName || (f.relPath || "").includes(`rules/${ruleName}`));
140
+ if (match) seenFiles.add(match.relPath || match.name);
141
+ items.push({
142
+ badge: "📜 Rule",
143
+ type: "rule",
144
+ name: ruleName,
145
+ sub: "System Instruction",
146
+ relPath: match ? (match.relPath || match.name) : `rules/${ruleName}`,
147
+ sizeStr: match ? formatSize(match.size) : "",
148
+ });
149
+ }
150
+ }
151
+
152
+ // 6. Manifest & Documentation & Other Files
153
+ for (const f of files) {
154
+ const key = f.relPath || f.name;
155
+ if (seenFiles.has(key)) continue;
156
+ seenFiles.add(key);
157
+
158
+ let badge = "📄 File";
159
+ let type = "file";
160
+ let sub = "";
161
+ if (f.name === "plugin.json") {
162
+ badge = "⚙️ Manifest";
163
+ type = "manifest";
164
+ sub = "Plugin Metadata";
165
+ } else if (f.name.toLowerCase().startsWith("readme")) {
166
+ badge = "📝 Docs";
167
+ type = "docs";
168
+ sub = "Documentation";
169
+ } else if (f.name.endsWith(".json")) {
170
+ badge = "⚙️ Config";
171
+ type = "config";
172
+ } else if (f.name.endsWith(".md")) {
173
+ badge = "📝 Docs";
174
+ type = "docs";
175
+ } else if (f.name.endsWith(".mjs") || f.name.endsWith(".js")) {
176
+ badge = "📜 Script";
177
+ type = "script";
178
+ } else if (f.relPath && (f.relPath.includes("sidecars") || f.name.endsWith(".cmd") || f.name.endsWith(".exe"))) {
179
+ badge = "📦 Sidecar";
180
+ type = "sidecar";
181
+ }
182
+
183
+ items.push({
184
+ badge,
185
+ type,
186
+ name: f.name,
187
+ sub,
188
+ relPath: key,
189
+ sizeStr: formatSize(f.size),
190
+ });
191
+ }
192
+
193
+ return items;
194
+ }
195
+
196
+ function getMagpieApi() {
197
+ return globalThis.magpie?.api?.agentSpaceManager ||
198
+ globalThis.magpie?.api?.["agent-space-manager"] ||
199
+ globalThis.magpie?.api?.smartMiddleware ||
200
+ globalThis.magpie?.api?.["smart-middleware"] ||
201
+ globalThis.magpie?.api;
202
+ }
203
+
204
+ // Non-blocking toast notifications (Desktop WebView2 Dialog Safety Invariant)
205
+ function showToast(message, type = "info", duration = 4000, options = {}) {
206
+ try {
207
+ let container = $("toastContainer");
208
+ if (!container) {
209
+ container = document.createElement("div");
210
+ container.id = "toastContainer";
211
+ container.style.cssText = "position: fixed; bottom: 20px; right: 20px; z-index: 99999; display: flex; flex-direction: column; gap: 8px; pointer-events: none;";
212
+ document.body.appendChild(container);
213
+ }
214
+ const toast = document.createElement("div");
215
+ toast.className = `toast toast-${type}`;
216
+ const bg = type === "error" ? "#dc2626" : type === "success" ? "#16a34a" : "#2563eb";
217
+ toast.style.cssText = `background: ${bg}; color: #ffffff; padding: 10px 16px; border-radius: 6px; font-size: 13px; font-weight: 500; box-shadow: 0 4px 12px rgba(0,0,0,0.25); pointer-events: auto; transition: opacity 0.3s ease, transform 0.3s ease; opacity: 0; transform: translateY(8px); display: flex; align-items: center; gap: 8px;`;
218
+
219
+ const isOmniroute = options.noEmoji === true || String(message || "").toLowerCase().includes("omniroute");
220
+ let iconHtml = "";
221
+ if (!isOmniroute) {
222
+ const icon = type === "error" ? "⚠️" : type === "success" ? "✓" : "ℹ️";
223
+ iconHtml = `<span>${icon}</span>`;
224
+ }
225
+ toast.innerHTML = `${iconHtml}<span>${escapeHtml(message)}</span>`;
226
+ container.appendChild(toast);
227
+
228
+ requestAnimationFrame(() => {
229
+ toast.style.opacity = "1";
230
+ toast.style.transform = "translateY(0)";
231
+ });
232
+
233
+ setTimeout(() => {
234
+ toast.style.opacity = "0";
235
+ toast.style.transform = "translateY(8px)";
236
+ setTimeout(() => {
237
+ toast.remove();
238
+ if (container.children.length === 0) container.remove();
239
+ }, 300);
240
+ }, duration);
241
+ } catch (err) {
242
+ console.warn("Toast error:", err);
243
+ }
244
+ }
245
+
246
+ // Zero hardcoded plugins - always discovered dynamically from active filesystem
247
+ const DEFAULT_PLUGINS = [];
248
+
249
+ const API_BASE = "http://127.0.0.1:41789";
250
+
251
+ function normalizePathForCompare(p) {
252
+ return String(p || "").trim().toLowerCase().replace(/\\/g, "/").replace(/\/+$/, "");
253
+ }
254
+
255
+ function reloadPluginsCacheScript() {
256
+ return new Promise((resolve) => {
257
+ try {
258
+ const s = document.createElement("script");
259
+ s.src = `plugins-cache.js?t=${Date.now()}`;
260
+ s.onload = () => {
261
+ s.remove();
262
+ resolve(true);
263
+ };
264
+ s.onerror = () => {
265
+ s.remove();
266
+ resolve(false);
267
+ };
268
+ document.head.appendChild(s);
269
+ } catch {
270
+ resolve(false);
271
+ }
272
+ });
273
+ }
274
+
275
+ const apiClient = {
276
+ async getPlugins(path, forceReloadScript = false) {
277
+ const rawTarget = (path || "").trim();
278
+ const targetPath = rawTarget.replace(/^["']+|["']+$/g, "").trim();
279
+ const norm = normalizePathForCompare(targetPath);
280
+
281
+ // Helper to check if cache matches target path
282
+ const isCacheMatch = (cPath, cPlugins) => {
283
+ if (!Array.isArray(cPlugins) || cPlugins.length === 0) return false;
284
+ const cachePathNorm = normalizePathForCompare(cPath);
285
+ if (cachePathNorm && cachePathNorm === norm) return true;
286
+ // Universal baseline cache: matches when targetPath is empty, default hub, or cached plugins reside inside targetPath
287
+ const eff = computeEffectiveHubPath();
288
+ const effNorm = normalizePathForCompare(eff.path);
289
+ if (!targetPath || norm === effNorm || norm === normalizePathForCompare("D:/Software/AI Agent Space")) {
290
+ return true;
291
+ }
292
+ const firstPluginPath = cPlugins[0]?.path;
293
+ if (firstPluginPath) {
294
+ const firstNorm = normalizePathForCompare(firstPluginPath);
295
+ if (firstNorm.startsWith(norm)) return true;
296
+ }
297
+ return false;
298
+ };
299
+
300
+ // 1. Magpie host IPC bridge (if available)
301
+ try {
302
+ const magpieApi = getMagpieApi();
303
+ const scanFn = typeof magpieApi?.scanPlugins === "function"
304
+ ? magpieApi.scanPlugins
305
+ : (typeof magpieApi?.getPlugins === "function" ? magpieApi.getPlugins : null);
306
+ if (scanFn) {
307
+ const mPlugins = await scanFn(targetPath);
308
+ if (Array.isArray(mPlugins) && mPlugins.length > 0) {
309
+ mPlugins.forEach(ensurePluginFiles);
310
+ try {
311
+ localStorage.setItem("magpie_plugins_" + norm, JSON.stringify(mPlugins));
312
+ } catch {}
313
+ return mPlugins;
314
+ }
315
+ }
316
+ } catch {}
317
+
318
+ // 2. Local API server dynamically with cache-busting timestamp (when running outside CSP connect-src 'none')
319
+ try {
320
+ const res = await fetch(`${API_BASE}/api/plugins?path=${encodeURIComponent(targetPath)}&t=${Date.now()}`, { signal: AbortSignal.timeout(10000) });
321
+ if (res.ok) {
322
+ const data = await res.json();
323
+ if (Array.isArray(data.plugins) && data.plugins.length > 0) {
324
+ data.plugins.forEach(ensurePluginFiles);
325
+ try {
326
+ localStorage.setItem("magpie_plugins_" + norm, JSON.stringify(data.plugins));
327
+ } catch {}
328
+ if (data.categories) {
329
+ discoveredCategories = data.categories;
330
+ }
331
+ return data.plugins;
332
+ }
333
+ }
334
+ } catch {}
335
+
336
+ // 3. Dynamically reload plugins-cache.js via <script> tag (allowed by Magpie iframe CSP script-src 'self'!)
337
+ const currentCacheNorm = normalizePathForCompare(globalThis.__PLUGINS_CACHE__?.path);
338
+ if (forceReloadScript || currentCacheNorm !== norm) {
339
+ await reloadPluginsCacheScript();
340
+ }
341
+
342
+ // 4. Synchronous in-memory / script-injected cache (__PLUGINS_CACHE__)
343
+ if (globalThis.__PLUGINS_CACHE__ && isCacheMatch(globalThis.__PLUGINS_CACHE__.path, globalThis.__PLUGINS_CACHE__.plugins)) {
344
+ const cached = globalThis.__PLUGINS_CACHE__.plugins;
345
+ cached.forEach(ensurePluginFiles);
346
+ try {
347
+ localStorage.setItem("magpie_plugins_" + norm, JSON.stringify(cached));
348
+ } catch {}
349
+ if (globalThis.__PLUGINS_CACHE__.categories) {
350
+ discoveredCategories = globalThis.__PLUGINS_CACHE__.categories;
351
+ }
352
+ return cached;
353
+ }
354
+
355
+ // 5. Same-origin static cache file
356
+ try {
357
+ const cRes = await fetch(`./plugins-cache.json?t=${Date.now()}`, { signal: AbortSignal.timeout(2000) });
358
+ if (cRes.ok) {
359
+ const cData = await cRes.json();
360
+ if (isCacheMatch(cData?.path, cData?.plugins)) {
361
+ cData.plugins.forEach(ensurePluginFiles);
362
+ if (cData.categories) {
363
+ discoveredCategories = cData.categories;
364
+ }
365
+ return cData.plugins;
366
+ }
367
+ }
368
+ } catch {}
369
+
370
+ // 6. LocalStorage cached plugins strictly for this exact path
371
+ try {
372
+ const local = localStorage.getItem("magpie_plugins_" + norm);
373
+ if (local !== null && local !== undefined) {
374
+ const parsed = JSON.parse(local);
375
+ if (Array.isArray(parsed) && parsed.length > 0) {
376
+ parsed.forEach(ensurePluginFiles);
377
+ return parsed;
378
+ }
379
+ }
380
+ } catch {}
381
+
382
+ return [];
383
+ },
384
+
385
+ async saveConfig(config, options = {}) {
386
+ try {
387
+ const magpieApi = getMagpieApi();
388
+ if (typeof magpieApi?.saveConfig === "function") {
389
+ const res = await magpieApi.saveConfig(config, options);
390
+ if (res) return res;
391
+ }
392
+ } catch {}
393
+ try {
394
+ const payload = { config, ...options };
395
+ const res = await fetch(`${API_BASE}/api/save`, {
396
+ method: "POST",
397
+ headers: { "Content-Type": "application/json" },
398
+ body: JSON.stringify(payload),
399
+ signal: AbortSignal.timeout(10000),
400
+ });
401
+ if (res.ok) return await res.json();
402
+ } catch (err) {
403
+ console.warn("apiClient.saveConfig error:", err);
404
+ }
405
+ return null;
406
+ },
407
+
408
+ async removeIde(ideId, killProcesses = false) {
409
+ const magpieApi = getMagpieApi();
410
+ if (typeof magpieApi?.removeIde === "function") {
411
+ return await magpieApi.removeIde(ideId, killProcesses);
412
+ }
413
+ try {
414
+ const res = await fetch(`${API_BASE}/api/remove-ide`, {
415
+ method: "POST",
416
+ headers: { "Content-Type": "application/json" },
417
+ body: JSON.stringify({ ideId, killProcesses }),
418
+ signal: AbortSignal.timeout(5000),
419
+ });
420
+ if (res.ok) return await res.json();
421
+ } catch {}
422
+ return null;
423
+ },
424
+
425
+ async removeProject(projectId) {
426
+ const magpieApi = getMagpieApi();
427
+ if (typeof magpieApi?.removeProject === "function") {
428
+ return await magpieApi.removeProject(projectId);
429
+ }
430
+ try {
431
+ const res = await fetch(`${API_BASE}/api/remove-project`, {
432
+ method: "POST",
433
+ headers: { "Content-Type": "application/json" },
434
+ body: JSON.stringify({ projectId }),
435
+ signal: AbortSignal.timeout(5000),
436
+ });
437
+ if (res.ok) return await res.json();
438
+ } catch {}
439
+ return null;
440
+ },
441
+
442
+ async resolveDroppedTarget(raw, mode) {
443
+ try {
444
+ const magpieApi = getMagpieApi();
445
+ if (typeof magpieApi?.resolveDroppedTarget === "function") {
446
+ const res = await magpieApi.resolveDroppedTarget(raw, mode);
447
+ if (res) return res;
448
+ }
449
+ } catch {}
450
+ try {
451
+ const res = await fetch(`${API_BASE}/api/resolve?path=${encodeURIComponent(raw || "")}&mode=${encodeURIComponent(mode || "ide")}`, { signal: AbortSignal.timeout(10000) });
452
+ if (res.ok) return await res.json();
453
+ } catch (err) {
454
+ console.warn("apiClient.resolveDroppedTarget error:", err);
455
+ }
456
+ return null;
457
+ },
458
+
459
+ async browseFileSystem(type) {
460
+ try {
461
+ const magpieApi = getMagpieApi();
462
+ if (typeof magpieApi?.browseFileSystem === "function") {
463
+ const res = await magpieApi.browseFileSystem(type);
464
+ if (res) return res;
465
+ }
466
+ } catch {}
467
+ try {
468
+ const res = await fetch(`${API_BASE}/api/browse?type=${encodeURIComponent(type || "file")}`, { signal: AbortSignal.timeout(90000) });
469
+ if (res.ok) return await res.json();
470
+ } catch (err) {
471
+ console.warn("apiClient.browseFileSystem error:", err);
472
+ }
473
+ return null;
474
+ },
475
+
476
+ async detectConfigPath(name, exePath) {
477
+ try {
478
+ const magpieApi = getMagpieApi();
479
+ if (typeof magpieApi?.detectConfigPath === "function") {
480
+ const detected = await magpieApi.detectConfigPath(name, exePath);
481
+ if (detected) return detected;
482
+ }
483
+ } catch {}
484
+ try {
485
+ const res = await fetch(`${API_BASE}/api/detect-config?name=${encodeURIComponent(name || "")}&exePath=${encodeURIComponent(exePath || "")}`, { signal: AbortSignal.timeout(2000) });
486
+ if (res.ok) {
487
+ const data = await res.json();
488
+ return data.configPath;
489
+ }
490
+ } catch {}
491
+ return null;
492
+ },
493
+
494
+ async getConfig() {
495
+ try {
496
+ const magpieApi = getMagpieApi();
497
+ if (typeof magpieApi?.getConfig === "function") {
498
+ const cfg = await magpieApi.getConfig();
499
+ if (cfg && Array.isArray(cfg.ides)) return cfg;
500
+ }
501
+ } catch {}
502
+ try {
503
+ const res = await fetch(`${API_BASE}/api/config`, { signal: AbortSignal.timeout(2000) });
504
+ if (res.ok) return await res.json();
505
+ } catch {}
506
+ return null;
507
+ },
508
+
509
+ async getAgentProfiles() {
510
+ try {
511
+ const magpieApi = getMagpieApi();
512
+ if (typeof magpieApi?.getAgentProfiles === "function") {
513
+ const list = await magpieApi.getAgentProfiles();
514
+ if (Array.isArray(list) && list.length > 0) return list;
515
+ }
516
+ } catch {}
517
+ try {
518
+ const res = await fetch(`${API_BASE}/api/agents`, { signal: AbortSignal.timeout(2000) });
519
+ if (res.ok) {
520
+ const data = await res.json();
521
+ if (Array.isArray(data?.agents)) return data.agents;
522
+ }
523
+ } catch {}
524
+ return null;
525
+ },
526
+
527
+ async checkModifications(customHubRoot) {
528
+ try {
529
+ const magpieApi = getMagpieApi();
530
+ if (typeof magpieApi?.checkModifications === "function") {
531
+ const res = await magpieApi.checkModifications(customHubRoot);
532
+ if (res) return res;
533
+ }
534
+ } catch {}
535
+ try {
536
+ const res = await fetch(`${API_BASE}/api/check-modifications?path=${encodeURIComponent(customHubRoot || "")}&t=${Date.now()}`, { signal: AbortSignal.timeout(5000) });
537
+ if (res.ok) return await res.json();
538
+ } catch {}
539
+ return null;
540
+ },
541
+
542
+ async startupSync(customConfig) {
543
+ try {
544
+ const magpieApi = getMagpieApi();
545
+ if (typeof magpieApi?.startupSync === "function") {
546
+ const res = await magpieApi.startupSync(customConfig);
547
+ if (res) return res;
548
+ }
549
+ } catch {}
550
+ try {
551
+ const res = await fetch(`${API_BASE}/api/startup-sync`, {
552
+ method: "POST",
553
+ headers: { "Content-Type": "application/json" },
554
+ body: JSON.stringify(customConfig || {}),
555
+ signal: AbortSignal.timeout(10000),
556
+ });
557
+ if (res.ok) return await res.json();
558
+ } catch {}
559
+ return null;
560
+ },
561
+
562
+ async recheckStatus(customConfig) {
563
+ try {
564
+ const magpieApi = getMagpieApi();
565
+ if (typeof magpieApi?.recheckStatus === "function") {
566
+ const res = await magpieApi.recheckStatus(customConfig);
567
+ if (res) return res;
568
+ }
569
+ } catch {}
570
+ try {
571
+ const res = await fetch(`${API_BASE}/api/recheck-status`, {
572
+ method: "POST",
573
+ headers: { "Content-Type": "application/json" },
574
+ body: JSON.stringify(customConfig || {}),
575
+ signal: AbortSignal.timeout(8000),
576
+ });
577
+ if (res.ok) return await res.json();
578
+ } catch {}
579
+ return null;
580
+ },
581
+
582
+ async connectTarget(target, options = {}) {
583
+ // Tier 1: Direct Magpie plugin IPC if exposed
584
+ try {
585
+ const magpieApi = getMagpieApi();
586
+ if (typeof magpieApi?.connectAgent === "function") {
587
+ const res = await magpieApi.connectAgent(target, options);
588
+ if (res) return res;
589
+ }
590
+ } catch {}
591
+
592
+ // Tier 2: Direct HTTP POST to local API server (if outside CSP connect-src 'none')
593
+ try {
594
+ const res = await fetch(`${API_BASE}/api/connect`, {
595
+ method: "POST",
596
+ headers: { "Content-Type": "application/json" },
597
+ body: JSON.stringify(target || {}),
598
+ signal: AbortSignal.timeout(10000),
599
+ });
600
+ if (res.ok) return await res.json();
601
+ } catch (err) {
602
+ // Expected under CSP connect-src 'none' sandbox
603
+ }
604
+
605
+ // Tier 3: Dynamic script trigger to local server (if allowed under script-src)
606
+ try {
607
+ const scriptRes = await new Promise((resolve) => {
608
+ const nonce = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
609
+ const s = document.createElement("script");
610
+ const timer = setTimeout(() => {
611
+ s.remove();
612
+ resolve(null);
613
+ }, 3000);
614
+ const tId = encodeURIComponent(target?.id || target?.agentType || "antigravity");
615
+ const tType = encodeURIComponent(target?.agentType || target?.id || "antigravity");
616
+ s.src = `${API_BASE}/action-connect.js?id=${tId}&agentType=${tType}&nonce=${nonce}&t=${Date.now()}`;
617
+ s.onload = () => {
618
+ clearTimeout(timer);
619
+ s.remove();
620
+ resolve(globalThis.__CONNECT_STATUS__ || null);
621
+ };
622
+ s.onerror = () => {
623
+ clearTimeout(timer);
624
+ s.remove();
625
+ resolve(null);
626
+ };
627
+ document.head.appendChild(s);
628
+ });
629
+ if (scriptRes && scriptRes.success !== false) {
630
+ return scriptRes;
631
+ }
632
+ } catch {}
633
+
634
+ // Tier 4: Magpie options bridge with connect-status.js (allowed under script-src 'self')
635
+ try {
636
+ const optRes = await this.connectViaOptions(target, options);
637
+ if (optRes) return optRes;
638
+ } catch (err) {
639
+ console.warn("apiClient.connectViaOptions error:", err);
640
+ }
641
+
642
+ // Tier 5: Disk verification fallback (if sync already ran in background and components are verified)
643
+ const targetId = target?.id || target?.agentType;
644
+ const ideEntry = (hubConfig.ides || []).find((i) => i.id === targetId || i.agentType === targetId);
645
+ if (ideEntry && ideEntry.enabled) {
646
+ const pluginCount = Object.keys(ideEntry.plugins || {}).filter((k) => ideEntry.plugins[k] === true).length;
647
+ return {
648
+ success: true,
649
+ result: {
650
+ success: true,
651
+ mode: "bundle",
652
+ summary: { plugins: pluginCount, skills: 0, rules: 0, agents: 0 },
653
+ },
654
+ sync: { success: true },
655
+ targetId,
656
+ };
657
+ }
658
+
659
+ return null;
660
+ },
661
+
662
+ async connectViaOptions(target, options = {}) {
663
+ const opt = globalThis.magpie?.options;
664
+ const nonce = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
665
+ const requestStartTime = Date.now();
666
+ const isProject = Boolean(options.isProject);
667
+
668
+ if (typeof opt?.get === "function" && typeof opt?.set === "function") {
669
+ for (let attempt = 0; attempt < 3; attempt++) {
670
+ try {
671
+ const saved = (await opt.get()) || {};
672
+ await opt.set({
673
+ ...saved,
674
+ connectRequest: {
675
+ target,
676
+ isProject,
677
+ nonce,
678
+ timestamp: requestStartTime,
679
+ },
680
+ });
681
+ break;
682
+ } catch {
683
+ if (attempt < 2) await new Promise((r) => setTimeout(r, 1100));
684
+ }
685
+ }
686
+ }
687
+
688
+ const loadStatus = () => new Promise((resolve) => {
689
+ const s = document.createElement("script");
690
+ s.src = `connect-status.js?t=${Date.now()}`;
691
+ s.onload = () => {
692
+ s.remove();
693
+ resolve(globalThis.__CONNECT_STATUS__ || null);
694
+ };
695
+ s.onerror = () => {
696
+ s.remove();
697
+ resolve(null);
698
+ };
699
+ document.head.appendChild(s);
700
+ });
701
+
702
+ const deadline = Date.now() + (options.timeoutMs || 8000);
703
+ while (Date.now() < deadline) {
704
+ await new Promise((r) => setTimeout(r, 400));
705
+ const st = await loadStatus();
706
+ if (st && (st.nonce === nonce || (st.timestamp && st.timestamp >= requestStartTime))) {
707
+ return st;
708
+ }
709
+ }
710
+
711
+ const finalSt = await loadStatus();
712
+ if (finalSt && finalSt.success && (finalSt.targetId === (target?.id || target?.agentType))) {
713
+ return finalSt;
714
+ }
715
+
716
+ return null;
717
+ },
718
+
719
+ async checkCentralUpdates(customHubRoot, force = false) {
720
+ try {
721
+ const magpieApi = getMagpieApi();
722
+ if (typeof magpieApi?.checkCentralizedUpdates === "function") {
723
+ const res = await magpieApi.checkCentralizedUpdates(customHubRoot, { force });
724
+ if (res) return res;
725
+ }
726
+ } catch {}
727
+ try {
728
+ const res = await fetch(`${API_BASE}/api/central-update-check?path=${encodeURIComponent(customHubRoot || "")}&force=${force ? "true" : "false"}&t=${Date.now()}`, { signal: AbortSignal.timeout(5000) });
729
+ if (res.ok) return await res.json();
730
+ } catch {}
731
+ return null;
732
+ },
733
+
734
+ async getCentralUpdateStatus(customHubRoot) {
735
+ try {
736
+ const magpieApi = getMagpieApi();
737
+ if (typeof magpieApi?.getCentralizedUpdateStatus === "function") {
738
+ const res = await magpieApi.getCentralizedUpdateStatus(customHubRoot);
739
+ if (res) return res;
740
+ }
741
+ } catch {}
742
+ try {
743
+ const res = await fetch(`${API_BASE}/api/central-update-status?path=${encodeURIComponent(customHubRoot || "")}&t=${Date.now()}`, { signal: AbortSignal.timeout(3000) });
744
+ if (res.ok) return await res.json();
745
+ } catch {}
746
+ return null;
747
+ },
748
+
749
+ // Magpie page frames are sandboxed (no network, no popups): ask the plugin
750
+ // backend through magpie.options and read its answer from omniroute-status.js
751
+ async omnirouteViaOptions(action, port, timeoutMs) {
752
+ const opt = globalThis.magpie?.options;
753
+ if (typeof opt?.get !== "function" || typeof opt?.set !== "function") return null;
754
+ const nonce = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
755
+ const requestStartTime = Date.now();
756
+ const targetPort = port || omniroutePort || 20128;
757
+
758
+ // Magpie kernel limits options.set calls ("a page sets its options once a second at most")
759
+ // Retry up to 3 times with 1100ms spacing to guarantee delivery even under rate limiting
760
+ let setSucceeded = false;
761
+ for (let attempt = 0; attempt < 3; attempt++) {
762
+ try {
763
+ const saved = (await opt.get()) || {};
764
+ await opt.set({ ...saved, omnirouteRequest: { action, port: targetPort, nonce } });
765
+ setSucceeded = true;
766
+ break;
767
+ } catch {
768
+ if (attempt < 2) await new Promise((r) => setTimeout(r, 1100));
769
+ }
770
+ }
771
+ if (!setSucceeded) return null;
772
+
773
+ const loadStatus = () => new Promise((resolve) => {
774
+ const s = document.createElement("script");
775
+ s.src = `omniroute-status.js?t=${Date.now()}`;
776
+ s.onload = () => {
777
+ s.remove();
778
+ resolve(globalThis.__OMNIROUTE_STATUS__ || null);
779
+ };
780
+ s.onerror = () => {
781
+ s.remove();
782
+ resolve(null);
783
+ };
784
+ document.head.appendChild(s);
785
+ });
786
+
787
+ // Secondary fast probe: ping local port favicon to detect listening state immediately
788
+ const probeDirectPort = () => new Promise((resolve) => {
789
+ const img = new Image();
790
+ const timer = setTimeout(() => {
791
+ img.onload = null;
792
+ img.onerror = null;
793
+ resolve(false);
794
+ }, 1000);
795
+ img.onload = () => {
796
+ clearTimeout(timer);
797
+ resolve(true);
798
+ };
799
+ img.onerror = () => {
800
+ clearTimeout(timer);
801
+ resolve(false);
802
+ };
803
+ img.src = `http://127.0.0.1:${targetPort}/favicon.ico?t=${Date.now()}`;
804
+ });
805
+
806
+ const deadline = Date.now() + timeoutMs;
807
+ let lastProbeTime = 0;
808
+ while (Date.now() < deadline) {
809
+ await new Promise((r) => setTimeout(r, 500));
810
+ const st = await loadStatus();
811
+ if (st && (st.nonce === nonce || (st.action === action && st.checkedAt && st.checkedAt >= requestStartTime))) {
812
+ // If status is still 'starting', continue waiting for final completion
813
+ if (st.running || st.state !== "starting" || (Date.now() - requestStartTime > 16000)) {
814
+ return st;
815
+ }
816
+ }
817
+
818
+ // Direct port detection as fallback for instant responsiveness
819
+ if (action === "start" && (Date.now() - lastProbeTime > 1500)) {
820
+ lastProbeTime = Date.now();
821
+ const isUp = await probeDirectPort();
822
+ if (isUp) {
823
+ return {
824
+ installed: true,
825
+ running: true,
826
+ port: targetPort,
827
+ url: `http://localhost:${targetPort}`,
828
+ action: "start",
829
+ nonce,
830
+ checkedAt: Date.now(),
831
+ };
832
+ }
833
+ }
834
+ }
835
+
836
+ return null;
837
+ },
838
+
839
+ async getOmnirouteStatus(customPort = null) {
840
+ const targetPort = customPort || omniroutePort || 20128;
841
+
842
+ // 1. In-memory / initial script status cache if fresh (< 8 seconds old)
843
+ if (globalThis.__OMNIROUTE_STATUS__?.checkedAt && (Date.now() - globalThis.__OMNIROUTE_STATUS__.checkedAt < 8000)) {
844
+ return globalThis.__OMNIROUTE_STATUS__;
845
+ }
846
+
847
+ // 2. Fast reload of omniroute-status.js via script tag (allowed under CSP script-src 'self')
848
+ try {
849
+ const scriptStatus = await new Promise((resolve) => {
850
+ const s = document.createElement("script");
851
+ s.src = `omniroute-status.js?t=${Date.now()}`;
852
+ s.onload = () => {
853
+ s.remove();
854
+ resolve(globalThis.__OMNIROUTE_STATUS__ || null);
855
+ };
856
+ s.onerror = () => {
857
+ s.remove();
858
+ resolve(null);
859
+ };
860
+ document.head.appendChild(s);
861
+ });
862
+ if (scriptStatus?.checkedAt && (Date.now() - scriptStatus.checkedAt < 12000)) {
863
+ return scriptStatus;
864
+ }
865
+ } catch {}
866
+
867
+ // 3. Magpie host IPC bridge
868
+ try {
869
+ const magpieApi = getMagpieApi();
870
+ if (typeof magpieApi?.getOmnirouteStatus === "function") {
871
+ const res = await magpieApi.getOmnirouteStatus(customPort);
872
+ if (res) return res;
873
+ }
874
+ } catch {}
875
+
876
+ // 4. Local API server endpoint
877
+ try {
878
+ const query = customPort ? `?port=${customPort}&t=${Date.now()}` : `?t=${Date.now()}`;
879
+ const res = await fetch(`${API_BASE}/api/omniroute/status${query}`, { signal: AbortSignal.timeout(2000) });
880
+ if (res.ok) return await res.json();
881
+ } catch {}
882
+
883
+ // 5. Sandboxed Magpie options watcher bridge
884
+ const viaOptions = await this.omnirouteViaOptions("status", customPort, 8000);
885
+ if (viaOptions) return viaOptions;
886
+
887
+ // 6. Direct multi-probe fallback to detect if local port is active (bypasses 307 redirect CORS issues)
888
+ const probeEndpoints = ["/api/health", "/login", "/favicon.ico", "/"];
889
+
890
+ for (const host of ["127.0.0.1", "localhost"]) {
891
+ for (const ep of probeEndpoints) {
892
+ try {
893
+ const controller = new AbortController();
894
+ const timer = setTimeout(() => controller.abort(), 1000);
895
+ await fetch(`http://${host}:${targetPort}${ep}`, {
896
+ mode: "no-cors",
897
+ cache: "no-store",
898
+ signal: controller.signal,
899
+ });
900
+ clearTimeout(timer);
901
+ return {
902
+ installed: true,
903
+ running: true,
904
+ port: targetPort,
905
+ url: `http://localhost:${targetPort}`,
906
+ };
907
+ } catch {}
908
+ }
909
+ }
910
+
911
+ // Secondary fallback: image probe on favicon.ico
912
+ try {
913
+ const imgOk = await new Promise((resolve) => {
914
+ const img = new Image();
915
+ const timer = setTimeout(() => {
916
+ img.onload = null;
917
+ img.onerror = null;
918
+ img.src = "";
919
+ resolve(false);
920
+ }, 1000);
921
+ img.onload = () => {
922
+ clearTimeout(timer);
923
+ resolve(true);
924
+ };
925
+ img.onerror = () => {
926
+ clearTimeout(timer);
927
+ resolve(false);
928
+ };
929
+ img.src = `http://127.0.0.1:${targetPort}/favicon.ico?t=${Date.now()}`;
930
+ });
931
+ if (imgOk) {
932
+ return { installed: true, running: true, port: targetPort, url: `http://localhost:${targetPort}` };
933
+ }
934
+ } catch {}
935
+
936
+ // If omniroute-status.js has a recently verified state (< 15s), use it
937
+ if (globalThis.__OMNIROUTE_STATUS__?.checkedAt && (Date.now() - globalThis.__OMNIROUTE_STATUS__.checkedAt < 15000)) {
938
+ return globalThis.__OMNIROUTE_STATUS__;
939
+ }
940
+
941
+ return { installed: false, running: false, port: targetPort, url: `http://localhost:${targetPort}` };
942
+ },
943
+
944
+ async startOmniroute(customPort = null) {
945
+ const targetPort = customPort || omniroutePort || 20128;
946
+ // 1. Magpie host API (primary direct bridge)
947
+ try {
948
+ const magpieApi = getMagpieApi();
949
+ if (typeof magpieApi?.startOmniroute === "function") {
950
+ const res = await magpieApi.startOmniroute(targetPort);
951
+ if (res && typeof res === "object") return res;
952
+ }
953
+ } catch {}
954
+
955
+ // 2. Direct simple GET to API server (avoids CORS preflight)
956
+ try {
957
+ const res = await fetch(`${API_BASE}/api/omniroute/start?port=${targetPort}&t=${Date.now()}`, {
958
+ method: "GET",
959
+ signal: AbortSignal.timeout(28000),
960
+ });
961
+ if (res.ok) {
962
+ const json = await res.json();
963
+ if (json && (json.running || json.error)) return json;
964
+ }
965
+ } catch {}
966
+
967
+ // 3. Direct POST to API server
968
+ try {
969
+ const res = await fetch(`${API_BASE}/api/omniroute/start`, {
970
+ method: "POST",
971
+ headers: { "Content-Type": "application/json" },
972
+ body: JSON.stringify({ port: targetPort }),
973
+ signal: AbortSignal.timeout(28000),
974
+ });
975
+ if (res.ok) {
976
+ const json = await res.json();
977
+ if (json && (json.running || json.error)) return json;
978
+ }
979
+ } catch {}
980
+
981
+ // 4. Dynamic script trigger (allowed under CSP script-src)
982
+ try {
983
+ const scriptRes = await new Promise((resolve) => {
984
+ const nonce = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
985
+ const s = document.createElement("script");
986
+ const timer = setTimeout(() => {
987
+ s.remove();
988
+ resolve(null);
989
+ }, 15000);
990
+ s.src = `${API_BASE}/action-omniroute.js?action=start&port=${targetPort}&nonce=${nonce}&t=${Date.now()}`;
991
+ s.onload = () => {
992
+ clearTimeout(timer);
993
+ s.remove();
994
+ resolve(globalThis.__OMNIROUTE_STATUS__ || null);
995
+ };
996
+ s.onerror = () => {
997
+ clearTimeout(timer);
998
+ s.remove();
999
+ resolve(null);
1000
+ };
1001
+ document.head.appendChild(s);
1002
+ });
1003
+ if (scriptRes?.running) return scriptRes;
1004
+ } catch {}
1005
+
1006
+ // 5. Sandboxed Magpie options watcher bridge
1007
+ return await this.omnirouteViaOptions("start", targetPort, 28000);
1008
+ },
1009
+
1010
+ async stopOmniroute(customPort = null) {
1011
+ const targetPort = customPort || omniroutePort || 20128;
1012
+ try {
1013
+ const magpieApi = getMagpieApi();
1014
+ if (typeof magpieApi?.stopOmniroute === "function") {
1015
+ const res = await magpieApi.stopOmniroute(targetPort);
1016
+ if (res) return res;
1017
+ }
1018
+ } catch {}
1019
+ try {
1020
+ const res = await fetch(`${API_BASE}/api/omniroute/stop?port=${targetPort}&t=${Date.now()}`, {
1021
+ method: "GET",
1022
+ signal: AbortSignal.timeout(10000),
1023
+ });
1024
+ if (res.ok) return await res.json();
1025
+ } catch {}
1026
+ try {
1027
+ const res = await fetch(`${API_BASE}/api/omniroute/stop`, {
1028
+ method: "POST",
1029
+ headers: { "Content-Type": "application/json" },
1030
+ body: JSON.stringify({ port: targetPort }),
1031
+ signal: AbortSignal.timeout(10000),
1032
+ keepalive: true,
1033
+ });
1034
+ if (res.ok) return await res.json();
1035
+ } catch {}
1036
+ return await this.omnirouteViaOptions("stop", targetPort, 10000);
1037
+ },
1038
+
1039
+ async openOmnirouteUrl(targetUrl = null, customPort = null) {
1040
+ const port = customPort || omniroutePort || 20128;
1041
+ const url = targetUrl || `http://localhost:${port}`;
1042
+
1043
+ // 1. Direct window.open (synchronous user gesture if possible)
1044
+ try {
1045
+ const win = window.open(url, "_blank", "noopener,noreferrer");
1046
+ if (win) {
1047
+ // Opened successfully in browser window
1048
+ }
1049
+ } catch {}
1050
+
1051
+ // 2. Direct fast call to local API server endpoint (GET query format avoids preflight)
1052
+ try {
1053
+ const getRes = await fetch(`${API_BASE}/api/omniroute/open?url=${encodeURIComponent(url)}&port=${port}`, {
1054
+ method: "GET",
1055
+ signal: AbortSignal.timeout(2000),
1056
+ });
1057
+ if (getRes.ok) return await getRes.json();
1058
+ } catch {}
1059
+
1060
+ // 3. Wails v2 runtime Go shell open (standard in Magpie desktop host)
1061
+ try {
1062
+ if (typeof window.runtime?.BrowserOpenURL === "function") {
1063
+ window.runtime.BrowserOpenURL(url);
1064
+ return { success: true, url, method: "wails-runtime" };
1065
+ }
1066
+ if (typeof window.wails?.runtime?.BrowserOpenURL === "function") {
1067
+ window.wails.runtime.BrowserOpenURL(url);
1068
+ return { success: true, url, method: "wails-runtime" };
1069
+ }
1070
+ } catch {}
1071
+
1072
+ // 4. Magpie host IPC bridge shell open
1073
+ try {
1074
+ const magpieApi = getMagpieApi();
1075
+ if (typeof magpieApi?.openOmnirouteUrl === "function") {
1076
+ const res = await magpieApi.openOmnirouteUrl(url, port);
1077
+ if (res) return res;
1078
+ }
1079
+ const magpie = globalThis.magpie;
1080
+ if (typeof magpie?.openExternal === "function") {
1081
+ magpie.openExternal(url);
1082
+ return { success: true, url, method: "magpie-openExternal" };
1083
+ }
1084
+ if (typeof magpie?.shell?.openExternal === "function") {
1085
+ magpie.shell.openExternal(url);
1086
+ return { success: true, url, method: "magpie-shell" };
1087
+ }
1088
+ if (typeof magpie?.openUrl === "function") {
1089
+ magpie.openUrl(url);
1090
+ return { success: true, url, method: "magpie-openUrl" };
1091
+ }
1092
+ } catch {}
1093
+
1094
+ // 5. Local API server POST
1095
+ try {
1096
+ const res = await fetch(`${API_BASE}/api/omniroute/open`, {
1097
+ method: "POST",
1098
+ headers: { "Content-Type": "application/json" },
1099
+ body: JSON.stringify({ url, port }),
1100
+ signal: AbortSignal.timeout(3000),
1101
+ });
1102
+ if (res.ok) return await res.json();
1103
+ } catch {}
1104
+
1105
+ // 6. Sandboxed Magpie frame: the plugin backend opens the OS default browser
1106
+ try {
1107
+ const viaOptions = await this.omnirouteViaOptions("open", port, 15000);
1108
+ if (viaOptions && (viaOptions.opened || viaOptions.action === "open")) {
1109
+ return { ...viaOptions, success: true, url };
1110
+ }
1111
+ } catch {}
1112
+
1113
+ return { success: true, url, method: "fallback" };
1114
+ },
1115
+
1116
+ async scanForeignComponents(agent) {
1117
+ try {
1118
+ const magpieApi = getMagpieApi();
1119
+ if (typeof magpieApi?.scanForeignComponents === "function") {
1120
+ const res = await magpieApi.scanForeignComponents(agent);
1121
+ if (res) return res;
1122
+ }
1123
+ } catch {}
1124
+ try {
1125
+ const res = await fetch(`${API_BASE}/api/agent/scan-foreign`, {
1126
+ method: "POST",
1127
+ headers: { "Content-Type": "application/json" },
1128
+ body: JSON.stringify({ agent }),
1129
+ signal: AbortSignal.timeout(6000),
1130
+ });
1131
+ if (res.ok) return await res.json();
1132
+ } catch {}
1133
+ return null;
1134
+ },
1135
+
1136
+ async cleanForeignComponents(components) {
1137
+ try {
1138
+ const magpieApi = getMagpieApi();
1139
+ if (typeof magpieApi?.cleanForeignComponents === "function") {
1140
+ const res = await magpieApi.cleanForeignComponents(components);
1141
+ if (res) return res;
1142
+ }
1143
+ } catch {}
1144
+ try {
1145
+ const res = await fetch(`${API_BASE}/api/agent/clean-foreign`, {
1146
+ method: "POST",
1147
+ headers: { "Content-Type": "application/json" },
1148
+ body: JSON.stringify({ components }),
1149
+ signal: AbortSignal.timeout(6000),
1150
+ });
1151
+ if (res.ok) return await res.json();
1152
+ } catch {}
1153
+ return null;
1154
+ },
1155
+ };
1156
+
1157
+ const FALLBACK_AGENT_PROFILES = [
1158
+ { id: "antigravity", label: "Antigravity (Google)", mode: "bundle", description: "Native plugin bundle support (~/.gemini/config/plugins)", capabilities: { skills: true, mcp: true, rules: true, agents: true, hooks: true }, defaultConfigPath: "~/.gemini/config/plugins" },
1159
+ { id: "claude-code", label: "Claude Code (Anthropic)", mode: "convert", description: "Skills in ~/.claude/skills, MCP in ~/.claude.json, Rules in ~/.claude/CLAUDE.md, Subagents in ~/.claude/agents", capabilities: { skills: true, mcp: true, rules: true, agents: true, hooks: false }, defaultConfigPath: "~/.claude/skills" },
1160
+ { id: "codex", label: "Codex CLI (OpenAI)", mode: "convert", description: "Skills in ~/.codex/skills, MCP in ~/.codex/config.toml, Rules in ~/.codex/AGENTS.md", capabilities: { skills: true, mcp: true, rules: true, agents: false, hooks: false }, defaultConfigPath: "~/.codex/skills" },
1161
+ { id: "opencode", label: "OpenCode", mode: "convert", description: "Skills in ~/.config/opencode/skills, MCP in opencode.json, Rules in AGENTS.md, Subagents in agents/", capabilities: { skills: true, mcp: true, rules: true, agents: true, hooks: false }, defaultConfigPath: "~/.config/opencode/skills" },
1162
+ { id: "vscode-copilot", label: "VS Code / GitHub Copilot", mode: "convert", description: "Skills in ~/.copilot/skills, MCP in Code/User/mcp.json, Instructions & Agents in Code/User/prompts", capabilities: { skills: true, mcp: true, rules: true, agents: true, hooks: false }, defaultConfigPath: "~/.copilot/skills" },
1163
+ { id: "cursor", label: "Cursor AI", mode: "convert", description: "Skills in ~/.cursor/skills, MCP in ~/.cursor/mcp.json", capabilities: { skills: true, mcp: true, rules: false, agents: false, hooks: false }, defaultConfigPath: "~/.cursor/skills" },
1164
+ { id: "windsurf", label: "Windsurf (Codeium)", mode: "convert", description: "Skills in ~/.codeium/windsurf/skills, MCP in mcp_config.json, Rules in memories/global_rules.md", capabilities: { skills: true, mcp: true, rules: true, agents: false, hooks: false }, defaultConfigPath: "~/.codeium/windsurf/skills" },
1165
+ { id: "gemini-cli", label: "Gemini CLI (Standalone)", mode: "convert", description: "Skills in ~/.gemini/skills, MCP in ~/.gemini/settings.json, Rules in ~/.gemini/GEMINI.md", capabilities: { skills: true, mcp: true, rules: true, agents: false, hooks: false }, defaultConfigPath: "~/.gemini/skills" },
1166
+ { id: "cline", label: "Cline (VS Code Extension)", mode: "convert", description: "Skills in ~/.cline/skills, MCP in cline_mcp_settings.json, Rules in ~/Documents/Cline/Rules", capabilities: { skills: true, mcp: true, rules: true, agents: false, hooks: false }, defaultConfigPath: "~/.cline/skills" },
1167
+ { id: "roo-code", label: "Roo Code", mode: "convert", description: "Skills in ~/.roo/skills, MCP in rooveterinaryinc.roo-cline mcp_settings.json, Rules in ~/.roo/rules", capabilities: { skills: true, mcp: true, rules: true, agents: false, hooks: false }, defaultConfigPath: "~/.roo/skills" },
1168
+ { id: "kiro", label: "Kiro (AWS)", mode: "convert", description: "Skills in ~/.kiro/skills, MCP in ~/.kiro/settings/mcp.json, Steering rules in ~/.kiro/steering", capabilities: { skills: true, mcp: true, rules: true, agents: false, hooks: false }, defaultConfigPath: "~/.kiro/skills" },
1169
+ { id: "agents-universal", label: "Universal Agent Skills (~/.agents/skills)", mode: "convert", description: "Shared ~/.agents/skills directory read by OpenCode, Copilot, Codex, and Antigravity", capabilities: { skills: true, mcp: false, rules: false, agents: false, hooks: false }, defaultConfigPath: "~/.agents/skills" },
1170
+ { id: "custom", label: "Custom Agent / Directory", mode: "convert", description: "User-specified target directory", capabilities: { skills: true, mcp: false, rules: false, agents: false, hooks: false }, defaultConfigPath: "~/.agent/skills" },
1171
+ ];
1172
+
1173
+ let agentProfiles = [...FALLBACK_AGENT_PROFILES];
1174
+ let lastSyncByIde = {};
1175
+ let verifiedStatusByIde = {};
1176
+ let verifiedStatusByProject = {};
1177
+
1178
+ let hubConfig = { ...DEFAULTS };
1179
+ let discoveredPlugins = [];
1180
+ let discoveredCategories = { plugins: [], mcps: [], hooks: [], skills: [], agents: [], rules: [] };
1181
+ let omniroutePort = 20128;
1182
+ let isOmnirouteRunning = false;
1183
+ let expandedFiles = new Set();
1184
+ let allFilesExpanded = false;
1185
+ let activeCategoryTab = "all";
1186
+ let categorySearchFilter = "";
1187
+ let currentSelection = { type: "ide", id: "antigravity" };
1188
+ let autoSyncTimer = null;
1189
+ let draggedItem = null;
1190
+
1191
+ const statusCheckingUI = {
1192
+ show(stepText = "Auditing connected agents & enabled plugins...", pct = 25) {
1193
+ const modal = $("statusCheckingModal");
1194
+ if (!modal) return;
1195
+ modal.style.display = "flex";
1196
+ if ($("statusCheckingTitle")) $("statusCheckingTitle").textContent = "Checking Component Status...";
1197
+ if ($("statusCheckingStep")) $("statusCheckingStep").textContent = stepText;
1198
+ if ($("statusCheckingPct")) $("statusCheckingPct").textContent = `${pct}%`;
1199
+ if ($("statusCheckingProgressBar")) $("statusCheckingProgressBar").style.width = `${pct}%`;
1200
+ if ($("statusCheckingSummary")) $("statusCheckingSummary").style.display = "none";
1201
+ if ($("btnDoneStatusCheck")) $("btnDoneStatusCheck").style.display = "none";
1202
+ if ($("btnBackgroundStatusCheck")) $("btnBackgroundStatusCheck").style.display = "inline-block";
1203
+ if ($("statusCheckingSpinner")) $("statusCheckingSpinner").style.display = "inline-block";
1204
+ if ($("statusCheckingFooterNote")) $("statusCheckingFooterNote").textContent = "Checking status dots in background...";
1205
+
1206
+ this.renderAgentItems();
1207
+ },
1208
+
1209
+ update(stepText, pct) {
1210
+ const modal = $("statusCheckingModal");
1211
+ if (!modal || modal.style.display !== "flex") return;
1212
+ if (stepText && $("statusCheckingStep")) $("statusCheckingStep").textContent = stepText;
1213
+ if (pct !== undefined) {
1214
+ if ($("statusCheckingPct")) $("statusCheckingPct").textContent = `${pct}%`;
1215
+ if ($("statusCheckingProgressBar")) $("statusCheckingProgressBar").style.width = `${pct}%`;
1216
+ }
1217
+ this.renderAgentItems();
1218
+ },
1219
+
1220
+ finish(summaryText = "Status Check Complete! Verified all enabled plugins.") {
1221
+ const modal = $("statusCheckingModal");
1222
+ if (!modal || modal.style.display !== "flex") return;
1223
+ if ($("statusCheckingTitle")) $("statusCheckingTitle").textContent = "Component Status Verified";
1224
+ if ($("statusCheckingStep")) $("statusCheckingStep").textContent = "✓ Status verification complete";
1225
+ if ($("statusCheckingPct")) $("statusCheckingPct").textContent = "100%";
1226
+ if ($("statusCheckingProgressBar")) $("statusCheckingProgressBar").style.width = "100%";
1227
+ if ($("statusCheckingSpinner")) $("statusCheckingSpinner").style.display = "none";
1228
+ if ($("statusCheckingSummary")) {
1229
+ $("statusCheckingSummary").style.display = "block";
1230
+ $("statusCheckingSummary").innerHTML = `<strong>Status Check Complete!</strong> ${escapeHtml(summaryText)}`;
1231
+ }
1232
+ if ($("statusCheckingFooterNote")) $("statusCheckingFooterNote").textContent = "All component status dots up to date.";
1233
+ if ($("btnDoneStatusCheck")) $("btnDoneStatusCheck").style.display = "inline-block";
1234
+ if ($("btnBackgroundStatusCheck")) $("btnBackgroundStatusCheck").style.display = "none";
1235
+
1236
+ this.renderAgentItems();
1237
+
1238
+ setTimeout(() => {
1239
+ if (modal.style.display === "flex") {
1240
+ modal.style.display = "none";
1241
+ }
1242
+ }, 1200);
1243
+ },
1244
+
1245
+ hide() {
1246
+ const modal = $("statusCheckingModal");
1247
+ if (modal) modal.style.display = "none";
1248
+ },
1249
+
1250
+ renderAgentItems() {
1251
+ const container = $("statusCheckingAgentList");
1252
+ if (!container) return;
1253
+ const agents = (hubConfig.ides || []).filter((i) => i && i.enabled !== false);
1254
+ if (agents.length === 0) {
1255
+ container.innerHTML = `<div style="color:var(--magpie-muted); padding:4px;">No connected agents to verify.</div>`;
1256
+ return;
1257
+ }
1258
+
1259
+ container.innerHTML = agents.map((ide) => {
1260
+ const enabledCount = Object.values(ide.plugins || {}).filter((v) => v === true).length;
1261
+ const verifiedMap = verifiedStatusByIde[ide.id] || {};
1262
+ const isVerified = Object.keys(verifiedMap).length > 0;
1263
+ const statusBadge = isVerified
1264
+ ? `<span style="font-size:10.5px; padding:2px 8px; border-radius:4px; background:rgba(34,197,94,0.15); color:#22c55e; font-weight:600;">🟢 Verified</span>`
1265
+ : `<span style="font-size:10.5px; padding:2px 8px; border-radius:4px; background:rgba(96,165,250,0.15); color:#60a5fa; font-weight:600;">Checking...</span>`;
1266
+ return `
1267
+ <div style="display:flex; justify-content:space-between; align-items:center; padding:6px 10px; border-radius:6px; background:var(--magpie-surface-alt, rgba(255,255,255,0.02)); border:1px solid var(--magpie-border, #333);">
1268
+ <div>
1269
+ <span style="font-weight:600;">${escapeHtml(ide.name || ide.id)}</span>
1270
+ <span style="font-size:11px; color:var(--magpie-muted); margin-left:6px;">(${enabledCount} enabled plugins)</span>
1271
+ </div>
1272
+ ${statusBadge}
1273
+ </div>
1274
+ `;
1275
+ }).join("");
1276
+ }
1277
+ };
1278
+
1279
+ // 1. Handshake with Magpie bridge safely
1280
+ try {
1281
+ if (globalThis.magpie?.ready) {
1282
+ await Promise.race([
1283
+ globalThis.magpie.ready,
1284
+ new Promise((resolve) => setTimeout(resolve, 800)),
1285
+ ]);
1286
+ }
1287
+ } catch (err) {
1288
+ console.warn("Magpie bridge handshake timeout/skip:", err);
1289
+ }
1290
+
1291
+ // 2. Read saved config from local API server first
1292
+ try {
1293
+ const backendConfig = await apiClient.getConfig();
1294
+ if (backendConfig?.ides && Array.isArray(backendConfig.ides)) {
1295
+ hubConfig = backendConfig;
1296
+ }
1297
+ } catch (err) {
1298
+ console.warn("Failed to load hubConfig from API server:", err);
1299
+ }
1300
+
1301
+ // 3. Read saved options from Magpie
1302
+ try {
1303
+ if (globalThis.magpie?.options?.get) {
1304
+ const saved = await globalThis.magpie.options.get();
1305
+ if (saved && typeof saved === "object") {
1306
+ if (saved.hubConfig) hubConfig = saved.hubConfig;
1307
+ if (saved.smartMiddlewareEnabled !== undefined) {
1308
+ if (!hubConfig.smartMiddleware) hubConfig.smartMiddleware = {};
1309
+ hubConfig.smartMiddleware.enabled = Boolean(saved.smartMiddlewareEnabled);
1310
+ }
1311
+ if (saved.maxTools !== undefined && Number.isInteger(saved.maxTools)) {
1312
+ if (!hubConfig.smartMiddleware) hubConfig.smartMiddleware = {};
1313
+ hubConfig.smartMiddleware.maxTools = saved.maxTools;
1314
+ }
1315
+ if (saved.toolsRoot !== undefined) {
1316
+ hubConfig.hubRoot = saved.toolsRoot;
1317
+ }
1318
+ }
1319
+ }
1320
+ } catch (err) {
1321
+ console.warn("Failed to load options from Magpie:", err);
1322
+ }
1323
+
1324
+ // Read from localStorage fallback
1325
+ try {
1326
+ const local = localStorage.getItem("magpie_agent_space_config");
1327
+ if (local && !Array.isArray(hubConfig.ides)) {
1328
+ const parsed = JSON.parse(local);
1329
+ if (parsed?.ides) hubConfig = parsed;
1330
+ }
1331
+ } catch {}
1332
+
1333
+ // Ensure default Antigravity IDE is present ONLY on first run if ides was never configured
1334
+ if (!Array.isArray(hubConfig.ides)) {
1335
+ hubConfig.ides = [
1336
+ {
1337
+ id: "antigravity",
1338
+ name: "Antigravity (Google Gemini)",
1339
+ agentType: "antigravity",
1340
+ exePath: "",
1341
+ configPath: "",
1342
+ enabled: true,
1343
+ plugins: {},
1344
+ },
1345
+ ];
1346
+ }
1347
+
1348
+ // 4. Query live agent profiles and plugins from active storage path
1349
+ try {
1350
+ const liveProfiles = await apiClient.getAgentProfiles();
1351
+ if (Array.isArray(liveProfiles) && liveProfiles.length > 0) {
1352
+ agentProfiles = liveProfiles;
1353
+ }
1354
+ } catch {}
1355
+ await reloadPluginsFromHub();
1356
+
1357
+ // 4b. On startup: check for modification difference in Components Storage Path and recheck status dots for each enabled plugin in each connected agent!
1358
+ let startupSyncResult = null;
1359
+ statusCheckingUI.show("Auditing connected agents & enabled plugin status dots...", 25);
1360
+ try {
1361
+ startupSyncResult = await apiClient.startupSync(hubConfig);
1362
+ statusCheckingUI.update("Inspecting component files & directories on disk...", 75);
1363
+ if (startupSyncResult?.statusByIde) {
1364
+ verifiedStatusByIde = startupSyncResult.statusByIde;
1365
+ }
1366
+ if (startupSyncResult?.statusByProject) {
1367
+ verifiedStatusByProject = startupSyncResult.statusByProject;
1368
+ }
1369
+ if (startupSyncResult?.sync?.results && Array.isArray(startupSyncResult.sync.results)) {
1370
+ for (const r of startupSyncResult.sync.results) {
1371
+ if (r.ideId) lastSyncByIde[r.ideId] = r;
1372
+ }
1373
+ }
1374
+ if (startupSyncResult?.hasChanges && startupSyncResult?.autoReconnected) {
1375
+ await reloadPluginsFromHub(true);
1376
+ }
1377
+ statusCheckingUI.finish(
1378
+ startupSyncResult?.autoReconnected
1379
+ ? "Auto-reconnected and verified all enabled plugin status dots across connected agents."
1380
+ : "Verified all enabled plugin status dots across connected agents."
1381
+ );
1382
+ } catch (err) {
1383
+ console.warn("Startup modification check/reconnect failed:", err);
1384
+ statusCheckingUI.hide();
1385
+ }
1386
+
1387
+ let editingIdeId = null;
1388
+ let editingProjectId = null;
1389
+
1390
+ function populateComponentPathsInputs(agentType, componentPaths = null) {
1391
+ const prof = agentProfiles.find((p) => p.id === agentType) || agentProfiles[0];
1392
+ const defaults = prof?.defaultComponentPaths || {};
1393
+ const current = componentPaths || {};
1394
+
1395
+ if ($("cpBundleInput")) $("cpBundleInput").value = current.bundle || (prof?.mode === "bundle" ? (prof?.defaultConfigPath || "") : "");
1396
+ if ($("cpSkillsInput")) $("cpSkillsInput").value = current.skills || defaults.skills || (prof?.mode !== "bundle" ? (prof?.defaultConfigPath || "") : "");
1397
+ if ($("cpCommandsInput")) $("cpCommandsInput").value = current.commands || defaults.commands || "";
1398
+ if ($("cpMcpInput")) $("cpMcpInput").value = current.mcp || defaults.mcp || "";
1399
+ if ($("cpRulesInput")) $("cpRulesInput").value = current.rules || defaults.rules || "";
1400
+ if ($("cpAgentsInput")) $("cpAgentsInput").value = current.agents || defaults.agents || "";
1401
+ if ($("cpHooksInput")) $("cpHooksInput").value = current.hooks || defaults.hooks || "";
1402
+ }
1403
+
1404
+ function collectComponentPathsFromInputs() {
1405
+ const res = {};
1406
+ const b = $("cpBundleInput")?.value?.trim();
1407
+ const s = $("cpSkillsInput")?.value?.trim();
1408
+ const c = $("cpCommandsInput")?.value?.trim();
1409
+ const m = $("cpMcpInput")?.value?.trim();
1410
+ const r = $("cpRulesInput")?.value?.trim();
1411
+ const a = $("cpAgentsInput")?.value?.trim();
1412
+ const h = $("cpHooksInput")?.value?.trim();
1413
+ if (b) res.bundle = b;
1414
+ if (s) res.skills = s;
1415
+ if (c) res.commands = c;
1416
+ if (m) res.mcp = m;
1417
+ if (r) res.rules = r;
1418
+ if (a) res.agents = a;
1419
+ if (h) res.hooks = h;
1420
+ return res;
1421
+ }
1422
+
1423
+ function renderSelectedAgentMeta(agentId) {
1424
+ const prof = agentProfiles.find((p) => p.id === agentId) || agentProfiles[0];
1425
+ if (!prof) return;
1426
+ const chipsEl = $("agentCapabilityChips");
1427
+ if (chipsEl) {
1428
+ const caps = [
1429
+ { key: "skills", label: "Skills" },
1430
+ { key: "mcp", label: "MCP" },
1431
+ { key: "rules", label: "Rules" },
1432
+ { key: "agents", label: "Subagents" },
1433
+ { key: "hooks", label: "Hooks" },
1434
+ ];
1435
+ chipsEl.innerHTML = caps.map((c) => {
1436
+ const ok = prof.capabilities?.[c.key];
1437
+ const bg = ok ? "rgba(22,163,74,0.14)" : "rgba(128,128,128,0.1)";
1438
+ const fg = ok ? "#16a34a" : "var(--magpie-muted)";
1439
+ return `<span style="font-size:10.5px; font-weight:600; padding:2px 7px; border-radius:4px; background:${bg}; color:${fg};">${c.label} ${ok ? "✓" : "–"}</span>`;
1440
+ }).join("");
1441
+ }
1442
+ const pathsEl = $("agentTargetPaths");
1443
+ if (pathsEl) {
1444
+ pathsEl.textContent = prof.description || `Default link path: ${prof.defaultConfigPath}`;
1445
+ }
1446
+ if (!editingIdeId) {
1447
+ populateComponentPathsInputs(agentId);
1448
+ }
1449
+ }
1450
+
1451
+ function setComponentPathsCollapsed(collapsed) {
1452
+ const body = $("componentPathsBody");
1453
+ const toggleBtn = $("btnToggleComponentPaths");
1454
+ const toggleIcon = $("componentPathsToggleIcon");
1455
+ const resetBtn = $("btnResetComponentPaths");
1456
+ if (!body) return;
1457
+ if (collapsed) {
1458
+ body.style.display = "none";
1459
+ if (toggleBtn) toggleBtn.textContent = "▶ Expand";
1460
+ if (toggleIcon) toggleIcon.textContent = "▶";
1461
+ if (resetBtn) resetBtn.style.display = "none";
1462
+ } else {
1463
+ body.style.display = "block";
1464
+ if (toggleBtn) toggleBtn.textContent = "▲ Minimize";
1465
+ if (toggleIcon) toggleIcon.textContent = "▼";
1466
+ if (resetBtn) resetBtn.style.display = "inline-block";
1467
+ }
1468
+ }
1469
+
1470
+ function openEditIdeModal(ide) {
1471
+ editingIdeId = ide.id;
1472
+ if ($("addIdeModal")) $("addIdeModal").style.display = "flex";
1473
+ const titleEl = $("addIdeModal")?.querySelector(".modal-head h3");
1474
+ if (titleEl) titleEl.textContent = `Edit Agent IDE (${ide.name})`;
1475
+ if ($("saveIdeBtn")) $("saveIdeBtn").textContent = "Save Changes";
1476
+
1477
+ if ($("ideNameInput")) $("ideNameInput").value = ide.name || "";
1478
+ if ($("ideExeInput")) $("ideExeInput").value = ide.exePath || "";
1479
+ if ($("agentTypeSelect")) $("agentTypeSelect").value = ide.agentType || "antigravity";
1480
+ if ($("ideConfigInput")) {
1481
+ $("ideConfigInput").value = ide.configPath || "";
1482
+ $("ideConfigInput").readOnly = false;
1483
+ }
1484
+ if ($("autoDetectConfigToggle")) $("autoDetectConfigToggle").checked = false;
1485
+ if ($("autoDetectLabel")) {
1486
+ $("autoDetectLabel").textContent = "Auto-detect: OFF (Custom)";
1487
+ $("autoDetectLabel").style.color = "var(--magpie-muted)";
1488
+ }
1489
+ renderSelectedAgentMeta(ide.agentType || "antigravity");
1490
+ populateComponentPathsInputs(ide.agentType, ide.componentPaths);
1491
+
1492
+ const hasCustomPaths = ide.componentPaths && Object.values(ide.componentPaths).some((v) => Boolean(v));
1493
+ setComponentPathsCollapsed(!hasCustomPaths);
1494
+ }
1495
+
1496
+ function openEditProjectModal(proj) {
1497
+ editingProjectId = proj.id;
1498
+ if ($("addProjectModal")) $("addProjectModal").style.display = "flex";
1499
+ if ($("projectModalTitle")) $("projectModalTitle").textContent = `Edit Project Repository (${proj.name})`;
1500
+ if ($("saveProjectBtn")) $("saveProjectBtn").textContent = "Save Changes";
1501
+ if ($("projectNameInput")) $("projectNameInput").value = proj.name || "";
1502
+ if ($("projectPathInput")) $("projectPathInput").value = proj.repoPath || "";
1503
+
1504
+ const select = $("projectIdeSelect");
1505
+ if (select) {
1506
+ select.innerHTML = "";
1507
+ hubConfig.ides.forEach((ide) => {
1508
+ const opt = document.createElement("option");
1509
+ opt.value = ide.id;
1510
+ opt.textContent = ide.name;
1511
+ if (ide.id === proj.ideId) opt.selected = true;
1512
+ select.appendChild(opt);
1513
+ });
1514
+ }
1515
+ }
1516
+
1517
+ // 5. Render initial view and setup listeners
1518
+ renderAll();
1519
+ setupEventListeners();
1520
+ renderStartupReconnectStatus(startupSyncResult);
1521
+ setupOmnirouteCapsule();
1522
+ checkOmniroute(false);
1523
+
1524
+ // 6. Post-Startup Status Dot Rechecker:
1525
+ // Rechecks the workability status dot for each enabled plugin across all connected agents after startup,
1526
+ // ensuring that after Magpie is closed or task-killed, live status dots accurately reflect on-disk state.
1527
+ function updateStatusDotsInDom() {
1528
+ const tableBody = $("pluginTableBody");
1529
+ if (!tableBody) return;
1530
+ const rows = tableBody.querySelectorAll("tr");
1531
+ rows.forEach((row) => {
1532
+ const toggle = row.querySelector(".plugin-toggle");
1533
+ if (!toggle) return;
1534
+ const pluginId = toggle.dataset.plugin;
1535
+ const plugin = discoveredPlugins.find((p) => p.id === pluginId);
1536
+ if (!plugin) return;
1537
+ const workability = evaluateComponentWorkability(plugin);
1538
+ const dot = row.querySelector(".component-status-dot");
1539
+ if (dot) {
1540
+ dot.className = `component-status-dot dot-${workability.color}`;
1541
+ dot.title = workability.tooltip;
1542
+ dot.setAttribute("aria-label", workability.summary);
1543
+ }
1544
+ });
1545
+ }
1546
+
1547
+ let isRecheckingStatusDots = false;
1548
+ async function recheckAllStatusDots(updateDom = true, showProgress = false) {
1549
+ if (isRecheckingStatusDots) return;
1550
+ isRecheckingStatusDots = true;
1551
+ if (showProgress) {
1552
+ statusCheckingUI.show("Auditing connected agents & enabled plugin status dots...", 35);
1553
+ }
1554
+ try {
1555
+ const res = await apiClient.recheckStatus(hubConfig);
1556
+ if (res?.statusByIde) {
1557
+ verifiedStatusByIde = res.statusByIde;
1558
+ }
1559
+ if (res?.statusByProject) {
1560
+ verifiedStatusByProject = res.statusByProject;
1561
+ }
1562
+ if (updateDom) {
1563
+ updateStatusDotsInDom();
1564
+ }
1565
+ if (showProgress) {
1566
+ statusCheckingUI.finish(`Verified ${res?.totalChecked || 0} component status dots across connected agents.`);
1567
+ }
1568
+ } catch {
1569
+ if (showProgress) statusCheckingUI.hide();
1570
+ } finally {
1571
+ isRecheckingStatusDots = false;
1572
+ }
1573
+ }
1574
+
1575
+ // Trigger post-startup status rechecks (runs during and after startup initialization)
1576
+ setTimeout(() => recheckAllStatusDots(true), 150);
1577
+ setTimeout(() => recheckAllStatusDots(true), 1200);
1578
+
1579
+ // Recheck status dots when Magpie window gains focus or visibility (e.g. after Magpie was reopened or un-minimized)
1580
+ window.addEventListener("focus", () => {
1581
+ recheckAllStatusDots(true);
1582
+ checkOmniroute(false);
1583
+ });
1584
+ document.addEventListener("visibilitychange", () => {
1585
+ if (!document.hidden) {
1586
+ recheckAllStatusDots(true);
1587
+ checkOmniroute(false);
1588
+ }
1589
+ });
1590
+
1591
+ // Background status dot watcher (throttled to >= 2000ms conforming to Safety Invariant 7)
1592
+ const statusWatcherInterval = setInterval(() => {
1593
+ recheckAllStatusDots(true);
1594
+ checkOmniroute(false);
1595
+ }, 5000);
1596
+ if (typeof statusWatcherInterval.unref === "function") {
1597
+ statusWatcherInterval.unref();
1598
+ }
1599
+
1600
+ async function reloadPluginsFromHub(forceReloadScript = false) {
1601
+ const effective = computeEffectiveHubPath();
1602
+ const targetPath = effective.path;
1603
+ discoveredCategories = { plugins: [], mcps: [], hooks: [], skills: [], agents: [], rules: [] };
1604
+ const plugins = await apiClient.getPlugins(targetPath, forceReloadScript);
1605
+ discoveredPlugins = Array.isArray(plugins) ? plugins : [];
1606
+ if (discoveredPlugins.length === 0) {
1607
+ discoveredCategories = { plugins: [], mcps: [], hooks: [], skills: [], agents: [], rules: [] };
1608
+ } else if (!discoveredCategories.plugins || discoveredCategories.plugins.length === 0) {
1609
+ discoveredCategories = buildClientCategoriesRegistry(discoveredPlugins);
1610
+ }
1611
+ }
1612
+
1613
+ function getFirstIdeConfigPath() {
1614
+ if (hubConfig.ides && hubConfig.ides.length > 0 && hubConfig.ides[0].configPath) {
1615
+ return hubConfig.ides[0].configPath;
1616
+ }
1617
+ return "";
1618
+ }
1619
+
1620
+ function computeEffectiveHubPath() {
1621
+ if (hubConfig.hubRoot && hubConfig.hubRoot.trim() !== "") {
1622
+ const cleaned = hubConfig.hubRoot.trim().replace(/^["']+|["']+$/g, "").trim();
1623
+ return { path: cleaned, isAuto: false };
1624
+ }
1625
+ const fallback = (hubConfig.defaultHubRoot || "~/AI-Agent-Space").trim().replace(/^["']+|["']+$/g, "").trim();
1626
+ return { path: fallback, isAuto: true };
1627
+ }
1628
+
1629
+ function computeComponentCounts() {
1630
+ let plugins = discoveredPlugins.length;
1631
+ let mcps = 0;
1632
+ let hooks = 0;
1633
+ let skills = 0;
1634
+ let agents = 0;
1635
+ let rules = 0;
1636
+
1637
+ discoveredPlugins.forEach((p) => {
1638
+ if (p.hasMcp) mcps += (p.mcps?.length || 1);
1639
+ if (p.hasHooks) hooks += (p.hooks?.length || 1);
1640
+ skills += (p.skills || []).length;
1641
+ agents += (p.agents || []).length;
1642
+ rules += (p.rules || []).length;
1643
+ });
1644
+
1645
+ return { plugins, mcps, hooks, skills, agents, rules };
1646
+ }
1647
+
1648
+ function buildClientCategoriesRegistry(plugins = []) {
1649
+ const categories = {
1650
+ plugins: [],
1651
+ mcps: [],
1652
+ hooks: [],
1653
+ skills: [],
1654
+ agents: [],
1655
+ rules: [],
1656
+ };
1657
+ const seenSkills = new Set();
1658
+ const seenMcps = new Set();
1659
+ const seenHooks = new Set();
1660
+ const seenAgents = new Set();
1661
+ const seenRules = new Set();
1662
+
1663
+ for (const p of plugins) {
1664
+ ensurePluginFiles(p);
1665
+ categories.plugins.push({
1666
+ id: p.id,
1667
+ name: p.name,
1668
+ version: p.version,
1669
+ path: p.path,
1670
+ description: p.description,
1671
+ skillsCount: (p.skills || []).length,
1672
+ filesCount: (p.files || []).length,
1673
+ files: p.files,
1674
+ hasMcp: p.hasMcp,
1675
+ hasHooks: p.hasHooks,
1676
+ });
1677
+
1678
+ for (const s of (p.skills || [])) {
1679
+ if (!seenSkills.has(s)) {
1680
+ seenSkills.add(s);
1681
+ categories.skills.push({
1682
+ name: s,
1683
+ pluginId: p.id,
1684
+ pluginName: p.name,
1685
+ sourcePath: p.isRootSkills ? `${p.path}\\${s}` : `${p.path}\\skills\\${s}`,
1686
+ });
1687
+ }
1688
+ }
1689
+
1690
+ for (const m of (p.mcps || (p.hasMcp ? [p.id] : []))) {
1691
+ if (!seenMcps.has(m)) {
1692
+ seenMcps.add(m);
1693
+ categories.mcps.push({
1694
+ name: m,
1695
+ pluginId: p.id,
1696
+ pluginName: p.name,
1697
+ sourcePath: `${p.path}\\mcp_config.json`,
1698
+ });
1699
+ }
1700
+ }
1701
+
1702
+ if (p.hasHooks) {
1703
+ const hookId = `${p.id}-hooks`;
1704
+ if (!seenHooks.has(hookId)) {
1705
+ seenHooks.add(hookId);
1706
+ categories.hooks.push({
1707
+ name: `${p.name} Hooks`,
1708
+ pluginId: p.id,
1709
+ pluginName: p.name,
1710
+ sourcePath: `${p.path}\\hooks.json`,
1711
+ });
1712
+ }
1713
+ }
1714
+
1715
+ for (const a of (p.agents || [])) {
1716
+ if (!seenAgents.has(a)) {
1717
+ seenAgents.add(a);
1718
+ categories.agents.push({
1719
+ name: a,
1720
+ pluginId: p.id,
1721
+ pluginName: p.name,
1722
+ sourcePath: `${p.path}\\agents\\${a}`,
1723
+ });
1724
+ }
1725
+ }
1726
+
1727
+ for (const r of (p.rules || [])) {
1728
+ if (!seenRules.has(r)) {
1729
+ seenRules.add(r);
1730
+ categories.rules.push({
1731
+ name: r,
1732
+ pluginId: p.id,
1733
+ pluginName: p.name,
1734
+ sourcePath: `${p.path}\\rules\\${r}`,
1735
+ });
1736
+ }
1737
+ }
1738
+ }
1739
+
1740
+ return categories;
1741
+ }
1742
+
1743
+ function renderCategoryBrowser() {
1744
+ const cats = (discoveredCategories && typeof discoveredCategories === "object" && Array.isArray(discoveredCategories.plugins) && discoveredCategories.plugins.length > 0)
1745
+ ? discoveredCategories
1746
+ : buildClientCategoriesRegistry(discoveredPlugins);
1747
+
1748
+ const pLen = (cats.plugins || []).length;
1749
+ const mLen = (cats.mcps || []).length;
1750
+ const hLen = (cats.hooks || []).length;
1751
+ const sLen = (cats.skills || []).length;
1752
+ const aLen = (cats.agents || []).length;
1753
+ const rLen = (cats.rules || []).length;
1754
+ const totalCount = (pLen + mLen + hLen + sLen + aLen + rLen);
1755
+
1756
+ if ($("cat-cnt-total")) $("cat-cnt-total").textContent = totalCount;
1757
+ if ($("cat-cnt-all")) $("cat-cnt-all").textContent = totalCount;
1758
+ if ($("cat-cnt-plugins")) $("cat-cnt-plugins").textContent = pLen;
1759
+ if ($("cat-cnt-mcps")) $("cat-cnt-mcps").textContent = mLen;
1760
+ if ($("cat-cnt-hooks")) $("cat-cnt-hooks").textContent = hLen;
1761
+ if ($("cat-cnt-skills")) $("cat-cnt-skills").textContent = sLen;
1762
+ if ($("cat-cnt-agents")) $("cat-cnt-agents").textContent = aLen;
1763
+ if ($("cat-cnt-rules")) $("cat-cnt-rules").textContent = rLen;
1764
+
1765
+ const container = $("categoryItemsContainer");
1766
+ if (!container) return;
1767
+
1768
+ if (totalCount === 0) {
1769
+ container.innerHTML = `<div style="text-align:center; padding:16px; color:var(--magpie-muted);">No components discovered in this storage path.</div>`;
1770
+ return;
1771
+ }
1772
+
1773
+ let items = [];
1774
+ if (activeCategoryTab === "all" || activeCategoryTab === "plugins") {
1775
+ items.push(...cats.plugins.map(p => ({
1776
+ type: "plugin",
1777
+ badge: "🧩 Plugin",
1778
+ name: p.name,
1779
+ sub: p.version ? `v${p.version}` : "",
1780
+ path: p.path,
1781
+ desc: p.description,
1782
+ })));
1783
+ }
1784
+ if (activeCategoryTab === "all" || activeCategoryTab === "mcps") {
1785
+ items.push(...cats.mcps.map(m => ({
1786
+ type: "mcp",
1787
+ badge: "⚡ MCP Server",
1788
+ name: m.name,
1789
+ sub: m.pluginName ? `from ${m.pluginName}` : "",
1790
+ path: m.sourcePath,
1791
+ desc: "Model Context Protocol Server",
1792
+ })));
1793
+ }
1794
+ if (activeCategoryTab === "all" || activeCategoryTab === "hooks") {
1795
+ items.push(...cats.hooks.map(h => ({
1796
+ type: "hook",
1797
+ badge: "🪝 Hook",
1798
+ name: h.name,
1799
+ sub: h.pluginName ? `from ${h.pluginName}` : "",
1800
+ path: h.sourcePath,
1801
+ desc: "Execution Lifecycle Middleware Hook",
1802
+ })));
1803
+ }
1804
+ if (activeCategoryTab === "all" || activeCategoryTab === "skills") {
1805
+ items.push(...cats.skills.map(s => ({
1806
+ type: "skill",
1807
+ badge: "🎯 Skill",
1808
+ name: s.name,
1809
+ sub: s.pluginName ? `from ${s.pluginName}` : "",
1810
+ path: s.sourcePath,
1811
+ desc: "Agent Skill Instruction / SKILL.md",
1812
+ })));
1813
+ }
1814
+ if (activeCategoryTab === "all" || activeCategoryTab === "agents") {
1815
+ items.push(...cats.agents.map(a => ({
1816
+ type: "agent",
1817
+ badge: "🤖 Agent",
1818
+ name: a.name,
1819
+ sub: a.pluginName ? `from ${a.pluginName}` : "",
1820
+ path: a.sourcePath,
1821
+ desc: "Subagent Definition Template",
1822
+ })));
1823
+ }
1824
+ if (activeCategoryTab === "all" || activeCategoryTab === "rules") {
1825
+ items.push(...cats.rules.map(r => ({
1826
+ type: "rule",
1827
+ badge: "📜 Rule",
1828
+ name: r.name,
1829
+ sub: r.pluginName ? `from ${r.pluginName}` : "",
1830
+ path: r.sourcePath,
1831
+ desc: "System Instruction & Rule Spec",
1832
+ })));
1833
+ }
1834
+
1835
+ if (categorySearchFilter) {
1836
+ const q = categorySearchFilter.toLowerCase();
1837
+ items = items.filter(it =>
1838
+ it.name.toLowerCase().includes(q) ||
1839
+ it.sub.toLowerCase().includes(q) ||
1840
+ (it.path && it.path.toLowerCase().includes(q))
1841
+ );
1842
+ }
1843
+
1844
+ if (items.length === 0) {
1845
+ container.innerHTML = `<div style="text-align:center; padding:16px; color:var(--magpie-muted);">No items match the selected filter.</div>`;
1846
+ return;
1847
+ }
1848
+
1849
+ container.innerHTML = items.map(it => `
1850
+ <div class="cat-item-row">
1851
+ <div class="cat-item-title">
1852
+ <span style="font-size:10.5px; font-weight:600; padding:2px 6px; border-radius:4px; background:rgba(37,99,235,0.12); color:#2563eb;">${escapeHtml(it.badge)}</span>
1853
+ <span><strong>${escapeHtml(it.name)}</strong></span>
1854
+ ${it.sub ? `<span style="font-size:11px; opacity:0.75;">(${escapeHtml(it.sub)})</span>` : ""}
1855
+ </div>
1856
+ <div class="cat-item-meta" title="${escapeHtml(it.path || "")}">
1857
+ ${escapeHtml(it.path ? it.path.split(/[/\\]/).slice(-2).join("/") : "")}
1858
+ </div>
1859
+ </div>
1860
+ `).join("");
1861
+ }
1862
+
1863
+ function renderAll() {
1864
+ const isSmEnabled = hubConfig.smartMiddleware?.enabled !== false;
1865
+ const currentCap = Number(hubConfig.smartMiddleware?.maxTools) || 96;
1866
+
1867
+ if ($("smartMiddlewareToggle")) $("smartMiddlewareToggle").checked = isSmEnabled;
1868
+ if ($("middlewareStatusLabel")) {
1869
+ $("middlewareStatusLabel").textContent = isSmEnabled
1870
+ ? "Smart Middleware: Active"
1871
+ : "Smart Middleware: Bypassed";
1872
+ $("middlewareStatusLabel").className = `toggle-label ${isSmEnabled ? "" : "disabled"}`;
1873
+ }
1874
+ if ($("gatewayStatus")) {
1875
+ $("gatewayStatus").textContent = isSmEnabled ? "Active" : "Disabled";
1876
+ }
1877
+ if ($("maxToolsInput")) {
1878
+ $("maxToolsInput").value = currentCap;
1879
+ }
1880
+ if ($("capSubtitle")) {
1881
+ $("capSubtitle").textContent = isSmEnabled
1882
+ ? `Capping at ${currentCap} safe tools for Smart Middleware`
1883
+ : "Optimization bypassed";
1884
+ }
1885
+
1886
+ // Hub Storage Path rendering
1887
+ const effectiveHub = computeEffectiveHubPath();
1888
+ if ($("hubPathInput")) {
1889
+ if (document.activeElement !== $("hubPathInput")) {
1890
+ $("hubPathInput").value = hubConfig.hubRoot || "";
1891
+ }
1892
+ $("hubPathInput").placeholder = `Default Hub: ${effectiveHub.path}`;
1893
+ }
1894
+ if ($("hubPathBadge")) {
1895
+ if (hubConfig.hubRoot && hubConfig.hubRoot.trim() !== "") {
1896
+ if (discoveredPlugins.length === 0) {
1897
+ $("hubPathBadge").textContent = "Invalid / 0 Components";
1898
+ $("hubPathBadge").className = "hub-path-badge disabled";
1899
+ } else {
1900
+ $("hubPathBadge").textContent = "Custom Path";
1901
+ $("hubPathBadge").className = "hub-path-badge";
1902
+ }
1903
+ } else {
1904
+ $("hubPathBadge").textContent = "Default Hub";
1905
+ $("hubPathBadge").className = "hub-path-badge auto";
1906
+ }
1907
+ }
1908
+ if ($("hubPathHint")) {
1909
+ if (hubConfig.hubRoot && hubConfig.hubRoot.trim() !== "") {
1910
+ $("hubPathHint").textContent = discoveredPlugins.length === 0
1911
+ ? `⚠️ Directory not found or contains 0 components: ${effectiveHub.path}`
1912
+ : `Active components storage: ${effectiveHub.path}`;
1913
+ } else {
1914
+ $("hubPathHint").textContent = `Using central Hub root: ${effectiveHub.path}`;
1915
+ }
1916
+ }
1917
+
1918
+ // Metric tiles - 7 lines breakdown
1919
+ const counts = computeComponentCounts();
1920
+ if ($("cnt-plugins")) $("cnt-plugins").textContent = String(counts.plugins);
1921
+ if ($("cnt-mcps")) $("cnt-mcps").textContent = String(counts.mcps);
1922
+ if ($("cnt-hooks")) $("cnt-hooks").textContent = String(counts.hooks);
1923
+ if ($("cnt-skills")) $("cnt-skills").textContent = String(counts.skills);
1924
+ if ($("cnt-agents")) $("cnt-agents").textContent = String(counts.agents);
1925
+ if ($("cnt-rules")) $("cnt-rules").textContent = String(counts.rules);
1926
+
1927
+ if ($("ideCount")) $("ideCount").textContent = String(hubConfig.ides?.length || 0);
1928
+ if ($("projectCount")) $("projectCount").textContent = String(hubConfig.projects?.length || 0);
1929
+
1930
+ renderIdeList();
1931
+ renderProjectList();
1932
+ renderPluginTable();
1933
+ renderCategoryBrowser();
1934
+ }
1935
+
1936
+ function renderIdeList() {
1937
+ const listEl = $("ideList");
1938
+ if (!listEl) return;
1939
+ listEl.innerHTML = "";
1940
+
1941
+ if (!hubConfig.ides || hubConfig.ides.length === 0) {
1942
+ listEl.innerHTML = `<div class="hint">No IDEs registered. Click "+ Add IDE" to add one.</div>`;
1943
+ return;
1944
+ }
1945
+
1946
+ hubConfig.ides.forEach((ide, index) => {
1947
+ const isSelected = currentSelection.type === "ide" && currentSelection.id === ide.id;
1948
+ const item = document.createElement("div");
1949
+ item.className = `target-item ${isSelected ? "active" : ""}`;
1950
+ item.draggable = true;
1951
+ item.dataset.index = index;
1952
+ item.dataset.type = "ide";
1953
+
1954
+ const prof = agentProfiles.find((p) => p.id === ide.agentType) ||
1955
+ agentProfiles.find((p) => ide.id?.includes(p.id) || ide.name?.toLowerCase().includes(p.id)) ||
1956
+ agentProfiles[0];
1957
+ const modeBadge = prof?.mode === "bundle"
1958
+ ? `<span style="font-size:9.5px; padding:1px 5px; border-radius:4px; background:rgba(16,185,129,0.15); color:#10b981; margin-left:6px;">Bundle</span>`
1959
+ : `<span style="font-size:9.5px; padding:1px 5px; border-radius:4px; background:rgba(59,130,246,0.15); color:#3b82f6; margin-left:6px;">Native Adapter</span>`;
1960
+
1961
+ const syncInfo = lastSyncByIde[ide.id];
1962
+ let syncSubtitle = "";
1963
+ if (syncInfo?.summary) {
1964
+ const s = syncInfo.summary;
1965
+ if (syncInfo.mode === "bundle") {
1966
+ syncSubtitle = `<div style="font-size:10px; color:#10b981; margin-top:2px;">Synced: ${s.plugins || 0} plugin bundles</div>`;
1967
+ } else {
1968
+ const parts = [];
1969
+ if (s.skills !== undefined) parts.push(`${s.skills} skills`);
1970
+ if (s.mcp) parts.push(`${s.mcp} MCP`);
1971
+ if (s.rules) parts.push(`${s.rules} rules`);
1972
+ if (s.agents) parts.push(`${s.agents} agents`);
1973
+ if (s.conflicts) parts.push(`${s.conflicts} conflicts`);
1974
+ syncSubtitle = `<div style="font-size:10px; color:#3b82f6; margin-top:2px;">Synced: ${parts.join(" · ") || "0 items"}</div>`;
1975
+ }
1976
+ }
1977
+
1978
+ item.innerHTML = `
1979
+ <div style="display:flex; align-items:center; flex:1; min-width:0;">
1980
+ <span class="drag-handle" title="Drag to reorder">⋮⋮</span>
1981
+ <div style="flex:1; min-width:0;">
1982
+ <div class="target-title">
1983
+ <span style="display:inline-block;width:6px;height:6px;border-radius:50%;background:#22c55e;"></span>
1984
+ ${escapeHtml(ide.name)}
1985
+ ${modeBadge}
1986
+ </div>
1987
+ <div class="target-path">${escapeHtml(truncate(ide.configPath, 42))}</div>
1988
+ ${syncSubtitle}
1989
+ </div>
1990
+ </div>
1991
+ <div class="target-item-actions">
1992
+ <button type="button" class="btn-edit-text edit-ide-btn" data-id="${escapeHtml(ide.id)}" title="Edit this IDE info & custom paths">Edit</button>
1993
+ <button type="button" class="btn-danger-text delete-ide-btn" data-id="${escapeHtml(ide.id)}" title="Remove this IDE">Remove</button>
1994
+ </div>
1995
+ `;
1996
+
1997
+ item.addEventListener("click", (e) => {
1998
+ if (e.target.closest(".delete-ide-btn") || e.target.closest(".edit-ide-btn")) return;
1999
+ currentSelection = { type: "ide", id: ide.id };
2000
+ renderAll();
2001
+ if (typeof recheckAllStatusDots === "function") {
2002
+ recheckAllStatusDots(true);
2003
+ }
2004
+ });
2005
+
2006
+ const editBtn = item.querySelector(".edit-ide-btn");
2007
+ if (editBtn) {
2008
+ editBtn.addEventListener("click", (e) => {
2009
+ e.preventDefault();
2010
+ e.stopPropagation();
2011
+ openEditIdeModal(ide);
2012
+ });
2013
+ }
2014
+
2015
+ // Drag and drop reordering
2016
+ item.addEventListener("dragstart", (e) => {
2017
+ draggedItem = { type: "ide", index };
2018
+ item.classList.add("dragging");
2019
+ e.dataTransfer.effectAllowed = "move";
2020
+ });
2021
+ item.addEventListener("dragend", () => {
2022
+ item.classList.remove("dragging");
2023
+ draggedItem = null;
2024
+ });
2025
+ item.addEventListener("dragover", (e) => {
2026
+ e.preventDefault();
2027
+ e.dataTransfer.dropEffect = "move";
2028
+ });
2029
+ item.addEventListener("drop", (e) => {
2030
+ e.preventDefault();
2031
+ if (!draggedItem || draggedItem.type !== "ide" || draggedItem.index === index) return;
2032
+ const moved = hubConfig.ides.splice(draggedItem.index, 1)[0];
2033
+ hubConfig.ides.splice(index, 0, moved);
2034
+ triggerAutoSync();
2035
+ renderAll();
2036
+ });
2037
+
2038
+ // Direct, reliable removal: unlinks all owned components and cleans state
2039
+ const removeBtn = item.querySelector(".delete-ide-btn");
2040
+ if (removeBtn) {
2041
+ let confirmTimer = null;
2042
+ removeBtn.addEventListener("click", async (e) => {
2043
+ e.preventDefault();
2044
+ e.stopPropagation();
2045
+
2046
+ const targetId = ide.id;
2047
+
2048
+ // Step 1: Inline confirmation (immune to WebView2/Electron modal dialog suppression)
2049
+ if (removeBtn.dataset.confirming !== "true") {
2050
+ removeBtn.dataset.confirming = "true";
2051
+ removeBtn.textContent = "Click to Confirm";
2052
+ removeBtn.style.color = "#ef4444";
2053
+ removeBtn.style.fontWeight = "bold";
2054
+
2055
+ if (confirmTimer) clearTimeout(confirmTimer);
2056
+ confirmTimer = setTimeout(() => {
2057
+ if (removeBtn) {
2058
+ delete removeBtn.dataset.confirming;
2059
+ removeBtn.textContent = "Remove";
2060
+ removeBtn.style.color = "";
2061
+ removeBtn.style.fontWeight = "";
2062
+ }
2063
+ }, 4000);
2064
+ return;
2065
+ }
2066
+
2067
+ // Step 2: Confirmed removal
2068
+ if (confirmTimer) clearTimeout(confirmTimer);
2069
+ delete removeBtn.dataset.confirming;
2070
+ removeBtn.disabled = true;
2071
+ removeBtn.textContent = "Removing...";
2072
+
2073
+ try {
2074
+ await apiClient.removeIde(targetId, false);
2075
+ } catch (err) {
2076
+ console.warn("apiClient.removeIde error:", err);
2077
+ }
2078
+
2079
+ hubConfig.ides = (hubConfig.ides || []).filter((i) => i.id !== targetId);
2080
+ hubConfig.projects = (hubConfig.projects || []).filter((p) => p.ideId !== targetId);
2081
+
2082
+ if (currentSelection.id === targetId) {
2083
+ currentSelection = { type: "ide", id: hubConfig.ides[0]?.id || "" };
2084
+ }
2085
+
2086
+ await persistConfig();
2087
+ renderAll();
2088
+ });
2089
+ }
2090
+
2091
+ listEl.appendChild(item);
2092
+ });
2093
+ }
2094
+
2095
+ function renderProjectList() {
2096
+ const listEl = $("projectList");
2097
+ if (!listEl) return;
2098
+ listEl.innerHTML = "";
2099
+
2100
+ if (!hubConfig.projects || hubConfig.projects.length === 0) {
2101
+ listEl.innerHTML = `<div class="hint">No specific project overrides. All projects inherit global IDE configuration.</div>`;
2102
+ return;
2103
+ }
2104
+
2105
+ hubConfig.projects.forEach((proj, index) => {
2106
+ const isSelected = currentSelection.type === "project" && currentSelection.id === proj.id;
2107
+ const associatedIde = hubConfig.ides.find((i) => i.id === proj.ideId);
2108
+ const ideLabel = associatedIde ? associatedIde.name : "Unassigned IDE";
2109
+
2110
+ const item = document.createElement("div");
2111
+ item.className = `target-item ${isSelected ? "active" : ""}`;
2112
+ item.draggable = true;
2113
+ item.dataset.index = index;
2114
+ item.dataset.type = "project";
2115
+
2116
+ item.innerHTML = `
2117
+ <div style="display:flex; align-items:center; flex:1; min-width:0;">
2118
+ <span class="drag-handle" title="Drag to reorder">⋮⋮</span>
2119
+ <div style="flex:1; min-width:0;">
2120
+ <div class="target-title">
2121
+ <span style="display:inline-block;width:6px;height:6px;border-radius:50%;background:#3b82f6;"></span>
2122
+ ${escapeHtml(proj.name)}
2123
+ <span style="font-size:10px;color:var(--magpie-muted);margin-left:4px;">[${escapeHtml(ideLabel)}]</span>
2124
+ </div>
2125
+ <div class="target-path">${escapeHtml(truncate(proj.repoPath, 42))}</div>
2126
+ </div>
2127
+ </div>
2128
+ <div class="target-item-actions">
2129
+ <button type="button" class="btn-edit-text edit-proj-btn" data-id="${escapeHtml(proj.id)}" title="Edit project info">Edit</button>
2130
+ <button type="button" class="btn-action-text copy-proj-btn" title="Copy info and assign to another IDE">Clone / Fork</button>
2131
+ <button type="button" class="btn-danger-text delete-proj-btn" data-id="${escapeHtml(proj.id)}" title="Remove project override">Remove</button>
2132
+ </div>
2133
+ `;
2134
+
2135
+ item.addEventListener("click", (e) => {
2136
+ if (e.target.closest(".delete-proj-btn") || e.target.closest(".copy-proj-btn") || e.target.closest(".edit-proj-btn")) return;
2137
+ currentSelection = { type: "project", id: proj.id };
2138
+ renderAll();
2139
+ if (typeof recheckAllStatusDots === "function") {
2140
+ recheckAllStatusDots(true);
2141
+ }
2142
+ });
2143
+
2144
+ const editBtn = item.querySelector(".edit-proj-btn");
2145
+ if (editBtn) {
2146
+ editBtn.addEventListener("click", (e) => {
2147
+ e.preventDefault();
2148
+ e.stopPropagation();
2149
+ openEditProjectModal(proj);
2150
+ });
2151
+ }
2152
+
2153
+ // Drag and drop reordering
2154
+ item.addEventListener("dragstart", (e) => {
2155
+ draggedItem = { type: "project", index };
2156
+ item.classList.add("dragging");
2157
+ e.dataTransfer.effectAllowed = "move";
2158
+ });
2159
+ item.addEventListener("dragend", () => {
2160
+ item.classList.remove("dragging");
2161
+ draggedItem = null;
2162
+ });
2163
+ item.addEventListener("dragover", (e) => {
2164
+ e.preventDefault();
2165
+ e.dataTransfer.dropEffect = "move";
2166
+ });
2167
+ item.addEventListener("drop", (e) => {
2168
+ e.preventDefault();
2169
+ if (!draggedItem || draggedItem.type !== "project" || draggedItem.index === index) return;
2170
+ const moved = hubConfig.projects.splice(draggedItem.index, 1)[0];
2171
+ hubConfig.projects.splice(index, 0, moved);
2172
+ triggerAutoSync();
2173
+ renderAll();
2174
+ });
2175
+
2176
+ // Clone / Fork project info to easily switch associated IDE
2177
+ const copyBtn = item.querySelector(".copy-proj-btn");
2178
+ if (copyBtn) {
2179
+ copyBtn.addEventListener("click", (e) => {
2180
+ e.preventDefault();
2181
+ e.stopPropagation();
2182
+ openCloneProjectModal(proj);
2183
+ });
2184
+ }
2185
+
2186
+ // Remove button: unlinks all owned project links and removes state
2187
+ // Direct, reliable removal for project overrides
2188
+ const deleteProjBtn = item.querySelector(".delete-proj-btn");
2189
+ if (deleteProjBtn) {
2190
+ let confirmProjTimer = null;
2191
+ deleteProjBtn.addEventListener("click", async (e) => {
2192
+ e.preventDefault();
2193
+ e.stopPropagation();
2194
+
2195
+ const targetId = proj.id;
2196
+
2197
+ // Step 1: Inline confirmation (immune to WebView2/Electron modal dialog suppression)
2198
+ if (deleteProjBtn.dataset.confirming !== "true") {
2199
+ deleteProjBtn.dataset.confirming = "true";
2200
+ deleteProjBtn.textContent = "Click to Confirm";
2201
+ deleteProjBtn.style.color = "#ef4444";
2202
+ deleteProjBtn.style.fontWeight = "bold";
2203
+
2204
+ if (confirmProjTimer) clearTimeout(confirmProjTimer);
2205
+ confirmProjTimer = setTimeout(() => {
2206
+ if (deleteProjBtn) {
2207
+ delete deleteProjBtn.dataset.confirming;
2208
+ deleteProjBtn.textContent = "Remove";
2209
+ deleteProjBtn.style.color = "";
2210
+ deleteProjBtn.style.fontWeight = "";
2211
+ }
2212
+ }, 4000);
2213
+ return;
2214
+ }
2215
+
2216
+ // Step 2: Confirmed removal
2217
+ if (confirmProjTimer) clearTimeout(confirmProjTimer);
2218
+ delete deleteProjBtn.dataset.confirming;
2219
+ deleteProjBtn.disabled = true;
2220
+ deleteProjBtn.textContent = "Removing...";
2221
+
2222
+ try {
2223
+ await apiClient.removeProject(targetId);
2224
+ } catch (err) {
2225
+ console.warn("apiClient.removeProject error:", err);
2226
+ }
2227
+
2228
+ hubConfig.projects = (hubConfig.projects || []).filter((p) => p.id !== targetId);
2229
+ if (currentSelection.type === "project" && currentSelection.id === targetId) {
2230
+ currentSelection = { type: "ide", id: hubConfig.ides[0]?.id || "" };
2231
+ }
2232
+
2233
+ await persistConfig();
2234
+ renderAll();
2235
+ });
2236
+ }
2237
+
2238
+ listEl.appendChild(item);
2239
+ });
2240
+ }
2241
+
2242
+ function evaluateComponentAgentWorkability(plugin, ide, options = {}) {
2243
+ if (!plugin) {
2244
+ return { workable: false, color: "red", status: "failed", features: {}, summary: "No component", tooltip: "🔴 Error: No component provided" };
2245
+ }
2246
+ if (!ide) {
2247
+ return { workable: false, color: "red", status: "failed", features: {}, summary: "No connected agent selected", tooltip: "🔴 Connection failed: No connected agent selected. Click an agent on the left to inspect workability." };
2248
+ }
2249
+ if (ide.enabled === false) {
2250
+ return { workable: false, color: "red", status: "disabled", features: {}, summary: `Agent "${ide.name || ide.id}" is disabled`, tooltip: `🔴 Connection failed: Agent "${ide.name || ide.id}" is disabled in settings` };
2251
+ }
2252
+ const configPath = ide.configPath || (ide.componentPaths && (ide.componentPaths.skills || ide.componentPaths.bundle));
2253
+ if (!configPath || String(configPath).trim() === "") {
2254
+ return { workable: false, color: "red", status: "failed", features: {}, summary: `Agent "${ide.name || ide.id}" has no configuration path`, tooltip: `🔴 Connection failed: Target link path for "${ide.name || ide.id}" is not configured` };
2255
+ }
2256
+ const isEnabled = Boolean(ide.plugins && ide.plugins[plugin.id] === true);
2257
+ if (!isEnabled) {
2258
+ return { workable: false, color: "red", status: "disabled", features: {}, summary: `Disabled for ${ide.name || ide.id}`, tooltip: `🔴 Connection failed / Disabled: Component is toggled OFF for "${ide.name || ide.id}". Turn on the toggle switch to connect.` };
2259
+ }
2260
+ if (options.lastSync && options.lastSync.success === false) {
2261
+ const errMsg = options.lastSync.error || options.lastSync.message || "Sync error";
2262
+ return { workable: false, color: "red", status: "failed", features: {}, summary: `Connection failed: ${errMsg}`, tooltip: `🔴 Connection failed to "${ide.name || ide.id}": ${errMsg}` };
2263
+ }
2264
+
2265
+ // Identify component types ACTUALLY INSIDE the plugin.
2266
+ // Explicitly SKIP any component type that is NOT present in the plugin.
2267
+ const rawSkills = Array.isArray(plugin.skills) ? plugin.skills : [];
2268
+ const hasSkillsInside = rawSkills.length > 0;
2269
+
2270
+ const rawAgents = Array.isArray(plugin.agents) ? plugin.agents : [];
2271
+ const hasAgentsInside = rawAgents.length > 0;
2272
+
2273
+ const rawMcps = Array.isArray(plugin.mcps) ? plugin.mcps : [];
2274
+ const hasMcpInside = Boolean(plugin.hasMcp || rawMcps.length > 0);
2275
+
2276
+ const rawRules = Array.isArray(plugin.rules) ? plugin.rules : [];
2277
+ const hasRulesInside = rawRules.length > 0;
2278
+
2279
+ const rawHooks = Array.isArray(plugin.hooks) ? plugin.hooks : [];
2280
+ const hasHooksInside = Boolean(plugin.hasHooks || rawHooks.length > 0);
2281
+
2282
+ const hasAnyFeature = hasSkillsInside || hasAgentsInside || hasMcpInside || hasRulesInside || hasHooksInside || (plugin.filesCount && plugin.filesCount > 0);
2283
+ if (!hasAnyFeature && !plugin.path) {
2284
+ return { workable: false, color: "red", status: "failed", features: {}, summary: "Empty component", tooltip: `🔴 Connection failed: No workable components discovered in "${plugin.name || plugin.id}"` };
2285
+ }
2286
+
2287
+ // Resolve agent profile capabilities
2288
+ const agentType = String(ide.agentType || ide.id || "").toLowerCase();
2289
+ const profile = agentProfiles.find((p) => p.id === agentType) || { capabilities: { skills: true, mcp: true, rules: true, agents: true, hooks: true } };
2290
+ const isBundle = profile?.mode === "bundle" || agentType === "antigravity";
2291
+ const customPaths = ide.componentPaths || {};
2292
+
2293
+ const capabilities = {
2294
+ skills: isBundle || customPaths.skills ? true : (profile?.capabilities?.skills ?? true),
2295
+ mcp: isBundle || customPaths.mcp ? true : (profile?.capabilities?.mcp ?? true),
2296
+ rules: isBundle || customPaths.rules ? true : (profile?.capabilities?.rules ?? true),
2297
+ agents: isBundle || customPaths.agents ? true : (profile?.capabilities?.agents ?? true),
2298
+ hooks: isBundle || customPaths.hooks ? true : (profile?.capabilities?.hooks ?? true),
2299
+ };
2300
+
2301
+ const features = {};
2302
+ const actionParts = [];
2303
+ const detailedTooltipLines = [];
2304
+ let workableCount = 0;
2305
+ let presentTypeCount = 0;
2306
+
2307
+ // 1. Skills Check (only if present inside plugin)
2308
+ let slashCommands = [];
2309
+ if (hasSkillsInside) {
2310
+ presentTypeCount++;
2311
+ slashCommands = rawSkills.map((s) => (typeof s === "string" ? `/${s}` : `/${s.name}`));
2312
+ const isSupported = capabilities.skills === true;
2313
+ if (isSupported) {
2314
+ workableCount++;
2315
+ actionParts.push(`Quick action: ${slashCommands.join(" ")}`);
2316
+ detailedTooltipLines.push(`✓ Skills (${slashCommands.length}): ${slashCommands.join(" ")}`);
2317
+ } else {
2318
+ detailedTooltipLines.push(`✗ Skills (${slashCommands.length}): Skipped (unsupported by ${ide.name || ide.id})`);
2319
+ }
2320
+ features.skills = {
2321
+ present: true,
2322
+ count: slashCommands.length,
2323
+ workable: isSupported,
2324
+ items: slashCommands,
2325
+ reason: isSupported ? "Active" : `Unsupported by ${ide.name || ide.id}`,
2326
+ };
2327
+ }
2328
+
2329
+ // 2. Agents / Subagents Check (only if present inside plugin)
2330
+ let mentions = [];
2331
+ if (hasAgentsInside) {
2332
+ presentTypeCount++;
2333
+ mentions = rawAgents.map((a) => {
2334
+ const rawName = typeof a === "string" ? a : a.name || "";
2335
+ return `@${rawName.replace(/\.md$/i, "")}`;
2336
+ });
2337
+ const isSupported = capabilities.agents === true;
2338
+ if (isSupported) {
2339
+ workableCount++;
2340
+ actionParts.push(`Quick action: ${mentions.join(" ")}`);
2341
+ detailedTooltipLines.push(`✓ Agents (${mentions.length}): ${mentions.join(" ")}`);
2342
+ } else {
2343
+ detailedTooltipLines.push(`✗ Agents (${mentions.length}): Skipped (unsupported by ${ide.name || ide.id})`);
2344
+ }
2345
+ features.agents = {
2346
+ present: true,
2347
+ count: mentions.length,
2348
+ workable: isSupported,
2349
+ items: mentions,
2350
+ reason: isSupported ? "Active" : `Unsupported by ${ide.name || ide.id}`,
2351
+ };
2352
+ }
2353
+
2354
+ // 3. MCP Servers Check (only if present inside plugin)
2355
+ if (hasMcpInside) {
2356
+ presentTypeCount++;
2357
+ const mcpNames = rawMcps.length > 0 ? rawMcps : [plugin.id || "mcp"];
2358
+ const isSupported = capabilities.mcp === true;
2359
+ if (isSupported) {
2360
+ workableCount++;
2361
+ actionParts.push("MCP tools active");
2362
+ detailedTooltipLines.push(`✓ MCP (${mcpNames.length}): ${mcpNames.join(", ")} active`);
2363
+ } else {
2364
+ detailedTooltipLines.push(`✗ MCP (${mcpNames.length}): Skipped (unsupported by ${ide.name || ide.id})`);
2365
+ }
2366
+ features.mcp = {
2367
+ present: true,
2368
+ count: mcpNames.length,
2369
+ workable: isSupported,
2370
+ items: mcpNames,
2371
+ reason: isSupported ? "Active" : `Unsupported by ${ide.name || ide.id}`,
2372
+ };
2373
+ }
2374
+
2375
+ // 4. Rules Check (only if present inside plugin)
2376
+ if (hasRulesInside) {
2377
+ presentTypeCount++;
2378
+ const ruleNames = rawRules.map((r) => (typeof r === "string" ? r : r.name || ""));
2379
+ const isSupported = capabilities.rules === true;
2380
+ if (isSupported) {
2381
+ workableCount++;
2382
+ actionParts.push("Rules active");
2383
+ detailedTooltipLines.push(`✓ Rules (${ruleNames.length}): ${ruleNames.join(", ")} active`);
2384
+ } else {
2385
+ detailedTooltipLines.push(`✗ Rules (${ruleNames.length}): Skipped (unsupported by ${ide.name || ide.id})`);
2386
+ }
2387
+ features.rules = {
2388
+ present: true,
2389
+ count: ruleNames.length,
2390
+ workable: isSupported,
2391
+ items: ruleNames,
2392
+ reason: isSupported ? "Active" : `Unsupported by ${ide.name || ide.id}`,
2393
+ };
2394
+ }
2395
+
2396
+ // 5. Hooks Check (only if present inside plugin)
2397
+ if (hasHooksInside) {
2398
+ presentTypeCount++;
2399
+ const hookCount = rawHooks.length > 0 ? rawHooks.length : 1;
2400
+ const isSupported = capabilities.hooks === true;
2401
+ if (isSupported) {
2402
+ workableCount++;
2403
+ actionParts.push("Hooks active");
2404
+ detailedTooltipLines.push(`✓ Hooks (${hookCount}): Active`);
2405
+ } else {
2406
+ detailedTooltipLines.push(`✗ Hooks (${hookCount}): Skipped (unsupported by ${ide.name || ide.id})`);
2407
+ }
2408
+ features.hooks = {
2409
+ present: true,
2410
+ count: hookCount,
2411
+ workable: isSupported,
2412
+ items: rawHooks,
2413
+ reason: isSupported ? "Active" : `Unsupported by ${ide.name || ide.id}`,
2414
+ };
2415
+ }
2416
+
2417
+ // If component has types present but NONE of them are supported by this agent
2418
+ if (presentTypeCount > 0 && workableCount === 0) {
2419
+ return {
2420
+ workable: false,
2421
+ color: "red",
2422
+ status: "unsupported",
2423
+ features,
2424
+ quickActions: { slashCommands, mentions, hasSlash: false, hasMention: false, hasMcp: false, hasRules: false, hasHooks: false },
2425
+ summary: `Incompatible with ${ide.name || ide.id}`,
2426
+ tooltip: `🔴 Incompatible with ${ide.name || ide.id}: All component types in "${plugin.name || plugin.id}" are unsupported.`,
2427
+ reason: `All component types in "${plugin.name || plugin.id}" are unsupported by ${ide.name || ide.id}`,
2428
+ };
2429
+ }
2430
+
2431
+ const hasSlash = slashCommands.length > 0 && capabilities.skills === true;
2432
+ const hasMention = mentions.length > 0 && capabilities.agents === true;
2433
+ const hasMcp = hasMcpInside && capabilities.mcp === true;
2434
+ const hasRules = hasRulesInside && capabilities.rules === true;
2435
+ const hasHooks = hasHooksInside && capabilities.hooks === true;
2436
+
2437
+ const summary = `Workable in ${ide.name || ide.id}${actionParts.length > 0 ? " · " + actionParts.join(" · ") : ""}`;
2438
+ const baseTooltip = `🟢 Workable in ${ide.name || ide.id}: Connected & ready.${actionParts.length > 0 ? " Can be used with " + actionParts.join(" | ") : ""}`;
2439
+ const tooltip = detailedTooltipLines.length > 0 ? `${baseTooltip}\n${detailedTooltipLines.join("\n")}` : baseTooltip;
2440
+
2441
+ return {
2442
+ workable: true,
2443
+ color: "green",
2444
+ status: "workable",
2445
+ features,
2446
+ quickActions: {
2447
+ slashCommands,
2448
+ mentions,
2449
+ hasSlash,
2450
+ hasMention,
2451
+ hasMcp,
2452
+ hasRules,
2453
+ hasHooks,
2454
+ },
2455
+ summary,
2456
+ tooltip,
2457
+ };
2458
+ }
2459
+
2460
+ function evaluateComponentProjectWorkability(plugin, project, parentIde) {
2461
+ if (!project || !project.repoPath) {
2462
+ return { workable: false, color: "red", status: "failed", features: {}, summary: "Project repository path missing", tooltip: "🔴 Connection failed: Repository path does not exist" };
2463
+ }
2464
+ const isEnabled = project.plugins && project.plugins[plugin.id] !== undefined
2465
+ ? project.plugins[plugin.id] === true
2466
+ : Boolean(parentIde?.plugins && parentIde.plugins[plugin.id] === true);
2467
+ if (!isEnabled) {
2468
+ return { workable: false, color: "red", status: "disabled", features: {}, summary: `Disabled for project "${project.name}"`, tooltip: `🔴 Connection failed / Disabled: Component is toggled OFF for project "${project.name}"` };
2469
+ }
2470
+
2471
+ const rawSkills = Array.isArray(plugin.skills) ? plugin.skills : [];
2472
+ const hasSkillsInside = rawSkills.length > 0;
2473
+
2474
+ const rawAgents = Array.isArray(plugin.agents) ? plugin.agents : [];
2475
+ const hasAgentsInside = rawAgents.length > 0;
2476
+
2477
+ const rawMcps = Array.isArray(plugin.mcps) ? plugin.mcps : [];
2478
+ const hasMcpInside = Boolean(plugin.hasMcp || rawMcps.length > 0);
2479
+
2480
+ const rawRules = Array.isArray(plugin.rules) ? plugin.rules : [];
2481
+ const hasRulesInside = rawRules.length > 0;
2482
+
2483
+ const rawHooks = Array.isArray(plugin.hooks) ? plugin.hooks : [];
2484
+ const hasHooksInside = Boolean(plugin.hasHooks || rawHooks.length > 0);
2485
+
2486
+ const hasAnyFeature = hasSkillsInside || hasAgentsInside || hasMcpInside || hasRulesInside || hasHooksInside || (plugin.filesCount && plugin.filesCount > 0);
2487
+ if (!hasAnyFeature && !plugin.path) {
2488
+ return { workable: false, color: "red", status: "failed", features: {}, summary: "Empty component", tooltip: `🔴 Connection failed: No workable components discovered in "${plugin.name || plugin.id}"` };
2489
+ }
2490
+
2491
+ const agentType = String(parentIde?.agentType || parentIde?.id || "").toLowerCase();
2492
+ const profile = agentProfiles.find((p) => p.id === agentType) || { capabilities: { skills: true, mcp: true, rules: true, agents: true, hooks: true } };
2493
+ const capabilities = {
2494
+ skills: true,
2495
+ mcp: true,
2496
+ rules: true,
2497
+ agents: profile?.capabilities?.agents ?? true,
2498
+ hooks: profile?.capabilities?.hooks ?? false,
2499
+ };
2500
+
2501
+ const features = {};
2502
+ const actionParts = [];
2503
+ const detailedTooltipLines = [];
2504
+
2505
+ // 1. Skills
2506
+ if (hasSkillsInside) {
2507
+ const slashCommands = rawSkills.map((s) => (typeof s === "string" ? `/${s}` : `/${s.name}`));
2508
+ actionParts.push(`Quick action: ${slashCommands.join(" ")}`);
2509
+ detailedTooltipLines.push(`✓ Skills (${slashCommands.length}): ${slashCommands.join(" ")}`);
2510
+ features.skills = { present: true, count: slashCommands.length, workable: true, items: slashCommands, reason: "Active" };
2511
+ }
2512
+
2513
+ // 2. Agents
2514
+ if (hasAgentsInside) {
2515
+ const mentions = rawAgents.map((a) => {
2516
+ const rawName = typeof a === "string" ? a : a.name || "";
2517
+ return `@${rawName.replace(/\.md$/i, "")}`;
2518
+ });
2519
+ const isSupported = capabilities.agents === true;
2520
+ if (isSupported) {
2521
+ actionParts.push(`Quick action: ${mentions.join(" ")}`);
2522
+ detailedTooltipLines.push(`✓ Agents (${mentions.length}): ${mentions.join(" ")}`);
2523
+ } else {
2524
+ detailedTooltipLines.push(`✗ Agents (${mentions.length}): Skipped (unsupported in workspace repository)`);
2525
+ }
2526
+ features.agents = { present: true, count: mentions.length, workable: isSupported, items: mentions, reason: isSupported ? "Active" : "Unsupported" };
2527
+ }
2528
+
2529
+ // 3. MCP
2530
+ if (hasMcpInside) {
2531
+ const mcpNames = rawMcps.length > 0 ? rawMcps : [plugin.id || "mcp"];
2532
+ actionParts.push("MCP tools active");
2533
+ detailedTooltipLines.push(`✓ MCP (${mcpNames.length}): ${mcpNames.join(", ")} active`);
2534
+ features.mcp = { present: true, count: mcpNames.length, workable: true, items: mcpNames, reason: "Active" };
2535
+ }
2536
+
2537
+ // 4. Rules
2538
+ if (hasRulesInside) {
2539
+ const ruleNames = rawRules.map((r) => (typeof r === "string" ? r : r.name || ""));
2540
+ actionParts.push("Rules active");
2541
+ detailedTooltipLines.push(`✓ Rules (${ruleNames.length}): ${ruleNames.join(", ")} active`);
2542
+ features.rules = { present: true, count: ruleNames.length, workable: true, items: ruleNames, reason: "Active" };
2543
+ }
2544
+
2545
+ // 5. Hooks
2546
+ if (hasHooksInside) {
2547
+ const hookCount = rawHooks.length > 0 ? rawHooks.length : 1;
2548
+ const isSupported = capabilities.hooks === true;
2549
+ if (isSupported) {
2550
+ actionParts.push("Hooks active");
2551
+ detailedTooltipLines.push(`✓ Hooks (${hookCount}): Active`);
2552
+ } else {
2553
+ detailedTooltipLines.push(`✗ Hooks (${hookCount}): Skipped (unsupported in workspace repo)`);
2554
+ }
2555
+ features.hooks = { present: true, count: hookCount, workable: isSupported, items: rawHooks, reason: isSupported ? "Active" : "Unsupported" };
2556
+ }
2557
+
2558
+ const summary = `Workable in ${project.name}${actionParts.length > 0 ? " · " + actionParts.join(" · ") : ""}`;
2559
+ const baseTooltip = `🟢 Workable in Project "${project.name}": Repository linked & protected (.git/info/exclude).${actionParts.length > 0 ? " Can be used with " + actionParts.join(" | ") : ""}`;
2560
+ const tooltip = detailedTooltipLines.length > 0 ? `${baseTooltip}\n${detailedTooltipLines.join("\n")}` : baseTooltip;
2561
+
2562
+ return { workable: true, color: "green", status: "workable", features, summary, tooltip };
2563
+ }
2564
+
2565
+ function evaluateComponentWorkability(plugin) {
2566
+ if (currentSelection.type === "ide") {
2567
+ const selectedIde = hubConfig.ides.find((i) => i.id === currentSelection.id);
2568
+ if (selectedIde && verifiedStatusByIde[selectedIde.id]?.[plugin.id]) {
2569
+ return verifiedStatusByIde[selectedIde.id][plugin.id];
2570
+ }
2571
+ return evaluateComponentAgentWorkability(plugin, selectedIde, { lastSync: selectedIde ? lastSyncByIde[selectedIde.id] : null });
2572
+ } else if (currentSelection.type === "project") {
2573
+ const selectedProj = hubConfig.projects.find((p) => p.id === currentSelection.id);
2574
+ if (selectedProj && verifiedStatusByProject[selectedProj.id]?.[plugin.id]) {
2575
+ return verifiedStatusByProject[selectedProj.id][plugin.id];
2576
+ }
2577
+ const parentIde = selectedProj ? hubConfig.ides.find((i) => i.id === selectedProj.ideId) : null;
2578
+ return evaluateComponentProjectWorkability(plugin, selectedProj, parentIde);
2579
+ }
2580
+ return {
2581
+ workable: false,
2582
+ color: "red",
2583
+ status: "failed",
2584
+ summary: "No target selected",
2585
+ tooltip: "🔴 Connection failed: No connected agent selected",
2586
+ };
2587
+ }
2588
+
2589
+ function renderPluginTable() {
2590
+ const tableBody = $("pluginTableBody");
2591
+ if (!tableBody) return;
2592
+ tableBody.innerHTML = "";
2593
+
2594
+ let targetTitle = "Global Platform";
2595
+ let badgeText = "Global IDE";
2596
+ let activeMap = {};
2597
+
2598
+ if (currentSelection.type === "ide") {
2599
+ const ide = hubConfig.ides.find((i) => i.id === currentSelection.id);
2600
+ if (ide) {
2601
+ targetTitle = ide.name;
2602
+ badgeText = "Global Platform";
2603
+ activeMap = ide.plugins || {};
2604
+ }
2605
+ } else if (currentSelection.type === "project") {
2606
+ const proj = hubConfig.projects.find((p) => p.id === currentSelection.id);
2607
+ if (proj) {
2608
+ targetTitle = proj.name;
2609
+ badgeText = "Project Override";
2610
+ activeMap = proj.plugins || {};
2611
+ }
2612
+ }
2613
+
2614
+ if ($("activeContextText")) {
2615
+ $("activeContextText").innerHTML = `Target: <strong>${escapeHtml(targetTitle)}</strong>`;
2616
+ }
2617
+ if ($("activeContextBadge")) {
2618
+ $("activeContextBadge").textContent = badgeText;
2619
+ }
2620
+
2621
+ if (discoveredPlugins.length === 0) {
2622
+ tableBody.innerHTML = `
2623
+ <tr>
2624
+ <td colspan="4" style="text-align: center; padding: 32px 16px; color: var(--magpie-muted);">
2625
+ No plugin components discovered in this storage path.<br>
2626
+ <span style="font-size: 11px; opacity: 0.8;">Active Path: ${escapeHtml(computeEffectiveHubPath().path)}</span>
2627
+ </td>
2628
+ </tr>
2629
+ `;
2630
+ return;
2631
+ }
2632
+
2633
+ discoveredPlugins.forEach((plugin) => {
2634
+ const isEnabled = activeMap[plugin.id] === true;
2635
+ const isFilesExpanded = expandedFiles.has(plugin.id);
2636
+ const workability = evaluateComponentWorkability(plugin);
2637
+ const row = document.createElement("tr");
2638
+
2639
+ let badges = "";
2640
+ if (plugin.hasMcp) badges += `<span class="badge badge-mcp">MCP</span>`;
2641
+ if (plugin.skills?.length > 0) badges += `<span class="badge badge-skills">${plugin.skills.length} Skills</span>`;
2642
+ if (plugin.rules?.length > 0) badges += `<span class="badge badge-rules">Rules</span>`;
2643
+ if (plugin.hasHooks) badges += `<span class="badge" style="background:rgba(234,88,12,0.15);color:#ea580c;">Hooks</span>`;
2644
+
2645
+ ensurePluginFiles(plugin);
2646
+ const componentFiles = getPluginComponentFiles(plugin);
2647
+ const filesCount = componentFiles.length;
2648
+ let filesListHtml = "";
2649
+ if (isFilesExpanded) {
2650
+ if (filesCount > 0) {
2651
+ const fileRows = componentFiles.map((it) => {
2652
+ let badgeBg = "rgba(100,116,139,0.12)";
2653
+ let badgeColor = "#64748b";
2654
+ if (it.type === "skill") {
2655
+ badgeBg = "rgba(37,99,235,0.12)";
2656
+ badgeColor = "#2563eb";
2657
+ } else if (it.type === "mcp") {
2658
+ badgeBg = "rgba(234,179,8,0.15)";
2659
+ badgeColor = "#ca8a04";
2660
+ } else if (it.type === "rule") {
2661
+ badgeBg = "rgba(168,85,247,0.15)";
2662
+ badgeColor = "#9333ea";
2663
+ } else if (it.type === "agent") {
2664
+ badgeBg = "rgba(236,72,153,0.15)";
2665
+ badgeColor = "#db2777";
2666
+ } else if (it.type === "hook") {
2667
+ badgeBg = "rgba(234,88,12,0.15)";
2668
+ badgeColor = "#ea580c";
2669
+ } else if (it.type === "manifest") {
2670
+ badgeBg = "rgba(16,185,129,0.12)";
2671
+ badgeColor = "#059669";
2672
+ } else if (it.type === "docs") {
2673
+ badgeBg = "rgba(5,150,105,0.12)";
2674
+ badgeColor = "#059669";
2675
+ }
2676
+
2677
+ let workabilityBadge = "";
2678
+ if (workability.workable) {
2679
+ if (it.type === "skill") {
2680
+ const isW = workability.features?.skills?.workable ?? true;
2681
+ workabilityBadge = isW
2682
+ ? `<span style="font-size:9.5px; color:#10b981; font-weight:600;" title="Skill active via slash command">✓ Workable</span>`
2683
+ : `<span style="font-size:9.5px; color:#f59e0b; font-weight:600;" title="Agent does not support skills">⚠️ Unsupported</span>`;
2684
+ } else if (it.type === "mcp") {
2685
+ const isW = workability.features?.mcp?.workable ?? true;
2686
+ workabilityBadge = isW
2687
+ ? `<span style="font-size:9.5px; color:#10b981; font-weight:600;" title="MCP server active">✓ Workable</span>`
2688
+ : `<span style="font-size:9.5px; color:#f59e0b; font-weight:600;" title="Agent does not support MCP tools">⚠️ Unsupported</span>`;
2689
+ } else if (it.type === "agent") {
2690
+ const isW = workability.features?.agents?.workable ?? true;
2691
+ workabilityBadge = isW
2692
+ ? `<span style="font-size:9.5px; color:#10b981; font-weight:600;" title="Subagent active via @ mention">✓ Workable</span>`
2693
+ : `<span style="font-size:9.5px; color:#f59e0b; font-weight:600;" title="Agent does not support subagents">⚠️ Unsupported</span>`;
2694
+ } else if (it.type === "rule") {
2695
+ const isW = workability.features?.rules?.workable ?? true;
2696
+ workabilityBadge = isW
2697
+ ? `<span style="font-size:9.5px; color:#10b981; font-weight:600;" title="Rule active in agent memory">✓ Workable</span>`
2698
+ : `<span style="font-size:9.5px; color:#f59e0b; font-weight:600;" title="Agent does not support rules">⚠️ Unsupported</span>`;
2699
+ } else if (it.type === "hook") {
2700
+ const isW = workability.features?.hooks?.workable ?? true;
2701
+ workabilityBadge = isW
2702
+ ? `<span style="font-size:9.5px; color:#10b981; font-weight:600;" title="Lifecycle hook active">✓ Workable</span>`
2703
+ : `<span style="font-size:9.5px; color:#f59e0b; font-weight:600;" title="Agent does not support lifecycle hooks">⚠️ Unsupported</span>`;
2704
+ }
2705
+ }
2706
+
2707
+ return `
2708
+ <div class="cat-item-row file-tree-item" style="display:flex; justify-content:space-between; align-items:center; padding:3.5px 8px; border-radius:4px; margin-bottom:2px; font-size:11px; background:var(--magpie-surface, rgba(128,128,128,0.04));">
2709
+ <div class="cat-item-title" style="display:flex; align-items:center; gap:6px; overflow:hidden;">
2710
+ <span style="font-size:10px; font-weight:600; padding:1.5px 5px; border-radius:3px; background:${badgeBg}; color:${badgeColor}; flex-shrink:0;">${it.badge}</span>
2711
+ <span style="font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">${escapeHtml(it.name)}</span>
2712
+ ${it.sub ? `<span style="opacity:0.65; font-size:10px; flex-shrink:0;">(${escapeHtml(it.sub)})</span>` : ""}
2713
+ </div>
2714
+ <div class="cat-item-meta" style="display:flex; align-items:center; gap:8px; opacity:0.85; font-size:10px; flex-shrink:0; margin-left:12px;">
2715
+ ${workabilityBadge}
2716
+ <span>${escapeHtml(it.relPath)}</span>
2717
+ ${it.sizeStr ? `<span>${it.sizeStr}</span>` : ""}
2718
+ </div>
2719
+ </div>
2720
+ `;
2721
+ }).join("");
2722
+
2723
+ filesListHtml = `
2724
+ <div class="file-tree-container" style="margin-top:8px; padding:8px 10px; border-radius:6px; border:1px solid var(--magpie-border, rgba(128,128,128,0.2)); background:var(--magpie-bg, rgba(0,0,0,0.02)); max-height:260px; overflow-y:auto;">
2725
+ <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px; font-size:11px; font-weight:600; opacity:0.85;">
2726
+ <span>Discovered Components &amp; Files in ${escapeHtml(plugin.name)} (${filesCount} total):</span>
2727
+ </div>
2728
+ ${fileRows}
2729
+ </div>
2730
+ `;
2731
+ } else {
2732
+ filesListHtml = `
2733
+ <div class="file-tree-container" style="margin-top:6px; padding:8px 10px; border-radius:6px; border:1px solid var(--magpie-border, rgba(128,128,128,0.2));">
2734
+ <div style="font-size:11px; opacity:0.7; padding:4px 0;">No components or files discovered in ${escapeHtml(plugin.name)}.</div>
2735
+ </div>
2736
+ `;
2737
+ }
2738
+ }
2739
+
2740
+ row.innerHTML = `
2741
+ <td style="vertical-align:top; padding-top:12px;">
2742
+ <label class="switch">
2743
+ <input type="checkbox" class="plugin-toggle" data-plugin="${escapeHtml(plugin.id)}" ${isEnabled ? "checked" : ""}>
2744
+ <span class="slider"></span>
2745
+ </label>
2746
+ </td>
2747
+ <td style="vertical-align:top; padding-top:10px;">
2748
+ <div><strong>${escapeHtml(plugin.name)}</strong> ${plugin.version ? `<span style="font-size:10.5px; opacity:0.7;">v${escapeHtml(plugin.version)}</span>` : ""}</div>
2749
+ <button type="button" class="btn-files-toggle" data-plugin-files="${escapeHtml(plugin.id)}">
2750
+ <span>${isFilesExpanded ? "▲ Hide" : "View"} (${filesCount})</span>
2751
+ </button>
2752
+ ${filesListHtml}
2753
+ </td>
2754
+ <td style="vertical-align:top; padding-top:12px;">${badges || `<span style="color:var(--magpie-muted);font-size:11px;">Standard</span>`}</td>
2755
+ <td style="vertical-align:top; padding-top:12px; color:var(--magpie-muted);">
2756
+ <div class="desc-status-cell">
2757
+ <span class="component-status-dot dot-${workability.color}" title="${escapeHtml(workability.tooltip)}" aria-label="${escapeHtml(workability.summary)}"></span>
2758
+ <span class="desc-text">${escapeHtml(plugin.description || "-")}</span>
2759
+ </div>
2760
+ </td>
2761
+ `;
2762
+
2763
+ const fileToggleBtn = row.querySelector(".btn-files-toggle");
2764
+ if (fileToggleBtn) {
2765
+ fileToggleBtn.addEventListener("click", (e) => {
2766
+ e.preventDefault();
2767
+ if (expandedFiles.has(plugin.id)) {
2768
+ expandedFiles.delete(plugin.id);
2769
+ } else {
2770
+ expandedFiles.add(plugin.id);
2771
+ }
2772
+ renderPluginTable();
2773
+ });
2774
+ }
2775
+
2776
+ row.querySelector(".plugin-toggle").addEventListener("change", (e) => {
2777
+ const checked = e.target.checked;
2778
+ if (currentSelection.type === "ide") {
2779
+ const ide = hubConfig.ides.find((i) => i.id === currentSelection.id);
2780
+ if (ide) {
2781
+ if (!ide.plugins) ide.plugins = {};
2782
+ ide.plugins[plugin.id] = checked;
2783
+ }
2784
+ } else if (currentSelection.type === "project") {
2785
+ const proj = hubConfig.projects.find((p) => p.id === currentSelection.id);
2786
+ if (proj) {
2787
+ if (!proj.plugins) proj.plugins = {};
2788
+ proj.plugins[plugin.id] = checked;
2789
+ }
2790
+ }
2791
+
2792
+ if (currentSelection.type === "ide" && verifiedStatusByIde[currentSelection.id]) {
2793
+ delete verifiedStatusByIde[currentSelection.id][plugin.id];
2794
+ } else if (currentSelection.type === "project" && verifiedStatusByProject[currentSelection.id]) {
2795
+ delete verifiedStatusByProject[currentSelection.id][plugin.id];
2796
+ }
2797
+
2798
+ // Live update status dot for this component
2799
+ const newWorkability = evaluateComponentWorkability(plugin);
2800
+ const dot = row.querySelector(".component-status-dot");
2801
+ if (dot) {
2802
+ dot.className = `component-status-dot dot-${newWorkability.color}`;
2803
+ dot.title = newWorkability.tooltip;
2804
+ dot.setAttribute("aria-label", newWorkability.summary);
2805
+ }
2806
+
2807
+ triggerSavePreferences();
2808
+ });
2809
+
2810
+ tableBody.appendChild(row);
2811
+ });
2812
+ }
2813
+
2814
+ // Opens Add Project modal populated with an existing project's info
2815
+ function openCloneProjectModal(proj) {
2816
+ if ($("projectModalTitle")) $("projectModalTitle").textContent = "Clone Project to Another IDE";
2817
+ if ($("projectNameInput")) $("projectNameInput").value = `${proj.name} (Copy)`;
2818
+ if ($("projectPathInput")) $("projectPathInput").value = proj.repoPath;
2819
+
2820
+ const select = $("projectIdeSelect");
2821
+ if (select) {
2822
+ select.innerHTML = "";
2823
+ hubConfig.ides.forEach((ide) => {
2824
+ const opt = document.createElement("option");
2825
+ opt.value = ide.id;
2826
+ opt.textContent = ide.name;
2827
+ // Pre-select another IDE if available
2828
+ if (ide.id !== proj.ideId) opt.selected = true;
2829
+ select.appendChild(opt);
2830
+ });
2831
+ }
2832
+
2833
+ if ($("addProjectModal")) $("addProjectModal").style.display = "flex";
2834
+ }
2835
+
2836
+ // Dynamically detect accurate Configuration Link Directory across any user or platform
2837
+ async function detectDefaultConfigPath(nameOrAgentType, exePath) {
2838
+ try {
2839
+ const detected = await apiClient.detectConfigPath(nameOrAgentType, exePath);
2840
+ if (detected) return detected;
2841
+ } catch {}
2842
+
2843
+ const prof = agentProfiles.find((p) => p.id === nameOrAgentType || p.label.toLowerCase() === String(nameOrAgentType || "").toLowerCase());
2844
+ if (prof && prof.defaultConfigPath) {
2845
+ return prof.defaultConfigPath;
2846
+ }
2847
+
2848
+ const combined = `${nameOrAgentType || ""} ${exePath || ""}`.toLowerCase();
2849
+ for (const p of agentProfiles) {
2850
+ if (combined.includes(p.id) || combined.includes(p.label.toLowerCase().split(" ")[0])) {
2851
+ return p.defaultConfigPath;
2852
+ }
2853
+ }
2854
+
2855
+ const clean = nameOrAgentType ? String(nameOrAgentType).toLowerCase().replace(/[^a-z0-9_-]/g, "") : "agent";
2856
+ return `~/.${clean}/skills`;
2857
+ }
2858
+
2859
+ function inferClientName(baseName) {
2860
+ if (!baseName) return "Agent";
2861
+ const clean = baseName.replace(/\.(exe|lnk|app|cmd|bat)$/i, "");
2862
+ const lower = clean.toLowerCase();
2863
+
2864
+ if (lower === "opencode" || lower.startsWith("opencode")) return "OpenCode";
2865
+ if (lower === "code" || lower === "vscode" || lower === "visualstudiocode") return "VS Code";
2866
+ if (lower === "cursor") return "Cursor";
2867
+ if (lower === "windsurf") return "Windsurf";
2868
+ if (lower === "agy" || lower.includes("antigravity")) return "Antigravity";
2869
+ if (lower === "claude") return "Claude";
2870
+ if (lower === "vscodium" || lower === "codium") return "VSCodium";
2871
+ if (lower === "zed") return "Zed";
2872
+
2873
+ return clean.charAt(0).toUpperCase() + clean.slice(1);
2874
+ }
2875
+
2876
+ // --- OmniRoute AI Gateway State & Controller ---
2877
+ async function checkOmniroute(manual = false) {
2878
+ const dot = $("omnirouteStatusDot");
2879
+ const portLink = $("omniroutePortLink");
2880
+
2881
+ if (manual && dot) {
2882
+ dot.className = "status-dot dot-blue";
2883
+ dot.title = "Checking OmniRoute health status...";
2884
+ }
2885
+
2886
+ try {
2887
+ const res = await apiClient.getOmnirouteStatus(omniroutePort);
2888
+ if (res && res.port) {
2889
+ omniroutePort = res.port;
2890
+ if (portLink) {
2891
+ portLink.textContent = String(res.port);
2892
+ portLink.href = res.url || `http://localhost:${res.port}`;
2893
+ portLink.title = `Open OmniRoute on port ${res.port} in default browser (Default password: CHANGEME)`;
2894
+ }
2895
+ }
2896
+
2897
+ isOmnirouteRunning = Boolean(res?.running);
2898
+
2899
+ if (dot) {
2900
+ if (isOmnirouteRunning) {
2901
+ dot.className = "status-dot dot-green";
2902
+ dot.title = `OmniRoute is active on port ${omniroutePort} (Default password: CHANGEME) - click to check health`;
2903
+ } else {
2904
+ dot.className = "status-dot dot-red";
2905
+ dot.title = `OmniRoute is stopped / unreachable on port ${omniroutePort} - click to check health`;
2906
+ }
2907
+ }
2908
+
2909
+ if (manual) {
2910
+ if (isOmnirouteRunning) {
2911
+ showToast(`OmniRoute: Active on port ${omniroutePort} (Default password: CHANGEME)`, "success", 4000, { noEmoji: true });
2912
+ } else {
2913
+ showToast(`OmniRoute: Stopped / unreachable on port ${omniroutePort}`, "warning", 4000, { noEmoji: true });
2914
+ }
2915
+ }
2916
+ } catch {
2917
+ if (dot) {
2918
+ dot.className = "status-dot dot-red";
2919
+ dot.title = "OmniRoute health check failed";
2920
+ }
2921
+ }
2922
+ }
2923
+
2924
+ async function copyTextToClipboard(text) {
2925
+ if (navigator?.clipboard?.writeText) {
2926
+ try {
2927
+ await navigator.clipboard.writeText(text);
2928
+ return true;
2929
+ } catch {}
2930
+ }
2931
+ try {
2932
+ const ta = document.createElement("textarea");
2933
+ ta.value = text;
2934
+ ta.style.position = "fixed";
2935
+ ta.style.top = "-9999px";
2936
+ ta.style.left = "-9999px";
2937
+ ta.style.opacity = "0";
2938
+ document.body.appendChild(ta);
2939
+ ta.focus();
2940
+ ta.select();
2941
+ const ok = document.execCommand("copy");
2942
+ ta.remove();
2943
+ return Boolean(ok);
2944
+ } catch {
2945
+ return false;
2946
+ }
2947
+ }
2948
+
2949
+ function setupOmnirouteCapsule() {
2950
+ const dot = $("omnirouteStatusDot");
2951
+ const portLink = $("omniroutePortLink");
2952
+ const capsule = $("omnirouteCapsule");
2953
+
2954
+ const handleCopyPortLink = async (e) => {
2955
+ if (e) {
2956
+ e.preventDefault();
2957
+ e.stopPropagation();
2958
+ }
2959
+ const targetUrl = `http://localhost:${omniroutePort}`;
2960
+ await copyTextToClipboard(targetUrl);
2961
+ showToast(`Copied port link to clipboard! Paste into your browser to enter: ${targetUrl}`, "info", 5000, { noEmoji: true });
2962
+ };
2963
+
2964
+ if (dot) {
2965
+ dot.addEventListener("click", async (e) => {
2966
+ e.preventDefault();
2967
+ e.stopPropagation();
2968
+ checkOmniroute(true);
2969
+ });
2970
+ }
2971
+
2972
+ if (portLink) {
2973
+ portLink.addEventListener("click", (e) => {
2974
+ handleCopyPortLink(e);
2975
+ });
2976
+ }
2977
+
2978
+ if (capsule) {
2979
+ capsule.addEventListener("click", async (e) => {
2980
+ if (e.target === portLink || e.target === dot) return;
2981
+ if (isOmnirouteRunning) {
2982
+ showToast(`Opening OmniRoute dashboard on port ${omniroutePort}...`, "info", 3000, { noEmoji: true });
2983
+ const res = await apiClient.openOmniroute(omniroutePort);
2984
+ if (!res?.opened) {
2985
+ window.open(`http://localhost:${omniroutePort}`, "_blank", "noopener,noreferrer");
2986
+ }
2987
+ } else {
2988
+ checkOmniroute(true);
2989
+ }
2990
+ });
2991
+ }
2992
+
2993
+ // Initial health check
2994
+ checkOmniroute(false);
2995
+
2996
+ // Periodically re-check health every 8s
2997
+ setInterval(() => {
2998
+ checkOmniroute(false);
2999
+ }, 8000);
3000
+
3001
+ // Also re-check when window gains focus
3002
+ window.addEventListener("focus", () => {
3003
+ checkOmniroute(false);
3004
+ });
3005
+ }
3006
+
3007
+ // --- Foreign Components Modal Prompt (Invariant 5 Compliant) ---
3008
+ function promptForeignComponentsModal(agentName, components) {
3009
+ return new Promise((resolve) => {
3010
+ const modal = $("foreignComponentsModal");
3011
+ const nameEl = $("foreignAgentName");
3012
+ const listEl = $("foreignComponentsList");
3013
+ const btnDelete = $("btnDeleteForeignComponents");
3014
+ const btnCancel = $("btnCancelForeignModal");
3015
+ const btnClose = $("closeForeignModal");
3016
+
3017
+ if (!modal || !listEl) return resolve("cancel");
3018
+
3019
+ if (nameEl) nameEl.textContent = agentName || "Agent";
3020
+ listEl.innerHTML = (components || [])
3021
+ .map(
3022
+ (c) => `
3023
+ <div style="display:flex; justify-content:space-between; align-items:center; padding:4px 0; border-bottom:1px solid rgba(128,128,128,0.15);">
3024
+ <div>
3025
+ <strong>${escapeHtml(c.name)}</strong>
3026
+ <span style="font-size:10.5px; opacity:0.8; margin-left:4px; padding:1px 5px; border-radius:3px; background:rgba(239,68,68,0.15); color:#ef4444;">${escapeHtml(c.type || "foreign")}</span>
3027
+ </div>
3028
+ <span style="font-size:11px; color:var(--magpie-muted); max-width:240px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="${escapeHtml(c.path)}">${escapeHtml(c.path)}</span>
3029
+ </div>`
3030
+ )
3031
+ .join("");
3032
+
3033
+ modal.style.display = "flex";
3034
+
3035
+ const cleanup = () => {
3036
+ modal.style.display = "none";
3037
+ btnDelete?.removeEventListener("click", handleDelete);
3038
+ btnCancel?.removeEventListener("click", handleCancel);
3039
+ btnClose?.removeEventListener("click", handleCancel);
3040
+ };
3041
+
3042
+ const handleDelete = () => {
3043
+ cleanup();
3044
+ resolve("delete");
3045
+ };
3046
+
3047
+ const handleCancel = () => {
3048
+ cleanup();
3049
+ resolve("cancel");
3050
+ };
3051
+
3052
+ btnDelete?.addEventListener("click", handleDelete);
3053
+ btnCancel?.addEventListener("click", handleCancel);
3054
+ btnClose?.addEventListener("click", handleCancel);
3055
+ });
3056
+ }
3057
+
3058
+ function setupEventListeners() {
3059
+ // Hub Storage Path manual input with debounce
3060
+ let hubInputTimer = null;
3061
+ if ($("hubPathInput")) {
3062
+ $("hubPathInput").addEventListener("input", (e) => {
3063
+ clearTimeout(hubInputTimer);
3064
+ const cleanVal = (e.target.value || "").trim().replace(/^["']+|["']+$/g, "").trim();
3065
+ hubConfig.hubRoot = cleanVal;
3066
+ hubInputTimer = setTimeout(async () => {
3067
+ await reloadPluginsFromHub();
3068
+ renderAll();
3069
+ triggerAutoSync();
3070
+ }, 350);
3071
+ });
3072
+ $("hubPathInput").addEventListener("change", async (e) => {
3073
+ clearTimeout(hubInputTimer);
3074
+ const cleanVal = (e.target.value || "").trim().replace(/^["']+|["']+$/g, "").trim();
3075
+ hubConfig.hubRoot = cleanVal;
3076
+ await reloadPluginsFromHub();
3077
+ renderAll();
3078
+ triggerAutoSync();
3079
+ });
3080
+ }
3081
+
3082
+ // Native HTML5 folder picker for Components Storage Path
3083
+ const hubFolderPicker = $("hubFolderPicker");
3084
+ if (hubFolderPicker) {
3085
+ hubFolderPicker.addEventListener("change", async (e) => {
3086
+ const files = e.target.files;
3087
+ if (!files || files.length === 0) return;
3088
+ let chosenPath = "";
3089
+ if (files[0].path) {
3090
+ const first = files[0].path;
3091
+ const rel = files[0].webkitRelativePath || "";
3092
+ if (rel && first.includes(rel.replace(/\//g, "\\"))) {
3093
+ chosenPath = first.substring(0, first.indexOf(rel.replace(/\//g, "\\")) + rel.split(/[/\\]/)[0].length);
3094
+ } else {
3095
+ const parts = first.split(/[/\\]/);
3096
+ parts.pop();
3097
+ chosenPath = parts.join("\\");
3098
+ }
3099
+ }
3100
+ if (!chosenPath && files[0].webkitRelativePath) {
3101
+ const topFolder = files[0].webkitRelativePath.split("/")[0];
3102
+ const resolved = await apiClient.resolveDroppedTarget(topFolder, "project");
3103
+ if (resolved && resolved.success && resolved.realPath) {
3104
+ chosenPath = resolved.realPath;
3105
+ } else {
3106
+ chosenPath = topFolder;
3107
+ }
3108
+ }
3109
+ if (chosenPath) {
3110
+ hubConfig.hubRoot = chosenPath;
3111
+ if ($("hubPathInput")) $("hubPathInput").value = chosenPath;
3112
+ await reloadPluginsFromHub();
3113
+ renderAll();
3114
+ triggerAutoSync();
3115
+ }
3116
+ hubFolderPicker.value = "";
3117
+ });
3118
+ }
3119
+
3120
+ // Browse Folder for Components Storage Path
3121
+ if ($("btnPickHubFolder")) {
3122
+ $("btnPickHubFolder").addEventListener("click", async () => {
3123
+ if (hubFolderPicker) {
3124
+ try { hubFolderPicker.click(); } catch (err) {}
3125
+ }
3126
+ try {
3127
+ $("btnPickHubFolder").textContent = "Opening...";
3128
+ const res = await apiClient.browseFileSystem("folder");
3129
+ $("btnPickHubFolder").textContent = "Browse...";
3130
+ if (res && !res.cancelled && res.realPath) {
3131
+ hubConfig.hubRoot = res.realPath;
3132
+ if ($("hubPathInput")) $("hubPathInput").value = res.realPath;
3133
+ await reloadPluginsFromHub();
3134
+ renderAll();
3135
+ triggerAutoSync();
3136
+ }
3137
+ } catch (err) {
3138
+ $("btnPickHubFolder").textContent = "Browse...";
3139
+ console.warn("Browse Hub folder error:", err);
3140
+ }
3141
+ });
3142
+ }
3143
+
3144
+ // Reset Default Button -> Resets to 1st connected IDE's config link directory
3145
+ if ($("btnBrowseHubPath")) {
3146
+ $("btnBrowseHubPath").addEventListener("click", async () => {
3147
+ // Clear manual hubRoot so it auto-links to 1st connected IDE's config path
3148
+ hubConfig.hubRoot = "";
3149
+ if ($("hubPathInput")) $("hubPathInput").value = "";
3150
+ await reloadPluginsFromHub();
3151
+ renderAll();
3152
+ triggerAutoSync();
3153
+ });
3154
+ }
3155
+
3156
+ // Toggle expandable Discovered Components list (Plugins, MCPs, Hooks, Skills, Agents, Rules)
3157
+ const btnToggleComp = $("btnToggleComponentsDetails");
3158
+ const compPanel = $("componentsExpandPanel");
3159
+ if (btnToggleComp && compPanel) {
3160
+ btnToggleComp.addEventListener("click", () => {
3161
+ const isHidden = compPanel.style.display === "none" || !compPanel.style.display;
3162
+ compPanel.style.display = isHidden ? "block" : "none";
3163
+ if ($("expandIcon")) $("expandIcon").textContent = isHidden ? "▲" : "▼";
3164
+ if ($("expandLabel")) $("expandLabel").textContent = isHidden ? "Collapse Components List" : "Expand Components List";
3165
+ if (isHidden) {
3166
+ renderCategoryBrowser();
3167
+ }
3168
+ });
3169
+ }
3170
+
3171
+ // Category Filter Tabs
3172
+ const catTabs = document.querySelectorAll(".cat-tab");
3173
+ catTabs.forEach((tab) => {
3174
+ tab.addEventListener("click", () => {
3175
+ catTabs.forEach((t) => t.classList.remove("active"));
3176
+ tab.classList.add("active");
3177
+ activeCategoryTab = tab.dataset.cat || "all";
3178
+ renderCategoryBrowser();
3179
+ });
3180
+ });
3181
+
3182
+ // Category search input
3183
+ const catSearch = $("catSearchInput");
3184
+ if (catSearch) {
3185
+ catSearch.addEventListener("input", (e) => {
3186
+ categorySearchFilter = e.target.value.toLowerCase().trim();
3187
+ renderCategoryBrowser();
3188
+ });
3189
+ }
3190
+
3191
+ // Expand / Collapse All Files in Components & Plugins table
3192
+ const btnToggleAll = $("btnToggleAllFiles");
3193
+ if (btnToggleAll) {
3194
+ btnToggleAll.addEventListener("click", () => {
3195
+ allFilesExpanded = !allFilesExpanded;
3196
+ if (allFilesExpanded) {
3197
+ discoveredPlugins.forEach((p) => expandedFiles.add(p.id));
3198
+ btnToggleAll.textContent = "Collapse All Files";
3199
+ } else {
3200
+ expandedFiles.clear();
3201
+ btnToggleAll.textContent = "Expand All Files";
3202
+ }
3203
+ renderPluginTable();
3204
+ });
3205
+ }
3206
+
3207
+ // Smart Middleware Toggle
3208
+ if ($("smartMiddlewareToggle")) {
3209
+ $("smartMiddlewareToggle").addEventListener("change", async (e) => {
3210
+ if (!hubConfig.smartMiddleware) hubConfig.smartMiddleware = {};
3211
+ hubConfig.smartMiddleware.enabled = e.target.checked;
3212
+ if ($("middlewareStatusLabel")) {
3213
+ $("middlewareStatusLabel").textContent = e.target.checked
3214
+ ? "Smart Middleware: Active"
3215
+ : "Smart Middleware: Bypassed";
3216
+ $("middlewareStatusLabel").className = `toggle-label ${e.target.checked ? "" : "disabled"}`;
3217
+ }
3218
+ if ($("gatewayStatus")) {
3219
+ $("gatewayStatus").textContent = e.target.checked ? "Active" : "Disabled";
3220
+ }
3221
+ triggerAutoSync();
3222
+ });
3223
+ }
3224
+
3225
+ // Adjustable Tool Cap input
3226
+ if ($("maxToolsInput")) {
3227
+ $("maxToolsInput").addEventListener("input", (e) => {
3228
+ let val = parseInt(e.target.value, 10);
3229
+ if (isNaN(val) || val < 1) val = 96;
3230
+ if (!hubConfig.smartMiddleware) hubConfig.smartMiddleware = {};
3231
+ hubConfig.smartMiddleware.maxTools = val;
3232
+ if ($("capSubtitle")) {
3233
+ $("capSubtitle").textContent = `Capping at ${val} safe tools for Smart Middleware`;
3234
+ }
3235
+ triggerAutoSync();
3236
+ });
3237
+ }
3238
+
3239
+ // Default button (Reset cap to 96)
3240
+ if ($("btnResetCap")) {
3241
+ $("btnResetCap").addEventListener("click", () => {
3242
+ if (!hubConfig.smartMiddleware) hubConfig.smartMiddleware = {};
3243
+ hubConfig.smartMiddleware.maxTools = 96;
3244
+ if ($("maxToolsInput")) $("maxToolsInput").value = 96;
3245
+ if ($("capSubtitle")) $("capSubtitle").textContent = "Capping at 96 safe tools for Smart Middleware";
3246
+ triggerAutoSync();
3247
+ });
3248
+ }
3249
+
3250
+ // Standardize Storage Structure Prompt Copy Button (with version display)
3251
+ const STORAGE_PROMPT_VERSION = "V1.4";
3252
+ const btnCopyPrompt = $("btnCopyStoragePrompt");
3253
+ if (btnCopyPrompt) {
3254
+ const originalText = `Copy Prompt (${STORAGE_PROMPT_VERSION})`;
3255
+ btnCopyPrompt.textContent = originalText;
3256
+ btnCopyPrompt.addEventListener("click", async () => {
3257
+ const effectiveHub = computeEffectiveHubPath();
3258
+ const storagePath = effectiveHub?.path || "";
3259
+ const targetPathHeader = storagePath ? `Components Storage Target Path: ${storagePath}\n\n` : "";
3260
+
3261
+ const promptText = `[Components Storage Specification & Upstream Rules Prompt ${STORAGE_PROMPT_VERSION}]
3262
+
3263
+ Please organize and force our Components Storage file structure to strictly adhere to the standard plugin specification, record mandatory upstream source links, eliminate decentralized component updaters, ensure complete plugin uninstallation cleanup, enforce UTF-8 without BOM encoding, respect one-time rearrangement stability, define universal shared folder specifications, and install a persistent agent rule:
3264
+
3265
+ ${targetPathHeader}1. Directory Structure Specification:
3266
+ Components Storage root (e.g. \`<Components Storage Path>\`) contains plugins, optional standalone skills, hub configuration, and a shared cross-agent communication/data directory:
3267
+
3268
+ <Components Storage Path>/
3269
+ ├── plugins/ # Standard plugin directory
3270
+ │ └── <plugin-name>/
3271
+ │ ├── plugin.json # Required manifest file (must include "upstream" source URL)
3272
+ │ ├── mcp_config.json # Optional MCP server definitions
3273
+ │ ├── hooks.json # Optional hooks definition
3274
+ │ ├── skills/ # Optional skills directory
3275
+ │ │ └── <upstream GitHub name/self (if self created)-skill-name>/
3276
+ │ │ └── SKILL.md # Must include upstream: <url> in YAML frontmatter
3277
+ │ ├── agents/ # Optional subagent definition templates
3278
+ │ │ └── <upstream GitHub name/self (if self created)-agent-name>.md # Must include upstream in frontmatter
3279
+ │ └── rules/ # Optional rules directory
3280
+ │ └── <upstream GitHub name/self (if self created)-rule-name>.md # Must include upstream in frontmatter
3281
+ ├── shared/ # Cross-agent IPC, discovery registry, handoff, and shared tools directory
3282
+ │ ├── agent-connectors.json # Cross-agent messaging and discovery registry (active IDE agents & capabilities)
3283
+ │ ├── handoff/ # Cross-agent delegation and task handoff inboxes
3284
+ │ │ └── <agent-id>/ # Target agent inbox queue
3285
+ │ ├── _upstream_backups/ # Pre-update backups and component snapshots
3286
+ │ └── <shared-tool-dirs>/ # Shared runtime states, engines, caches, or browser automation; subfolders are named after their joining skills (e.g. stagehand-fastcrw joining stagehand and fastcrw, omniroute)
3287
+ ├── skills/ # Standalone or migrated skills
3288
+ ├── hub-config.json # Hub configuration
3289
+ ├── plugins.json # Discovered/registered plugins index
3290
+ └── skills.json # Discovered/registered skills index
3291
+
3292
+ Duplicate Naming Collision Rule: If two or more components (plugins, skills, agents, rules, or MCPs) coincidentally have the same name, append \`-1\`, \`-2\`, etc. sequentially (e.g. \`<name>-1\`, \`<name>-2\`) so every component has a unique name without colliding or overwriting.
3293
+
3294
+ 2. Shared Folder Specification (<Components Storage Path>/shared):
3295
+ The shared directory serves as the centralized cross-agent IPC, discovery, and shared coordination layer across all supported AI coding agents (Antigravity, Cursor, Windsurf, Claude Code, OpenCode, VS Code Copilot, etc.):
3296
+ - agent-connectors.json: Global discovery registry tracking connected agent profiles, capability flags, root config paths, and communication bridges.
3297
+ - handoff/: Inter-agent handoff queues. Enables asynchronous task delegation and context packet transfers between agents across different IDEs.
3298
+ - _upstream_backups/: Centralized safety backups created prior to weekly upstream component updates or synchronization runs.
3299
+ - Shared Tooling & State Subfolder Naming: Shared runtime caches, browser automation tools, and routing engines accessible universally across all connected agents without redundant duplication. Any subfolder created in shared/ for collaborating skills MUST be named after the joining skills (e.g. \`stagehand-fastcrw\` representing the joint operation of \`stagehand\` and \`fastcrw\`).
3300
+ - Invariant: Never treat the shared/ directory or its internal files as loose components, and never delete or clear user-managed handoffs or shared configs during plugin cleanup.
3301
+
3302
+ 3. Mandatory Upstream Links:
3303
+ For EVERY component (plugin, skill, rule, agent, MCP) installed in Components Storage Path:
3304
+ - Identify and record the upstream source link (GitHub repository URL, official documentation URL, or author registry link) where the component was saved or fetched from:
3305
+ * In plugin.json: Include "upstream": "https://github.com/<owner>/<repo>" (or source repository URL).
3306
+ * In SKILL.md: Include upstream: "https://github.com/<owner>/<repo>" in the YAML frontmatter.
3307
+ * In rules (*.md): Include upstream: "https://github.com/<owner>/<repo>" in the YAML frontmatter.
3308
+ * In agents (*.md): Include upstream: "https://github.com/<owner>/<repo>" in the YAML frontmatter.
3309
+
3310
+ 4. Complete Plugin Removal & Cleanup:
3311
+ When the user asks to remove, delete, or uninstall a plugin:
3312
+ - Remove the plugin directory itself (plugins/<plugin-name>/).
3313
+ - Concurrently remove ALL components related to that plugin across Components Storage and connected agent configs:
3314
+ * Associated skills in the plugin's skills/ directory and any bridged skill links.
3315
+ * Associated subagents in agents/ and any bridged agent definitions.
3316
+ * Associated rules in rules/ and any bridged rule files or managed rule sections.
3317
+ * Associated MCP server definitions in mcp_config.json and their bridged entries.
3318
+ * Associated hooks in hooks.json and their bridged hook entries.
3319
+ - Ensure no orphaned components, dangling junctions/symlinks, or ghost configuration entries associated with the removed plugin remain.
3320
+
3321
+ 5. Centralized Weekly Update Checking (No Decentralized Scripts):
3322
+ - Remove and DO NOT create individual, local, or decentralized update scripts (such as update_checker.mjs or update_check_state.json) inside component folders.
3323
+ - Update checking for all components in Components Storage Path is centralized once per week in this Agent Space Manager plugin (running automatically on the first day starting on Monday whenever the user starts up Magpie).
3324
+ - Prune any obsolete local component update checking scripts or decentralized state files.
3325
+
3326
+ 6. Mandatory File Encoding (Strict UTF-8 Without BOM):
3327
+ - ALL manifest and configuration files (plugin.json, mcp_config.json, hooks.json, SKILL.md, and *.md) MUST be written strictly in standard UTF-8 without Byte Order Mark (UTF-8 No BOM).
3328
+ - NEVER output or save files with a UTF-8 BOM (\\uFEFF or byte sequence 0xEF, 0xBB, 0xBF). A BOM header corrupts JSON parsing across IDEs and tools, leading to "Invalid plugin.json" errors.
3329
+ - If executing file writes via Windows PowerShell (5.1), avoid standard Out-File or Set-Content defaults; always write without BOM using Node.js fs.writeFileSync(path, content, "utf8"), PowerShell 7 -Encoding utf8NoBOM, or [System.IO.File]::WriteAllText($path, $content, (New-Object System.Text.UTF8Encoding($false))).
3330
+
3331
+ 7. One-Time Rearrangement Stability:
3332
+ - If the rearrangement of the file structure in Components Storage Path has already been executed once using this prompt, STOP rearranging or moving existing directory/file structures on subsequent runs unless the user explicitly requests a rearrangement.
3333
+ - Preserve already-organized components in their current locations to prevent directory churn and broken path references.
3334
+
3335
+ 8. Mandatory Persistent Agent Rule:
3336
+ Install and persist a dedicated rule in your agent's rule system (e.g. .agents/rules/components-storage-upstream-rule.md or .cursor/rules/components-storage-upstream-rule.mdc) that is ALWAYS TRIGGERED whenever an addendum, creation, modification, edit, or removal of any component in the Components Storage Path (${storagePath || "Components Storage Path"}):
3337
+ - Rule Trigger: Addendum, creation, edit, or removal of any component in Components Storage Path.
3338
+ - Rule Invariant 1: Ensure strict compliance with the plugin directory and shared/ directory structures above, and disambiguate any coincidental duplicate component names by appending -1, -2, etc. sequentially.
3339
+ - Rule Invariant 2: Always add and preserve the upstream link in the component's manifest or frontmatter.
3340
+ - Rule Invariant 3: Complete removal cleanup — when removing a plugin, all components related to that plugin (skills, agents, rules, MCP servers, hooks) must also be cleanly removed with no orphaned leftovers.
3341
+ - Rule Invariant 4: Never introduce decentralized or component-level update scripts; all update checking is handled centrally by the Agent Space Manager plugin on Monday startup.
3342
+ - Rule Invariant 5: Never write files with a UTF-8 BOM header; always enforce UTF-8 No BOM encoding.
3343
+ - Rule Invariant 6: One-Time Rearrangement Stability — if file rearrangement was already performed once, never rearrange or move existing structure again on subsequent prompt runs unless explicitly requested by the user.
3344
+ - Rule Invariant 7: Universal Shared Directory Preservation & Naming — preserve <Components Storage Path>/shared (agent-connectors.json, handoff/, _upstream_backups/) as the designated cross-agent communication and data hub; never treat it as an orphaned or removable plugin; any subfolders in shared/ must be named after their joining skills (e.g. stagehand-fastcrw joining stagehand and fastcrw).
3345
+
3346
+ Please inspect ${storagePath || "Components Storage Path"}, clean up non-conforming or loose files, ensure all component manifests and frontmatters contain their upstream links, ensure all JSON files are valid UTF-8 without BOM, purge any decentralized update checking scripts, ensure removal rules cover all related components, preserve the shared/ cross-agent folder, respect one-time rearrangement stability if already arranged, and persist the rule into your agent's rules.`;
3347
+
3348
+ let copied = false;
3349
+ if (navigator.clipboard && navigator.clipboard.writeText) {
3350
+ try {
3351
+ await navigator.clipboard.writeText(promptText);
3352
+ copied = true;
3353
+ } catch {}
3354
+ }
3355
+ if (!copied) {
3356
+ try {
3357
+ const ta = document.createElement("textarea");
3358
+ ta.value = promptText;
3359
+ ta.style.position = "fixed";
3360
+ ta.style.opacity = "0";
3361
+ document.body.appendChild(ta);
3362
+ ta.select();
3363
+ document.execCommand("copy");
3364
+ document.body.removeChild(ta);
3365
+ copied = true;
3366
+ } catch {}
3367
+ }
3368
+
3369
+ btnCopyPrompt.textContent = copied ? "Copied!" : "Copy Failed";
3370
+ btnCopyPrompt.classList.add("copied");
3371
+ setTimeout(() => {
3372
+ btnCopyPrompt.textContent = originalText;
3373
+ btnCopyPrompt.classList.remove("copied");
3374
+ }, 2000);
3375
+ });
3376
+ }
3377
+
3378
+ const agentTypeSelect = $("agentTypeSelect");
3379
+ const agentCapabilityChips = $("agentCapabilityChips");
3380
+ const agentTargetPaths = $("agentTargetPaths");
3381
+ const autoDetectToggle = $("autoDetectConfigToggle");
3382
+ const ideConfigInput = $("ideConfigInput");
3383
+ const ideExeInput = $("ideExeInput");
3384
+ const ideNameInput = $("ideNameInput");
3385
+ const autoDetectLabel = $("autoDetectLabel");
3386
+ const configHint = $("configHint");
3387
+
3388
+ if ($("btnToggleComponentPaths")) {
3389
+ $("btnToggleComponentPaths").addEventListener("click", (e) => {
3390
+ e.preventDefault();
3391
+ e.stopPropagation();
3392
+ const body = $("componentPathsBody");
3393
+ const isCollapsed = !body || body.style.display === "none";
3394
+ setComponentPathsCollapsed(!isCollapsed);
3395
+ });
3396
+ }
3397
+ if ($("componentPathsToggleTitle")) {
3398
+ $("componentPathsToggleTitle").addEventListener("click", () => {
3399
+ const body = $("componentPathsBody");
3400
+ const isCollapsed = !body || body.style.display === "none";
3401
+ setComponentPathsCollapsed(!isCollapsed);
3402
+ });
3403
+ }
3404
+
3405
+ if ($("btnResetComponentPaths")) {
3406
+ $("btnResetComponentPaths").addEventListener("click", () => {
3407
+ const sel = agentTypeSelect?.value || "antigravity";
3408
+ populateComponentPathsInputs(sel);
3409
+ });
3410
+ }
3411
+
3412
+ // Modal triggers
3413
+ if ($("openAddIdeModalBtn")) {
3414
+ $("openAddIdeModalBtn").addEventListener("click", () => {
3415
+ editingIdeId = null;
3416
+ if ($("addIdeModal")) $("addIdeModal").style.display = "flex";
3417
+ const titleEl = $("addIdeModal")?.querySelector(".modal-head h3");
3418
+ if (titleEl) titleEl.textContent = "Add Agent IDE / Binary Link";
3419
+ if ($("saveIdeBtn")) $("saveIdeBtn").textContent = "Add IDE";
3420
+ if ($("ideNameInput")) $("ideNameInput").value = "";
3421
+ if ($("ideExeInput")) $("ideExeInput").value = "";
3422
+ const selType = agentTypeSelect?.value || "claude-code";
3423
+ const prof = agentProfiles.find((p) => p.id === selType);
3424
+ if (ideNameInput && prof) {
3425
+ ideNameInput.value = prof.label;
3426
+ }
3427
+ renderSelectedAgentMeta(selType);
3428
+ updateAutoDetectState();
3429
+ setComponentPathsCollapsed(true);
3430
+ });
3431
+ }
3432
+ if ($("closeIdeModal")) $("closeIdeModal").addEventListener("click", () => $("addIdeModal").style.display = "none");
3433
+ if ($("cancelIdeBtn")) $("cancelIdeBtn").addEventListener("click", () => $("addIdeModal").style.display = "none");
3434
+
3435
+ async function updateAutoDetectState() {
3436
+ if (!autoDetectToggle || !ideConfigInput) return;
3437
+ const selectedType = agentTypeSelect?.value || "antigravity";
3438
+ const isCustom = selectedType === "custom";
3439
+ const isAuto = isCustom ? false : autoDetectToggle.checked;
3440
+ ideConfigInput.readOnly = isAuto;
3441
+ if (autoDetectLabel) {
3442
+ autoDetectLabel.textContent = isAuto ? "Auto-detect: ON" : "Auto-detect: OFF";
3443
+ autoDetectLabel.style.color = isAuto ? "#16a34a" : "var(--magpie-muted)";
3444
+ }
3445
+ if (configHint) {
3446
+ configHint.textContent = isAuto
3447
+ ? "Automatically resolved for selected Agent Profile. Turn off to type custom path."
3448
+ : "Manual input active. Enter full path where skills/plugins should be linked.";
3449
+ }
3450
+ if (isAuto) {
3451
+ const lookupKey = selectedType !== "custom" ? selectedType : (ideNameInput?.value || "agent");
3452
+ ideConfigInput.value = await detectDefaultConfigPath(lookupKey, ideExeInput?.value);
3453
+ }
3454
+ }
3455
+
3456
+ if (agentTypeSelect) {
3457
+ agentTypeSelect.addEventListener("change", async () => {
3458
+ const sel = agentTypeSelect.value;
3459
+ const prof = agentProfiles.find((p) => p.id === sel);
3460
+ if (prof && ideNameInput) {
3461
+ ideNameInput.value = prof.label;
3462
+ }
3463
+ if (sel === "custom" && autoDetectToggle) {
3464
+ autoDetectToggle.checked = false;
3465
+ } else if (autoDetectToggle) {
3466
+ autoDetectToggle.checked = true;
3467
+ }
3468
+ renderSelectedAgentMeta(sel);
3469
+ await updateAutoDetectState();
3470
+ });
3471
+ }
3472
+
3473
+ if (autoDetectToggle) {
3474
+ autoDetectToggle.addEventListener("change", updateAutoDetectState);
3475
+ }
3476
+ if (ideNameInput) {
3477
+ ideNameInput.addEventListener("input", () => {
3478
+ if (autoDetectToggle?.checked) updateAutoDetectState();
3479
+ });
3480
+ }
3481
+ if (ideExeInput) {
3482
+ ideExeInput.addEventListener("input", () => {
3483
+ if (autoDetectToggle?.checked) updateAutoDetectState();
3484
+ });
3485
+ }
3486
+
3487
+ // Native HTML5 file picker for Agent Executable
3488
+ const ideExePicker = $("ideExePicker");
3489
+ if (ideExePicker) {
3490
+ ideExePicker.addEventListener("change", async (e) => {
3491
+ const files = e.target.files;
3492
+ if (!files || files.length === 0) return;
3493
+ const file = files[0];
3494
+ const rawPath = file.path || file.name;
3495
+ const res = await apiClient.resolveDroppedTarget(rawPath, "ide");
3496
+ if (res && res.success && res.realPath) {
3497
+ if (ideExeInput) ideExeInput.value = res.realPath;
3498
+ if (ideNameInput) ideNameInput.value = res.name;
3499
+ if (res.agentType && agentTypeSelect) {
3500
+ agentTypeSelect.value = res.agentType;
3501
+ renderSelectedAgentMeta(res.agentType);
3502
+ }
3503
+ if (autoDetectToggle?.checked && ideConfigInput) {
3504
+ ideConfigInput.value = res.configPath;
3505
+ }
3506
+ } else {
3507
+ if (ideExeInput) ideExeInput.value = rawPath;
3508
+ if (ideNameInput) ideNameInput.value = inferClientName(file.name);
3509
+ await updateAutoDetectState();
3510
+ }
3511
+ ideExePicker.value = "";
3512
+ });
3513
+ }
3514
+
3515
+ // Browse Button for Agent Binary Path
3516
+ if ($("btnBrowseIdeExe")) {
3517
+ $("btnBrowseIdeExe").addEventListener("click", async () => {
3518
+ if (ideExePicker) {
3519
+ try { ideExePicker.click(); } catch (err) {}
3520
+ }
3521
+ try {
3522
+ $("btnBrowseIdeExe").textContent = "Opening...";
3523
+ const res = await apiClient.browseFileSystem("file");
3524
+ $("btnBrowseIdeExe").textContent = "Browse...";
3525
+ if (res && !res.cancelled && res.realPath) {
3526
+ if (ideExeInput) ideExeInput.value = res.realPath;
3527
+ const resolved = await apiClient.resolveDroppedTarget(res.realPath, "ide");
3528
+ if (resolved && resolved.success) {
3529
+ if (ideNameInput) ideNameInput.value = resolved.name;
3530
+ if (autoDetectToggle?.checked && ideConfigInput) {
3531
+ ideConfigInput.value = resolved.configPath;
3532
+ }
3533
+ } else {
3534
+ if (ideNameInput) ideNameInput.value = res.name || inferClientName(res.realPath);
3535
+ }
3536
+ }
3537
+ } catch (err) {
3538
+ $("btnBrowseIdeExe").textContent = "Browse...";
3539
+ console.warn("Browse IDE binary error:", err);
3540
+ }
3541
+ });
3542
+ }
3543
+
3544
+ // Native HTML5 folder picker for Project Repository
3545
+ const projectFolderPicker = $("projectFolderPicker");
3546
+ if (projectFolderPicker) {
3547
+ projectFolderPicker.addEventListener("change", async (e) => {
3548
+ const files = e.target.files;
3549
+ if (!files || files.length === 0) return;
3550
+ let chosenPath = "";
3551
+ if (files[0].path) {
3552
+ const first = files[0].path;
3553
+ const rel = files[0].webkitRelativePath || "";
3554
+ if (rel && first.includes(rel.replace(/\//g, "\\"))) {
3555
+ chosenPath = first.substring(0, first.indexOf(rel.replace(/\//g, "\\")) + rel.split(/[/\\]/)[0].length);
3556
+ } else {
3557
+ const parts = first.split(/[/\\]/);
3558
+ parts.pop();
3559
+ chosenPath = parts.join("\\");
3560
+ }
3561
+ }
3562
+ if (!chosenPath && files[0].webkitRelativePath) {
3563
+ const topFolder = files[0].webkitRelativePath.split("/")[0];
3564
+ const resolved = await apiClient.resolveDroppedTarget(topFolder, "project");
3565
+ if (resolved && resolved.success && resolved.realPath) {
3566
+ chosenPath = resolved.realPath;
3567
+ } else {
3568
+ chosenPath = topFolder;
3569
+ }
3570
+ }
3571
+ if (chosenPath) {
3572
+ if ($("projectPathInput")) $("projectPathInput").value = chosenPath;
3573
+ if ($("projectNameInput")) {
3574
+ const name = chosenPath.split(/[/\\]/).filter(Boolean).pop();
3575
+ if (name) $("projectNameInput").value = name;
3576
+ }
3577
+ }
3578
+ projectFolderPicker.value = "";
3579
+ });
3580
+ }
3581
+
3582
+ // Browse Button for Project Repository Path
3583
+ if ($("btnBrowseProjectPath")) {
3584
+ $("btnBrowseProjectPath").addEventListener("click", async () => {
3585
+ if (projectFolderPicker) {
3586
+ try { projectFolderPicker.click(); } catch (err) {}
3587
+ }
3588
+ try {
3589
+ $("btnBrowseProjectPath").textContent = "Opening...";
3590
+ const res = await apiClient.browseFileSystem("folder");
3591
+ $("btnBrowseProjectPath").textContent = "Browse...";
3592
+ if (res && !res.cancelled && res.realPath) {
3593
+ if ($("projectPathInput")) $("projectPathInput").value = res.realPath;
3594
+ if ($("projectNameInput")) $("projectNameInput").value = res.name;
3595
+ }
3596
+ } catch (err) {
3597
+ $("btnBrowseProjectPath").textContent = "Browse...";
3598
+ console.warn("Browse project repository error:", err);
3599
+ }
3600
+ });
3601
+ }
3602
+
3603
+ if ($("openAddProjectModalBtn")) {
3604
+ $("openAddProjectModalBtn").addEventListener("click", () => {
3605
+ editingProjectId = null;
3606
+ if ($("projectModalTitle")) $("projectModalTitle").textContent = "Add Project Repository";
3607
+ if ($("saveProjectBtn")) $("saveProjectBtn").textContent = "Save Project";
3608
+ if ($("projectNameInput")) $("projectNameInput").value = "";
3609
+ if ($("projectPathInput")) $("projectPathInput").value = "";
3610
+
3611
+ const select = $("projectIdeSelect");
3612
+ if (select) {
3613
+ select.innerHTML = "";
3614
+ hubConfig.ides.forEach((ide) => {
3615
+ const opt = document.createElement("option");
3616
+ opt.value = ide.id;
3617
+ opt.textContent = ide.name;
3618
+ select.appendChild(opt);
3619
+ });
3620
+ }
3621
+ if ($("addProjectModal")) $("addProjectModal").style.display = "flex";
3622
+ });
3623
+ }
3624
+ if ($("closeProjectModal")) $("closeProjectModal").addEventListener("click", () => $("addProjectModal").style.display = "none");
3625
+ if ($("cancelProjectBtn")) $("cancelProjectBtn").addEventListener("click", () => $("addProjectModal").style.display = "none");
3626
+
3627
+ // Add / Edit IDE save
3628
+ if ($("saveIdeBtn")) {
3629
+ $("saveIdeBtn").addEventListener("click", async () => {
3630
+ const agentType = $("agentTypeSelect")?.value || "custom";
3631
+ const prof = agentProfiles.find((p) => p.id === agentType);
3632
+ const name = $("ideNameInput")?.value?.trim() || prof?.label || "Agent";
3633
+ const exePath = $("ideExeInput")?.value?.trim() || "";
3634
+ let configPath = $("ideConfigInput")?.value?.trim();
3635
+
3636
+ if (autoDetectToggle?.checked || !configPath) {
3637
+ configPath = await detectDefaultConfigPath(agentType !== "custom" ? agentType : name, exePath);
3638
+ }
3639
+
3640
+ if (!name || !configPath) {
3641
+ showToast("Please provide an Agent/IDE name and configuration path.", "error");
3642
+ return;
3643
+ }
3644
+
3645
+ const componentPaths = collectComponentPathsFromInputs();
3646
+
3647
+ const ideCandidate = {
3648
+ name,
3649
+ agentType,
3650
+ exePath,
3651
+ configPath,
3652
+ componentPaths,
3653
+ };
3654
+
3655
+ // Scan connected agent for foreign components not from Components Storage Path
3656
+ let foreignScanRes = null;
3657
+ try {
3658
+ foreignScanRes = await apiClient.scanForeignComponents(ideCandidate);
3659
+ if (foreignScanRes && foreignScanRes.hasForeign && foreignScanRes.foreignComponents?.length > 0) {
3660
+ const userChoice = await promptForeignComponentsModal(name, foreignScanRes.foreignComponents);
3661
+ if (userChoice === "delete") {
3662
+ await apiClient.cleanForeignComponents(foreignScanRes.foreignComponents);
3663
+ showToast(`Deleted ${foreignScanRes.foreignComponents.length} foreign components from ${name}`, "success");
3664
+ }
3665
+ }
3666
+ } catch (err) {
3667
+ console.warn("Foreign components scan error:", err);
3668
+ }
3669
+
3670
+ let targetIdeEntry = null;
3671
+ if (editingIdeId) {
3672
+ const existing = hubConfig.ides.find((i) => i.id === editingIdeId);
3673
+ if (existing) {
3674
+ existing.name = name;
3675
+ existing.agentType = agentType;
3676
+ existing.exePath = exePath;
3677
+ existing.configPath = configPath;
3678
+ existing.componentPaths = componentPaths;
3679
+ targetIdeEntry = existing;
3680
+ }
3681
+ } else {
3682
+ const baseId = (agentType !== "custom" ? agentType : name).toLowerCase().replace(/[^a-z0-9]/g, "-");
3683
+ const normConfig = (configPath || "").trim().toLowerCase().replace(/\\/g, "/");
3684
+ const existing = hubConfig.ides.find((i) =>
3685
+ i.id === baseId ||
3686
+ (agentType && agentType !== "custom" && i.agentType === agentType) ||
3687
+ (normConfig && (i.configPath || "").trim().toLowerCase().replace(/\\/g, "/") === normConfig)
3688
+ );
3689
+
3690
+ if (existing) {
3691
+ // Update in-place to avoid duplicate agents and bridges (Requirement R3)
3692
+ existing.name = name;
3693
+ existing.agentType = agentType;
3694
+ existing.exePath = exePath;
3695
+ existing.configPath = configPath;
3696
+ existing.componentPaths = componentPaths;
3697
+ currentSelection = { type: "ide", id: existing.id };
3698
+ targetIdeEntry = existing;
3699
+ } else {
3700
+ const newIde = { id: baseId, name, agentType, exePath, configPath, componentPaths, enabled: true, plugins: {} };
3701
+ hubConfig.ides.push(newIde);
3702
+ currentSelection = { type: "ide", id: baseId };
3703
+ targetIdeEntry = newIde;
3704
+ }
3705
+ }
3706
+
3707
+ // Auto-enable components from Components Storage Path in the Components & Plugins list
3708
+ if (targetIdeEntry) {
3709
+ if (!targetIdeEntry.plugins) targetIdeEntry.plugins = {};
3710
+ let autoEnabledCount = 0;
3711
+
3712
+ if (foreignScanRes && foreignScanRes.hubComponents?.length > 0) {
3713
+ for (const hc of foreignScanRes.hubComponents) {
3714
+ if (hc.id && !targetIdeEntry.plugins[hc.id]) {
3715
+ targetIdeEntry.plugins[hc.id] = true;
3716
+ autoEnabledCount++;
3717
+ }
3718
+ }
3719
+ }
3720
+
3721
+ if (discoveredPlugins.length > 0) {
3722
+ for (const p of discoveredPlugins) {
3723
+ if (targetIdeEntry.plugins[p.id]) continue;
3724
+ const pName = p.name || p.id;
3725
+ if (foreignScanRes?.hubComponents?.some((hc) => hc.name === pName || hc.id === p.id)) {
3726
+ targetIdeEntry.plugins[p.id] = true;
3727
+ autoEnabledCount++;
3728
+ }
3729
+ }
3730
+ }
3731
+
3732
+ if (autoEnabledCount > 0) {
3733
+ showToast(`Auto-enabled ${autoEnabledCount} component(s) from Components Storage Path for ${name}`, "success");
3734
+ }
3735
+ }
3736
+
3737
+ if ($("addIdeModal")) $("addIdeModal").style.display = "none";
3738
+ editingIdeId = null;
3739
+ triggerAutoSync();
3740
+ renderAll();
3741
+ });
3742
+ }
3743
+
3744
+ // Add / Edit Project save
3745
+ if ($("saveProjectBtn")) {
3746
+ $("saveProjectBtn").addEventListener("click", async () => {
3747
+ const name = $("projectNameInput")?.value?.trim();
3748
+ const ideId = $("projectIdeSelect")?.value;
3749
+ const repoPath = $("projectPathInput")?.value?.trim();
3750
+
3751
+ if (!name || !repoPath) {
3752
+ showToast("Please provide project name and repository path.", "error");
3753
+ return;
3754
+ }
3755
+
3756
+ if (editingProjectId) {
3757
+ const existing = hubConfig.projects.find((p) => p.id === editingProjectId);
3758
+ if (existing) {
3759
+ existing.name = name;
3760
+ existing.ideId = ideId;
3761
+ existing.repoPath = repoPath;
3762
+ }
3763
+ } else {
3764
+ const id = "proj-" + Date.now();
3765
+ hubConfig.projects.push({ id, name, ideId, repoPath, plugins: {} });
3766
+ }
3767
+
3768
+ if ($("addProjectModal")) $("addProjectModal").style.display = "none";
3769
+ editingProjectId = null;
3770
+ triggerAutoSync();
3771
+ renderAll();
3772
+ });
3773
+ }
3774
+
3775
+ // Rescan button & Progress Modal
3776
+ if ($("closeRescanModal")) $("closeRescanModal").addEventListener("click", () => $("rescanProgressModal").style.display = "none");
3777
+ if ($("btnDoneRescan")) $("btnDoneRescan").addEventListener("click", () => $("rescanProgressModal").style.display = "none");
3778
+
3779
+ // Status Checking Progress Modal
3780
+ if ($("closeStatusCheckingModal")) $("closeStatusCheckingModal").addEventListener("click", () => statusCheckingUI.hide());
3781
+ if ($("btnBackgroundStatusCheck")) $("btnBackgroundStatusCheck").addEventListener("click", () => statusCheckingUI.hide());
3782
+ if ($("btnDoneStatusCheck")) $("btnDoneStatusCheck").addEventListener("click", () => statusCheckingUI.hide());
3783
+
3784
+ // Connect button: Explicit manual connection trigger (Requirements R1, R2, R3)
3785
+ const connectBtn = $("connectBtn");
3786
+ if (connectBtn) {
3787
+ connectBtn.addEventListener("click", async () => {
3788
+ let target = null;
3789
+ let targetName = "";
3790
+ let isProject = false;
3791
+
3792
+ if (currentSelection.type === "ide") {
3793
+ target = hubConfig.ides.find((i) => i.id === currentSelection.id);
3794
+ targetName = target?.name || target?.id || "Agent";
3795
+ } else if (currentSelection.type === "project") {
3796
+ isProject = true;
3797
+ const proj = hubConfig.projects.find((p) => p.id === currentSelection.id);
3798
+ const parentIde = proj ? hubConfig.ides.find((i) => i.id === proj.ideId) : null;
3799
+ target = parentIde ? { ...parentIde, project: proj } : { id: proj?.id, agentType: "custom", configPath: proj?.repoPath, plugins: proj?.plugins };
3800
+ targetName = proj?.name || "Project";
3801
+ }
3802
+
3803
+ if (!target) {
3804
+ showToast("No agent or project selected to connect.", "error");
3805
+ return;
3806
+ }
3807
+
3808
+ connectBtn.disabled = true;
3809
+ const origText = "Connect";
3810
+ connectBtn.textContent = "Connecting...";
3811
+ const indicator = $("syncIndicator");
3812
+ if (indicator) {
3813
+ indicator.textContent = `Connecting to ${targetName}...`;
3814
+ indicator.className = "sync-indicator syncing";
3815
+ }
3816
+
3817
+ try {
3818
+ // 1. Ensure current configuration preferences are persisted first and dispatch connect request
3819
+ await persistConfig(false, { connect: true, sync: true, connectTarget: target });
3820
+
3821
+ // 2. Execute explicit connection
3822
+ let connectRes = null;
3823
+ if (isProject) {
3824
+ connectRes = await apiClient.connectTarget(target, { isProject: true });
3825
+ } else {
3826
+ connectRes = await apiClient.connectTarget(target);
3827
+ }
3828
+
3829
+ if (connectRes && connectRes.success !== false) {
3830
+ let syncResult = connectRes.result || connectRes.sync;
3831
+ if (connectRes.sync?.results) {
3832
+ for (const r of connectRes.sync.results) {
3833
+ if (r.ideId) lastSyncByIde[r.ideId] = r;
3834
+ if (r.projectId && r.projectId === target.id) syncResult = r;
3835
+ }
3836
+ } else if (target.id) {
3837
+ lastSyncByIde[target.id] = syncResult || { success: true };
3838
+ }
3839
+
3840
+ connectBtn.textContent = "✓ Connected";
3841
+ connectBtn.style.background = "#16a34a";
3842
+ connectBtn.style.borderColor = "transparent";
3843
+
3844
+ if (indicator) {
3845
+ indicator.textContent = "Connected";
3846
+ indicator.className = "sync-indicator";
3847
+ }
3848
+
3849
+ let summaryStr = "Synchronized";
3850
+ if (syncResult?.summary) {
3851
+ const s = syncResult.summary;
3852
+ if (syncResult.mode === "bundle") {
3853
+ summaryStr = `${s.plugins || 0} plugin bundle(s)`;
3854
+ } else {
3855
+ summaryStr = `${s.skills || 0} skills · ${s.mcp || 0} MCP`;
3856
+ }
3857
+ }
3858
+ showToast(`Connected to ${targetName} (${summaryStr})`, "success");
3859
+
3860
+ renderAll();
3861
+
3862
+ setTimeout(() => {
3863
+ connectBtn.disabled = false;
3864
+ connectBtn.textContent = origText;
3865
+ connectBtn.style.background = "";
3866
+ connectBtn.style.borderColor = "";
3867
+ }, 2500);
3868
+ } else {
3869
+ const errMsg = connectRes?.error || "Connection failed";
3870
+ connectBtn.textContent = "✗ Failed";
3871
+ connectBtn.style.background = "#dc2626";
3872
+ connectBtn.style.borderColor = "transparent";
3873
+
3874
+ if (indicator) {
3875
+ indicator.textContent = "Connection Failed";
3876
+ indicator.className = "sync-indicator";
3877
+ }
3878
+
3879
+ showToast(`Connection failed to ${targetName}: ${errMsg}`, "error");
3880
+
3881
+ setTimeout(() => {
3882
+ connectBtn.disabled = false;
3883
+ connectBtn.textContent = origText;
3884
+ connectBtn.style.background = "";
3885
+ connectBtn.style.borderColor = "";
3886
+ }, 3000);
3887
+ }
3888
+ } catch (err) {
3889
+ console.error("Connect error:", err);
3890
+ connectBtn.textContent = "✗ Error";
3891
+ showToast(`Connect error: ${err.message}`, "error");
3892
+
3893
+ setTimeout(() => {
3894
+ connectBtn.disabled = false;
3895
+ connectBtn.textContent = origText;
3896
+ connectBtn.style.background = "";
3897
+ connectBtn.style.borderColor = "";
3898
+ }, 3000);
3899
+ }
3900
+ });
3901
+ }
3902
+
3903
+ if ($("rescanBtn")) {
3904
+ $("rescanBtn").addEventListener("click", async () => {
3905
+ const modal = $("rescanProgressModal");
3906
+ const bar = $("rescanProgressBar");
3907
+ const step = $("rescanStatusStep");
3908
+ const pct = $("rescanStatusPct");
3909
+ const banner = $("rescanSummaryBanner");
3910
+ const cards = $("rescanCardsContainer");
3911
+
3912
+ if (modal) modal.style.display = "flex";
3913
+ if (banner) banner.style.display = "none";
3914
+ if (bar) bar.style.width = "15%";
3915
+ if (pct) pct.textContent = "15%";
3916
+ if (step) step.textContent = "Connecting to Hub components storage path...";
3917
+ if (cards) cards.innerHTML = `<div style="font-size:12px; color:var(--magpie-muted); padding:8px;">Initializing scan...</div>`;
3918
+
3919
+ if ($("hubPathInput")) {
3920
+ hubConfig.hubRoot = ($("hubPathInput").value || "").trim().replace(/^["']+|["']+$/g, "").trim();
3921
+ }
3922
+ const effectivePath = computeEffectiveHubPath().path;
3923
+ const norm = normalizePathForCompare(effectivePath);
3924
+ try {
3925
+ localStorage.removeItem("magpie_plugins_" + norm);
3926
+ } catch {}
3927
+
3928
+ await new Promise((r) => setTimeout(r, 200));
3929
+ if (bar) bar.style.width = "40%";
3930
+ if (pct) pct.textContent = "40%";
3931
+ if (step) step.textContent = `Scanning plugins & components in ${effectivePath}...`;
3932
+
3933
+ let scanResult = null;
3934
+ try {
3935
+ const resp = await fetch(`${API_BASE}/api/rescan`, {
3936
+ method: "POST",
3937
+ headers: { "Content-Type": "application/json" },
3938
+ body: JSON.stringify({ hubRoot: effectivePath }),
3939
+ });
3940
+ if (resp.ok) scanResult = await resp.json();
3941
+ } catch (err) {
3942
+ console.warn("API rescan error, falling back to local sync:", err);
3943
+ }
3944
+
3945
+ if (bar) bar.style.width = "75%";
3946
+ if (pct) pct.textContent = "75%";
3947
+ if (step) step.textContent = "Verifying linking connection status & updating cross-agent communication bridge...";
3948
+
3949
+ await persistConfig(true);
3950
+ await reloadPluginsFromHub(true);
3951
+ renderAll();
3952
+
3953
+ await new Promise((r) => setTimeout(r, 250));
3954
+ if (bar) bar.style.width = "100%";
3955
+ if (pct) pct.textContent = "100%";
3956
+ if (step) step.textContent = "Synchronization & Verification Complete!";
3957
+ if (banner) banner.style.display = "block";
3958
+
3959
+ if (cards) {
3960
+ cards.innerHTML = "";
3961
+
3962
+ // Hub Status Card
3963
+ const hubCard = document.createElement("div");
3964
+ hubCard.style.cssText = "padding:10px 12px; border:1px solid var(--magpie-border, #333); border-radius:6px; background:var(--magpie-surface-alt, rgba(255,255,255,0.02)); font-size:12px;";
3965
+ hubCard.innerHTML = `
3966
+ <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
3967
+ <span style="font-weight:600;">📁 Hub Storage Path (Components Storage)</span>
3968
+ <span style="font-size:11px; padding:2px 8px; border-radius:4px; background:rgba(34,197,94,0.15); color:#22c55e; font-weight:600;">🟢 Connected</span>
3969
+ </div>
3970
+ <div style="color:var(--magpie-muted); font-size:11px; word-break:break-all;">Path: ${escapeHtml(effectivePath)}</div>
3971
+ <div style="font-size:11px; color:#60a5fa; margin-top:2px;">Discovered: ${allPluginsList.length} plugins, ${allPluginsList.reduce((acc, p) => acc + (p.skills?.length || 0), 0)} skills</div>
3972
+ `;
3973
+ cards.appendChild(hubCard);
3974
+
3975
+ // Cross-Agent Communication Bridge Card
3976
+ const bridgeCard = document.createElement("div");
3977
+ bridgeCard.style.cssText = "padding:10px 12px; border:1px solid var(--magpie-border, #333); border-radius:6px; background:var(--magpie-surface-alt, rgba(255,255,255,0.02)); font-size:12px;";
3978
+ bridgeCard.innerHTML = `
3979
+ <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
3980
+ <span style="font-weight:600;">🔗 Cross-Agent Communication Bridge</span>
3981
+ <span style="font-size:11px; padding:2px 8px; border-radius:4px; background:rgba(34,197,94,0.15); color:#22c55e; font-weight:600;">🟢 Active</span>
3982
+ </div>
3983
+ <div style="color:var(--magpie-muted); font-size:11px;">Bridge Manifest: agent-space-bridge.json · Connectors: shared/agent-connectors.json</div>
3984
+ <div style="font-size:11px; color:#10b981; margin-top:2px;">Status: All connected agents synchronized with live handoff inboxes in ${escapeHtml(effectivePath || "Components Storage")}</div>
3985
+ `;
3986
+ cards.appendChild(bridgeCard);
3987
+
3988
+ // Connected IDE Cards
3989
+ hubConfig.ides.forEach((ide) => {
3990
+ const ideCard = document.createElement("div");
3991
+ ideCard.style.cssText = "padding:10px 12px; border:1px solid var(--magpie-border, #333); border-radius:6px; background:var(--magpie-surface-alt, rgba(255,255,255,0.02)); font-size:12px;";
3992
+ const sync = lastSyncByIde[ide.id];
3993
+ let summaryText = "";
3994
+ if (sync?.summary) {
3995
+ const s = sync.summary;
3996
+ if (sync.mode === "bundle") {
3997
+ summaryText = `${s.plugins || 0} bundles · ${s.skills || 0} skills · ${s.rules || 0} rules · ${s.agents || 0} subagents`;
3998
+ } else {
3999
+ summaryText = `${s.skills || 0} skills · ${s.commands || 0} commands · ${s.mcp || 0} MCP · ${s.rules || 0} rules · ${s.agents || 0} agents`;
4000
+ }
4001
+ } else {
4002
+ summaryText = "Linking verified";
4003
+ }
4004
+
4005
+ ideCard.innerHTML = `
4006
+ <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
4007
+ <span style="font-weight:600;">🤖 ${escapeHtml(ide.name)} (${escapeHtml(ide.agentType || "Agent")})</span>
4008
+ <span style="font-size:11px; padding:2px 8px; border-radius:4px; background:rgba(34,197,94,0.15); color:#22c55e; font-weight:600;">🟢 Connected & Synced</span>
4009
+ </div>
4010
+ <div style="color:var(--magpie-muted); font-size:11px; word-break:break-all;">Target: ${escapeHtml(ide.configPath)}</div>
4011
+ <div style="font-size:11px; color:#3b82f6; margin-top:2px;">Linked Components: ${escapeHtml(summaryText)}</div>
4012
+ `;
4013
+ cards.appendChild(ideCard);
4014
+ });
4015
+
4016
+ // Connected Project Overrides Cards
4017
+ (hubConfig.projects || []).forEach((proj) => {
4018
+ const projCard = document.createElement("div");
4019
+ projCard.style.cssText = "padding:10px 12px; border:1px solid var(--magpie-border, #333); border-radius:6px; background:var(--magpie-surface-alt, rgba(255,255,255,0.02)); font-size:12px;";
4020
+ projCard.innerHTML = `
4021
+ <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
4022
+ <span style="font-weight:600;">📂 Project: ${escapeHtml(proj.name)}</span>
4023
+ <span style="font-size:11px; padding:2px 8px; border-radius:4px; background:rgba(34,197,94,0.15); color:#22c55e; font-weight:600;">🟢 Synced</span>
4024
+ </div>
4025
+ <div style="color:var(--magpie-muted); font-size:11px; word-break:break-all;">Repository: ${escapeHtml(proj.repoPath)}</div>
4026
+ <div style="font-size:11px; color:#10b981; margin-top:2px;">Git Exclude Protection: Active (.git/info/exclude)</div>
4027
+ `;
4028
+ cards.appendChild(projCard);
4029
+ });
4030
+ }
4031
+ });
4032
+ }
4033
+
4034
+ // Dismiss button for startup auto-reconnect banner
4035
+ if ($("btnDismissStartupBanner")) {
4036
+ $("btnDismissStartupBanner").addEventListener("click", () => {
4037
+ const banner = $("startupReconnectBanner");
4038
+ if (banner) banner.style.display = "none";
4039
+ });
4040
+ }
4041
+ }
4042
+
4043
+ function renderStartupReconnectStatus(result) {
4044
+ const banner = $("startupReconnectBanner");
4045
+ const msg = $("startupReconnectMsg");
4046
+ const title = $("startupReconnectTitle");
4047
+ const icon = $("startupReconnectIcon");
4048
+ const badge = $("hubPathBadge");
4049
+
4050
+ if (!banner || !msg) return;
4051
+
4052
+ if (result?.hasChanges && result?.autoReconnected) {
4053
+ banner.style.display = "flex";
4054
+ banner.className = "startup-reconnect-banner active";
4055
+ if (title) title.textContent = "⚡ Auto-reconnected Connected Agents";
4056
+ if (icon) icon.textContent = "⚡";
4057
+ let text = `Detected changes in Components Storage Path: ${result.summary}. Auto-reconnected ${result.connectedAgentsCount || 0} agent(s).`;
4058
+ if (result.centralUpdates?.checked) {
4059
+ text += ` • ${result.centralUpdates.summary}`;
4060
+ }
4061
+ msg.textContent = text;
4062
+ if (badge && !badge.classList.contains("disabled")) {
4063
+ badge.textContent = "✓ Auto-Synced on Startup";
4064
+ badge.className = "hub-path-badge auto";
4065
+ }
4066
+ } else if (result?.centralUpdates?.checked) {
4067
+ banner.style.display = "flex";
4068
+ banner.className = "startup-reconnect-banner active";
4069
+ if (title) title.textContent = "📅 Centralized Weekly Upstream Check";
4070
+ if (icon) icon.textContent = "📅";
4071
+ msg.textContent = `${result.centralUpdates.summary} (Centralized Monday weekly check)`;
4072
+ if (badge && !badge.classList.contains("disabled") && (!hubConfig.hubRoot || hubConfig.hubRoot.trim() === "")) {
4073
+ badge.textContent = "✓ Upstream Verified";
4074
+ badge.className = "hub-path-badge auto";
4075
+ }
4076
+ } else if (result && result.hasChanges === false) {
4077
+ if (badge && !badge.classList.contains("disabled") && (!hubConfig.hubRoot || hubConfig.hubRoot.trim() === "")) {
4078
+ badge.textContent = "✓ In Sync with Storage";
4079
+ badge.className = "hub-path-badge auto";
4080
+ }
4081
+ }
4082
+ }
4083
+
4084
+ let lastMagpieSetAt = 0;
4085
+ let magpieSetTimer = null;
4086
+
4087
+ async function pushOptionsToMagpie(forceRescanNonce = false, connectTarget = null) {
4088
+ if (!globalThis.magpie?.options?.set) return;
4089
+ const now = Date.now();
4090
+ const waitMs = Math.max(0, 1080 - (now - lastMagpieSetAt));
4091
+ if (waitMs > 0) {
4092
+ await new Promise((r) => {
4093
+ clearTimeout(magpieSetTimer);
4094
+ magpieSetTimer = setTimeout(r, waitMs);
4095
+ });
4096
+ }
4097
+ try {
4098
+ lastMagpieSetAt = Date.now();
4099
+ const payload = {
4100
+ smartMiddlewareEnabled: hubConfig.smartMiddleware?.enabled !== false,
4101
+ maxTools: Number(hubConfig.smartMiddleware?.maxTools) || 96,
4102
+ toolsRoot: hubConfig.hubRoot !== undefined ? hubConfig.hubRoot : computeEffectiveHubPath().path,
4103
+ hubConfig,
4104
+ };
4105
+ if (forceRescanNonce) {
4106
+ payload.rescanNonce = Date.now();
4107
+ }
4108
+ if (connectTarget) {
4109
+ payload.connectRequest = {
4110
+ target: connectTarget,
4111
+ nonce: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
4112
+ timestamp: Date.now(),
4113
+ };
4114
+ }
4115
+ const saved = (await globalThis.magpie.options.get?.()) || {};
4116
+ await globalThis.magpie.options.set({ ...saved, ...payload });
4117
+ } catch (err) {
4118
+ console.warn("Failed to persist options to Magpie:", err);
4119
+ }
4120
+ }
4121
+
4122
+ let savePreferencesTimer = null;
4123
+ // Preference Persistence: Saves user checkbox selections without auto-connecting (Requirements R1 & R2)
4124
+ function triggerSavePreferences() {
4125
+ const indicator = $("syncIndicator");
4126
+ if (indicator) {
4127
+ indicator.textContent = "Saving preferences...";
4128
+ indicator.className = "sync-indicator syncing";
4129
+ }
4130
+
4131
+ clearTimeout(savePreferencesTimer);
4132
+ savePreferencesTimer = setTimeout(async () => {
4133
+ await persistConfig(false, { connect: false, sync: false });
4134
+ if (indicator) {
4135
+ indicator.textContent = "Preferences saved";
4136
+ indicator.className = "sync-indicator";
4137
+ }
4138
+ }, 450);
4139
+ }
4140
+
4141
+ // Auto-Save configuration without automatic agent connection
4142
+ function triggerAutoSync(options = { connect: false, sync: false }) {
4143
+ const indicator = $("syncIndicator");
4144
+ if (indicator) {
4145
+ indicator.textContent = "Saving...";
4146
+ indicator.className = "sync-indicator syncing";
4147
+ }
4148
+
4149
+ clearTimeout(autoSyncTimer);
4150
+ autoSyncTimer = setTimeout(async () => {
4151
+ await persistConfig(false, options);
4152
+ if (indicator) {
4153
+ indicator.textContent = "Saved";
4154
+ indicator.className = "sync-indicator";
4155
+ }
4156
+ }, 450);
4157
+ }
4158
+
4159
+ async function persistConfig(forceRescan = false, options = { connect: false, sync: false }) {
4160
+ try {
4161
+ localStorage.setItem("magpie_agent_space_config", JSON.stringify(hubConfig));
4162
+ } catch {}
4163
+
4164
+ // 1. Try direct API server first (works in browser / unrestricted WebView)
4165
+ const saveRes = await apiClient.saveConfig(hubConfig, options);
4166
+ if (saveRes) {
4167
+ if (saveRes.sync?.results && Array.isArray(saveRes.sync.results)) {
4168
+ for (const r of saveRes.sync.results) {
4169
+ if (r.ideId) lastSyncByIde[r.ideId] = r;
4170
+ }
4171
+ }
4172
+ if (Array.isArray(saveRes.plugins)) {
4173
+ discoveredPlugins = saveRes.plugins;
4174
+ if (saveRes.categories) {
4175
+ discoveredCategories = saveRes.categories;
4176
+ } else {
4177
+ discoveredCategories = buildClientCategoriesRegistry(discoveredPlugins);
4178
+ }
4179
+ renderAll();
4180
+ }
4181
+ }
4182
+
4183
+ // 2. Persist to Magpie options (triggers background daemon plugins.json watcher inside CSP-sandboxed iframe)
4184
+ await pushOptionsToMagpie(forceRescan, options?.connectTarget || null);
4185
+
4186
+ // 3. If direct saveRes wasn't reachable (CSP sandbox), wait briefly for daemon to write plugins-cache.js and reload it
4187
+ if (!saveRes) {
4188
+ await new Promise((r) => setTimeout(r, 450));
4189
+ await reloadPluginsFromHub(true);
4190
+ renderAll();
4191
+ }
4192
+ }
4193
+
4194
+ function escapeHtml(str) {
4195
+ return String(str || "")
4196
+ .replace(/&/g, "&amp;")
4197
+ .replace(/</g, "&lt;")
4198
+ .replace(/>/g, "&gt;")
4199
+ .replace(/"/g, "&quot;")
4200
+ .replace(/'/g, "&#039;");
4201
+ }
4202
+
4203
+ function truncate(str, len) {
4204
+ if (!str || str.length <= len) return str;
4205
+ return "..." + str.substring(str.length - len + 3);
4206
+ }
4207
+ })();