@jmanuelcorral/bond-app 0.1.5 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +280 -23
  2. package/app/brand/TOKENS.md +5 -5
  3. package/app/layouts/bond.json +10 -14
  4. package/app/mods/bond-agents/api.js +35 -0
  5. package/app/mods/bond-agents/branch.svg +1 -0
  6. package/app/mods/bond-agents/brand.js +53 -2
  7. package/app/mods/bond-agents/config.js +4 -0
  8. package/app/mods/bond-agents/eye-off.svg +1 -0
  9. package/app/mods/bond-agents/eye.svg +1 -0
  10. package/app/mods/bond-agents/main.js +308 -327
  11. package/app/mods/bond-agents/model.js +376 -5
  12. package/app/mods/bond-board/api.js +35 -0
  13. package/app/mods/bond-board/branch.svg +1 -0
  14. package/app/mods/bond-board/brand.js +53 -2
  15. package/app/mods/bond-board/config.js +4 -0
  16. package/app/mods/bond-board/main.js +1000 -449
  17. package/app/mods/bond-board/model.js +170 -28
  18. package/app/mods/bond-pane/close.svg +1 -0
  19. package/app/mods/bond-pane/hide.svg +1 -0
  20. package/app/mods/bond-pane/main.js +103 -0
  21. package/app/mods/bond-pane/mod.json +1 -0
  22. package/app/mods/bond-pane/model.js +18 -0
  23. package/app/mods/bond-pane/split-down.svg +1 -0
  24. package/app/mods/bond-pane/split-right.svg +1 -0
  25. package/app/mods/bond-pane/unzoom.svg +1 -0
  26. package/app/mods/bond-pane/zoom.svg +1 -0
  27. package/app/mods/bond-settings/api.js +35 -0
  28. package/app/mods/bond-settings/brand.js +53 -2
  29. package/app/mods/bond-settings/config.js +4 -0
  30. package/app/mods/bond-settings/main.js +1216 -272
  31. package/app/mods/bond-settings/mod.json +1 -1
  32. package/app/mods/bond-status/api.js +35 -0
  33. package/app/mods/bond-status/brand.js +53 -2
  34. package/app/mods/bond-status/config.js +4 -0
  35. package/app/mods/bond-status/main.js +37 -15
  36. package/app/mods/bond-status/model.js +19 -1
  37. package/app/mods/bond-tabs/brand.js +53 -2
  38. package/app/mods/bond-tabs/main.js +45 -3
  39. package/app/mods/bond-titlebar/brand.js +53 -2
  40. package/app/mods/bond-titlebar/main.js +85 -29
  41. package/app/mods/bond-titlebar/version.js +3 -0
  42. package/app/themes/bond-dark.json +5 -5
  43. package/app/themes/bond-light.json +5 -5
  44. package/package.json +1 -1
  45. package/runner/Dockerfile +16 -2
  46. package/runner/SPIKE-BOND.md +6 -2
  47. package/runner/entrypoint.sh +16 -0
  48. package/runner/setup.sh +439 -8
  49. package/runner/versions.env +32 -1
  50. package/scripts/app-install.ts +322 -27
  51. package/src/cli.ts +562 -21
  52. package/src/config.ts +15 -3
  53. package/src/core/agy-login.ts +683 -0
  54. package/src/core/delivery.ts +125 -6
  55. package/src/core/doctor.ts +748 -0
  56. package/src/core/hub-session.ts +108 -91
  57. package/src/core/hub.ts +40 -8
  58. package/src/core/orchestrator.ts +1481 -187
  59. package/src/core/paths.ts +107 -0
  60. package/src/core/permissions.ts +143 -0
  61. package/src/core/pr-source.ts +147 -0
  62. package/src/core/repo-host.ts +60 -0
  63. package/src/core/service-windows.ts +180 -0
  64. package/src/core/service.ts +861 -0
  65. package/src/core/setup-install.ts +1380 -0
  66. package/src/core/setup.ts +62 -1
  67. package/src/core/watchdog.ts +6 -6
  68. package/src/db/database.ts +54 -7
  69. package/src/db/settings-repo.ts +332 -7
  70. package/src/db/ticket-repo.ts +73 -25
  71. package/src/index.ts +4 -4
  72. package/src/runner/azure-devops-client.ts +273 -0
  73. package/src/runner/docker-client.ts +93 -9
  74. package/src/runner/github-client.ts +148 -3
  75. package/src/runner/hc-client.ts +33 -5
  76. package/src/runner/image-builder.ts +123 -5
  77. package/src/runner/jira-client.ts +368 -0
  78. package/src/runner/tool-catalog.ts +84 -0
  79. package/src/server/app.ts +467 -8
  80. package/src/types.ts +140 -2
@@ -22,14 +22,19 @@
22
22
  // PUT /setup { suggestions_model } and the orchestrator injects it per run as
23
23
  // ~/.pi/agent/supi/config.json next to the models.json.
24
24
  //
25
- // Props: none (the panel), or { view: "credential", agent, provider } /
26
- // { view: "rebuild" } / { view: "wizard", step } when this mod is opened as a
27
- // dialog or overlay by itself or by bond-board.
28
- import { View, div } from "gpui-kit";
25
+ // Plan bond-app-ajustes-imagen P1: Ajustes is no longer a side panel of the layout but a
26
+ // modal dialog with a section list on the left (Orquestador · Agentes · GitHub · Imagen ·
27
+ // Avanzado), each with a mark when something needs the person. The wizard is the same
28
+ // dialog walked step by step (Agentes → GitHub → Imagen): one interface, not two.
29
+ //
30
+ // Props: { view: "settings", section? } (the dialog, the default), { view: "wizard", step }
31
+ // (first launch), { view: "credential", agent, provider } or { view: "agy-login", agent }
32
+ // for the dialogs each agent row opens on top.
33
+ import { View, div, svg, image } from "gpui-kit";
29
34
  import { v_flex, h_flex, InputState, Input, TextareaState, Textarea } from "gpui-base";
30
35
  import { props, theme, openOverlay, closeOverlay, notify, shared, setShared, exec, run } from "herdr";
31
- import { api } from "./api.js";
32
- import { UI } from "./brand.js";
36
+ import { api, diagnose, health, resetToken, startCommand, apiUrl } from "./api.js";
37
+ import { UI, stateColor } from "./brand.js";
33
38
  import { buildPiModelsDoc, validateConfigJson, normalizeBaseUrl, parseModelIds, suggestSuggestionModel, suggestDefaultModel, toggleModelLine } from "./pi-models.js";
34
39
 
35
40
  const RELOAD_KEY = "bond.settings.reload";
@@ -37,10 +42,125 @@ const RELOAD_KEY = "bond.settings.reload";
37
42
  /** DOM-safe id fragment for a provider model id (they carry :, / and spaces). */
38
43
  const slug = (s) => String(s).replace(/[^A-Za-z0-9_.-]/g, "_");
39
44
 
