@hienlh/ppm 0.25.2 → 0.25.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.25.3] - 2026-11-14
4
+
5
+ ### Fixed
6
+
7
+ - **A chat waiting on your database approval or login now tells Telegram**, with the project, chat, connection and the SQL (secrets hidden), and a link to answer in PPM; Telegram never takes the password.
8
+ - **A database change waits 30 minutes for your answer** instead of 10, with one reminder 5 minutes before it ends.
9
+ - **SQL or a reason that mentions a password is never sent** to Telegram or to push and ntfy notifications.
10
+
3
11
  ## [0.25.2] - 2026-11-14
4
12
 
5
13
  ### Added
package/CLAUDE.md CHANGED
@@ -255,7 +255,7 @@ Related: `configService.save()`/`set()` throw when `load()` has not run, because
255
255
  - **Telegram HTML must be escaped before it is formatted, and a bot has one reader**: PPMBot's formatter converted Markdown without escaping, so one `<` or `&` in an answer made Telegram refuse the whole message ("can't parse entities"); `telegram/telegram-html-format.ts` escapes first and splits without cutting a tag. And Telegram answers a second `getUpdates` on the same bot with 409, so two programs (or a dev and a live PPM) on one bot starve each other — the bridge and the connect-link poller hand the bot over through `assistantBridgeReading`.
256
256
  - **Bun's `mock.module` is process-global, so a partial mock breaks *other* test files**: the mock outlives the file that set it, and any file run later in the same process that imports the real module gets the stub. A stub missing one export the real module has then fails *that* file at link time, far from the mock: `tunnel-registry-routes.test.ts` replaced `tunnel-spawn.ts` without `MAX_PROBE_FAILURES`, and `assistant-route-call.test.ts` — which loads the server's routers — failed only when the two ran together. Capture the real module first and spread it (`...RealTunnelSpawn`) under the overrides.
257
257
  - **A schedule's `updated_at` moves on its own**: the scheduler writes `last_run_at`/`next_fire_at` after every run and when a run opens its session, which bumps `updated_at`, so "unchanged since the card was built" cannot be judged by that column alone — a schedule firing every few minutes could never be approved. The Assistant's schedule tools accept an unchanged `updated_at` and otherwise compare the fields the card showed (`unchangedSince` in `assistant-schedule-shape.ts`).
