Файли
openidea/src/workbench/notificationStore.ts
T
Bert Verhelstтаbertyhell c931cbecc0 fix(run): keep the dependency install prompt inside the IDE (#8242)
Branch switches rewrite lockfiles, so the "Dependencies changed since the last install" prompt came back each time and, with the IDE in the background, was mirrored to an OS notification. Notifications can now pass system: false to stay in the balloon and the Notifications tool window, and the install prompt does (IDEA keeps system notifications for finished builds, tests and long tasks). The package.json check now also counts overrides, resolutions, pnpm overrides/patches/extensions/peer rules, bundled deps, *Meta and workspaces, ignoring key order; baselines move to a v2 store.

Co-authored-by: bertyhell <[email protected]>
2026-12-05 23:17:06 +08:00

276 рядки
11 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
/** Notification center: balloons + history, backing `NotificationService`. */
import type { ReactNode } from "react";
import { create } from "zustand";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { buildToolRecovery } from "@/platform/buildToolRecovery";
import { tx, txTemplate } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import type { NotificationService } from "./contributions";
export type NotificationLevel = "info" | "warning" | "error";
export interface IdeNotification {
id: number;
key?: string;
level: NotificationLevel;
title: string;
body?: ReactNode;
actions?: Array<{ label: string; run: () => void }>;
time: number;
read: boolean;
/** Text shown as written (see `NotificationService.notify`). */
verbatim?: boolean;
/** Currently shown as a balloon. */
balloon: boolean;
sticky: boolean;
suppressGroupAction?: boolean;
group: string;
/** Listed in the Notifications tool window (the group's "Show in tool window"). */
logged: boolean;
}
/** Notification groups shown in Settings › Appearance & Behavior › Notifications. */
export const NOTIFICATION_GROUPS: ReadonlyArray<{ id: string; title: string }> = [
{ id: "system", title: "System Messages" },
{ id: "lsp", title: "Language Servers" },
{ id: "vcs", title: "Version Control" },
{ id: "run", title: "Run and Debug" },
{ id: "tools", title: "External Tools" },
{ id: "search", title: "Find in Files" },
{ id: "plugins", title: "Plugins" },
{ id: "terminal", title: "Terminal" },
{ id: "updates", title: "IDE Updates" },
{ id: "distractionFree", title: "Distraction Free Mode" },
];
export type NotificationDisplay = "balloon" | "sticky" | "none";
interface NotificationPrefs {
balloons: boolean;
sound: boolean;
display: NotificationDisplay;
log: boolean;
}
/** Settings › Notifications for one group (raw settings: the shell does not depend on the settings feature). */
export function notificationPrefs(group: string): NotificationPrefs {
const n = useProject.getState().settings?.notifications;
const g = n?.groups?.[group];
const display = g?.display === "sticky" || g?.display === "none" ? g.display : "balloon";
return { balloons: n?.balloons !== false, sound: n?.sound === true, display, log: g?.log !== false };
}
/** Errors always show; other notifications offer "Don't Show Again" for their group. */
export function canSuppress(n: Pick<IdeNotification, "level" | "group" | "suppressGroupAction">): boolean {
return n.suppressGroupAction !== false && n.level !== "error" && notificationPrefs(n.group).display !== "none";
}
/**
* "Don't Show Again": the group's balloons are turned off (Settings ›
* Notifications › "No popup"); its notifications are still logged.
*/
export async function suppressGroup(group: string): Promise<void> {
const groups = { ...(useProject.getState().settings?.notifications?.groups ?? {}) };
groups[group] = { ...(groups[group] ?? {}), display: "none", log: groups[group]?.log ?? true };
const settings = await call(commands.settingsSet("global", "notifications.groups", JSON.stringify(groups)));
useProject.setState({ settings });
useNotifications.setState((s) => ({
items: s.items.flatMap((x) => (x.group !== group || !x.balloon ? [x] : x.logged ? [{ ...x, balloon: false }] : [])),
}));
}
function groupOf(n: { group?: string; key?: string }): string {
if (n.group) return n.group;
if (n.key?.startsWith("app.update")) return "updates";
if (n.key?.startsWith("lsp")) return "lsp";
return "system";
}
let audio: AudioContext | null = null;
/** Short notification chime ("Play sound"). */
function playSound() {
try {
audio ??= new AudioContext();
const osc = audio.createOscillator();
const gain = audio.createGain();
osc.frequency.value = 880;
gain.gain.setValueAtTime(0.08, audio.currentTime);
gain.gain.exponentialRampToValueAtTime(0.0001, audio.currentTime + 0.25);
osc.connect(gain).connect(audio.destination);
osc.start();
osc.stop(audio.currentTime + 0.25);
} catch {
/* no audio output */
}
}
interface NotificationState {
items: IdeNotification[];
}
export const useNotifications = create<NotificationState>(() => ({ items: [] }));
/** IDEA fades balloons out after 10 s; errors are sticky balloons (as IDEA's error groups). */
export const BALLOON_TIMEOUT: Record<NotificationLevel, number | null> = { info: 10000, warning: 10000, error: null };
/**
* Sticky balloons fade too, after 5 minutes of active window time, as in IDEA:
* the notification stays unread in the Notifications tool window. One that the
* tool window does not list stays until dismissed.
*/
export const STICKY_BALLOON_TIMEOUT = 5 * 60 * 1000;
/** Fade-out delay of a balloon, or null when it stays until dismissed. */
export function balloonTimeout(n: Pick<IdeNotification, "level" | "sticky" | "logged">): number | null {
if (n.sticky) return n.logged ? STICKY_BALLOON_TIMEOUT : null;
return BALLOON_TIMEOUT[n.level] ?? BALLOON_TIMEOUT.info;
}
const MAX_HISTORY = 200;
let seq = 0;
/**
* OS toasts for a burst of balloons (an external agent editing files while OpenIDEA
* is in the background, a build) are coalesced: the first shows at once, the ones
* that follow within a quiet period become one toast naming the last and how many
* more arrived. Balloons and the Notifications tool window keep every notification.
*/
const SYSTEM_TOAST_QUIET_MS = 3000;
/** A steady stream still raises a summary this often. */
const SYSTEM_TOAST_MAX_WAIT_MS = 30_000;
let toastTimer: ReturnType<typeof setTimeout> | undefined;
let toastBatch: Array<{ title: string; body: string }> = [];
let toastBatchStart = 0;
function showToast(title: string, body: string) {
void call(commands.showSystemNotification(title, body)).catch(() => {});
}
/** Ends a quiet period: the toasts held back during it, as one. */
function flushToasts() {
const batch = toastBatch;
toastBatch = [];
if (!batch.length) {
toastTimer = undefined;
return;
}
const last = batch[batch.length - 1]!;
const more = batch.length - 1;
const count = more === 1 ? tx`${more} more notification` : tx`${more} more notifications`;
showToast(last.title, more === 0 ? last.body : [last.body, count].filter(Boolean).join("\n"));
// What arrives right after the summary joins the next one.
toastTimer = setTimeout(flushToasts, SYSTEM_TOAST_QUIET_MS);
}
function systemToast(title: string, body: string) {
if (toastTimer === undefined) {
showToast(title, body);
toastTimer = setTimeout(flushToasts, SYSTEM_TOAST_QUIET_MS);
return;
}
if (!toastBatch.length) toastBatchStart = Date.now();
toastBatch.push({ title, body });
clearTimeout(toastTimer);
const waited = Date.now() - toastBatchStart;
toastTimer = setTimeout(flushToasts, Math.max(0, Math.min(SYSTEM_TOAST_QUIET_MS, SYSTEM_TOAST_MAX_WAIT_MS - waited)));
}
export function notify(n: Parameters<NotificationService["notify"]>[0]): number {
const id = ++seq;
const group = groupOf(n);
const prefs = notificationPrefs(group);
// The answer to a command the user ran is not a notification they opted out of.
const balloon = n.userInitiated === true || (prefs.balloons && prefs.display !== "none");
const sticky = prefs.display === "sticky" || (n.sticky ?? BALLOON_TIMEOUT[n.level] === null);
// Neither shown nor listed: dropped, as IDEA's "No popup" + no log.
if (!balloon && !prefs.log) return id;
const item: IdeNotification = {
id,
key: n.key,
level: n.level,
title: n.title,
body: n.body,
actions: n.actions,
verbatim: n.verbatim,
time: Date.now(),
read: false,
balloon,
sticky,
suppressGroupAction: n.suppressGroupAction,
group,
logged: prefs.log,
};
useNotifications.setState((s) => {
const rest = n.key ? s.items.filter((x) => x.key !== n.key) : s.items;
return { items: [item, ...rest].slice(0, MAX_HISTORY) };
});
// OS toast owns the chime when system notifications are on and the app is backgrounded.
const systemOn = useProject.getState().settings?.notifications?.systemNotifications !== false;
const backgrounded = typeof document !== "undefined" && !document.hasFocus();
const system = n.system !== false;
if (balloon && prefs.sound && !n.silent && !(backgrounded && (systemOn || !system))) playSound();
if (balloon && system && isTauri()) {
// In the UI language, as the balloon shows it; a plugin's own text stays as written.
const shown = (text: string) => (n.verbatim ? text : txTemplate(text));
const plain = typeof n.body === "string" ? shown(n.body) : "";
systemToast(shown(n.title), plain);
}
return id;
}
export function dismissBalloon(id: number) {
useNotifications.setState((s) => ({
// Unlogged notifications only existed for their balloon.
items: s.items.flatMap((x) => (x.id !== id ? [x] : x.logged ? [{ ...x, balloon: false }] : [])),
}));
}
/** Hides the balloon for `key`: the condition it reported no longer holds. */
export function expireNotification(key: string) {
// Called on every success (a server turning ready): nothing shown, no new state.
if (!useNotifications.getState().items.some((x) => x.key === key && x.balloon)) return;
useNotifications.setState((s) => ({
items: s.items.flatMap((x) => (x.key !== key || !x.balloon ? [x] : x.logged ? [{ ...x, balloon: false }] : [])),
}));
}
export function removeNotification(id: number) {
useNotifications.setState((s) => ({ items: s.items.filter((x) => x.id !== id) }));
}
export function clearNotifications() {
useNotifications.setState({ items: [] });
}
/** A project switch drops the previous project's notifications; app-wide ones (updates) stay. */
export function clearProjectNotifications() {
useNotifications.setState((s) => ({ items: s.items.filter((x) => x.group === "updates") }));
}
/** The list was seen: its entries are read; unlogged balloons were not shown there. */
export function markAllNotificationsRead() {
useNotifications.setState((s) => ({
items: s.items.map((x) => (!x.logged || (x.read && !x.balloon) ? x : { ...x, read: true, balloon: false })),
}));
}
export const notificationServiceImpl: NotificationService = {
notify: (n) => void notify(n),
expire: expireNotification,
};
export function installNotifyEvents(): () => void {
return onIdeEvent(
"notify",
// Backend text may carry values (paths, names); `{name}` catalog templates translate it.
(e) => {
const recovery = e.body ? buildToolRecovery(e.body) : undefined;
void notify({
level: e.level,
title: txTemplate(e.title),
...recovery,
body: recovery ? txTemplate(recovery.body) : undefined,
});
},
);
}