Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(chat): add inline markdown artifact previews (#16185)

FraterCCCLXIII98155d1b87c0
diff --git a/.pr/markdown-artifact-preview/chat-card.png b/.pr/markdown-artifact-preview/chat-card.png
new file mode 100644
index 0000000000..b8a2048101
Binary files /dev/null and b/.pr/markdown-artifact-preview/chat-card.png differ
diff --git a/.pr/markdown-artifact-preview/files-drawer.png b/.pr/markdown-artifact-preview/files-drawer.png
new file mode 100644
index 0000000000..b395f77d65
Binary files /dev/null and b/.pr/markdown-artifact-preview/files-drawer.png differ
diff --git a/.pr/markdown-artifact-preview/preview-scrolled.png b/.pr/markdown-artifact-preview/preview-scrolled.png
new file mode 100644
index 0000000000..d72fd8770c
Binary files /dev/null and b/.pr/markdown-artifact-preview/preview-scrolled.png differ
diff --git a/__tests__/api/mock-conversation-handlers.test.ts b/__tests__/api/mock-conversation-handlers.test.ts
index 61ddf86ff4..6c95efe0a1 100644
--- a/__tests__/api/mock-conversation-handlers.test.ts
+++ b/__tests__/api/mock-conversation-handlers.test.ts
@@ -3,12 +3,15 @@ import AgentServerConversationService from "#/api/conversation-service/agent-ser
import AgentServerGitService from "#/api/git-service/agent-server-git-service.api";
import EventService from "#/api/event-service/event-service.api";
import { TABLE_DEMO_CONVERSATION_ID } from "#/fixtures/table-demo-conversation";
+import {
+ CANVAS_DEMO_CONVERSATION_ID,
+ CANVAS_DEMO_FILE_PATH,
+} from "#/fixtures/canvas-demo-conversation";
describe("mock conversation handlers", () => {
it("returns adapted conversations for batch lookups", async () => {
- const [conversation] = await AgentServerConversationService.batchGetAppConversations([
- "1",
- ]);
+ const [conversation] =
+ await AgentServerConversationService.batchGetAppConversations(["1"]);
expect(conversation?.id).toBe("1");
expect(conversation?.title).toBe("My New Project");
@@ -66,4 +69,30 @@ describe("mock conversation handlers", () => {
expect(page.items[0]?.source).toBe("agent");
expect(page.items[1]?.source).toBe("user");
});
+
+ it("returns the generated-canvas demo conversation and file event", async () => {
+ const [conversation] =
+ await AgentServerConversationService.batchGetAppConversations([
+ CANVAS_DEMO_CONVERSATION_ID,
+ ]);
+ const page = await EventService.searchEvents(
+ CANVAS_DEMO_CONVERSATION_ID,
+ null,
+ null,
+ { limit: 50, sortOrder: "TIMESTAMP_DESC" },
+ );
+
+ expect(conversation?.title).toBe("Generated canvas demo");
+ expect(page.items).toHaveLength(4);
+ expect(page.items).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ observation: expect.objectContaining({
+ kind: "FileEditorObservation",
+ path: CANVAS_DEMO_FILE_PATH,
+ }),
+ }),
+ ]),
+ );
+ });
});
diff --git a/__tests__/components/conversation-events/chat/group-events.test.ts b/__tests__/components/conversation-events/chat/group-events.test.ts
index 61b79ce1b6..210a08673a 100644
--- a/__tests__/components/conversation-events/chat/group-events.test.ts
+++ b/__tests__/components/conversation-events/chat/group-events.test.ts
@@ -2,7 +2,6 @@ import { describe, it, expect } from "vitest";
import {
groupEvents,
isGroupableEvent,
- EVENT_GROUP_MIN_SIZE,
} from "#/components/conversation-events/chat/group-events";
import {
ActionEvent,
@@ -15,11 +14,13 @@ import {
import { TextContent } from "#/types/agent-server/core/base/common";
import {
ExecuteBashAction,
+ FileEditorAction,
FinishAction,
ThinkAction,
} from "#/types/agent-server/core/base/action";
import {
ExecuteBashObservation,
+ FileEditorObservation,
PlanningFileEditorObservation,
TaskTrackerObservation,
} from "#/types/agent-server/core/base/observation";
@@ -108,6 +109,41 @@ const makePlanObs = (
} as PlanningFileEditorObservation,
});
+const makeMarkdownFileEditorAction = (
+ id: string,
+): ActionEvent<FileEditorAction> => ({
+ ...makeBashAction(id),
+ tool_name: "file_editor",
+ action: {
+ kind: "FileEditorAction",
+ command: "create",
+ path: "canvas.md",
+ file_text: "# Demo",
+ old_str: null,
+ new_str: null,
+ insert_line: null,
+ view_range: null,
+ },
+});
+
+const makeMarkdownFileEditorObservation = (
+ id: string,
+ actionId: string,
+): ObservationEvent<FileEditorObservation> => ({
+ ...makeBashObservation(id, actionId),
+ tool_name: "file_editor",
+ observation: {
+ kind: "FileEditorObservation",
+ command: "create",
+ output: "Created canvas.md",
+ path: "canvas.md",
+ prev_exist: false,
+ old_content: null,
+ new_content: "# Demo",
+ error: null,
+ },
+});
+
const makeTaskTrackerObservation = (
id: string,
actionId: string,
@@ -177,8 +213,40 @@ describe("isGroupableEvent", () => {
expect(isGroupableEvent(makePlanObs("o1", "a1"))).toBe(false);
});
+ it("does not group markdown file-editor create actions or observations", () => {
+ expect(isGroupableEvent(makeMarkdownFileEditorAction("a1"))).toBe(false);
+ expect(
+ isGroupableEvent(makeMarkdownFileEditorObservation("o1", "a1")),
+ ).toBe(false);
+ });
+
+ it("still groups markdown file-editor view observations", () => {
+ const viewObservation = makeMarkdownFileEditorObservation("o1", "a1");
+ viewObservation.observation = {
+ ...viewObservation.observation,
+ command: "view",
+ output: "",
+ new_content: null,
+ content: [{ type: "text", text: " 1\t# README" }],
+ };
+ expect(isGroupableEvent(viewObservation)).toBe(true);
+ });
+
+ it("ungroups a markdown create observation when path comes from the action", () => {
+ const action = makeMarkdownFileEditorAction("a1");
+ const observation = makeMarkdownFileEditorObservation("o1", "a1");
+ observation.observation = {
+ ...observation.observation,
+ path: null,
+ };
+ expect(isGroupableEvent(observation)).toBe(true);
+ expect(isGroupableEvent(observation, action)).toBe(false);
+ });
+
it("does not group TaskTrackerObservation", () => {
- expect(isGroupableEvent(makeTaskTrackerObservation("o1", "a1"))).toBe(false);
+ expect(isGroupableEvent(makeTaskTrackerObservation("o1", "a1"))).toBe(
+ false,
+ );
});
it("does not group AgentErrorEvent", () => {
@@ -307,7 +375,10 @@ describe("groupEvents", () => {
const a2 = makeBashAction("a2");
const a3 = makeBashAction("a3");
const a4 = makeBashAction("a4", [
- { type: "text", text: "Let me check tests for the new conversation button:" },
+ {
+ type: "text",
+ text: "Let me check tests for the new conversation button:",
+ },
]);
const a5 = makeBashAction("a5");
const a6 = makeBashAction("a6");
@@ -320,7 +391,16 @@ describe("groupEvents", () => {
makeBashObservation("o5", "a5"),
makeBashObservation("o6", "a6"),
];
- const allEvents = [a1, a2, a3, ...events.slice(0, 3), a4, a5, a6, ...events.slice(3)];
+ const allEvents = [
+ a1,
+ a2,
+ a3,
+ ...events.slice(0, 3),
+ a4,
+ a5,
+ a6,
+ ...events.slice(3),
+ ];
const result = groupEvents(events, undefined, allEvents);
@@ -365,11 +445,10 @@ describe("groupEvents", () => {
]);
const observation = makeBashObservation("o1", "a1");
- const result = groupEvents(
- [action, observation],
- undefined,
- [action, observation],
- );
+ const result = groupEvents([action, observation], undefined, [
+ action,
+ observation,
+ ]);
expect(result.map((item) => item.kind)).toEqual(["thought", "group"]);
if (result[1].kind === "group") {
diff --git a/__tests__/components/conversation-events/get-event-content.test.tsx b/__tests__/components/conversation-events/get-event-content.test.tsx
index 44dc346359..d786a49bfa 100644
--- a/__tests__/components/conversation-events/get-event-content.test.tsx
+++ b/__tests__/components/conversation-events/get-event-content.test.tsx
@@ -170,6 +170,38 @@ describe("getEventContent", () => {
expect(screen.getByText("/workspace/README.md")).toBeInTheDocument();
});
+ it.each([
+ ["create", "OBSERVATION_MESSAGE$WRITE"],
+ ["str_replace", "OBSERVATION_MESSAGE$EDIT"],
+ ])(
+ "titles a %s file-editor observation with %s",
+ (command, expectedTitleKey) => {
+ const fileEditorObservation: ObservationEvent = {
+ id: "obs-2",
+ timestamp: new Date().toISOString(),
+ source: "environment",
+ tool_name: "file_editor",
+ tool_call_id: "tool-2",
+ action_id: "action-2",
+ observation: {
+ kind: "FileEditorObservation",
+ command: command as "create" | "str_replace",
+ output: "",
+ path: "/workspace/canvas.md",
+ prev_exist: command !== "create",
+ old_content: null,
+ new_content: "# Canvas",
+ error: null,
+ },
+ };
+
+ const { title } = getEventContent(fileEditorObservation);
+
+ render(<span>{title}</span>);
+ expect(screen.getByText(expectedTitleKey)).toBeInTheDocument();
+ },
+ );
+
it("shows action kind for action-like events missing tool_name/tool_call_id", () => {
// Simulate an event that has an action object but fails the strict isActionEvent() guard
const malformedEvent = {
diff --git a/__tests__/components/features/chat/tool-visualizers/file-editor/file-editor.test.tsx b/__tests__/components/features/chat/tool-visualizers/file-editor/file-editor.test.tsx
index bd914affdf..c9ee825da8 100644
--- a/__tests__/components/features/chat/tool-visualizers/file-editor/file-editor.test.tsx
+++ b/__tests__/components/features/chat/tool-visualizers/file-editor/file-editor.test.tsx
@@ -1,15 +1,38 @@
-import { describe, it, expect } from "vitest";
+import { beforeEach, describe, it, expect, vi } from "vitest";
import { screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
import { fileEditorVisualizer } from "#/components/features/chat/tool-visualizers/file-editor/file-editor";
+import { useConversationStore } from "#/stores/conversation-store";
+import { useFilesTabStore } from "#/stores/files-tab-store";
import {
renderVisualizer,
fileEditorAction,
fileEditorObservation,
} from "../test-utils";
+vi.mock("#/hooks/query/use-active-conversation", () => ({
+ useActiveConversation: () => ({
+ data: {
+ id: "test-conversation-id",
+ workspace: { working_dir: "/workspace" },
+ },
+ }),
+}));
+
const Body = fileEditorVisualizer.Body;
describe("fileEditorVisualizer", () => {
+ beforeEach(() => {
+ useConversationStore.setState({
+ hasRightPanelToggled: false,
+ selectedTab: "terminal",
+ });
+ useFilesTabStore.setState({
+ selectedPath: null,
+ selectedConversationId: null,
+ });
+ });
+
it("shows path and content for a create action", () => {
const { container } = renderVisualizer(
<Body
@@ -139,4 +162,151 @@ describe("fileEditorVisualizer", () => {
);
expect(screen.getByText("No replacement performed")).toBeInTheDocument();
});
+
+ it("opens the generated file in the right drawer when its chip is clicked", async () => {
+ const user = userEvent.setup();
+ renderVisualizer(
+ <Body
+ observation={fileEditorObservation({
+ command: "create",
+ path: "/workspace/app.ts",
+ new_content: "const x = 1;",
+ })}
+ />,
+ );
+
+ await user.click(screen.getByRole("button", { name: "/workspace/app.ts" }));
+
+ expect(useFilesTabStore.getState()).toMatchObject({
+ selectedPath: "app.ts",
+ selectedConversationId: "test-conversation-id",
+ });
+ expect(useConversationStore.getState()).toMatchObject({
+ hasRightPanelToggled: true,
+ selectedTab: "files",
+ });
+ });
+
+ it("keeps markdown view observations as a CodeBlock, not a rich preview", () => {
+ const { container } = renderVisualizer(
+ <Body
+ observation={fileEditorObservation({
+ command: "view",
+ path: "/workspace/README.md",
+ content: [
+ {
+ type: "text",
+ text: "Here's the result of running `cat -n`:\n 1\t# README",
+ },
+ ],
+ })}
+ />,
+ );
+
+ expect(
+ screen.queryByTestId("markdown-file-preview"),
+ ).not.toBeInTheDocument();
+ expect(container).toHaveTextContent("# README");
+ });
+
+ it("renders a height-clipped markdown preview with a View bar for .md creates", async () => {
+ const user = userEvent.setup();
+ const markdown = [
+ "# Agent Canvas Demo",
+ "",
+ "This report was generated by the agent.",
+ "",
+ "## Highlights",
+ "",
+ "- First point",
+ "- Second point",
+ "- Third point",
+ ].join("\n");
+
+ renderVisualizer(
+ <Body
+ observation={fileEditorObservation({
+ command: "create",
+ path: "canvas.md",
+ new_content: markdown,
+ })}
+ />,
+ );
+
+ expect(screen.getByTestId("markdown-file-preview")).toBeInTheDocument();
+ expect(screen.getByTestId("markdown-file-preview-content")).toHaveClass(
+ "max-h-40",
+ "overflow-y-auto",
+ "custom-scrollbar-always",
+ );
+ expect(screen.getByText("Agent Canvas Demo")).toBeInTheDocument();
+ expect(screen.getByText("canvas.md")).toBeInTheDocument();
+
+ await user.click(screen.getByTestId("markdown-file-preview-view"));
+
+ expect(useFilesTabStore.getState()).toMatchObject({
+ selectedPath: "canvas.md",
+ selectedConversationId: "test-conversation-id",
+ });
+ expect(useConversationStore.getState()).toMatchObject({
+ hasRightPanelToggled: true,
+ selectedTab: "files",
+ });
+ });
+
+ it("keeps non-markdown creates as a full code block", () => {
+ const { container } = renderVisualizer(
+ <Body
+ observation={fileEditorObservation({
+ command: "create",
+ path: "/workspace/app.ts",
+ new_content: "const x = 1;",
+ })}
+ />,
+ );
+
+ expect(
+ screen.queryByTestId("markdown-file-preview"),
+ ).not.toBeInTheDocument();
+ expect(container).toHaveTextContent("const x = 1;");
+ });
+
+ it("shows an in-flight markdown create preview without a View affordance", () => {
+ renderVisualizer(
+ <Body
+ action={fileEditorAction({
+ command: "create",
+ path: "/workspace/notes.md",
+ file_text: "# Draft",
+ })}
+ />,
+ );
+
+ expect(screen.getByTestId("markdown-file-preview")).toBeInTheDocument();
+ expect(screen.getByText("Draft")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("markdown-file-preview-view"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("stores a workspace-relative path when View opens an absolute .md create", async () => {
+ const user = userEvent.setup();
+
+ renderVisualizer(
+ <Body
+ observation={fileEditorObservation({
+ command: "create",
+ path: "/workspace/docs/report.md",
+ new_content: "# Report",
+ })}
+ />,
+ );
+
+ await user.click(screen.getByTestId("markdown-file-preview-view"));
+
+ expect(useFilesTabStore.getState()).toMatchObject({
+ selectedPath: "docs/report.md",
+ selectedConversationId: "test-conversation-id",
+ });
+ });
});
diff --git a/__tests__/utils/is-markdown-file-path.test.ts b/__tests__/utils/is-markdown-file-path.test.ts
new file mode 100644
index 0000000000..deb34dba0b
--- /dev/null
+++ b/__tests__/utils/is-markdown-file-path.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+import { isMarkdownFilePath } from "#/utils/is-markdown-file-path";
+
+describe("isMarkdownFilePath", () => {
+ it("matches markdown extensions", () => {
+ expect(isMarkdownFilePath("canvas.md")).toBe(true);
+ expect(isMarkdownFilePath("/workspace/project/report.markdown")).toBe(true);
+ expect(isMarkdownFilePath("docs/page.mdx")).toBe(true);
+ });
+
+ it("matches extensions case-insensitively", () => {
+ expect(isMarkdownFilePath("README.MD")).toBe(true);
+ expect(isMarkdownFilePath("notes.Markdown")).toBe(true);
+ });
+
+ it("uses only the last extension of dotted names", () => {
+ expect(isMarkdownFilePath("foo.bar.md")).toBe(true);
+ expect(isMarkdownFilePath("report.md.bak")).toBe(false);
+ });
+
+ it("rejects paths without a markdown extension", () => {
+ expect(isMarkdownFilePath("Makefile")).toBe(false);
+ expect(isMarkdownFilePath("/workspace/app.ts")).toBe(false);
+ expect(isMarkdownFilePath("")).toBe(false);
+ });
+});
diff --git a/__tests__/utils/workspace-relative-path.test.ts b/__tests__/utils/workspace-relative-path.test.ts
new file mode 100644
index 0000000000..dac077e099
--- /dev/null
+++ b/__tests__/utils/workspace-relative-path.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+import { toWorkspaceRelativePath } from "#/utils/workspace-relative-path";
+
+describe("toWorkspaceRelativePath", () => {
+ it("strips the conversation working directory prefix from absolute paths", () => {
+ expect(
+ toWorkspaceRelativePath(
+ "/workspace/project/report.md",
+ "/workspace/project",
+ ),
+ ).toBe("report.md");
+ expect(
+ toWorkspaceRelativePath(
+ "/workspace/project/src/index.ts",
+ "/workspace/project",
+ ),
+ ).toBe("src/index.ts");
+ });
+
+ it("leaves already-relative paths unchanged", () => {
+ expect(toWorkspaceRelativePath("canvas.md", "/workspace/project")).toBe(
+ "canvas.md",
+ );
+ expect(toWorkspaceRelativePath("./docs/a.md", "/workspace/project")).toBe(
+ "docs/a.md",
+ );
+ });
+
+ it("falls back to DEFAULT_WORKING_DIR when workingDir is omitted", () => {
+ expect(toWorkspaceRelativePath("/workspace/project/canvas.md")).toBe(
+ "canvas.md",
+ );
+ });
+});
diff --git a/src/components/conversation-events/chat/event-content-helpers/get-event-content.tsx b/src/components/conversation-events/chat/event-content-helpers/get-event-content.tsx
index e05afb92ee..d0ae422ac0 100644
--- a/src/components/conversation-events/chat/event-content-helpers/get-event-content.tsx
+++ b/src/components/conversation-events/chat/event-content-helpers/get-event-content.tsx
@@ -190,6 +190,8 @@ const getObservationEventTitle = (
case "StrReplaceEditorObservation":
if (event.observation.command === "view") {
observationKey = "OBSERVATION_MESSAGE$READ";
+ } else if (event.observation.command === "create") {
+ observationKey = "OBSERVATION_MESSAGE$WRITE";
} else {
observationKey = "OBSERVATION_MESSAGE$EDIT";
}
diff --git a/src/components/conversation-events/chat/event-message-components/generic-event-message-wrapper.tsx b/src/components/conversation-events/chat/event-message-components/generic-event-message-wrapper.tsx
index 6dd0c02f05..6142b27b4c 100644
--- a/src/components/conversation-events/chat/event-message-components/generic-event-message-wrapper.tsx
+++ b/src/components/conversation-events/chat/event-message-components/generic-event-message-wrapper.tsx
@@ -25,6 +25,7 @@ import { getInvokeSkillItems } from "../event-content-helpers/get-invoke-skill-i
import { ConversationConfirmationButtons } from "#/components/shared/buttons/conversation-confirmation-buttons";
import { SkillReadyContentList } from "./skill-ready-content-list";
import SkillsIcon from "#/icons/skills.svg?react";
+import { isMarkdownFileEditorEvent } from "#/components/features/chat/tool-visualizers/primitives/markdown-file-preview";
interface GenericEventMessageWrapperProps {
event: OpenHandsEvent | SkillReadyEvent;
@@ -103,13 +104,19 @@ export function GenericEventMessageWrapper({
details
);
+ // Markdown file-editor cards carry a clipped preview; expand them by
+ // default so the artifact is visible without an extra chevron click.
+ const initiallyExpanded =
+ !isSkillReadyEvent(event) &&
+ isMarkdownFileEditorEvent(event, correspondingAction);
+
return (
<div>
<GenericEventMessage
title={title}
details={bodyDetails}
success={success}
- initiallyExpanded={false}
+ initiallyExpanded={initiallyExpanded}
titleIcon={
skillKnowledge ? (
<SkillsIcon className="h-4 w-4 stroke-[var(--oh-muted)] flex-shrink-0 mr-2" />
diff --git a/src/components/conversation-events/chat/group-events.ts b/src/components/conversation-events/chat/group-events.ts
index 2118875923..44dab427d4 100644
--- a/src/components/conversation-events/chat/group-events.ts
+++ b/src/components/conversation-events/chat/group-events.ts
@@ -4,6 +4,7 @@ import {
isObservationEvent,
isPlanningFileEditorObservationEvent,
} from "#/types/agent-server/type-guards";
+import { isMarkdownFileEditorEvent } from "#/components/features/chat/tool-visualizers/primitives/markdown-file-preview";
import { getThoughtSourceAction } from "./event-thought-helpers";
/** Minimum run-length before consecutive actions get folded into a single
@@ -16,15 +17,23 @@ export const EVENT_GROUP_MIN_SIZE = 2;
* that we want to fold into an `EventGroup` when several appear in a row.
*
* Events that have their own dedicated rendering (FinishAction, ThinkAction,
- * HookExecution, AgentError, MessageEvent, PlanPreview, TaskTracker) are
- * treated as group breakers.
+ * HookExecution, AgentError, MessageEvent, PlanPreview, markdown file
+ * artifacts, TaskTracker) are treated as group breakers.
*/
-export const isGroupableEvent = (event: OpenHandsEvent): boolean => {
+export const isGroupableEvent = (
+ event: OpenHandsEvent,
+ correspondingAction?: ActionEvent,
+): boolean => {
if (isActionEvent(event)) {
const { kind } = event.action;
if (kind === "FinishAction" || kind === "ThinkAction") {
return false;
}
+ // Keep markdown *create* artifact cards outside collapsed groups so their
+ // clipped preview is visible without expanding a parent summary.
+ if (isMarkdownFileEditorEvent(event, correspondingAction)) {
+ return false;
+ }
return true;
}
@@ -32,6 +41,9 @@ export const isGroupableEvent = (event: OpenHandsEvent): boolean => {
if (isPlanningFileEditorObservationEvent(event)) {
return false;
}
+ if (isMarkdownFileEditorEvent(event, correspondingAction)) {
+ return false;
+ }
if (event.observation.kind === "TaskTrackerObservation") {
return false;
}
@@ -92,7 +104,13 @@ export const groupEvents = (
};
events.forEach((event, index) => {
- if (isGroupableEvent(event)) {
+ const correspondingAction = isObservationEvent(event)
+ ? allEvents.find(
+ (candidate): candidate is ActionEvent =>
+ isActionEvent(candidate) && candidate.id === event.action_id,
+ )
+ : undefined;
+ if (isGroupableEvent(event, correspondingAction)) {
const thoughtAction = getThoughtSourceAction(event, allEvents);
if (thoughtAction && !emittedThoughtActionIds.has(thoughtAction.id)) {
flushRun();
diff --git a/src/components/features/chat/path-component.tsx b/src/components/features/chat/path-component.tsx
index febc792dda..9e0d5a71df 100644
--- a/src/components/features/chat/path-component.tsx
+++ b/src/components/features/chat/path-component.tsx
@@ -60,14 +60,19 @@ function PathComponent(props: { children?: ReactNode }) {
// Extract the filename from the decoded path
const filename = extractFilename(decodedPath);
return (
- <span className="font-mono" title={decodedPath}>
+ <span
+ className="font-mono font-normal tracking-tight"
+ title={decodedPath}
+ >
{filename}
</span>
);
} catch (e) {
// Just log the error without any message to avoid localization issues
EventLogger.error(String(e));
- return <span className="font-mono">{path}</span>;
+ return (
+ <span className="font-mono font-normal tracking-tight">{path}</span>
+ );
}
};
@@ -80,14 +85,22 @@ function PathComponent(props: { children?: ReactNode }) {
),
);
- return <strong className="font-mono">{processedChildren}</strong>;
+ return (
+ <span className="font-normal tracking-tight">{processedChildren}</span>
+ );
}
if (typeof children === "string") {
- return <strong>{processPath(children)}</strong>;
+ return (
+ <span className="font-normal tracking-tight">
+ {processPath(children)}
+ </span>
+ );
}
- return <strong className="font-mono">{children}</strong>;
+ return (
+ <span className="font-mono font-normal tracking-tight">{children}</span>
+ );
}
export { PathComponent, isLikelyDirectory };
diff --git a/src/components/features/chat/tool-visualizers/file-editor/file-editor.tsx b/src/components/features/chat/tool-visualizers/file-editor/file-editor.tsx
index ee337a4f4d..f33335477f 100644
--- a/src/components/features/chat/tool-visualizers/file-editor/file-editor.tsx
+++ b/src/components/features/chat/tool-visualizers/file-editor/file-editor.tsx
@@ -1,11 +1,3 @@
-import React from "react";
-import { getLanguageFromPath } from "#/utils/get-language-from-path";
-import { defineVisualizer } from "../define";
-import { textFromContent } from "../text-content";
-import { CodeBlock } from "../primitives/code-block";
-import { DiffView } from "../primitives/diff-view";
-import { FilePathChip } from "../primitives/file-path-chip";
-
/**
* File-editor visualizer for `file_editor` / `str_replace_editor` tools.
*
@@ -13,77 +5,203 @@ import { FilePathChip } from "../primitives/file-path-chip";
* before vs after; `create`/`view` β†’ the file content. Action card (shown while
* the edit is in flight): `create` β†’ new content; `str_replace` β†’ diff of the
* replaced snippet; `view`/`undo_edit` β†’ just the path + range.
+ *
+ * Created Markdown artifacts get a height-clipped rich preview with a View bar
+ * that opens the Files drawer, instead of dumping the full source into a code
+ * block. Reads/edits of `.md` files keep the normal CodeBlock / DiffView path.
*/
-export const fileEditorVisualizer = defineVisualizer({
- actionKinds: ["FileEditorAction", "StrReplaceEditorAction"],
- observationKinds: ["FileEditorObservation", "StrReplaceEditorObservation"],
- Body: function FileEditorBody({ action, observation }) {
- const path = observation?.observation.path ?? action?.action.path ?? "";
- const command = observation?.observation.command ?? action?.action.command;
- const language = getLanguageFromPath(path);
+import React from "react";
+import { getLanguageFromPath } from "#/utils/get-language-from-path";
+import { toWorkspaceRelativePath } from "#/utils/workspace-relative-path";
+import { useOptionalConversationId } from "#/hooks/use-conversation-id";
+import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+import { useSelectConversationTab } from "#/hooks/use-select-conversation-tab";
+import { useFilesTabStore } from "#/stores/files-tab-store";
+import type {
+ FileEditorAction,
+ StrReplaceEditorAction,
+} from "#/types/agent-server/core/base/action";
+import type {
+ FileEditorObservation,
+ StrReplaceEditorObservation,
+} from "#/types/agent-server/core/base/observation";
+import { defineVisualizer, VisualizerProps } from "../define";
+import { textFromContent } from "../text-content";
+import { CodeBlock } from "../primitives/code-block";
+import { DiffView } from "../primitives/diff-view";
+import { FilePathChip } from "../primitives/file-path-chip";
+import {
+ isMarkdownFilePath,
+ MarkdownFilePreview,
+} from "../primitives/markdown-file-preview";
- const viewRange = action?.action.view_range;
- const range =
- command === "view" && viewRange
- ? `${viewRange[0]}-${viewRange[1]}`
- : undefined;
- const chip = path ? <FilePathChip path={path} range={range} /> : null;
+type FileEditorCardProps = VisualizerProps<
+ FileEditorAction | StrReplaceEditorAction,
+ FileEditorObservation | StrReplaceEditorObservation
+>;
- if (observation) {
- const obs = observation.observation;
- let body: React.ReactNode = null;
- if (obs.error) {
- body = (
- <span className="whitespace-pre-wrap text-xs text-danger">
- {obs.error}
- </span>
- );
- } else if (obs.old_content != null && obs.new_content != null) {
- // Nullish, not truthy: an empty string is a valid side of the diff β€”
- // clearing a file or inserting into an empty file must still render it.
- body = <DiffView oldText={obs.old_content} newText={obs.new_content} />;
- } else {
- // `view` returns the snippet the agent saw in `content` (the `cat -n`
- // output) rather than `output`/`new_content`, so fall back to it.
- // Mirrors the markdown path's "prefer content for view" handling.
- const content =
- obs.new_content ||
- obs.output ||
- (obs.content ? textFromContent(obs.content) : "");
- body = content ? (
- <CodeBlock code={content} language={language} />
- ) : null;
- }
- return (
- <div className="flex flex-col gap-2">
- {chip}
- {body}
- </div>
- );
+/** The path the event touched; observations win because they are authoritative. */
+const resolvePath = ({ action, observation }: FileEditorCardProps): string =>
+ observation?.observation.path ?? action?.action.path ?? "";
+
+interface FileEditorCardBodyProps extends FileEditorCardProps {
+ /**
+ * Deep-links the file into the Files drawer. Absent outside a conversation
+ * route, where there is no drawer to open; the card then stays read-only.
+ * Also omitted for in-flight creates so View does not open a missing file.
+ */
+ onOpenFile?: () => void;
+}
+
+function FileEditorCardBody({
+ action,
+ observation,
+ onOpenFile,
+}: FileEditorCardBodyProps) {
+ const path = resolvePath({ action, observation });
+ const command = observation?.observation.command ?? action?.action.command;
+ const language = getLanguageFromPath(path);
+
+ const viewRange = action?.action.view_range;
+ const range =
+ command === "view" && viewRange
+ ? `${viewRange[0]}-${viewRange[1]}`
+ : undefined;
+ const chip = path ? (
+ <FilePathChip path={path} range={range} onClick={onOpenFile} />
+ ) : null;
+
+ const renderFileContent = (content: string) => {
+ // Only created Markdown artifacts get the rich preview β€” `view` returns
+ // `cat -n` numbered snippets that must stay in a CodeBlock.
+ if (path && command === "create" && isMarkdownFilePath(path)) {
+ // Markdown artifacts own their card (clipped preview + optional View),
+ // so skip the separate path chip to avoid a duplicate filename affordance.
+ return {
+ chip: null as React.ReactNode,
+ body: (
+ <MarkdownFilePreview
+ content={content}
+ path={path}
+ onView={onOpenFile}
+ />
+ ),
+ };
}
+ return {
+ chip,
+ body: <CodeBlock code={content} language={language} />,
+ };
+ };
- if (action) {
- const act = action.action;
- let body: React.ReactNode = null;
- if (act.command === "create" && act.file_text) {
- body = <CodeBlock code={act.file_text} language={language} />;
- } else if (
- (act.command === "str_replace" || act.command === "insert") &&
- act.new_str != null
- ) {
- // `insert` carries only `new_str`, no `old_str`. Key on `new_str` and
- // default `old_str` to "" so an in-flight insert shows an addition diff
- // instead of nothing.
- body = <DiffView oldText={act.old_str ?? ""} newText={act.new_str} />;
- }
- return (
- <div className="flex flex-col gap-2">
- {chip}
- {body}
- </div>
+ if (observation) {
+ const obs = observation.observation;
+ let body: React.ReactNode = null;
+ let leadingChip: React.ReactNode = chip;
+ if (obs.error) {
+ body = (
+ <span className="whitespace-pre-wrap text-xs text-danger">
+ {obs.error}
+ </span>
);
+ } else if (obs.old_content != null && obs.new_content != null) {
+ // Nullish, not truthy: an empty string is a valid side of the diff β€”
+ // clearing a file or inserting into an empty file must still render it.
+ body = <DiffView oldText={obs.old_content} newText={obs.new_content} />;
+ } else {
+ // `view` returns the snippet the agent saw in `content` (the `cat -n`
+ // output) rather than `output`/`new_content`, so fall back to it.
+ // Mirrors the markdown path's "prefer content for view" handling.
+ const content =
+ obs.new_content ||
+ obs.output ||
+ (obs.content ? textFromContent(obs.content) : "");
+ if (content) {
+ const rendered = renderFileContent(content);
+ leadingChip = rendered.chip;
+ body = rendered.body;
+ }
+ }
+ return (
+ <div className="flex flex-col gap-2">
+ {leadingChip}
+ {body}
+ </div>
+ );
+ }
+
+ if (action) {
+ const act = action.action;
+ let body: React.ReactNode = null;
+ let leadingChip: React.ReactNode = chip;
+ if (act.command === "create" && act.file_text) {
+ const rendered = renderFileContent(act.file_text);
+ leadingChip = rendered.chip;
+ body = rendered.body;
+ } else if (
+ (act.command === "str_replace" || act.command === "insert") &&
+ act.new_str != null
+ ) {
+ // `insert` carries only `new_str`, no `old_str`. Key on `new_str` and
+ // default `old_str` to "" so an in-flight insert shows an addition diff
+ // instead of nothing.
+ body = <DiffView oldText={act.old_str ?? ""} newText={act.new_str} />;
}
+ return (
+ <div className="flex flex-col gap-2">
+ {leadingChip}
+ {body}
+ </div>
+ );
+ }
+
+ return null;
+}
+
+/**
+ * Conversation-scoped wrapper: owns the Files-drawer deep link. Split from the
+ * card so the conversation-only hooks below never run outside a conversation
+ * route (they throw on a missing conversation id).
+ */
+function FileEditorCardWithDrawerLink({
+ conversationId,
+ ...props
+}: FileEditorCardProps & { conversationId: string }) {
+ const { navigateToTab } = useSelectConversationTab();
+ const setSelectedPath = useFilesTabStore((state) => state.setSelectedPath);
+ const { data: conversation } = useActiveConversation();
+ const path = resolvePath(props);
+ const workingDir = conversation?.workspace?.working_dir;
+
+ // Only deep-link once the observation exists β€” the file is not guaranteed
+ // to be on disk while the create action is still in flight.
+ const onOpenFile =
+ path && props.observation
+ ? () => {
+ setSelectedPath(
+ toWorkspaceRelativePath(path, workingDir),
+ conversationId,
+ );
+ navigateToTab("files");
+ }
+ : undefined;
+
+ return <FileEditorCardBody {...props} onOpenFile={onOpenFile} />;
+}
+
+export const fileEditorVisualizer = defineVisualizer({
+ actionKinds: ["FileEditorAction", "StrReplaceEditorAction"],
+ observationKinds: ["FileEditorObservation", "StrReplaceEditorObservation"],
+ Body: function FileEditorBody(props) {
+ const { conversationId } = useOptionalConversationId();
- return null;
+ return conversationId ? (
+ <FileEditorCardWithDrawerLink
+ {...props}
+ conversationId={conversationId}
+ />
+ ) : (
+ <FileEditorCardBody {...props} />
+ );
},
});
diff --git a/src/components/features/chat/tool-visualizers/primitives/file-path-chip.tsx b/src/components/features/chat/tool-visualizers/primitives/file-path-chip.tsx
index 3e10bb79e3..6ac0fe8a67 100644
--- a/src/components/features/chat/tool-visualizers/primitives/file-path-chip.tsx
+++ b/src/components/features/chat/tool-visualizers/primitives/file-path-chip.tsx
@@ -5,16 +5,37 @@ interface FilePathChipProps {
path: string;
/** Optional line-range suffix, e.g. "12-48". */
range?: string;
+ /** Opens the referenced file when the surrounding visualizer can navigate. */
+ onClick?: () => void;
}
/**
- * Monospace file-path pill with a file icon and an optional line-range suffix.
+ * Monospace file-path pill with an optional navigation affordance.
+ *
+ * The static variant remains available for visualizers without a workspace
+ * target; passing `onClick` upgrades the same visual language to a button.
*/
-export function FilePathChip({ path, range }: FilePathChipProps) {
- return (
- <span className="inline-flex max-w-full items-center gap-1.5 self-start rounded bg-surface-raised px-2 py-0.5 font-mono text-xs text-foreground">
+export function FilePathChip({ path, range, onClick }: FilePathChipProps) {
+ const content = (
+ <>
<FileIcon className="h-3.5 w-3.5 flex-shrink-0 text-muted" />
<span className="break-all">{range ? `${path}:${range}` : path}</span>
- </span>
+ </>
);
+ const className =
+ "inline-flex max-w-full items-center gap-1.5 self-start rounded bg-surface-raised px-2 py-0.5 font-mono text-xs text-foreground";
+
+ if (onClick) {
+ return (
+ <button
+ type="button"
+ className={`${className} cursor-pointer hover:bg-[var(--oh-interactive-hover)]`}
+ onClick={onClick}
+ >
+ {content}
+ </button>
+ );
+ }
+
+ return <span className={className}>{content}</span>;
}
diff --git a/src/components/features/chat/tool-visualizers/primitives/markdown-file-preview.tsx b/src/components/features/chat/tool-visualizers/primitives/markdown-file-preview.tsx
new file mode 100644
index 0000000000..91d1adc3c1
--- /dev/null
+++ b/src/components/features/chat/tool-visualizers/primitives/markdown-file-preview.tsx
@@ -0,0 +1,206 @@
+/**
+ * Inline markdown artifact preview for chat tool cards.
+ *
+ * Shows a height-limited scrollable rich preview so long reports stay compact
+ * in the stream; the footer View action deep-links into the Files drawer for
+ * the full document. Markdown *create* file-editor events stay expanded and
+ * ungrouped so the preview is visible without an extra click.
+ */
+import { useTranslation } from "react-i18next";
+import { ArrowUpRight } from "lucide-react";
+import FileIcon from "#/icons/file.svg?react";
+import { I18nKey } from "#/i18n/declaration";
+import { MarkdownRenderer } from "#/components/features/markdown/markdown-renderer";
+import { planComponents } from "#/components/features/markdown/plan-components";
+import { Typography } from "#/ui/typography";
+import { isMarkdownFilePath } from "#/utils/is-markdown-file-path";
+import type {
+ ActionEvent,
+ ObservationEvent,
+ OpenHandsEvent,
+} from "#/types/agent-server/core";
+import {
+ isActionEvent,
+ isObservationEvent,
+} from "#/types/agent-server/type-guards";
+import type {
+ FileEditorAction,
+ StrReplaceEditorAction,
+} from "#/types/agent-server/core/base/action";
+import type {
+ FileEditorObservation,
+ StrReplaceEditorObservation,
+} from "#/types/agent-server/core/base/observation";
+
+export { isMarkdownFilePath } from "#/utils/is-markdown-file-path";
+
+const FILE_EDITOR_ACTION_KINDS = new Set([
+ "FileEditorAction",
+ "StrReplaceEditorAction",
+]);
+const FILE_EDITOR_OBSERVATION_KINDS = new Set([
+ "FileEditorObservation",
+ "StrReplaceEditorObservation",
+]);
+
+interface MarkdownFilePreviewProps {
+ content: string;
+ path: string;
+ /** When omitted (e.g. in-flight create), the View affordance is hidden. */
+ onView?: () => void;
+}
+
+/**
+ * Resolves the file path for a file-editor action/observation, including the
+ * observation's originating action when the observation omits `path`.
+ */
+function getFileEditorEventPath(
+ event: OpenHandsEvent,
+ correspondingAction?: ActionEvent,
+): string | null {
+ if (isActionEvent(event) && FILE_EDITOR_ACTION_KINDS.has(event.action.kind)) {
+ return (
+ (event as ActionEvent<FileEditorAction | StrReplaceEditorAction>).action
+ .path || null
+ );
+ }
+
+ if (
+ isObservationEvent(event) &&
+ FILE_EDITOR_OBSERVATION_KINDS.has(event.observation.kind)
+ ) {
+ const path = (
+ event as ObservationEvent<
+ FileEditorObservation | StrReplaceEditorObservation
+ >
+ ).observation.path;
+ if (path) return path;
+ if (
+ correspondingAction &&
+ FILE_EDITOR_ACTION_KINDS.has(correspondingAction.action.kind)
+ ) {
+ return (
+ (
+ correspondingAction as ActionEvent<
+ FileEditorAction | StrReplaceEditorAction
+ >
+ ).action.path || null
+ );
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Resolves the file-editor command (`create` / `view` / …), including the
+ * observation's originating action when the observation omits `command`.
+ */
+function getFileEditorEventCommand(
+ event: OpenHandsEvent,
+ correspondingAction?: ActionEvent,
+): string | null {
+ if (isActionEvent(event) && FILE_EDITOR_ACTION_KINDS.has(event.action.kind)) {
+ return (
+ (event as ActionEvent<FileEditorAction | StrReplaceEditorAction>).action
+ .command || null
+ );
+ }
+
+ if (
+ isObservationEvent(event) &&
+ FILE_EDITOR_OBSERVATION_KINDS.has(event.observation.kind)
+ ) {
+ const command = (
+ event as ObservationEvent<
+ FileEditorObservation | StrReplaceEditorObservation
+ >
+ ).observation.command;
+ if (command) return command;
+ if (
+ correspondingAction &&
+ FILE_EDITOR_ACTION_KINDS.has(correspondingAction.action.kind)
+ ) {
+ return (
+ (
+ correspondingAction as ActionEvent<
+ FileEditorAction | StrReplaceEditorAction
+ >
+ ).action.command || null
+ );
+ }
+ }
+
+ return null;
+}
+
+/**
+ * True for file-editor *create* events whose path is a markdown artifact.
+ *
+ * Used to keep those cards expanded and outside collapsed action groups so
+ * the clipped preview is visible by default. Reads/edits of `.md` files stay
+ * on the normal groupable path.
+ */
+export function isMarkdownFileEditorEvent(
+ event: OpenHandsEvent,
+ correspondingAction?: ActionEvent,
+): boolean {
+ const path = getFileEditorEventPath(event, correspondingAction);
+ const command = getFileEditorEventCommand(event, correspondingAction);
+ return Boolean(path && command === "create" && isMarkdownFilePath(path));
+}
+
+/**
+ * Height-clipped markdown card with an optional View bar that opens the file.
+ */
+export function MarkdownFilePreview({
+ content,
+ path,
+ onView,
+}: MarkdownFilePreviewProps) {
+ const { t } = useTranslation("openhands");
+ const fileName = path.split("/").pop() || path;
+
+ return (
+ <div
+ className="w-full overflow-hidden rounded-[12px] border border-[var(--oh-border)] bg-[var(--oh-surface)]"
+ data-testid="markdown-file-preview"
+ >
+ <div
+ data-testid="markdown-file-preview-content"
+ className="max-h-40 overflow-y-auto px-4 py-3 text-white custom-scrollbar-always [--oh-scroll-fade-from:var(--oh-surface)]"
+ >
+ {/* Deliberately compact: the clipped in-stream card reuses the plan
+ preview's small typography; the Files drawer renders the same
+ artifact full-size with the default components. */}
+ <MarkdownRenderer
+ content={content}
+ includeStandard
+ includeHeadings
+ components={planComponents}
+ />
+ </div>
+ <div className="flex h-10 items-center justify-between gap-2 border-t border-[var(--oh-border)] px-3">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <FileIcon className="h-3.5 w-3.5 flex-shrink-0 text-[var(--oh-muted)]" />
+ <Typography.Text className="truncate font-mono text-[11px] leading-4 tracking-[0.11px] text-[var(--oh-muted)]">
+ {fileName}
+ </Typography.Text>
+ </div>
+ {onView ? (
+ <button
+ type="button"
+ onClick={onView}
+ className="flex shrink-0 cursor-pointer items-center gap-1 transition-opacity hover:opacity-80"
+ data-testid="markdown-file-preview-view"
+ >
+ <Typography.Text className="text-[11px] leading-4 tracking-[0.11px] text-white">
+ {t(I18nKey.COMMON$VIEW)}
+ </Typography.Text>
+ <ArrowUpRight className="text-white" size={16} />
+ </button>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/features/files-tab/file-content-viewer.tsx b/src/components/features/files-tab/file-content-viewer.tsx
index 2a15f11356..b2ebf8f076 100644
--- a/src/components/features/files-tab/file-content-viewer.tsx
+++ b/src/components/features/files-tab/file-content-viewer.tsx
@@ -7,6 +7,7 @@ import {
withWorkspaceCacheBuster,
} from "#/stores/use-workspace-mutation-counter";
import { MarkdownRenderer } from "#/components/features/markdown/markdown-renderer";
+import { isMarkdownFilePath } from "#/utils/is-markdown-file-path";
import { HighlightedSourceView } from "./highlighted-source-view";
import type { ViewMode } from "./view-mode";
@@ -16,7 +17,6 @@ interface FileContentViewerProps {
}
const HTML_LIKE_EXTS = new Set(["html", "htm", "svg"]);
-const MARKDOWN_EXTS = new Set(["md", "markdown", "mdx"]);
// Office/document formats we can't preview inline. The label doubles as the
// allow-list (a present entry => Office doc) and feeds a clear, format-named
@@ -181,19 +181,21 @@ export function FileContentViewer({ path, viewMode }: FileContentViewerProps) {
);
}
- if (kind === "text" && MARKDOWN_EXTS.has(getExtension(path))) {
+ if (kind === "text" && isMarkdownFilePath(path)) {
// Match the right-pane chrome color so the rich-rendered markdown
// blends with the surrounding files tab instead of painting a stark
- // white card. We use `prose-invert` (typography plugin's dark-theme
- // variant) and then layer arbitrary CSS-variable overrides on top to
- // pin body / bold / quote text to pure white β€” the user specifically
- // asked for every text element (not just headings) to read as white.
- // The custom heading components in `markdown/headings.tsx` already
- // hard-code `text-white`, so headers stay white through this change.
+ // white card. `--oh-scroll-fade-from` keeps wide-table edge fades on
+ // the same surface (otherwise they default to `--oh-color-base`).
+ // We use `prose-invert` (typography plugin's dark-theme variant) and
+ // then layer arbitrary CSS-variable overrides on top to pin body /
+ // bold / quote text to pure white β€” the user specifically asked for
+ // every text element (not just headings) to read as white. The custom
+ // heading components in `markdown/headings.tsx` already hard-code
+ // `text-white`, so headers stay white through this change.
return (
<div
data-testid="file-content-viewer-markdown"
- className="h-full w-full overflow-auto bg-[var(--oh-surface)] text-white custom-scrollbar-always"
+ className="h-full w-full overflow-auto bg-[var(--oh-surface)] text-white custom-scrollbar-always [--oh-scroll-fade-from:var(--oh-surface)]"
>
<div className="prose prose-sm prose-invert max-w-none p-6 [--tw-prose-body:#fff] [--tw-prose-bold:#fff] [--tw-prose-headings:#fff] [--tw-prose-lead:#fff] [--tw-prose-counters:#fff] [--tw-prose-quotes:#fff] [--tw-prose-quote-borders:var(--oh-border-subtle)] [--tw-prose-bullets:var(--oh-muted)] [--tw-prose-hr:var(--oh-border-subtle)] [--tw-prose-captions:var(--oh-muted)] [--tw-prose-kbd:#fff]">
<MarkdownRenderer
diff --git a/src/components/features/markdown/markdown-table-scroll.tsx b/src/components/features/markdown/markdown-table-scroll.tsx
index ea23ec1a8e..44a527ae1c 100644
--- a/src/components/features/markdown/markdown-table-scroll.tsx
+++ b/src/components/features/markdown/markdown-table-scroll.tsx
@@ -68,6 +68,11 @@ export function MarkdownTableScroll({ children }: MarkdownTableScrollProps) {
>
{children}
</div>
+ {/* The fades blend into whatever surface the table sits on, which differs
+ between the chat stream and cards like the markdown artifact preview.
+ Set `--oh-scroll-fade-from` on any ancestor to match another surface.
+ The value is inlined at both edges because Tailwind only extracts
+ classes from literal strings, not interpolated constants. */}
<div
aria-hidden
data-testid="markdown-table-scroll-fade-left"
@@ -75,7 +80,7 @@ export function MarkdownTableScroll({ children }: MarkdownTableScrollProps) {
className={cn(
"pointer-events-none absolute inset-y-0 left-0 z-10",
FADE_WIDTH_CLASS,
- "bg-gradient-to-r from-base to-transparent",
+ "bg-gradient-to-r from-[var(--oh-scroll-fade-from,var(--oh-color-base))] to-transparent",
"transition-opacity duration-300 ease-out motion-reduce:transition-none",
fadeState.left ? "opacity-100" : "opacity-0",
)}
@@ -87,7 +92,7 @@ export function MarkdownTableScroll({ children }: MarkdownTableScrollProps) {
className={cn(
"pointer-events-none absolute inset-y-0 right-0 z-10",
FADE_WIDTH_CLASS,
- "bg-gradient-to-l from-base to-transparent",
+ "bg-gradient-to-l from-[var(--oh-scroll-fade-from,var(--oh-color-base))] to-transparent",
"transition-opacity duration-300 ease-out motion-reduce:transition-none",
fadeState.right ? "opacity-100" : "opacity-0",
)}
diff --git a/src/fixtures/canvas-demo-conversation.ts b/src/fixtures/canvas-demo-conversation.ts
new file mode 100644
index 0000000000..f8118860e2
--- /dev/null
+++ b/src/fixtures/canvas-demo-conversation.ts
@@ -0,0 +1,131 @@
+/**
+ * Generated-canvas demo fixture β€” models an agent creating a Markdown artifact
+ * so mock mode can demonstrate chat-to-drawer file navigation without an LLM.
+ */
+import type {
+ ActionEvent,
+ MessageEvent,
+ ObservationEvent,
+ OpenHandsEvent,
+} from "#/types/agent-server/core";
+import { SecurityRisk } from "#/types/agent-server/core";
+import type { FileEditorAction } from "#/types/agent-server/core/base/action";
+import type { FileEditorObservation } from "#/types/agent-server/core/base/observation";
+
+export const CANVAS_DEMO_CONVERSATION_ID = "canvas-demo";
+export const CANVAS_DEMO_FILE_PATH = "canvas.md";
+
+export const CANVAS_DEMO_MARKDOWN = [
+ "# Agent Canvas Demo",
+ "",
+ "This report was generated by the agent and opened from the file chip in chat.",
+ "",
+ "## Release snapshot",
+ "",
+ "| Area | Status | Next step |",
+ "| --- | --- | --- |",
+ "| Conversation UX | Ready | Validate the drawer flow |",
+ "| Markdown preview | Ready | Review rich rendering |",
+ "| Accessibility | Ready | Confirm keyboard navigation |",
+ "",
+ "## Highlights",
+ "",
+ "- The artifact stays in the conversation workspace.",
+ "- The chat chip is the compact entry point.",
+ "- The Files drawer provides the full rich Markdown view.",
+].join("\n");
+
+const BASE_TIME = Date.UTC(2026, 6, 29, 12, 0, 0);
+const timestamp = (offsetSeconds: number) =>
+ new Date(BASE_TIME + offsetSeconds * 1000).toISOString();
+
+/**
+ * Creates a minimal message event with the same SDK shape used by history.
+ */
+function createMessage(
+ id: string,
+ role: "user" | "assistant",
+ text: string,
+ offsetSeconds: number,
+): MessageEvent {
+ return {
+ id,
+ timestamp: timestamp(offsetSeconds),
+ source: role === "user" ? "user" : "agent",
+ llm_message: {
+ role,
+ content: [{ type: "text", text }],
+ },
+ activated_microagents: [],
+ extended_content: [],
+ };
+}
+
+const createCanvasAction: ActionEvent<FileEditorAction> = {
+ id: "canvas-demo-action",
+ timestamp: timestamp(1),
+ source: "agent",
+ thought: [],
+ thinking_blocks: [],
+ action: {
+ kind: "FileEditorAction",
+ command: "create",
+ path: CANVAS_DEMO_FILE_PATH,
+ file_text: CANVAS_DEMO_MARKDOWN,
+ old_str: null,
+ new_str: null,
+ insert_line: null,
+ view_range: null,
+ },
+ tool_name: "file_editor",
+ tool_call_id: "canvas-demo-tool-call",
+ tool_call: {
+ id: "canvas-demo-tool-call",
+ type: "function",
+ function: {
+ name: "file_editor",
+ arguments: JSON.stringify({
+ command: "create",
+ path: CANVAS_DEMO_FILE_PATH,
+ }),
+ },
+ },
+ llm_response_id: "canvas-demo-response",
+ security_risk: SecurityRisk.LOW,
+};
+
+const createCanvasObservation: ObservationEvent<FileEditorObservation> = {
+ id: "canvas-demo-observation",
+ timestamp: timestamp(2),
+ source: "environment",
+ tool_name: "file_editor",
+ tool_call_id: "canvas-demo-tool-call",
+ action_id: createCanvasAction.id,
+ observation: {
+ kind: "FileEditorObservation",
+ command: "create",
+ output: `Created ${CANVAS_DEMO_FILE_PATH}`,
+ path: CANVAS_DEMO_FILE_PATH,
+ prev_exist: false,
+ old_content: null,
+ new_content: CANVAS_DEMO_MARKDOWN,
+ error: null,
+ },
+};
+
+export const CANVAS_DEMO_EVENTS: OpenHandsEvent[] = [
+ createMessage(
+ "canvas-demo-user",
+ "user",
+ "Create a concise project canvas as a Markdown report.",
+ 0,
+ ),
+ createCanvasAction,
+ createCanvasObservation,
+ createMessage(
+ "canvas-demo-agent",
+ "assistant",
+ "I generated the project canvas. Open it from the file chip above.",
+ 3,
+ ),
+];
diff --git a/src/mocks/conversation-handlers.ts b/src/mocks/conversation-handlers.ts
index 81fcbd98b8..9eb9620db0 100644
--- a/src/mocks/conversation-handlers.ts
+++ b/src/mocks/conversation-handlers.ts
@@ -1,4 +1,4 @@
-import { http, delay, HttpResponse } from "msw";
+import { http, delay, HttpResponse, passthrough } from "msw";
import type { DirectConversationInfo } from "#/api/agent-server-adapter";
import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
import {
@@ -10,10 +10,17 @@ import {
TABLE_DEMO_CONVERSATION_ID,
TABLE_DEMO_EVENTS,
} from "#/fixtures/table-demo-conversation";
+import {
+ CANVAS_DEMO_CONVERSATION_ID,
+ CANVAS_DEMO_EVENTS,
+ CANVAS_DEMO_FILE_PATH,
+ CANVAS_DEMO_MARKDOWN,
+} from "#/fixtures/canvas-demo-conversation";
/** Map from conversation id β†’ events returned by GET /events/search */
const CONVERSATION_EVENTS: Record<string, unknown[]> = {
[TABLE_DEMO_CONVERSATION_ID]: TABLE_DEMO_EVENTS,
+ [CANVAS_DEMO_CONVERSATION_ID]: CANVAS_DEMO_EVENTS,
};
const now = Date.now();
@@ -97,6 +104,14 @@ const conversations: MockConversation[] = [
execution_status: "idle",
workspace: { working_dir: "/workspace/project" },
},
+ {
+ id: CANVAS_DEMO_CONVERSATION_ID,
+ title: "Generated canvas demo",
+ created_at: new Date(now - 12 * 60 * 60 * 1000).toISOString(),
+ updated_at: new Date(now - 12 * 60 * 60 * 1000).toISOString(),
+ execution_status: "idle",
+ workspace: { working_dir: "/workspace/project" },
+ },
];
const CONVERSATIONS = new Map<string, MockConversation>(
@@ -337,6 +352,28 @@ export const CONVERSATION_HANDLERS = [
HttpResponse.json({ ok: true }),
),
+ // The generated-canvas fixture behaves like a real workspace artifact:
+ // after the chat chip opens the Files drawer, its static-session URL serves
+ // the same Markdown bytes carried by the file-editor observation.
+ http.get(
+ "*/api/conversations/:conversationId/workspace/*",
+ ({ params, request }) => {
+ const conversationId = params.conversationId?.toString();
+ const url = new URL(request.url);
+ if (
+ conversationId === CANVAS_DEMO_CONVERSATION_ID &&
+ url.pathname.endsWith(`/${CANVAS_DEMO_FILE_PATH}`)
+ ) {
+ return HttpResponse.text(CANVAS_DEMO_MARKDOWN, {
+ headers: { "Content-Type": "text/markdown; charset=utf-8" },
+ });
+ }
+ // Leave every other workspace-file GET on its previous bypass behavior
+ // so this fixture handler does not force 404s for unrelated mocks.
+ return passthrough();
+ },
+ ),
+
http.post("*/api/conversations/:conversationId/pause", async () =>
HttpResponse.json({ success: true }),
),
diff --git a/src/utils/is-markdown-file-path.ts b/src/utils/is-markdown-file-path.ts
new file mode 100644
index 0000000000..a2b9fd8481
--- /dev/null
+++ b/src/utils/is-markdown-file-path.ts
@@ -0,0 +1,11 @@
+/** Extensions treated as Markdown for rich preview rendering. */
+const MARKDOWN_EXTS = new Set(["md", "markdown", "mdx"]);
+
+/**
+ * True when `path` ends with a Markdown extension (`.md`, `.markdown`, `.mdx`).
+ */
+export function isMarkdownFilePath(path: string): boolean {
+ const idx = path.lastIndexOf(".");
+ if (idx === -1) return false;
+ return MARKDOWN_EXTS.has(path.slice(idx + 1).toLowerCase());
+}
diff --git a/src/utils/workspace-relative-path.ts b/src/utils/workspace-relative-path.ts
new file mode 100644
index 0000000000..49ab8343ee
--- /dev/null
+++ b/src/utils/workspace-relative-path.ts
@@ -0,0 +1,46 @@
+import { DEFAULT_WORKING_DIR } from "#/api/agent-server-config";
+
+function normalizeWorkspaceRoot(root: string): string {
+ const trimmed = root.trim();
+ const withLeading = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
+ return withLeading.replace(/\/+$/, "");
+}
+
+/**
+ * Convert an agent file path into a workspace-relative path for the Files
+ * drawer / workspace file APIs.
+ *
+ * File-editor events typically carry absolute sandbox paths
+ * (e.g. `/workspace/project/report.md`) while `selectedPath` and
+ * `useWorkspaceFileContent` expect paths relative to the conversation
+ * working directory (e.g. `report.md`).
+ */
+export function toWorkspaceRelativePath(
+ path: string,
+ workingDir?: string | null,
+): string {
+ const trimmedPath = path.trim();
+ if (!trimmedPath) {
+ return trimmedPath;
+ }
+
+ if (!trimmedPath.startsWith("/")) {
+ return trimmedPath.replace(/^\.\//, "");
+ }
+
+ const roots = [workingDir, DEFAULT_WORKING_DIR].filter(
+ (value): value is string => Boolean(value?.trim()),
+ );
+
+ for (const root of roots) {
+ const normalizedRoot = normalizeWorkspaceRoot(root);
+ if (trimmedPath === normalizedRoot) {
+ return "";
+ }
+ if (trimmedPath.startsWith(`${normalizedRoot}/`)) {
+ return trimmedPath.slice(normalizedRoot.length + 1);
+ }
+ }
+
+ return trimmedPath.replace(/^\/+/, "");
+}