@narumitw/pi-notify 0.2.0 → 0.4.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,27 @@ 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
+ | "addTeams"
63
+ | "addLine"
64
+ | "recipientId"
65
+ | "userKey"
66
+ | "bearerToken"
67
+ | "ntfyTopic"
44
68
  | "edit"
45
69
  | "select"
46
70
  | "token"
47
71
  | "label"
48
72
  | "chat"
49
73
  | "topic"
74
+ | "serverUrl"
75
+ | "priority"
50
76
  | "save"
51
77
  | "saveOnly"
52
78
  | "remove"
@@ -66,15 +92,27 @@ export interface MenuOptions {
66
92
  export const helpLines = [
67
93
  "Create a bot with @BotFather in Telegram, then start a private conversation or add it to your group with permission to send messages.",
68
94
  "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.",
95
+ "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.",
96
+ "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.",
97
+ "Gotify labels are generated automatically. Edit the label or optional safe-integer priority from the destination review. An empty priority uses the server default.",
98
+ "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.",
99
+ "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.",
100
+ "For Microsoft Teams, create a Workflows webhook with Anyone authentication. Enter its complete current signed URL only in the masked field. The workflow owns its target. HTTP 202 means trigger acceptance, not proof of a Teams post; live interoperability is not yet verified. See docs/settings.md for supported URLs, setup, and revocation.",
101
+ "For LINE, enable Messaging API on an Official Account and enter its channel access token and user/group/room ID in masked inputs. Recipient eligibility and account quotas apply. LINE Notify is not supported. See docs/settings.md for setup and revocation.",
102
+ "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.",
103
+ "For Pushover, enter the application token and user key in masked inputs. Delivery uses normal priority only, without emergency acknowledgement or retries.",
104
+ "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.",
105
+ "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.",
106
+ "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.",
107
+ "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
108
  "Use a negative group/supergroup chat ID when applicable. Forum topic IDs are optional positive integers.",
71
109
  "Destinations are User settings only. Project settings require trust and may select existing destinations but cannot change credentials or addresses.",
72
110
  "Notifications disclose hostname, session name/ID, workspace and Git metadata, elapsed time and timestamp. No conversation or code is sent.",
73
111
  "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
112
  "Input or new work cancels a pending reminder. Saved policy/destination changes cancel pending reminders. Settings save immediately; closing does not undo them.",
75
113
  "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.",
114
+ "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.",
115
+ "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
116
  ];
79
117
 
80
118
  export async function showNotifyMenu(ctx: ExtensionCommandContext, options: MenuOptions) {
@@ -111,22 +149,71 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
111
149
  if (!draft) throw new Error("Destination draft is unavailable.");
112
150
  return draft;
113
151
  };
152
+ const telegramDraft = () => {
153
+ const destination = assertDraft();
154
+ if (destination.provider !== "telegram") throw new Error("Not a Telegram destination.");
155
+ return destination;
156
+ };
157
+ const ntfyDraft = () => {
158
+ const destination = assertDraft();
159
+ if (destination.provider !== "ntfy") throw new Error("Not an ntfy destination.");
160
+ return destination;
161
+ };
162
+ const serverDraft = () => {
163
+ const destination = assertDraft();
164
+ if (destination.provider !== "gotify" && destination.provider !== "ntfy" && destination.provider !== "bark")
165
+ throw new Error("Not a server destination.");
166
+ return destination;
167
+ };
168
+ const priorityDraft = () => {
169
+ const destination = serverDraft();
170
+ if (destination.provider === "bark") throw new Error("Priority is unavailable.");
171
+ return destination;
172
+ };
173
+ const reportError = () => {
174
+ if (isCurrent())
175
+ ctx.ui.notify(
176
+ "Notify operation failed. Check the input, settings file, and Project selections. No credential values are shown.",
177
+ "error",
178
+ );
179
+ };
114
180
  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.");
181
+ const value = assertDraft();
182
+ const destination = providers.get(value.provider)?.validate(value);
183
+ if (!destination) throw new Error("Invalid destination settings. Check the required fields.");
117
184
  await apply(saveDestination(store, selectedId, destination, actionSignal, selectNew));
118
185
  draft = undefined;
119
186
  return { kind: "to", screen: "main" } as const;
120
187
  };
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."];
188
+ const addWebhook = async (provider: "discord" | "webhook" | "teams", actionSignal: AbortSignal) => {
189
+ const result = await runSecretInput(menuCtx, {
190
+ title:
191
+ provider === "teams"
192
+ ? "Teams workflow webhook URL"
193
+ : `${provider === "discord" ? "Discord" : "Generic webhook"} URL`,
194
+ signal: actionSignal,
195
+ isCurrent,
196
+ onError: reportError,
197
+ });
198
+ actionSignal.throwIfAborted();
199
+ current();
200
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" } as const;
201
+ if (result.kind !== "submitted") return { kind: "stay" } as const;
202
+ const destination = providers.get(provider)?.validate({
203
+ provider,
204
+ label:
205
+ provider === "teams"
206
+ ? "Microsoft Teams notifications"
207
+ : provider === "discord"
208
+ ? "Discord notifications"
209
+ : "Generic webhook notifications",
210
+ webhookUrl: result.value,
211
+ });
212
+ if (!destination) throw new Error("Use a valid webhook URL.");
213
+ selectedId = randomUUID();
214
+ draft = destination;
215
+ return { kind: "to", screen: "review" } as const;
216
+ };
130
217
  const menu = defineMenu<State, Screen, Action>({
131
218
  start: "main",
132
219
  screens: {
@@ -140,8 +227,8 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
140
227
  ...state.snapshot.diagnostics,
141
228
  ],
142
229
  items: [
143
- { id: "destinations", label: "Telegram destinations", to: "destinations" },
144
- { id: "test", label: "Send test to Telegram…", to: "testSelect" },
230
+ { id: "destinations", label: "Destinations", to: "destinations" },
231
+ { id: "test", label: "Send test…", to: "testSelect" },
145
232
  { id: "settings", label: "Settings", to: "settings" },
146
233
  { id: "status", label: "Status", to: "status" },
147
234
  { id: "help", label: "Help", to: "help" },
@@ -150,25 +237,38 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
150
237
  }),
151
238
  destinations: ({ state }) => ({
152
239
  kind: "actions",
153
- title: "Telegram destinations · User",
240
+ title: "Destinations · User",
154
241
  items: [
155
242
  ...Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
156
- id,
243
+ // Stored IDs cannot contain ':', so rows cannot shadow the add actions.
244
+ id: `destination:${id}`,
157
245
  label: safeText(value.label),
158
- description: `Telegram · ${safeText(value.chatId)} · token configured`,
246
+ description: destinationDescription(value),
159
247
  action: "select" as const,
160
248
  })),
249
+ { id: "add:destination", label: "Add destination…", to: "addDestination" },
250
+ ],
251
+ }),
252
+ addDestination: () => ({
253
+ kind: "actions",
254
+ title: "Add destination · User",
255
+ items: [
161
256
  { id: "add", label: "Add Telegram destination", action: "add" },
257
+ { id: "addGotify", label: "Add Gotify destination", action: "addGotify" },
258
+ { id: "addSlack", label: "Add Slack destination", action: "addSlack" },
259
+ { id: "addNtfy", label: "Add ntfy destination", action: "addNtfy" },
260
+ { id: "addPushover", label: "Add Pushover destination", action: "addPushover" },
261
+ { id: "addDiscord", label: "Add Discord destination", action: "addDiscord" },
262
+ { id: "addBark", label: "Add Bark destination", action: "addBark" },
263
+ { id: "addWebhook", label: "Add Generic webhook destination", action: "addWebhook" },
264
+ { id: "addLine", label: "Add LINE destination", action: "addLine" },
265
+ { id: "addTeams", label: "Add Microsoft Teams destination", action: "addTeams" },
162
266
  ],
163
267
  }),
