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