Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: add local Agent Canvas Planner support (#16178)

Vasco Schiavo9bd078884046
diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.ts
index e88144cca8..331ca13ab0 100644
--- a/__tests__/api/agent-server-adapter.test.ts
+++ b/__tests__/api/agent-server-adapter.test.ts
@@ -1869,6 +1869,7 @@ describe("buildStartConversationRequestWithEncryptedSettings", () => {
conversationSettings: (DEFAULT_SETTINGS.conversation_settings ??
{}) as Record<string, SettingsValue>,
secretsEncrypted: true,
+ skillEnablement: { disabledSkills: [] },
});
secretsSpy = vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([]);
});
diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.ts
index b84eff16bf..f4d0c08e56 100644
--- a/__tests__/api/agent-server-conversation-service.test.ts
+++ b/__tests__/api/agent-server-conversation-service.test.ts
@@ -12,6 +12,7 @@ import {
} from "#/api/backend-registry/active-store";
import type { Backend } from "#/api/backend-registry/types";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { setStoredConversationMetadata } from "#/api/conversation-metadata-store";
import {
getFetchCall,
getJsonBody,
@@ -661,6 +662,254 @@ describe("AgentServerConversationService", () => {
"/api/conversations/conv-abc",
);
});
+
+ it("deletes the hidden planner helper reported by the server alongside its parent", async () => {
+ mockHttpDelete.mockResolvedValue({ data: undefined });
+ mockHttpGet.mockImplementation((_url: string, options: unknown) => {
+ const ids = (options as { params: { ids: string[] } }).params.ids;
+ if (ids.includes("conv-abc")) {
+ return Promise.resolve({
+ data: [
+ {
+ id: "conv-abc",
+ created_at: "2024-01-01T00:00:00.000Z",
+ updated_at: "2024-01-01T00:00:00.000Z",
+ sub_conversation_ids: ["plan-abc"],
+ },
+ ],
+ });
+ }
+ return Promise.resolve({
+ data: [
+ {
+ id: "plan-abc",
+ created_at: "2024-01-01T00:00:00.000Z",
+ updated_at: "2024-01-01T00:00:00.000Z",
+ tags: { plannerparent: "conv-abc" },
+ },
+ ],
+ });
+ });
+
+ await AgentServerConversationService.deleteConversation("conv-abc");
+
+ expect(mockHttpDelete).toHaveBeenCalledWith(
+ "/api/conversations/plan-abc",
+ );
+ expect(mockHttpDelete).toHaveBeenCalledWith(
+ "/api/conversations/conv-abc",
+ );
+ });
+
+ it("still deletes the parent when the planner helper is already gone", async () => {
+ mockHttpGet.mockImplementation((_url: string, options: unknown) => {
+ const ids = (options as { params: { ids: string[] } }).params.ids;
+ if (ids.includes("conv-abc")) {
+ return Promise.resolve({
+ data: [
+ {
+ id: "conv-abc",
+ created_at: "2024-01-01T00:00:00.000Z",
+ updated_at: "2024-01-01T00:00:00.000Z",
+ sub_conversation_ids: ["plan-abc"],
+ },
+ ],
+ });
+ }
+ return Promise.resolve({
+ data: [
+ {
+ id: "plan-abc",
+ created_at: "2024-01-01T00:00:00.000Z",
+ updated_at: "2024-01-01T00:00:00.000Z",
+ tags: { plannerparent: "conv-abc" },
+ },
+ ],
+ });
+ });
+ mockHttpDelete.mockImplementation(async (path: string) => {
+ if (path === "/api/conversations/plan-abc") {
+ throw new Error("404 Not Found");
+ }
+ return { data: undefined };
+ });
+
+ await expect(
+ AgentServerConversationService.deleteConversation("conv-abc"),
+ ).resolves.toBeUndefined();
+
+ expect(mockHttpDelete).toHaveBeenCalledWith(
+ "/api/conversations/conv-abc",
+ );
+ });
+
+ it("does not delete an unrelated non-planner child conversation", async () => {
+ // Regression: sub_conversation_ids is the generic server-derived child
+ // list, not a planner-only list β€” an untagged child (e.g. a delegated
+ // sub-agent from another feature) must survive deleting the parent.
+ mockHttpDelete.mockResolvedValue({ data: undefined });
+ mockHttpGet.mockImplementation((_url: string, options: unknown) => {
+ const ids = (options as { params: { ids: string[] } }).params.ids;
+ if (ids.includes("conv-abc")) {
+ return Promise.resolve({
+ data: [
+ {
+ id: "conv-abc",
+ created_at: "2024-01-01T00:00:00.000Z",
+ updated_at: "2024-01-01T00:00:00.000Z",
+ sub_conversation_ids: ["other-conv"],
+ },
+ ],
+ });
+ }
+ return Promise.resolve({
+ data: [
+ {
+ id: "other-conv",
+ created_at: "2024-01-01T00:00:00.000Z",
+ updated_at: "2024-01-01T00:00:00.000Z",
+ tags: {},
+ },
+ ],
+ });
+ });
+
+ await AgentServerConversationService.deleteConversation("conv-abc");
+
+ expect(mockHttpDelete).not.toHaveBeenCalledWith(
+ "/api/conversations/other-conv",
+ );
+ expect(mockHttpDelete).toHaveBeenCalledWith(
+ "/api/conversations/conv-abc",
+ );
+ });
+ });
+
+ describe("createLocalPlanningConversation", () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ mockGetSettingsForConversation.mockResolvedValue({
+ agentSettings: { llm: { model: "openhands/global-model" } },
+ conversationSettings: {},
+ secretsEncrypted: true,
+ });
+ mockHttpPost.mockResolvedValue({
+ data: {
+ id: "plan-abc",
+ created_at: "2024-01-01T00:00:00.000Z",
+ updated_at: "2024-01-01T00:00:00.000Z",
+ },
+ });
+ });
+
+ afterEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ });
+
+ it("ignores active_profile for an ACP parent and falls back to global settings", async () => {
+ // ACP parents get active_profile stamped with whatever LLM profile was
+ // globally active at *their* creation time β€” not meaningfully tied to
+ // the ACP agent β€” so it must not be treated as the planner's model.
+ // agent_kind and active_profile are both derived client-side by
+ // toAppConversation (from info.agent.kind and stored metadata
+ // respectively), not read off the raw GET response.
+ setStoredConversationMetadata("conv-abc", {
+ selected_repository: null,
+ selected_branch: null,
+ git_provider: null,
+ active_profile: "stale-acp-snapshot",
+ });
+ mockHttpGet.mockResolvedValue({
+ data: [
+ {
+ id: "conv-abc",
+ created_at: "2024-01-01T00:00:00.000Z",
+ updated_at: "2024-01-01T00:00:00.000Z",
+ agent: { kind: "ACPAgent", llm: { model: "acp-managed" } },
+ sub_conversation_ids: [],
+ },
+ ],
+ });
+
+ await AgentServerConversationService.createLocalPlanningConversation(
+ "conv-abc",
+ );
+
+ expect(mockGetProfile).not.toHaveBeenCalledWith(
+ "stale-acp-snapshot",
+ { exposeSecrets: "encrypted" },
+ );
+ const [, payload] = mockHttpPost.mock.calls[0] as [
+ string,
+ { agent: { llm: { model: string } } },
+ ];
+ expect(payload.agent.llm.model).toBe("openhands/global-model");
+ });
+
+ it("uses active_profile for an openhands-kind parent", async () => {
+ // agent_kind and active_profile are both derived client-side by
+ // toAppConversation (from info.agent.kind and stored metadata
+ // respectively), not read off the raw GET response.
+ setStoredConversationMetadata("conv-abc", {
+ selected_repository: null,
+ selected_branch: null,
+ git_provider: null,
+ active_profile: "switched-llm",
+ });
+ mockHttpGet.mockResolvedValue({
+ data: [
+ {
+ id: "conv-abc",
+ created_at: "2024-01-01T00:00:00.000Z",
+ updated_at: "2024-01-01T00:00:00.000Z",
+ sub_conversation_ids: [],
+ },
+ ],
+ });
+ mockGetProfile.mockResolvedValue({
+ name: "switched-llm",
+ api_key_set: true,
+ config: { model: "openhands/switched-model" },
+ });
+
+ await AgentServerConversationService.createLocalPlanningConversation(
+ "conv-abc",
+ );
+
+ expect(mockGetProfile).toHaveBeenCalledWith("switched-llm", {
+ exposeSecrets: "encrypted",
+ });
+ const [, payload] = mockHttpPost.mock.calls[0] as [
+ string,
+ { agent: { llm: { model: string } } },
+ ];
+ expect(payload.agent.llm.model).toBe("openhands/switched-model");
+ });
+
+ it("streams the planner's LLM tokens, matching the code agent", async () => {
+ mockHttpGet.mockResolvedValue({
+ data: [
+ {
+ id: "conv-abc",
+ created_at: "2024-01-01T00:00:00.000Z",
+ updated_at: "2024-01-01T00:00:00.000Z",
+ sub_conversation_ids: [],
+ },
+ ],
+ });
+
+ await AgentServerConversationService.createLocalPlanningConversation(
+ "conv-abc",
+ );
+
+ const [, payload] = mockHttpPost.mock.calls[0] as [
+ string,
+ { agent: { llm: { stream?: boolean } } },
+ ];
+ expect(payload.agent.llm.stream).toBe(true);
+ });
});
describe("conversation update fallbacks", () => {
diff --git a/__tests__/components/chat/chat-interface.test.tsx b/__tests__/components/chat/chat-interface.test.tsx
index b1bace7804..119c57052b 100644
--- a/__tests__/components/chat/chat-interface.test.tsx
+++ b/__tests__/components/chat/chat-interface.test.tsx
@@ -79,6 +79,11 @@ vi.mock("#/hooks/use-agent-state", () => ({
useAgentState: vi.fn(() => ({
curAgentState: AgentState.AWAITING_USER_INPUT,
})),
+ usePlanningAgentState: vi.fn(() => ({
+ localPlanningConversationId: null,
+ curPlanningAgentState: AgentState.AWAITING_USER_INPUT,
+ isPlanningAgentRunning: false,
+ })),
}));
const trackInitialQuerySubmittedMock = vi.fn();
diff --git a/__tests__/components/chat/message-display-continuity.test.tsx b/__tests__/components/chat/message-display-continuity.test.tsx
index cb6bb621d5..44f1e0ec16 100644
--- a/__tests__/components/chat/message-display-continuity.test.tsx
+++ b/__tests__/components/chat/message-display-continuity.test.tsx
@@ -50,6 +50,11 @@ vi.mock("#/hooks/use-agent-state", () => ({
useAgentState: vi.fn(() => ({
curAgentState: AgentState.AWAITING_USER_INPUT,
})),
+ usePlanningAgentState: vi.fn(() => ({
+ localPlanningConversationId: null,
+ curPlanningAgentState: AgentState.AWAITING_USER_INPUT,
+ isPlanningAgentRunning: false,
+ })),
}));
vi.mock("#/components/features/chat/btw-messages", () => ({
@@ -144,6 +149,7 @@ describe("ChatInterface – message display continuity (spec 3.1)", () => {
vi.mocked(useConversationWebSocket).mockReturnValue({
isLoadingHistory: true,
connectionState: "OPEN",
+ mainConnectionState: "OPEN",
sendMessage: vi.fn(),
reconnect: vi.fn(),
});
@@ -174,6 +180,7 @@ describe("ChatInterface – message display continuity (spec 3.1)", () => {
vi.mocked(useConversationWebSocket).mockReturnValue({
isLoadingHistory: true,
connectionState: "OPEN",
+ mainConnectionState: "OPEN",
sendMessage: vi.fn(),
reconnect: vi.fn(),
});
@@ -195,6 +202,7 @@ describe("ChatInterface – message display continuity (spec 3.1)", () => {
vi.mocked(useConversationWebSocket).mockReturnValue({
isLoadingHistory: true,
connectionState: "OPEN",
+ mainConnectionState: "OPEN",
sendMessage: vi.fn(),
reconnect: vi.fn(),
});
@@ -225,6 +233,7 @@ describe("ChatInterface – message display continuity (spec 3.1)", () => {
vi.mocked(useConversationWebSocket).mockReturnValue({
isLoadingHistory: false,
connectionState: "OPEN",
+ mainConnectionState: "OPEN",
sendMessage: vi.fn(),
reconnect: vi.fn(),
});
diff --git a/__tests__/components/conversation-events/chat/event-message-plan-preview.test.tsx b/__tests__/components/conversation-events/chat/event-message-plan-preview.test.tsx
index 2c6ee598d9..bd85783666 100644
--- a/__tests__/components/conversation-events/chat/event-message-plan-preview.test.tsx
+++ b/__tests__/components/conversation-events/chat/event-message-plan-preview.test.tsx
@@ -2,7 +2,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { screen } from "@testing-library/react";
import { EventMessage } from "#/components/conversation-events/chat/event-message";
import { useConversationStore } from "#/stores/conversation-store";
-import { useAgentState } from "#/hooks/use-agent-state";
+import { useAgentState, usePlanningAgentState } from "#/hooks/use-agent-state";
import { AgentState } from "#/types/agent-state";
import {
renderWithProviders,
@@ -16,10 +16,13 @@ vi.mock("#/hooks/query/use-config", () => ({
}),
}));
-// Mock useAgentState
-vi.mock("#/hooks/use-agent-state");
+// Mock useAgentState (main) and usePlanningAgentState (planner) independently
+// so each test controls exactly one without the other's default bleeding in.
+vi.mock("#/hooks/use-agent-state", () => ({
+ useAgentState: vi.fn(),
+ usePlanningAgentState: vi.fn(),
+}));
-// Mock PlanPreview component to verify it's rendered with correct props
// Mock useConversationId (EventMessage -> useAgentState -> useActiveConversation -> useConversationId)
vi.mock("#/hooks/use-conversation-id", () => ({
useOptionalConversationId: () => ({ conversationId: "test-conversation-id" }),
@@ -44,14 +47,17 @@ vi.mock("#/components/features/chat/plan-preview", () => ({
describe("EventMessage - PlanPreview rendering", () => {
beforeEach(() => {
vi.clearAllMocks();
- // Reset conversation store
- useConversationStore.setState({
- planContent: null,
- });
- // Default mock for useAgentState
+ useConversationStore.setState({ planContent: null });
vi.mocked(useAgentState).mockReturnValue({
curAgentState: AgentState.INIT,
});
+ // A resolved planner id by default, idle, so the isStreaming-specific
+ // tests below only need to vary isLastMessage / planning agent state.
+ vi.mocked(usePlanningAgentState).mockReturnValue({
+ localPlanningConversationId: "planner-1",
+ curPlanningAgentState: AgentState.INIT,
+ isPlanningAgentRunning: false,
+ });
});
afterEach(() => {
@@ -177,14 +183,16 @@ describe("EventMessage - PlanPreview rendering", () => {
});
describe("isStreaming prop", () => {
- it("should pass isStreaming=true when isLastMessage is true and agent state is RUNNING", () => {
+ it("should pass isStreaming=true when isLastMessage is true and planner is RUNNING", () => {
const event = createPlanningObservationEvent("plan-obs-1");
const planPreviewEventIds = new Set(["plan-obs-1"]);
const planContent = "Streaming plan content";
useConversationStore.setState({ planContent });
- vi.mocked(useAgentState).mockReturnValue({
- curAgentState: AgentState.RUNNING,
+ vi.mocked(usePlanningAgentState).mockReturnValue({
+ localPlanningConversationId: "planner-1",
+ curPlanningAgentState: AgentState.RUNNING,
+ isPlanningAgentRunning: true,
});
renderWithProviders(
@@ -202,14 +210,16 @@ describe("EventMessage - PlanPreview rendering", () => {
expect(planPreview).toHaveAttribute("data-is-streaming", "true");
});
- it("should pass isStreaming=false when isLastMessage is false even if agent is RUNNING", () => {
+ it("should pass isStreaming=false when isLastMessage is false even if planner is RUNNING", () => {
const event = createPlanningObservationEvent("plan-obs-1");
const planPreviewEventIds = new Set(["plan-obs-1"]);
const planContent = "Plan content";
useConversationStore.setState({ planContent });
- vi.mocked(useAgentState).mockReturnValue({
- curAgentState: AgentState.RUNNING,
+ vi.mocked(usePlanningAgentState).mockReturnValue({
+ localPlanningConversationId: "planner-1",
+ curPlanningAgentState: AgentState.RUNNING,
+ isPlanningAgentRunning: true,
});
renderWithProviders(
@@ -227,14 +237,16 @@ describe("EventMessage - PlanPreview rendering", () => {
expect(planPreview).toHaveAttribute("data-is-streaming", "false");
});
- it("should pass isStreaming=false when agent state is not RUNNING even if isLastMessage is true", () => {
+ it("should pass isStreaming=false when planner state is not RUNNING even if isLastMessage is true", () => {
const event = createPlanningObservationEvent("plan-obs-1");
const planPreviewEventIds = new Set(["plan-obs-1"]);
const planContent = "Completed plan content";
useConversationStore.setState({ planContent });
- vi.mocked(useAgentState).mockReturnValue({
- curAgentState: AgentState.AWAITING_USER_INPUT,
+ vi.mocked(usePlanningAgentState).mockReturnValue({
+ localPlanningConversationId: "planner-1",
+ curPlanningAgentState: AgentState.AWAITING_USER_INPUT,
+ isPlanningAgentRunning: false,
});
renderWithProviders(
@@ -252,14 +264,47 @@ describe("EventMessage - PlanPreview rendering", () => {
expect(planPreview).toHaveAttribute("data-is-streaming", "false");
});
- it("should pass isStreaming=false when agent state is FINISHED", () => {
+ it("should pass isStreaming=false when localPlanningConversationId hasn't resolved yet, even if isLastMessage and planner state are RUNNING", () => {
+ // Regression: useAgentState(undefined) falls back to the route
+ // conversation's own state, so without this guard the code agent's
+ // activity could be mistaken for the planner's before the planner id
+ // resolves (e.g. right after "Create a Plan" is clicked).
+ const event = createPlanningObservationEvent("plan-obs-1");
+ const planPreviewEventIds = new Set(["plan-obs-1"]);
+ const planContent = "Plan content";
+
+ useConversationStore.setState({ planContent });
+ vi.mocked(usePlanningAgentState).mockReturnValue({
+ localPlanningConversationId: null,
+ curPlanningAgentState: AgentState.RUNNING,
+ isPlanningAgentRunning: false,
+ });
+
+ renderWithProviders(
+ <EventMessage
+ event={event}
+ messages={[]}
+ isLastMessage
+ isInLast10Actions={false}
+ planPreviewEventIds={planPreviewEventIds}
+ />,
+ );
+
+ const planPreview = screen.getByTestId("plan-preview");
+ expect(planPreview).toBeInTheDocument();
+ expect(planPreview).toHaveAttribute("data-is-streaming", "false");
+ });
+
+ it("should pass isStreaming=false when planner state is FINISHED", () => {
const event = createPlanningObservationEvent("plan-obs-1");
const planPreviewEventIds = new Set(["plan-obs-1"]);
const planContent = "Finished plan content";
useConversationStore.setState({ planContent });
- vi.mocked(useAgentState).mockReturnValue({
- curAgentState: AgentState.FINISHED,
+ vi.mocked(usePlanningAgentState).mockReturnValue({
+ localPlanningConversationId: "planner-1",
+ curPlanningAgentState: AgentState.FINISHED,
+ isPlanningAgentRunning: false,
});
renderWithProviders(
diff --git a/__tests__/components/features/conversation/conversation-tabs-context-menu.test.tsx b/__tests__/components/features/conversation/conversation-tabs-context-menu.test.tsx
index 6dd3f78d10..53dacf79d7 100644
--- a/__tests__/components/features/conversation/conversation-tabs-context-menu.test.tsx
+++ b/__tests__/components/features/conversation/conversation-tabs-context-menu.test.tsx
@@ -67,15 +67,14 @@ describe("ConversationTabsContextMenu", () => {
"DIFF_VIEWER$COMMITS",
"COMMON$TERMINAL",
"COMMON$BROWSER",
+ // Local planning is now supported, so the Planner tab is a default tab.
+ "COMMON$PLANNER",
];
for (const tab of expectedTabs) {
expect(screen.getByText(tab)).toBeInTheDocument();
}
expect(screen.queryByText("FILES$DIFF_VIEW")).not.toBeInTheDocument();
-
- // Planner is cloud-only; on the default (local) backend it is hidden.
- expect(screen.queryByText("COMMON$PLANNER")).not.toBeInTheDocument();
});
it("should show the Planner entry when the active backend is cloud", () => {
@@ -139,14 +138,14 @@ describe("ConversationTabsContextMenu", () => {
const storeState = useConversationStore.getState();
expect(storeState.hasRightPanelToggled).toBe(true);
- // Next pinned tab after Files is Commits.
- expect(storeState.selectedTab).toBe("commits");
+ // Planner is first in the tab order, so it becomes active when files unpins.
+ expect(storeState.selectedTab).toBe("planner");
const storedState = JSON.parse(
localStorage.getItem(`conversation-state-${CONVERSATION_ID}`)!,
);
expect(storedState.unpinnedTabs).toContain("files");
- expect(storedState.selectedTab).toBe("commits");
+ expect(storedState.selectedTab).toBe("planner");
});
it("should not close the right panel when unpinning a non-active tab", async () => {
diff --git a/__tests__/components/features/conversation/conversation-tabs.test.tsx b/__tests__/components/features/conversation/conversation-tabs.test.tsx
index ece1c47658..f65df72e74 100644
--- a/__tests__/components/features/conversation/conversation-tabs.test.tsx
+++ b/__tests__/components/features/conversation/conversation-tabs.test.tsx
@@ -52,6 +52,11 @@ vi.mock("#/hooks/use-handle-build-plan-click", () => ({
let mockCurAgentState = AgentState.AWAITING_USER_INPUT;
vi.mock("#/hooks/use-agent-state", () => ({
useAgentState: () => ({ curAgentState: mockCurAgentState }),
+ usePlanningAgentState: () => ({
+ localPlanningConversationId: null,
+ curPlanningAgentState: AgentState.AWAITING_USER_INPUT,
+ isPlanningAgentRunning: false,
+ }),
}));
vi.mock("#/hooks/query/use-unified-vscode-url", () => ({
@@ -475,7 +480,7 @@ describe("ConversationTabs localStorage behavior", () => {
mockConversationId = REAL_CONVERSATION_ID;
});
- it("should hide the planner tab when the active backend is local", () => {
+ it("should show the planner tab when the active backend is local", () => {
// Arrange
seedActiveBackend({
id: "local-test",
@@ -490,10 +495,10 @@ describe("ConversationTabs localStorage behavior", () => {
wrapper: createWrapper(REAL_CONVERSATION_ID),
});
- // Assert
+ // Assert: local planning is now supported, so the tab is shown.
expect(
- screen.queryByTestId("conversation-tab-planner"),
- ).not.toBeInTheDocument();
+ screen.getByTestId("conversation-tab-planner"),
+ ).toBeInTheDocument();
});
it("should show the planner tab when the active backend is cloud", () => {
diff --git a/__tests__/contexts/conversation-websocket-context.test.tsx b/__tests__/contexts/conversation-websocket-context.test.tsx
index e73cba07ab..98caec8ef7 100644
--- a/__tests__/contexts/conversation-websocket-context.test.tsx
+++ b/__tests__/contexts/conversation-websocket-context.test.tsx
@@ -1,8 +1,13 @@
+import React from "react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, waitFor, act } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createUserMessageEvent } from "test-utils";
-import { ConversationWebSocketProvider } from "#/contexts/conversation-websocket-context";
+import {
+ ConversationWebSocketProvider,
+ useConversationWebSocket,
+} from "#/contexts/conversation-websocket-context";
+import { useConversationStore } from "#/stores/conversation-store";
import { useEventStore } from "#/stores/use-event-store";
import useMetricsStore from "#/stores/metrics-store";
import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";
@@ -75,6 +80,19 @@ vi.mock("#/utils/error-handler", () => ({
trackError: errorHandlerMocks.trackError,
}));
+const sendEventMock = vi.hoisted(() => vi.fn());
+vi.mock("@openhands/typescript-client/clients", async () => {
+ const actual = await vi.importActual<
+ typeof import("@openhands/typescript-client/clients")
+ >("@openhands/typescript-client/clients");
+ return {
+ ...actual,
+ ConversationClient: vi.fn(function ConversationClientMock() {
+ return { sendEvent: sendEventMock };
+ }),
+ };
+});
+
const AGENT_REPLY_ID = "evt-agent-reply";
// An agent reply that streamed in over the WebSocket *after* the initial REST
@@ -356,6 +374,89 @@ describe("ConversationWebSocketProvider β€” conversation-scoped event store", ()
);
});
+ // The socket is never OPEN in these tests (the useWebSocket mock returns
+ // `socket: null`), so every send falls through to the REST queue β€” exactly
+ // the window this suite is about.
+ describe("plan-mode message routing before the planning socket opens", () => {
+ function SendMessageProbe({
+ onReady,
+ }: {
+ onReady: (send: ReturnType<typeof useConversationWebSocket>) => void;
+ }) {
+ const context = useConversationWebSocket();
+ React.useEffect(() => onReady(context), [context, onReady]);
+ return null;
+ }
+
+ const renderPlanMode = (subConversationIds?: string[]) => {
+ let context: ReturnType<typeof useConversationWebSocket> | null = null;
+ render(
+ <QueryClientProvider client={queryClient}>
+ <ConversationWebSocketProvider
+ conversationId="conv-parent"
+ conversationUrl="http://localhost/api"
+ subConversationIds={subConversationIds}
+ // The react-query lookup that resolves ids into conversations has
+ // not landed yet β€” this is the race the fix is about.
+ subConversations={undefined}
+ >
+ <SendMessageProbe
+ onReady={(value) => {
+ context = value;
+ }}
+ />
+ </ConversationWebSocketProvider>
+ </QueryClientProvider>,
+ );
+ return () => context!;
+ };
+
+ beforeEach(() => {
+ sendEventMock.mockReset().mockResolvedValue(undefined);
+ useConversationStore.setState({ conversationMode: "plan" });
+ });
+
+ afterEach(() => {
+ useConversationStore.setState({ conversationMode: "code" });
+ });
+
+ it("queues the first prompt to the planner, not the parent code agent", async () => {
+ const getContext = renderPlanMode(["planning-1"]);
+ await waitFor(() => expect(getContext()).not.toBeNull());
+
+ await act(async () => {
+ await getContext().sendMessage({
+ role: "user",
+ content: [{ type: "text", text: "plan this" }],
+ });
+ });
+
+ expect(sendEventMock).toHaveBeenCalledWith(
+ "planning-1",
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it("errors instead of falling back to the parent when no planner exists yet", async () => {
+ const getContext = renderPlanMode(undefined);
+ await waitFor(() => expect(getContext()).not.toBeNull());
+
+ await expect(
+ act(async () => {
+ await getContext().sendMessage({
+ role: "user",
+ content: [{ type: "text", text: "plan this" }],
+ });
+ }),
+ ).rejects.toThrow("Planning conversation is not ready yet");
+
+ // Falling back to `conv-parent` here would run a planning prompt in the
+ // code agent β€” the boundary plan mode exists to enforce.
+ expect(sendEventMock).not.toHaveBeenCalled();
+ });
+ });
+
it("preserves the conversation's attached plugins across an agent-triggered model switch", async () => {
// Arrange: the conversation's metadata already carries an attached plugin.
setStoredConversationMetadata("conv-switch", {
diff --git a/__tests__/contexts/websocket-provider-wrapper.test.tsx b/__tests__/contexts/websocket-provider-wrapper.test.tsx
index fcd8d008de..9baf4b61e8 100644
--- a/__tests__/contexts/websocket-provider-wrapper.test.tsx
+++ b/__tests__/contexts/websocket-provider-wrapper.test.tsx
@@ -9,23 +9,29 @@
*/
import React from "react";
import { render } from "@testing-library/react";
-import { describe, it, expect, vi, beforeEach } from "vitest";
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { WebSocketProviderWrapper } from "#/contexts/websocket-provider-wrapper";
+import { useConversationStore } from "#/stores/conversation-store";
import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+import { LOCAL_PLANNER_PARENT_TAG_KEY } from "#/utils/plan-file";
// ── Mocks ────────────────────────────────────────────────────────────────────
const capturedUrlPerRender: (string | null | undefined)[] = [];
+const capturedSubConversationIdsPerRender: (readonly string[])[] = [];
vi.mock("#/contexts/conversation-websocket-context", () => ({
ConversationWebSocketProvider: ({
conversationUrl,
+ subConversationIds,
children,
}: {
conversationUrl?: string | null;
+ subConversationIds?: readonly string[];
children?: React.ReactNode;
}) => {
capturedUrlPerRender.push(conversationUrl);
+ capturedSubConversationIdsPerRender.push(subConversationIds ?? []);
return <>{children}</>;
},
}));
@@ -35,8 +41,14 @@ vi.mock("#/hooks/query/use-active-conversation", () => ({
useActiveConversation: () => mockUseActiveConversation(),
}));
+const mockUseSubConversations = vi.fn();
vi.mock("#/hooks/query/use-sub-conversations", () => ({
- useSubConversations: () => ({ data: [] }),
+ useSubConversations: (...args: unknown[]) => mockUseSubConversations(...args),
+}));
+
+const mockUseActiveBackend = vi.fn();
+vi.mock("#/contexts/active-backend-context", () => ({
+ useActiveBackend: () => mockUseActiveBackend(),
}));
// ── Helpers ───────────────────────────────────────────────────────────────────
@@ -79,7 +91,10 @@ function renderWrapper() {
describe("WebSocketProviderWrapper β€” conversationUrl gating", () => {
beforeEach(() => {
capturedUrlPerRender.length = 0;
+ capturedSubConversationIdsPerRender.length = 0;
vi.clearAllMocks();
+ mockUseActiveBackend.mockReturnValue({ backend: { kind: "local" } });
+ mockUseSubConversations.mockReturnValue({ data: [] });
});
it("passes conversation_url through when sandbox_status is null (local backend)", () => {
@@ -111,7 +126,8 @@ describe("WebSocketProviderWrapper β€” conversationUrl gating", () => {
data: makeConversation({
sandbox_status: "PAUSED",
// The API keeps the stale URL even while paused β€” this is the regression.
- conversation_url: "https://sandbox.example.com/api/conversations/conv-1",
+ conversation_url:
+ "https://sandbox.example.com/api/conversations/conv-1",
}),
});
@@ -138,3 +154,117 @@ describe("WebSocketProviderWrapper β€” conversationUrl gating", () => {
expect(capturedUrlPerRender.at(-1)).toBeUndefined();
});
});
+
+/**
+ * Regression: ConversationWebSocketProvider resets its planning-history
+ * tracking (and drops any pending PLAN.md update) whenever the
+ * `subConversationIds` array it receives changes *by reference* β€” even when
+ * the resolved planner id hasn't actually changed. `useSubConversations`
+ * returns a brand-new array on every refetch (e.g. the default
+ * refetchOnWindowFocus, or just `execution_status` ticking between polls),
+ * so deriving `subConversationIds` straight from that array without an
+ * intermediate primitive-keyed memo silently breaks live PLAN.md updates
+ * after the first refetch β€” the Planner tab then only catches up on a full
+ * reload. See websocket-provider-wrapper.tsx's plannerConversationId memo.
+ */
+describe("WebSocketProviderWrapper β€” subConversationIds reference stability", () => {
+ beforeEach(() => {
+ capturedUrlPerRender.length = 0;
+ capturedSubConversationIdsPerRender.length = 0;
+ vi.clearAllMocks();
+ mockUseActiveBackend.mockReturnValue({ backend: { kind: "local" } });
+ });
+
+ it("keeps the same subConversationIds array reference across refetches that resolve to the same planner", () => {
+ mockUseActiveConversation.mockReturnValue({
+ data: makeConversation({ sub_conversation_ids: ["planner-1"] }),
+ });
+ // A fresh array/object literal every call β€” exactly what a refetch (even
+ // one returning identical planner data) produces from useSubConversations.
+ mockUseSubConversations.mockImplementation(() => ({
+ data: [
+ makeConversation({
+ id: "planner-1",
+ tags: { [LOCAL_PLANNER_PARENT_TAG_KEY]: "conv-1" },
+ }),
+ ],
+ }));
+
+ const { rerender } = render(
+ <WebSocketProviderWrapper conversationId="conv-1">
+ <div />
+ </WebSocketProviderWrapper>,
+ );
+ rerender(
+ <WebSocketProviderWrapper conversationId="conv-1">
+ <div />
+ </WebSocketProviderWrapper>,
+ );
+
+ expect(capturedSubConversationIdsPerRender.length).toBeGreaterThanOrEqual(
+ 2,
+ );
+ expect(capturedSubConversationIdsPerRender.at(-1)).toEqual(["planner-1"]);
+ // The actual regression check: same reference, not just same value.
+ expect(capturedSubConversationIdsPerRender.at(-1)).toBe(
+ capturedSubConversationIdsPerRender.at(-2),
+ );
+ });
+});
+
+/**
+ * Regression: `localPlanningConversationId` is a single unscoped Zustand
+ * field, not keyed by conversation. Right after switching conversations,
+ * this component re-renders with the new `conversationId` prop before
+ * `useActiveConversation()` has refetched for it (and before the separate
+ * reset effect in routes/conversation.tsx has cleared the *previous*
+ * conversation's value out of the store) β€” trusting the stale store value
+ * during that window would open the planner socket for the wrong
+ * conversation's planner. See `trustedLocalPlanningConversationId` in
+ * websocket-provider-wrapper.tsx.
+ */
+describe("WebSocketProviderWrapper β€” stale cross-conversation localPlanningConversationId", () => {
+ beforeEach(() => {
+ capturedUrlPerRender.length = 0;
+ capturedSubConversationIdsPerRender.length = 0;
+ vi.clearAllMocks();
+ mockUseActiveBackend.mockReturnValue({ backend: { kind: "local" } });
+ mockUseSubConversations.mockReturnValue({ data: [] });
+ });
+
+ afterEach(() => {
+ useConversationStore.setState({ localPlanningConversationId: null });
+ });
+
+ it("does not fall back to a stale localPlanningConversationId while the active conversation query hasn't caught up to the rendered conversationId", () => {
+ // The store still holds the *previous* conversation's planner id, and
+ // useActiveConversation hasn't resolved data for the new conversationId
+ // yet (data undefined β€” exactly the state on the first render after a
+ // conversation switch).
+ useConversationStore.setState({ localPlanningConversationId: "planner-A" });
+ mockUseActiveConversation.mockReturnValue({ data: undefined });
+
+ render(
+ <WebSocketProviderWrapper conversationId="conv-B">
+ <div />
+ </WebSocketProviderWrapper>,
+ );
+
+ expect(capturedSubConversationIdsPerRender.at(-1)).toEqual([]);
+ });
+
+ it("trusts localPlanningConversationId once the active conversation has resolved to the conversation being rendered", () => {
+ useConversationStore.setState({ localPlanningConversationId: "planner-B" });
+ mockUseActiveConversation.mockReturnValue({
+ data: makeConversation({ id: "conv-B", sub_conversation_ids: [] }),
+ });
+
+ render(
+ <WebSocketProviderWrapper conversationId="conv-B">
+ <div />
+ </WebSocketProviderWrapper>,
+ );
+
+ expect(capturedSubConversationIdsPerRender.at(-1)).toEqual(["planner-B"]);
+ });
+});
diff --git a/__tests__/hooks/mutation/use-read-conversation-file.test.tsx b/__tests__/hooks/mutation/use-read-conversation-file.test.tsx
new file mode 100644
index 0000000000..24e1684596
--- /dev/null
+++ b/__tests__/hooks/mutation/use-read-conversation-file.test.tsx
@@ -0,0 +1,146 @@
+import { describe, expect, it, vi, afterEach, beforeEach } from "vitest";
+import React from "react";
+import { renderHook, waitFor, act } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { AxiosError, AxiosHeaders } from "axios";
+import { useReadConversationFile } from "#/hooks/mutation/use-read-conversation-file";
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { displayErrorToast } from "#/utils/custom-toast-handlers";
+
+vi.mock(
+ "#/api/conversation-service/agent-server-conversation-service.api",
+ () => ({
+ default: { readConversationFile: vi.fn() },
+ }),
+);
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displayErrorToast: vi.fn(),
+}));
+
+function makeAxiosError(status: number): AxiosError {
+ return new AxiosError(
+ `Request failed with status code ${status}`,
+ String(status),
+ undefined,
+ undefined,
+ {
+ status,
+ statusText: String(status),
+ headers: new AxiosHeaders(),
+ config: { headers: new AxiosHeaders() },
+ data: undefined,
+ },
+ );
+}
+
+describe("useReadConversationFile", () => {
+ let queryClient: QueryClient;
+ let wrapper: ({
+ children,
+ }: {
+ children: React.ReactNode;
+ }) => React.ReactElement;
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ children,
+ );
+ });
+
+ afterEach(() => {
+ queryClient.clear();
+ vi.clearAllMocks();
+ });
+
+ it("resolves with the file content on success", async () => {
+ vi.mocked(
+ AgentServerConversationService.readConversationFile,
+ ).mockResolvedValue("# Plan\n\n- step 1");
+
+ const { result } = renderHook(() => useReadConversationFile(), {
+ wrapper,
+ });
+
+ let content: string | undefined;
+ await act(async () => {
+ content = await result.current.mutateAsync({
+ conversationId: "conv-1",
+ });
+ });
+
+ expect(content).toBe("# Plan\n\n- step 1");
+ expect(displayErrorToast).not.toHaveBeenCalled();
+ });
+
+ it("stays silent on a 404 β€” the expected no-plan-yet state", async () => {
+ vi.mocked(
+ AgentServerConversationService.readConversationFile,
+ ).mockRejectedValue(makeAxiosError(404));
+
+ const { result } = renderHook(() => useReadConversationFile(), {
+ wrapper,
+ });
+
+ act(() => {
+ result.current.mutate({ conversationId: "conv-1" });
+ });
+
+ await waitFor(() => {
+ expect(result.current.isError).toBe(true);
+ });
+
+ expect(displayErrorToast).not.toHaveBeenCalled();
+ });
+
+ it("shows an error toast for a non-404 failure, e.g. a transient 500", async () => {
+ // Regression: meta.disableToast used to suppress the toast
+ // unconditionally, silently stranding the Planner tab on its empty
+ // state for real failures too, not just the expected 404.
+ vi.mocked(
+ AgentServerConversationService.readConversationFile,
+ ).mockRejectedValue(makeAxiosError(500));
+
+ const { result } = renderHook(() => useReadConversationFile(), {
+ wrapper,
+ });
+
+ act(() => {
+ result.current.mutate({ conversationId: "conv-1" });
+ });
+
+ await waitFor(() => {
+ expect(result.current.isError).toBe(true);
+ });
+
+ expect(displayErrorToast).toHaveBeenCalled();
+ });
+
+ it("shows an error toast for a non-Axios failure (e.g. a network error)", async () => {
+ vi.mocked(
+ AgentServerConversationService.readConversationFile,
+ ).mockRejectedValue(new Error("Network Error"));
+
+ const { result } = renderHook(() => useReadConversationFile(), {
+ wrapper,
+ });
+
+ act(() => {
+ result.current.mutate({ conversationId: "conv-1" });
+ });
+
+ await waitFor(() => {
+ expect(result.current.isError).toBe(true);
+ });
+
+ expect(displayErrorToast).toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx b/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx
index ef724fd983..d4a3c8f9da 100644
--- a/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx
+++ b/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx
@@ -226,19 +226,42 @@ describe("useSwitchLlmProfile", () => {
});
await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ // The switch carries the previous record forward wholesale rather than
+ // re-listing known fields, so optional keys the record never had stay
+ // absent instead of being materialized as null.
expect(getStoredConversationMetadata("conv-1")).toEqual({
selected_repository: "octocat/hello-world",
selected_branch: "main",
git_provider: "github",
- selected_workspace: null,
- workspace_mode: null,
active_profile: "claude-sonnet-4.6",
// Client-clock ISO timestamp; the mutation path has no event timestamp.
stamped_at: expect.any(String),
- plugins: null,
});
});
+ it("preserves metadata fields the switch does not know about, such as the local planner id", async () => {
+ vi.mocked(AgentServerConversationService.switchProfile).mockResolvedValue(
+ undefined as never,
+ );
+ setStoredConversationMetadata("conv-1", {
+ selected_repository: null,
+ selected_branch: null,
+ git_provider: null,
+ local_planning_conversation_id: "plan-conv-1",
+ });
+
+ const { result } = renderSwitchHook();
+ result.current.mutate({
+ conversationId: "conv-1",
+ profileName: "claude-sonnet-4.6",
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(
+ getStoredConversationMetadata("conv-1")?.local_planning_conversation_id,
+ ).toBe("plan-conv-1");
+ });
+
it("preserves the conversation's attached plugins across a profile switch", async () => {
vi.mocked(AgentServerConversationService.switchProfile).mockResolvedValue(
undefined as never,
diff --git a/__tests__/hooks/use-handle-plan-click.test.tsx b/__tests__/hooks/use-handle-plan-click.test.tsx
index 67d2415981..e0aca746b6 100644
--- a/__tests__/hooks/use-handle-plan-click.test.tsx
+++ b/__tests__/hooks/use-handle-plan-click.test.tsx
@@ -1,5 +1,7 @@
+import React from "react";
import { describe, it, expect, afterEach, vi, beforeEach } from "vitest";
-import { renderHook, waitFor, act } from "@testing-library/react";
+import { renderHook, act, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useHandlePlanClick } from "#/hooks/use-handle-plan-click";
import { useConversationStore } from "#/stores/conversation-store";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
@@ -8,16 +10,36 @@ import {
getConversationState,
setConversationState,
} from "#/utils/conversation-local-storage";
-import { displaySuccessToast } from "#/utils/custom-toast-handlers";
-import type { Conversation } from "#/api/open-hands.types";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+} from "#/utils/custom-toast-handlers";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { getStoredConversationMetadata } from "#/api/conversation-metadata-store";
import { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+import { useSubConversations } from "#/hooks/query/use-sub-conversations";
+import { LOCAL_PLANNER_PARENT_TAG_KEY } from "#/utils/plan-file";
// Mock dependencies
vi.mock("#/stores/conversation-store");
vi.mock("#/hooks/query/use-active-conversation");
vi.mock("#/hooks/mutation/use-create-conversation");
+vi.mock("#/hooks/query/use-sub-conversations");
vi.mock("#/utils/conversation-local-storage");
vi.mock("#/utils/custom-toast-handlers");
+vi.mock("#/contexts/active-backend-context");
+vi.mock(
+ "#/api/conversation-service/agent-server-conversation-service.api",
+ () => ({
+ default: {
+ createLocalPlanningConversation: vi.fn(),
+ },
+ }),
+);
+vi.mock("#/api/conversation-metadata-store", () => ({
+ getStoredConversationMetadata: vi.fn(),
+}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string) => key,
@@ -30,14 +52,48 @@ vi.mock("react-i18next", () => ({
const mockSetConversationMode = vi.fn();
const mockSetSubConversationTaskId = vi.fn();
+const mockSetLocalPlanningConversationId = vi.fn();
const mockCreateConversation = vi.fn();
+function createTestQueryClient() {
+ return new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+}
+
+function createWrapper(queryClient: QueryClient) {
+ return function Wrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ };
+}
+
+function renderPlanHook() {
+ return renderHook(() => useHandlePlanClick(), {
+ wrapper: createWrapper(createTestQueryClient()),
+ });
+}
+
+function renderPlanHookWithClient() {
+ const queryClient = createTestQueryClient();
+ const rendered = renderHook(() => useHandlePlanClick(), {
+ wrapper: createWrapper(queryClient),
+ });
+ return { ...rendered, queryClient };
+}
+
// Helper function to create properly typed mock return values
function asMockReturnValue<T>(value: Partial<T>): T {
return value as T;
}
-function makeConversation(overrides?: Partial<AppConversation>): AppConversation {
+function makeConversation(
+ overrides?: Partial<AppConversation>,
+): AppConversation {
return {
id: "conv-123",
title: "Test Conversation",
@@ -56,14 +112,32 @@ function makeConversation(overrides?: Partial<AppConversation>): AppConversation
} as AppConversation;
}
+/** Tags a fetched sub-conversation as the planner helper for `parentId`. */
+function makeTaggedPlannerConversation(
+ id: string,
+ parentId: string,
+): AppConversation {
+ return makeConversation({
+ id,
+ tags: { [LOCAL_PLANNER_PARENT_TAG_KEY]: parentId },
+ });
+}
+
describe("useHandlePlanClick", () => {
beforeEach(() => {
vi.clearAllMocks();
+ vi.mocked(useActiveBackend).mockReturnValue({
+ backend: { kind: "cloud" },
+ } as ReturnType<typeof useActiveBackend>);
+ vi.mocked(getStoredConversationMetadata).mockReturnValue(null);
+
vi.mocked(useConversationStore).mockReturnValue({
setConversationMode: mockSetConversationMode,
setSubConversationTaskId: mockSetSubConversationTaskId,
subConversationTaskId: null,
+ setLocalPlanningConversationId: mockSetLocalPlanningConversationId,
+ localPlanningConversationId: null,
});
vi.mocked(useActiveConversation).mockReturnValue(
@@ -77,6 +151,12 @@ describe("useHandlePlanClick", () => {
}),
);
+ vi.mocked(useSubConversations).mockReturnValue(
+ asMockReturnValue<ReturnType<typeof useSubConversations>>({
+ data: [],
+ }),
+ );
+
vi.mocked(useCreateConversation).mockReturnValue(
asMockReturnValue<ReturnType<typeof useCreateConversation>>({
mutate: mockCreateConversation,
@@ -128,7 +208,7 @@ describe("useHandlePlanClick", () => {
filesTabContentViewMode: "rich",
});
- renderHook(() => useHandlePlanClick());
+ renderPlanHook();
expect(getConversationState).toHaveBeenCalledWith(conversationId);
expect(mockSetSubConversationTaskId).toHaveBeenCalledWith(storedTaskId);
@@ -155,6 +235,8 @@ describe("useHandlePlanClick", () => {
setConversationMode: mockSetConversationMode,
setSubConversationTaskId: mockSetSubConversationTaskId,
subConversationTaskId: existingTaskId,
+ setLocalPlanningConversationId: mockSetLocalPlanningConversationId,
+ localPlanningConversationId: null,
}),
);
@@ -168,7 +250,7 @@ describe("useHandlePlanClick", () => {
filesTabContentViewMode: "rich",
});
- renderHook(() => useHandlePlanClick());
+ renderPlanHook();
expect(getConversationState).toHaveBeenCalledWith(conversationId);
expect(mockSetSubConversationTaskId).not.toHaveBeenCalled();
@@ -186,13 +268,317 @@ describe("useHandlePlanClick", () => {
}),
);
- renderHook(() => useHandlePlanClick());
+ renderPlanHook();
expect(getConversationState).not.toHaveBeenCalled();
expect(mockSetSubConversationTaskId).not.toHaveBeenCalled();
});
});
+ describe("local planner conversations", () => {
+ it("restores local planning conversation id from metadata", () => {
+ vi.mocked(getStoredConversationMetadata).mockReturnValue({
+ selected_repository: null,
+ selected_branch: null,
+ git_provider: null,
+ local_planning_conversation_id: "plan-conv-1",
+ });
+
+ renderPlanHook();
+
+ expect(mockSetLocalPlanningConversationId).toHaveBeenCalledWith(
+ "plan-conv-1",
+ );
+ });
+
+ it("creates a local planning conversation on local backends", async () => {
+ vi.mocked(useActiveBackend).mockReturnValue({
+ backend: { kind: "local" },
+ } as ReturnType<typeof useActiveBackend>);
+ vi.mocked(
+ AgentServerConversationService.createLocalPlanningConversation,
+ ).mockResolvedValue(makeConversation({ id: "plan-conv-1" }));
+
+ const { result } = renderPlanHook();
+
+ act(() => {
+ result.current.handlePlanClick();
+ });
+
+ await waitFor(() => {
+ expect(
+ AgentServerConversationService.createLocalPlanningConversation,
+ ).toHaveBeenCalledWith("conv-123", undefined);
+ });
+ await waitFor(() => {
+ expect(mockSetLocalPlanningConversationId).toHaveBeenCalledWith(
+ "plan-conv-1",
+ );
+ });
+ expect(mockSetConversationMode).toHaveBeenCalledWith("plan");
+ expect(mockCreateConversation).not.toHaveBeenCalled();
+ expect(displaySuccessToast).toHaveBeenCalled();
+ });
+
+ it("invalidates the parent's own active-conversation query, not just the paginated list", async () => {
+ // Regression: invalidating only ["user", "conversations"] (the
+ // paginated list) leaves the parent's own cached AppConversation
+ // (what useActiveConversation reads sub_conversation_ids from) stale
+ // until the next poll. onSuccess now delegates to the shared
+ // invalidateConversationQueries helper, which covers both.
+ vi.mocked(useActiveBackend).mockReturnValue({
+ backend: { kind: "local" },
+ } as ReturnType<typeof useActiveBackend>);
+ vi.mocked(
+ AgentServerConversationService.createLocalPlanningConversation,
+ ).mockResolvedValue(makeConversation({ id: "plan-conv-1" }));
+
+ const { result, queryClient } = renderPlanHookWithClient();
+ const invalidateQueriesSpy = vi.spyOn(queryClient, "invalidateQueries");
+
+ act(() => {
+ result.current.handlePlanClick();
+ });
+
+ await waitFor(() => {
+ expect(mockSetLocalPlanningConversationId).toHaveBeenCalledWith(
+ "plan-conv-1",
+ );
+ });
+
+ expect(invalidateQueriesSpy).toHaveBeenCalledWith({
+ queryKey: ["user", "conversation", "conv-123"],
+ });
+ });
+
+ it("passes an initial message through to the newly created local planner", async () => {
+ vi.mocked(useActiveBackend).mockReturnValue({
+ backend: { kind: "local" },
+ } as ReturnType<typeof useActiveBackend>);
+ vi.mocked(
+ AgentServerConversationService.createLocalPlanningConversation,
+ ).mockResolvedValue(makeConversation({ id: "plan-conv-1" }));
+
+ const { result } = renderPlanHook();
+
+ act(() => {
+ result.current.handlePlanClick(
+ undefined,
+ "Build a website about open source.",
+ );
+ });
+
+ await waitFor(() => {
+ expect(
+ AgentServerConversationService.createLocalPlanningConversation,
+ ).toHaveBeenCalledWith(
+ "conv-123",
+ "Build a website about open source.",
+ );
+ });
+ });
+
+ it("recovers the planner from the server when browser storage was cleared", () => {
+ vi.mocked(useActiveBackend).mockReturnValue({
+ backend: { kind: "local" },
+ } as ReturnType<typeof useActiveBackend>);
+ // Storage loss: no metadata hint, only the server-derived relationship.
+ vi.mocked(getStoredConversationMetadata).mockReturnValue(null);
+ vi.mocked(useActiveConversation).mockReturnValue(
+ asMockReturnValue<ReturnType<typeof useActiveConversation>>({
+ data: makeConversation({ sub_conversation_ids: ["plan-conv-1"] }),
+ isLoading: false,
+ isPending: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ }),
+ );
+ vi.mocked(useSubConversations).mockReturnValue(
+ asMockReturnValue<ReturnType<typeof useSubConversations>>({
+ data: [makeTaggedPlannerConversation("plan-conv-1", "conv-123")],
+ }),
+ );
+
+ renderPlanHook();
+
+ expect(mockSetLocalPlanningConversationId).toHaveBeenCalledWith(
+ "plan-conv-1",
+ );
+ });
+
+ it("adopts the server-reported planner instead of creating a second hidden one", () => {
+ vi.mocked(useActiveBackend).mockReturnValue({
+ backend: { kind: "local" },
+ } as ReturnType<typeof useActiveBackend>);
+ vi.mocked(getStoredConversationMetadata).mockReturnValue(null);
+ vi.mocked(useActiveConversation).mockReturnValue(
+ asMockReturnValue<ReturnType<typeof useActiveConversation>>({
+ data: makeConversation({ sub_conversation_ids: ["plan-conv-1"] }),
+ isLoading: false,
+ isPending: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ }),
+ );
+ vi.mocked(useSubConversations).mockReturnValue(
+ asMockReturnValue<ReturnType<typeof useSubConversations>>({
+ data: [makeTaggedPlannerConversation("plan-conv-1", "conv-123")],
+ }),
+ );
+
+ const { result } = renderPlanHook();
+
+ act(() => {
+ result.current.handlePlanClick();
+ });
+
+ expect(
+ AgentServerConversationService.createLocalPlanningConversation,
+ ).not.toHaveBeenCalled();
+ });
+
+ it("does not adopt an unrelated non-planner child conversation as the planner", async () => {
+ // Regression: sub_conversation_ids is the generic child list β€” an
+ // existing, non-planner child (e.g. a delegated sub-agent) must not be
+ // mistaken for the planner just because it's present in the list.
+ vi.mocked(useActiveBackend).mockReturnValue({
+ backend: { kind: "local" },
+ } as ReturnType<typeof useActiveBackend>);
+ vi.mocked(getStoredConversationMetadata).mockReturnValue(null);
+ vi.mocked(useActiveConversation).mockReturnValue(
+ asMockReturnValue<ReturnType<typeof useActiveConversation>>({
+ data: makeConversation({ sub_conversation_ids: ["other-conv-1"] }),
+ isLoading: false,
+ isPending: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ }),
+ );
+ // Fetched, but untagged for this parent β€” not the planner.
+ vi.mocked(useSubConversations).mockReturnValue(
+ asMockReturnValue<ReturnType<typeof useSubConversations>>({
+ data: [makeConversation({ id: "other-conv-1", tags: null })],
+ }),
+ );
+ vi.mocked(
+ AgentServerConversationService.createLocalPlanningConversation,
+ ).mockResolvedValue(makeConversation({ id: "plan-conv-1" }));
+
+ const { result } = renderPlanHook();
+
+ // The unrelated child must never be restored as the planner.
+ expect(mockSetLocalPlanningConversationId).not.toHaveBeenCalledWith(
+ "other-conv-1",
+ );
+
+ act(() => {
+ result.current.handlePlanClick();
+ });
+
+ // With no tagged planner found, clicking Plan creates a real one
+ // instead of silently adopting the unrelated child.
+ await waitFor(() => {
+ expect(
+ AgentServerConversationService.createLocalPlanningConversation,
+ ).toHaveBeenCalledWith("conv-123", undefined);
+ });
+ });
+
+ it("resets to code mode and shows an error toast when local planner creation fails", async () => {
+ vi.mocked(useActiveBackend).mockReturnValue({
+ backend: { kind: "local" },
+ } as ReturnType<typeof useActiveBackend>);
+ vi.mocked(
+ AgentServerConversationService.createLocalPlanningConversation,
+ ).mockRejectedValue(new Error("boom"));
+
+ const { result } = renderPlanHook();
+
+ act(() => {
+ result.current.handlePlanClick();
+ });
+
+ expect(mockSetConversationMode).toHaveBeenCalledWith("plan");
+
+ await waitFor(() => {
+ expect(mockSetConversationMode).toHaveBeenCalledWith("code");
+ });
+ expect(displayErrorToast).toHaveBeenCalled();
+ expect(mockSetLocalPlanningConversationId).not.toHaveBeenCalled();
+ });
+
+ it("does not create a duplicate local planning conversation", () => {
+ vi.mocked(useActiveBackend).mockReturnValue({
+ backend: { kind: "local" },
+ } as ReturnType<typeof useActiveBackend>);
+ vi.mocked(useConversationStore).mockReturnValue(
+ asMockReturnValue<ReturnType<typeof useConversationStore>>({
+ setConversationMode: mockSetConversationMode,
+ setSubConversationTaskId: mockSetSubConversationTaskId,
+ subConversationTaskId: null,
+ setLocalPlanningConversationId: mockSetLocalPlanningConversationId,
+ localPlanningConversationId: "plan-conv-1",
+ }),
+ );
+
+ const { result } = renderPlanHook();
+
+ act(() => {
+ result.current.handlePlanClick();
+ });
+
+ expect(
+ AgentServerConversationService.createLocalPlanningConversation,
+ ).not.toHaveBeenCalled();
+ expect(mockCreateConversation).not.toHaveBeenCalled();
+ });
+
+ it("does not create a second local planning conversation while the first creation is still in flight", async () => {
+ // Regression: the local-backend guard used to check only
+ // localPlanningConversationId/serverPlanningConversationId, neither of
+ // which is set yet while the mutation is still pending β€” a second
+ // invocation (e.g. a rapid re-click, or a /plan submission racing the
+ // button) could pass the guard and spawn a duplicate planner.
+ vi.mocked(useActiveBackend).mockReturnValue({
+ backend: { kind: "local" },
+ } as ReturnType<typeof useActiveBackend>);
+
+ let resolveCreate: (value: AppConversation) => void = () => {};
+ const pending = new Promise<AppConversation>((resolve) => {
+ resolveCreate = resolve;
+ });
+ vi.mocked(
+ AgentServerConversationService.createLocalPlanningConversation,
+ ).mockReturnValue(pending);
+
+ const { result } = renderPlanHook();
+
+ act(() => {
+ result.current.handlePlanClick();
+ });
+
+ await waitFor(() => {
+ expect(result.current.isCreatingConversation).toBe(true);
+ });
+
+ act(() => {
+ result.current.handlePlanClick();
+ });
+
+ expect(
+ AgentServerConversationService.createLocalPlanningConversation,
+ ).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ resolveCreate(makeConversation({ id: "plan-conv-1" }));
+ await pending;
+ });
+ });
+ });
+
describe("plan creation prevention", () => {
it("prevents plan creation when subConversationTaskId exists in store", () => {
const taskId = "task-123";
@@ -202,10 +588,12 @@ describe("useHandlePlanClick", () => {
setConversationMode: mockSetConversationMode,
setSubConversationTaskId: mockSetSubConversationTaskId,
subConversationTaskId: taskId,
+ setLocalPlanningConversationId: mockSetLocalPlanningConversationId,
+ localPlanningConversationId: null,
}),
);
- const { result } = renderHook(() => useHandlePlanClick());
+ const { result } = renderPlanHook();
act(() => {
result.current.handlePlanClick();
@@ -229,7 +617,7 @@ describe("useHandlePlanClick", () => {
typeof useActiveConversation
>);
- const { result } = renderHook(() => useHandlePlanClick());
+ const { result } = renderPlanHook();
act(() => {
result.current.handlePlanClick();
@@ -251,7 +639,7 @@ describe("useHandlePlanClick", () => {
}),
);
- const { result } = renderHook(() => useHandlePlanClick());
+ const { result } = renderPlanHook();
act(() => {
result.current.handlePlanClick();
@@ -278,7 +666,7 @@ describe("useHandlePlanClick", () => {
}),
);
- const { result } = renderHook(() => useHandlePlanClick());
+ const { result } = renderPlanHook();
act(() => {
result.current.handlePlanClick();
@@ -311,6 +699,40 @@ describe("useHandlePlanClick", () => {
expect(displaySuccessToast).toHaveBeenCalled();
});
+ it("passes an initial message through as the cloud planner's query", () => {
+ const conversationId = "conv-123";
+
+ vi.mocked(useActiveConversation).mockReturnValue(
+ asMockReturnValue<ReturnType<typeof useActiveConversation>>({
+ data: makeConversation({ id: conversationId }),
+ isLoading: false,
+ isPending: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ }),
+ );
+
+ const { result } = renderPlanHook();
+
+ act(() => {
+ result.current.handlePlanClick(
+ undefined,
+ "Build a website about open source.",
+ );
+ });
+
+ expect(mockCreateConversation).toHaveBeenCalledWith(
+ {
+ parentConversationId: conversationId,
+ agentType: "plan",
+ entryPoint: "plan_sub_conversation",
+ query: "Build a website about open source.",
+ },
+ expect.objectContaining({ onSuccess: expect.any(Function) }),
+ );
+ });
+
it("does not persist subConversationTaskId when task_id is missing", () => {
const conversationId = "conv-123";
@@ -325,7 +747,7 @@ describe("useHandlePlanClick", () => {
}),
);
- const { result } = renderHook(() => useHandlePlanClick());
+ const { result } = renderPlanHook();
act(() => {
result.current.handlePlanClick();
diff --git a/src/api/agent-server-adapter.test.ts b/src/api/agent-server-adapter.test.ts
index 42f8ac9dde..a23a154399 100644
--- a/src/api/agent-server-adapter.test.ts
+++ b/src/api/agent-server-adapter.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { CANVAS_UI_CLIENT_TOOL_NAME } from "#/constants/canvas-ui";
import { LAUNCH_CHILD_CONVERSATION_TOOL_NAME } from "#/constants/child-conversation";
import { DEFAULT_SETTINGS } from "#/services/settings";
@@ -7,7 +7,26 @@ import {
AGENT_CANVAS_SOURCE,
CLIENT_SOURCE_TAG_KEY,
buildStartConversationRequest,
+ buildStartPlanningConversationRequest,
+ buildStartPlanningConversationRequestWithEncryptedSettings,
+ toConversationPage,
} from "./agent-server-adapter";
+import SettingsService from "./settings-service/settings-service.api";
+import AgentProfilesService from "./agent-profiles-service/agent-profiles-service.api";
+import ProfilesService from "./profiles-service/profiles-service.api";
+
+vi.mock("./settings-service/settings-service.api", () => ({
+ default: { getSettingsForConversation: vi.fn() },
+}));
+vi.mock("./secrets-service", () => ({
+ SecretsService: { getSecrets: vi.fn().mockResolvedValue([]) },
+}));
+vi.mock("./agent-profiles-service/agent-profiles-service.api", () => ({
+ default: { listProfiles: vi.fn() },
+}));
+vi.mock("./profiles-service/profiles-service.api", () => ({
+ default: { getProfile: vi.fn() },
+}));
const encryptedValue = "gAAAAAencrypted-mcp-header";
@@ -36,6 +55,12 @@ function getAgentContextSkillNames(
return agentSettings?.agent_context?.skills?.map((skill) => skill.name) ?? [];
}
+function getPlannerAgentContextSkillNames(payload: {
+ agent: { agent_context?: { skills?: Array<{ name?: string }> } };
+}): Array<string | undefined> {
+ return payload.agent.agent_context?.skills?.map((skill) => skill.name) ?? [];
+}
+
describe("buildStartConversationRequest", () => {
it("marks OpenHands start requests as encrypted when MCP headers are encrypted", () => {
const agentSettings = {
@@ -102,6 +127,126 @@ describe("buildStartConversationRequest", () => {
expect(payload.secrets_encrypted).toBe(true);
});
+ it("builds a raw planning agent request for local Planner", () => {
+ const agentSettings = {
+ agent_kind: "openhands",
+ llm: {
+ model: "openhands/minimax-m2.7",
+ api_key: "gAAAAAencrypted-llm-api-key",
+ },
+ };
+
+ const payload = buildStartPlanningConversationRequest({
+ encryptedAgentSettings: agentSettings,
+ workingDir: "/workspace/project/agent-canvas",
+ parentConversationId: "parent-1",
+ secretsEncrypted: true,
+ customSecrets: [{ name: "CUSTOM_TOKEN" }],
+ });
+
+ expect(payload.agent).toMatchObject({
+ kind: "Agent",
+ system_prompt_filename: "system_prompt_planning.j2",
+ system_prompt_kwargs: {
+ plan_structure: expect.stringContaining("OBJECTIVE"),
+ },
+ llm: {
+ model: "openhands/minimax-m2.7",
+ api_key: "gAAAAAencrypted-llm-api-key",
+ },
+ tools: [
+ { name: "glob", params: {} },
+ { name: "grep", params: {} },
+ {
+ name: "planning_file_editor",
+ params: {
+ plan_path: "/workspace/project/agent-canvas/.agents_tmp/PLAN.md",
+ },
+ },
+ ],
+ // Matches the SDK planning preset's get_planning_condenser.
+ condenser: {
+ kind: "LLMSummarizingCondenser",
+ max_size: 100,
+ keep_first: 6,
+ llm: {
+ model: "openhands/minimax-m2.7",
+ usage_id: "planning_condenser",
+ },
+ },
+ });
+ expect(payload.agent_settings).toBeUndefined();
+ expect(payload.worktree).toBe(false);
+ expect(payload.tags).toEqual({ plannerparent: "parent-1" });
+ expect(payload.secrets_encrypted).toBe(true);
+ expect(payload.secrets).toHaveProperty("CUSTOM_TOKEN");
+ });
+
+ it("links the local planner to its parent server-side so the relationship survives storage loss", () => {
+ const payload = buildStartPlanningConversationRequest({
+ encryptedAgentSettings: {
+ agent_kind: "openhands",
+ llm: { model: "openhands/minimax-m2.7" },
+ },
+ workingDir: "/workspace/project",
+ parentConversationId: "parent-1",
+ });
+
+ // The agent-server derives the parent's `sub_conversation_ids` from this,
+ // which is what makes the planner recoverable without localStorage.
+ expect(payload.parent_conversation_id).toBe("parent-1");
+ });
+
+ it("defaults the planner's max_iterations to 500 when not provided", () => {
+ const payload = buildStartPlanningConversationRequest({
+ encryptedAgentSettings: {
+ agent_kind: "openhands",
+ llm: { model: "openhands/minimax-m2.7" },
+ },
+ workingDir: "/workspace/project",
+ parentConversationId: "parent-1",
+ });
+
+ expect(payload.max_iterations).toBe(500);
+ });
+
+ it("uses the caller-provided max_iterations instead of the hardcoded default", () => {
+ const payload = buildStartPlanningConversationRequest({
+ encryptedAgentSettings: {
+ agent_kind: "openhands",
+ llm: { model: "openhands/minimax-m2.7" },
+ },
+ workingDir: "/workspace/project",
+ parentConversationId: "parent-1",
+ maxIterations: 250,
+ });
+
+ expect(payload.max_iterations).toBe(250);
+ });
+
+ it("omits local planner helper conversations from paginated conversation results", () => {
+ const page = toConversationPage({
+ items: [
+ {
+ id: "main-1",
+ created_at: "2024-01-01T00:00:00.000Z",
+ updated_at: "2024-01-01T00:00:00.000Z",
+ execution_status: "idle",
+ tags: {},
+ },
+ {
+ id: "plan-1",
+ created_at: "2024-01-01T00:00:00.000Z",
+ updated_at: "2024-01-01T00:00:00.000Z",
+ execution_status: "idle",
+ tags: { plannerparent: "main-1" },
+ },
+ ],
+ });
+
+ expect(page.items.map((item) => item.id)).toEqual(["main-1"]);
+ });
+
it("keeps ACP start requests unencrypted when no encrypted MCP values are present", () => {
const agentSettings = {
agent_kind: "acp",
@@ -257,6 +402,227 @@ describe("buildStartConversationRequest", () => {
});
});
+describe("buildStartPlanningConversationRequestWithEncryptedSettings", () => {
+ const globallyActiveSettings = {
+ agentSettings: {
+ agent_kind: "openhands",
+ llm: {
+ model: "openhands/globally-active-model",
+ api_key: "gAAAAAglobal-key",
+ base_url: "https://global.example.com",
+ },
+ },
+ conversationSettings: {},
+ secretsEncrypted: true,
+ skillEnablement: { disabledSkills: [] },
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(SettingsService.getSettingsForConversation).mockResolvedValue(
+ globallyActiveSettings,
+ );
+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({
+ profiles: [
+ {
+ id: "profile-parent",
+ name: "parent-profile",
+ agent_kind: "openhands",
+ revision: 1,
+ llm_profile_ref: "parent-llm",
+ mcp_server_refs: null,
+ },
+ ],
+ active_agent_profile_id: "profile-other",
+ });
+ vi.mocked(ProfilesService.getProfile).mockResolvedValue({
+ name: "parent-llm",
+ api_key_set: true,
+ config: {
+ model: "openhands/parent-profile-model",
+ api_key: "gAAAAAparent-key",
+ base_url: "https://parent.example.com",
+ },
+ });
+ });
+
+ it("pins the planner to the parent's launched profile, not the globally active one", async () => {
+ const payload =
+ await buildStartPlanningConversationRequestWithEncryptedSettings({
+ workingDir: "/workspace/project",
+ parentConversationId: "parent-1",
+ parentAgentProfileId: "profile-parent",
+ });
+
+ expect(ProfilesService.getProfile).toHaveBeenCalledWith(
+ "parent-llm",
+ "encrypted",
+ );
+ expect(payload.agent.llm).toMatchObject({
+ model: "openhands/parent-profile-model",
+ api_key: "gAAAAAparent-key",
+ base_url: "https://parent.example.com",
+ });
+ });
+
+ it("falls back to global settings when the parent was not launched from a profile", async () => {
+ const payload =
+ await buildStartPlanningConversationRequestWithEncryptedSettings({
+ workingDir: "/workspace/project",
+ parentConversationId: "parent-1",
+ parentAgentProfileId: null,
+ });
+
+ expect(AgentProfilesService.listProfiles).not.toHaveBeenCalled();
+ expect(payload.agent.llm).toMatchObject({
+ model: "openhands/globally-active-model",
+ });
+ });
+
+ it("prefers the parent conversation's current active_profile over its launched agent profile", async () => {
+ // The conversation launched under "parent-profile" (-> "parent-llm"), but
+ // was later switched to a different LLM profile via /model or the
+ // agent's own SwitchLLMTool β€” active_profile tracks that switch.
+ vi.mocked(ProfilesService.getProfile).mockImplementation(async (name) =>
+ name === "switched-llm"
+ ? {
+ name: "switched-llm",
+ api_key_set: true,
+ config: {
+ model: "openhands/switched-model",
+ api_key: "gAAAAAswitched-key",
+ base_url: "https://switched.example.com",
+ },
+ }
+ : {
+ name: "parent-llm",
+ api_key_set: true,
+ config: {
+ model: "openhands/parent-profile-model",
+ api_key: "gAAAAAparent-key",
+ base_url: "https://parent.example.com",
+ },
+ },
+ );
+
+ const payload =
+ await buildStartPlanningConversationRequestWithEncryptedSettings({
+ workingDir: "/workspace/project",
+ parentConversationId: "parent-1",
+ parentActiveProfileName: "switched-llm",
+ parentAgentProfileId: "profile-parent",
+ });
+
+ expect(ProfilesService.getProfile).toHaveBeenCalledWith(
+ "switched-llm",
+ "encrypted",
+ );
+ // The launched agent profile must not even be consulted once
+ // active_profile resolves successfully.
+ expect(AgentProfilesService.listProfiles).not.toHaveBeenCalled();
+ expect(payload.agent.llm).toMatchObject({
+ model: "openhands/switched-model",
+ api_key: "gAAAAAswitched-key",
+ base_url: "https://switched.example.com",
+ });
+ });
+
+ it("falls back to the launched agent profile when active_profile can't be resolved", async () => {
+ vi.mocked(ProfilesService.getProfile).mockImplementation(async (name) => {
+ if (name === "dangling-llm") throw new Error("not found");
+ return {
+ name: "parent-llm",
+ api_key_set: true,
+ config: {
+ model: "openhands/parent-profile-model",
+ api_key: "gAAAAAparent-key",
+ base_url: "https://parent.example.com",
+ },
+ };
+ });
+
+ const payload =
+ await buildStartPlanningConversationRequestWithEncryptedSettings({
+ workingDir: "/workspace/project",
+ parentConversationId: "parent-1",
+ parentActiveProfileName: "dangling-llm",
+ parentAgentProfileId: "profile-parent",
+ });
+
+ expect(payload.agent.llm).toMatchObject({
+ model: "openhands/parent-profile-model",
+ });
+ });
+
+ it("falls back to global settings when the parent's profile reference dangles", async () => {
+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({
+ profiles: [],
+ active_agent_profile_id: null,
+ });
+
+ const payload =
+ await buildStartPlanningConversationRequestWithEncryptedSettings({
+ workingDir: "/workspace/project",
+ parentConversationId: "parent-1",
+ parentAgentProfileId: "profile-parent",
+ });
+
+ expect(ProfilesService.getProfile).not.toHaveBeenCalled();
+ expect(payload.agent.llm).toMatchObject({
+ model: "openhands/globally-active-model",
+ });
+ });
+
+ it("mirrors the parent's configured max_iterations instead of hardcoding a lower cap", async () => {
+ vi.mocked(SettingsService.getSettingsForConversation).mockResolvedValue({
+ ...globallyActiveSettings,
+ conversationSettings: { max_iterations: 1000 },
+ });
+
+ const payload =
+ await buildStartPlanningConversationRequestWithEncryptedSettings({
+ workingDir: "/workspace/project",
+ parentConversationId: "parent-1",
+ });
+
+ expect(payload.max_iterations).toBe(1000);
+ });
+
+ it("falls back to 500 when the parent has no configured max_iterations", async () => {
+ const payload =
+ await buildStartPlanningConversationRequestWithEncryptedSettings({
+ workingDir: "/workspace/project",
+ parentConversationId: "parent-1",
+ });
+
+ expect(payload.max_iterations).toBe(500);
+ });
+
+ it("applies the full skill enablement to the planner's agent context, mirroring the code agent", async () => {
+ // Both lists, because they cover different populations (#16302): the
+ // allow-list gates the bundled catalog, the deny-list still wins over it.
+ // `add-javadoc` is a catalog skill outside the recommended defaults, so
+ // it only loads because the allow-list names it.
+ vi.mocked(SettingsService.getSettingsForConversation).mockResolvedValue({
+ ...globallyActiveSettings,
+ skillEnablement: {
+ enabledSkills: ["add-javadoc", "agent-memory"],
+ disabledSkills: ["agent-memory"],
+ },
+ });
+
+ const payload =
+ await buildStartPlanningConversationRequestWithEncryptedSettings({
+ workingDir: "/workspace/project",
+ parentConversationId: "parent-1",
+ });
+
+ const skillNames = getPlannerAgentContextSkillNames(payload);
+ expect(skillNames).not.toContain("agent-memory");
+ expect(skillNames).toContain("add-javadoc");
+ });
+});
+
describe("buildStartConversationRequest β€” agentProfileId path", () => {
it("sends agent_profile_id and omits agent_settings (mutually exclusive)", () => {
const settings = makeSettings({
diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.ts
index 9585602de4..8febe54e86 100644
--- a/src/api/agent-server-adapter.ts
+++ b/src/api/agent-server-adapter.ts
@@ -51,6 +51,14 @@ import {
LAUNCH_CHILD_CONVERSATION_CLIENT_TOOL,
LAUNCH_CHILD_CONVERSATION_TOOL_NAME,
} from "./launch-child-conversation-client-tool";
+import {
+ buildPlanPath,
+ LOCAL_PLANNER_PARENT_TAG_KEY,
+ PLAN_STRUCTURE_TEXT,
+ PLANNING_AGENT_INSTRUCTION,
+ PLANNING_FILE_EDITOR_TOOL_NAME,
+ PLANNING_SYSTEM_PROMPT_FILENAME,
+} from "#/utils/plan-file";
export interface DirectConversationInfo {
id: string;
@@ -115,11 +123,26 @@ export interface DirectConversationInfo {
agent_profile_id: string;
revision: number;
} | null;
+ /**
+ * Server-owned, derived from the catalog's ``parent_conversation_id`` link
+ * (agent-server >= 1.37.1, SDK #4188) β€” a conversation started with a
+ * parent is discoverable here on any browser, which is what makes the
+ * local planner's relationship server state rather than a browser-local
+ * hint. Absent on older agent-servers and on the cloud wire shape.
+ */
+ sub_conversation_ids?: string[] | null;
}
const DEFAULT_TOOL_NAMES = ["terminal", "file_editor", "task_tracker"];
const BROWSER_TOOL_SET_NAME = "browser_tool_set";
const TASK_TOOL_SET_NAME = "task_tool_set";
+// Falls back to the same default the code agent uses when the user has not
+// configured `conversation_settings.max_iterations` (see buildConfiguredConversationSettings).
+const DEFAULT_MAX_ITERATIONS = 500;
+
+function resolveMaxIterations(value: unknown): number {
+ return typeof value === "number" ? value : DEFAULT_MAX_ITERATIONS;
+}
function browserToolsEnabled() {
return import.meta.env.VITE_ENABLE_BROWSER_TOOLS !== "false";
@@ -404,7 +427,7 @@ export function toAppConversation(
working_dir: info.workspace?.working_dir ?? getAgentServerWorkingDir(),
},
public: false,
- sub_conversation_ids: [],
+ sub_conversation_ids: info.sub_conversation_ids ?? [],
};
}
@@ -413,7 +436,9 @@ export function toConversationPage(data: {
next_page_id?: string | null;
}): AppConversationPage {
return {
- items: data.items.map(toAppConversation),
+ items: data.items
+ .filter((item) => !item.tags?.[LOCAL_PLANNER_PARENT_TAG_KEY])
+ .map(toAppConversation),
next_page_id: data.next_page_id ?? null,
};
}
@@ -481,6 +506,8 @@ export const AUTOMATION_TAG_KEYS: readonly string[] = [
* - ``automationid`` / ``automationrunid`` β†’ raw UUIDs consumed by the
* conversation panel's automation filter (chip noise), while
* ``automationname`` / ``automationtrigger`` stay visible
+ * - ``localplannerparent`` β†’ internal routing for the local planner; already
+ * surfaced by the hidden-from-list planner filter
*/
export const RESERVED_CONVERSATION_TAG_KEYS: ReadonlySet<string> = new Set([
ACP_SERVER_TAG_KEY,
@@ -497,6 +524,7 @@ export const RESERVED_CONVERSATION_TAG_KEYS: ReadonlySet<string> = new Set([
"archiveworkspacepath",
"workspace",
"working_dir",
+ LOCAL_PLANNER_PARENT_TAG_KEY,
]);
/**
@@ -572,6 +600,41 @@ function normalizeSecretString(value: unknown): string | undefined {
return trimmed.length > 0 ? trimmed : undefined;
}
+function buildNormalizedLlmSettings(value: unknown): SettingsRecord {
+ const llm = toRecord(value);
+
+ llm.model =
+ typeof llm.model === "string" && llm.model.trim().length > 0
+ ? llm.model
+ : DEFAULT_SETTINGS.llm_model;
+
+ const apiKey = normalizeSecretString(llm.api_key);
+ if (apiKey) {
+ llm.api_key = apiKey;
+ } else {
+ delete llm.api_key;
+ }
+
+ const baseUrl = normalizeSecretString(llm.base_url);
+ if (baseUrl) {
+ llm.base_url = baseUrl;
+ } else {
+ delete llm.base_url;
+ }
+
+ if (isSubscriptionLlmConfig(llm)) {
+ llm.auth_type = LLM_AUTH_TYPE_SUBSCRIPTION;
+ llm.subscription_vendor = OPENAI_SUBSCRIPTION_VENDOR;
+ delete llm.api_key;
+ delete llm.base_url;
+ } else {
+ delete llm.auth_type;
+ delete llm.subscription_vendor;
+ }
+
+ return llm;
+}
+
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === "object" && !Array.isArray(value);
}
@@ -915,41 +978,12 @@ function buildConfiguredOpenHandsAgentSettings(
query?: string,
): AgentSettingsPayload {
const agentSettings = toRecord(settings.agent_settings);
- const llm = toRecord(agentSettings.llm);
-
- llm.model =
- typeof llm.model === "string" && llm.model.trim().length > 0
- ? llm.model
- : DEFAULT_SETTINGS.llm_model;
+ const llm = buildNormalizedLlmSettings(agentSettings.llm);
// Stream assistant tokens (parity with ACP agents). The agent-server only
// emits StreamingDeltaEvents for SDK LLM agents when an LLM has stream=True.
llm.stream = true;
- const apiKey = normalizeSecretString(llm.api_key);
- if (apiKey) {
- llm.api_key = apiKey;
- } else {
- delete llm.api_key;
- }
-
- const baseUrl = normalizeSecretString(llm.base_url);
- if (baseUrl) {
- llm.base_url = baseUrl;
- } else {
- delete llm.base_url;
- }
-
- if (isSubscriptionLlmConfig(llm)) {
- llm.auth_type = LLM_AUTH_TYPE_SUBSCRIPTION;
- llm.subscription_vendor = OPENAI_SUBSCRIPTION_VENDOR;
- delete llm.api_key;
- delete llm.base_url;
- } else {
- delete llm.auth_type;
- delete llm.subscription_vendor;
- }
-
const mcpConfig = toRecord(agentSettings.mcp_config);
if (Object.keys(mcpConfig).length === 0) {
delete agentSettings.mcp_config;
@@ -1035,18 +1069,17 @@ interface LookupSecret {
description?: string;
}
-type StartConversationPayload = Record<string, unknown> & {
- // Omitted when launching via ``agent_profile_id`` β€” the two are mutually
- // exclusive agent sources; the server resolves the profile server-side.
- agent_settings?: AgentSettingsPayload;
- agent_profile_id?: string;
+/** A custom secret's public identity β€” name + optional description, no value. */
+type CustomSecretInput = { name: string; description?: string };
+
+type StartConversationPayloadBase = Record<string, unknown> & {
workspace: LocalWorkspacePayload;
confirmation_policy: SettingsRecord;
security_analyzer?: SettingsRecord;
initial_message?: InitialMessagePayload;
max_iterations: number;
stuck_detection: true;
- autotitle: true;
+ autotitle: boolean;
title_llm_profile?: string;
worktree: boolean;
secrets_encrypted?: true;
@@ -1058,6 +1091,23 @@ type StartConversationPayload = Record<string, unknown> & {
tool_module_qualnames?: Record<string, string>;
};
+type AgentSettingsStartConversationPayload = StartConversationPayloadBase & {
+ // Omitted when launching via ``agent_profile_id`` β€” the two are mutually
+ // exclusive agent sources; the server resolves the profile server-side.
+ agent_settings?: AgentSettingsPayload;
+ agent_profile_id?: string;
+ agent?: never;
+};
+
+// The local planner bypasses agent assembly entirely and sends a raw agent
+// spec, so neither of the two managed agent sources applies.
+type RawAgentStartConversationPayload = StartConversationPayloadBase & {
+ agent: SettingsRecord;
+ agent_settings?: never;
+ agent_profile_id?: never;
+ parent_conversation_id?: string;
+};
+
export interface StartConversationOptions {
settings: Settings;
query?: string;
@@ -1074,7 +1124,7 @@ export interface StartConversationOptions {
encryptedAgentSettings?: Record<string, SettingsValue>;
encryptedConversationSettings?: Record<string, SettingsValue>;
secretsEncrypted?: boolean;
- customSecrets?: Array<{ name: string; description?: string }>;
+ customSecrets?: CustomSecretInput[];
// When set, the conversation launches from this AgentProfile (resolved
// server-side) instead of an inline ``agent_settings`` dump (#3727).
agentProfileId?: string;
@@ -1084,9 +1134,41 @@ export interface StartConversationOptions {
workspaceHookConfig?: HookConfig | null;
}
+/**
+ * Build the `request.secrets` map shared by the standard and planning
+ * conversation builders. Every saved secret rides as a LookupSecret the
+ * agent-server resolves from its own store at spawn time β€” `request.secrets` is
+ * the sole channel, uniform for ACP and non-ACP (agent-canvas#1039). For ACP the
+ * resolution runs off the event loop (software-agent-sdk#3510, >=1.25.0), so the
+ * loopback fetch can't deadlock. Returns `undefined` when there are no custom
+ * secrets so callers can omit the field.
+ */
+function buildCustomSecrets(
+ customSecrets: CustomSecretInput[] | undefined,
+): Record<string, LookupSecret> | undefined {
+ if (!customSecrets?.length) return undefined;
+
+ const backend = getEffectiveLocalBackend();
+ const headers = backend ? buildAuthHeaders(backend) : {};
+
+ const secrets: Record<string, LookupSecret> = {};
+ for (const secret of customSecrets) {
+ const lookupSecret: LookupSecret = {
+ kind: "LookupSecret",
+ url: `/api/settings/secrets/${encodeURIComponent(secret.name)}`,
+ description: secret.description,
+ };
+ if (Object.keys(headers).length > 0) {
+ lookupSecret.headers = headers;
+ }
+ secrets[secret.name] = lookupSecret;
+ }
+ return secrets;
+}
+
export function buildStartConversationRequest(
options: StartConversationOptions,
-): StartConversationPayload {
+): AgentSettingsStartConversationPayload {
const sourceAgentSettings = options.encryptedAgentSettings
? { ...options.settings, agent_settings: options.encryptedAgentSettings }
: options.settings;
@@ -1120,7 +1202,7 @@ export function buildStartConversationRequest(
sourceConversationOptions,
);
- const payload: StartConversationPayload = {
+ const payload: AgentSettingsStartConversationPayload = {
// ``agent_profile_id`` and ``agent_settings`` are mutually exclusive agent
// sources; the profile path lets the server resolve the profile (#3727).
//
@@ -1157,10 +1239,7 @@ export function buildStartConversationRequest(
: [],
confirmation_policy:
getConversationConfirmationPolicy(conversationSettings),
- max_iterations:
- typeof conversationSettings.max_iterations === "number"
- ? conversationSettings.max_iterations
- : 500,
+ max_iterations: resolveMaxIterations(conversationSettings.max_iterations),
stuck_detection: true,
autotitle: true,
...(options.titleLlmProfile
@@ -1240,36 +1319,242 @@ export function buildStartConversationRequest(
payload.agent_definitions = conversationSettings.agent_definitions;
}
- // Every saved secret rides as a LookupSecret the agent-server resolves back
- // from its own store at spawn time β€” ``request.secrets`` is the sole channel,
- // uniform for ACP and non-ACP (agent-canvas#1039). For ACP the resolution
- // runs off the event loop (software-agent-sdk#3510, >=1.25.0), so the loopback
- // fetch can't deadlock.
- if (options.customSecrets && options.customSecrets.length > 0) {
- const backend = getEffectiveLocalBackend();
- const headers = backend ? buildAuthHeaders(backend) : {};
-
- const secrets: Record<string, LookupSecret> = {};
- for (const secret of options.customSecrets) {
- const lookupSecret: LookupSecret = {
- kind: "LookupSecret",
- url: `/api/settings/secrets/${encodeURIComponent(secret.name)}`,
- description: secret.description,
- };
-
- if (Object.keys(headers).length > 0) {
- lookupSecret.headers = headers;
- }
+ const secrets = buildCustomSecrets(options.customSecrets);
+ if (secrets) {
+ payload.secrets = secrets;
+ }
- secrets[secret.name] = lookupSecret;
- }
+ return payload;
+}
+
+export function buildStartPlanningConversationRequest(options: {
+ encryptedAgentSettings: Record<string, SettingsValue>;
+ workingDir: string;
+ parentConversationId: string;
+ initialMessage?: string;
+ secretsEncrypted?: boolean;
+ customSecrets?: CustomSecretInput[];
+ /** Mirrors the parent's configured `conversation_settings.max_iterations` β€” see DEFAULT_MAX_ITERATIONS. */
+ maxIterations?: number;
+ /** Mirrors the code agent's skill filtering β€” see buildConfiguredOpenHandsAgentSettings. */
+ skillEnablement?: SkillEnablement;
+}): RawAgentStartConversationPayload {
+ const agentSettings = toRecord(options.encryptedAgentSettings);
+ const llm = buildNormalizedLlmSettings(agentSettings.llm);
+ // Stream assistant tokens, matching the code agent (see
+ // buildConfiguredOpenHandsAgentSettings) β€” otherwise the agent-server never
+ // emits StreamingDeltaEvents for the planner and its replies would appear
+ // all at once instead of token-by-token.
+ llm.stream = true;
+
+ const planPath = buildPlanPath(options.workingDir);
+
+ // Put the planner's directive + boundaries in the system prompt (matching the
+ // OpenHands app-server's PLANNING_AGENT_INSTRUCTION), preserving any suffix
+ // buildAgentContext already set (e.g. the runtime-services block).
+ const agentContext = buildAgentContext(
+ agentSettings,
+ undefined,
+ options.skillEnablement,
+ );
+ const existingSuffix = agentContext.system_message_suffix;
+ agentContext.system_message_suffix =
+ typeof existingSuffix === "string"
+ ? `${PLANNING_AGENT_INSTRUCTION}\n\n${existingSuffix}`
+ : PLANNING_AGENT_INSTRUCTION;
+
+ // Idle planner: "Create a Plan" only switches to plan mode and provisions
+ // this conversation; the user sends the first message themselves, so nothing
+ // is injected into the chat. An explicit initialMessage is still honored.
+ const initialMessage = buildInitialMessage(options.initialMessage);
+
+ const payload: RawAgentStartConversationPayload = {
+ agent: {
+ kind: "Agent",
+ llm,
+ tools: [
+ { name: "glob", params: {} },
+ { name: "grep", params: {} },
+ {
+ name: PLANNING_FILE_EDITOR_TOOL_NAME,
+ params: { plan_path: planPath },
+ },
+ ],
+ system_prompt_filename: PLANNING_SYSTEM_PROMPT_FILENAME,
+ system_prompt_kwargs: { plan_structure: PLAN_STRUCTURE_TEXT },
+ // agent_context (skills + project context) is intentionally included so
+ // the planner shares the code agent's project context. This goes beyond
+ // the bare SDK `get_planning_agent()` preset (which sets no context); it
+ // mirrors how the frontend builds every agent, so the local planner is
+ // not context-starved relative to the code agent.
+ agent_context: agentContext,
+ // Mirror the SDK planning preset's condenser (openhands-tools preset
+ // `get_planning_condenser`): a larger rolling window and more pinned
+ // initial context than the default, with its own usage_id so its
+ // summarization LLM calls are attributed separately. The planning
+ // conversation is sent as a raw agent spec (it bypasses the agent-server's
+ // default agent assembly), so without this it would never condense β€”
+ // diverging from the canonical planning agent on long sessions.
+ condenser: {
+ kind: "LLMSummarizingCondenser",
+ llm: { ...llm, usage_id: "planning_condenser" },
+ max_size: 100,
+ keep_first: 6,
+ },
+ },
+ workspace: {
+ kind: "LocalWorkspace",
+ working_dir: options.workingDir,
+ },
+ // No Canvas UI client tool: the planner's only output is PLAN.md, which the
+ // Planner tab surfaces on its own via PlanningFileEditorObservation. Handing
+ // it the panel-control tool would only let it navigate the right-side panel
+ // away from the plan the user is reading.
+ client_tools: [],
+ confirmation_policy: { kind: "NeverConfirm" },
+ max_iterations: options.maxIterations ?? DEFAULT_MAX_ITERATIONS,
+ stuck_detection: true,
+ autotitle: false,
+ worktree: false,
+ // Two independent links to the parent, for two different jobs:
+ //
+ // - ``parent_conversation_id`` is the server-owned relationship (SDK
+ // #4188, agent-server >= 1.37.1). The parent's ``sub_conversation_ids``
+ // is derived from it, so the planner is recoverable from the server on
+ // any browser and after storage loss. Older agent-servers ignore the
+ // field (``StartConversationRequest`` does not forbid extras), which is
+ // why the client-side metadata hint is still written as a fallback.
+ // - The tag is what hides the helper from the conversation list; it is
+ // also the only marker on agent-servers too old for the parent link.
+ parent_conversation_id: options.parentConversationId,
+ tags: { [LOCAL_PLANNER_PARENT_TAG_KEY]: options.parentConversationId },
+ ...(initialMessage ? { initial_message: initialMessage } : {}),
+ };
+ if (options.secretsEncrypted) {
+ payload.secrets_encrypted = true;
+ }
+
+ const secrets = buildCustomSecrets(options.customSecrets);
+ if (secrets) {
payload.secrets = secrets;
}
return payload;
}
+/**
+ * Resolve the encrypted LLM config for a named LLM profile, so a planner can
+ * run the parent conversation's *current* model (`active_profile`, tracking
+ * `/model` and `SwitchLLMTool`) rather than a stale launch-time value.
+ * Returns `null` β€” caller falls back further β€” if unknown or lookup fails.
+ */
+async function resolveLlmProfileSettings(
+ profileName: string,
+): Promise<SettingsRecord | null> {
+ try {
+ const { default: ProfilesService } =
+ await import("./profiles-service/profiles-service.api");
+ // ``encrypted`` matches ``secrets_encrypted`` on the payload: the
+ // agent-server decrypts with the same cipher it encrypted with.
+ const detail = await ProfilesService.getProfile(profileName, "encrypted");
+ return isPlainRecord(detail.config) ? detail.config : null;
+ } catch (error) {
+ console.warn(
+ `Falling back: could not resolve LLM profile ${profileName}`,
+ error,
+ );
+ return null;
+ }
+}
+
+/**
+ * Resolve the encrypted LLM config the given AgentProfile launches with, as a
+ * fallback for `resolveLlmProfileSettings`. AgentProfiles hold a reference
+ * (`llm_profile_ref`), not credentials, so this is a two-hop lookup: profile
+ * id -> llm profile name -> encrypted LLM config. Returns `null` β€” caller
+ * falls back to global settings β€” for an unknown/ACP/dangling-ref profile or
+ * a failed lookup, none of which should block plan creation outright.
+ */
+async function resolveAgentProfileLlmSettings(
+ agentProfileId: string,
+): Promise<SettingsRecord | null> {
+ try {
+ const { default: AgentProfilesService } =
+ await import("./agent-profiles-service/agent-profiles-service.api");
+
+ const { profiles } = await AgentProfilesService.listProfiles();
+ const summary = profiles.find(
+ (profile) => profile.id === agentProfileId && profile.llm_profile_ref,
+ );
+ if (!summary?.llm_profile_ref) return null;
+
+ return await resolveLlmProfileSettings(summary.llm_profile_ref);
+ } catch (error) {
+ console.warn(
+ `Falling back to global agent settings: could not resolve the LLM for agent profile ${agentProfileId}`,
+ error,
+ );
+ return null;
+ }
+}
+
+export async function buildStartPlanningConversationRequestWithEncryptedSettings(options: {
+ workingDir: string;
+ parentConversationId: string;
+ /**
+ * The parent conversation's current LLM profile (`AppConversation.active_profile`,
+ * tracking `/model` and `SwitchLLMTool`). Takes priority over
+ * `parentAgentProfileId` so a model switch on the parent carries over to a
+ * planner created afterward, without a *different* conversation's global
+ * profile activation repointing it.
+ */
+ parentActiveProfileName?: string | null;
+ /**
+ * `launched_agent_profile.agent_profile_id` of the parent, when started
+ * from an AgentProfile. Fallback for when `parentActiveProfileName` can't
+ * be resolved (e.g. an ACP parent, whose `active_profile` is a stale
+ * launch-time snapshot rather than anything the ACP agent itself runs).
+ */
+ parentAgentProfileId?: string | null;
+ initialMessage?: string;
+}): Promise<RawAgentStartConversationPayload> {
+ const { SecretsService } = await import("./secrets-service");
+
+ const [settingsResult, customSecrets] = await Promise.all([
+ SettingsService.getSettingsForConversation(),
+ SecretsService.getSecrets(),
+ ]);
+
+ const profileLlm =
+ (options.parentActiveProfileName
+ ? await resolveLlmProfileSettings(options.parentActiveProfileName)
+ : null) ??
+ (options.parentAgentProfileId
+ ? await resolveAgentProfileLlmSettings(options.parentAgentProfileId)
+ : null);
+ const encryptedAgentSettings: Record<string, SettingsValue> = profileLlm
+ ? { ...settingsResult.agentSettings, llm: profileLlm as SettingsValue }
+ : settingsResult.agentSettings;
+
+ await assertSubscriptionAuthReady(encryptedAgentSettings);
+
+ // Mirror the code agent's configured cap (see DEFAULT_MAX_ITERATIONS) rather
+ // than hardcoding a different value the planner could silently stop against.
+ const maxIterations = resolveMaxIterations(
+ settingsResult.conversationSettings.max_iterations,
+ );
+
+ return buildStartPlanningConversationRequest({
+ ...options,
+ encryptedAgentSettings,
+ secretsEncrypted: settingsResult.secretsEncrypted,
+ customSecrets,
+ maxIterations,
+ skillEnablement: settingsResult.skillEnablement,
+ });
+}
+
export const SUBSCRIPTION_LOGIN_REQUIRED_ERROR =
"Connect your ChatGPT subscription before starting a conversation with this LLM profile.";
diff --git a/src/api/conversation-metadata-store.ts b/src/api/conversation-metadata-store.ts
index c2bb299167..45f63c5a44 100644
--- a/src/api/conversation-metadata-store.ts
+++ b/src/api/conversation-metadata-store.ts
@@ -48,6 +48,12 @@ export interface ConversationMetadata {
stamped_at?: string | null;
/** Store plugin coordinates only; parameters may contain secrets. */
plugins?: PluginSpec[] | null;
+ /**
+ * Local-only client-managed planning conversation id. Cloud backends expose
+ * real sub-conversations through `sub_conversation_ids`; local agent-server
+ * backends do not, so Canvas stores the relationship here.
+ */
+ local_planning_conversation_id?: string | null;
}
export const toPluginCoordinates = (plugin: PluginSpec): PluginSpec => ({
@@ -93,6 +99,25 @@ export const setStoredConversationMetadata = (
writeAll(all);
};
+/**
+ * Merge `patch` into a conversation's stored metadata, preserving every
+ * existing field β€” `setStoredConversationMetadata` does a full-object
+ * replace, which would otherwise silently drop fields the caller doesn't
+ * enumerate (e.g. `plugins`).
+ */
+export const mergeStoredConversationMetadata = (
+ conversationId: string,
+ patch: Partial<ConversationMetadata>,
+): void => {
+ setStoredConversationMetadata(conversationId, {
+ selected_repository: null,
+ selected_branch: null,
+ git_provider: null,
+ ...(getStoredConversationMetadata(conversationId) ?? {}),
+ ...patch,
+ });
+};
+
export const removeStoredConversationMetadata = (
conversationId: string,
): void => {
diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.ts
index ea76dd530f..fc881d5c16 100644
--- a/src/api/conversation-service/agent-server-conversation-service.api.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts
@@ -41,6 +41,7 @@ import {
DirectConversationInfo,
assertSubscriptionAuthReady,
buildStartConversationRequestWithEncryptedSettings,
+ buildStartPlanningConversationRequestWithEncryptedSettings,
emptyHooksResponse,
getDefaultConversationTitle,
toAppConversation,
@@ -56,11 +57,13 @@ import { getTelemetryDistinctId } from "../../services/telemetry";
import {
ConversationMetadata,
getStoredConversationMetadata,
+ mergeStoredConversationMetadata,
removeStoredConversationMetadata,
setStoredConversationMetadata,
type WorkspaceMode,
} from "../conversation-metadata-store";
import { resolveTitleLlmProfile } from "#/utils/title-llm-profile";
+import { isPlannerConversationOf } from "#/utils/plan-file";
import type {
GetHooksResponse,
PluginSpec,
@@ -201,6 +204,19 @@ function normalizeTags(value: unknown): Record<string, string> | null {
return tags;
}
+/**
+ * ``ConversationInfo.sub_conversation_ids`` β€” the agent-server derives it from
+ * its own catalog of conversations that name this one as parent (SDK #4188),
+ * which is what lets Canvas find a conversation's local planner without any
+ * browser-local state. Absent on agent-servers older than 1.37.1; parsed
+ * defensively so a non-conforming payload degrades to "no children" instead of
+ * crashing the list.
+ */
+function normalizeSubConversationIds(value: unknown): string[] | null {
+ if (!Array.isArray(value)) return null;
+ return value.filter((entry): entry is string => typeof entry === "string");
+}
+
function normalizeLaunchedAgentProfile(
value: unknown,
): DirectConversationInfo["launched_agent_profile"] {
@@ -266,6 +282,9 @@ function requireDirectConversationInfo(item: unknown): DirectConversationInfo {
launched_agent_profile: normalizeLaunchedAgentProfile(
item.launched_agent_profile,
),
+ sub_conversation_ids: normalizeSubConversationIds(
+ item.sub_conversation_ids,
+ ),
// SDK-runtime ACP model fields (populated when the agent-server supports
// ``ConversationInfo.current_model_*``). Consumed by the conversation
// adapter to drive the per-card chip's model text. Older agent-servers
@@ -559,6 +578,103 @@ class AgentServerConversationService {
};
}
+ static async createLocalPlanningConversation(
+ parentConversationId: string,
+ initialMessage?: string,
+ ): Promise<AppConversation> {
+ if (getActiveBackend().backend.kind === "cloud") {
+ throw new Error("Local planning conversations require a local backend.");
+ }
+
+ const [parent] = await this.batchGetAppConversations([
+ parentConversationId,
+ ]);
+ const workingDir =
+ parent?.workspace?.working_dir ?? getAgentServerWorkingDir();
+
+ const payload =
+ await buildStartPlanningConversationRequestWithEncryptedSettings({
+ workingDir,
+ parentConversationId,
+ // Pin the planner to the parent's own current model. Only meaningful
+ // for "openhands"-kind parents: an ACP parent's active_profile is a
+ // stale launch-time snapshot (/model is a no-op for ACP), not a live
+ // value, so treating it as authoritative would pin the planner to
+ // the wrong model instead of falling through to global settings.
+ parentActiveProfileName:
+ parent?.agent_kind === "openhands"
+ ? (parent?.active_profile ?? null)
+ : null,
+ // Fallback when active_profile can't be resolved (e.g. an ACP parent).
+ parentAgentProfileId:
+ parent?.launched_agent_profile?.agent_profile_id ?? null,
+ initialMessage,
+ });
+
+ const data = await new ConversationClient(
+ getAgentServerClientOptions(),
+ ).createConversation<DirectConversationInfo>(payload);
+
+ // Client-side fallback only: agent-servers >= 1.37.1 persist the link via
+ // `parent_conversation_id` and hand it back on the parent's
+ // `sub_conversation_ids`, which is the source of truth. This hint covers
+ // older backends that ignore the field.
+ mergeStoredConversationMetadata(parentConversationId, {
+ local_planning_conversation_id: data.id,
+ });
+
+ return toAppConversation(data);
+ }
+
+ /**
+ * Ids of the conversations owned by `parentConversationId` on a local
+ * backend β€” today that means its planner helper, the only child Canvas
+ * creates locally.
+ *
+ * `sub_conversation_ids` is the generic server-derived child list, so each
+ * child is kept only if it's tagged `plannerparent` for this parent β€”
+ * otherwise deleting the parent would also delete an unrelated non-planner
+ * child (e.g. a delegated sub-agent). The stored metadata hint is merged in
+ * for agent-servers older than 1.37.1, which report no children at all.
+ */
+ static async getLocalPlanningConversationIds(
+ parentConversationId: string,
+ ): Promise<string[]> {
+ if (getActiveBackend().backend.kind === "cloud") return [];
+
+ const ids = new Set<string>();
+
+ try {
+ const [parent] = await this.batchGetAppConversations([
+ parentConversationId,
+ ]);
+ const childIds = parent?.sub_conversation_ids ?? [];
+ if (childIds.length > 0) {
+ const children = await this.batchGetAppConversations(childIds);
+ for (const child of children) {
+ if (child && isPlannerConversationOf(child, parentConversationId)) {
+ ids.add(child.id);
+ }
+ }
+ }
+ } catch (error) {
+ // The stored hint below still covers the common case, and callers
+ // (delete) must not be blocked by a failed lookup.
+ console.warn(
+ `Failed to read sub-conversations of ${parentConversationId}`,
+ error,
+ );
+ }
+
+ const stored =
+ getStoredConversationMetadata(
+ parentConversationId,
+ )?.local_planning_conversation_id;
+ if (stored) ids.add(stored);
+
+ return [...ids];
+ }
+
static async getStartTask(
taskId: string,
): Promise<AppConversationStartTask | null> {
@@ -799,11 +915,35 @@ class AgentServerConversationService {
static async deleteConversation(conversationId: string): Promise<void> {
if (getActiveBackend().backend.kind === "cloud") {
await deleteCloudConversation(conversationId);
- } else {
- await new ConversationClient(
- getAgentServerClientOptions(),
- ).deleteConversation(conversationId);
+ removeStoredConversationMetadata(conversationId);
+ return;
}
+
+ // The agent-server orphans children rather than cascading, and the local
+ // planner helper is hidden from the conversation list by its
+ // `plannerparent` tag β€” so without this it would survive its parent as an
+ // invisible, unreachable conversation (plus its events and state).
+ const planningConversationIds =
+ await this.getLocalPlanningConversationIds(conversationId);
+
+ const client = new ConversationClient(getAgentServerClientOptions());
+ await Promise.all(
+ planningConversationIds.map(async (planningConversationId) => {
+ try {
+ await client.deleteConversation(planningConversationId);
+ } catch (error) {
+ // Already gone (or unreachable): never block deleting the parent the
+ // user actually asked to remove.
+ console.warn(
+ `Failed to delete planning conversation ${planningConversationId}`,
+ error,
+ );
+ }
+ removeStoredConversationMetadata(planningConversationId);
+ }),
+ );
+
+ await client.deleteConversation(conversationId);
removeStoredConversationMetadata(conversationId);
}
diff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.ts
index f8f9cdec5e..dd323a9bdb 100644
--- a/src/api/settings-service/settings-service.api.ts
+++ b/src/api/settings-service/settings-service.api.ts
@@ -7,6 +7,7 @@ import type {
import { DEFAULT_SETTINGS } from "#/services/settings";
import { Settings, SettingsSchema, SettingsValue } from "#/types/settings";
import { stringRecord } from "#/utils/mcp-config";
+import type { SkillEnablement } from "#/utils/skill-enablement";
import { getActiveBackend } from "../backend-registry/active-store";
import {
fetchCloudConversationSettingsSchema,
@@ -317,6 +318,25 @@ const cloudCompatibleMcpConfig = async (value: unknown): Promise<unknown> => {
return hasWrapper ? { ...value, mcpServers: converted } : converted;
};
+/**
+ * Read the skill allow-/deny-lists off a raw API response β€” for
+ * `getSettingsForConversation`, which returns the encrypted dump as-is rather
+ * than a normalized `Settings` object (so `toSkillEnablement` can't be used).
+ *
+ * `enabledSkills` stays `undefined` when absent: that is the "never migrated"
+ * signal `resolveEnabledCatalogSkills` reads, and an empty array would instead
+ * mean "every catalog skill off".
+ */
+const getSkillEnablement = (response: SettingsApiResponse): SkillEnablement => {
+ const prefs = response.misc_settings?.app_preferences;
+ const disabled = prefs?.disabled_skills;
+ const enabled = prefs?.enabled_skills;
+ return {
+ disabledSkills: Array.isArray(disabled) ? disabled : [],
+ enabledSkills: Array.isArray(enabled) ? enabled : undefined,
+ };
+};
+
/**
* Transform API response into Settings object with derived fields.
*/
@@ -489,6 +509,7 @@ class SettingsService {
agentSettings: Record<string, SettingsValue>;
conversationSettings: Record<string, SettingsValue>;
secretsEncrypted: boolean;
+ skillEnablement: SkillEnablement;
}> {
// Check cache first
if (isCacheValid() && settingsCache.encrypted) {
@@ -496,6 +517,7 @@ class SettingsService {
agentSettings: settingsCache.encrypted.agent_settings,
conversationSettings: settingsCache.encrypted.conversation_settings,
secretsEncrypted: true,
+ skillEnablement: getSkillEnablement(settingsCache.encrypted),
};
}
@@ -510,6 +532,7 @@ class SettingsService {
agentSettings: response.agent_settings,
conversationSettings: response.conversation_settings,
secretsEncrypted: true,
+ skillEnablement: getSkillEnablement(response),
};
}
diff --git a/src/components/conversation-events/chat/event-message.tsx b/src/components/conversation-events/chat/event-message.tsx
index a976cbbe55..49ce591080 100644
--- a/src/components/conversation-events/chat/event-message.tsx
+++ b/src/components/conversation-events/chat/event-message.tsx
@@ -22,7 +22,7 @@ import {
} from "#/types/agent-server/type-guards";
import { useConfig } from "#/hooks/query/use-config";
import { useConversationStore } from "#/stores/conversation-store";
-import { useAgentState } from "#/hooks/use-agent-state";
+import { useAgentState, usePlanningAgentState } from "#/hooks/use-agent-state";
import { AgentState } from "#/types/agent-state";
import { ChatMessage } from "#/components/features/chat/chat-message";
import { GoalStatusContent } from "#/components/features/chat/goal-status-content";
@@ -128,6 +128,41 @@ const renderUserMessageWithSkillReady = (
}
};
+/**
+ * Renders the plan preview. Its own component so `usePlanningAgentState()`
+ * only subscribes on this rare row, not every message in the conversation.
+ */
+function PlanningObservationPreview({
+ planContent,
+ isLastMessage,
+ isMainAgentRunning,
+}: {
+ planContent: string | null;
+ isLastMessage: boolean;
+ isMainAgentRunning: boolean;
+}) {
+ const {
+ localPlanningConversationId,
+ curPlanningAgentState,
+ isPlanningAgentRunning,
+ } = usePlanningAgentState();
+
+ // Guard on the id explicitly β€” useAgentState(undefined) falls back to the
+ // route conversation, which could be mistaken for the planner's activity.
+ const isStreaming =
+ isLastMessage &&
+ !!localPlanningConversationId &&
+ curPlanningAgentState === AgentState.RUNNING;
+
+ return (
+ <PlanPreview
+ planContent={planContent}
+ isStreaming={isStreaming}
+ isBuildDisabled={isMainAgentRunning || isPlanningAgentRunning}
+ />
+ );
+}
+
export function EventMessage({
event,
messages,
@@ -140,7 +175,8 @@ export function EventMessage({
const { planContent } = useConversationStore();
const { curAgentState } = useAgentState();
- // Disable Build button while agent is running (streaming)
+ // Planner-running state is folded in by PlanningObservationPreview below,
+ // not read here, to avoid a second useAgentState() subscription per row.
const isAgentRunning =
curAgentState === AgentState.RUNNING ||
curAgentState === AgentState.LOADING;
@@ -256,14 +292,11 @@ export function EventMessage({
planPreviewEventIds &&
shouldShowPlanPreview(event.id, planPreviewEventIds)
) {
- // Show shine effect only if this is the last message AND agent is running
- const isStreaming =
- isLastMessage && curAgentState === AgentState.RUNNING;
return (
- <PlanPreview
+ <PlanningObservationPreview
planContent={planContent}
- isStreaming={isStreaming}
- isBuildDisabled={isAgentRunning}
+ isLastMessage={isLastMessage}
+ isMainAgentRunning={isAgentRunning}
/>
);
}
diff --git a/src/components/features/chat/chat-interface.tsx b/src/components/features/chat/chat-interface.tsx
index 967fd4a8c4..ff6b46ccc4 100644
--- a/src/components/features/chat/chat-interface.tsx
+++ b/src/components/features/chat/chat-interface.tsx
@@ -22,7 +22,7 @@ import { ChatSuggestions } from "./chat-suggestions";
import { ScrollProvider } from "#/context/scroll-context";
import { useInitialQueryStore } from "#/stores/initial-query-store";
import { useSendMessage } from "#/hooks/use-send-message";
-import { useAgentState } from "#/hooks/use-agent-state";
+import { useAgentState, usePlanningAgentState } from "#/hooks/use-agent-state";
import { useIsArchivedConversation } from "#/hooks/use-is-archived-conversation";
import { useHandleBuildPlanClick } from "#/hooks/use-handle-build-plan-click";
@@ -115,6 +115,7 @@ export function ChatInterface() {
} = useNewConversationCommand();
const { curAgentState } = useAgentState();
+ const { isPlanningAgentRunning } = usePlanningAgentState();
const { handleBuildPlanClick } = useHandleBuildPlanClick();
// Cloud conversations whose sandbox is MISSING or ERROR are read-only:
@@ -651,7 +652,8 @@ export function ChatInterface() {
<ScrollToBottomButton onClick={scrollDomToBottom} />
</div>
) : (
- curAgentState === AgentState.RUNNING && (
+ (curAgentState === AgentState.RUNNING ||
+ isPlanningAgentRunning) && (
<div className="pointer-events-none absolute inset-x-9 bottom-0 flex justify-center">
<TypingIndicator events={allConversationEvents} />
</div>
diff --git a/src/components/features/chat/interactive-chat-box.tsx b/src/components/features/chat/interactive-chat-box.tsx
index bc411162ea..1fbff59f2b 100644
--- a/src/components/features/chat/interactive-chat-box.tsx
+++ b/src/components/features/chat/interactive-chat-box.tsx
@@ -2,6 +2,7 @@ import { CustomChatInput } from "./custom-chat-input";
import { useBtwInterceptor } from "#/hooks/chat/use-btw-interceptor";
import { useGoalInterceptor } from "#/hooks/chat/use-goal-interceptor";
import { useModelInterceptor } from "#/hooks/chat/use-model-interceptor";
+import { usePlanModeInterceptor } from "#/hooks/chat/use-plan-mode-interceptor";
import { useChatAttachmentUpload } from "#/hooks/chat/use-chat-attachment-upload";
import { AgentState } from "#/types/agent-state";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
@@ -52,7 +53,15 @@ export function InteractiveChatBox({
onSubmit(message, imagesToEmbed, [...files, ...imagesAsFiles]);
clearAllFiles();
});
- const handleAfterModel = useGoalInterceptor(conversationId, handleAfterGoal);
+ const handleAfterPlanMode = usePlanModeInterceptor(
+ conversationId,
+ curAgentState,
+ handleAfterGoal,
+ );
+ const handleAfterModel = useGoalInterceptor(
+ conversationId,
+ handleAfterPlanMode,
+ );
const handleSubmit = useModelInterceptor(conversationId, handleAfterModel);
const handleSuggestionsClick = (suggestion: string) => {
diff --git a/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsx b/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsx
index 3634050ae9..a309aa0471 100644
--- a/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsx
+++ b/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsx
@@ -17,7 +17,6 @@ import PillIcon from "#/icons/pill.svg?react";
import PillFillIcon from "#/icons/pill-fill.svg?react";
import DoubleCheckIcon from "#/icons/double-check.svg?react";
import { useTaskList } from "#/hooks/use-task-list";
-import { useActiveBackend } from "#/contexts/active-backend-context";
import { useSelectConversationTab } from "#/hooks/use-select-conversation-tab";
import { useIsArchivedConversation } from "#/hooks/use-is-archived-conversation";
import { ArchivedDisabledTooltip } from "../../context-menu/archived-disabled-tooltip";
@@ -87,7 +86,6 @@ export function ConversationTabsContextMenu({
const { navigateToTab } = useSelectConversationTab();
const { hasTaskList } = useTaskList();
- const { backend } = useActiveBackend();
const isArchivedConversation = useIsArchivedConversation();
const tabConfig = [
@@ -119,10 +117,6 @@ export function ConversationTabsContextMenu({
});
}
- const visibleTabConfig = tabConfig.filter(
- ({ tab }) => tab !== "planner" || backend.kind === "cloud",
- );
-
const handleOpenTab = (tab: string) => {
if (isArchivedConversation) {
return;
@@ -146,7 +140,7 @@ export function ConversationTabsContextMenu({
setUnpinnedTabs(newUnpinnedTabs);
if (selectedTab === tab && isRightPanelShown) {
- const nextPinnedTab = visibleTabConfig.find(
+ const nextPinnedTab = tabConfig.find(
({ tab: tabKey }) =>
tabKey !== tab && !newUnpinnedTabs.includes(tabKey),
);
@@ -172,7 +166,7 @@ export function ConversationTabsContextMenu({
spacing={isPortaled ? "none" : "default"}
className={cn("z-[9999] w-fit", isPortaled ? "mt-0" : "mt-2")}
>
- {visibleTabConfig.map(({ tab, icon: Icon, i18nKey }) => {
+ {tabConfig.map(({ tab, icon: Icon, i18nKey }) => {
const pinned = !state.unpinnedTabs.includes(tab);
return (
<li key={tab} className="list-none">
diff --git a/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx b/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx
index 2a748fa50c..2279437e19 100644
--- a/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx
+++ b/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx
@@ -19,7 +19,7 @@ import { useSelectConversationTab } from "#/hooks/use-select-conversation-tab";
import { useTaskList } from "#/hooks/use-task-list";
import { useActiveBackend } from "#/contexts/active-backend-context";
import { useHandleBuildPlanClick } from "#/hooks/use-handle-build-plan-click";
-import { useAgentState } from "#/hooks/use-agent-state";
+import { useAgentState, usePlanningAgentState } from "#/hooks/use-agent-state";
import { AgentState } from "#/types/agent-state";
import { Typography } from "#/ui/typography";
import { mobileTopBarIconClassName } from "#/utils/mobile-top-bar-icon-button-classes";
@@ -45,6 +45,7 @@ export function ConversationTabs({
const { handleBuildPlanClick } = useHandleBuildPlanClick();
const { curAgentState } = useAgentState();
+ const { isPlanningAgentRunning } = usePlanningAgentState();
const {
selectTab,
@@ -155,10 +156,8 @@ export function ConversationTabs({
// Pinned tabs always show in the bar. Unpinned tabs stay hidden unless the
// user has that tab selected β€” then it appears while active so the bar
- // matches the open panel. Hide Planner on local backends β€” the planning
- // agent isn't supported locally.
+ // matches the open panel.
const visibleTabs = tabs.filter((tab) => {
- if (tab.tabValue === "planner" && backend.kind !== "cloud") return false;
if (!persistedState.unpinnedTabs.includes(tab.tabValue)) return true;
return selectedTab === tab.tabValue;
});
@@ -167,7 +166,8 @@ export function ConversationTabs({
const isAgentRunning =
curAgentState === AgentState.RUNNING ||
- curAgentState === AgentState.LOADING;
+ curAgentState === AgentState.LOADING ||
+ isPlanningAgentRunning;
const isBuildDisabled = isAgentRunning || !planContent;
const tabsRowInnerRef = useRef<HTMLDivElement>(null);
diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsx
index 3178190373..8cf712ec5b 100644
--- a/src/contexts/conversation-websocket-context.tsx
+++ b/src/contexts/conversation-websocket-context.tsx
@@ -75,6 +75,7 @@ import {
invalidateConversationQueries,
updateConversationLlmModelInCache,
} from "#/hooks/mutation/conversation-mutation-utils";
+import { isPlanFilePath } from "#/utils/plan-file";
export type WebSocketConnectionState =
| "CONNECTING"
@@ -88,6 +89,11 @@ interface SendMessageResult {
interface ConversationWebSocketContextType {
connectionState: WebSocketConnectionState;
+ /**
+ * The main connection's own state, unmerged with the planning connection β€”
+ * see `useMainWebSocketStatus`.
+ */
+ mainConnectionState: WebSocketConnectionState;
sendMessage: (message: SendMessageRequest) => Promise<SendMessageResult>;
isLoadingHistory: boolean;
reconnect: () => void;
@@ -189,7 +195,10 @@ export function ConversationWebSocketProvider({
const { setPlanContent } = useConversationStore();
- // Hook for reading conversation file
+ useEffect(() => {
+ setPlanContent(null);
+ }, [conversationId, setPlanContent]);
+
const { mutate: readConversationFile } = useReadConversationFile();
// Track planning-agent received events (still WS-driven).
@@ -201,9 +210,6 @@ export function ConversationWebSocketProvider({
conversationId: string;
} | null>(null);
- const isPlanFilePath = (path: string | null): boolean =>
- path?.toUpperCase().endsWith("PLAN.MD") ?? false;
-
const handleNonErrorEvent = useCallback(() => {
// A normal event means connectivity recovered: clear a transient connection
// error, but keep sticky conversation errors (e.g. a wrong API key).
@@ -396,6 +402,16 @@ export function ConversationWebSocketProvider({
return buildWebSocketUrl(conversationId, conversationUrl);
}, [conversationId, conversationUrl, isPreloadingHistory]);
+ // Derived from `subConversationIds` (the pre-filtered, tag-verified id
+ // list) rather than the resolved `subConversations` entry, which lands a
+ // tick later β€” routing on it would leave a window where the first prompt
+ // sent in plan mode fell through to the parent (the code agent) instead of
+ // the planner.
+ const planningConversationId = useMemo(
+ () => subConversationIds?.[0] ?? null,
+ [subConversationIds],
+ );
+
const planningAgentWsUrl = useMemo(() => {
if (!subConversations?.length) {
return null;
@@ -634,11 +650,17 @@ export function ConversationWebSocketProvider({
// Handle conversation state updates
// TODO: Tests
if (isConversationStateUpdateEvent(event)) {
- if (isFullStateConversationStateUpdateEvent(event)) {
- setExecutionStatus(event.value.execution_status);
+ if (
+ isFullStateConversationStateUpdateEvent(event) &&
+ conversationId
+ ) {
+ setExecutionStatus(conversationId, event.value.execution_status);
}
- if (isAgentStatusConversationStateUpdateEvent(event)) {
- setExecutionStatus(event.value);
+ if (
+ isAgentStatusConversationStateUpdateEvent(event) &&
+ conversationId
+ ) {
+ setExecutionStatus(conversationId, event.value);
}
if (isStatsConversationStateUpdateEvent(event)) {
updateMetricsFromStats(event);
@@ -862,11 +884,24 @@ export function ConversationWebSocketProvider({
// Handle conversation state updates
// TODO: Tests
if (isConversationStateUpdateEvent(event)) {
- if (isFullStateConversationStateUpdateEvent(event)) {
- setExecutionStatus(event.value.execution_status);
+ // Scope to the planning agent's own conversation id, not the main
+ // `conversationId` β€” this socket reports the planning helper
+ // conversation's run/idle transitions, which must never overwrite
+ // the main conversation's status in the shared store.
+ if (
+ isFullStateConversationStateUpdateEvent(event) &&
+ planningConversationId
+ ) {
+ setExecutionStatus(
+ planningConversationId,
+ event.value.execution_status,
+ );
}
- if (isAgentStatusConversationStateUpdateEvent(event)) {
- setExecutionStatus(event.value);
+ if (
+ isAgentStatusConversationStateUpdateEvent(event) &&
+ planningConversationId
+ ) {
+ setExecutionStatus(planningConversationId, event.value);
}
if (isStatsConversationStateUpdateEvent(event)) {
updateMetricsFromStats(event);
@@ -942,6 +977,7 @@ export function ConversationWebSocketProvider({
consumeMatchingPendingMessage,
queryClient,
subConversations,
+ planningConversationId,
conversationId,
setExecutionStatus,
appendInput,
@@ -1089,19 +1125,28 @@ export function ConversationWebSocketProvider({
const currentMode = useConversationStore.getState().conversationMode;
const currentSocket =
currentMode === "plan" ? planningAgentSocket : mainSocket;
+ const targetConversationId =
+ currentMode === "plan" ? planningConversationId : conversationId;
if (currentSocket?.readyState !== WebSocket.OPEN) {
// WebSocket not connected - queue message via REST API
// Message will be delivered automatically when conversation becomes ready
- if (!conversationId) {
- const error = new Error("No conversation ID available");
+ if (!targetConversationId) {
+ // Never fall back to the parent in plan mode: without a planner
+ // target the message would run in the code agent, which is exactly
+ // the boundary plan mode exists to enforce.
+ const error = new Error(
+ currentMode === "plan"
+ ? "Planning conversation is not ready yet"
+ : "No conversation ID available",
+ );
setErrorMessage(error.message);
throw error;
}
try {
await new ConversationClient(getAgentServerClientOptions()).sendEvent(
- conversationId,
+ targetConversationId,
{
role: "user",
content: message.content,
@@ -1133,7 +1178,13 @@ export function ConversationWebSocketProvider({
throw error;
}
},
- [mainSocket, planningAgentSocket, setErrorMessage, conversationId],
+ [
+ mainSocket,
+ planningAgentSocket,
+ setErrorMessage,
+ conversationId,
+ planningConversationId,
+ ],
);
// Track main socket state changes
@@ -1195,8 +1246,20 @@ export function ConversationWebSocketProvider({
}, [planningAgentSocket, planningAgentWsUrl]);
const contextValue = useMemo(
- () => ({ connectionState, sendMessage, isLoadingHistory, reconnect }),
- [connectionState, sendMessage, isLoadingHistory, reconnect],
+ () => ({
+ connectionState,
+ mainConnectionState,
+ sendMessage,
+ isLoadingHistory,
+ reconnect,
+ }),
+ [
+ connectionState,
+ mainConnectionState,
+ sendMessage,
+ isLoadingHistory,
+ reconnect,
+ ],
);
return (
diff --git a/src/contexts/websocket-provider-wrapper.tsx b/src/contexts/websocket-provider-wrapper.tsx
index 0e9a375ae0..680371a967 100644
--- a/src/contexts/websocket-provider-wrapper.tsx
+++ b/src/contexts/websocket-provider-wrapper.tsx
@@ -2,6 +2,10 @@ import React from "react";
import { ConversationWebSocketProvider } from "#/contexts/conversation-websocket-context";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useSubConversations } from "#/hooks/query/use-sub-conversations";
+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+import { useConversationStore } from "#/stores/conversation-store";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { findPlannerConversationId } from "#/utils/plan-file";
interface WebSocketProviderWrapperProps {
children: React.ReactNode;
@@ -13,20 +17,84 @@ export function WebSocketProviderWrapper({
conversationId,
}: WebSocketProviderWrapperProps) {
const { data: conversation } = useActiveConversation();
+ const { backend } = useActiveBackend();
+ const isLocalBackend = backend.kind !== "cloud";
+ const localPlanningConversationId = useConversationStore(
+ (state) => state.localPlanningConversationId,
+ );
+
+ // `localPlanningConversationId` is a single unscoped Zustand field. Right
+ // after switching conversations it can still hold the *previous*
+ // conversation's planner id, since the reset effect in
+ // routes/conversation.tsx and `useActiveConversation()`'s refetch both lag
+ // this render β€” only trust it once `conversation` matches `conversationId`.
+ const isConversationDataFresh = conversation?.id === conversationId;
+ const trustedLocalPlanningConversationId = isConversationDataFresh
+ ? localPlanningConversationId
+ : null;
+
+ // Candidate ids to resolve. On local backends `sub_conversation_ids` is the
+ // generic (untyped) child list, so fetch it below to find the
+ // `plannerparent`-tagged entry; cloud has no such ambiguity. Memoized: a
+ // fresh array literal each render would re-fire ConversationWebSocketProvider's
+ // reference-keyed effects and wipe the pending PLAN.md read.
+ const candidateConversationIds = React.useMemo(() => {
+ if (!isLocalBackend) {
+ return conversation?.sub_conversation_ids ?? [];
+ }
+ if (
+ conversation?.sub_conversation_ids &&
+ conversation.sub_conversation_ids.length > 0
+ ) {
+ return conversation.sub_conversation_ids;
+ }
+ return trustedLocalPlanningConversationId
+ ? [trustedLocalPlanningConversationId]
+ : [];
+ }, [
+ isLocalBackend,
+ conversation?.sub_conversation_ids,
+ trustedLocalPlanningConversationId,
+ ]);
const { data: subConversations } = useSubConversations(
- conversation?.sub_conversation_ids ?? [],
+ candidateConversationIds,
);
+ // Identify the planner via the `plannerparent` tag rather than list
+ // position β€” an unrelated child must never be adopted as the planner.
+ // Kept as its own memo (a primitive) rather than inlined below: `subConversations`
+ // gets a new array reference on every refetch even when the planner id
+ // hasn't changed, and planningConversationIds must not rebuild its own
+ // array in that case β€” see candidateConversationIds above.
+ const plannerConversationId = React.useMemo(() => {
+ if (!isLocalBackend) return null;
+ return findPlannerConversationId(subConversations, conversation?.id);
+ }, [isLocalBackend, subConversations, conversation?.id]);
+
+ const planningConversationIds = React.useMemo(() => {
+ if (!isLocalBackend) return candidateConversationIds;
+ if (plannerConversationId) return [plannerConversationId];
+ // Tag data hasn't resolved yet β€” bridge with the verified store id (see
+ // `trustedLocalPlanningConversationId` above), otherwise stay empty
+ // rather than guessing an untagged child is the planner.
+ return trustedLocalPlanningConversationId
+ ? [trustedLocalPlanningConversationId]
+ : [];
+ }, [
+ isLocalBackend,
+ candidateConversationIds,
+ plannerConversationId,
+ trustedLocalPlanningConversationId,
+ ]);
+
const filteredSubConversations = subConversations?.filter(
- (subConversation) => subConversation !== null,
+ (subConversation): subConversation is AppConversation =>
+ subConversation !== null &&
+ planningConversationIds.includes(subConversation.id),
);
- // Don't pass a conversation URL to the WebSocket provider while the cloud
- // sandbox is PAUSED. The URL still points to the old sandbox host, which
- // rejects connections until the sandbox has fully resumed. Treating the URL
- // as absent here keeps wsUrl === null in ConversationWebSocketProvider, so
- // no connection is attempted until useActiveConversation detects the
- // transition out of PAUSED (via fast 3-second polling).
+ // Suppress the URL while the cloud sandbox is PAUSED β€” it still points at
+ // the old (now-rejecting) host until the sandbox resumes.
const conversationUrl =
conversation?.sandbox_status === "PAUSED"
? null
@@ -37,7 +105,7 @@ export function WebSocketProviderWrapper({
conversationId={conversationId}
conversationUrl={conversationUrl}
sessionApiKey={conversation?.session_api_key}
- subConversationIds={conversation?.sub_conversation_ids}
+ subConversationIds={planningConversationIds}
subConversations={filteredSubConversations}
>
{children}
diff --git a/src/hooks/chat/record-model-switch-message.ts b/src/hooks/chat/record-model-switch-message.ts
index 0fd23feb24..dce835c134 100644
--- a/src/hooks/chat/record-model-switch-message.ts
+++ b/src/hooks/chat/record-model-switch-message.ts
@@ -2,7 +2,7 @@ import { getLastRenderableEventId } from "#/hooks/chat/model-command-event-ancho
import { useModelStore, SeededSwitch } from "#/stores/model-store";
import {
getStoredConversationMetadata,
- setStoredConversationMetadata,
+ mergeStoredConversationMetadata,
} from "#/api/conversation-metadata-store";
import { OpenHandsEvent } from "#/types/agent-server/core";
import { isSwitchLLMObservationEvent } from "#/types/agent-server/type-guards";
@@ -39,21 +39,14 @@ export function stampActiveLlmProfile(
) {
useModelStore.getState().setActiveProfile(conversationId, profileName);
- const prev = getStoredConversationMetadata(conversationId);
- setStoredConversationMetadata(conversationId, {
- selected_repository: prev?.selected_repository ?? null,
- selected_branch: prev?.selected_branch ?? null,
- git_provider: prev?.git_provider ?? null,
- selected_workspace: prev?.selected_workspace ?? null,
- // Carry the attached-workspace mode forward too β€” the full-object replace
- // would otherwise drop it (#15520). This helper is the single write site
- // for the profile-switch stamp, so one line covers every path.
- workspace_mode: prev?.workspace_mode ?? null,
+ // Merge rather than replace: the stamp only owns these two fields, and the
+ // record carries others it must not drop β€” the attached workspace mode
+ // (#15520), the plugins snapshot behind the in-conversation plugins view,
+ // and the local planner conversation id. Enumerating them here meant every
+ // new field had to remember to opt in.
+ mergeStoredConversationMetadata(conversationId, {
active_profile: profileName,
stamped_at: stampedAt,
- // Full-object replace: carry the plugins snapshot forward so the
- // in-conversation plugins view survives a profile switch.
- plugins: prev?.plugins ?? null,
});
}
diff --git a/src/hooks/chat/use-plan-mode-interceptor.test.ts b/src/hooks/chat/use-plan-mode-interceptor.test.ts
new file mode 100644
index 0000000000..0bf3187e5b
--- /dev/null
+++ b/src/hooks/chat/use-plan-mode-interceptor.test.ts
@@ -0,0 +1,189 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { usePlanModeInterceptor } from "./use-plan-mode-interceptor";
+import { AgentState } from "#/types/agent-state";
+import type { WebSocketConnectionState } from "#/contexts/conversation-websocket-context";
+
+const setConversationMode = vi.fn();
+const handlePlanClick = vi.fn();
+let isCreatingConversation = false;
+let hasPlanner = false;
+let mainWebSocketStatus: WebSocketConnectionState = "OPEN";
+let unifiedWebSocketStatus: WebSocketConnectionState = "OPEN";
+let isPlanningAgentRunning = false;
+
+vi.mock("#/stores/conversation-store", () => ({
+ useConversationStore: (selector: (s: unknown) => unknown) =>
+ selector({ setConversationMode }),
+}));
+vi.mock("#/hooks/use-handle-plan-click", () => ({
+ useHandlePlanClick: () => ({
+ handlePlanClick,
+ hasPlanner,
+ isCreatingConversation,
+ }),
+}));
+vi.mock("#/hooks/use-unified-websocket-status", () => ({
+ useMainWebSocketStatus: () => mainWebSocketStatus,
+ useUnifiedWebSocketStatus: () => unifiedWebSocketStatus,
+}));
+vi.mock("#/hooks/use-agent-state", () => ({
+ usePlanningAgentState: () => ({ isPlanningAgentRunning }),
+}));
+
+const CONV = "conv-1";
+
+const setup = (
+ conversationId: string | null,
+ curAgentState: AgentState = AgentState.AWAITING_USER_INPUT,
+) => {
+ const onSubmit = vi.fn();
+ const { result } = renderHook(() =>
+ usePlanModeInterceptor(conversationId, curAgentState, onSubmit),
+ );
+ return { intercept: result.current, onSubmit };
+};
+
+describe("usePlanModeInterceptor", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ isCreatingConversation = false;
+ hasPlanner = false;
+ mainWebSocketStatus = "OPEN";
+ unifiedWebSocketStatus = "OPEN";
+ isPlanningAgentRunning = false;
+ });
+
+ it("passes a non-command message straight through to onSubmit", () => {
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("hello there");
+ expect(onSubmit).toHaveBeenCalledWith("hello there");
+ expect(handlePlanClick).not.toHaveBeenCalled();
+ expect(setConversationMode).not.toHaveBeenCalled();
+ });
+
+ it("enables plan mode for /plan", () => {
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("/plan");
+ expect(handlePlanClick).toHaveBeenCalledWith(undefined, undefined);
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("creates the planner with the task as its initial message for /plan <task> when no planner exists yet", () => {
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("/plan Build a website about open source. ");
+ expect(handlePlanClick).toHaveBeenCalledWith(
+ undefined,
+ "Build a website about open source.",
+ );
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(setConversationMode).not.toHaveBeenCalled();
+ });
+
+ it("sends the task straight to the existing planner for /plan <task> when a planner already exists", () => {
+ hasPlanner = true;
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("/plan Build a website about open source.");
+ expect(setConversationMode).toHaveBeenCalledWith("plan");
+ expect(onSubmit).toHaveBeenCalledWith("Build a website about open source.");
+ expect(handlePlanClick).not.toHaveBeenCalled();
+ });
+
+ it("falls back to a bare toggle for /plan with only whitespace after it", () => {
+ hasPlanner = true;
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("/plan ");
+ expect(handlePlanClick).toHaveBeenCalledWith(undefined, undefined);
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("switches back to code mode for /code", () => {
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("/code");
+ expect(setConversationMode).toHaveBeenCalledWith("code");
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("switches to code mode and sends the task for /code <task>", () => {
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("/code fix the bug in auth.ts ");
+ expect(setConversationMode).toHaveBeenCalledWith("code");
+ expect(onSubmit).toHaveBeenCalledWith("fix the bug in auth.ts");
+ expect(handlePlanClick).not.toHaveBeenCalled();
+ });
+
+ it("falls back to a bare toggle for /code with only whitespace after it", () => {
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("/code ");
+ expect(setConversationMode).toHaveBeenCalledWith("code");
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("passes through (no toggle) when there is no conversation", () => {
+ const { intercept, onSubmit } = setup(null);
+ intercept("/plan");
+ expect(onSubmit).toHaveBeenCalledWith("/plan");
+ expect(handlePlanClick).not.toHaveBeenCalled();
+ });
+
+ it("swallows /plan while the agent is running (matches the disabled button)", () => {
+ const { intercept, onSubmit } = setup(CONV, AgentState.RUNNING);
+ intercept("/plan");
+ expect(handlePlanClick).not.toHaveBeenCalled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("swallows /code while the agent is running (matches the disabled button)", () => {
+ const { intercept, onSubmit } = setup(CONV, AgentState.RUNNING);
+ intercept("/code");
+ expect(setConversationMode).not.toHaveBeenCalled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("swallows /plan while a planning conversation is already being created", () => {
+ isCreatingConversation = true;
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("/plan");
+ expect(handlePlanClick).not.toHaveBeenCalled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("swallows /plan while the websocket is disconnected (matches the disabled button)", () => {
+ unifiedWebSocketStatus = "CLOSED";
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("/plan");
+ expect(handlePlanClick).not.toHaveBeenCalled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("swallows /code while the main websocket is disconnected", () => {
+ mainWebSocketStatus = "CLOSED";
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("/code");
+ expect(setConversationMode).not.toHaveBeenCalled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("does not swallow /code when only the planning socket is disconnected", () => {
+ // Regression: /code only needs the main socket, so a momentary planning
+ // reconnect (main OPEN, merged status CLOSED) must not silently drop it.
+ mainWebSocketStatus = "OPEN";
+ unifiedWebSocketStatus = "CLOSED";
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("/code fix the bug");
+ expect(setConversationMode).toHaveBeenCalledWith("code");
+ expect(onSubmit).toHaveBeenCalledWith("fix the bug");
+ });
+
+ it("swallows /plan <task> when the existing planner is already running", () => {
+ // Regression: a new message must not be routed into a planner that's
+ // still mid-run, mirroring isPlanningAgentRunning elsewhere.
+ hasPlanner = true;
+ isPlanningAgentRunning = true;
+ const { intercept, onSubmit } = setup(CONV);
+ intercept("/plan another task");
+ expect(setConversationMode).not.toHaveBeenCalled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(handlePlanClick).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/hooks/chat/use-plan-mode-interceptor.ts b/src/hooks/chat/use-plan-mode-interceptor.ts
new file mode 100644
index 0000000000..8f82ef8f88
--- /dev/null
+++ b/src/hooks/chat/use-plan-mode-interceptor.ts
@@ -0,0 +1,100 @@
+import { useCallback } from "react";
+import { useConversationStore } from "#/stores/conversation-store";
+import { useHandlePlanClick } from "#/hooks/use-handle-plan-click";
+import {
+ useMainWebSocketStatus,
+ useUnifiedWebSocketStatus,
+} from "#/hooks/use-unified-websocket-status";
+import { usePlanningAgentState } from "#/hooks/use-agent-state";
+import { AgentState } from "#/types/agent-state";
+import { PLAN_COMMAND, CODE_COMMAND } from "#/utils/constants";
+
+const PLAN_PREFIX = `${PLAN_COMMAND} `;
+const CODE_PREFIX = `${CODE_COMMAND} `;
+
+/**
+ * Intercepts "/plan [task]" and "/code [task]" and toggles the conversation's
+ * mode like the Code/Plan button, instead of sending them as a chat message.
+ * A bare command only switches mode; "<task>" is sent immediately (mode is
+ * set synchronously first, so the send routes to the new mode β€” see
+ * conversation-websocket-context.tsx's `getState().conversationMode` read),
+ * or becomes the new planner's `initial_message` if it doesn't exist yet.
+ *
+ * Swallows the command while the relevant agent is running, a planner is
+ * being created, or the socket it needs is disconnected β€” "/code" gates on
+ * the main socket alone (not the main+planning merged status) so a momentary
+ * planning reconnect can't swallow it, and "/plan <task>" also checks the
+ * planner's own running state so it can't be routed into one still mid-run.
+ */
+export const usePlanModeInterceptor = (
+ conversationId: string | null | undefined,
+ curAgentState: AgentState,
+ onSubmit: (message: string) => void,
+) => {
+ const setConversationMode = useConversationStore(
+ (s) => s.setConversationMode,
+ );
+ const { handlePlanClick, hasPlanner, isCreatingConversation } =
+ useHandlePlanClick();
+ const isMainWebSocketConnected = useMainWebSocketStatus() === "OPEN";
+ const isWebSocketConnected = useUnifiedWebSocketStatus() === "OPEN";
+ const { isPlanningAgentRunning } = usePlanningAgentState();
+
+ return useCallback(
+ (message: string) => {
+ const trimmed = message.trim();
+ const isPlan =
+ trimmed === PLAN_COMMAND || trimmed.startsWith(PLAN_PREFIX);
+ const isCode =
+ trimmed === CODE_COMMAND || trimmed.startsWith(CODE_PREFIX);
+ if (!conversationId || (!isPlan && !isCode)) {
+ onSubmit(message);
+ return;
+ }
+
+ if (curAgentState === AgentState.RUNNING || isCreatingConversation) {
+ return;
+ }
+
+ if (isPlan) {
+ if (isPlanningAgentRunning || !isWebSocketConnected) {
+ return;
+ }
+ const task = trimmed.slice(PLAN_COMMAND.length).trim();
+ if (task && hasPlanner) {
+ // Planner already exists: switch mode, then send normally β€” the
+ // send path reads the just-set mode synchronously, so this routes
+ // to the planner rather than the code agent.
+ setConversationMode("plan");
+ onSubmit(task);
+ } else {
+ handlePlanClick(undefined, task || undefined);
+ }
+ } else {
+ if (!isMainWebSocketConnected) {
+ return;
+ }
+ setConversationMode("code");
+ const task = trimmed.slice(CODE_COMMAND.length).trim();
+ if (task) {
+ // The parent (code) conversation always already exists, so this
+ // can always send immediately β€” same synchronous-mode-read routing
+ // as the /plan-with-existing-planner case above.
+ onSubmit(task);
+ }
+ }
+ },
+ [
+ conversationId,
+ curAgentState,
+ hasPlanner,
+ isCreatingConversation,
+ isMainWebSocketConnected,
+ isPlanningAgentRunning,
+ isWebSocketConnected,
+ onSubmit,
+ handlePlanClick,
+ setConversationMode,
+ ],
+ );
+};
diff --git a/src/hooks/mutation/use-read-conversation-file.ts b/src/hooks/mutation/use-read-conversation-file.ts
index 4628d45c1f..3b51bf4803 100644
--- a/src/hooks/mutation/use-read-conversation-file.ts
+++ b/src/hooks/mutation/use-read-conversation-file.ts
@@ -1,5 +1,8 @@
import { useMutation } from "@tanstack/react-query";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { getErrorStatus } from "#/hooks/query/use-settings";
+import { displayErrorToast } from "#/utils/custom-toast-handlers";
+import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
interface UseReadConversationFileVariables {
conversationId: string;
@@ -9,6 +12,9 @@ interface UseReadConversationFileVariables {
export const useReadConversationFile = () =>
useMutation({
mutationKey: ["read-conversation-file"],
+ // A 404 (no plan yet) is expected and must stay silent; `onError` below
+ // re-shows the toast for anything else so real failures still surface.
+ meta: { disableToast: true },
mutationFn: async ({
conversationId,
filePath,
@@ -17,4 +23,8 @@ export const useReadConversationFile = () =>
conversationId,
filePath,
),
+ onError: (error) => {
+ if (getErrorStatus(error) === 404) return;
+ displayErrorToast(retrieveAxiosErrorMessage(error));
+ },
});
diff --git a/src/hooks/query/query-keys.ts b/src/hooks/query/query-keys.ts
index ffa597dbf3..44edeeaf58 100644
--- a/src/hooks/query/query-keys.ts
+++ b/src/hooks/query/query-keys.ts
@@ -80,6 +80,14 @@ export const APP_UPDATE_QUERY_KEYS = {
latestVersion: ["agent-canvas-latest-version"] as const,
} as const;
+export const CONVERSATION_QUERY_KEYS = {
+ subConversations: ["v1", "sub-conversations"] as const,
+} as const;
+
+export const LOCAL_PLANNER_MUTATION_KEYS = {
+ create: ["create-local-planning-conversation"] as const,
+} as const;
+
/** Cache configuration shared across all config-related queries */
export const CONFIG_CACHE_OPTIONS = {
staleTime: 1000 * 60 * 5, // 5 minutes
diff --git a/src/hooks/query/use-sub-conversations.ts b/src/hooks/query/use-sub-conversations.ts
index 5dd3922480..c7de6c4abd 100644
--- a/src/hooks/query/use-sub-conversations.ts
+++ b/src/hooks/query/use-sub-conversations.ts
@@ -2,6 +2,7 @@ import { useQuery } from "@tanstack/react-query";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
import { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
import { useActiveBackend } from "#/contexts/active-backend-context";
+import { CONVERSATION_QUERY_KEYS } from "./query-keys";
const FIVE_MINUTES = 1000 * 60 * 5;
const FIFTEEN_MINUTES = 1000 * 60 * 15;
@@ -31,7 +32,12 @@ export const useSubConversations = (
// `null` result captured while the cloud backend was active can
// bleed through to the next local visit. Same invariant as
// `useUserConversation` and `usePaginatedConversations`.
- queryKey: ["v1", "sub-conversations", ids, active.backend.id, active.orgId],
+ queryKey: [
+ ...CONVERSATION_QUERY_KEYS.subConversations,
+ ids,
+ active.backend.id,
+ active.orgId,
+ ],
queryFn: async () => {
if (ids.length === 0) {
return [];
diff --git a/src/hooks/use-agent-state.test.tsx b/src/hooks/use-agent-state.test.tsx
index 77b0c32321..e2bf9c3572 100644
--- a/src/hooks/use-agent-state.test.tsx
+++ b/src/hooks/use-agent-state.test.tsx
@@ -2,16 +2,24 @@ import { act, renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useAgentState } from "./use-agent-state";
import { useActiveConversation } from "./query/use-active-conversation";
+import { useOptionalConversationId } from "./use-conversation-id";
import { useConversationStateStore } from "#/stores/conversation-state-store";
import { AgentState } from "#/types/agent-state";
import { ExecutionStatus } from "#/types/agent-server/core/base/common";
+const TEST_CONVERSATION_ID = "test-conversation-id";
+
vi.mock("./query/use-active-conversation", () => ({
useActiveConversation: vi.fn(),
}));
+vi.mock("./use-conversation-id", () => ({
+ useOptionalConversationId: vi.fn(),
+}));
+
describe("useAgentState", () => {
const mockUseActiveConversation = vi.mocked(useActiveConversation);
+ const mockUseOptionalConversationId = vi.mocked(useOptionalConversationId);
beforeEach(() => {
act(() => {
@@ -21,6 +29,10 @@ describe("useAgentState", () => {
mockUseActiveConversation.mockReturnValue({
data: null,
} as ReturnType<typeof useActiveConversation>);
+
+ mockUseOptionalConversationId.mockReturnValue({
+ conversationId: TEST_CONVERSATION_ID,
+ });
});
it("prefers live websocket execution status over cached conversation status", () => {
@@ -33,7 +45,7 @@ describe("useAgentState", () => {
act(() => {
useConversationStateStore
.getState()
- .setExecutionStatus(ExecutionStatus.RUNNING);
+ .setExecutionStatus(TEST_CONVERSATION_ID, ExecutionStatus.RUNNING);
});
const { result } = renderHook(() => useAgentState());
diff --git a/src/hooks/use-agent-state.ts b/src/hooks/use-agent-state.ts
index a86388911f..ccd7d8cdc0 100644
--- a/src/hooks/use-agent-state.ts
+++ b/src/hooks/use-agent-state.ts
@@ -1,6 +1,8 @@
import { useMemo } from "react";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+import { useOptionalConversationId } from "#/hooks/use-conversation-id";
import { useConversationStateStore } from "#/stores/conversation-state-store";
+import { useConversationStore } from "#/stores/conversation-store";
import { AgentState } from "#/types/agent-state";
import { ExecutionStatus } from "#/types/agent-server/core/base/common";
@@ -41,13 +43,30 @@ export interface UseAgentStateResult {
/**
* Returns the current agent state from conversation execution status.
+ *
+ * Defaults to the conversation in the current route. Pass `conversationId`
+ * to read another conversation's status instead β€” e.g. a local planner
+ * helper conversation, whose run/idle transitions are tracked separately
+ * from the main conversation's (see conversation-state-store.ts).
*/
-export function useAgentState(): UseAgentStateResult {
- const liveExecutionStatus = useConversationStateStore(
- (state) => state.execution_status,
+export function useAgentState(conversationId?: string): UseAgentStateResult {
+ const { conversationId: routeConversationId } = useOptionalConversationId();
+ const targetConversationId = conversationId ?? routeConversationId;
+ const isRouteConversation =
+ !conversationId || conversationId === routeConversationId;
+
+ const liveExecutionStatus = useConversationStateStore((state) =>
+ targetConversationId
+ ? (state.executionStatusByConversation[targetConversationId] ?? null)
+ : null,
);
- const fallbackExecutionStatus =
+ // The REST fallback only ever describes the route's own conversation, so it
+ // only applies when no other conversation was explicitly requested.
+ const routeConversationExecutionStatus =
useActiveConversation().data?.execution_status ?? null;
+ const fallbackExecutionStatus = isRouteConversation
+ ? routeConversationExecutionStatus
+ : null;
const executionStatus = liveExecutionStatus ?? fallbackExecutionStatus;
const curAgentState = useMemo(
@@ -57,3 +76,32 @@ export function useAgentState(): UseAgentStateResult {
return { curAgentState, executionStatus };
}
+
+export interface UsePlanningAgentStateResult {
+ localPlanningConversationId: string | null;
+ curPlanningAgentState: AgentState;
+ /** Running or loading. `false` (not "unknown") when there's no planner yet. */
+ isPlanningAgentRunning: boolean;
+}
+
+/**
+ * The local planner helper's own state β€” read separately from the main
+ * conversation's via `useAgentState` since the two run independently.
+ */
+export function usePlanningAgentState(): UsePlanningAgentStateResult {
+ const localPlanningConversationId = useConversationStore(
+ (state) => state.localPlanningConversationId,
+ );
+ const { curAgentState: curPlanningAgentState } = useAgentState(
+ localPlanningConversationId ?? undefined,
+ );
+ const isPlanningAgentRunning =
+ !!localPlanningConversationId &&
+ (curPlanningAgentState === AgentState.RUNNING ||
+ curPlanningAgentState === AgentState.LOADING);
+ return {
+ localPlanningConversationId,
+ curPlanningAgentState,
+ isPlanningAgentRunning,
+ };
+}
diff --git a/src/hooks/use-app-title.test.tsx b/src/hooks/use-app-title.test.tsx
index 660ead070b..63b95d25bd 100644
--- a/src/hooks/use-app-title.test.tsx
+++ b/src/hooks/use-app-title.test.tsx
@@ -82,7 +82,7 @@ describe("useAppTitle", () => {
// @ts-expect-error - only returning partial config for test
data: { title: "My Conversation" },
});
- useConversationStateStore.getState().setExecutionStatus(status);
+ useConversationStateStore.getState().setExecutionStatus("123", status);
const { result } = renderAppTitleHook();
diff --git a/src/hooks/use-app-title.ts b/src/hooks/use-app-title.ts
index 5f1f956070..187721c8e6 100644
--- a/src/hooks/use-app-title.ts
+++ b/src/hooks/use-app-title.ts
@@ -8,8 +8,10 @@ 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 liveExecutionStatus = useConversationStateStore((state) =>
+ conversationId
+ ? (state.executionStatusByConversation[conversationId] ?? null)
+ : null,
);
const conversationTitle = conversation?.title;
diff --git a/src/hooks/use-handle-plan-click.ts b/src/hooks/use-handle-plan-click.ts
index 243cef56cf..599084972e 100644
--- a/src/hooks/use-handle-plan-click.ts
+++ b/src/hooks/use-handle-plan-click.ts
@@ -1,14 +1,88 @@
-import { useCallback, useEffect } from "react";
+import { useCallback, useEffect, type MouseEvent } from "react";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
import { useConversationStore } from "#/stores/conversation-store";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useCreateConversation } from "#/hooks/mutation/use-create-conversation";
-import { displaySuccessToast } from "#/utils/custom-toast-handlers";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+} from "#/utils/custom-toast-handlers";
import {
getConversationState,
setConversationState,
} from "#/utils/conversation-local-storage";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { getStoredConversationMetadata } from "#/api/conversation-metadata-store";
+import {
+ CONVERSATION_QUERY_KEYS,
+ LOCAL_PLANNER_MUTATION_KEYS,
+} from "#/hooks/query/query-keys";
+import { useSubConversations } from "#/hooks/query/use-sub-conversations";
+import { findPlannerConversationId } from "#/utils/plan-file";
+import { invalidateConversationQueries } from "#/hooks/mutation/conversation-mutation-utils";
+
+function useCreateLocalPlanningConversationMutation(options: {
+ onCreated: (planningConversationId: string) => void;
+ onInitialized: () => void;
+ onFailed: () => void;
+}) {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationKey: LOCAL_PLANNER_MUTATION_KEYS.create,
+ mutationFn: (variables: {
+ parentConversationId: string;
+ initialMessage?: string;
+ }) =>
+ AgentServerConversationService.createLocalPlanningConversation(
+ variables.parentConversationId,
+ variables.initialMessage,
+ ),
+ onSuccess: (planningConversation, variables) => {
+ options.onCreated(planningConversation.id);
+ invalidateConversationQueries(
+ queryClient,
+ variables.parentConversationId,
+ );
+ queryClient.invalidateQueries({
+ queryKey: CONVERSATION_QUERY_KEYS.subConversations,
+ });
+ options.onInitialized();
+ },
+ onError: options.onFailed,
+ });
+}
+
+function restorePlanningConversationIds(options: {
+ conversationId: string;
+ serverPlanningConversationId: string | null;
+ subConversationTaskId: string | null;
+ localPlanningConversationId: string | null;
+ setSubConversationTaskId: (taskId: string | null) => void;
+ setLocalPlanningConversationId: (conversationId: string | null) => void;
+}) {
+ const storedState = getConversationState(options.conversationId);
+ if (storedState.subConversationTaskId && !options.subConversationTaskId) {
+ options.setSubConversationTaskId(storedState.subConversationTaskId);
+ }
+
+ // Server first: `sub_conversation_ids` is derived by the agent-server from
+ // the planner's `parent_conversation_id`, so it survives cleared site data
+ // and follows the user to another browser. The localStorage hint is only the
+ // fallback for agent-servers older than 1.37.1, which drop the parent link.
+ const restoredId =
+ options.serverPlanningConversationId ??
+ getStoredConversationMetadata(options.conversationId)
+ ?.local_planning_conversation_id ??
+ null;
+
+ if (restoredId && restoredId !== options.localPlanningConversationId) {
+ options.setLocalPlanningConversationId(restoredId);
+ }
+}
/**
* Custom hook that encapsulates the logic for handling plan creation.
@@ -19,61 +93,132 @@ import {
*/
export const useHandlePlanClick = () => {
const { t } = useTranslation("openhands");
+ const { backend } = useActiveBackend();
const {
setConversationMode,
setSubConversationTaskId,
subConversationTaskId,
+ setLocalPlanningConversationId,
+ localPlanningConversationId,
} = useConversationStore();
const { data: conversation } = useActiveConversation();
- const { mutate: createConversation, isPending: isCreatingConversation } =
+ const { mutate: createConversation, isPending: isCreatingCloudConversation } =
useCreateConversation();
+ const {
+ mutate: createLocalPlanningConversation,
+ isPending: isCreatingLocalPlanningConversation,
+ } = useCreateLocalPlanningConversationMutation({
+ onCreated: setLocalPlanningConversationId,
+ onInitialized: () => {
+ displaySuccessToast(
+ t(I18nKey.PLANNING_AGENTT$PLANNING_AGENT_INITIALIZED),
+ );
+ },
+ // handlePlanClick sets conversationMode("plan") before this mutation
+ // starts. On failure, back out of that mode instead of stranding the
+ // user in plan mode with no planner to talk to.
+ onFailed: () => {
+ setConversationMode("code");
+ displayErrorToast(t(I18nKey.CONVERSATION$ERROR_STARTING_CONVERSATION));
+ },
+ });
- // Restore subConversationTaskId from localStorage on conversation load
- // This handles the case where page was refreshed while sub-conversation creation was in progress
+ // On local backends the agent-server reports the planner helper back on the
+ // parent's `sub_conversation_ids` (it was created with
+ // `parent_conversation_id`), so that is the authoritative handle. Cloud
+ // sub-conversations are driven by their own task/socket plumbing.
+ const isLocalBackend = backend.kind !== "cloud";
+ const { data: rawSubConversations } = useSubConversations(
+ isLocalBackend ? conversation?.sub_conversation_ids : undefined,
+ );
+
+ const serverPlanningConversationId = isLocalBackend
+ ? findPlannerConversationId(rawSubConversations, conversation?.id)
+ : null;
+
+ // Restore planning conversation ids on conversation load. This handles page
+ // refreshes while cloud or local planning conversation creation is in
+ // progress, and recovers the local planner after browser storage is lost.
useEffect(() => {
if (!conversation?.id) return;
- const storedState = getConversationState(conversation.id);
- if (storedState.subConversationTaskId && !subConversationTaskId) {
- setSubConversationTaskId(storedState.subConversationTaskId);
- }
- }, [conversation?.id, subConversationTaskId, setSubConversationTaskId]);
+ restorePlanningConversationIds({
+ conversationId: conversation.id,
+ serverPlanningConversationId,
+ subConversationTaskId,
+ localPlanningConversationId,
+ setSubConversationTaskId,
+ setLocalPlanningConversationId,
+ });
+ }, [
+ conversation?.id,
+ serverPlanningConversationId,
+ localPlanningConversationId,
+ setLocalPlanningConversationId,
+ subConversationTaskId,
+ setSubConversationTaskId,
+ ]);
+
+ const hasCloudPlanner = !!(
+ (conversation?.sub_conversation_ids &&
+ conversation.sub_conversation_ids.length > 0) ||
+ subConversationTaskId
+ );
+ // Whether a planner helper already exists for this conversation β€” callers
+ // (e.g. the `/plan <task>` interceptor) use this to decide whether they can
+ // send a message to the planner immediately, or must wait for creation.
+ const hasPlanner = isLocalBackend
+ ? !!(localPlanningConversationId || serverPlanningConversationId)
+ : hasCloudPlanner;
const handlePlanClick = useCallback(
- (event?: React.MouseEvent<HTMLButtonElement> | KeyboardEvent) => {
+ (
+ event?: MouseEvent<HTMLButtonElement> | KeyboardEvent,
+ initialMessage?: string,
+ ) => {
event?.preventDefault();
event?.stopPropagation();
- // Set conversation mode to "plan" immediately
setConversationMode("plan");
- // Check if sub_conversation_ids is not empty or if a sub-conversation creation is already in progress
- if (
- (conversation?.sub_conversation_ids &&
- conversation.sub_conversation_ids.length > 0) ||
- !conversation?.id ||
- subConversationTaskId
- ) {
- // Do nothing if any condition is true
+ if (backend.kind !== "cloud") {
+ // Guard on the server-reported helper, the store, and the mutation's
+ // own in-flight state β€” the last one stops two rapid invocations
+ // (e.g. a double-click) from both passing before either updates and
+ // creating two planners for the same parent.
+ if (
+ !conversation?.id ||
+ localPlanningConversationId ||
+ serverPlanningConversationId ||
+ isCreatingLocalPlanningConversation
+ ) {
+ return;
+ }
+ createLocalPlanningConversation({
+ parentConversationId: conversation.id,
+ initialMessage,
+ });
+ return;
+ }
+
+ if (hasCloudPlanner || !conversation?.id) {
return;
}
- // Create a new sub-conversation if we have a current conversation ID
createConversation(
{
parentConversationId: conversation.id,
agentType: "plan",
entryPoint: "plan_sub_conversation",
+ ...(initialMessage ? { query: initialMessage } : {}),
},
{
onSuccess: (data) => {
displaySuccessToast(
t(I18nKey.PLANNING_AGENTT$PLANNING_AGENT_INITIALIZED),
);
- // Track the task ID to poll for sub-conversation creation
if (data.task_id) {
setSubConversationTaskId(data.task_id);
- // Persist to localStorage so it survives page refresh
setConversationState(conversation.id, {
subConversationTaskId: data.task_id,
});
@@ -83,14 +228,24 @@ export const useHandlePlanClick = () => {
);
},
[
+ backend.kind,
conversation,
createConversation,
+ createLocalPlanningConversation,
+ hasCloudPlanner,
+ isCreatingLocalPlanningConversation,
+ localPlanningConversationId,
+ serverPlanningConversationId,
setConversationMode,
setSubConversationTaskId,
- subConversationTaskId,
t,
],
);
- return { handlePlanClick, isCreatingConversation };
+ return {
+ handlePlanClick,
+ hasPlanner,
+ isCreatingConversation:
+ isCreatingCloudConversation || isCreatingLocalPlanningConversation,
+ };
};
diff --git a/src/hooks/use-unified-websocket-status.ts b/src/hooks/use-unified-websocket-status.ts
index 3be2125fe5..8786a8fd9b 100644
--- a/src/hooks/use-unified-websocket-status.ts
+++ b/src/hooks/use-unified-websocket-status.ts
@@ -10,3 +10,16 @@ export function useUnifiedWebSocketStatus(): WebSocketConnectionState {
const conversationContext = useConversationWebSocket();
return conversationContext ? conversationContext.connectionState : "CLOSED";
}
+
+/**
+ * The main connection's own status, unmerged with the planning connection.
+ * Use for actions that only address the main conversation (e.g. `/code`) β€”
+ * `useUnifiedWebSocketStatus` can report non-OPEN purely from a momentary
+ * planning reconnect.
+ */
+export function useMainWebSocketStatus(): WebSocketConnectionState {
+ const conversationContext = useConversationWebSocket();
+ return conversationContext
+ ? conversationContext.mainConnectionState
+ : "CLOSED";
+}
diff --git a/src/routes/planner-tab.tsx b/src/routes/planner-tab.tsx
index 6af41b22b5..a54826a438 100644
--- a/src/routes/planner-tab.tsx
+++ b/src/routes/planner-tab.tsx
@@ -9,6 +9,8 @@ import { useScrollToBottom } from "#/hooks/use-scroll-to-bottom";
import { MarkdownRenderer } from "#/components/features/markdown/markdown-renderer";
import { planComponents } from "#/components/features/markdown/plan-components";
import { useHandlePlanClick } from "#/hooks/use-handle-plan-click";
+import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+import { useReadConversationFile } from "#/hooks/mutation/use-read-conversation-file";
function PlannerTab() {
const { t } = useTranslation("openhands");
@@ -20,7 +22,41 @@ function PlannerTab() {
scrollDomToBottom,
} = useScrollToBottom(scrollRef);
- const { planContent, conversationMode } = useConversationStore();
+ const {
+ planContent,
+ conversationMode,
+ localPlanningConversationId,
+ setPlanContent,
+ } = useConversationStore();
+ const { data: conversation } = useActiveConversation();
+ const { mutate: readConversationFile } = useReadConversationFile();
+
+ React.useEffect(() => {
+ // Prefer the planner helper's own id β€” it's where PLAN.md is canonically
+ // read from (see conversation-websocket-context.tsx). The parent id is
+ // only a fallback for local planners created before the working_dir was
+ // shared, where both ids happen to resolve to the same file.
+ const readConversationId = localPlanningConversationId ?? conversation?.id;
+ if (!readConversationId || planContent !== null) return;
+
+ readConversationFile(
+ { conversationId: readConversationId },
+ {
+ onSuccess: (fileContent) => {
+ setPlanContent(fileContent);
+ },
+ onError: () => {
+ // Missing PLAN.md is the normal empty-planner state.
+ },
+ },
+ );
+ }, [
+ conversation?.id,
+ localPlanningConversationId,
+ planContent,
+ readConversationFile,
+ setPlanContent,
+ ]);
// Auto-scroll to bottom when plan content changes
React.useEffect(() => {
@@ -29,7 +65,8 @@ function PlannerTab() {
}
}, [planContent, autoScroll, scrollDomToBottom]);
const isPlanMode = conversationMode === "plan";
- const { handlePlanClick } = useHandlePlanClick();
+ const { handlePlanClick, hasPlanner, isCreatingConversation } =
+ useHandlePlanClick();
if (planContent !== null && planContent !== undefined) {
return (
@@ -53,7 +90,7 @@ function PlannerTab() {
type="button"
variant="secondary"
onClick={handlePlanClick}
- isDisabled={isPlanMode}
+ isDisabled={isPlanMode || isCreatingConversation || hasPlanner}
className="min-w-40 justify-center px-6"
>
{t(I18nKey.COMMON$CREATE_A_PLAN)}
diff --git a/src/stores/conversation-state-store.ts b/src/stores/conversation-state-store.ts
index dd2dc4027f..e299273b67 100644
--- a/src/stores/conversation-state-store.ts
+++ b/src/stores/conversation-state-store.ts
@@ -2,12 +2,21 @@ import { create } from "zustand";
import { ExecutionStatus } from "#/types/agent-server/core/base/common";
interface ConversationStateStore {
- execution_status: ExecutionStatus | null;
+ /**
+ * Latest execution status per conversation, fed by the main and planning
+ * WebSocket handlers. Scoped by conversation id so the planning helper
+ * conversation's own run/idle transitions can never overwrite the main
+ * conversation's status (or vice versa) β€” see conversation-websocket-context.tsx.
+ */
+ executionStatusByConversation: Record<string, ExecutionStatus>;
/**
- * Set the agent status
+ * Set the agent status for a specific conversation.
*/
- setExecutionStatus: (execution_status: ExecutionStatus) => void;
+ setExecutionStatus: (
+ conversationId: string,
+ execution_status: ExecutionStatus,
+ ) => void;
/**
* Reset the store to initial state
@@ -17,11 +26,16 @@ interface ConversationStateStore {
export const useConversationStateStore = create<ConversationStateStore>(
(set) => ({
- execution_status: null,
+ executionStatusByConversation: {},
- setExecutionStatus: (execution_status: ExecutionStatus) =>
- set({ execution_status }),
+ setExecutionStatus: (conversationId, execution_status) =>
+ set((state) => ({
+ executionStatusByConversation: {
+ ...state.executionStatusByConversation,
+ [conversationId]: execution_status,
+ },
+ })),
- reset: () => set({ execution_status: null }),
+ reset: () => set({ executionStatusByConversation: {} }),
}),
);
diff --git a/src/stores/conversation-store.ts b/src/stores/conversation-store.ts
index 91967e42e4..621f4bec79 100644
--- a/src/stores/conversation-store.ts
+++ b/src/stores/conversation-store.ts
@@ -46,7 +46,8 @@ interface ConversationState {
hasRightPanelToggled: boolean;
planContent: string | null;
conversationMode: ConversationMode;
- subConversationTaskId: string | null; // Task ID for sub-conversation creation
+ subConversationTaskId: string | null; // Task ID for cloud sub-conversation creation
+ localPlanningConversationId: string | null;
}
interface ConversationActions {
@@ -82,6 +83,7 @@ interface ConversationActions {
setHasRightPanelToggled: (hasRightPanelToggled: boolean) => void;
setConversationMode: (conversationMode: ConversationMode) => void;
setSubConversationTaskId: (taskId: string | null) => void;
+ setLocalPlanningConversationId: (conversationId: string | null) => void;
setPlanContent: (planContent: string | null) => void;
}
@@ -144,6 +146,7 @@ export const useConversationStore = create<ConversationStore>()(
planContent: null,
conversationMode: getInitialConversationMode(),
subConversationTaskId: null,
+ localPlanningConversationId: null,
// Actions
setIsRightPanelShown: (isRightPanelShown) =>
@@ -355,6 +358,7 @@ export const useConversationStore = create<ConversationStore>()(
shouldHideSuggestions: false,
conversationMode: getInitialConversationMode(),
subConversationTaskId: null,
+ localPlanningConversationId: null,
planContent: null,
},
false,
@@ -375,6 +379,13 @@ export const useConversationStore = create<ConversationStore>()(
setSubConversationTaskId: (subConversationTaskId) =>
set({ subConversationTaskId }, false, "setSubConversationTaskId"),
+ setLocalPlanningConversationId: (localPlanningConversationId) =>
+ set(
+ { localPlanningConversationId },
+ false,
+ "setLocalPlanningConversationId",
+ ),
+
setPlanContent: (planContent) =>
set({ planContent }, false, "setPlanContent"),
}),
diff --git a/src/utils/constants.ts b/src/utils/constants.ts
index 00e7901014..151d7406ed 100644
--- a/src/utils/constants.ts
+++ b/src/utils/constants.ts
@@ -44,6 +44,12 @@ export const MODEL_COMMAND = "/model";
/** The /goal slash command β€” drives the agent toward an objective, judging completion each round. */
export const GOAL_COMMAND = "/goal";
+/** The /plan slash command β€” switches the conversation into Plan mode. */
+export const PLAN_COMMAND = "/plan";
+
+/** The /code slash command β€” switches the conversation back to Code mode. */
+export const CODE_COMMAND = "/code";
+
/** Built-in slash commands surfaced in the menu for V1 conversations. */
export const BUILT_IN_COMMANDS: SlashCommandItem[] = [
{
@@ -88,6 +94,28 @@ export const BUILT_IN_COMMANDS: SlashCommandItem[] = [
},
command: GOAL_COMMAND,
},
+ {
+ skill: {
+ name: "plan",
+ type: "agentskills",
+ source: null,
+ content:
+ "Switch the conversation into Plan mode, or start planning immediately with /plan <task>",
+ triggers: [PLAN_COMMAND],
+ },
+ command: PLAN_COMMAND,
+ },
+ {
+ skill: {
+ name: "code",
+ type: "agentskills",
+ source: null,
+ content:
+ "Switch the conversation back to Code mode, or resume immediately with /code <task>",
+ triggers: [CODE_COMMAND],
+ },
+ command: CODE_COMMAND,
+ },
];
// Skill content metadata prefixes
diff --git a/src/utils/plan-file.ts b/src/utils/plan-file.ts
new file mode 100644
index 0000000000..2c3c6bde51
--- /dev/null
+++ b/src/utils/plan-file.ts
@@ -0,0 +1,101 @@
+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+
+export const PLAN_RELATIVE_PATH = ".agents_tmp/PLAN.md";
+export const PLANNING_SYSTEM_PROMPT_FILENAME = "system_prompt_planning.j2";
+export const PLANNING_FILE_EDITOR_TOOL_NAME = "planning_file_editor";
+export const LOCAL_PLANNER_PARENT_TAG_KEY = "plannerparent";
+
+const PLAN_FILENAME_UPPER = "PLAN.MD";
+
+// Mirrors the SDK planning preset's `format_plan_structure()` output
+// (software-agent-sdk openhands-tools/openhands/tools/preset/planning.py,
+// `PLAN_STRUCTURE`). The planning agent loads `system_prompt_planning.j2` with
+// this injected as `{{plan_structure}}`; keep it byte-identical to that SDK
+// output so the local planner matches the canonical planning agent.
+export const PLAN_STRUCTURE_TEXT = [
+ "The plan must follow this structure exactly:",
+ "",
+ "1. OBJECTIVE",
+ " * Summarize the goal of the plan in one or two sentences.",
+ " * Restate the problem in clear operational terms.",
+ "",
+ "2. CONTEXT SUMMARY",
+ " * Briefly describe the relevant system components, files, or data involved.",
+ " * Mention any dependencies or constraints (technical, organizational, or external).",
+ "",
+ "3. APPROACH OVERVIEW",
+ " * Outline the chosen approach at a high level.",
+ " * Mention why it was selected (short rationale) if alternatives were considered.",
+ "",
+ "4. IMPLEMENTATION STEPS",
+ " * Provide a step-by-step plan for execution.",
+ " * Each step should include:",
+ " - a **goal** (what this step accomplishes),",
+ " - a **method** (how to do it, briefly),",
+ " - and optionally a **reference** (file, module, or function impacted).",
+ "",
+ "5. TESTING AND VALIDATION",
+ " * Describe how the implementation can be verified or validated.",
+ " * This section should describe what success looks like β€” expected outputs, behaviors, or conditions.",
+].join("\n");
+
+// System-prompt suffix for the local planning agent (mirrors the OpenHands
+// app-server's PLANNING_AGENT_INSTRUCTION). The planner's directive + boundaries
+// live in the system prompt; the planning conversation is created idle, so the
+// user types the first message themselves and nothing is injected into the chat.
+export const PLANNING_AGENT_INSTRUCTION = [
+ "<IMPORTANT_PLANNING_BOUNDARIES>",
+ "You are a Planning Agent that can ONLY create plans - you CANNOT execute code or make changes.",
+ "",
+ "Create or update the plan for the current task in the configured PLAN.md file.",
+ "",
+ "After you finalize the plan in PLAN.md:",
+ '- Do NOT ask "Ready to proceed?" or offer to execute the plan',
+ "- Do NOT attempt to run any implementation commands",
+ "- Instead, tell the user they can click the **Build** button below the plan preview to switch to the code agent and execute the plan.",
+ "",
+ "Your role ends when the plan is finalized. Implementation is handled by the code agent.",
+ "</IMPORTANT_PLANNING_BOUNDARIES>",
+].join("\n");
+
+export function buildPlanPath(workingDir: string): string {
+ const normalized = workingDir.replace(/\/+$/, "");
+ return `${normalized}/${PLAN_RELATIVE_PATH}`;
+}
+
+export function isPlanFilePath(path: string | null | undefined): boolean {
+ if (!path) return false;
+ const normalized = path.replace(/\\/g, "/").toUpperCase();
+ return (
+ normalized === PLAN_FILENAME_UPPER ||
+ normalized.endsWith(`/${PLAN_FILENAME_UPPER}`)
+ );
+}
+
+/**
+ * Whether `conversation` is the local planner helper for `parentConversationId`
+ * β€” identity comes from the `plannerparent` tag `createLocalPlanningConversation`
+ * stamps on creation, never from list position (`sub_conversation_ids` is the
+ * generic, untyped child list).
+ */
+export function isPlannerConversationOf(
+ conversation: Pick<AppConversation, "tags"> | null | undefined,
+ parentConversationId: string,
+): boolean {
+ return (
+ conversation?.tags?.[LOCAL_PLANNER_PARENT_TAG_KEY] === parentConversationId
+ );
+}
+
+/** Finds the planner helper among a conversation's fetched sub-conversations. */
+export function findPlannerConversationId(
+ subConversations: (AppConversation | null)[] | null | undefined,
+ parentConversationId: string | null | undefined,
+): string | null {
+ if (!parentConversationId) return null;
+ return (
+ subConversations?.find((sub) =>
+ isPlannerConversationOf(sub, parentConversationId),
+ )?.id ?? null
+ );
+}