164
268
  destination: () => ({
165
269
  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
- ],
270
+ title: `${providerLabel(knownDestination())} destination · User`,
271
+ lines: destinationLines(knownDestination()),
172
272
  items: [
173
273
  { id: "edit", label: "Edit destination", action: "edit" },
174
274
  { id: "remove", label: "Remove destination…", to: "remove" },
@@ -223,7 +323,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
223
323
  label: "Send notifications to",
224
324
  currentValue: `${state.editing.targetIds.length}${inherited("targetIds") ? " (inherited)" : ""}`,
225
325
  action: "target",
226
- description: "Choose which saved Telegram chats receive notifications.",
326
+ description: "Choose which saved destinations receive notifications.",
227
327
  },
228
328
  ],
229
329
  };
@@ -234,14 +334,14 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
234
334
  items: Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
235
335
  id,
236
336
  label: safeText(value.label),
237
- description: safeText(value.chatId),
337
+ description: destinationDescription(value),
238
338
  selected: state.editing.targetIds.includes(id),
239
339
  })),
240
340
  action: "target",
241
341
  enableSearch: true,
242
342
  actions:
243
343
  scope === "project"
244
- ? [{ id: "inherit", label: "Restore inherited selection", action: "inheritTargets" }]
344
+ ? [{ id: "inherit:targets", label: "Restore inherited selection", action: "inheritTargets" }]
245
345
  : [],
