@worca/ui 0.21.0 → 0.23.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.
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Fleet-scoped chat commands.
3
+ *
4
+ * /fleets list active fleets (running + paused)
5
+ * /fleet [id|last] show one fleet's status
6
+ * /fleet-children <id|last> per-child status table
7
+ * /fleet-halt <id> graceful halt (in-flight finish naturally)
8
+ * /fleet-stop <id> [--force] hard stop (SIGTERM + control file), with confirmation
9
+ * /fleet-pause <id> pause every in-flight child
10
+ * /fleet-resume <id> resume paused/interrupted children, re-dispatch failed
11
+ *
12
+ * Authz: every handler runs *after* the inbound allowlist gate in
13
+ * index.js — same gate that already guards /pause, /resume, /stop.
14
+ *
15
+ * Destructive actions (/fleet-stop) require a confirmation token written
16
+ * into chat_context with a 60s expiry. The token mechanism is local to
17
+ * this module so we don't bloat chat_context.js's public API for what is
18
+ * really a per-command UX concern.
19
+ *
20
+ * @module commands/fleet
21
+ */
22
+
23
+ import { statusEmoji } from './global.js';
24
+
25
+ const CONFIRM_TTL_MS = 60_000;
26
+
27
+ /** Pick the most recent fleet from a list (created_at desc). */
28
+ function pickLatest(fleets) {
29
+ if (!fleets || fleets.length === 0) return null;
30
+ return [...fleets].sort((a, b) => {
31
+ const at = a.created_at || '';
32
+ const bt = b.created_at || '';
33
+ return bt.localeCompare(at);
34
+ })[0];
35
+ }
36
+
37
+ async function fetchFleets(restClient) {
38
+ const resp = await restClient.get('/api/fleet-runs');
39
+ const data = resp.data;
40
+ if (!data || data.ok === false) return [];
41
+ return Array.isArray(data.fleets) ? data.fleets : [];
42
+ }
43
+
44
+ async function fetchFleetById(restClient, id) {
45
+ const resp = await restClient.get(
46
+ `/api/fleet-runs/${encodeURIComponent(id)}`,
47
+ );
48
+ const data = resp.data;
49
+ if (!data || data.ok === false) return null;
50
+ return data.fleet ?? null;
51
+ }
52
+
53
+ /**
54
+ * Resolve "last" / short-suffix / full-id into a fleet manifest object.
55
+ * Returns { fleet, disambig } — exactly one of them populated.
56
+ */
57
+ async function resolveFleet(restClient, idArg, command) {
58
+ if (!idArg || idArg === 'last') {
59
+ const all = await fetchFleets(restClient);
60
+ const latest = pickLatest(all);
61
+ if (!latest) return { disambig: 'No fleets found.' };
62
+ return { fleet: latest };
63
+ }
64
+ if (idArg.startsWith('f_')) {
65
+ const fleet = await fetchFleetById(restClient, idArg);
66
+ if (!fleet) return { disambig: `Fleet \`${idArg}\` not found.` };
67
+ return { fleet };
68
+ }
69
+ // Short suffix match — `4318dbf9` matches `f_..._4318dbf9`.
70
+ const all = await fetchFleets(restClient);
71
+ const matches = all.filter((f) => f.fleet_id?.endsWith(idArg));
72
+ if (matches.length === 0) {
73
+ return { disambig: `No fleet matches \`${idArg}\`.` };
74
+ }
75
+ if (matches.length > 1) {
76
+ const lines = matches.map((f) => ` • \`${f.fleet_id}\` — ${f.status}`);
77
+ return {
78
+ disambig:
79
+ `Multiple fleets match \`${idArg}\`:\n${lines.join('\n')}\n\n` +
80
+ `Usage: /${command} <fleet_id>`,
81
+ };
82
+ }
83
+ return { fleet: matches[0] };
84
+ }
85
+
86
+ function fmtFleetSummary(fleet) {
87
+ const id = fleet.fleet_id;
88
+ const title = fleet.work_request?.title || '(no title)';
89
+ const status = fleet.status || 'unknown';
90
+ const reason = fleet.halt_reason ? ` (${fleet.halt_reason})` : '';
91
+ const childCount = fleet.children_count ?? fleet.children?.length ?? 0;
92
+ const completed = (fleet.children || []).filter(
93
+ (c) => c.status === 'completed',
94
+ ).length;
95
+ const failed = (fleet.children || []).filter(
96
+ (c) => c.status === 'failed' || c.status === 'setup_failed',
97
+ ).length;
98
+ const parts = [`${statusEmoji(status)} **Fleet:** \`${id}\``];
99
+ parts.push(` **Title:** ${title}`);
100
+ parts.push(` **Status:** ${status}${reason}`);
101
+ parts.push(
102
+ ` **Children:** ${completed}/${childCount} completed${failed ? `, ${failed} failed` : ''}`,
103
+ );
104
+ if (fleet.cost_usd != null) {
105
+ parts.push(` **Cost:** $${Number(fleet.cost_usd).toFixed(2)}`);
106
+ }
107
+ return parts.join('\n');
108
+ }
109
+
110
+ function fmtChildrenTable(fleet) {
111
+ const children = fleet.children || [];
112
+ if (children.length === 0) return ' (no children dispatched yet)';
113
+ return children
114
+ .map((c) => {
115
+ const project =
116
+ (c.project_path || '').split('/').filter(Boolean).pop() || '(?)';
117
+ const st = c.status || 'unknown';
118
+ const rid = c.run_id ? ` \`${c.run_id}\`` : '';
119
+ return ` ${statusEmoji(st)} **${project}** — ${st}${rid}`;
120
+ })
121
+ .join('\n');
122
+ }
123
+
124
+ /**
125
+ * Creates handlers for the /fleet… commands.
126
+ *
127
+ * The chatContext is used for /fleet-stop confirmation tokens — we store
128
+ * a `pending_fleet_stop = { fleet_id, expires_at }` shape on the chat key
129
+ * and clear it after the confirming message comes in.
130
+ *
131
+ * @param {{ chatContext, restClient }} deps
132
+ */
133
+ export function createFleetHandlers({ chatContext, restClient }) {
134
+ async function fleets() {
135
+ const all = await fetchFleets(restClient);
136
+ const active = all.filter((f) => {
137
+ const s = f.status;
138
+ return s === 'running' || s === 'paused' || s === 'resuming';
139
+ });
140
+ if (active.length === 0) return 'No active fleets.';
141
+ const lines = active.map((f) => {
142
+ const childCount = f.children_count ?? f.children?.length ?? 0;
143
+ const title = f.work_request?.title || '(no title)';
144
+ const reason = f.halt_reason ? ` (${f.halt_reason})` : '';
145
+ return [
146
+ `${statusEmoji(f.status)} **Fleet:** \`${f.fleet_id}\``,
147
+ ` **Title:** ${title}`,
148
+ ` **Status:** ${f.status}${reason} | **Children:** ${childCount}`,
149
+ ].join('\n');
150
+ });
151
+ return `Active fleets:\n\n${lines.join('\n')}`;
152
+ }
153
+
154
+ async function fleet(_chatKey, args) {
155
+ const resolved = await resolveFleet(restClient, args[0], 'fleet');
156
+ if (resolved.disambig) return resolved.disambig;
157
+ return fmtFleetSummary(resolved.fleet);
158
+ }
159
+
160
+ async function fleetChildren(_chatKey, args) {
161
+ const resolved = await resolveFleet(restClient, args[0], 'fleet-children');
162
+ if (resolved.disambig) return resolved.disambig;
163
+ const f = resolved.fleet;
164
+ return `Children of \`${f.fleet_id}\`:\n\n` + fmtChildrenTable(f);
165
+ }
166
+
167
+ async function fleetHalt(_chatKey, args) {
168
+ const resolved = await resolveFleet(restClient, args[0], 'fleet-halt');
169
+ if (resolved.disambig) return resolved.disambig;
170
+ const id = resolved.fleet.fleet_id;
171
+ const resp = await restClient.delete(
172
+ `/api/fleet-runs/${encodeURIComponent(id)}`,
173
+ );
174
+ if (!resp.data || resp.data.ok === false) {
175
+ return `Failed to halt fleet \`${id}\` (${resp.status}).`;
176
+ }
177
+ return `\u{1F7E1} Halted fleet \`${id}\`.\nIn-flight children will finish naturally.`;
178
+ }
179
+
180
+ async function fleetStop(chatKey, args) {
181
+ const isForce = args.includes('--force') || args.includes('YES');
182
+ const cleanArgs = args.filter((a) => a !== '--force' && a !== 'YES');
183
+ const resolved = await resolveFleet(restClient, cleanArgs[0], 'fleet-stop');
184
+ if (resolved.disambig) return resolved.disambig;
185
+ const id = resolved.fleet.fleet_id;
186
+
187
+ const ctx = chatContext.get(chatKey) || {};
188
+ const pending = ctx.pending_fleet_stop;
189
+
190
+ if (!isForce) {
191
+ // Issue / refresh a confirmation token.
192
+ chatContext.set(chatKey, {
193
+ pending_fleet_stop: {
194
+ fleet_id: id,
195
+ expires_at: new Date(Date.now() + CONFIRM_TTL_MS).toISOString(),
196
+ },
197
+ });
198
+ const child_count =
199
+ resolved.fleet.children_count ?? (resolved.fleet.children || []).length;
200
+ return (
201
+ `⚠ \`/fleet-stop\` will SIGTERM every in-flight child of fleet \`${id}\` (${child_count} children).\n` +
202
+ `Confirm with \`/fleet-stop ${id} YES\` within 60s, or pass \`--force\`.`
203
+ );
204
+ }
205
+
206
+ // --force or YES path. Either matches a fresh confirmation token, or
207
+ // the caller is bypassing the gate entirely with --force.
208
+ if (
209
+ args.includes('YES') &&
210
+ (!pending ||
211
+ pending.fleet_id !== id ||
212
+ new Date(pending.expires_at).getTime() < Date.now())
213
+ ) {
214
+ return `Confirmation expired or never issued for fleet \`${id}\`. Re-run \`/fleet-stop ${id}\` to get a fresh token.`;
215
+ }
216
+
217
+ chatContext.set(chatKey, { pending_fleet_stop: null });
218
+ const resp = await restClient.post(
219
+ `/api/fleet-runs/${encodeURIComponent(id)}/stop`,
220
+ );
221
+ if (!resp.data || resp.data.ok === false) {
222
+ return `Failed to stop fleet \`${id}\` (${resp.status}).`;
223
+ }
224
+ const count = resp.data.stopped_count ?? '?';
225
+ return `\u{1F534} Stopped fleet \`${id}\`. SIGTERM sent to ${count} child(ren).`;
226
+ }
227
+
228
+ async function fleetPause(_chatKey, args) {
229
+ const resolved = await resolveFleet(restClient, args[0], 'fleet-pause');
230
+ if (resolved.disambig) return resolved.disambig;
231
+ const id = resolved.fleet.fleet_id;
232
+ const resp = await restClient.post(
233
+ `/api/fleet-runs/${encodeURIComponent(id)}/pause`,
234
+ );
235
+ if (!resp.data || resp.data.ok === false) {
236
+ return `Failed to pause fleet \`${id}\` (${resp.status}).`;
237
+ }
238
+ const count = resp.data.paused_count ?? '?';
239
+ return `\u{1F7E1} Paused fleet \`${id}\`. ${count} child(ren) will pause at their next iteration boundary.`;
240
+ }
241
+
242
+ async function fleetResume(_chatKey, args) {
243
+ const resolved = await resolveFleet(restClient, args[0], 'fleet-resume');
244
+ if (resolved.disambig) return resolved.disambig;
245
+ const id = resolved.fleet.fleet_id;
246
+ const resp = await restClient.post(
247
+ `/api/fleet-runs/${encodeURIComponent(id)}/resume`,
248
+ );
249
+ if (!resp.data || resp.data.ok === false) {
250
+ return `Failed to resume fleet \`${id}\` (${resp.status}).`;
251
+ }
252
+ const continued = resp.data.continued_count ?? 0;
253
+ const redispatched = resp.data.redispatched_count ?? 0;
254
+ return `\u{1F7E2} Resumed fleet \`${id}\`. ${continued} continued in-place, ${redispatched} re-dispatched.`;
255
+ }
256
+
257
+ return {
258
+ fleets,
259
+ fleet,
260
+ 'fleet-children': fleetChildren,
261
+ 'fleet-halt': fleetHalt,
262
+ 'fleet-stop': fleetStop,
263
+ 'fleet-pause': fleetPause,
264
+ 'fleet-resume': fleetResume,
265
+ };
266
+ }
@@ -115,6 +115,15 @@ const HELP_TEXT = `/start \u2014 show your chat ID
115
115
  /resume [run_id] \u2014 resume paused run
116
116
  /stop [run_id] \u2014 stop run
117
117
 
118
+ Fleet commands (cross-project):
119
+ /fleets \u2014 list active fleets
120
+ /fleet [id|last] \u2014 fleet status
121
+ /fleet-children <id|last> \u2014 per-child status
122
+ /fleet-halt <id> \u2014 graceful halt (in-flight finish naturally)
123
+ /fleet-stop <id> [--force] \u2014 SIGTERM every in-flight child (confirms first)
124
+ /fleet-pause <id> \u2014 pause every in-flight child
125
+ /fleet-resume <id> \u2014 resume paused/interrupted, re-dispatch failed
126
+
118
127
  Commands with [run_id] auto-resolve to the active run if omitted.
119
128
  Use \`*suffix\` to match by ending, e.g. /status \`*2db5\`
120
129
  Project commands require /use first.`;
