diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 561bcd2b3e04..8fe7d65356a4 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -35,7 +35,7 @@ import { useFilesystemReadAccess } from "~/state/filesystem"; import { useOpenInPreferredEditor } from "../editorPreferences"; import { useFileContextMenuHandler } from "../fileContextMenu"; import { type DraftId } from "../composerDraftStore"; -import { openDiffFilePrimaryAction } from "../diffFileActions"; +import { openDiffFilePrimaryAction, resolveDiffPathForWorkspace } from "../diffFileActions"; import { toolCallDiff } from "../lib/toolCallDiff"; import { useCheckpointDiff, useTurnItemDetail } from "~/state/queries"; import { revisionedQuery } from "~/state/revisionedQuery"; @@ -862,6 +862,16 @@ export default function DiffPanel({ )?.cwd, }; }; + // A mention names the file from the thread's folder, the way the file viewer opens it. + const threadMentionPath = (filePath: string) => { + const repositoryFile = repositoryFileTarget(filePath); + if (repositoryFile?.insideThreadFolder === false) return null; + return resolveDiffPathForWorkspace({ + filePath, + workspaceRoot: activeCwd, + repositoryRoot: repositoryFile ? undefined : diffPathRepositoryRoot, + }); + }; const openDiffFile = (filePath: string) => { const repositoryFile = repositoryFileTarget(filePath); openDiffFilePrimaryAction({ @@ -1798,6 +1808,8 @@ export default function DiffPanel({ selectedPath={selectedFilePath} revealRequestId={selectedFileRevealRequestId} onSelectFile={revealDiffFile} + workspaceRoot={activeCwd} + mentionPath={threadMentionPath} /> ) : null} diff --git a/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx b/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx index 73b99454faa8..32373806fb46 100644 --- a/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx @@ -2,6 +2,9 @@ import { FileTree } from "@pierre/trees"; import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; +import { ComposerHandleContext, type ComposerHandleRef } from "~/composerHandleContext"; +import { dismissContextMenu } from "~/contextMenuFallback"; + import { render } from "../../../test/render"; import { DiffFileTree, type DiffFileTreeEntry } from "./DiffFileTree"; @@ -16,7 +19,12 @@ it("expands every folder without asking the tree about all folders for each one" using getItem = vi.spyOn(FileTree.prototype, "getItem"); await using _screen = await render(
- {}} ariaLabel="Changed files" /> + {}} + workspaceRoot="/repo" + ariaLabel="Changed files" + />
, ); const collapseAll = page.getByRole("button", { name: "Collapse all folders" }); @@ -31,3 +39,80 @@ it("expands every folder without asking the tree about all folders for each one" // grew with the square of the folder count (hundreds of thousands at 600 folders). expect(getItem.mock.calls.length).toBeLessThan(FOLDERS * 2 * 20); }); + +function findTreeRow(path: string): HTMLElement | null { + for (const host of document.querySelectorAll("*")) { + const row = host.shadowRoot?.querySelector(`[data-item-path="${path}"]`); + if (row) return row; + } + return null; +} + +function rightClick(row: HTMLElement) { + row.dispatchEvent( + new MouseEvent("contextmenu", { bubbles: true, cancelable: true, composed: true, button: 2 }), + ); +} + +it("copies a folder's path and a file's name from the right-click menu without opening the file", async () => { + const onSelectFile = vi.fn(); + await using _screen = await render( +
+ +
, + ); + using _menu = { [Symbol.dispose]: () => dismissContextMenu() }; + using clipboard = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined); + + // Empty folders flatten into one "apps / web / src" row. + await vi.waitFor(() => expect(findTreeRow("apps/web/src/")).not.toBeNull()); + rightClick(findTreeRow("apps/web/src/")!); + const copyPath = page.getByRole("menuitem", { name: "Copy path", exact: true }); + await expect.element(copyPath).toBeVisible(); + // No chat is open, so there is nothing to add the row to. + await expect.element(page.getByRole("menuitem", { name: "Add to chat" })).not.toBeInTheDocument(); + await userEvent.click(copyPath); + await vi.waitFor(() => expect(clipboard).toHaveBeenCalledWith("apps/web/src")); + + rightClick(findTreeRow("apps/web/src/a.ts")!); + await userEvent.click(page.getByRole("menuitem", { name: "Copy name", exact: true })); + await vi.waitFor(() => expect(clipboard).toHaveBeenLastCalledWith("a.ts")); + expect(onSelectFile).not.toHaveBeenCalled(); +}); + +it("adds a row to the open chat by the thread's path", async () => { + const insertTextAtEnd = vi.fn(() => true); + const composerRef = { current: { insertTextAtEnd } } as unknown as ComposerHandleRef; + await using _screen = await render( + +
+ {}} + workspaceRoot="/repo/apps/web" + // The thread works in the repository's apps/web folder. + mentionPath={(path) => path.replace(/^apps\/web\//, "")} + ariaLabel="Changed files" + /> +
+
, + ); + using _menu = { [Symbol.dispose]: () => dismissContextMenu() }; + + await vi.waitFor(() => expect(findTreeRow("apps/web/src/a.ts")).not.toBeNull()); + rightClick(findTreeRow("apps/web/src/a.ts")!); + await userEvent.click(page.getByRole("menuitem", { name: "Add to chat", exact: true })); + await vi.waitFor(() => + expect(insertTextAtEnd).toHaveBeenCalledWith("[a.ts](src/a.ts) ", { + ensureLeadingBoundary: true, + }), + ); +}); diff --git a/apps/web/src/components/diffs/DiffFileTree.tsx b/apps/web/src/components/diffs/DiffFileTree.tsx index 57bc23b33130..925b73b146a0 100644 --- a/apps/web/src/components/diffs/DiffFileTree.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.tsx @@ -1,12 +1,21 @@ -import type { GitStatusEntry } from "@pierre/trees"; +import type { + ContextMenuItem as TreeContextMenuItem, + ContextMenuOpenContext as TreeContextMenuOpenContext, + GitStatusEntry, +} from "@pierre/trees"; import { FileTree, useFileTree } from "@pierre/trees/react"; +import { settlePromise } from "@t3tools/client-runtime/state/runtime"; +import * as Cause from "effect/Cause"; +import * as AsyncResult from "effect/reactivity/AsyncResult"; import { T, useGT } from "gt-react"; import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react"; import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react"; +import { useComposerHandleContext } from "~/composerHandleContext"; import { useStableCallback } from "~/hooks/useStableCallback"; import { useTheme } from "~/hooks/useTheme"; import { cn } from "~/lib/utils"; +import { readLocalApi } from "~/localApi"; import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle, @@ -18,6 +27,13 @@ import { setAllDirectoriesExpanded, subscribeOncePerTask, } from "../files/fileTreeExpansion"; +import { + addFileTreeRowToChat, + addToChatMenuItem, + copyFileTreeRow, + fileTreeCopyMenuItems, + useTreeContextMenuAnchor, +} from "../files/fileTreeRowMenu"; import { Button } from "../ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { @@ -25,6 +41,7 @@ import { compareDiffFileTreeEntries, collectDirectoryPaths, diffFileTreeModel, + diffFileTreeRow, type DiffFileTreeEntry, } from "./diffFileTree.logic"; import { diffFileTreePositions } from "@t3tools/client-runtime/diff-file-order"; @@ -34,6 +51,10 @@ export type { DiffFileTreeEntry } from "./diffFileTree.logic"; interface DiffFileTreeProps { readonly entries: ReadonlyArray; readonly onSelectFile: (path: string) => void; + /** Host folder the diff paths belong to; copied paths use its separators. */ + readonly workspaceRoot: string | undefined; + /** The open thread's path for a row; Add to chat is offered only where it returns one. */ + readonly mentionPath?: (path: string) => string | null; readonly selectedPath?: string | null; readonly revealRequestId?: number; readonly ariaLabel: string; @@ -45,6 +66,8 @@ interface DiffFileTreeProps { export function DiffFileTree({ entries, onSelectFile, + workspaceRoot, + mentionPath, selectedPath = null, revealRequestId = 0, ariaLabel, @@ -89,7 +112,40 @@ export function DiffFileTree({ } }); + const contextMenuAnchor = useTreeContextMenuAnchor(); + const composerRef = useComposerHandleContext(); + const showRowContextMenu = useStableCallback( + (item: TreeContextMenuItem, context: TreeContextMenuOpenContext) => { + const api = readLocalApi(); + if (!api) { + context.close(); + return; + } + const row = diffFileTreeRow(item.path, presented.selectionPath); + const position = contextMenuAnchor.takeOver(context); + void settlePromise(async () => { + // A pull request opened outside a thread has no chat to add to. + const threadPath = composerRef?.current == null ? null : (mentionPath?.(row.path) ?? null); + const clicked = await api.contextMenu.show( + [...fileTreeCopyMenuItems(), ...(threadPath === null ? [] : [addToChatMenuItem()])], + position, + ); + if (clicked === "add-to-chat") { + if (threadPath !== null) addFileTreeRowToChat(composerRef, threadPath); + } else if (clicked !== null) await copyFileTreeRow(clicked, row, workspaceRoot); + }).then((result) => { + if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause); + }); + }, + ); + const { model } = useFileTree({ + composition: { + contextMenu: { + triggerMode: "right-click", + onOpen: (item, context) => showRowContextMenu(item, context), + }, + }, density: "compact", flattenEmptyDirectories: true, initialExpansion: "open", @@ -255,6 +311,7 @@ export function DiffFileTree({ ); if (clickedSelectedRow) onSelectFile(presented.selectionPath(path)); }} + onContextMenuCapture={contextMenuAnchor.onContextMenuCapture} className="min-h-0 flex-1 overflow-hidden" style={pierreTreeStyle(resolvedTheme)} onPointerOver={titleClippedPierreTreeRow} diff --git a/apps/web/src/components/diffs/diffFileTree.logic.test.ts b/apps/web/src/components/diffs/diffFileTree.logic.test.ts index 757ab3f83de4..65af6c6bb2d7 100644 --- a/apps/web/src/components/diffs/diffFileTree.logic.test.ts +++ b/apps/web/src/components/diffs/diffFileTree.logic.test.ts @@ -1,7 +1,12 @@ import type { FileDiffMetadata } from "@pierre/diffs"; import { describe, expect, it } from "vite-plus/test"; -import { buildDiffFileTreeUpdates, diffFileTreeEntries } from "./diffFileTree.logic"; +import { + buildDiffFileTreeUpdates, + diffFileTreeEntries, + diffFileTreeModel, + diffFileTreeRow, +} from "./diffFileTree.logic"; function file(type: FileDiffMetadata["type"], name: string, prevName = name): FileDiffMetadata { return { type, name, prevName } as FileDiffMetadata; @@ -40,3 +45,15 @@ describe("buildDiffFileTreeUpdates", () => { ]); }); }); + +describe("diffFileTreeRow", () => { + it("names a file that shares its path with a folder by its real path", () => { + const presented = diffFileTreeModel(["docs", "docs/guide.md"]); + const [aliasedFile] = presented.paths; + expect(aliasedFile).not.toBe("docs"); + expect(diffFileTreeRow(aliasedFile!, presented.selectionPath)).toEqual({ + path: "docs", + name: "docs", + }); + }); +}); diff --git a/apps/web/src/components/diffs/diffFileTree.logic.ts b/apps/web/src/components/diffs/diffFileTree.logic.ts index b819133d75da..504eff80ad6f 100644 --- a/apps/web/src/components/diffs/diffFileTree.logic.ts +++ b/apps/web/src/components/diffs/diffFileTree.logic.ts @@ -72,6 +72,12 @@ export function diffFileTreeModel(paths: ReadonlyArray) { }; } +/** A row's path as the diff names it (a folder without its trailing slash) and its last segment. */ +export function diffFileTreeRow(modelPath: string, selectionPath: (modelPath: string) => string) { + const path = selectionPath(modelPath).replace(/\/$/, ""); + return { path, name: basenameOfPath(path) }; +} + export function collectDirectoryPaths(paths: ReadonlyArray): ReadonlyArray { const directories = new Set(); for (const path of paths) { diff --git a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx index 1924cbb941cf..734c6594d4a7 100644 --- a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx @@ -130,6 +130,29 @@ describe("FileBrowserPanel", () => { await vi.waitFor(() => expect((row.getRootNode() as ShadowRoot).activeElement).toBe(row)); }); + it("copies a folder's path as the panel shows it", async () => { + await using _screen = await render( + {}} + workspaceMutationId={null} + hostFolder + />, + ); + using _menu = { [Symbol.dispose]: () => dismissContextMenu() }; + using clipboard = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined); + await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull()); + findTreeRow("src/")!.dispatchEvent( + new MouseEvent("contextmenu", { bubbles: true, cancelable: true, composed: true, button: 2 }), + ); + await userEvent.click(page.getByRole("menuitem", { name: "Copy path", exact: true })); + await vi.waitFor(() => expect(clipboard).toHaveBeenCalledWith("/repo/src")); + }); + it("dragging a file row carries a composer mention without opening it, and dragend releases it", async () => { const onOpenFile = vi.fn(); await using _screen = await render( diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 8f0bf626ba03..3048d01bbf75 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -26,7 +26,7 @@ import { useTheme } from "~/hooks/useTheme"; import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh"; import { useFileContextMenu, type FileContextMenuAction } from "~/fileContextMenu"; import { readLocalApi } from "~/localApi"; -import { T3_PIERRE_ICONS } from "~/pierre-icons"; +import { basenameOfPath, T3_PIERRE_ICONS } from "~/pierre-icons"; import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle, @@ -35,6 +35,14 @@ import { import { joinHostPath } from "./filePath"; import { createFileTreeDragMentionController } from "./fileTreeDragMention"; +import { + addFileTreeRowToChat, + addToChatMenuItem, + copyFileTreeRow, + fileTreeCopyMenuItems, + isFileTreeCopyAction, + useTreeContextMenuAnchor, +} from "./fileTreeRowMenu"; import { areAllDirectoriesExpanded, coalesceReentrantCalls, @@ -202,8 +210,7 @@ export default function FileBrowserPanel({ // path update scrolls to it again until the user takes over the scroll position. const followedRevealRef = useRef(null); - // Shadow-DOM row rects are unreliable; capture the composed contextmenu event's viewport position. - const contextMenuPointerRef = useRef<{ x: number; y: number; at: number } | null>(null); + const contextMenuAnchor = useTreeContextMenuAnchor(); const showEntryContextMenu = useStableCallback( (item: TreeContextMenuItem, context: TreeContextMenuOpenContext) => { @@ -214,22 +221,16 @@ export default function FileBrowserPanel({ } const relativePath = item.path.replace(/\/$/, ""); const mention = serializeComposerFileLink(panelPath(relativePath)); - const pointer = contextMenuPointerRef.current; - const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000; - const anchorRect = context.anchorElement.getBoundingClientRect(); - const position = pointerIsFresh - ? { x: pointer.x, y: pointer.y } - : { x: anchorRect.left, y: anchorRect.bottom }; const fileTarget = { environmentId, filePath: relativePath, workspaceRoot: cwd }; const fileMenuItems = fileContextMenu.buildItems(fileTarget); - // The app menu owns focus; the tree's outside-click handler would dismiss it before click. - context.close({ restoreFocus: !pointerIsFresh }); + const position = contextMenuAnchor.takeOver(context); void settlePromise(async () => { const clicked = await api.contextMenu.show( [ ...fileMenuItems, + ...fileTreeCopyMenuItems(), { id: "copy-mention", label: gt("Copy mention") }, - { id: "add-to-chat", label: gt("Add to chat") }, + addToChatMenuItem(), ], position, ); @@ -241,6 +242,11 @@ export default function FileBrowserPanel({ await fileContextMenu.activate(clicked as FileContextMenuAction, fileTarget); return; } + if (isFileTreeCopyAction(clicked)) { + const row = { name: basenameOfPath(relativePath), path: panelPath(relativePath) }; + await copyFileTreeRow(clicked, row, cwd); + return; + } if (clicked === "copy-mention") { try { await writeTextToClipboard(mention); @@ -253,25 +259,7 @@ export default function FileBrowserPanel({ } return; } - if (clicked === "add-to-chat") { - const composer = composerRef?.current; - if (!composer) { - toastManager.add({ - type: "error", - title: gt("Unable to add to chat"), - description: gt("Open a chat for this project and try again."), - }); - return; - } - const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true }); - if (!inserted) { - toastManager.add({ - type: "error", - title: gt("Unable to add to chat"), - description: gt("The chat isn't ready to accept input right now."), - }); - } - } + if (clicked === "add-to-chat") addFileTreeRowToChat(composerRef, panelPath(relativePath)); }).then((result) => { if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause); }); @@ -549,10 +537,7 @@ export default function FileBrowserPanel({
{ - contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp }; - }} + onContextMenuCapture={contextMenuAnchor.onContextMenuCapture} // Capture dragstart before the tree selects the row so selection sees the drag flag. onDragStartCapture={(event) => dragMention.handleDragStart(event.nativeEvent)} onDragEnd={() => dragMention.handleDragEnd((path) => model.getItem(path)?.deselect())} diff --git a/apps/web/src/components/files/fileTreeRowMenu.ts b/apps/web/src/components/files/fileTreeRowMenu.ts new file mode 100644 index 000000000000..7875a2751c91 --- /dev/null +++ b/apps/web/src/components/files/fileTreeRowMenu.ts @@ -0,0 +1,90 @@ +import type { ContextMenuOpenContext } from "@pierre/trees"; +import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; +import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; +import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; +import { msg } from "gt-react"; +import { useRef } from "react"; + +import { toastManager } from "~/components/ui/toast"; +import type { ComposerHandleRef } from "~/composerHandleContext"; +import { writeTextToClipboard } from "~/hooks/useCopyToClipboard"; +import { m } from "~/i18n/messages"; + +/** Opens the app's menu in place of a Pierre tree's own row menu. */ +export function useTreeContextMenuAnchor() { + // Shadow-DOM row rects are unreliable; keep the composed contextmenu event's viewport position. + const pointerRef = useRef<{ x: number; y: number; at: number } | null>(null); + return { + // Capture runs before the tree's shadow-internal row handler opens the menu. + onContextMenuCapture: (event: { clientX: number; clientY: number; timeStamp: number }) => { + pointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp }; + }, + /** Closes the tree's menu and returns where the app menu opens. */ + takeOver: (context: ContextMenuOpenContext) => { + const pointer = pointerRef.current; + const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000; + const anchorRect = context.anchorElement.getBoundingClientRect(); + // The app menu owns focus; the tree's outside-click handler would dismiss it before click. + context.close({ restoreFocus: !pointerIsFresh }); + return pointerIsFresh + ? { x: pointer.x, y: pointer.y } + : { x: anchorRect.left, y: anchorRect.bottom }; + }, + }; +} + +type FileTreeCopyAction = "copy-name" | "copy-path"; + +export function fileTreeCopyMenuItems() { + return [ + { id: "copy-name", label: m(msg("Copy name")) }, + { id: "copy-path", label: m(msg("Copy path")) }, + ] as const; +} + +export function isFileTreeCopyAction(id: string): id is FileTreeCopyAction { + return id === "copy-name" || id === "copy-path"; +} + +export async function copyFileTreeRow( + action: FileTreeCopyAction, + row: { readonly name: string; readonly path: string }, + hostRoot: string | undefined, +): Promise { + try { + await writeTextToClipboard( + action === "copy-name" ? row.name : formatFilePathForClipboard(row.path, hostRoot), + ); + } catch (error) { + toastManager.add({ + type: "error", + title: action === "copy-name" ? m(msg("Failed to copy name")) : m(msg("Failed to copy path")), + description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")), + }); + } +} + +export function addToChatMenuItem() { + return { id: "add-to-chat", label: m(msg("Add to chat")) } as const; +} + +/** Mentions `path` at the end of the open chat's composer. */ +export function addFileTreeRowToChat(composerRef: ComposerHandleRef | null, path: string): void { + const composer = composerRef?.current; + if (!composer) { + toastManager.add({ + type: "error", + title: m(msg("Unable to add to chat")), + description: m(msg("Open a chat for this project and try again.")), + }); + return; + } + const mention = serializeComposerFileLink(path); + if (!composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true })) { + toastManager.add({ + type: "error", + title: m(msg("Unable to add to chat")), + description: m(msg("The chat isn't ready to accept input right now.")), + }); + } +} diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index d06cb1efeaac..ee2706764072 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -420,6 +420,7 @@ function PullRequestCodeTab({ fixFindingLabel: requestedFixFindingLabel, onFixFinding, onAddToChat, + mentionPath, onAddToAgentSelection, onRefresh, refreshToken = 0, @@ -439,6 +440,7 @@ function PullRequestCodeTab({ onFixFinding?: (finding: PullRequestFinding) => void; /** Absent where there is no composer beside the panel to add a conversation to. */ onAddToChat?: (subject: PullRequestChatSubject) => void; + mentionPath?: (path: string) => string | null; onAddToAgentSelection?: (input: PullRequestAgentSelectionInput) => void; onRefresh: () => void; refreshToken?: number; @@ -2022,6 +2024,8 @@ function PullRequestCodeTab({ )} entries={fileTreeEntries} onSelectFile={revealFile} + workspaceRoot={detail.workspaceRoot} + {...(mentionPath ? { mentionPath } : {})} footer={ nextCursor === null ? null : (
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 1e14ab19d901..7595682dfc1e 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -67,7 +67,7 @@ import { usePreparePullRequestThreadAction } from "~/state/sourceControlActions" import { cn } from "~/lib/utils"; import { readLocalApi } from "~/localApi"; import type { ReviewCommentContext } from "~/reviewCommentContext"; -import { useProjects, useServerConfigs } from "~/state/entities"; +import { useProject, useProjects, useQuietThreadShell, useServerConfigs } from "~/state/entities"; import { useEnvironments } from "~/state/environments"; import { useEnvironmentQuery } from "~/state/query"; import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; @@ -80,6 +80,8 @@ import { PullRequestChangeBreakdownStat } from "./PullRequestChangeBreakdownStat import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { PullRequestThreadLinks } from "./PullRequestThreadLinks"; import { vcsEnvironment } from "~/state/vcs"; +import { resolveDiffPathForWorkspace } from "~/diffFileActions"; +import { findProjectForChangeRequest } from "@t3tools/client-runtime/change-request-links"; import { RelativeTime } from "~/components/RelativeTime"; import { useUiStateStore } from "~/uiStateStore"; @@ -395,6 +397,22 @@ export function PullRequestDetailPanel({ project.id === requestedReference.projectId && project.environmentId === environmentId, ); const repositoryIdentity = project?.repositoryIdentity; + // Add to chat names a file from the folder of the thread this panel sits in. + const chatThread = useQuietThreadShell(context === "thread" ? threadRef : null); + const chatProject = useProject( + chatThread + ? { environmentId: chatThread.environmentId, projectId: chatThread.projectId } + : null, + ); + const chatCwd = chatThread?.worktreePath ?? chatProject?.workspaceRoot ?? null; + const chatGitStatus = useEnvironmentQuery( + chatThread && chatCwd !== null + ? vcsEnvironment.status({ environmentId: chatThread.environmentId, input: { cwd: chatCwd } }) + : null, + ); + const chatRepositoryRoot = + chatGitStatus.data?.workingTree.rootPath ?? + (chatThread?.worktreePath ? undefined : chatProject?.repositoryIdentity?.rootPath); const supportsThreadPullRequests = environmentConfigs.get(environmentId) !== undefined; const reference = resolvePullRequestReference( requestedReference, @@ -946,6 +964,25 @@ export function PullRequestDetailPanel({ }; const attachTarget = composerDraftTarget ?? null; + const pullRequestLink = detail + ? sourceControlClients.parseChangeRequestUrl(detail.url)?.link + : undefined; + // Only a thread checked out from this pull request's repository can name its files. + const threadMentionPath = + attachTarget !== null && + chatThread?.environmentId === environmentId && + chatProject !== null && + chatCwd !== null && + chatRepositoryRoot !== undefined && + pullRequestLink !== undefined && + findProjectForChangeRequest([chatProject], pullRequestLink) !== undefined + ? (path: string) => + resolveDiffPathForWorkspace({ + filePath: path, + workspaceRoot: chatCwd, + repositoryRoot: chatRepositoryRoot, + }) + : undefined; const canPrepareWorktree = prepareThread.isAllowed && canOperateThread; const canFixFindings = attachTarget !== null || canPrepareWorktree; const handoffLabels = pullRequestHandoffLabels(attachTarget !== null, resolve); @@ -2187,6 +2224,7 @@ export function PullRequestDetailPanel({ >