@narumitw/pi-notify 0.1.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,13 +52,26 @@ 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"
74
+ | "saveOnly"
51
75
  | "remove"
52
76
  | "prepareTest"
53
77
  | "sendTest";
@@ -65,14 +89,25 @@ export interface MenuOptions {
65
89
  export const helpLines = [
66
90
  "Create a bot with @BotFather in Telegram, then start a private conversation or add it to your group with permission to send messages.",
67
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.",
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.",
68
103
  "Use a negative group/supergroup chat ID when applicable. Forum topic IDs are optional positive integers.",
69
104
  "Destinations are User settings only. Project settings require trust and may select existing destinations but cannot change credentials or addresses.",
70
105
  "Notifications disclose hostname, session name/ID, workspace and Git metadata, elapsed time and timestamp. No conversation or code is sent.",
71
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.",
72
107
  "Input or new work cancels a pending reminder. Saved policy/destination changes cancel pending reminders. Settings save immediately; closing does not undo them.",
73
108
  "RPC/print/JSON cannot observe terminal activity and deliver at settlement instead. Short-lived processes can exit before delivery completes.",
74
- "Delivery is best effort, one attempt, with no automatic retries or history replay. Accepted means Telegram accepted the message, not that it was read.",
75
- "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.",
76
111
  ];
77
112
 
78
113
  export async function showNotifyMenu(ctx: ExtensionCommandContext, options: MenuOptions) {
@@ -109,15 +144,63 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
109
144
  if (!draft) throw new Error("Destination draft is unavailable.");
110
145
  return draft;
111
146
  };
112
- const draftLines = () =>
113
- draft
114
- ? [
115
- `Label: ${safeText(draft.label)}`,
116
- `Chat: ${safeText(draft.chatId)}`,
117
- `Topic: ${draft.messageThreadId ?? "none"}`,
118
- "Bot token: configured (hidden)",
119
- ]
120
- : ["No destination draft."];
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
+ };
175
+ const saveDraft = async (actionSignal: AbortSignal, selectNew: boolean) => {
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.");
179
+ await apply(saveDestination(store, selectedId, destination, actionSignal, selectNew));
180
+ draft = undefined;
181
+ return { kind: "to", screen: "main" } as const;
182
+ };
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
+ };
121
204
  const menu = defineMenu<State, Screen, Action>({
122
205
  start: "main",
123
206
  screens: {
@@ -131,8 +214,8 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
131
214
  ...state.snapshot.diagnostics,
132
215
  ],
133
216
  items: [
134
- { id: "destinations", label: "Telegram destinations", to: "destinations" },
135
- { id: "test", label: "Send test to Telegram…", to: "testSelect" },
217
+ { id: "destinations", label: "Destinations", to: "destinations" },
218
+ { id: "test", label: "Send test…", to: "testSelect" },
136
219
  { id: "settings", label: "Settings", to: "settings" },
137
220
  { id: "status", label: "Status", to: "status" },
138
221
  { id: "help", label: "Help", to: "help" },
@@ -141,25 +224,36 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
141
224
  }),
142
225
  destinations: ({ state }) => ({
143
226
  kind: "actions",
144
- title: "Telegram destinations · User",
227
+ title: "Destinations · User",
145
228
  items: [
146
229
  ...Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
147
- id,
230
+ // Stored IDs cannot contain ':', so rows cannot shadow the add actions.
231
+ id: `destination:${id}`,
148
232
  label: safeText(value.label),
149
- description: `Telegram · ${safeText(value.chatId)} · token configured`,
233
+ description: destinationDescription(value),
150
234
  action: "select" as const,
151
235
  })),
236
+ { id: "add:destination", label: "Add destination…", to: "addDestination" },
237
+ ],
238
+ }),
239
+ addDestination: () => ({
240
+ kind: "actions",
241
+ title: "Add destination · User",
242
+ items: [
152
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" },
153
251
  ],
154
252
  }),