246
346
  }),
247
347
  delay: () => ({
@@ -265,7 +365,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
265
365
  }),
266
366
  label: () => ({
267
367
  kind: "input",
268
- title: "Telegram destination label",
368
+ title: `${providerLabel(assertDraft())} destination label`,
269
369
  initialValue: assertDraft().label,
270
370
  action: "label",
271
371
  }),
@@ -273,27 +373,52 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
273
373
  kind: "input",
274
374
  title: "Telegram chat ID",
275
375
  lines: ["Numeric private chat, group, or supergroup ID. Group IDs can be negative."],
276
- initialValue: assertDraft().chatId,
376
+ initialValue: telegramDraft().chatId,
277
377
  action: "chat",
278
378
  }),
279
379
  topic: () => ({
280
380
  kind: "input",
281
381
  title: "Forum topic ID (optional)",
282
382
  lines: ["Leave empty for no topic."],
283
- initialValue: String(assertDraft().messageThreadId ?? ""),
383
+ initialValue: String(telegramDraft().messageThreadId ?? ""),
284
384
  action: "topic",
285
385
  }),
386
+ ntfyTopic: () => ({
387
+ kind: "input",
388
+ title: "ntfy topic",
389
+ lines: ["A topic name is not access control. Configure server authentication and topic permissions."],
390
+ initialValue: ntfyDraft().topic,
391
+ action: "ntfyTopic",
392
+ }),
393
+ serverUrl: () => ({
394
+ kind: "input",
395
+ title: `${providerLabel(serverDraft())} server URL`,
396
+ lines: ["HTTP(S) base URL with an optional reverse-proxy path. No credentials, query, or fragment."],
397
+ initialValue: serverDraft().serverUrl,
398
+ action: "serverUrl",
399
+ }),
400
+ priority: () => ({
401
+ kind: "input",
402
+ title: `${providerLabel(priorityDraft())} priority (optional)`,
403
+ lines: [
404
+ priorityDraft().provider === "ntfy"
405
+ ? "Integer from 1 to 5. Leave empty for the server default."
406
+ : "Safe integer from -9007199254740991 to 9007199254740991. Leave empty for the server default.",
407
+ ],
408
+ initialValue: String(priorityDraft().priority ?? ""),
409
+ action: "priority",
410
+ }),
286
411
  review: () => ({
287
412
  kind: "actions",
288
- title: "Review Telegram destination · User",
413
+ title: `Review ${providerLabel(assertDraft())} destination · User`,
289
414
  lines: [
290
- ...draftLines(),
415
+ ...destinationLines(assertDraft()),
291
416
  ...(store.snapshot.effective.destinations[selectedId]
292
417
  ? ["Save keeps your current notification selection."]
293
418
  : [
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.",
419
+ "Use this destination for notifications?",
420
+ "Save and use: save this destination and select it for User notifications.",
421
+ "Save only: save this destination without selecting it.",
297
422
  ]),
298
423
  "Automatic notifications default to On. Saved Off settings and Project choices are unchanged.",
299
424
  ],
@@ -303,10 +428,38 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
303
428
  label: store.snapshot.effective.destinations[selectedId] ? "Save changes" : "Save and use",
304
429
  action: "save",
305
430
  },
306
- { id: "token", label: "Replace bot token…", action: "token" },
307
- { id: "chat", label: "Change chat ID…", to: "chat" },
431
+ {
432
+ id: "token",
433
+ label: `Replace ${credentialLabels[assertDraft().provider]}…`,
434
+ action: "token",
435
+ },
436
+ ...(assertDraft().provider === "telegram"
437
+ ? [{ id: "chat", label: "Change chat ID…", to: "chat" as const }]
438
+ : []),
439
+ ...(assertDraft().provider === "gotify" ||
440
+ assertDraft().provider === "ntfy" ||
441
+ assertDraft().provider === "bark"
442
+ ? [{ id: "serverUrl", label: "Change server URL…", to: "serverUrl" as const }]
443
+ : []),
444
+ ...(assertDraft().provider === "pushover"
445
+ ? [{ id: "userKey", label: "Replace user key…", action: "userKey" as const }]
446
+ : []),
447
+ ...(assertDraft().provider === "line"
448
+ ? [{ id: "recipientId", label: "Replace recipient ID…", action: "recipientId" as const }]
449
+ : []),
308
450
  { id: "label", label: "Change label…", to: "label" },
309
- { id: "topic", label: "Set forum topic ID…", to: "topic" },
451
+ ...(assertDraft().provider === "webhook"
452
+ ? [{ id: "bearerToken", label: "Set Bearer token (empty for none)…", action: "bearerToken" as const }]
453
+ : []),
454
+ ...(assertDraft().provider === "telegram"
455
+ ? [{ id: "topic", label: "Set forum topic ID…", to: "topic" as const }]
456
+ : []),
457
+ ...(assertDraft().provider === "ntfy"
458
+ ? [{ id: "ntfyTopic", label: "Change topic…", to: "ntfyTopic" as const }]
459
+ : []),
460
+ ...(assertDraft().provider === "gotify" || assertDraft().provider === "ntfy"
461
+ ? [{ id: "priority", label: "Set priority…", to: "priority" as const }]
462
+ : []),
310
463
  ...(!store.snapshot.effective.destinations[selectedId]
311
464
  ? [{ id: "saveOnly", label: "Save only", action: "saveOnly" as const }]
312
465
  : []),
@@ -314,7 +467,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
314
467
  }),
