@narumitw/pi-notify 0.2.0 → 0.3.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/src/menu.ts CHANGED
@@ -2,6 +2,13 @@ import { randomUUID } from "node:crypto";
2
2
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
3
3
  import { defineMenu, runMenu, runSecretInput, runTask } from "@narumitw/pi-tui-kit";
4
4
  import type { Coordinator } from "./coordinator.js";
5
+ import {
6
+ credentialLabels,
7
+ destinationDescription,
8
+ destinationLines,
9
+ displayServerUrl,
10
+ providerLabel,
11
+ } from "./destination-ui.js";
5
12
  import { displayPath, notificationMetadata, safeText } from "./metadata.js";
6
13
  import type { Destination, Notification, Providers } from "./provider.js";
7
14
  import {
@@ -19,6 +26,7 @@ import {
19
26
  type Screen =
20
27
  | "main"
21
28
  | "destinations"
29
+ | "addDestination"
22
30
  | "destination"
23
31
  | "settings"
24
32
  | "targets"
@@ -27,6 +35,9 @@ type Screen =
27
35
  | "label"
28
36
  | "chat"
29
37
  | "topic"
38
+ | "serverUrl"
39
+ | "priority"
40
+ | "ntfyTopic"
30
41
  | "review"
31
42
  | "remove"
32
43
  | "testSelect"
@@ -41,12 +52,24 @@ type Action =
41
52
  | "target"
42
53
  | "inheritTargets"
43
54
  | "add"
55
+ | "addGotify"
56
+ | "addSlack"
57
+ | "addNtfy"
58
+ | "addPushover"
59
+ | "addDiscord"
60
+ | "addBark"
61
+ | "addWebhook"
62
+ | "userKey"
63
+ | "bearerToken"
64
+ | "ntfyTopic"
44
65
  | "edit"
45
66
  | "select"
46
67
  | "token"
47
68
  | "label"
48
69
  | "chat"
49
70
  | "topic"
71
+ | "serverUrl"
72
+ | "priority"
50
73
  | "save"
51
74
  | "saveOnly"
52
75
  | "remove"
@@ -66,15 +89,25 @@ export interface MenuOptions {
66
89
  export const helpLines = [
67
90
  "Create a bot with @BotFather in Telegram, then start a private conversation or add it to your group with permission to send messages.",
68
91
  "Obtain the numeric chat ID from Telegram Bot API getUpdates after sending a message. Do not share or paste the token into Pi chat. Stop other update consumers before using getUpdates; this extension does not poll.",
69
- "Setup needs only a bot token and chat ID. Labels are generated automatically. Edit the label or optional forum topic ID from the destination review.",
92
+ "Telegram setup needs a bot token and chat ID. Labels are generated automatically. Edit the label or optional forum topic ID from the destination review.",
93
+ "For Gotify, create an application on your server and use its application token, not a client token. Enter the server base URL, including any reverse-proxy path. Prefer HTTPS; HTTP sends credentials without encryption.",
94
+ "Gotify labels are generated automatically. Edit the label or optional safe-integer priority from the destination review. An empty priority uses the server default.",
95
+ "For Slack, enable Incoming Webhooks in a Slack app and add a webhook to your workspace. Its installation fixes the channel. Paste the complete hooks.slack.com URL only into the masked field; never into Pi chat.",
96
+ "Slack webhook URLs are secrets. Reviews and Status show only that a webhook is configured. Revoke an exposed webhook in the Slack app before replacing it.",
97
+ "For ntfy, subscribe to a topic and configure server authentication and topic permissions. Topic secrecy is not access control. Review the server, optional Bearer token, and priority from 1 to 5.",
98
+ "For Pushover, enter the application token and user key in masked inputs. Delivery uses normal priority only, without emergency acknowledgement or retries.",
99
+ "For Discord, paste a normal text-channel webhook URL into the masked input. Mentions and link embeds are disabled; forum/media channels and thread selection are not supported.",
100
+ "For Bark, enter the device key in the masked input and review the hosted or self-hosted server base. JSON delivery keeps the key and message out of URLs, not server body logs. Native Basic authentication is not supported.",
101
+ "For Generic webhooks, enter the endpoint in the masked input and set an optional Bearer token in review. The fixed JSON payload has id, title, body, and settledAt (Unix milliseconds); no templates or custom headers.",
102
+ "Self-hosted ntfy, Bark, and Generic endpoints can reach private networks. Prefer HTTPS; HTTP sends credentials and metadata without encryption. See the bundled docs/settings.md for setup and revocation.",
70
103
  "Use a negative group/supergroup chat ID when applicable. Forum topic IDs are optional positive integers.",
71
104
  "Destinations are User settings only. Project settings require trust and may select existing destinations but cannot change credentials or addresses.",
72
105
  "Notifications disclose hostname, session name/ID, workspace and Git metadata, elapsed time and timestamp. No conversation or code is sent.",
73
106
  "Inactivity uses only input Pi forwards to this extension. Fullscreen focus, mouse, and viewport/search keys can be consumed first and do not reliably cancel reminders. Reading without typing can still trigger a notification.",
74
107
  "Input or new work cancels a pending reminder. Saved policy/destination changes cancel pending reminders. Settings save immediately; closing does not undo them.",
75
108
  "RPC/print/JSON cannot observe terminal activity and deliver at settlement instead. Short-lived processes can exit before delivery completes.",
76
- "Delivery is best effort, one attempt, with no automatic retries or history replay. Accepted means Telegram accepted the message, not that it was read.",
77
- "Manual file changes require /reload or session start. Repair malformed files before saving. Revoke exposed tokens through BotFather.",
109
+ "Delivery is best effort, one attempt, with no automatic retries or history replay. Accepted means the provider accepted the message, not that it was read.",
110
+ "Manual file changes require /reload or session start. Repair malformed files before saving. Revoke exposed Telegram tokens through BotFather or Gotify application tokens on your server.",
78
111
  ];
79
112
 
80
113
  export async function showNotifyMenu(ctx: ExtensionCommandContext, options: MenuOptions) {
@@ -111,22 +144,63 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
111
144
  if (!draft) throw new Error("Destination draft is unavailable.");
112
145
  return draft;
113
146
  };
147
+ const telegramDraft = () => {
148
+ const destination = assertDraft();
149
+ if (destination.provider !== "telegram") throw new Error("Not a Telegram destination.");
150
+ return destination;
151
+ };
152
+ const ntfyDraft = () => {
153
+ const destination = assertDraft();
154
+ if (destination.provider !== "ntfy") throw new Error("Not an ntfy destination.");
155
+ return destination;
156
+ };
157
+ const serverDraft = () => {
158
+ const destination = assertDraft();
159
+ if (destination.provider !== "gotify" && destination.provider !== "ntfy" && destination.provider !== "bark")
160
+ throw new Error("Not a server destination.");
161
+ return destination;
162
+ };
163
+ const priorityDraft = () => {
164
+ const destination = serverDraft();
165
+ if (destination.provider === "bark") throw new Error("Priority is unavailable.");
166
+ return destination;
167
+ };
168
+ const reportError = () => {
169
+ if (isCurrent())
170
+ ctx.ui.notify(
171
+ "Notify operation failed. Check the input, settings file, and Project selections. No credential values are shown.",
172
+ "error",
173
+ );
174
+ };
114
175
  const saveDraft = async (actionSignal: AbortSignal, selectNew: boolean) => {
115
- const destination = providers.get("telegram")?.validate(assertDraft());
116
- if (!destination) throw new Error("Invalid Telegram destination. Check the bot token and chat ID.");
176
+ const value = assertDraft();
177
+ const destination = providers.get(value.provider)?.validate(value);
178
+ if (!destination) throw new Error("Invalid destination settings. Check the required fields.");
117
179
  await apply(saveDestination(store, selectedId, destination, actionSignal, selectNew));
118
180
  draft = undefined;
119
181
  return { kind: "to", screen: "main" } as const;
120
182
  };
121
- const draftLines = () =>
122
- draft
123
- ? [
124
- `Label: ${safeText(draft.label)}`,
125
- `Chat: ${safeText(draft.chatId)}`,
126
- `Topic: ${draft.messageThreadId ?? "none"}`,
127
- "Bot token: configured (hidden)",
128
- ]
129
- : ["No destination draft."];
183
+ const addWebhook = async (provider: "discord" | "webhook", actionSignal: AbortSignal) => {
184
+ const result = await runSecretInput(menuCtx, {
185
+ title: `${provider === "discord" ? "Discord" : "Generic webhook"} URL`,
186
+ signal: actionSignal,
187
+ isCurrent,
188
+ onError: reportError,
189
+ });
190
+ actionSignal.throwIfAborted();
191
+ current();
192
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" } as const;
193
+ if (result.kind !== "submitted") return { kind: "stay" } as const;
194
+ const destination = providers.get(provider)?.validate({
195
+ provider,
196
+ label: provider === "discord" ? "Discord notifications" : "Generic webhook notifications",
197
+ webhookUrl: result.value,
198
+ });
199
+ if (!destination) throw new Error("Use a valid webhook URL.");
200
+ selectedId = randomUUID();
201
+ draft = destination;
202
+ return { kind: "to", screen: "review" } as const;
203
+ };
130
204
  const menu = defineMenu<State, Screen, Action>({
131
205
  start: "main",
132
206
  screens: {
@@ -140,8 +214,8 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
140
214
  ...state.snapshot.diagnostics,
141
215
  ],
142
216
  items: [
143
- { id: "destinations", label: "Telegram destinations", to: "destinations" },
144
- { id: "test", label: "Send test to Telegram…", to: "testSelect" },
217
+ { id: "destinations", label: "Destinations", to: "destinations" },
218
+ { id: "test", label: "Send test…", to: "testSelect" },
145
219
  { id: "settings", label: "Settings", to: "settings" },
146
220
  { id: "status", label: "Status", to: "status" },
147
221
  { id: "help", label: "Help", to: "help" },
@@ -150,25 +224,36 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
150
224
  }),
151
225
  destinations: ({ state }) => ({
152
226
  kind: "actions",
153
- title: "Telegram destinations · User",
227
+ title: "Destinations · User",
154
228
  items: [
155
229
  ...Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
156
- id,
230
+ // Stored IDs cannot contain ':', so rows cannot shadow the add actions.
231
+ id: `destination:${id}`,
157
232
  label: safeText(value.label),
158
- description: `Telegram · ${safeText(value.chatId)} · token configured`,
233
+ description: destinationDescription(value),
159
234
  action: "select" as const,
160
235
  })),
236
+ { id: "add:destination", label: "Add destination…", to: "addDestination" },
237
+ ],
238
+ }),
239
+ addDestination: () => ({
240
+ kind: "actions",
241
+ title: "Add destination · User",
242
+ items: [
161
243
  { id: "add", label: "Add Telegram destination", action: "add" },
244
+ { id: "addGotify", label: "Add Gotify destination", action: "addGotify" },
245
+ { id: "addSlack", label: "Add Slack destination", action: "addSlack" },
246
+ { id: "addNtfy", label: "Add ntfy destination", action: "addNtfy" },
247
+ { id: "addPushover", label: "Add Pushover destination", action: "addPushover" },
248
+ { id: "addDiscord", label: "Add Discord destination", action: "addDiscord" },
249
+ { id: "addBark", label: "Add Bark destination", action: "addBark" },
250
+ { id: "addWebhook", label: "Add Generic webhook destination", action: "addWebhook" },
162
251
  ],
163
252
  }),
164
253
  destination: () => ({
165
254
  kind: "actions",
166
- title: "Telegram destination · User",
167
- lines: [
168
- `Label: ${safeText(knownDestination().label)}`,
169
- `Chat: ${safeText(knownDestination().chatId)}`,
170
- "Bot token: configured (hidden)",
171
- ],
255
+ title: `${providerLabel(knownDestination())} destination · User`,
256
+ lines: destinationLines(knownDestination()),
172
257
  items: [
173
258
  { id: "edit", label: "Edit destination", action: "edit" },
174
259
  { id: "remove", label: "Remove destination…", to: "remove" },
@@ -223,7 +308,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
223
308
  label: "Send notifications to",
224
309
  currentValue: `${state.editing.targetIds.length}${inherited("targetIds") ? " (inherited)" : ""}`,
225
310
  action: "target",
226
- description: "Choose which saved Telegram chats receive notifications.",
311
+ description: "Choose which saved destinations receive notifications.",
227
312
  },
228
313
  ],
229
314
  };
@@ -234,14 +319,14 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
234
319
  items: Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
235
320
  id,
236
321
  label: safeText(value.label),
237
- description: safeText(value.chatId),
322
+ description: destinationDescription(value),
238
323
  selected: state.editing.targetIds.includes(id),
239
324
  })),