@@ -1,6 +1,9 @@
1
1
  const MENTION_RE = /^@\S+$/i;
2
2
 
3
- const COMMAND_RE = /^\/([a-z_]+)(?:@\S+)?$/i;
3
+ // Allow `-` so namespaced commands like /fleet-halt and /fleet-resume parse.
4
+ // Hyphens must appear inside the name, not lead or trail. Backwards-compatible
5
+ // — every existing underscore-only command still matches.
6
+ const COMMAND_RE = /^\/([a-z_][a-z0-9_-]*)(?:@\S+)?$/i;
4
7
 
5
8
  /**
6
9
  * Parses a chat message into a command name and argument list.
@@ -12,6 +12,7 @@ import { createWebhookOutAdapter } from './adapters/webhook_out.js';
12
12
  import { createAllowlistGuard } from './allowlist.js';
13
13
  import { createChatContext } from './chat_context.js';
14
14
  import { createControlHandlers } from './commands/control.js';
15
+ import { createFleetHandlers } from './commands/fleet.js';
15
16
  import { createGlobalHandlers } from './commands/global.js';
16
17
  import { parseCommand } from './commands/parser.js';
17
18
  import { createProjectHandlers } from './commands/project.js';
@@ -65,10 +66,12 @@ export function createIntegrations({
65
66
  });
66
67
  const projectHandlers = createProjectHandlers({ chatContext, restClient });
67
68
  const controlHandlers = createControlHandlers({ chatContext, restClient });
69
+ const fleetHandlers = createFleetHandlers({ chatContext, restClient });
68
70
  const allHandlers = {
69
71
  ...globalHandlers,
70
72
  ...projectHandlers,
71
73
  ...controlHandlers,
74
+ ...fleetHandlers,
72
75
  };
73
76
 
74
77
  // Mutable adapter registry — keyed by adapter name
@@ -154,6 +154,90 @@ function renderCostBudgetWarning(envelope) {
154
154
  return mdMsg(parts.join('\n'), 'warning');
155
155
  }
156
156
 
157
+ // ---------------------------------------------------------------------------
158
+ // Fleet event renderers
159
+ // ---------------------------------------------------------------------------
160
+ // Mirror the run-event renderers' shape: short title line + indented meta
161
+ // rows. fleet_id replaces run_id as the primary key; envelopes are
162
+ // fleet-shaped (top-level fleet_id, no `pipeline` wrapper). See
163
+ // src/worca/events/fleet_emitter.py for the envelope schema.
164
+
165
+ function fleetId(envelope) {
166
+ return envelope.fleet_id ?? 'fleet';
167
+ }
168
+
169
+ function projectBasename(p) {
170
+ if (!p) return '';
171
+ const parts = p.split('/').filter(Boolean);
172
+ return parts[parts.length - 1] || p;
173
+ }
174
+
175
+ function renderFleetLaunched(envelope) {
176
+ const p = envelope.payload ?? {};
177
+ const projects = Array.isArray(p.projects) ? p.projects : [];
178
+ const projectsLabel = projects.length
179
+ ? projects.slice(0, 5).map(projectBasename).join(', ') +
180
+ (projects.length > 5 ? `, +${projects.length - 5} more` : '')
181
+ : '(none)';
182
+ const parts = [`\u{1F680} **Fleet launched:** \`${fleetId(envelope)}\``];
183
+ parts.push(` **Projects:** ${projects.length} — ${projectsLabel}`);
184
+ if (p.plan_mode && p.plan_mode !== 'none') {
185
+ parts.push(` **Plan mode:** ${p.plan_mode}`);
186
+ }
187
+ if (p.guide_attached) parts.push(' **Guide:** attached');
188
+ if (p.base_branch) parts.push(` **Base:** ${p.base_branch}`);
189
+ return mdMsg(parts.join('\n'), 'info');
190
+ }
191
+
192
+ function renderFleetHalted(envelope) {
193
+ const p = envelope.payload ?? {};
194
+ const reason = p.halt_reason || 'unknown';
195
+ // Severity matches the reason: circuit_breaker is an error, user/stopped is
196
+ // a warning. Keeps Slack/Discord colour coding consistent with the per-run
197
+ // pipeline.run.interrupted vs pipeline.circuit_breaker.tripped split.
198
+ const sev = reason === 'circuit_breaker' ? 'error' : 'warning';
199
+ const parts = [`\u{1F6D1} **Fleet halted:** \`${fleetId(envelope)}\``];
200
+ parts.push(` **Reason:** ${reason}`);
201
+ if (p.in_flight_count != null) {
202
+ parts.push(` **In-flight at halt:** ${p.in_flight_count}`);
203
+ }
204
+ if (p.pending_count != null && p.pending_count > 0) {
205
+ parts.push(` **Pending (not dispatched):** ${p.pending_count}`);
206
+ }
207
+ return mdMsg(parts.join('\n'), sev);
208
+ }
209
+
210
+ function renderFleetCompleted(envelope) {
211
+ const p = envelope.payload ?? {};
212
+ const parts = [`✅ **Fleet completed:** \`${fleetId(envelope)}\``];
213
+ if (p.child_count != null) {
214
+ parts.push(
215
+ ` **Children:** ${p.completed_count ?? p.child_count}/${p.child_count} completed`,
216
+ );
217
+ }
218
+ if (p.duration_ms != null) {
219
+ parts.push(` **Duration:** ${fmtMs(p.duration_ms)}`);
220
+ }
221
+ return mdMsg(parts.join('\n'), 'success');
222
+ }
223
+
224
+ function renderFleetFailed(envelope) {
225
+ const p = envelope.payload ?? {};
226
+ const parts = [`❌ **Fleet failed:** \`${fleetId(envelope)}\``];
227
+ if (p.child_count != null) {
228
+ const failed = p.failed_count ?? 0;
229
+ const interrupted = p.interrupted_count ?? 0;
230
+ const completed = p.completed_count ?? 0;
231
+ parts.push(
232
+ ` **Children:** ${completed}/${p.child_count} completed, ${failed} failed, ${interrupted} interrupted`,
233
+ );
234
+ }
235
+ if (p.duration_ms != null) {
236
+ parts.push(` **Duration:** ${fmtMs(p.duration_ms)}`);
237
+ }
238
+ return mdMsg(parts.join('\n'), 'error');
239
+ }
240
+
157
241
  // ---------------------------------------------------------------------------
158
242
  // Registry
159
243
  // ---------------------------------------------------------------------------
@@ -173,6 +257,20 @@ const EVENT_RENDERERS = {
173
257
  'pipeline.git.pr_merged': renderGitPrMerged,
174
258
  'pipeline.circuit_breaker.tripped': renderCbTripped,
175
259
  'pipeline.cost.budget_warning': renderCostBudgetWarning,
260
+ // fleet.launched is intentionally NOT in this map by default — projects
261
+ // that launch many fleets per day would find it noisy. Opt-in callers
262
+ // can register it themselves via renderEvent's renderer override (or
263
+ // by extending TIER1_EVENTS in a future per-project config).
264
+ 'fleet.halted': renderFleetHalted,
265
+ 'fleet.completed': renderFleetCompleted,
266
+ 'fleet.failed': renderFleetFailed,
267
+ };
268
+
269
+ // fleet.launched ships as an opt-in renderer rather than a Tier-1 default —
270
+ // see comment above. Callers that want it can pull it from this export and
271
+ // register it in their own pipeline.
272
+ export const OPT_IN_RENDERERS = {
273
+ 'fleet.launched': renderFleetLaunched,
176
274
  };
177
275
 
178
276
  export const TIER1_EVENTS = Object.keys(EVENT_RENDERERS);
@@ -13,5 +13,12 @@ export function createRestClient({ host, port }) {
13
13
  });
14
14
  return { status: r.status, data: r.ok ? await r.json() : null };
15
15
  },
16
+ // DELETE used by /fleet-halt (DELETE /api/fleet-runs/:id) — added when
17
+ // chat fleet commands landed. Mirrors the get/post pair: no body, returns
18
+ // parsed JSON on 2xx, null on error status.
19
+ async delete(path) {
20
+ const r = await fetch(`${base}${path}`, { method: 'DELETE' });
21
+ return { status: r.status, data: r.ok ? await r.json() : null };
22
+ },
16
23
  };
17
24
  }