315
468
  remove: () => ({
316
469
  kind: "actions",
317
- title: "Remove Telegram destination?",
470
+ title: `Remove ${providerLabel(knownDestination())} destination?`,
318
471
  lines: [
319
472
  safeText(knownDestination().label),
320
473
  "Also removes its User selection. Existing messages are not recalled.",
@@ -328,15 +481,21 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
328
481
  items: Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
329
482
  id,
330
483
  label: safeText(value.label),
484
+ description: destinationDescription(value),
331
485
  action: "prepareTest" as const,
332
486
  })),
333
487
  }),
334
488
  testReview: () => ({
335
489
  kind: "review",
336
- title: `Send test to ${safeText(testDestination?.label ?? "Telegram")}?`,
490
+ title: `Send test to ${safeText(testDestination?.label ?? "destination")}?`,
491
+ lines: testDestination ? [destinationDescription(testDestination)] : [],
337
492
  content: `${testNotification?.title ?? ""}\n${testNotification?.body ?? ""}`,
338
493
  viewportSize: "adaptive",
339
- confirm: { id: "send", label: "Send test to Telegram", action: "sendTest" },
494
+ confirm: {
495
+ id: "send",
496
+ label: `Send test to ${testDestination ? providerLabel(testDestination) : "destination"}`,
497
+ action: "sendTest",
498
+ },
340
499
  }),
341
500
  status: ({ state }) => ({
342
501
  kind: "detail",
@@ -351,7 +510,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
351
510
  `Pending reminder: ${coordinator.pendingAt ? new Date(coordinator.pendingAt).toISOString() : "none"}`,
352
511
  ...Object.entries(state.snapshot.effective.destinations).map(([id, value]) => {
353
512
  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"}`;
513
+ 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
514
  }),
356
515
  ...state.snapshot.diagnostics,
357
516
  ],
@@ -420,11 +579,16 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
420
579
  return { kind: "stay" };
421
580
  },
