@narumitw/pi-notify 0.1.0 → 0.2.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/README.md CHANGED
@@ -38,7 +38,7 @@ Restart Pi or run `/reload` after persistent installation. The extension uses Pi
38
38
 
39
39
  Create a bot with Telegram's [BotFather](https://t.me/BotFather), then start a private conversation with it. Obtain that conversation's numeric chat ID through the [Bot API](https://core.telegram.org/bots/api#getupdates) after sending a message; keep the bot token private. For a group, add the bot and permit it to send messages. Stop any other update consumer before manually using `getUpdates`; an active webhook also prevents that method from working.
40
40
 
41
- Run `/notify`, add a Telegram destination, and confirm its settings. Use Send test to preview the disclosed metadata and explicitly send a test. In Settings, select the destination and enable notifications. The next eligible settled work period sends a reminder. Setup alone does not enable automatic notifications.
41
+ Run `/notify`, add a Telegram destination with its bot token and chat ID, and confirm its settings. The name is generated automatically; the review screen lets you change it or set an optional forum topic ID. Use Send test to preview the disclosed metadata and explicitly send a test. Choose Save and use to save the chat and select it for User notifications, or Save only to store it without selecting it. Automatic notifications are on by default, so the next eligible settled work period sends a reminder. Settings lets you pause automatic notifications or change the selected destinations. Existing Off settings and explicit Project selections are preserved.
42
42
 
43
43
  ## 💬 Commands
44
44
 
@@ -50,7 +50,7 @@ RPC receives manual configuration instructions instead of a custom terminal scre
50
50
 
51
51
  User settings are stored at `<getAgentDir()>/pi-notify.json`, normally `~/.pi/agent/pi-notify.json`. Trusted project overrides use `<workspace>/.pi/pi-notify.json`. Choose User or Project scope in `/notify` Settings. Destinations and credentials are always User-scoped.
52
52
 
53
- Notifications default to disabled, with immediate mode and a stored inactivity duration of 30 seconds. Loading defaults does not create a file. Successful menu saves apply immediately; manual edits take effect on session start or `/reload`.
53
+ Notifications default to enabled, with immediate mode and a stored inactivity duration of 30 seconds. Loading defaults does not create a file. Successful menu saves apply immediately; manual edits take effect on session start or `/reload`.
54
54
 
55
55
  ```json
56
56
  {
package/docs/settings.md CHANGED
@@ -6,7 +6,7 @@ Use `/notify` for setup or edit the canonical user JSON file. Settings load on s
6
6
 
7
7
  | Field | Accepted values | Default | Scope |
8
8
  | --- | --- | --- | --- |
9
- | `enabled` | Boolean | `false` | User or trusted Project |
9
+ | `enabled` | Boolean | `true` | User or trusted Project |
10
10
  | `mode` | `immediate`, `after-inactivity` | `immediate` | User or trusted Project |
11
11
  | `inactivitySeconds` | Whole number from 1 to 86400 | `30` | User or trusted Project |
12
12
  | `targetIds` | Array of unique existing destination IDs, at most 32 | Empty | User or trusted Project |
@@ -14,6 +14,8 @@ Use `/notify` for setup or edit the canonical user JSON file. Settings load on s
14
14
 
15
15
  Destination IDs contain 1–64 ASCII letters, digits, underscores, or hyphens, starting with a letter or digit; `constructor`, `prototype`, and `__proto__` are reserved. The menu creates IDs automatically.
16
16
 
17
+ New destinations require only a bot token and chat ID before review. The menu generates the label as `Telegram <chatId>` and leaves the forum topic unset. The review screen lets you change the label, chat ID, token, or optional topic before saving. Editing an existing destination opens that review with its current values; changing the chat ID preserves its label. Destination changes take effect only after confirmation. For a new chat, Save and use adds it to User `targetIds` in the same atomic save; Save only stores it without selecting it. Editing an existing destination preserves its selection state. Explicit Project selections and saved `enabled: false` values are unchanged. Automatic notifications default to On; Off pauses automatic delivery but still allows manual tests. No delivery occurs without a selected destination.
18
+
17
19
  Each Telegram destination has `provider: "telegram"`, a nonempty `label` of at most 128 characters, `botToken`, a numeric string `chatId`, and optional positive safe-integer `messageThreadId`. A group or supergroup ID can be negative. Store IDs as strings, not JSON numbers. Forum topic IDs use Telegram's `message_thread_id` field. Other Telegram chat products with additional required fields are not supported.
18
20
 
19
21
  Resolve defaults, User fields, then trusted Project overrides. Project arrays replace rather than merge. Project files cannot define destinations or credentials. Unknown provider IDs do not fall back to Telegram. Invalid fields, unreadable files, unsupported destinations, or missing selected IDs produce diagnostics and disable automatic delivery until repaired; no partial routing is attempted.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-notify",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Telegram notifications when Pi settles, with optional inactivity reminders.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/menu.ts CHANGED
@@ -48,6 +48,7 @@ type Action =
48
48
  | "chat"
49
49
  | "topic"
50
50
  | "save"
51
+ | "saveOnly"
51
52
  | "remove"
52
53
  | "prepareTest"
53
54
  | "sendTest";
@@ -65,6 +66,7 @@ export interface MenuOptions {
65
66
  export const helpLines = [
66
67
  "Create a bot with @BotFather in Telegram, then start a private conversation or add it to your group with permission to send messages.",
67
68
  "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.",
68
70
  "Use a negative group/supergroup chat ID when applicable. Forum topic IDs are optional positive integers.",
69
71
  "Destinations are User settings only. Project settings require trust and may select existing destinations but cannot change credentials or addresses.",
70
72
  "Notifications disclose hostname, session name/ID, workspace and Git metadata, elapsed time and timestamp. No conversation or code is sent.",
@@ -109,6 +111,13 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
109
111
  if (!draft) throw new Error("Destination draft is unavailable.");
110
112
  return draft;
111
113
  };
114
+ 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.");
117
+ await apply(saveDestination(store, selectedId, destination, actionSignal, selectNew));
118
+ draft = undefined;
119
+ return { kind: "to", screen: "main" } as const;
120
+ };
112
121
  const draftLines = () =>
113
122
  draft
114
123
  ? [
@@ -185,11 +194,11 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
185
194
  },
186
195
  {
187
196
  id: "enabled",
188
- label: "Notifications",
189
- currentValue: inherited("enabled") ? "Inherit" : String(own.enabled ?? false),
190
- values: scope === "project" ? ["Inherit", "true", "false"] : ["false", "true"],
197
+ label: "Automatic notifications",
198
+ currentValue: inherited("enabled") ? "Inherit" : (own.enabled ?? true) ? "On" : "Off",
199
+ values: scope === "project" ? ["Inherit", "On", "Off"] : ["Off", "On"],
191
200
  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"}.`,
201
+ 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
202
  },