240
325
  action: "target",
241
326
  enableSearch: true,
242
327
  actions:
243
328
  scope === "project"
244
- ? [{ id: "inherit", label: "Restore inherited selection", action: "inheritTargets" }]
329
+ ? [{ id: "inherit:targets", label: "Restore inherited selection", action: "inheritTargets" }]
245
330
  : [],
246
331
  }),
247
332
  delay: () => ({
@@ -265,7 +350,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
265
350
  }),
266
351
  label: () => ({
267
352
  kind: "input",
268
- title: "Telegram destination label",
353
+ title: `${providerLabel(assertDraft())} destination label`,
269
354
  initialValue: assertDraft().label,
270
355
  action: "label",
271
356
  }),
@@ -273,27 +358,52 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
273
358
  kind: "input",
274
359
  title: "Telegram chat ID",
275
360
  lines: ["Numeric private chat, group, or supergroup ID. Group IDs can be negative."],
276
- initialValue: assertDraft().chatId,
361
+ initialValue: telegramDraft().chatId,
277
362
  action: "chat",
278
363
  }),
279
364
  topic: () => ({
280
365
  kind: "input",
281
366
  title: "Forum topic ID (optional)",
282
367
  lines: ["Leave empty for no topic."],
283
- initialValue: String(assertDraft().messageThreadId ?? ""),
368
+ initialValue: String(telegramDraft().messageThreadId ?? ""),
284
369
  action: "topic",
285
370
  }),
