Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix(acp): wait for initialization before starting sessions (#10927)

Julioa617c195edd6
diff --git a/docs/guides/editor_features/agents.md b/docs/guides/editor_features/agents.md
index c723f987ba..bc31062539 100644
--- a/docs/guides/editor_features/agents.md
+++ b/docs/guides/editor_features/agents.md
@@ -23,6 +23,8 @@ marimo currently supports the following agents:
Claude Code Agent that uses your [Claude Code CLI subscription](https://docs.claude.com/en/docs/claude-code/overview) to help you with coding tasks.
+The Claude ACP adapter requires Node.js 22 or later. Sign in through the Claude CLI before you connect from marimo.
+
**Installation and login:**
```bash
@@ -38,13 +40,13 @@ claude
=== "macOS/Linux"
```bash
- npx stdio-to-ws "npx @zed-industries/claude-code-acp" --port 3017
+ npx stdio-to-ws "npx @agentclientprotocol/claude-agent-acp" --port 3017
```
=== "Windows"
```bash
- npx stdio-to-ws "cmd /c npx @zed-industries/claude-code-acp" --port 3017
+ npx stdio-to-ws "cmd /c npx @agentclientprotocol/claude-agent-acp" --port 3017
```
### Gemini Agent
diff --git a/frontend/src/components/chat/acp/__tests__/agent-panel-initialization.test.tsx b/frontend/src/components/chat/acp/__tests__/agent-panel-initialization.test.tsx
new file mode 100644
index 0000000000..97f906b77a
--- /dev/null
+++ b/frontend/src/components/chat/acp/__tests__/agent-panel-initialization.test.tsx
@@ -0,0 +1,383 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { Provider } from "jotai";
+import { JsonRpcError, type useAcpClient } from "use-acp";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { MockRequestClient } from "@/__mocks__/requests";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { pendingAiPromptAtom } from "@/core/ai/state";
+import { requestClientAtom } from "@/core/network/requests";
+import { cwdAtom, filenameAtom } from "@/core/saving/file-state";
+import { store } from "@/core/state/jotai";
+import AgentPanel from "../agent-panel";
+import {
+ addSession,
+ agentSessionStateAtom,
+ updateSessionExternalAgentSessionId,
+} from "../state";
+import type { AgentConnectionState, ExternalAgentSessionId } from "../types";
+
+type Agent = NonNullable<ReturnType<typeof useAcpClient>["agent"]>;
+type InitializeResponse = Awaited<ReturnType<Agent["initialize"]>>;
+
+const { client, connect, disconnect, setActiveSessionId } = vi.hoisted(() => {
+ const client: {
+ agent: ReturnType<typeof createAgent>["agent"] | null;
+ connectionState: AgentConnectionState;
+ activeSessionId: ExternalAgentSessionId | null;
+ } = {
+ agent: null,
+ connectionState: { status: "connected" },
+ activeSessionId: null,
+ };
+ return {
+ client,
+ connect: vi.fn().mockResolvedValue(undefined),
+ disconnect: vi.fn(),
+ setActiveSessionId: (sessionId: ExternalAgentSessionId | null) => {
+ client.activeSessionId = sessionId;
+ },
+ };
+});
+
+vi.mock("use-acp", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("use-acp")>()),
+ useAcpClient: () => ({
+ ...client,
+ connect,
+ disconnect,
+ notifications: [],
+ setActiveSessionId,
+ clearNotifications: vi.fn(),
+ }),
+}));
+vi.mock("@/components/editor/ai/add-cell-with-ai", () => ({
+ PromptInput: () => null,
+}));
+vi.mock("../session-tabs", () => ({ SessionTabs: () => null }));
+vi.mock("../blocks", () => ({ ReadyToChatBlock: () => null }));
+
+const initialized: InitializeResponse = {
+ protocolVersion: 1,
+ agentCapabilities: {},
+};
+const advertisedAuth: InitializeResponse = {
+ ...initialized,
+ authMethods: [{ id: "login", name: "Log in" }],
+};
+
+function createAgent() {
+ const initialization = Promise.withResolvers<InitializeResponse>();
+ const agent = {
+ initialize: vi
+ .fn<Agent["initialize"]>()
+ .mockReturnValue(initialization.promise),
+ authenticate: vi.fn<Agent["authenticate"]>().mockResolvedValue(undefined),
+ newSession: vi.fn<Agent["newSession"]>().mockImplementation(async () => {
+ client.activeSessionId = "new-session" as ExternalAgentSessionId;
+ return { sessionId: "new-session" };
+ }),
+ loadSession: vi
+ .fn<NonNullable<Agent["loadSession"]>>()
+ .mockImplementation(async ({ sessionId }) => {
+ client.activeSessionId = sessionId as ExternalAgentSessionId;
+ return {};
+ }),
+ cancel: vi.fn<Agent["cancel"]>().mockResolvedValue(undefined),
+ prompt: vi
+ .fn<Agent["prompt"]>()
+ .mockResolvedValue({ stopReason: "end_turn" }),
+ };
+ return { agent, initialization };
+}
+
+function renderPanel() {
+ const panel = () => (
+ <Provider store={store}>
+ <TooltipProvider>
+ <AgentPanel />
+ </TooltipProvider>
+ </Provider>
+ );
+ const view = render(panel());
+ return { ...view, refresh: () => view.rerender(panel()) };
+}
+
+function expectNoSessionRequests(
+ agent: ReturnType<typeof createAgent>["agent"],
+) {
+ expect(agent.newSession).not.toHaveBeenCalled();
+ expect(agent.loadSession).not.toHaveBeenCalled();
+}
+
+describe("AgentPanel initialization", () => {
+ beforeEach(() => {
+ client.agent = null;
+ client.activeSessionId = null;
+ client.connectionState = { status: "connected" };
+ store.set(requestClientAtom, MockRequestClient.create());
+ store.set(filenameAtom, "notebook.py");
+ store.set(cwdAtom, "/notebooks");
+ store.set(pendingAiPromptAtom, null);
+ store.set(
+ agentSessionStateAtom,
+ addSession({ sessions: [], activeTabId: null }, { agentId: "claude" }),
+ );
+ });
+
+ afterEach(() => {
+ store.set(pendingAiPromptAtom, null);
+ store.set(agentSessionStateAtom, { sessions: [], activeTabId: null });
+ store.set(filenameAtom, null);
+ store.set(cwdAtom, null);
+ });
+
+ it.each([null, "saved-session"])(
+ "waits for initialization before creating/loading %s",
+ async (sessionId) => {
+ const { agent, initialization } = createAgent();
+ client.agent = agent;
+ if (sessionId) {
+ store.set(agentSessionStateAtom, (state) =>
+ updateSessionExternalAgentSessionId(
+ state,
+ sessionId as ExternalAgentSessionId,
+ ),
+ );
+ }
+ const { refresh } = renderPanel();
+ expect(agent.initialize).toHaveBeenCalledOnce();
+ expectNoSessionRequests(agent);
+ expect(
+ screen.queryByRole("button", { name: "Restart" }),
+ ).not.toBeInTheDocument();
+
+ await act(async () => initialization.resolve(initialized));
+ expect(agent.authenticate).not.toHaveBeenCalled();
+ if (sessionId) {
+ expect(agent.loadSession).toHaveBeenCalledExactlyOnceWith({
+ sessionId,
+ cwd: "/notebooks",
+ mcpServers: [],
+ });
+ expect(agent.newSession).not.toHaveBeenCalled();
+ } else {
+ expect(agent.newSession).toHaveBeenCalledExactlyOnceWith({
+ cwd: "/notebooks",
+ mcpServers: [],
+ _meta: undefined,
+ });
+ expect(agent.loadSession).not.toHaveBeenCalled();
+ }
+ expect(
+ screen.getByRole("button", { name: "Restart" }),
+ ).toBeInTheDocument();
+ refresh();
+ expect(
+ agent.newSession.mock.calls.length +
+ agent.loadSession.mock.calls.length,
+ ).toBe(1);
+ },
+ );
+
+ it("uses existing CLI credentials even when the agent advertises login methods", async () => {
+ const { agent, initialization } = createAgent();
+ agent.authenticate.mockRejectedValue(new Error("Method not implemented."));
+ client.agent = agent;
+ renderPanel();
+
+ await act(async () => initialization.resolve(advertisedAuth));
+ expect(agent.authenticate).not.toHaveBeenCalled();
+ expect(agent.newSession).toHaveBeenCalledOnce();
+ });
+
+ it("surfaces initialization failures and offers a connection retry", async () => {
+ const { agent, initialization } = createAgent();
+ client.agent = agent;
+ const { refresh } = renderPanel();
+
+ await act(async () => initialization.reject(new Error("Handshake failed")));
+ expect(await screen.findByText("Handshake failed")).toBeInTheDocument();
+ expectNoSessionRequests(agent);
+ fireEvent.click(screen.getByRole("button", { name: "Retry connection" }));
+ expect(disconnect).toHaveBeenCalledOnce();
+ expect(connect).toHaveBeenCalledTimes(2);
+
+ const retried = createAgent();
+ client.agent = retried.agent;
+ refresh();
+ expect(screen.queryByText("Handshake failed")).not.toBeInTheDocument();
+ expectNoSessionRequests(retried.agent);
+ await act(async () => retried.initialization.resolve(initialized));
+ expect(retried.agent.newSession).toHaveBeenCalledOnce();
+ });
+
+ it("surfaces missing CLI credentials and lets the user retry after login", async () => {
+ const { agent, initialization } = createAgent();
+ const authError = new JsonRpcError({
+ code: -32_000,
+ message: "Authentication required",
+ data: { message: "Run claude /login in the terminal" },
+ });
+ agent.newSession
+ .mockRejectedValueOnce(authError)
+ .mockRejectedValueOnce(authError);
+ client.agent = agent;
+ renderPanel();
+
+ await act(async () => initialization.resolve(advertisedAuth));
+ expect(
+ await screen.findByText("Run claude /login in the terminal"),
+ ).toBeInTheDocument();
+ expect(agent.authenticate).not.toHaveBeenCalled();
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Restart session" }));
+ });
+ expect(agent.newSession).toHaveBeenCalledTimes(2);
+ expect(
+ screen.getByText("Run claude /login in the terminal"),
+ ).toBeInTheDocument();
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Restart session" }));
+ });
+ expect(agent.newSession).toHaveBeenCalledTimes(3);
+ expect(
+ screen.queryByText("Run claude /login in the terminal"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("does not authenticate or start a session for an agent switched away during initialization", async () => {
+ const old = createAgent();
+ const next = createAgent();
+ client.agent = old.agent;
+ renderPanel();
+ act(() => {
+ client.agent = next.agent;
+ store.set(agentSessionStateAtom, (state) =>
+ addSession(state, { agentId: "codex" }),
+ );
+ });
+
+ await act(async () => old.initialization.resolve(advertisedAuth));
+ expect(old.agent.authenticate).not.toHaveBeenCalled();
+ expectNoSessionRequests(old.agent);
+ expectNoSessionRequests(next.agent);
+ await act(async () => next.initialization.resolve(initialized));
+ expect(next.agent.newSession).toHaveBeenCalledOnce();
+ });
+
+ it("ignores a late initialization error from the previous agent", async () => {
+ const old = createAgent();
+ const next = createAgent();
+ client.agent = old.agent;
+ renderPanel();
+ act(() => {
+ client.agent = next.agent;
+ store.set(agentSessionStateAtom, (state) =>
+ addSession(state, { agentId: "codex" }),
+ );
+ });
+ await act(async () => next.initialization.resolve(initialized));
+ await act(async () =>
+ old.initialization.reject(new Error("Old agent failed")),
+ );
+ expect(screen.queryByText("Old agent failed")).not.toBeInTheDocument();
+ expect(next.agent.newSession).toHaveBeenCalledOnce();
+ });
+
+ it("ignores the old handshake when the same agent reconnects before it finishes", async () => {
+ const { agent, initialization } = createAgent();
+ const reinitialization = Promise.withResolvers<InitializeResponse>();
+ agent.initialize
+ .mockReturnValueOnce(initialization.promise)
+ .mockReturnValueOnce(reinitialization.promise);
+ client.agent = agent;
+ const { refresh } = renderPanel();
+
+ client.connectionState = { status: "disconnected" };
+ refresh();
+ client.connectionState = { status: "connected" };
+ refresh();
+ expect(agent.initialize).toHaveBeenCalledTimes(2);
+ await act(async () => initialization.resolve(advertisedAuth));
+ expect(agent.authenticate).not.toHaveBeenCalled();
+ expectNoSessionRequests(agent);
+ await act(async () => reinitialization.resolve(initialized));
+ expect(agent.newSession).toHaveBeenCalledOnce();
+ });
+
+ it("invalidates readiness on disconnect and reinitializes before resuming", async () => {
+ const { agent, initialization } = createAgent();
+ const reinitialization = Promise.withResolvers<InitializeResponse>();
+ agent.initialize
+ .mockReturnValueOnce(initialization.promise)
+ .mockReturnValueOnce(reinitialization.promise);
+ client.agent = agent;
+ const { refresh } = renderPanel();
+ await act(async () => initialization.resolve(initialized));
+ expect(agent.newSession).toHaveBeenCalledOnce();
+
+ client.connectionState = { status: "disconnected" };
+ refresh();
+ client.connectionState = { status: "connected" };
+ refresh();
+ expect(agent.loadSession).not.toHaveBeenCalled();
+ await act(async () => reinitialization.resolve(initialized));
+ expect(agent.loadSession).toHaveBeenCalledExactlyOnceWith({
+ sessionId: "new-session",
+ cwd: "/notebooks",
+ mcpServers: [],
+ });
+ expect(agent.newSession).toHaveBeenCalledOnce();
+ });
+
+ it("keeps a queued prompt pending until initialization and session loading finish", async () => {
+ const { agent, initialization } = createAgent();
+ const loading = Promise.withResolvers<undefined>();
+ agent.loadSession.mockImplementation(async ({ sessionId }) => {
+ await loading.promise;
+ client.activeSessionId = sessionId as ExternalAgentSessionId;
+ return {};
+ });
+ client.agent = agent;
+ client.activeSessionId = "saved-session" as ExternalAgentSessionId;
+ store.set(agentSessionStateAtom, (state) =>
+ updateSessionExternalAgentSessionId(
+ state,
+ "saved-session" as ExternalAgentSessionId,
+ ),
+ );
+ store.set(pendingAiPromptAtom, { prompt: "Help", submit: true });
+ renderPanel();
+ expect(store.get(pendingAiPromptAtom)).toEqual({
+ prompt: "Help",
+ submit: true,
+ });
+ expect(agent.prompt).not.toHaveBeenCalled();
+
+ await act(async () => initialization.resolve(initialized));
+ expect(agent.loadSession).toHaveBeenCalledOnce();
+ expect(agent.prompt).not.toHaveBeenCalled();
+ expect(store.get(pendingAiPromptAtom)).toEqual({
+ prompt: "Help",
+ submit: true,
+ });
+ await act(async () => loading.resolve(undefined));
+ expect(agent.prompt).toHaveBeenCalledOnce();
+ expect(agent.loadSession.mock.invocationCallOrder[0]).toBeLessThan(
+ agent.prompt.mock.invocationCallOrder[0],
+ );
+ expect(store.get(pendingAiPromptAtom)).toBeNull();
+ });
+
+ it("does not finish initialization after unmount", async () => {
+ const { agent, initialization } = createAgent();
+ client.agent = agent;
+ const { unmount } = renderPanel();
+ unmount();
+ await act(async () => initialization.resolve(advertisedAuth));
+ expect(agent.authenticate).not.toHaveBeenCalled();
+ expectNoSessionRequests(agent);
+ });
+});
diff --git a/frontend/src/components/chat/acp/__tests__/agent-panel.test.tsx b/frontend/src/components/chat/acp/__tests__/agent-panel.test.tsx
index 098d70ed89..9f12c2f43d 100644
--- a/frontend/src/components/chat/acp/__tests__/agent-panel.test.tsx
+++ b/frontend/src/components/chat/acp/__tests__/agent-panel.test.tsx
@@ -90,14 +90,16 @@ vi.mock("../context-utils", async (importOriginal) => ({
}));
vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));
-function renderPanel() {
- return render(
+async function renderPanel() {
+ const view = render(
<Provider store={store}>
<TooltipProvider>
<AgentPanel />
</TooltipProvider>
</Provider>,
);
+ await screen.findByRole("textbox", { name: "Prompt" });
+ return view;
}
function submitPrompt(prompt = "Explain this notebook") {
@@ -138,7 +140,7 @@ describe("AgentPanel prompt submission", () => {
it("preserves the draft, attachment and title when the notebook is unnamed", async () => {
store.set(filenameAtom, null);
- renderPanel();
+ await renderPanel();
const title = store.get(selectedTabAtom)?.title;
fireEvent.change(screen.getByLabelText("Attachment"), {
target: {
@@ -181,7 +183,7 @@ describe("AgentPanel prompt submission", () => {
"shows a rejected prompt and allows another submission after dismissal (%s)",
async (error) => {
agent.prompt.mockRejectedValueOnce(error);
- renderPanel();
+ await renderPanel();
submitPrompt();
expect(await screen.findByText(/Agent unavailable/)).toBeInTheDocument();
@@ -205,7 +207,7 @@ describe("AgentPanel prompt submission", () => {
data: { message: "Sign in to the agent" },
}),
);
- renderPanel();
+ await renderPanel();
submitPrompt();
expect(await screen.findByText("Sign in to the agent")).toBeInTheDocument();
@@ -221,7 +223,7 @@ describe("AgentPanel prompt submission", () => {
vi.mocked(parseContextFromPrompt).mockRejectedValueOnce(
new Error("Context unavailable"),
);
- renderPanel();
+ await renderPanel();
submitPrompt();
expect(await screen.findByText("Context unavailable")).toBeInTheDocument();
@@ -234,7 +236,7 @@ describe("AgentPanel prompt submission", () => {
it("reports failures from a queued prompt through the same handler", async () => {
agent.prompt.mockRejectedValueOnce(new Error("Queued prompt failed"));
- renderPanel();
+ await renderPanel();
act(() =>
store.set(pendingAiPromptAtom, {
prompt: "Help with this cell",
@@ -255,7 +257,7 @@ describe("AgentPanel prompt submission", () => {
it("clears busy state when a cancelled prompt settles", async () => {
const response = Promise.withResolvers<{ stopReason: string }>();
agent.prompt.mockReturnValueOnce(response.promise);
- renderPanel();
+ await renderPanel();
submitPrompt();
await waitFor(() => expect(agent.prompt).toHaveBeenCalledOnce());
expect(screen.getByText("Agent is working...")).toBeInTheDocument();
diff --git a/frontend/src/components/chat/acp/__tests__/state.test.ts b/frontend/src/components/chat/acp/__tests__/state.test.ts
index 948c103f36..7fe0e6813d 100644
--- a/frontend/src/components/chat/acp/__tests__/state.test.ts
+++ b/frontend/src/components/chat/acp/__tests__/state.test.ts
@@ -673,14 +673,14 @@ describe("state utility functions", () => {
it("should return correct command for claude on non-Windows", () => {
vi.spyOn(shortcuts, "isPlatformWindows").mockReturnValue(false);
expect(getAgentConnectionCommand("claude")).toMatchInlineSnapshot(`
- "npx stdio-to-ws "npx @zed-industries/claude-code-acp" --port 3017"
+ "npx stdio-to-ws "npx @agentclientprotocol/claude-agent-acp" --port 3017"
`);
});
it("should return correct command for claude on Windows", () => {
vi.spyOn(shortcuts, "isPlatformWindows").mockReturnValue(true);
expect(getAgentConnectionCommand("claude")).toMatchInlineSnapshot(`
- "npx stdio-to-ws "cmd /c npx @zed-industries/claude-code-acp" --port 3017"
+ "npx stdio-to-ws "cmd /c npx @agentclientprotocol/claude-agent-acp" --port 3017"
`);
});
diff --git a/frontend/src/components/chat/acp/agent-panel.tsx b/frontend/src/components/chat/acp/agent-panel.tsx
index 777af88e05..3d672f5d10 100644
--- a/frontend/src/components/chat/acp/agent-panel.tsx
+++ b/frontend/src/components/chat/acp/agent-panel.tsx
@@ -718,13 +718,28 @@ const AgentPanel: React.FC = () => {
clearNotifications,
} = acpClient;
+ const isConnected = connectionState.status === "connected";
+ const [initializedConnection, setInitializedConnection] = useState<{
+ agent: NonNullable<typeof agent>;
+ wsUrl: string;
+ } | null>(null);
+ const isAgentReady =
+ isConnected &&
+ agent !== null &&
+ initializedConnection?.agent === agent &&
+ initializedConnection.wsUrl === wsUrl;
+
useEffect(() => {
- if (!agent) {
+ setInitializedConnection(null);
+ setActiveSessionId(null);
+ if (!agent || !isConnected) {
return;
}
+ let cancelled = false;
+ setError(null);
- const initAndAuth = async () => {
- const response = await agent.initialize({
+ const initialize = async () => {
+ await agent.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: {
@@ -734,23 +749,26 @@ const AgentPanel: React.FC = () => {
},
});
- // We try to authenticate with the agent if it supports it.
- // The user must then restart the session
- const authMethods = response?.authMethods;
- if (authMethods && authMethods.length > 0) {
- await agent.authenticate({ methodId: authMethods[0].id });
+ // Agents use credentials from their CLI login. Advertised auth methods
+ // describe login options, not whether authentication is required.
+ if (!cancelled) {
+ setInitializedConnection({ agent, wsUrl });
}
};
- initAndAuth().catch((error) => {
- logger.error("Failed to initialize/authenticate agent", { error });
+ initialize().catch((error) => {
+ if (!cancelled) {
+ logger.error("Failed to initialize agent", { error });
+ setError(error instanceof Error ? error : String(error));
+ }
});
- }, [agent]);
+ return () => {
+ cancelled = true;
+ };
+ }, [agent, isConnected, wsUrl, setActiveSessionId]);
// Auto-connect to agent when we have an active session, but only once per session
useEffect(() => {
- setActiveSessionId(null);
-
if (wsUrl === NO_WS_SET) {
return;
}
@@ -770,7 +788,7 @@ const AgentPanel: React.FC = () => {
}, [wsUrl]);
const handleNewSession = useEvent(async () => {
- if (!agent) {
+ if (!agent || !isAgentReady) {
return;
}
@@ -814,7 +832,7 @@ const AgentPanel: React.FC = () => {
const handleResumeSession = useEvent(
async (previousSessionId: ExternalAgentSessionId) => {
- if (!agent) {
+ if (!agent || !isAgentReady) {
return;
}
logger.debug("Resuming agent session", {
@@ -825,6 +843,8 @@ const AgentPanel: React.FC = () => {
}
creatingOrResumingSession.current = true;
try {
+ // Loading replays the agent's history through session notifications.
+ clearNotifications(previousSessionId);
const loadedSession = await agent.loadSession({
sessionId: previousSessionId,
cwd: getCwd(),
@@ -848,12 +868,19 @@ const AgentPanel: React.FC = () => {
},
);
- // Create or resume a session when successfully connected
- const isConnected = connectionState.status === "connected";
+ const handleRestartSession = useEvent(async () => {
+ setError(null);
+ try {
+ await handleNewSession();
+ } catch (error) {
+ setError(error instanceof Error ? error : String(error));
+ }
+ });
+
+ // Create or resume a session once initialization finishes.
const tabLastActiveSessionId = selectedTab?.externalAgentSessionId;
useEffect(() => {
- // No need to do anything if we're not connected, don't have an agent, or don't have a selected tab
- if (!isConnected || !selectedTab || !agent) {
+ if (!isAgentReady || !selectedTab || !agent) {
return;
}
@@ -893,12 +920,12 @@ const AgentPanel: React.FC = () => {
createOrResumeSession();
// oxlint-disable-next-line react-hooks/exhaustive-deps
- }, [isConnected, agent, tabLastActiveSessionId, activeSessionId]);
+ }, [isAgentReady, agent, tabLastActiveSessionId, activeSessionId]);
// Handler for prompt submission
const handlePromptSubmit = useEvent(
async (_e: KeyboardEvent | undefined, prompt: string) => {
- if (!activeSessionId || !agent || isLoading) {
+ if (!activeSessionId || !agent || !isAgentReady || isLoading) {
return;
}
@@ -983,7 +1010,7 @@ const AgentPanel: React.FC = () => {
!activeSessionId ||
!agent ||
isLoading ||
- connectionState.status !== "connected" ||
+ !isAgentReady ||
!pendingPrompt
) {
return;
@@ -999,7 +1026,7 @@ const AgentPanel: React.FC = () => {
activeSessionId,
agent,
isLoading,
- connectionState.status,
+ isAgentReady,
pendingPrompt,
setPendingPrompt,
handlePromptSubmit,
@@ -1019,7 +1046,10 @@ const AgentPanel: React.FC = () => {
logger.debug("Manual connect requested", {
currentStatus: connectionState.status,
});
- connect();
+ setError(null);
+ void connect().catch((error) => {
+ setError(error instanceof Error ? error : String(error));
+ });
});
// Handler for manual disconnect
@@ -1112,14 +1142,22 @@ const AgentPanel: React.FC = () => {
className="w-3/4 mx-auto mt-10"
error={displayError}
action={
- isAuthError ? (
+ !isAgentReady ? (
<Button
variant="linkDestructive"
size="sm"
onClick={() => {
- setError(null);
- handleNewSession();
+ disconnect();
+ handleManualConnect();
}}
+ >
+ Retry connection
+ </Button>
+ ) : isAuthError ? (
+ <Button
+ variant="linkDestructive"
+ size="sm"
+ onClick={handleRestartSession}
>
Restart session
</Button>
@@ -1153,14 +1191,16 @@ const AgentPanel: React.FC = () => {
}
const isLoadingSession =
- tabLastActiveSessionId == null && connectionState.status === "connected";
+ isConnected && (!isAgentReady || tabLastActiveSessionId == null);
if (isLoadingSession) {
return (
<DelayMount milliseconds={delay}>
<div className="flex items-center justify-center h-full min-h-[200px] flex-col">
<Spinner size="medium" className="text-primary" />
<span className="text-sm text-muted-foreground">
- Creating a new session...
+ {isAgentReady
+ ? "Creating a new session..."
+ : "Initializing agent..."}
</span>
</div>
</DelayMount>
@@ -1232,7 +1272,7 @@ const AgentPanel: React.FC = () => {
currentAgentId={selectedTab?.agentId}
onConnect={handleManualConnect}
onDisconnect={handleManualDisconnect}
- onRestartThread={handleNewSession}
+ onRestartThread={isAgentReady ? handleRestartSession : undefined}
hasActiveSession={true}
shouldShowConnectionControl={wsUrl !== NO_WS_SET}
/>
diff --git a/frontend/src/components/chat/acp/state.ts b/frontend/src/components/chat/acp/state.ts
index 550ec42388..8b66cb4246 100644
--- a/frontend/src/components/chat/acp/state.ts
+++ b/frontend/src/components/chat/acp/state.ts
@@ -257,7 +257,7 @@ interface AgentConfig {
const AGENT_CONFIG: Record<ExternalAgentId, AgentConfig> = {
claude: {
port: 3017,
- command: "npx @zed-industries/claude-code-acp",
+ command: "npx @agentclientprotocol/claude-agent-acp",
sessionSupport: "single",
},
gemini: {