45
+ /**
46
+ * Agents whose credential comes from a login driven in a throwaway container (the
47
+ * orchestrator's /settings/<agent>/login/* API) instead of a pasted config.
48
+ */
49
+ const LOGIN_TEXT = {
50
+ agy: {
51
+ button: "Login OAuth…",
52
+ title: "Login OAuth de agy",
53
+ intro: "Login OAuth para agy en un contenedor efímero. Al autenticar, la sesión se guarda en el orquestador (0600) y se inyecta en cada run.",
54
+ starting: "Iniciando contenedor y agy…",
55
+ startingSub: "Generando la URL de autorización de Google…",
56
+ placeholder: "pega aquí el código de autorización",
57
+ step2: "2. Pega el código de autorización:",
58
+ authenticating: "Verificando código y autenticando con agy…",
59
+ success: (email) => `✓ Autenticado con éxito${email ? `: ${email}` : ""}`,
60
+ successSub: "La sesión ha quedado guardada en el orquestador (0600). El contenedor efímero se ha destruido.",
61
+ },
62
+ claude: {
63
+ button: "Login con Claude…",
64
+ title: "Login con Claude",
65
+ intro: "«claude setup-token» en un contenedor efímero: un token de un año que solo sirve para inferencia con tu suscripción. Se guarda en el orquestador (0600) y se inyecta en cada run. Se revoca en claude.ai/settings/claude-code.",
66
+ starting: "Iniciando contenedor y claude…",
67
+ startingSub: "Generando la URL de autorización de Anthropic…",
68
+ placeholder: "pega aquí el código que muestra la página",
69
+ step2: "2. Autoriza y pega el código que te muestra la página:",
70
+ authenticating: "Verificando código y obteniendo el token…",
71
+ success: () => `✓ Token guardado · caduca el ${new Date(Date.now() + 365 * 86400000).toISOString().slice(0, 10)}`,
72
+ successSub: "El token no sale del orquestador ni se muestra aquí. El contenedor efímero se ha destruido. Para revocarlo: claude.ai/settings/claude-code.",
73
+ },
74
+ codex: {
75
+ button: "Login con ChatGPT…",
76
+ title: "Login con ChatGPT (codex)",
77
+ intro: "codex usa tu cuenta de ChatGPT (también las personales, Plus o Pro). El login corre en un contenedor efímero; la sesión se guarda en el orquestador (0600) y llega a cada run por stdin.",
78
+ starting: "Iniciando contenedor y codex…",
79
+ startingSub: "Generando la URL de autorización de OpenAI…",
80
+ placeholder: "http://127.0.0.1:1455/auth/callback?code=…",
81
+ step2: "2. Al autorizar, el navegador acaba en una página que no carga (127.0.0.1:1455). Es lo esperado: copia la dirección completa de la barra y pégala aquí:",
82
+ authenticating: "Entregando la autorización a codex…",
83
+ success: (email) => `✓ Sesión de ChatGPT guardada${email ? `: ${email}` : ""}`,
84
+ successSub: "La sesión no sale del orquestador ni se muestra aquí. El contenedor efímero se ha destruido. Para cerrarla: ChatGPT → Ajustes → Seguridad → cerrar sesión en todos los dispositivos.",
85
+ },
86
+ copilot: {
87
+ button: "Login con Copilot…",
88
+ title: "Login con Copilot",
89
+ intro: "copilot inicia sesión con tu cuenta de GitHub (necesita Copilot). Ojo: su token lleva permiso «repo» y un agente del run puede leerlo. Se guarda en el orquestador (0600) y llega a cada run por stdin.",
90
+ starting: "Iniciando contenedor y copilot…",
91
+ startingSub: "Pidiendo un código de dispositivo a GitHub…",
92
+ placeholder: "",
93
+ step2: "2. Escribe este código en esa página y autoriza:",
94
+ authenticating: "Esperando a que autorices en GitHub…",
95
+ success: (email) => `✓ Sesión de copilot guardada${email ? `: ${email}` : ""}`,
96
+ successSub: "El token no sale del orquestador ni se muestra aquí. El contenedor efímero se ha destruido. Para revocarlo: github.com/settings/applications (GitHub Copilot CLI).",
97
+ },
98
+ };
99
+
100
+ /** « · caduca el AAAA-MM-DD» for credentials with a known expiry (claude's setup-token). */
101
+ const expiryText = (iso) => (iso ? ` · caduca el ${String(iso).slice(0, 10)}` : "");
102
+
103
+ /** The dialog's sections, in order; the wizard walks WIZARD_STEPS of them. */
104
+ export const SECTIONS = [
105
+ { id: "orchestrator", label: "Orquestador" },
106
+ { id: "agents", label: "Agentes" },
107
+ { id: "github", label: "GitHub" },
108
+ { id: "azure", label: "Azure DevOps" },
109
+ { id: "jira", label: "Jira" },
110
+ { id: "image", label: "Imagen" },
111
+ { id: "advanced", label: "Avanzado" },
112
+ ];
113
+ export const WIZARD_STEPS = ["agents", "github", "integrations", "image"];
114
+
115
+ /** Agents whose tickets block without a credential (their login is driven here). */
116
+ const BLOCKING = new Set(["agy", "claude"]);
117
+ const DAY = 86400000;
118
+
119
+ /** Program icon of an agent (herdr's icons), as in the Agentes panel; null → initials. */
120
+ const AGENT_ICONS = { pi: true, antigravity: false, claude: false, codex: false, copilot: true };
121
+ const ICON_ALIASES = { agy: "antigravity" };
122
+ function agentIcon(agent) {
123
+ const name = ICON_ALIASES[agent] ?? agent;
124
+ return Object.prototype.hasOwnProperty.call(AGENT_ICONS, name) ? { icon: `icons/${name}.svg`, tint: AGENT_ICONS[name] } : null;
125
+ }
126
+
127
+ /** Debian package names, as the orchestrator and setup.sh accept them. */
128
+ const APT_RE = /^[a-z0-9][a-z0-9+.-]{1,62}$/;
129
+
130
+ /** Selected agents the image does not carry (the image needs a rebuild to run them). */
131
+ export function missingInImage(setup) {
132
+ const img = setup?.image;
133
+ if (!img?.present || !Array.isArray(img.agents)) return [];
134
+ return (setup.agents_selected ?? []).filter((a) => !img.agents.includes(a));
135
+ }
136
+
137
+ /** «⚠ n» / «⟳» marks of each section from the loaded state; null when nothing is pending. */
138
+ export function sectionMarks({ conn, setup, creds, jira, now = Date.now() }) {
139
+ const marks = {};
140
+ if (conn && conn.state !== "ok") marks.orchestrator = { mark: "⚠", tone: "error" };
141
+ if (setup) {
142
+ const byAgent = new Map((creds ?? []).map((c) => [c.agent, c]));
143
+ const pending = (setup.agents_selected ?? []).filter((a) => {
144
+ const st = (setup.agents ?? []).find((x) => x.agent === a);
145
+ const exp = byAgent.get(a)?.expires_at;
146
+ return !st?.configured || (exp && Date.parse(exp) - now < 30 * DAY);
147
+ }).length + missingInImage(setup).length;
148
+ if (!(setup.agents_selected ?? []).length) marks.agents = { mark: "⚠", tone: "error" };
149
+ else if (pending) marks.agents = { mark: `⚠ ${pending}`, tone: "waiting" };
150
+ if (!setup.github?.configured) marks.github = { mark: "⚠", tone: "error" };
151
+ if (!setup.image?.present) marks.image = { mark: "⚠", tone: "error" };
152
+ else if (setup.image.stale || missingInImage(setup).length) marks.image = { mark: "⟳", tone: "waiting" };
153
+ }
154
+ if (jira?.invalid) {
155
+ marks.jira = { mark: "⚠", tone: "error" };
156
+ }
157
+ return marks;
158
+ }
159
+
40
160
  export default class BondSettings extends View {
41
161
  init(_props, cx) {
42
162
  const p = props() ?? {};
43
- this.view = p.view ?? "panel";
163
+ this.view = p.view ?? "settings";
44
164
  this.busy = false;
45
165
  this.error = null;
46
166
  this.handle = cx.focus_handle();
@@ -116,65 +236,136 @@ export default class BondSettings extends View {
116
236
  else this.piName.focus();
117
237
  return;
118
238
  }
119
- if (this.view === "rebuild") return;
239
+ if (this.view === "agy-login") {
240
+ this.loginAgent = LOGIN_TEXT[p.agent] ? p.agent : "agy";
241
+ this.agyUserCode = null;
242
+ this.agyDevice = false;
243
+ this.agyAuto = false; // codex: the orchestrator catches the browser's return
244
+ this.agyShowPaste = false; // the paste fallback, opened on demand
245
+ this.agyStatus = "starting";
246
+ this.agyUrl = null;
247
+ this.agyEmail = null;
248
+ this.agyError = null;
249
+ this.agyCode = InputState.new({ placeholder: LOGIN_TEXT[this.loginAgent].placeholder });
250
+ this.agyBusy = false;
251
+ this.startAgyLogin(cx);
252
+ cx.timer.every(800, (cx) => {
253
+ if (this.agyStatus === "success" || this.agyStatus === "error") return;
254
+ this.pollAgyStatus(cx);
255
+ });
256
+ return;
257
+ }
120
258
 
121
259
  this.creds = [];
260
+ this.toolSelection = null; // the tool groups while their PUT /setup is in flight
261
+ // Plan bond-app-azure-jira P1: Azure DevOps (Azure Repos). The PAT field never shows the
262
+ // stored one; an empty PAT with a stored credential only changes the switch.
263
+ this.azureDevOps = null;
264
+ this.azureOrg = InputState.new({ placeholder: "https://dev.azure.com/tu-organización" });
265
+ this.azurePat = InputState.new({ placeholder: "PAT con Code: read & write (y Pull requests si tus skills lo usan)" });
266
+ this.azurePat.set_masked(true);
267
+ this.azureAgents = true;
268
+ this.azureBusy = false;
269
+ this.azureOrgLoaded = false;
270
+ this.rbStatus = null; // GET /system/rebuild: { running, step, total, detail, ok, error }
271
+ this.aptInput = InputState.new({ placeholder: "p. ej. graphviz tmux (separados por espacios o comas)" });
272
+ this.aptLoaded = null; // what the field was filled with, so polling never overwrites typing
122
273
  this.loadError = null;
123
274
  this.github = null; // what the orchestrator has stored: { configured, login }
124
275
  this.ghLocal = null; // the host's gh session: { installed, login, ok }
125
276
  this.ghBusy = false;
277
+ this.jira = null;
278
+ this.favorites = null; // ★ repos of the new-ticket dialog (GET /repos/favorites)
279
+ this.favBusy = false;
280
+ this.jiraSite = InputState.new({ placeholder: "https://tu-organizacion.atlassian.net" });
281
+ this.jiraEmail = InputState.new({ placeholder: "tu-email@empresa.com" });
282
+ this.jiraToken = InputState.new({ placeholder: "API token de Jira Cloud (atlassian.com)" });
283
+ this.jiraAgentsEnabled = true;
284
+ this.jiraBusy = false;
285
+ this.jiraError = null;
126
286
  this.setup = null; // W-P2 «Configuración»: el agregado de GET /setup
127
- if (this.view === "wizard") {
128
- // W-P2: the four wizard steps. Every piece of progress lives in the orchestrator
129
- // (selection, credentials, gh), so Esc never loses anything: it reopens from
130
- // Ajustes showing the real state (D-W2).
131
- this.step = Math.min(4, Math.max(1, Number(p.step) || 1));
132
- this.wizSelection = null; // what the user ticked in step 1; null until they touch it
133
- this.rbBusy = false;
134
- this.loadWizard(cx);
135
- cx.timer.every(2000, (cx) => this.loadWizard(cx));
136
- return;
137
- }
287
+ this.conn = null; // «Orquestador»: { state, detail } de diagnose()
288
+ this.connBusy = null; // "reconnect" | "restart" | "start" mientras dura la acción
289
+ this.doctor = null; // GET /doctor: informe de doctor sin secretos
290
+ this.doctorBusy = false;
291
+ this.doctorError = null;
292
+ this.doctorLoaded = false;
293
+ // Every piece of progress lives in the orchestrator (selection, credentials, gh), so
294
+ // Esc never loses anything: the dialog reopens showing the real state (D-W2).
295
+ this.wizSelection = null; // the selection while its PUT /setup is in flight
296
+ this.rbBusy = false;
297
+ // Wizard: steps 1..4 over WIZARD_STEPS; settings: the asked section, else the first
298
+ // one with something pending once the state arrives (null until then).
299
+ this.step = Math.min(WIZARD_STEPS.length, Math.max(1, Number(p.step) || 1));
300
+ this.section = SECTIONS.some((x) => x.id === p.section) ? p.section : null;
138
301
  this.seenReload = shared(RELOAD_KEY) ?? null;
139
302
  this.load(cx);
140
303
  cx.timer.every(1000, (cx) => {
304
+ if (this.rbBusy || this.rbStatus?.running) this.loadRebuildStatus(cx);
141
305
  const marker = shared(RELOAD_KEY) ?? null;
142
306
  if (marker !== this.seenReload) {
143
307
  this.seenReload = marker;
144
308
  this.load(cx);
145
309
  }
146
310
  });
147
- cx.timer.every(15000, (cx) => this.load(cx));
311
+ cx.timer.every(5000, (cx) => this.load(cx));
148
312
  }
149
313
 
314
+ // Re-reads everything the dialog shows (the aggregate, the credential dates, gh), so a
315
+ // credential saved in its own dialog on top shows up here without reopening.
150
316
  load(cx) {
317
+ if (!this.doctorLoaded) {
318
+ this.doctorLoaded = true;
319
+ this.loadDoctor(cx);
320
+ }
151
321
  cx.spawn(async (cx) => {
322
+ if (!this.connBusy) this.conn = await diagnose();
152
323
  try {
153
324
  this.creds = (await api("/settings/credentials")) ?? [];
154
325
  this.github = (await api("/settings/github")) ?? { configured: false };
155
- this.setup = (await api("/setup")) ?? null;
326
+ this.azureDevOps = (await api("/settings/azure-devops")) ?? { configured: false };
327
+ this.jira = (await api("/settings/jira")) ?? { configured: false };
328
+ if (!this.favBusy) this.favorites = (await api("/repos/favorites"))?.favorites ?? [];
329
+ if (this.jira?.configured) {
330
+ if (!this.jiraSite.value()) this.jiraSite.set_value(this.jira.site ?? "");
331
+ if (!this.jiraEmail.value()) this.jiraEmail.set_value(this.jira.email ?? "");
332
+ this.jiraAgentsEnabled = this.jira.agents_enabled !== false;
333
+ }
334
+ if (!this.wizSelection && !this.toolSelection) this.setup = (await api("/setup")) ?? null;
335
+ if (this.setup && this.aptLoaded === null) {
336
+ this.aptLoaded = (this.setup.apt_extra ?? []).join(" ");
337
+ this.aptInput.set_value(this.aptLoaded);
338
+ }
156
339
  this.loadError = null;
157
340
  } catch (e) {
158
341
  this.loadError = String(e?.message ?? e);
159
342
  }
160
343
  this.ghLocal = await this.ghSession();
344
+ try {
345
+ this.rbStatus = (await api("/system/rebuild")) ?? null;
346
+ } catch {}
347
+ if (!this.section) {
348
+ const marks = sectionMarks({ conn: this.conn, setup: this.setup, creds: this.creds });
349
+ this.section = ["orchestrator", "agents", "github", "image"].find((id) => marks[id]) ?? "agents";
350
+ }
161
351
  cx.notify();
162
352
  });
163
353
  }
164
354
 
165
- // W-P2: the wizard re-reads everything it shows (the aggregate, the credential dates,
166
- // gh), so a credential saved in its own dialog shows up here without reopening.
167
- loadWizard(cx) {
355
+ loadDoctor(cx) {
356
+ if (this.doctorBusy) return;
357
+ this.doctorBusy = true;
358
+ this.doctorError = null;
359
+ cx.notify();
168
360
  cx.spawn(async (cx) => {
169
361
  try {
170
- this.setup = (await api("/setup")) ?? null;
171
- this.creds = (await api("/settings/credentials")) ?? [];
172
- this.github = (await api("/settings/github")) ?? { configured: false };
173
- this.loadError = null;
362
+ this.doctor = (await api("/doctor")) ?? null;
363
+ this.doctorError = null;
174
364
  } catch (e) {
175
- this.loadError = String(e?.message ?? e);
365
+ this.doctorError = String(e?.message ?? e);
366
+ } finally {
367
+ this.doctorBusy = false;
176
368
  }
177
- this.ghLocal = await this.ghSession();
178
369
  cx.notify();
179
370
  });
180
371
  }
@@ -232,32 +423,6 @@ export default class BondSettings extends View {
232
423
  run("tab.new", { name: "gh auth login", argv: ["gh", "auth", "login", "--web"] });
233
424
  }
234
425
 
235
- githubSection() {
236
- const t = theme();
237
- const gh = this.github;
238
- const local = this.ghLocal;
239
- const stored = gh?.configured
240
- ? `credencial guardada${gh.login ? ` · ${gh.login}` : ""}`
241
- : "sin credencial: lanzar un run no funcionará";
242
- const localLine = !local
243
- ? "comprobando gh…"
244
- : !local.installed
245
- ? "gh no está instalado en este equipo"
246
- : local.ok
247
- ? `sesión de gh: ${local.login ?? "activa"}`
248
- : "gh no tiene sesión";
249
- return v_flex().gap(4)
250
- .child(div().pt(8).text_size(11).font_semibold().text_color(t.muted).child("GITHUB (D20)"))
251
- .child(div().text_size(11.5).text_color(gh?.configured ? t.working : t.blocked).child(stored))
252
- .child(div().text_size(11).text_color(t.dim).child(localLine))
253
- .child(h_flex().gap(6).flex_wrap()
254
- .when(Boolean(local?.ok), (el) => el.child(this.button("gh-use", this.ghBusy ? "Guardando…" : "Usar mi sesión de gh", true, (cx) => this.useGhSession(cx))))
255
- .when(Boolean(local?.installed) && !local?.ok, (el) => el.child(this.button("gh-login", "Iniciar sesión", true, () => this.ghLogin())))
256
- .when(Boolean(gh?.configured), (el) => el.child(this.button("gh-remove", "Quitar", false, (cx) => this.removeGithub(cx)))))
257
- .child(div().text_size(11).text_color(t.dim)
258
- .child("El token sale de `gh auth token` y lo guarda el orquestador; llega a cada run por stdin, nunca a la imagen."));
259
- }
260
-
261
426
  saveCredential(cx) {
262
427
  if (this.busy) return;
263
428
  const p = props();
@@ -464,25 +629,6 @@ export default class BondSettings extends View {
464
629
  });
465
630
  }
466
631
 
467
- rebuild(cx) {
468
- if (this.busy) return;
469
- const p = props();
470
- this.busy = true;
471
- this.error = null;
472
- cx.notify();
473
- cx.spawn(async (cx) => {
474
- try {
475
- const res = await api("/system/rebuild", { method: "POST", body: {} });
476
- notify({ title: "Imagen reconstruida", body: String(res?.image ?? ""), level: "success" });
477
- closeOverlay(p.overlay);
478
- } catch (e) {
479
- this.error = String(e?.message ?? e);
480
- this.busy = false;
481
- cx.notify();
482
- }
483
- });
484
- }
485
-
486
632
  // ---- W-P2: wizard (D-W1) -----------------------------------------------------------
487
633
 
488
634
  // What the orchestrator is missing; empty when complete. Used by the panel section and
@@ -536,47 +682,22 @@ export default class BondSettings extends View {
536
682
  cx.notify();
537
683
  }
538
684
 
685
+ /** Agentes needs a selection and one credential; GitHub and Imagen can stay pending. */
539
686
  wizNext(cx) {
540
687
  if (this.busy || !this.setup) return;
541
- if (this.step === 1) {
542
- const sel = this.selectedAgents();
543
- if (sel.length === 0) {
544
- this.error = "Elige al menos un agente para continuar.";
688
+ if (WIZARD_STEPS[this.step - 1] === "agents") {
689
+ if (!this.selectedAgents().length) {
690
+ this.error = "Añade al menos un agente para continuar.";
545
691
  cx.notify();
546
692
  return;
547
693
  }
548
- // Criterio 2: la selección ya se guardó con cada clic; si alguno falló,
549
- // se reintenta aquí antes de colar al paso 2.
550
- if (this.wizSelection === null) {
551
- this.step = 2;
552
- this.error = null;
694
+ if (!this.anyCredential()) {
695
+ this.error = "Conecta al menos un agente: sin credencial ningún ticket puede arrancar.";
553
696
  cx.notify();
554
697
  return;
555
698
  }
556
- this.busy = true;
557
- this.error = null;
558
- cx.notify();
559
- cx.spawn(async (cx) => {
560
- try {
561
- this.setup = await api("/setup", { method: "PUT", body: { agents_selected: sel } });
562
- this.wizSelection = null;
563
- this.step = 2;
564
- } catch (e) {
565
- this.error = String(e?.message ?? e);
566
- }
567
- this.busy = false;
568
- cx.notify();
569
- });
570
- return;
571
- }
572
- if (this.step === 2 && !this.anyCredential()) {
573
- // criterion 3: «Finalizar» exige al menos un agente con credencial; no dejar
574
- // colar eso tan tarde.
575
- this.error = "Finalizar exige al menos un agente con credencial: guarda una arriba.";
576
- cx.notify();
577
- return;
578
699
  }
579
- this.step = Math.min(4, this.step + 1);
700
+ this.step = Math.min(WIZARD_STEPS.length, this.step + 1);
580
701
  this.error = null;
581
702
  cx.notify();
582
703
  }
@@ -593,10 +714,9 @@ export default class BondSettings extends View {
593
714
  cx.notify();
594
715
  cx.spawn(async (cx) => {
595
716
  try {
596
- // criterion 5: setup_done only via this explicit write (W-P1); the wizard never
597
- // bothers again, Ajustes keeps showing and editing the state.
717
+ // setup_done only via this explicit write (W-P1); the wizard never bothers again.
598
718
  this.setup = await api("/setup", { method: "PUT", body: { setup_done: true } });
599
- notify({ title: "Configuración guardada", body: "Ajustes siempre muestra y edita el estado.", level: "success" });
719
+ notify({ title: "Configuración guardada", body: "Puedes cambiarla cuando quieras en Ajustes.", level: "success" });
600
720
  setShared(RELOAD_KEY, Date.now());
601
721
  closeOverlay(props().overlay);
602
722
  } catch (e) {
@@ -607,23 +727,18 @@ export default class BondSettings extends View {
607
727
  });
608
728
  }
609
729
 
610
- // Step 4 rebuild (image plan P2): carries the agents chosen in step 1 so the image is
611
- // built with runner/setup.sh installing exactly those; it keeps the wizard open to
612
- // finish after.
613
- wizRebuild(cx) {
730
+ /** Rebuilds the runner image with the chosen agents (the orchestrator falls back to the
731
+ * same selection when the list is empty). Credentials are never touched. */
732
+ rebuildImage(cx) {
614
733
  if (this.rbBusy) return;
615
734
  const agents = this.selectedAgents();
616
- if (!agents.length) {
617
- this.error = "Elige al menos un agente en el paso 1 antes de reconstruir.";
618
- cx.notify();
619
- return;
620
- }
621
735
  this.rbBusy = true;
736
+ this.rbStatus = { running: true, step: 0, total: 0, detail: "Preparando el build…", started_at: new Date().toISOString() };
622
737
  this.error = null;
623
738
  cx.notify();
624
739
  cx.spawn(async (cx) => {
625
740
  try {
626
- const res = await api("/system/rebuild", { method: "POST", body: { agents } });
741
+ const res = await api("/system/rebuild", { method: "POST", body: agents.length ? { agents } : {} });
627
742
  notify({ title: "Imagen reconstruida", body: String(res?.image ?? ""), level: "success" });
628
743
  } catch (e) {
629
744
  this.error = String(e?.message ?? e);
@@ -631,14 +746,700 @@ export default class BondSettings extends View {
631
746
  this.rbBusy = false;
632
747
  try {
633
748
  this.setup = (await api("/setup")) ?? this.setup;
749
+ this.rbStatus = (await api("/system/rebuild")) ?? this.rbStatus;
750
+ } catch {}
751
+ cx.notify();
752
+ });
753
+ }
754
+
755
+ /** Where the image build is (GET /system/rebuild): step, total and what it is doing. */
756
+ loadRebuildStatus(cx) {
757
+ cx.spawn(async (cx) => {
758
+ try {
759
+ this.rbStatus = (await api("/system/rebuild")) ?? null;
760
+ cx.notify();
634
761
  } catch {}
762
+ });
763
+ }
764
+
765
+ /** The progress bar of a build in flight: «Paso 12 de 27 · instalando…». */
766
+ rebuildProgress() {
767
+ const t = theme();
768
+ const st = this.rbStatus ?? {};
769
+ const pct = st.total ? Math.max(2, Math.min(100, Math.round((st.step / st.total) * 100))) : 2;
770
+ const since = st.started_at ? Math.max(0, Math.round((Date.now() - Date.parse(st.started_at)) / 1000)) : 0;
771
+ const clock = `${Math.floor(since / 60)}:${String(since % 60).padStart(2, "0")}`;
772
+ return v_flex().id("image-progress").gap(6).p(10).rounded(UI.radius).border_1().border_color(t.border).bg(t.background)
773
+ .child(h_flex().gap(8).items_center()
774
+ .child(div().flex_1().text_size(UI.text.small).font_semibold().text_color(t.foreground)
775
+ .child(st.total ? `Paso ${st.step} de ${st.total}` : "Empezando…"))
776
+ .child(div().text_size(UI.text.small).text_color(t.dim).child(clock)))
777
+ .child(div().w_full().h(6).rounded(3).bg(t.raised).overflow_hidden()
778
+ .child(div().h_full().rounded(3).bg(t.accent).w(`${pct}%`)))
779
+ .child(div().id("image-progress-detail").text_size(UI.text.small).text_color(t.muted).truncate().child(st.detail || "…"));
780
+ }
781
+
782
+ /** Opens the credential or login dialog of an agent on top of this one. */
783
+ openCredential(agent) {
784
+ const c = (this.creds ?? []).find((x) => x.agent === agent);
785
+ openOverlay({
786
+ mod: "bond-settings", kind: "dialog", modal: true, width: 480, height: 0.92,
787
+ props: LOGIN_TEXT[agent] ? { view: "agy-login", agent } : { view: "credential", agent, provider: c?.provider ?? "" },
788
+ });
789
+ }
790
+
791
+ // ---- Plan bond-app-ajustes-imagen P1: the dialog ------------------------------------
792
+
793
+ tone(t, name) {
794
+ if (name === "ok") return stateColor(t, "running");
795
+ if (name === "waiting") return stateColor(t, "waiting");
796
+ if (name === "error") return t.blocked;
797
+ return t.dim;
798
+ }
799
+
800
+ /** A small «● text» status line. */
801
+ status(id, text, color) {
802
+ return h_flex().id(id).gap(6).items_center()
803
+ .child(div().w(7).h(7).rounded(4).bg(color))
804
+ .child(div().text_size(UI.text.body).font_semibold().text_color(color).child(text));
805
+ }
806
+
807
+ sectionTitle(title, subtitle) {
808
+ const t = theme();
809
+ return v_flex().gap(2)
810
+ .child(div().text_size(UI.text.title + 3).font_family(UI.fontSans).font_semibold().text_color(t.foreground).child(title))
811
+ .when(Boolean(subtitle), (el) => el.child(div().text_size(UI.text.small).font_family(UI.fontSans).text_color(t.muted).child(subtitle)));
812
+ }
813
+
814
+ note(text) {
815
+ return div().text_size(UI.text.small).font_family(UI.fontSans).text_color(theme().dim).child(text);
816
+ }
817
+
818
+ tipButton(id, text, primary, tip, action) {
819
+ return this.button(id, text, primary, action).tooltip(tip);
820
+ }
821
+
822
+ agentBadge(agent, size = 22) {
823
+ const t = theme();
824
+ const pic = agentIcon(agent);
825
+ const box = div().w(size).h(size).flex_none().rounded(6).bg(t.raised).border_1().border_color(t.border)
826
+ .flex().items_center().justify_center();
827
+ if (!pic) return box.child(div().text_size(UI.text.tiny).font_semibold().text_color(t.muted).child(agent.slice(0, 2)));
828
+ const s = Math.round(size * 0.62);
829
+ return box.child(pic.tint ? svg(pic.icon).size(s).text_color(t.foreground) : image(pic.icon).w(s).h(s));
830
+ }
831
+
832
+ orchestratorSection() {
833
+ const t = theme();
834
+ const c = this.conn;
835
+ const labels = { ok: "Conectado", down: "No responde", "no-token": "Sin fichero de token", "bad-token": "El token no es de este orquestador", error: "Error al hablar con la API" };
836
+ const busy = { reconnect: "Reconectando…", restart: "Reiniciando…", start: "Arrancando…" }[this.connBusy];
837
+ const text = busy ?? (!c ? "Comprobando…" : labels[c.state] ?? c.state);
838
+ const color = busy || !c ? t.dim : this.tone(t, c.state === "ok" ? "ok" : "error");
839
+ const canRestart = c?.state === "ok" || c?.state === "error";
840
+ const needsStart = c?.state === "down" || c?.state === "no-token";
841
+ return v_flex().gap(12)
842
+ .child(this.sectionTitle("Orquestador", "El proceso local que lanza los runs y guarda credenciales."))
843
+ .child(v_flex().gap(4)
844
+ .child(this.status("conn-status", text, color))
845
+ .child(div().text_size(UI.text.small).text_color(t.muted).child(apiUrl())))
846
+ .when(Boolean(c?.detail) && c?.state !== "ok" && !busy, (el) => el.child(this.note(c.detail)))
847
+ .when(c?.state === "bad-token", (el) => el.child(this.note("Reinstala apuntando a su token: npm run app:install -- --token-file <data-dir>/token")))
848
+ .child(h_flex().gap(6)
849
+ .when(needsStart, (el) => el.child(this.button("conn-start", "Arrancar", true, (cx) => this.startOrchestrator(cx))))
850
+ .child(this.tipButton("conn-reconnect", "Reconectar", false, "Vuelve a leer el token y comprueba la conexión", (cx) => this.reconnect(cx)))
851
+ .when(canRestart, (el) => el.child(this.tipButton("conn-restart", "Reiniciar", false,
852
+ "Para y arranca el orquestador con el mismo comando. Los runs con contenedor vivo siguen y se reconcilian al volver.",
853
+ (cx) => this.restartOrchestrator(cx)))));
854
+ }
855
+
856
+ /** One row of the Agentes section: icon, name, credential state and one action. */
857
+ agentRow(name) {
858
+ const t = theme();
859
+ const s = this.setup;
860
+ const configured = Boolean((s?.agents ?? []).find((a) => a.agent === name)?.configured);
861
+ const c = (this.creds ?? []).find((x) => x.agent === name);
862
+ const exp = c?.expires_at ? Date.parse(c.expires_at) : null;
863
+ const expired = exp !== null && exp < Date.now();
864
+ const soon = exp !== null && !expired && exp - Date.now() < 30 * DAY;
865
+ const inImage = !missingInImage(s).includes(name);
866
+ let text;
867
+ let color;
868
+ if (!configured) {
869
+ text = BLOCKING.has(name) ? "sin credencial · sus tickets se bloquean" : "sin credencial";
870
+ color = this.tone(t, BLOCKING.has(name) ? "error" : "waiting");
871
+ } else if (expired) {
872
+ text = `caducó el ${String(c.expires_at).slice(0, 10)}`;
873
+ color = this.tone(t, "error");
874
+ } else {
875
+ text = (c?.email || c?.provider || "credencial guardada") + expiryText(c?.expires_at);
876
+ color = soon ? this.tone(t, "waiting") : t.muted;
877
+ }
878
+ const action = name === "pi" ? (configured ? "Configurar" : "Conectar") : (configured ? "Renovar" : "Conectar");
879
+ return h_flex().id(`agent-row-${name}`).gap(10).items_center().px(10).py(8).rounded(UI.radius)
880
+ .border_1().border_color(t.border).bg(t.background)
881
+ .child(this.agentBadge(name))
882
+ .child(v_flex().flex_1().min_w(0).gap(1)
883
+ .child(div().text_size(UI.text.body).font_semibold().text_color(t.foreground).child(name))
884
+ .child(div().text_size(UI.text.small).text_color(color).truncate().child(text))
885
+ .when(!inImage, (el) => el.child(div().id(`agent-noimage-${name}`).text_size(UI.text.small).text_color(this.tone(t, "waiting"))
886
+ .cursor_pointer().on_click((_e, cx) => { this.goTo(cx, "image"); })
887
+ .child("⟳ no está en la imagen: reconstrúyela en Imagen"))))
888
+ .child(this.button(`agent-cred-${name}`, action, !configured || expired, () => this.openCredential(name))
889
+ .tooltip(name === "pi"
890
+ ? "Abre el formulario «modelo local / OpenAI-compatible» (nombre, URL, clave opcional); los modelos se cargan del provider."
891
+ : LOGIN_TEXT[name] ? `${LOGIN_TEXT[name].title} en un contenedor efímero` : "Pega la config del agente tras iniciar sesión"))
892
+ .child(div().id(`agent-remove-${name}`).w(22).h(22).rounded(UI.radius).flex().items_center().justify_center()
893
+ .text_color(t.dim).cursor_pointer().hover((st) => st.bg(t.hover).text_color(t.foreground))
894
+ .tooltip("Quitar de tus agentes (la credencial se conserva)")
895
+ .on_click((_e, cx) => this.toggleAgent(cx, name)).child("✕"));
896
+ }
897
+
898
+ agentsSection() {
899
+ const t = theme();
900
+ const s = this.setup;
901
+ if (!s) return v_flex().gap(12).child(this.sectionTitle("Agentes")).child(this.note("Cargando…"));
902
+ const sel = this.selectedAgents();
903
+ const others = (s.agents ?? []).map((a) => a.agent).filter((a) => !sel.includes(a));
904
+ return v_flex().gap(12)
905
+ .child(this.sectionTitle("Agentes", "Los agentes que pueden trabajar en tus tickets."))
906
+ .when(sel.length === 0, (el) => el.child(this.note("Aún no has elegido ninguno: añade al menos uno.")))
907
+ .child(v_flex().gap(6).children(sel.map((name) => this.agentRow(name))))
908
+ .when(others.length > 0, (el) => el.child(v_flex().gap(6)
909
+ .child(div().text_size(UI.text.small).font_semibold().text_color(t.muted).child("Añadir agente"))
910
+ .child(h_flex().gap(6).flex_wrap().children(others.map((name) =>
911
+ h_flex().id(`agent-add-${name}`).gap(6).items_center().h(UI.button).pl(4).pr(10).rounded(UI.radius)
912
+ .border_1().border_color(t.border).bg(t.raised).cursor_pointer()
913
+ .hover((st) => st.bg(t.hover))
914
+ .on_click((_e, cx) => this.toggleAgent(cx, name))
915
+ .child(this.agentBadge(name, 18))
916
+ .child(div().text_size(UI.text.small).text_color(t.foreground).child(`+ ${name}`)))))))
917
+ .child(this.note("Las credenciales se guardan en el orquestador y llegan a cada run por stdin; nunca van en la imagen."));
918
+ }
919
+
920
+ githubSection() {
921
+ const t = theme();
922
+ const gh = this.github;
923
+ const local = this.ghLocal;
924
+ const stored = Boolean(gh?.configured);
925
+ const localLine = !local
926
+ ? "Comprobando gh en este equipo…"
927
+ : !local.installed
928
+ ? "gh no está instalado en este equipo."
929
+ : local.ok
930
+ ? `gh en este equipo: sesión de ${local.login ?? "GitHub"}.`
931
+ : "gh en este equipo no tiene sesión.";
932
+ const canUse = Boolean(local?.ok) && (!stored || (local.login && local.login !== gh?.login));
933
+ return v_flex().gap(12)
934
+ .child(this.sectionTitle("GitHub", "Para clonar los repos de los tickets, crear ramas y abrir PR."))
935
+ .child(v_flex().gap(4)
936
+ .child(this.status("gh-status", stored ? `Conectado${gh.login ? ` como ${gh.login}` : ""}` : "Sin conectar",
937
+ this.tone(t, stored ? "ok" : "error")))
938
+ .when(!stored, (el) => el.child(this.note("Sin GitHub no se pueden lanzar tickets.")))
939
+ .child(this.note(localLine)))
940
+ .child(h_flex().gap(6).flex_wrap()
941
+ .when(canUse, (el) => el.child(this.tipButton("gh-use", this.ghBusy ? "Guardando…" : `Usar la sesión de gh${local?.login ? ` (${local.login})` : ""}`, true,
942
+ "Lee `gh auth token` y lo guarda el orquestador; llega a cada run por stdin, nunca a la imagen.", (cx) => this.useGhSession(cx))))
943
+ .when(Boolean(local?.installed) && !local?.ok, (el) => el.child(this.button("gh-login", "Iniciar sesión en gh", !stored, () => this.ghLogin())))
944
+ .when(stored, (el) => el.child(this.button("gh-remove", "Quitar", false, (cx) => this.removeGithub(cx)))));
945
+ }
946
+
947
+ // ---- Plan bond-app-azure-jira P1: Azure DevOps -----------------------------------------
948
+
949
+ saveAzure(cx) {
950
+ if (this.azureBusy) return;
951
+ const stored = Boolean(this.azureDevOps?.configured);
952
+ const org = String(this.azureOrg.value() ?? "").trim();
953
+ const pat = String(this.azurePat.value() ?? "").trim();
954
+ let body;
955
+ if (pat) body = { org_url: org, pat, agents_enabled: this.azureAgents };
956
+ else if (stored) body = { agents_enabled: this.azureAgents };
957
+ else {
958
+ this.error = "Escribe la URL de la organización y el PAT.";
959
+ cx.notify();
960
+ return;
961
+ }
962
+ this.azureBusy = true;
963
+ this.error = null;
964
+ cx.notify();
965
+ cx.spawn(async (cx) => {
966
+ try {
967
+ this.azureDevOps = await api("/settings/azure-devops", { method: "PUT", body });
968
+ this.azurePat.set_value("");
969
+ notify({ title: "Azure DevOps guardado", body: this.azureDevOps?.account ?? "", level: "success" });
970
+ } catch (e) {
971
+ this.error = `Azure DevOps: ${String(e?.message ?? e)}`;
972
+ }
973
+ this.azureBusy = false;
974
+ cx.notify();
975
+ });
976
+ }
977
+
978
+ removeAzure(cx) {
979
+ cx.spawn(async (cx) => {
980
+ try {
981
+ this.azureDevOps = await api("/settings/azure-devops", { method: "DELETE" });
982
+ this.azureOrgLoaded = false;
983
+ notify({ title: "Credencial de Azure DevOps quitada", level: "info" });
984
+ } catch (e) {
985
+ this.error = String(e?.message ?? e);
986
+ }
987
+ cx.notify();
988
+ });
989
+ }
990
+
991
+ azureSection() {
992
+ const t = theme();
993
+ const az = this.azureDevOps;
994
+ const stored = Boolean(az?.configured);
995
+ if (stored && !this.azureOrgLoaded) {
996
+ this.azureOrgLoaded = true;
997
+ this.azureOrg.set_value(az.org_url ?? "");
998
+ this.azureAgents = az.agents_enabled !== false;
999
+ }
1000
+ const label = (text) => div().pt(2).text_size(UI.text.small).font_semibold().text_color(t.muted).child(text);
1001
+ const input = (state) => Input.new(state).h(UI.button + 4).px(10).rounded(UI.radius).border_1().border_color(t.input).bg(t.background).text_size(12);
1002
+ return v_flex().gap(12)
1003
+ .child(this.sectionTitle("Azure DevOps", "Para tickets sobre repos de Azure Repos: clonar, crear ramas y abrir PR."))
1004
+ .child(this.status("azure-status", stored ? `Conectado${az.account ? ` como ${az.account}` : ""}` : "Sin conectar",
1005
+ stored ? this.tone(t, "ok") : t.dim))
1006
+ .when(stored, (el) => el.child(this.note(`Organización: ${az.org_url}`)))
1007
+ .when(!stored, (el) => el.child(this.note("Opcional: solo hace falta si tus tickets trabajan sobre Azure Repos.")))
1008
+ .child(v_flex().gap(4)
1009
+ .child(label("Organización"))
1010
+ .child(input(this.azureOrg))
1011
+ .child(label(stored ? "PAT (vacío: conserva el guardado)" : "PAT"))
1012
+ .child(input(this.azurePat)))
1013
+ .child(h_flex().id("azure-agents").gap(8).items_center().cursor_pointer()
1014
+ .on_click((_e, cx) => { this.azureAgents = !this.azureAgents; cx.notify(); })
1015
+ .child(this.checkbox(this.azureAgents))
1016
+ .child(div().text_size(UI.text.body).text_color(t.foreground).child("Disponible para los agentes del run")))
1017
+ .when(this.azureAgents, (el) => el.child(this.note("Los agentes reciben AZURE_DEVOPS_ORG_URL, AZURE_DEVOPS_PAT y AZURE_DEVOPS_EXT_PAT (az devops, skills de PR): pueden usar el PAT con todos sus permisos. Dale solo los que necesites.")))
1018
+ .child(h_flex().gap(6)
1019
+ .child(this.button("azure-save", this.azureBusy ? "Comprobando…" : "Guardar", true, (cx) => this.saveAzure(cx)))
1020
+ .when(stored, (el) => el.child(this.button("azure-remove", "Quitar", false, (cx) => this.removeAzure(cx)))))
1021
+ .child(this.note("Se comprueba contra la organización al guardar; el PAT se guarda en el orquestador y llega a cada run por stdin, nunca a la imagen."));
1022
+ }
1023
+
1024
+ jiraSection() {
1025
+ const t = theme();
1026
+ const j = this.jira;
1027
+ const configured = Boolean(j?.configured);
1028
+ const statusText = configured
1029
+ ? `Conectado como ${j.account_name ?? j.email} en ${j.site}`
1030
+ : "Sin conectar";
1031
+ const statusColor = configured ? this.tone(t, "ok") : t.muted;
1032
+
1033
+ return v_flex().gap(12)
1034
+ .child(this.sectionTitle("Jira", "Para enlazar issues como historia del ticket y dar acceso a los agentes."))
1035
+ .child(v_flex().gap(4)
1036
+ .child(this.status("jira-status", statusText, statusColor))
1037
+ .when(!configured, (el) => el.child(this.note("Jira es opcional: configúralo para buscar y enlazar issues de Jira Cloud como historias de tus tickets."))))
1038
+ .child(v_flex().gap(8)
1039
+ .child(v_flex().gap(3)
1040
+ .child(div().text_size(UI.text.small).font_medium().text_color(t.muted).child("Sitio de Jira Cloud"))
1041
+ .child(Input.new(this.jiraSite).h(UI.button + 4).px(10).rounded(UI.radius).border_1().border_color(t.input).bg(t.background).text_size(12)))
1042
+ .child(v_flex().gap(3)
1043
+ .child(div().text_size(UI.text.small).font_medium().text_color(t.muted).child("Email de la cuenta"))
1044
+ .child(Input.new(this.jiraEmail).h(UI.button + 4).px(10).rounded(UI.radius).border_1().border_color(t.input).bg(t.background).text_size(12)))
1045
+ .child(v_flex().gap(3)
1046
+ .child(div().text_size(UI.text.small).font_medium().text_color(t.muted).child("API token de Jira Cloud"))
1047
+ .child(Input.new(this.jiraToken).h(UI.button + 4).px(10).rounded(UI.radius).border_1().border_color(t.input).bg(t.background).text_size(12))
1048
+ .child(div().text_size(UI.text.tiny).text_color(t.dim).child("El token nunca se muestra tras guardarse y viaja a los agentes solo por stdin. Déjalo vacío para conservar el token guardado.")))
1049
+ .child(v_flex().gap(2)
1050
+ .child(h_flex().id("jira-agents-enabled").gap(7).items_center().px(2).py(3).cursor_pointer()
1051
+ .text_color(t.foreground).font_family(UI.fontSans).text_size(UI.text.small)
1052
+ .on_click((_e, cx) => {
1053
+ this.jiraAgentsEnabled = !this.jiraAgentsEnabled;
1054
+ cx.notify();
1055
+ })
1056
+ .child(div().w(13).h(13).rounded(3).border_1()
1057
+ .border_color(this.jiraAgentsEnabled ? t.accent : t.border)
1058
+ .bg(this.jiraAgentsEnabled ? t.accent : t.input)
1059
+ .child(div().text_size(10).text_center().text_color(t.chrome).child(this.jiraAgentsEnabled ? "✓" : "")))
1060
+ .child("Disponible para los agentes"))
1061
+ .when(this.jiraAgentsEnabled, (el) => el.child(div().pl(22).text_size(UI.text.tiny).font_family(UI.fontSans).text_color(t.dim)
1062
+ .child("Aviso de riesgo: con «Disponible para los agentes» activado, cualquier agente del run puede usar el API token con todos sus permisos (JIRA_URL, JIRA_USERNAME, JIRA_API_TOKEN por stdin).")))))
1063
+ .when(Boolean(this.jiraError), (el) => el.child(div().id("jira-error").text_size(UI.text.small).text_color(t.blocked).child(this.jiraError)))
1064
+ .child(h_flex().gap(6).flex_wrap()
1065
+ .child(this.button("jira-save", this.jiraBusy ? "Guardando…" : "Guardar", true, (cx) => this.saveJira(cx)))
1066
+ .when(configured, (el) => el.child(this.button("jira-remove", "Quitar", false, (cx) => this.removeJira(cx)))));
1067
+ }
1068
+
1069
+ saveJira(cx) {
1070
+ const site = this.jiraSite.value().trim();
1071
+ const email = this.jiraEmail.value().trim();
1072
+ const token = this.jiraToken.value().trim();
1073
+ if (!site) {
1074
+ this.jiraError = "Introduce la URL de tu sitio de Jira Cloud (https://<algo>.atlassian.net)";
1075
+ cx.notify();
1076
+ return;
1077
+ }
1078
+ if (!email) {
1079
+ this.jiraError = "Introduce el email de tu cuenta";
1080
+ cx.notify();
1081
+ return;
1082
+ }
1083
+ if (!token && !this.jira?.configured) {
1084
+ this.jiraError = "Introduce el API token de Jira";
1085
+ cx.notify();
1086
+ return;
1087
+ }
1088
+ this.jiraBusy = true;
1089
+ this.jiraError = null;
1090
+ cx.notify();
1091
+ cx.spawn(async (cx) => {
1092
+ try {
1093
+ const body = {
1094
+ site,
1095
+ email,
1096
+ token,
1097
+ agents_enabled: this.jiraAgentsEnabled,
1098
+ };
1099
+ const summary = await api("/settings/jira", { method: "PUT", body });
1100
+ this.jira = summary;
1101
+ this.jiraToken.set_value("");
1102
+ this.jiraError = null;
1103
+ } catch (e) {
1104
+ this.jiraError = String(e?.message ?? e);
1105
+ if (this.jira) this.jira.invalid = true;
1106
+ } finally {
1107
+ this.jiraBusy = false;
1108
+ cx.notify();
1109
+ }
1110
+ });
1111
+ }
1112
+
1113
+ removeJira(cx) {
1114
+ this.jiraBusy = true;
1115
+ this.jiraError = null;
1116
+ cx.notify();
1117
+ cx.spawn(async (cx) => {
1118
+ try {
1119
+ const summary = await api("/settings/jira", { method: "DELETE" });
1120
+ this.jira = summary;
1121
+ this.jiraToken.set_value("");
1122
+ this.jiraError = null;
1123
+ } catch (e) {
1124
+ this.jiraError = String(e?.message ?? e);
1125
+ } finally {
1126
+ this.jiraBusy = false;
1127
+ cx.notify();
1128
+ }
1129
+ });
1130
+ }
1131
+
1132
+ /** Tool groups as the person has them now (the pending PUT wins over the loaded state). */
1133
+ selectedTools() {
1134
+ return this.toolSelection ?? (this.setup?.tools_selected ?? []);
1135
+ }
1136
+
1137
+ /** Ticks a tool group on or off; each click is saved (PUT /setup), like the agents. */
1138
+ toggleTool(cx, id) {
1139
+ const catalog = (this.setup?.catalog ?? []).map((g) => g.id);
1140
+ const cur = new Set(this.selectedTools());
1141
+ if (cur.has(id)) cur.delete(id);
1142
+ else cur.add(id);
1143
+ const sel = catalog.filter((g) => cur.has(g));
1144
+ this.toolSelection = sel;
1145
+ this.error = null;
1146
+ cx.notify();
1147
+ cx.spawn(async (cx) => {
1148
+ try {
1149
+ this.setup = await api("/setup", { method: "PUT", body: { tools_selected: sel } });
1150
+ } catch (e) {
1151
+ this.error = String(e?.message ?? e);
1152
+ }
1153
+ this.toolSelection = null;
1154
+ cx.notify();
1155
+ });
1156
+ }
1157
+
1158
+ /** Saves the extra Debian packages typed in the field (comma or space separated). */
1159
+ saveAptExtra(cx) {
1160
+ const pkgs = [...new Set(String(this.aptInput.value() ?? "").split(/[\s,]+/).map((x) => x.trim()).filter(Boolean))];
1161
+ const bad = pkgs.filter((x) => !APT_RE.test(x));
1162
+ if (bad.length) {
1163
+ this.error = `Nombre de paquete no válido: ${bad.join(", ")}`;
1164
+ cx.notify();
1165
+ return;
1166
+ }
1167
+ this.error = null;
1168
+ cx.spawn(async (cx) => {
1169
+ try {
1170
+ this.setup = await api("/setup", { method: "PUT", body: { apt_extra: pkgs } });
1171
+ this.aptLoaded = (this.setup?.apt_extra ?? []).join(" ");
1172
+ this.aptInput.set_value(this.aptLoaded);
1173
+ notify({ title: "Paquetes guardados", body: pkgs.length ? pkgs.join(", ") : "ninguno", level: "success" });
1174
+ } catch (e) {
1175
+ this.error = String(e?.message ?? e);
1176
+ }
1177
+ cx.notify();
1178
+ });
1179
+ }
1180
+
1181
+ checkbox(on) {
1182
+ const t = theme();
1183
+ return div().w(16).h(16).flex_none().rounded(4).border_1().border_color(on ? t.accent : t.border)
1184
+ .bg(on ? t.accent : t.background).flex().items_center().justify_center()
1185
+ .text_size(11).font_semibold().text_color(t.accent_foreground ?? t.background).child(on ? "✓" : "");
1186
+ }
1187
+
1188
+ /** One tool group: checkbox, name, contents, rough size and how it stands in the image. */
1189
+ toolRow(g, img) {
1190
+ const t = theme();
1191
+ const on = this.selectedTools().includes(g.id);
1192
+ const inImage = (img.tools ?? []).includes(g.id);
1193
+ const state = !img.present ? null
1194
+ : on && !inImage ? { text: "falta", tone: "waiting" }
1195
+ : !on && inImage ? { text: "sobra", tone: "waiting" }
1196
+ : inImage ? { text: "en la imagen", tone: "ok" } : null;
1197
+ return h_flex().id(`tool-${g.id}`).gap(10).items_start().px(10).py(7).rounded(UI.radius).cursor_pointer()
1198
+ .border_1().border_color(on ? t.accent : t.border).bg(t.background)
1199
+ .hover((st) => st.bg(t.hover))
1200
+ .on_click((_e, cx) => this.toggleTool(cx, g.id))
1201
+ .child(div().pt(1).child(this.checkbox(on)))
1202
+ .child(v_flex().flex_1().min_w(0).gap(1)
1203
+ .child(h_flex().gap(8).items_center()
1204
+ .child(div().text_size(UI.text.body).font_semibold().text_color(t.foreground).child(g.label))
1205
+ .when(Boolean(state), (el) => el.child(div().id(`tool-state-${g.id}`).text_size(UI.text.tiny).text_color(this.tone(t, state.tone)).child(state.text))))
1206
+ .child(div().text_size(UI.text.small).font_family(UI.fontSans).text_color(t.muted).child(g.description)))
1207
+ .child(div().flex_none().text_size(UI.text.small).text_color(t.dim).child(`~${g.size_mb >= 1000 ? `${(g.size_mb / 1000).toFixed(1)} GB` : `${g.size_mb} MB`}`));
1208
+ }
1209
+
1210
+ imageSection() {
1211
+ const t = theme();
1212
+ const s = this.setup;
1213
+ const img = s?.image ?? {};
1214
+ const missing = missingInImage(s);
1215
+ const extra = (img.agents ?? []).filter((a) => !this.selectedAgents().includes(a));
1216
+ const stale = Boolean(img.stale) || missing.length > 0;
1217
+ const needs = !img.present || stale;
1218
+ const catalog = s?.catalog ?? [];
1219
+ const base = catalog.filter((g) => g.default);
1220
+ const sdks = catalog.filter((g) => !g.default);
1221
+ const total = catalog.filter((g) => this.selectedTools().includes(g.id)).reduce((n, g) => n + g.size_mb, 0);
1222
+ const changes = [];
1223
+ if (missing.length) changes.push(`añadir ${missing.join(", ")}`);
1224
+ if (img.missing_tools?.length) changes.push(`instalar ${img.missing_tools.join(", ")}`);
1225
+ if (img.extra_tools?.length) changes.push(`quitar ${img.extra_tools.join(", ")}`);
1226
+ if (img.apt_changed) changes.push("paquetes apt");
1227
+ if (img.recipe_changed) changes.push("receta de la imagen actualizada en bond-app (setup.sh, versiones…)");
1228
+ const label = (text) => div().pt(4).text_size(UI.text.small).font_semibold().text_color(t.muted).child(text);
1229
+ const building = this.rbBusy || Boolean(this.rbStatus?.running);
1230
+ return v_flex().gap(12)
1231
+ .child(this.sectionTitle("Imagen del runner", "La imagen Docker en la que corre cada run: agentes y herramientas."))
1232
+ .child(v_flex().gap(6)
1233
+ .child(this.status("image-status", !s ? "Comprobando…" : !img.present ? "No hay imagen" : stale ? "Desfasada" : "Al día",
1234
+ !s ? t.dim : this.tone(t, !img.present ? "error" : stale ? "waiting" : "ok")))
1235
+ .when(Boolean(img.present && img.agents?.length), (el) => el.child(h_flex().gap(6).flex_wrap().items_center()
1236
+ .child(div().text_size(UI.text.small).text_color(t.muted).child("Agentes:"))
1237
+ .children(img.agents.map((a) => h_flex().id(`image-agent-${a}`).gap(4).items_center()
1238
+ .child(this.agentBadge(a, 18)).child(div().text_size(UI.text.small).text_color(t.foreground).child(a))))))
1239
+ .when(changes.length > 0, (el) => el.child(div().id("image-stale").text_size(UI.text.small).text_color(this.tone(t, "waiting"))
1240
+ .child(`⟳ Cambios sin aplicar: ${changes.join(" · ")}. Reconstruye para aplicarlos.`)))
1241
+ .when(extra.length > 0, (el) => el.child(this.note(`También lleva ${extra.join(", ")}, que no tienes elegidos.`))))
1242
+ .when(catalog.length > 0, (el) => el
1243
+ .child(label("Herramientas"))
1244
+ .child(v_flex().gap(6).children(base.map((g) => this.toolRow(g, img))))
1245
+ .child(label("SDK y extras (opcionales: si tus repos traen devcontainer, no hacen falta)"))
1246
+ .child(v_flex().gap(6).children(sdks.map((g) => this.toolRow(g, img))))
1247
+ .child(label("Paquetes de Debian adicionales"))
1248
+ .child(h_flex().gap(6).items_center()
1249
+ .child(div().flex_1().child(Input.new(this.aptInput).h(UI.button + 4).px(10).rounded(UI.radius).border_1().border_color(t.input).bg(t.background).text_size(12)))
1250
+ .child(this.button("apt-save", "Guardar", false, (cx) => this.saveAptExtra(cx))))
1251
+ .child(this.note(`Herramientas elegidas: ~${(total / 1000).toFixed(1)} GB sobre la imagen base.`)))
1252
+ .when(building, (el) => el.child(this.rebuildProgress()))
1253
+ .when(!building && this.rbStatus?.ok === false, (el) => el.child(div().id("image-build-error").text_size(UI.text.small).text_color(t.blocked)
1254
+ .child(`El último build falló${this.rbStatus.error ? `: ${String(this.rbStatus.error).slice(0, 160)}` : ""}. El detalle está en el log del orquestador.`)))
1255
+ .child(h_flex().gap(6).items_center()
1256
+ .child(this.button("image-rebuild", building ? "Reconstruyendo…" : (img.present ? "Reconstruir" : "Construir"), needs && !building, (cx) => { if (!building) this.rebuildImage(cx); }))
1257
+ .when(building, (el) => el.child(this.note("Puede tardar varios minutos; puedes cerrar Ajustes, el build sigue."))))
1258
+ .child(this.note("Reconstruir trae las versiones fijadas de bond, hc, los agentes y las herramientas. No toca las credenciales."));
1259
+ }
1260
+
1261
+ integrationsWizardSection() {
1262
+ return v_flex().id("wiz-integrations").gap(18)
1263
+ .child(this.note("Paso opcional: configura Azure DevOps y/o Jira si tus tickets trabajan con ellos, o pulsa Saltar / Siguiente para hacerlo más tarde en Ajustes."))
1264
+ .child(this.azureSection())
1265
+ .child(div().h(1).bg(theme().border))
1266
+ .child(this.jiraSection());
1267
+ }
1268
+
1269
+ advancedSection() {
1270
+ const t = theme();
1271
+ const s = this.setup;
1272
+ const row = (label, value) => h_flex().gap(10).items_start()
1273
+ .child(div().w(150).flex_none().text_size(UI.text.small).text_color(t.muted).child(label))
1274
+ .child(div().flex_1().min_w(0).text_size(UI.text.small).text_color(t.foreground).child(value));
1275
+ return v_flex().gap(12)
1276
+ .child(this.sectionTitle("Avanzado"))
1277
+ .child(v_flex().gap(8)
1278
+ .child(row("API", apiUrl()))
1279
+ .child(row("Asistente", s ? (s.setup_done ? "terminado" : "sin terminar") : "—"))
1280
+ .child(row("Credenciales", "En el orquestador, 0600; llegan a cada run por stdin.")))
1281
+ .child(this.doctorBlock())
1282
+ .child(this.favoritesBlock())
1283
+ .child(h_flex().child(this.button("wiz-reopen", "Abrir el asistente", false, (cx) => {
1284
+ this.view = "wizard";
1285
+ this.step = 1;
1286
+ this.error = null;
1287
+ cx.notify();
1288
+ })));
1289
+ }
1290
+
1291
+ doctorBlock() {
1292
+ const t = theme();
1293
+ const d = this.doctor;
1294
+ const iconFor = (status) => (status === "ok" ? "✓" : status === "warn" ? "!" : "✗");
1295
+ const toneFor = (status) => (status === "ok" ? "ok" : status === "warn" ? "waiting" : "error");
1296
+ const summaryText = d?.summary
1297
+ ? `${d.platform ?? ""} · ${d.summary.ok ?? 0} bien · ${d.summary.warn ?? 0} avisos · ${d.summary.fail ?? 0} fallos`
1298
+ : null;
1299
+ return v_flex().id("doctor-block").gap(8)
1300
+ .child(h_flex().gap(8).items_center()
1301
+ .child(div().flex_1().text_size(UI.text.body).font_semibold().text_color(t.foreground).child("Estado de la instalación"))
1302
+ .child(this.button("doctor-refresh", this.doctorBusy ? "Actualizando…" : "Actualizar", false, (cx) => this.loadDoctor(cx))))
1303
+ .when(Boolean(summaryText), (el) => el.child(div().id("doctor-summary").text_size(UI.text.small).text_color(t.muted).child(summaryText)))
1304
+ .when(Boolean(this.doctorError), (el) => el.child(div().id("doctor-error").text_size(UI.text.small).text_color(t.blocked).child(this.doctorError)))
1305
+ .when(!d && !this.doctorError, (el) => el.child(this.note(this.doctorBusy ? "Comprobando…" : "Sin datos de diagnóstico.")))
1306
+ .when(Boolean(d?.checks?.length), (el) => el.child(v_flex().gap(6).children(d.checks.map((c) =>
1307
+ v_flex().id(`doctor-check-${c.id}`).gap(2).p(8).rounded(UI.radius).border_1().border_color(t.border).bg(t.background)
1308
+ .child(h_flex().gap(8).items_center()
1309
+ .child(div().w(14).flex_none().text_size(UI.text.small).font_semibold().text_color(this.tone(t, toneFor(c.status))).child(iconFor(c.status)))
1310
+ .child(div().flex_1().min_w(0).text_size(UI.text.small).font_semibold().text_color(t.foreground).child(c.name))
1311
+ .child(div().flex_none().text_size(UI.text.tiny).text_color(this.tone(t, toneFor(c.status))).child(c.status)))
1312
+ .child(div().pl(22).text_size(UI.text.small).text_color(t.muted).child(c.detail))
1313
+ .when(Boolean(c.fix), (fixEl) => fixEl.child(div().id(`doctor-fix-${c.id}`).pl(22).text_size(UI.text.tiny).text_color(t.dim).child(`Solución: ${c.fix}`)))))));
1314
+ }
1315
+
1316
+ /** The ★ repos of the new-ticket dialog («Dónde»): listed here to remove them. */
1317
+ favoritesBlock() {
1318
+ const t = theme();
1319
+ const favs = this.favorites ?? [];
1320
+ const label = (url) => {
1321
+ const az = /dev\.azure\.com\/([^/]+)\/([^/]+)\/_git\/([^/]+)/.exec(url);
1322
+ if (az) return `${az[1]}/${decodeURIComponent(az[2])}/${decodeURIComponent(az[3])}`;
1323
+ const gh = /github\.com\/([^/]+)\/([^/]+?)(?:\.git)?$/.exec(url);
1324
+ return gh ? `${gh[1]}/${gh[2]}` : url;
1325
+ };
1326
+ const slug = (url) => url.replace(/[^A-Za-z0-9.-]/g, "_");
1327
+ return v_flex().id("fav-repos").gap(6)
1328
+ .child(div().text_size(UI.text.body).font_semibold().text_color(t.foreground).child("Repos favoritos"))
1329
+ .child(favs.length === 0
1330
+ ? this.note("Sin favoritos. Márcalos con ★ en «Dónde» al crear un ticket.")
1331
+ : v_flex().gap(4).children(favs.map((url) => h_flex().id(`fav-${slug(url)}`).gap(8).items_center()
1332
+ .child(div().flex_1().min_w(0).truncate().text_size(UI.text.small).text_color(t.foreground).child(label(url)))
1333
+ .child(div().id(`fav-del-${slug(url)}`).px(6).rounded(UI.radius).cursor_pointer().text_size(UI.text.small)
1334
+ .text_color(t.muted).hover((st) => st.bg(t.hover)).child("✕")
1335
+ .on_click((_e, cx) => this.removeFavorite(cx, url))))))
1336
+ .when(favs.length > 0, (el) => el.child(this.note("Se marcan y desmarcan con ★ en el alta de ticket.")));
1337
+ }
1338
+
1339
+ removeFavorite(cx, url) {
1340
+ const next = (this.favorites ?? []).filter((u) => u !== url);
1341
+ this.favorites = next;
1342
+ this.favBusy = true;
1343
+ cx.notify();
1344
+ cx.spawn(async (cx) => {
1345
+ try {
1346
+ this.favorites = (await api("/repos/favorites", { method: "PUT", body: { favorites: next } }))?.favorites ?? next;
1347
+ } catch (e) {
1348
+ this.error = `No se pudo quitar el favorito: ${String(e?.message ?? e)}`;
1349
+ }
1350
+ this.favBusy = false;
635
1351
  cx.notify();
636
1352
  });
637
1353
  }
638
1354
 
1355
+ goTo(cx, id) {
1356
+ if (this.view === "wizard") {
1357
+ const i = WIZARD_STEPS.indexOf(id);
1358
+ if (i >= 0) this.step = i + 1;
1359
+ } else {
1360
+ this.section = id;
1361
+ }
1362
+ this.error = null;
1363
+ cx.notify();
1364
+ }
1365
+
1366
+ /** The section shown: the wizard's step, or the chosen one (agents until loaded). */
1367
+ currentSection() {
1368
+ return this.view === "wizard" ? WIZARD_STEPS[this.step - 1] : (this.section ?? "agents");
1369
+ }
1370
+
1371
+ navItem(id, label, active, mark, onClick) {
1372
+ const t = theme();
1373
+ return h_flex().id(`nav-${id}`).h(30).px(10).gap(8).items_center().rounded(UI.radius).cursor_pointer()
1374
+ .bg(active ? t.selected : t.popover)
1375
+ .hover((st) => st.bg(active ? t.selected : t.hover))
1376
+ .on_click((_e, cx) => onClick(cx))
1377
+ .child(div().flex_1().min_w(0).truncate().text_size(UI.text.body).font_family(UI.fontSans)
1378
+ .font_weight(active ? 600 : 400).text_color(active ? t.foreground : t.muted).child(label))
1379
+ .when(Boolean(mark), (el) => el.child(div().id(`nav-mark-${id}`).text_size(UI.text.small).font_semibold()
1380
+ .text_color(this.tone(t, mark.tone)).child(mark.mark)));
1381
+ }
1382
+
1383
+ renderSettings() {
1384
+ const t = theme();
1385
+ const wizard = this.view === "wizard";
1386
+ const current = this.currentSection();
1387
+ const marks = sectionMarks({ conn: this.conn, setup: this.setup, creds: this.creds, jira: this.jira });
1388
+ const WIZARD_LABELS = { integrations: "Azure DevOps y Jira" };
1389
+ const nav = wizard
1390
+ ? WIZARD_STEPS.map((id, i) => {
1391
+ const label = WIZARD_LABELS[id] ?? SECTIONS.find((x) => x.id === id).label;
1392
+ const mark = i + 1 < this.step ? { mark: "✓", tone: "ok" } : marks[id] ?? null;
1393
+ return this.navItem(id, `${i + 1} ${label}`, current === id, mark, (cx) => this.goTo(cx, id));
1394
+ })
1395
+ : SECTIONS.map((x) => this.navItem(x.id, x.label, current === x.id, marks[x.id] ?? null, (cx) => this.goTo(cx, x.id)));
1396
+ const body = {
1397
+ orchestrator: () => this.orchestratorSection(),
1398
+ agents: () => this.agentsSection(),
1399
+ github: () => this.githubSection(),
1400
+ azure: () => this.azureSection(),
1401
+ jira: () => this.jiraSection(),
1402
+ integrations: () => this.integrationsWizardSection(),
1403
+ image: () => this.imageSection(),
1404
+ advanced: () => this.advancedSection(),
1405
+ }[current]();
1406
+ const actions = [];
1407
+ if (wizard) {
1408
+ if (this.step > 1) actions.push(this.button("wiz-back", "Atrás", false, (cx) => this.wizBack(cx)));
1409
+ if (current === "integrations") actions.push(this.button("wiz-skip", "Saltar", false, (cx) => this.wizNext(cx)));
1410
+ actions.push(this.step < WIZARD_STEPS.length
1411
+ ? this.button("wiz-next", "Siguiente", true, (cx) => this.wizNext(cx))
1412
+ : this.button("wiz-finish", this.busy ? "Guardando…" : "Finalizar", true, (cx) => this.wizFinish(cx)));
1413
+ }
1414
+ const pending = wizard && this.step === WIZARD_STEPS.length && this.setup && !this.setup.complete ? this.pendingParts(this.setup) : [];
1415
+ return v_flex().id(wizard ? "bond-wizard" : "bond-settings-dialog").track_focus(this.handle).on_key_down((e, cx) => this.key(e, cx))
1416
+ .size_full().bg(t.popover).rounded(UI.radiusLg).border_1().border_color(t.border).text_color(t.foreground)
1417
+ .font_family("JetBrains Mono").overflow_hidden()
1418
+ .child(h_flex().h(46).flex_none().px(16).gap(10).items_center().border_b_1().border_color(t.border)
1419
+ .child(div().flex_1().text_size(UI.text.title + 2).font_family(UI.fontSans).font_semibold()
1420
+ .child(wizard ? "Configuración inicial" : "Ajustes"))
1421
+ .when(wizard, (el) => el.child(div().text_size(UI.text.small).text_color(t.dim).child(`Paso ${this.step} de ${WIZARD_STEPS.length}`)))
1422
+ .child(div().id("settings-close").w(24).h(24).rounded(UI.radius).flex().items_center().justify_center()
1423
+ .text_color(t.muted).cursor_pointer().hover((st) => st.bg(t.hover).text_color(t.foreground))
1424
+ .tooltip("Cerrar (Esc). Lo guardado no se pierde.")
1425
+ .on_click(() => closeOverlay(props().overlay)).child("✕")))
1426
+ .child(h_flex().flex_1().min_h(0).items_start()
1427
+ .child(v_flex().id("settings-nav").w(176).flex_none().h_full().p(8).gap(2).border_r_1().border_color(t.border).children(nav))
1428
+ .child(v_flex().id("settings-body").flex_1().min_w(0).h_full().p(20).gap(14).overflow_y_scrollbar()
1429
+ .when(Boolean(this.loadError), (el) => el.child(div().text_size(UI.text.small).text_color(t.blocked).child(`API: ${this.loadError}`)))
1430
+ .child(body)
1431
+ .when(Boolean(this.error), (el) => el.child(div().id("settings-error").text_size(UI.text.small).text_color(t.blocked).child(this.error)))
1432
+ .when(pending.length > 0, (el) => el.child(this.note(`Al finalizar quedará pendiente: ${pending.join(" · ")}. Podrás completarlo en Ajustes.`)))))
1433
+ .when(wizard, (el) => el.child(h_flex().h(52).flex_none().px(16).gap(8).items_center().justify_end().border_t_1().border_color(t.border)
1434
+ .children(actions)));
1435
+ }
1436
+
639
1437
  key(e, cx) {
640
1438
  if (e.key === "escape") {
641
1439
  closeOverlay(props().overlay);
1440
+ if (this.view === "agy-login") {
1441
+ this.cancelAgyLogin(cx, false);
1442
+ }
642
1443
  cx.stop_propagation();
643
1444
  }
644
1445
  }
@@ -651,61 +1452,297 @@ export default class BondSettings extends View {
651
1452
  .cursor_pointer().hover((s) => s.opacity(0.85)).on_click((_e, cx) => action(cx)).child(text);
652
1453
  }
653
1454
 
654
- // W-P2: «Configuración» in the Ajustes panel: the aggregated state at a glance, with
655
- // «Reabrir asistente» always visible (D-W2). Each piece is edited by the sections below.
656
- setupSection() {
657
- const t = theme();
658
- const s = this.setup;
659
- const pend = this.pendingParts(s);
660
- const mark = (name) => {
661
- const a = s?.agents?.find((x) => x.agent === name);
662
- return `${name}${a?.configured ? " ✓" : " ✗"}`;
663
- };
664
- return v_flex().gap(4)
665
- .child(div().text_size(11).font_semibold().text_color(t.muted).child("CONFIGURACIÓN (W-P2)"))
666
- .child(div().id("setup-status").text_size(11.5).font_semibold()
667
- .text_color(!s ? t.dim : s.complete ? t.working : t.blocked)
668
- .child(!s ? "Sin datos del orquestador" : s.complete ? "Configuración completa" : `Pendiente: ${pend.join(" · ")}`))
669
- .when(Boolean(s), (el) => el
670
- .child(div().text_size(11).text_color(t.dim)
671
- .child(`Agentes elegidos: ${s.agents_selected.length ? s.agents_selected.map(mark).join(" ") : "ninguno"}`))
672
- .child(div().text_size(11).text_color(t.dim).child(`Asistente: ${s.setup_done ? "terminado" : "sin terminar"}`)))
673
- .child(h_flex().pt(2)
674
- .child(this.button("wiz-reopen", "Reabrir asistente", false, () => openOverlay({
675
- mod: "bond-settings", kind: "dialog", modal: true, width: 560, height: 0.92,
676
- props: { view: "wizard", step: 1 },
677
- }))))
678
- .child(div().text_size(11).text_color(t.dim).child("Cada pieza se edita abajo: gh, credenciales y rebuild."));
679
- }
680
-
681
- renderPanel() {
1455
+ reconnect(cx) {
1456
+ if (this.connBusy) return;
1457
+ this.connBusy = "reconnect";
1458
+ resetToken();
1459
+ cx.notify();
1460
+ cx.spawn(async (cx) => {
1461
+ this.conn = await diagnose();
1462
+ this.connBusy = null;
1463
+ this.load(cx);
1464
+ notify({ title: "Orquestador", body: this.conn.state === "ok" ? "Conectado" : this.conn.detail, level: this.conn.state === "ok" ? "success" : "error" });
1465
+ cx.notify();
1466
+ });
1467
+ }
1468
+
1469
+ /** Waits until /health is `up` (true) or not (false), up to `ms`. */
1470
+ async waitHealth(cx, up, ms) {
1471
+ const until = Date.now() + ms;
1472
+ while (Date.now() < until) {
1473
+ let ok = false;
1474
+ try {
1475
+ await health();
1476
+ ok = true;
1477
+ } catch {}
1478
+ if (ok === up) return true;
1479
+ await cx.sleep(500);
1480
+ }
1481
+ return false;
1482
+ }
1483
+
1484
+ restartOrchestrator(cx) {
1485
+ if (this.connBusy) return;
1486
+ this.connBusy = "restart";
1487
+ cx.notify();
1488
+ cx.spawn(async (cx) => {
1489
+ try {
1490
+ await api("/system/restart", { method: "POST" });
1491
+ // It answers first and goes down right after; then the new process comes up.
1492
+ await this.waitHealth(cx, false, 10000);
1493
+ const back = await this.waitHealth(cx, true, 30000);
1494
+ if (!back) throw new Error(`no ha vuelto en 30 s: mira <data-dir>/orchestrator.log (${apiUrl()})`);
1495
+ resetToken();
1496
+ notify({ title: "Orquestador reiniciado", body: apiUrl(), level: "success" });
1497
+ } catch (e) {
1498
+ notify({ title: "No se pudo reiniciar", body: String(e?.message ?? e), level: "error" });
1499
+ }
1500
+ this.connBusy = null;
1501
+ this.load(cx);
1502
+ cx.notify();
1503
+ });
1504
+ }
1505
+
1506
+ startOrchestrator(cx) {
1507
+ if (this.connBusy) return;
1508
+ this.connBusy = "start";
1509
+ cx.notify();
1510
+ run("tab.new", { name: "bond-app", argv: startCommand(), focus: false });
1511
+ cx.spawn(async (cx) => {
1512
+ const up = await this.waitHealth(cx, true, 30000);
1513
+ resetToken();
1514
+ if (!up) notify({ title: "El orquestador no arranca", body: "Mira la pestaña «bond-app»", level: "error" });
1515
+ this.connBusy = null;
1516
+ this.load(cx);
1517
+ cx.notify();
1518
+ });
1519
+ }
1520
+
1521
+ startAgyLogin(cx) {
1522
+ this.agyStatus = "starting";
1523
+ this.agyUrl = null;
1524
+ this.agyEmail = null;
1525
+ this.agyError = null;
1526
+ this.agyBusy = true;
1527
+ cx.notify();
1528
+ cx.spawn(async (cx) => {
1529
+ try {
1530
+ const res = await api(`/settings/${this.loginAgent ?? "agy"}/login/start`, { method: "POST" });
1531
+ if (res?.status) this.agyStatus = res.status;
1532
+ if (res?.url) this.agyUrl = res.url;
1533
+ this.agyUserCode = res?.user_code ?? null;
1534
+ this.agyDevice = Boolean(res?.device);
1535
+ this.agyAuto = Boolean(res?.auto);
1536
+ if (res?.email) this.agyEmail = res.email;
1537
+ if (res?.error) this.agyError = res.error;
1538
+ } catch (e) {
1539
+ this.agyStatus = "error";
1540
+ this.agyError = String(e?.message ?? e);
1541
+ } finally {
1542
+ this.agyBusy = false;
1543
+ cx.notify();
1544
+ }
1545
+ });
1546
+ }
1547
+
1548
+ pollAgyStatus(cx) {
1549
+ cx.spawn(async (cx) => {
1550
+ try {
1551
+ const res = await api(`/settings/${this.loginAgent ?? "agy"}/login/status`);
1552
+ if (!res) return;
1553
+ let changed = false;
1554
+ if (res.status && res.status !== this.agyStatus) {
1555
+ this.agyStatus = res.status;
1556
+ changed = true;
1557
+ }
1558
+ if (res.url && res.url !== this.agyUrl) {
1559
+ this.agyUrl = res.url;
1560
+ changed = true;
1561
+ }
1562
+ if ((res.user_code ?? null) !== this.agyUserCode || Boolean(res.device) !== this.agyDevice || Boolean(res.auto) !== this.agyAuto) {
1563
+ this.agyUserCode = res.user_code ?? null;
1564
+ this.agyDevice = Boolean(res.device);
1565
+ this.agyAuto = Boolean(res.auto);
1566
+ changed = true;
1567
+ }
1568
+ if (res.email && res.email !== this.agyEmail) {
1569
+ this.agyEmail = res.email;
1570
+ changed = true;
1571
+ }
1572
+ if (res.error && res.error !== this.agyError) {
1573
+ this.agyError = res.error;
1574
+ changed = true;
1575
+ }
1576
+ if (changed) {
1577
+ if (this.agyStatus === "waiting_code" && !this.agyDevice) {
1578
+ this.agyCode.focus();
1579
+ }
1580
+ cx.notify();
1581
+ }
1582
+ } catch {}
1583
+ });
1584
+ }
1585
+
1586
+ submitAgyCode(cx) {
1587
+ const code = this.agyCode.value().trim();
1588
+ if (!code) {
1589
+ this.agyError = "El código no puede estar vacío.";
1590
+ cx.notify();
1591
+ return;
1592
+ }
1593
+ this.agyBusy = true;
1594
+ this.agyError = null;
1595
+ this.agyStatus = "authenticating";
1596
+ cx.notify();
1597
+ cx.spawn(async (cx) => {
1598
+ try {
1599
+ const res = await api(`/settings/${this.loginAgent ?? "agy"}/login/code`, {
1600
+ method: "POST",
1601
+ body: { code },
1602
+ });
1603
+ if (res?.status) this.agyStatus = res.status;
1604
+ if (res?.email) this.agyEmail = res.email;
1605
+ if (res?.error) this.agyError = res.error;
1606
+ } catch (e) {
1607
+ this.agyStatus = "error";
1608
+ this.agyError = String(e?.message ?? e);
1609
+ } finally {
1610
+ this.agyBusy = false;
1611
+ cx.notify();
1612
+ }
1613
+ });
1614
+ }
1615
+
1616
+ cancelAgyLogin(cx, close = true) {
1617
+ const p = props() ?? {};
1618
+ cx.spawn(async (cx) => {
1619
+ try {
1620
+ await api(`/settings/${this.loginAgent ?? "agy"}/login/cancel`, { method: "POST" });
1621
+ } catch {}
1622
+ if (close && p.overlay) {
1623
+ closeOverlay(p.overlay);
1624
+ }
1625
+ });
1626
+ }
1627
+
1628
+ copyToClipboard(text, cx) {
1629
+ if (!text) return;
1630
+ try {
1631
+ if (cx && typeof cx.write_to_clipboard === "function") {
1632
+ cx.write_to_clipboard(text);
1633
+ notify({ title: "URL copiada", body: "Pégala en tu navegador para autorizar", level: "info" });
1634
+ return;
1635
+ }
1636
+ } catch {}
1637
+ try {
1638
+ exec("wl-copy", [text]).catch(() => {
1639
+ exec("xclip", ["-selection", "clipboard"]).catch(() => {});
1640
+ });
1641
+ } catch {}
1642
+ notify({ title: "URL copiada", body: "Pégala en tu navegador para autorizar", level: "info" });
1643
+ }
1644
+
1645
+ finishAgyLogin(cx) {
1646
+ const p = props() ?? {};
1647
+ cx.spawn(async (cx) => {
1648
+ try {
1649
+ await api(`/settings/${this.loginAgent ?? "agy"}/login/finish`, { method: "POST" });
1650
+ } catch {}
1651
+ setShared(RELOAD_KEY, Date.now());
1652
+ if (p.overlay) {
1653
+ closeOverlay(p.overlay);
1654
+ }
1655
+ });
1656
+ }
1657
+
1658
+ renderAgyLogin(p) {
682
1659
  const t = theme();
683
- const row = (c) => h_flex().id(`cred-${c.agent}`).gap(8).items_center().py(4).font_family("JetBrains Mono")
684
- .child(div().w(70).text_size(UI.text.body).text_color(t.foreground).child(c.agent))
685
- .child(div().flex_1().text_size(UI.text.small).text_color(c.configured ? t.working : t.dim).truncate()
686
- .child(c.configured ? `credencial${c.provider ? ` · ${c.provider}` : ""}` : "sin credencial"))
687
- .child(this.button(`renew-${c.agent}`, c.configured ? "Renovar" : "Iniciar", false, () => openOverlay({
688
- mod: "bond-settings", kind: "dialog", modal: true, width: 480, height: 0.92,
689
- props: { view: "credential", agent: c.agent, provider: c.provider ?? "" },
690
- })));
691
- return v_flex().id("bond-settings").size_full().p(10).gap(8).bg(t.chrome).text_color(t.foreground).font_family("JetBrains Mono").overflow_y_scrollbar()
692
- .child(h_flex().items_center()
693
- .child(div().flex_1().text_size(UI.text.title).font_semibold().child("Ajustes"))
694
- .child(div().id("settings-close").w(24).h(22).rounded(UI.radius).flex().items_center().justify_center()
695
- .text_color(t.muted).cursor_pointer().hover((s) => s.bg(t.hover).text_color(t.foreground))
696
- .on_click(() => run("layout.toggle", { id: "settings" })).child("✕")))
697
- .child(this.setupSection())
698
- .child(this.githubSection())
699
- .child(div().text_size(UI.text.small).font_semibold().text_color(t.muted).child("CREDENCIALES DE AGENTES (D7)"))
700
- .when(Boolean(this.loadError), (el) => el.child(div().text_size(UI.text.small).text_color(t.blocked).child(`API: ${this.loadError}`)))
701
- .children(this.creds.map(row))
702
- .child(div().text_size(UI.text.small).text_color(t.dim)
703
- .child("Los tickets de agentes sin credencial no se bloquean; si una caduca, renuévala aquí."))
704
- .child(div().pt(8).text_size(UI.text.small).font_semibold().text_color(t.muted).child("IMAGEN DEL RUNNER"))
705
- .child(this.button("rebuild", "Rebuild…", false, () => openOverlay({
706
- mod: "bond-settings", kind: "dialog", modal: true, width: 420, props: { view: "rebuild" },
707
- })))
708
- .child(div().text_size(UI.text.small).text_color(t.dim).child("El rebuild no toca ni renueva las credenciales."));
1660
+ const L = LOGIN_TEXT[this.loginAgent ?? "agy"];
1661
+ const children = [];
1662
+
1663
+ children.push(div().text_size(11.5).text_color(t.dim).child(L.intro));
1664
+
1665
+ if (this.agyStatus === "starting") {
1666
+ children.push(
1667
+ v_flex().gap(6).py(12).items_center()
1668
+ .child(div().text_size(12).text_color(t.muted).child(L.starting))
1669
+ .child(div().text_size(11).text_color(t.dim).child(L.startingSub))
1670
+ );
1671
+ } else if (this.agyStatus === "waiting_code") {
1672
+ children.push(
1673
+ v_flex().gap(8)
1674
+ .child(div().text_size(12).font_semibold().text_color(t.foreground).child("1. Abre este enlace en tu navegador:"))
1675
+ .child(
1676
+ h_flex().gap(6).items_center()
1677
+ .child(
1678
+ div().flex_1().p(8).rounded(UI.radius).border_1().border_color(t.border).bg(t.background).text_size(11).truncate()
1679
+ .child(this.agyUrl || "Cargando URL…")
1680
+ )
1681
+ .when(Boolean(this.agyUrl), (el) =>
1682
+ el.child(
1683
+ this.button("agy-copy-url", "Copiar", false, (cx) => {
1684
+ this.copyToClipboard(this.agyUrl, cx);
1685
+ })
1686
+ )
1687
+ )
1688
+ )
1689
+ .when(!this.agyAuto, (el) => el.child(div().text_size(12).font_semibold().text_color(t.foreground).pt(4).child(L.step2)))
1690
+ // codex with the return caught by the orchestrator: nothing to paste unless it fails.
1691
+ .when(this.agyAuto, (el) => el
1692
+ .child(div().id("login-auto").text_size(12).font_semibold().text_color(t.foreground).pt(4)
1693
+ .child("2. Autoriza en el navegador: bond-app recoge la vuelta solo y este diálogo se cierra al terminar."))
1694
+ .when(!this.agyShowPaste, (x) => x.child(div().id("login-show-paste").text_size(11).text_color(t.dim).cursor_pointer()
1695
+ .hover((st) => st.text_color(t.foreground))
1696
+ .on_click((_e, cx) => { this.agyShowPaste = true; cx.notify(); this.agyCode.focus(); })
1697
+ .child("¿El navegador se queda en una página que no carga? Pega aquí su dirección")))
1698
+ .when(this.agyShowPaste, (x) => x.child(div().text_size(11.5).text_color(t.dim).child(L.step2))))
1699
+ .when(!this.agyDevice && (!this.agyAuto || this.agyShowPaste), (el) => el.child(
1700
+ Input.new(this.agyCode).h(32).px(10).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12.5)
1701
+ ))
1702
+ // Device flow (copilot): the code to type at the link; it finishes by itself.
1703
+ .when(this.agyDevice && Boolean(this.agyUserCode), (el) => el
1704
+ .child(h_flex().gap(8).items_center()
1705
+ .child(div().id("login-user-code").px(14).py(8).rounded(UI.radius).border_1().border_color(t.accent).bg(t.background)
1706
+ .text_size(20).font_semibold().text_color(t.foreground).child(this.agyUserCode))
1707
+ .child(this.button("login-copy-code", "Copiar código", false, (cx) => this.copyToClipboard(this.agyUserCode, cx))))
1708
+ .child(div().text_size(11.5).text_color(t.dim).child("Esperando a que autorices… se cierra solo al terminar.")))
1709
+ );
1710
+ } else if (this.agyStatus === "authenticating") {
1711
+ children.push(
1712
+ v_flex().gap(6).py(12).items_center()
1713
+ .child(div().text_size(12).text_color(t.muted).child(L.authenticating))
1714
+ .child(div().text_size(11).text_color(t.dim).child("Guardando sesión en el orquestador…"))
1715
+ );
1716
+ } else if (this.agyStatus === "success") {
1717
+ children.push(
1718
+ v_flex().gap(8).py(8)
1719
+ .child(div().text_size(13).font_semibold().text_color(t.working).child(L.success(this.agyEmail)))
1720
+ .child(div().text_size(11.5).text_color(t.dim).child(L.successSub))
1721
+ );
1722
+ }
1723
+
1724
+ if (this.agyError) {
1725
+ children.push(
1726
+ div().pt(4).text_size(11.5).text_color(t.blocked).child(`Error: ${this.agyError}`)
1727
+ );
1728
+ }
1729
+
1730
+ const actions = [];
1731
+ if (this.agyStatus === "success") {
1732
+ actions.push(this.button("agy-finish", "Listo", true, (cx) => this.finishAgyLogin(cx)));
1733
+ } else if (this.agyStatus === "waiting_code") {
1734
+ actions.push(this.button("agy-cancel", "Cancelar", false, (cx) => this.cancelAgyLogin(cx)));
1735
+ if (!this.agyDevice && (!this.agyAuto || this.agyShowPaste)) {
1736
+ actions.push(this.button("agy-submit", this.agyBusy ? "Enviando…" : (this.loginAgent === "codex" ? "Enviar dirección" : "Enviar código"), true, (cx) => this.submitAgyCode(cx)));
1737
+ }
1738
+ } else if (this.agyStatus === "error") {
1739
+ actions.push(this.button("agy-cancel", "Cerrar", false, (cx) => this.cancelAgyLogin(cx)));
1740
+ actions.push(this.button("agy-retry", "Reintentar", true, (cx) => this.startAgyLogin(cx)));
1741
+ } else {
1742
+ actions.push(this.button("agy-cancel", "Cancelar", false, (cx) => this.cancelAgyLogin(cx)));
1743
+ }
1744
+
1745
+ return this.renderDialog(L.title, children, actions, true);
709
1746
  }
710
1747
 
711
1748
  renderDialog(title, body, actions, fit = false) {
@@ -725,91 +1762,6 @@ export default class BondSettings extends View {
725
1762
  .child(h_flex().pt(8).gap(8).justify_end().children(actions));
726
1763
  }
727
1764
 
728
- // ---- W-P2: the wizard itself ---------------------------------------------------------
729
-
730
- wizardStepBody() {
731
- const t = theme();
732
- if (!this.setup) return div().text_size(UI.text.small).text_color(t.muted).child("Comprobando estado de la configuración…");
733
- if (this.step === 1) {
734
- const sel = this.selectedAgents();
735
- const rows = (this.setup.agents ?? []).map((a) =>
736
- h_flex().id(`wiz-agent-${a.agent}`).gap(8).items_center().px(4).py(4).rounded(UI.radius).cursor_pointer()
737
- .hover((s) => s.bg(t.hover))
738
- .on_click((_e, cx) => this.toggleAgent(cx, a.agent))
739
- .child(div().w(30).text_size(UI.text.body).text_color(sel.includes(a.agent) ? t.working : t.dim)
740
- .child(sel.includes(a.agent) ? "[x]" : "[ ]"))
741
- .child(div().text_size(UI.text.body).text_color(t.foreground).child(a.agent)));
742
- return v_flex().gap(6)
743
- .child(div().text_size(11.5).text_color(t.muted).child("Con qué agentes vas a trabajar. La imagen del runner soporta estos cinco; los demás entrarán cuando la imagen los soporte."))
744
- .children(rows)
745
- .child(div().text_size(11).text_color(t.dim).child("Aquí solo se guarda la selección; las credenciales son en el siguiente paso."));
746
- }
747
- if (this.step === 2) {
748
- const s = this.setup;
749
- const rows = (s.agents_selected ?? []).map((name) => {
750
- const state = (s.agents ?? []).find((a) => a.agent === name);
751
- const c = this.creds.find((x) => x.agent === name);
752
- const configured = Boolean(state?.configured);
753
- const bits = [c?.provider, c?.updated_at ? String(c.updated_at).slice(0, 10) : null].filter(Boolean);
754
- const status = configured ? ["credencial", ...bits].join(" · ") : "sin credencial";
755
- return h_flex().id(`wiz-cred-row-${name}`).gap(8).items_center().py(4).font_family("JetBrains Mono")
756
- .child(div().w(70).text_size(UI.text.body).text_color(t.foreground).child(name))
757
- .child(div().flex_1().text_size(UI.text.small).text_color(configured ? t.working : t.dim).truncate().child(status))
758
- .child(this.button(`wiz-cred-${name}`, configured ? "Renovar" : "Iniciar", false, () => openOverlay({
759
- mod: "bond-settings", kind: "dialog", modal: true, width: 480, height: 0.92,
760
- props: { view: "credential", agent: name, provider: c?.provider ?? "" },
761
- })));
762
- });
763
- return v_flex().gap(6)
764
- .child(div().text_size(11.5).text_color(t.muted).child("Inicia sesión con cada agente y pega aquí su config (D7). Hace falta al menos un agente con credencial para poder finalizar."))
765
- .child(div().text_size(11).text_color(t.dim).child("pi no necesita escribir JSON: «Iniciar» abre el formulario «modelo local / OpenAI-compatible» (nombre, URL, clave opcional); al salir del campo URL se cargan los modelos del provider para marcarlos con checkboxes, y entre ellos se elige el de sugerencias. El paquete supi aún no está en la imagen del runner (P2 del plan de la imagen, pendiente): la elección se guarda y queda inactiva hasta que lo incluya. La config completa se sigue pudiendo pegar en «modo avanzado»."))
766
- .when(rows.length === 0, (el) => el.child(div().text_size(UI.text.small).text_color(t.dim).child("No hay agentes elegidos: vuelve atrás y elige al menos uno.")))
767
- .children(rows)
768
- .when(!this.anyCredential(), (el) => el.child(div().text_size(11).text_color(t.blocked).child("Finalizar exige al menos un agente con credencial.")));
769
- }
770
- if (this.step === 3) {
771
- return v_flex().gap(6)
772
- .child(this.githubSection())
773
- .child(div().text_size(11).text_color(t.dim).child("Sin GitHub no se podrán clonar los repos al lanzar tickets; puedes conectarlo luego desde Ajustes."));
774
- }
775
- const img = this.setup.image ?? {};
776
- return v_flex().gap(6)
777
- .child(div().text_size(11.5).text_color(t.muted).child("La imagen del runner se construye con «Rebuild», con las versiones fijadas de bond, hc y los agentes elegidos en el paso 1."))
778
- .child(div().id("wiz-image-state").text_size(UI.text.small).font_semibold()
779
- .text_color(img.present ? t.working : t.blocked)
780
- .child(img.present ? `imagen presente${img.agents?.length ? ` · agentes en la imagen: ${img.agents.join(", ")}` : ""}` : "imagen ausente: «Rebuild» la construye"))
781
- .child(div().text_size(11).text_color(t.dim)
782
- .child(this.selectedAgents().length
783
- ? `Rebuild instalará en la imagen: ${this.selectedAgents().join(", ")} (más gh y la CLI de Azure DevOps).`
784
- : "Aún no has elegido agentes: «Rebuild» construiría la imagen mínima (pi)."))
785
- .child(h_flex().gap(6)
786
- .child(this.button("wiz-rebuild", this.rbBusy ? "Reconstruyendo…" : "Rebuild", false, (cx) => this.wizRebuild(cx))))
787
- .when(!this.setup.complete, (el) => el.child(div().text_size(11).text_color(t.dim).child(`Al finalizar quedará pendiente: ${this.pendingParts(this.setup).join(" · ")}. Podrás arreglarlo desde Ajustes.`)));
788
- }
789
-
790
- renderWizard() {
791
- const t = theme();
792
- const titles = ["agentes", "credenciales", "GitHub", "imagen"];
793
- const steps = h_flex().gap(10).items_center()
794
- .children(titles.map((title, i) => div().id(`wiz-step-${i + 1}`).text_size(UI.text.tiny).font_semibold()
795
- .text_color(this.step === i + 1 ? t.accent : t.dim).child(`${i + 1} ${title}`)));
796
- const actions = [];
797
- if (this.step > 1) actions.push(this.button("wiz-back", "Atrás", false, (cx) => this.wizBack(cx)));
798
- actions.push(this.step < 4
799
- ? this.button("wiz-next", this.busy && this.step === 1 ? "Guardando…" : "Siguiente", true, (cx) => this.wizNext(cx))
800
- : this.button("wiz-finish", this.busy ? "Guardando…" : "Finalizar", true, (cx) => this.wizFinish(cx)));
801
- return v_flex().id("bond-wizard").track_focus(this.handle).on_key_down((e, cx) => this.key(e, cx))
802
- .w_full().h_full().p(18).gap(10).bg(t.popover).rounded(UI.radiusLg).border_1().border_color(t.border).text_color(t.foreground).font_family("JetBrains Mono")
803
- .child(h_flex().items_center().child(div().flex_1().text_size(UI.text.title + 2).font_semibold().child("Asistente de configuración"))
804
- .child(div().text_size(UI.text.small).text_color(t.dim).child(`PASO ${this.step} DE 4 · Esc`)))
805
- .child(steps)
806
- .child(v_flex().flex_1().min_h(0).overflow_y_scrollbar().gap(10).child(this.wizardStepBody()))
807
- .when(Boolean(this.loadError), (el) => el.child(div().text_size(UI.text.small).text_color(t.blocked).child(`API: ${this.loadError}`)))
808
- .when(Boolean(this.error), (el) => el.child(div().text_size(UI.text.small).text_color(t.blocked).child(this.error)))
809
- .child(h_flex().pt(8).gap(8).justify_end().children(actions))
810
- .child(div().text_size(UI.text.tiny).text_color(t.dim).child("Esc cierra sin perder lo guardado; «Reabrir asistente» en Ajustes abre de nuevo cuando quieras."));
811
- }
812
-
813
1765
  // W-P3: the pi credential dialog, built from the four fields (pi-models.js makes the
814
1766
  // models.json); «modo avanzado» swaps to the full-JSON paste from W-P2.
815
1767
  renderPiCredential(p) {
@@ -818,7 +1770,7 @@ export default class BondSettings extends View {
818
1770
  const input = (state) => Input.new(state).h(32).px(10).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12.5);
819
1771
  if (this.advanced) {
820
1772
  return this.renderDialog(`Credencial de ${p.agent}`, [
821
- div().text_size(11.5).text_color(t.dim).child("Modo avanzado: pega el models.json completo del agente (D7). Se guarda en el orquestador y llega a cada run por stdin; no va en la imagen."),
1773
+ div().text_size(11.5).text_color(t.dim).child("Modo avanzado: pega el models.json completo del agente. Se guarda en el orquestador y llega a cada run por stdin; no va en la imagen."),
822
1774
  Input.new(this.provider).h(32).px(10).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12.5),
823
1775
  Textarea.new(this.config).h(150).p(8).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12),
824
1776
  ], [
@@ -836,7 +1788,7 @@ export default class BondSettings extends View {
836
1788
  div().text_size(11).text_color(t.dim).child("Si no le pones ruta, se añade /v1 (donde suelen servir estos servidores)."),
837
1789
  label("API KEY (OPCIONAL)"),
838
1790
  input(this.piKey),
839
- div().text_size(11).text_color(t.dim).child("pi exige que el provider lleve una clave aunque el servidor no la compruebe: si la tuya no pide, escribe «none». Con una URL vacía, rellénala siempre."),
1791
+ div().text_size(11).text_color(t.dim).child("Vacía conserva la clave que ya tenía este provider (por seguridad no se muestra); si nunca tuvo, se guarda «none», que pi acepta con servidores que no la comprueban."),
840
1792
  // W-P5: no «Cargar» button and no duplicated MODELOS field: the list loads on the
841
1793
  // URL blur (tiny animated line while waiting) and the checkboxes are the only UI.
842
1794
  ...(this.piListBusy
@@ -922,11 +1874,10 @@ export default class BondSettings extends View {
922
1874
  render() {
923
1875
  const t = theme();
924
1876
  const p = props() ?? {};
925
- if (this.view === "wizard") return this.renderWizard();
926
1877
  if (this.view === "credential" && this.isPi) return this.renderPiCredential(p);
927
1878
  if (this.view === "credential") {
928
1879
  return this.renderDialog(`Credencial de ${p.agent}`, [
929
- div().text_size(11.5).text_color(t.dim).child("Pega la config del agente tras iniciar sesión (D7). Se guarda en el orquestador y llega a cada run por stdin; no va en la imagen."),
1880
+ div().text_size(11.5).text_color(t.dim).child("Pega la config del agente tras iniciar sesión. Se guarda en el orquestador y llega a cada run por stdin; no va en la imagen."),
930
1881
  Input.new(this.provider).h(32).px(10).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12.5),
931
1882
  Textarea.new(this.config).h(150).p(8).rounded(8).border_1().border_color(t.input).bg(t.background).text_size(12),
932
1883
  ], [
@@ -934,14 +1885,7 @@ export default class BondSettings extends View {
934
1885
  this.button("cred-save", this.busy ? "Guardando…" : "Guardar", true, (cx) => this.saveCredential(cx)),
935
1886
  ], true);
936
1887
  }
937
- if (this.view === "rebuild") {
938
- return this.renderDialog("¿Reconstruir la imagen del runner?", [
939
- div().text_size(12.5).text_color(t.muted).child("Trae las versiones fijadas de bond, hc y los agentes. Puede tardar minutos. No toca las credenciales."),
940
- ], [
941
- this.button("rb-back", "Volver", false, () => closeOverlay(p.overlay)),
942
- this.button("rb-go", this.busy ? "Reconstruyendo…" : "Rebuild", true, (cx) => this.rebuild(cx)),
943
- ]);
944
- }
945
- return this.renderPanel();
1888
+ if (this.view === "agy-login") return this.renderAgyLogin(p);
1889
+ return this.renderSettings();
946
1890
  }
947
1891
  }