@blackbelt-technology/pi-dashboard-chat-gateway-plugin 0.9.0 → 0.11.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.
package/package.json CHANGED
@@ -1,7 +1,10 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-chat-gateway-plugin",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Inbound chat control plane — drive dashboard pi sessions from a chat platform (Discord shipped). Extensible adapter layer; no bridge or server protocol change.",
5
+ "keywords": [
6
+ "pi-dashboard-plugin"
7
+ ],
5
8
  "license": "MIT",
6
9
  "publishConfig": {
7
10
  "access": "public"
@@ -55,6 +58,7 @@
55
58
  {
56
59
  "slot": "settings-section",
57
60
  "component": "ChatGatewaySettings",
61
+ "module": "./src/client/ChatGatewaySettings.tsx",
58
62
  "config": {
59
63
  "tab": "general"
60
64
  }
@@ -67,9 +71,8 @@
67
71
  "react-dom": ">=18.0.0"
68
72
  },
69
73
  "dependencies": {
70
- "@blackbelt-technology/dashboard-plugin-runtime": "^0.9.0",
71
- "@blackbelt-technology/pi-dashboard-mcp-server-plugin": "^0.9.0",
72
- "@blackbelt-technology/pi-dashboard-shared": "^0.9.0",
74
+ "@blackbelt-technology/dashboard-plugin-runtime": "^0.11.0",
75
+ "@blackbelt-technology/pi-dashboard-shared": "^0.11.0",
73
76
  "discord.js": "^14.27.0"
74
77
  },
75
78
  "devDependencies": {
@@ -0,0 +1,493 @@
1
+ /**
2
+ * chat-gateway — dashboard plugin client entry (settings-section, task 10.1).
3
+ *
4
+ * Edits the gateway config through the canonical partial-write lane
5
+ * (`plugin_config_write` → `POST /api/config/plugins/chat-gateway`), which
6
+ * shallow-merges. The page buffers its edits into the host Save bar (draft
7
+ * source `plugin:chat-gateway`, no Save button of its own) and commits ONLY the
8
+ * keys the operator edited, so a key it does not own is never overwritten by a
9
+ * stale snapshot.
10
+ *
11
+ * The bot TOKEN is write-only: the draft holds just a "replace token" string,
12
+ * cleared after a commit / Discard / reset, never sent blank, never echoed from
13
+ * the server, and scrubbed out of every error text and "Copy details" payload.
14
+ *
15
+ * The bindings table is read-only and fetched from the plugin's own
16
+ * `/api/chat-gateway/bindings` route (registered only when configured).
17
+ *
18
+ * See change: add-chat-gateway, retro-ux-plugin-settings-wave-2.
19
+ */
20
+
21
+ import { SelectField, SettingsGroup, SettingsNotice, SettingsStatusPill, SettingsTable, TextAreaField, TextField, ToggleField, usePluginConfig, usePluginSend, useSettingsDraftSource } from "@blackbelt-technology/dashboard-plugin-runtime";
22
+ import type { SlotProps } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/slot-props.js";
23
+ import type React from "react";
24
+ import { useEffect, useState } from "react";
25
+ import type { Binding, ChatGatewayConfig } from "../shared/types.js";
26
+ import { TeamControlsPanel } from "./team-controls-panel.js";
27
+
28
+ interface BindingsResponse {
29
+ bindings: Binding[];
30
+ status: { running: boolean; boundChannels: number; pendingSpawns: number };
31
+ }
32
+
33
+ /** Editable form values, kept as the strings the operator types. */
34
+ interface Draft {
35
+ enabled: boolean;
36
+ threadPerConversation: boolean;
37
+ mirrorDashboardSessions: boolean;
38
+ allowedRoots: string;
39
+ defaultCwd: string;
40
+ fixedMap: string;
41
+ allowlist: string;
42
+ admins: string;
43
+ groupChannels: string;
44
+ steerPrefix: string;
45
+ sessionVisibility: "hidden" | "shown";
46
+ }
47
+
48
+ const INVALID_FIELDS = "Fix the invalid fields before saving.";
49
+ const SAVE_FAILED = "Couldn't save these settings. Your changes are still here.";
50
+
51
+ function parseList(value: string): string[] {
52
+ return value
53
+ .split(/[\n,]/)
54
+ .map((s) => s.trim())
55
+ .filter((s) => s.length > 0);
56
+ }
57
+
58
+ function parseLines(value: string): string[] {
59
+ return value
60
+ .split("\n")
61
+ .map((s) => s.trim())
62
+ .filter((s) => s.length > 0);
63
+ }
64
+
65
+ function formatFixedMap(map: Record<string, string>): string {
66
+ return Object.entries(map)
67
+ .map(([k, v]) => `${k}=${v}`)
68
+ .join("\n");
69
+ }
70
+
71
+ /** Split one `channelKey=cwd` line on its first `=`; `null` when malformed. */
72
+ function splitMapLine(line: string): [string, string] | null {
73
+ const trimmed = line.trim();
74
+ const eq = trimmed.indexOf("=");
75
+ if (eq <= 0) return null;
76
+ const key = trimmed.slice(0, eq).trim();
77
+ const cwd = trimmed.slice(eq + 1).trim();
78
+ return key.length > 0 && cwd.length > 0 ? [key, cwd] : null;
79
+ }
80
+
81
+ /** `channelKey=cwd` per line; the first `=` splits (cwd paths may contain none). */
82
+ function parseFixedMap(value: string): Record<string, string> {
83
+ const out: Record<string, string> = {};
84
+ for (const line of value.split("\n")) {
85
+ const pair = splitMapLine(line);
86
+ if (pair) out[pair[0]] = pair[1];
87
+ }
88
+ return out;
89
+ }
90
+
91
+ /** 1-based numbers of the non-blank lines that are not `channelKey=folder`. */
92
+ function badMapLines(value: string): number[] {
93
+ const bad: number[] = [];
94
+ value.split("\n").forEach((line, i) => {
95
+ if (line.trim().length > 0 && !splitMapLine(line)) bad.push(i + 1);
96
+ });
97
+ return bad;
98
+ }
99
+
100
+ function mapLineError(bad: number[]): string | null {
101
+ if (bad.length === 0) return null;
102
+ return bad.length === 1
103
+ ? `Line ${bad[0]} is not in the form channelKey=folder, so it would be dropped.`
104
+ : `Lines ${bad.join(", ")} are not in the form channelKey=folder, so they would be dropped.`;
105
+ }
106
+
107
+ /**
108
+ * Remove every spelling of a secret (raw, trimmed, JSON-escaped, URL-encoded)
109
+ * from text that may be shown or copied. A server error can echo the request.
110
+ */
111
+ function scrubSecret(text: string, secret: string): string {
112
+ const spellings = new Set<string>();
113
+ for (const s of [secret, secret.trim()]) {
114
+ if (s.length === 0) continue;
115
+ spellings.add(s);
116
+ spellings.add(JSON.stringify(s).slice(1, -1));
117
+ spellings.add(encodeURIComponent(s));
118
+ }
119
+ let out = text;
120
+ for (const s of [...spellings].sort((a, b) => b.length - a.length)) out = out.split(s).join("[token hidden]");
121
+ return out;
122
+ }
123
+
124
+ /** The saved config as editable form values (defaults mirror the server's). */
125
+ function savedDraft(config: ChatGatewayConfig | undefined): Draft {
126
+ return {
127
+ enabled: config?.enabled ?? true,
128
+ threadPerConversation: config?.threadPerConversation ?? true,
129
+ mirrorDashboardSessions: config?.mirrorDashboardSessions ?? false,
130
+ allowedRoots: (config?.allowedRoots ?? []).join("\n"),
131
+ defaultCwd: config?.defaultCwd ?? "",
132
+ fixedMap: formatFixedMap(config?.fixedMap ?? {}),
133
+ allowlist: (config?.allowlist ?? []).join(", "),
134
+ admins: (config?.admins ?? []).join(", "),
135
+ groupChannels: (config?.groupChannels ?? []).join(", "),
136
+ steerPrefix: config?.steerPrefix ?? "!",
137
+ sessionVisibility: config?.sessionVisibility ?? "hidden",
138
+ };
139
+ }
140
+
141
+ /** Header pill: Not set up (no gateway route yet) · Paused · Running · Not running. */
142
+ function GatewayStatus({ bindings, enabled }: { bindings: BindingsResponse | null; enabled: boolean }): React.ReactElement {
143
+ if (!bindings) {
144
+ return (
145
+ <SettingsStatusPill tone="neutral" status="not-set-up" testId="chat-gateway-status">
146
+ Not set up · add a bot token
147
+ </SettingsStatusPill>
148
+ );
149
+ }
150
+ if (!enabled) {
151
+ return (
152
+ <SettingsStatusPill tone="neutral" icon={null} status="paused" testId="chat-gateway-status">
153
+ Paused
154
+ </SettingsStatusPill>
155
+ );
156
+ }
157
+ return bindings.status.running ? (
158
+ <SettingsStatusPill tone="success" status="running" testId="chat-gateway-status">
159
+ Running
160
+ </SettingsStatusPill>
161
+ ) : (
162
+ <SettingsStatusPill tone="warning" status="not-running" testId="chat-gateway-status">
163
+ Not running
164
+ </SettingsStatusPill>
165
+ );
166
+ }
167
+
168
+ const WIRE: { [K in keyof Draft]: (v: Draft[K]) => unknown } = {
169
+ enabled: (v) => v,
170
+ threadPerConversation: (v) => v,
171
+ mirrorDashboardSessions: (v) => v,
172
+ allowedRoots: parseLines,
173
+ defaultCwd: (v) => v,
174
+ fixedMap: parseFixedMap,
175
+ allowlist: parseList,
176
+ admins: parseList,
177
+ groupChannels: parseList,
178
+ steerPrefix: (v) => v,
179
+ sessionVisibility: (v) => v,
180
+ };
181
+
182
+ export function ChatGatewaySettings(_props: SlotProps<"settings-section">): React.ReactElement {
183
+ const config = usePluginConfig<ChatGatewayConfig>();
184
+ const send = usePluginSend();
185
+
186
+ // Values this page saved successfully, shown as "saved" until the next
187
+ // `plugin_config_update` replaces them — so a save never flashes the old
188
+ // values back while the broadcast is in flight (or lost).
189
+ const [landed, setLanded] = useState<Partial<Draft>>({});
190
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reset on every config broadcast.
191
+ useEffect(() => setLanded({}), [config]);
192
+ const saved: Draft = { ...savedDraft(config), ...landed };
193
+
194
+ // Only the EDITED keys live in `draft`; every other field shows the saved
195
+ // value, so a clean page adopts a `plugin_config_update` broadcast and a dirty
196
+ // page keeps its edited keys while the rest adopt it.
197
+ const [draft, setDraft] = useState<Partial<Draft>>({});
198
+ // Write-only secret: the typed replacement only, never seeded from the server.
199
+ const [token, setToken] = useState("");
200
+ const [busy, setBusy] = useState(false);
201
+ const [notice, setNotice] = useState<{ details: string } | null>(null);
202
+ const [bindings, setBindings] = useState<BindingsResponse | null>(null);
203
+ const [refreshKey, setRefreshKey] = useState(0);
204
+
205
+ // Drop draft keys the stored config now matches (our own save landing, or
206
+ // another writer saving the same value), so a later broadcast never turns a
207
+ // stale draft key into a ghost edit. Keyed on `config`: `saved` is derived.
208
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `saved` derives from `config` + `landed`.
209
+ useEffect(() => {
210
+ setDraft((d) => {
211
+ const stale = (Object.keys(d) as Array<keyof Draft>).filter((k) => d[k] === saved[k]);
212
+ if (stale.length === 0) return d;
213
+ const next = { ...d };
214
+ for (const k of stale) delete next[k];
215
+ return next;
216
+ });
217
+ }, [config, landed]);
218
+
219
+ const value: Draft = { ...saved, ...draft };
220
+ const editedKeys = (Object.keys(draft) as Array<keyof Draft>).filter((k) => draft[k] !== saved[k]);
221
+ const tokenTyped = token.trim().length > 0;
222
+ const isDirty = editedKeys.length > 0 || tokenTyped;
223
+
224
+ const mapError = mapLineError(badMapLines(value.fixedMap));
225
+ const noAllowedFolders = parseLines(value.allowedRoots).length === 0;
226
+
227
+ function edit<K extends keyof Draft>(key: K) {
228
+ return (v: Draft[K]) => {
229
+ setNotice(null);
230
+ setDraft((d) => {
231
+ const next = { ...d };
232
+ if (v === saved[key]) delete next[key];
233
+ else next[key] = v;
234
+ return next;
235
+ });
236
+ };
237
+ }
238
+
239
+ // `refreshKey` re-reads the bindings after a successful commit.
240
+ // biome-ignore lint/correctness/useExhaustiveDependencies: refetch trigger only.
241
+ useEffect(() => {
242
+ let cancelled = false;
243
+ void (async () => {
244
+ try {
245
+ const res = await fetch("/api/chat-gateway/bindings");
246
+ if (!res.ok) return;
247
+ const body = (await res.json()) as BindingsResponse;
248
+ if (!cancelled) setBindings(body);
249
+ } catch {
250
+ /* unavailable until configured — leave the table hidden */
251
+ }
252
+ })();
253
+ return () => {
254
+ cancelled = true;
255
+ };
256
+ }, [refreshKey]);
257
+
258
+ async function commit(): Promise<void> {
259
+ if (mapError) throw new Error(INVALID_FIELDS);
260
+ const partial: Record<string, unknown> = {};
261
+ for (const key of editedKeys) partial[key] = (WIRE[key] as (v: unknown) => unknown)(value[key]);
262
+ // A blank token means "keep the stored secret" — never send it, so a save
263
+ // cannot erase the token by omission-through-the-form.
264
+ if (tokenTyped) partial.token = token.trim();
265
+ if (Object.keys(partial).length === 0) return;
266
+ setBusy(true);
267
+ try {
268
+ await send({ type: "plugin_config_write", id: "chat-gateway", config: partial });
269
+ } catch (err) {
270
+ const raw = err instanceof Error ? err.message : String(err);
271
+ setNotice({ details: scrubSecret(raw, token) });
272
+ // The host shows this message: a sentence, never the raw server text.
273
+ throw new Error(SAVE_FAILED);
274
+ } finally {
275
+ setBusy(false);
276
+ }
277
+ // Keep what was typed while the save was in flight: clear the token only if
278
+ // it is still the one sent, and leave edited keys to the prune effect above,
279
+ // which drops each once the stored config matches it (no revert-to-old flash).
280
+ const sentToken = partial.token;
281
+ setToken((t) => (t.trim() === sentToken ? "" : t));
282
+ const sent: Partial<Draft> = {};
283
+ for (const key of editedKeys) (sent as Record<string, unknown>)[key] = value[key];
284
+ setLanded((l) => ({ ...l, ...sent }));
285
+ setNotice(null);
286
+ setRefreshKey((k) => k + 1);
287
+ }
288
+
289
+ function reset(): void {
290
+ setToken("");
291
+ setDraft({});
292
+ setNotice(null);
293
+ }
294
+
295
+ useSettingsDraftSource({ id: "plugin:chat-gateway", isDirty, commit, reset });
296
+
297
+ const configured = bindings !== null;
298
+ return (
299
+ <div className="space-y-3" data-testid="chat-gateway-settings">
300
+ <div className="flex flex-wrap items-center gap-2">
301
+ <GatewayStatus bindings={bindings} enabled={saved.enabled} />
302
+ </div>
303
+ <p className="text-xs text-[var(--text-secondary)]">Drive dashboard sessions from Discord.</p>
304
+
305
+ {notice && (
306
+ <SettingsNotice
307
+ tone="error"
308
+ testId="chat-gateway-notice"
309
+ onRetry={() => void commit().catch(() => {})}
310
+ retrying={busy}
311
+ details={notice.details}
312
+ >
313
+ {SAVE_FAILED}
314
+ </SettingsNotice>
315
+ )}
316
+
317
+ <SettingsGroup title="Discord connection" testId="chat-gateway-group-connection">
318
+ <ToggleField
319
+ label="Answer Discord messages"
320
+ hint="Turn off to pause the gateway without losing its settings."
321
+ value={value.enabled}
322
+ onChange={edit("enabled")}
323
+ testIds={{ control: "chat-gateway-enabled" }}
324
+ />
325
+ <TextField
326
+ label="Bot token"
327
+ type="password"
328
+ autoComplete="off"
329
+ hint={
330
+ configured
331
+ ? "A token is saved. Paste a new one to replace it."
332
+ : "Create a bot in the Discord developer portal and paste its token. Without it the gateway does nothing."
333
+ }
334
+ placeholder={configured ? "•••••••• saved" : "Paste bot token"}
335
+ value={token}
336
+ onChange={(v) => {
337
+ setNotice(null);
338
+ setToken(v);
339
+ }}
340
+ testIds={{ control: "chat-gateway-token" }}
341
+ />
342
+ </SettingsGroup>
343
+
344
+ <SettingsGroup title="Where sessions run" testId="chat-gateway-group-where">
345
+ {noAllowedFolders && (
346
+ <SettingsNotice tone="warning" testId="chat-gateway-allowed-roots-warning">
347
+ No allowed folders yet, so no session can start. Add at least one folder.
348
+ </SettingsNotice>
349
+ )}
350
+ <TextAreaField
351
+ label="Allowed folders"
352
+ hint="One folder per line. Every new session's folder must be inside one of these. Required."
353
+ placeholder="/Users/you/Projects"
354
+ rows={3}
355
+ mono
356
+ value={value.allowedRoots}
357
+ onChange={edit("allowedRoots")}
358
+ testIds={{ control: "chat-gateway-allowed-roots" }}
359
+ />
360
+ <TextField
361
+ label="Default folder"
362
+ hint="Used when a channel has no folder below. Must be inside an allowed folder."
363
+ placeholder="/Users/you/Projects/app"
364
+ mono
365
+ value={value.defaultCwd}
366
+ onChange={edit("defaultCwd")}
367
+ testIds={{ control: "chat-gateway-default-cwd" }}
368
+ />
369
+ <TextAreaField
370
+ label="Channel folders"
371
+ hint={
372
+ <>
373
+ One <code>channelKey=folder</code> per line. Pins a channel to a folder.
374
+ </>
375
+ }
376
+ placeholder="discord:123456789:-=/repos/proj"
377
+ rows={3}
378
+ mono
379
+ value={value.fixedMap}
380
+ onChange={edit("fixedMap")}
381
+ error={mapError}
382
+ testIds={{ control: "chat-gateway-fixed-map", error: "chat-gateway-fixed-map-error" }}
383
+ />
384
+ </SettingsGroup>
385
+
386
+ <SettingsGroup title="Who can use it" defaultOpen={false} testId="chat-gateway-group-access">
387
+ <TextField
388
+ label="Allowed users"
389
+ hint="Discord user ids, comma-separated. They can talk to sessions in direct messages."
390
+ placeholder="123456789012345678"
391
+ mono
392
+ value={value.allowlist}
393
+ onChange={edit("allowlist")}
394
+ testIds={{ control: "chat-gateway-allowlist" }}
395
+ />
396
+ <TextField
397
+ label="Admins"
398
+ hint="Can also bind channels to sessions."
399
+ mono
400
+ value={value.admins}
401
+ onChange={edit("admins")}
402
+ testIds={{ control: "chat-gateway-admins" }}
403
+ />
404
+ <TextField
405
+ label="Group channels"
406
+ hint="Channel ids where the bot answers everyone, not only allowed users."
407
+ mono
408
+ value={value.groupChannels}
409
+ onChange={edit("groupChannels")}
410
+ testIds={{ control: "chat-gateway-group-channels" }}
411
+ />
412
+ </SettingsGroup>
413
+
414
+ <SettingsGroup title="Behaviour" defaultOpen={false} testId="chat-gateway-group-behaviour">
415
+ <ToggleField
416
+ label="New thread per conversation"
417
+ hint="A new channel message starts a new thread and a new session."
418
+ value={value.threadPerConversation}
419
+ onChange={edit("threadPerConversation")}
420
+ testIds={{ control: "chat-gateway-thread-per-conversation" }}
421
+ />
422
+ <ToggleField
423
+ label="Mirror dashboard sessions"
424
+ hint="Every dashboard session gets its own Discord thread and sends its activity there."
425
+ value={value.mirrorDashboardSessions}
426
+ onChange={edit("mirrorDashboardSessions")}
427
+ testIds={{ control: "chat-gateway-mirror-dashboard-sessions" }}
428
+ />
429
+ <TextField
430
+ label="Steer prefix"
431
+ hint="Start a message with this to interrupt a running turn."
432
+ mono
433
+ value={value.steerPrefix}
434
+ onChange={edit("steerPrefix")}
435
+ testIds={{ control: "chat-gateway-steer-prefix" }}
436
+ />
437
+ <SelectField
438
+ label="Chat sessions on the board"
439
+ hint="Hidden sessions appear when “Show hidden” is on."
440
+ value={value.sessionVisibility}
441
+ options={[
442
+ { value: "hidden", label: "Hidden" },
443
+ { value: "shown", label: "Shown" },
444
+ ]}
445
+ onChange={(v) => edit("sessionVisibility")(v as Draft["sessionVisibility"])}
446
+ testIds={{ control: "chat-gateway-session-visibility" }}
447
+ />
448
+ </SettingsGroup>
449
+
450
+ <SettingsNotice tone="info" testId="chat-gateway-pairing-hint">
451
+ Pairing: a direct message from an unknown user is accepted only when it contains the current pairing
452
+ code. The code is printed in the server log when the gateway starts.
453
+ </SettingsNotice>
454
+
455
+ <SettingsGroup
456
+ title="Bound channels"
457
+ meta={bindings && bindings.bindings.length > 0 ? String(bindings.bindings.length) : undefined}
458
+ testId="chat-gateway-group-bindings"
459
+ >
460
+ {bindings && bindings.bindings.length > 0 ? (
461
+ <SettingsTable
462
+ testId="chat-gateway-bindings"
463
+ caption="Bound channels"
464
+ columns={["Channel", "Session", "Folder", "Source"]}
465
+ rows={bindings.bindings.map((b) => ({
466
+ key: `${b.platform}:${b.channelId}:${b.threadId ?? "-"}`,
467
+ cells: [
468
+ <span key="c" className="break-all">
469
+ {b.channelId}
470
+ </span>,
471
+ <span key="s" className="break-all">
472
+ {b.sessionId}
473
+ </span>,
474
+ <code key="f" className="break-all">
475
+ {b.cwd}
476
+ </code>,
477
+ b.source,
478
+ ],
479
+ }))}
480
+ />
481
+ ) : (
482
+ <p data-testid="chat-gateway-bindings-empty" className="text-xs text-[var(--text-secondary)]">
483
+ {bindings
484
+ ? "No channels are bound yet. They appear here once the gateway is running."
485
+ : "Bound channels appear here once the gateway is set up and running."}
486
+ </p>
487
+ )}
488
+ </SettingsGroup>
489
+
490
+ <TeamControlsPanel />
491
+ </div>
492
+ );
493
+ }