From 6d8e2b14072a735f20decd4c08f5fb57375332d3 Mon Sep 17 00:00:00 2001 From: Anton Omelianenko <57302245+antoniooo12@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:07:59 +0200 Subject: [PATCH 1/4] feat(web): copy a file or folder name or path from the changed-files tree Right-clicking a row in the changed-files tree of the PR Code tab and the Diff panel offers Copy name and Copy path. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/DiffPanel.tsx | 1 + .../diffs/DiffFileTree.browser.test.tsx | 53 ++++++++++++- .../web/src/components/diffs/DiffFileTree.tsx | 79 ++++++++++++++++++- .../diffs/diffFileTree.logic.test.ts | 19 ++++- .../components/diffs/diffFileTree.logic.ts | 6 ++ .../pullRequest/PullRequestCodeTab.tsx | 1 + apps/web/src/i18n/translations/de.json | 2 + apps/web/src/i18n/translations/en.json | 2 + apps/web/src/i18n/translations/es.json | 2 + apps/web/src/i18n/translations/fr.json | 2 + apps/web/src/i18n/translations/ja.json | 2 + apps/web/src/i18n/translations/ko.json | 2 + apps/web/src/i18n/translations/pt-BR.json | 2 + apps/web/src/i18n/translations/ru.json | 2 + apps/web/src/i18n/translations/sv.json | 2 + apps/web/src/i18n/translations/zh.json | 2 + 16 files changed, 176 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 561bcd2b3e04..0640ce84dd77 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -1798,6 +1798,7 @@ export default function DiffPanel({ selectedPath={selectedFilePath} revealRequestId={selectedFileRevealRequestId} onSelectFile={revealDiffFile} + workspaceRoot={activeCwd} /> ) : 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..d980bd5356df 100644 --- a/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx @@ -2,6 +2,8 @@ import { FileTree } from "@pierre/trees"; import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; +import { dismissContextMenu } from "~/contextMenuFallback"; + import { render } from "../../../test/render"; import { DiffFileTree, type DiffFileTreeEntry } from "./DiffFileTree"; @@ -16,7 +18,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 +38,47 @@ 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/")!); + await userEvent.click(page.getByRole("menuitem", { name: "Copy path", exact: true })); + 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(); +}); diff --git a/apps/web/src/components/diffs/DiffFileTree.tsx b/apps/web/src/components/diffs/DiffFileTree.tsx index 57bc23b33130..97f0e0a0bce1 100644 --- a/apps/web/src/components/diffs/DiffFileTree.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.tsx @@ -1,12 +1,24 @@ -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 { thrownErrorMessage } from "@t3tools/client-runtime/errors"; +import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; +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 { writeTextToClipboard } from "~/hooks/useCopyToClipboard"; import { useStableCallback } from "~/hooks/useStableCallback"; import { useTheme } from "~/hooks/useTheme"; +import { m } from "~/i18n/messages"; import { cn } from "~/lib/utils"; +import { readLocalApi } from "~/localApi"; import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle, @@ -19,12 +31,14 @@ import { subscribeOncePerTask, } from "../files/fileTreeExpansion"; import { Button } from "../ui/button"; +import { toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { buildDiffFileTreeUpdates, compareDiffFileTreeEntries, collectDirectoryPaths, diffFileTreeModel, + diffFileTreeRow, type DiffFileTreeEntry, } from "./diffFileTree.logic"; import { diffFileTreePositions } from "@t3tools/client-runtime/diff-file-order"; @@ -34,6 +48,8 @@ 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; readonly selectedPath?: string | null; readonly revealRequestId?: number; readonly ariaLabel: string; @@ -45,6 +61,7 @@ interface DiffFileTreeProps { export function DiffFileTree({ entries, onSelectFile, + workspaceRoot, selectedPath = null, revealRequestId = 0, ariaLabel, @@ -89,7 +106,59 @@ export function DiffFileTree({ } }); + // 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 showRowContextMenu = useStableCallback( + (item: TreeContextMenuItem, context: TreeContextMenuOpenContext) => { + const api = readLocalApi(); + if (!api) { + context.close(); + return; + } + const row = diffFileTreeRow(item.path, presented.selectionPath); + 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 }; + // The app menu owns focus; the tree's outside-click handler would dismiss it before click. + context.close({ restoreFocus: !pointerIsFresh }); + void settlePromise(async () => { + const clicked = await api.contextMenu.show( + [ + { id: "copy-name", label: gt("Copy name") }, + { id: "copy-path", label: gt("Copy path") }, + ], + position, + ); + if (clicked === null) return; + try { + await writeTextToClipboard( + clicked === "copy-name" + ? row.name + : formatFilePathForClipboard(row.path, workspaceRoot), + ); + } catch (error) { + toastManager.add({ + type: "error", + title: clicked === "copy-name" ? gt("Failed to copy name") : gt("Failed to copy path"), + description: thrownErrorMessage(error, m) ?? gt("An error occurred."), + }); + } + }).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 +324,14 @@ export function DiffFileTree({ ); if (clickedSelectedRow) onSelectFile(presented.selectionPath(path)); }} + // Capture runs before the tree's shadow-internal row handler opens the menu. + onContextMenuCapture={(event) => { + contextMenuPointerRef.current = { + x: event.clientX, + y: event.clientY, + at: event.timeStamp, + }; + }} 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/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index d06cb1efeaac..a810768c4362 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -2022,6 +2022,7 @@ function PullRequestCodeTab({ )} entries={fileTreeEntries} onSelectFile={revealFile} + workspaceRoot={detail.workspaceRoot} footer={ nextCursor === null ? null : (
diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 7900e7318609..d24d8e5531ff 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -5513,6 +5513,8 @@ "1601d7e39a52c48f": "Laden des Diffs wiederholen", "b7b137472adb6989": "Teilweise Diff-Vorschau", "f0d79aa56f06663f": "Diese Datei ist zu groß für die vollständige Anzeige. Die Zahlen umfassen alle Änderungen.", + "1bafe6e935abb5f4": "Namen kopieren", + "e4bdcc949413e1da": "Name konnte nicht kopiert werden", "7fdde2b893ba1b9d": "Entfernt", "e58ce271d835b447": "Hinzugefügt", "07b9970b662ab70d": "Mermaid-Quelltext anzeigen", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 5bdd7c383d31..07c3b0477279 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -5514,6 +5514,8 @@ "1601d7e39a52c48f": "Retry loading diff", "b7b137472adb6989": "Partial diff preview", "f0d79aa56f06663f": "This file is too large to show in full. Counts include all changes.", + "1bafe6e935abb5f4": "Copy name", + "e4bdcc949413e1da": "Failed to copy name", "7fdde2b893ba1b9d": "Removed", "e58ce271d835b447": "Added", "07b9970b662ab70d": "Show Mermaid source", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 91dbb2b07f50..85db626176c1 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -5512,6 +5512,8 @@ "1601d7e39a52c48f": "Reintentar la carga del diff", "b7b137472adb6989": "Vista previa parcial del diff", "f0d79aa56f06663f": "Este archivo es demasiado grande para mostrarlo completo. Los recuentos incluyen todos los cambios.", + "1bafe6e935abb5f4": "Copiar nombre", + "e4bdcc949413e1da": "No se pudo copiar el nombre", "7fdde2b893ba1b9d": "Eliminado", "e58ce271d835b447": "Añadido", "07b9970b662ab70d": "Mostrar el código fuente de Mermaid", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index f5cf7e62a474..f5af7b71be19 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -5513,6 +5513,8 @@ "1601d7e39a52c48f": "Réessayer de charger le diff", "b7b137472adb6989": "Aperçu partiel du diff", "f0d79aa56f06663f": "Ce fichier est trop volumineux pour être affiché en entier. Les totaux incluent toutes les modifications.", + "1bafe6e935abb5f4": "Copier le nom", + "e4bdcc949413e1da": "Échec de la copie du nom", "7fdde2b893ba1b9d": "Supprimé", "e58ce271d835b447": "Ajouté", "07b9970b662ab70d": "Afficher la source Mermaid", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 7e3be343b068..32905ba830cf 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -5496,6 +5496,8 @@ "1601d7e39a52c48f": "差分の読み込みを再試行", "b7b137472adb6989": "差分の部分プレビュー", "f0d79aa56f06663f": "このファイルは大きすぎて全体を表示できません。件数にはすべての変更が含まれます。", + "1bafe6e935abb5f4": "名前をコピー", + "e4bdcc949413e1da": "名前をコピーできませんでした", "7fdde2b893ba1b9d": "削除", "e58ce271d835b447": "追加", "07b9970b662ab70d": "Mermaid のソースを表示", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index ef69858aead1..2e896f2aced1 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -5493,6 +5493,8 @@ "1601d7e39a52c48f": "변경 사항 다시 불러오기", "b7b137472adb6989": "변경 사항 일부 미리 보기", "f0d79aa56f06663f": "이 파일은 너무 커서 전체를 표시할 수 없습니다. 개수에는 모든 변경 사항이 포함됩니다.", + "1bafe6e935abb5f4": "이름 복사", + "e4bdcc949413e1da": "이름을 복사하지 못했습니다", "7fdde2b893ba1b9d": "삭제됨", "e58ce271d835b447": "추가됨", "07b9970b662ab70d": "Mermaid 소스 표시", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b2f82a27a41..be26fa16e676 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -5512,6 +5512,8 @@ "1601d7e39a52c48f": "Tentar carregar o diff novamente", "b7b137472adb6989": "Pré-visualização parcial do diff", "f0d79aa56f06663f": "Este arquivo é grande demais para ser mostrado por inteiro. As contagens incluem todas as alterações.", + "1bafe6e935abb5f4": "Copiar nome", + "e4bdcc949413e1da": "Falha ao copiar o nome", "7fdde2b893ba1b9d": "Removido", "e58ce271d835b447": "Adicionado", "07b9970b662ab70d": "Mostrar o código Mermaid", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 2891cb8165d7..d48564683430 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -5512,6 +5512,8 @@ "1601d7e39a52c48f": "Повторить загрузку диффа", "b7b137472adb6989": "Частичный предпросмотр диффа", "f0d79aa56f06663f": "Файл слишком большой, чтобы показать его полностью. Счётчики учитывают все изменения.", + "1bafe6e935abb5f4": "Копировать имя", + "e4bdcc949413e1da": "Не удалось скопировать имя", "7fdde2b893ba1b9d": "Удалено", "e58ce271d835b447": "Добавлено", "07b9970b662ab70d": "Показать исходник Mermaid", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index c792d6fb4a98..37efe271cfd0 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -5513,6 +5513,8 @@ "1601d7e39a52c48f": "Försök läsa in diffen igen", "b7b137472adb6989": "Partiell diffförhandsvisning", "f0d79aa56f06663f": "Den här filen är för stor för att visas i sin helhet. Antalen inkluderar alla ändringar.", + "1bafe6e935abb5f4": "Kopiera namn", + "e4bdcc949413e1da": "Det gick inte att kopiera namnet", "7fdde2b893ba1b9d": "Borttagen", "e58ce271d835b447": "Tillagd", "07b9970b662ab70d": "Visa Mermaid-källa", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index cd80e9a35102..1463ae4f156e 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -5519,6 +5519,8 @@ "1601d7e39a52c48f": "重试加载差异", "b7b137472adb6989": "部分差异预览", "f0d79aa56f06663f": "此文件过大,无法完整显示。统计包含全部改动。", + "1bafe6e935abb5f4": "复制名称", + "e4bdcc949413e1da": "复制名称失败", "7fdde2b893ba1b9d": "已删除", "e58ce271d835b447": "已添加", "07b9970b662ab70d": "显示 Mermaid 源码", From bed105623f6e562ba03b2b450194ba2946562805 Mon Sep 17 00:00:00 2001 From: Anton Omelianenko <57302245+antoniooo12@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:34:34 +0200 Subject: [PATCH 2/4] feat(web): copy a file or folder name or path from the Files panel The Files panel menu gets the same Copy name and Copy path items; both trees share the right-click anchor and copy helpers. Co-Authored-By: Claude Opus 5.5 --- .../web/src/components/diffs/DiffFileTree.tsx | 54 +++------------- .../files/FileBrowserPanel.browser.test.tsx | 23 +++++++ .../src/components/files/FileBrowserPanel.tsx | 31 ++++----- .../src/components/files/fileTreeRowMenu.ts | 63 +++++++++++++++++++ 4 files changed, 112 insertions(+), 59 deletions(-) create mode 100644 apps/web/src/components/files/fileTreeRowMenu.ts diff --git a/apps/web/src/components/diffs/DiffFileTree.tsx b/apps/web/src/components/diffs/DiffFileTree.tsx index 97f0e0a0bce1..8f0d995ea683 100644 --- a/apps/web/src/components/diffs/DiffFileTree.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.tsx @@ -4,8 +4,6 @@ import type { GitStatusEntry, } from "@pierre/trees"; import { FileTree, useFileTree } from "@pierre/trees/react"; -import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; -import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; import { settlePromise } from "@t3tools/client-runtime/state/runtime"; import * as Cause from "effect/Cause"; import * as AsyncResult from "effect/reactivity/AsyncResult"; @@ -13,10 +11,8 @@ import { T, useGT } from "gt-react"; import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react"; import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react"; -import { writeTextToClipboard } from "~/hooks/useCopyToClipboard"; import { useStableCallback } from "~/hooks/useStableCallback"; import { useTheme } from "~/hooks/useTheme"; -import { m } from "~/i18n/messages"; import { cn } from "~/lib/utils"; import { readLocalApi } from "~/localApi"; import { @@ -30,8 +26,12 @@ import { setAllDirectoriesExpanded, subscribeOncePerTask, } from "../files/fileTreeExpansion"; +import { + copyFileTreeRow, + fileTreeCopyMenuItems, + useTreeContextMenuAnchor, +} from "../files/fileTreeRowMenu"; import { Button } from "../ui/button"; -import { toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { buildDiffFileTreeUpdates, @@ -106,8 +106,7 @@ export function DiffFileTree({ } }); - // 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 showRowContextMenu = useStableCallback( (item: TreeContextMenuItem, context: TreeContextMenuOpenContext) => { const api = readLocalApi(); @@ -116,36 +115,10 @@ export function DiffFileTree({ return; } const row = diffFileTreeRow(item.path, presented.selectionPath); - 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 }; - // 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( - [ - { id: "copy-name", label: gt("Copy name") }, - { id: "copy-path", label: gt("Copy path") }, - ], - position, - ); - if (clicked === null) return; - try { - await writeTextToClipboard( - clicked === "copy-name" - ? row.name - : formatFilePathForClipboard(row.path, workspaceRoot), - ); - } catch (error) { - toastManager.add({ - type: "error", - title: clicked === "copy-name" ? gt("Failed to copy name") : gt("Failed to copy path"), - description: thrownErrorMessage(error, m) ?? gt("An error occurred."), - }); - } + const clicked = await api.contextMenu.show(fileTreeCopyMenuItems(), position); + if (clicked !== null) await copyFileTreeRow(clicked, row, workspaceRoot); }).then((result) => { if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause); }); @@ -324,14 +297,7 @@ export function DiffFileTree({ ); if (clickedSelectedRow) onSelectFile(presented.selectionPath(path)); }} - // Capture runs before the tree's shadow-internal row handler opens the menu. - onContextMenuCapture={(event) => { - contextMenuPointerRef.current = { - x: event.clientX, - y: event.clientY, - at: event.timeStamp, - }; - }} + onContextMenuCapture={contextMenuAnchor.onContextMenuCapture} className="min-h-0 flex-1 overflow-hidden" style={pierreTreeStyle(resolvedTheme)} onPointerOver={titleClippedPierreTreeRow} 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..626d0f88e5ba 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,12 @@ import { import { joinHostPath } from "./filePath"; import { createFileTreeDragMentionController } from "./fileTreeDragMention"; +import { + copyFileTreeRow, + fileTreeCopyMenuItems, + isFileTreeCopyAction, + useTreeContextMenuAnchor, +} from "./fileTreeRowMenu"; import { areAllDirectoriesExpanded, coalesceReentrantCalls, @@ -202,8 +208,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,20 +219,14 @@ 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") }, ], @@ -241,6 +240,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); @@ -549,10 +553,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..d558f6c39831 --- /dev/null +++ b/apps/web/src/components/files/fileTreeRowMenu.ts @@ -0,0 +1,63 @@ +import type { ContextMenuOpenContext } from "@pierre/trees"; +import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; +import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; +import { msg } from "gt-react"; +import { useRef } from "react"; + +import { toastManager } from "~/components/ui/toast"; +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.")), + }); + } +} From 33863e48ce2ed8fa828c90d2c416b85868b6cf1e Mon Sep 17 00:00:00 2001 From: Anton Omelianenko <57302245+antoniooo12@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:55:06 +0200 Subject: [PATCH 3/4] feat(web): add a changed file or folder to the chat from the file tree The changed-files tree menu offers Add to chat when a chat is open, sharing the Files panel's mention insert. Co-Authored-By: Claude Opus 5.5 --- .../diffs/DiffFileTree.browser.test.tsx | 34 ++++++++++++++++++- .../web/src/components/diffs/DiffFileTree.tsx | 14 ++++++-- .../src/components/files/FileBrowserPanel.tsx | 24 +++---------- .../src/components/files/fileTreeRowMenu.ts | 27 +++++++++++++++ 4 files changed, 76 insertions(+), 23 deletions(-) diff --git a/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx b/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx index d980bd5356df..bc55c5e54bef 100644 --- a/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx @@ -2,6 +2,7 @@ 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"; @@ -74,7 +75,11 @@ it("copies a folder's path and a file's name from the right-click menu without o // Empty folders flatten into one "apps / web / src" row. await vi.waitFor(() => expect(findTreeRow("apps/web/src/")).not.toBeNull()); rightClick(findTreeRow("apps/web/src/")!); - await userEvent.click(page.getByRole("menuitem", { name: "Copy path", exact: true })); + 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")!); @@ -82,3 +87,30 @@ it("copies a folder's path and a file's name from the right-click menu without o await vi.waitFor(() => expect(clipboard).toHaveBeenLastCalledWith("a.ts")); expect(onSelectFile).not.toHaveBeenCalled(); }); + +it("adds a row to the open chat as a mention", async () => { + const insertTextAtEnd = vi.fn(() => true); + const composerRef = { current: { insertTextAtEnd } } as unknown as ComposerHandleRef; + await using _screen = await render( + +
+ {}} + workspaceRoot="/repo" + 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](apps/web/src/a.ts) ", { + ensureLeadingBoundary: true, + }), + ); +}); diff --git a/apps/web/src/components/diffs/DiffFileTree.tsx b/apps/web/src/components/diffs/DiffFileTree.tsx index 8f0d995ea683..60136aa38c6d 100644 --- a/apps/web/src/components/diffs/DiffFileTree.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.tsx @@ -11,6 +11,7 @@ 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"; @@ -27,6 +28,8 @@ import { subscribeOncePerTask, } from "../files/fileTreeExpansion"; import { + addFileTreeRowToChat, + addToChatMenuItem, copyFileTreeRow, fileTreeCopyMenuItems, useTreeContextMenuAnchor, @@ -107,6 +110,7 @@ export function DiffFileTree({ }); const contextMenuAnchor = useTreeContextMenuAnchor(); + const composerRef = useComposerHandleContext(); const showRowContextMenu = useStableCallback( (item: TreeContextMenuItem, context: TreeContextMenuOpenContext) => { const api = readLocalApi(); @@ -117,8 +121,14 @@ export function DiffFileTree({ const row = diffFileTreeRow(item.path, presented.selectionPath); const position = contextMenuAnchor.takeOver(context); void settlePromise(async () => { - const clicked = await api.contextMenu.show(fileTreeCopyMenuItems(), position); - if (clicked !== null) await copyFileTreeRow(clicked, row, workspaceRoot); + // A pull request opened outside a thread has no chat to add to. + const chatOpen = composerRef?.current != null; + const clicked = await api.contextMenu.show( + [...fileTreeCopyMenuItems(), ...(chatOpen ? [addToChatMenuItem()] : [])], + position, + ); + if (clicked === "add-to-chat") addFileTreeRowToChat(composerRef, row.path); + else if (clicked !== null) await copyFileTreeRow(clicked, row, workspaceRoot); }).then((result) => { if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause); }); diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 626d0f88e5ba..3048d01bbf75 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -36,6 +36,8 @@ import { import { joinHostPath } from "./filePath"; import { createFileTreeDragMentionController } from "./fileTreeDragMention"; import { + addFileTreeRowToChat, + addToChatMenuItem, copyFileTreeRow, fileTreeCopyMenuItems, isFileTreeCopyAction, @@ -228,7 +230,7 @@ export default function FileBrowserPanel({ ...fileMenuItems, ...fileTreeCopyMenuItems(), { id: "copy-mention", label: gt("Copy mention") }, - { id: "add-to-chat", label: gt("Add to chat") }, + addToChatMenuItem(), ], position, ); @@ -257,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); }); diff --git a/apps/web/src/components/files/fileTreeRowMenu.ts b/apps/web/src/components/files/fileTreeRowMenu.ts index d558f6c39831..7875a2751c91 100644 --- a/apps/web/src/components/files/fileTreeRowMenu.ts +++ b/apps/web/src/components/files/fileTreeRowMenu.ts @@ -1,10 +1,12 @@ 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"; @@ -61,3 +63,28 @@ export async function copyFileTreeRow( }); } } + +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.")), + }); + } +} From 2b35b02fb0e5a35df0d48b2749c6ab655b197671 Mon Sep 17 00:00:00 2001 From: Anton Omelianenko <57302245+antoniooo12@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:11:01 +0200 Subject: [PATCH 4/4] fix(web): Add to chat names a changed file from the thread's folder The Diff panel and the PR Code tab pass a thread-relative path, and the item is hidden where the thread cannot name the file. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/DiffPanel.tsx | 13 +++++- .../diffs/DiffFileTree.browser.test.tsx | 8 ++-- .../web/src/components/diffs/DiffFileTree.tsx | 12 ++++-- .../pullRequest/PullRequestCodeTab.tsx | 3 ++ .../pullRequest/PullRequestDetailPanel.tsx | 40 ++++++++++++++++++- 5 files changed, 67 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 0640ce84dd77..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({ @@ -1799,6 +1809,7 @@ export default function DiffPanel({ 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 bc55c5e54bef..32373806fb46 100644 --- a/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.browser.test.tsx @@ -88,7 +88,7 @@ it("copies a folder's path and a file's name from the right-click menu without o expect(onSelectFile).not.toHaveBeenCalled(); }); -it("adds a row to the open chat as a mention", async () => { +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( @@ -97,7 +97,9 @@ it("adds a row to the open chat as a mention", async () => { {}} - workspaceRoot="/repo" + workspaceRoot="/repo/apps/web" + // The thread works in the repository's apps/web folder. + mentionPath={(path) => path.replace(/^apps\/web\//, "")} ariaLabel="Changed files" />
@@ -109,7 +111,7 @@ it("adds a row to the open chat as a mention", async () => { 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](apps/web/src/a.ts) ", { + 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 60136aa38c6d..925b73b146a0 100644 --- a/apps/web/src/components/diffs/DiffFileTree.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.tsx @@ -53,6 +53,8 @@ interface DiffFileTreeProps { 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; @@ -65,6 +67,7 @@ export function DiffFileTree({ entries, onSelectFile, workspaceRoot, + mentionPath, selectedPath = null, revealRequestId = 0, ariaLabel, @@ -122,13 +125,14 @@ export function DiffFileTree({ const position = contextMenuAnchor.takeOver(context); void settlePromise(async () => { // A pull request opened outside a thread has no chat to add to. - const chatOpen = composerRef?.current != null; + const threadPath = composerRef?.current == null ? null : (mentionPath?.(row.path) ?? null); const clicked = await api.contextMenu.show( - [...fileTreeCopyMenuItems(), ...(chatOpen ? [addToChatMenuItem()] : [])], + [...fileTreeCopyMenuItems(), ...(threadPath === null ? [] : [addToChatMenuItem()])], position, ); - if (clicked === "add-to-chat") addFileTreeRowToChat(composerRef, row.path); - else if (clicked !== null) await copyFileTreeRow(clicked, row, workspaceRoot); + 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); }); diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index a810768c4362..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; @@ -2023,6 +2025,7 @@ 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({ >