π OpenHands: AI-Driven Development
feat: link chat file paths to the Files drawer (#16181)
Shashwat Pratap Singh150e76046db0
diff --git a/__tests__/components/conversation-events/chat/event-message-components/event-group.test.tsx b/__tests__/components/conversation-events/chat/event-message-components/event-group.test.tsxindex 8405642fa0..264d5cb20c 100644--- a/__tests__/components/conversation-events/chat/event-message-components/event-group.test.tsx+++ b/__tests__/components/conversation-events/chat/event-message-components/event-group.test.tsx@@ -8,7 +8,10 @@ import {ObservationEvent,SecurityRisk,} from "#/types/agent-server/core";-import { ExecuteBashAction } from "#/types/agent-server/core/base/action";+import {+ ExecuteBashAction,+ FileEditorAction,+} from "#/types/agent-server/core/base/action";import { ExecuteBashObservation } from "#/types/agent-server/core/base/observation";const makeBashAction = (@@ -228,4 +231,51 @@ describe("EventGroup", () => {expect(screen.queryByRole("region")).not.toBeInTheDocument();expect(screen.queryByTestId("child")).not.toBeInTheDocument();});++ it("keeps grouped file-action titles non-interactive inside the toggle", () => {+ const fileAction: ActionEvent<FileEditorAction> = {+ id: "a-file",+ timestamp: new Date().toISOString(),+ source: "agent",+ thought: [],+ thinking_blocks: [],+ action: {+ kind: "FileEditorAction",+ command: "str_replace",+ path: "src/app.ts",+ file_text: null,+ old_str: "a",+ new_str: "b",+ insert_line: null,+ view_range: null,+ },+ tool_name: "file_editor",+ tool_call_id: "call_a-file",+ tool_call: {+ id: "call_a-file",+ type: "function",+ function: {+ name: "file_editor",+ arguments: JSON.stringify({+ command: "str_replace",+ path: "src/app.ts",+ }),+ },+ },+ llm_response_id: "response_a-file",+ security_risk: SecurityRisk.UNKNOWN,+ };++ renderWithProviders(+ <EventGroup events={[fileAction]}>+ <div>child</div>+ </EventGroup>,+ );++ const toggle = screen.getByTestId("event-group-toggle");+ expect(+ toggle.querySelector('[data-testid="path-component-link"]'),+ ).toBeNull();+ expect(toggle.querySelectorAll("button")).toHaveLength(0);+ });});diff --git a/__tests__/components/features/chat/chat-markdown-path-linking.test.tsx b/__tests__/components/features/chat/chat-markdown-path-linking.test.tsxnew file mode 100644index 0000000000..5d42760f15--- /dev/null+++ b/__tests__/components/features/chat/chat-markdown-path-linking.test.tsx@@ -0,0 +1,118 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import ConversationService from "#/api/conversation-service/conversation-service.api";+import { ChatMessage } from "#/components/features/chat/chat-message";+import { WorkspaceFilesForChatContext } from "#/components/features/chat/chat-markdown-path-code";+import { useFilesTabStore } from "#/stores/files-tab-store";++const openWorkspaceFile = vi.fn();++vi.mock("#/services/canvas-ui", () => ({+ openWorkspaceFile: (...args: unknown[]) => openWorkspaceFile(...args),+}));++vi.mock("#/hooks/use-conversation-id", () => ({+ useOptionalConversationId: () => ({ conversationId: "conv-1" }),+}));++const WORKSPACE_FILES = ["test.md", "motivational_message.md", "src/app.ts"];++function renderAgentMessage(+ message: string,+ files: string[] = WORKSPACE_FILES,+) {+ return render(+ <WorkspaceFilesForChatContext.Provider value={files}>+ <ChatMessage type="agent" message={message} />+ </WorkspaceFilesForChatContext.Provider>,+ );+}++describe("assistant chat Markdown path linking", () => {+ beforeEach(() => {+ openWorkspaceFile.mockClear();+ ConversationService.setCurrentConversation(null);+ useFilesTabStore.setState({+ selectedPath: null,+ selectedConversationId: null,+ openPaths: [],+ });+ });++ it("opens the Files drawer when an existing workspace path is clicked", async () => {+ const user = userEvent.setup();++ renderAgentMessage("Created `test.md`");++ await user.click(screen.getByTestId("markdown-file-path-link"));++ expect(openWorkspaceFile).toHaveBeenCalledWith("test.md", "conv-1");+ });++ it("opens the Files drawer for bold-emphasized existing paths", async () => {+ const user = userEvent.setup();++ renderAgentMessage(+ "The file **motivational_message.md** has been created with an inspiring quote.",+ );++ await user.click(screen.getByTestId("markdown-file-path-link"));++ expect(openWorkspaceFile).toHaveBeenCalledWith(+ "motivational_message.md",+ "conv-1",+ );+ });++ it("links absolute nested working-dir paths using ConversationService working_dir", async () => {+ const user = userEvent.setup();+ ConversationService.setCurrentConversation({+ id: "conv-1",+ workspace: { working_dir: "/workspace/project/packages/app" },+ } as never);++ renderAgentMessage("See `/workspace/project/packages/app/src/index.ts`", [+ "src/index.ts",+ ]);++ await user.click(screen.getByTestId("markdown-file-path-link"));++ expect(openWorkspaceFile).toHaveBeenCalledWith("src/index.ts", "conv-1");+ });++ it("does not link paths that are not in the workspace", () => {+ renderAgentMessage("Send me exactly same text - profile.md");++ expect(+ screen.queryByTestId("markdown-file-path-link"),+ ).not.toBeInTheDocument();+ expect(screen.getByText(/profile\.md/)).toBeInTheDocument();+ });++ it("does not link missing backtick paths either", () => {+ renderAgentMessage("See `profile.md` please");++ expect(+ screen.queryByTestId("markdown-file-path-link"),+ ).not.toBeInTheDocument();+ expect(screen.getByText("profile.md").tagName).toBe("CODE");+ });++ it("keeps path code nested in a Markdown link as plain code", () => {+ renderAgentMessage("See [`src/app.ts`](https://example.com)");++ expect(+ screen.queryByTestId("markdown-file-path-link"),+ ).not.toBeInTheDocument();+ expect(screen.getByText("src/app.ts").tagName).toBe("CODE");+ });++ it("does not link ordinary dotted / non-path inline code", () => {+ renderAgentMessage("Use `console.log` and `v1.2.3`");++ expect(+ screen.queryByTestId("markdown-file-path-link"),+ ).not.toBeInTheDocument();+ });+});diff --git a/__tests__/components/features/chat/file-path-chip.test.tsx b/__tests__/components/features/chat/file-path-chip.test.tsxnew file mode 100644index 0000000000..ee69e5ae73--- /dev/null+++ b/__tests__/components/features/chat/file-path-chip.test.tsx@@ -0,0 +1,40 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { FilePathChip } from "#/components/features/chat/tool-visualizers/primitives/file-path-chip";++const openWorkspaceFile = vi.fn();++vi.mock("#/services/canvas-ui", () => ({+ openWorkspaceFile: (...args: unknown[]) => openWorkspaceFile(...args),+}));++vi.mock("#/hooks/use-conversation-id", () => ({+ useOptionalConversationId: () => ({ conversationId: "conv-1" }),+}));++describe("FilePathChip", () => {+ beforeEach(() => {+ openWorkspaceFile.mockClear();+ });++ it("opens the workspace file when clicked without a custom handler", async () => {+ const user = userEvent.setup();+ render(<FilePathChip path="test.md" />);++ await user.click(screen.getByTestId("file-path-chip"));++ expect(openWorkspaceFile).toHaveBeenCalledWith("test.md", "conv-1");+ });++ it("prefers a custom onClick over the default open handler", async () => {+ const user = userEvent.setup();+ const onClick = vi.fn();+ render(<FilePathChip path="test.md" onClick={onClick} />);++ await user.click(screen.getByTestId("file-path-chip"));++ expect(onClick).toHaveBeenCalledTimes(1);+ expect(openWorkspaceFile).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/components/features/chat/path-component.test.tsx b/__tests__/components/features/chat/path-component.test.tsxindex 90ee0e66e6..3fe3411b08 100644--- a/__tests__/components/features/chat/path-component.test.tsx+++ b/__tests__/components/features/chat/path-component.test.tsx@@ -1,5 +1,20 @@-import { describe, expect, it } from "vitest";-import { isLikelyDirectory } from "#/components/features/chat/path-component";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import {+ isLikelyDirectory,+ PathComponent,+} from "#/components/features/chat/path-component";++const openWorkspaceFile = vi.fn();++vi.mock("#/services/canvas-ui", () => ({+ openWorkspaceFile: (...args: unknown[]) => openWorkspaceFile(...args),+}));++vi.mock("#/hooks/use-conversation-id", () => ({+ useOptionalConversationId: () => ({ conversationId: "conv-1" }),+}));describe("isLikelyDirectory", () => {it("should return false for empty path", () => {@@ -32,3 +47,19 @@ describe("isLikelyDirectory", () => {expect(isLikelyDirectory("script.test.ts")).toBe(false);});});++describe("PathComponent", () => {+ beforeEach(() => {+ openWorkspaceFile.mockClear();+ });++ it("opens the workspace file when the path is clicked", async () => {+ const user = userEvent.setup();+ const path = "docs/test.md";+ render(<PathComponent>{path}</PathComponent>);++ await user.click(screen.getByTestId("path-component-link"));++ expect(openWorkspaceFile).toHaveBeenCalledWith(path, "conv-1");+ });+});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.tsxindex c9ee825da8..0f018a1fa2 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,6 +1,7 @@-import { beforeEach, describe, it, expect, vi } from "vitest";+import { beforeEach, describe, it, expect } from "vitest";import { screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";+import ConversationService from "#/api/conversation-service/conversation-service.api";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";@@ -10,19 +11,14 @@ import {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(() => {+ ConversationService.setCurrentConversation({+ id: "test-conversation-id",+ workspace: { working_dir: "/workspace" },+ } as never);useConversationStore.setState({hasRightPanelToggled: false,selectedTab: "terminal",@@ -30,6 +26,7 @@ describe("fileEditorVisualizer", () => {useFilesTabStore.setState({selectedPath: null,selectedConversationId: null,+ openPaths: [],});});diff --git a/__tests__/services/canvas-ui.test.ts b/__tests__/services/canvas-ui.test.tsindex 9eb1193fb6..133e8c8429 100644--- a/__tests__/services/canvas-ui.test.ts+++ b/__tests__/services/canvas-ui.test.ts@@ -1,11 +1,12 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import ConversationService from "#/api/conversation-service/conversation-service.api";import {CANVAS_UI_CLIENT_ACTION_KIND,CANVAS_UI_CLIENT_TOOL_NAME,LEGACY_CANVAS_UI_TOOL_NAME,} from "#/constants/canvas-ui";-import { handleCanvasUIAction } from "#/services/canvas-ui";+import { handleCanvasUIAction, openWorkspaceFile } from "#/services/canvas-ui";import { useConversationStore } from "#/stores/conversation-store";import { useFilesTabStore } from "#/stores/files-tab-store";import type { CanvasUIAction } from "#/types/agent-server/core";@@ -19,9 +20,7 @@ function action(overrides: Partial<CanvasUIAction>): CanvasUIAction {describe("handleCanvasUIAction", () => {beforeEach(() => {- // Arrange (shared): collapsed right panel, no selected file. Lets us- // observe both the tab/panel toggling and the path mutation that the- // dispatcher performs.+ ConversationService.setCurrentConversation(null);useConversationStore.setState({selectedTab: null,isRightPanelShown: false,@@ -30,6 +29,7 @@ describe("handleCanvasUIAction", () => {useFilesTabStore.setState({selectedPath: null,selectedConversationId: null,+ openPaths: [],});});@@ -44,6 +44,7 @@ describe("handleCanvasUIAction", () => {expect(conv.isRightPanelShown).toBe(true);expect(useFilesTabStore.getState().selectedPath).toBe("docs/intro.html");expect(useFilesTabStore.getState().selectedConversationId).toBe("conv-1");+ expect(useFilesTabStore.getState().openPaths).toEqual(["docs/intro.html"]);});it("show_preview selects the files tab and the requested path", () => {@@ -94,6 +95,71 @@ describe("handleCanvasUIAction", () => {expect(useFilesTabStore.getState().selectedPath).toBe("previous.txt");expect(useConversationStore.getState().selectedTab).toBe("files");});++ it("strips the conversation working dir from absolute host paths", () => {+ ConversationService.setCurrentConversation({+ id: "conv-abs",+ workspace: { working_dir: "/Users/me/ws" },+ } as never);++ handleCanvasUIAction(+ action({+ command: "navigate_to_file",+ path: "/Users/me/ws/agentic_ai.docx",+ }),+ "conv-abs",+ );++ expect(useFilesTabStore.getState().selectedPath).toBe("agentic_ai.docx");+ });++ it("strips a nested /workspace working dir before selecting the file", () => {+ ConversationService.setCurrentConversation({+ id: "conv-nested",+ workspace: { working_dir: "/workspace/project/packages/app" },+ } as never);++ handleCanvasUIAction(+ action({+ command: "navigate_to_file",+ path: "/workspace/project/packages/app/src/index.ts",+ }),+ "conv-nested",+ );++ expect(useFilesTabStore.getState().selectedPath).toBe("src/index.ts");+ });+});++describe("openWorkspaceFile", () => {+ beforeEach(() => {+ ConversationService.setCurrentConversation(null);+ useConversationStore.setState({+ selectedTab: null,+ isRightPanelShown: false,+ hasRightPanelToggled: false,+ });+ useFilesTabStore.setState({+ selectedPath: null,+ selectedConversationId: null,+ openPaths: [],+ });+ });++ it("delegates to navigate_to_file with the active conversation", () => {+ ConversationService.setCurrentConversation({+ id: "conv-1",+ workspace: { working_dir: "/Users/me/project" },+ } as never);++ openWorkspaceFile("/Users/me/project/test.md");++ expect(useConversationStore.getState().selectedTab).toBe("files");+ expect(useConversationStore.getState().isRightPanelShown).toBe(true);+ expect(useFilesTabStore.getState().selectedPath).toBe("test.md");+ expect(useFilesTabStore.getState().selectedConversationId).toBe("conv-1");+ expect(useFilesTabStore.getState().openPaths).toEqual(["test.md"]);+ });});describe("isCanvasUIActionEvent", () => {diff --git a/__tests__/utils/path-utils.test.ts b/__tests__/utils/path-utils.test.tsindex 390adb7ca3..27b7c70bf9 100644--- a/__tests__/utils/path-utils.test.ts+++ b/__tests__/utils/path-utils.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from "vitest";-import { getPathBasename, stripWorkspacePrefix } from "#/utils/path-utils";+import {+ getPathBasename,+ looksLikeWorkspaceFilePath,+ stripWorkspacePrefix,+ toFilesTabPath,+} from "#/utils/path-utils";describe("getPathBasename", () => {it("returns an empty string for empty or whitespace-only input", () => {@@ -54,3 +59,33 @@ describe("stripWorkspacePrefix", () => {expect(stripWorkspacePrefix("")).toBe("");});});++describe("toFilesTabPath", () => {+ it("strips workspace and working-dir prefixes", () => {+ expect(toFilesTabPath("/workspace/repo/src/a.ts")).toBe("src/a.ts");+ expect(toFilesTabPath("/Users/me/ws/a.ts", "/Users/me/ws")).toBe("a.ts");+ });++ it("aliases toWorkspaceRelativePath for Files-drawer callers", () => {+ expect(toFilesTabPath("/workspace/project/a.ts")).toBe("a.ts");+ expect(toFilesTabPath("src/a.ts:12-40", "/workspace/project")).toBe(+ "src/a.ts",+ );+ });+});++describe("looksLikeWorkspaceFilePath", () => {+ it("accepts common workspace file tokens", () => {+ expect(looksLikeWorkspaceFilePath("test.md")).toBe(true);+ expect(looksLikeWorkspaceFilePath("src/app.ts")).toBe(true);+ expect(looksLikeWorkspaceFilePath("docs/guide.md:12")).toBe(true);+ });++ it("rejects non-path dotted tokens, versions, MIME types, and URLs", () => {+ expect(looksLikeWorkspaceFilePath("console.log")).toBe(false);+ expect(looksLikeWorkspaceFilePath("v1.2.3")).toBe(false);+ expect(looksLikeWorkspaceFilePath("application/json")).toBe(false);+ expect(looksLikeWorkspaceFilePath("https://example.com/a.ts")).toBe(false);+ expect(looksLikeWorkspaceFilePath("bareword")).toBe(false);+ });+});diff --git a/__tests__/utils/workspace-relative-path.test.ts b/__tests__/utils/workspace-relative-path.test.tsindex dac077e099..352bf05604 100644--- a/__tests__/utils/workspace-relative-path.test.ts+++ b/__tests__/utils/workspace-relative-path.test.ts@@ -31,4 +31,29 @@ describe("toWorkspaceRelativePath", () => {"canvas.md",);});++ it("strips a nested working dir before the generic /workspace/<name>/ fallback", () => {+ const workingDir = "/workspace/project/packages/app";+ expect(+ toWorkspaceRelativePath(+ "/workspace/project/packages/app/src/index.ts",+ workingDir,+ ),+ ).toBe("src/index.ts");+ expect(+ toWorkspaceRelativePath(+ "/workspace/project/packages/app/src/index.ts:12",+ workingDir,+ ),+ ).toBe("src/index.ts");+ expect(toWorkspaceRelativePath(workingDir, workingDir)).toBe("");+ });++ it("strips editor line suffixes from POSIX and Windows paths", () => {+ expect(toWorkspaceRelativePath("src/a.ts:12")).toBe("src/a.ts");+ expect(toWorkspaceRelativePath("src/a.ts:12-40")).toBe("src/a.ts");+ expect(toWorkspaceRelativePath("C:\\repo\\src\\a.ts:12", "C:\\repo")).toBe(+ "src/a.ts",+ );+ });});diff --git a/src/components/conversation-events/chat/event-message-components/event-group.tsx b/src/components/conversation-events/chat/event-message-components/event-group.tsxindex 1e373bab95..22f61eb3a8 100644--- a/src/components/conversation-events/chat/event-message-components/event-group.tsx+++ b/src/components/conversation-events/chat/event-message-components/event-group.tsx@@ -11,6 +11,7 @@ import {import { I18nKey } from "#/i18n/declaration";import { getEventContent } from "../event-content-helpers/get-event-content";import { IsInEventGroupContext } from "../../../features/chat/is-in-event-group-context";+import { PathInteractiveContext } from "../../../features/chat/path-component";interface EventGroupProps {/** The events represented by this group. Used to compute the summary. */@@ -131,7 +132,11 @@ export function EventGroup({<><span className="flex items-center gap-2 min-w-0 font-normal text-[var(--oh-muted)]"><Chevron className="h-4 w-4 fill-[var(--oh-muted)] flex-shrink-0" />- <span className="truncate">{latestTitle ?? countSummary}</span>+ <span className="truncate">+ <PathInteractiveContext.Provider value={false}>+ {latestTitle ?? countSummary}+ </PathInteractiveContext.Provider>+ </span></span><span className="flex items-center flex-shrink-0 font-normal text-[var(--oh-muted)]"><span className="truncate">{countSummary}</span>diff --git a/src/components/features/chat/chat-interface.tsx b/src/components/features/chat/chat-interface.tsxindex a4f2e9a32b..967fd4a8c4 100644--- a/src/components/features/chat/chat-interface.tsx+++ b/src/components/features/chat/chat-interface.tsx@@ -15,6 +15,8 @@ import { AgentState } from "#/types/agent-state";import { useFilteredEvents } from "#/hooks/use-filtered-events";import { useScrollToBottom } from "#/hooks/use-scroll-to-bottom";import { useLoadOlderEvents } from "#/hooks/use-load-older-events";+import { useAutoRefreshFilesOnEdit } from "#/hooks/use-auto-refresh-files-on-edit";+import { WorkspaceFilesForChatProvider } from "./chat-markdown-path-code";import { TypingIndicator } from "./typing-indicator";import { ChatSuggestions } from "./chat-suggestions";import { ScrollProvider } from "#/context/scroll-context";@@ -62,6 +64,8 @@ function getEntryPoint(}export function ChatInterface() {+ useAutoRefreshFilesOnEdit();+const { trackInitialQuerySubmitted, trackUserMessageSent } = useTracking();const { setMessageToSend, conversationMode, planContent } =useConversationStore();@@ -486,83 +490,90 @@ export function ChatInterface() {});return (- <ScrollProvider value={scrollProviderValue}>- <div- className="relative flex h-full flex-col justify-between px-4"- data-testid="chat-interface"- >- {!hasSubstantiveAgentActions &&- !hasPendingUserMessages &&- !userEventsExist &&- !hasModelEntries &&- !isChatLoading &&- !isProvisioningTask &&- totalEvents === 0 &&- !isArchivedConversation &&- // With no usable LLM the suggestions can't be acted on (the input is- // disabled). They're also a `pointer-events-auto` overlay that would- // sit over the LlmNotConfiguredBanner below and swallow clicks on its- // setup button β so hide them and let the banner be the lone CTA.- !llmBlocked && (- <ChatSuggestions- onSuggestionsClick={(message) => setMessageToSend(message)}- />- )}- {/* Note: We only hide chat suggestions when there's a user message */}-+ <WorkspaceFilesForChatProvider>+ <ScrollProvider value={scrollProviderValue}><div- ref={scrollRef}- data-testid="chat-scroll-container"- onScroll={(e) => {- onChatBodyScroll(e.currentTarget);- maybeLoadOlder(e.currentTarget);- }}- onWheel={handleWheelForPagination}- className="custom-scrollbar-always flex min-h-0 grow flex-col gap-2 overflow-x-hidden overflow-y-auto px-0 pt-4 pb-8 md:px-4"+ className="relative flex h-full flex-col justify-between px-4"+ data-testid="chat-interface">- {isChatLoading && isReturningToConversation && (- <ChatMessagesSkeleton />- )}-- {isChatLoading && !isReturningToConversation && (- <div className="flex justify-center" data-testid="loading-spinner">- <LoadingSpinner size="small" />- </div>- )}-- {isLoadingOlderEvents && (- <div- className="flex items-center justify-center gap-2 py-3 text-sm text-neutral-400"- data-testid="loading-older-events"- >- <LoadingSpinner size="small" />- <span>{t(I18nKey.CHAT_INTERFACE$FETCHING_OLDER_MESSAGES)}</span>- </div>- )}-- {/*- * Render whenever there's anything to display. Previously this- * was gated on `conversationUserEventsExist`, but with the lazy- * "50 most recent" REST fetch the initial window may not include- * any `source: "user"` events (long agent runs between user- * turns). That left the chat blank, leaving the user nothing to- * scroll β which is why "scroll up to load older" appeared- * broken. The empty-state ChatSuggestions block above still- * keeps its own gate (`!userEventsExist && !hasSubstantiveAgentActions`)- * so brand-new conversations show suggestions, not an empty chat.- */}- {/* /model entries created before any event is rendered are+ {!hasSubstantiveAgentActions &&+ !hasPendingUserMessages &&+ !userEventsExist &&+ !hasModelEntries &&+ !isChatLoading &&+ !isProvisioningTask &&+ totalEvents === 0 &&+ !isArchivedConversation &&+ // With no usable LLM the suggestions can't be acted on (the input is+ // disabled). They're also a `pointer-events-auto` overlay that would+ // sit over the LlmNotConfiguredBanner below and swallow clicks on its+ // setup button β so hide them and let the banner be the lone CTA.+ !llmBlocked && (+ <ChatSuggestions+ onSuggestionsClick={(message) => setMessageToSend(message)}+ />+ )}+ {/* Note: We only hide chat suggestions when there's a user message */}++ <div+ ref={scrollRef}+ data-testid="chat-scroll-container"+ onScroll={(e) => {+ onChatBodyScroll(e.currentTarget);+ maybeLoadOlder(e.currentTarget);+ }}+ onWheel={handleWheelForPagination}+ className="custom-scrollbar-always flex min-h-0 grow flex-col gap-2 overflow-x-hidden overflow-y-auto px-0 pt-4 pb-8 md:px-4"+ >+ {isChatLoading && isReturningToConversation && (+ <ChatMessagesSkeleton />+ )}++ {isChatLoading && !isReturningToConversation && (+ <div+ className="flex justify-center"+ data-testid="loading-spinner"+ >+ <LoadingSpinner size="small" />+ </div>+ )}++ {isLoadingOlderEvents && (+ <div+ className="flex items-center justify-center gap-2 py-3 text-sm text-neutral-400"+ data-testid="loading-older-events"+ >+ <LoadingSpinner size="small" />+ <span>{t(I18nKey.CHAT_INTERFACE$FETCHING_OLDER_MESSAGES)}</span>+ </div>+ )}++ {/*+ * Render whenever there's anything to display. Previously this+ * was gated on `conversationUserEventsExist`, but with the lazy+ * "50 most recent" REST fetch the initial window may not include+ * any `source: "user"` events (long agent runs between user+ * turns). That left the chat blank, leaving the user nothing to+ * scroll β which is why "scroll up to load older" appeared+ * broken. The empty-state ChatSuggestions block above still+ * keeps its own gate (`!userEventsExist && !hasSubstantiveAgentActions`)+ * so brand-new conversations show suggestions, not an empty chat.+ */}+ {/* /model entries created before any event is rendered areanchored to `null` and live above the message list. */}- <ModelMessages conversationId={conversationId} anchorEventId={null} />-- {showConversationMessages && renderableEvents.length > 0 && (- <Messages- messages={renderableEvents}- allEvents={allConversationEvents}+ <ModelMessages+ conversationId={conversationId}+ anchorEventId={null}/>- )}- {/*+ {showConversationMessages && renderableEvents.length > 0 && (+ <Messages+ messages={renderableEvents}+ allEvents={allConversationEvents}+ />+ )}++ {/*Render the local pending-message queue independently so messagesthe user just submitted show up immediately (with a faded "sending"treatment) even before any real conversation event has come back@@ -570,92 +581,95 @@ export function ChatInterface() {UserMessageEvent echoes back over the WebSocket, so this neverdouble-renders alongside the real event list.*/}- <PendingUserMessages />+ <PendingUserMessages />- {/* Goal-loop status sits at the end of the message flow β above the+ {/* Goal-loop status sits at the end of the message flow β above thecomposer and its typing indicator β so progress stays in view. */}- <GoalStatusBanner conversationId={conversationId} />- </div>+ <GoalStatusBanner conversationId={conversationId} />+ </div>++ <div className="flex shrink-0 flex-col gap-[6px] pb-4">+ <SkillInstallRestartBanner conversationId={conversationId} />+ <BtwMessages conversationId={conversationId} />+ {errorMessage && (+ <ErrorMessageBanner+ message={errorMessage}+ code={errorCode}+ classification={errorClassification}+ onDismiss={removeErrorMessage}+ onRetry={+ errorMessage === SERVER_CONNECTION_ERROR_MESSAGE+ ? () => conversationWebSocket?.reconnect()+ : undefined+ }+ onReauth={+ isAcpAuthErrorCode(errorCode)+ ? () => navigate("/settings/agents")+ : undefined+ }+ />+ )}++ {llmBlocked && !isArchivedConversation && (+ <LlmNotConfiguredBanner />+ )}++ {isArchivedConversation ? (+ // Archived / sandbox-error: show a read-only notice in place of+ // the chat input. The conversation history above is still visible.+ <div+ data-testid="archived-conversation-banner"+ className="mx-1 px-4 py-3 rounded-lg bg-[var(--oh-surface)] border border-[var(--oh-border-subtle)]"+ >+ <p className="text-xs font-semibold text-[var(--oh-foreground)]">+ {sandboxStatus === "ERROR"+ ? t(I18nKey.CHAT_INTERFACE$ERROR_SANDBOX_TITLE)+ : t(I18nKey.CHAT_INTERFACE$ARCHIVED_SANDBOX_TITLE)}+ </p>+ <p className="text-xs text-[var(--oh-muted)] mt-0.5">+ {sandboxStatus === "ERROR"+ ? t(I18nKey.CHAT_INTERFACE$ERROR_SANDBOX_DESCRIPTION)+ : t(I18nKey.CHAT_INTERFACE$ARCHIVED_SANDBOX_DESCRIPTION)}+ </p>+ </div>+ ) : (+ <div className="relative">+ <div className="pointer-events-none absolute inset-x-0 bottom-full mb-1 z-20">+ <div className="flex justify-between relative">+ <div className="flex items-end gap-1 pointer-events-auto">+ <ConfirmationModeEnabled />+ {isStartingStatus && (+ <ChatStatusIndicator+ statusColor={serverStatusColor}+ status={serverStatusText}+ />+ )}+ </div>- <div className="flex shrink-0 flex-col gap-[6px] pb-4">- <SkillInstallRestartBanner conversationId={conversationId} />- <BtwMessages conversationId={conversationId} />- {errorMessage && (- <ErrorMessageBanner- message={errorMessage}- code={errorCode}- classification={errorClassification}- onDismiss={removeErrorMessage}- onRetry={- errorMessage === SERVER_CONNECTION_ERROR_MESSAGE- ? () => conversationWebSocket?.reconnect()- : undefined- }- onReauth={- isAcpAuthErrorCode(errorCode)- ? () => navigate("/settings/agents")- : undefined- }- />- )}-- {llmBlocked && !isArchivedConversation && <LlmNotConfiguredBanner />}-- {isArchivedConversation ? (- // Archived / sandbox-error: show a read-only notice in place of- // the chat input. The conversation history above is still visible.- <div- data-testid="archived-conversation-banner"- className="mx-1 px-4 py-3 rounded-lg bg-[var(--oh-surface)] border border-[var(--oh-border-subtle)]"- >- <p className="text-xs font-semibold text-[var(--oh-foreground)]">- {sandboxStatus === "ERROR"- ? t(I18nKey.CHAT_INTERFACE$ERROR_SANDBOX_TITLE)- : t(I18nKey.CHAT_INTERFACE$ARCHIVED_SANDBOX_TITLE)}- </p>- <p className="text-xs text-[var(--oh-muted)] mt-0.5">- {sandboxStatus === "ERROR"- ? t(I18nKey.CHAT_INTERFACE$ERROR_SANDBOX_DESCRIPTION)- : t(I18nKey.CHAT_INTERFACE$ARCHIVED_SANDBOX_DESCRIPTION)}- </p>- </div>- ) : (- <div className="relative">- <div className="pointer-events-none absolute inset-x-0 bottom-full mb-1 z-20">- <div className="flex justify-between relative">- <div className="flex items-end gap-1 pointer-events-auto">- <ConfirmationModeEnabled />- {isStartingStatus && (- <ChatStatusIndicator- statusColor={serverStatusColor}- status={serverStatusText}- />+ {!hitBottom ? (+ <div className="absolute left-1/2 transform -translate-x-1/2 bottom-0 pointer-events-auto">+ <ScrollToBottomButton onClick={scrollDomToBottom} />+ </div>+ ) : (+ curAgentState === AgentState.RUNNING && (+ <div className="pointer-events-none absolute inset-x-9 bottom-0 flex justify-center">+ <TypingIndicator events={allConversationEvents} />+ </div>+ ))}</div>-- {!hitBottom ? (- <div className="absolute left-1/2 transform -translate-x-1/2 bottom-0 pointer-events-auto">- <ScrollToBottomButton onClick={scrollDomToBottom} />- </div>- ) : (- curAgentState === AgentState.RUNNING && (- <div className="pointer-events-none absolute inset-x-9 bottom-0 flex justify-center">- <TypingIndicator events={allConversationEvents} />- </div>- )- )}</div>- </div>- <InteractiveChatBox- onSubmit={handleSendMessage}- disabled={isNewConversationPending || llmBlocked}- hasStartedConversation={hasStartedConversation}- />- </div>- )}+ <InteractiveChatBox+ onSubmit={handleSendMessage}+ disabled={isNewConversationPending || llmBlocked}+ hasStartedConversation={hasStartedConversation}+ />+ </div>+ )}+ </div></div>- </div>- </ScrollProvider>+ </ScrollProvider>+ </WorkspaceFilesForChatProvider>);}diff --git a/src/components/features/chat/chat-markdown-path-code.tsx b/src/components/features/chat/chat-markdown-path-code.tsxnew file mode 100644index 0000000000..bfafd3e7e8--- /dev/null+++ b/src/components/features/chat/chat-markdown-path-code.tsx@@ -0,0 +1,161 @@+import React, { createContext, useContext } from "react";+import type { ExtraProps } from "react-markdown";+import ConversationService from "#/api/conversation-service/conversation-service.api";+import { useOptionalConversationId } from "#/hooks/use-conversation-id";+import { useWorkspaceFiles } from "#/hooks/query/use-workspace-files";+import { openWorkspaceFile } from "#/services/canvas-ui";+import { looksLikeWorkspaceFilePath, toFilesTabPath } from "#/utils/path-utils";+import { cn } from "#/utils/utils";+import { code as defaultCode } from "../markdown/code";+import { anchor as defaultAnchor } from "../markdown/anchor";++/** True while rendering Markdown descendants of an existing `<a>`. */+const InMarkdownLinkContext = createContext(false);++/**+ * Workspace paths available for chat Markdown linking. Absent outside+ * ChatInterface (e.g. unit tests) so ChatCode never requires QueryClient.+ */+export const WorkspaceFilesForChatContext = createContext<string[] | undefined>(+ undefined,+);++/** Fetches workspace files once for the chat tree and exposes them to path links. */+export function WorkspaceFilesForChatProvider({+ children,+}: {+ children: React.ReactNode;+}) {+ const { data } = useWorkspaceFiles();+ return (+ <WorkspaceFilesForChatContext.Provider value={data}>+ {children}+ </WorkspaceFilesForChatContext.Provider>+ );+}++type CodeProps = React.ClassAttributes<HTMLElement> &+ React.HTMLAttributes<HTMLElement> &+ ExtraProps;++type AnchorProps = React.ClassAttributes<HTMLAnchorElement> &+ React.AnchorHTMLAttributes<HTMLAnchorElement> &+ ExtraProps;++type StrongProps = React.ClassAttributes<HTMLElement> &+ React.HTMLAttributes<HTMLElement> &+ ExtraProps;++/** Flatten React children to plain text, or null if mixed nodes. */+function getPlainText(children: React.ReactNode): string | null {+ if (children == null || typeof children === "boolean") return "";+ if (typeof children === "string" || typeof children === "number") {+ return String(children);+ }+ if (Array.isArray(children)) {+ const parts = children.map(getPlainText);+ if (parts.some((part) => part === null)) return null;+ return parts.join("");+ }+ return null;+}++/**+ * Only link paths that currently exist in the conversation workspace.+ * workingDir comes from ConversationService β same source as navigate_to_file.+ */+function useExistingWorkspacePath(candidate: string): string | null {+ const files = useContext(WorkspaceFilesForChatContext);+ if (!files?.length || !looksLikeWorkspaceFilePath(candidate)) return null;++ const workingDir =+ ConversationService.getCurrentConversation()?.workspace?.working_dir;+ const normalized = toFilesTabPath(candidate, workingDir);+ if (!normalized) return null;+ return files.includes(normalized) ? normalized : null;+}++function ChatMarkdownPathLink({+ path,+ className,+ children,+}: {+ path: string;+ className?: string;+ children: React.ReactNode;+}) {+ const { conversationId } = useOptionalConversationId();++ return (+ <button+ type="button"+ data-testid="markdown-file-path-link"+ title={path}+ className={cn(+ className,+ "cursor-pointer rounded border border-surface-raised bg-surface-raised px-[0.4em] py-[0.2em] font-mono text-foreground hover:underline",+ )}+ onClick={(event) => {+ event.stopPropagation();+ openWorkspaceFile(path, conversationId);+ }}+ >+ {children}+ </button>+ );+}++/**+ * Chat-only inline code: existing workspace paths become Files-drawer buttons.+ * Nested under an existing Markdown link β stay plain `<code>`.+ */+export function ChatCode(props: CodeProps) {+ const { children, className } = props;+ const inLink = useContext(InMarkdownLinkContext);+ const match = /language-(\w+)/.exec(className || "");+ const codeString = String(children).replace(/\n$/, "");+ const isMultiline = String(children).includes("\n");+ const existingPath = useExistingWorkspacePath(+ !match && !isMultiline && !inLink ? codeString : "",+ );++ if (existingPath) {+ return (+ <ChatMarkdownPathLink path={existingPath} className={className}>+ {children}+ </ChatMarkdownPathLink>+ );+ }++ return defaultCode(props);+}++/**+ * Agents often emphasize paths with `**file.md**` instead of backticks.+ * Link those only when the whole strong span is an existing workspace file.+ */+export function ChatStrong(props: StrongProps) {+ const { children } = props;+ const inLink = useContext(InMarkdownLinkContext);+ const text = getPlainText(children)?.trim() ?? "";+ const existingPath = useExistingWorkspacePath(!inLink ? text : "");++ if (existingPath) {+ return (+ <ChatMarkdownPathLink path={existingPath}>+ {children}+ </ChatMarkdownPathLink>+ );+ }++ return <strong>{children}</strong>;+}++/** Marks descendants so nested path tokens are not turned into a button. */+export function ChatAnchor(props: AnchorProps) {+ return (+ <InMarkdownLinkContext.Provider value>+ {defaultAnchor(props)}+ </InMarkdownLinkContext.Provider>+ );+}diff --git a/src/components/features/chat/path-component.tsx b/src/components/features/chat/path-component.tsxindex 9e0d5a71df..06bb2d0ef2 100644--- a/src/components/features/chat/path-component.tsx+++ b/src/components/features/chat/path-component.tsx@@ -1,6 +1,15 @@-import { ReactNode } from "react";+import { createContext, ReactNode, useContext } from "react";+import { useOptionalConversationId } from "#/hooks/use-conversation-id";+import { openWorkspaceFile } from "#/services/canvas-ui";import EventLogger from "#/utils/event-logger";+/**+ * When false, PathComponent renders a non-interactive span. EventGroup's+ * header wraps titles in a toggle <button>, so nested path buttons would be+ * invalid markup β that context sets this to false.+ */+export const PathInteractiveContext = createContext(true);+/*** Decodes HTML entities in a string* @param text The text to decode@@ -47,28 +56,43 @@ const extractFilename = (path: string): string => {};/**- * Component that displays only the filename in the text but shows the full path on hover- * Similar to MonoComponent but with path-specific functionality+ * Displays only the filename, with the full path on hover.+ * Click opens the Files drawer on that path (when interactive).*/function PathComponent(props: { children?: ReactNode }) {const { children } = props;+ const { conversationId } = useOptionalConversationId();+ const interactive = useContext(PathInteractiveContext);const processPath = (path: string) => {try {- // First decode any HTML entities in the pathconst decodedPath = decodeHtmlEntities(path);- // Extract the filename from the decoded pathconst filename = extractFilename(decodedPath);+ if (!interactive) {+ return (+ <span+ className="font-mono font-normal tracking-tight"+ title={decodedPath}+ >+ {filename}+ </span>+ );+ }return (- <span- className="font-mono font-normal tracking-tight"+ <button+ type="button"+ data-testid="path-component-link"+ className="cursor-pointer font-mono font-normal tracking-tight hover:underline"title={decodedPath}+ onClick={(event) => {+ event.stopPropagation();+ openWorkspaceFile(decodedPath, conversationId);+ }}>{filename}- </span>+ </button>);} catch (e) {- // Just log the error without any message to avoid localization issuesEventLogger.error(String(e));return (<span className="font-mono font-normal tracking-tight">{path}</span>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.tsxindex f33335477f..335f33ef61 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@@ -12,11 +12,8 @@*/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 { openWorkspaceFile } from "#/services/canvas-ui";import type {FileEditorAction,StrReplaceEditorAction,@@ -160,30 +157,19 @@ function FileEditorCardBody({/*** 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).+ * card so conversation-only navigation never runs outside a conversation route.*/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");- }+ ? () => openWorkspaceFile(path, conversationId): undefined;return <FileEditorCardBody {...props} onOpenFile={onOpenFile} />;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.tsxindex 6ac0fe8a67..21939246d3 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@@ -1,21 +1,27 @@-import React from "react";import FileIcon from "#/icons/file.svg?react";+import { useOptionalConversationId } from "#/hooks/use-conversation-id";+import { openWorkspaceFile } from "#/services/canvas-ui";interface FilePathChipProps {path: string;/** Optional line-range suffix, e.g. "12-48". */range?: string;- /** Opens the referenced file when the surrounding visualizer can navigate. */+ /**+ * Opens the referenced file when the surrounding visualizer can navigate.+ * Defaults to `openWorkspaceFile` so chips without a parent handler still+ * deep-link into the Files drawer.+ */onClick?: () => void;}/*** 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.+ * Passing `onClick` upgrades the same visual language to a custom handler+ * (e.g. markdown artifact View). Without it, click opens the Files drawer.*/export function FilePathChip({ path, range, onClick }: FilePathChipProps) {+ const { conversationId } = useOptionalConversationId();const content = (<><FileIcon className="h-3.5 w-3.5 flex-shrink-0 text-muted" />@@ -23,19 +29,24 @@ export function FilePathChip({ path, range, onClick }: FilePathChipProps) {</>);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";+ "inline-flex max-w-full cursor-pointer items-center gap-1.5 self-start rounded bg-surface-raised px-2 py-0.5 text-left font-mono text-xs text-foreground hover:bg-[var(--oh-interactive-hover)]";- 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>;+ return (+ <button+ type="button"+ data-testid="file-path-chip"+ title={path}+ className={className}+ onClick={(event) => {+ event.stopPropagation();+ if (onClick) {+ onClick();+ return;+ }+ openWorkspaceFile(path, conversationId);+ }}+ >+ {content}+ </button>+ );}diff --git a/src/components/features/chat/user-message-body.tsx b/src/components/features/chat/user-message-body.tsxindex 4da4e98792..29f023e34d 100644--- a/src/components/features/chat/user-message-body.tsx+++ b/src/components/features/chat/user-message-body.tsx@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";import { cn } from "#/utils/utils";import { I18nKey } from "#/i18n/declaration";import { MarkdownRenderer } from "../markdown/markdown-renderer";+import { ChatAnchor, ChatCode, ChatStrong } from "./chat-markdown-path-code";const USER_MESSAGE_MAX_LINES = 5;const USER_MESSAGE_LENGTH_THRESHOLD = 360;@@ -12,6 +13,9 @@ export const chatBubbleMarkdownComponents = {p: ({ children }: React.ComponentProps<"p">) => (<p className="m-0 leading-6">{children}</p>),+ code: ChatCode,+ a: ChatAnchor,+ strong: ChatStrong,};export function UserMessageBody({diff --git a/src/services/canvas-ui.ts b/src/services/canvas-ui.tsindex 583eb08d2a..c6b90c8fba 100644--- a/src/services/canvas-ui.ts+++ b/src/services/canvas-ui.ts@@ -1,9 +1,11 @@+import ConversationService from "#/api/conversation-service/conversation-service.api";import {ConversationTab,useConversationStore,} from "#/stores/conversation-store";import { useFilesTabStore } from "#/stores/files-tab-store";import type { CanvasUIAction } from "#/types/agent-server/core";+import { toFilesTabPath } from "#/utils/path-utils";const VALID_TABS: ReadonlySet<ConversationTab> = new Set<ConversationTab>(["files",@@ -29,20 +31,43 @@ function isValidTab(value: string): value is ConversationTab {return VALID_TABS.has(value as ConversationTab);}+/**+ * Chat path click β same as agent `navigate_to_file`.+ * Optional `conversationId` tags the selection so FilesTab accepts it.+ */+export function openWorkspaceFile(+ path: string,+ conversationId?: string | null,+): void {+ const conversation = ConversationService.getCurrentConversation();+ handleCanvasUIAction(+ {+ kind: "CanvasUIAction",+ command: "navigate_to_file",+ path,+ } as CanvasUIAction,+ conversationId ?? conversation?.id ?? null,+ );+}+export function handleCanvasUIAction(action: CanvasUIAction,conversationId: string | null = null,): void {switch (action.command) {case "navigate_to_file":- case "show_preview":+ case "show_preview": {navigateToTab("files");- if (action.path) {- useFilesTabStore- .getState()- .setSelectedPath(action.path, conversationId);- }+ if (!action.path) return;++ const workingDir =+ ConversationService.getCurrentConversation()?.workspace?.working_dir;+ const path = toFilesTabPath(action.path, workingDir);+ if (!path) return;++ useFilesTabStore.getState().setSelectedPath(path, conversationId);return;+ }case "open_tab":if (action.tab === "vscode") {// The in-app VS Code tab was removed β on cloud backends VS Codediff --git a/src/utils/path-utils.ts b/src/utils/path-utils.tsindex f17d33fe5d..f5e81b6e50 100644--- a/src/utils/path-utils.ts+++ b/src/utils/path-utils.ts@@ -1,6 +1,7 @@/*** Path manipulation utilities*/+import { DEFAULT_WORKING_DIR } from "#/api/agent-server-config";/*** Strip workspace prefix from file paths@@ -19,6 +20,89 @@ export const stripWorkspacePrefix = (path: string): string => {return workspaceMatch ? workspaceMatch[1] : path;};+function normalizeWorkspaceRoot(root: string): string {+ const trimmed = root.trim().replace(/\\/g, "/").replace(/\/+$/, "");+ if (!trimmed) return "";+ // Keep Windows drive roots (`C:` / `C:/repo`) and POSIX absolutes as-is.+ if (trimmed.startsWith("/") || /^[A-Za-z]:(\/|$)/.test(trimmed)) {+ return trimmed;+ }+ return `/${trimmed}`;+}++/**+ * Convert an agent/chat file path into a workspace-relative path for the Files+ * drawer / workspace file APIs.+ *+ * Strips editor `:line` / `:start-end` suffixes, then removes the conversation+ * working directory (or `DEFAULT_WORKING_DIR`) when present as a prefix.+ * Nested roots must match `workingDir` first β the generic `/workspace/<name>/`+ * heuristic is only a fallback when no root matches.+ */+export const toFilesTabPath = (+ path: string,+ workingDir?: string | null,+): string => {+ let result = path.trim().replace(/\\/g, "/");+ if (!result) return "";++ // Strip editor `:12` / `:12-40` suffixes. Safe on Windows paths too β+ // the drive colon is at the start (`C:`), never at the end.+ result = result.replace(/:(\d+)(-\d+)?$/, "");++ const roots = [workingDir, DEFAULT_WORKING_DIR].filter(+ (value): value is string => Boolean(value?.trim()),+ );++ for (const root of roots) {+ const normalizedRoot = normalizeWorkspaceRoot(root);+ if (!normalizedRoot) continue;+ if (result === normalizedRoot) {+ return "";+ }+ if (result.startsWith(`${normalizedRoot}/`)) {+ return result.slice(normalizedRoot.length + 1);+ }+ }++ if (!result.startsWith("/")) {+ return result.replace(/^\.\//, "");+ }++ return stripWorkspacePrefix(result).replace(/^\.\//, "");+};++const WORKSPACE_FILE_EXTENSION =+ /\.(md|txt|ts|tsx|js|jsx|mjs|cjs|py|json|html?|css|scss|ya?ml|toml|rs|go|java|kt|swift|c|cc|cpp|h|hpp|sh|bash|zsh|sql|xml|svg|pdf|env|rb|php|vue|svelte|lock|ini|cfg|docx?|xlsx?|pptx?|odt|rtf)$/i;++/**+ * Conservative check for inline chat tokens that should open in Files.+ * Rejects URLs, MIME types, versions, and dotted identifiers like `console.log`.+ */+export const looksLikeWorkspaceFilePath = (text: string): boolean => {+ const trimmed = text.trim();+ if (!trimmed || /\s/.test(trimmed) || /^https?:\/\//i.test(trimmed)) {+ return false;+ }++ let path = trimmed.replace(/\\/g, "/").replace(/^\.\//, "");+ path = path.replace(/:(\d+)(-\d+)?$/, "");++ if (+ /^(application|audio|image|text|video|font|multipart|message|model)\/[\w.+-]+$/i.test(+ path,+ )+ ) {+ return false;+ }+ if (/^v?\d+(\.\d+){1,3}([-+][\w.]+)?$/i.test(path)) {+ return false;+ }++ const lastSegment = path.includes("/") ? (path.split("/").pop() ?? "") : path;+ return WORKSPACE_FILE_EXTENSION.test(lastSegment);+};+/*** Returns the basename (top-level folder/file name) from a path string,* tolerating POSIX and Windows separators and trailing slashes.diff --git a/src/utils/workspace-relative-path.ts b/src/utils/workspace-relative-path.tsindex 49ab8343ee..0c93afd031 100644--- a/src/utils/workspace-relative-path.ts+++ b/src/utils/workspace-relative-path.ts@@ -1,46 +1,7 @@-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.+ * Workspace-relative path helpers for 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`).+ * Implementation lives in path-utils (`toFilesTabPath`) so chat links,+ * canvas_ui navigation, and markdown artifact View share one normalizer.*/-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(/^\/+/, "");-}+export { toFilesTabPath as toWorkspaceRelativePath } from "./path-utils";