diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index 685cac0fc7f62..27cb6df270d64 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -37,8 +37,16 @@ const state = vi.hoisted(() => ({ diffFilesCollapsed: false, project: { workspaceRoot: "/project", - repositoryIdentity: null as { rootPath: string } | null, + repositoryIdentity: null, + } as { + workspaceRoot: string; + repositoryIdentity: { rootPath: string } | null; + trackedFolders?: ReadonlyArray; }, + gitRepositories: [] as ReadonlyArray<{ repositoryPath: string; name: string; cwd: string }>, + taskFolder: null as { projectIsWorktree: boolean } | null, + gitRepositoriesLoading: false, + diffPreviewCwds: [] as string[], toolCallItem: null as unknown, config: null as unknown as Atom.Atom, status: null as unknown as ResultAtom, @@ -54,8 +62,10 @@ vi.mock("~/state/server", () => ({ })); vi.mock("~/state/review", () => ({ reviewEnvironment: { - diffPreview: ({ input }: { input: { baseRef?: string } }) => - state.previews.get(input.baseRef ?? null)!, + diffPreview: ({ input }: { input: { cwd: string; baseRef?: string } }) => { + state.diffPreviewCwds.push(input.cwd); + return state.previews.get(input.baseRef ?? null)!; + }, branchCommits: () => state.commits, diffFilePatch: () => state.patch, diffFileContents: {}, @@ -79,6 +89,13 @@ vi.mock("~/state/filesystem", () => ({ useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }), filesystemEnvironment: {}, })); +vi.mock("~/hooks/useThreadGitRepositories", () => ({ + useThreadGitRepositories: () => ({ + repositories: state.gitRepositories, + taskFolder: state.taskFolder, + loading: state.gitRepositoriesLoading, + }), +})); vi.mock("~/hooks/useThreadRouteTarget", () => ({ useThreadRouteRef: () => state.threadRef })); vi.mock("~/hooks/useSettings", () => ({ useClientSettings: (select: (settings: ClientSettings) => unknown) => @@ -108,7 +125,11 @@ vi.mock("./diffs/DiffFileTree", () => ({ DiffFileTree: () => null })); vi.mock("./DiffFilePathCopyButton", () => ({ DiffFilePathCopyButton: () => null })); import DiffPanel from "./DiffPanel"; -import { useDiffPanelSessionStore, useDiffPanelStore } from "~/diffPanelStore"; +import { + chooseThreadGitRepository, + useDiffPanelSessionStore, + useDiffPanelStore, +} from "~/diffPanelStore"; import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore"; const cwd = "/project-worktree"; @@ -140,6 +161,7 @@ function setup(failedBaseRef: string | null) { useDiffPanelStore.setState({ byThreadKey: {}, branchBaseRefByThreadKey: {}, + gitRepositoryPathByThreadKey: {}, }); useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} }); useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} }); @@ -147,6 +169,10 @@ function setup(failedBaseRef: string | null) { reset(); state.diffFilesCollapsed = false; state.project = { workspaceRoot: "/project", repositoryIdentity: null }; + state.gitRepositories = []; + state.taskFolder = null; + state.gitRepositoriesLoading = false; + state.diffPreviewCwds = []; state.toolCallItem = null; state.checkpoints = []; state.checkpointDiff = null; @@ -429,6 +455,122 @@ it("shows a turn's repositories in a folder that is not a Git repository", async await expect.element(api).not.toBeInTheDocument(); }); +it.each([ + { width: 600, path: "docs/server", fullPath: true }, + { width: 540, path: "docs/server", fullPath: true }, + { width: 480, path: "docs/server", fullPath: true }, + { width: 480, path: "services/billing/api-server", fullPath: false }, + { width: 390, path: "docs/server", fullPath: false }, +])("shows the repository path $path in a $width px panel", async ({ width, path, fullPath }) => { + using context = setup("origin/orphan"); + // A feature branch against the automatic base, as most threads compare. + useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, null); + const branchPreview = preview(); + state.previews.set( + null, + Atom.make( + AsyncResult.success({ + ...branchPreview, + sources: branchPreview.sources.map((source) => ({ + ...source, + headRef: "feature/43-nested-repos", + baseRef: null, + })), + } as ReviewDiffPreviewResult), + ), + ); + state.project = { ...state.project, trackedFolders: [{ path: "server" }] }; + state.gitRepositories = ["server", path].map((repositoryPath) => ({ + repositoryPath: `/project/${repositoryPath}`, + name: "server", + cwd: `/project/${repositoryPath}`, + })); + chooseThreadGitRepository(context.threadRef, `/project/${path}`); + await using screen = await render( + +
+ +
+
, + ); + const picker = screen.getByRole("button", { name: `Repository: ${path}` }); + const label = picker.getByText(path, { exact: true }); + await expect.element(label).toBeVisible(); + await vi.waitFor(() => { + // The path, which tells `docs/server` from `server`, is not cut short where it fits. + if (fullPath) { + expect(label.element().scrollWidth).toBeLessThanOrEqual(label.element().clientWidth); + } + // At any width the header row still fits the panel. + const headerRow = picker.element().parentElement!; + expect(headerRow.scrollWidth).toBeLessThanOrEqual(headerRow.clientWidth); + }); +}); + +it("starts on the task folder's first repository when its project folder is no repository", async () => { + using context = setup("origin/orphan"); + // The plain project folder sits inside an enclosing checkout, so Git calls it a repository. + state.taskFolder = { projectIsWorktree: false }; + state.project = { ...state.project, trackedFolders: [{ path: "web" }] }; + state.gitRepositories = ["web", "server"].map((path) => ({ + repositoryPath: `/project/${path}`, + name: path, + cwd: `/task/${path}`, + })); + await using screen = await render( + +
+ +
+
, + ); + // The same default the thread details panel resolves. + const picker = screen.getByRole("button", { name: "Repository: web" }); + await expect.element(picker).toBeVisible(); + await userEvent.click(picker); + await expect.element(page.getByRole("menuitemradio", { name: "plain" })).not.toBeInTheDocument(); +}); + +it("waits for a chosen repository before reading its diff while the panel is hidden", async () => { + using context = setup("origin/orphan"); + state.project = { ...state.project, trackedFolders: [{ path: "web" }] }; + // After a reload the chosen repository is known, but the repositories are still being read. + chooseThreadGitRepository(context.threadRef, "/project/web"); + useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main"); + state.gitRepositoriesLoading = true; + const panel = () => ( + +
+ +
+
+ ); + await using screen = await render(panel()); + // The web repository's base ref is never compared in the thread's own folder. + expect(state.diffPreviewCwds).not.toContain(cwd); + + state.gitRepositoriesLoading = false; + state.gitRepositories = [{ repositoryPath: "/project/web", name: "web", cwd: "/project/web" }]; + await screen.rerender(panel()); + await vi.waitFor(() => expect(state.diffPreviewCwds).toContain("/project/web")); + expect(state.diffPreviewCwds).not.toContain(cwd); +}); + // Paths as git's numstat reports them; the parsed patch keeps their edge whitespace. it.each([ { path: " leading.ts", name: " leading.ts" }, diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 561bcd2b3e040..589d2dd39cdbf 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -44,11 +44,14 @@ import { type DiffPanelSelection, resolveToolCallDiffTarget, selectThreadBranchBaseRef, + chooseThreadGitRepository, selectThreadDiffPanelSelection, useDiffPanelSessionStore, useDiffPanelStore, + useThreadGitRepositoryPath, } from "../diffPanelStore"; import { useLocalStorage } from "../hooks/useLocalStorage"; +import { useThreadGitRepositories } from "../hooks/useThreadGitRepositories"; import { isTestChangedFile } from "@t3tools/shared/changedFileKind"; import { useHideTestFiles } from "./diffs/useHideTestFiles"; import { useRenderedAppearance } from "../hooks/useTheme"; @@ -69,7 +72,6 @@ import { useThreadCheckpointSummaries, useQuietThreadShell, useQuietThreadVisibleTurnItems, - useQuietThreadProjection, } from "../state/entities"; import { useClientSettings, updateClientSettings } from "../hooks/useSettings"; import { formatRelativeTimeLabel, formatShortTimestamp } from "../timestampFormat"; @@ -109,7 +111,6 @@ import { useEnvironmentQuery, useEnvironmentQueryRefresh } from "../state/query" import { useAtomCommand } from "../state/use-atom-command"; import { serverEnvironment } from "../state/server"; import { reviewEnvironment } from "../state/review"; -import { filesystemEnvironment } from "../state/filesystem"; import { vcsEnvironment } from "../state/vcs"; import { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices"; import { createGitDiffFileContentsLoader } from "../lib/diffFileContents"; @@ -123,8 +124,8 @@ import { projectCommitUrl } from "@t3tools/client-runtime/change-request-links"; import { isRelativePathInsideFolder, repositorySectionForPath, - threadChangedRepositories, - threadGitRepositories, + resolveThreadGitRepository, + threadGitRepositoryLabel, turnDiffSections, type TurnDiffSection, } from "@t3tools/client-runtime/state/thread-repositories"; @@ -134,7 +135,6 @@ type DiffThemeType = "light" | "dark"; const AUTOMATIC_BASE_REF = "__automatic_base_ref__"; const ALL_REPOSITORIES = "__all_repositories__"; const THREAD_FOLDER = "__thread_folder__"; -const NO_GIT_REPOSITORIES: ReturnType = Object.freeze([]); const NO_TURN_DIFF_SECTIONS: ReadonlyArray = []; const DIFF_FILE_TREE_STORAGE_KEY = "t3code.diffFileTreeOpen"; @@ -300,42 +300,36 @@ export default function DiffPanel({ const storedDiffSelection = useDiffPanelStore((state) => selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef), ); - const threadFolderIsRepo = gitStatusQuery.data?.isRepo ?? true; // The checkout the Git scopes read: the thread's folder, or a repository the thread changed. // A plain folder has no history of its own, so it starts on the latest one changed. - const repositoryStructure = useQuietThreadProjection(routeThreadRef); const tracksFolders = (activeProject?.trackedFolders?.length ?? 0) > 0; - const threadWorktreePath = activeThread?.worktreePath ?? null; // Unchanged repositories are listed too: work done outside a turn only shows in these scopes. - const taskFolderQuery = useEnvironmentQuery( - visible && tracksFolders && activeThread != null && threadWorktreePath !== null - ? filesystemEnvironment.taskFolder({ - environmentId: activeThread.environmentId, - input: { worktreePath: threadWorktreePath }, - }) - : null, - ); - const projectFoldersQuery = useEnvironmentQuery( - visible && tracksFolders && activeThread != null && threadWorktreePath === null - ? filesystemEnvironment.listFolders({ - environmentId: activeThread.environmentId, - input: { projectId: activeThread.projectId }, - }) - : null, - ); - const gitRepositories = threadGitRepositories({ - changed: - repositoryStructure === null - ? NO_GIT_REPOSITORIES - : threadChangedRepositories(repositoryStructure.projection), - taskFolder: taskFolderQuery.data?.taskFolder ?? null, - folders: projectFoldersQuery.data?.folders ?? null, + const threadWorktreePath = activeThread?.worktreePath ?? null; + const chosenGitRepositoryPath = useThreadGitRepositoryPath(routeThreadRef); + const { + repositories: gitRepositories, + taskFolder, + loading: gitRepositoriesLoading, + } = useThreadGitRepositories({ + threadRef: routeThreadRef, + isServerThread: true, + projectId: activeProjectId, + worktreePath: threadWorktreePath, threadCwd: activeCwd ?? null, + // As in the thread details panel, which this must resolve the same repository as. + // Also while hidden once a repository is chosen: the diff still loads then, for that repository. + enabled: + (visible || chosenGitRepositoryPath !== null) && + (tracksFolders || threadWorktreePath !== null), + }); + // A task folder's plain project directory can sit inside someone else's repository. + const threadFolderIsRepo = + (gitStatusQuery.data?.isRepo ?? true) && taskFolder?.projectIsWorktree !== false; + const gitRepository = resolveThreadGitRepository({ + repositories: gitRepositories, + chosenPath: chosenGitRepositoryPath, + threadFolderIsRepo, }); - const [gitRepositoryPath, setGitRepositoryPath] = useState(null); - const gitRepository = - gitRepositories.find((repository) => repository.repositoryPath === gitRepositoryPath) ?? - (threadFolderIsRepo ? null : (gitRepositories[0] ?? null)); const gitCwd = gitRepository?.cwd ?? activeCwd; const isGitRepo = threadFolderIsRepo || gitRepository !== null; const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadRef); @@ -438,8 +432,14 @@ export default function DiffPanel({ }, { enabled: (isGitRepo || hasRepositoryChanges) && selectedTurn !== undefined }, ); + // The chosen repository's commit or base ref means nothing in the thread's folder, so its diff + // waits until the repository is found again, as after a reload. + const awaitingChosenRepository = + chosenGitRepositoryPath !== null && + gitRepository?.repositoryPath !== chosenGitRepositoryPath && + gitRepositoriesLoading; const branchDiffPreviewInput = - canReadFiles && isGitSelection && activeThread && gitCwd + canReadFiles && isGitSelection && activeThread && gitCwd && !awaitingChosenRepository ? { cwd: gitCwd, ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}), @@ -548,6 +548,10 @@ export default function DiffPanel({ const refreshDiffFromUserAction = refreshPreviewQuery; const threadFolderName = activeProject?.title ?? gt("Project folder"); + const gitRepositoryLabel = + gitRepository === null + ? threadFolderName + : threadGitRepositoryLabel(gitRepository, activeProject?.workspaceRoot ?? null); const preview = branchDiffPreview.data; const gitDiff = selectedGitSource?.diff; @@ -932,12 +936,8 @@ export default function DiffPanel({ }; const selectGitRepository = (value: string) => { const nextPath = value === THREAD_FOLDER ? null : value; - if (nextPath === (gitRepository?.repositoryPath ?? null)) return; - setGitRepositoryPath(nextPath); - // A commit or base ref of the repository being left means nothing in the next one. - if (selectedCommitSha === null && rememberedBaseRef === null) return; - selectBranchBaseRef(null); - if (selectedGitScope === "unstaged") selectGitScope("unstaged"); + if (!routeThreadRef || nextPath === (gitRepository?.repositoryPath ?? null)) return; + chooseThreadGitRepository(routeThreadRef, nextPath); }; const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : ""; const selectedCommitValue = selectedCommitSha !== null ? `commit:${selectedCommitSha}` : ""; @@ -1180,12 +1180,12 @@ export default function DiffPanel({ } - className="min-w-14 max-w-48 shrink" - aria-label={gt("Repository: {name}", { - name: gitRepository?.name ?? threadFolderName, - })} + // The path tells same-named repositories apart, so the comparison gives way first. A + // narrower row caps it so it still fits; only a phone-width row truncates it further. + className="max-w-48 shrink-0 @max-[18rem]/diff-refs:max-w-32 @max-[14rem]/diff-refs:min-w-14 @max-[14rem]/diff-refs:shrink" + aria-label={gt("Repository: {name}", { name: gitRepositoryLabel })} > - {gitRepository?.name ?? threadFolderName} + {gitRepositoryLabel} @@ -1204,7 +1204,9 @@ export default function DiffPanel({ value={repository.repositoryPath} closeOnClick > - {repository.name} + + {threadGitRepositoryLabel(repository, activeProject?.workspaceRoot ?? null)} + ))} diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx index 2ca6982d24580..3bea8c472f582 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx @@ -16,6 +16,12 @@ const state = vi.hoisted(() => ({ folder: "", pullRequests: [] as unknown[], configLoaded: true, + /** Repositories the project covers besides its own folder, all on `main`. */ + repositories: [] as string[], + /** Whether the project tracks `repositories`; false once tracking stopped. */ + tracked: true, + /** A worktree thread's task folder: each repository's path, keyed to its worktree. */ + taskFolder: null as null | { readonly repositories: ReadonlyArray<[string, string]> }, })); // The read of t3.json is a cache: a re-read is the only way to see what is on disk now. @@ -70,6 +76,11 @@ vi.mock(import("~/state/entities"), async (importOriginal) => ({ title: state.workspaceRoot === SCRATCH_ROOT ? "No project" : "plain", workspaceRoot: state.workspaceRoot, scripts: [], + trackedFolders: (state.tracked ? state.repositories : []).map((path) => ({ + path, + name: path.split("/").at(-1)!, + discovered: true, + })), }) as never, useProjects: (() => []) as never, useQuietThreadShell: ((ref: unknown) => @@ -98,31 +109,83 @@ vi.mock(import("~/state/entities"), async (importOriginal) => ({ : [], )) as never, })); -// Neither folder is a repository, which is what the server reports for both. +// Neither folder is a repository, which is what the server reports for both; the project's +// other repositories are. vi.mock(import("~/state/vcs"), async (importOriginal) => { const actual = await importOriginal(); - const notARepo = Atom.make( - AsyncResult.success({ - isRepo: false, - hasPrimaryRemote: false, - isDefaultRef: false, - refName: null, - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - hasUpstream: false, - aheadCount: 0, - behindCount: 0, - aheadOfDefaultCount: 0, - pr: null, - }), - ); + const status = (isRepo: boolean) => + Atom.make( + AsyncResult.success({ + isRepo, + hasPrimaryRemote: false, + isDefaultRef: isRepo, + refName: isRepo ? "main" : null, + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, + aheadOfDefaultCount: 0, + pr: null, + }), + ); + const notARepo = status(false); + const repo = status(true); + return { + ...actual, + vcsEnvironment: { + ...actual.vcsEnvironment, + status: ((query: { input: { cwd: string } }) => + state.repositories.includes(query.input.cwd) ? repo : notARepo) as never, + }, + }; +}); +vi.mock(import("~/state/filesystem"), async (importOriginal) => { + const actual = await importOriginal(); return { ...actual, - vcsEnvironment: { ...actual.vcsEnvironment, status: (() => notARepo) as never }, + filesystemEnvironment: { + ...actual.filesystemEnvironment, + taskFolder: (() => + Atom.make( + AsyncResult.success({ + taskFolder: + state.taskFolder === null + ? null + : { + root: "/task", + projectId: "project", + projectRoot: state.workspaceRoot, + anchor: state.workspaceRoot, + projectPath: state.folder, + projectIsWorktree: false, + repositories: state.taskFolder.repositories.map( + ([repositoryPath, worktreePath]) => ({ + repositoryPath, + worktreePath, + name: repositoryPath.split("/").at(-1)!, + }), + ), + }, + }), + )) as never, + listFolders: (() => + Atom.make( + AsyncResult.success({ + folders: state.repositories.map((path) => ({ + path, + name: path.split("/").at(-1)!, + state: "git" as const, + discovered: true, + })), + }), + )) as never, + }, }; }); import { render } from "../../../test/render"; +import { useDiffPanelStore } from "../../diffPanelStore"; import { useRightPanelStore } from "../../rightPanelStore"; import { PopoverCreateHandle } from "../ui/popover"; import { ChatCanvasContext } from "./ChatCanvasContext"; @@ -151,8 +214,13 @@ function setup(input: { folder: string; pullRequests?: ThreadPullRequestLink[]; configLoaded?: boolean; + repositories?: string[]; }) { state.configLoaded = input.configLoaded ?? true; + state.repositories = input.repositories ?? []; + state.tracked = true; + state.taskFolder = null; + useDiffPanelStore.setState({ gitRepositoryPathByThreadKey: {} }); state.workspaceRoot = input.workspaceRoot; state.folder = input.folder; state.pullRequests = input.pullRequests ?? []; @@ -179,12 +247,15 @@ function Panel({ draftEnvMode, onMachines = false, withScripts = false, + inPlace = false, }: { fixture: ReturnType; /** Renders an unsent draft in this mode instead of a started thread. */ draftEnvMode?: "local" | "worktree"; onMachines?: boolean; withScripts?: boolean; + /** A started thread that runs in the project folder rather than a worktree. */ + inPlace?: boolean; }) { const noop = () => {}; const scriptResult = async () => ({ ok: true }) as never; @@ -209,7 +280,7 @@ function Panel({ threadId={threadRef.threadId} projectId={ProjectId.make("project")} composerDraftTarget={threadRef} - worktreePath={draftEnvMode === undefined ? state.folder : null} + worktreePath={draftEnvMode === undefined && !inPlace ? state.folder : null} isServerThread={draftEnvMode === undefined} activeProjectName={state.workspaceRoot === SCRATCH_ROOT ? "No project" : "plain"} activeProjectScripts={withScripts ? [] : undefined} @@ -315,3 +386,49 @@ it("lists the t3.json actions on disk when the actions menu opens again after th await chooser.click(); await expect.element(page.getByRole("menuitem", { name: /Dev 4200/ })).toBeVisible(); }); + +it("acts in a project's nested repository when its folder is none, and names the one picked", async () => { + using fixture = setup({ + workspaceRoot: "/work", + folder: "/work", + repositories: ["/work/docs/server", "/work/server", "/work/web"], + }); + await using _screen = await render(); + // Two repositories share a name, so each is named by its folder in the project. + const picker = page.getByRole("button", { name: "Repository: docs/server" }); + await expect.element(picker).toBeVisible(); + await expect.element(picker.getByText("main")).toBeVisible(); + // The Git actions read the nested repository, not the plain project folder. + await expect + .element(page.getByRole("button", { name: "Initialize Git" })) + .not.toBeInTheDocument(); + + await picker.click(); + await expect.element(page.getByRole("menuitemradio", { name: "plain" })).not.toBeInTheDocument(); + await page.getByRole("menuitemradio", { name: "web" }).click(); + await expect.element(page.getByRole("button", { name: "Repository: web" })).toBeVisible(); +}); + +it("keeps a worktree thread's repositories after the project stops tracking folders", async () => { + using fixture = setup({ workspaceRoot: "/work", folder: "/task/work" }); + state.tracked = false; + state.taskFolder = { + repositories: [ + ["/work/web", "/task/web"], + ["/work/server", "/task/server"], + ], + }; + await using _screen = await render(); + // The task folder still holds both worktrees; its plain project folder is no repository. + const picker = page.getByRole("button", { name: "Repository: web" }); + await expect.element(picker).toBeVisible(); + await picker.click(); + await expect.element(page.getByRole("menuitemradio", { name: "server" })).toBeVisible(); +}); + +it("hides the repository picker when the project covers no other repository", async () => { + using fixture = setup({ workspaceRoot: "/work/plain", folder: "/work/plain" }); + await using _screen = await render(); + await expect.element(page.getByRole("button", { name: "Initialize Git" })).toBeVisible(); + await expect.element(page.getByRole("button", { name: /^Repository:/ })).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index 32de434760a45..c480507d96b5d 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -9,12 +9,16 @@ import type { import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; +import { + resolveThreadGitRepository, + threadGitRepositoryLabel, +} from "@t3tools/client-runtime/state/thread-repositories"; import type { ComposerThreadTarget, DraftId } from "../../composerDraftStore"; import { useT3ProjectFileState } from "../../hooks/useT3ProjectFileScripts"; import { type EnvMode, type EnvironmentOption } from "../BranchToolbar.logic"; import { BranchToolbar } from "../BranchToolbar"; -import GitActionsControl from "../GitActionsControl"; +import ThreadGitActionsControl, { GitActionsControl } from "../GitActionsControl"; import ProjectScriptsControl, { type NewProjectScriptInput, type ProjectScriptActionResult, @@ -27,6 +31,7 @@ import { ThreadDetailsSection } from "./ThreadDetailsSection"; import { ThreadAutomationsPanel } from "./ThreadAutomationsPanel"; import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl"; import { ThreadRepositorySections } from "./ThreadRepositorySections"; +import { ThreadGitRepositoryPicker } from "./ThreadGitRepositoryPicker"; import { ThreadServersPanel } from "./ThreadServersPanel"; import { ThreadDetailsContext, @@ -36,6 +41,13 @@ import { import { ThreadDetailsItemsMenuItems } from "./ThreadDetailsItemsMenu"; import { resolveThreadDetailsVisibility, THREAD_DETAILS_ITEMS } from "./threadDetailsItems"; import { useClientSettings } from "../../hooks/useSettings"; +import { useThreadGitRepositories } from "../../hooks/useThreadGitRepositories"; +import { + chooseThreadGitRepository, + selectThreadBranchBaseRef, + useDiffPanelStore, + useThreadGitRepositoryPath, +} from "../../diffPanelStore"; import { useProject, useServerConfigs } from "../../state/entities"; import { filesystemEnvironment } from "../../state/filesystem"; import { useEnvironmentQuery } from "../../state/query"; @@ -129,6 +141,32 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { serverConfig !== undefined && project !== null && !isScratchProject(project, serverConfig.scratchWorkspaceRoot); + const { repositories: gitRepositories } = useThreadGitRepositories({ + threadRef: activeThreadRef, + isServerThread: props.isServerThread, + projectId: props.projectId, + worktreePath: props.worktreePath, + threadCwd: props.gitCwd, + enabled: offersGit && (tracksFolders || props.worktreePath !== null), + }); + // The repository the branch, Git actions, and Changes rows act in; null is the thread's folder. + const chosenGitRepositoryPath = useThreadGitRepositoryPath(activeThreadRef); + const gitRepository = resolveThreadGitRepository({ + repositories: gitRepositories, + chosenPath: chosenGitRepositoryPath, + threadFolderIsRepo: folderIsRepo, + }); + const gitRepositoryLabel = + gitRepository === null + ? null + : threadGitRepositoryLabel(gitRepository, project?.workspaceRoot ?? null); + const changesBaseRef = useDiffPanelStore((state) => + selectThreadBranchBaseRef(state, activeThreadRef), + ); + const chooseGitRepository = (repositoryPath: string | null) => { + if (repositoryPath === (gitRepository?.repositoryPath ?? null)) return; + chooseThreadGitRepository(activeThreadRef, repositoryPath); + }; const branchToolbarProps = { showGitControls: folderIsRepo, environmentId: props.environmentId, @@ -188,15 +226,21 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { environment: density === "full" && visible.environment, openIn: density !== "essential" && visible.openIn && props.showOpenInPicker, scripts: visible.scripts && props.activeProjectScripts !== undefined, - branch: offersGit && folderIsRepo && visible.branch, + // Names the repository the rows below act in whenever there is more than one. + gitRepository: + offersGit && + gitRepositories.length > 0 && + (visible.branch || visible.gitActions || visible.changes), + // Another repository's branch is shown on its picker row, not switched from here. + branch: offersGit && folderIsRepo && gitRepository === null && visible.branch, // Without a branch selector, linked pull requests still need somewhere to show. - pullRequests: !(offersGit && folderIsRepo) && visible.branch, + pullRequests: !(offersGit && folderIsRepo && gitRepository === null) && visible.branch, // A plain folder that tracks repositories is not asked to become one itself. git: offersGit && props.activeProjectName !== undefined && - (folderIsRepo || (!tracksFolders && taskFolder === null)) && - (visible.gitActions || (visible.changes && folderIsRepo)), + (gitRepository !== null || folderIsRepo || (!tracksFolders && taskFolder === null)) && + (visible.gitActions || (visible.changes && (folderIsRepo || gitRepository !== null))), // Also for a project that tracks nothing: a thread can change a submodule. repositories: offersGit && density !== "essential" && visible.gitActions, }; @@ -256,7 +300,11 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { ) : null} - {show.branch || show.pullRequests || show.git || show.repositories ? ( + {show.gitRepository || + show.branch || + show.pullRequests || + show.git || + show.repositories ? (
+ {show.gitRepository ? ( + + ) : null} {show.branch ? ( ) : null} @@ -274,8 +335,28 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { composerTarget={props.composerDraftTarget} /> ) : null} - {show.git && props.gitCwd ? ( + {show.git && gitRepository !== null && gitRepositoryLabel !== null ? ( + ) : show.git && props.gitCwd ? ( + ) : null} diff --git a/apps/web/src/components/chat/ThreadGitRepositoryPicker.tsx b/apps/web/src/components/chat/ThreadGitRepositoryPicker.tsx new file mode 100644 index 0000000000000..8fb8b8c0beb33 --- /dev/null +++ b/apps/web/src/components/chat/ThreadGitRepositoryPicker.tsx @@ -0,0 +1,107 @@ +import { + threadGitRepositoryLabel, + type ThreadGitRepository, +} from "@t3tools/client-runtime/state/thread-repositories"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { FolderGitIcon } from "lucide-react"; +import { useGT } from "gt-react"; + +import { cn } from "~/lib/utils"; +import { useEnvironmentQuery } from "~/state/query"; +import { vcsEnvironment } from "~/state/vcs"; + +import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../ui/menu"; +import { ThreadDetailsControl } from "./ThreadDetailsControl"; +import { + THREAD_DETAILS_PANEL_ICON_CLASS, + THREAD_DETAILS_PANEL_LABEL_CLASS, +} from "./threadDetailsPanelStyles"; + +const THREAD_FOLDER = "__thread_folder__"; + +/** + * Picks the repository the details panel's branch, Git actions, and Changes rows act in: the + * thread's own folder or another repository it reaches. The row always names the one picked. + */ +export function ThreadGitRepositoryPicker(props: { + environmentId: EnvironmentId; + projectRoot: string | null; + /** The thread's own folder; listed only when it is a repository itself. */ + threadFolder: { readonly name: string; readonly isRepo: boolean }; + repositories: ReadonlyArray; + /** Null for the thread's own folder. */ + selected: ThreadGitRepository | null; + onSelect: (repositoryPath: string | null) => void; +}) { + const gt = useGT(); + const { selected } = props; + // Local status only, as a repository section reads it: the Git actions below hold the full one. + const status = useEnvironmentQuery( + selected === null + ? null + : vcsEnvironment.status({ + environmentId: props.environmentId, + input: { cwd: selected.cwd, includeRemote: false }, + }), + ); + const label = + selected === null + ? props.threadFolder.name + : threadGitRepositoryLabel(selected, props.projectRoot); + // The thread's own folder shows its branch on the branch row below this one. + const branch = + selected === null || status.data == null + ? null + : status.data.isRepo + ? (status.data.refName ?? gt("Detached HEAD")) + : gt("Not a Git repository"); + + return ( + + } + aria-label={gt("Repository: {name}", { name: label })} + > + + + + {label} + + {branch !== null ? ( + + {branch} + + ) : null} + + + + props.onSelect(value === THREAD_FOLDER ? null : value)} + > + {props.threadFolder.isRepo ? ( + + {props.threadFolder.name} + + ) : null} + {props.repositories.map((repository) => ( + + + {threadGitRepositoryLabel(repository, props.projectRoot)} + + + ))} + + + + ); +} diff --git a/apps/web/src/diffPanelStore.test.ts b/apps/web/src/diffPanelStore.test.ts index bb6d603d2bc56..40c64c8c26615 100644 --- a/apps/web/src/diffPanelStore.test.ts +++ b/apps/web/src/diffPanelStore.test.ts @@ -4,7 +4,9 @@ import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { beforeEach, describe, expect, it } from "vite-plus/test"; import { + chooseThreadGitRepository, resolveToolCallDiffTarget, + selectThreadBranchBaseRef, useDiffPanelSessionStore, useDiffPanelStore, } from "./diffPanelStore"; @@ -14,10 +16,53 @@ describe("diffPanelStore", () => { useDiffPanelStore.setState({ byThreadKey: {}, branchBaseRefByThreadKey: {}, + gitRepositoryPathByThreadKey: {}, }); useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} }); }); + it("drops a commit and base ref of the repository a thread's Git controls leave", () => { + const ref = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") }; + const key = scopedThreadKey(ref); + const store = useDiffPanelStore.getState(); + store.selectBranchBaseRef(ref, "origin/main"); + store.selectCommit(ref, "abc123"); + chooseThreadGitRepository(ref, "/work/web"); + expect(useDiffPanelStore.getState().gitRepositoryPathByThreadKey[key]).toBe("/work/web"); + expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ + kind: "branch", + baseRef: null, + }); + + // Uncommitted changes and a turn read whichever repository is picked, so they stay. + store.selectBranchBaseRef(ref, "origin/main"); + store.selectGitScope(ref, "unstaged"); + chooseThreadGitRepository(ref, null); + expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ kind: "unstaged" }); + expect(selectThreadBranchBaseRef(useDiffPanelStore.getState(), ref)).toBeNull(); + store.selectTurn(ref, RunId.make("run")); + chooseThreadGitRepository(ref, "/work/web"); + expect(useDiffPanelStore.getState().byThreadKey[key]?.kind).toBe("turn"); + }); + + it("restores a nested repository with the base ref chosen in it after a reload", async () => { + const ref = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") }; + chooseThreadGitRepository(ref, "/work/web"); + useDiffPanelStore.getState().selectBranchBaseRef(ref, "origin/release"); + + const { storage, name } = useDiffPanelStore.persist.getOptions(); + const persisted = await storage!.getItem(name!); + expect(persisted).not.toBeNull(); + useDiffPanelStore.setState(useDiffPanelStore.getInitialState()); + await storage!.setItem(name!, persisted!); + await useDiffPanelStore.persist.rehydrate(); + + // The base ref still applies to the repository it was chosen in, not the thread's folder. + const state = useDiffPanelStore.getState(); + expect(state.gitRepositoryPathByThreadKey[scopedThreadKey(ref)]).toBe("/work/web"); + expect(selectThreadBranchBaseRef(state, ref)).toBe("origin/release"); + }); + it("keeps a tool call selection independent of checkpoints and allows returning to Git changes", () => { const ref = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") }; const target = { diff --git a/apps/web/src/diffPanelStore.ts b/apps/web/src/diffPanelStore.ts index 207756445e91f..b90ad187afc76 100644 --- a/apps/web/src/diffPanelStore.ts +++ b/apps/web/src/diffPanelStore.ts @@ -39,6 +39,14 @@ interface DiffPanelStoreState { selectTurn: (ref: ScopedThreadRef, turnId: RunId, filePath?: string) => void; selectTurnRepository: (ref: ScopedThreadRef, turnId: RunId, repository: string | null) => void; selectCommit: (ref: ScopedThreadRef, sha: string) => void; + /** + * The repository a thread's Git controls and Git diff act in, by `repositoryPath`; null is + * the thread's own folder. Saved with the commit and base ref it scopes, so a reload cannot + * apply a nested repository's refs to the thread's folder. + */ + gitRepositoryPathByThreadKey: Record; + /** A commit or base ref of the repository being left means nothing in the next one. */ + chooseGitRepository: (ref: ScopedThreadRef, repositoryPath: string | null) => void; reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray) => void; removeThread: (ref: ScopedThreadRef) => void; } @@ -63,6 +71,7 @@ export const useDiffPanelStore = create()( (set) => ({ byThreadKey: {}, branchBaseRefByThreadKey: {}, + gitRepositoryPathByThreadKey: {}, selectGitScope: (ref, scope) => set((state) => { const threadKey = scopedThreadKey(ref); @@ -157,6 +166,26 @@ export const useDiffPanelStore = create()( branchBaseRefByThreadKey: { ...state.branchBaseRefByThreadKey, [threadKey]: baseRef }, }; }), + chooseGitRepository: (ref, repositoryPath) => + set((state) => { + const threadKey = scopedThreadKey(ref); + const gitRepositoryPathByThreadKey = { + ...state.gitRepositoryPathByThreadKey, + [threadKey]: repositoryPath, + }; + const previous = state.byThreadKey[threadKey]; + if (previous?.kind !== "commit" && branchBaseRef(state, threadKey) === null) { + return { gitRepositoryPathByThreadKey }; + } + return { + gitRepositoryPathByThreadKey, + byThreadKey: + previous?.kind === "branch" || previous?.kind === "commit" + ? { ...state.byThreadKey, [threadKey]: { kind: "branch", baseRef: null } } + : state.byThreadKey, + branchBaseRefByThreadKey: { ...state.branchBaseRefByThreadKey, [threadKey]: null }, + }; + }), reconcileTurnSelection: (ref, availableTurnIds) => set((state) => { const threadKey = scopedThreadKey(ref); @@ -179,13 +208,19 @@ export const useDiffPanelStore = create()( removeThread: (ref) => set((state) => { const threadKey = scopedThreadKey(ref); - if (!(threadKey in state.byThreadKey) && !(threadKey in state.branchBaseRefByThreadKey)) { + if ( + !(threadKey in state.byThreadKey) && + !(threadKey in state.branchBaseRefByThreadKey) && + !(threadKey in state.gitRepositoryPathByThreadKey) + ) { return state; } const { [threadKey]: _removed, ...byThreadKey } = state.byThreadKey; const { [threadKey]: _removedBaseRef, ...branchBaseRefByThreadKey } = state.branchBaseRefByThreadKey; - return { byThreadKey, branchBaseRefByThreadKey }; + const { [threadKey]: _removedRepository, ...gitRepositoryPathByThreadKey } = + state.gitRepositoryPathByThreadKey; + return { byThreadKey, branchBaseRefByThreadKey, gitRepositoryPathByThreadKey }; }), }), { @@ -197,6 +232,7 @@ export const useDiffPanelStore = create()( partialize: (state) => ({ byThreadKey: state.byThreadKey, branchBaseRefByThreadKey: state.branchBaseRefByThreadKey, + gitRepositoryPathByThreadKey: state.gitRepositoryPathByThreadKey, }), }, ), @@ -231,6 +267,16 @@ export const useDiffPanelSessionStore = create()((se setIgnoreWhitespace: (ignoreWhitespace) => set({ ignoreWhitespace }), })); +export function useThreadGitRepositoryPath(ref: ScopedThreadRef | null | undefined): string | null { + return useDiffPanelStore((state) => + ref ? (state.gitRepositoryPathByThreadKey[scopedThreadKey(ref)] ?? null) : null, + ); +} + +export function chooseThreadGitRepository(ref: ScopedThreadRef, repositoryPath: string | null) { + useDiffPanelStore.getState().chooseGitRepository(ref, repositoryPath); +} + export function selectThreadDiffPanelSelection( byThreadKey: Record, ref: ScopedThreadRef | null | undefined, diff --git a/apps/web/src/hooks/useThreadGitRepositories.ts b/apps/web/src/hooks/useThreadGitRepositories.ts new file mode 100644 index 0000000000000..ae4c486623012 --- /dev/null +++ b/apps/web/src/hooks/useThreadGitRepositories.ts @@ -0,0 +1,70 @@ +import { + threadChangedRepositories, + threadGitRepositories, + type ThreadGitRepository, +} from "@t3tools/client-runtime/state/thread-repositories"; +import type { ProjectId, ScopedThreadRef } from "@t3tools/contracts"; + +import { useQuietThreadProjection } from "~/state/entities"; +import { filesystemEnvironment } from "~/state/filesystem"; +import { useEnvironmentQuery } from "~/state/query"; + +const NO_GIT_REPOSITORIES: ReadonlyArray = Object.freeze([]); + +/** + * Every repository besides its own folder whose Git state a thread can show: the ones it changed, + * then its task folder's worktrees, or the project's tracked repositories when it runs in place. + * A project that tracks no folders asks the server nothing. + */ +export function useThreadGitRepositories(input: { + readonly threadRef: ScopedThreadRef | null; + /** False for a draft, which has changed nothing yet. */ + readonly isServerThread: boolean; + readonly projectId: ProjectId | null; + readonly worktreePath: string | null; + readonly threadCwd: string | null; + /** + * False while nothing reads the list. A thread in its own worktree keeps its task folder when + * the project stops tracking folders, so only an in-place thread needs the project to track some. + */ + readonly enabled: boolean; +}): { + readonly repositories: ReadonlyArray; + /** The worktree thread's task folder, once read; null otherwise. */ + readonly taskFolder: { readonly projectIsWorktree: boolean } | null; + /** True until the first read of the folders this thread reaches comes back. */ + readonly loading: boolean; +} { + const { threadRef, worktreePath, enabled } = input; + const structure = useQuietThreadProjection(input.isServerThread ? threadRef : null); + const taskFolderQuery = useEnvironmentQuery( + enabled && threadRef !== null && worktreePath !== null + ? filesystemEnvironment.taskFolder({ + environmentId: threadRef.environmentId, + input: { worktreePath }, + }) + : null, + ); + const foldersQuery = useEnvironmentQuery( + enabled && threadRef !== null && input.projectId !== null && worktreePath === null + ? filesystemEnvironment.listFolders({ + environmentId: threadRef.environmentId, + input: { projectId: input.projectId }, + }) + : null, + ); + const taskFolder = taskFolderQuery.data?.taskFolder ?? null; + return { + repositories: threadGitRepositories({ + changed: + structure === null ? NO_GIT_REPOSITORIES : threadChangedRepositories(structure.projection), + taskFolder, + folders: foldersQuery.data?.folders ?? null, + threadCwd: input.threadCwd, + }), + taskFolder, + loading: + (taskFolderQuery.isPending && taskFolderQuery.data === null) || + (foldersQuery.isPending && foldersQuery.data === null), + }; +} diff --git a/docs/user/multi-repo-projects.md b/docs/user/multi-repo-projects.md index d58ab4ad3b423..80bef36699440 100644 --- a/docs/user/multi-repo-projects.md +++ b/docs/user/multi-repo-projects.md @@ -69,9 +69,15 @@ hand show up too. Git actions run in one repository at a time. -- **Web and desktop:** the thread details panel lists the repositories the thread changed, most - recent first, each with its branch and uncommitted changes. Expand one to commit, push, or open a - pull request there. **Other repositories...** adds any other repository of the project. +- **Web and desktop:** the repository picker at the top of the thread details panel's Git rows + chooses which repository the branch, Git actions, and **Changes** rows act in, and always names + it. A repository inside the project folder is named by its path there, such as + `docs/server`. When the project folder is not a repository itself, the first one is + picked. The choice is per thread, lasts until you reload, and is shared with the Diff pane's + repository picker. Another repository's branch is shown next to its name; switch it from a + terminal. Below that, the panel lists the repositories the thread changed, most recent first, + each with its branch and uncommitted changes. Expand one to commit, push, or open a pull request + there. **Other repositories...** adds any other repository of the project. - **Mobile:** open **Git controls** in the thread. The sheet lists the repositories under **Repositories**; tap one for its own commit, push, and pull request actions. @@ -209,5 +215,5 @@ restored: - One Git action runs in one repository. There is no commit or push across several at once. - Only the project folder's `t3.json` is read. Setup scripts and actions inside one of its repositories are not picked up. -- The Diff pane's repository picker and the base branch field for a plain folder are on web and - desktop only. +- The repository pickers in the Diff pane and the thread details panel, and the base branch field + for a plain folder, are on web and desktop only. diff --git a/packages/client-runtime/src/state/threadRepositories.test.ts b/packages/client-runtime/src/state/threadRepositories.test.ts index 04625dac4071b..fa786d4641652 100644 --- a/packages/client-runtime/src/state/threadRepositories.test.ts +++ b/packages/client-runtime/src/state/threadRepositories.test.ts @@ -20,12 +20,14 @@ import { repositoryCheckpointScopeIds, repositoryFilePath, repositorySectionForPath, + resolveThreadGitRepository, resolveWorktreeRepositorySelection, rewindFileRestore, THREAD_REPOSITORY_SECTIONS_VISIBLE, isRelativePathInsideFolder, threadChangedRepositories, threadGitRepositories, + threadGitRepositoryLabel, threadRepositoryScopes, threadRepositorySections, unpinThreadRepository, @@ -256,6 +258,20 @@ describe("threadRepositorySections", () => { ], }), ).toEqual([{ repositoryPath: "/work/wrapper/cli", name: "cli" }]); + + expect( + pinnableThreadRepositories({ + sections, + threadCwd: "/work/wrapper", + folders: [ + { path: "/work/wrapper/api", name: "api", state: "git" }, + { path: "/work/wrapper/specs/api", name: "api", state: "git" }, + ], + }), + ).toEqual([ + { repositoryPath: "/work/wrapper/api", name: "api" }, + { repositoryPath: "/work/wrapper/specs/api", name: "specs/api" }, + ]); }); it("offers Git changes of every repository a thread reaches, changed ones first", () => { @@ -282,6 +298,46 @@ describe("threadRepositorySections", () => { ).toEqual([{ repositoryPath: "/work/api", name: "api", cwd: "/wt/api" }]); }); + it("acts in the chosen repository, else the thread's folder or its first repository", () => { + const api = { repositoryPath: "/work/api", name: "api", cwd: "/work/api" }; + const web = { repositoryPath: "/work/web", name: "web", cwd: "/work/web" }; + const repositories = [api, web]; + expect( + resolveThreadGitRepository({ repositories, chosenPath: null, threadFolderIsRepo: true }), + ).toBeNull(); + expect( + resolveThreadGitRepository({ repositories, chosenPath: web.cwd, threadFolderIsRepo: true }), + ).toBe(web); + // A plain folder has no Git state of its own to show. + expect( + resolveThreadGitRepository({ repositories, chosenPath: null, threadFolderIsRepo: false }), + ).toBe(api); + // A repository the thread no longer reaches is never acted in. + expect( + resolveThreadGitRepository({ + repositories, + chosenPath: "/work/gone", + threadFolderIsRepo: true, + }), + ).toBeNull(); + expect( + resolveThreadGitRepository({ repositories: [], chosenPath: null, threadFolderIsRepo: false }), + ).toBeNull(); + }); + + it("names a repository by its folder in the project, so two of one name stay apart", () => { + const nested = { repositoryPath: "/work/docs/server", name: "server" }; + expect(threadGitRepositoryLabel(nested, "/work")).toBe("docs/server"); + expect(threadGitRepositoryLabel({ ...nested, repositoryPath: "/work/server" }, "/work")).toBe( + "server", + ); + // A folder outside the project, or no known project folder, keeps its name. + expect(threadGitRepositoryLabel({ ...nested, repositoryPath: "/elsewhere/api" }, "/work")).toBe( + "server", + ); + expect(threadGitRepositoryLabel(nested, null)).toBe("server"); + }); + it("lists a task folder's worktrees, changed first, and never a shared checkout", () => { const taskFolder = { root: "/wt/task", diff --git a/packages/client-runtime/src/state/threadRepositories.ts b/packages/client-runtime/src/state/threadRepositories.ts index 930c4622a313e..34f32bb624154 100644 --- a/packages/client-runtime/src/state/threadRepositories.ts +++ b/packages/client-runtime/src/state/threadRepositories.ts @@ -478,6 +478,38 @@ export function threadGitRepositories(input: { ]; } +/** + * The repository a thread's Git controls act in, or null for the thread's own folder. A folder + * that is no repository itself falls to the first one it reaches, as does a choice it no longer + * reaches. + */ +export function resolveThreadGitRepository(input: { + readonly repositories: ReadonlyArray; + /** The `repositoryPath` the user chose; null for the thread's own folder. */ + readonly chosenPath: string | null; + readonly threadFolderIsRepo: boolean; +}): Repository | null { + return ( + input.repositories.find((repository) => repository.repositoryPath === input.chosenPath) ?? + (input.threadFolderIsRepo ? null : (input.repositories[0] ?? null)) + ); +} + +/** + * How a picker names a repository: its folder from the project folder when it sits inside it, + * which tells apart two of the same name, and its name otherwise. + */ +export function threadGitRepositoryLabel( + repository: Pick, + projectRoot: string | null, +): string { + const relative = + projectRoot === null ? undefined : relativeFolderPath(projectRoot, repository.repositoryPath); + return relative === undefined || relative === "" || !isRelativePathInsideFolder(relative) + ? repository.name + : relative; +} + /** * A task folder's repositories, each bound to its worktree: changed ones first, then the rest. * A changed repository inside one of those worktrees, such as a submodule, follows them. @@ -594,10 +626,29 @@ export function pinnableThreadRepositories(input: { const shown = new Set( [...input.sections.visible, ...input.sections.hidden].map((section) => section.key), ); - return input.folders.flatMap((folder) => - folder.state !== "git" || folder.path === input.threadCwd || shown.has(folder.path) - ? [] - : [{ repositoryPath: folder.path, name: folder.name }], + return distinctRepositoryNames( + input.folders.flatMap((folder) => + folder.state !== "git" || folder.path === input.threadCwd || shown.has(folder.path) + ? [] + : [{ repositoryPath: folder.path, name: folder.name }], + ), + input.threadCwd, + ); +} + +/** Repositories that share a folder name, like `server` and `docs/server`, go by their path. */ +function distinctRepositoryNames( + repositories: ReadonlyArray, + root: string | null, +): ReadonlyArray { + const counts = new Map(); + for (const repository of repositories) { + counts.set(repository.name, (counts.get(repository.name) ?? 0) + 1); + } + return repositories.map((repository) => + (counts.get(repository.name) ?? 0) > 1 + ? { ...repository, name: threadGitRepositoryLabel(repository, root) } + : repository, ); } @@ -609,12 +660,15 @@ export function addableTaskFolderRepositories(input: { const present = new Set( input.taskFolder.repositories.map((repository) => repository.repositoryPath), ); - return input.folders.flatMap((folder) => - folder.state !== "git" || - folder.path === input.taskFolder.projectRoot || - present.has(folder.path) - ? [] - : [{ repositoryPath: folder.path, name: folder.name }], + return distinctRepositoryNames( + input.folders.flatMap((folder) => + folder.state !== "git" || + folder.path === input.taskFolder.projectRoot || + present.has(folder.path) + ? [] + : [{ repositoryPath: folder.path, name: folder.name }], + ), + input.taskFolder.projectRoot, ); }