diff --git a/playwright.config.ts b/playwright.config.ts index 31c832b12..f1a462f1c 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -103,6 +103,13 @@ export default defineConfig({ ...devices["Desktop Chrome"], }, }, + { + name: "notifications", + testMatch: ["**/notifications.spec.ts", "**/fixtures/tauri-mock.spec.ts"], + use: { + ...devices["Desktop Chrome"], + }, + }, { name: "voice-conversation", testMatch: [ diff --git a/src/shared/hooks/__tests__/useCompletionNotifications.test.ts b/src/shared/hooks/__tests__/useCompletionNotifications.test.ts index 705356ff1..11e8a4ff2 100644 --- a/src/shared/hooks/__tests__/useCompletionNotifications.test.ts +++ b/src/shared/hooks/__tests__/useCompletionNotifications.test.ts @@ -3,6 +3,7 @@ import type React from "react"; import { isValidElement } from "react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { + FOCUS_STATE_SEED_TIMEOUT_MS, getCompletionOutcome, getNotificationBody, useCompletionNotifications, @@ -186,6 +187,7 @@ describe("useCompletionNotifications", () => { }), ); mocks.getCurrentWindow.mockReturnValue({ + isFocused: vi.fn().mockResolvedValue(true), onFocusChanged: vi.fn().mockResolvedValue(vi.fn()), unminimize: vi.fn().mockResolvedValue(undefined), show: vi.fn().mockResolvedValue(undefined), @@ -214,6 +216,7 @@ describe("useCompletionNotifications", () => { | null = null; const appWindow = { + isFocused: vi.fn().mockResolvedValue(true), onFocusChanged: vi.fn((handler) => { focusChanged = handler; return Promise.resolve(vi.fn()); @@ -278,6 +281,7 @@ describe("useCompletionNotifications", () => { let focusChanged: ((event: { payload: boolean }) => void) | null = null; mocks.getCurrentWindow.mockReturnValue({ + isFocused: vi.fn().mockResolvedValue(true), onFocusChanged: vi.fn((handler) => { focusChanged = handler; return Promise.resolve(vi.fn()); @@ -357,6 +361,7 @@ describe("useCompletionNotifications", () => { ), ); mocks.getCurrentWindow.mockReturnValue({ + isFocused: vi.fn().mockResolvedValue(true), onFocusChanged: vi.fn((handler) => { focusChanged = handler; return Promise.resolve(vi.fn()); @@ -401,6 +406,7 @@ describe("useCompletionNotifications", () => { : Promise.resolve(undefined), ); mocks.getCurrentWindow.mockReturnValue({ + isFocused: vi.fn().mockResolvedValue(true), onFocusChanged: vi.fn((handler) => { focusChanged = handler; return Promise.resolve(vi.fn()); @@ -453,6 +459,7 @@ describe("useCompletionNotifications", () => { : Promise.resolve(undefined), ); mocks.getCurrentWindow.mockReturnValue({ + isFocused: vi.fn().mockResolvedValue(true), onFocusChanged: vi.fn((handler) => { focusChanged = handler; return Promise.resolve(vi.fn()); @@ -502,6 +509,7 @@ describe("useCompletionNotifications", () => { window.addEventListener("goose:open-settings", onOpenSettings); mocks.getCurrentWindow.mockReturnValue({ + isFocused: vi.fn().mockResolvedValue(true), onFocusChanged: vi.fn((handler) => { focusChanged = handler; return Promise.resolve(vi.fn()); @@ -614,6 +622,7 @@ describe("useCompletionNotifications", () => { ); mocks.getCurrentWindow.mockReturnValue({ + isFocused: vi.fn().mockResolvedValue(true), onFocusChanged: vi.fn((handler) => { focusChanged = handler; return Promise.resolve(vi.fn()); @@ -660,6 +669,7 @@ describe("useCompletionNotifications", () => { ); mocks.getCurrentWindow.mockReturnValue({ + isFocused: vi.fn().mockResolvedValue(true), onFocusChanged: vi.fn((handler) => { focusChanged = handler; return Promise.resolve(vi.fn()); @@ -700,6 +710,301 @@ describe("useCompletionNotifications", () => { ); }); + it("routes to desktop delivery when the window starts unfocused before any focus event", async () => { + const onFocusChanged = vi.fn().mockResolvedValue(vi.fn()); + mocks.getCurrentWindow.mockReturnValue({ + isFocused: vi.fn().mockResolvedValue(false), + onFocusChanged, + unminimize: vi.fn().mockResolvedValue(undefined), + show: vi.fn().mockResolvedValue(undefined), + setFocus: vi.fn().mockResolvedValue(undefined), + }); + + renderHook(() => useCompletionNotifications(vi.fn())); + + // Wait for the focus listener registration so the isFocused seed has + // resolved too; no focus-change event is ever delivered in this test. + await waitFor(() => expect(onFocusChanged).toHaveBeenCalled()); + + useChatSessionStore.getState().addSession({ + id: "session-4", + title: "Background start", + createdAt: "2026-06-05T00:00:00.000Z", + updatedAt: "2026-06-05T00:00:00.000Z", + messageCount: 1, + }); + useChatStore.getState().setMessages("session-4", [makeMsg("completed")]); + + act(() => { + useChatStore.getState().setChatState("session-4", "streaming"); + useChatStore.getState().setChatState("session-4", "idle"); + }); + + await waitFor(() => + expect(mocks.invoke).toHaveBeenCalledWith( + "show_completion_notification", + { + body: "Background start finished", + sessionId: "session-4", + sound: "berd-sounds-4.mp3", + }, + ), + ); + }); + + function makeAppWindow(isFocused: () => Promise) { + let focusChanged: ((event: { payload: boolean }) => void) | null = null; + const onFocusChanged = vi.fn((handler) => { + focusChanged = handler; + return Promise.resolve(vi.fn()); + }); + mocks.getCurrentWindow.mockReturnValue({ + isFocused: vi.fn(isFocused), + onFocusChanged, + unminimize: vi.fn().mockResolvedValue(undefined), + show: vi.fn().mockResolvedValue(undefined), + setFocus: vi.fn().mockResolvedValue(undefined), + }); + return { + onFocusChanged, + fireFocusChanged: (payload: boolean) => focusChanged?.({ payload }), + }; + } + + function completeSession(sessionId: string, title: string) { + useChatSessionStore.getState().addSession({ + id: sessionId, + title, + createdAt: "2026-06-05T00:00:00.000Z", + updatedAt: "2026-06-05T00:00:00.000Z", + messageCount: 1, + }); + useChatStore.getState().setMessages(sessionId, [makeMsg("completed")]); + act(() => { + useChatStore.getState().setChatState(sessionId, "streaming"); + useChatStore.getState().setChatState(sessionId, "idle"); + }); + } + + it("defers a completion finishing before the focus query settles, then delivers exactly one desktop notification", async () => { + const focusQuery = deferred(); + const { onFocusChanged } = makeAppWindow(() => focusQuery.promise); + + renderHook(() => useCompletionNotifications(vi.fn())); + await waitFor(() => expect(onFocusChanged).toHaveBeenCalled()); + + completeSession("session-defer", "Deferred start"); + + // The query is still pending: delivery must be buffered, not routed with + // the placeholder focused default. + await act(async () => { + await Promise.resolve(); + }); + expect(mocks.invoke).not.toHaveBeenCalledWith( + "show_completion_notification", + expect.anything(), + ); + expect(mocks.toast).not.toHaveBeenCalled(); + + focusQuery.resolve(false); + + await waitFor(() => + expect(mocks.invoke).toHaveBeenCalledWith( + "show_completion_notification", + { + body: "Deferred start finished", + sessionId: "session-defer", + sound: "berd-sounds-4.mp3", + }, + ), + ); + const desktopCalls = mocks.invoke.mock.calls.filter( + ([command]) => command === "show_completion_notification", + ); + expect(desktopCalls).toHaveLength(1); + expect(mocks.toast).not.toHaveBeenCalled(); + }); + + it("delivers a desktop notification for an actively viewed session completing before the focus query settles in an unfocused window", async () => { + const focusQuery = deferred(); + const { onFocusChanged } = makeAppWindow(() => focusQuery.promise); + + renderHook(() => useCompletionNotifications(vi.fn())); + await waitFor(() => expect(onFocusChanged).toHaveBeenCalled()); + + // The user is "viewing" this session, but the window is actually + // backgrounded — the hook must not drop the completion based on the + // placeholder focused default before the query settles. + useChatStore.setState({ + activeSessionId: "session-viewed", + isViewingActiveSession: true, + }); + completeSession("session-viewed", "Viewed background"); + + await act(async () => { + await Promise.resolve(); + }); + expect(mocks.invoke).not.toHaveBeenCalledWith( + "show_completion_notification", + expect.anything(), + ); + + focusQuery.resolve(false); + + await waitFor(() => + expect(mocks.invoke).toHaveBeenCalledWith( + "show_completion_notification", + { + body: "Viewed background finished", + sessionId: "session-viewed", + sound: "berd-sounds-4.mp3", + }, + ), + ); + const desktopCalls = mocks.invoke.mock.calls.filter( + ([command]) => command === "show_completion_notification", + ); + expect(desktopCalls).toHaveLength(1); + expect(mocks.toast).not.toHaveBeenCalled(); + }); + + it("lets a focus event that arrives before the query settles win over the stale query result", async () => { + const focusQuery = deferred(); + const { onFocusChanged, fireFocusChanged } = makeAppWindow( + () => focusQuery.promise, + ); + + renderHook(() => useCompletionNotifications(vi.fn())); + await waitFor(() => expect(onFocusChanged).toHaveBeenCalled()); + + // Fresh event: the window lost focus after mount, before the (stale) + // query reported it as focused. + act(() => { + fireFocusChanged(false); + }); + focusQuery.resolve(true); + await act(async () => { + await Promise.resolve(); + }); + + completeSession("session-race", "Event wins"); + + await waitFor(() => + expect(mocks.invoke).toHaveBeenCalledWith( + "show_completion_notification", + { + body: "Event wins finished", + sessionId: "session-race", + sound: "berd-sounds-4.mp3", + }, + ), + ); + expect(mocks.toast).not.toHaveBeenCalled(); + }); + + it("falls back to the default focus state when the focus query rejects", async () => { + const { onFocusChanged } = makeAppWindow(() => + Promise.reject(new Error("focus query failed")), + ); + mocks.toast.mockReturnValue("toast-id"); + + renderHook(() => useCompletionNotifications(vi.fn())); + await waitFor(() => expect(onFocusChanged).toHaveBeenCalled()); + + completeSession("session-reject", "Query rejected"); + + // Rejection releases buffered completions with the focused default: the + // in-app toast path, exactly once. + await waitFor(() => expect(mocks.toast).toHaveBeenCalledTimes(1)); + expect(mocks.invoke).not.toHaveBeenCalledWith( + "show_completion_notification", + expect.anything(), + ); + }); + + it("releases buffered completions after the bounded fallback when the focus query never settles", async () => { + const { onFocusChanged } = makeAppWindow( + () => new Promise(() => {}), + ); + mocks.toast.mockReturnValue("toast-id"); + + // Fake timers must be active before mount so the bounded-fallback timer + // itself is controllable. + vi.useFakeTimers(); + try { + renderHook(() => useCompletionNotifications(vi.fn())); + // Flush the dynamic import microtasks so the listener registers. + await vi.advanceTimersByTimeAsync(0); + expect(onFocusChanged).toHaveBeenCalled(); + + completeSession("session-timeout", "Hung query"); + + await vi.advanceTimersByTimeAsync(0); + expect(mocks.toast).not.toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(FOCUS_STATE_SEED_TIMEOUT_MS); + expect(mocks.toast).toHaveBeenCalledTimes(1); + expect(mocks.invoke).not.toHaveBeenCalledWith( + "show_completion_notification", + expect.anything(), + ); + } finally { + vi.useRealTimers(); + } + }); + + it("preserves the typed event timestamp while delivery waits for initial focus", async () => { + const { subscribeToCompletionNotificationEvents } = await import( + "@/shared/notifications/completionEvents" + ); + const seen = vi.fn(); + const unsubscribe = subscribeToCompletionNotificationEvents(seen); + const focusQuery = deferred(); + const { onFocusChanged } = makeAppWindow(() => focusQuery.promise); + + try { + renderHook(() => useCompletionNotifications(vi.fn())); + await waitFor(() => expect(onFocusChanged).toHaveBeenCalled()); + const completionMs = 1_750_000_000_003; + const nowSpy = vi.spyOn(Date, "now").mockReturnValue(completionMs); + try { + completeSession("session-buffered-event", "Buffered event"); + } finally { + nowSpy.mockRestore(); + } + await act(async () => { + await Promise.resolve(); + }); + expect(seen).not.toHaveBeenCalled(); + expect(mocks.invoke).not.toHaveBeenCalledWith( + "should_suppress_completion_notification", + expect.anything(), + ); + + await act(async () => { + focusQuery.resolve(false); + }); + await waitFor(() => expect(seen).toHaveBeenCalledTimes(1)); + expect(seen).toHaveBeenCalledWith( + expect.objectContaining({ + sessionId: "session-buffered-event", + occurredAt: new Date(completionMs).toISOString(), + body: "Buffered event finished", + navigation: { kind: "session", sessionId: "session-buffered-event" }, + }), + ); + await waitFor(() => + expect(mocks.invoke).toHaveBeenCalledWith( + "show_completion_notification", + expect.objectContaining({ sessionId: "session-buffered-event" }), + ), + ); + expect(mocks.toast).not.toHaveBeenCalled(); + } finally { + unsubscribe(); + } + }); + it("preserves completion timestamps when suppression resolves out of order", async () => { const { subscribeToCompletionNotificationEvents } = await import( "@/shared/notifications/completionEvents" @@ -721,6 +1026,7 @@ describe("useCompletionNotifications", () => { let focusChanged: ((event: { payload: boolean }) => void) | null = null; mocks.getCurrentWindow.mockReturnValue({ + isFocused: vi.fn().mockResolvedValue(true), onFocusChanged: vi.fn((handler) => { focusChanged = handler; return Promise.resolve(vi.fn()); @@ -797,6 +1103,7 @@ describe("useCompletionNotifications", () => { let focusChanged: ((event: { payload: boolean }) => void) | null = null; mocks.getCurrentWindow.mockReturnValue({ + isFocused: vi.fn().mockResolvedValue(true), onFocusChanged: vi.fn((handler) => { focusChanged = handler; return Promise.resolve(vi.fn()); diff --git a/src/shared/hooks/useCompletionNotifications.ts b/src/shared/hooks/useCompletionNotifications.ts index f695192d5..99c7975c0 100644 --- a/src/shared/hooks/useCompletionNotifications.ts +++ b/src/shared/hooks/useCompletionNotifications.ts @@ -27,6 +27,9 @@ import { getPlatform } from "@/shared/lib/platform"; import type { Message } from "@/shared/types/messages"; const COMPLETION_NOTIFICATION_CLICKED_EVENT = "completion-notification-clicked"; +// Upper bound on how long completion delivery may wait for the initial +// window-focus query before proceeding with the best-known focus state. +export const FOCUS_STATE_SEED_TIMEOUT_MS = 1000; async function shouldSuppressCompletionNotification( sessionId: string, @@ -87,6 +90,11 @@ export function useCompletionNotifications( onNavigateToSession: (sessionId: string) => void, ): void { const windowFocusedRef = useRef(true); + // Resolves once the focus state has been seeded (initial isFocused() query + // settled, a real focus event arrived, or the bounded fallback elapsed). + // Completion delivery waits on this so a session finishing before the + // mount-time query settles is not misclassified by the default value. + const focusStateReadyRef = useRef>(Promise.resolve()); // Keep a stable ref so the Zustand subscriber never has a stale callback. const navigateRef = useRef(onNavigateToSession); useEffect(() => { @@ -106,18 +114,61 @@ export function useCompletionNotifications( if (!window.__TAURI_INTERNALS__) return; let unlisten: (() => void) | null = null; let cancelled = false; + let markFocusStateReady!: () => void; + focusStateReadyRef.current = new Promise((resolve) => { + markFocusStateReady = resolve; + }); + // Bounded fallback: never hold completion delivery hostage to a focus + // query that fails to settle. + const fallbackTimer = setTimeout( + markFocusStateReady, + FOCUS_STATE_SEED_TIMEOUT_MS, + ); + // A real focus-change event is always fresher than the mount-time query, + // so once one arrives the query result must not clobber it. + let focusEventSeen = false; import("@tauri-apps/api/window") - .then(({ getCurrentWindow }) => - getCurrentWindow().onFocusChanged(({ payload: focused }) => { - windowFocusedRef.current = focused; - }), - ) + .then(({ getCurrentWindow }) => { + const appWindow = getCurrentWindow(); + // Register the focus listener before sampling focus so a change that + // happens while the sample is in flight is observed (and wins). + return appWindow + .onFocusChanged(({ payload: focused }) => { + // A cleaned-up effect generation must not write into state now + // owned by a newer generation (StrictMode remounts). + if (cancelled) return; + focusEventSeen = true; + windowFocusedRef.current = focused; + markFocusStateReady(); + }) + .then((unlistenFocus) => { + // Seed from the real focus state: the ref defaults to true, so a + // completion that lands before any focus-change event would + // otherwise be delivered as an in-app toast in a backgrounded + // window instead of a desktop notification. + void appWindow + .isFocused() + .then((focused) => { + if (!cancelled && !focusEventSeen) { + windowFocusedRef.current = focused; + } + markFocusStateReady(); + }) + .catch(() => { + markFocusStateReady(); + }); + return unlistenFocus; + }); + }) .then((fn) => { if (cancelled) fn(); else unlisten = fn; }); return () => { cancelled = true; + clearTimeout(fallbackTimer); + // Don't leave buffered completions waiting on a torn-down listener. + markFocusStateReady(); unlisten?.(); }; }, []); @@ -217,13 +268,11 @@ export function useCompletionNotifications( const occurredAtMs = Date.now(); const chatStoreState = useChatStore.getState(); - const isViewingThisSession = isSessionActivelyViewed( - chatStoreState, - sessionId, - ); - // Skip if user is already watching this session in a focused window. - if (isViewingThisSession && windowFocusedRef.current) continue; - + // The "actively watching in a focused window" skip is evaluated + // only after the focus state is seeded (inside the buffered + // continuation below): checking it here would read the + // placeholder `true` default and silently drop a completion + // that lands while the mount-time focus query is in flight. const messages = chatStoreState.messagesBySession[sessionId] ?? []; const outcome = getCompletionOutcome(messages); const session = useChatSessionStore @@ -236,8 +285,12 @@ export function useCompletionNotifications( ? session.title : ""; const body = getNotificationBody(outcome, title); - void shouldSuppressCompletionNotification(sessionId).then( - (suppress) => { + // Wait for the seeded focus state before evaluating suppression + // so neither the focus routing below reads the placeholder + // default nor the suppression result goes stale while buffered. + void focusStateReadyRef.current + .then(() => shouldSuppressCompletionNotification(sessionId)) + .then((suppress) => { if (suppress) return; const currentPrefs = getNotificationPrefs(); if (!currentPrefs.enabled) return; @@ -305,8 +358,7 @@ export function useCompletionNotifications( viewLabel: tRef.current("actions.view"), changeSoundLabel: tRef.current("actions.changeSound"), }); - }, - ); + }); } } }, diff --git a/tests/e2e/fixtures/tauri-mock.spec.ts b/tests/e2e/fixtures/tauri-mock.spec.ts new file mode 100644 index 000000000..759b7deeb --- /dev/null +++ b/tests/e2e/fixtures/tauri-mock.spec.ts @@ -0,0 +1,91 @@ +import { test, expect } from "@playwright/test"; +import { buildInitScript } from "./tauri-mock"; + +test("shared mock preserves held ACP completion, focus and voice controls", async ({ + page, +}) => { + await page.addInitScript({ + content: buildInitScript({ holdAcpPrompts: true }), + }); + await page.goto("/"); + + const result = await page.evaluate(async () => { + const harness = window.__GOOSE_E2E__ as typeof window.__GOOSE_E2E__ & { + acpRequests: () => Array<{ id: number; method: string }>; + completeAcpPrompts: () => void; + pocketVoiceStreamIds: () => number[]; + pocketVoiceSpokenTexts: () => string[]; + }; + const internals = window.__TAURI_INTERNALS__ as { + invoke: (command: string, args?: unknown) => Promise; + }; + const socket = new WebSocket("ws://mock-goose"); + await new Promise((resolve) => { + socket.addEventListener("open", () => resolve(), { once: true }); + }); + const delivered: unknown[] = []; + socket.addEventListener("message", (event) => { + delivered.push(JSON.parse(String(event.data))); + }); + const initialCompletions = harness.completedPromptSessionIds().length; + socket.send( + JSON.stringify({ + jsonrpc: "2.0", + id: 98765, + method: "session/prompt", + params: { sessionId: "fixture-held-session", prompt: [] }, + }), + ); + const requestObserved = harness + .acpRequests() + .some((request) => request.id === 98765); + const beforeRelease = { + delivered: delivered.length, + completions: harness.completedPromptSessionIds().length, + }; + harness.completeAcpPrompts(); + const afterRelease = [...harness.completedPromptSessionIds()]; + harness.completeAcpPrompts(); + const afterSecondRelease = [...harness.completedPromptSessionIds()]; + const initiallyFocused = await internals.invoke("plugin:window|is_focused"); + harness.setWindowFocused(false); + const finallyFocused = await internals.invoke("plugin:window|is_focused"); + await internals.invoke("start_pocket_voice_stream", { streamId: 345 }); + await internals.invoke("append_pocket_voice_stream", { + streamId: 345, + text: "Retained voice stream", + }); + await internals.invoke("finish_pocket_voice_stream", { streamId: 345 }); + socket.close(); + return { + requestObserved, + initialCompletions, + beforeRelease, + delivered, + afterRelease, + afterSecondRelease, + initiallyFocused, + finallyFocused, + streamIds: harness.pocketVoiceStreamIds(), + spokenTexts: harness.pocketVoiceSpokenTexts(), + }; + }); + + expect(result.requestObserved).toBe(true); + expect(result.beforeRelease).toEqual({ + delivered: 0, + completions: result.initialCompletions, + }); + expect(result.delivered).toContainEqual({ + jsonrpc: "2.0", + id: 98765, + result: { stopReason: "end_turn" }, + }); + expect(result.afterRelease).toHaveLength(result.initialCompletions + 1); + expect(result.afterRelease.at(-1)).toBe("fixture-held-session"); + expect(result.afterSecondRelease).toEqual(result.afterRelease); + expect(result.initiallyFocused).toBe(true); + expect(result.finallyFocused).toBe(false); + expect(result.streamIds).toContain(345); + expect(result.spokenTexts).toContain("Retained voice stream"); +}); diff --git a/tests/e2e/fixtures/tauri-mock.ts b/tests/e2e/fixtures/tauri-mock.ts index 7965ece87..2300a2aaa 100644 --- a/tests/e2e/fixtures/tauri-mock.ts +++ b/tests/e2e/fixtures/tauri-mock.ts @@ -41,6 +41,7 @@ export function buildInitScript(options?: { lines: string[]; errorMessage: string; }; + windowFocused?: boolean; }): string { const modelId = JSON.stringify(options?.modelId ?? "gpt-4.1"); const modelName = JSON.stringify(options?.modelId ?? "GPT-4.1"); @@ -143,6 +144,7 @@ export function buildInitScript(options?: { } } const AGENT_SETUP_FAILURE = ${agentSetupFailure}; + let windowFocused = ${JSON.stringify(options?.windowFocused ?? true)}; const DISTRO = { present: false, kgooseConfigured: false, @@ -320,16 +322,36 @@ export function buildInitScript(options?: { })(); const SKILL_SOURCES = SKILLS.map(skillToSourceEntry); const POCKET_VOICE_SPOKEN_TEXTS = []; + const SHOWN_COMPLETION_NOTIFICATIONS = []; + const COMPLETED_PROMPT_SESSION_IDS = []; + + // sessionId -> { promise, resolve } used to keep a session/prompt turn + // open until a test explicitly releases it. + const PROMPT_HOLDS = new Map(); const VOICE_STREAM_TEXTS = new Map(); let voiceSpeechId = 0; window.__GOOSE_E2E__ = { + completedPromptSessionIds: () => clone(COMPLETED_PROMPT_SESSION_IDS), + holdPrompt: (sessionId) => { + let resolve; + const promise = new Promise((r) => { + resolve = r; + }); + PROMPT_HOLDS.set(sessionId, { promise, resolve }); + }, + releasePrompt: (sessionId) => { + const hold = PROMPT_HOLDS.get(sessionId); + PROMPT_HOLDS.delete(sessionId); + hold?.resolve(); + }, acpRequests: () => clone(ACP_REQUESTS), completeAcpPrompts: () => { for (const [id, { socket, sessionId }] of PENDING_ACP_PROMPTS) { socket.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(jsonRpcResult(id, { stopReason: "end_turn" })), })); + COMPLETED_PROMPT_SESSION_IDS.push(sessionId); window.__GOOSE_E2E__.emitAcpNotification({ sessionId, update: { sessionUpdate: "session_info_update", _meta: { goose: { activeRunId: null } } }, @@ -357,6 +379,14 @@ export function buildInitScript(options?: { } }, emitTauriEvent, + getWindowFocused: () => windowFocused, + setWindowFocused: (focused) => { + windowFocused = focused; + emitTauriEvent(focused ? "tauri://focus" : "tauri://blur", null); + }, + shownCompletionNotifications: () => + clone(SHOWN_COMPLETION_NOTIFICATIONS), + tauriEventListenerCount: (event) => EVENT_LISTENERS.get(event)?.size ?? 0, pocketVoiceSpokenTexts: () => clone(POCKET_VOICE_SPOKEN_TEXTS), pocketVoiceStreamIds: () => [...VOICE_STREAM_TEXTS.keys()], }; @@ -559,6 +589,15 @@ export function buildInitScript(options?: { }; persistAgentSources(); } + const holdRelease = + PROMPT_HOLDS.get(message.params?.sessionId) ?? + PROMPT_HOLDS.get("*"); + if (holdRelease) { + // A test asked to hold this turn open; resolve when released. + return holdRelease.promise.then(() => + jsonRpcResult(message.id, { stopReason: "end_turn" }), + ); + } return jsonRpcResult(message.id, { stopReason: "end_turn" }); } case "_goose/providers/list": @@ -736,6 +775,7 @@ export function buildInitScript(options?: { queueMicrotask(() => { window.__GOOSE_E2E__.emitAcpNotification({ sessionId: session.sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "PRIVATE DRAFT: I would set the temperature to 10 degrees." } } }); this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(jsonRpcResult(message.id, { stopReason: "end_turn" })) })); + COMPLETED_PROMPT_SESSION_IDS.push(session.sessionId); }); return; } @@ -751,12 +791,19 @@ export function buildInitScript(options?: { if (!response) { return; } - queueMicrotask(() => { + // Responses may be promises (e.g. a held session/prompt) so tests + // can control when an agent turn finishes. + Promise.resolve(response).then((resolved) => { + if (!resolved) return; this.dispatchEvent( new MessageEvent("message", { - data: JSON.stringify(response), + data: JSON.stringify(resolved), }), ); + // Record only completed turns whose end_turn response was delivered. + if (message.method === "session/prompt" && resolved.result?.stopReason === "end_turn") { + COMPLETED_PROMPT_SESSION_IDS.push(message.params.sessionId); + } }); } @@ -982,6 +1029,13 @@ export function buildInitScript(options?: { }); case "list_session_windows": return Promise.resolve([]); + case "plugin:window|is_focused": + return Promise.resolve(windowFocused); + case "show_completion_notification": + SHOWN_COMPLETION_NOTIFICATIONS.push(args ?? {}); + return Promise.resolve(null); + case "should_suppress_completion_notification": + return Promise.resolve(false); case "plugin:window|is_fullscreen": return Promise.resolve(false); case "plugin:window|set_min_size": diff --git a/tests/e2e/notifications.spec.ts b/tests/e2e/notifications.spec.ts new file mode 100644 index 000000000..388041138 --- /dev/null +++ b/tests/e2e/notifications.spec.ts @@ -0,0 +1,272 @@ +/** + * Behavioral coverage for completion-notification delivery routing. + * + * These tests run against the browser Tauri IPC mock (tests/e2e/fixtures/ + * tauri-mock.ts): "native delivery" is observed as a captured + * `show_completion_notification` invoke, NOT as a real OS notification. + * Verifying the actual native notification surface requires a real Tauri + * runtime and is out of scope for this suite. + */ +import { test as base, expect, type Page } from "@playwright/test"; +import { buildInitScript } from "./fixtures/tauri-mock"; + +declare global { + interface Window { + __GOOSE_E2E__: { + emitTauriEvent: (event: string, payload: unknown) => void; + getWindowFocused: () => boolean; + setWindowFocused: (focused: boolean) => void; + shownCompletionNotifications: () => Array<{ + body?: string; + sessionId?: string; + sound?: unknown; + }>; + tauriEventListenerCount: (event: string) => number; + completedPromptSessionIds: () => string[]; + holdPrompt: (sessionId: string) => void; + releasePrompt: (sessionId: string) => void; + }; + } +} + +const test = base.extend<{ + notifyPage: Page; + windowFocused: boolean | undefined; + notificationPrefs: Record | null; +}>({ + windowFocused: [undefined, { option: true }], + notificationPrefs: [null, { option: true }], + notifyPage: async ({ page, windowFocused, notificationPrefs }, use) => { + await page.addInitScript({ + content: buildInitScript({ + ...(windowFocused === undefined ? {} : { windowFocused }), + // The default inventory configures only "claude" while the mocked + // _goose/defaults/read reports "openai", which trips the + // provider-setup-required home and disables the composer. Supply a + // configured openai entry so prompts can actually be sent. + providerInventory: [ + { + providerId: "openai", + providerName: "OpenAI", + description: "OpenAI provider", + defaultModel: "gpt-4.1", + configured: true, + providerType: "Preferred", + category: "model", + configKeys: [], + setupSteps: [], + supportsRefresh: true, + refreshing: false, + lastUpdatedAt: null, + lastRefreshAttemptAt: null, + lastRefreshError: null, + stale: false, + modelSelectionHint: null, + models: [ + { + id: "gpt-4.1", + name: "GPT-4.1", + family: "GPT", + recommended: true, + }, + ], + }, + ], + }), + }); + if (notificationPrefs) { + await page.addInitScript( + (prefs) => + window.localStorage.setItem( + "goose:notifications", + JSON.stringify(prefs), + ), + notificationPrefs, + ); + } + await use(page); + }, +}); + +async function waitForHome(page: Page) { + await expect(page.getByText("Jump to session")).toBeVisible({ + timeout: 10_000, + }); +} + +/** Wait until the hook's focus listener is registered so a blur event lands. */ +async function waitForFocusListener(page: Page) { + await expect + .poll(() => + page.evaluate(() => + window.__GOOSE_E2E__.tauriEventListenerCount("tauri://blur"), + ), + ) + .toBeGreaterThan(0); +} + +async function sendPromptFromHome(page: Page, text: string) { + const input = page.getByRole("textbox", { name: "Start a conversation" }); + await input.fill(text); + await input.press("Enter"); +} + +/** Require a delivered end_turn and the renderer leaving its running state. */ +async function completePrompt(page: Page, text: string) { + await page.evaluate(() => window.__GOOSE_E2E__.holdPrompt("*")); + await sendPromptFromHome(page, text); + const stop = page.getByRole("button", { + name: "Stop generation", + exact: true, + }); + await expect(stop).toBeVisible(); + await page.evaluate(() => window.__GOOSE_E2E__.releasePrompt("*")); + await expect + .poll( + () => + page.evaluate(() => window.__GOOSE_E2E__.completedPromptSessionIds()), + { message: "mocked turn delivered its end_turn completion" }, + ) + .toHaveLength(1); + await expect(stop).toHaveCount(0); +} + +function shownNotifications(page: Page) { + return page.evaluate(() => + window.__GOOSE_E2E__.shownCompletionNotifications(), + ); +} + +function queryMockedWindowFocus(page: Page) { + return page.evaluate(() => + ( + window.__TAURI_INTERNALS__ as { + invoke: (command: string, args?: unknown) => Promise; + } + ).invoke("plugin:window|is_focused", { label: "main" }), + ); +} + +test.describe("completion notification delivery (simulated Tauri)", () => { + test("shared Tauri mock reports focused by default", async ({ + notifyPage: page, + }) => { + await page.goto("/"); + + await expect.poll(() => queryMockedWindowFocus(page)).toBe(true); + expect( + await page.evaluate(() => window.__GOOSE_E2E__.getWindowFocused()), + ).toBe(true); + }); + + test("shared Tauri mock can switch focus to false", async ({ + notifyPage: page, + }) => { + await page.goto("/"); + await waitForHome(page); + await waitForFocusListener(page); + + await page.evaluate(() => window.__GOOSE_E2E__.setWindowFocused(false)); + + await expect.poll(() => queryMockedWindowFocus(page)).toBe(false); + expect( + await page.evaluate(() => window.__GOOSE_E2E__.getWindowFocused()), + ).toBe(false); + }); + test.describe("window starts backgrounded (seeded focus state)", () => { + test.use({ windowFocused: false }); + + test("routes a completion to native delivery exactly once with session metadata", async ({ + notifyPage: page, + }) => { + await page.goto("/"); + await waitForHome(page); + await sendPromptFromHome(page, "finish in background"); + + await expect.poll(() => shownNotifications(page)).toHaveLength(1); + const [shown] = await shownNotifications(page); + expect(shown.body).toBe("finish in background finished"); + expect(typeof shown.sessionId).toBe("string"); + expect(shown.sessionId?.length).toBeGreaterThan(0); + + // No in-app toast on the native path, and no duplicate native call. + await page.waitForTimeout(500); + await expect(page.getByText(/finished$/)).toHaveCount(0); + expect(await shownNotifications(page)).toHaveLength(1); + }); + }); + + test("blur event before completion routes to native delivery", async ({ + notifyPage: page, + }) => { + await page.goto("/"); + await waitForHome(page); + await waitForFocusListener(page); + await page.evaluate(() => { + window.__GOOSE_E2E__.holdPrompt("*"); + }); + await sendPromptFromHome(page, "background me"); + await page.evaluate(() => { + window.__GOOSE_E2E__.setWindowFocused(false); + window.__GOOSE_E2E__.releasePrompt("*"); + }); + + await expect.poll(() => shownNotifications(page)).toHaveLength(1); + await expect(page.getByText(/finished$/)).toHaveCount(0); + }); + + test("focused window viewing another surface shows the in-app toast instead", async ({ + notifyPage: page, + }) => { + await page.goto("/"); + await waitForHome(page); + await page.evaluate(() => { + window.__GOOSE_E2E__.holdPrompt("*"); + }); + await sendPromptFromHome(page, "long running turn"); + // Leave the session view while the turn is still running. + await page.getByTestId("nav-home").click(); + await waitForHome(page); + await page.evaluate(() => { + window.__GOOSE_E2E__.releasePrompt("*"); + }); + + await expect(page.getByText("long running turn finished")).toBeVisible(); + await expect( + page.getByRole("button", { name: "View", exact: true }), + ).toBeVisible(); + expect(await shownNotifications(page)).toHaveLength(0); + }); + + test("completion in the actively viewed focused session is suppressed on both channels", async ({ + notifyPage: page, + }) => { + await page.goto("/"); + await waitForHome(page); + await completePrompt(page, "watching this one"); + + // After proven completion, allow delayed delivery routing to fire if broken. + await page.waitForTimeout(1500); + await expect(page.getByText(/finished$/)).toHaveCount(0); + expect(await shownNotifications(page)).toHaveLength(0); + }); + + test.describe("notifications disabled", () => { + test.use({ + windowFocused: false, + notificationPrefs: { enabled: false }, + }); + + test("delivers nothing even for a background completion", async ({ + notifyPage: page, + }) => { + await page.goto("/"); + await waitForHome(page); + await completePrompt(page, "disabled background"); + + await page.waitForTimeout(1500); + expect(await shownNotifications(page)).toHaveLength(0); + await expect(page.getByText(/finished$/)).toHaveCount(0); + }); + }); +});