371
+ ntfyTopic: () => ({
372
+ kind: "input",
373
+ title: "ntfy topic",
374
+ lines: ["A topic name is not access control. Configure server authentication and topic permissions."],
375
+ initialValue: ntfyDraft().topic,
376
+ action: "ntfyTopic",
377
+ }),
378
+ serverUrl: () => ({
379
+ kind: "input",
380
+ title: `${providerLabel(serverDraft())} server URL`,
381
+ lines: ["HTTP(S) base URL with an optional reverse-proxy path. No credentials, query, or fragment."],
382
+ initialValue: serverDraft().serverUrl,
383
+ action: "serverUrl",
384
+ }),
385
+ priority: () => ({
386
+ kind: "input",
387
+ title: `${providerLabel(priorityDraft())} priority (optional)`,
388
+ lines: [
389
+ priorityDraft().provider === "ntfy"
390
+ ? "Integer from 1 to 5. Leave empty for the server default."
391
+ : "Safe integer from -9007199254740991 to 9007199254740991. Leave empty for the server default.",
392
+ ],
393
+ initialValue: String(priorityDraft().priority ?? ""),
394
+ action: "priority",
395
+ }),
286
396
  review: () => ({
287
397
  kind: "actions",
288
- title: "Review Telegram destination · User",
398
+ title: `Review ${providerLabel(assertDraft())} destination · User`,
289
399
  lines: [
290
- ...draftLines(),
400
+ ...destinationLines(assertDraft()),
291
401
  ...(store.snapshot.effective.destinations[selectedId]
292
402
  ? ["Save keeps your current notification selection."]
293
403
  : [
294
- "Use this chat for notifications?",
295
- "Save and use: save this chat and select it for User notifications.",
296
- "Save only: save this chat without selecting it.",
404
+ "Use this destination for notifications?",
405
+ "Save and use: save this destination and select it for User notifications.",
406
+ "Save only: save this destination without selecting it.",
297
407
  ]),
298
408
  "Automatic notifications default to On. Saved Off settings and Project choices are unchanged.",
299
409
  ],
@@ -303,10 +413,35 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
303
413
  label: store.snapshot.effective.destinations[selectedId] ? "Save changes" : "Save and use",
304
414
  action: "save",
305
415
  },
306
- { id: "token", label: "Replace bot token…", action: "token" },
307
- { id: "chat", label: "Change chat ID…", to: "chat" },
416
+ {
417
+ id: "token",
418
+ label: `Replace ${credentialLabels[assertDraft().provider]}…`,
419
+ action: "token",
420
+ },
421
+ ...(assertDraft().provider === "telegram"
422
+ ? [{ id: "chat", label: "Change chat ID…", to: "chat" as const }]
423
+ : []),
424
+ ...(assertDraft().provider === "gotify" ||
425
+ assertDraft().provider === "ntfy" ||
426
+ assertDraft().provider === "bark"
427
+ ? [{ id: "serverUrl", label: "Change server URL…", to: "serverUrl" as const }]
428
+ : []),
429
+ ...(assertDraft().provider === "pushover"
430
+ ? [{ id: "userKey", label: "Replace user key…", action: "userKey" as const }]
431
+ : []),
308
432
  { id: "label", label: "Change label…", to: "label" },
309
- { id: "topic", label: "Set forum topic ID…", to: "topic" },
433
+ ...(assertDraft().provider === "webhook"
434
+ ? [{ id: "bearerToken", label: "Set Bearer token (empty for none)…", action: "bearerToken" as const }]
435
+ : []),
436
+ ...(assertDraft().provider === "telegram"
437
+ ? [{ id: "topic", label: "Set forum topic ID…", to: "topic" as const }]
438
+ : []),
439
+ ...(assertDraft().provider === "ntfy"
440
+ ? [{ id: "ntfyTopic", label: "Change topic…", to: "ntfyTopic" as const }]
441
+ : []),
442
+ ...(assertDraft().provider === "gotify" || assertDraft().provider === "ntfy"
443
+ ? [{ id: "priority", label: "Set priority…", to: "priority" as const }]
444
+ : []),
310
445
  ...(!store.snapshot.effective.destinations[selectedId]
311
446
  ? [{ id: "saveOnly", label: "Save only", action: "saveOnly" as const }]
312
447
  : []),
@@ -314,7 +449,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
314
449
  }),