155
253
  destination: () => ({
156
254
  kind: "actions",
157
- title: "Telegram destination · User",
158
- lines: [
159
- `Label: ${safeText(knownDestination().label)}`,
160
- `Chat: ${safeText(knownDestination().chatId)}`,
161
- "Bot token: configured (hidden)",
162
- ],
255
+ title: `${providerLabel(knownDestination())} destination · User`,
256
+ lines: destinationLines(knownDestination()),
163
257
  items: [
164
258
  { id: "edit", label: "Edit destination", action: "edit" },
165
259
  { id: "remove", label: "Remove destination…", to: "remove" },
@@ -185,11 +279,11 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
185
279
  },
186
280
  {
187
281
  id: "enabled",
188
- label: "Notifications",
189
- currentValue: inherited("enabled") ? "Inherit" : String(own.enabled ?? false),
190
- values: scope === "project" ? ["Inherit", "true", "false"] : ["false", "true"],
282
+ label: "Automatic notifications",
283
+ currentValue: inherited("enabled") ? "Inherit" : (own.enabled ?? true) ? "On" : "Off",
284
+ values: scope === "project" ? ["Inherit", "On", "Off"] : ["Off", "On"],
191
285
  action: "policy",
192
- description: `Effective: ${state.snapshot.effective.enabled}. Source: ${Object.hasOwn(state.snapshot.project, "enabled") ? "Project" : Object.hasOwn(state.snapshot.user, "enabled") ? "User" : "default"}.`,
286
+ description: `Send to selected destinations when Pi stops automatic work. Off still allows manual tests. Effective: ${state.snapshot.effective.enabled ? "On" : "Off"}. Source: ${Object.hasOwn(state.snapshot.project, "enabled") ? "Project" : Object.hasOwn(state.snapshot.user, "enabled") ? "User" : "default"}.`,
193
287
  },
194
288
  {
195
289
  id: "mode",
@@ -211,28 +305,28 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
211
305
  },
212
306
  {
213
307
  id: "targetIds",
214
- label: "Selected destinations",
308
+ label: "Send notifications to",
215
309
  currentValue: `${state.editing.targetIds.length}${inherited("targetIds") ? " (inherited)" : ""}`,
216
310
  action: "target",
217
- description: "Select existing User destinations for this scope.",
311
+ description: "Choose which saved destinations receive notifications.",
218
312
  },
219
313
  ],
220
314
  };
221
315
  },
222
316
  targets: ({ state }) => ({
223
317
  kind: "multiSelect",
224
- title: `Selected destinations · ${scope}`,
318
+ title: `Send notifications to · ${scope}`,
225
319
  items: Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
226
320
  id,
227
321
  label: safeText(value.label),
228
- description: safeText(value.chatId),
322
+ description: destinationDescription(value),
229
323
  selected: state.editing.targetIds.includes(id),
230
324
  })),
231
325
  action: "target",
232
326
  enableSearch: true,
233
327
  actions:
234
328
  scope === "project"
235
- ? [{ id: "inherit", label: "Restore inherited selection", action: "inheritTargets" }]
329
+ ? [{ id: "inherit:targets", label: "Restore inherited selection", action: "inheritTargets" }]
236
330
  : [],
237
331
  }),
238
332
  delay: () => ({
@@ -256,7 +350,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
256
350
  }),
257
351
  label: () => ({
258
352
  kind: "input",
259
- title: "Telegram destination label",
353
+ title: `${providerLabel(assertDraft())} destination label`,
260
354
  initialValue: assertDraft().label,
261
355
  action: "label",
262
356
  }),
@@ -264,28 +358,98 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
264
358
  kind: "input",
265
359
  title: "Telegram chat ID",
266
360
  lines: ["Numeric private chat, group, or supergroup ID. Group IDs can be negative."],
267
- initialValue: assertDraft().chatId,
361
+ initialValue: telegramDraft().chatId,
268
362
  action: "chat",
269
363
  }),
