@narumitw/pi-notify 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +104 -2
- package/docs/settings.md +62 -0
- package/package.json +37 -4
- package/src/activity.ts +21 -0
- package/src/coordinator.ts +162 -0
- package/src/index.ts +1 -0
- package/src/menu.ts +520 -0
- package/src/metadata.ts +69 -0
- package/src/notify.ts +133 -0
- package/src/provider.ts +68 -0
- package/src/settings.ts +250 -0
- package/src/telegram.ts +94 -0
- package/src/text.ts +10 -0
package/src/menu.ts
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { defineMenu, runMenu, runSecretInput, runTask } from "@narumitw/pi-tui-kit";
|
|
4
|
+
import type { Coordinator } from "./coordinator.js";
|
|
5
|
+
import { displayPath, notificationMetadata, safeText } from "./metadata.js";
|
|
6
|
+
import type { Destination, Notification, Providers } from "./provider.js";
|
|
7
|
+
import {
|
|
8
|
+
policyKeys,
|
|
9
|
+
resolveSettings,
|
|
10
|
+
type Scope,
|
|
11
|
+
type Settings,
|
|
12
|
+
type SettingsStore,
|
|
13
|
+
type Snapshot,
|
|
14
|
+
saveDestination,
|
|
15
|
+
savePolicy,
|
|
16
|
+
validSeconds,
|
|
17
|
+
} from "./settings.js";
|
|
18
|
+
|
|
19
|
+
type Screen =
|
|
20
|
+
| "main"
|
|
21
|
+
| "destinations"
|
|
22
|
+
| "destination"
|
|
23
|
+
| "settings"
|
|
24
|
+
| "targets"
|
|
25
|
+
| "delay"
|
|
26
|
+
| "customDelay"
|
|
27
|
+
| "label"
|
|
28
|
+
| "chat"
|
|
29
|
+
| "topic"
|
|
30
|
+
| "review"
|
|
31
|
+
| "remove"
|
|
32
|
+
| "testSelect"
|
|
33
|
+
| "testReview"
|
|
34
|
+
| "status"
|
|
35
|
+
| "help";
|
|
36
|
+
type Action =
|
|
37
|
+
| "scope"
|
|
38
|
+
| "policy"
|
|
39
|
+
| "delay"
|
|
40
|
+
| "customDelay"
|
|
41
|
+
| "target"
|
|
42
|
+
| "inheritTargets"
|
|
43
|
+
| "add"
|
|
44
|
+
| "edit"
|
|
45
|
+
| "select"
|
|
46
|
+
| "token"
|
|
47
|
+
| "label"
|
|
48
|
+
| "chat"
|
|
49
|
+
| "topic"
|
|
50
|
+
| "save"
|
|
51
|
+
| "remove"
|
|
52
|
+
| "prepareTest"
|
|
53
|
+
| "sendTest";
|
|
54
|
+
interface State {
|
|
55
|
+
snapshot: Snapshot;
|
|
56
|
+
editing: Settings;
|
|
57
|
+
}
|
|
58
|
+
export interface MenuOptions {
|
|
59
|
+
store: SettingsStore;
|
|
60
|
+
coordinator: Coordinator;
|
|
61
|
+
providers: Providers;
|
|
62
|
+
signal: AbortSignal;
|
|
63
|
+
isCurrent(): boolean;
|
|
64
|
+
}
|
|
65
|
+
export const helpLines = [
|
|
66
|
+
"Create a bot with @BotFather in Telegram, then start a private conversation or add it to your group with permission to send messages.",
|
|
67
|
+
"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.",
|
|
68
|
+
"Use a negative group/supergroup chat ID when applicable. Forum topic IDs are optional positive integers.",
|
|
69
|
+
"Destinations are User settings only. Project settings require trust and may select existing destinations but cannot change credentials or addresses.",
|
|
70
|
+
"Notifications disclose hostname, session name/ID, workspace and Git metadata, elapsed time and timestamp. No conversation or code is sent.",
|
|
71
|
+
"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
|
+
"Input or new work cancels a pending reminder. Saved policy/destination changes cancel pending reminders. Settings save immediately; closing does not undo them.",
|
|
73
|
+
"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.",
|
|
76
|
+
];
|
|
77
|
+
|
|
78
|
+
export async function showNotifyMenu(ctx: ExtensionCommandContext, options: MenuOptions) {
|
|
79
|
+
const { store, coordinator, providers, signal, isCurrent } = options;
|
|
80
|
+
// Kit reserves one column internally; preserve the host's zero-width contract.
|
|
81
|
+
const custom: ExtensionCommandContext["ui"]["custom"] = (factory, customOptions) =>
|
|
82
|
+
ctx.ui.custom(async (...args) => {
|
|
83
|
+
const component = await factory(...args);
|
|
84
|
+
const render = component.render.bind(component);
|
|
85
|
+
component.render = (width) => (width <= 0 ? [] : render(width));
|
|
86
|
+
return component;
|
|
87
|
+
}, customOptions);
|
|
88
|
+
const menuCtx = { ...ctx, ui: { ...ctx.ui, custom } };
|
|
89
|
+
let scope: Scope = "user";
|
|
90
|
+
let selectedId = "";
|
|
91
|
+
let draft: Destination | undefined;
|
|
92
|
+
let testNotification: Notification | undefined;
|
|
93
|
+
let testDestination: Destination | undefined;
|
|
94
|
+
const current = () => {
|
|
95
|
+
signal.throwIfAborted();
|
|
96
|
+
if (!isCurrent()) throw new Error("Session replaced.");
|
|
97
|
+
};
|
|
98
|
+
const apply = async (operation: Promise<Snapshot>) => {
|
|
99
|
+
const snapshot = await operation;
|
|
100
|
+
current();
|
|
101
|
+
coordinator.apply(snapshot.effective);
|
|
102
|
+
};
|
|
103
|
+
const knownDestination = () => {
|
|
104
|
+
const destination = store.snapshot.effective.destinations[selectedId];
|
|
105
|
+
if (!destination) throw new Error("Destination is unavailable.");
|
|
106
|
+
return destination;
|
|
107
|
+
};
|
|
108
|
+
const assertDraft = () => {
|
|
109
|
+
if (!draft) throw new Error("Destination draft is unavailable.");
|
|
110
|
+
return draft;
|
|
111
|
+
};
|
|
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."];
|
|
121
|
+
const menu = defineMenu<State, Screen, Action>({
|
|
122
|
+
start: "main",
|
|
123
|
+
screens: {
|
|
124
|
+
main: ({ state }) => ({
|
|
125
|
+
kind: "actions",
|
|
126
|
+
title: "Notify",
|
|
127
|
+
lines: [
|
|
128
|
+
`Notifications: ${state.snapshot.effective.enabled ? "enabled" : "disabled"} · ${state.snapshot.effective.mode}`,
|
|
129
|
+
`Selected: ${state.snapshot.effective.targetIds.map((id) => safeText(state.snapshot.effective.destinations[id]?.label ?? id)).join(", ") || "none"}`,
|
|
130
|
+
`Editing: ${scope === "user" ? "User" : "Project"}`,
|
|
131
|
+
...state.snapshot.diagnostics,
|
|
132
|
+
],
|
|
133
|
+
items: [
|
|
134
|
+
{ id: "destinations", label: "Telegram destinations", to: "destinations" },
|
|
135
|
+
{ id: "test", label: "Send test to Telegram…", to: "testSelect" },
|
|
136
|
+
{ id: "settings", label: "Settings", to: "settings" },
|
|
137
|
+
{ id: "status", label: "Status", to: "status" },
|
|
138
|
+
{ id: "help", label: "Help", to: "help" },
|
|
139
|
+
],
|
|
140
|
+
hint: "close",
|
|
141
|
+
}),
|
|
142
|
+
destinations: ({ state }) => ({
|
|
143
|
+
kind: "actions",
|
|
144
|
+
title: "Telegram destinations · User",
|
|
145
|
+
items: [
|
|
146
|
+
...Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
|
|
147
|
+
id,
|
|
148
|
+
label: safeText(value.label),
|
|
149
|
+
description: `Telegram · ${safeText(value.chatId)} · token configured`,
|
|
150
|
+
action: "select" as const,
|
|
151
|
+
})),
|
|
152
|
+
{ id: "add", label: "Add Telegram destination", action: "add" },
|
|
153
|
+
],
|
|
154
|
+
}),
|
|
155
|
+
destination: () => ({
|
|
156
|
+
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
|
+
],
|
|
163
|
+
items: [
|
|
164
|
+
{ id: "edit", label: "Edit destination", action: "edit" },
|
|
165
|
+
{ id: "remove", label: "Remove destination…", to: "remove" },
|
|
166
|
+
],
|
|
167
|
+
}),
|
|
168
|
+
settings: ({ state }) => {
|
|
169
|
+
const own = state.snapshot[scope];
|
|
170
|
+
const inherited = (key: (typeof policyKeys)[number]) => scope === "project" && !Object.hasOwn(own, key);
|
|
171
|
+
return {
|
|
172
|
+
kind: "settings",
|
|
173
|
+
title: `Notify Settings · ${scope === "user" ? "User" : "Project"}`,
|
|
174
|
+
lines: ["Changes save immediately. Closing does not undo saved changes."],
|
|
175
|
+
items: [
|
|
176
|
+
{
|
|
177
|
+
id: "scope",
|
|
178
|
+
label: "Scope",
|
|
179
|
+
currentValue: scope === "user" ? "User" : "Project",
|
|
180
|
+
values: ["User", "Project"],
|
|
181
|
+
action: "scope",
|
|
182
|
+
description: store.projectPath
|
|
183
|
+
? "Project overrides require trust."
|
|
184
|
+
: "Project scope is unavailable until trusted.",
|
|
185
|
+
},
|
|
186
|
+
{
|
|
187
|
+
id: "enabled",
|
|
188
|
+
label: "Notifications",
|
|
189
|
+
currentValue: inherited("enabled") ? "Inherit" : String(own.enabled ?? false),
|
|
190
|
+
values: scope === "project" ? ["Inherit", "true", "false"] : ["false", "true"],
|
|
191
|
+
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"}.`,
|
|
193
|
+
},
|
|
194
|
+
{
|
|
195
|
+
id: "mode",
|
|
196
|
+
label: "Mode",
|
|
197
|
+
currentValue: inherited("mode") ? "Inherit" : String(own.mode ?? "immediate"),
|
|
198
|
+
values:
|
|
199
|
+
scope === "project" ? ["Inherit", "immediate", "after-inactivity"] : ["immediate", "after-inactivity"],
|
|
200
|
+
action: "policy",
|
|
201
|
+
description: `Effective: ${state.snapshot.effective.mode}. Inactivity falls back to immediate outside TUI.`,
|
|
202
|
+
},
|
|
203
|
+
{
|
|
204
|
+
id: "inactivitySeconds",
|
|
205
|
+
label: "Input inactivity time",
|
|
206
|
+
currentValue: `${state.editing.inactivitySeconds}s${inherited("inactivitySeconds") ? " (inherited)" : ""}`,
|
|
207
|
+
disabled: state.editing.mode !== "after-inactivity",
|
|
208
|
+
action: "delay",
|
|
209
|
+
description:
|
|
210
|
+
"Only forwarded input resets this timer. Fullscreen focus, mouse, and viewport/search keys may not reach it.",
|
|
211
|
+
},
|
|
212
|
+
{
|
|
213
|
+
id: "targetIds",
|
|
214
|
+
label: "Selected destinations",
|
|
215
|
+
currentValue: `${state.editing.targetIds.length}${inherited("targetIds") ? " (inherited)" : ""}`,
|
|
216
|
+
action: "target",
|
|
217
|
+
description: "Select existing User destinations for this scope.",
|
|
218
|
+
},
|
|
219
|
+
],
|
|
220
|
+
};
|
|
221
|
+
},
|
|
222
|
+
targets: ({ state }) => ({
|
|
223
|
+
kind: "multiSelect",
|
|
224
|
+
title: `Selected destinations · ${scope}`,
|
|
225
|
+
items: Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
|
|
226
|
+
id,
|
|
227
|
+
label: safeText(value.label),
|
|
228
|
+
description: safeText(value.chatId),
|
|
229
|
+
selected: state.editing.targetIds.includes(id),
|
|
230
|
+
})),
|
|
231
|
+
action: "target",
|
|
232
|
+
enableSearch: true,
|
|
233
|
+
actions:
|
|
234
|
+
scope === "project"
|
|
235
|
+
? [{ id: "inherit", label: "Restore inherited selection", action: "inheritTargets" }]
|
|
236
|
+
: [],
|
|
237
|
+
}),
|
|
238
|
+
delay: () => ({
|
|
239
|
+
kind: "choice",
|
|
240
|
+
title: `Input inactivity time · ${scope}`,
|
|
241
|
+
items: [
|
|
242
|
+
...(scope === "project" ? [{ id: "inherit", label: "Inherit User setting" }] : []),
|
|
243
|
+
{ id: "30", label: "30 seconds" },
|
|
244
|
+
{ id: "60", label: "1 minute" },
|
|
245
|
+
{ id: "120", label: "2 minutes" },
|
|
246
|
+
{ id: "custom", label: "Custom seconds…" },
|
|
247
|
+
],
|
|
248
|
+
action: "delay",
|
|
249
|
+
}),
|
|
250
|
+
customDelay: ({ state }) => ({
|
|
251
|
+
kind: "input",
|
|
252
|
+
title: "Inactivity seconds",
|
|
253
|
+
lines: ["Whole seconds from 1 to 86400."],
|
|
254
|
+
initialValue: String(state.editing.inactivitySeconds),
|
|
255
|
+
action: "customDelay",
|
|
256
|
+
}),
|
|
257
|
+
label: () => ({
|
|
258
|
+
kind: "input",
|
|
259
|
+
title: "Telegram destination label",
|
|
260
|
+
initialValue: assertDraft().label,
|
|
261
|
+
action: "label",
|
|
262
|
+
}),
|
|
263
|
+
chat: () => ({
|
|
264
|
+
kind: "input",
|
|
265
|
+
title: "Telegram chat ID",
|
|
266
|
+
lines: ["Numeric private chat, group, or supergroup ID. Group IDs can be negative."],
|
|
267
|
+
initialValue: assertDraft().chatId,
|
|
268
|
+
action: "chat",
|
|
269
|
+
}),
|
|
270
|
+
topic: () => ({
|
|
271
|
+
kind: "input",
|
|
272
|
+
title: "Forum topic ID (optional)",
|
|
273
|
+
lines: ["Leave empty for no topic."],
|
|
274
|
+
initialValue: String(assertDraft().messageThreadId ?? ""),
|
|
275
|
+
action: "topic",
|
|
276
|
+
}),
|
|
277
|
+
review: () => ({
|
|
278
|
+
kind: "actions",
|
|
279
|
+
title: "Review Telegram destination · User",
|
|
280
|
+
lines: draftLines(),
|
|
281
|
+
items: [
|
|
282
|
+
{ id: "save", label: "Save destination", action: "save" },
|
|
283
|
+
{ id: "token", label: "Replace bot token…", action: "token" },
|
|
284
|
+
],
|
|
285
|
+
}),
|
|
286
|
+
remove: () => ({
|
|
287
|
+
kind: "actions",
|
|
288
|
+
title: "Remove Telegram destination?",
|
|
289
|
+
lines: [
|
|
290
|
+
safeText(knownDestination().label),
|
|
291
|
+
"Also removes its User selection. Existing messages are not recalled.",
|
|
292
|
+
"Remove any Project selection first.",
|
|
293
|
+
],
|
|
294
|
+
items: [{ id: "confirm", label: "Remove destination", action: "remove" }],
|
|
295
|
+
}),
|
|
296
|
+
testSelect: ({ state }) => ({
|
|
297
|
+
kind: "actions",
|
|
298
|
+
title: "Test destination · sends externally",
|
|
299
|
+
items: Object.entries(state.snapshot.effective.destinations).map(([id, value]) => ({
|
|
300
|
+
id,
|
|
301
|
+
label: safeText(value.label),
|
|
302
|
+
action: "prepareTest" as const,
|
|
303
|
+
})),
|
|
304
|
+
}),
|
|
305
|
+
testReview: () => ({
|
|
306
|
+
kind: "review",
|
|
307
|
+
title: `Send test to ${safeText(testDestination?.label ?? "Telegram")}?`,
|
|
308
|
+
content: `${testNotification?.title ?? ""}\n${testNotification?.body ?? ""}`,
|
|
309
|
+
viewportSize: "adaptive",
|
|
310
|
+
confirm: { id: "send", label: "Send test to Telegram", action: "sendTest" },
|
|
311
|
+
}),
|
|
312
|
+
status: ({ state }) => ({
|
|
313
|
+
kind: "detail",
|
|
314
|
+
title: "Notify Status",
|
|
315
|
+
lines: [
|
|
316
|
+
`User: ${displayPath(store.userPath)}`,
|
|
317
|
+
`Project: ${store.projectPath ? displayPath(store.projectPath) : "not trusted / unavailable"}`,
|
|
318
|
+
...policyKeys.map(
|
|
319
|
+
(key) =>
|
|
320
|
+
`${key}: source ${Object.hasOwn(state.snapshot.project, key) ? "Project" : Object.hasOwn(state.snapshot.user, key) ? "User" : "default"}`,
|
|
321
|
+
),
|
|
322
|
+
`Pending reminder: ${coordinator.pendingAt ? new Date(coordinator.pendingAt).toISOString() : "none"}`,
|
|
323
|
+
...Object.entries(state.snapshot.effective.destinations).map(([id, value]) => {
|
|
324
|
+
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"}`;
|
|
326
|
+
}),
|
|
327
|
+
...state.snapshot.diagnostics,
|
|
328
|
+
],
|
|
329
|
+
}),
|
|
330
|
+
help: () => ({ kind: "detail", title: "Notify Help", lines: helpLines }),
|
|
331
|
+
},
|
|
332
|
+
actions: {
|
|
333
|
+
scope: ({ value }) => {
|
|
334
|
+
if (value === "Project" && !store.projectPath)
|
|
335
|
+
throw new Error("Trust the project before editing Project settings.");
|
|
336
|
+
scope = value === "Project" ? "project" : "user";
|
|
337
|
+
return { kind: "stay" };
|
|
338
|
+
},
|
|
339
|
+
policy: async ({ itemId, value, signal: actionSignal }) => {
|
|
340
|
+
if (itemId !== "enabled" && itemId !== "mode") throw new Error("Invalid setting.");
|
|
341
|
+
await apply(
|
|
342
|
+
savePolicy(
|
|
343
|
+
store,
|
|
344
|
+
scope,
|
|
345
|
+
itemId,
|
|
346
|
+
value === "Inherit" ? undefined : itemId === "enabled" ? value === "true" : value,
|
|
347
|
+
actionSignal,
|
|
348
|
+
),
|
|
349
|
+
);
|
|
350
|
+
return { kind: "stay" };
|
|
351
|
+
},
|
|
352
|
+
delay: async ({ itemId, signal: actionSignal }) => {
|
|
353
|
+
if (itemId === "inactivitySeconds") return { kind: "to", screen: "delay" };
|
|
354
|
+
if (itemId === "custom") return { kind: "to", screen: "customDelay" };
|
|
355
|
+
await apply(
|
|
356
|
+
savePolicy(
|
|
357
|
+
store,
|
|
358
|
+
scope,
|
|
359
|
+
"inactivitySeconds",
|
|
360
|
+
itemId === "inherit" ? undefined : Number(itemId),
|
|
361
|
+
actionSignal,
|
|
362
|
+
),
|
|
363
|
+
);
|
|
364
|
+
return { kind: "back" };
|
|
365
|
+
},
|
|
366
|
+
customDelay: async ({ value, signal: actionSignal }) => {
|
|
367
|
+
if (!value || !/^\d+$/.test(value) || !validSeconds(Number(value)))
|
|
368
|
+
throw new Error("Use whole seconds from 1 to 86400.");
|
|
369
|
+
await apply(savePolicy(store, scope, "inactivitySeconds", Number(value), actionSignal));
|
|
370
|
+
return { kind: "to", screen: "settings" };
|
|
371
|
+
},
|
|
372
|
+
target: async ({ itemId, selected, signal: actionSignal }) => {
|
|
373
|
+
if (itemId === "targetIds") return { kind: "to", screen: "targets" };
|
|
374
|
+
await apply(
|
|
375
|
+
store.change(
|
|
376
|
+
scope,
|
|
377
|
+
(document, project, user) => {
|
|
378
|
+
const edited = resolveSettings(user, scope === "project" ? project : {}, providers).effective;
|
|
379
|
+
const ids = new Set(edited.targetIds);
|
|
380
|
+
if (selected) ids.add(itemId);
|
|
381
|
+
else ids.delete(itemId);
|
|
382
|
+
document.targetIds = [...ids];
|
|
383
|
+
},
|
|
384
|
+
actionSignal,
|
|
385
|
+
),
|
|
386
|
+
);
|
|
387
|
+
return { kind: "stay" };
|
|
388
|
+
},
|
|
389
|
+
inheritTargets: async ({ signal: actionSignal }) => {
|
|
390
|
+
await apply(savePolicy(store, "project", "targetIds", undefined, actionSignal));
|
|
391
|
+
return { kind: "stay" };
|
|
392
|
+
},
|
|
393
|
+
select: ({ itemId }) => {
|
|
394
|
+
selectedId = itemId;
|
|
395
|
+
return { kind: "to", screen: "destination" };
|
|
396
|
+
},
|
|
397
|
+
add: async ({ signal: actionSignal }) => {
|
|
398
|
+
const result = await runSecretInput(menuCtx, { title: "Telegram bot token", signal: actionSignal, isCurrent });
|
|
399
|
+
actionSignal.throwIfAborted();
|
|
400
|
+
current();
|
|
401
|
+
if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
|
|
402
|
+
if (result.kind !== "submitted") return { kind: "stay" };
|
|
403
|
+
selectedId = randomUUID();
|
|
404
|
+
draft = { provider: "telegram", label: "", botToken: result.value.trim(), chatId: "" };
|
|
405
|
+
return { kind: "to", screen: "label" };
|
|
406
|
+
},
|
|
407
|
+
edit: () => {
|
|
408
|
+
draft = { ...knownDestination() };
|
|
409
|
+
return { kind: "to", screen: "label" };
|
|
410
|
+
},
|
|
411
|
+
token: async ({ signal: actionSignal }) => {
|
|
412
|
+
const result = await runSecretInput(menuCtx, {
|
|
413
|
+
title: "Replace Telegram bot token",
|
|
414
|
+
signal: actionSignal,
|
|
415
|
+
isCurrent,
|
|
416
|
+
});
|
|
417
|
+
actionSignal.throwIfAborted();
|
|
418
|
+
current();
|
|
419
|
+
if (result.kind === "submitted") assertDraft().botToken = result.value.trim();
|
|
420
|
+
if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
|
|
421
|
+
return { kind: "stay" };
|
|
422
|
+
},
|
|
423
|
+
label: ({ value }) => {
|
|
424
|
+
if (!value?.trim() || value.length > 128) throw new Error("Use a label from 1 to 128 characters.");
|
|
425
|
+
assertDraft().label = value.trim();
|
|
426
|
+
return { kind: "to", screen: "chat" };
|
|
427
|
+
},
|
|
428
|
+
chat: ({ value }) => {
|
|
429
|
+
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" };
|
|
432
|
+
},
|
|
433
|
+
topic: ({ value }) => {
|
|
434
|
+
const topic = value?.trim();
|
|
435
|
+
if (topic && (!/^\d+$/.test(topic) || !Number.isSafeInteger(Number(topic)) || Number(topic) <= 0))
|
|
436
|
+
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;
|
|
439
|
+
return { kind: "to", screen: "review" };
|
|
440
|
+
},
|
|
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
|
+
},
|
|
448
|
+
remove: async ({ signal: actionSignal }) => {
|
|
449
|
+
await apply(saveDestination(store, selectedId, undefined, actionSignal));
|
|
450
|
+
return { kind: "to", screen: "main" };
|
|
451
|
+
},
|
|
452
|
+
prepareTest: async ({ itemId, signal: actionSignal }) => {
|
|
453
|
+
selectedId = itemId;
|
|
454
|
+
testDestination = { ...knownDestination() };
|
|
455
|
+
const now = Date.now();
|
|
456
|
+
const notification = await notificationMetadata(
|
|
457
|
+
{
|
|
458
|
+
id: `test-${randomUUID()}`,
|
|
459
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
460
|
+
sessionName: ctx.sessionManager.getSessionName(),
|
|
461
|
+
cwd: ctx.cwd,
|
|
462
|
+
startedAt: now,
|
|
463
|
+
settledAt: now,
|
|
464
|
+
error: false,
|
|
465
|
+
},
|
|
466
|
+
actionSignal,
|
|
467
|
+
);
|
|
468
|
+
actionSignal.throwIfAborted();
|
|
469
|
+
current();
|
|
470
|
+
testNotification = { ...notification, title: "Pi notification test" };
|
|
471
|
+
return { kind: "to", screen: "testReview" };
|
|
472
|
+
},
|
|
473
|
+
sendTest: async ({ signal: actionSignal }) => {
|
|
474
|
+
current();
|
|
475
|
+
if (!testDestination || !testNotification) throw new Error("Prepare a new test.");
|
|
476
|
+
const destination = testDestination;
|
|
477
|
+
const notification = testNotification;
|
|
478
|
+
const result = await runTask(menuCtx, {
|
|
479
|
+
label: "Sending Telegram test…",
|
|
480
|
+
signal: actionSignal,
|
|
481
|
+
isCurrent,
|
|
482
|
+
task: ({ signal: taskSignal }) => coordinator.send(selectedId, destination, notification, taskSignal),
|
|
483
|
+
});
|
|
484
|
+
actionSignal.throwIfAborted();
|
|
485
|
+
current();
|
|
486
|
+
if (result.kind === "completed")
|
|
487
|
+
ctx.ui.notify(
|
|
488
|
+
result.value.state === "accepted"
|
|
489
|
+
? "Telegram accepted the test notification."
|
|
490
|
+
: `Telegram test: ${result.value.state === "failed" ? result.value.code : result.value.state}.`,
|
|
491
|
+
result.value.state === "accepted" ? "info" : "warning",
|
|
492
|
+
);
|
|
493
|
+
if (result.kind === "cancelled") return { kind: "close" };
|
|
494
|
+
return { kind: "to", screen: "main" };
|
|
495
|
+
},
|
|
496
|
+
},
|
|
497
|
+
});
|
|
498
|
+
try {
|
|
499
|
+
return await runMenu(menuCtx, menu, {
|
|
500
|
+
signal,
|
|
501
|
+
isCurrent,
|
|
502
|
+
getState: () => ({
|
|
503
|
+
snapshot: store.snapshot,
|
|
504
|
+
editing: resolveSettings(store.snapshot.user, scope === "project" ? store.snapshot.project : {}, providers)
|
|
505
|
+
.effective,
|
|
506
|
+
}),
|
|
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
|
+
},
|
|
514
|
+
});
|
|
515
|
+
} finally {
|
|
516
|
+
draft = undefined;
|
|
517
|
+
testDestination = undefined;
|
|
518
|
+
testNotification = undefined;
|
|
519
|
+
}
|
|
520
|
+
}
|
package/src/metadata.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { homedir, hostname } from "node:os";
|
|
3
|
+
import { basename, dirname, isAbsolute, sep } from "node:path";
|
|
4
|
+
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
|
|
5
|
+
import type { Notification } from "./provider.js";
|
|
6
|
+
import { clipText } from "./text.js";
|
|
7
|
+
|
|
8
|
+
export interface Metadata {
|
|
9
|
+
id: string;
|
|
10
|
+
sessionId: string;
|
|
11
|
+
sessionName?: string;
|
|
12
|
+
cwd: string;
|
|
13
|
+
startedAt: number;
|
|
14
|
+
settledAt: number;
|
|
15
|
+
error: boolean;
|
|
16
|
+
}
|
|
17
|
+
export const safeText = (value: string) => clipText(sanitizeTerminalText(value).replaceAll("@", "@"), 400);
|
|
18
|
+
export function displayPath(raw: string): string {
|
|
19
|
+
const path = safeText(raw);
|
|
20
|
+
const home = safeText(homedir());
|
|
21
|
+
return path === home ? "~" : path.startsWith(`${home}${sep}`) ? `~${path.slice(home.length)}` : path;
|
|
22
|
+
}
|
|
23
|
+
function git(cwd: string, args: string[], signal: AbortSignal): Promise<string | undefined> {
|
|
24
|
+
return new Promise((resolve) => {
|
|
25
|
+
execFile(
|
|
26
|
+
"git",
|
|
27
|
+
["-C", cwd, "rev-parse", ...args],
|
|
28
|
+
{ signal, timeout: 1500, maxBuffer: 8192, encoding: "utf8", windowsHide: true },
|
|
29
|
+
(error, stdout) => resolve(error ? undefined : stdout.trim()),
|
|
30
|
+
);
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
export async function notificationMetadata(data: Metadata, signal: AbortSignal): Promise<Notification> {
|
|
34
|
+
const [root, common, branch] = await Promise.all([
|
|
35
|
+
git(data.cwd, ["--show-toplevel"], signal),
|
|
36
|
+
git(data.cwd, ["--git-common-dir"], signal),
|
|
37
|
+
git(data.cwd, ["--abbrev-ref", "HEAD"], signal),
|
|
38
|
+
]);
|
|
39
|
+
signal.throwIfAborted();
|
|
40
|
+
const detached = branch === "HEAD" ? await git(data.cwd, ["--short", "HEAD"], signal) : undefined;
|
|
41
|
+
signal.throwIfAborted();
|
|
42
|
+
const lines = [
|
|
43
|
+
`Computer: ${safeText(hostname())}`,
|
|
44
|
+
`Session: ${data.sessionName ? `${safeText(data.sessionName)} ` : ""}(${safeText(data.sessionId)})`,
|
|
45
|
+
`Workspace: ${displayPath(data.cwd)}`,
|
|
46
|
+
];
|
|
47
|
+
if (root) {
|
|
48
|
+
// Sanitize before splitting paths. Common Git directory names identify linked worktrees.
|
|
49
|
+
const cleanRoot = safeText(root);
|
|
50
|
+
const cleanCommon = common ? safeText(common) : undefined;
|
|
51
|
+
const commonDirectory = cleanCommon && isAbsolute(cleanCommon) ? cleanCommon : undefined;
|
|
52
|
+
const repository =
|
|
53
|
+
commonDirectory && basename(commonDirectory) === ".git"
|
|
54
|
+
? basename(dirname(commonDirectory))
|
|
55
|
+
: basename(cleanRoot);
|
|
56
|
+
lines.push(`Repository: ${repository}`, `Worktree: ${displayPath(root)}`);
|
|
57
|
+
if (branch) lines.push(`Branch: ${safeText(branch === "HEAD" ? `detached ${detached ?? "HEAD"}` : branch)}`);
|
|
58
|
+
}
|
|
59
|
+
lines.push(
|
|
60
|
+
`Elapsed: ${Math.max(0, Math.floor((data.settledAt - data.startedAt) / 1000))}s`,
|
|
61
|
+
`Stopped: ${new Date(data.settledAt).toISOString()}`,
|
|
62
|
+
);
|
|
63
|
+
return {
|
|
64
|
+
id: data.id,
|
|
65
|
+
title: data.error ? "Pi stopped with an error" : "Pi is ready for review",
|
|
66
|
+
body: lines.join("\n"),
|
|
67
|
+
settledAt: data.settledAt,
|
|
68
|
+
};
|
|
69
|
+
}
|