315
450
  remove: () => ({
316
451
  kind: "actions",
317
- title: "Remove Telegram destination?",
452
+ title: `Remove ${providerLabel(knownDestination())} destination?`,
318
453
  lines: [
319
454
  safeText(knownDestination().label),
320
455
  "Also removes its User selection. Existing messages are not recalled.",
@@ -328,15 +463,21 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
328
463
  items: Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
329
464
  id,
330
465
  label: safeText(value.label),
466
+ description: destinationDescription(value),
331
467
  action: "prepareTest" as const,
332
468
  })),
333
469
  }),
334
470
  testReview: () => ({
335
471
  kind: "review",
336
- title: `Send test to ${safeText(testDestination?.label ?? "Telegram")}?`,
472
+ title: `Send test to ${safeText(testDestination?.label ?? "destination")}?`,
473
+ lines: testDestination ? [destinationDescription(testDestination)] : [],
337
474
  content: `${testNotification?.title ?? ""}\n${testNotification?.body ?? ""}`,
338
475
  viewportSize: "adaptive",
339
- confirm: { id: "send", label: "Send test to Telegram", action: "sendTest" },
476
+ confirm: {
477
+ id: "send",
478
+ label: `Send test to ${testDestination ? providerLabel(testDestination) : "destination"}`,
479
+ action: "sendTest",
480
+ },
340
481
  }),