270
364
  topic: () => ({
271
365
  kind: "input",
272
366
  title: "Forum topic ID (optional)",
273
367
  lines: ["Leave empty for no topic."],
274
- initialValue: String(assertDraft().messageThreadId ?? ""),
368
+ initialValue: String(telegramDraft().messageThreadId ?? ""),
275
369
  action: "topic",
276
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
+ }),
277
396
  review: () => ({
278
397
  kind: "actions",
279
- title: "Review Telegram destination · User",
280
- lines: draftLines(),
398
+ title: `Review ${providerLabel(assertDraft())} destination · User`,
399
+ lines: [
400
+ ...destinationLines(assertDraft()),
401
+ ...(store.snapshot.effective.destinations[selectedId]
402
+ ? ["Save keeps your current notification selection."]
403
+ : [
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.",
407
+ ]),
408
+ "Automatic notifications default to On. Saved Off settings and Project choices are unchanged.",
409
+ ],
281
410
  items: [
282
- { id: "save", label: "Save destination", action: "save" },
283
- { id: "token", label: "Replace bot token…", action: "token" },
411
+ {
412
+ id: "save",
413
+ label: store.snapshot.effective.destinations[selectedId] ? "Save changes" : "Save and use",
414
+ action: "save",
415
+ },
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
+ : []),
432
+ { id: "label", label: "Change label…", to: "label" },
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
+ : []),
445
+ ...(!store.snapshot.effective.destinations[selectedId]
446
+ ? [{ id: "saveOnly", label: "Save only", action: "saveOnly" as const }]
447
+ : []),
284
448
  ],
285
449
  }),
286
450
  remove: () => ({
287
451
  kind: "actions",
288
- title: "Remove Telegram destination?",
452
+ title: `Remove ${providerLabel(knownDestination())} destination?`,
289
453
  lines: [
290
454
  safeText(knownDestination().label),
291
455
  "Also removes its User selection. Existing messages are not recalled.",
@@ -299,15 +463,21 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
299
463
  items: Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
300
464
  id,
301
465
  label: safeText(value.label),
466
+ description: destinationDescription(value),
302
467
  action: "prepareTest" as const,
303
468
  })),
304
469
  }),
305
470
  testReview: () => ({
306
471
  kind: "review",
307
- title: `Send test to ${safeText(testDestination?.label ?? "Telegram")}?`,
472
+ title: `Send test to ${safeText(testDestination?.label ?? "destination")}?`,
473
+ lines: testDestination ? [destinationDescription(testDestination)] : [],
308
474
  content: `${testNotification?.title ?? ""}\n${testNotification?.body ?? ""}`,
309
475
  viewportSize: "adaptive",
310
- 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
+ },
311
481
  }),
312
482
  status: ({ state }) => ({
313
483
  kind: "detail",
@@ -322,7 +492,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
322
492
  `Pending reminder: ${coordinator.pendingAt ? new Date(coordinator.pendingAt).toISOString() : "none"}`,
323
493
  ...Object.entries(state.snapshot.effective.destinations).map(([id, value]) => {
324
494
  const result = coordinator.statuses.get(id)?.result;
325
- 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"}`;
326
496
  }),
327
497
  ...state.snapshot.diagnostics,
328
498
  ],
@@ -343,7 +513,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
343
513
  store,
344
514
  scope,
345
515
  itemId,
346
- value === "Inherit" ? undefined : itemId === "enabled" ? value === "true" : value,
516
+ value === "Inherit" ? undefined : itemId === "enabled" ? value === "On" : value,
347
517
  actionSignal,
348
518
  ),
349
519
  );
@@ -391,60 +561,279 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
391
561
  return { kind: "stay" };
392
562
  },
393
563
  select: ({ itemId }) => {
394
- selectedId = itemId;
564
+ selectedId = itemId.slice("destination:".length);
395
565
  return { kind: "to", screen: "destination" };
396
566
  },
397
567
  add: async ({ signal: actionSignal }) => {
398
- 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
+ });
399
574
  actionSignal.throwIfAborted();
400
575
  current();
401
576
  if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
402
577
  if (result.kind !== "submitted") return { kind: "stay" };
403
578
  selectedId = randomUUID();
404
579
  draft = { provider: "telegram", label: "", botToken: result.value.trim(), chatId: "" };
405
- return { kind: "to", screen: "label" };
580
+ return { kind: "to", screen: "chat" };
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" };
406
726
  },
407
727
  edit: () => {
408
728
  draft = { ...knownDestination() };
409
- return { kind: "to", screen: "label" };
729
+ return { kind: "to", screen: "review" };
410
730
  },
