🙌 OpenHands: AI-Driven Development
fix(chat): toast on bare /btw and offer Resume only on the latest goal status (#18036)
Engel Nysta547bf4a7655
diff --git a/__tests__/components/features/chat/goal-status-content.test.tsx b/__tests__/components/features/chat/goal-status-content.test.tsxindex 903d02d63c..1df01fd109 100644--- a/__tests__/components/features/chat/goal-status-content.test.tsx+++ b/__tests__/components/features/chat/goal-status-content.test.tsx@@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { GoalStatusContent } from "#/components/features/chat/goal-status-content";import { useGoalStore } from "#/stores/goal-store";+import { useEventStore, type OHEvent } from "#/stores/use-event-store";import type { GoalStatus } from "#/types/agent-server/core/events/conversation-state-event";const stopGoal = vi.fn();@@ -32,6 +33,16 @@ const status = (overrides: Partial<GoalStatus> = {}): GoalStatus =>...overrides,}) as GoalStatus;+const goalEvent = (id: string, timestamp: string, value: GoalStatus): OHEvent =>+ ({+ id,+ kind: "ConversationStateUpdateEvent",+ timestamp,+ source: "environment",+ key: "goal",+ value,+ }) as unknown as OHEvent;+describe("GoalStatusContent loop controls", () => {beforeEach(() => {vi.clearAllMocks();@@ -39,6 +50,7 @@ describe("GoalStatusContent loop controls", () => {resumeGoal.mockResolvedValue(undefined);pauseConversation.mockResolvedValue(undefined);useGoalStore.setState({ statusByConversation: {} });+ useEventStore.getState().clearEvents();});it("Stop cancels the loop and interrupts the agent on an active goal", async () => {@@ -75,4 +87,49 @@ describe("GoalStatusContent loop controls", () => {expect(screen.queryByTestId("goal-stop")).toBeNull();expect(screen.queryByTestId("goal-resume")).toBeNull();});++ describe("superseded interrupted rows", () => {+ const interrupted = status({ status: "interrupted", iteration: 0 });++ it("offers Resume only on the latest goal status", () => {+ useEventStore+ .getState()+ .addEvents([+ goalEvent("goal-old", "2026-01-01T00:00:00Z", interrupted),+ goalEvent("goal-new", "2026-01-01T00:01:00Z", interrupted),+ ]);++ const { unmount } = render(+ <GoalStatusContent status={interrupted} eventId="goal-old" />,+ );+ expect(screen.queryByTestId("goal-resume")).toBeNull();+ unmount();++ render(<GoalStatusContent status={interrupted} eventId="goal-new" />);+ expect(screen.getByTestId("goal-resume")).toBeInTheDocument();+ });++ it.each([+ [+ "still running (e.g. after a reload)",+ { active: true, status: "running" },+ ],+ ["capped", { status: "capped", iteration: 2 }],+ ["complete", { status: "complete", iteration: 1 }],+ ] as const)(+ "hides Resume once the resumed goal is %s, with no live loop in the goal store",+ (_label, later) => {+ useEventStore+ .getState()+ .addEvents([+ goalEvent("goal-old", "2026-01-01T00:00:00Z", interrupted),+ goalEvent("goal-new", "2026-01-01T00:01:00Z", status(later)),+ ]);++ render(<GoalStatusContent status={interrupted} eventId="goal-old" />);++ expect(screen.queryByTestId("goal-resume")).toBeNull();+ },+ );+ });});diff --git a/__tests__/hooks/chat/use-btw-interceptor.test.ts b/__tests__/hooks/chat/use-btw-interceptor.test.tsindex f42696e970..bb68dea038 100644--- a/__tests__/hooks/chat/use-btw-interceptor.test.ts+++ b/__tests__/hooks/chat/use-btw-interceptor.test.ts@@ -7,9 +7,17 @@ const mockAskAgent = vi.hoisted(() =>vi.fn<(id: string, q: string) => Promise<{ response: string }>>(),);+const mockDisplayErrorToast = vi.hoisted(() => vi.fn());+vi.mock("#/hooks/mutation/conversation-mutation-utils", () => ({askAgent: (id: string, q: string) => mockAskAgent(id, q),}));+vi.mock("#/utils/custom-toast-handlers", () => ({+ displayErrorToast: (message: string) => mockDisplayErrorToast(message),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));const CONV = "conv-1";const entries = () => useBtwStore.getState().entriesByConversation[CONV] ?? [];@@ -18,6 +26,7 @@ describe("useBtwInterceptor", () => {beforeEach(() => {useBtwStore.setState({ entriesByConversation: {} });mockAskAgent.mockReset();+ mockDisplayErrorToast.mockReset();});it("falls through to onSubmit for non-/btw messages", () => {@@ -47,6 +56,23 @@ describe("useBtwInterceptor", () => {});});+ it.each(["/btw", "/btw ", " /btw "])(+ "toasts and asks nothing for a bare %j (no question)",+ (message) => {+ const onSubmit = vi.fn();+ const { result } = renderHook(() => useBtwInterceptor(CONV, onSubmit));++ act(() => result.current(message));++ expect(mockDisplayErrorToast).toHaveBeenCalledWith(+ "CHAT_INTERFACE$BTW_QUESTION_REQUIRED",+ );+ expect(mockAskAgent).not.toHaveBeenCalled();+ expect(onSubmit).not.toHaveBeenCalled();+ expect(entries()).toEqual([]);+ },+ );+it("marks the entry as error when askAgent rejects", async () => {mockAskAgent.mockRejectedValueOnce(new Error("boom"));const { result } = renderHook(() => useBtwInterceptor(CONV, vi.fn()));diff --git a/src/components/conversation-events/chat/event-message.tsx b/src/components/conversation-events/chat/event-message.tsxindex 431f93fa53..5e6fac8a6f 100644--- a/src/components/conversation-events/chat/event-message.tsx+++ b/src/components/conversation-events/chat/event-message.tsx@@ -217,7 +217,7 @@ function EventMessageComponent({isConversationStateUpdateEvent(event) &&isGoalConversationStateUpdateEvent(event)) {- return <GoalStatusContent status={event.value} />;+ return <GoalStatusContent status={event.value} eventId={event.id} />;}// Agent error eventsdiff --git a/src/components/features/chat/goal-status-content.tsx b/src/components/features/chat/goal-status-content.tsxindex 5c64422a2f..d3515815cb 100644--- a/src/components/features/chat/goal-status-content.tsx+++ b/src/components/features/chat/goal-status-content.tsx@@ -5,6 +5,11 @@ import XCircle from "#/icons/x-circle-solid.svg?react";import { I18nKey } from "#/i18n/declaration";import { GoalStatus } from "#/types/agent-server/core/events/conversation-state-event";import { useGoalStore } from "#/stores/goal-store";+import { useEventStore, type OHEvent } from "#/stores/use-event-store";+import {+ isConversationStateUpdateEvent,+ isGoalConversationStateUpdateEvent,+} from "#/types/agent-server/type-guards";import { useOptionalConversationId } from "#/hooks/use-conversation-id";import {pauseConversation,@@ -26,6 +31,20 @@ const STATUS_LABEL_KEY: Record<GoalStatus["status"], I18nKey> = {interrupted: I18nKey.GOAL$STATUS_INTERRUPTED,};+/** Id of the newest goal status event in the (timestamp-sorted) event list. */+const findLatestGoalEventId = (events: OHEvent[]): string | undefined => {+ for (let i = events.length - 1; i >= 0; i -= 1) {+ const event = events[i];+ if (+ isConversationStateUpdateEvent(event) &&+ isGoalConversationStateUpdateEvent(event)+ ) {+ return event.id;+ }+ }+ return undefined;+};+/*** Goal-status row: objective, round count, status word, the judge's score, the* judge's "missing" note (expandable), and an indicator — spinner while running,@@ -35,15 +54,25 @@ const STATUS_LABEL_KEY: Record<GoalStatus["status"], I18nKey> = {* Also exposes the loop controls at the end of the row: a Stop button while the* loop is active and a Resume button once it is interrupted. Stop both cancels* the loop (`stopGoal`) and interrupts the conversation, because the backend's- * stop deliberately leaves the in-flight agent turn running.+ * stop deliberately leaves the in-flight agent turn running. Only the latest+ * goal status offers Resume: the backend resumes the conversation's last goal,+ * so an interrupted row that a later goal status superseded has nothing left to+ * resume (it answers `no_resumable_goal`).** Used in two places: the live bottom banner (GoalStatusBanner) while a loop is* active, and inline in the message timeline for the terminal status, so a* finished `/goal` settles into the conversation. Because the inline copy mounts* fresh once terminal, `initiallyExpanded={!active}` expands the note there- * without any re-mount trickery.+ * without any re-mount trickery. Inline rows pass their `eventId` so a row can+ * tell whether a later goal status superseded it.*/-export function GoalStatusContent({ status }: { status: GoalStatus }) {+export function GoalStatusContent({+ status,+ eventId,+}: {+ status: GoalStatus;+ eventId?: string;+}) {const { t } = useTranslation("openhands");const { conversationId } = useOptionalConversationId();// Whether *some* goal loop is currently live for this conversation. Used to@@ -54,6 +83,12 @@ export function GoalStatusContent({ status }: { status: GoalStatus }) {? Boolean(s.statusByConversation[conversationId]?.active): false,);+ // Read from the event list rather than the goal store: the store is only fed+ // by live WebSocket events, so after a reload it is empty while the history+ // (REST) still holds the newer running/capped/complete status.+ const isLatestGoalStatus = useEventStore(+ (s) => eventId === undefined || findLatestGoalEventId(s.events) === eventId,+ );const [pending, setPending] = useState(false);const {active,@@ -110,7 +145,12 @@ export function GoalStatusContent({ status }: { status: GoalStatus }) {{t(I18nKey.GOAL$STOP)}</button>);- } else if (conversationId && status.status === "interrupted" && !goalActive) {+ } else if (+ conversationId &&+ status.status === "interrupted" &&+ isLatestGoalStatus &&+ !goalActive+ ) {actionButton = (<buttontype="button"diff --git a/src/hooks/chat/use-btw-interceptor.ts b/src/hooks/chat/use-btw-interceptor.tsindex 89fdfb2b98..cdbce2a644 100644--- a/src/hooks/chat/use-btw-interceptor.ts+++ b/src/hooks/chat/use-btw-interceptor.ts@@ -1,6 +1,9 @@import { useCallback } from "react";+import { useTranslation } from "react-i18next";import { askAgent } from "#/hooks/mutation/conversation-mutation-utils";import { useBtwStore } from "#/stores/btw-store";+import { displayErrorToast } from "#/utils/custom-toast-handlers";+import { I18nKey } from "#/i18n/declaration";import { BTW_COMMAND } from "#/utils/constants";const BTW_PREFIX = `${BTW_COMMAND} `;@@ -14,6 +17,7 @@ export const useBtwInterceptor = (conversationId: string | null | undefined,onSubmit: (message: string) => void,) => {+ const { t } = useTranslation();const addPending = useBtwStore((s) => s.addPending);const resolve = useBtwStore((s) => s.resolve);const fail = useBtwStore((s) => s.fail);@@ -27,7 +31,10 @@ export const useBtwInterceptor = (return;}const question = trimmed.slice(BTW_COMMAND.length).trim();- if (!question) return;+ if (!question) {+ displayErrorToast(t(I18nKey.CHAT_INTERFACE$BTW_QUESTION_REQUIRED)); // bare /btw — nothing to ask+ return;+ }const entryId = addPending(conversationId, question);askAgent(conversationId, question)@@ -36,6 +43,6 @@ export const useBtwInterceptor = (fail(conversationId, entryId, err?.message ?? "Failed to ask agent"),);},- [conversationId, onSubmit, addPending, resolve, fail],+ [conversationId, onSubmit, addPending, resolve, fail, t],);};diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex db5dc23b5b..27894e4f5e 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -10318,6 +10318,23 @@"uk": "Очікування відповіді агента…","ca": "Esperant la resposta de l'agent…"},+ "CHAT_INTERFACE$BTW_QUESTION_REQUIRED": {+ "en": "Please provide a question — e.g. /btw <question>",+ "ja": "質問を入力してください(例: /btw <question>)",+ "zh-CN": "请提供一个问题,例如 /btw <question>",+ "zh-TW": "請提供一個問題,例如 /btw <question>",+ "ko-KR": "질문을 입력하세요. 예: /btw <question>",+ "no": "Oppgi et spørsmål, f.eks. /btw <question>",+ "it": "Inserisci una domanda, ad es. /btw <question>",+ "pt": "Forneça uma pergunta, por exemplo /btw <question>",+ "es": "Proporciona una pregunta, por ejemplo /btw <question>",+ "ar": "يرجى تقديم سؤال، مثل /btw <question>",+ "fr": "Veuillez poser une question, par ex. /btw <question>",+ "tr": "Lütfen bir soru girin, örn. /btw <question>",+ "de": "Bitte gib eine Frage an, z. B. /btw <question>",+ "uk": "Вкажіть запитання, наприклад /btw <question>",+ "ca": "Proporciona una pregunta, p. ex. /btw <question>"+ },"GOAL$PREFIX": {"en": "Goal:","ja": "ゴール:",