422
581
  select: ({ itemId }) => {
423
- selectedId = itemId;
582
+ selectedId = itemId.slice("destination:".length);
424
583
  return { kind: "to", screen: "destination" };
425
584
  },
426
585
  add: async ({ signal: actionSignal }) => {
427
- const result = await runSecretInput(menuCtx, { title: "Telegram bot token", signal: actionSignal, isCurrent });
586
+ const result = await runSecretInput(menuCtx, {
587
+ title: "Telegram bot token",
588
+ signal: actionSignal,
589
+ isCurrent,
590
+ onError: reportError,
591
+ });
428
592
  actionSignal.throwIfAborted();
429
593
  current();
430
594
  if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
@@ -433,19 +597,270 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
433
597
  draft = { provider: "telegram", label: "", botToken: result.value.trim(), chatId: "" };
434
598
  return { kind: "to", screen: "chat" };
435
599
  },
600
+ addGotify: async ({ signal: actionSignal }) => {
601
+ const result = await runSecretInput(menuCtx, {
602
+ title: "Gotify application token",
603
+ signal: actionSignal,
604
+ isCurrent,
605
+ onError: reportError,
606
+ });
607
+ actionSignal.throwIfAborted();
608
+ current();
609
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
610
+ if (result.kind !== "submitted") return { kind: "stay" };
611
+ selectedId = randomUUID();
612
+ draft = { provider: "gotify", label: "", appToken: result.value.trim(), serverUrl: "" };
613
+ return { kind: "to", screen: "serverUrl" };
614
+ },
615
+ addSlack: async ({ signal: actionSignal }) => {
616
+ const result = await runSecretInput(menuCtx, {
617
+ title: "Slack webhook URL",
618
+ signal: actionSignal,
619
+ isCurrent,
620
+ onError: reportError,
621
+ });
622
+ actionSignal.throwIfAborted();
623
+ current();
624
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
625
+ if (result.kind !== "submitted") return { kind: "stay" };
626
+ const destination = providers.get("slack")?.validate({
627
+ provider: "slack",
628
+ label: "Slack notifications",
629
+ webhookUrl: result.value,
630
+ });
631
+ if (destination?.provider !== "slack") throw new Error("Use a valid Slack Incoming Webhook URL.");
632
+ selectedId = randomUUID();
633
+ draft = destination;
634
+ return { kind: "to", screen: "review" };
635
+ },
636
+ addLine: async ({ signal: actionSignal }) => {
637
+ const token = await runSecretInput(menuCtx, {
638
+ title: "LINE channel access token",
639
+ signal: actionSignal,
640
+ isCurrent,
641
+ onError: reportError,
642
+ });
643
+ actionSignal.throwIfAborted();
644
+ current();
645
+ if (token.kind === "closed" && token.reason === "close") return { kind: "close" };
646
+ if (token.kind !== "submitted") return { kind: "stay" };
647
+ const recipient = await runSecretInput(menuCtx, {
648
+ title: "LINE recipient ID (user, group, or room)",
649
+ signal: actionSignal,
650
+ isCurrent,
651
+ onError: reportError,
652
+ });
653
+ actionSignal.throwIfAborted();
654
+ current();
655
+ if (recipient.kind === "closed" && recipient.reason === "close") return { kind: "close" };
656
+ if (recipient.kind !== "submitted") return { kind: "stay" };
657
+ const destination = providers.get("line")?.validate({
658
+ provider: "line",
659
+ label: "LINE notifications",
660
+ channelAccessToken: token.value.trim(),
661
+ recipientId: recipient.value.trim(),
662
+ });
663
+ if (!destination) throw new Error("Use a valid LINE token and recipient ID.");
664
+ selectedId = randomUUID();
665
+ draft = destination;
666
+ return { kind: "to", screen: "review" };
667
+ },
668
+ recipientId: async ({ signal: actionSignal }) => {
669
+ const result = await runSecretInput(menuCtx, {
670
+ title: "Replace LINE recipient ID",
671
+ signal: actionSignal,
672
+ isCurrent,
673
+ onError: reportError,
674
+ });
675
+ actionSignal.throwIfAborted();
676
+ current();
677
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
678
+ if (result.kind === "submitted") {
679
+ const destination = assertDraft();
680
+ const valid = providers.get("line")?.validate({ ...destination, recipientId: result.value.trim() });
681
+ if (destination.provider !== "line" || valid?.provider !== "line")
682
+ throw new Error("Use a valid LINE user, group, or room ID.");
683
+ destination.recipientId = valid.recipientId;
684
+ }
685
+ return { kind: "stay" };
686
+ },
687
+ addDiscord: ({ signal: actionSignal }) => addWebhook("discord", actionSignal),
688
+ addWebhook: ({ signal: actionSignal }) => addWebhook("webhook", actionSignal),
689
+ addTeams: ({ signal: actionSignal }) => addWebhook("teams", actionSignal),
690
+ addBark: async ({ signal: actionSignal }) => {
691
+ const result = await runSecretInput(menuCtx, {
692
+ title: "Bark device key",
693
+ signal: actionSignal,
694
+ isCurrent,
695
+ onError: reportError,
696
+ });
697
+ actionSignal.throwIfAborted();
698
+ current();
699
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
700
+ if (result.kind !== "submitted") return { kind: "stay" };
701
+ const destination = providers.get("bark")?.validate({
702
+ provider: "bark",
703
+ label: "Bark notifications",
704
+ serverUrl: "https://api.day.app",
705
+ deviceKey: result.value.trim(),
706
+ });
707
+ if (!destination) throw new Error("Use a valid Bark device key.");
708
+ selectedId = randomUUID();
709
+ draft = destination;
710
+ return { kind: "to", screen: "review" };
711
+ },
712
+ addPushover: async ({ signal: actionSignal }) => {
713
+ const app = await runSecretInput(menuCtx, {
714
+ title: "Pushover application token",
715
+ signal: actionSignal,
716
+ isCurrent,
717
+ onError: reportError,
718
+ });
719
+ actionSignal.throwIfAborted();
720
+ current();
721
+ if (app.kind === "closed" && app.reason === "close") return { kind: "close" };
722
+ if (app.kind !== "submitted") return { kind: "stay" };
723
+ const user = await runSecretInput(menuCtx, {
724
+ title: "Pushover user key",
725
+ signal: actionSignal,
726
+ isCurrent,
727
+ onError: reportError,
728
+ });
729
+ actionSignal.throwIfAborted();
730
+ current();
731
+ if (user.kind === "closed" && user.reason === "close") return { kind: "close" };
732
+ if (user.kind !== "submitted") return { kind: "stay" };
733
+ const destination = providers.get("pushover")?.validate({
734
+ provider: "pushover",
735
+ label: "Pushover notifications",
736
+ appToken: app.value.trim(),
737
+ userKey: user.value.trim(),
738
+ });
739
+ if (!destination) throw new Error("Use a valid application token and user key.");
740
+ selectedId = randomUUID();
741
+ draft = destination;
742
+ return { kind: "to", screen: "review" };
743
+ },
744
+ userKey: async ({ signal: actionSignal }) => {
745
+ const result = await runSecretInput(menuCtx, {
746
+ title: "Replace Pushover user key",
747
+ signal: actionSignal,
748
+ isCurrent,
749
+ onError: reportError,
750
+ });
751
+ actionSignal.throwIfAborted();
752
+ current();
753
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
754
+ if (result.kind === "submitted") {
755
+ const destination = assertDraft();
756
+ const valid = providers.get("pushover")?.validate({ ...destination, userKey: result.value.trim() });
757
+ if (destination.provider !== "pushover" || valid?.provider !== "pushover")
758
+ throw new Error("Use a valid user key.");
759
+ destination.userKey = valid.userKey;
760
+ }
761
+ return { kind: "stay" };
762
+ },
763
+ bearerToken: async ({ signal: actionSignal }) => {
764
+ const result = await runSecretInput(menuCtx, {
765
+ title: "Bearer token (empty for none)",
766
+ required: false,
767
+ signal: actionSignal,
768
+ isCurrent,
769
+ onError: reportError,
770
+ });
771
+ actionSignal.throwIfAborted();
772
+ current();
773
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
774
+ if (result.kind === "submitted") {
775
+ const destination = assertDraft();
776
+ const valid = providers
777
+ .get("webhook")
778
+ ?.validate({ ...destination, bearerToken: result.value.trim() || undefined });
779
+ if (destination.provider !== "webhook" || valid?.provider !== "webhook")
780
+ throw new Error("Use a valid Bearer token or leave it empty.");
781
+ destination.bearerToken = valid.bearerToken;
782
+ }
783
+ return { kind: "stay" };
784
+ },
785
+ addNtfy: () => {
786
+ selectedId = randomUUID();
787
+ draft = { provider: "ntfy", label: "ntfy notifications", serverUrl: "https://ntfy.sh", topic: "" };
788
+ return { kind: "to", screen: "ntfyTopic" };
789
+ },
790
+ ntfyTopic: ({ value }) => {
791
+ const destination = assertDraft();
792
+ const valid = providers.get("ntfy")?.validate({ ...destination, topic: value?.trim() });
793
+ if (destination.provider !== "ntfy" || valid?.provider !== "ntfy") throw new Error("Use a valid ntfy topic.");
794
+ destination.topic = valid.topic;
795
+ return { kind: "to", screen: "review" };
796
+ },
436
797
  edit: () => {
437
798
  draft = { ...knownDestination() };
438
799
  return { kind: "to", screen: "review" };
439
800
  },
