Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(frontend/copilot): remove the tab title counter and re-notify chats once opened (#15568)

Krzysztof Czerwinski1598d615cbdf
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts
index 1d0a90f2dd..f759c8414a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts
@@ -11,10 +11,8 @@ import {
import { IMPERSONATION_HEADER_NAME } from "@/lib/constants";
import {
COPILOT_COMPLETION_NOTIFICATION,
- ORIGINAL_TITLE,
deduplicateMessages,
extractSendMessageText,
- formatNotificationTitle,
getCopilotAuthHeaders,
extractSendMessageAttachments,
getSendSuppressionReason,
@@ -40,32 +38,6 @@ import { getSystemHeaders } from "@/lib/impersonation";
const mockGetWebSocketToken = vi.mocked(getWebSocketToken);
const mockGetSystemHeaders = vi.mocked(getSystemHeaders);
-describe("formatNotificationTitle", () => {
- it("returns base title when count is 0", () => {
- expect(formatNotificationTitle(0)).toBe(ORIGINAL_TITLE);
- });
-
- it("returns formatted title with count", () => {
- expect(formatNotificationTitle(3)).toBe(
- `(3) New activity - ${ORIGINAL_TITLE}`,
- );
- });
-
- it("returns base title for negative count", () => {
- expect(formatNotificationTitle(-1)).toBe(ORIGINAL_TITLE);
- });
-
- it("returns base title for NaN", () => {
- expect(formatNotificationTitle(NaN)).toBe(ORIGINAL_TITLE);
- });
-
- it("returns formatted title for count of 1", () => {
- expect(formatNotificationTitle(1)).toBe(
- `(1) New activity - ${ORIGINAL_TITLE}`,
- );
- });
-});
-
describe("hasVisibleAssistantContent", () => {
function assistant(parts: UIMessage["parts"]): UIMessage[] {
return [{ id: "a1", role: "assistant", parts }];
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotNotifications.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotNotifications.test.tsx
index 09183eefc5..6e23931d47 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotNotifications.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotNotifications.test.tsx
@@ -41,6 +41,17 @@ function makeWrapper() {
};
}
+function setVisibility(state: DocumentVisibilityState) {
+ Object.defineProperty(document, "visibilityState", {
+ configurable: true,
+ get: () => state,
+ });
+}
+
+function setFocused(focused: boolean) {
+ vi.spyOn(document, "hasFocus").mockReturnValue(focused);
+}
+
beforeEach(() => {
capturedHandler = null;
NotificationCtor.mockClear();
@@ -65,6 +76,7 @@ beforeEach(() => {
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
+ vi.restoreAllMocks();
});
describe("useCopilotNotifications — OS notification dispatch", () => {
@@ -109,3 +121,183 @@ describe("useCopilotNotifications — OS notification dispatch", () => {
});
});
});
+
+describe("useCopilotNotifications — opening a finished chat", () => {
+ it("takes the open chat off the finished list", async () => {
+ setVisibility("visible");
+ setFocused(true);
+ useCopilotUIStore.setState({
+ completedSessionIDs: new Set(["sess-1", "sess-2"]),
+ });
+
+ renderHook(() => useCopilotNotifications("sess-1"), {
+ wrapper: makeWrapper(),
+ });
+
+ await waitFor(() => {
+ expect(useCopilotUIStore.getState().completedSessionIDs).toEqual(
+ new Set(["sess-2"]),
+ );
+ });
+ });
+
+ it("notifies again for a chat's next finished turn once it has been opened", async () => {
+ const { rerender } = renderHook(
+ ({ active }: { active: string | null }) =>
+ useCopilotNotifications(active),
+ {
+ wrapper: makeWrapper(),
+ initialProps: { active: null as string | null },
+ },
+ );
+ const completion = {
+ type: "copilot_completion",
+ event: "session_completed",
+ session_id: "sess-1",
+ };
+
+ act(() => capturedHandler!(completion));
+ await waitFor(() => expect(NotificationCtor).toHaveBeenCalledTimes(1));
+
+ setVisibility("visible");
+ setFocused(true);
+ rerender({ active: "sess-1" });
+ await waitFor(() => {
+ expect(useCopilotUIStore.getState().completedSessionIDs.size).toBe(0);
+ });
+ rerender({ active: null });
+ setVisibility("hidden");
+
+ act(() => capturedHandler!(completion));
+ await waitFor(() => expect(NotificationCtor).toHaveBeenCalledTimes(2));
+ });
+});
+
+describe("useCopilotNotifications — background tabs", () => {
+ it("keeps the open chat on the finished list until its tab is visible", async () => {
+ useCopilotUIStore.setState({ completedSessionIDs: new Set(["sess-1"]) });
+
+ renderHook(() => useCopilotNotifications("sess-1"), {
+ wrapper: makeWrapper(),
+ });
+ await act(async () => {});
+
+ expect(useCopilotUIStore.getState().completedSessionIDs).toContain(
+ "sess-1",
+ );
+
+ setVisibility("visible");
+ setFocused(true);
+ act(() => {
+ document.dispatchEvent(new Event("visibilitychange"));
+ });
+
+ await waitFor(() => {
+ expect(useCopilotUIStore.getState().completedSessionIDs.size).toBe(0);
+ });
+ });
+});
+
+describe("useCopilotNotifications — unfocused windows", () => {
+ it("keeps the open chat on the finished list until its window has focus", async () => {
+ setVisibility("visible");
+ setFocused(false);
+ useCopilotUIStore.setState({ completedSessionIDs: new Set(["sess-1"]) });
+
+ renderHook(() => useCopilotNotifications("sess-1"), {
+ wrapper: makeWrapper(),
+ });
+ await act(async () => {});
+
+ expect(useCopilotUIStore.getState().completedSessionIDs).toContain(
+ "sess-1",
+ );
+
+ setFocused(true);
+ act(() => {
+ window.dispatchEvent(new Event("focus"));
+ });
+
+ await waitFor(() => {
+ expect(useCopilotUIStore.getState().completedSessionIDs.size).toBe(0);
+ });
+ });
+});
+
+describe("useCopilotNotifications — focus inside an iframe", () => {
+ it("does not notify for the open chat while the user works in an embedded frame", async () => {
+ setVisibility("visible");
+ // Focus moving into an iframe blurs the window but keeps document focus.
+ setFocused(true);
+ renderHook(() => useCopilotNotifications("sess-1"), {
+ wrapper: makeWrapper(),
+ });
+ act(() => {
+ window.dispatchEvent(new Event("blur"));
+ });
+
+ act(() => {
+ capturedHandler!({
+ type: "copilot_completion",
+ event: "session_completed",
+ session_id: "sess-1",
+ });
+ });
+ await act(async () => {});
+
+ expect(NotificationCtor).not.toHaveBeenCalled();
+ expect(useCopilotUIStore.getState().completedSessionIDs).not.toContain(
+ "sess-1",
+ );
+ });
+});
+
+describe("useCopilotNotifications — returning into an embedded frame", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("notices the user is back even when no focus event reaches the page", async () => {
+ vi.useFakeTimers();
+ setVisibility("visible");
+ setFocused(false);
+ useCopilotUIStore.setState({ completedSessionIDs: new Set(["sess-1"]) });
+ renderHook(() => useCopilotNotifications("sess-1"), {
+ wrapper: makeWrapper(),
+ });
+
+ // Focus returns straight into an iframe: the document has focus again,
+ // but neither "focus" nor "visibilitychange" fires here.
+ setFocused(true);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2_000);
+ });
+
+ expect(useCopilotUIStore.getState().completedSessionIDs.size).toBe(0);
+ });
+});
+
+describe("useCopilotNotifications — tab title", () => {
+ it("leaves the tab title alone when sessions finish", async () => {
+ document.title = "AutoPilot";
+ useCopilotUIStore.setState({
+ completedSessionIDs: new Set(["sess-old-1", "sess-old-2"]),
+ });
+ renderHook(() => useCopilotNotifications(null), { wrapper: makeWrapper() });
+
+ act(() => {
+ capturedHandler!({
+ type: "copilot_completion",
+ event: "session_completed",
+ session_id: "sess-3",
+ });
+ });
+
+ await waitFor(() => {
+ expect(useCopilotUIStore.getState().completedSessionIDs).toContain(
+ "sess-3",
+ );
+ });
+ expect(document.title).toBe("AutoPilot");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
index 29f170f080..2da968985f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
@@ -29,7 +29,6 @@ import { parseAsString, useQueryState } from "nuqs";
import { useEffect, useMemo, useRef, useState } from "react";
import { useStableCallback } from "@/hooks/useStableCallback";
import { useCopilotChatRuntimeStore } from "../../copilotChatRegistry";
-import { formatNotificationTitle } from "../../helpers";
import { fetchAndExportChat } from "../../helpers/exportChatAsMarkdown";
import { shouldShowSessionProcessingIndicator } from "../../sessionActivity";
import { useCopilotUIStore } from "../../store";
@@ -62,9 +61,6 @@ export function ChatSidebar() {
const isCollapsed = state === "collapsed";
const [sessionId, setSessionId] = useQueryState("sessionId", parseAsString);
const completedSessionIDs = useCopilotUIStore((s) => s.completedSessionIDs);
- const clearCompletedSession = useCopilotUIStore(
- (s) => s.clearCompletedSession,
- );
const openSearch = useGlobalSearchStore((state) => state.openSearch);
const closeSearch = useGlobalSearchStore((state) => state.closeSearch);
const isChatSearchEnabled = useGetFlag(Flag.CHAT_SEARCH);
@@ -187,14 +183,6 @@ export function ChatSidebar() {
});
}, [sessionId, queryClient]);
- // Clear completed indicator when navigating to a session (works for all paths)
- useEffect(() => {
- if (!sessionId || !completedSessionIDs.has(sessionId)) return;
- clearCompletedSession(sessionId);
- const remaining = Math.max(0, completedSessionIDs.size - 1);
- document.title = formatNotificationTitle(remaining);
- }, [sessionId, completedSessionIDs, clearCompletedSession]);
-
function handleNewChat() {
setSessionId(null);
// Without this the ?expertId= deep-link adoption in `useChatSession`
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
index 4655f882b6..dda131e25d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
@@ -8,8 +8,6 @@ import { parseSpecialMarkers } from "./helpers/messageMarkers";
import { WORKSPACE_FOLDER_PART_TYPE } from "./helpers/workspaceAttachments";
import { TURN_PAUSED_PART_TYPE } from "./turnPause";
-export const ORIGINAL_TITLE = "AutoGPT";
-
/**
* Title/body/icon for the OS-level notification fired when a copilot session
* completes. Kept in sync with the same copy hardcoded in `public/push-sw.js`
@@ -51,16 +49,6 @@ export class CopilotAuthError extends Error {
}
}
-/**
- * Build the document title showing how many sessions are ready.
- * Returns the base title when count is 0.
- */
-export function formatNotificationTitle(count: number): string {
- return count > 0
- ? `(${count}) New activity - ${ORIGINAL_TITLE}`
- : ORIGINAL_TITLE;
-}
-
/**
* Safely parse a JSON string (from localStorage) into a `Set<string>` of
* session IDs. Returns an empty set for `null`, malformed, or non-array values.
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts
index 22a2af23c5..4c2a576e5c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts
@@ -1,7 +1,7 @@
import { Key, storage } from "@/services/storage/local-storage";
import { create } from "zustand";
import { clearContentCache } from "./components/ArtifactPanel/components/useArtifactContent";
-import { ORIGINAL_TITLE, parseSessionIDs } from "./helpers";
+import { parseSessionIDs } from "./helpers";
export interface DeleteTarget {
id: string;
@@ -769,8 +769,5 @@ export const useCopilotUIStore = create<CopilotUIState>((set, get) => ({
copilotLlmAuth: null,
isDryRun: false,
});
- if (isClient) {
- document.title = ORIGINAL_TITLE;
- }
},
}));
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotNotifications.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotNotifications.ts
index a3057897d2..a788dedf47 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotNotifications.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotNotifications.ts
@@ -3,16 +3,12 @@ import type { WebSocketNotification } from "@/lib/autogpt-server-api/types";
import { Key } from "@/services/storage/local-storage";
import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef } from "react";
-import {
- COPILOT_COMPLETION_NOTIFICATION,
- ORIGINAL_TITLE,
- formatNotificationTitle,
- parseSessionIDs,
-} from "./helpers";
+import { COPILOT_COMPLETION_NOTIFICATION, parseSessionIDs } from "./helpers";
import { useCopilotUIStore } from "./store";
import { SESSION_LIST_QUERY_KEY } from "./useSessionList";
const NOTIFICATION_SOUND_PATH = "/notification.mp3";
+const SEEN_RECHECK_MS = 2_000;
/**
* Show a browser notification with click-to-navigate behaviour.
@@ -51,9 +47,17 @@ async function showBrowserNotification(
}
}
+// The user is here while the tab is visible and the document has focus. That
+// stays true while they work inside an embedded iframe, where a window blur
+// alone would say they had left. The handler and the clear effect share it so
+// they never disagree about the same moment.
+function isUserAway() {
+ return document.visibilityState === "hidden" || !document.hasFocus();
+}
+
/**
* Listens for copilot completion notifications via WebSocket.
- * Updates the Zustand store, plays a sound, and updates document.title.
+ * Updates the Zustand store and plays a sound.
*/
export function useCopilotNotifications(activeSessionID: string | null) {
const api = useBackendAPI();
@@ -61,19 +65,41 @@ export function useCopilotNotifications(activeSessionID: string | null) {
const audioRef = useRef<HTMLAudioElement | null>(null);
const activeSessionRef = useRef(activeSessionID);
activeSessionRef.current = activeSessionID;
- const windowFocusedRef = useRef(true);
+ const completedSessionIDs = useCopilotUIStore((s) => s.completedSessionIDs);
+
+ // Seeing a finished chat takes it off the list. The handler below skips
+ // chats already on it, so a chat left there never notifies again. Only a
+ // tab the user is in counts: the list is shared across tabs, so a tab that
+ // merely has the chat open must not mark it seen for the others.
+ useEffect(() => {
+ function clearIfSeen() {
+ if (isUserAway()) return;
+ if (!activeSessionID || !completedSessionIDs.has(activeSessionID)) return;
+ useCopilotUIStore.getState().clearCompletedSession(activeSessionID);
+ }
+
+ clearIfSeen();
+ document.addEventListener("visibilitychange", clearIfSeen);
+ window.addEventListener("focus", clearIfSeen);
+ // Coming back by clicking straight into an embedded frame (the desktop
+ // preview) fires no event in this document, so re-check while the open
+ // chat is still on the list. Clearing it ends the interval.
+ const recheck =
+ activeSessionID && completedSessionIDs.has(activeSessionID)
+ ? window.setInterval(clearIfSeen, SEEN_RECHECK_MS)
+ : undefined;
+ return () => {
+ document.removeEventListener("visibilitychange", clearIfSeen);
+ window.removeEventListener("focus", clearIfSeen);
+ window.clearInterval(recheck);
+ };
+ }, [activeSessionID, completedSessionIDs]);
- // Pre-load audio element and sync document title with persisted state
useEffect(() => {
if (typeof window === "undefined") return;
const audio = new Audio(NOTIFICATION_SOUND_PATH);
audio.volume = 0.5;
audioRef.current = audio;
-
- const count = useCopilotUIStore.getState().completedSessionIDs.size;
- if (count > 0) {
- document.title = formatNotificationTitle(count);
- }
}, []);
// Listen for WebSocket notifications
@@ -88,19 +114,16 @@ export function useCopilotNotifications(activeSessionID: string | null) {
const state = useCopilotUIStore.getState();
const isActiveSession = sessionID === activeSessionRef.current;
- const isUserAway =
- document.visibilityState === "hidden" || !windowFocusedRef.current;
+ const userAway = isUserAway();
// Skip if viewing the active session and it's in focus
- if (isActiveSession && !isUserAway) return;
+ if (isActiveSession && !userAway) return;
// Skip if we already notified for this session (e.g. WS replay)
if (state.completedSessionIDs.has(sessionID)) return;
// Always update UI state (checkmark + title) regardless of notification setting
state.addCompletedSession(sessionID);
- const count = useCopilotUIStore.getState().completedSessionIDs.size;
- document.title = formatNotificationTitle(count);
// Sound and browser notifications are gated by the user setting
if (!state.isNotificationsEnabled) return;
@@ -114,7 +137,7 @@ export function useCopilotNotifications(activeSessionID: string | null) {
if (
typeof Notification !== "undefined" &&
Notification.permission === "granted" &&
- isUserAway
+ userAway
) {
showBrowserNotification(COPILOT_COMPLETION_NOTIFICATION.title, {
body: COPILOT_COMPLETION_NOTIFICATION.body,
@@ -130,36 +153,6 @@ export function useCopilotNotifications(activeSessionID: string | null) {
};
}, [api]);
- // Track window focus for browser notifications when app is in background
- useEffect(() => {
- function handleFocus() {
- windowFocusedRef.current = true;
- if (useCopilotUIStore.getState().completedSessionIDs.size === 0) {
- document.title = ORIGINAL_TITLE;
- }
- }
- function handleBlur() {
- windowFocusedRef.current = false;
- }
- function handleVisibilityChange() {
- if (
- document.visibilityState === "visible" &&
- useCopilotUIStore.getState().completedSessionIDs.size === 0
- ) {
- document.title = ORIGINAL_TITLE;
- }
- }
-
- window.addEventListener("focus", handleFocus);
- window.addEventListener("blur", handleBlur);
- document.addEventListener("visibilitychange", handleVisibilityChange);
- return () => {
- window.removeEventListener("focus", handleFocus);
- window.removeEventListener("blur", handleBlur);
- document.removeEventListener("visibilitychange", handleVisibilityChange);
- };
- }, []);
-
// Sync completedSessionIDs across tabs via localStorage storage events
useEffect(() => {
function handleStorage(e: StorageEvent) {
@@ -168,7 +161,6 @@ export function useCopilotNotifications(activeSessionID: string | null) {
// additions (new completions) and removals (cleared sessions) propagate.
const next = parseSessionIDs(e.newValue);
useCopilotUIStore.setState({ completedSessionIDs: next });
- document.title = formatNotificationTitle(next.size);
// Refetch the session list so the sidebar reflects the latest
// is_processing state (avoids stale spinner after cross-tab clear).