Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(notification): prevent replayed task notifications (#948)

geng yuebc5a1c43d581
diff --git a/apps/desktop/electron/main/ipc/notification-ipc.ts b/apps/desktop/electron/main/ipc/notification-ipc.ts
index d9c3d16f0..f9deb3676 100644
--- a/apps/desktop/electron/main/ipc/notification-ipc.ts
+++ b/apps/desktop/electron/main/ipc/notification-ipc.ts
@@ -17,10 +17,67 @@ export type NotificationIpcDependencies = {
// Windows delivers Action Center activation through the native notification
// presenter, which can only find notifications that are still strongly
-// referenced by the main process. Keep task notifications alive until their
-// native lifecycle ends instead of letting the IPC handler's local reference
-// disappear as soon as it returns.
-const taskNativeNotifications = new Set<SystemNotification>();
+// referenced by the main process. Keep task notifications indexed by their
+// durable id until the user acknowledges them. The id also makes delivery
+// idempotent when a late/replayed renderer event arrives for the same row.
+type TaskNativeNotificationEntry = {
+ notification: SystemNotification;
+ dismissed: boolean;
+};
+
+const taskNativeNotifications = new Map<string, TaskNativeNotificationEntry>();
+const dismissedTaskNotificationIds = new Set<string>();
+// A clear/mark-all acknowledgement dismisses every task row that existed at
+// that point. Renderer events carry the durable creation timestamp so Main can
+// reject a delayed pre-ack replay even when its native object was never shown.
+let dismissedBefore = 0;
+// Interactive prompts do not have durable ids or read/clear actions, but they
+// still need a strong reference until Electron reports their native lifecycle.
+const interactiveNativeNotifications = new Set<SystemNotification>();
+const MAX_DISMISSED_TASK_NOTIFICATION_IDS = 512;
+
+function rememberDismissedTaskNotification(id: string): void {
+ dismissedTaskNotificationIds.delete(id);
+ dismissedTaskNotificationIds.add(id);
+ while (dismissedTaskNotificationIds.size > MAX_DISMISSED_TASK_NOTIFICATION_IDS) {
+ const oldest = dismissedTaskNotificationIds.values().next().value;
+ if (typeof oldest !== "string") break;
+ dismissedTaskNotificationIds.delete(oldest);
+ }
+}
+
+function dismissTaskNativeNotification(id: string): void {
+ if (!id) return;
+ const entry = taskNativeNotifications.get(id);
+ taskNativeNotifications.delete(id);
+ rememberDismissedTaskNotification(id);
+ if (entry) {
+ entry.dismissed = true;
+ try {
+ entry.notification.close();
+ } catch {
+ // Native notification teardown is best-effort; the durable row is
+ // already acknowledged by the host.
+ }
+ }
+}
+
+function dismissAllTaskNativeNotifications(): void {
+ for (const id of [...taskNativeNotifications.keys()]) {
+ dismissTaskNativeNotification(id);
+ }
+}
+
+function releaseTaskNativeNotification(
+ id: string,
+ notification: SystemNotification,
+ retainId: boolean,
+): void {
+ const entry = taskNativeNotifications.get(id);
+ if (!entry || entry.notification !== notification) return;
+ taskNativeNotifications.delete(id);
+ if (retainId || entry.dismissed) rememberDismissedTaskNotification(id);
+}
/** Register durable notification queries and native notification actions. */
export function registerNotificationIpc({
@@ -45,19 +102,32 @@ export function registerNotificationIpc({
handle(IPC.invoke.notificationMarkRead, async (input: { id?: string } = {}) => {
const host = getHost();
if (!host) throw new Error("host unavailable");
- return host.call("notification.markRead", input);
+ const id = typeof input.id === "string" ? input.id.trim() : "";
+ const result = await host.call<{ ok?: boolean }>("notification.markRead", input);
+ if (id && result?.ok !== false) dismissTaskNativeNotification(id);
+ return result;
});
handle(IPC.invoke.notificationMarkAllRead, async () => {
const host = getHost();
if (!host) throw new Error("host unavailable");
- return host.call("notification.markAllRead");
+ const requestedAt = Date.now();
+ const result = await host.call<{ ok?: boolean }>("notification.markAllRead");
+ if (result?.ok === false) return result;
+ dismissedBefore = Math.max(dismissedBefore, requestedAt);
+ dismissAllTaskNativeNotifications();
+ return result;
});
handle(IPC.invoke.notificationClear, async () => {
const host = getHost();
if (!host) throw new Error("host unavailable");
- return host.call("notification.clear");
+ const requestedAt = Date.now();
+ const result = await host.call<{ ok?: boolean }>("notification.clear");
+ if (result?.ok === false) return result;
+ dismissedBefore = Math.max(dismissedBefore, requestedAt);
+ dismissAllTaskNativeNotifications();
+ return result;
});
handle(
@@ -78,6 +148,7 @@ export function registerNotificationIpc({
kind?: "task" | "interactive";
title?: string;
body?: string;
+ createdAt?: string;
} = {}) => {
const mainWindow = getMainWindow();
if (
@@ -92,8 +163,18 @@ export function registerNotificationIpc({
const kind = input.kind === "interactive" ? "interactive" : "task";
const title = String(input.title ?? "").trim().slice(0, 100);
const body = String(input.body ?? "").trim().slice(0, 240);
+ const createdAt =
+ typeof input.createdAt === "string" ? Date.parse(input.createdAt) : NaN;
if (!id || !sessionId || !title) return { shown: false };
+ if (
+ kind === "task" &&
+ Number.isFinite(createdAt) &&
+ createdAt <= dismissedBefore
+ ) {
+ return { shown: false };
+ }
+
const liveWindow = !mainWindow.isDestroyed();
const windowVisible = liveWindow && mainWindow.isVisible() === true;
const windowFocused = liveWindow && mainWindow.isFocused() === true;
@@ -109,11 +190,34 @@ export function registerNotificationIpc({
return { shown: false };
}
+ const existingTaskNotification =
+ kind === "task" ? taskNativeNotifications.get(id) : undefined;
+ if (
+ kind === "task" &&
+ (existingTaskNotification?.dismissed === true ||
+ existingTaskNotification !== undefined ||
+ dismissedTaskNotificationIds.has(id))
+ ) {
+ // A durable row is exactly-once. Replayed IPC events must not create a
+ // second Windows toast after the first one has moved to Action Center.
+ return { shown: false };
+ }
+
const notification = new SystemNotification({ title, body });
- taskNativeNotifications.add(notification);
- const releaseNotification = () => taskNativeNotifications.delete(notification);
- notification.once("close", releaseNotification);
- notification.once("failed", releaseNotification);
+ if (kind === "task") {
+ taskNativeNotifications.set(id, { notification, dismissed: false });
+ } else {
+ interactiveNativeNotifications.add(notification);
+ }
+ const releaseNotification = (retainId: boolean) => {
+ if (kind === "task") {
+ releaseTaskNativeNotification(id, notification, retainId);
+ } else {
+ interactiveNativeNotifications.delete(notification);
+ }
+ };
+ notification.once("close", () => releaseNotification(true));
+ notification.once("failed", () => releaseNotification(false));
notification.once("click", () => {
const window = getMainWindow();
try {
@@ -123,13 +227,13 @@ export function registerNotificationIpc({
window.focus();
sendToRenderer(IPC.event.notificationActivated, { id, sessionId });
} finally {
- releaseNotification();
+ releaseNotification(true);
}
});
try {
notification.show();
} catch {
- releaseNotification();
+ releaseNotification(false);
}
return { shown: true };
},
diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsx
index 8eef787c4..47acab9c0 100644
--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx
+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx
@@ -626,7 +626,11 @@ export function useAppShellRuntime() {
}
});
const offNotificationChanged = api.onNotificationChanged((notification) => {
- useAppStore.getState().receiveNotification(notification);
+ const accepted = useAppStore.getState().receiveNotification(notification);
+ // A host replay, renderer reload, or post-clear delayed event may refer
+ // to a row that is already present/acknowledged. Do not surface a native
+ // banner for an event the store intentionally rejected.
+ if (!accepted) return;
const failed = notification.kind === "task.failed";
const title = t(
failed ? "notifications.failedTitle" : "notifications.completedTitle",
@@ -644,6 +648,7 @@ export function useAppShellRuntime() {
kind: "task",
title,
body,
+ createdAt: notification.createdAt,
})
.catch(() => undefined);
});
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 161e10b20..697e93e06 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -527,6 +527,8 @@ export const api = {
kind: "task" | "interactive";
title: string;
body: string;
+ /** Durable task timestamp used by Main to reject pre-dismissal replays. */
+ createdAt?: string;
}) => invoke<{ shown: boolean }>(IPC.invoke.notificationShowNative, input),
setNotificationViewingSession: (sessionId: string | null) =>
invoke<{ ok: boolean }>(IPC.invoke.notificationSetViewingSession, {
diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.ts
index 8cf9b4a80..e42f31f57 100644
--- a/apps/desktop/src/stores/app-state.ts
+++ b/apps/desktop/src/stores/app-state.ts
@@ -314,7 +314,8 @@ export type AppState = {
/** Reload contributed work panel views. */
refreshPluginViews: () => Promise<void>;
refreshNotifications: () => Promise<void>;
- receiveNotification: (notification: AppNotification) => void;
+ /** Returns true only when this event was accepted as a new durable row. */
+ receiveNotification: (notification: AppNotification) => boolean;
markNotificationRead: (id: string) => Promise<void>;
markAllNotificationsRead: () => Promise<void>;
clearNotifications: () => Promise<void>;
diff --git a/apps/desktop/src/stores/runtime/catalog-runtime.ts b/apps/desktop/src/stores/runtime/catalog-runtime.ts
index 7022cac0f..ef97efc8c 100644
--- a/apps/desktop/src/stores/runtime/catalog-runtime.ts
+++ b/apps/desktop/src/stores/runtime/catalog-runtime.ts
@@ -1,6 +1,16 @@
export type CatalogRuntime = {
beginProviderRefresh: () => number;
providerGeneration: () => number;
+ /** Generation for notification list requests; newer mutations invalidate old reads. */
+ notificationGeneration: () => number;
+ invalidateNotificationRefresh: () => number;
+ /** Notification ids acknowledged individually; bounded to avoid unbounded renderer state. */
+ notificationReadIds: Set<string>;
+ rememberNotificationRead: (id: string) => void;
+ notificationReadBefore: () => number | null;
+ setNotificationReadBefore: (timestamp: number) => void;
+ notificationClearedAt: () => number | null;
+ setNotificationClearedAt: (timestamp: number) => void;
refreshedProviderModels: Set<string>;
providerModelLoads: Map<string, Promise<void>>;
getPluginRefresh: () => Promise<void> | null;
@@ -10,9 +20,27 @@ export type CatalogRuntime = {
/** Coalesces catalog reads without putting mutable request state in the store. */
export function createCatalogRuntime(): CatalogRuntime {
let providerModelsGeneration = 0;
+ let notificationStateGeneration = 0;
+ let notificationsReadBefore: number | null = null;
+ let notificationsClearedAt: number | null = null;
let pluginRefreshInFlight: Promise<void> | null = null;
const refreshedProviderModels = new Set<string>();
const providerModelLoads = new Map<string, Promise<void>>();
+ const notificationReadIds = new Set<string>();
+
+ const rememberNotificationRead = (id: string): void => {
+ const normalized = id.trim();
+ if (!normalized) return;
+ notificationReadIds.delete(normalized);
+ notificationReadIds.add(normalized);
+ // Notification ids are durable, but this process only needs a bounded
+ // replay guard. The host remains authoritative for older rows.
+ while (notificationReadIds.size > 512) {
+ const oldest = notificationReadIds.values().next().value;
+ if (typeof oldest !== "string") break;
+ notificationReadIds.delete(oldest);
+ }
+ };
return {
beginProviderRefresh: () => {
@@ -21,6 +49,23 @@ export function createCatalogRuntime(): CatalogRuntime {
return providerModelsGeneration;
},
providerGeneration: () => providerModelsGeneration,
+ notificationGeneration: () => notificationStateGeneration,
+ invalidateNotificationRefresh: () => {
+ notificationStateGeneration += 1;
+ return notificationStateGeneration;
+ },
+ notificationReadIds,
+ rememberNotificationRead,
+ notificationReadBefore: () => notificationsReadBefore,
+ setNotificationReadBefore: (timestamp) => {
+ if (!Number.isFinite(timestamp)) return;
+ notificationsReadBefore = Math.max(notificationsReadBefore ?? 0, timestamp);
+ },
+ notificationClearedAt: () => notificationsClearedAt,
+ setNotificationClearedAt: (timestamp) => {
+ if (!Number.isFinite(timestamp)) return;
+ notificationsClearedAt = Math.max(notificationsClearedAt ?? 0, timestamp);
+ },
refreshedProviderModels,
providerModelLoads,
getPluginRefresh: () => pluginRefreshInFlight,
diff --git a/apps/desktop/src/stores/slices/catalog-slice.ts b/apps/desktop/src/stores/slices/catalog-slice.ts
index dea45c15b..e30884cd1 100644
--- a/apps/desktop/src/stores/slices/catalog-slice.ts
+++ b/apps/desktop/src/stores/slices/catalog-slice.ts
@@ -175,23 +175,92 @@ export function createCatalogSlice({
},
refreshNotifications: async () => {
+ const generation = catalogRuntime.notificationGeneration();
const result = await api.listNotifications({ limit: 200 });
- set((state) => ({
- notifications: result.notifications,
- unreadNotificationCount: result.unreadCount,
- sessionOutcomes: {
- ...state.sessionOutcomes,
- ...latestSessionOutcomes(result.notifications),
- },
- }));
+ if (generation !== catalogRuntime.notificationGeneration()) return;
+ const clearedAt = catalogRuntime.notificationClearedAt();
+ const readBefore = catalogRuntime.notificationReadBefore();
+ const readIds = catalogRuntime.notificationReadIds;
+ const touchedSessionIds = new Set(
+ result.notifications.map((notification) => notification.sessionId),
+ );
+ const notifications = result.notifications
+ .filter((notification) => {
+ const createdAt = Date.parse(notification.createdAt);
+ return !(
+ clearedAt !== null &&
+ Number.isFinite(createdAt) &&
+ createdAt <= clearedAt
+ );
+ })
+ .map((notification) => {
+ const createdAt = Date.parse(notification.createdAt);
+ const acknowledgedById = readIds.has(notification.id);
+ const acknowledgedByTime =
+ readBefore !== null &&
+ Number.isFinite(createdAt) &&
+ createdAt <= readBefore;
+ if (
+ (acknowledgedById || acknowledgedByTime) &&
+ !notification.readAt
+ ) {
+ const acknowledgedAt =
+ acknowledgedByTime && readBefore !== null
+ ? readBefore
+ : Date.now();
+ return {
+ ...notification,
+ readAt: new Date(acknowledgedAt).toISOString(),
+ };
+ }
+ return notification;
+ });
+ const rawUnreadCount = result.notifications.reduce(
+ (count, notification) => count + (notification.readAt ? 0 : 1),
+ 0,
+ );
+ const effectiveUnreadCount = notifications.reduce(
+ (count, notification) => count + (notification.readAt ? 0 : 1),
+ 0,
+ );
+ set((state) => {
+ const sessionOutcomes = { ...state.sessionOutcomes };
+ for (const sessionId of touchedSessionIds) {
+ delete sessionOutcomes[sessionId];
+ }
+ Object.assign(sessionOutcomes, latestSessionOutcomes(notifications));
+ return {
+ notifications,
+ // Host count includes rows hidden by a local acknowledgement
+ // watermark; adjust only for rows present in this response.
+ unreadNotificationCount: Math.max(
+ 0,
+ result.unreadCount - rawUnreadCount + effectiveUnreadCount,
+ ),
+ sessionOutcomes,
+ };
+ });
},
receiveNotification: (notification: AppNotification) => {
+ const createdAt = Date.parse(notification.createdAt);
+ const clearedAt = catalogRuntime.notificationClearedAt();
+ const readBefore = catalogRuntime.notificationReadBefore();
+ if (
+ !Number.isFinite(createdAt) ||
+ catalogRuntime.notificationReadIds.has(notification.id) ||
+ (clearedAt !== null && createdAt <= clearedAt) ||
+ (readBefore !== null && createdAt <= readBefore) ||
+ get().notifications.some((item) => item.id === notification.id)
+ ) {
+ return false;
+ }
+ // A notification event is a state mutation too. Invalidate any list
+ // request that was already in flight so its older snapshot cannot erase
+ // this newly accepted row when it resolves.
+ catalogRuntime.invalidateNotificationRefresh();
set((state) => {
- const withoutCurrent = state.notifications.filter(
- (item) => item.id !== notification.id,
- );
- const notifications = [notification, ...withoutCurrent].slice(0, 200);
+ const notifications = [notification, ...state.notifications].slice(0, 200);
return {
notifications,
sessionOutcomes: {
@@ -199,42 +268,134 @@ export function createCatalogSlice({
[notification.sessionId]:
notification.kind === "task.failed" ? "failed" : "completed",
},
- unreadNotificationCount: notifications.reduce(
- (count, item) => count + (item.readAt ? 0 : 1),
- 0,
- ),
+ unreadNotificationCount:
+ state.unreadNotificationCount + (notification.readAt ? 0 : 1),
};
});
+ return true;
},
markNotificationRead: async (id) => {
const item = get().notifications.find((notification) => notification.id === id);
if (!item || item.readAt) return;
- await api.markNotificationRead(id);
+ const generation = catalogRuntime.invalidateNotificationRefresh();
+ try {
+ await api.markNotificationRead(id);
+ } catch (error) {
+ if (generation === catalogRuntime.notificationGeneration()) {
+ await get().refreshNotifications().catch(() => undefined);
+ }
+ throw error;
+ }
+ catalogRuntime.rememberNotificationRead(id);
const readAt = new Date().toISOString();
- set((state) => ({
- notifications: state.notifications.map((notification) =>
+ set((state) => {
+ const notifications = state.notifications.map((notification) =>
notification.id === id ? { ...notification, readAt } : notification,
- ),
- unreadNotificationCount: Math.max(0, state.unreadNotificationCount - 1),
- }));
+ );
+ const sessionId = state.notifications.find(
+ (notification) => notification.id === id,
+ )?.sessionId;
+ const sessionOutcomes = { ...state.sessionOutcomes };
+ if (sessionId) {
+ delete sessionOutcomes[sessionId];
+ Object.assign(
+ sessionOutcomes,
+ latestSessionOutcomes(
+ notifications.filter(
+ (notification) => notification.sessionId === sessionId,
+ ),
+ ),
+ );
+ }
+ return {
+ notifications,
+ unreadNotificationCount: Math.max(
+ 0,
+ state.unreadNotificationCount - 1,
+ ),
+ sessionOutcomes,
+ };
+ });
},
markAllNotificationsRead: async () => {
if (get().unreadNotificationCount === 0) return;
- await api.markAllNotificationsRead();
- const readAt = new Date().toISOString();
- set((state) => ({
- notifications: state.notifications.map((notification) =>
- notification.readAt ? notification : { ...notification, readAt },
- ),
- unreadNotificationCount: 0,
- }));
+ const acknowledgedIds = new Set(
+ get()
+ .notifications.filter((notification) => !notification.readAt)
+ .map((notification) => notification.id),
+ );
+ const requestedAt = Date.now();
+ const generation = catalogRuntime.invalidateNotificationRefresh();
+ try {
+ await api.markAllNotificationsRead();
+ } catch (error) {
+ if (generation === catalogRuntime.notificationGeneration()) {
+ await get().refreshNotifications().catch(() => undefined);
+ }
+ throw error;
+ }
+ const readAtMs = requestedAt;
+ const readAt = new Date(readAtMs).toISOString();
+ for (const id of acknowledgedIds) {
+ catalogRuntime.rememberNotificationRead(id);
+ }
+ catalogRuntime.setNotificationReadBefore(readAtMs);
+ set((state) => {
+ const notifications = state.notifications.map((notification) =>
+ notification.readAt || !acknowledgedIds.has(notification.id)
+ ? notification
+ : { ...notification, readAt },
+ );
+ const acknowledgedSessionIds = new Set(
+ state.notifications
+ .filter((notification) => acknowledgedIds.has(notification.id))
+ .map((notification) => notification.sessionId),
+ );
+ const sessionOutcomes = { ...state.sessionOutcomes };
+ for (const sessionId of acknowledgedSessionIds) {
+ delete sessionOutcomes[sessionId];
+ }
+ Object.assign(
+ sessionOutcomes,
+ latestSessionOutcomes(
+ notifications.filter((notification) =>
+ acknowledgedSessionIds.has(notification.sessionId),
+ ),
+ ),
+ );
+ return {
+ notifications,
+ unreadNotificationCount: notifications.reduce(
+ (count, notification) => count + (notification.readAt ? 0 : 1),
+ 0,
+ ),
+ sessionOutcomes,
+ };
+ });
},
clearNotifications: async () => {
- await api.clearNotifications();
- set({ notifications: [], unreadNotificationCount: 0 });
+ const requestedAt = Date.now();
+ const generation = catalogRuntime.invalidateNotificationRefresh();
+ try {
+ await api.clearNotifications();
+ } catch (error) {
+ // A failed clear must leave the local inbox usable. The generation
+ // invalidation above intentionally discards any older list response;
+ // fetch a current snapshot before surfacing the original error.
+ if (generation === catalogRuntime.notificationGeneration()) {
+ await get().refreshNotifications().catch(() => undefined);
+ }
+ throw error;
+ }
+ catalogRuntime.setNotificationClearedAt(requestedAt);
+ catalogRuntime.setNotificationReadBefore(requestedAt);
+ set({ notifications: [], unreadNotificationCount: 0, sessionOutcomes: {} });
+ // A turn that completed after the clear began is a legitimate new result.
+ // Reconcile once so it is not lost if its event raced the clear request.
+ await get().refreshNotifications();
},
openNotification: async (id) => {
diff --git a/apps/desktop/test/notification-contract.test.mjs b/apps/desktop/test/notification-contract.test.mjs
index 45b7846b6..54956b4b0 100644
--- a/apps/desktop/test/notification-contract.test.mjs
+++ b/apps/desktop/test/notification-contract.test.mjs
@@ -31,6 +31,8 @@ const [
]);
const eventsSource = readStoreModuleSync("slices/events-slice.ts");
+const catalogSource = readStoreModuleSync("slices/catalog-slice.ts");
+const catalogRuntimeSource = readStoreModuleSync("runtime/catalog-runtime.ts");
const notificationIpcSource = readMainModuleSync("ipc/notification-ipc.ts");
const desktopServicesSource = readMainModuleSync("services/desktop-services.ts");
@@ -112,18 +114,128 @@ test("task and interactive native notifications keep separate visibility rules",
});
test("native notifications retain live objects through OS activation", () => {
- assert.match(notificationIpcSource, /const taskNativeNotifications = new Set<SystemNotification>\(\)/);
- assert.match(notificationIpcSource, /taskNativeNotifications\.add\(notification\)/);
- assert.match(notificationIpcSource, /notification\.once\("close", releaseNotification\)/);
- assert.match(notificationIpcSource, /notification\.once\("failed", releaseNotification\)/);
+ assert.match(
+ notificationIpcSource,
+ /const taskNativeNotifications = new Map<string, TaskNativeNotificationEntry>\(\)/,
+ );
+ assert.match(
+ notificationIpcSource,
+ /taskNativeNotifications\.set\(id, \{ notification, dismissed: false \}\)/,
+ );
+ assert.match(notificationIpcSource, /notification\.once\("close", \(\) => releaseNotification\(true\)\)/);
+ assert.match(notificationIpcSource, /notification\.once\("failed", \(\) => releaseNotification\(false\)\)/);
assert.match(notificationIpcSource, /notification\.once\("click",/);
- assert.match(notificationIpcSource, /releaseNotification\(\);/);
+ assert.match(notificationIpcSource, /releaseNotification\((?:true|false)\)/);
assert.match(desktopServicesSource, /getMainWindow: \(\) => BrowserWindow \| null/);
assert.match(desktopServicesSource, /notification\.once\("click",/);
assert.match(desktopServicesSource, /window\.show\(\);/);
assert.match(desktopServicesSource, /window\.focus\(\);/);
});
+test("task native notifications are idempotent by durable notification id", () => {
+ // A renderer reload or a repeated host event may deliver the same durable
+ // notification more than once. Native delivery must keep one live object per
+ // durable id so Windows Action Center cannot accumulate duplicate banners.
+ assert.match(
+ notificationIpcSource,
+ /const taskNativeNotifications = new Map<string, TaskNativeNotificationEntry>\(\)/,
+ );
+ assert.match(notificationIpcSource, /taskNativeNotifications\.get\(id\)/);
+ assert.match(notificationIpcSource, /taskNativeNotifications\.set\(id, \{ notification, dismissed: false \}\)/);
+ assert.match(notificationIpcSource, /taskNativeNotifications\.delete\(id\)/);
+ assert.match(
+ notificationIpcSource,
+ /existingTaskNotification(?:\?\.dismissed|\s*!==\s*undefined)/,
+ );
+ assert.ok(
+ notificationIpcSource.indexOf("existingTaskNotification") <
+ notificationIpcSource.indexOf("new SystemNotification"),
+ "duplicate guard must run before constructing a native object",
+ );
+});
+
+test("read and clear notification actions dismiss outstanding task banners", () => {
+ const readStart = notificationIpcSource.indexOf(
+ "handle(IPC.invoke.notificationMarkRead",
+ );
+ const allReadStart = notificationIpcSource.indexOf(
+ "handle(IPC.invoke.notificationMarkAllRead",
+ );
+ const clearStart = notificationIpcSource.indexOf(
+ "handle(IPC.invoke.notificationClear",
+ );
+ const setViewingStart = notificationIpcSource.indexOf(
+ "IPC.invoke.notificationSetViewingSession",
+ );
+ const readHandler = notificationIpcSource.slice(readStart, allReadStart);
+ const allReadHandler = notificationIpcSource.slice(allReadStart, clearStart);
+ const clearHandler = notificationIpcSource.slice(clearStart, setViewingStart);
+
+ assert.match(readHandler, /dismissTaskNativeNotification\(id\)/);
+ assert.match(allReadHandler, /dismissAllTaskNativeNotifications\(\)/);
+ assert.match(clearHandler, /dismissAllTaskNativeNotifications\(\)/);
+ assert.ok(
+ readHandler.indexOf("await host.call") <
+ readHandler.indexOf("dismissTaskNativeNotification"),
+ "read acknowledgement must succeed before dismissing the native object",
+ );
+ assert.ok(
+ clearHandler.indexOf("await host.call") <
+ clearHandler.indexOf("dismissAllTaskNativeNotifications"),
+ "clear acknowledgement must succeed before dismissing native objects",
+ );
+ assert.match(notificationIpcSource, /function dismissTaskNativeNotification/);
+ assert.match(notificationIpcSource, /notification\.close\(\)/);
+ // Interactive prompts are transient and are not tied to durable inbox ids.
+ assert.match(notificationIpcSource, /interactiveNativeNotifications/);
+});
+
+test("notification list refreshes cannot resurrect cleared rows", () => {
+ assert.match(catalogRuntimeSource, /notificationGeneration/);
+ assert.match(catalogRuntimeSource, /invalidateNotificationRefresh/);
+ assert.match(catalogRuntimeSource, /notificationClearedAt/);
+ assert.match(catalogRuntimeSource, /setNotificationClearedAt/);
+
+ const refreshStart = catalogSource.indexOf("refreshNotifications: async");
+ const receiveStart = catalogSource.indexOf("receiveNotification:", refreshStart);
+ const clearStart = catalogSource.indexOf("clearNotifications: async");
+ const openStart = catalogSource.indexOf("openNotification:", clearStart);
+ const refreshBlock = catalogSource.slice(refreshStart, receiveStart);
+ const receiveBlock = catalogSource.slice(receiveStart, clearStart);
+ const clearBlock = catalogSource.slice(clearStart, openStart);
+
+ assert.match(refreshBlock, /notificationGeneration\(\)/);
+ assert.match(refreshBlock, /generation !== catalogRuntime\.notificationGeneration\(\)/);
+ assert.match(receiveBlock, /notificationClearedAt\(\)/);
+ assert.match(receiveBlock, /createdAt/);
+ assert.match(receiveBlock, /return;/);
+ assert.match(clearBlock, /invalidateNotificationRefresh\(\)/);
+ assert.match(clearBlock, /setNotificationClearedAt/);
+ assert.match(clearBlock, /sessionOutcomes:\s*\{\}/);
+
+ // A stale list response must be filtered before replacing the store. Merely
+ // guarding the request generation is insufficient when the clear operation
+ // itself performs a follow-up refresh against a lagging host read.
+ assert.match(
+ refreshBlock,
+ /result\.notifications[\s\S]{0,800}\.filter\(/,
+ );
+ assert.match(refreshBlock, /result\.unreadCount/);
+ assert.match(refreshBlock, /rawUnreadCount/);
+ assert.match(refreshBlock, /effectiveUnreadCount/);
+ assert.match(refreshBlock, /touchedSessionIds/);
+ assert.match(refreshBlock, /delete sessionOutcomes\[sessionId\]/);
+ assert.match(refreshBlock, /notificationClearedAt\(\)/);
+
+ assert.match(receiveBlock, /state\.unreadNotificationCount \+ /);
+
+ const readBlock = catalogSource.slice(
+ catalogSource.indexOf("markNotificationRead:"),
+ catalogSource.indexOf("markAllNotificationsRead:", refreshStart),
+ );
+ assert.match(readBlock, /state\.unreadNotificationCount\s*-\s*1/);
+});
+
test("plugins can request and send native notifications behind notify permission", () => {
assert.match(pluginRuntimeSource, /"ui\.getNotificationPermission"/);
assert.match(pluginRuntimeSource, /"ui\.requestNotificationPermission"/);
diff --git a/apps/desktop/test/notification-ipc-dismissal.test.mjs b/apps/desktop/test/notification-ipc-dismissal.test.mjs
new file mode 100644
index 000000000..9a0e7b2dd
--- /dev/null
+++ b/apps/desktop/test/notification-ipc-dismissal.test.mjs
@@ -0,0 +1,218 @@
+import assert from "node:assert/strict";
+import { EventEmitter } from "node:events";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import ts from "typescript";
+
+const IPC = {
+ invoke: {
+ notificationList: "notification.list",
+ notificationMarkRead: "notification.markRead",
+ notificationMarkAllRead: "notification.markAllRead",
+ notificationClear: "notification.clear",
+ notificationSetViewingSession: "notification.setViewingSession",
+ notificationShowNative: "notification.showNative",
+ },
+ event: { notificationActivated: "notification.activated" },
+};
+
+class FakeNotification extends EventEmitter {
+ static instances = [];
+ static isSupported() {
+ return true;
+ }
+
+ constructor(options) {
+ super();
+ this.options = options;
+ this.closed = false;
+ FakeNotification.instances.push(this);
+ }
+
+ show() {
+ this.shown = true;
+ }
+
+ close() {
+ this.closed = true;
+ this.emit("close");
+ }
+}
+
+function loadNotificationIpc() {
+ const file = new URL("../electron/main/ipc/notification-ipc.ts", import.meta.url);
+ const { outputText } = ts.transpileModule(readFileSync(file, "utf8"), {
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.CommonJS,
+ },
+ fileName: file.pathname,
+ });
+ const module = { exports: {} };
+ new Function("require", "exports", "module", outputText)(
+ (id) => {
+ if (id === "electron") return { Notification: FakeNotification };
+ if (id === "@pi-desktop/shared") return { IPC };
+ if (id === "../notification-policy") {
+ return { shouldShowNativeNotification: () => true };
+ }
+ throw new Error(`unexpected dependency: ${id}`);
+ },
+ module.exports,
+ module,
+ );
+ return module.exports;
+}
+
+function harness({ hostCall } = {}) {
+ FakeNotification.instances = [];
+ const handlers = new Map();
+ const calls = [];
+ const events = [];
+ const host = {
+ call: async (method, input) => {
+ calls.push({ method, input });
+ return hostCall ? hostCall(method, input) : { ok: true };
+ },
+ };
+ const mainWindow = {
+ isDestroyed: () => false,
+ isVisible: () => true,
+ isFocused: () => false,
+ isMinimized: () => false,
+ show: () => {},
+ focus: () => {},
+ restore: () => {},
+ };
+ const { registerNotificationIpc } = loadNotificationIpc();
+ registerNotificationIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ getHost: () => host,
+ getMainWindow: () => mainWindow,
+ getViewingSessionId: () => "session-current",
+ setViewingSessionId: () => {},
+ sendToRenderer: (channel, payload) => events.push({ channel, payload }),
+ });
+ return {
+ handlers,
+ calls,
+ events,
+ show: (input) => handlers.get(IPC.invoke.notificationShowNative)(input),
+ markRead: (id) => handlers.get(IPC.invoke.notificationMarkRead)({ id }),
+ markAllRead: () => handlers.get(IPC.invoke.notificationMarkAllRead)(),
+ clear: () => handlers.get(IPC.invoke.notificationClear)(),
+ };
+}
+
+test("duplicate task delivery is idempotent and read dismissal leaves a tombstone", async () => {
+ const h = harness();
+ const input = {
+ id: "durable-1",
+ sessionId: "session-1",
+ kind: "task",
+ title: "Task finished",
+ body: "Done",
+ };
+
+ assert.deepEqual(await h.show(input), { shown: true });
+ assert.deepEqual(await h.show(input), { shown: false });
+ assert.equal(FakeNotification.instances.length, 1);
+ assert.equal(FakeNotification.instances[0].closed, false);
+
+ await h.markRead(input.id);
+ assert.equal(FakeNotification.instances[0].closed, true);
+ assert.deepEqual(await h.show(input), { shown: false });
+ assert.deepEqual(h.calls.map(({ method }) => method), [
+ "notification.markRead",
+ ]);
+});
+
+test("clear and mark-all-read close every task object, while interactive prompts stay independent", async () => {
+ const h = harness();
+ const task = (id) => ({
+ id,
+ sessionId: "session-1",
+ kind: "task",
+ title: "Task finished",
+ body: "Done",
+ });
+ const interactive = {
+ id: "same-id",
+ sessionId: "session-1",
+ kind: "interactive",
+ title: "Approval",
+ body: "Please choose",
+ };
+
+ await h.show(task("task-1"));
+ await h.show(task("task-2"));
+ await h.markAllRead();
+ assert.deepEqual(FakeNotification.instances.map((item) => item.closed), [true, true]);
+
+ // An interactive prompt may reuse an id without colliding with task rows.
+ await h.show(interactive);
+ await h.show(interactive);
+ assert.equal(FakeNotification.instances.length, 4);
+ assert.equal(FakeNotification.instances[2].closed, false);
+ assert.equal(FakeNotification.instances[3].closed, false);
+
+ await h.clear();
+ assert.equal(FakeNotification.instances[2].closed, false);
+ assert.equal(FakeNotification.instances[3].closed, false);
+ assert.deepEqual(h.calls.map(({ method }) => method), [
+ "notification.markAllRead",
+ "notification.clear",
+ ]);
+});
+
+test("acknowledgement watermarks reject old task events but allow a later turn", async () => {
+ const h = harness();
+ const now = Date.now();
+ const task = (id, createdAt) => ({
+ id,
+ sessionId: "session-1",
+ kind: "task",
+ title: "Task finished",
+ body: "Done",
+ createdAt,
+ });
+
+ await h.markAllRead();
+ assert.deepEqual(
+ await h.show(task("before-mark-all", new Date(now - 60_000).toISOString())),
+ { shown: false },
+ );
+ assert.deepEqual(
+ await h.show(task("after-mark-all", new Date(now + 60_000).toISOString())),
+ { shown: true },
+ );
+
+ await h.clear();
+ assert.deepEqual(
+ await h.show(task("before-clear", new Date(now - 30_000).toISOString())),
+ { shown: false },
+ );
+ assert.deepEqual(
+ await h.show(task("after-clear", new Date(now + 120_000).toISOString())),
+ { shown: true },
+ );
+});
+
+test("a failed host acknowledgement does not dismiss a task banner prematurely", async () => {
+ const h = harness({
+ hostCall: async (method) => {
+ if (method === "notification.markRead") throw new Error("host unavailable");
+ return { ok: true };
+ },
+ });
+ const input = {
+ id: "durable-failure",
+ sessionId: "session-1",
+ kind: "task",
+ title: "Task failed",
+ body: "Retry",
+ };
+ await h.show(input);
+ await assert.rejects(h.markRead(input.id), /host unavailable/);
+ assert.equal(FakeNotification.instances[0].closed, false);
+});
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 31ee5b757..f1e6abd50 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -781,9 +781,14 @@ setup so a fast completion cannot beat the viewing-context update. Electron
combines this hint with Main-owned window visibility/focus at the terminal event
boundary. Missing, null, or mismatched context fails safe to notification. It
also invokes
-`pi-desktop/notification/showNative({ id, sessionId, kind, title, body })` after
-localizing a new record, where `kind` is `"task" | "interactive"`. This
-Electron-only request never crosses into the host RPC domain.
+`pi-desktop/notification/showNative({ id, sessionId, kind, title, body, createdAt? })`
+after localizing a new record, where `kind` is `"task" | "interactive"` and
+`createdAt` is the durable task timestamp when available. Main keeps a
+`dismissedBefore` watermark for successful mark-all-read/clear actions and
+rejects task deliveries at or before that timestamp; individual acknowledgements
+use the durable id as a tombstone. This prevents a delayed renderer or host
+replay from resurfacing an already acknowledged banner. This Electron-only
+request never crosses into the host RPC domain.
```ts
type AppNotification = {
@@ -825,6 +830,10 @@ Main sends two events:
and recalculates the exact unread count. A terminal result already visible in
the focused current chat, repeated terminal updates, and aborted turns emit
nothing.
+- The durable `id` is the renderer and Electron native-delivery idempotency key.
+ A repeated `notification.changed` payload for an id already present in the
+ local list is a no-op; a delayed payload whose row was acknowledged or
+ cleared is ignored and must not recreate the row or its sidebar outcome.
- `pi-desktop/notification/event/activated` after the user clicks Electron's
native system notification. Renderer follows its existing session-selection
path, including project activation for a project-bound session.
@@ -863,6 +872,14 @@ package identity so notification attribution, notification settings, taskbar
grouping, and installed shortcuts resolve to `PI-Desktop`, never the stock
Electron host.
+Task native objects are retained by durable notification id, with at most one
+live object per id. Replayed `showNative` requests do not create a second
+object. A successful `notification.markRead`, `notification.markAllRead`, or
+`notification.clear` closes matching task objects (and leaves an id tombstone
+long enough to reject late delivery); a failed host mutation does not dismiss
+the object optimistically. Interactive prompt notifications use a separate
+transient registry and are not affected by task inbox mutations.
+
The viewing-session hint is advisory and fail-safe: missing, stale, hidden, or
unfocused renderer state creates the durable notification. Suppression occurs
only when the main window is visible and focused and the reported chat session
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 504cf968e..6e81b4d09 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -736,6 +736,10 @@ type NotificationListResult = {
- `notification.markAllRead({}) -> { ok: true }` updates every unread row in
one transaction.
- `notification.clear({}) -> { ok: true }` deletes inbox rows only.
+- `id` is the stable exactly-once key for renderer and native delivery. A
+ client must discard duplicate or delayed records for an id it has already
+ acknowledged/cleared; clearing the inbox never makes an old terminal turn
+ eligible for insertion again. A later terminal turn receives a new id.
- No `notification.created` JSON-RPC server notification is emitted. Electron
receives the inserted record directly from `session.endTurn`, avoiding a
second ordering channel between terminal turn persistence and UI refresh.
@@ -1276,4 +1280,3 @@ notification carrying that same snapshot. Approval and rejection require the
current entity digest, so a security-relevant edit cannot reuse an older local
decision. Disconnect deletes only local credentials, vault keys, metadata and
staging files; remote objects remain intact.
-
diff --git a/docs/spec/04-ux/07-ui-design-system.md b/docs/spec/04-ux/07-ui-design-system.md
index 03989ae43..d5ff5b7bd 100644
--- a/docs/spec/04-ux/07-ui-design-system.md
+++ b/docs/spec/04-ux/07-ui-design-system.md
@@ -263,8 +263,11 @@ creating a failure. Opening a conversation acknowledges its unread terminal
outcome: the terminal mark clears immediately and the matching durable task
notification is marked read so the mark cannot return after a notification
refresh or app restart. Outcomes already marked read never produce a terminal
-mark. Reduced-motion mode disables the breathing animation while retaining its
-orange fill and localized accessible name.
+mark. Marking the row read, marking all rows read, or clearing the inbox also
+dismisses any matching task-native banner; a late event for that durable id
+cannot restore the mark, row, or banner. Reduced-motion mode disables the
+breathing animation while retaining its orange fill and localized accessible
+name.
### 4.6 Tailwind CSS variable stub
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index ce9e691b0..8f2cabff8 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -3798,10 +3798,15 @@ Sidebar footer Popover (360px max)
- `All` shows the newest retained rows; `Unread` filters to `readAt == null`.
- Selecting a row first calls `notification.markRead`, closes the popover, then
activates the row's durable session (including its project when applicable)
- and scrolls the transcript to its latest content.
-- Mark all read is idempotent and preserves rows. Clear deletes every inbox
- row but never deletes a session, transcript, or turn.
-- `notification.changed` updates the visible list and badge. Opening the
+ and scrolls the transcript to its latest content. The successful read also
+ dismisses the matching task-native banner before a late activation can
+ surface it again.
+- Mark all read is idempotent and preserves rows; it dismisses every outstanding
+ task-native banner. Clear deletes every inbox row, dismisses all task-native
+ banners, and leaves sessions, transcripts, and turns intact.
+- `notification.changed` updates the visible list and badge only for a new
+ durable id. A duplicate id, or a delayed event for an acknowledged/cleared
+ row, is ignored. Opening the
popover also refreshes the bounded list from host-core. A
`notification.activated` event from Electron follows the same session
activation path as a row click.
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index 82e58db35..9b21d069b 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -443,15 +443,20 @@ may be retained while exactly one workspace supplies the visible shell context.
`session.endTurn` closes the turn without inserting a notification. Any
background session or unfocused/hidden window creates the durable record.
An `aborted` turn never creates one.
-3. Electron emits `notification.changed` to every live renderer so the bell
- badge and currently open inbox refresh.
+3. Electron emits `notification.changed` to every live renderer for the newly
+ inserted durable row so the bell badge and currently open inbox refresh.
+ Renderer delivery is keyed by the durable `id`: duplicate ids and delayed
+ events for rows already acknowledged or cleared are ignored.
4. For a task result, a focused main window produces no native banner. If
it is unfocused and native notifications are supported, Electron shows one
platform notification derived from the event kind and session title. The
separate interactive ask/permission/plan path may alert for a focused
background session while suppressing the exact visible session. On
Windows, the banner is attributed to the canonical PI-Desktop
- AppUserModelID shared with the NSIS package and taskbar identity.
+ AppUserModelID shared with the NSIS package and taskbar identity. Electron
+ retains at most one task-native object per durable id; successful read,
+ mark-all-read, and clear actions close the matching objects and retain a
+ tombstone against late/replayed delivery.
5. Clicking the native notification shows/restores and focuses the main
window, then emits `notification.activated { sessionId }`.
6. Renderer activation selects the bound project when present, loads the
@@ -470,9 +475,12 @@ may be retained while exactly one workspace supplies the visible shell context.
current renderer lifetime and never marks rows read implicitly.
- Arrow keys move through rows with wrap disabled; `Home` / `End` jump to the
first/last row; Enter/Space marks the row read and activates its session.
-- Mark all read updates every unread row in one host transaction. Clear
- removes all inbox rows in one host transaction. Both operations are
- idempotent, refresh the exact unread count, and leave sessions/turns intact.
+- Mark all read updates every unread row in one host transaction and dismisses
+ outstanding task-native objects. Clear removes all inbox rows in one host
+ transaction, dismisses outstanding task-native objects, and leaves
+ sessions/turns intact. Both operations are idempotent and refresh the exact
+ unread count; a failed host mutation does not optimistically dismiss a
+ banner.
- The renderer does not synthesize notification records from stream events.
Host-core's unique `turn_id` is the exactly-once boundary across repeated
terminal updates, renderer reloads, and process restarts.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index b5624a6d1..4f251c0d6 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -4111,7 +4111,10 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
row read and confirm its session has no terminal sidebar mark, then
close/reopen the popover and restart the app. 8) Select the other session
from its terminal-marked sidebar row. 9) Generate a host fixture with 205
- eligible terminal turns. 10) Use Mark all read, then Clear.
+ eligible terminal turns. 10) Use Mark all read, then Clear. 11) While a
+ native task banner and a renderer refresh are still in flight, deliver a
+ delayed `notification.changed` payload for a cleared/read durable id and a
+ duplicate payload for an id that is already present.
- **Expected**: A's visible-current completion creates no row or terminal sidebar mark. Exactly two rows
exist, newest first: the unfocused A completion and background B failure,
with localized labels, snapshotted session titles, and B's stable code.
@@ -4124,7 +4127,11 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
preserves rows with zero unread. Selecting the other session clears its
terminal sidebar mark and marks its task notification read; neither mark
returns after refresh or restart. Clear empties only the inbox and leaves
- sessions, turns, and transcripts intact.
+ sessions, turns, and transcripts intact. Clear/read also dismisses any
+ outstanding task-native object, a repeated durable id produces no second
+ banner or row, and a delayed pre-clear event cannot resurrect the cleared
+ item; a genuinely new post-clear turn still produces exactly one row and
+ banner.
- **Specs linked**: `03-runtime/04-data-storage.md`,
`03-runtime/06-host-rpc-protocol.md`, `03-runtime/01-ipc-protocol.md`,
`04-ux/07-ui-design-system.md`, `04-ux/08-component-spec.md`,
@@ -4146,7 +4153,8 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
Unfocus the app and abort a turn. 7) Repeat with native delivery suppressed
by the OS. 8) On Windows, inspect the native notification attribution,
notification-settings entry, taskbar group, installed executable, and Start
- menu shortcut.
+ menu shortcut. 9) Deliver the same durable id twice, then mark it read and
+ clear the inbox while its native object is still pending in the OS.
- **Expected**: Focused-current A creates neither inbox row, terminal sidebar mark, nor native banner.
Focused-background B creates an inbox row without a native banner. Unfocused
current A and the minimized failure each create one durable row and one
@@ -4156,7 +4164,9 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
currently selected session. Abort shows neither surface. OS suppression does
not lose the durable row or surface a misleading app error. Every inspected
Windows system surface identifies `PI-Desktop`; no stock Electron application
- name or identity is exposed.
+ name or identity is exposed. Duplicate delivery is idempotent: one durable
+ id owns at most one live native object, and mark-read/clear closes that
+ object so a late activation or renderer event cannot show the old task again.
- **Specs linked**: `03-runtime/01-ipc-protocol.md`,
`04-ux/07-ui-design-system.md`, `04-ux/09-interaction-patterns.md`,
`08-meta/decisions-log.md` (D117/D141)
@@ -9182,6 +9192,9 @@ This test plan spec is accepted when:
- Mark all read and Clear expose icon tooltips/accessible names, disabled and
empty states remain understandable, and reduced-motion mode changes the
popover instantly without suppressing focus or unread state.
+- While a task banner is pending, mark its row read and then clear the inbox;
+ inject a delayed duplicate event afterwards. The old row, sidebar mark, and
+ native banner stay dismissed, while a new post-clear task appears once.
### US-UI-66 Application update notice layout
- In a conversation with the docked composer visible, exercise manual
diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
index f9d551336..04148043a 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -655,10 +655,13 @@ type AgentEvent =
避免快速完成先于查看上下文更新。Electron 将此提示与 Main 拥有的窗口
visibility/focus 结合起来,在终态事件边界进行判断。缺失、null 或不匹配的
上下文都会安全地创建公告。它还调用
-`pi-desktop/notification/showNative({ id, sessionId, title, body, source? })` 之后
+`pi-desktop/notification/showNative({ id, sessionId, title, body, source?, createdAt? })` 之后
本地化新记录。可选的 `source` 对终端任务结果使用 `"task"`,对 asktool、
工具权限和 Plan 审批询问使用 `"interactive"`;省略或未知值默认为
-`"task"`。这个仅限 Electron 的请求永远不会进入主机 RPC 域。
+`"task"`。任务通知带有持久记录的 `createdAt` 时,Main 会在成功的“全部已读”
+或清空操作后使用 `dismissedBefore` 水位拒绝迟到的旧事件,单条已读则使用
+持久 ID tombstone;这样渲染器或主机重放不会再次弹出已处理的通知。这个仅限
+Electron 的请求永远不会进入主机 RPC 域。
```ts
type AppNotification = {
@@ -700,6 +703,9 @@ Main 发送两个事件:
并重新计算确切的未读计数。最终结果已经可见
聚焦的当前聊天、重复的终端更新和中止的回合会发出
什么也没有。
+- 持久 `id` 是 Renderer 和 Electron 本机投递的幂等键。对于本地列表中
+ 已存在 id 的重复 `notification.changed` 负载必须无操作;已确认或已清除
+ 行的延迟负载会被忽略,不得重新创建行或侧边栏结果。
- 用户点击 Electron 后的 `pi-desktop/notification/event/activated`
本机系统通知。 Renderer 遵循其现有的会话选择
路径,包括项目绑定会话的项目激活。
@@ -733,6 +739,13 @@ Electron 主将 `net.aiuo.pi-desktop` 注册为进程 AppUserModelID
分组,安装的快捷方式解析为 `PI-Desktop`,而不是库存
Electron 主机。
+任务本机对象按持久 notification id 保留,每个 id 最多一个活动对象。
+重放的 `showNative` 请求不得创建第二个对象。`notification.markRead`、
+`notification.markAllRead` 或 `notification.clear` 的主机变更成功后,关闭
+匹配的任务对象(并保留 id tombstone 一段时间以拒绝迟到投递);主机变更
+失败时不得乐观地关闭对象。交互询问使用独立的临时注册表,不受任务收件箱
+变更影响。
+
查看会话提示是建议性的和自动防故障的:丢失、陈旧、隐藏或
未聚焦的渲染器状态会创建持久通知。发生抑制
仅当主窗口可见且聚焦且报告的聊天会话时
diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
index 10a3a3767..06c36d94b 100644
--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
@@ -519,6 +519,9 @@ type NotificationListResult = {
- `notification.markAllRead({}) -> { ok: true }` 更新中的每个未读行
一笔交易。
- `notification.clear({}) -> { ok: true }` 仅删除收件箱行。
+- `id` 是 Renderer 和本机投递的稳定一次性键。客户端必须丢弃已经确认/清除
+ 的 id 的重复或延迟记录;清空收件箱不会让旧终端回合再次具备插入资格。
+ 后续真正的终端回合会获得新的 id。
- 不发出 `notification.created` JSON-RPC 服务器通知。 Electron
直接从 `session.endTurn` 接收插入的记录,避免了
终端转持久化和UI刷新之间的第二个点餐通道。
@@ -1030,4 +1033,3 @@ schedule,Manual 转 Hourly 继续使用现有默认间隔行为。
保存和读取工作区绑定时统一使用现有项目路径规范化规则。在 Windows 上,
斜杠方向、大小写、末尾分隔符和扩展路径前缀的差异不会再让同项目会话看不到任务。
缺失的旧版绑定与显式 null 仍保持不同语义;其他项目的工具不能查询或修改绑定任务。
-
diff --git a/docs/zh-CN/spec/04-ux/07-ui-design-system.md b/docs/zh-CN/spec/04-ux/07-ui-design-system.md
index 70d4d847c..90e638c26 100644
--- a/docs/zh-CN/spec/04-ux/07-ui-design-system.md
+++ b/docs/zh-CN/spec/04-ux/07-ui-design-system.md
@@ -235,8 +235,9 @@ PI-Desktop 的行为类似于桌面应用程序 shell,因此意外拖动
结果:终端标记立即清除并且匹配持久任务
通知被标记为已读,因此该标记在通知后无法返回
刷新或重新启动应用程序。已标记为已读的结果永远不会产生终端
-标记。缩减运动模式会禁用呼吸动画,同时保留其
-橙色填充和本地化的可访问名称。
+标记。将行标记为已读、将全部行标记为已读或清除收件箱也会关闭匹配的
+任务本机横幅;该 durable id 的迟到事件不能恢复标记、行或横幅。缩减运动
+模式会禁用呼吸动画,同时保留其橙色填充和本地化的可访问名称。
### 4. 6 Tailwind CSS 变量存根
diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.md
index 96ea92a2d..5a5f703b9 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -2701,10 +2701,13 @@ Sidebar footer Popover (360px max)
- `All` 显示最新保留的行; `Unread` 过滤至 `readAt == null`。
- 选择一行首先调用 `notification.markRead`,关闭弹出窗口,然后
激活该行的持久会话(包括其项目(如果适用))
- 并将记录滚动到最新内容。
-- 将所有读取标记为幂等并保留行。清除会删除每个收件箱
- 行,但绝不会删除会话、转录本或回合。
-- `notification.changed` 更新可见列表和徽章。打开
+ 并将记录滚动到最新内容。读取成功后也会关闭匹配的任务本机横幅,
+ 以防迟到激活再次显示它。
+- 将所有读取标记为幂等并保留行,同时关闭所有待处理的任务本机横幅。
+ 清除会删除每个收件箱行、关闭全部任务本机横幅,但绝不会删除会话、
+ 转录本或回合。
+- `notification.changed` 只为新的 durable id 更新可见列表和徽章。重复 id,
+ 或针对已确认/已清除行的延迟事件,都会被忽略。打开
弹出窗口还刷新 host-core 中的有界列表。一个
来自 Electron 的 `notification.activated` 事件遵循同一会话
激活路径为一行单击。
diff --git a/docs/zh-CN/spec/04-ux/09-interaction-patterns.md b/docs/zh-CN/spec/04-ux/09-interaction-patterns.md
index b1e1d1537..bd281ce68 100644
--- a/docs/zh-CN/spec/04-ux/09-interaction-patterns.md
+++ b/docs/zh-CN/spec/04-ux/09-interaction-patterns.md
@@ -350,13 +350,17 @@
`session.endTurn` 关闭回合而不插入通知。任意
后台会话或 unfocused/hidden 窗口创建持久记录。
`aborted` 回合永远不会创建一个。
-3. Electron 向每个实时渲染器发出 `notification.changed`,以便响铃
- 徽章和当前打开的收件箱刷新。
+3. Electron 为新插入的持久行向每个实时渲染器发出
+ `notification.changed`,以便响铃徽章和当前打开的收件箱刷新。
+ Renderer 按持久 `id` 幂等处理:重复 id,以及针对已确认或已清除行的
+ 延迟事件,都会被忽略。
4. 对于终端任务结果,本机通知仅在主窗口未聚焦时出现。聚焦背景会话的完成
仍会创建持久行,但不会出现本机横幅。asktool、工具权限和 Plan 审批询问
使用带有 `kind: "interactive"` 的同一个 Electron 表面:确切的聚焦当前
会话保持静默,而聚焦于其他会话时可以收到横幅。在 Windows 上,每个横幅
都归因于与 NSIS 包和任务栏标识共享的规范 PI-Desktop AppUserModelID。
+ Electron 每个持久 id 最多保留一个任务本机对象;成功的已读、全部已读和
+ 清除操作会关闭匹配对象,并保留 tombstone 以抵御迟到/重放投递。
5. 单击本机通知 shows/restores 并聚焦于主通知
窗口,然后发出 `notification.activated { sessionId }`。
6. Renderer 激活选择绑定项目(如果存在),加载
@@ -377,9 +381,10 @@
当前渲染器生命周期并且从不标记隐式读取的行。
- 箭头键在禁用换行的情况下在行中移动; `Home` / `End` 跳转到
first/last 行; Enter/Space 标记该行已读取并激活其会话。
-- 标记一个主机事务中每个未读行的所有读取更新。清除
- 删除一个主机事务中的所有收件箱行。两个操作都是
- 幂等,刷新确切的未读计数,并保持 sessions/turns 不变。
+- 标记一个主机事务中每个未读行的所有读取更新,并关闭待处理的任务本机对象。
+ 清除删除一个主机事务中的所有收件箱行,关闭待处理的任务本机对象,并保持
+ sessions/turns 不变。两个操作都是幂等并刷新确切的未读计数;主机变更失败时
+ 不会乐观地关闭横幅。
- 渲染器不会从流事件中合成通知记录。
Host-core 独特的 `turn_id` 是重复的一次边界
终端更新、渲染器重新加载和进程重新启动。
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index cb6d5b061..4e6e8c0ae 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -2549,7 +2549,7 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
row 读取并确认其会话没有终端侧边栏标记,然后
close/reopen 弹出窗口并重新启动应用程序。 8) 选择其他会话
从其带有终端标记的侧边栏行。 9) 用205生成一个主机装置
- 符合资格的终端回合。 10) 使用“标记全部已读”,然后“清除”。
+ 符合资格的终端回合。 10) 使用“标记全部已读”,然后“清除”。 11) 当本机任务横幅和渲染器刷新仍在进行时,投递一个针对已清除/已读 durable id 的延迟 `notification.changed` 负载,以及一个已存在 id 的重复负载。
- **预期**:A 的可见当前完成不会创建任何行。正好两行
存在,最新的优先:未聚焦的 A 完成和背景 B 失败,
带有本地化标签、快照会话标题和 B 的稳定代码。
@@ -2562,7 +2562,7 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
保留零个未读行。选择其他会话会清除其
终端侧边栏标记并标记其任务通知已读;都没有标记
刷新或重启后返回。清除仅清空收件箱并离开
- 会议、回合和成绩单完好无损。
+ 会议、回合和成绩单完好无损。清除/已读也会关闭所有待处理的任务本机通知;重复 durable id 不会产生第二个横幅或行,清除前的延迟事件不能复活已清除项目;清除后真正的新回合仍只产生一行和一个横幅。
- **链接规格**:`03-runtime/04-data-storage.md`,
`03-runtime/06-host-rpc-protocol.md`、`03-runtime/01-ipc-protocol.md`、
`04-ux/07-ui-design-system.md`、`04-ux/08-component-spec.md`、
@@ -2584,7 +2584,7 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
取消应用程序的焦点并中止回合。 7) 重复并抑制本机传递
由操作系统。 8) 在 Windows 上,检查本机通知属性,
通知设置条目、任务栏组、已安装的可执行文件和开始
- 菜单快捷方式。
+ 菜单快捷方式。 9) 将同一 durable id 投递两次,然后在本机对象仍由操作系统持有时标记已读并清除收件箱。
- **预期**:当前焦点 A 既不创建收件箱行,也不创建本机横幅。
聚焦背景 B 创建一个没有本机横幅的收件箱行。不专心
当前 A 和最小化故障分别创建一个持久行和一个
@@ -2593,7 +2593,7 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
没有事件打开错误当前选定的会话。中止不显示两个表面。操作系统抑制确实
不会丢失持久行或出现误导性应用程序错误。每检查一次
Windows系统表面识别`PI-Desktop`;无库存 Electron 应用程序
- 姓名或身份被暴露。
+ 姓名或身份被暴露。重复投递必须幂等:一个 durable id 最多拥有一个活动的本机对象,标记已读/清除会关闭该对象,迟到的激活或渲染器事件不能再次显示旧任务。
- **链接规格**:`03-runtime/01-ipc-protocol.md`,
`04-ux/07-ui-design-system.md`、`04-ux/09-interaction-patterns.md`、
`08-meta/decisions-log.md` (D117/D141)
@@ -6077,6 +6077,7 @@ eleven-tool-round desktop paths are verified by
- 标记所有已读并清除公开图标 tooltips/accessible 名称、禁用和
空状态仍然是可以理解的,并且减少运动模式改变了
立即弹出,无需抑制焦点或未读状态。
+- 本机任务横幅待处理时,先将其行标记为已读,再清除收件箱,然后注入延迟重复事件。旧行、侧边栏标记和本机横幅都保持关闭,清除后的新任务只出现一次。
### US-UI-66 应用程序更新通知布局
- 在与停靠的输入框的对话中可见,练习手册