440
801
  token: async ({ signal: actionSignal }) => {
441
802
  const result = await runSecretInput(menuCtx, {
442
- title: "Replace Telegram bot token",
803
+ title: `Replace ${providerLabel(assertDraft())} ${credentialLabels[assertDraft().provider]}`,
804
+ required: assertDraft().provider !== "ntfy",
443
805
  signal: actionSignal,
444
806
  isCurrent,
807
+ onError: reportError,
445
808
  });
446
809
  actionSignal.throwIfAborted();
447
810
  current();
448
- if (result.kind === "submitted") assertDraft().botToken = result.value.trim();
811
+ if (result.kind === "submitted") {
812
+ const destination = assertDraft();
813
+ switch (destination.provider) {
814
+ case "telegram":
815
+ destination.botToken = result.value.trim();
816
+ break;
817
+ case "gotify":
818
+ destination.appToken = result.value.trim();
819
+ break;
820
+ case "pushover": {
821
+ const valid = providers.get("pushover")?.validate({ ...destination, appToken: result.value.trim() });
822
+ if (valid?.provider !== "pushover") throw new Error("Use a valid application token.");
823
+ destination.appToken = valid.appToken;
824
+ break;
825
+ }
826
+ case "bark": {
827
+ const valid = providers.get("bark")?.validate({ ...destination, deviceKey: result.value.trim() });
828
+ if (valid?.provider !== "bark") throw new Error("Use a valid device key.");
829
+ destination.deviceKey = valid.deviceKey;
830
+ break;
831
+ }
832
+ case "line": {
833
+ const valid = providers
834
+ .get("line")
835
+ ?.validate({ ...destination, channelAccessToken: result.value.trim() });
836
+ if (valid?.provider !== "line") throw new Error("Use a valid LINE channel access token.");
837
+ destination.channelAccessToken = valid.channelAccessToken;
838
+ break;
839
+ }
840
+ case "teams":
841
+ case "discord":
842
+ case "webhook": {
843
+ const valid = providers.get(destination.provider)?.validate({ ...destination, webhookUrl: result.value });
844
+ if (valid?.provider !== destination.provider) throw new Error("Use a valid webhook URL.");
845
+ destination.webhookUrl = valid.webhookUrl;
846
+ break;
847
+ }
848
+ case "ntfy": {
849
+ const valid = providers
850
+ .get("ntfy")
851
+ ?.validate({ ...destination, accessToken: result.value.trim() || undefined });
852
+ if (valid?.provider !== "ntfy") throw new Error("Use a valid access token or leave it empty.");
853
+ destination.accessToken = valid.accessToken;
854
+ break;
855
+ }
856
+ case "slack": {
857
+ const valid = providers.get("slack")?.validate({ ...destination, webhookUrl: result.value });
858
+ if (valid?.provider !== "slack") throw new Error("Use a valid Slack Incoming Webhook URL.");
859
+ destination.webhookUrl = valid.webhookUrl;
860
+ break;
861
+ }
862
+ }
863
+ }
449
864
  if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
450
865
  return { kind: "stay" };
451
866
  },