341
482
  status: ({ state }) => ({
342
483
  kind: "detail",
@@ -351,7 +492,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
351
492
  `Pending reminder: ${coordinator.pendingAt ? new Date(coordinator.pendingAt).toISOString() : "none"}`,
352
493
  ...Object.entries(state.snapshot.effective.destinations).map(([id, value]) => {
353
494
  const result = coordinator.statuses.get(id)?.result;
354
- return `${safeText(value.label)} · ${state.snapshot.effective.targetIds.includes(id) ? "selected" : "not selected"} · token configured (User) · ${result ? (result.state === "failed" ? `${result.code}${result.retryAfterSeconds ? `; retry after ${result.retryAfterSeconds}s (not automatic)` : ""}` : result.state) : "no delivery"}`;
495
+ return `${safeText(value.label)} · ${destinationDescription(value)} (User) · ${state.snapshot.effective.targetIds.includes(id) ? "selected" : "not selected"} · ${result ? (result.state === "failed" ? `${result.code}${result.retryAfterSeconds ? `; retry after ${result.retryAfterSeconds}s (not automatic)` : ""}` : result.state) : "no delivery"}`;
355
496
  }),
356
497
  ...state.snapshot.diagnostics,
357
498
  ],
@@ -420,11 +561,16 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
420
561
  return { kind: "stay" };
421
562
  },
422
563
  select: ({ itemId }) => {
423
- selectedId = itemId;
564
+ selectedId = itemId.slice("destination:".length);
424
565
  return { kind: "to", screen: "destination" };
425
566
  },
426
567
  add: async ({ signal: actionSignal }) => {
427
- const result = await runSecretInput(menuCtx, { title: "Telegram bot token", signal: actionSignal, isCurrent });
568
+ const result = await runSecretInput(menuCtx, {
569
+ title: "Telegram bot token",
570
+ signal: actionSignal,
571
+ isCurrent,
572
+ onError: reportError,
573
+ });
428
574
  actionSignal.throwIfAborted();
429
575
  current();
430
576
  if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
@@ -433,19 +579,209 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
433
579
  draft = { provider: "telegram", label: "", botToken: result.value.trim(), chatId: "" };
434
580
  return { kind: "to", screen: "chat" };
435
581
  },
