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.

preview: agent sidebar (claude code and gemini cli) (#6331)

Myles Scolnick219510af2147
diff --git a/frontend/package.json b/frontend/package.json
index e62ec447d7..e5060e809a 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -102,6 +102,7 @@
"@xterm/addon-attach": "^0.11.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/xterm": "^5.5.0",
+ "@zed-industries/agent-client-protocol": "^0.1.2",
"ai": "^5.0.30",
"ansi_up": "^6.0.6",
"class-variance-authority": "^0.7.1",
@@ -150,6 +151,7 @@
"remark-gfm": "^4.0.1",
"rpc-anywhere": "^1.7.0",
"sql-formatter": "^15.6.6",
+ "streamdown": "^1.2.0",
"string-dedent": "^3.0.2",
"swiper": "^11.2.10",
"tailwind-merge": "^2.6.0",
@@ -157,6 +159,7 @@
"thememirror": "^2.0.1",
"timestring": "^7.0.0",
"typescript-memoize": "^1.1.1",
+ "use-acp": "^0.1.5",
"use-resize-observer": "^9.1.0",
"vega-lite": "^5.23.0",
"vega-loader": "^4.5.3",
diff --git a/frontend/src/components/ai/ai-provider-icon.tsx b/frontend/src/components/ai/ai-provider-icon.tsx
index 23d58084eb..83d3960d8a 100644
--- a/frontend/src/components/ai/ai-provider-icon.tsx
+++ b/frontend/src/components/ai/ai-provider-icon.tsx
@@ -14,9 +14,13 @@ import type { ProviderId } from "@/core/ai/ids/ids";
import { cn } from "@/utils/cn";
import marimoIcon from "../../assets/icon-32x32.png?inline";
-const icons: Record<ProviderId, string> = {
+type Aliases = "claude" | "gemini";
+
+const icons: Record<ProviderId | Aliases, string> = {
openai: OpenAIIcon,
anthropic: AnthropicIcon,
+ claude: AnthropicIcon,
+ gemini: GeminiIcon,
google: GeminiIcon,
ollama: OllamaIcon,
azure: AzureIcon,
diff --git a/frontend/src/components/chat/acp/__tests__/__snapshots__/prompt.test.ts.snap b/frontend/src/components/chat/acp/__tests__/__snapshots__/prompt.test.ts.snap
new file mode 100644
index 0000000000..46afd2e3ed
--- /dev/null
+++ b/frontend/src/components/chat/acp/__tests__/__snapshots__/prompt.test.ts.snap
@@ -0,0 +1,304 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`getAgentPrompt > should generate complete agent prompt with default filename 1`] = `
+"
+ I am currently editing a marimo notebook.
+ You can read or write to the notebook at @test-notebook.py
+
+ If you make edits to the notebook, only edit the contents inside the function decorator with @app.cell.
+ marimo will automatically handle adding the parameters and return statement of the function. For example,
+ for each edit, just return:
+
+ \`\`\`
+ @app.cell
+ def __():
+ <your code here>
+ return
+ \`\`\`
+
+ ## Marimo fundamentals
+
+ Marimo is a reactive notebook that differs from traditional notebooks in key ways:
+
+ - Cells execute automatically when their dependencies change
+ - Variables cannot be redeclared across cells
+ - The notebook forms a directed acyclic graph (DAG)
+ - The last expression in a cell is automatically displayed
+ - UI elements are reactive and update the notebook automatically
+
+ ## Code Requirements
+
+ 1. All code must be complete and runnable
+ 2. Follow consistent coding style throughout
+ 3. Include descriptive variable names and helpful comments
+ 4. Import all modules in the first cell, always including \`import marimo as mo\`
+ 5. Never redeclare variables across cells
+ 6. Ensure no cycles in notebook dependency graph
+ 7. The last expression in a cell is automatically displayed, just like in Jupyter notebooks.
+ 8. Don't include comments in markdown cells
+ 9. Don't include comments in SQL cells
+
+ ## Reactivity
+
+ Marimo's reactivity means:
+
+ - When a variable changes, all cells that use that variable automatically re-execute
+ - UI elements trigger updates when their values change without explicit callbacks
+ - UI element values are accessed through \`.value\` attribute
+ - You cannot access a UI element's value in the same cell where it's defined
+
+ ## Best Practices
+
+ <data_handling>
+ - Use pandas for data manipulation
+ - Implement proper data validation
+ - Handle missing values appropriately
+ - Use efficient data structures
+ - A variable in the last expression of a cell is automatically displayed as a table
+ </data_handling>
+
+ <visualization>
+ - For matplotlib: use plt.gca() as the last expression instead of plt.show()
+ - For plotly: return the figure object directly
+ - For altair: return the chart object directly
+ - Include proper labels, titles, and color schemes
+ - Make visualizations interactive where appropriate
+ </visualization>
+
+ <ui_elements>
+ - Access UI element values with .value attribute (e.g., slider.value)
+ - Create UI elements in one cell and reference them in later cells
+ - Create intuitive layouts with mo.hstack(), mo.vstack(), and mo.tabs()
+ - Prefer reactive updates over callbacks (marimo handles reactivity automatically)
+ - Group related UI elements for better organization
+ </ui_elements>
+
+ <sql>
+ - When writing duckdb, prefer using marimo's SQL cells, which start with _df = mo.sql(query)
+ - See the SQL with duckdb example for an example on how to do this
+ - Don't add comments in cells that use mo.sql()
+ - Consider using \`vega_datasets\` for common example datasets
+ </sql>
+
+ ## Troubleshooting
+
+ Common issues and solutions:
+ - Circular dependencies: Reorganize code to remove cycles in the dependency graph
+ - UI element value access: Move access to a separate cell from definition
+ - Visualization not showing: Ensure the visualization object is the last expression
+
+ ## Available UI elements
+
+ - \`mo.ui.altair_chart(altair_chart)\`
+ - \`mo.ui.button(value=None, kind='primary')\`
+ - \`mo.ui.run_button(label=None, tooltip=None, kind='primary')\`
+ - \`mo.ui.checkbox(label='', value=False)\`
+ - \`mo.ui.date(value=None, label=None, full_width=False)\`
+ - \`mo.ui.dropdown(options, value=None, label=None, full_width=False)\`
+ - \`mo.ui.file(label='', multiple=False, full_width=False)\`
+ - \`mo.ui.number(value=None, label=None, full_width=False)\`
+ - \`mo.ui.radio(options, value=None, label=None, full_width=False)\`
+ - \`mo.ui.refresh(options: List[str], default_interval: str)\`
+ - \`mo.ui.slider(start, stop, value=None, label=None, full_width=False, step=None)\`
+ - \`mo.ui.range_slider(start, stop, value=None, label=None, full_width=False, step=None)\`
+ - \`mo.ui.table(data, columns=None, on_select=None, sortable=True, filterable=True)\`
+ - \`mo.ui.text(value='', label=None, full_width=False)\`
+ - \`mo.ui.text_area(value='', label=None, full_width=False)\`
+ - \`mo.ui.data_explorer(df)\`
+ - \`mo.ui.dataframe(df)\`
+ - \`mo.ui.plotly(plotly_figure)\`
+ - \`mo.ui.tabs(elements: dict[str, mo.ui.Element])\`
+ - \`mo.ui.array(elements: list[mo.ui.Element])\`
+ - \`mo.ui.form(element: mo.ui.Element, label='', bordered=True)\`
+
+ ## Layout and utility functions
+
+ - \`mo.md(text)\` - display markdown
+ - \`mo.stop(predicate, output=None)\` - stop execution conditionally
+ - \`mo.Html(html)\` - display HTML
+ - \`mo.image(image)\` - display an image
+ - \`mo.hstack(elements)\` - stack elements horizontally
+ - \`mo.vstack(elements)\` - stack elements vertically
+ - \`mo.tabs(elements)\` - create a tabbed interface
+
+ ## Examples
+
+ <example title="Basic UI with reactivity">
+
+ @app.cell
+ def __():
+ import marimo as mo
+ import matplotlib.pyplot as plt
+ import numpy as np
+ return
+
+ @app.cell
+ def __():
+ n_points = mo.ui.slider(10, 100, value=50, label="Number of points")
+ n_points
+ return
+
+ @app.cell
+ def __():
+ x = np.random.rand(n_points.value)
+ y = np.random.rand(n_points.value)
+
+ plt.figure(figsize=(8, 6))
+ plt.scatter(x, y, alpha=0.7)
+ plt.title(f"Scatter plot with {n_points.value} points")
+ plt.xlabel("X axis")
+ plt.ylabel("Y axis")
+ plt.gca()
+ return
+
+ </example>
+
+ <example title="Data explorer">
+
+ @app.cell
+ def __():
+ import marimo as mo
+ import pandas as pd
+ from vega_datasets import data
+ return
+
+ @app.cell
+ def __():
+ cars_df = data.cars()
+ mo.ui.data_explorer(cars_df)
+ return
+
+ </example>
+
+ <example title="Multiple UI elements">
+
+ @app.cell
+ def __():
+ import marimo as mo
+ import pandas as pd
+ import matplotlib.pyplot as plt
+ import seaborn as sns
+ return
+
+ @app.cell
+ def __():
+ iris = sns.load_dataset('iris')
+ return
+
+ @app.cell
+ def __():
+ species_selector = mo.ui.dropdown(
+ options=["All"] + iris["species"].unique().tolist(),
+ value="All",
+ label="Species"
+ )
+ x_feature = mo.ui.dropdown(
+ options=iris.select_dtypes('number').columns.tolist(),
+ value="sepal_length",
+ label="X Feature"
+ )
+ y_feature = mo.ui.dropdown(
+ options=iris.select_dtypes('number').columns.tolist(),
+ value="sepal_width",
+ label="Y Feature"
+ )
+ mo.hstack([species_selector, x_feature, y_feature])
+ return
+
+ @app.cell
+ def __():
+ filtered_data = iris if species_selector.value == "All" else iris[iris["species"] == species_selector.value]
+
+ plt.figure(figsize=(10, 6))
+ sns.scatterplot(
+ data=filtered_data,
+ x=x_feature.value,
+ y=y_feature.value,
+ hue="species"
+ )
+ plt.title(f"{y_feature.value} vs {x_feature.value}")
+ plt.gca()
+ return
+
+ </example>
+
+ <example title="Interactive chart with Altair">
+
+ @app.cell
+ def __():
+ import marimo as mo
+ import altair as alt
+ import pandas as pd
+ return
+
+ @app.cell
+ def __():
+ # Load dataset
+ cars_df = pd.read_csv('<https://raw.githubusercontent.com/vega/vega-datasets/master/data/cars.json>')
+ _chart = alt.Chart(cars_df).mark_point().encode(
+ x='Horsepower',
+ y='Miles_per_Gallon',
+ color='Origin',
+ )
+ return
+
+ @app.cell
+ def __():
+ chart = mo.ui.altair_chart(_chart)
+ chart
+ return
+
+ @app.cell
+ def __():
+ # Display the selection
+ chart.value
+ return
+
+ </example>
+
+ <example title="Run Button Example">
+
+ @app.cell
+ def __():
+ import marimo as mo
+ return
+
+ @app.cell
+ def __():
+ first_button = mo.ui.run_button(label="Option 1")
+ second_button = mo.ui.run_button(label="Option 2")
+ [first_button, second_button]
+ return
+
+ @app.cell
+ def __():
+ if first_button.value:
+ print("You chose option 1!")
+ elif second_button.value:
+ print("You chose option 2!")
+ else:
+ print("Click a button!")
+ return
+
+ </example>
+
+ <example title="SQL with duckdb">
+
+ @app.cell
+ def __():
+ import marimo as mo
+ import pandas as pd
+ return
+
+ @app.cell
+ def __():
+ cars_df = pd.read_csv('<https://raw.githubusercontent.com/vega/vega-datasets/master/data/cars.json>')
+ return
+
+ @app.cell
+ def __():
+ _df = mo.sql("SELECT * from cars_df WHERE Miles_per_Gallon > 20")
+ return
+
+ </example>"
+`;
diff --git a/frontend/src/components/chat/acp/__tests__/atoms.test.ts b/frontend/src/components/chat/acp/__tests__/atoms.test.ts
new file mode 100644
index 0000000000..950dbeef1b
--- /dev/null
+++ b/frontend/src/components/chat/acp/__tests__/atoms.test.ts
@@ -0,0 +1,56 @@
+/* Copyright 2025 Marimo. All rights reserved. */
+
+import { createStore } from "jotai";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { addSession, agentSessionStateAtom, selectedTabAtom } from "../state";
+
+describe("Jotai atoms", () => {
+ let store: ReturnType<typeof createStore>;
+
+ beforeEach(() => {
+ store = createStore();
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2025-01-01T00:00:00Z"));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ describe("agentSessionStateAtom", () => {
+ it("should have initial empty state", () => {
+ const state = store.get(agentSessionStateAtom);
+ expect(state).toEqual({
+ sessions: [],
+ activeTabId: null,
+ });
+ });
+ });
+
+ describe("activeSessionAtom", () => {
+ it("should return null when no active session", () => {
+ const activeSession = store.get(selectedTabAtom);
+ expect(activeSession).toBe(null);
+ });
+
+ it("should return active session when available", () => {
+ const state = addSession(
+ {
+ sessions: [],
+ activeTabId: null,
+ },
+ { agentId: "gemini" },
+ );
+
+ store.set(agentSessionStateAtom, state);
+ const activeSession = store.get(selectedTabAtom);
+
+ expect(activeSession).toEqual(
+ expect.objectContaining({
+ agentId: "gemini",
+ title: "New gemini session",
+ }),
+ );
+ });
+ });
+});
diff --git a/frontend/src/components/chat/acp/__tests__/prompt.test.ts b/frontend/src/components/chat/acp/__tests__/prompt.test.ts
new file mode 100644
index 0000000000..c7174df280
--- /dev/null
+++ b/frontend/src/components/chat/acp/__tests__/prompt.test.ts
@@ -0,0 +1,12 @@
+/* Copyright 2025 Marimo. All rights reserved. */
+
+import { describe, expect, it } from "vitest";
+import { getAgentPrompt } from "../prompt";
+
+describe("getAgentPrompt", () => {
+ it("should generate complete agent prompt with default filename", () => {
+ const result = getAgentPrompt("test-notebook.py");
+
+ expect(result).toMatchSnapshot();
+ });
+});
diff --git a/frontend/src/components/chat/acp/__tests__/state.test.ts b/frontend/src/components/chat/acp/__tests__/state.test.ts
new file mode 100644
index 0000000000..03bfb16cdb
--- /dev/null
+++ b/frontend/src/components/chat/acp/__tests__/state.test.ts
@@ -0,0 +1,621 @@
+/* Copyright 2025 Marimo. All rights reserved. */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ type AgentSession,
+ type AgentSessionState,
+ addSession,
+ type ExternalAgentId,
+ getAgentConnectionCommand,
+ getAgentDisplayName,
+ getAllAgentIds,
+ getSessionsByAgent,
+ removeSession,
+ type TabId,
+ truncateTitle,
+ updateSessionExternalAgentSessionId,
+ updateSessionLastUsed,
+ updateSessionTitle,
+} from "../state";
+import type { ExternalAgentSessionId } from "../types";
+
+describe("state utility functions", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Mock Date.now for consistent testing
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2025-01-01T00:00:00Z"));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ describe("truncateTitle", () => {
+ it("should not truncate short titles", () => {
+ expect(truncateTitle("Hello")).toBe("Hello");
+ expect(truncateTitle("Test message")).toBe("Test message");
+ });
+
+ it("should truncate long titles to default 20 characters", () => {
+ const longTitle = "This is a very long title that should be truncated";
+ const result = truncateTitle(longTitle);
+ expect(result).toBe("This is a very lo...");
+ expect(result.length).toBe(20);
+ });
+
+ it("should truncate to custom max length", () => {
+ const longTitle = "This is a long title";
+ const result = truncateTitle(longTitle, 10);
+ expect(result).toBe("This is...");
+ expect(result.length).toBe(10);
+ });
+
+ it("should handle empty strings", () => {
+ expect(truncateTitle("")).toBe("");
+ });
+
+ it("should handle titles exactly at max length", () => {
+ const exactTitle = "Exactly twenty chars";
+ expect(exactTitle.length).toBe(20);
+ expect(truncateTitle(exactTitle)).toBe(exactTitle);
+ });
+ });
+
+ describe("addSession", () => {
+ it("should add session to empty state", () => {
+ const initialState: AgentSessionState = {
+ sessions: [],
+ activeTabId: null,
+ };
+
+ const session = { agentId: "claude" as ExternalAgentId };
+ const newState = addSession(initialState, session);
+
+ // Remove the dynamic tabId for snapshot comparison
+ const { tabId, ...sessionWithoutId } = newState.sessions[0];
+ expect({
+ ...newState,
+ sessions: [sessionWithoutId],
+ activeTabId: "[DYNAMIC_TAB_ID]",
+ }).toMatchInlineSnapshot(`
+ {
+ "activeTabId": "[DYNAMIC_TAB_ID]",
+ "sessions": [
+ {
+ "agentId": "claude",
+ "createdAt": 1735689600000,
+ "externalAgentSessionId": null,
+ "lastUsedAt": 1735689600000,
+ "title": "New claude session",
+ },
+ ],
+ }
+ `);
+ expect(newState.activeTabId).toBe(newState.sessions[0].tabId);
+ });
+
+ it("should add session when no existing session for different agent", () => {
+ const existingSession: AgentSession = {
+ agentId: "gemini",
+ tabId: "tab_existing" as TabId,
+ title: "Existing gemini session",
+ createdAt: 1735689600000,
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ };
+ const initialState: AgentSessionState = {
+ sessions: [existingSession],
+ activeTabId: existingSession.tabId,
+ };
+
+ const newSession = { agentId: "claude" as ExternalAgentId };
+ const newState = addSession(initialState, newSession);
+
+ // Remove dynamic tabId for snapshot
+ const { tabId, ...sessionWithoutId } = newState.sessions[0];
+ expect({
+ ...newState,
+ sessions: [sessionWithoutId],
+ activeTabId: "[DYNAMIC_TAB_ID]",
+ }).toMatchInlineSnapshot(`
+ {
+ "activeTabId": "[DYNAMIC_TAB_ID]",
+ "sessions": [
+ {
+ "agentId": "claude",
+ "createdAt": 1735689600000,
+ "externalAgentSessionId": null,
+ "lastUsedAt": 1735689600000,
+ "title": "New claude session",
+ },
+ ],
+ }
+ `);
+ });
+
+ it("should replace existing session for same agent (single session support)", () => {
+ const existingSession: AgentSession = {
+ agentId: "claude",
+ tabId: "tab_existing" as TabId,
+ title: "Existing claude session",
+ createdAt: 1735689600000,
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ };
+ const initialState: AgentSessionState = {
+ sessions: [existingSession],
+ activeTabId: existingSession.tabId,
+ };
+
+ const newSession = {
+ agentId: "claude" as ExternalAgentId,
+ firstMessage: "Hello",
+ };
+ const newState = addSession(initialState, newSession);
+
+ expect(newState).toMatchInlineSnapshot(`
+ {
+ "activeTabId": "tab_existing",
+ "sessions": [
+ {
+ "agentId": "claude",
+ "createdAt": 1735689600000,
+ "externalAgentSessionId": null,
+ "lastUsedAt": 1735689600000,
+ "tabId": "tab_existing",
+ "title": "Hello",
+ },
+ ],
+ }
+ `);
+ });
+
+ it("should not mutate original state", () => {
+ const initialState: AgentSessionState = {
+ sessions: [],
+ activeTabId: null,
+ };
+
+ const newState = addSession(initialState, { agentId: "claude" });
+
+ expect(initialState.sessions).toHaveLength(0);
+ expect(newState.sessions).toHaveLength(1);
+ });
+ });
+
+ describe("removeSession", () => {
+ let sessions: AgentSession[];
+ let state: AgentSessionState;
+
+ beforeEach(() => {
+ sessions = [
+ {
+ agentId: "claude",
+ tabId: "tab_1" as TabId,
+ title: "Claude session 1",
+ createdAt: 1735689600000,
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ },
+ {
+ agentId: "gemini",
+ tabId: "tab_2" as TabId,
+ title: "Gemini session",
+ createdAt: 1735689600000,
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ },
+ {
+ agentId: "claude",
+ tabId: "tab_3" as TabId,
+ title: "Claude session 2",
+ createdAt: 1735689600000,
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ },
+ ];
+ state = {
+ sessions,
+ activeTabId: sessions[1].tabId, // middle session is active
+ };
+ });
+
+ it("should remove specified session", () => {
+ const newState = removeSession(state, sessions[1].tabId);
+
+ expect(newState).toMatchInlineSnapshot(`
+ {
+ "activeTabId": "tab_3",
+ "sessions": [
+ {
+ "agentId": "claude",
+ "createdAt": 1735689600000,
+ "externalAgentSessionId": null,
+ "lastUsedAt": 1735689600000,
+ "tabId": "tab_1",
+ "title": "Claude session 1",
+ },
+ {
+ "agentId": "claude",
+ "createdAt": 1735689600000,
+ "externalAgentSessionId": null,
+ "lastUsedAt": 1735689600000,
+ "tabId": "tab_3",
+ "title": "Claude session 2",
+ },
+ ],
+ }
+ `);
+ });
+
+ it("should keep active session if not the one being removed", () => {
+ const newState = removeSession(state, sessions[1].tabId);
+ expect(newState.activeTabId).toMatchInlineSnapshot(`"tab_3"`);
+ });
+
+ it("should set active session to last session when removing active session", () => {
+ const newState = removeSession(state, sessions[1].tabId);
+ expect(newState.activeTabId).toMatchInlineSnapshot(`"tab_3"`);
+ });
+
+ it("should set active session to null when removing last session", () => {
+ const singleSession: AgentSession = {
+ agentId: "claude",
+ tabId: "tab_single" as TabId,
+ title: "Single session",
+ createdAt: 1735689600000,
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ };
+ const singleSessionState: AgentSessionState = {
+ sessions: [singleSession],
+ activeTabId: singleSession.tabId,
+ };
+
+ const newState = removeSession(singleSessionState, singleSession.tabId);
+ expect(newState.sessions).toHaveLength(0);
+ expect(newState.activeTabId).toBe(null);
+ });
+
+ it("should handle removing non-existent session", () => {
+ const fakeId = "fake_session_id" as TabId;
+ const newState = removeSession(state, fakeId);
+
+ expect(newState.sessions).toHaveLength(3);
+ expect(newState.activeTabId).toBe(sessions[1].tabId);
+ });
+ });
+
+ describe("updateSessionTitle", () => {
+ let sessions: AgentSession[];
+ let state: AgentSessionState;
+
+ beforeEach(() => {
+ sessions = [
+ {
+ agentId: "claude",
+ tabId: "tab_1" as TabId,
+ title: "Original title",
+ createdAt: 1735689600000,
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ },
+ {
+ agentId: "gemini",
+ tabId: "tab_2" as TabId,
+ title: "Another title",
+ createdAt: 1735689600000,
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ },
+ ];
+ state = {
+ sessions,
+ activeTabId: sessions[0].tabId,
+ };
+ });
+
+ it("should update title of specified session", () => {
+ const newTitle = "Updated title for session";
+ const newState = updateSessionTitle(state, newTitle);
+
+ expect(newState.sessions.map((s) => s.title)).toMatchInlineSnapshot(`
+ [
+ "Updated title for...",
+ "Another title",
+ ]
+ `);
+ });
+
+ it("should truncate long titles", () => {
+ const longTitle = "This is a very long title that needs to be truncated";
+ const newState = updateSessionTitle(state, longTitle);
+
+ expect({
+ title: newState.sessions[0].title,
+ length: newState.sessions[0].title.length,
+ }).toMatchInlineSnapshot(`
+ {
+ "length": 20,
+ "title": "This is a very lo...",
+ }
+ `);
+ });
+
+ it("should not mutate original state", () => {
+ const originalTitle = sessions[0].title;
+ updateSessionTitle(state, "New title");
+
+ expect(sessions[0].title).toBe(originalTitle);
+ });
+ });
+
+ describe("updateSessionLastUsed", () => {
+ let sessions: AgentSession[];
+ let state: AgentSessionState;
+
+ beforeEach(() => {
+ sessions = [
+ {
+ agentId: "claude",
+ tabId: "tab_1" as TabId,
+ title: "Claude session",
+ createdAt: 1735689600000,
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ },
+ {
+ agentId: "gemini",
+ tabId: "tab_2" as TabId,
+ title: "Gemini session",
+ createdAt: 1735689600000,
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ },
+ ];
+ state = {
+ sessions,
+ activeTabId: sessions[0].tabId,
+ };
+ });
+
+ it("should update lastUsedAt timestamp", () => {
+ const originalTimestamp = sessions[0].lastUsedAt;
+
+ // Advance time by 1 hour
+ vi.advanceTimersByTime(3600000);
+
+ const newState = updateSessionLastUsed(state, sessions[0].tabId);
+
+ expect({
+ updatedTimestamp: newState.sessions[0].lastUsedAt,
+ unchangedTimestamp: newState.sessions[1].lastUsedAt,
+ timestampChanged: newState.sessions[0].lastUsedAt !== originalTimestamp,
+ }).toMatchInlineSnapshot(`
+ {
+ "timestampChanged": true,
+ "unchangedTimestamp": 1735689600000,
+ "updatedTimestamp": 1735693200000,
+ }
+ `);
+ });
+
+ it("should handle non-existent session ID", () => {
+ const fakeId = "fake_session_id" as TabId;
+ const originalTimestamp = sessions[0].lastUsedAt;
+
+ vi.advanceTimersByTime(3600000);
+
+ const newState = updateSessionLastUsed(state, fakeId);
+
+ expect(newState.sessions[0].lastUsedAt).toBe(originalTimestamp);
+ expect(newState.sessions[1].lastUsedAt).toBe(originalTimestamp);
+ });
+ });
+
+ describe("updateSessionExternalAgentSessionId", () => {
+ let sessions: AgentSession[];
+ let state: AgentSessionState;
+
+ beforeEach(() => {
+ sessions = [
+ {
+ agentId: "claude",
+ tabId: "tab_1" as TabId,
+ title: "Claude session",
+ createdAt: 1735689600000,
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ },
+ {
+ agentId: "gemini",
+ tabId: "tab_2" as TabId,
+ title: "Gemini session",
+ createdAt: 1735689600000,
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ },
+ ];
+ state = {
+ sessions,
+ activeTabId: sessions[0].tabId,
+ };
+ });
+
+ it("should update externalAgentSessionId and lastUsedAt", () => {
+ const originalTimestamp = sessions[0].lastUsedAt;
+ const agentSessionId = "agent_session_123" as ExternalAgentSessionId;
+
+ // Advance time by 1 hour
+ vi.advanceTimersByTime(3600000);
+
+ const newState = updateSessionExternalAgentSessionId(
+ state,
+ agentSessionId,
+ );
+
+ expect({
+ updatedSession: {
+ externalAgentSessionId: newState.sessions[0].externalAgentSessionId,
+ lastUsedAt: newState.sessions[0].lastUsedAt,
+ },
+ unchangedSession: {
+ externalAgentSessionId: newState.sessions[1].externalAgentSessionId,
+ },
+ timestampChanged: newState.sessions[0].lastUsedAt !== originalTimestamp,
+ }).toMatchInlineSnapshot(`
+ {
+ "timestampChanged": true,
+ "unchangedSession": {
+ "externalAgentSessionId": null,
+ },
+ "updatedSession": {
+ "externalAgentSessionId": "agent_session_123",
+ "lastUsedAt": 1735693200000,
+ },
+ }
+ `);
+ });
+
+ it("should not mutate original state", () => {
+ const originalSession = sessions[0];
+ const agentSessionId = "agent_session_123" as ExternalAgentSessionId;
+
+ updateSessionExternalAgentSessionId(state, agentSessionId);
+
+ expect(originalSession.externalAgentSessionId).toBe(null);
+ });
+ });
+
+ describe("getSessionsByAgent", () => {
+ let sessions: AgentSession[];
+
+ beforeEach(() => {
+ // Create sessions with different timestamps for sorting test
+ sessions = [
+ {
+ agentId: "claude",
+ tabId: "tab_1" as TabId,
+ title: "First claude",
+ createdAt: 1735689600000, // 2025-01-01T00:00:00Z
+ lastUsedAt: 1735689600000,
+ externalAgentSessionId: null,
+ },
+ {
+ agentId: "gemini",
+ tabId: "tab_2" as TabId,
+ title: "First gemini",
+ createdAt: 1735693200000, // 2025-01-01T01:00:00Z
+ lastUsedAt: 1735693200000,
+ externalAgentSessionId: null,
+ },
+ {
+ agentId: "claude",
+ tabId: "tab_3" as TabId,
+ title: "Second claude",
+ createdAt: 1735696800000, // 2025-01-01T02:00:00Z
+ lastUsedAt: 1735696800000,
+ externalAgentSessionId: null,
+ },
+ {
+ agentId: "claude",
+ tabId: "tab_4" as TabId,
+ title: "Third claude",
+ createdAt: 1735700400000, // 2025-01-01T03:00:00Z
+ lastUsedAt: 1735700400000,
+ externalAgentSessionId: null,
+ },
+ ];
+ });
+
+ it("should filter sessions by agent", () => {
+ const claudeSessions = getSessionsByAgent(sessions, "claude");
+
+ expect({
+ length: claudeSessions.length,
+ allClaude: claudeSessions.every((s) => s.agentId === "claude"),
+ agentIds: claudeSessions.map((s) => s.agentId),
+ }).toMatchInlineSnapshot(`
+ {
+ "agentIds": [
+ "claude",
+ "claude",
+ "claude",
+ ],
+ "allClaude": true,
+ "length": 3,
+ }
+ `);
+ });
+
+ it("should sort sessions by lastUsedAt in descending order", () => {
+ const claudeSessions = getSessionsByAgent(sessions, "claude");
+
+ expect(claudeSessions.map((s) => s.title)).toMatchInlineSnapshot(`
+ [
+ "Third claude",
+ "Second claude",
+ "First claude",
+ ]
+ `);
+ });
+
+ it("should return empty array for non-existent agent", () => {
+ const nonExistentSessions = getSessionsByAgent(
+ sessions,
+ "nonexistent" as ExternalAgentId,
+ );
+ expect(nonExistentSessions).toMatchInlineSnapshot("[]");
+ });
+
+ it("should return empty array for empty sessions list", () => {
+ const result = getSessionsByAgent([], "claude");
+ expect(result).toMatchInlineSnapshot("[]");
+ });
+ });
+
+ describe("getAllAgentIds", () => {
+ it("should return all available agent IDs", () => {
+ const agentIds = getAllAgentIds();
+ expect(agentIds).toMatchInlineSnapshot(`
+ [
+ "claude",
+ "gemini",
+ ]
+ `);
+ });
+ });
+
+ describe("getAgentDisplayName", () => {
+ it("should capitalize agent names", () => {
+ expect({
+ claude: getAgentDisplayName("claude"),
+ gemini: getAgentDisplayName("gemini"),
+ }).toMatchInlineSnapshot(`
+ {
+ "claude": "Claude",
+ "gemini": "Gemini",
+ }
+ `);
+ });
+ });
+
+ describe("getAgentConnectionCommand", () => {
+ it("should return correct command for claude", () => {
+ expect(getAgentConnectionCommand("claude")).toMatchInlineSnapshot(`
+ "npx supergateway --stdio\\
+ "npx @zed-industries/claude-code-acp" \\
+ --outputTransport ws --port 3017 "
+ `);
+ });
+
+ it("should return correct command for gemini", () => {
+ expect(getAgentConnectionCommand("gemini")).toMatchInlineSnapshot(`
+ "npx supergateway --stdio\\
+ "npx @google/gemini-cli --experimental-acp" \\
+ --outputTransport ws --port 3019 "
+ `);
+ });
+ });
+});
diff --git a/frontend/src/components/chat/acp/agent-docs.tsx b/frontend/src/components/chat/acp/agent-docs.tsx
new file mode 100644
index 0000000000..35cf75619c
--- /dev/null
+++ b/frontend/src/components/chat/acp/agent-docs.tsx
@@ -0,0 +1,78 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { TerminalIcon } from "lucide-react";
+import { memo } from "react";
+import { AiProviderIcon } from "@/components/ai/ai-provider-icon";
+import { CopyClipboardIcon } from "@/components/icons/copy-icon";
+import { cn } from "@/utils/cn";
+import {
+ type ExternalAgentId,
+ getAgentConnectionCommand,
+ getAgentDisplayName,
+ getAllAgentIds,
+} from "./state";
+
+interface AgentDocItemProps {
+ agentId: ExternalAgentId;
+ showCopy?: boolean;
+ className?: string;
+}
+
+const AgentDocItem = memo<AgentDocItemProps>(
+ ({ agentId, showCopy = true, className }) => {
+ const command = getAgentConnectionCommand(agentId);
+ const displayName = getAgentDisplayName(agentId);
+
+ return (
+ <div className={cn("space-y-2", className)}>
+ <div className="flex items-center gap-2">
+ <AiProviderIcon provider={agentId} className="h-4 w-4" />
+ <span className="font-medium text-sm">{displayName}</span>
+ </div>
+ <div className="bg-muted/50 rounded-md p-2 border">
+ <div className="flex items-start gap-2 text-xs">
+ <TerminalIcon className="h-4 w-4 mt-0.5 text-muted-foreground flex-shrink-0" />
+ <code className="text-xs font-mono break-all flex-1 whitespace-pre-wrap">
+ {command}
+ </code>
+ {showCopy && (
+ <CopyClipboardIcon value={command} className="h-3 w-3" />
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ },
+);
+AgentDocItem.displayName = "AgentDocItem";
+
+interface AgentDocsProps {
+ title?: string;
+ description?: string;
+ agents?: ExternalAgentId[];
+ showCopy?: boolean;
+ className?: string;
+}
+
+export const AgentDocs = memo<AgentDocsProps>(
+ ({
+ title,
+ description,
+ agents = getAllAgentIds(),
+ showCopy = true,
+ className,
+ }) => (
+ <div className={cn("space-y-4", className)}>
+ <div className="space-y-2">
+ <h3 className="font-medium text-sm">{title}</h3>
+ <p className="text-xs text-muted-foreground">{description}</p>
+ </div>
+ <div className="space-y-3">
+ {agents.map((agentId) => (
+ <AgentDocItem key={agentId} agentId={agentId} showCopy={showCopy} />
+ ))}
+ </div>
+ </div>
+ ),
+);
+AgentDocs.displayName = "AgentDocs";
diff --git a/frontend/src/components/chat/acp/agent-panel.css b/frontend/src/components/chat/acp/agent-panel.css
new file mode 100644
index 0000000000..803f0d2fb6
--- /dev/null
+++ b/frontend/src/components/chat/acp/agent-panel.css
@@ -0,0 +1,23 @@
+@source "../node_modules/streamdown/dist/index.js";
+
+.mo-agent-panel {
+ /* Make headers a bit smaller */
+ --text-2xl: 1rem;
+ --text-3xl: 1rem;
+
+ pre {
+ width: 100%;
+ }
+
+ [data-code-block-container="true"] {
+ margin-top: 0 !important;
+ }
+
+ [data-code-block-header="true"] {
+ padding: 4px !important;
+ }
+
+ code {
+ font-size: inherit !important;
+ }
+}
diff --git a/frontend/src/components/chat/acp/agent-panel.tsx b/frontend/src/components/chat/acp/agent-panel.tsx
new file mode 100644
index 0000000000..4a804a9952
--- /dev/null
+++ b/frontend/src/components/chat/acp/agent-panel.tsx
@@ -0,0 +1,715 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { useAtom } from "jotai";
+import { capitalize } from "lodash-es";
+import {
+ BotMessageSquareIcon,
+ RefreshCwIcon,
+ StopCircleIcon,
+} from "lucide-react";
+import React, { memo, useEffect, useRef, useState } from "react";
+import useEvent from "react-use-event-hook";
+import { useAcpClient } from "use-acp";
+import {
+ ConnectionStatus,
+ PermissionRequest,
+} from "@/components/chat/acp/common";
+import { PromptInput } from "@/components/editor/ai/add-cell-with-ai";
+import { PanelEmptyState } from "@/components/editor/chrome/panels/empty-state";
+import { Spinner } from "@/components/icons/spinner";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/utils/cn";
+import { Logger } from "@/utils/Logger";
+import { AgentDocs } from "./agent-docs";
+import { AgentSelector } from "./agent-selector";
+import ScrollToBottomButton from "./scroll-to-bottom-button";
+import { SessionTabs } from "./session-tabs";
+import {
+ agentSessionStateAtom,
+ type ExternalAgentId,
+ getAgentWebSocketUrl,
+ selectedTabAtom,
+ updateSessionExternalAgentSessionId,
+ updateSessionTitle,
+} from "./state";
+import { AgentThread } from "./thread";
+import "./agent-panel.css";
+import type {
+ ReadTextFileResponse,
+ RequestPermissionResponse,
+ WriteTextFileResponse,
+} from "@zed-industries/agent-client-protocol";
+import { toast } from "@/components/ui/use-toast";
+import { useRequestClient } from "@/core/network/requests";
+import { filenameAtom } from "@/core/saving/file-state";
+import { store } from "@/core/state/jotai";
+import { Functions } from "@/utils/functions";
+import { Paths } from "@/utils/paths";
+import { getAgentPrompt } from "./prompt";
+import type {
+ AgentConnectionState,
+ AgentPendingPermission,
+ ExternalAgentSessionId,
+ NotificationEvent,
+} from "./types";
+
+const logger = Logger.get("agents");
+
+interface AgentTitleProps {
+ currentAgentId?: ExternalAgentId;
+}
+
+const AgentTitle = memo<AgentTitleProps>(({ currentAgentId }) => (
+ <span className="text-sm font-medium">
+ {currentAgentId ? capitalize(currentAgentId) : "Agents"}
+ </span>
+));
+AgentTitle.displayName = "AgentTitle";
+
+interface ConnectionControlProps {
+ connectionState: AgentConnectionState;
+ onConnect: () => void;
+ onDisconnect: () => void;
+}
+
+const ConnectionControl = memo<ConnectionControlProps>(
+ ({ connectionState, onConnect, onDisconnect }) => {
+ const isConnected = connectionState.status === "connected";
+
+ return (
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={isConnected ? onDisconnect : onConnect}
+ disabled={connectionState.status === "connecting"}
+ >
+ {isConnected ? "Disconnect" : "Connect"}
+ </Button>
+ );
+ },
+);
+ConnectionControl.displayName = "ConnectionControl";
+
+interface HeaderInfoProps {
+ currentAgentId?: ExternalAgentId;
+ connectionStatus: string;
+ shouldShowConnectionControl?: boolean;
+}
+
+const HeaderInfo = memo<HeaderInfoProps>(
+ ({ currentAgentId, connectionStatus, shouldShowConnectionControl }) => (
+ <div className="flex items-center gap-2">
+ <BotMessageSquareIcon className="h-4 w-4 text-muted-foreground" />
+ <AgentTitle currentAgentId={currentAgentId} />
+ {shouldShowConnectionControl && (
+ <ConnectionStatus status={connectionStatus} />
+ )}
+ </div>
+ ),
+);
+HeaderInfo.displayName = "HeaderInfo";
+
+interface AgentPanelHeaderProps {
+ connectionState: AgentConnectionState;
+ currentAgentId?: ExternalAgentId;
+ onConnect: () => void;
+ onDisconnect: () => void;
+ onRestartThread?: () => void;
+ hasActiveSession?: boolean;
+ shouldShowConnectionControl?: boolean;
+}
+
+const AgentPanelHeader = memo<AgentPanelHeaderProps>(
+ ({
+ connectionState,
+ currentAgentId,
+ onConnect,
+ onDisconnect,
+ onRestartThread,
+ hasActiveSession,
+ shouldShowConnectionControl,
+ }) => (
+ <div className="flex border-b px-3 py-2 justify-between shrink-0 items-center">
+ <HeaderInfo
+ currentAgentId={currentAgentId}
+ connectionStatus={connectionState.status}
+ shouldShowConnectionControl={shouldShowConnectionControl}
+ />
+ <div className="flex items-center gap-2">
+ {hasActiveSession &&
+ connectionState.status === "connected" &&
+ onRestartThread && (
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={onRestartThread}
+ title="Restart thread (create new session)"
+ >
+ <RefreshCwIcon className="h-3 w-3 mr-1" />
+ Restart
+ </Button>
+ )}
+
+ {shouldShowConnectionControl && (
+ <ConnectionControl
+ connectionState={connectionState}
+ onConnect={onConnect}
+ onDisconnect={onDisconnect}
+ />
+ )}
+ </div>
+ </div>
+ ),
+);
+AgentPanelHeader.displayName = "AgentPanelHeader";
+
+interface EmptyStateProps {
+ currentAgentId?: ExternalAgentId;
+ connectionState: AgentConnectionState;
+ onConnect: () => void;
+ onDisconnect: () => void;
+}
+
+const EmptyState = memo<EmptyStateProps>(
+ ({ currentAgentId, connectionState, onConnect, onDisconnect }) => (
+ <div className="flex flex-col h-full">
+ <AgentPanelHeader
+ connectionState={connectionState}
+ currentAgentId={currentAgentId}
+ onConnect={onConnect}
+ onDisconnect={onDisconnect}
+ hasActiveSession={false}
+ />
+ <SessionTabs />
+ <div className="flex-1 flex items-center justify-center p-6">
+ <div className="max-w-md w-full space-y-6">
+ <PanelEmptyState
+ title="No Agent Sessions"
+ description="Create a new session to start a conversation"
+ action={<AgentSelector className="border-y-1 rounded" />}
+ icon={<BotMessageSquareIcon />}
+ />
+ {connectionState.status === "disconnected" && (
+ <AgentDocs
+ className="border-t pt-6"
+ title="Connect to an agent"
+ description="Start agents by running these commands in your terminal:"
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ ),
+);
+EmptyState.displayName = "EmptyState";
+
+interface LoadingIndicatorProps {
+ isLoading: boolean;
+ isRequestingPermission: boolean;
+ onStop: () => void;
+}
+
+const LoadingIndicator = memo<LoadingIndicatorProps>(
+ ({ isLoading, isRequestingPermission, onStop }) => {
+ if (!isLoading) {
+ return null;
+ }
+
+ return (
+ <div className="px-3 py-2 border-t bg-muted/30 flex-shrink-0">
+ <div className="flex items-center justify-between text-xs text-muted-foreground">
+ <div className="flex items-center gap-2">
+ <Spinner size="small" className="text-primary" />
+ {isRequestingPermission ? (
+ <span>Waiting for permission to continue...</span>
+ ) : (
+ <span>Agent is working...</span>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={onStop}
+ className="h-6 px-2"
+ >
+ <StopCircleIcon className="h-3 w-3 mr-1" />
+ <span className="text-xs">Stop</span>
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+ },
+);
+LoadingIndicator.displayName = "LoadingIndicator";
+
+interface PromptAreaProps {
+ isLoading: boolean;
+ activeSessionId: ExternalAgentSessionId | null;
+ promptValue: string;
+ onPromptValueChange: (value: string) => void;
+ onPromptSubmit: (e: KeyboardEvent | undefined, prompt: string) => void;
+}
+
+const PromptArea = memo<PromptAreaProps>(
+ ({
+ isLoading,
+ activeSessionId,
+ promptValue,
+ onPromptValueChange,
+ onPromptSubmit,
+ }) => (
+ <div
+ className={cn(
+ "px-3 py-2 border-t bg-background flex-shrink-0 min-h-[80px]",
+ (isLoading || !activeSessionId) && "opacity-50 pointer-events-none",
+ )}
+ >
+ <PromptInput
+ value={promptValue}
+ onChange={isLoading ? Functions.NOOP : onPromptValueChange}
+ onSubmit={onPromptSubmit}
+ onClose={Functions.NOOP}
+ placeholder={isLoading ? "Processing..." : "Ask your AI agent..."}
+ className={isLoading ? "opacity-50 pointer-events-none" : ""}
+ maxHeight="120px"
+ />
+ </div>
+ ),
+);
+PromptArea.displayName = "PromptArea";
+
+interface ChatContentProps {
+ hasNotifications: boolean;
+ connectionState: AgentConnectionState;
+ sessionId: ExternalAgentSessionId | null;
+ notifications: NotificationEvent[];
+ pendingPermission: AgentPendingPermission;
+ onResolvePermission: (option: unknown) => void;
+ onRetryConnection?: () => void;
+ onRetryLastAction?: () => void;
+ onDismissError?: (errorId: string) => void;
+}
+
+const ChatContent = memo<ChatContentProps>(
+ ({
+ hasNotifications,
+ connectionState,
+ notifications,
+ pendingPermission,
+ onResolvePermission,
+ onRetryConnection,
+ onRetryLastAction,
+ onDismissError,
+ sessionId,
+ }) => {
+ const [isScrolledToBottom, setIsScrolledToBottom] = useState(true);
+ const scrollContainerRef = useRef<HTMLDivElement>(null);
+
+ // Scroll handler to determine if we're at the bottom of the chat
+ const handleScroll = useEvent(() => {
+ const container = scrollContainerRef.current;
+ if (!container) {
+ return;
+ }
+
+ const { scrollTop, scrollHeight, clientHeight } = container;
+ const hasOverflow = scrollHeight > clientHeight;
+ const isAtBottom = hasOverflow
+ ? Math.abs(scrollHeight - clientHeight - scrollTop) < 5
+ : true; // 5px threshold
+ setIsScrolledToBottom(isAtBottom);
+ });
+
+ const scrollToBottom = useEvent(() => {
+ const container = scrollContainerRef.current;
+ if (!container) {
+ return;
+ }
+
+ container.scrollTo({
+ top: container.scrollHeight,
+ behavior: "smooth",
+ });
+ });
+
+ // Auto-scroll to bottom when new notifications arrive (if already at bottom)
+ useEffect(() => {
+ if (isScrolledToBottom && notifications.length > 0) {
+ // Use setTimeout to ensure DOM is updated before scrolling
+ const timeout = setTimeout(scrollToBottom, 100);
+ return () => clearTimeout(timeout);
+ }
+ }, [notifications.length, isScrolledToBottom, scrollToBottom]);
+
+ return (
+ <div className="flex-1 flex flex-col overflow-hidden flex-shrink-0 relative">
+ {pendingPermission && (
+ <div className="p-3 border-b">
+ <PermissionRequest
+ permission={pendingPermission}
+ onResolve={onResolvePermission}
+ />
+ </div>
+ )}
+
+ <div
+ ref={scrollContainerRef}
+ className="flex-1 bg-muted/20 w-full flex flex-col overflow-y-auto p-2"
+ onScroll={handleScroll}
+ >
+ {sessionId && (
+ <div className="text-xs text-muted-foreground mb-2 px-2">
+ Session ID: {sessionId}
+ </div>
+ )}
+ {hasNotifications ? (
+ <div className="space-y-2">
+ <AgentThread
+ isConnected={connectionState.status === "connected"}
+ notifications={notifications}
+ onRetryConnection={onRetryConnection}
+ onRetryLastAction={onRetryLastAction}
+ onDismissError={onDismissError}
+ />
+ </div>
+ ) : (
+ <div className="flex items-center justify-center h-full min-h-[200px]">
+ <PanelEmptyState
+ title="Waiting for agent"
+ description="Your AI agent will appear here when active"
+ icon={<BotMessageSquareIcon />}
+ />
+ </div>
+ )}
+ </div>
+
+ <ScrollToBottomButton
+ isVisible={!isScrolledToBottom && hasNotifications}
+ onScrollToBottom={scrollToBottom}
+ />
+ </div>
+ );
+ },
+);
+ChatContent.displayName = "ChatContent";
+
+const NO_WS_SET = "_skip_auto_connect_";
+
+function getCwd() {
+ const filename = store.get(filenameAtom);
+ if (!filename) {
+ return "";
+ }
+ return Paths.basename(filename);
+}
+
+const AgentPanel: React.FC = () => {
+ const [isLoading, setIsLoading] = useState(false);
+ const [promptValue, setPromptValue] = useState("");
+
+ const [selectedTab] = useAtom(selectedTabAtom);
+ const [sessionState, setSessionState] = useAtom(agentSessionStateAtom);
+
+ const wsUrl = selectedTab
+ ? getAgentWebSocketUrl(selectedTab.agentId)
+ : NO_WS_SET;
+ const { sendUpdateFile, sendFileDetails } = useRequestClient();
+ const isCreatingNewSession = useRef(false);
+
+ const acpClient = useAcpClient({
+ wsUrl,
+ clientOptions: {
+ readTextFile: (request): Promise<ReadTextFileResponse> => {
+ logger.debug("Agent requesting file read", {
+ path: request.path,
+ });
+ return sendFileDetails({ path: request.path }).then((response) => ({
+ content: response.contents || "",
+ }));
+ },
+ writeTextFile: (request): Promise<WriteTextFileResponse> => {
+ logger.debug("Agent requesting file write", {
+ path: request.path,
+ contentLength: request.content.length,
+ });
+ return sendUpdateFile({
+ path: request.path,
+ contents: request.content,
+ }).then(() => null);
+ },
+ },
+ autoConnect: false, // We'll manage connection manually based on active session
+ });
+
+ const {
+ connect,
+ disconnect,
+ connectionState,
+ notifications,
+ pendingPermission,
+ resolvePermission,
+ activeSessionId,
+ agent,
+ } = acpClient;
+
+ // Auto-connect to agent when we have an active session, but only once per session
+ useEffect(() => {
+ if (wsUrl === NO_WS_SET) {
+ return;
+ }
+
+ logger.debug("Auto-connecting to agent", {
+ sessionId: activeSessionId,
+ });
+ connect();
+
+ return () => {
+ // We don't want to disconnect so users can switch between different
+ // panels without losing their session
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [wsUrl]);
+
+ const handleNewSession = useEvent(async () => {
+ if (isCreatingNewSession.current) {
+ return;
+ }
+ if (!agent) {
+ return;
+ }
+
+ // If there is an active session, we should stop it
+ if (activeSessionId) {
+ await agent.cancel({ sessionId: activeSessionId }).catch((error) => {
+ logger.error("Failed to cancel active session", { error });
+ });
+ }
+
+ logger.debug("Creating new agent session", {});
+ isCreatingNewSession.current = true;
+ const newSession = await agent
+ .newSession({
+ cwd: getCwd(),
+ mcpServers: [],
+ })
+ .finally(() => {
+ isCreatingNewSession.current = false;
+ });
+ setSessionState((prev) =>
+ updateSessionExternalAgentSessionId(
+ prev,
+ newSession.sessionId as ExternalAgentSessionId,
+ ),
+ );
+ });
+
+ const handleResumeSession = useEvent(
+ async (previousSessionId: ExternalAgentSessionId) => {
+ if (!agent) {
+ return;
+ }
+ logger.debug("Resuming agent session", {
+ sessionId: previousSessionId,
+ });
+ if (!agent.loadSession) {
+ throw new Error("Agent does not support loading sessions");
+ }
+ await agent.loadSession({
+ sessionId: previousSessionId,
+ cwd: getCwd(),
+ mcpServers: [],
+ });
+ setSessionState((prev) =>
+ updateSessionExternalAgentSessionId(prev, previousSessionId),
+ );
+ },
+ );
+
+ // Create or resume a session when successfully connected
+ const isConnected = connectionState.status === "connected";
+ 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) {
+ return;
+ }
+
+ // Already have an active session
+ if (activeSessionId && tabLastActiveSessionId) {
+ return;
+ }
+
+ const createOrResumeSession = async () => {
+ try {
+ // Check if we need to create a new session
+ if (tabLastActiveSessionId) {
+ // Try to resume existing session
+ try {
+ await handleResumeSession(tabLastActiveSessionId);
+ } catch (resumeError) {
+ logger.debug("Failed to resume session, creating new session", {
+ externalSessionId: tabLastActiveSessionId,
+ error: resumeError,
+ });
+ // Fall back to creating new session
+ await handleNewSession();
+ }
+ } else {
+ // No existing session, create new one
+ await handleNewSession();
+ }
+ } catch (error) {
+ logger.error("Failed to create or resume session:", error);
+ }
+ };
+
+ createOrResumeSession();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isConnected, agent, tabLastActiveSessionId, activeSessionId]);
+
+ // Handler for prompt submission
+ const handlePromptSubmit = useEvent(
+ async (_e: KeyboardEvent | undefined, prompt: string) => {
+ if (!activeSessionId || !agent || isLoading) {
+ return;
+ }
+
+ logger.debug("Submitting prompt to agent", {
+ sessionId: activeSessionId,
+ });
+ setIsLoading(true);
+ setPromptValue("");
+
+ // Update session title with first message if it's still the default
+ if (selectedTab?.title.startsWith("New ")) {
+ setSessionState((prev) => updateSessionTitle(prev, prompt));
+ }
+
+ const filename = store.get(filenameAtom);
+ if (!filename) {
+ toast({
+ title: "Notebook must be named",
+ description: "Please name the notebook to use the agent",
+ variant: "danger",
+ });
+ return;
+ }
+
+ try {
+ await agent.prompt({
+ sessionId: activeSessionId,
+ prompt: [
+ { type: "text", text: prompt },
+ {
+ type: "resource_link",
+ uri: filename,
+ mimeType: "text/x-python",
+ name: filename,
+ },
+ {
+ type: "resource",
+ resource: {
+ uri: "marimo_rules.md",
+ mimeType: "text/markdown",
+ text: getAgentPrompt(filename),
+ },
+ },
+ ],
+ });
+ } catch (error) {
+ logger.error("Failed to send prompt", { error });
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ );
+
+ // Handler for stopping the current operation
+ const handleStop = useEvent(async () => {
+ if (!activeSessionId || !agent) {
+ return;
+ }
+ await agent.cancel({ sessionId: activeSessionId });
+ setIsLoading(false);
+ });
+
+ // Handler for manual connect
+ const handleManualConnect = useEvent(() => {
+ logger.debug("Manual connect requested", {
+ currentStatus: connectionState.status,
+ });
+ connect();
+ });
+
+ // Handler for manual disconnect
+ const handleManualDisconnect = useEvent(() => {
+ logger.debug("Manual disconnect requested", {
+ sessionId: activeSessionId,
+ currentStatus: connectionState.status,
+ });
+ disconnect();
+ });
+
+ const hasNotifications = notifications.length > 0;
+ const hasActiveSessions = sessionState.sessions.length > 0;
+
+ if (!hasActiveSessions) {
+ return (
+ <EmptyState
+ currentAgentId={selectedTab?.agentId}
+ connectionState={connectionState}
+ onConnect={handleManualConnect}
+ onDisconnect={handleManualDisconnect}
+ />
+ );
+ }
+
+ return (
+ <div className="flex flex-col flex-1 overflow-hidden mo-agent-panel">
+ <AgentPanelHeader
+ connectionState={connectionState}
+ currentAgentId={selectedTab?.agentId}
+ onConnect={handleManualConnect}
+ onDisconnect={handleManualDisconnect}
+ onRestartThread={handleNewSession}
+ hasActiveSession={true}
+ shouldShowConnectionControl={wsUrl !== NO_WS_SET}
+ />
+ <SessionTabs />
+
+ <ChatContent
+ sessionId={activeSessionId}
+ hasNotifications={hasNotifications}
+ connectionState={connectionState}
+ notifications={notifications}
+ pendingPermission={pendingPermission}
+ onResolvePermission={(option) => {
+ logger.debug("Resolving permission request", {
+ sessionId: activeSessionId,
+ option,
+ });
+ resolvePermission(option as RequestPermissionResponse);
+ }}
+ onRetryConnection={handleManualConnect}
+ />
+
+ <LoadingIndicator
+ isLoading={isLoading}
+ isRequestingPermission={!!pendingPermission}
+ onStop={handleStop}
+ />
+
+ <PromptArea
+ isLoading={isLoading}
+ activeSessionId={activeSessionId}
+ promptValue={promptValue}
+ onPromptValueChange={setPromptValue}
+ onPromptSubmit={handlePromptSubmit}
+ />
+ </div>
+ );
+};
+
+export default AgentPanel;
diff --git a/frontend/src/components/chat/acp/agent-selector.tsx b/frontend/src/components/chat/acp/agent-selector.tsx
new file mode 100644
index 0000000000..96ba6b9bbf
--- /dev/null
+++ b/frontend/src/components/chat/acp/agent-selector.tsx
@@ -0,0 +1,138 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { useAtom, useSetAtom } from "jotai";
+import { ChevronDownIcon } from "lucide-react";
+import React, { memo, useState } from "react";
+import useEvent from "react-use-event-hook";
+import { AiProviderIcon } from "@/components/ai/ai-provider-icon";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { cn } from "@/utils/cn";
+import { AgentDocs } from "./agent-docs";
+import {
+ type AgentSession,
+ addSession,
+ agentSessionStateAtom,
+ type ExternalAgentId,
+ getAgentSessionSupport,
+ selectedTabAtom,
+} from "./state";
+
+interface AgentSelectorProps {
+ onSessionCreated?: (agentId: ExternalAgentId) => void;
+ className?: string;
+}
+
+const AVAILABLE_AGENTS = [
+ {
+ id: "claude",
+ displayName: "Claude",
+ iconId: "anthropic",
+ },
+ {
+ id: "gemini",
+ displayName: "Gemini",
+ iconId: "google",
+ },
+] as const;
+
+interface AgentMenuItemProps {
+ agent: (typeof AVAILABLE_AGENTS)[number];
+ onSelect: (agentId: ExternalAgentId) => void;
+ existingSessions: AgentSession[];
+}
+
+const AgentMenuItem = memo<AgentMenuItemProps>(
+ ({ agent, onSelect, existingSessions }) => {
+ const sessionSupport = getAgentSessionSupport(agent.id);
+ const hasExistingSession = existingSessions.some(
+ (s) => s.agentId === agent.id,
+ );
+
+ const getText = () => {
+ if (sessionSupport === "single" && hasExistingSession) {
+ return `Reset ${agent.displayName} session`;
+ }
+ return `New ${agent.displayName} session`;
+ };
+
+ return (
+ <DropdownMenuItem
+ onClick={() => onSelect(agent.id)}
+ className="cursor-pointer"
+ >
+ <div className="flex items-center w-full">
+ <AiProviderIcon provider={agent.iconId} className="h-3 w-3 mr-2" />
+ <span>{getText()}</span>
+ </div>
+ </DropdownMenuItem>
+ );
+ },
+);
+AgentMenuItem.displayName = "AgentMenuItem";
+
+export const AgentSelector: React.FC<AgentSelectorProps> = memo(
+ ({ onSessionCreated, className }) => {
+ const [sessionState, setSessionState] = useAtom(agentSessionStateAtom);
+ const setActiveTab = useSetAtom(selectedTabAtom);
+ const [isOpen, setIsOpen] = useState(false);
+
+ const handleCreateSession = useEvent(async (agentId: ExternalAgentId) => {
+ const newState = addSession(sessionState, {
+ agentId,
+ });
+
+ setSessionState(newState);
+ setActiveTab(newState.activeTabId);
+ setIsOpen(false);
+
+ onSessionCreated?.(agentId);
+ });
+
+ return (
+ <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
+ <DropdownMenuTrigger asChild={true}>
+ <Button
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "h-6 gap-1 px-2 text-xs bg-muted/30 hover:bg-muted/50 border border-border border-y-0 rounded-none focus-visible:ring-0",
+ className,
+ )}
+ >
+ <span>New session</span>
+ <ChevronDownIcon className="h-3 w-3" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-fit">
+ {AVAILABLE_AGENTS.map((agent) => (
+ <AgentMenuItem
+ key={agent.id}
+ agent={agent}
+ onSelect={handleCreateSession}
+ existingSessions={sessionState.sessions}
+ />
+ ))}
+ <DropdownMenuSeparator />
+ <div className="px-2 py-2">
+ <div className="text-xs font-medium text-muted-foreground mb-3">
+ To start an external agent, run the following command in your
+ terminal:
+ </div>
+ <AgentDocs
+ agents={AVAILABLE_AGENTS.map((agent) => agent.id)}
+ showCopy={true}
+ />
+ </div>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+ },
+);
+AgentSelector.displayName = "AgentSelector";
diff --git a/frontend/src/components/chat/acp/blocks.tsx b/frontend/src/components/chat/acp/blocks.tsx
new file mode 100644
index 0000000000..a7d6a88909
--- /dev/null
+++ b/frontend/src/components/chat/acp/blocks.tsx
@@ -0,0 +1,664 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import type {
+ ContentBlock,
+ ToolCallContent,
+ ToolCallLocation,
+} from "@zed-industries/agent-client-protocol";
+import { capitalize } from "lodash-es";
+import {
+ FileAudio2Icon,
+ FileIcon,
+ FileImageIcon,
+ FileJsonIcon,
+ FileTextIcon,
+ FileVideoCameraIcon,
+ RotateCcwIcon,
+ WifiIcon,
+ WifiOffIcon,
+ WrenchIcon,
+ XCircleIcon,
+ XIcon,
+} from "lucide-react";
+import React from "react";
+import { Streamdown } from "streamdown";
+import { mergeToolCalls } from "use-acp";
+import { JsonOutput } from "@/components/editor/output/JsonOutput";
+import { Button } from "@/components/ui/button";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { logNever } from "@/utils/assertNever";
+import { cn } from "@/utils/cn";
+import { type Base64String, base64ToDataURL } from "@/utils/json/base64";
+import { Strings } from "@/utils/strings";
+import { SimpleAccordion } from "./common";
+import type {
+ AgentNotificationEvent,
+ AgentThoughtNotificationEvent,
+ ConnectionChangeNotificationEvent,
+ ContentBlockOf,
+ ErrorNotificationEvent,
+ PlanNotificationEvent,
+ SessionNotificationEventData,
+ ToolCallNotificationEvent,
+ ToolCallUpdateNotificationEvent,
+ UserNotificationEvent,
+} from "./types";
+import {
+ isAgentMessages,
+ isAgentThoughts,
+ isPlans,
+ isToolCalls,
+ isUserMessages,
+} from "./utils";
+
+export const ErrorBlock = (props: {
+ data: ErrorNotificationEvent["data"];
+ onRetry?: () => void;
+ onDismiss?: () => void;
+}) => {
+ const { message } = props.data;
+
+ // Don't show WebSocket connection errors
+ if (message.includes("WebSocket")) {
+ return null;
+ }
+
+ return (
+ <div
+ className="border border-[var(--red-6)] bg-[var(--red-2)] rounded-lg p-4 my-2"
+ data-block-type="error"
+ >
+ <div className="flex items-start gap-3">
+ <div className="flex-shrink-0">
+ <XCircleIcon className="h-5 w-5 text-[var(--red-11)]" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-2">
+ <h4 className="text-sm font-medium text-[var(--red-11)]">
+ Agent Error
+ </h4>
+ </div>
+ <div className="text-sm text-[var(--red-11)] leading-relaxed mb-3">
+ {message}
+ </div>
+ <div className="flex items-center gap-2">
+ {props.onRetry && (
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={props.onRetry}
+ className="text-[var(--red-11)] border-[var(--red-6)] hover:bg-[var(--red-3)]"
+ >
+ <RotateCcwIcon className="h-3 w-3 mr-1" />
+ Retry
+ </Button>
+ )}
+ {props.onDismiss && (
+ <Button
+ size="xs"
+ variant="ghost"
+ onClick={props.onDismiss}
+ className="text-[var(--red-10)] hover:bg-[var(--red-3)]"
+ >
+ <XIcon className="h-3 w-3 mr-1" />
+ Dismiss
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export const ConnectionChangeBlock = (props: {
+ data: ConnectionChangeNotificationEvent["data"];
+ isConnected: boolean;
+ onRetry?: () => void;
+ timestamp?: number;
+}) => {
+ const { status } = props.data;
+
+ if (props.isConnected) {
+ return null;
+ }
+
+ const getStatusConfig = () => {
+ switch (status) {
+ case "connected":
+ return {
+ icon: <WifiIcon className="h-4 w-4" />,
+ title: "Connected to Agent",
+ message: "Successfully established connection with the AI agent",
+ bgColor: "bg-[var(--blue-2)]",
+ borderColor: "border-[var(--blue-6)]",
+ textColor: "text-[var(--blue-11)]",
+ iconColor: "text-[var(--blue-10)]",
+ };
+ case "disconnected":
+ return {
+ icon: <WifiOffIcon className="h-4 w-4" />,
+ title: "Disconnected from Agent",
+ message: "Connection to the AI agent has been lost",
+ bgColor: "bg-[var(--amber-2)]",
+ borderColor: "border-[var(--amber-6)]",
+ textColor: "text-[var(--amber-11)]",
+ iconColor: "text-[var(--amber-10)]",
+ };
+ case "connecting":
+ return {
+ icon: <WifiIcon className="h-4 w-4 animate-pulse" />,
+ title: "Connecting to Agent",
+ message: "Establishing connection with the AI agent...",
+ bgColor: "bg-[var(--gray-2)]",
+ borderColor: "border-[var(--gray-6)]",
+ textColor: "text-[var(--gray-11)]",
+ iconColor: "text-[var(--gray-10)]",
+ };
+ case "error":
+ return {
+ icon: <WifiOffIcon className="h-4 w-4" />,
+ title: "Connection Error",
+ message: "Failed to connect to the AI agent",
+ bgColor: "bg-[var(--red-2)]",
+ borderColor: "border-[var(--red-6)]",
+ textColor: "text-[var(--red-11)]",
+ iconColor: "text-[var(--red-10)]",
+ };
+ default:
+ return {
+ icon: <WifiOffIcon className="h-4 w-4" />,
+ title: "Connection Status Changed",
+ message: `Agent connection status: ${status}`,
+ bgColor: "bg-[var(--gray-2)]",
+ borderColor: "border-[var(--gray-6)]",
+ textColor: "text-[var(--gray-11)]",
+ iconColor: "text-[var(--gray-10)]",
+ };
+ }
+ };
+
+ const config = getStatusConfig();
+ const showRetry = status === "disconnected" || status === "error";
+
+ return (
+ <div
+ className={`border ${config.borderColor} ${config.bgColor} rounded-lg p-3 my-2`}
+ data-block-type="connection-change"
+ data-status={status}
+ >
+ <div className="flex items-start gap-3">
+ <div className={`flex-shrink-0 ${config.iconColor}`}>{config.icon}</div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-1">
+ <h4 className={`text-sm font-medium ${config.textColor}`}>
+ {config.title}
+ </h4>
+ {props.timestamp && (
+ <span className="text-xs text-muted-foreground">
+ {new Date(props.timestamp).toLocaleTimeString()}
+ </span>
+ )}
+ </div>
+ <div className={`text-sm ${config.textColor} opacity-90 mb-2`}>
+ {config.message}
+ </div>
+ {showRetry && props.onRetry && (
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={props.onRetry}
+ className={`${config.textColor} ${config.borderColor} hover:${config.bgColor}`}
+ >
+ <RotateCcwIcon className="h-3 w-3 mr-1" />
+ Retry Connection
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export const AgentThoughtsBlock = (props: {
+ startTimestamp: number;
+ endTimestamp: number;
+ data: AgentThoughtNotificationEvent[];
+}) => {
+ const startAsSeconds = props.startTimestamp / 1000;
+ const endAsSeconds = props.endTimestamp / 1000;
+ const totalSeconds = Math.round(endAsSeconds - startAsSeconds) || "1";
+ return (
+ <div className="text-xs text-muted-foreground">
+ <SimpleAccordion title={`Thought for ${totalSeconds}s`}>
+ <div className="flex flex-col gap-2 text-muted-foreground">
+ <ContentBlocks data={props.data.map((item) => item.content)} />
+ </div>
+ </SimpleAccordion>
+ </div>
+ );
+};
+
+export const PlansBlock = (props: { data: PlanNotificationEvent[] }) => {
+ const plans = props.data.flatMap((item) => item.entries);
+
+ return (
+ <div className="rounded-lg border bg-background p-2 text-xs">
+ <div className="flex items-center justify-between mb-2">
+ <span className="font-medium text-muted-foreground">
+ To-dos{" "}
+ <span className="font-normal text-muted-foreground">
+ {plans.length}
+ </span>
+ </span>
+ </div>
+ <ul className="flex flex-col gap-1">
+ {plans.map((item, index) => (
+ <li
+ key={`${item.status}-${index}`}
+ className={`
+ flex items-center gap-2 px-2 py-1 rounded
+ `}
+ >
+ <input
+ type="checkbox"
+ checked={item.status === "completed"}
+ readOnly={true}
+ className="accent-primary h-4 w-4 rounded border border-muted-foreground/30"
+ tabIndex={-1}
+ />
+ <span
+ className={cn(
+ "text-xs",
+ item.status === "completed" &&
+ "line-through text-muted-foreground",
+ )}
+ >
+ {item.content}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+};
+
+export const UserMessagesBlock = (props: { data: UserNotificationEvent[] }) => {
+ return (
+ <div className="flex flex-col gap-2 text-muted-foreground border p-2 bg-background rounded break-words">
+ <ContentBlocks data={props.data.map((item) => item.content)} />
+ </div>
+ );
+};
+
+export const AgentMessagesBlock = (props: {
+ data: AgentNotificationEvent[];
+}) => {
+ return (
+ <div className="flex flex-col gap-2">
+ <ContentBlocks data={props.data.map((item) => item.content)} />
+ </div>
+ );
+};
+
+export const ContentBlocks = (props: { data: ContentBlock[] }) => {
+ const renderBlock = (block: ContentBlock) => {
+ if (block.type === "text") {
+ return <Streamdown>{block.text}</Streamdown>;
+ }
+ if (block.type === "image") {
+ return <ImageBlock data={block} />;
+ }
+ if (block.type === "audio") {
+ return <AudioBlock data={block} />;
+ }
+ if (block.type === "resource") {
+ return <ResourceBlock data={block} />;
+ }
+ if (block.type === "resource_link") {
+ return <ResourceLinkBlock data={block} />;
+ }
+ logNever(block);
+ return null;
+ };
+
+ return (
+ <div>
+ {props.data.map((item, index) => {
+ return (
+ <React.Fragment key={`${item.type}-${index}`}>
+ {renderBlock(item)}
+ </React.Fragment>
+ );
+ })}
+ </div>
+ );
+};
+
+export const ImageBlock = (props: { data: ContentBlockOf<"image"> }) => {
+ return (
+ <img
+ src={`data:${props.data.mimeType};base64,${props.data.data}`}
+ alt={props.data.uri ?? ""}
+ />
+ );
+};
+
+export const AudioBlock = (props: { data: ContentBlockOf<"audio"> }) => {
+ return (
+ <audio
+ src={`data:${props.data.mimeType};base64,${props.data.data}`}
+ controls={true}
+ >
+ <track kind="captions" />
+ </audio>
+ );
+};
+
+export const ResourceBlock = (props: { data: ContentBlockOf<"resource"> }) => {
+ if ("text" in props.data.resource) {
+ return (
+ <Popover>
+ <PopoverTrigger>
+ <span className="flex items-center gap-1">
+ {props.data.resource.mimeType && (
+ <MimeIcon mimeType={props.data.resource.mimeType} />
+ )}
+ {props.data.resource.uri}
+ </span>
+ </PopoverTrigger>
+ <PopoverContent className="max-h-96 overflow-y-auto scrollbar-thin">
+ <Streamdown>{props.data.resource.text}</Streamdown>
+ </PopoverContent>
+ </Popover>
+ );
+ }
+
+ if ("blob" in props.data.resource) {
+ if (props.data.resource.mimeType?.startsWith("image/")) {
+ return (
+ <ImageBlock
+ data={{
+ type: "image",
+ mimeType: props.data.resource.mimeType,
+ data: props.data.resource.blob,
+ }}
+ />
+ );
+ }
+ if (props.data.resource.mimeType?.startsWith("audio/")) {
+ return (
+ <AudioBlock
+ data={{
+ type: "audio",
+ mimeType: props.data.resource.mimeType,
+ data: props.data.resource.blob,
+ }}
+ />
+ );
+ }
+ const dataURL = base64ToDataURL(
+ props.data.resource.blob as Base64String,
+ props.data.resource.mimeType ?? "",
+ );
+ return (
+ <a href={dataURL} className="flex items-center gap-1" download={true}>
+ {props.data.resource.mimeType && (
+ <MimeIcon mimeType={props.data.resource.mimeType} />
+ )}
+ {props.data.resource.uri}
+ </a>
+ );
+ }
+ logNever(props.data.resource);
+ return null;
+};
+
+export const ResourceLinkBlock = (props: {
+ data: ContentBlockOf<"resource_link">;
+}) => {
+ if (props.data.uri.startsWith("http")) {
+ return (
+ <a
+ href={props.data.uri}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-link hover:underline"
+ >
+ {props.data.name}
+ </a>
+ );
+ }
+
+ return (
+ <span className="flex items-center gap-1">
+ {props.data.mimeType && <MimeIcon mimeType={props.data.mimeType} />}
+ {props.data.name || props.data.title || props.data.uri}
+ </span>
+ );
+};
+
+export const MimeIcon = (props: { mimeType: string }) => {
+ if (props.mimeType.startsWith("image/")) {
+ return <FileImageIcon className="h-2 w-2" />;
+ }
+ if (props.mimeType.startsWith("audio/")) {
+ return <FileAudio2Icon className="h-2 w-2" />;
+ }
+ if (props.mimeType.startsWith("video/")) {
+ return <FileVideoCameraIcon className="h-2 w-2" />;
+ }
+ if (props.mimeType.startsWith("text/")) {
+ return <FileTextIcon className="h-2 w-2" />;
+ }
+ if (props.mimeType.startsWith("application/")) {
+ return <FileJsonIcon className="h-2 w-2" />;
+ }
+ return <FileIcon className="h-2 w-2" />;
+};
+
+export const SessionNotificationsBlock = <
+ T extends SessionNotificationEventData,
+>(props: {
+ data: T[];
+ startTimestamp: number;
+ endTimestamp: number;
+}) => {
+ if (props.data.length === 0) {
+ return null;
+ }
+ const kind = props.data[0].sessionUpdate;
+
+ const renderItems = (items: T[]) => {
+ if (isToolCalls(items)) {
+ return <ToolNotificationsBlock data={items} />;
+ }
+ if (isAgentThoughts(items)) {
+ return (
+ <AgentThoughtsBlock
+ startTimestamp={props.startTimestamp}
+ endTimestamp={props.endTimestamp}
+ data={items}
+ />
+ );
+ }
+ if (isUserMessages(items)) {
+ return <UserMessagesBlock data={items} />;
+ }
+ if (isAgentMessages(items)) {
+ return <AgentMessagesBlock data={items} />;
+ }
+ if (isPlans(items)) {
+ return <PlansBlock data={items} />;
+ }
+
+ return (
+ <SimpleAccordion title={items[0].sessionUpdate}>
+ <JsonOutput data={items} format="tree" className="max-h-64" />
+ </SimpleAccordion>
+ );
+ };
+
+ return (
+ <div className="flex flex-col text-sm gap-2" data-block-type={kind}>
+ {renderItems(props.data)}
+ </div>
+ );
+};
+
+export const ToolNotificationsBlock = (props: {
+ data: Array<ToolCallNotificationEvent | ToolCallUpdateNotificationEvent>;
+}) => {
+ const toolCalls = mergeToolCalls(props.data);
+
+ return (
+ <div className="flex flex-col text-muted-foreground">
+ {toolCalls.map((item) => (
+ <SimpleAccordion
+ key={item.toolCallId}
+ status={
+ item.status === "completed"
+ ? "success"
+ : item.status === "failed"
+ ? "error"
+ : item.status === "in_progress" || item.status === "pending"
+ ? "loading"
+ : undefined
+ }
+ title={
+ <span data-tool-data={JSON.stringify(item)}>
+ {handleBackticks(toolTitle(item))}
+ </span>
+ }
+ defaultIcon={<WrenchIcon className="h-3 w-3" />}
+ >
+ <ToolBodyBlock data={item} />
+ </SimpleAccordion>
+ ))}
+ </div>
+ );
+};
+
+export const DiffBlocks = (props: {
+ data: Array<Extract<ToolCallContent, { type: "diff" }>>;
+}) => {
+ return (
+ <div className="flex flex-col gap-2 text-muted-foreground">
+ {props.data.map((item) => {
+ return (
+ <div
+ key={item.path}
+ className="border rounded-md overflow-hidden bg-[var(--gray-2)] max-h-64 overflow-y-auto scrollbar-thin"
+ >
+ {/* File path header */}
+ <div className="px-2 py-1 bg-[var(--gray-2)] border-b text-xs font-medium text-[var(--gray-11)]">
+ {item.path}
+ </div>
+
+ <div className="font-mono text-xs">
+ {/* Removed lines */}
+ {item.oldText && (
+ <div className="px-3 py-1 border-b bg-[var(--red-2)] border-b-[var(--red-6)]">
+ <div className="flex">
+ <span className="text-[var(--red-11)] select-none mr-2">
+ -
+ </span>
+ <pre className="text-[var(--red-11)] px-1 rounded whitespace-pre-wrap break-words flex-1 line-through opacity-80">
+ {item.oldText}
+ </pre>
+ </div>
+ </div>
+ )}
+
+ {/* Added lines */}
+ {item.newText && (
+ <div className="px-3 py-1 bg-[var(--grass-2)] border-b-[var(--grass-6)]">
+ <div className="flex">
+ <span className="text-[var(--grass-11)] select-none mr-2">
+ +
+ </span>
+ <pre className="text-[var(--grass-11)] px-1 rounded whitespace-pre-wrap break-words flex-1 italic opacity-90">
+ {item.newText}
+ </pre>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+};
+
+function toolTitle(
+ item: Pick<ToolCallUpdateNotificationEvent, "title" | "kind" | "locations">,
+) {
+ const prefix =
+ item.title || Strings.startCase(item.kind || "") || "Tool call";
+ const firstLocation = item.locations?.[0];
+ // Add the first location if it is not in the title already
+ if (firstLocation && !prefix.includes(firstLocation.path)) {
+ return `${prefix}: ${firstLocation.path}`;
+ }
+ return prefix;
+}
+
+function handleBackticks(text: string) {
+ if (text.startsWith("`") && text.endsWith("`")) {
+ return <i>{text.slice(1, -1)}</i>;
+ }
+ return text;
+}
+
+export const LocationsBlock = (props: { data: ToolCallLocation[] }) => {
+ // Only show locations if there are multiple locations, otherwise it is
+ // in the title
+ if (props.data.length <= 1) {
+ return null;
+ }
+
+ const locations = props.data.map((item) => {
+ if (item.line) {
+ return `${item.path}:${item.line}`;
+ }
+ return item.path;
+ });
+ return <div className="flex flex-col gap-2">{locations.join("\n")}</div>;
+};
+
+export const ToolBodyBlock = (props: {
+ data:
+ | Omit<ToolCallNotificationEvent, "sessionUpdate">
+ | Omit<ToolCallUpdateNotificationEvent, "sessionUpdate">;
+}) => {
+ const content = props.data.content
+ ?.filter((item) => item.type === "content")
+ .map((item) => item.content);
+ const diffs = props.data.content?.filter((item) => item.type === "diff");
+ const locations = props.data.locations;
+ const isFailed = props.data.status === "failed";
+ const hasLocations = locations && locations.length > 0;
+
+ if (content?.length === 0 && diffs?.length === 0 && hasLocations) {
+ return (
+ <div className="flex flex-col gap-2 pr-2">
+ <span className="text-xs text-muted-foreground">
+ {capitalize(props.data.kind || "")}{" "}
+ {locations?.map((item) => item.path).join(", ")}
+ </span>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-2 pr-2">
+ {locations && <LocationsBlock data={locations} />}
+ {content && <ContentBlocks data={content} />}
+ {diffs && !isFailed && <DiffBlocks data={diffs} />}
+ </div>
+ );
+};
diff --git a/frontend/src/components/chat/acp/common.tsx b/frontend/src/components/chat/acp/common.tsx
new file mode 100644
index 0000000000..0724525b93
--- /dev/null
+++ b/frontend/src/components/chat/acp/common.tsx
@@ -0,0 +1,198 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import {
+ CheckCircleIcon,
+ Loader2,
+ PlugIcon,
+ ShieldCheckIcon,
+ WifiIcon,
+ WifiOffIcon,
+ XCircleIcon,
+} from "lucide-react";
+import React, { memo } from "react";
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from "@/components/ui/accordion";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/utils/cn";
+import { ToolBodyBlock } from "./blocks";
+import type { AgentPendingPermission } from "./types";
+
+interface SimpleAccordionProps {
+ title: string | React.ReactNode;
+ children: React.ReactNode | string;
+ status?: "loading" | "error" | "success";
+ index?: number;
+ defaultIcon?: React.ReactNode;
+}
+
+export const SimpleAccordion: React.FC<SimpleAccordionProps> = ({
+ title,
+ children,
+ status,
+ index = 0,
+ defaultIcon,
+}) => {
+ const getStatusIcon = () => {
+ switch (status) {
+ case "loading":
+ return <Loader2 className="h-3 w-3 animate-spin" />;
+ case "error":
+ return <XCircleIcon className="h-3 w-3 text-destructive" />;
+ case "success":
+ return <CheckCircleIcon className="h-3 w-3 text-[var(--blue-9)]" />;
+ default:
+ return defaultIcon;
+ }
+ };
+
+ return (
+ <Accordion
+ key={`tool-${index}`}
+ type="single"
+ collapsible={true}
+ className="w-full"
+ >
+ <AccordionItem value="tool-call" className="border-0">
+ <AccordionTrigger
+ className={cn(
+ "py-1 text-xs border-border shadow-none! ring-0! bg-muted hover:bg-muted/30 px-2 gap-1 rounded-sm [&[data-state=open]>svg]:rotate-180",
+ status === "error" && "text-destructive/80",
+ status === "success" && "text-[var(--blue-8)]",
+ )}
+ >
+ <span className="flex items-center gap-1">
+ {getStatusIcon()}
+ <code className="font-mono text-xs">{title}</code>
+ </span>
+ </AccordionTrigger>
+ <AccordionContent className="p-2">
+ <div className="space-y-3 max-h-64 overflow-y-auto scrollbar-thin">
+ {status !== "error" && (
+ <div className="text-xs font-medium text-muted-foreground mb-1">
+ {children}
+ </div>
+ )}
+
+ {status === "error" && (
+ <div className="bg-destructive/10 border border-destructive/20 rounded-md p-3 text-xs text-destructive">
+ {children}
+ </div>
+ )}
+ </div>
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
+ );
+};
+
+interface ConnectionStatusProps {
+ status: string;
+ className?: string;
+}
+
+export const ConnectionStatus: React.FC<ConnectionStatusProps> = memo(
+ ({ status, className }) => {
+ const getStatusConfig = () => {
+ switch (status) {
+ case "connected":
+ return {
+ icon: <WifiIcon className="h-3 w-3" />,
+ label: "Connected",
+ variant: "default" as const,
+ className:
+ "bg-[var(--blue-3)] text-[var(--blue-11)] border-[var(--blue-5)]",
+ };
+ case "connecting":
+ return {
+ icon: <PlugIcon className="h-3 w-3 animate-pulse" />,
+ label: "Connecting",
+ variant: "secondary" as const,
+ className:
+ "bg-[var(--yellow-3)] text-[var(--yellow-11)] border-[var(--yellow-5)]",
+ };
+ case "disconnected":
+ return {
+ icon: <WifiOffIcon className="h-3 w-3" />,
+ label: "Disconnected",
+ variant: "outline" as const,
+ className:
+ "bg-[var(--red-3)] text-[var(--red-11)] border-[var(--red-5)]",
+ };
+ default:
+ return {
+ icon: <WifiOffIcon className="h-3 w-3" />,
+ label: status || "Unknown",
+ variant: "outline" as const,
+ className:
+ "bg-[var(--gray-3)] text-[var(--gray-11)] border-[var(--gray-5)]",
+ };
+ }
+ };
+
+ const config = getStatusConfig();
+
+ return (
+ <Badge
+ variant={config.variant}
+ className={cn(config.className, className)}
+ >
+ {config.icon}
+ <span className="ml-1 text-xs font-medium">{config.label}</span>
+ </Badge>
+ );
+ },
+);
+ConnectionStatus.displayName = "ConnectionStatus";
+
+interface PermissionRequestProps {
+ permission: NonNullable<AgentPendingPermission>;
+ onResolve: (option: unknown) => void;
+}
+
+export const PermissionRequest: React.FC<PermissionRequestProps> = memo(
+ ({ permission, onResolve }) => {
+ return (
+ <div className="border border-[var(--amber-8)] bg-[var(--amber-2)] rounded-lg p-2">
+ <div className="flex items-center gap-2 mb-3">
+ <ShieldCheckIcon className="h-4 w-4 text-[var(--amber-11)]" />
+ <h3 className="text-sm font-medium text-[var(--amber-11)]">
+ Permission Request
+ </h3>
+ </div>
+ <p className="text-sm text-[var(--amber-11)] mb-3">
+ The AI agent is requesting permission to proceed:
+ </p>
+ <ToolBodyBlock data={permission.toolCall} />
+ <div className="flex gap-2">
+ {permission.options.map((option) => (
+ <Button
+ key={option.optionId}
+ size="xs"
+ variant="text"
+ className={
+ option.kind.startsWith("allow")
+ ? "text-[var(--blue-10)]"
+ : "text-[var(--red-10)]"
+ }
+ onClick={() => onResolve(option)}
+ >
+ {option.kind.startsWith("allow") && (
+ <CheckCircleIcon className="h-3 w-3 mr-1" />
+ )}
+ {option.kind.startsWith("reject") && (
+ <XCircleIcon className="h-3 w-3 mr-1" />
+ )}
+ {option.name}
+ </Button>
+ ))}
+ </div>
+ </div>
+ );
+ },
+);
+PermissionRequest.displayName = "PermissionRequest";
diff --git a/frontend/src/components/chat/acp/prompt.ts b/frontend/src/components/chat/acp/prompt.ts
new file mode 100644
index 0000000000..d63f53e2b0
--- /dev/null
+++ b/frontend/src/components/chat/acp/prompt.ts
@@ -0,0 +1,284 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+export function getAgentPrompt(filename: string) {
+ return `
+ I am currently editing a marimo notebook.
+ You can read or write to the notebook at @${filename}
+
+ If you make edits to the notebook, only edit the contents inside the function decorator with @app.cell.
+ marimo will automatically handle adding the parameters and return statement of the function. For example,
+ for each edit, just return:
+
+ \`\`\`
+ @app.cell
+ def __():
+ <your code here>
+ return
+ \`\`\`
+
+ ## Marimo fundamentals
+
+ Marimo is a reactive notebook that differs from traditional notebooks in key ways:
+
+ - Cells execute automatically when their dependencies change
+ - Variables cannot be redeclared across cells
+ - The notebook forms a directed acyclic graph (DAG)
+ - The last expression in a cell is automatically displayed
+ - UI elements are reactive and update the notebook automatically
+
+ ## Code Requirements
+
+ 1. All code must be complete and runnable
+ 2. Follow consistent coding style throughout
+ 3. Include descriptive variable names and helpful comments
+ 4. Import all modules in the first cell, always including \`import marimo as mo\`
+ 5. Never redeclare variables across cells
+ 6. Ensure no cycles in notebook dependency graph
+ 7. The last expression in a cell is automatically displayed, just like in Jupyter notebooks.
+ 8. Don't include comments in markdown cells
+ 9. Don't include comments in SQL cells
+
+ ## Reactivity
+
+ Marimo's reactivity means:
+
+ - When a variable changes, all cells that use that variable automatically re-execute
+ - UI elements trigger updates when their values change without explicit callbacks
+ - UI element values are accessed through \`.value\` attribute
+ - You cannot access a UI element's value in the same cell where it's defined
+
+ ## Best Practices
+
+ <data_handling>
+ - Use pandas for data manipulation
+ - Implement proper data validation
+ - Handle missing values appropriately
+ - Use efficient data structures
+ - A variable in the last expression of a cell is automatically displayed as a table
+ </data_handling>
+
+ <visualization>
+ - For matplotlib: use plt.gca() as the last expression instead of plt.show()
+ - For plotly: return the figure object directly
+ - For altair: return the chart object directly
+ - Include proper labels, titles, and color schemes
+ - Make visualizations interactive where appropriate
+ </visualization>
+
+ <ui_elements>
+ - Access UI element values with .value attribute (e.g., slider.value)
+ - Create UI elements in one cell and reference them in later cells
+ - Create intuitive layouts with mo.hstack(), mo.vstack(), and mo.tabs()
+ - Prefer reactive updates over callbacks (marimo handles reactivity automatically)
+ - Group related UI elements for better organization
+ </ui_elements>
+
+ <sql>
+ - When writing duckdb, prefer using marimo's SQL cells, which start with _df = mo.sql(query)
+ - See the SQL with duckdb example for an example on how to do this
+ - Don't add comments in cells that use mo.sql()
+ - Consider using \`vega_datasets\` for common example datasets
+ </sql>
+
+ ## Troubleshooting
+
+ Common issues and solutions:
+ - Circular dependencies: Reorganize code to remove cycles in the dependency graph
+ - UI element value access: Move access to a separate cell from definition
+ - Visualization not showing: Ensure the visualization object is the last expression
+
+ ## Available UI elements
+
+ - \`mo.ui.altair_chart(altair_chart)\`
+ - \`mo.ui.button(value=None, kind='primary')\`
+ - \`mo.ui.run_button(label=None, tooltip=None, kind='primary')\`
+ - \`mo.ui.checkbox(label='', value=False)\`
+ - \`mo.ui.date(value=None, label=None, full_width=False)\`
+ - \`mo.ui.dropdown(options, value=None, label=None, full_width=False)\`
+ - \`mo.ui.file(label='', multiple=False, full_width=False)\`
+ - \`mo.ui.number(value=None, label=None, full_width=False)\`
+ - \`mo.ui.radio(options, value=None, label=None, full_width=False)\`
+ - \`mo.ui.refresh(options: List[str], default_interval: str)\`
+ - \`mo.ui.slider(start, stop, value=None, label=None, full_width=False, step=None)\`
+ - \`mo.ui.range_slider(start, stop, value=None, label=None, full_width=False, step=None)\`
+ - \`mo.ui.table(data, columns=None, on_select=None, sortable=True, filterable=True)\`
+ - \`mo.ui.text(value='', label=None, full_width=False)\`
+ - \`mo.ui.text_area(value='', label=None, full_width=False)\`
+ - \`mo.ui.data_explorer(df)\`
+ - \`mo.ui.dataframe(df)\`
+ - \`mo.ui.plotly(plotly_figure)\`
+ - \`mo.ui.tabs(elements: dict[str, mo.ui.Element])\`
+ - \`mo.ui.array(elements: list[mo.ui.Element])\`
+ - \`mo.ui.form(element: mo.ui.Element, label='', bordered=True)\`
+
+ ## Layout and utility functions
+
+ - \`mo.md(text)\` - display markdown
+ - \`mo.stop(predicate, output=None)\` - stop execution conditionally
+ - \`mo.Html(html)\` - display HTML
+ - \`mo.image(image)\` - display an image
+ - \`mo.hstack(elements)\` - stack elements horizontally
+ - \`mo.vstack(elements)\` - stack elements vertically
+ - \`mo.tabs(elements)\` - create a tabbed interface
+
+ ## Examples
+
+ <example title="Basic UI with reactivity">
+ ${formatCells([
+ `
+ import marimo as mo
+ import matplotlib.pyplot as plt
+ import numpy as np
+ `,
+ `
+ n_points = mo.ui.slider(10, 100, value=50, label="Number of points")
+ n_points
+ `,
+ `
+ x = np.random.rand(n_points.value)
+ y = np.random.rand(n_points.value)
+
+ plt.figure(figsize=(8, 6))
+ plt.scatter(x, y, alpha=0.7)
+ plt.title(f"Scatter plot with {n_points.value} points")
+ plt.xlabel("X axis")
+ plt.ylabel("Y axis")
+ plt.gca()
+ `,
+ ])}
+ </example>
+
+ <example title="Data explorer">
+ ${formatCells([
+ `
+ import marimo as mo
+ import pandas as pd
+ from vega_datasets import data
+ `,
+ `
+ cars_df = data.cars()
+ mo.ui.data_explorer(cars_df)
+ `,
+ ])}
+ </example>
+
+ <example title="Multiple UI elements">
+ ${formatCells([
+ `
+ import marimo as mo
+ import pandas as pd
+ import matplotlib.pyplot as plt
+ import seaborn as sns
+ `,
+ `
+ iris = sns.load_dataset('iris')
+ `,
+ `
+ species_selector = mo.ui.dropdown(
+ options=["All"] + iris["species"].unique().tolist(),
+ value="All",
+ label="Species"
+ )
+ x_feature = mo.ui.dropdown(
+ options=iris.select_dtypes('number').columns.tolist(),
+ value="sepal_length",
+ label="X Feature"
+ )
+ y_feature = mo.ui.dropdown(
+ options=iris.select_dtypes('number').columns.tolist(),
+ value="sepal_width",
+ label="Y Feature"
+ )
+ mo.hstack([species_selector, x_feature, y_feature])
+ `,
+ `
+ filtered_data = iris if species_selector.value == "All" else iris[iris["species"] == species_selector.value]
+
+ plt.figure(figsize=(10, 6))
+ sns.scatterplot(
+ data=filtered_data,
+ x=x_feature.value,
+ y=y_feature.value,
+ hue="species"
+ )
+ plt.title(f"{y_feature.value} vs {x_feature.value}")
+ plt.gca()
+ `,
+ ])}
+ </example>
+
+ <example title="Interactive chart with Altair">
+ ${formatCells([
+ `
+ import marimo as mo
+ import altair as alt
+ import pandas as pd
+ `,
+ `# Load dataset
+ cars_df = pd.read_csv('<https://raw.githubusercontent.com/vega/vega-datasets/master/data/cars.json>')
+ _chart = alt.Chart(cars_df).mark_point().encode(
+ x='Horsepower',
+ y='Miles_per_Gallon',
+ color='Origin',
+ )
+ `,
+ "chart = mo.ui.altair_chart(_chart)\nchart",
+ `
+ # Display the selection
+ chart.value`,
+ ])}
+ </example>
+
+ <example title="Run Button Example">
+ ${formatCells([
+ "import marimo as mo",
+ `
+ first_button = mo.ui.run_button(label="Option 1")
+ second_button = mo.ui.run_button(label="Option 2")
+ [first_button, second_button]`,
+ `
+ if first_button.value:
+ print("You chose option 1!")
+ elif second_button.value:
+ print("You chose option 2!")
+ else:
+ print("Click a button!")`,
+ ])}
+ </example>
+
+ <example title="SQL with duckdb">
+ ${formatCells([
+ "import marimo as mo\nimport pandas as pd",
+ `cars_df = pd.read_csv('<https://raw.githubusercontent.com/vega/vega-datasets/master/data/cars.json>')`,
+ `_df = mo.sql("SELECT * from cars_df WHERE Miles_per_Gallon > 20")`,
+ ])}
+ </example>`;
+}
+
+function formatCells(cells: string[]) {
+ // Option 1:
+ // return cells.map((cell) => {
+ // return `# Cell ${cell}`;
+ // });
+
+ const indent = " ";
+ const indentCode = (code: string) => {
+ return code
+ .trim()
+ .split("\n")
+ .map((line) => indent + line)
+ .join("\n");
+ };
+
+ // Option 2:
+ const formatCell = (cell: string) => {
+ return `
+ @app.cell
+ def __():
+ ${indentCode(cell)}
+ return
+ `;
+ };
+
+ return cells.map(formatCell).join("");
+}
diff --git a/frontend/src/components/chat/acp/scroll-to-bottom-button.tsx b/frontend/src/components/chat/acp/scroll-to-bottom-button.tsx
new file mode 100644
index 0000000000..6fc58a960e
--- /dev/null
+++ b/frontend/src/components/chat/acp/scroll-to-bottom-button.tsx
@@ -0,0 +1,50 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { ArrowDownIcon } from "lucide-react";
+import { memo } from "react";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/utils/cn";
+
+interface ScrollToBottomButtonProps {
+ isVisible: boolean;
+ onScrollToBottom: () => void;
+ className?: string;
+}
+
+const ScrollToBottomButton = memo<ScrollToBottomButtonProps>(
+ ({ isVisible, onScrollToBottom, className }) => {
+ if (!isVisible) {
+ return null;
+ }
+
+ return (
+ <div
+ className={cn(
+ "absolute bottom-2 right-6 z-10 animate-in fade-in-0 zoom-in-95 duration-200",
+ className,
+ )}
+ >
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={onScrollToBottom}
+ className={cn(
+ "h-8 w-8 p-0 rounded-full",
+ "bg-background/90 backdrop-blur-sm",
+ "border border-border/50",
+ "shadow-md shadow-black/10",
+ "hover:bg-background hover:shadow-black/15",
+ "transition-all duration-200",
+ "focus:outline-none focus:ring-2 focus:ring-primary/50",
+ )}
+ >
+ <ArrowDownIcon className="h-4 w-4" />
+ <span className="sr-only">Scroll to bottom</span>
+ </Button>
+ </div>
+ );
+ },
+);
+ScrollToBottomButton.displayName = "ScrollToBottomButton";
+
+export default ScrollToBottomButton;
diff --git a/frontend/src/components/chat/acp/session-tabs.tsx b/frontend/src/components/chat/acp/session-tabs.tsx
new file mode 100644
index 0000000000..bdd993830c
--- /dev/null
+++ b/frontend/src/components/chat/acp/session-tabs.tsx
@@ -0,0 +1,138 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { useAtom, useSetAtom } from "jotai";
+import { XIcon } from "lucide-react";
+import React, { memo } from "react";
+import useEvent from "react-use-event-hook";
+import { AiProviderIcon } from "@/components/ai/ai-provider-icon";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/utils/cn";
+import { AgentSelector } from "./agent-selector";
+import {
+ type AgentSession,
+ agentSessionStateAtom,
+ removeSession,
+ selectedTabAtom,
+ type TabId,
+ updateSessionLastUsed,
+} from "./state";
+
+interface SessionTabProps {
+ session: AgentSession;
+ isActive: boolean;
+ onSelect: (sessionId: TabId) => void;
+ onClose: (sessionId: TabId) => void;
+}
+
+const SessionTab: React.FC<SessionTabProps> = memo(
+ ({ session, isActive, onSelect, onClose }) => {
+ return (
+ <div
+ className={cn(
+ "flex items-center gap-1 px-2 py-1 text-xs border-r border-border bg-muted/30 hover:bg-muted/50 cursor-pointer min-w-0",
+ isActive && "bg-background border-b-0 relative z-10",
+ )}
+ onClick={() => onSelect(session.tabId)}
+ >
+ <div className="flex items-center gap-1 min-w-0 flex-1">
+ <span className="text-muted-foreground text-[10px] font-medium">
+ <AiProviderIcon provider={session.agentId} className="h-3 w-3" />
+ </span>
+ <span className="truncate" title={session.title}>
+ {session.title}
+ </span>
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-4 w-4 p-0 hover:bg-destructive/20 hover:text-destructive flex-shrink-0"
+ onClick={(e) => {
+ e.stopPropagation();
+ onClose(session.tabId);
+ }}
+ >
+ <XIcon className="h-3 w-3" />
+ </Button>
+ </div>
+ );
+ },
+);
+SessionTab.displayName = "SessionTab";
+
+interface SessionTabsProps {
+ onAddSession?: () => void;
+ className?: string;
+}
+
+interface SessionListProps {
+ sessions: AgentSession[];
+ activeTabId: TabId | null;
+ onSelectSession: (sessionId: TabId) => void;
+ onCloseSession: (sessionId: TabId) => void;
+}
+
+const SessionList = memo<SessionListProps>(
+ ({ sessions, activeTabId, onSelectSession, onCloseSession }) => (
+ <div className="flex min-w-0 flex-1 overflow-x-auto">
+ {sessions.map((session) => (
+ <SessionTab
+ key={session.tabId}
+ session={session}
+ isActive={session.tabId === activeTabId}
+ onSelect={onSelectSession}
+ onClose={onCloseSession}
+ />
+ ))}
+ </div>
+ ),
+);
+SessionList.displayName = "SessionList";
+
+interface EmptySessionTabsProps {
+ className?: string;
+}
+
+const EmptySessionTabs = memo<EmptySessionTabsProps>(({ className }) => (
+ <div className={cn("flex items-center border-b bg-muted/20", className)}>
+ <AgentSelector className="h-6" />
+ </div>
+));
+EmptySessionTabs.displayName = "EmptySessionTabs";
+
+export const SessionTabs: React.FC<SessionTabsProps> = memo(({ className }) => {
+ const [sessionState, setSessionState] = useAtom(agentSessionStateAtom);
+ const setActiveSession = useSetAtom(selectedTabAtom);
+
+ const handleSelectSession = useEvent((sessionId: TabId) => {
+ setActiveSession(sessionId);
+ setSessionState((prev) => updateSessionLastUsed(prev, sessionId));
+ });
+
+ const handleCloseSession = useEvent((sessionId: TabId) => {
+ setSessionState((prev) => removeSession(prev, sessionId));
+ });
+
+ const { sessions, activeTabId } = sessionState;
+
+ if (sessions.length === 0) {
+ return <EmptySessionTabs className={className} />;
+ }
+
+ return (
+ <div
+ className={cn(
+ "flex items-center border-b bg-muted/20 overflow-hidden",
+ className,
+ )}
+ >
+ <SessionList
+ sessions={sessions}
+ activeTabId={activeTabId}
+ onSelectSession={handleSelectSession}
+ onCloseSession={handleCloseSession}
+ />
+ <AgentSelector className="h-6 flex-shrink-0" />
+ </div>
+ );
+});
+SessionTabs.displayName = "SessionTabs";
diff --git a/frontend/src/components/chat/acp/state.ts b/frontend/src/components/chat/acp/state.ts
new file mode 100644
index 0000000000..9e16328d32
--- /dev/null
+++ b/frontend/src/components/chat/acp/state.ts
@@ -0,0 +1,263 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { atom } from "jotai";
+import { atomWithStorage } from "jotai/utils";
+import { capitalize } from "lodash-es";
+import type { TypedString } from "@/utils/typed";
+import { generateUUID } from "@/utils/uuid";
+import type { ExternalAgentSessionId, SessionSupportType } from "./types";
+
+// Types
+export type TabId = TypedString<"TabId">;
+export type ExternalAgentId = "claude" | "gemini";
+
+// No agents support loading sessions, so we limit to 1, otherwise
+// this is confusing to the user when switching between sessions
+const MAX_SESSIONS = 1;
+
+export interface AgentSession {
+ tabId: TabId;
+ agentId: ExternalAgentId;
+ title: string;
+ createdAt: number;
+ lastUsedAt: number;
+ // Store the actual agent session ID for resumption
+ externalAgentSessionId: ExternalAgentSessionId | null;
+}
+
+export interface AgentSessionState {
+ sessions: AgentSession[];
+ activeTabId: TabId | null;
+}
+
+// Constants
+const STORAGE_KEY = "marimo:acp:sessions:v1";
+
+// Atoms
+export const agentSessionStateAtom = atomWithStorage<AgentSessionState>(
+ STORAGE_KEY,
+ {
+ sessions: [],
+ activeTabId: null,
+ },
+);
+
+export const selectedTabAtom = atom(
+ (get) => {
+ const state = get(agentSessionStateAtom);
+ if (!state.activeTabId) {
+ return null;
+ }
+ return (
+ state.sessions.find((session) => session.tabId === state.activeTabId) ||
+ null
+ );
+ },
+ (_get, set, activeTabId: TabId | null) => {
+ set(agentSessionStateAtom, (prev) => ({
+ ...prev,
+ activeTabId: activeTabId,
+ }));
+ },
+);
+
+// Utilities
+function generateTabId(): TabId {
+ // Our tab ID for internal session management
+ return `tab_${generateUUID()}` as TabId;
+}
+
+export function truncateTitle(title: string, maxLength = 20): string {
+ if (title.length <= maxLength) {
+ return title;
+ }
+ return `${title.slice(0, maxLength - 3)}...`;
+}
+
+export function addSession(
+ state: AgentSessionState,
+ session: {
+ agentId: ExternalAgentId;
+ firstMessage?: string;
+ },
+): AgentSessionState {
+ const sessionSupport = getAgentSessionSupport(session.agentId);
+
+ const now = Date.now();
+ const title = session.firstMessage
+ ? truncateTitle(session.firstMessage.trim())
+ : `New ${session.agentId} session`;
+ const tabId = generateTabId();
+
+ if (sessionSupport === "single") {
+ // For single session agents, replace any existing session for this agent
+ const existingSessions = state.sessions.filter(
+ (s) => s.agentId === session.agentId,
+ );
+ const otherSessions = state.sessions.filter(
+ (s) => s.agentId !== session.agentId,
+ );
+
+ if (existingSessions.length > 0) {
+ // Replace the existing session (overwrite it)
+ const existingSession = existingSessions[0];
+ const updatedSession: AgentSession = {
+ agentId: session.agentId,
+ title,
+ createdAt: now,
+ lastUsedAt: now,
+ tabId: existingSession.tabId, // Keep the same ID to maintain tab reference
+ externalAgentSessionId: null, // Clear the external session ID
+ };
+
+ return {
+ ...state,
+ sessions: [...otherSessions.slice(0, MAX_SESSIONS - 1), updatedSession],
+ activeTabId: updatedSession.tabId,
+ };
+ }
+ }
+
+ // For multiple session agents or when no existing session exists
+ return {
+ ...state,
+ sessions: [
+ ...state.sessions.slice(0, MAX_SESSIONS - 1),
+ {
+ agentId: session.agentId,
+ tabId,
+ title,
+ createdAt: now,
+ lastUsedAt: now,
+ externalAgentSessionId: null,
+ },
+ ],
+ activeTabId: tabId,
+ };
+}
+
+export function removeSession(
+ state: AgentSessionState,
+ sessionId: TabId,
+): AgentSessionState {
+ const filteredSessions = state.sessions.filter((s) => s.tabId !== sessionId);
+ const newActiveTabId =
+ state.activeTabId === sessionId
+ ? filteredSessions.length > 0
+ ? filteredSessions[filteredSessions.length - 1].tabId
+ : null
+ : state.activeTabId;
+
+ return {
+ sessions: filteredSessions,
+ activeTabId: newActiveTabId,
+ };
+}
+
+export function updateSessionTitle(
+ state: AgentSessionState,
+ title: string,
+): AgentSessionState {
+ const selectedTab = state.activeTabId;
+ if (!selectedTab) {
+ return state;
+ }
+ return {
+ ...state,
+ sessions: state.sessions.map((session) =>
+ session.tabId === selectedTab
+ ? { ...session, title: truncateTitle(title) }
+ : session,
+ ),
+ };
+}
+
+export function updateSessionLastUsed(
+ state: AgentSessionState,
+ sessionId: TabId,
+): AgentSessionState {
+ return {
+ ...state,
+ sessions: state.sessions.map((session) =>
+ session.tabId === sessionId
+ ? { ...session, lastUsedAt: Date.now() }
+ : session,
+ ),
+ };
+}
+
+/**
+ * Update the sessionId for the current;y selected tab
+ */
+export function updateSessionExternalAgentSessionId(
+ state: AgentSessionState,
+ externalAgentSessionId: ExternalAgentSessionId,
+): AgentSessionState {
+ const selectedTab = state.activeTabId;
+ if (!selectedTab) {
+ return state;
+ }
+ return {
+ ...state,
+ sessions: state.sessions.map((session) =>
+ session.tabId === selectedTab
+ ? { ...session, externalAgentSessionId, lastUsedAt: Date.now() }
+ : session,
+ ),
+ };
+}
+
+export function getSessionsByAgent(
+ sessions: AgentSession[],
+ agentId: ExternalAgentId,
+): AgentSession[] {
+ return sessions
+ .filter((session) => session.agentId === agentId)
+ .sort((a, b) => b.lastUsedAt - a.lastUsedAt);
+}
+
+export function getAllAgentIds(): ExternalAgentId[] {
+ return ["claude", "gemini"];
+}
+
+export function getAgentDisplayName(agentId: ExternalAgentId): string {
+ return capitalize(agentId);
+}
+
+export function getAgentWebSocketUrl(agentId: ExternalAgentId): string {
+ return AGENT_CONFIG[agentId].webSocketUrl;
+}
+
+interface AgentConfig {
+ port: number;
+ command: string;
+ webSocketUrl: string;
+ sessionSupport: SessionSupportType;
+}
+
+const AGENT_CONFIG: Record<ExternalAgentId, AgentConfig> = {
+ claude: {
+ port: 3017,
+ command: "npx @zed-industries/claude-code-acp",
+ webSocketUrl: "ws://localhost:3017/message",
+ sessionSupport: "single",
+ },
+ gemini: {
+ port: 3019,
+ command: "npx @google/gemini-cli --experimental-acp",
+ webSocketUrl: "ws://localhost:3019/message",
+ sessionSupport: "single",
+ },
+};
+
+export function getAgentSessionSupport(
+ agentId: ExternalAgentId,
+): SessionSupportType {
+ return AGENT_CONFIG[agentId].sessionSupport;
+}
+
+export function getAgentConnectionCommand(agentId: ExternalAgentId): string {
+ const port = AGENT_CONFIG[agentId].port;
+ const command = AGENT_CONFIG[agentId].command;
+ return `npx supergateway --stdio\\\n "${command}" \\\n --outputTransport ws --port ${port} `;
+}
diff --git a/frontend/src/components/chat/acp/thread.tsx b/frontend/src/components/chat/acp/thread.tsx
new file mode 100644
index 0000000000..8dd9f1bc67
--- /dev/null
+++ b/frontend/src/components/chat/acp/thread.tsx
@@ -0,0 +1,121 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import React from "react";
+import { groupNotifications } from "use-acp";
+import {
+ ConnectionChangeBlock,
+ ErrorBlock,
+ SessionNotificationsBlock,
+} from "./blocks";
+
+type NotificationEvent = Awaited<
+ ReturnType<typeof groupNotifications>
+>[number][number];
+
+interface AgentThreadProps {
+ notifications: NotificationEvent[];
+ isConnected: boolean;
+ onRetryConnection?: () => void;
+ onRetryLastAction?: () => void;
+ onDismissError?: (errorId: string) => void;
+}
+
+export const AgentThread = ({
+ notifications,
+ isConnected,
+ onRetryConnection,
+ onRetryLastAction,
+ onDismissError,
+}: AgentThreadProps) => {
+ let combinedNotifications = groupNotifications(notifications);
+
+ // Filter out all connection changes unless it is the last one
+ combinedNotifications = combinedNotifications.filter((group, index) => {
+ const isLast = index === combinedNotifications.length - 1;
+ if (isLast) {
+ return true;
+ }
+ if (isConnectionChangeGroup(group)) {
+ return false;
+ }
+ return true;
+ });
+
+ const renderNotification = (group: NotificationEvent[]) => {
+ if (group.length === 0) {
+ return null;
+ }
+
+ if (isErrorGroup(group)) {
+ const lastError = group[group.length - 1];
+ return (
+ <ErrorBlock
+ key={lastError.id}
+ data={lastError.data}
+ onRetry={onRetryLastAction}
+ onDismiss={
+ onDismissError ? () => onDismissError(lastError.id) : undefined
+ }
+ />
+ );
+ }
+ if (isConnectionChangeGroup(group)) {
+ const lastConnectionChange = group[group.length - 1];
+ return (
+ <ConnectionChangeBlock
+ key={lastConnectionChange.id}
+ data={lastConnectionChange.data}
+ isConnected={isConnected}
+ onRetry={onRetryConnection}
+ timestamp={lastConnectionChange.timestamp}
+ />
+ );
+ }
+ if (isSessionNotificationGroup(group)) {
+ const startTimestamp = group[0].timestamp;
+ const endTimestamp = group[group.length - 1].timestamp;
+ const data = group.map((item) => item.data.update);
+ return (
+ <SessionNotificationsBlock
+ data={data}
+ startTimestamp={startTimestamp}
+ endTimestamp={endTimestamp}
+ />
+ );
+ }
+ return "Unknown notification type";
+ };
+
+ return (
+ <div className="flex flex-col gap-4 px-2 pb-10">
+ {combinedNotifications.map((notification) => (
+ <React.Fragment key={notification[0].id}>
+ {renderNotification(notification)}
+ </React.Fragment>
+ ))}
+ </div>
+ );
+};
+
+function isErrorGroup(
+ group: NotificationEvent[],
+): group is Array<Extract<NotificationEvent, { type: "error" }>> {
+ // We only check the first since we know the group is the same type
+ return group[0].type === "error";
+}
+
+function isConnectionChangeGroup(
+ group: NotificationEvent[],
+): group is Array<Extract<NotificationEvent, { type: "connection_change" }>> {
+ // We only check the first since we know the group is the same type
+ return group[0].type === "connection_change";
+}
+
+function isSessionNotificationGroup(
+ group: NotificationEvent[],
+): group is Array<
+ Extract<NotificationEvent, { type: "session_notification" }>
+> {
+ // We only check the first since we know the group is the same type
+ return group[0].type === "session_notification";
+}
diff --git a/frontend/src/components/chat/acp/types.ts b/frontend/src/components/chat/acp/types.ts
new file mode 100644
index 0000000000..9bfdfa0340
--- /dev/null
+++ b/frontend/src/components/chat/acp/types.ts
@@ -0,0 +1,63 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import type { ContentBlock } from "@zed-industries/agent-client-protocol";
+import type { groupNotifications, useAcpClient } from "use-acp";
+
+export type NotificationEvent = Awaited<
+ ReturnType<typeof groupNotifications>
+>[number][number];
+
+export type AgentConnectionState = ReturnType<
+ typeof useAcpClient
+>["connectionState"];
+
+export type AgentPendingPermission = ReturnType<
+ typeof useAcpClient
+>["pendingPermission"];
+
+// Notification events
+
+export type ErrorNotificationEvent = Extract<
+ NotificationEvent,
+ { type: "error" }
+>;
+export type ConnectionChangeNotificationEvent = Extract<
+ NotificationEvent,
+ { type: "connection_change" }
+>;
+export type SessionNotificationEvent = Extract<
+ NotificationEvent,
+ { type: "session_notification" }
+>;
+
+// Session notification events
+
+export type SessionNotificationEventData =
+ SessionNotificationEvent["data"]["update"];
+export type SessionNotificationEventType =
+ SessionNotificationEventData["sessionUpdate"];
+
+export type NotificationDataOf<T extends SessionNotificationEventType> =
+ Extract<SessionNotificationEventData, { sessionUpdate: T }>;
+
+// Session notification event data
+
+export type UserNotificationEvent = NotificationDataOf<"user_message_chunk">;
+export type AgentNotificationEvent = NotificationDataOf<"agent_message_chunk">;
+export type AgentThoughtNotificationEvent =
+ NotificationDataOf<"agent_thought_chunk">;
+export type ToolCallNotificationEvent = NotificationDataOf<"tool_call">;
+export type ToolCallUpdateNotificationEvent =
+ NotificationDataOf<"tool_call_update">;
+export type PlanNotificationEvent = NotificationDataOf<"plan">;
+
+export type ContentBlockType = ContentBlock["type"];
+export type ContentBlockOf<T extends ContentBlockType> = Extract<
+ ContentBlock,
+ { type: T }
+>;
+
+// Agent session support types
+export type SessionSupportType = "single" | "multiple";
+export type ExternalAgentSessionId = NonNullable<
+ ReturnType<typeof useAcpClient>["activeSessionId"]
+>;
diff --git a/frontend/src/components/chat/acp/utils.ts b/frontend/src/components/chat/acp/utils.ts
new file mode 100644
index 0000000000..609563a2bf
--- /dev/null
+++ b/frontend/src/components/chat/acp/utils.ts
@@ -0,0 +1,45 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import type { NotificationDataOf, SessionNotificationEventData } from "./types";
+
+export function isToolCalls(
+ group: SessionNotificationEventData[],
+): group is Array<NotificationDataOf<"tool_call" | "tool_call_update">> {
+ // We only check the first since we know the group is the same type
+ const first = group[0];
+ return (
+ first.sessionUpdate === "tool_call" ||
+ first.sessionUpdate === "tool_call_update"
+ );
+}
+
+export function isAgentThoughts(
+ group: SessionNotificationEventData[],
+): group is Array<NotificationDataOf<"agent_thought_chunk">> {
+ // We only check the first since we know the group is the same type
+ const first = group[0];
+ return first.sessionUpdate === "agent_thought_chunk";
+}
+
+export function isUserMessages(
+ group: SessionNotificationEventData[],
+): group is Array<NotificationDataOf<"user_message_chunk">> {
+ // We only check the first since we know the group is the same type
+ const first = group[0];
+ return first.sessionUpdate === "user_message_chunk";
+}
+
+export function isAgentMessages(
+ group: SessionNotificationEventData[],
+): group is Array<NotificationDataOf<"agent_message_chunk">> {
+ // We only check the first since we know the group is the same type
+ const first = group[0];
+ return first.sessionUpdate === "agent_message_chunk";
+}
+
+export function isPlans(
+ group: SessionNotificationEventData[],
+): group is Array<NotificationDataOf<"plan">> {
+ // We only check the first since we know the group is the same type
+ const first = group[0];
+ return first.sessionUpdate === "plan";
+}
diff --git a/frontend/src/components/chat/tool-call-accordion.tsx b/frontend/src/components/chat/tool-call-accordion.tsx
index f41706c8d7..87cb20e3af 100644
--- a/frontend/src/components/chat/tool-call-accordion.tsx
+++ b/frontend/src/components/chat/tool-call-accordion.tsx
@@ -65,7 +65,7 @@ export const ToolCallAccordion: React.FC<ToolCallAccordionProps> = ({
key={`tool-${index}`}
type="single"
collapsible={true}
- className="w-full my-4"
+ className="w-full"
>
<AccordionItem value="tool-call" className="border-0">
<AccordionTrigger
diff --git a/frontend/src/components/editor/chrome/types.ts b/frontend/src/components/editor/chrome/types.ts
index 97436b6fd6..615ae28342 100644
--- a/frontend/src/components/editor/chrome/types.ts
+++ b/frontend/src/components/editor/chrome/types.ts
@@ -8,6 +8,7 @@ import {
FileTextIcon,
FolderTreeIcon,
FunctionSquareIcon,
+ HatGlassesIcon,
KeyRoundIcon,
type LucideIcon,
NetworkIcon,
@@ -17,6 +18,7 @@ import {
TextSearchIcon,
XCircleIcon,
} from "lucide-react";
+import { getFeatureFlag } from "@/core/config/feature-flag";
import { isWasm } from "@/core/wasm/utils";
export type PanelType =
@@ -32,6 +34,7 @@ export type PanelType =
| "datasources"
| "scratchpad"
| "chat"
+ | "agents"
| "secrets"
| "logs";
@@ -86,6 +89,13 @@ export const PANELS: PanelDescriptor[] = [
tooltip: "Chat with AI",
position: "sidebar",
},
+ {
+ type: "agents",
+ Icon: HatGlassesIcon,
+ tooltip: "Agents",
+ position: "sidebar",
+ hidden: !getFeatureFlag("external_agents"),
+ },
{
type: "documentation",
Icon: TextSearchIcon,
diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
index fc09126591..6e38debf3e 100644
--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
@@ -1,5 +1,10 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import React, { type PropsWithChildren, Suspense, useEffect } from "react";
+import React, {
+ type PropsWithChildren,
+ Suspense,
+ useEffect,
+ useId,
+} from "react";
import {
type ImperativePanelHandle,
Panel,
@@ -25,6 +30,9 @@ import { handleDragging } from "./utils";
const LazyTerminal = React.lazy(() => import("@/components/terminal/terminal"));
const LazyChatPanel = React.lazy(() => import("@/components/chat/chat-panel"));
+const LazyAgentPanel = React.lazy(
+ () => import("@/components/chat/acp/agent-panel"),
+);
const LazyDependencyGraphPanel = React.lazy(
() => import("@/components/editor/chrome/panels/dependency-graph-panel"),
);
@@ -55,6 +63,9 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
const sidebarRef = React.useRef<ImperativePanelHandle>(null);
const terminalRef = React.useRef<ImperativePanelHandle>(null);
+ const helperPanelId = useId();
+ const terminalPanelId = useId();
+
// sync sidebar
useEffect(() => {
if (!sidebarRef.current) {
@@ -161,6 +172,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
{selectedPanel === "snippets" && <LazySnippetsPanel />}
{selectedPanel === "scratchpad" && <LazyScratchpadPanel />}
{selectedPanel === "chat" && <LazyChatPanel />}
+ {selectedPanel === "agents" && <LazyAgentPanel />}
{selectedPanel === "logs" && <LazyLogsPanel />}
{selectedPanel === "tracing" && <LazyTracingPanel />}
{selectedPanel === "secrets" && <LazySecretsPanel />}
@@ -173,7 +185,8 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
const helperPanel = (
<Panel
ref={sidebarRef}
- id="helper"
+ id={`helper-${helperPanelId}`}
+ data-testid="helper"
key={"helper"}
collapsedSize={0}
collapsible={true}
@@ -203,7 +216,8 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
const terminalPanel = (
<Panel
ref={terminalRef}
- id="terminal"
+ id={`terminal-${terminalPanelId}`}
+ data-testid="terminal"
key={"terminal"}
collapsedSize={0}
collapsible={true}
diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsx
index c2c08a3274..c32b14d346 100644
--- a/frontend/src/core/config/feature-flag.tsx
+++ b/frontend/src/core/config/feature-flag.tsx
@@ -13,6 +13,7 @@ export interface ExperimentalFeatures {
performant_table_charts: boolean;
mcp_docs: boolean;
sql_linter: boolean;
+ external_agents: boolean;
// Add new feature flags here
}
@@ -24,6 +25,7 @@ const defaultValues: ExperimentalFeatures = {
performant_table_charts: false,
mcp_docs: false,
sql_linter: false,
+ external_agents: import.meta.env.DEV,
};
export function getFeatureFlag<T extends keyof ExperimentalFeatures>(
diff --git a/frontend/src/utils/Logger.ts b/frontend/src/utils/Logger.ts
index 27bd5a0322..5ae4fefe8d 100644
--- a/frontend/src/utils/Logger.ts
+++ b/frontend/src/utils/Logger.ts
@@ -25,13 +25,13 @@ const createNamespacedLogger = (
): ILogger => {
const prefix = `[${namespace}]`;
return {
- debug: (...args) => baseLogger.debug(prefix, ...args),
+ debug: (...args) => console.debug(prefix, ...args),
log: (...args) => baseLogger.log(prefix, ...args),
warn: (...args) => baseLogger.warn(prefix, ...args),
error: (...args) => baseLogger.error(prefix, ...args),
trace: (...args) => baseLogger.trace(prefix, ...args),
get: (subNamespace: string) =>
- createNamespacedLogger(`${namespace}.${subNamespace}`, baseLogger),
+ createNamespacedLogger(`${namespace}:${subNamespace}`, baseLogger),
disabled: (disabled = true) => {
if (disabled) {
return DisabledLogger;
@@ -46,9 +46,7 @@ const createNamespacedLogger = (
*/
const ConsoleLogger: ILogger = {
debug: (...args) => {
- if (process.env.NODE_ENV !== "production") {
- console.debug(...args);
- }
+ console.debug(...args);
},
log: (...args) => {
console.log(...args);
@@ -62,7 +60,8 @@ const ConsoleLogger: ILogger = {
trace: (...args) => {
console.trace(...args);
},
- get: (namespace: string) => createNamespacedLogger(namespace, ConsoleLogger),
+ get: (namespace: string) =>
+ createNamespacedLogger(`marimo:${namespace}`, ConsoleLogger),
disabled: (disabled = true) => {
if (disabled) {
return DisabledLogger;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a1528b0549..b1160153ae 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -286,6 +286,9 @@ importers:
'@xterm/xterm':
specifier: ^5.5.0
version: 5.5.0
+ '@zed-industries/agent-client-protocol':
+ specifier: ^0.1.2
+ version: 0.1.2
ai:
specifier: ^5.0.30
version: 5.0.30([email protected])
@@ -430,6 +433,9 @@ importers:
sql-formatter:
specifier: ^15.6.6
version: 15.6.6
+ streamdown:
+ specifier: ^1.2.0
+ version: 1.2.0(@types/[email protected])([email protected])
string-dedent:
specifier: ^3.0.2
version: 3.0.2
@@ -451,6 +457,9 @@ importers:
typescript-memoize:
specifier: ^1.1.1
version: 1.1.1
+ use-acp:
+ specifier: ^0.1.5
use-resize-observer:
specifier: ^9.1.0
@@ -3355,6 +3364,27 @@ packages:
cpu: [x64]
os: [win32]
+ '@shikijs/[email protected]':
+ resolution: {integrity: sha512-L1Safnhra3tX/oJK5kYHaWmLEBJi1irASwewzY3taX5ibyXyMkkSDZlq01qigjryOBwrXSdFgTiZ3ryzSNeu7Q==}
+
+ '@shikijs/[email protected]':
+ resolution: {integrity: sha512-Nm3/azSsaVS7hk6EwtHEnTythjQfwvrO5tKqMlaH9TwG1P+PNaR8M0EAKZ+GaH2DFwvcr4iSfTveyxMIvXEHMw==}
+
+ '@shikijs/[email protected]':
+ resolution: {integrity: sha512-hozwnFHsLvujK4/CPVHNo3Bcg2EsnG8krI/ZQ2FlBlCRpPZW4XAEQmEwqegJsypsTAN9ehu2tEYe30lYKSZW/w==}
+
+ '@shikijs/[email protected]':
+ resolution: {integrity: sha512-bVx5PfuZHDSHoBal+KzJZGheFuyH4qwwcwG/n+MsWno5cTlKmaNtTsGzJpHYQ8YPbB5BdEdKU1rga5/6JGY8ww==}
+
+ '@shikijs/[email protected]':
+ resolution: {integrity: sha512-fTR3QAgnwYpfGczpIbzPjlRnxyONJOerguQv1iwpyQZ9QXX4qy/XFQqXlf17XTsorxnHoJGbH/LXBvwtqDsF5A==}
+
+ '@shikijs/[email protected]':
+ resolution: {integrity: sha512-K5UIBzxCyv0YoxN3LMrKB9zuhp1bV+LgewxuVwHdl4Gz5oePoUFrr9EfgJlGlDeXCU1b/yhdnXeuRvAnz8HN8Q==}
+
+ '@shikijs/[email protected]':
+ resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==}
+
'@sinclair/[email protected]':
resolution: {integrity: sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==}
@@ -4204,6 +4234,9 @@ packages:
resolution: {integrity: sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==}
+ '@zed-industries/[email protected]':
+ resolution: {integrity: sha512-A1RCN7Uf09vngbhBVLiZENenKYOYD2OGiILLGXPaSBloDbem8xmLaDmrKQuYl0kjLJ1DcWmVaHUv97n1l5vJ6w==}
+
resolution: {integrity: sha512-d8XPSGjfyzlXC3Xx891DJRyZfqk5JU0BJrDQcsWomFIV1/BIzPW5HDH5iDdWpqWaav0YVIEzT1RHTwWr0FFshA==}
@@ -6051,6 +6084,12 @@ packages:
engines: {node: '>=6'}
deprecated: this library is no longer supported
+ resolution: {integrity: sha512-uN+PdsmySN4gdczqM0DXzltS4dELSO4U/p/QVLiiypyZMBR1CaewgQTI7ZxArFazBoCk7lGRVvYsyxos0VHGNg==}
+ peerDependencies:
+ react: '>=16.8.0'
+ react-markdown: '>=9.0.0'
+
resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==}
engines: {node: '>= 0.4'}
@@ -6088,12 +6127,39 @@ packages:
resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-N+LqofjR2zuzTjCPzyDUdSshy4Ma6li7p/c3pA78uTwzFgENbgbUrm2ugwsOdcjI1muO+o6Dgzp9p8WHtn/39Q==}
+
+ resolution: {integrity: sha512-zJfpXq44yff2hmE0XmwEOzdWin5xwH+QIhMLOScpX91e/NSGPsAzNCvLQDIEPyO2TXi+lBmU6hjLIhV8MwP2kw==}
+
+ resolution: {integrity: sha512-CUSRHXyKjzHov8yKsQjGOElXy/3EKpyX56ELnkHH34vDVw1N1XSQ1ZcAvTyAPtGqLTuKP/uxM+aLkSPqF/EtMw==}
+
+ resolution: {integrity: sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==}
+
+ resolution: {integrity: sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g==}
+
+ resolution: {integrity: sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==}
+
+ resolution: {integrity: sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==}
+
resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}
+ resolution: {integrity: sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A==}
+
resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}
+ resolution: {integrity: sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==}
+
resolution: {integrity: sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ==}
@@ -6147,6 +6213,9 @@ packages:
resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
+ resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}
+
resolution: {integrity: sha512-TwAZM+zE5Tq3lrEHvOlvwgj1XLWQCtaaibSN11Q+gGBAS7Y1uZSWwXXRe4iF6OXnaq1riyQAPFOBtYc77Mxq0g==}
@@ -6881,6 +6950,11 @@ packages:
engines: {node: '>= 18'}
hasBin: true
+ resolution: {integrity: sha512-r3UrXED9lMlHF97jJByry90cwrZBBvZmjG1L68oYfuPMW+uDTnuMbyJDymCWwbTE+f+3LhpNDKfpR3a3saFyjA==}
+ engines: {node: '>= 20'}
+ hasBin: true
+
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
engines: {node: '>= 0.4'}
@@ -6916,6 +6990,9 @@ packages:
resolution: {integrity: sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==}
+ resolution: {integrity: sha512-Tl9GBNeG/AhJnQM221bJR2HPvLOSnLE/T9cJI9tlc6zwQk2nPk/4f0cHkOdEixQPC/j8UtKDdITswvLAy1OZ1w==}
+
resolution: {integrity: sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==}
@@ -6999,6 +7076,9 @@ packages:
resolution: {integrity: sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==}
+ resolution: {integrity: sha512-lvEqd+fHjATVs+2v/8kg9i5Q0AP2k85H0WUOwpIVvUML8BapsMvh1XAogmQjOCsLpoKRCVQqEkQBB3NhVBcsOg==}
+
resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==}
@@ -7287,6 +7367,12 @@ packages:
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
+ resolution: {integrity: sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w==}
+
+ resolution: {integrity: sha512-rPiZhzC3wXwE59YQMRDodUwwT9FZ9nNBwQQfsd1wfdtlKEyCdRV0avrTcSZ5xlIvGRVPd/cx6ZN45ECmS39xvg==}
+
resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==}
engines: {node: '>=12'}
@@ -8006,6 +8092,12 @@ packages:
resolution: {integrity: sha512-Oe56aUPnkHyyDxxkvqtd7KkdQP5uIUfHxd5XTb3wE9d/kRnZLmKbDB0GWk919tdQ+mxxPtG6EAs6RMT6i1qtHg==}
+ resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==}
+ peerDependencies:
+ '@types/react': '>=18'
+ react: '>=18'
+
resolution: {integrity: sha512-xaijuJB0kzGiUdG7nc2MOMDUDBWPyGAjZtUrow9XxUeua8IqeP+VlIfAZ3bphpcLTnSZXz6z9jcVC/TCwbfgdw==}
peerDependencies:
@@ -8169,6 +8261,15 @@ packages:
resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==}
+
+ resolution: {integrity: sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==}
+
+ resolution: {integrity: sha512-uorlqlzAKjKQZ5P+kTJr3eeJGSVroLKoHmquUj4zHWuR+hEyNqlXsSKlYYF5F4NI6nl7tWCs0apKJ0lmfsXAPA==}
+
resolution: {integrity: sha512-iETxpjK6YoRWJG5o6hXLwvjYAoW+FEZn9os0PD/b6AP6xQwsa/Y7lCVgIixBbUPMfhu+i2LtdeAqVTgGlQarfA==}
hasBin: true
@@ -8196,9 +8297,15 @@ packages:
resolution: {integrity: sha512-+IOGrxl3FZ8ZM9ixCWQZzFRiRn7Rzn9bu3iFHwg/yz4tlOUQgbO4PHLgG+1ZT60zcIV8tief6Qrmyl8qcoJP0g==}
+ resolution: {integrity: sha512-OiM2wrZ/wuhKkigASodFoo8wimG3H12LWQaH8qSPVJn9apWKFSH3YOCtbKpBorTVw/eI7cuT21XBbvwEswbIOA==}
+
resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}
+ resolution: {integrity: sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA==}
+
resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}
@@ -8398,6 +8505,9 @@ packages:
resolution: {integrity: sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-uIrKI+f9IPz1zDT+GMz+0RjzKJiijVr6WDWm9Pe3NNY6QigKCfifCEv9v9R2mDASKKjzjQ2QpFLcxaR3iHSnMA==}
+
resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==}
engines: {node: '>= 0.4'}
@@ -8524,6 +8634,11 @@ packages:
resolution: {integrity: sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==}
+ resolution: {integrity: sha512-FBRV8mXgFQx+MbLgVKjEpGzlmm5H/3VDh7mebd9g9xSOnqi1UyrqR4na917jecTcCCNQuyRPTRPIB9DH5X8pDg==}
+ peerDependencies:
+ react: ^18.0.0 || ^19.0.0
+
resolution: {integrity: sha512-Nk/brWYpD85WlOgzw5h173aci0Teyv8YdIAEtV+N88nDB0dLlazZyJMIsN6eo1/AR61l+p6CJTG1JIyFaoNEEA==}
@@ -8740,6 +8855,9 @@ packages:
resolution: {integrity: sha512-P+Vu1qXfzediirmHOC3xKGAYeZtPcV9g76X+xg2FD4tYgR71ewMA35Y3sCz3zhiN/dwefRpJX0yBcgwi1fXNQA==}
+ resolution: {integrity: sha512-gBXpgUm/3rp1lMZZrM/w7D8GKqshif0zAymAhbCyIt8KMe+0v9DQ7cdYLR4FHH/cKpdTXb+A/tKKU3eolfsI+g==}
+
resolution: {integrity: sha512-bl6mpH3T7I3UFxuvDEXLxy/VuFxBk5bbzplh7tXI68mwMokNYd1t9qPBHlnyTwfa4JGC4zP516I1hYYtQ/vspA==}
peerDependencies:
@@ -9122,12 +9240,18 @@ packages:
resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}
+ resolution: {integrity: sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==}
+
resolution: {integrity: sha512-2qCTHimwdxLfz+YzdGfkqNlH0tLi9xjTnHddPmJwtIG9MGsdbutfTc4P+haPD7l7Cjxf/WZj+we5qfVPvvxfYw==}
resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}
+ resolution: {integrity: sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==}
+
resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}
@@ -9173,6 +9297,12 @@ packages:
resolution: {integrity: sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==}
+ resolution: {integrity: sha512-PmsjtVOLtMeuCYp/8zt9CiQ7kuS8p4Umq2cANXvAMcLFuVxxD8Z3FyMKhjuUS49s9a/gDtvXtrpPs/E+VrYyuQ==}
+ peerDependencies:
+ react: ^19
+ react-dom: ^19
+
resolution: {integrity: sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==}
engines: {node: '>=10'}
@@ -9367,6 +9497,9 @@ packages:
resolution: {integrity: sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==}
engines: {'0': node >=0.6.0}
+ resolution: {integrity: sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==}
+
resolution: {integrity: sha512-jRDZ1IMLttGj41KcZvlrYAaI3CfqpLpfpf+Mfig13viT6NKvRzWZ+lXz0Y5D60w6uJIBAOGq9mSHf0gktF0duw==}
@@ -9516,6 +9649,9 @@ packages:
resolution: {integrity: sha512-lNR9aAefbGPpHO7AEnY0hCFjz1eTkWCXYvkTRrTHs9qv8zJp+SkVYpzfLIFXQQiG3tVvbNFQgVg2bQS8YGgxyw==}
+ resolution: {integrity: sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==}
+
resolution: {integrity: sha512-r4DIlprAGwJ7YM11VZp4R884m0Vmgr6EAKe3P+kO0PPj3Unqyvv59rczf6UiGcb9Z8QxZVcqKNwv/g0WNdWwsw==}
@@ -9794,6 +9930,24 @@ packages:
react:
optional: true
+ resolution: {integrity: sha512-gyPKpIaxY9XcO2vSMrLbiER7QMAMGOQZVRdJ6Zi782jkbzZygq5GI9nG8g+sMgitRtndwaBSl7uiqC49o1SSiw==}
+ engines: {node: '>=12.20.0'}
+ peerDependencies:
+ '@types/react': '>=18.0.0'
+ immer: '>=9.0.6'
+ react: '>=18.0.0'
+ use-sync-external-store: '>=1.2.0'
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ immer:
+ optional: true
+ react:
+ optional: true
+ use-sync-external-store:
+ optional: true
+
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
@@ -13278,6 +13432,39 @@ snapshots:
'@rollup/[email protected]':
optional: true
+ '@shikijs/[email protected]':
+ dependencies:
+ '@shikijs/types': 3.12.2
+ '@shikijs/vscode-textmate': 10.0.2
+ '@types/hast': 3.0.4
+ hast-util-to-html: 9.0.5
+
+ '@shikijs/[email protected]':
+ dependencies:
+ '@shikijs/types': 3.12.2
+ '@shikijs/vscode-textmate': 10.0.2
+ oniguruma-to-es: 4.3.3
+
+ '@shikijs/[email protected]':
+ dependencies:
+ '@shikijs/types': 3.12.2
+ '@shikijs/vscode-textmate': 10.0.2
+
+ '@shikijs/[email protected]':
+ dependencies:
+ '@shikijs/types': 3.12.2
+
+ '@shikijs/[email protected]':
+ dependencies:
+ '@shikijs/types': 3.12.2
+
+ '@shikijs/[email protected]':
+ dependencies:
+ '@shikijs/vscode-textmate': 10.0.2
+ '@types/hast': 3.0.4
+
+ '@shikijs/[email protected]': {}
+
'@sinclair/[email protected]': {}
'@sourcegraph/[email protected]':
@@ -14268,6 +14455,10 @@ snapshots:
'@xtuc/[email protected]': {}
+ '@zed-industries/[email protected]':
+ dependencies:
+ zod: 3.25.76
+
@@ -16427,6 +16618,11 @@ snapshots:
ajv: 6.12.6
har-schema: 2.0.0
+ dependencies:
+ react: 19.1.1
+ react-markdown: 10.1.0(@types/[email protected])([email protected])
+
@@ -16459,6 +16655,61 @@ snapshots:
dependencies:
function-bind: 1.1.2
+ dependencies:
+ '@types/hast': 3.0.4
+ hastscript: 9.0.1
+ web-namespaces: 2.0.1
+
+ dependencies:
+ '@types/hast': 3.0.4
+ hast-util-from-dom: 5.0.1
+ hast-util-from-html: 2.0.3
+ unist-util-remove-position: 5.0.0
+
+ dependencies:
+ '@types/hast': 3.0.4
+ devlop: 1.1.0
+ hast-util-from-parse5: 8.0.3
+ parse5: 7.3.0
+ vfile: 6.0.3
+ vfile-message: 4.0.2
+
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/unist': 3.0.3
+ devlop: 1.1.0
+ hastscript: 9.0.1
+ property-information: 7.1.0
+ vfile: 6.0.3
+ vfile-location: 5.0.3
+ web-namespaces: 2.0.1
+
+ dependencies:
+ '@types/hast': 3.0.4
+
+ dependencies:
+ '@types/hast': 3.0.4
+
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/unist': 3.0.3
+ ccount: 2.0.1
+ comma-separated-tokens: 2.0.3
+ hast-util-whitespace: 3.0.0
+ html-void-elements: 3.0.0
+ mdast-util-to-hast: 13.2.0
+ property-information: 7.1.0
+ space-separated-tokens: 2.0.2
+ stringify-entities: 4.0.4
+ zwitch: 2.0.4
+
dependencies:
'@types/estree': 1.0.8
@@ -16479,10 +16730,25 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/unist': 3.0.3
+ hast-util-is-element: 3.0.0
+ unist-util-find-after: 5.0.0
+
dependencies:
'@types/hast': 3.0.4
+ dependencies:
+ '@types/hast': 3.0.4
+ comma-separated-tokens: 2.0.3
+ hast-util-parse-selector: 4.0.0
+ property-information: 7.1.0
+ space-separated-tokens: 2.0.2
+
@@ -16530,6 +16796,8 @@ snapshots:
+
dependencies:
domelementtype: 2.3.0
@@ -17243,6 +17511,8 @@ snapshots:
+
@@ -17330,6 +17600,18 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ longest-streak: 3.1.0
+ mdast-util-from-markdown: 2.0.2
+ mdast-util-to-markdown: 2.1.2
+ unist-util-remove-position: 5.0.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@types/estree-jsx': 1.0.5
@@ -17526,6 +17808,16 @@ snapshots:
micromark-util-combine-extensions: 2.0.1
micromark-util-types: 2.0.2
+ dependencies:
+ '@types/katex': 0.16.7
+ devlop: 1.1.0
+ katex: 0.16.22
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
dependencies:
micromark-util-character: 2.1.1
@@ -17879,6 +18171,14 @@ snapshots:
dependencies:
wrappy: 1.0.2
+
+ dependencies:
+ oniguruma-parser: 0.12.1
+ regex: 6.0.1
+ regex-recursion: 6.0.2
+
dependencies:
define-lazy-prop: 2.0.0
@@ -18714,6 +19014,24 @@ snapshots:
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ '@types/react': 19.1.12
+ devlop: 1.1.0
+ hast-util-to-jsx-runtime: 2.3.6
+ html-url-attributes: 3.0.1
+ mdast-util-to-hast: 13.2.0
+ react: 19.1.1
+ remark-parse: 11.0.0
+ remark-rehype: 11.1.2
+ unified: 11.0.5
+ unist-util-visit: 5.0.0
+ vfile: 6.0.3
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@types/hast': 3.0.4
@@ -18952,6 +19270,16 @@ snapshots:
get-proto: 1.0.1
which-builtin-type: 1.2.1
+ dependencies:
+ regex-utilities: 2.3.0
+
+
+ dependencies:
+ regex-utilities: 2.3.0
+
@@ -19022,6 +19350,16 @@ snapshots:
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/katex': 0.16.7
+ hast-util-from-html-isomorphic: 2.0.0
+ hast-util-to-text: 4.0.2
+ katex: 0.16.22
+ unist-util-visit-parents: 6.0.1
+ vfile: 6.0.3
+
dependencies:
'@types/mdast': 4.0.4
@@ -19033,6 +19371,15 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-math: 3.0.0
+ micromark-extension-math: 3.1.0
+ unified: 11.0.5
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@types/mdast': 4.0.4
@@ -19300,6 +19647,17 @@ snapshots:
+ dependencies:
+ '@shikijs/core': 3.12.2
+ '@shikijs/engine-javascript': 3.12.2
+ '@shikijs/engine-oniguruma': 3.12.2
+ '@shikijs/langs': 3.12.2
+ '@shikijs/themes': 3.12.2
+ '@shikijs/types': 3.12.2
+ '@shikijs/vscode-textmate': 10.0.2
+ '@types/hast': 3.0.4
+
dependencies:
es-errors: 1.3.0
@@ -19463,6 +19821,25 @@ snapshots:
+ dependencies:
+ clsx: 2.1.1
+ katex: 0.16.22
+ lucide-react: 0.542.0([email protected])
+ marked: 16.2.1
+ mermaid: 11.11.0
+ react: 19.1.1
+ react-markdown: 10.1.0(@types/[email protected])([email protected])
+ rehype-katex: 7.0.1
+ remark-gfm: 4.0.1
+ remark-math: 6.0.0
+ shiki: 3.12.2
+ tailwind-merge: 3.3.1
+ transitivePeerDependencies:
+ - '@types/react'
+ - supports-color
+
@@ -19760,6 +20137,8 @@ snapshots:
+
dependencies:
tailwindcss: 4.1.13
@@ -20128,6 +20507,11 @@ snapshots:
trough: 2.2.0
vfile: 6.0.3
+ dependencies:
+ '@types/unist': 3.0.3
+ unist-util-is: 6.0.0
+
dependencies:
'@types/unist': 3.0.3
@@ -20136,6 +20520,11 @@ snapshots:
dependencies:
'@types/unist': 3.0.3
+ dependencies:
+ '@types/unist': 3.0.3
+ unist-util-visit: 5.0.0
+
dependencies:
'@types/unist': 3.0.3
@@ -20183,6 +20572,17 @@ snapshots:
querystringify: 2.2.0
requires-port: 1.0.0
+ dependencies:
+ '@zed-industries/agent-client-protocol': 0.1.2
+ react: 19.1.1
+ react-dom: 19.1.1([email protected])
+ transitivePeerDependencies:
+ - '@types/react'
+ - immer
+ - use-sync-external-store
+
dependencies:
react: 19.1.1
@@ -20559,6 +20959,11 @@ snapshots:
core-util-is: 1.0.2
extsprintf: 1.3.0
+ dependencies:
+ '@types/unist': 3.0.3
+ vfile: 6.0.3
+
dependencies:
'@types/unist': 3.0.3
@@ -20721,6 +21126,8 @@ snapshots:
+
@@ -21008,4 +21415,10 @@ snapshots:
'@types/react': 19.1.12
react: 19.1.1
+ optionalDependencies:
+ '@types/react': 19.1.12
+ react: 19.1.1
+ use-sync-external-store: 1.5.0([email protected])
+