@@ -456,7 +871,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
456
871
  },
457
872
  chat: ({ value }) => {
458
873
  if (!value || !/^-?[1-9]\d{0,30}$/.test(value.trim())) throw new Error("Use a numeric Telegram chat ID.");
459
- const destination = assertDraft();
874
+ const destination = telegramDraft();
460
875
  destination.chatId = value.trim();
461
876
  if (!destination.label) destination.label = `Telegram ${destination.chatId}`;
462
877
  return { kind: "to", screen: "review" };
@@ -465,8 +880,35 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
465
880
  const topic = value?.trim();
466
881
  if (topic && (!/^\d+$/.test(topic) || !Number.isSafeInteger(Number(topic)) || Number(topic) <= 0))
467
882
  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;
883
+ if (topic) telegramDraft().messageThreadId = Number(topic);
884
+ else delete telegramDraft().messageThreadId;
885
+ return { kind: "to", screen: "review" };
886
+ },
887
+ serverUrl: ({ value }) => {
888
+ const destination = serverDraft();
889
+ const normalized = providers.get(destination.provider)?.validate({
890
+ ...destination,
891
+ label: destination.label || "Gotify",
892
+ serverUrl: value?.trim(),
893
+ });
894
+ if (
895
+ !normalized ||
896
+ (normalized.provider !== "gotify" && normalized.provider !== "ntfy" && normalized.provider !== "bark")
897
+ )
898
+ throw new Error("Use a valid server URL and credentials. No URL credentials, query, or fragment.");
899
+ destination.serverUrl = normalized.serverUrl;
900
+ if (!destination.label) destination.label = `Gotify ${displayServerUrl(destination.serverUrl)}`.slice(0, 128);
901
+ return { kind: "to", screen: "review" };
902
+ },
903
+ priority: ({ value }) => {
904
+ const priority = value?.trim();
905
+ if (priority && (!/^-?\d+$/.test(priority) || !Number.isSafeInteger(Number(priority))))
906
+ throw new Error("Use a safe-integer priority or leave it empty.");
907
+ const destination = priorityDraft();
908
+ if (priority && destination.provider === "ntfy" && (Number(priority) < 1 || Number(priority) > 5))
909
+ throw new Error("Use a priority from 1 to 5.");
910
+ if (priority) destination.priority = Number(priority);
911
+ else delete destination.priority;
470
912
  return { kind: "to", screen: "review" };
471
913
  },