582
+ addGotify: async ({ signal: actionSignal }) => {
583
+ const result = await runSecretInput(menuCtx, {
584
+ title: "Gotify application token",
585
+ signal: actionSignal,
586
+ isCurrent,
587
+ onError: reportError,
588
+ });
589
+ actionSignal.throwIfAborted();
590
+ current();
591
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
592
+ if (result.kind !== "submitted") return { kind: "stay" };
593
+ selectedId = randomUUID();
594
+ draft = { provider: "gotify", label: "", appToken: result.value.trim(), serverUrl: "" };
595
+ return { kind: "to", screen: "serverUrl" };
596
+ },
597
+ addSlack: async ({ signal: actionSignal }) => {
598
+ const result = await runSecretInput(menuCtx, {
599
+ title: "Slack webhook URL",
600
+ signal: actionSignal,
601
+ isCurrent,
602
+ onError: reportError,
603
+ });
604
+ actionSignal.throwIfAborted();
605
+ current();
606
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
607
+ if (result.kind !== "submitted") return { kind: "stay" };
608
+ const destination = providers.get("slack")?.validate({
609
+ provider: "slack",
610
+ label: "Slack notifications",
611
+ webhookUrl: result.value,
612
+ });
613
+ if (destination?.provider !== "slack") throw new Error("Use a valid Slack Incoming Webhook URL.");
614
+ selectedId = randomUUID();
615
+ draft = destination;
616
+ return { kind: "to", screen: "review" };
617
+ },
618
+ addDiscord: ({ signal: actionSignal }) => addWebhook("discord", actionSignal),
619
+ addWebhook: ({ signal: actionSignal }) => addWebhook("webhook", actionSignal),
620
+ addBark: async ({ signal: actionSignal }) => {
621
+ const result = await runSecretInput(menuCtx, {
622
+ title: "Bark device key",
623
+ signal: actionSignal,
624
+ isCurrent,
625
+ onError: reportError,
626
+ });
627
+ actionSignal.throwIfAborted();
628
+ current();
629
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
630
+ if (result.kind !== "submitted") return { kind: "stay" };
631
+ const destination = providers.get("bark")?.validate({
632
+ provider: "bark",
633
+ label: "Bark notifications",
634
+ serverUrl: "https://api.day.app",
635
+ deviceKey: result.value.trim(),
636
+ });
637
+ if (!destination) throw new Error("Use a valid Bark device key.");
638
+ selectedId = randomUUID();
639
+ draft = destination;
640
+ return { kind: "to", screen: "review" };
641
+ },
642
+ addPushover: async ({ signal: actionSignal }) => {
643
+ const app = await runSecretInput(menuCtx, {
644
+ title: "Pushover application token",
645
+ signal: actionSignal,
646
+ isCurrent,
647
+ onError: reportError,
648
+ });
649
+ actionSignal.throwIfAborted();
650
+ current();
651
+ if (app.kind === "closed" && app.reason === "close") return { kind: "close" };
652
+ if (app.kind !== "submitted") return { kind: "stay" };
653
+ const user = await runSecretInput(menuCtx, {
654
+ title: "Pushover user key",
655
+ signal: actionSignal,
656
+ isCurrent,
657
+ onError: reportError,
658
+ });
659
+ actionSignal.throwIfAborted();
660
+ current();
661
+ if (user.kind === "closed" && user.reason === "close") return { kind: "close" };
662
+ if (user.kind !== "submitted") return { kind: "stay" };
663
+ const destination = providers.get("pushover")?.validate({
664
+ provider: "pushover",
665
+ label: "Pushover notifications",
666
+ appToken: app.value.trim(),
667
+ userKey: user.value.trim(),
668
+ });
669
+ if (!destination) throw new Error("Use a valid application token and user key.");
670
+ selectedId = randomUUID();
671
+ draft = destination;
672
+ return { kind: "to", screen: "review" };
673
+ },
674
+ userKey: async ({ signal: actionSignal }) => {
675
+ const result = await runSecretInput(menuCtx, {
676
+ title: "Replace Pushover user key",
677
+ signal: actionSignal,
678
+ isCurrent,
679
+ onError: reportError,
680
+ });
681
+ actionSignal.throwIfAborted();
682
+ current();
683
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
684
+ if (result.kind === "submitted") {
685
+ const destination = assertDraft();
686
+ const valid = providers.get("pushover")?.validate({ ...destination, userKey: result.value.trim() });
687
+ if (destination.provider !== "pushover" || valid?.provider !== "pushover")
688
+ throw new Error("Use a valid user key.");
689
+ destination.userKey = valid.userKey;
690
+ }
691
+ return { kind: "stay" };
692
+ },
693
+ bearerToken: async ({ signal: actionSignal }) => {
694
+ const result = await runSecretInput(menuCtx, {
695
+ title: "Bearer token (empty for none)",
696
+ required: false,
697
+ signal: actionSignal,
698
+ isCurrent,
699
+ onError: reportError,
700
+ });
701
+ actionSignal.throwIfAborted();
702
+ current();
703
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
704
+ if (result.kind === "submitted") {
705
+ const destination = assertDraft();
706
+ const valid = providers
707
+ .get("webhook")
708
+ ?.validate({ ...destination, bearerToken: result.value.trim() || undefined });
709
+ if (destination.provider !== "webhook" || valid?.provider !== "webhook")
710
+ throw new Error("Use a valid Bearer token or leave it empty.");
711
+ destination.bearerToken = valid.bearerToken;
712
+ }
713
+ return { kind: "stay" };
714
+ },
715
+ addNtfy: () => {
716
+ selectedId = randomUUID();
717
+ draft = { provider: "ntfy", label: "ntfy notifications", serverUrl: "https://ntfy.sh", topic: "" };
718
+ return { kind: "to", screen: "ntfyTopic" };
719
+ },
720
+ ntfyTopic: ({ value }) => {
721
+ const destination = assertDraft();
722
+ const valid = providers.get("ntfy")?.validate({ ...destination, topic: value?.trim() });
723
+ if (destination.provider !== "ntfy" || valid?.provider !== "ntfy") throw new Error("Use a valid ntfy topic.");
724
+ destination.topic = valid.topic;
725
+ return { kind: "to", screen: "review" };
726
+ },
436
727
  edit: () => {
437
728
  draft = { ...knownDestination() };
438
729
  return { kind: "to", screen: "review" };
439
730
  },