194
203
  {
195
204
  id: "mode",
@@ -211,17 +220,17 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
211
220
  },
212
221
  {
213
222
  id: "targetIds",
214
- label: "Selected destinations",
223
+ label: "Send notifications to",
215
224
  currentValue: `${state.editing.targetIds.length}${inherited("targetIds") ? " (inherited)" : ""}`,
216
225
  action: "target",
217
- description: "Select existing User destinations for this scope.",
226
+ description: "Choose which saved Telegram chats receive notifications.",
218
227
  },
219
228
  ],
220
229
  };
221
230
  },
222
231
  targets: ({ state }) => ({
223
232
  kind: "multiSelect",
224
- title: `Selected destinations · ${scope}`,
233
+ title: `Send notifications to · ${scope}`,
225
234
  items: Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
226
235
  id,
227
236
  label: safeText(value.label),
@@ -277,10 +286,30 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
277
286
  review: () => ({
278
287
  kind: "actions",
279
288
  title: "Review Telegram destination · User",
280
- lines: draftLines(),
289
+ lines: [
290
+ ...draftLines(),
291
+ ...(store.snapshot.effective.destinations[selectedId]
292
+ ? ["Save keeps your current notification selection."]
293
+ : [
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.",
297
+ ]),
298
+ "Automatic notifications default to On. Saved Off settings and Project choices are unchanged.",
299
+ ],
281
300
  items: [
282
- { id: "save", label: "Save destination", action: "save" },
301
+ {
302
+ id: "save",
303
+ label: store.snapshot.effective.destinations[selectedId] ? "Save changes" : "Save and use",
304
+ action: "save",
305
+ },
283
306
  { id: "token", label: "Replace bot token…", action: "token" },
307
+ { id: "chat", label: "Change chat ID…", to: "chat" },
308
+ { id: "label", label: "Change label…", to: "label" },
309
+ { id: "topic", label: "Set forum topic ID…", to: "topic" },
310
+ ...(!store.snapshot.effective.destinations[selectedId]
311
+ ? [{ id: "saveOnly", label: "Save only", action: "saveOnly" as const }]
312
+ : []),
284
313
  ],
285
314
  }),
286
315
  remove: () => ({
@@ -343,7 +372,7 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
343
372
  store,
344
373
  scope,
345
374
  itemId,
346
- value === "Inherit" ? undefined : itemId === "enabled" ? value === "true" : value,
375
+ value === "Inherit" ? undefined : itemId === "enabled" ? value === "On" : value,
347
376
  actionSignal,
348
377
  ),
349
378
  );
@@ -402,11 +431,11 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
402
431
  if (result.kind !== "submitted") return { kind: "stay" };
403
432
  selectedId = randomUUID();
404
433
  draft = { provider: "telegram", label: "", botToken: result.value.trim(), chatId: "" };
405
- return { kind: "to", screen: "label" };
434
+ return { kind: "to", screen: "chat" };
406
435
  },
407
436
  edit: () => {
408
437
  draft = { ...knownDestination() };
409
- return { kind: "to", screen: "label" };
438
+ return { kind: "to", screen: "review" };
410
439
  },
411
440
  token: async ({ signal: actionSignal }) => {
412
441
  const result = await runSecretInput(menuCtx, {
@@ -423,12 +452,14 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
423
452
  label: ({ value }) => {
424
453
  if (!value?.trim() || value.length > 128) throw new Error("Use a label from 1 to 128 characters.");
425
454
  assertDraft().label = value.trim();
426
- return { kind: "to", screen: "chat" };
455
+ return { kind: "to", screen: "review" };
427
456
  },
428
457
  chat: ({ value }) => {
429
458
  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" };
459
+ const destination = assertDraft();
460
+ destination.chatId = value.trim();
461
+ if (!destination.label) destination.label = `Telegram ${destination.chatId}`;
462
+ return { kind: "to", screen: "review" };
432
463
  },
433
464
  topic: ({ value }) => {
434
465
  const topic = value?.trim();
@@ -438,13 +469,8 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
438
469
  else delete assertDraft().messageThreadId;
439
470
  return { kind: "to", screen: "review" };
440
471
  },
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" };
447
- },
472
+ save: ({ signal: actionSignal }) => saveDraft(actionSignal, true),
473
+ saveOnly: ({ signal: actionSignal }) => saveDraft(actionSignal, false),
448
474
  remove: async ({ signal: actionSignal }) => {
449
475
  await apply(saveDestination(store, selectedId, undefined, actionSignal));
450
476
  return { kind: "to", screen: "main" };
package/src/settings.ts CHANGED
@@ -23,7 +23,7 @@ export const MAX_INACTIVITY_SECONDS = 86_400;
23
23
  export const MAX_DESTINATIONS = 32;
24
24
  export const policyKeys = ["enabled", "mode", "inactivitySeconds", "targetIds"] as const;
25
25
  export const defaults = (): Settings => ({
26
- enabled: false,
26
+ enabled: true,
27
27
  mode: "immediate",
28
28
  inactivitySeconds: 30,
29
29
  targetIds: [],
@@ -219,6 +219,7 @@ export function saveDestination(
219
219
  id: string,
220
220
  destination: Destination | undefined,
221
221
  signal: AbortSignal,
222
+ selectNew = true,
222
223
  ) {
223
224
  if (!validId(id)) throw new Error("Invalid destination ID.");
224
225
  const normalized = destination ? store.validate(destination) : undefined;
@@ -230,6 +231,16 @@ export function saveDestination(
230
231
  throw new Error("Invalid destinations setting. Repair the file before changing destinations.");
231
232
  const destinations = isObject(document.destinations) ? { ...document.destinations } : {};
232
233
  if (normalized) {
234
+ if (selectNew && !Object.hasOwn(destinations, id)) {
235
+ const diagnostics: string[] = [];
236
+ const selection = policy(
237
+ Object.hasOwn(document, "targetIds") ? { targetIds: document.targetIds } : {},
238
+ diagnostics,
239
+ );
240
+ if (diagnostics.length)
241
+ throw new Error("Invalid selected destinations. Repair targetIds before adding a destination.");
242
+ document.targetIds = [...new Set([...(selection.targetIds ?? []), id])];
243
+ }
233
244
  if (Object.hasOwn(destinations, id) && !isObject(destinations[id]))
234
245
  throw new Error("Invalid stored destination. Repair the file before replacing this entry.");
235
246
  // Validators return owned optional keys as undefined so JSON publication removes them.