π OpenHands: AI-Driven Development
Show agent state emoji prefix in browser tab title (#236)
Robert Brennane3ca6e6f776f
diff --git a/__tests__/hooks/use-agent-notification.test.ts b/__tests__/hooks/use-agent-notification.test.tsindex 28cf36b88d..b84d914f38 100644--- a/__tests__/hooks/use-agent-notification.test.ts+++ b/__tests__/hooks/use-agent-notification.test.ts@@ -1,8 +1,7 @@import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";-import { renderHook, act } from "@testing-library/react";+import { renderHook } from "@testing-library/react";import { useAgentNotification } from "#/hooks/use-agent-notification";import { AgentState } from "#/types/agent-state";-import * as browserTabModule from "#/utils/browser-tab";// Mock useSettings to control the sound notification settingvi.mock("#/hooks/query/use-settings", () => ({@@ -11,10 +10,6 @@ vi.mock("#/hooks/query/use-settings", () => ({}),}));-// Spy on browserTab methods-vi.spyOn(browserTabModule.browserTab, "startNotification");-vi.spyOn(browserTabModule.browserTab, "stopNotification");-// Mock Audioconst mockPlay = vi.fn().mockResolvedValue(undefined);const mockAudio = {@@ -38,34 +33,10 @@ describe("useAgentNotification", () => {beforeEach(() => {vi.useFakeTimers();vi.clearAllMocks();- // Simulate tab not focused- Object.defineProperty(document, "hasFocus", {- value: () => false,- configurable: true,- });});afterEach(() => {vi.useRealTimers();- // Restore hasFocus- Object.defineProperty(document, "hasFocus", {- value: () => true,- configurable: true,- });- });-- it("starts browser tab notification when agent reaches FINISHED state and tab is not focused", () => {- const { rerender } = renderHook(- ({ state }) => useAgentNotification(state),- { initialProps: { state: AgentState.RUNNING } },- );-- // Transition to FINISHED- rerender({ state: AgentState.FINISHED });-- expect(- browserTabModule.browserTab.startNotification,- ).toHaveBeenCalledTimes(1);});it("plays notification sound when agent reaches FINISHED state and sound is enabled", () => {@@ -74,27 +45,23 @@ describe("useAgentNotification", () => {{ initialProps: { state: AgentState.RUNNING } },);- // Transition to FINISHEDrerender({ state: AgentState.FINISHED });expect(mockPlay).toHaveBeenCalledTimes(1);});- it("starts notification when agent reaches AWAITING_USER_INPUT state", () => {+ it("plays notification sound when agent reaches AWAITING_USER_INPUT state", () => {const { rerender } = renderHook(({ state }) => useAgentNotification(state),{ initialProps: { state: AgentState.RUNNING } },);- // Transition to AWAITING_USER_INPUTrerender({ state: AgentState.AWAITING_USER_INPUT });- expect(- browserTabModule.browserTab.startNotification,- ).toHaveBeenCalledTimes(1);+ expect(mockPlay).toHaveBeenCalledTimes(1);});- it("starts notification when agent reaches AWAITING_USER_CONFIRMATION state", () => {+ it("plays notification sound when agent reaches AWAITING_USER_CONFIRMATION state", () => {const { rerender } = renderHook(({ state }) => useAgentNotification(state),{ initialProps: { state: AgentState.RUNNING } },@@ -102,46 +69,6 @@ describe("useAgentNotification", () => {rerender({ state: AgentState.AWAITING_USER_CONFIRMATION });- expect(- browserTabModule.browserTab.startNotification,- ).toHaveBeenCalledTimes(1);- });-- it("stops browser tab notification when window gains focus", () => {- const { rerender } = renderHook(- ({ state }) => useAgentNotification(state),- { initialProps: { state: AgentState.RUNNING } },- );-- rerender({ state: AgentState.FINISHED });-- // Simulate window focus- act(() => {- window.dispatchEvent(new Event("focus"));- });-- expect(- browserTabModule.browserTab.stopNotification,- ).toHaveBeenCalledTimes(1);- });-- it("does not start tab flash when focused, but still plays sound", () => {- Object.defineProperty(document, "hasFocus", {- value: () => true,- configurable: true,- });-- const { rerender } = renderHook(- ({ state }) => useAgentNotification(state),- { initialProps: { state: AgentState.RUNNING } },- );-- rerender({ state: AgentState.FINISHED });-- expect(- browserTabModule.browserTab.startNotification,- ).not.toHaveBeenCalled();- // Sound still plays when focused (completion chime UX pattern)expect(mockPlay).toHaveBeenCalledTimes(1);});@@ -174,9 +101,6 @@ describe("useAgentNotification", () => {rerender({ state: AgentState.RUNNING });- expect(- browserTabModule.browserTab.startNotification,- ).not.toHaveBeenCalled();expect(mockPlay).not.toHaveBeenCalled();});});diff --git a/__tests__/utils/agent-state-emoji.test.ts b/__tests__/utils/agent-state-emoji.test.tsnew file mode 100644index 0000000000..eb304621de--- /dev/null+++ b/__tests__/utils/agent-state-emoji.test.ts@@ -0,0 +1,23 @@+import { describe, it, expect } from "vitest";++import { getAgentStateEmoji } from "#/utils/agent-state-emoji";+import { ExecutionStatus } from "#/types/agent-server/core/base/common";++describe("getAgentStateEmoji", () => {+ it.each([+ [ExecutionStatus.RUNNING, "π’"],+ [ExecutionStatus.FINISHED, "β "],+ [ExecutionStatus.IDLE, "β "],+ [ExecutionStatus.WAITING_FOR_CONFIRMATION, "β "],+ [ExecutionStatus.PAUSED, "βͺ"],+ [ExecutionStatus.ERROR, "π΄"],+ [ExecutionStatus.STUCK, "π΄"],+ ])("returns %s for execution status %s", (status, emoji) => {+ expect(getAgentStateEmoji(status)).toBe(emoji);+ });++ it("returns null for an unknown / missing status", () => {+ expect(getAgentStateEmoji(null)).toBeNull();+ expect(getAgentStateEmoji(undefined)).toBeNull();+ });+});diff --git a/__tests__/utils/browser-tab.test.ts b/__tests__/utils/browser-tab.test.tsdeleted file mode 100644index f133e431cf..0000000000--- a/__tests__/utils/browser-tab.test.ts+++ /dev/null@@ -1,77 +0,0 @@-import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";--import { browserTab } from "#/utils/browser-tab";--// These tests exercise the browser-tab notification flasher behavior.-// Specifically we verify that when the document title changes externally-// while a notification is active, the flasher updates its internal-// baseline so it restores/toggles to the new title instead of an old one.--describe("browserTab notifications", () => {- const MESSAGE = "Agent ready";- const INITIAL = "Conversation 123 | OpenHands";- const RENAMED = "My renamed title | OpenHands";-- beforeEach(() => {- vi.useFakeTimers();- // reset title for each test- document.title = INITIAL;- });-- afterEach(() => {- browserTab.stopNotification();- vi.runOnlyPendingTimers();- vi.useRealTimers();- });-- it("flashes the browser tab title between the original title and the notification message", () => {- browserTab.startNotification(MESSAGE);-- // First tick: should switch to the notification message- vi.advanceTimersByTime(1000);- expect(document.title).toBe(MESSAGE);-- // Next tick: should switch back to original- vi.advanceTimersByTime(1000);- expect(document.title).toBe(INITIAL);-- // Next tick: should switch to message again- vi.advanceTimersByTime(1000);- expect(document.title).toBe(MESSAGE);- });-- it("stops flashing and restores original title when stopNotification is called", () => {- browserTab.startNotification(MESSAGE);-- vi.advanceTimersByTime(1000);- expect(document.title).toBe(MESSAGE);-- browserTab.stopNotification();- expect(document.title).toBe(INITIAL);- });-- it("updates baseline when title changes during an active notification and restores to the new title", () => {- // Start flashing- browserTab.startNotification(MESSAGE);-- // Tick once: should switch to the message- vi.advanceTimersByTime(1000);- expect(document.title).toBe(MESSAGE);-- // Simulate an external rename while flashing (e.g., user edits title)- document.title = RENAMED;-- // Next tick: flasher observes the external change and updates baseline- vi.advanceTimersByTime(1000);- // On this tick, we toggle back to the message- expect(document.title).toBe(MESSAGE);-- // Next tick should toggle to the updated baseline (renamed title)- vi.advanceTimersByTime(1000);- expect(document.title).toBe(RENAMED);-- // Stop flashing: title should remain the updated baseline- browserTab.stopNotification();- expect(document.title).toBe(RENAMED);- });-});diff --git a/src/hooks/use-agent-notification.ts b/src/hooks/use-agent-notification.tsindex 38ea1fd2f7..8cc8566e74 100644--- a/src/hooks/use-agent-notification.ts+++ b/src/hooks/use-agent-notification.ts@@ -1,9 +1,6 @@import { useEffect, useRef } from "react";-import { useTranslation } from "react-i18next";import { AgentState } from "#/types/agent-state";-import { browserTab } from "#/utils/browser-tab";import { useSettings } from "#/hooks/query/use-settings";-import { AGENT_STATUS_MAP } from "#/utils/status";import notificationSound from "#/assets/notification.mp3";const NOTIFICATION_STATES: AgentState[] = [@@ -13,16 +10,13 @@ const NOTIFICATION_STATES: AgentState[] = [];/**- * Hook that triggers browser tab flashing and notification sound- * when the agent transitions into a state that requires user attention.- *- * - Flashes the browser tab title when the tab is not focused.- * - Plays a notification sound if enabled in settings.- * - Stops flashing when the user focuses the tab.+ * Hook that plays a notification sound when the agent transitions into a+ * state that requires user attention. The browser tab title itself is+ * managed by `useAppTitle`, which prefixes the title with an emoji that+ * reflects the current agent state.*/export function useAgentNotification(curAgentState: AgentState) {const { data: settings } = useSettings();- const { t } = useTranslation("openhands");const audioRef = useRef<HTMLAudioElement | undefined>(undefined);const prevStateRef = useRef<AgentState | undefined>(undefined);@@ -51,26 +45,5 @@ export function useAgentNotification(curAgentState: AgentState) {// Ignore autoplay errors (browsers may block autoplay)});}-- if (typeof document !== "undefined" && !document.hasFocus()) {- const i18nKey = AGENT_STATUS_MAP[curAgentState];- const message = i18nKey ? t(i18nKey) : curAgentState;- browserTab.startNotification(message);- }- }, [curAgentState, isSoundEnabled, t]);-- // Stop tab notification when window gains focus- useEffect(() => {- if (typeof window === "undefined") return undefined;-- const handleFocus = () => {- browserTab.stopNotification();- };-- window.addEventListener("focus", handleFocus);- return () => {- window.removeEventListener("focus", handleFocus);- browserTab.stopNotification();- };- }, []);+ }, [curAgentState, isSoundEnabled]);}diff --git a/src/hooks/use-app-title.test.tsx b/src/hooks/use-app-title.test.tsxindex 5751b7d6ec..660ead070b 100644--- a/src/hooks/use-app-title.test.tsx+++ b/src/hooks/use-app-title.test.tsx@@ -4,6 +4,8 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { useParams } from "react-router";import { useUserConversation } from "./query/use-user-conversation";import { useAppTitle } from "./use-app-title";+import { useConversationStateStore } from "#/stores/conversation-state-store";+import { ExecutionStatus } from "#/types/agent-server/core/base/common";const renderAppTitleHook = () =>renderHook(() => useAppTitle(), {@@ -31,6 +33,7 @@ describe("useAppTitle", () => {// @ts-expect-error - only returning partial config for testmockUseUserConversation.mockReturnValue({ data: null });mockUseParams.mockReturnValue({});+ useConversationStateStore.getState().reset();});it("returns the OSS app title outside conversations", async () => {@@ -62,4 +65,61 @@ describe("useAppTitle", () => {await waitFor(() => expect(result.current).toBe("OpenHands"));});++ it.each([+ [ExecutionStatus.RUNNING, "π’"],+ [ExecutionStatus.FINISHED, "β "],+ [ExecutionStatus.IDLE, "β "],+ [ExecutionStatus.WAITING_FOR_CONFIRMATION, "β "],+ [ExecutionStatus.PAUSED, "βͺ"],+ [ExecutionStatus.ERROR, "π΄"],+ [ExecutionStatus.STUCK, "π΄"],+ ])(+ "prefixes the title with %s emoji for execution status %s",+ async (status, emoji) => {+ mockUseParams.mockReturnValue({ conversationId: "123" });+ mockUseUserConversation.mockReturnValue({+ // @ts-expect-error - only returning partial config for test+ data: { title: "My Conversation" },+ });+ useConversationStateStore.getState().setExecutionStatus(status);++ const { result } = renderAppTitleHook();++ await waitFor(() =>+ expect(result.current).toBe(`${emoji} My Conversation | OpenHands`),+ );+ },+ );++ it("falls back to the conversation's execution_status when the live store is empty", async () => {+ mockUseParams.mockReturnValue({ conversationId: "123" });+ mockUseUserConversation.mockReturnValue({+ // @ts-expect-error - only returning partial config for test+ data: {+ title: "My Conversation",+ execution_status: ExecutionStatus.RUNNING,+ },+ });++ const { result } = renderAppTitleHook();++ await waitFor(() =>+ expect(result.current).toBe("π’ My Conversation | OpenHands"),+ );+ });++ it("does not add an emoji when in a conversation but execution status is unknown", async () => {+ mockUseParams.mockReturnValue({ conversationId: "123" });+ mockUseUserConversation.mockReturnValue({+ // @ts-expect-error - only returning partial config for test+ data: { title: "My Conversation" },+ });++ const { result } = renderAppTitleHook();++ await waitFor(() =>+ expect(result.current).toBe("My Conversation | OpenHands"),+ );+ });});diff --git a/src/hooks/use-app-title.ts b/src/hooks/use-app-title.tsindex 37b2b03548..5f1f956070 100644--- a/src/hooks/use-app-title.ts+++ b/src/hooks/use-app-title.ts@@ -1,16 +1,30 @@import { useParams } from "react-router";import { useUserConversation } from "#/hooks/query/use-user-conversation";+import { useConversationStateStore } from "#/stores/conversation-state-store";+import { getAgentStateEmoji } from "#/utils/agent-state-emoji";const APP_TITLE = "OpenHands";export const useAppTitle = () => {const { conversationId } = useParams<{ conversationId: string }>();const { data: conversation } = useUserConversation(conversationId ?? null);+ const liveExecutionStatus = useConversationStateStore(+ (state) => state.execution_status,+ );+const conversationTitle = conversation?.title;+ const baseTitle =+ conversationId && conversationTitle+ ? `${conversationTitle} | ${APP_TITLE}`+ : APP_TITLE;- if (conversationId && conversationTitle) {- return `${conversationTitle} | ${APP_TITLE}`;+ if (!conversationId) {+ return baseTitle;}- return APP_TITLE;+ const executionStatus =+ liveExecutionStatus ?? conversation?.execution_status ?? null;+ const emoji = getAgentStateEmoji(executionStatus);++ return emoji ? `${emoji} ${baseTitle}` : baseTitle;};diff --git a/src/utils/agent-state-emoji.ts b/src/utils/agent-state-emoji.tsnew file mode 100644index 0000000000..fffb0877a4--- /dev/null+++ b/src/utils/agent-state-emoji.ts@@ -0,0 +1,32 @@+import { ExecutionStatus } from "#/types/agent-server/core/base/common";++/**+ * Maps a conversation's execution status to a single emoji that visually+ * conveys the agent's state in the browser tab title.+ *+ * β green check β agent finished or is otherwise waiting on the user+ * π’ green circle β agent is actively running+ * βͺ gray circle β agent is paused/stopped+ * π΄ red circle β agent is in an error state+ *+ * Returns null when the status is unknown so callers can omit the prefix.+ */+export function getAgentStateEmoji(+ status: ExecutionStatus | null | undefined,+): string | null {+ switch (status) {+ case ExecutionStatus.RUNNING:+ return "π’";+ case ExecutionStatus.FINISHED:+ case ExecutionStatus.IDLE:+ case ExecutionStatus.WAITING_FOR_CONFIRMATION:+ return "β ";+ case ExecutionStatus.PAUSED:+ return "βͺ";+ case ExecutionStatus.ERROR:+ case ExecutionStatus.STUCK:+ return "π΄";+ default:+ return null;+ }+}diff --git a/src/utils/browser-tab.ts b/src/utils/browser-tab.tsdeleted file mode 100644index f08d9656ee..0000000000--- a/src/utils/browser-tab.ts+++ /dev/null@@ -1,42 +0,0 @@-let originalTitle = "";-let titleInterval: number | undefined;--const isBrowser =- typeof window !== "undefined" && typeof document !== "undefined";--export const browserTab = {- startNotification(message: string) {- if (!isBrowser) return;-- // Always capture the current title as the baseline to restore to- originalTitle = document.title;-- // Clear any existing interval- if (titleInterval) {- this.stopNotification();- }-- // Alternate between the latest baseline title and the notification message.- // If the title changes externally (e.g., user renames conversation),- // update the baseline so we restore to the new value when stopping.- titleInterval = window.setInterval(() => {- const current = document.title;- if (current !== originalTitle && current !== message) {- originalTitle = current;- }- document.title = current === message ? originalTitle : message;- }, 1000);- },-- stopNotification() {- if (!isBrowser) return;-- if (titleInterval) {- window.clearInterval(titleInterval);- titleInterval = undefined;- }- if (originalTitle) {- document.title = originalTitle;- }- },-};