440
731
  token: async ({ signal: actionSignal }) => {
441
732
  const result = await runSecretInput(menuCtx, {
442
- title: "Replace Telegram bot token",
733
+ title: `Replace ${providerLabel(assertDraft())} ${credentialLabels[assertDraft().provider]}`,
734
+ required: assertDraft().provider !== "ntfy",
443
735
  signal: actionSignal,
444
736
  isCurrent,
737
+ onError: reportError,
445
738
  });
446
739
  actionSignal.throwIfAborted();
447
740
  current();
448
- if (result.kind === "submitted") assertDraft().botToken = result.value.trim();
741
+ if (result.kind === "submitted") {
742
+ const destination = assertDraft();
743
+ switch (destination.provider) {
744
+ case "telegram":
745
+ destination.botToken = result.value.trim();
746
+ break;
747
+ case "gotify":
748
+ destination.appToken = result.value.trim();
749
+ break;
750
+ case "pushover": {
751
+ const valid = providers.get("pushover")?.validate({ ...destination, appToken: result.value.trim() });
752
+ if (valid?.provider !== "pushover") throw new Error("Use a valid application token.");
753
+ destination.appToken = valid.appToken;
754
+ break;
755
+ }
756
+ case "bark": {
757
+ const valid = providers.get("bark")?.validate({ ...destination, deviceKey: result.value.trim() });
758
+ if (valid?.provider !== "bark") throw new Error("Use a valid device key.");
759
+ destination.deviceKey = valid.deviceKey;
760
+ break;
761
+ }
762
+ case "discord":
763
+ case "webhook": {
764
+ const valid = providers.get(destination.provider)?.validate({ ...destination, webhookUrl: result.value });
765
+ if (valid?.provider !== destination.provider) throw new Error("Use a valid webhook URL.");
766
+ destination.webhookUrl = valid.webhookUrl;
767
+ break;
768
+ }
769
+ case "ntfy": {
770
+ const valid = providers
771
+ .get("ntfy")
772
+ ?.validate({ ...destination, accessToken: result.value.trim() || undefined });
773
+ if (valid?.provider !== "ntfy") throw new Error("Use a valid access token or leave it empty.");
774
+ destination.accessToken = valid.accessToken;
775
+ break;
776
+ }
777
+ case "slack": {
778
+ const valid = providers.get("slack")?.validate({ ...destination, webhookUrl: result.value });
779
+ if (valid?.provider !== "slack") throw new Error("Use a valid Slack Incoming Webhook URL.");
780
+ destination.webhookUrl = valid.webhookUrl;
781
+ break;
782
+ }
783
+ }
784
+ }
449
785
  if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
450
786
  return { kind: "stay" };
451
787
  },
