Skip to content

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

feat(desktop): show unread task result badge on Windows taskbar

大胖0f0755452039
diff --git a/.github/pr-assets/taskbar-unread-overlay/windows11-taskbar-badge.png b/.github/pr-assets/taskbar-unread-overlay/windows11-taskbar-badge.png
new file mode 100644
index 000000000..b648c33c7
Binary files /dev/null and b/.github/pr-assets/taskbar-unread-overlay/windows11-taskbar-badge.png differ
diff --git a/apps/desktop/electron/main/bootstrap/app-lifecycle.ts b/apps/desktop/electron/main/bootstrap/app-lifecycle.ts
index 0e5f02787..63648ce02 100644
--- a/apps/desktop/electron/main/bootstrap/app-lifecycle.ts
+++ b/apps/desktop/electron/main/bootstrap/app-lifecycle.ts
@@ -19,6 +19,7 @@ import {
import { catalogs, resolveLocale } from "@pi-desktop/i18n";
import { installApplicationMenu } from "../application-menu";
import { createTraySessions } from "../tray-sessions";
+import { createTaskbarUnreadBadge } from "../taskbar-unread-badge";
import { createWindow, type WindowLifecycleState } from "./window";
import { windowToggleAction } from "./window-visibility";
import type { BrowserPane } from "../browser-view";
@@ -116,6 +117,12 @@ export function createApplicationLifecycle({
onChanged: () => updateTrayMenu(),
logger,
});
+ const taskbarUnreadBadge = createTaskbarUnreadBadge({
+ getHost,
+ getMainWindow: () => state.mainWindow,
+ isQuitting: () => state.quitting,
+ logger,
+ });
let trayActivationGeneration = 0;
function applyDevelopmentBranding() {
@@ -276,6 +283,9 @@ export function createApplicationLifecycle({
state.tray.on("double-click", restoreMainWindow);
updateTrayMenu();
void traySessions.refresh();
+ void taskbarUnreadBadge.refresh();
+ // Window is live here; force-paint any count learned before the BrowserWindow existed.
+ taskbarUnreadBadge.replay();
}
@@ -661,6 +671,7 @@ export function createApplicationLifecycle({
return {
traySessions,
+ taskbarUnreadBadge,
applyDevelopmentBranding,
hasVisibleWindow,
restoreMainWindow,
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.ts
index 6c9b98b55..f6e02fb1f 100644
--- a/apps/desktop/electron/main/index.ts
+++ b/apps/desktop/electron/main/index.ts
@@ -798,6 +798,7 @@ function describeError(error: unknown): string {
/** Pull the user's MCP server records from host-core into the local runtime. */
function sendToRenderer(channel: string, payload: unknown) {
applicationLifecycle?.traySessions.observeEvent(channel, payload);
+ applicationLifecycle?.taskbarUnreadBadge.observeEvent(channel, payload);
if (channel === IPC.event.pluginChanged) {
applicationLifecycle?.applyNativeThemeSource({
theme: applicationAppearanceState.appThemePreference,
@@ -1239,6 +1240,7 @@ const voiceService = createVoiceService(dataDir + "/voice-models", () => mainWin
function registerIpc() {
return registerIpcHandlers({
traySessions: applicationLifecycle!.traySessions,
+ taskbarUnreadBadge: applicationLifecycle!.taskbarUnreadBadge,
ipcMain,
getMainWindow: () => mainWindow,
getHost: () => host,
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index 3a9879c81..cf16e39b1 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -34,6 +34,7 @@ import { registerSpeechIpc } from "./speech-ipc";
import { registerVoiceIpc } from "./voice-ipc";
import type { IpcRegistrar } from "./types";
import type { createTraySessions } from "../tray-sessions";
+import type { createTaskbarUnreadBadge } from "../taskbar-unread-badge";
export type RegisterIpcDependencies = {
isQuitting: () => boolean;
@@ -41,6 +42,7 @@ export type RegisterIpcDependencies = {
getMainWindow: () => BrowserWindow | null;
getHost: () => HostProcess | null;
traySessions: ReturnType<typeof createTraySessions>;
+ taskbarUnreadBadge: ReturnType<typeof createTaskbarUnreadBadge>;
getSidecar: () => AgentSidecar | null;
getAgentHostBridge: () => AgentHostBridge | null;
/**
@@ -125,6 +127,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
getCloseBehavior,
markMenuRendererReady,
traySessions,
+ taskbarUnreadBadge,
executeNativeMenuAction,
scheduledRunsBySession,
isDevelopmentBuild,
@@ -165,6 +168,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
const handler = async (...args: any[]) => {
const result = await fn(...args);
traySessions.observeInvoke(channel);
+ taskbarUnreadBadge.observeInvoke(channel);
return result;
};
ipcHandlers.set(channel, handler);
diff --git a/apps/desktop/electron/main/taskbar-unread-badge.ts b/apps/desktop/electron/main/taskbar-unread-badge.ts
new file mode 100644
index 000000000..acfc79686
--- /dev/null
+++ b/apps/desktop/electron/main/taskbar-unread-badge.ts
@@ -0,0 +1,215 @@
+import { app, nativeImage, type BrowserWindow } from "electron";
+import {
+ IPC,
+ type NotificationListResult,
+} from "@pi-desktop/shared";
+import type { HostProcess } from "./host-process";
+import type { Logger } from "./logger";
+import {
+ TASKBAR_UNREAD_OVERLAY_SCALE_FACTOR,
+ buildTaskbarUnreadOverlayPng,
+ formatTaskbarUnreadOverlayLabel,
+ renderTaskbarUnreadOverlayPng,
+} from "./taskbar-unread-overlay";
+
+const REFRESH_AFTER_INVOKE = new Set<string>([
+ IPC.invoke.notificationMarkRead,
+ IPC.invoke.notificationMarkAllRead,
+ IPC.invoke.notificationClear,
+]);
+
+/**
+ * Main-owned shell badge for unread durable task notifications.
+ * Uses host unreadCount (completed + failed). Does not change D295 bell filtering.
+ *
+ * `desiredCount` is what we last learned from the host; `appliedCount` is what we
+ * successfully painted onto the OS shell. Windows overlay needs a live BrowserWindow,
+ * so a host update that arrives before the window exists must not mark the count as
+ * applied — otherwise a later refresh with the same count early-returns and the
+ * overlay never appears.
+ *
+ * On win32, painting prefers a smooth renderer Canvas PNG. The deterministic
+ * main-process bitmap remains a fallback before the renderer is ready. Both
+ * paths are 64×64 + scaleFactor 3 → ~21×21 logical, with no intermediate resize.
+ */
+export function createTaskbarUnreadBadge({
+ getHost,
+ getMainWindow,
+ isQuitting,
+ logger,
+}: {
+ getHost: () => HostProcess | null;
+ getMainWindow: () => BrowserWindow | null;
+ isQuitting: () => boolean;
+ logger: Pick<Logger, "app">;
+}) {
+ let revision = 0;
+ let pending: Promise<void> | null = null;
+ let desiredCount: number | null = null;
+ let appliedCount: number | null = null;
+ /** Bumped on every win32 paint attempt; stale async paints must no-op. */
+ let paintRevision = 0;
+
+ function apply(count: number, options?: { force?: boolean }): Promise<void> {
+ const next = Math.max(0, Math.floor(count));
+ desiredCount = next;
+ if (!options?.force && appliedCount === next) return Promise.resolve();
+
+ if (process.platform === "win32") {
+ return paintWin32(next);
+ }
+
+ try {
+ app.setBadgeCount(next);
+ appliedCount = next;
+ } catch (error) {
+ logger.app("diagnostics", "warn", "shell badge count update failed", {
+ data: String(error),
+ });
+ }
+ return Promise.resolve();
+ }
+
+ async function paintWin32(next: number): Promise<void> {
+ const window = getMainWindow();
+ if (!window || window.isDestroyed()) {
+ // Remember desiredCount but do not advance appliedCount.
+ return;
+ }
+
+ const myRevision = ++paintRevision;
+ try {
+ if (next <= 0) {
+ if (myRevision !== paintRevision) return;
+ if (window.isDestroyed()) return;
+ window.setOverlayIcon(null, "");
+ appliedCount = next;
+ return;
+ }
+
+ const label = formatTaskbarUnreadOverlayLabel(next);
+ if (!label) {
+ if (myRevision !== paintRevision) return;
+ if (window.isDestroyed()) return;
+ window.setOverlayIcon(null, "");
+ appliedCount = 0;
+ return;
+ }
+
+ let png: Buffer | null = null;
+ const contents = window.webContents;
+ if (contents && !contents.isDestroyed()) {
+ try {
+ png = await renderTaskbarUnreadOverlayPng(contents, next);
+ } catch (error) {
+ logger.app(
+ "diagnostics",
+ "warn",
+ "taskbar overlay canvas render failed; using bitmap fallback",
+ { data: String(error) },
+ );
+ }
+ }
+ if (!png) png = buildTaskbarUnreadOverlayPng(next);
+
+ if (myRevision !== paintRevision) return;
+ if (window.isDestroyed()) return;
+
+ if (!png) {
+ window.setOverlayIcon(null, "");
+ appliedCount = 0;
+ return;
+ }
+
+ // 64×64 raster + scaleFactor 3 → ~21×21 logical DIP for a readable badge.
+ let image = nativeImage.createFromBuffer(png, {
+ scaleFactor: TASKBAR_UNREAD_OVERLAY_SCALE_FACTOR,
+ });
+ if (image.isEmpty() && typeof nativeImage.createFromDataURL === "function") {
+ image = nativeImage.createFromDataURL(
+ `data:image/png;base64,${png.toString("base64")}`,
+ );
+ }
+ if (image.isEmpty()) {
+ window.setOverlayIcon(null, "");
+ appliedCount = 0;
+ return;
+ }
+ // The 64px source is already sized for the Windows overlay slot.
+ window.setOverlayIcon(image, label);
+ appliedCount = next;
+ } catch (error) {
+ if (myRevision !== paintRevision) return;
+ logger.app("diagnostics", "warn", "taskbar overlay icon update failed", {
+ data: String(error),
+ });
+ }
+ }
+
+ function refresh(): Promise<void> {
+ revision += 1;
+ if (pending) return pending;
+ pending = (async () => {
+ let observed: number;
+ do {
+ observed = revision;
+ const host = getHost();
+ if (!host || isQuitting()) {
+ await apply(0);
+ return;
+ }
+ try {
+ const inbox = await host.call<NotificationListResult>(
+ "notification.list",
+ { limit: 1 },
+ );
+ if (isQuitting()) return;
+ if (host !== getHost()) {
+ revision += 1;
+ continue;
+ }
+ if (observed !== revision) continue;
+ await apply(inbox.unreadCount ?? 0);
+ } catch (error) {
+ if (host !== getHost()) {
+ revision += 1;
+ continue;
+ }
+ if (observed !== revision || isQuitting()) continue;
+ logger.app("diagnostics", "warn", "taskbar unread badge refresh failed", {
+ data: String(error),
+ });
+ }
+ } while (observed !== revision);
+ })().finally(() => {
+ pending = null;
+ });
+ return pending;
+ }
+
+ /** Re-paint the last desired count (e.g. main window / tray just became ready). */
+ function replay(): void {
+ if (desiredCount === null) {
+ void refresh();
+ return;
+ }
+ void apply(desiredCount, { force: true });
+ }
+
+ return {
+ refresh,
+ replay,
+ observeEvent(channel: string, _payload?: unknown) {
+ if (isQuitting()) return;
+ if (
+ channel === IPC.event.notificationChanged ||
+ channel === IPC.event.hostStatus
+ ) {
+ void refresh();
+ }
+ },
+ observeInvoke(channel: string) {
+ if (REFRESH_AFTER_INVOKE.has(channel)) void refresh();
+ },
+ };
+}
diff --git a/apps/desktop/electron/main/taskbar-unread-overlay.ts b/apps/desktop/electron/main/taskbar-unread-overlay.ts
new file mode 100644
index 000000000..207a311b0
--- /dev/null
+++ b/apps/desktop/electron/main/taskbar-unread-overlay.ts
@@ -0,0 +1,419 @@
+import { deflateSync } from "node:zlib";
+import type { WebContents } from "electron";
+
+/**
+ * OS shell badge for durable task outcomes.
+ *
+ * Count = ALL unread `task.completed` + `task.failed` rows (host
+ * `notification.list` unreadCount). This is intentionally different from the
+ * D295 bell inbox in `notification-inbox.ts`, which still lists and badges
+ * failures only.
+ *
+ * Display policy: counts 1–99 show the real digit string; counts ≥100 show
+ * "99+" so a Windows overlay stays readable.
+ *
+ * Primary raster: a renderer Canvas at 64×64 using the Windows system UI font.
+ * Paired with `nativeImage.createFromBuffer(png, { scaleFactor: 3 })`, this
+ * occupies a ~21×21 logical Windows overlay image. The deterministic bitmap PNG
+ * remains the fallback before a renderer exists or if Canvas rendering fails.
+ *
+ * Shape: always a black circle. Multi-digit and "99+" labels fit inside it,
+ * never a pill or capsule. Black (#000) fill, white (#fff) glyphs.
+ */
+
+/** Physical PNG edge length (px). Logical DIP size = SIZE / SCALE_FACTOR. */
+export const TASKBAR_UNREAD_OVERLAY_SIZE = 64;
+
+/**
+ * Electron `nativeImage` scaleFactor so 64px raster → ~21×21 logical DIP.
+ * The larger logical image matches the visual weight of common Windows taskbar
+ * badges; do not rely on a second OS scale to enlarge a smaller bitmap.
+ */
+export const TASKBAR_UNREAD_OVERLAY_SCALE_FACTOR = 3;
+
+const OVERLAY_SIZE = TASKBAR_UNREAD_OVERLAY_SIZE;
+
+/**
+ * Circle inset from canvas edge (physical px). The Windows shell clamps an
+ * overlay to its own small slot, so use the full supplied raster rather than
+ * surrendering visible area to a transparent safety margin.
+ */
+const CIRCLE_INSET = 0;
+
+/** Single-digit bold bitmaps: 7×9. Digit "1" has widened top bar + base. */
+const SINGLE_GLYPH_W = 7;
+const SINGLE_GLYPH_H = 9;
+const SINGLE_GLYPHS: Record<string, number[]> = {
+ // bit 6 = leftmost pixel
+ "0": [
+ 0b0111110, 0b1100011, 0b1100011, 0b1100011, 0b1100011, 0b1100011, 0b1100011,
+ 0b1100011, 0b0111110,
+ ],
+ "1": [
+ 0b0111000, 0b1111100, 0b0011000, 0b0011000, 0b0011000, 0b0011000, 0b0011000,
+ 0b0011000, 0b1111111,
+ ],
+ "2": [
+ 0b0111110, 0b1100011, 0b0000011, 0b0000110, 0b0001100, 0b0011000, 0b0110000,
+ 0b1100000, 0b1111111,
+ ],
+ "3": [
+ 0b0111110, 0b1100011, 0b0000011, 0b0000011, 0b0011110, 0b0000011, 0b0000011,
+ 0b1100011, 0b0111110,
+ ],
+ "4": [
+ 0b0000110, 0b0001110, 0b0011010, 0b0110010, 0b1100010, 0b1111111, 0b0000010,
+ 0b0000010, 0b0000010,
+ ],
+ "5": [
+ 0b1111111, 0b1100000, 0b1100000, 0b1111110, 0b0000011, 0b0000011, 0b0000011,
+ 0b1100011, 0b0111110,
+ ],
+ "6": [
+ 0b0111110, 0b1100011, 0b1100000, 0b1100000, 0b1111110, 0b1100011, 0b1100011,
+ 0b1100011, 0b0111110,
+ ],
+ "7": [
+ 0b1111111, 0b0000011, 0b0000010, 0b0000110, 0b0001100, 0b0011000, 0b0011000,
+ 0b0110000, 0b0110000,
+ ],
+ "8": [
+ 0b0111110, 0b1100011, 0b1100011, 0b1100011, 0b0111110, 0b1100011, 0b1100011,
+ 0b1100011, 0b0111110,
+ ],
+ "9": [
+ 0b0111110, 0b1100011, 0b1100011, 0b1100011, 0b0111111, 0b0000011, 0b0000011,
+ 0b1100011, 0b0111110,
+ ],
+};
+
+/** Multi-digit / "99+" bitmaps: 5×7 (separate, smaller layout than singles). */
+const MULTI_GLYPH_W = 5;
+const MULTI_GLYPH_H = 7;
+const MULTI_GLYPHS: Record<string, number[]> = {
+ "0": [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
+ "1": [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
+ "2": [0b01110, 0b10001, 0b00001, 0b00110, 0b01000, 0b10000, 0b11111],
+ "3": [0b01110, 0b10001, 0b00001, 0b00110, 0b00001, 0b10001, 0b01110],
+ "4": [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],
+ "5": [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],
+ "6": [0b01110, 0b10000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],
+ "7": [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000],
+ "8": [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],
+ "9": [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00001, 0b01110],
+ "+": [0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000],
+};
+
+/**
+ * Format the overlay accessibility label / drawn text for an unread count.
+ * Returns null when the overlay should be cleared.
+ */
+export function formatTaskbarUnreadOverlayLabel(count: number): string | null {
+ const n = Math.floor(Number(count));
+ if (!Number.isFinite(n) || n <= 0) return null;
+ if (n >= 100) return "99+";
+ return String(n);
+}
+
+/**
+ * Build the renderer-side Canvas paint. Segoe UI gives the small numeral the
+ * same smooth, conventional appearance as Windows' common taskbar badges;
+ * custom bitmap glyphs are visibly jagged once the shell downsamples them.
+ */
+export function buildTaskbarUnreadOverlayCanvasScript(count: number): string | null {
+ const label = formatTaskbarUnreadOverlayLabel(count);
+ if (!label) return null;
+
+ const labelLiteral = JSON.stringify(label);
+ return `(() => {
+ const size = ${OVERLAY_SIZE};
+ const label = ${labelLiteral};
+ const canvas = document.createElement("canvas");
+ canvas.width = size;
+ canvas.height = size;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return null;
+ const center = size / 2;
+ const radius = ${circleRadius()};
+ ctx.clearRect(0, 0, size, size);
+ ctx.fillStyle = "#000";
+ ctx.beginPath();
+ ctx.arc(center, center, radius, 0, Math.PI * 2);
+ ctx.fill();
+ const singleDigit = label.length === 1;
+ let fontSize = singleDigit ? 50 : label.length === 2 ? 31 : 24;
+ const maxWidth = radius * 2 * 0.78;
+ ctx.fillStyle = "#fff";
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ do {
+ ctx.font = "600 " + fontSize + "px \\\"Segoe UI\\\", sans-serif";
+ if (ctx.measureText(label).width <= maxWidth) break;
+ fontSize -= 1;
+ } while (fontSize > 14);
+ ctx.save();
+ ctx.translate(center, center - (singleDigit ? 2 : 0));
+ if (singleDigit) ctx.scale(1.1, 1.03);
+ ctx.fillText(label, 0, 0);
+ ctx.restore();
+ return canvas.toDataURL("image/png");
+})()`;
+}
+
+/** Render the smooth badge PNG in the renderer process. */
+export async function renderTaskbarUnreadOverlayPng(
+ webContents: Pick<WebContents, "isDestroyed" | "executeJavaScript"> | null | undefined,
+ count: number,
+): Promise<Buffer | null> {
+ if (!webContents || webContents.isDestroyed()) return null;
+ const script = buildTaskbarUnreadOverlayCanvasScript(count);
+ if (!script) return null;
+ const result = await webContents.executeJavaScript(script, true);
+ if (typeof result !== "string") return null;
+ const prefix = "data:image/png;base64,";
+ if (!result.startsWith(prefix)) return null;
+ const png = Buffer.from(result.slice(prefix.length), "base64");
+ return png.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
+ ? png
+ : null;
+}
+
+/**
+ * Build a deterministic 64×64 PNG (SDF anti-aliased black circle, white
+ * custom bitmap glyphs) for `BrowserWindow.setOverlayIcon`. Returns null when
+ * count clears the overlay.
+ *
+ * Pair with `nativeImage.createFromBuffer(png, { scaleFactor: 3 })`.
+ */
+export function buildTaskbarUnreadOverlayPng(count: number): Buffer | null {
+ const label = formatTaskbarUnreadOverlayLabel(count);
+ if (!label) return null;
+ const rgba = new Uint8Array(OVERLAY_SIZE * OVERLAY_SIZE * 4);
+ paintBadgeShape(rgba);
+ paintLabel(rgba, label);
+ return encodeRgbaPng(OVERLAY_SIZE, OVERLAY_SIZE, rgba);
+}
+
+function clamp01(v: number): number {
+ if (v <= 0) return 0;
+ if (v >= 1) return 1;
+ return v;
+}
+
+/** Coverage alpha from signed distance (positive = inside). ~1px AA rim. */
+function coverageFromSdf(dist: number): number {
+ return clamp01(0.5 + dist);
+}
+
+function circleRadius(): number {
+ return OVERLAY_SIZE / 2 - CIRCLE_INSET;
+}
+
+function paintBadgeShape(rgba: Uint8Array): void {
+ const size = OVERLAY_SIZE;
+ const cx = (size - 1) / 2;
+ const cy = (size - 1) / 2;
+ const radius = circleRadius();
+
+ for (let y = 0; y < size; y += 1) {
+ for (let x = 0; x < size; x += 1) {
+ const px = x - cx;
+ const py = y - cy;
+ const dist = radius - Math.sqrt(px * px + py * py);
+ const alpha = coverageFromSdf(dist);
+ if (alpha <= 0) continue;
+ const i = (y * size + x) * 4;
+ rgba[i] = 0;
+ rgba[i + 1] = 0;
+ rgba[i + 2] = 0;
+ rgba[i + 3] = Math.round(alpha * 255);
+ }
+ }
+}
+
+type GlyphLayout = {
+ glyphs: Record<string, number[]>;
+ glyphW: number;
+ glyphH: number;
+ scale: number;
+ gap: number;
+};
+
+/**
+ * Single-digit layout: large bold glyphs (~44–48px tall ≈ 11–12 logical).
+ * Multi-digit / "99+" use a separate smaller layout and must not share these
+ * proportions.
+ */
+function layoutForLabel(label: string): GlyphLayout {
+ const diameter = circleRadius() * 2;
+ if (label.length <= 1) {
+ // Target glyph height ≈ 46px (≈11.5 logical) → ~77% of 60px diameter;
+ // white ink still reads as ~65–70% of the disc at taskbar scale.
+ const scale = 46 / SINGLE_GLYPH_H;
+ return {
+ glyphs: SINGLE_GLYPHS,
+ glyphW: SINGLE_GLYPH_W,
+ glyphH: SINGLE_GLYPH_H,
+ scale,
+ gap: 0,
+ };
+ }
+
+ const n = label.length;
+ const maxW = diameter * 0.82;
+ const preferred = n === 2 ? 4.2 : 2.8;
+ const gapPreferred = n === 2 ? 3 : 2;
+ for (let scale = preferred; scale >= 1.5; scale -= 0.1) {
+ const gap = scale >= 3 ? gapPreferred : Math.max(1, Math.floor(scale / 2));
+ const totalW = n * MULTI_GLYPH_W * scale + (n - 1) * gap;
+ if (totalW <= maxW) {
+ return {
+ glyphs: MULTI_GLYPHS,
+ glyphW: MULTI_GLYPH_W,
+ glyphH: MULTI_GLYPH_H,
+ scale,
+ gap,
+ };
+ }
+ }
+ return {
+ glyphs: MULTI_GLYPHS,
+ glyphW: MULTI_GLYPH_W,
+ glyphH: MULTI_GLYPH_H,
+ scale: 1.5,
+ gap: 1,
+ };
+}
+
+function paintLabel(rgba: Uint8Array, label: string): void {
+ const size = OVERLAY_SIZE;
+ const { glyphs, glyphW, glyphH, scale, gap } = layoutForLabel(label);
+ const totalW = label.length * glyphW * scale + (label.length - 1) * gap;
+ const totalH = glyphH * scale;
+ let originX = (size - totalW) / 2;
+ const originY = (size - totalH) / 2;
+
+ for (const ch of label) {
+ const rows = glyphs[ch];
+ if (!rows) continue;
+ for (let gy = 0; gy < glyphH; gy += 1) {
+ const row = rows[gy] ?? 0;
+ for (let gx = 0; gx < glyphW; gx += 1) {
+ if (((row >> (glyphW - 1 - gx)) & 1) !== 1) continue;
+ paintSoftBlock(
+ rgba,
+ originX + gx * scale,
+ originY + gy * scale,
+ scale,
+ );
+ }
+ }
+ originX += glyphW * scale + gap;
+ }
+}
+
+/**
+ * Draw a filled white block with ~1px coverage AA on the edges, blended over
+ * the existing black badge (preserving shape alpha).
+ */
+function paintSoftBlock(
+ rgba: Uint8Array,
+ ox: number,
+ oy: number,
+ cell: number,
+): void {
+ const size = OVERLAY_SIZE;
+ // Inset slightly so adjacent cells don't fuse into a blob; AA on the rim.
+ const pad = Math.min(0.35, cell * 0.06);
+ const x0 = ox + pad;
+ const y0 = oy + pad;
+ const x1 = ox + cell - pad;
+ const y1 = oy + cell - pad;
+
+ const minX = Math.max(0, Math.floor(x0 - 1));
+ const maxX = Math.min(size - 1, Math.ceil(x1 + 1));
+ const minY = Math.max(0, Math.floor(y0 - 1));
+ const maxY = Math.min(size - 1, Math.ceil(y1 + 1));
+
+ for (let y = minY; y <= maxY; y += 1) {
+ for (let x = minX; x <= maxX; x += 1) {
+ const px = x + 0.5;
+ const py = y + 0.5;
+ const dx = Math.max(x0 - px, 0, px - x1);
+ const dy = Math.max(y0 - py, 0, py - y1);
+ const outside = Math.sqrt(dx * dx + dy * dy);
+ const insideX = Math.min(px - x0, x1 - px);
+ const insideY = Math.min(py - y0, y1 - py);
+ const inside = Math.min(insideX, insideY);
+ const dist = outside > 0 ? -outside : inside;
+ const cov = coverageFromSdf(dist);
+ if (cov <= 0) continue;
+
+ const i = (y * size + x) * 4;
+ const shapeA = rgba[i + 3]! / 255;
+ if (shapeA <= 0) continue;
+ const t = cov;
+ rgba[i] = Math.round(255 * t);
+ rgba[i + 1] = Math.round(255 * t);
+ rgba[i + 2] = Math.round(255 * t);
+ rgba[i + 3] = Math.round(shapeA * 255);
+ }
+ }
+}
+
+function encodeRgbaPng(width: number, height: number, rgba: Uint8Array): Buffer {
+ const stride = width * 4;
+ const raw = Buffer.alloc((stride + 1) * height);
+ for (let y = 0; y < height; y += 1) {
+ const rowStart = y * (stride + 1);
+ raw[rowStart] = 0;
+ for (let x = 0; x < stride; x += 1) {
+ raw[rowStart + 1 + x] = rgba[y * stride + x]!;
+ }
+ }
+ const compressed = deflateSync(raw, { level: 9 });
+ const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(width, 0);
+ ihdr.writeUInt32BE(height, 4);
+ ihdr[8] = 8; // bit depth
+ ihdr[9] = 6; // RGBA
+ ihdr[10] = 0;
+ ihdr[11] = 0;
+ ihdr[12] = 0;
+ return Buffer.concat([
+ signature,
+ pngChunk("IHDR", ihdr),
+ pngChunk("IDAT", compressed),
+ pngChunk("IEND", Buffer.alloc(0)),
+ ]);
+}
+
+function pngChunk(type: string, data: Buffer): Buffer {
+ const typeBuf = Buffer.from(type, "ascii");
+ const len = Buffer.alloc(4);
+ len.writeUInt32BE(data.length, 0);
+ const crcBuf = Buffer.alloc(4);
+ crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
+ return Buffer.concat([len, typeBuf, data, crcBuf]);
+}
+
+const CRC_TABLE = (() => {
+ const table = new Uint32Array(256);
+ for (let n = 0; n < 256; n += 1) {
+ let c = n;
+ for (let k = 0; k < 8; k += 1) {
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ }
+ table[n] = c >>> 0;
+ }
+ return table;
+})();
+
+function crc32(buf: Buffer): number {
+ let c = 0xffffffff;
+ for (let i = 0; i < buf.length; i += 1) {
+ c = CRC_TABLE[(c ^ buf[i]!) & 0xff]! ^ (c >>> 8);
+ }
+ return (c ^ 0xffffffff) >>> 0;
+}
diff --git a/apps/desktop/src/components/NotificationCenter.tsx b/apps/desktop/src/components/NotificationCenter.tsx
index b5c4f10f4..501a3b5d5 100644
--- a/apps/desktop/src/components/NotificationCenter.tsx
+++ b/apps/desktop/src/components/NotificationCenter.tsx
@@ -77,6 +77,7 @@ export function NotificationCenter({
() => inboxUnreadCount(storedNotifications),
[storedNotifications],
);
+ const allUnreadCount = useAppStore((state) => state.unreadNotificationCount);
const refreshNotifications = useAppStore((state) => state.refreshNotifications);
const markAllNotificationsRead = useAppStore(
(state) => state.markAllNotificationsRead,
@@ -272,7 +273,7 @@ export function NotificationCenter({
className="notification-action"
tooltip={t("notifications.markAllRead")}
ariaLabel={t("notifications.markAllRead")}
- disabled={busy || unreadCount === 0}
+ disabled={busy || allUnreadCount === 0}
onClick={() => void runToolbarAction(markAllNotificationsRead)}
>
<IconCheckCheck size={15} aria-hidden />
@@ -282,7 +283,7 @@ export function NotificationCenter({
className="notification-action"
tooltip={t("notifications.clearAll")}
ariaLabel={t("notifications.clearAll")}
- disabled={busy || notifications.length === 0}
+ disabled={busy || storedNotifications.length === 0}
onClick={() => void runToolbarAction(clearNotifications)}
>
<IconTrash size={15} aria-hidden />
diff --git a/apps/desktop/src/lib/notification-inbox.ts b/apps/desktop/src/lib/notification-inbox.ts
index 2f152d143..54ca43f6b 100644
--- a/apps/desktop/src/lib/notification-inbox.ts
+++ b/apps/desktop/src/lib/notification-inbox.ts
@@ -1,10 +1,11 @@
import type { AppNotification } from "@pi-desktop/shared";
/**
- * The inbox popover surfaces only outcomes that need attention. Successful
+ * The inbox popover surfaces only outcomes that need attention (D295). Successful
* completions stay in the durable record so the sidebar outcome badge and the
* native system notification keep working, but listing every one of them
- * buried the failures under noise.
+ * buried the failures under noise. The OS shell/taskbar unread overlay is
+ * separate and counts all unread task notifications (completed + failed).
*/
export function inboxNotifications(
notifications: AppNotification[],
diff --git a/apps/desktop/test/notification-inbox.test.mjs b/apps/desktop/test/notification-inbox.test.mjs
index bee4ceeb7..aa75d966a 100644
--- a/apps/desktop/test/notification-inbox.test.mjs
+++ b/apps/desktop/test/notification-inbox.test.mjs
@@ -53,5 +53,11 @@ test("inbox unread count ignores unread completions", () => {
test("notification center renders the filtered inbox instead of the raw store", () => {
assert.match(componentSource, /inboxNotifications\(storedNotifications\)/);
assert.match(componentSource, /inboxUnreadCount\(storedNotifications\)/);
- assert.doesNotMatch(componentSource, /state\.unreadNotificationCount/);
+});
+
+test("notification center actions can clear taskbar-only completed outcomes", () => {
+ assert.match(componentSource, /const allUnreadCount = useAppStore\(/);
+ assert.match(componentSource, /state\.unreadNotificationCount/);
+ assert.match(componentSource, /disabled=\{busy \|\| allUnreadCount === 0\}/);
+ assert.match(componentSource, /disabled=\{busy \|\| storedNotifications\.length === 0\}/);
});
diff --git a/apps/desktop/test/taskbar-unread-badge.test.mjs b/apps/desktop/test/taskbar-unread-badge.test.mjs
new file mode 100644
index 000000000..ff8ed64c8
--- /dev/null
+++ b/apps/desktop/test/taskbar-unread-badge.test.mjs
@@ -0,0 +1,437 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import ts from "typescript";
+import {
+ inboxNotifications,
+ inboxUnreadCount,
+} from "../src/lib/notification-inbox.ts";
+
+const IPC = {
+ invoke: {
+ notificationMarkRead: "pi-desktop/notification/markRead",
+ notificationMarkAllRead: "pi-desktop/notification/markAllRead",
+ notificationClear: "pi-desktop/notification/clear",
+ },
+ event: {
+ notificationChanged: "pi-desktop/notification/event/changed",
+ hostStatus: "pi-desktop/app/event/hostStatus",
+ },
+};
+
+function loadBadgeModule({ renderPng } = {}) {
+ const file = new URL("../electron/main/taskbar-unread-badge.ts", import.meta.url);
+ const { outputText } = ts.transpileModule(readFileSync(file, "utf8"), {
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.CommonJS,
+ },
+ fileName: file.pathname,
+ });
+
+ const badgeCounts = [];
+ const resizeCalls = [];
+ const createFromBufferCalls = [];
+ function makeFakeNativeImage(buffer) {
+ return {
+ isEmpty: () => !buffer || buffer.length === 0,
+ buffer,
+ resize(options) {
+ resizeCalls.push(options);
+ return makeFakeNativeImage(buffer);
+ },
+ };
+ }
+ const electron = {
+ app: {
+ setBadgeCount(count) {
+ badgeCounts.push(count);
+ },
+ },
+ nativeImage: {
+ createFromBuffer(buffer, options) {
+ createFromBufferCalls.push({
+ bufferLength: buffer?.length ?? 0,
+ scaleFactor: options?.scaleFactor,
+ });
+ return makeFakeNativeImage(buffer);
+ },
+ createFromDataURL(url) {
+ const prefix = "data:image/png;base64,";
+ const b64 = typeof url === "string" && url.startsWith(prefix)
+ ? url.slice(prefix.length)
+ : "";
+ const buffer = Buffer.from(b64, "base64");
+ return makeFakeNativeImage(buffer);
+ },
+ },
+ };
+
+ const syncPngCalls = [];
+ const canvasPngCalls = [];
+ const overlay = {
+ TASKBAR_UNREAD_OVERLAY_SCALE_FACTOR: 3,
+ buildTaskbarUnreadOverlayPng(count) {
+ syncPngCalls.push(count);
+ if (count <= 0) return null;
+ return Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, count & 0xff]);
+ },
+ async renderTaskbarUnreadOverlayPng(_contents, count) {
+ canvasPngCalls.push(count);
+ if (renderPng) return renderPng(count);
+ if (count <= 0) return null;
+ return Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0xca, count & 0xff]);
+ },
+ formatTaskbarUnreadOverlayLabel(count) {
+ if (count <= 0) return null;
+ return count >= 100 ? "99+" : String(count);
+ },
+ };
+
+ const module = { exports: {} };
+ new Function("require", "exports", "module", outputText)(
+ (id) => {
+ if (id === "electron") return electron;
+ if (id === "@pi-desktop/shared") return { IPC };
+ if (id === "./taskbar-unread-overlay") return overlay;
+ throw new Error(`unexpected dependency: ${id}`);
+ },
+ module.exports,
+ module,
+ );
+
+ return {
+ createTaskbarUnreadBadge: module.exports.createTaskbarUnreadBadge,
+ badgeCounts,
+ syncPngCalls,
+ canvasPngCalls,
+ resizeCalls,
+ createFromBufferCalls,
+ };
+}
+
+function makeWindow(overlayIcons) {
+ return {
+ isDestroyed: () => false,
+ setOverlayIcon(image, description) {
+ overlayIcons.push({ image, description });
+ },
+ webContents: {
+ isDestroyed: () => false,
+ async executeJavaScript() {
+ return null;
+ },
+ },
+ };
+}
+
+function harness({ platform = "linux", unreadCount = 0, windowReady = true, renderPng } = {}) {
+ const previousPlatform = process.platform;
+ Object.defineProperty(process, "platform", {
+ configurable: true,
+ value: platform,
+ });
+
+ const loaded = loadBadgeModule({ renderPng });
+ const listCalls = [];
+ const overlayIcons = [];
+ let currentUnread = unreadCount;
+ let hostRef = {
+ call: async (method, input) => {
+ listCalls.push({ method, input });
+ assert.equal(method, "notification.list");
+ return { notifications: [], unreadCount: currentUnread };
+ },
+ };
+ let mainWindow = windowReady ? makeWindow(overlayIcons) : null;
+
+ const badge = loaded.createTaskbarUnreadBadge({
+ getHost: () => hostRef,
+ getMainWindow: () => mainWindow,
+ isQuitting: () => false,
+ logger: { app() {} },
+ });
+
+ return {
+ badge,
+ listCalls,
+ badgeCounts: loaded.badgeCounts,
+ syncPngCalls: loaded.syncPngCalls,
+ canvasPngCalls: loaded.canvasPngCalls,
+ resizeCalls: loaded.resizeCalls,
+ createFromBufferCalls: loaded.createFromBufferCalls,
+ overlayIcons,
+ setUnreadCount(next) {
+ currentUnread = next;
+ },
+ setMainWindow(next) {
+ mainWindow = next;
+ },
+ makeWindow() {
+ mainWindow = makeWindow(overlayIcons);
+ return mainWindow;
+ },
+ dispose() {
+ Object.defineProperty(process, "platform", {
+ configurable: true,
+ value: previousPlatform,
+ });
+ },
+ };
+}
+
+async function waitFor(predicate, { timeoutMs = 1000 } = {}) {
+ const start = Date.now();
+ while (!predicate()) {
+ if (Date.now() - start > timeoutMs) {
+ throw new Error("timed out waiting for condition");
+ }
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+}
+
+test("observeInvoke on markRead triggers notification.list refresh", async () => {
+ const h = harness({ platform: "linux", unreadCount: 3 });
+ try {
+ h.badge.observeInvoke(IPC.invoke.notificationMarkRead);
+ await waitFor(() => h.listCalls.length >= 1);
+ assert.equal(h.listCalls[0].method, "notification.list");
+ assert.deepEqual(h.listCalls[0].input, { limit: 1 });
+ await waitFor(() => h.badgeCounts.includes(3));
+ assert.equal(h.badgeCounts.at(-1), 3);
+ } finally {
+ h.dispose();
+ }
+});
+
+test("observeInvoke on markAllRead and clear also refresh", async () => {
+ for (const channel of [
+ IPC.invoke.notificationMarkAllRead,
+ IPC.invoke.notificationClear,
+ ]) {
+ const h = harness({ platform: "linux", unreadCount: 1 });
+ try {
+ h.badge.observeInvoke(channel);
+ await waitFor(() => h.listCalls.length >= 1);
+ assert.equal(h.listCalls[0].method, "notification.list");
+ await waitFor(() => h.badgeCounts.length >= 1);
+ assert.equal(h.badgeCounts.at(-1), 1);
+ } finally {
+ h.dispose();
+ }
+ }
+});
+
+test("observeInvoke ignores unrelated channels", async () => {
+ const h = harness({ platform: "linux", unreadCount: 9 });
+ try {
+ h.badge.observeInvoke("pi-desktop/session/list");
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ assert.equal(h.listCalls.length, 0);
+ assert.equal(h.badgeCounts.length, 0);
+ } finally {
+ h.dispose();
+ }
+});
+
+test("observeEvent(notificationChanged) refreshes from host unreadCount", async () => {
+ const h = harness({ platform: "linux", unreadCount: 5 });
+ try {
+ h.badge.observeEvent(IPC.event.notificationChanged, {});
+ await waitFor(() => h.listCalls.length >= 1);
+ await waitFor(() => h.badgeCounts.includes(5));
+ assert.equal(h.badgeCounts.at(-1), 5);
+ } finally {
+ h.dispose();
+ }
+});
+
+test("refresh applies host unreadCount to the shell badge", async () => {
+ const h = harness({ platform: "linux", unreadCount: 7 });
+ try {
+ await h.badge.refresh();
+ assert.equal(h.listCalls.length, 1);
+ assert.equal(h.badgeCounts.at(-1), 7);
+ } finally {
+ h.dispose();
+ }
+});
+
+test("refresh with unreadCount 0 clears the shell badge", async () => {
+ const h = harness({ platform: "linux", unreadCount: 4 });
+ try {
+ await h.badge.refresh();
+ assert.equal(h.badgeCounts.at(-1), 4);
+ h.setUnreadCount(0);
+ await h.badge.refresh();
+ assert.equal(h.badgeCounts.at(-1), 0);
+ } finally {
+ h.dispose();
+ }
+});
+
+test("refresh with unreadCount 0 clears the Windows overlay icon", async () => {
+ const h = harness({ platform: "win32", unreadCount: 2 });
+ try {
+ await h.badge.refresh();
+ assert.ok(h.overlayIcons.length >= 1);
+ assert.notEqual(h.overlayIcons.at(-1).image, null);
+ assert.equal(h.overlayIcons.at(-1).description, "2");
+ assert.ok(h.canvasPngCalls.includes(2));
+
+ h.setUnreadCount(0);
+ await h.badge.refresh();
+ assert.equal(h.overlayIcons.at(-1).image, null);
+ assert.equal(h.overlayIcons.at(-1).description, "");
+ } finally {
+ h.dispose();
+ }
+});
+
+test("Windows: refresh before window is ready keeps the update for replay", async () => {
+ const h = harness({ platform: "win32", unreadCount: 3, windowReady: false });
+ try {
+ await h.badge.refresh();
+ assert.equal(h.listCalls.length, 1);
+ assert.equal(h.overlayIcons.length, 0, "no overlay while window is missing");
+
+ // Same count again must not be treated as already applied.
+ await h.badge.refresh();
+ assert.equal(h.overlayIcons.length, 0);
+
+ h.makeWindow();
+ h.badge.replay();
+ await waitFor(() => h.overlayIcons.length >= 1);
+ assert.equal(h.overlayIcons.length, 1);
+ assert.notEqual(h.overlayIcons[0].image, null);
+ assert.equal(h.overlayIcons[0].description, "3");
+ } finally {
+ h.dispose();
+ }
+});
+
+test("Windows: createTray-style replay paints after late window readiness", async () => {
+ const h = harness({ platform: "win32", unreadCount: 2, windowReady: false });
+ try {
+ h.badge.observeEvent(IPC.event.notificationChanged, { reason: "insert" });
+ await waitFor(() => h.listCalls.length >= 1);
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(h.overlayIcons.length, 0);
+
+ h.makeWindow();
+ // createTray calls refresh() then replay().
+ await h.badge.refresh();
+ h.badge.replay();
+ await waitFor(() => h.overlayIcons.length >= 1);
+ assert.ok(h.overlayIcons.length >= 1);
+ assert.equal(h.overlayIcons.at(-1).description, "2");
+ } finally {
+ h.dispose();
+ }
+});
+
+test("Windows: uses smooth Canvas PNG with scaleFactor 3 and no resize", async () => {
+ const h = harness({ platform: "win32", unreadCount: 9 });
+ try {
+ await h.badge.refresh();
+ assert.ok(h.canvasPngCalls.includes(9));
+ assert.equal(h.syncPngCalls.length, 0);
+ assert.equal(h.overlayIcons.at(-1).description, "9");
+ assert.ok(h.createFromBufferCalls.length >= 1);
+ assert.equal(h.createFromBufferCalls.at(-1).scaleFactor, 3);
+ assert.equal(h.resizeCalls.length, 0, "must not intermediate-resize overlay");
+ } finally {
+ h.dispose();
+ }
+});
+
+test("Windows: falls back to the bitmap if Canvas rendering fails", async () => {
+ const h = harness({
+ platform: "win32",
+ unreadCount: 4,
+ renderPng: async () => { throw new Error("renderer unavailable"); },
+ });
+ try {
+ await h.badge.refresh();
+ assert.deepEqual(h.canvasPngCalls, [4]);
+ assert.deepEqual(h.syncPngCalls, [4]);
+ assert.equal(h.overlayIcons.at(-1).description, "4");
+ } finally {
+ h.dispose();
+ }
+});
+
+test("Windows: a delayed Canvas result cannot replace a newer paint", async () => {
+ let finishFirst;
+ const firstRender = new Promise((resolve) => { finishFirst = resolve; });
+ let renderCount = 0;
+ const h = harness({
+ platform: "win32",
+ unreadCount: 1,
+ renderPng: () => ++renderCount === 1
+ ? firstRender
+ : Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
+ });
+ try {
+ const firstRefresh = h.badge.refresh();
+ await waitFor(() => h.canvasPngCalls.includes(1));
+ h.badge.replay();
+ await waitFor(() => h.overlayIcons.length === 1);
+ finishFirst(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
+ await firstRefresh;
+ assert.equal(h.overlayIcons.length, 1, "stale first paint must not apply");
+ } finally {
+ h.dispose();
+ }
+});
+
+test("badge source has no image.resize and imports the Canvas renderer", () => {
+ const source = readFileSync(
+ new URL("../electron/main/taskbar-unread-badge.ts", import.meta.url),
+ "utf8",
+ );
+ assert.doesNotMatch(source, /image\.resize/);
+ assert.doesNotMatch(source, /resize\s*\(/);
+ assert.match(source, /renderTaskbarUnreadOverlayPng/);
+ assert.match(source, /scaleFactor:\s*TASKBAR_UNREAD_OVERLAY_SCALE_FACTOR/);
+ assert.match(source, /buildTaskbarUnreadOverlayPng/);
+});
+
+test("D295 inbox still counts failures only while shell uses full unreadCount", () => {
+ const rows = [
+ {
+ id: "c1",
+ kind: "task.completed",
+ sessionId: "s",
+ sessionTitle: "S",
+ turnId: "t1",
+ createdAt: "2026-09-24T00:00:00.000Z",
+ readAt: null,
+ },
+ {
+ id: "f1",
+ kind: "task.failed",
+ sessionId: "s",
+ sessionTitle: "S",
+ turnId: "t2",
+ createdAt: "2026-09-24T00:00:01.000Z",
+ readAt: null,
+ },
+ {
+ id: "c2",
+ kind: "task.completed",
+ sessionId: "s",
+ sessionTitle: "S",
+ turnId: "t3",
+ createdAt: "2026-09-24T00:00:02.000Z",
+ readAt: null,
+ },
+ ];
+ assert.deepEqual(
+ inboxNotifications(rows).map((row) => row.id),
+ ["f1"],
+ );
+ assert.equal(inboxUnreadCount(rows), 1);
+ // Shell badge path reads host unreadCount (completed + failed) — 3 here.
+ assert.equal(rows.filter((row) => row.readAt == null).length, 3);
+});
diff --git a/apps/desktop/test/taskbar-unread-overlay.test.mjs b/apps/desktop/test/taskbar-unread-overlay.test.mjs
new file mode 100644
index 000000000..aecb7415a
--- /dev/null
+++ b/apps/desktop/test/taskbar-unread-overlay.test.mjs
@@ -0,0 +1,350 @@
+import assert from "node:assert/strict";
+import { inflateSync } from "node:zlib";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import {
+ TASKBAR_UNREAD_OVERLAY_SCALE_FACTOR,
+ TASKBAR_UNREAD_OVERLAY_SIZE,
+ buildTaskbarUnreadOverlayCanvasScript,
+ buildTaskbarUnreadOverlayPng,
+ formatTaskbarUnreadOverlayLabel,
+ renderTaskbarUnreadOverlayPng,
+} from "../electron/main/taskbar-unread-overlay.ts";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+
+/** Read PNG IHDR width/height (big-endian) after the 8-byte signature + 4-byte length + "IHDR". */
+function readPngIhdrSize(png) {
+ assert.ok(Buffer.isBuffer(png));
+ assert.ok(png.length >= 24);
+ assert.deepEqual([...png.subarray(0, 8)], [137, 80, 78, 71, 13, 10, 26, 10]);
+ assert.equal(png.toString("ascii", 12, 16), "IHDR");
+ return {
+ width: png.readUInt32BE(16),
+ height: png.readUInt32BE(20),
+ };
+}
+
+/**
+ * Decode an RGBA PNG produced by our filter-None encoder (no interlacing).
+ * Returns { width, height, rgba: Uint8Array }.
+ */
+function decodeRgbaPng(png) {
+ const { width, height } = readPngIhdrSize(png);
+ const idats = [];
+ let offset = 8;
+ while (offset + 8 <= png.length) {
+ const len = png.readUInt32BE(offset);
+ const type = png.toString("ascii", offset + 4, offset + 8);
+ const data = png.subarray(offset + 8, offset + 8 + len);
+ if (type === "IDAT") idats.push(data);
+ if (type === "IEND") break;
+ offset += 12 + len;
+ }
+ const raw = inflateSync(Buffer.concat(idats));
+ const stride = width * 4;
+ const expected = (stride + 1) * height;
+ assert.equal(raw.length, expected);
+ const rgba = new Uint8Array(width * height * 4);
+ for (let y = 0; y < height; y += 1) {
+ const rowStart = y * (stride + 1);
+ assert.equal(raw[rowStart], 0, "expected filter type None");
+ for (let x = 0; x < stride; x += 1) {
+ rgba[y * stride + x] = raw[rowStart + 1 + x];
+ }
+ }
+ return { width, height, rgba };
+}
+
+/** Bounding box of pixels whose channel exceeds threshold (default: near-white). */
+function whiteGlyphBBox(rgba, width, height, { minLuma = 180, minAlpha = 128 } = {}) {
+ let minX = width;
+ let minY = height;
+ let maxX = -1;
+ let maxY = -1;
+ let count = 0;
+ for (let y = 0; y < height; y += 1) {
+ for (let x = 0; x < width; x += 1) {
+ const i = (y * width + x) * 4;
+ const r = rgba[i];
+ const g = rgba[i + 1];
+ const b = rgba[i + 2];
+ const a = rgba[i + 3];
+ if (a < minAlpha) continue;
+ const luma = (r + g + b) / 3;
+ if (luma < minLuma) continue;
+ count += 1;
+ if (x < minX) minX = x;
+ if (y < minY) minY = y;
+ if (x > maxX) maxX = x;
+ if (y > maxY) maxY = y;
+ }
+ }
+ if (count === 0) return null;
+ return {
+ minX,
+ minY,
+ maxX,
+ maxY,
+ width: maxX - minX + 1,
+ height: maxY - minY + 1,
+ count,
+ };
+}
+
+/** Opaque (or mostly opaque) non-transparent pixel coverage + radial extent. */
+function circleCoverage(rgba, width, height, { minAlpha = 128 } = {}) {
+ let opaque = 0;
+ let minX = width;
+ let minY = height;
+ let maxX = -1;
+ let maxY = -1;
+ for (let y = 0; y < height; y += 1) {
+ for (let x = 0; x < width; x += 1) {
+ const a = rgba[(y * width + x) * 4 + 3];
+ if (a < minAlpha) continue;
+ opaque += 1;
+ if (x < minX) minX = x;
+ if (y < minY) minY = y;
+ if (x > maxX) maxX = x;
+ if (y > maxY) maxY = y;
+ }
+ }
+ const bboxW = maxX >= 0 ? maxX - minX + 1 : 0;
+ const bboxH = maxY >= 0 ? maxY - minY + 1 : 0;
+ // Transparent margin from canvas edge (min of four sides).
+ const margin = maxX >= 0
+ ? Math.min(minX, minY, width - 1 - maxX, height - 1 - maxY)
+ : width;
+ return {
+ opaque,
+ ratio: opaque / (width * height),
+ bboxW,
+ bboxH,
+ margin,
+ diameter: Math.min(bboxW, bboxH),
+ };
+}
+
+test("clears the overlay label and png when count is zero or negative", () => {
+ assert.equal(formatTaskbarUnreadOverlayLabel(0), null);
+ assert.equal(formatTaskbarUnreadOverlayLabel(-3), null);
+ assert.equal(buildTaskbarUnreadOverlayPng(0), null);
+ assert.equal(buildTaskbarUnreadOverlayPng(-1), null);
+});
+
+test("formats unread counts 1–99 as their real digit string", () => {
+ assert.equal(formatTaskbarUnreadOverlayLabel(1), "1");
+ assert.equal(formatTaskbarUnreadOverlayLabel(5), "5");
+ assert.equal(formatTaskbarUnreadOverlayLabel(9), "9");
+ assert.equal(formatTaskbarUnreadOverlayLabel(10), "10");
+ assert.equal(formatTaskbarUnreadOverlayLabel(36), "36");
+ assert.equal(formatTaskbarUnreadOverlayLabel(99), "99");
+});
+
+test("caps overlay text at 99+ for counts of 100 or more", () => {
+ assert.equal(formatTaskbarUnreadOverlayLabel(100), "99+");
+ assert.equal(formatTaskbarUnreadOverlayLabel(101), "99+");
+ assert.equal(formatTaskbarUnreadOverlayLabel(999), "99+");
+});
+
+test("exports 64px raster with scaleFactor 3 (~21px logical)", () => {
+ assert.equal(TASKBAR_UNREAD_OVERLAY_SIZE, 64);
+ assert.equal(TASKBAR_UNREAD_OVERLAY_SCALE_FACTOR, 3);
+ assert.equal(
+ TASKBAR_UNREAD_OVERLAY_SIZE / TASKBAR_UNREAD_OVERLAY_SCALE_FACTOR,
+ 64 / 3,
+ );
+});
+
+test("builds a deterministic 64×64 PNG with the PNG signature for positive counts", () => {
+ const one = buildTaskbarUnreadOverlayPng(1);
+ const again = buildTaskbarUnreadOverlayPng(1);
+ const hundred = buildTaskbarUnreadOverlayPng(100);
+ assert.ok(Buffer.isBuffer(one));
+ assert.ok(Buffer.isBuffer(hundred));
+ assert.deepEqual([...one.subarray(0, 8)], [137, 80, 78, 71, 13, 10, 26, 10]);
+ assert.deepEqual([...hundred.subarray(0, 8)], [137, 80, 78, 71, 13, 10, 26, 10]);
+ assert.deepEqual(one, again);
+ assert.notDeepEqual(one, hundred);
+
+ const oneSize = readPngIhdrSize(one);
+ const hundredSize = readPngIhdrSize(hundred);
+ assert.equal(oneSize.width, 64);
+ assert.equal(oneSize.height, 64);
+ assert.equal(oneSize.width, TASKBAR_UNREAD_OVERLAY_SIZE);
+ assert.equal(oneSize.height, TASKBAR_UNREAD_OVERLAY_SIZE);
+ assert.equal(hundredSize.width, TASKBAR_UNREAD_OVERLAY_SIZE);
+ assert.equal(hundredSize.height, TASKBAR_UNREAD_OVERLAY_SIZE);
+});
+
+test("single-digit, two-digit, and 99+ overlays produce different PNG buffers", () => {
+ const five = buildTaskbarUnreadOverlayPng(5);
+ const thirtysix = buildTaskbarUnreadOverlayPng(36);
+ const hundred = buildTaskbarUnreadOverlayPng(100);
+ assert.ok(Buffer.isBuffer(five));
+ assert.ok(Buffer.isBuffer(thirtysix));
+ assert.ok(Buffer.isBuffer(hundred));
+ assert.notDeepEqual(five, thirtysix);
+ assert.notDeepEqual(thirtysix, hundred);
+ assert.notDeepEqual(five, hundred);
+});
+
+test("fallback circle fills the complete 64px canvas", () => {
+ const png = buildTaskbarUnreadOverlayPng(8);
+ const { width, height, rgba } = decodeRgbaPng(png);
+ assert.equal(width, 64);
+ assert.equal(height, 64);
+ const cov = circleCoverage(rgba, width, height);
+ assert.ok(cov.diameter >= 63, `diameter ${cov.diameter}`);
+ assert.ok(cov.margin <= 1, `margin ${cov.margin}`);
+ assert.ok(cov.ratio >= 0.65, `opaque ratio ${cov.ratio}`);
+ // Perfect circle: bbox roughly square.
+ assert.ok(Math.abs(cov.bboxW - cov.bboxH) <= 2);
+});
+
+test("Canvas path uses the full badge area and a prominent single digit", () => {
+ const one = buildTaskbarUnreadOverlayCanvasScript(1);
+ assert.ok(one);
+ assert.match(one, /const radius = 32/);
+ assert.match(one, /let fontSize = singleDigit \? 50/);
+ assert.match(one, /ctx\.font = "600 "/);
+ assert.match(one, /ctx\.scale\(1\.1, 1\.03\)/);
+});
+
+test("Canvas PNG decoding rejects invalid renderer output", async () => {
+ const valid = buildTaskbarUnreadOverlayPng(7);
+ const contents = (result) => ({
+ isDestroyed: () => false,
+ executeJavaScript: async () => result,
+ });
+ assert.deepEqual(
+ await renderTaskbarUnreadOverlayPng(contents(`data:image/png;base64,${valid.toString("base64")}`), 7),
+ valid,
+ );
+ assert.equal(
+ await renderTaskbarUnreadOverlayPng(contents("data:image/png;base64,bm90IGEgcG5n"), 7),
+ null,
+ );
+ assert.equal(await renderTaskbarUnreadOverlayPng(contents(null), 7), null);
+});
+
+test("single-digit white glyph height ≈44–48px and ~65–80% of circle diameter", () => {
+ for (const count of [1, 8]) {
+ const png = buildTaskbarUnreadOverlayPng(count);
+ const { width, height, rgba } = decodeRgbaPng(png);
+ const cov = circleCoverage(rgba, width, height);
+ const glyph = whiteGlyphBBox(rgba, width, height);
+ assert.ok(glyph, `expected white glyph for ${count}`);
+ assert.ok(
+ glyph.height >= 44 && glyph.height <= 48,
+ `glyph height ${glyph.height} for ${count}`,
+ );
+ const ratio = glyph.height / cov.diameter;
+ assert.ok(
+ ratio >= 0.65 && ratio <= 0.85,
+ `glyph/diameter ratio ${ratio} for ${count}`,
+ );
+ }
+});
+
+test("digit 1 has widened top bar and base (not a thin stem)", () => {
+ const png = buildTaskbarUnreadOverlayPng(1);
+ const { width, height, rgba } = decodeRgbaPng(png);
+ const glyph = whiteGlyphBBox(rgba, width, height);
+ assert.ok(glyph);
+
+ function rowWhiteWidth(y) {
+ let min = width;
+ let max = -1;
+ for (let x = 0; x < width; x += 1) {
+ const i = (y * width + x) * 4;
+ if (rgba[i + 3] < 128) continue;
+ if ((rgba[i] + rgba[i + 1] + rgba[i + 2]) / 3 < 180) continue;
+ if (x < min) min = x;
+ if (x > max) max = x;
+ }
+ return max >= 0 ? max - min + 1 : 0;
+ }
+
+ // Sample bands: tip row alone is narrow; the widened top bar sits just below it.
+ const h = glyph.height;
+ let topW = 0;
+ for (let y = glyph.minY; y <= glyph.minY + Math.floor(h * 0.3); y += 1) {
+ topW = Math.max(topW, rowWhiteWidth(y));
+ }
+ let baseW = 0;
+ for (let y = glyph.maxY - Math.floor(h * 0.2); y <= glyph.maxY; y += 1) {
+ baseW = Math.max(baseW, rowWhiteWidth(y));
+ }
+ const midY = Math.floor((glyph.minY + glyph.maxY) / 2);
+ const stemW = Math.min(
+ rowWhiteWidth(midY),
+ rowWhiteWidth(midY - 1),
+ rowWhiteWidth(midY + 1),
+ );
+ assert.ok(stemW > 0, "stem present");
+ assert.ok(topW > stemW, `top bar ${topW} should exceed stem ${stemW}`);
+ assert.ok(baseW > stemW, `base ${baseW} should exceed stem ${stemW}`);
+ // Base should be clearly wider than a thin stem (≈2× or more).
+ assert.ok(baseW >= stemW * 1.8, `base ${baseW} vs stem ${stemW}`);
+});
+
+test("two-digit / 99+ use smaller glyph layout than single-digit", () => {
+ const single = whiteGlyphBBox(
+ decodeRgbaPng(buildTaskbarUnreadOverlayPng(8)).rgba,
+ 64,
+ 64,
+ );
+ const two = whiteGlyphBBox(
+ decodeRgbaPng(buildTaskbarUnreadOverlayPng(36)).rgba,
+ 64,
+ 64,
+ );
+ const capped = whiteGlyphBBox(
+ decodeRgbaPng(buildTaskbarUnreadOverlayPng(100)).rgba,
+ 64,
+ 64,
+ );
+ assert.ok(single && two && capped);
+ // Multi-digit row is shorter than the single-digit glyph height.
+ assert.ok(
+ two.height < single.height,
+ `two-digit height ${two.height} vs single ${single.height}`,
+ );
+ assert.ok(
+ capped.height < single.height,
+ `99+ height ${capped.height} vs single ${single.height}`,
+ );
+ // Single-digit must not reuse multi-digit proportions (taller + typically narrower).
+ assert.ok(single.height >= 44);
+ assert.ok(two.height <= 36);
+});
+
+test("source uses a Segoe UI Canvas path for smooth Windows badge glyphs", () => {
+ const overlaySource = readFileSync(
+ join(root, "electron/main/taskbar-unread-overlay.ts"),
+ "utf8",
+ );
+ assert.match(overlaySource, /buildTaskbarUnreadOverlayCanvasScript/);
+ assert.match(overlaySource, /renderTaskbarUnreadOverlayPng/);
+ assert.match(overlaySource, /\.fillText\s*\(/);
+ assert.match(overlaySource, /ctx\.font/);
+ assert.match(overlaySource, /Segoe UI/);
+ assert.match(overlaySource, /executeJavaScript/);
+ assert.doesNotMatch(overlaySource, /\.roundRect\s*\(/);
+ assert.doesNotMatch(overlaySource, /ctx\.ellipse\s*\(/);
+ assert.match(overlaySource, /D295/);
+ assert.match(overlaySource, /failures only|failure-only|failures-only/i);
+});
+
+test("documents the D295 bell vs shell-badge count split", () => {
+ const inboxSource = readFileSync(
+ join(root, "src/lib/notification-inbox.ts"),
+ "utf8",
+ );
+ assert.match(inboxSource, /task\.completed/);
+ assert.match(inboxSource, /notification\.kind !== "task\.completed"/);
+});
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index b2e4619c7..9fb7de6f9 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -3851,7 +3851,9 @@ Sidebar footer Popover (360px max)
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.
+ banners, and leaves sessions, transcripts, and turns intact. These actions
+ remain available for successful completions hidden from the failure-only
+ bell list, so the taskbar unread badge can be cleared from the popover.
- `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
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index f67b3a908..be3199ebd 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -4222,7 +4222,11 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
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.
+ duplicate payload for an id that is already present. 12) On Windows, create
+ one unread successful outcome while the bell has no failure rows. Open the
+ empty bell popover, use Mark all read, then create another success and use
+ Clear. 13) Create enough unread outcomes for a two-digit count and inspect
+ the taskbar overlay before and after marking all outcomes read.
- **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.
@@ -4239,7 +4243,14 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
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.
+ banner. On Windows, the taskbar overlay is a smooth black circular badge
+ with a centered white system-font numeral. Its visual weight matches common
+ Windows taskbar badges for both single- and two-digit counts. A success-only
+ outcome increments the taskbar badge without adding a bell row or bell
+ count; both toolbar actions remain enabled when relevant and clear the
+ taskbar badge. The badge also clears when no unread outcomes remain. The
+ underlying taskbar button keeps the
+ PI-Desktop `P` icon and PI-Desktop name while the overlay is present.
- **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`,