472
914
  save: ({ signal: actionSignal }) => saveDraft(actionSignal, true),
@@ -502,9 +944,10 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
502
944
  const destination = testDestination;
503
945
  const notification = testNotification;
504
946
  const result = await runTask(menuCtx, {
505
- label: "Sending Telegram test…",
947
+ label: `Sending ${providerLabel(destination)} test…`,
506
948
  signal: actionSignal,
507
949
  isCurrent,
950
+ onError: reportError,
508
951
  task: ({ signal: taskSignal }) => coordinator.send(selectedId, destination, notification, taskSignal),
509
952
  });
510
953
  actionSignal.throwIfAborted();
@@ -512,8 +955,8 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
512
955
  if (result.kind === "completed")
513
956
  ctx.ui.notify(
514
957
  result.value.state === "accepted"
515
- ? "Telegram accepted the test notification."
516
- : `Telegram test: ${result.value.state === "failed" ? result.value.code : result.value.state}.`,
958
+ ? `${providerLabel(destination)} accepted the test notification.`
959
+ : `${providerLabel(destination)} test: ${result.value.state === "failed" ? result.value.code : result.value.state}.`,
517
960
  result.value.state === "accepted" ? "info" : "warning",
518
961
  );
519
962
  if (result.kind === "cancelled") return { kind: "close" };
@@ -530,13 +973,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
530
973
  editing: resolveSettings(store.snapshot.user, scope === "project" ? store.snapshot.project : {}, providers)
531
974
  .effective,
532
975
  }),
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
- },
976
+ onError: reportError,
540
977
  });
541
978
  } finally {
542
979
  draft = undefined;