@@ -456,7 +792,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
456
792
  },
457
793
  chat: ({ value }) => {
458
794
  if (!value || !/^-?[1-9]\d{0,30}$/.test(value.trim())) throw new Error("Use a numeric Telegram chat ID.");
459
- const destination = assertDraft();
795
+ const destination = telegramDraft();
460
796
  destination.chatId = value.trim();
461
797
  if (!destination.label) destination.label = `Telegram ${destination.chatId}`;
462
798
  return { kind: "to", screen: "review" };
@@ -465,8 +801,35 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
465
801
  const topic = value?.trim();
466
802
  if (topic && (!/^\d+$/.test(topic) || !Number.isSafeInteger(Number(topic)) || Number(topic) <= 0))
467
803
  throw new Error("Use a positive whole topic ID or leave it empty.");
468
- if (topic) assertDraft().messageThreadId = Number(topic);
469
- else delete assertDraft().messageThreadId;
804
+ if (topic) telegramDraft().messageThreadId = Number(topic);
805
+ else delete telegramDraft().messageThreadId;
806
+ return { kind: "to", screen: "review" };
807
+ },
808
+ serverUrl: ({ value }) => {
809
+ const destination = serverDraft();
810
+ const normalized = providers.get(destination.provider)?.validate({
811
+ ...destination,
812
+ label: destination.label || "Gotify",
813
+ serverUrl: value?.trim(),
814
+ });
815
+ if (
816
+ !normalized ||
817
+ (normalized.provider !== "gotify" && normalized.provider !== "ntfy" && normalized.provider !== "bark")
818
+ )
819
+ throw new Error("Use a valid server URL and credentials. No URL credentials, query, or fragment.");
820
+ destination.serverUrl = normalized.serverUrl;
821
+ if (!destination.label) destination.label = `Gotify ${displayServerUrl(destination.serverUrl)}`.slice(0, 128);
822
+ return { kind: "to", screen: "review" };
823
+ },
824
+ priority: ({ value }) => {
825
+ const priority = value?.trim();
826
+ if (priority && (!/^-?\d+$/.test(priority) || !Number.isSafeInteger(Number(priority))))
827
+ throw new Error("Use a safe-integer priority or leave it empty.");
828
+ const destination = priorityDraft();
829
+ if (priority && destination.provider === "ntfy" && (Number(priority) < 1 || Number(priority) > 5))
830
+ throw new Error("Use a priority from 1 to 5.");
831
+ if (priority) destination.priority = Number(priority);
832
+ else delete destination.priority;
470
833
  return { kind: "to", screen: "review" };
471
834
  },
472
835
  save: ({ signal: actionSignal }) => saveDraft(actionSignal, true),
@@ -502,9 +865,10 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
502
865
  const destination = testDestination;
503
866
  const notification = testNotification;
504
867
  const result = await runTask(menuCtx, {
505
- label: "Sending Telegram test…",
868
+ label: `Sending ${providerLabel(destination)} test…`,
506
869
  signal: actionSignal,
507
870
  isCurrent,
871
+ onError: reportError,
508
872
  task: ({ signal: taskSignal }) => coordinator.send(selectedId, destination, notification, taskSignal),
509
873
  });
510
874
  actionSignal.throwIfAborted();
@@ -512,8 +876,8 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
512
876
  if (result.kind === "completed")
513
877
  ctx.ui.notify(
514
878
  result.value.state === "accepted"
515
- ? "Telegram accepted the test notification."
516
- : `Telegram test: ${result.value.state === "failed" ? result.value.code : result.value.state}.`,
879
+ ? `${providerLabel(destination)} accepted the test notification.`
880
+ : `${providerLabel(destination)} test: ${result.value.state === "failed" ? result.value.code : result.value.state}.`,
517
881
  result.value.state === "accepted" ? "info" : "warning",
518
882
  );
519
883
  if (result.kind === "cancelled") return { kind: "close" };
@@ -530,13 +894,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
530
894
  editing: resolveSettings(store.snapshot.user, scope === "project" ? store.snapshot.project : {}, providers)
531
895
  .effective,
532
896
  }),
533
- onError: () => {
534
- if (isCurrent())
535
- ctx.ui.notify(
536
- "Notify operation failed. Check the input, settings file, and Project selections. No credential values are shown.",
537
- "error",
538
- );
539
- },
897
+ onError: reportError,
540
898
  });
541
899
  } finally {
542
900
  draft = undefined;