411
731
  token: async ({ signal: actionSignal }) => {
412
732
  const result = await runSecretInput(menuCtx, {
413
- title: "Replace Telegram bot token",
733
+ title: `Replace ${providerLabel(assertDraft())} ${credentialLabels[assertDraft().provider]}`,
734
+ required: assertDraft().provider !== "ntfy",
414
735
  signal: actionSignal,
415
736
  isCurrent,
737
+ onError: reportError,
416
738
  });
417
739
  actionSignal.throwIfAborted();
418
740
  current();
419
- 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
+ }
420
785
  if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
421
786
  return { kind: "stay" };
422
787
  },
423
788
  label: ({ value }) => {
424
789
  if (!value?.trim() || value.length > 128) throw new Error("Use a label from 1 to 128 characters.");
425
790
  assertDraft().label = value.trim();
426
- return { kind: "to", screen: "chat" };
791
+ return { kind: "to", screen: "review" };
427
792
  },
428
793
  chat: ({ value }) => {
429
794
  if (!value || !/^-?[1-9]\d{0,30}$/.test(value.trim())) throw new Error("Use a numeric Telegram chat ID.");
430
- assertDraft().chatId = value.trim();
431
- return { kind: "to", screen: "topic" };
795
+ const destination = telegramDraft();
796
+ destination.chatId = value.trim();
797
+ if (!destination.label) destination.label = `Telegram ${destination.chatId}`;
798
+ return { kind: "to", screen: "review" };
432
799
  },
433
800
  topic: ({ value }) => {
434
801
  const topic = value?.trim();
435
802
  if (topic && (!/^\d+$/.test(topic) || !Number.isSafeInteger(Number(topic)) || Number(topic) <= 0))
436
803
  throw new Error("Use a positive whole topic ID or leave it empty.");
437
- if (topic) assertDraft().messageThreadId = Number(topic);
438
- else delete assertDraft().messageThreadId;
804
+ if (topic) telegramDraft().messageThreadId = Number(topic);
805
+ else delete telegramDraft().messageThreadId;
439
806
  return { kind: "to", screen: "review" };
440
807
  },
441
- save: async ({ signal: actionSignal }) => {
442
- const destination = providers.get("telegram")?.validate(assertDraft());
443
- if (!destination) throw new Error("Invalid Telegram destination. Check the bot token and chat ID.");
444
- await apply(saveDestination(store, selectedId, destination, actionSignal));
445
- draft = undefined;
446
- return { kind: "to", screen: "main" };
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;
833
+ return { kind: "to", screen: "review" };
447
834
  },
835
+ save: ({ signal: actionSignal }) => saveDraft(actionSignal, true),
836
+ saveOnly: ({ signal: actionSignal }) => saveDraft(actionSignal, false),
448
837
  remove: async ({ signal: actionSignal }) => {
449
838
  await apply(saveDestination(store, selectedId, undefined, actionSignal));
450
839
  return { kind: "to", screen: "main" };
@@ -476,9 +865,10 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
476
865
  const destination = testDestination;
477
866
  const notification = testNotification;
478
867
  const result = await runTask(menuCtx, {
479
- label: "Sending Telegram test…",
868
+ label: `Sending ${providerLabel(destination)} test…`,
480
869
  signal: actionSignal,
481
870
  isCurrent,
871
+ onError: reportError,
482
872
  task: ({ signal: taskSignal }) => coordinator.send(selectedId, destination, notification, taskSignal),
483
873
  });
484
874
  actionSignal.throwIfAborted();
@@ -486,8 +876,8 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
486
876
  if (result.kind === "completed")
487
877
  ctx.ui.notify(
488
878
  result.value.state === "accepted"
489
- ? "Telegram accepted the test notification."
490
- : `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}.`,
491
881
  result.value.state === "accepted" ? "info" : "warning",
492
882
  );
493
883
  if (result.kind === "cancelled") return { kind: "close" };
@@ -504,13 +894,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
504
894
  editing: resolveSettings(store.snapshot.user, scope === "project" ? store.snapshot.project : {}, providers)
505
895
  .effective,
506
896
  }),
507
- onError: () => {
508
- if (isCurrent())
509
- ctx.ui.notify(
510
- "Notify operation failed. Check the input, settings file, and Project selections. No credential values are shown.",
511
- "error",
512
- );
513
- },
897
+ onError: reportError,
514
898
  });
515
899
  } finally {
516
900
  draft = undefined;