Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(desktop): log why every notification sound plays (#98687)

Charles Viend251bc9a64f7
diff --git a/products/desktop/docs/TROUBLESHOOTING.md b/products/desktop/docs/TROUBLESHOOTING.md
index 6d67c771d5b2..c9e425a529c0 100644
--- a/products/desktop/docs/TROUBLESHOOTING.md
+++ b/products/desktop/docs/TROUBLESHOOTING.md
@@ -19,6 +19,28 @@ These choices follow the native Codex 0.144.0 approval dialog.
They preserve the current session permission mode and do not enable automatic approval review or remove sandbox limits.
Compare clients with the same workspace, permission settings, saved rules, and approval reviewer.
+## The app made a sound and nothing was waiting
+
+Every notification writes one line before anything rings, at info level, so it is in packaged builds too. The log file is `~/.posthog-code/logs/main.log` (`logs-dev` for a dev build, `logs-test` for a test build).
+
+```bash
+grep -E "Notification|Playing completion sound|Speech notification" ~/.posthog-code/logs/main.log | tail -20
+```
+
+Read the fields in this order:
+
+- `reason` — what raised it: `task_completed`, `task_needs_input`, `canvas_generation`, `image_build`, `error`, `settings_test`.
+- `context.trigger` — for task notifications, the exact code path: a local prompt response, a cloud turn complete, or a local, cloud or pi permission request.
+- `channel` — `native` (app unfocused), `toast` (focused, looking elsewhere) or `suppress` (looking at the target, so nothing rings).
+- `soundPlayed` — whether the app played its own completion sound. A following `Completion sound failed to play` warning means it did not reach the speakers after all.
+- `osChimePlayed` — whether the operating system rang its own notification chime instead. This is what happens when the chosen sound is `none` or no longer resolves, so a `soundPlayed: false` line can still be the source of a noise.
+- `resolvedSound` on the `Playing completion sound` line — the concrete sound, which is the only way to identify one of the `random-*` modes. A `reason: settings_preview` on that line is the user pressing preview in settings, not a notification.
+- `target` and `viewingTarget` — the task or canvas the notification is about, and the one on screen. Equal targets are what makes `channel` suppress.
+
+The line carries no titles or message text on purpose, so identify the notification from `reason` and `target` rather than from what it said.
+
+A sound with no notification the user was waiting on shows up as a `reason`/`trigger` pair that does not match what they were doing. Take the task id from `target` and the `context.taskRunId` from the line and follow that run.
+
## Black screen during development
If the app launches but renders a blank/black screen, it's almost always a stale Vite cache.
diff --git a/products/desktop/packages/core/src/notification/agentSessionNotifications.ts b/products/desktop/packages/core/src/notification/agentSessionNotifications.ts
index 4625bea62605..ba35bbbe112c 100644
--- a/products/desktop/packages/core/src/notification/agentSessionNotifications.ts
+++ b/products/desktop/packages/core/src/notification/agentSessionNotifications.ts
@@ -1,7 +1,23 @@
+// The code path that raised the notification. Carried all the way to the
+// notification log so a sound the user did not expect names its own origin.
+export type AgentSessionNotificationTrigger =
+ | "local_prompt_response"
+ | "cloud_turn_complete"
+ | "local_permission_request"
+ | "cloud_permission_request"
+ | "pi_turn_completed"
+ | "pi_mcp_permission_request";
+
export type AgentSessionNotification =
| {
kind: "turn_completed";
+ trigger: Extract<
+ AgentSessionNotificationTrigger,
+ "local_prompt_response" | "cloud_turn_complete" | "pi_turn_completed"
+ >;
taskId: string;
+ // Absent on the pi runtime, which keys its sessions by task.
+ taskRunId?: string;
taskTitle: string;
stopReason: string;
durationMs?: number;
@@ -10,7 +26,14 @@ export type AgentSessionNotification =
}
| {
kind: "needs_input";
+ trigger: Extract<
+ AgentSessionNotificationTrigger,
+ | "local_permission_request"
+ | "cloud_permission_request"
+ | "pi_mcp_permission_request"
+ >;
taskId: string;
+ taskRunId?: string;
taskTitle: string;
isTaskAuthor?: boolean;
agentSpoke?: boolean;
diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts
index 79250827d3dd..e79343e826d4 100644
--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts
+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts
@@ -124,6 +124,7 @@ describe("PiSessionController", () => {
expect(notifier.notify).toHaveBeenCalledTimes(2);
expect(notifier.notify).toHaveBeenCalledWith({
kind: "needs_input",
+ trigger: "pi_mcp_permission_request",
taskId: "task-1",
taskTitle: "Fix notifications",
});
@@ -616,6 +617,7 @@ describe("PiSessionController", () => {
expect(notifier.notify).toHaveBeenCalledWith({
kind: "turn_completed",
+ trigger: "pi_turn_completed",
taskId: "task-1",
taskTitle: "Fix notifications",
stopReason: "end_turn",
@@ -686,6 +688,7 @@ describe("PiSessionController", () => {
expect(notifier.notify).toHaveBeenCalledOnce();
expect(notifier.notify).toHaveBeenCalledWith({
kind: "turn_completed",
+ trigger: "pi_turn_completed",
taskId: "task-1",
taskTitle: "Fix notifications",
stopReason: "end_turn",
diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.ts
index 41480bbbf347..6565a2ce80b7 100644
--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts
+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.ts
@@ -664,6 +664,7 @@ export class PiSessionController {
if (context) {
this.notifier?.notify({
kind: "needs_input",
+ trigger: "pi_mcp_permission_request",
taskId,
taskTitle: context.taskTitle,
isTaskAuthor: context.isTaskAuthor,
@@ -1022,6 +1023,7 @@ export class PiSessionController {
: undefined;
this.notifier?.notify({
kind: "turn_completed",
+ trigger: "pi_turn_completed",
taskId,
taskTitle: notificationContext.taskTitle,
stopReason,
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index ef202cef97ce..f212e70f4f23 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -69,7 +69,10 @@ import {
} from "@posthog/shared/domain-types";
import type { SendCommandOutput } from "../cloud-task/schemas";
import type { CommentTarget } from "../comments/anchors";
-import type { AgentSessionNotification } from "../notification/agentSessionNotifications";
+import type {
+ AgentSessionNotification,
+ AgentSessionNotificationTrigger,
+} from "../notification/agentSessionNotifications";
import { extractPostHogObjectReferences } from "../posthog-objects/references";
import type { SpeechKind, SpeechSource } from "../speech/identifiers";
import {
@@ -3568,6 +3571,7 @@ export class SessionService {
taskRunId,
session,
stopReason,
+ "cloud_turn_complete",
turnStartedAtTs ? acpMsg.ts - turnStartedAtTs : undefined,
);
}
@@ -3660,12 +3664,18 @@ export class SessionService {
taskRunId: string,
session: NotifiableAgentSession,
stopReason: string,
+ trigger: Extract<
+ AgentSessionNotificationTrigger,
+ "local_prompt_response" | "cloud_turn_complete"
+ >,
durationMs?: number,
): void {
this.d.notifyAgentSession({
kind: "turn_completed",
+ trigger,
taskTitle: session.taskTitle,
taskId: session.taskId,
+ taskRunId,
stopReason,
durationMs,
isTaskAuthor: session.isTaskAuthor,
@@ -3676,11 +3686,17 @@ export class SessionService {
private notifyNeedsInput(
taskRunId: string,
session: NotifiableAgentSession,
+ trigger: Extract<
+ AgentSessionNotificationTrigger,
+ "local_permission_request" | "cloud_permission_request"
+ >,
): void {
this.d.notifyAgentSession({
kind: "needs_input",
+ trigger,
taskTitle: session.taskTitle,
taskId: session.taskId,
+ taskRunId,
isTaskAuthor: session.isTaskAuthor,
agentSpoke: this.agentSpokeSinceTurnStarted(
taskRunId,
@@ -3760,6 +3776,7 @@ export class SessionService {
taskRunId,
session,
stopReason,
+ "local_prompt_response",
turnStartedAtTs ? acpMsg.ts - turnStartedAtTs : undefined,
);
}
@@ -4005,7 +4022,7 @@ export class SessionService {
this.d.store.setPendingPermissions(taskRunId, newPermissions);
this.d.taskViewedApi.markActivity(session.taskId);
- this.notifyNeedsInput(taskRunId, session);
+ this.notifyNeedsInput(taskRunId, session, "local_permission_request");
}
private handleCloudPermissionRequest(
@@ -4062,7 +4079,7 @@ export class SessionService {
this.d.store.setPendingPermissions(taskRunId, newPermissions);
this.d.taskViewedApi.markActivity(session.taskId);
- this.notifyNeedsInput(taskRunId, session);
+ this.notifyNeedsInput(taskRunId, session, "cloud_permission_request");
}
private surfacePersistedPendingPermissions(
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasGenerationToasts.ts b/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasGenerationToasts.ts
index 5fbd01fc7225..969653a5f18b 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasGenerationToasts.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasGenerationToasts.ts
@@ -64,6 +64,8 @@ function emitCanvasGenerationNotification(
if (status === "completed") {
if (buildHealthy) {
bus.notify({
+ reason: "canvas_generation",
+ debug: { status, buildHealthy },
body: `${name} is ready`,
target,
toast: { level: "success", description: "Generation finished." },
@@ -72,6 +74,8 @@ function emitCanvasGenerationNotification(
// The agent finished but the canvas build didn't succeed — announcing
// "ready" would be a lie the user only discovers on opening the canvas.
bus.notify({
+ reason: "canvas_generation",
+ debug: { status, buildHealthy },
body: `${name} finished with a failed build`,
target,
toast: {
@@ -82,6 +86,8 @@ function emitCanvasGenerationNotification(
}
} else if (status === "failed") {
bus.notify({
+ reason: "canvas_generation",
+ debug: { status, buildHealthy },
body: `${name} generation failed`,
target,
toast: {
diff --git a/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.test.ts b/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.test.ts
index 1e16c6df6f26..02c4b6394bd1 100644
--- a/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.test.ts
+++ b/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.test.ts
@@ -19,7 +19,9 @@ describe("AgentSessionNotificationService", () => {
service.notify({
kind: "turn_completed",
+ trigger: "local_prompt_response",
taskId: "task-1",
+ taskRunId: "run-1",
taskTitle: "Fix notifications",
stopReason: "end_turn",
durationMs: 42_000,
@@ -31,6 +33,11 @@ describe("AgentSessionNotificationService", () => {
"end_turn",
"task-1",
42_000,
+ {
+ trigger: "local_prompt_response",
+ taskRunId: "run-1",
+ agentSpoke: false,
+ },
);
expect(speech.speak).toHaveBeenCalledWith(
expect.objectContaining({
@@ -46,7 +53,9 @@ describe("AgentSessionNotificationService", () => {
service.notify({
kind: "needs_input",
+ trigger: "cloud_permission_request",
taskId: "task-1",
+ taskRunId: "run-1",
taskTitle: "Fix notifications",
isTaskAuthor: true,
agentSpoke: true,
@@ -55,6 +64,11 @@ describe("AgentSessionNotificationService", () => {
expect(notifications.notifyPermissionRequest).toHaveBeenCalledWith(
"Fix notifications",
"task-1",
+ {
+ trigger: "cloud_permission_request",
+ taskRunId: "run-1",
+ agentSpoke: true,
+ },
);
expect(speech.speak).not.toHaveBeenCalled();
});
@@ -66,6 +80,7 @@ describe("AgentSessionNotificationService", () => {
service.notify({
kind: "turn_completed",
+ trigger: "local_prompt_response",
taskId: "task-1",
taskTitle: "Fix notifications",
stopReason: "end_turn",
diff --git a/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.ts b/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.ts
index bef6165b6130..4d42ff1c8550 100644
--- a/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.ts
+++ b/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.ts
@@ -2,10 +2,13 @@ import type {
AgentSessionNotification,
AgentSessionNotifier,
} from "@posthog/core/notification/agentSessionNotifications";
+import { logger } from "@posthog/ui/shell/logger";
import { inject, injectable } from "inversify";
import { NotificationBus } from "./notifications";
import { SpeechNotifier } from "./speechNotifier";
+const log = logger.scope("notifications");
+
@injectable()
export class AgentSessionNotificationService implements AgentSessionNotifier {
constructor(
@@ -17,13 +20,28 @@ export class AgentSessionNotificationService implements AgentSessionNotifier {
notify(notification: AgentSessionNotification): void {
if (notification.isTaskAuthor !== true) {
+ log.debug("Agent session notification dropped, not the task author", {
+ kind: notification.kind,
+ trigger: notification.trigger,
+ taskId: notification.taskId,
+ taskRunId: notification.taskRunId,
+ });
return;
}
+ // Everything the session knew about the trigger rides along, so the
+ // notification log names the exact path that rang.
+ const debug = {
+ trigger: notification.trigger,
+ taskRunId: notification.taskRunId,
+ agentSpoke: notification.agentSpoke === true,
+ };
+
if (notification.kind === "needs_input") {
this.notifications.notifyPermissionRequest(
notification.taskTitle,
notification.taskId,
+ debug,
);
if (!notification.agentSpoke) {
this.speech.speak({
@@ -43,6 +61,7 @@ export class AgentSessionNotificationService implements AgentSessionNotifier {
notification.stopReason,
notification.taskId,
notification.durationMs,
+ debug,
);
if (notification.stopReason === "end_turn" && !notification.agentSpoke) {
this.speech.speak({
diff --git a/products/desktop/packages/ui/src/features/notifications/notifications.test.ts b/products/desktop/packages/ui/src/features/notifications/notifications.test.ts
index 50a84551822f..be22264f6be2 100644
--- a/products/desktop/packages/ui/src/features/notifications/notifications.test.ts
+++ b/products/desktop/packages/ui/src/features/notifications/notifications.test.ts
@@ -16,6 +16,10 @@ const toastMock = vi.hoisted(() => ({
}));
vi.mock("@posthog/ui/primitives/toast", () => ({ toast: toastMock }));
+import {
+ clearCapturedLogs,
+ formatCapturedLogs,
+} from "@posthog/ui/shell/logCapture";
import { playCompletionSound } from "@posthog/ui/utils/sounds";
import type {
IActiveView,
@@ -280,6 +284,63 @@ describe("sound", () => {
settings: { scaleSoundWithTaskLength },
});
bus.notifyPromptComplete("My task", "end_turn", TASK_ID, durationMs);
- expect(play).toHaveBeenCalledWith("meep", 80, [], expectedRate);
+ expect(play).toHaveBeenCalledWith(
+ "meep",
+ 80,
+ [],
+ expectedRate,
+ "task_completed",
+ );
+ });
+});
+
+describe("notification log", () => {
+ // The only record of why the app made a noise. A user reporting a sound they
+ // did not expect has nothing else to send us.
+ it.each([
+ {
+ label: "delivered notification names its reason, trigger and sound",
+ hasFocus: false,
+ activeTarget: undefined,
+ settings: undefined,
+ expected: [
+ '"reason":"task_needs_input"',
+ '"trigger":"local_permission_request"',
+ '"channel":"native"',
+ '"soundPlayed":true',
+ '"sound":"meep"',
+ ],
+ // The line reaches central logs, so the task title must not ride along.
+ absent: ["needs your input", "My task"],
+ },
+ {
+ label: "suppressed notification records that nothing played",
+ hasFocus: true,
+ activeTarget: taskTarget(TASK_ID),
+ settings: undefined,
+ expected: ['"channel":"suppress"', '"soundPlayed":false'],
+ absent: [],
+ },
+ {
+ // A sound of "none" leaves the OS chime audible, so a noise still came
+ // out and the line has to name it.
+ label: "native notification with no completion sound names the OS chime",
+ hasFocus: false,
+ activeTarget: undefined,
+ settings: { completionSound: "none" as const },
+ expected: ['"soundPlayed":false', '"osChimePlayed":true'],
+ absent: [],
+ },
+ ])("$label", ({ hasFocus, activeTarget, settings, expected, absent }) => {
+ clearCapturedLogs();
+ const { bus } = makeBus({ hasFocus, activeTarget, settings });
+
+ bus.notifyPermissionRequest("My task", TASK_ID, {
+ trigger: "local_permission_request",
+ });
+
+ const logs = formatCapturedLogs();
+ for (const fragment of expected) expect(logs).toContain(fragment);
+ for (const fragment of absent) expect(logs).not.toContain(fragment);
});
});
diff --git a/products/desktop/packages/ui/src/features/notifications/notifications.ts b/products/desktop/packages/ui/src/features/notifications/notifications.ts
index 04272edf86d2..102d9076e7c7 100644
--- a/products/desktop/packages/ui/src/features/notifications/notifications.ts
+++ b/products/desktop/packages/ui/src/features/notifications/notifications.ts
@@ -20,16 +20,30 @@ import {
type INotificationSettings,
NOTIFICATION_SETTINGS_PROVIDER,
} from "./identifiers";
-import { routeNotification } from "./routeNotification";
+import { describeTarget, routeNotification } from "./routeNotification";
const MAX_TITLE_LENGTH = 50;
const log = logger.scope("notifications");
+// Why a notification was raised. Every delivery logs it, so a sound the user
+// did not expect can be traced back to the producer that asked for it.
+export type NotificationReason =
+ | "task_completed"
+ | "task_needs_input"
+ | "canvas_generation"
+ | "image_build"
+ | "error"
+ | "settings_test";
+
// In-app toast presentation for the focused-but-elsewhere tier. Only levels that
// support an action link are allowed (the bus derives the action from `target`).
type ToastLevel = "success" | "error" | "warning";
export interface NotificationDescriptor {
+ reason: NotificationReason;
+ // Extra facts the producer knows about the trigger (which code path raised
+ // it, the stop reason, the task run). Logged verbatim beside `reason`.
+ debug?: Record<string, unknown>;
// Native title; defaults to "PostHog".
title?: string;
body: string;
@@ -79,12 +93,13 @@ export class NotificationBus {
) {}
notify(descriptor: NotificationDescriptor): void {
+ const appFocused = this.view.hasFocus();
+ const viewingTarget = this.view.getActiveTarget();
const channel = routeNotification({
- appFocused: this.view.hasFocus(),
- viewingTarget: this.view.getActiveTarget(),
+ appFocused,
+ viewingTarget,
notificationTarget: descriptor.target,
});
- if (channel === "suppress") return;
const settings = this.settings.get();
const playbackRate =
@@ -92,6 +107,41 @@ export class NotificationBus {
descriptor.soundDurationMs !== undefined
? playbackRateForTaskDuration(descriptor.soundDurationMs)
: 1;
+ // Answers "does a sound come out of this?" for both the log line and the
+ // native silent flag below. A `custom:` id whose sound was deleted
+ // resolves to nothing. Under a `random-*` sound this re-picks, so it
+ // reports whether a sound plays, not which one.
+ const willPlaySound =
+ resolveSoundUrl(settings.completionSound, settings.customSounds) !== null;
+ // A native notification we leave unsilenced rings the OS chime instead, so
+ // the line has to name that noise rather than read as silence.
+ const nativeSilent = descriptor.silent ?? willPlaySound;
+ const osChimePlayed =
+ channel === "native" && settings.desktopNotifications && !nativeSilent;
+
+ // One line for every notification, including the suppressed ones. At info
+ // level on purpose: packaged builds drop debug, and "the app made a noise
+ // and I do not know why" is not reproducible without this in the log file.
+ // `body` stays out — info lines reach central logs and it carries task,
+ // canvas and image names, which `reason` and `target` identify without.
+ log.info("Notification", {
+ reason: descriptor.reason,
+ channel,
+ target: describeTarget(descriptor.target),
+ viewingTarget: describeTarget(viewingTarget),
+ appFocused,
+ sound: settings.completionSound,
+ soundPlayed: channel !== "suppress" && willPlaySound,
+ osChimePlayed,
+ volume: settings.completionVolume,
+ playbackRate,
+ soundDurationMs: descriptor.soundDurationMs,
+ desktopNotifications: settings.desktopNotifications,
+ context: descriptor.debug,
+ });
+
+ if (channel === "suppress") return;
+
// Sound fires on both delivered tiers (toast + native), not on suppress —
// matching the pre-bus behavior where any non-suppressed notification rang.
playCompletionSound(
@@ -99,6 +149,7 @@ export class NotificationBus {
settings.completionVolume,
settings.customSounds,
playbackRate,
+ descriptor.reason,
);
if (channel === "toast") {
@@ -107,17 +158,11 @@ export class NotificationBus {
}
// native
- // Silence the OS notification's own chime only when we'll actually play a
- // completion sound. A `custom:` id whose sound was deleted resolves to
- // nothing, so the native chime should still ring rather than leaving the
- // notification silent-and-soundless.
- const willPlaySound =
- resolveSoundUrl(settings.completionSound, settings.customSounds) !== null;
if (settings.desktopNotifications) {
this.notifications.notify({
title: descriptor.title ?? "PostHog",
body: descriptor.body,
- silent: descriptor.silent ?? willPlaySound,
+ silent: nativeSilent,
target: descriptor.target,
});
}
@@ -133,9 +178,12 @@ export class NotificationBus {
stopReason: string,
taskId?: string,
durationMs?: number,
+ debug?: Record<string, unknown>,
): void {
if (stopReason !== "end_turn") return;
this.notify({
+ reason: "task_completed",
+ debug: { ...debug, stopReason },
body: `"${this.truncateTitle(taskTitle)}" finished`,
target: taskId ? { kind: "task", taskId } : undefined,
toast: { level: "success" },
@@ -151,8 +199,14 @@ export class NotificationBus {
return () => this.taskActivityListeners.delete(listener);
}
- notifyPermissionRequest(taskTitle: string, taskId?: string): void {
+ notifyPermissionRequest(
+ taskTitle: string,
+ taskId?: string,
+ debug?: Record<string, unknown>,
+ ): void {
this.notify({
+ reason: "task_needs_input",
+ debug,
body: `"${this.truncateTitle(taskTitle)}" needs your input`,
target: taskId ? { kind: "task", taskId } : undefined,
toast: { level: "warning" },
@@ -169,6 +223,7 @@ export class NotificationBus {
): void {
const summary = summarizeError(error);
this.notify({
+ reason: "error",
title,
body: summary,
target,
diff --git a/products/desktop/packages/ui/src/features/notifications/routeNotification.ts b/products/desktop/packages/ui/src/features/notifications/routeNotification.ts
index 5e9efe552a9c..c1974777f53d 100644
--- a/products/desktop/packages/ui/src/features/notifications/routeNotification.ts
+++ b/products/desktop/packages/ui/src/features/notifications/routeNotification.ts
@@ -37,8 +37,9 @@ export function resolveActiveNotificationTarget(
}
// Stable identity string for a target. A new kind is a compile error here (the
-// switch is exhaustive), so equality and key-based lookups stay in one place.
-function targetKey(target: NotificationTarget): string {
+// switch is exhaustive), so equality, log lines and key-based lookups stay in
+// one place.
+export function targetKey(target: NotificationTarget): string {
switch (target.kind) {
case "task":
return `task:${target.taskId}`;
@@ -47,6 +48,11 @@ function targetKey(target: NotificationTarget): string {
}
}
+// Log-safe rendering of an optional target.
+export function describeTarget(target: NotificationTarget | undefined): string {
+ return target ? targetKey(target) : "none";
+}
+
// Whether two targets point at the same thing.
export function targetsEqual(
a: NotificationTarget | undefined,
diff --git a/products/desktop/packages/ui/src/features/notifications/speechNotifier.ts b/products/desktop/packages/ui/src/features/notifications/speechNotifier.ts
index b1b82d8f6604..e141b01cf193 100644
--- a/products/desktop/packages/ui/src/features/notifications/speechNotifier.ts
+++ b/products/desktop/packages/ui/src/features/notifications/speechNotifier.ts
@@ -3,6 +3,7 @@ import {
SPEECH_QUEUE_SERVICE,
} from "@posthog/core/speech/identifiers";
import type { NotificationTarget } from "@posthog/platform/notifications";
+import { logger } from "@posthog/ui/shell/logger";
import { inject, injectable } from "inversify";
import {
ACTIVE_VIEW_PROVIDER,
@@ -10,13 +11,15 @@ import {
type ISpeechNotifySettings,
SPEECH_NOTIFY_SETTINGS,
} from "./identifiers";
-import { routeNotification } from "./routeNotification";
+import { describeTarget, routeNotification } from "./routeNotification";
import {
type SpeechKind,
type SpeechSource,
shouldSpeak,
} from "./speechRouting";
+const log = logger.scope("notifications");
+
export interface SpeakRequest {
text: string;
kind: SpeechKind;
@@ -49,16 +52,36 @@ export class SpeechNotifier {
const target: NotificationTarget | undefined = request.taskId
? { kind: "task", taskId: request.taskId }
: undefined;
+ // Read focus and route once: a focus change between the decision and the
+ // log line would otherwise leave the two contradicting each other.
+ const appFocused = this.view.hasFocus();
+ const viewingTarget = this.view.getActiveTarget();
const channel = routeNotification({
- appFocused: this.view.hasFocus(),
- viewingTarget: this.view.getActiveTarget(),
+ appFocused,
+ viewingTarget,
notificationTarget: target,
});
- if (
- !shouldSpeak(request.kind, request.source, channel, this.settings.get())
- )
- return;
+ const speaks = shouldSpeak(
+ request.kind,
+ request.source,
+ channel,
+ this.settings.get(),
+ );
+
+ // Speech is the other way the app makes a noise, so it logs the same
+ // decision shape as the notification bus.
+ log.info("Speech notification", {
+ kind: request.kind,
+ source: request.source,
+ channel,
+ spoke: speaks,
+ target: describeTarget(target),
+ viewingTarget: describeTarget(viewingTarget),
+ appFocused,
+ });
+
+ if (!speaks) return;
this.queue.enqueue({
text: request.text,
diff --git a/products/desktop/packages/ui/src/features/settings/sections/NotificationsSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/NotificationsSettings.tsx
index fe1ba81205fe..3f85920b2f68 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/NotificationsSettings.tsx
+++ b/products/desktop/packages/ui/src/features/settings/sections/NotificationsSettings.tsx
@@ -354,6 +354,8 @@ export function NotificationsSettings() {
completionSound,
completionVolume,
customSounds,
+ 1,
+ "settings_preview",
)
}
>
@@ -740,7 +742,13 @@ function CustomSoundRow({
size="icon-sm"
aria-label={`Play ${sound.name}`}
onClick={() =>
- playCompletionSound(`custom:${sound.id}`, volume, [sound])
+ playCompletionSound(
+ `custom:${sound.id}`,
+ volume,
+ [sound],
+ 1,
+ "settings_preview",
+ )
}
>
<Play weight="fill" size={11} />
@@ -776,6 +784,7 @@ function TestSection({
const testToast = () =>
bus?.notify({
+ reason: "settings_test",
body: "Test notification",
toast: {
level: "success",
@@ -788,6 +797,7 @@ function TestSection({
const testToastDeepLink = () => {
if (!bus || !deepLinkTask) return;
bus.notify({
+ reason: "settings_test",
body: `"${deepLinkTask.title}"`,
target: { kind: "task", taskId: deepLinkTask.id },
toast: {
diff --git a/products/desktop/packages/ui/src/features/settings/sections/environments/imageBuildWatcher.ts b/products/desktop/packages/ui/src/features/settings/sections/environments/imageBuildWatcher.ts
index 6e952c9f02b4..cd78a4795639 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/environments/imageBuildWatcher.ts
+++ b/products/desktop/packages/ui/src/features/settings/sections/environments/imageBuildWatcher.ts
@@ -31,6 +31,8 @@ function notifyBuildResult(image: SandboxCustomImage): void {
: undefined;
if (image.status === "ready") {
bus.notify({
+ reason: "image_build",
+ debug: { imageId: image.id, status: image.status },
body: `Image "${image.name}" is ready (v${image.version})`,
target,
toast: { level: "success" },
@@ -38,6 +40,8 @@ function notifyBuildResult(image: SandboxCustomImage): void {
return;
}
bus.notify({
+ reason: "image_build",
+ debug: { imageId: image.id, status: image.status },
body: `Image "${image.name}" build failed: ${imageFailureDetail(image).split("\n")[0]}`,
target,
toast: { level: "error" },
diff --git a/products/desktop/packages/ui/src/utils/sounds.ts b/products/desktop/packages/ui/src/utils/sounds.ts
index 9e4a69923888..509917f9e5c1 100644
--- a/products/desktop/packages/ui/src/utils/sounds.ts
+++ b/products/desktop/packages/ui/src/utils/sounds.ts
@@ -3,6 +3,7 @@ import type {
CompletionSound,
CustomSound,
} from "@posthog/ui/features/settings/settingsStore";
+import { logger } from "@posthog/ui/shell/logger";
import bubblesUrl from "../assets/sounds/bubbles.mp3";
import daniloUrl from "../assets/sounds/danilo.mp3";
import dropUrl from "../assets/sounds/drop.mp3";
@@ -20,6 +21,7 @@ import switchUrl from "../assets/sounds/switch.mp3";
import wilhelmUrl from "../assets/sounds/wilhelm.mp3";
const CUSTOM_SOUND_PREFIX = "custom:";
+const log = logger.scope("sounds");
const SOUND_URLS: Record<Exclude<BuiltInCompletionSound, "none">, string> = {
guitar: guitarUrl,
@@ -98,20 +100,46 @@ export function resolveSoundUrl(
return SOUND_URLS[sound as Exclude<BuiltInCompletionSound, "none">] ?? null;
}
+// Names the concrete sound a `random-*` mode picked, without putting a custom
+// sound's inline data URL in the log.
+function describeSoundUrl(url: string, customSounds: CustomSound[]): string {
+ const builtIn = Object.entries(SOUND_URLS).find(([, u]) => u === url);
+ if (builtIn) return builtIn[0];
+ const custom = customSounds.find((s) => s.dataUrl === url);
+ return custom ? `${CUSTOM_SOUND_PREFIX}${custom.id}` : "unknown";
+}
+
export function playTrashSound(): void {
const audio = new Audio(dropUrl);
audio.volume = 0.35;
void audio.play().catch(() => undefined);
}
+// `reason` only reaches the log: it separates a notification's sound from a
+// settings preview, which otherwise look identical in the log file.
export function playCompletionSound(
sound: CompletionSound,
volume = 80,
customSounds: CustomSound[] = [],
playbackRate = 1,
+ reason = "unspecified",
): void {
const url = resolveSoundUrl(sound, customSounds);
- if (!url) return;
+ if (!url) {
+ log.debug("Completion sound resolved to nothing, staying quiet", {
+ sound,
+ reason,
+ });
+ return;
+ }
+ const resolvedSound = describeSoundUrl(url, customSounds);
+ log.info("Playing completion sound", {
+ sound,
+ resolvedSound,
+ reason,
+ volume,
+ playbackRate,
+ });
if (currentAudio) {
currentAudio.pause();
@@ -122,8 +150,14 @@ export function playCompletionSound(
audio.volume = Math.max(0, Math.min(100, volume)) / 100;
audio.playbackRate = playbackRate;
currentAudio = audio;
- audio.play().catch(() => {
+ audio.play().catch((error: unknown) => {
// Audio play can fail if user hasn't interacted with the page yet
+ log.warn("Completion sound failed to play", {
+ sound,
+ resolvedSound,
+ reason,
+ error,
+ });
});
audio.addEventListener("ended", () => {
if (currentAudio === audio) {