258
- - **A `db_execute` approval is answered over HTTP, never over the chat socket**: the card posts `{ approved, password }` to `/api/db/ai-approvals/:requestId` so a wrong password can be answered on the card while the approval stays pending, and so the password is never in a socket broadcast or the session trace. `ws/chat.ts` drops an `approval_response` naming one of these requests (`ppmApprovals.has`, which covers the session tools' cards too) — without that, an older bundle's generic Allow cleared the slot and took the card off every device while the broker went on waiting, so the AI sat out the ten minutes.
258
+ - **A `db_execute` approval is answered over HTTP, never over the chat socket**: the card posts `{ approved, password }` to `/api/db/ai-approvals/:requestId` so a wrong password can be answered on the card while the approval stays pending, and so the password is never in a socket broadcast or the session trace. `ws/chat.ts` drops an `approval_response` naming one of these requests (`ppmApprovals.has`, which covers the session tools' cards too) — without that, an older bundle's generic Allow cleared the slot and took the card off every device while the broker went on waiting, so the AI sat out the whole wait (now 30 minutes).
259
259
  - **A session has one approval slot, and a provider's approval must keep it**: `entry.pendingApprovalEvent` is what `session_state` replays and what the browser's single `pendingApproval` shows. A `db_execute` (or a session tool's card) announced while Claude or Codex waits on its own approval (parallel tool calls in a non-bypass session) used to overwrite it — the provider's card vanished and its turn waited forever. `announcePpmApproval` offers it to the slot (`chat-pending-approval.ts`, origin `ppm`), which never queues it: while another card holds the slot it waits in its broker, and the slot's `idle` shows it once the slot is free. `tests/unit/ws/chat-db-approval.test.ts` pins it. Two provider requests at once break it the same way: Claude asking two `AskUserQuestion` in one message put the second card over the first, the answer to the second emptied the slot, and the turn waited on the first for over two hours with nothing on screen to answer. A provider (or PPM Assistant endpoint) request arriving while another holds the slot now waits in `entry.approvalQueue` and is **not sent** until the slot's `promote` shows it (one of PPM's own approvals in the slot gives way instead: it waits in its broker and comes back after the queue); a message typed instead declines every request in line (`supersedeApprovals`; never just drops one: a background agent can still be waiting after `done`, which is why provider and endpoint cards stay through a `done` while PPM's own end with the turn), nothing else that empties the slot may run while a request is on screen (stopping a background command used to), and an answer to one still in line only takes it out of line (`tests/unit/ws/chat-parallel-approvals.test.ts`). PPM's approvals are cancelled **before** the slot is cleared: a cancelled one's `resolved` re-enters the slot, and settled first, none of them is shown again as the other cards leave.
260
260
  - **A session tool's wait has to survive two timeouts that are not its own, and a message pushed to Claude with no live stream goes nowhere**: `send_to_session { wait: true }` holds one MCP request open for up to an hour with no byte sent. Bun.serve cuts such a request after **10 s** of silence, so `/api/sessions-mcp` calls `server.timeout(req, 0)` through `c.env` — which exists only when the server is passed in (`app.fetch(req, server)`); a test or fixture server that calls `app.fetch(req)` gets waits that die at 10 s. And the provider's per-server MCP timeout is read **once, when the CLI starts**, so it cannot follow the wait setting: it is fixed at the settings' maximum plus the card time (`SESSION_COLLAB_TOOLS_TIMEOUT_MS`), or a user who lengthens the wait gets calls the still-running CLI cuts at the old value. Separately, both providers' `pushMessage` return **false** and drop the message when the session has no live stream (one starting up, or one torn down while PPM was still building the turn's context) — it used to be dropped without a word. `ws/chat.ts` therefore waits for a stream to be live or for no consumer at all (`awaitLiveStreamOrNone`) before choosing push or a new turn, hands a refused push over to a new turn once the consumer has wound down (`handOffToSession`), echoes the message to devices only after the provider has it, and reports `inserted`/`queued`/`started` from what actually happened. `tests/e2e/session-collab-e2e.mjs` scenario 9 holds a real 60 s wait through the fixture server.
261
261
  - **"PPM's password" is the auth token, so it proves presence, not a secret the AI lacks**: the token sits in `ppm.db`, which any process of the same OS user — the agent included — can read. The user chose it knowing that; the protection that holds regardless is that the connection's credentials never leave PPM and every change is shown, approved once and audited. Do not describe it as more than that.
@@ -83,4 +83,4 @@ This skill covers the `ppm` CLI, its HTTP API, and its config DB. It does **not*
83
83
  - Third-party extensions (inspect via `ppm ext list`).
84
84
  - The Claude Agent SDK internals (separate skill).
85
85
 
86
- <!-- Generated for PPM v0.25.2 at build time. Re-run `ppm export skill --install` to refresh. -->
86
+ <!-- Generated for PPM v0.25.3 at build time. Re-run `ppm export skill --install` to refresh. -->
@@ -842,4 +842,4 @@ Authenticate with `?token=<token>` (see Authentication).
842
842
  - `/ws/android`
843
843
  - `/ws/project/<project>/<type>/<id>` — `<type>`: `terminal`, `chat`, `group`, `lsp` (for `chat`, `<id>` is the session id)
844
844
 
845
- <!-- Generated from src/server/routes/ for PPM v0.25.2 -->
845
+ <!-- Generated from src/server/routes/ for PPM v0.25.3 -->
@@ -1042,10 +1042,11 @@ default), and never in a design session.
1042
1042
  `http` server `ppm-db` with the token in `Authorization` and the three tools allowed by the
1043
1043
  PreToolUse hook (`CLAUDE_DB_TOOLS` — `db_execute` asks the user itself, with more than a generic
1044
1044
  Allow could show), and Codex gets `mcp_servers.ppm_db` with `bearer_token_env_var` and
1045
- `default_tools_approval_mode = "approve"`. Both are given a 45-minute tool timeout
1046
- (`DB_TOOLS_TIMEOUT_MS`): the user's ten minutes to answer plus the approved script's own run.
1045
+ `default_tools_approval_mode = "approve"`. Both are given a 65-minute tool timeout
1046
+ (`DB_TOOLS_TIMEOUT_MS`): the user's thirty minutes to answer plus the approved script's own run.
1047
1047
  `/api/db-tools-mcp` (`db-ai-tools-endpoint.ts`, mounted before auth) resolves the token to its
1048
- session.
1048
+ session, and lifts Bun's idle timeout for the request (`server.timeout(req, 0)`, as
1049
+ `/api/sessions-mcp` does), since a `db_execute` call holds it for as long as the approval waits.
1049
1050
 
1050
1051
  **`db_query`** refuses SQL that `isReadOnlyQuery` reads as a write, pointing the AI at
1051
1052
  `db_execute`, then opens the connection with `readonly: true` whatever the connection's own
@@ -1084,8 +1085,8 @@ Then `db-approval-broker.ts` asks:
1084
1085
  A socket's `approval_response` for such a request is ignored.
1085
1086
  3. The approval settles as approved (the right password), declined (Decline), cancelled (the
1086
1087
  user sends a message, presses Stop, deletes the chat, the turn ends first, or the provider drops
1087
- the call) or timed out (10 minutes). Every outcome takes the card off every device
1088
- (`approval_resolved`).
1088
+ the call) or timed out (`DB_APPROVAL_WAIT_MS`, 30 minutes). Every outcome takes the card off
1089
+ every device (`approval_resolved`).
1089
1090
  One approval per session at a time; a second call while one waits is answered "busy".
1090
1091
  4. Approved, `runApprovedScript` (`db-ai-run.ts`) opens a writable session — a readonly
1091
1092
  connection included: the approval is what lifts it, for that script — runs `BEGIN` (or
@@ -1094,6 +1095,16 @@ Then `db-approval-broker.ts` asks:
1094
1095
  other than `expected_rows` rolls everything back. MySQL and MariaDB commit DDL by
1095
1096
  themselves, which the tool description says.
1096
1097
 
1098
+ **Away from PPM.** The card is one of PPM's own approvals, so it never reaches the PPM Assistant's
1099
+ Telegram chats as a card — answering it takes PPM's password, which Telegram never carries. The
1100
+ broker tells `db-attention-events.ts` instead: `approval_shown` when it asks, and
1101
+ `approval_reminder` once, `DB_APPROVAL_REMINDER_BEFORE_MS` (5 minutes) before it gives up. A tool
1102
+ reaching a connection that asks for its password with no login held tells the same bus
1103
+ `login_needed` (`db-login-attention.ts`, once per connection and chat in 30 minutes) and sends a
1104
+ *Database login needed* notification through the usual channels. The Assistant's Telegram bridge
1105
+ turns these into notices with no buttons but *Open in PPM*
1106
+ ([PPM Assistant → Telegram](ppm-assistant.md#telegram)).
1107
+
1097
1108
  "PPM's password" is the auth token the user signs in with (`ppm-password.ts`; with auth off, no
1098
1109
  password is asked). It is a check that the person at the screen means it, not a secret from the
1099
1110
  AI: the token is in `ppm.db`, which a process running as the same OS user can read. The
@@ -1140,6 +1140,17 @@ when two watches and `/status` all want it. In quiet hours a watched chat's card
1140
1140
  chat still shows the request; one answered meanwhile is skipped. The hold is in memory: a restart
1141
1141
  drops it, and the card itself stays in PPM for as long as the chat shows it.
1142
1142
 
1143
+ **Database notices** (`assistant-telegram-db-notices.ts`). A chat's `db_execute` waiting for
1144
+ approval, the reminder 5 minutes before it gives up, and a connection nobody has logged in to
1145
+ (`db-attention-events.ts`, see [AI database tools](ai-chat-and-providers.md)) reach every
1146
+ connected chat as notices: project, chat, connection and database, and for a change the SQL
1147
+ (redacted, then cut at 600 characters) and the AI's reason, with an *Open in PPM* link and no
1148
+ other button. A script or reason that mentions a password is not shown at all: SQL spells a
1149
+ password literal in too many ways for a pattern to be trusted with it. Answering takes PPM's password and logging in takes the database's, and neither is
1150
+ asked for or taken on Telegram; every notice says so. In quiet hours the approval's notice is held
1151
+ like a watched chat's card and sent at their end if the change still waits; the reminder and the
1152
+ login notice are dropped.
1153
+
1143
1154
  ### Manager cards, replies and quiet hours
1144
1155
 
1145
1156
  **Cards on the phone** (`card-outbound.ts`, `assistant-telegram-manager-cards.ts`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hienlh/ppm",
3
- "version": "0.25.2",
3
+ "version": "0.25.3",
4
4
  "description": "Personal Project Manager — mobile-first web IDE with AI assistance",
5
5
  "author": "hienlh",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -997,7 +997,9 @@ const approvals: PendingApprovals = createPendingApprovals({
997
997
  // Not buffered into the turn's replay: the tool call's own card already shows what is
998
998
  // asked, and a device that connects later reads the approval from `session_state`. Told to
999
999
  // chat listeners only when it is a session-tool card of the PPM Assistant, which Telegram
1000
- // shows too; the others are answered over HTTP with PPM's password, nowhere else.
1000
+ // shows too; the others are answered over HTTP with PPM's password, nowhere else. A
1001
+ // `db_execute` card still reaches Telegram, as a notice with no buttons: the broker tells
1002
+ // `db-attention-events.ts`, which the Assistant's Telegram bridge listens to.
1001
1003
  broadcast(sessionId, ev);
1002
1004
  const relayed = collabCardForListeners(sessionId, entry.projectPath, ev);
1003
1005
  if (relayed) chatLifecycle.emit("approval_shown", { sessionId, card: relayed, projectName: entry.projectName ?? "", providerId: entry.providerId });
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Tells the user on Telegram that a chat's database tool waits on them, so they learn of it when
3
+ * they are away from PPM: a `db_execute` change waiting for approval (and once more shortly before
4
+ * it gives up), and a connection nobody has logged in to since PPM started. Sent as it happens,
5
+ * whether or not a PPM screen shows the chat: the card itself says nothing to a phone.
6
+ *
7
+ * Notices only, with no Allow or Deny: approving a change takes PPM's password, and a login takes
8
+ * the database's, and neither is ever asked for or taken on Telegram. Each notice says so, names
9
+ * the project, the chat and the connection, and links to the chat in PPM.
10
+ *
11
+ * Sent to every connected chat (the send lane checks each again before every call), nothing when
12
+ * none is. Quiet hours: an approval's notice is held and sent when they end if the change still
13
+ * waits; the reminder and the login notice are dropped, since by then the chat has given up or
14
+ * moved on, and the held notice already covers an approval that still waits. The login notice is
15
+ * deduplicated where it is raised (`db-login-attention.ts`).
16
+ */
17
+ import { dbApprovalBroker } from "../db-ai-tools/db-approval-broker.ts";
18
+ import { dbAttentionEvents, type DbAttentionBus, type DbAttentionEvents } from "../db-ai-tools/db-attention-events.ts";
19
+ import { getSessionProjectName, getSessionProvider, getSessionTitle, resolveMigratedSession } from "../db.service.ts";
20
+ import { escapeTelegramHtml, truncateText } from "../notification-format.ts";
21
+ import { redactForTelegram } from "../telegram/telegram-html-format.ts";
22
+ import { chatControl } from "../chat-control/chat-control.ts";
23
+ import { chatService } from "../chat.service.ts";
24
+ import { assistantClock } from "../assistant-wake/assistant-clock.ts";
25
+ import { currentQuietWindowEnd } from "../assistant-wake/wake-quiet-hours.ts";
26
+ import { createLogger } from "../logger.ts";
27
+ import { MENTIONS_PASSWORD, PASSWORD_WITHHELD, type DbExecuteApprovalInput } from "../../shared/db-ai-tools.ts";
28
+ import { canSendTo, reachableChats } from "./assistant-telegram-access.ts";
29
+ import { placeLink } from "./assistant-telegram-links.ts";
30
+ import { sendMessageTask, type AssistantTelegramSendQueue } from "./assistant-telegram-send-queue.ts";
31
+ import { createQuietHold, type QuietHold, type QuietHoldDeps } from "./assistant-telegram-quiet-hold.ts";
32
+
33
+ const log = createLogger("assistant-telegram");
34
+
35
+ /** How much of the SQL a notice repeats; the whole script is on the card in PPM. */
36
+ export const DB_NOTICE_SQL_MAX = 600;
37
+ const REASON_MAX = 300;
38
+ const NAME_MAX = 80;
39
+
40
+ export const ANSWER_IN_PPM = "Answer in PPM: approving needs PPM's password, which is never asked for here.";
41
+ export const LOGIN_IN_PPM = "Log in from PPM's Database panel, then ask the chat to try again. The password is never asked for here.";
42
+
43
+ /** Who a session is, as a notice names it. */
44
+ export interface DescribedChat {
45
+ project: string;
46
+ providerId: string | null;
47
+ title: string;
48
+ }
49
+
50
+ export interface DbNoticesDeps {
51
+ queue: AssistantTelegramSendQueue;
52
+ /** The link that opens a chat in PPM. */
53
+ chatLink: (project: string, providerId: string | null, sessionId: string) => Promise<string>;
54
+ connectedChats?: () => string[];
55
+ events?: Pick<DbAttentionBus, "on">;
56
+ describe?: (sessionId: string) => DescribedChat;
57
+ /** The id a session goes by now: Codex renames a new chat during its first turn. */
58
+ canonical?: (sessionId: string) => string;
59
+ /** Quiet hours, and whether a held approval still waits (tests pass a fake clock and window). */
60
+ quiet?: QuietHoldDeps;
61
+ }
62
+
63
+ type Shown = DbAttentionEvents["approval_shown"];
64
+ type Held = Shown & { targetSessionId: string; card: { requestId: string } };
65
+
66
+ function realDescribe(sessionId: string): DescribedChat {
67
+ const live = chatControl()?.liveState(sessionId);
68
+ return {
69
+ project: live?.projectName || getSessionProjectName(sessionId) || "",
70
+ providerId: live?.providerId || getSessionProvider(sessionId),
71
+ // The user's rename, else the title the chat shows (its provider's, from the first message).
72
+ title: getSessionTitle(sessionId) || chatService.getSession(sessionId)?.title || "",
73
+ };
74
+ }
75
+
76
+ const realQuiet: QuietHoldDeps = {
77
+ clock: assistantClock,
78
+ quietEnd: currentQuietWindowEnd,
79
+ stillWaiting: (_sessionId, requestId) => dbApprovalBroker.has(requestId),
80
+ };
81
+
82
+ const name = (text: string, fallback: string): string =>
83
+ escapeTelegramHtml(truncateText(redactForTelegram(text.replace(/\s+/g, " ").trim()) || fallback, NAME_MAX));
84
+
85
+ /** "Chat “Fix jobs” in api": who is asking, escaped. */
86
+ function whichChat(chat: DescribedChat): string {
87
+ const title = `“${name(chat.title, "Untitled chat")}”`;
88
+ return chat.project ? `Chat ${title} in <b>${name(chat.project, "")}</b>` : `Chat ${title}`;
89
+ }
90
+
91
+ function where(input: Pick<DbExecuteApprovalInput, "connectionName" | "database">): string {
92
+ const conn = `<b>${name(input.connectionName, "a connection")}</b>`;
93
+ return input.database ? `${conn} (database ${name(input.database, "")})` : conn;
94
+ }
95
+
96
+ /** Redacted first, so a cut cannot leave half a secret the redaction no longer recognises. */
97
+ const excerpt = (text: string, max: number): string => escapeTelegramHtml(truncateText(redactForTelegram(text), max));
98
+
99
+ const minutesLeft = (expiresAt: number, now: number): number => Math.max(1, Math.round((expiresAt - now) / 60_000));
100
+
101
+ export function approvalNoticeHtml(chat: DescribedChat, input: DbExecuteApprovalInput, expiresAt: number, now: number): string {
102
+ const lines = [
103
+ "🔐 <b>A database change is waiting for your approval</b>",
104
+ "",
105
+ `${whichChat(chat)} wants to run this on ${where(input)}:`,
106
+ MENTIONS_PASSWORD.test(input.sql) ? `<i>${escapeTelegramHtml(PASSWORD_WITHHELD)}</i>` : `<pre>${excerpt(input.sql, DB_NOTICE_SQL_MAX)}</pre>`,
107
+ ];
108
+ const reason = input.reason?.trim();
109
+ if (reason) lines.push(`Why: ${MENTIONS_PASSWORD.test(reason) ? `<i>${escapeTelegramHtml(PASSWORD_WITHHELD)}</i>` : excerpt(reason, REASON_MAX)}`);
110
+ lines.push("", `Nothing runs unless you approve within ${minutesLeft(expiresAt, now)} minutes. ${ANSWER_IN_PPM}`);
111
+ return lines.join("\n");
112
+ }
113
+
114
+ export function reminderNoticeHtml(chat: DescribedChat, input: DbExecuteApprovalInput, expiresAt: number, now: number): string {
115
+ return [
116
+ "⏰ <b>Still waiting: a database change</b>",
117
+ "",
118
+ `${whichChat(chat)} still waits for your approval to change ${where(input)}. `
119
+ + `PPM gives up in ${minutesLeft(expiresAt, now)} minutes and nothing runs. ${ANSWER_IN_PPM}`,
120
+ ].join("\n");
121
+ }
122
+
123
+ export function loginNoticeHtml(chat: DescribedChat, connectionName: string): string {
124
+ return [
125
+ "🔑 <b>A database needs you to log in</b>",
126
+ "",
127
+ `${whichChat(chat)} tried to use ${where({ connectionName })}, which asks for its password, and nobody has logged in to it since PPM started.`,
128
+ LOGIN_IN_PPM,
129
+ ].join("\n");
130
+ }
131
+
132
+ export class AssistantTelegramDbNotices {
133
+ private offs: Array<() => void> = [];
134
+ private readonly connectedChats: () => string[];
135
+ private readonly describe: (sessionId: string) => DescribedChat;
136
+ private readonly canonical: (sessionId: string) => string;
137
+ private readonly quiet: QuietHoldDeps;
138
+ /** Approvals shown in quiet hours, sent at their end if they still wait. */
139
+ private readonly quietHold: QuietHold<Held>;
140
+
141
+ constructor(private readonly deps: DbNoticesDeps) {
142
+ this.connectedChats = deps.connectedChats ?? (() => reachableChats().map((c) => c.chatId));
143
+ this.describe = deps.describe ?? realDescribe;
144
+ this.canonical = deps.canonical ?? resolveMigratedSession;
145
+ this.quiet = deps.quiet ?? realQuiet;
146
+ this.quietHold = createQuietHold<Held>(this.quiet, (p) => this.send(p.sessionId, "db approval", (chat) => approvalNoticeHtml(chat, p.input, p.expiresAt, this.quiet.clock.now())), "database approval notice");
147
+ }
148
+
149
+ attach(): void {
150
+ if (this.offs.length) return;
151
+ const events = this.deps.events ?? dbAttentionEvents;
152
+ this.offs = [
153
+ events.on("approval_shown", (p) => this.onShown(p)),
154
+ events.on("approval_reminder", (p) => this.onReminder(p)),
155
+ events.on("login_needed", (p) => this.onLogin(p)),
156
+ ];
157
+ }
158
+
159
+ detach(): void {
160
+ for (const off of this.offs.splice(0)) off();
161
+ this.quietHold.clear();
162
+ }
163
+
164
+ private onShown(p: Shown): void {
165
+ if (this.quietHold.offer({ ...p, targetSessionId: p.sessionId, card: { requestId: p.requestId } })) return;
166
+ this.send(p.sessionId, "db approval", (chat) => approvalNoticeHtml(chat, p.input, p.expiresAt, this.quiet.clock.now()));
167
+ }
168
+
169
+ private onReminder(p: DbAttentionEvents["approval_reminder"]): void {
170
+ if (this.inQuietHours()) return void log.info(`db approval ${p.requestId}: reminder not sent in quiet hours`);
171
+ this.send(p.sessionId, "db approval reminder", (chat) => reminderNoticeHtml(chat, p.input, p.expiresAt, this.quiet.clock.now()));
172
+ }
173
+
174
+ private onLogin(p: DbAttentionEvents["login_needed"]): void {
175
+ if (this.inQuietHours()) return void log.info(`db login for connection ${p.connectionId}: notice not sent in quiet hours`);
176
+ this.send(p.sessionId, "db login", (chat) => loginNoticeHtml(chat, p.connectionName));
177
+ }
178
+
179
+ private inQuietHours(): boolean {
180
+ try { return this.quiet.quietEnd() !== null; } catch { return false; }
181
+ }
182
+
183
+ private send(sessionId: string, label: string, render: (chat: DescribedChat) => string): void {
184
+ let chats: string[];
185
+ try { chats = this.connectedChats().filter(canSendTo); } catch { chats = []; }
186
+ if (!chats.length) return;
187
+ void this.deliver(chats, sessionId, label, render).catch((e) => log.warn(`${label} notice for ${sessionId} not sent: ${(e as Error).message}`));
188
+ }
189
+
190
+ private async deliver(chats: string[], asked: string, label: string, render: (chat: DescribedChat) => string): Promise<void> {
191
+ // Held through quiet hours, or sent just as Codex renamed the chat: name and link the chat as it is now.
192
+ let sessionId = asked;
193
+ try { sessionId = this.canonical(asked); } catch { /* the id it was asked under */ }
194
+ const chat = this.describe(sessionId);
195
+ let html = render(chat);
196
+ const url = await this.deps.chatLink(chat.project, chat.providerId, sessionId).catch(() => null);
197
+ const link = url ? placeLink(url) : {};
198
+ if (link.inline) html += `\n\n${link.inline}`;
199
+ for (const chatId of chats) {
200
+ this.deps.queue.enqueue(chatId, sendMessageTask(this.deps.queue, chatId, {
201
+ html,
202
+ ...(link.button ? {
203
+ markup: { inline_keyboard: [[link.button]] },
204
+ fallbackHtml: `${html}\n\n${escapeTelegramHtml(link.button.text)}: ${escapeTelegramHtml(link.button.url!)}`,
205
+ } : {}),
206
+ }, { label }));
207
+ }
208
+ }
209
+ }
@@ -40,7 +40,8 @@ export interface QuietHold<T extends HeldDecision> {
40
40
  size(): number;
41
41
  }
42
42
 
43
- export function createQuietHold<T extends HeldDecision>(deps: QuietHoldDeps, release: (item: T) => void): QuietHold<T> {
43
+ /** `what` names the held items in the log line at the end of quiet hours. */
44
+ export function createQuietHold<T extends HeldDecision>(deps: QuietHoldDeps, release: (item: T) => void, what = "watched-chat card"): QuietHold<T> {
44
45
  const held = new Map<string, T>();
45
46
  let timer: Cancel | null = null;
46
47
 
@@ -66,7 +67,7 @@ export function createQuietHold<T extends HeldDecision>(deps: QuietHoldDeps, rel
66
67
  sent++;
67
68
  try { release(item); } catch (e) { log.warn(`held card ${item.card.requestId} not sent: ${(e as Error).message}`); }
68
69
  }
69
- if (items.length) log.info(`quiet hours over: ${sent} of ${items.length} held watched-chat card(s) still waiting, sent`);
70
+ if (items.length) log.info(`quiet hours over: ${sent} of ${items.length} held ${what}(s) still waiting, sent`);
70
71
  }
71
72
 
72
73
  return {
@@ -8,7 +8,9 @@
8
8
  * before any access check — that message is how a chat becomes allowed at all.
9
9
  *
10
10
  * It also carries what the user asked to hear about other chats (`assistant-telegram-relay.ts`):
11
- * a watched chat's cards, and watch reports from Assistant sessions no chat is bound to.
11
+ * a watched chat's cards, and watch reports from Assistant sessions no chat is bound to. And
12
+ * it tells the user when a chat's database tool waits on them (`assistant-telegram-db-notices.ts`):
13
+ * notices only, since the answer needs a password that is never taken on Telegram.
12
14
  *
13
15
  * Nothing here runs on its own: `startAssistantHub()` starts it when the Telegram side of the
14
16
  * Assistant is switched on.
@@ -37,6 +39,7 @@ import { AssistantTelegramCards } from "./assistant-telegram-cards.ts";
37
39
  import { assistantSessionLink, chatLink } from "./assistant-telegram-links.ts";
38
40
  import { AssistantTelegramMirror, type MirrorCardSink } from "./assistant-telegram-mirror.ts";
39
41
  import { AssistantTelegramRelay } from "./assistant-telegram-relay.ts";
42
+ import { AssistantTelegramDbNotices } from "./assistant-telegram-db-notices.ts";
40
43
  import type { RelayedCard } from "./assistant-telegram-cards.ts";
41
44
  import { AssistantTelegramPoller } from "./assistant-telegram-poller.ts";
42
45
  import { AssistantTelegramSendQueue, EDIT_INTERVAL_MS, outcomeOf, sendMessageTask } from "./assistant-telegram-send-queue.ts";
@@ -109,6 +112,7 @@ interface Running {
109
112
  inbound: AssistantTelegramInbound;
110
113
  mirror: AssistantTelegramMirror;
111
114
  relay: AssistantTelegramRelay;
115
+ dbNotices: AssistantTelegramDbNotices;
112
116
  cards: BridgeCards;
113
117
  codes: ButtonCodes<BridgeAction>;
114
118
  offs: Array<() => void>;
@@ -140,6 +144,7 @@ export class AssistantTelegramBridge {
140
144
  const relay = new AssistantTelegramRelay({
141
145
  queue, chatLink: links.chatLink, relayCard: (chatId, card) => cards.relayed(chatId, card),
142
146
  });
147
+ const dbNotices = new AssistantTelegramDbNotices({ queue, chatLink: links.chatLink });
143
148
  const mirror = new AssistantTelegramMirror({
144
149
  queue, state, now, cards,
145
150
  showToolCalls: () => bridgeConfig().show_tool_calls,
@@ -176,11 +181,12 @@ export class AssistantTelegramBridge {
176
181
  () => cardOutbound.detach(managerCards),
177
182
  ];
178
183
  cardOutbound.attach(managerCards);
179
- this.run = { poller, queue, state, inbound, mirror, relay, cards, codes, offs };
184
+ this.run = { poller, queue, state, inbound, mirror, relay, dbNotices, cards, codes, offs };
180
185
 
181
186
  recoverInterrupted(queue, state);
182
187
  mirror.attach();
183
188
  relay.attach();
189
+ dbNotices.attach();
184
190
  assistantBridgeReading(token);
185
191
  void client.setMyCommands(BOT_COMMANDS);
186
192
  log.info(`Reading Telegram bot ${client.botId}`);
@@ -193,6 +199,7 @@ export class AssistantTelegramBridge {
193
199
  this.run = null;
194
200
  for (const off of run.offs) off();
195
201
  run.relay.detach();
202
+ run.dbNotices.detach();
196
203
  run.mirror.detach();
197
204
  run.inbound.stop();
198
205
  await run.poller.stop();
@@ -1,4 +1,7 @@
1
+ import type { Context } from "hono";
1
2
  import type { ConnectionRow } from "../db.service.ts";
3
+ import { missingLogin } from "../database/connection-login.ts";
4
+ import { holdRequestOpen } from "../../server/helpers/hold-request-open.ts";
2
5
  import { getAdapter } from "../database/adapter-registry.ts";
3
6
  import { isReadOnlyQuery } from "../database/readonly-check.ts";
4
7
  import { detectOperation, insertQueryLog, type QueryLogInput, type QueryOperation } from "../query-audit/query-audit.service.ts";
@@ -20,6 +23,7 @@ import { aiDatabaseArg, aiTargetConfig } from "./db-ai-target.ts";
20
23
  import { formatStatementResults } from "./db-ai-format.ts";
21
24
  import { runAiQuery, runApprovedScript, transactionControlIn } from "./db-ai-run.ts";
22
25
  import { dbApprovalBroker, type DbApprovalOutcome } from "./db-approval-broker.ts";
26
+ import { dbLoginAttention } from "./db-login-attention.ts";
23
27
  import {
24
28
  DB_EXECUTE_RESULT_ROWS, DB_EXECUTE_STATEMENT_TIMEOUT_MS, DB_QUERY_DEFAULT_ROWS, DB_QUERY_MAX_ROWS, DB_QUERY_TIMEOUT_MS,
25
29
  OPEN_QUERY_WAIT_MS, dbChangeHint, dbToolDefinitions,
@@ -57,6 +61,11 @@ export function createDbToolsMcpHandler(deps: {
57
61
  /** Whether the user has this tool on (Settings → Tools). */
58
62
  enabled: (tool: string) => boolean;
59
63
  openSession?: (conn: ConnectionRow, config: Awaited<ReturnType<typeof aiTargetConfig>>) => Promise<DbQuerySession>;
64
+ /**
65
+ * A tool reached a connection nobody has logged in to: tell the user away from PPM, since the
66
+ * AI can only ask in the chat (`db-login-attention.ts`). Nobody is told when left out.
67
+ */
68
+ loginNeeded?: (sessionId: string, conn: ConnectionRow) => void;
60
69
  }) {
61
70
  const openSession = deps.openSession ?? ((conn, config) => getAdapter(conn.type).openQuerySession(config));
62
71
 
@@ -210,6 +219,15 @@ export function createDbToolsMcpHandler(deps: {
210
219
  if (!sql.trim()) return textResult("`sql` is required.", true);
211
220
  if (sql.length > MAX_DB_TOOL_SQL_CHARS) return textResult(`\`sql\` is longer than ${MAX_DB_TOOL_SQL_CHARS} characters; split it into smaller scripts.`, true);
212
221
  if (splitSqlScript(sql, dialectNameOf(conn.type)).length === 0) return textResult("The SQL has no statements to run: only comments or semicolons.", true);
222
+ // open_query needs no login: the user runs its tab, and the tab asks for the login itself.
223
+ if (name !== OPEN_QUERY_TOOL && deps.loginNeeded) {
224
+ try {
225
+ // A config that cannot be read is the tool's own error to report, below.
226
+ if (missingLogin(conn)) deps.loginNeeded(sessionId, conn);
227
+ } catch (e) {
228
+ console.warn(`[db-tools] telling the user about ${conn.name}'s login failed: ${errorText(e)}`);
229
+ }
230
+ }
213
231
  if (name === DB_QUERY_TOOL) return dbQuery(conn, target.database, sql, args);
214
232
  if (name === OPEN_QUERY_TOOL) return openQuery(sessionId, conn, target.database, sql);
215
233
  return dbExecute(sessionId, conn, target.database, sql, args, signal);
@@ -217,9 +235,20 @@ export function createDbToolsMcpHandler(deps: {
217
235
  });
218
236
  }
219
237
 
220
- export const dbToolsMcpHandler = createDbToolsMcpHandler({
238
+ const handler = createDbToolsMcpHandler({
221
239
  resolveToken: (token) => dbToolsMcpTokens.resolve(token),
222
240
  openTab: (sessionId, req, waitMs) => tabOpenBroker.request(sessionId, req, waitMs),
223
241
  approve: (sessionId, input, signal) => dbApprovalBroker.request(sessionId, input, undefined, signal),
224
242
  enabled: (tool) => isPpmTool(tool) && ppmToolOn(configService.get("ai"), tool),
243
+ loginNeeded: (sessionId, conn) => { dbLoginAttention.loginNeeded(sessionId, conn); },
225
244
  });
245
+
246
+ /**
247
+ * The endpoint as mounted. A `db_execute` call holds its request for as long as the approval
248
+ * waits (`DB_APPROVAL_WAIT_MS`) with no byte sent, so Bun's idle timeout for the request is
249
+ * lifted, as `/api/sessions-mcp` does; the approval's own timer bounds the wait instead.
250
+ */
251
+ export function dbToolsMcpHandler(c: Context): Promise<Response> {
252
+ holdRequestOpen(c, 0);
253
+ return handler(c);
254
+ }
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { DB_EXECUTE_APPROVAL, type DbApprovalAnswer, type DbExecuteApprovalInput } from "../../shared/db-ai-tools.ts";
3
3
  import { checkPpmPassword, ppmPasswordRequired } from "../ppm-password.ts";
4
+ import { dbAttentionEvents, type DbAttentionBus } from "./db-attention-events.ts";
4
5
 
5
6
  /**
6
7
  * The server half of `db_execute`'s approval. The call waits here while the chat shows the user
@@ -10,6 +11,11 @@ import { checkPpmPassword, ppmPasswordRequired } from "../ppm-password.ts";
10
11
  * password typed again. A wrong password leaves the approval pending; a decline, the user
11
12
  * sending a message or stopping the chat, or nobody answering in time settles it as declined.
12
13
  *
14
+ * While it waits, the approval is also told to the channels that reach the user away from PPM
15
+ * (`db-attention-events.ts`: the PPM Assistant's Telegram bridge), once when it is shown and once
16
+ * more `DB_APPROVAL_REMINDER_BEFORE_MS` before it gives up. Those are notices; the answer, and
17
+ * PPM's password with it, is given in PPM only.
18
+ *
13
19
  * One approval per session at a time, and a session is known by the id it goes by now: Codex
14
20
  * renames a new chat during its first turn, which can be while the approval waits.
15
21
  */
@@ -31,8 +37,13 @@ export type DbApprovalAnswerResult =
31
37
  | { ok: true; approved: boolean }
32
38
  | { ok: false; status: 400 | 403 | 404; error: string };
33
39
 
34
- /** How long the user has to answer. */
35
- export const DB_APPROVAL_WAIT_MS = 10 * 60_000;
40
+ /**
41
+ * How long the user has to answer. Every timeout above the call — the providers' MCP timeout
42
+ * (`DB_TOOLS_TIMEOUT_MS`) and the endpoint's request (`dbToolsMcpHandler`) — outlasts it.
43
+ */
44
+ export const DB_APPROVAL_WAIT_MS = 30 * 60_000;
45
+ /** How long before the approval gives up the user is reminded of it, once. */
46
+ export const DB_APPROVAL_REMINDER_BEFORE_MS = 5 * 60_000;
36
47
 
37
48
  interface Pending {
38
49
  sessionId: string;
@@ -46,10 +57,17 @@ export function createDbApprovalBroker(opts: {
46
57
  canonical?: (sessionId: string) => string;
47
58
  passwordRequired?: () => boolean;
48
59
  checkPassword?: (typed: unknown) => boolean;
60
+ /** Where the approval is told to the user's other channels; the process-wide bus by default. */
61
+ events?: Pick<DbAttentionBus, "emit">;
62
+ now?: () => number;
63
+ reminderBeforeMs?: number;
49
64
  }) {
50
65
  const canonical = opts.canonical ?? ((sessionId: string) => sessionId);
51
66
  const passwordRequired = opts.passwordRequired ?? ppmPasswordRequired;
52
67
  const checkPassword = opts.checkPassword ?? checkPpmPassword;
68
+ const events = opts.events ?? dbAttentionEvents;
69
+ const now = opts.now ?? Date.now;
70
+ const reminderBeforeMs = opts.reminderBeforeMs ?? DB_APPROVAL_REMINDER_BEFORE_MS;
53
71
  const pending = new Map<string, Pending>();
54
72
 
55
73
  function pendingOf(sessionId: string): [string, Pending] | null {
@@ -72,12 +90,14 @@ export function createDbApprovalBroker(opts: {
72
90
  const event: DbApprovalEvent = { type: "approval_request", requestId, tool: DB_EXECUTE_APPROVAL, input: { ...input, passwordRequired: passwordRequired() } };
73
91
  return new Promise<DbApprovalOutcome>((done) => {
74
92
  let timer: ReturnType<typeof setTimeout> | undefined;
93
+ let reminder: ReturnType<typeof setTimeout> | undefined;
75
94
  const onAbort = () => settle({ approved: false, reason: "cancelled", message: "The call was cancelled before the user answered, so nothing ran." });
76
95
  const settle = (outcome: DbApprovalOutcome): void => {
77
96
  const entry = pending.get(requestId);
78
97
  if (!entry) return;
79
98
  pending.delete(requestId);
80
99
  if (timer) clearTimeout(timer);
100
+ if (reminder) clearTimeout(reminder);
81
101
  signal?.removeEventListener("abort", onAbort);
82
102
  try {
83
103
  opts.chat()?.resolved(canonical(entry.sessionId), requestId, outcome.approved);
@@ -105,6 +125,14 @@ export function createDbApprovalBroker(opts: {
105
125
  approved: false, reason: "timeout",
106
126
  message: `The user did not answer within ${Math.round(waitMs / 60_000)} minutes, so nothing ran.`,
107
127
  }), waitMs);
128
+ const notice = { sessionId, requestId, input: event.input, expiresAt: now() + waitMs };
129
+ events.emit("approval_shown", notice);
130
+ if (waitMs > reminderBeforeMs) {
131
+ reminder = setTimeout(() => {
132
+ reminder = undefined;
133
+ if (pending.has(requestId)) events.emit("approval_reminder", { ...notice, sessionId: canonical(sessionId) });
134
+ }, waitMs - reminderBeforeMs);
135
+ }
108
136
  });
109
137
  }
110
138
 
@@ -0,0 +1,53 @@
1
+ import { createLogger } from "../logger.ts";
2
+ import type { DbExecuteApprovalInput } from "../../shared/db-ai-tools.ts";
3
+
4
+ /**
5
+ * Moments when a chat's database tool waits on the user, for the channels that can tell them
6
+ * while they are away from PPM (the PPM Assistant's Telegram bridge listens here). These are
7
+ * notices only: the answer — PPM's password, a database login — is given in PPM and nowhere else.
8
+ *
9
+ * - `approval_shown`: a `db_execute` change waits for the user's approval.
10
+ * - `approval_reminder`: the same approval is still waiting, a few minutes before it gives up.
11
+ * - `login_needed`: a tool reached a connection that asks for its password and nobody has logged
12
+ * in to it since PPM started. Already deduplicated per connection and chat by the sender.
13
+ *
14
+ * Synchronous: a listener only enqueues. A listener that throws is logged and the others still run.
15
+ */
16
+ export interface DbAttentionEvents {
17
+ approval_shown: { sessionId: string; requestId: string; input: DbExecuteApprovalInput; expiresAt: number };
18
+ approval_reminder: { sessionId: string; requestId: string; input: DbExecuteApprovalInput; expiresAt: number };
19
+ login_needed: { sessionId: string; connectionId: number; connectionName: string };
20
+ }
21
+
22
+ export type DbAttentionEventName = keyof DbAttentionEvents;
23
+
24
+ const log = createLogger("db-tools");
25
+
26
+ export function createDbAttentionEvents() {
27
+ const listeners = new Map<DbAttentionEventName, Set<(payload: never) => void>>();
28
+
29
+ /** Subscribes; the returned function unsubscribes. */
30
+ function on<K extends DbAttentionEventName>(name: K, listener: (payload: DbAttentionEvents[K]) => void): () => void {
31
+ let set = listeners.get(name);
32
+ if (!set) listeners.set(name, set = new Set());
33
+ set.add(listener as (payload: never) => void);
34
+ return () => { set!.delete(listener as (payload: never) => void); };
35
+ }
36
+
37
+ function emit<K extends DbAttentionEventName>(name: K, payload: DbAttentionEvents[K]): void {
38
+ for (const listener of [...(listeners.get(name) ?? [])]) {
39
+ try {
40
+ (listener as (p: DbAttentionEvents[K]) => void)(payload);
41
+ } catch (e) {
42
+ log.warn(`listener for "${name}" failed (session=${payload.sessionId}): ${(e as Error)?.message ?? e}`);
43
+ }
44
+ }
45
+ }
46
+
47
+ return { on, emit };
48
+ }
49
+
50
+ export type DbAttentionBus = ReturnType<typeof createDbAttentionEvents>;
51
+
52
+ /** The process-wide bus the database tools emit on. */
53
+ export const dbAttentionEvents = createDbAttentionEvents();
@@ -0,0 +1,86 @@
1
+ import { getSessionProjectName, getSessionProvider, getSessionTitle, resolveMigratedSession } from "../db.service.ts";
2
+ import { hasHeldLogin } from "../database/connection-login.ts";
3
+ import { createLogger } from "../logger.ts";
4
+ import { dbAttentionEvents, type DbAttentionBus } from "./db-attention-events.ts";
5
+
6
+ /**
7
+ * Tells the user that a chat's database tool reached a connection nobody has logged in to since
8
+ * PPM started (its password is asked for, never saved). Without this the AI only reads an error
9
+ * and asks in the chat, which a user away from PPM never sees, so the chat just stops.
10
+ *
11
+ * Told once per connection and chat within `DB_LOGIN_NOTICE_WINDOW_MS`: an AI retrying, or
12
+ * reading several tables, would otherwise send one notice per call. The notice goes out on the
13
+ * attention bus (the PPM Assistant's Telegram bridge) and as an ordinary "Needs approval"
14
+ * notification (push, the notification bot, ntfy). Logging in happens in PPM's Database panel only.
15
+ */
16
+
17
+ export const DB_LOGIN_NOTICE_WINDOW_MS = 30 * 60_000;
18
+
19
+ const log = createLogger("db-tools");
20
+
21
+ export interface DbLoginAttentionDeps {
22
+ events?: Pick<DbAttentionBus, "emit">;
23
+ now?: () => number;
24
+ windowMs?: number;
25
+ /** The id a session goes by now; Codex renames a new chat during its first turn. */
26
+ canonical?: (sessionId: string) => string;
27
+ /** The "Needs approval" notification; none when left out. */
28
+ notify?: (sessionId: string, conn: { id: number; name: string }) => void;
29
+ }
30
+
31
+ export function createDbLoginAttention(deps: DbLoginAttentionDeps = {}) {
32
+ const events = deps.events ?? dbAttentionEvents;
33
+ const now = deps.now ?? Date.now;
34
+ const windowMs = deps.windowMs ?? DB_LOGIN_NOTICE_WINDOW_MS;
35
+ const canonical = deps.canonical ?? ((sessionId: string) => sessionId);
36
+ /** When each connection-and-chat pair was last told, pruned as it ages. */
37
+ const told = new Map<string, number>();
38
+
39
+ /** The user is told, unless this pair was told within the window; true when told now. */
40
+ function loginNeeded(asked: string, conn: { id: number; name: string }): boolean {
41
+ const sessionId = canonical(asked);
42
+ const at = now();
43
+ for (const [key, when] of told) if (at - when >= windowMs) told.delete(key);
44
+ const key = `${conn.id}\u0000${sessionId}`;
45
+ if (told.has(key)) return false;
46
+ told.set(key, at);
47
+ events.emit("login_needed", { sessionId, connectionId: conn.id, connectionName: conn.name });
48
+ try {
49
+ deps.notify?.(sessionId, conn);
50
+ } catch (e) {
51
+ log.warn(`login notification for connection ${conn.id} failed: ${(e as Error).message}`);
52
+ }
53
+ return true;
54
+ }
55
+
56
+ return { loginNeeded, size: () => told.size };
57
+ }
58
+
59
+ /** How the login notification waits: apart from the session's own, and only while nobody has logged in. */
60
+ export function loginNotificationOptions(connectionId: number, sessionId: string, hasLogin: (id: number) => boolean = hasHeldLogin) {
61
+ return {
62
+ // Its own slot: the turn usually ends right after, and its "Chat completed" must not replace this.
63
+ ownKey: `db-login:${connectionId}:${sessionId}`,
64
+ // Someone logged in meanwhile: nothing left to tell.
65
+ stillUnseen: () => !hasLogin(connectionId),
66
+ };
67
+ }
68
+
69
+ /** The "Needs approval" notification for a connection waiting on a login, through the usual channels. */
70
+ function notifyLoginNeeded(sessionId: string, conn: { id: number; name: string }): void {
71
+ const project = getSessionProjectName(sessionId) ?? "";
72
+ const providerId = getSessionProvider(sessionId) ?? undefined;
73
+ // Imported here: the chat and notification services are heavy, and this module is loaded with the endpoint.
74
+ Promise.all([import("../chat.service.ts"), import("../notification.service.ts")]).then(([{ chatService }, { notificationService }]) => {
75
+ const sessionTitle = getSessionTitle(sessionId) || chatService.getSession(sessionId)?.title || `Session ${sessionId.slice(0, 8)}`;
76
+ return notificationService.broadcast("approval_request", {
77
+ title: "Database login needed",
78
+ body: `${project || "Project"} — AI needs ${conn.name}: log in in PPM's Database panel`,
79
+ project, sessionId, ...(providerId ? { providerId } : {}), sessionTitle,
80
+ }, loginNotificationOptions(conn.id, sessionId));
81
+ }).catch((e) => {
82
+ log.warn(`login notification for ${sessionId} not sent: ${(e as Error).message}`);
83
+ });
84
+ }
85
+
86
+ export const dbLoginAttention = createDbLoginAttention({ canonical: resolveMigratedSession, notify: notifyLoginNeeded });
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import type { NotificationPayload } from "./notification.service.ts";
6
6
  import { isAssistantProject } from "../shared/assistant-project.ts";
7
- import { dbExecuteApprovalInput } from "../shared/db-ai-tools.ts";
7
+ import { MENTIONS_PASSWORD, PASSWORD_WITHHELD, dbExecuteApprovalInput } from "../shared/db-ai-tools.ts";
8
8
  import { sessionCollabApprovalInput, type SessionCollabApprovalInput } from "../shared/session-collab.ts";
9
9
 
10
10
  /** What a session-collaboration card asks, as a notification's title says it. */
@@ -78,9 +78,10 @@ export function describeApprovalInput(tool: string, input: unknown): Pick<Notifi
78
78
  if (!input || typeof input !== "object") return {};
79
79
  const i = input as Record<string, unknown>;
80
80
 
81
- // A database change: the AI's reason, not the SQL, which may quote the rows it changes.
81
+ // A database change: the AI's reason, not the SQL, which may quote the rows it changes — and not
82
+ // the reason either when it mentions a password.
82
83
  const db = dbExecuteApprovalInput(tool, input);
83
- if (db) return db.reason ? { detail: db.reason, detailStyle: "quote" } : {};
84
+ if (db) return db.reason ? { detail: MENTIONS_PASSWORD.test(db.reason) ? PASSWORD_WITHHELD : db.reason, detailStyle: "quote" } : {};
84
85
 
85
86
  const collab = sessionCollabApprovalInput(tool, input);
86
87
  if (collab) {
@@ -42,6 +42,12 @@ export interface BroadcastOptions {
42
42
  * replaces the older one on the device too.
43
43
  */
44
44
  coalesceKey?: string;
45
+ /**
46
+ * Its own waiting slot and device tag, even though it names a session: for news about a
47
+ * session that must neither replace that session's own notification (a waiting approval) nor
48
+ * be replaced by it (the turn's "Chat completed" right after).
49
+ */
50
+ ownKey?: string;
45
51
  /**
46
52
  * Called the moment the notification goes out — synchronously inside `broadcast` when
47
53
  * there is no delay — and never for one that is switched off, replaced or seen. Lets a
@@ -81,13 +87,14 @@ export class NotificationService {
81
87
  log.debug(`Notification ${type} not sent: switched off`);
82
88
  return Promise.resolve("off");
83
89
  }
84
- const tag = opts.coalesceKey;
90
+ const tag = opts.ownKey ?? opts.coalesceKey;
91
+ const ownTag = opts.ownKey !== undefined;
85
92
  if (settings.delay_seconds === 0) {
86
93
  sent(opts);
87
- return this.deliver(type, payload, tag).then(() => "sent");
94
+ return this.deliver(type, payload, tag, ownTag).then(() => "sent");
88
95
  }
89
96
 
90
- const key = payload.sessionId || opts.coalesceKey || null;
97
+ const key = opts.ownKey ?? (payload.sessionId || opts.coalesceKey || null);
91
98
  if (key) this.pending.get(key)?.();
92
99
  return new Promise<BroadcastOutcome>((resolve) => {
93
100
  const cancel = () => {
@@ -107,13 +114,13 @@ export class NotificationService {
107
114
  return resolve("seen");
108
115
  }
109
116
  sent(opts);
110
- this.deliver(type, payload, tag).finally(() => resolve("sent"));
117
+ this.deliver(type, payload, tag, ownTag).finally(() => resolve("sent"));
111
118
  }, settings.delay_seconds * this.msPerSecond);
112
119
  if (key) this.pending.set(key, cancel);
113
120
  });
114
121
  }
115
122
 
116
- private async deliver(type: NotificationType, event: NotificationPayload, coalesceKey?: string): Promise<void> {
123
+ private async deliver(type: NotificationType, event: NotificationPayload, coalesceKey?: string, ownTag = false): Promise<void> {
117
124
  const settings = resolveNotificationSettings(configService.get("notifications"));
118
125
  const payload: NotificationPayload = { ...event, providerId: event.providerId || providerOf(event.sessionId) };
119
126
  const deviceName = (configService.get("device_name") as string) || "PPM";
@@ -149,7 +156,8 @@ export class NotificationService {
149
156
  path: notificationPath(payload),
150
157
  // Same tag = the newer notification replaces the older one on the device. Right for a
151
158
  // session or a coalesce key; wrong for two Jira hits that land in the same millisecond.
152
- tag: payload.sessionId ? `ppm-${payload.sessionId}`
159
+ tag: ownTag && coalesceKey ? `ppm-${coalesceKey}`
160
+ : payload.sessionId ? `ppm-${payload.sessionId}`
153
161
  : coalesceKey ? `ppm-${coalesceKey}`
154
162
  : `ppm-${type}-${crypto.randomUUID()}`,
155
163
  project: payload.project,
@@ -106,6 +106,15 @@ export interface DbQueryTabOpen {
106
106
  sql: string;
107
107
  }
108
108
 
109
+ /**
110
+ * Text that sets or uses a database password, which no redaction pattern can be trusted to hide:
111
+ * SQL writes one as a quoted literal in many forms (`PASSWORD 'x'`, `IDENTIFIED BY 'x'`,
112
+ * `REPLACE 'old'`, `E'x'`, `$$x$$`, dynamic SQL), and a notification that reaches a phone stays
113
+ * there. A script or reason that matches is left out of every notice; the card in PPM shows it.
114
+ */
115
+ export const MENTIONS_PASSWORD = /pass(?:word|wd)|identified/i;
116
+ export const PASSWORD_WITHHELD = "(Not shown here: it sets or uses a password. Open the chat in PPM to read it.)";
117
+
109
118
  export const MAX_DB_TOOL_SQL_CHARS = 50_000;
110
119
  export const MAX_DB_TOOL_REASON_CHARS = 2_000;
111
120