Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 146 additions & 4 deletions apps/web/src/components/DiffPanel.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<unknown>;
},
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<null>,
status: null as unknown as ResultAtom<VcsStatusResult>,
Expand All @@ -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: {},
Expand All @@ -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) =>
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -140,13 +161,18 @@ function setup(failedBaseRef: string | null) {
useDiffPanelStore.setState({
byThreadKey: {},
branchBaseRefByThreadKey: {},
gitRepositoryPathByThreadKey: {},
});
useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} });
useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} });
};
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;
Expand Down Expand Up @@ -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(
<RegistryContext.Provider value={context.registry}>
<div style={{ height: 600, width, display: "flex", flexDirection: "column" }}>
<DiffPanel
mode="embedded"
composerDraftTarget={context.threadRef}
workspaceMutationId={null}
visible
/>
</div>
</RegistryContext.Provider>,
);
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(
<RegistryContext.Provider value={context.registry}>
<div style={{ height: 600, width: 600, display: "flex", flexDirection: "column" }}>
<DiffPanel
mode="embedded"
composerDraftTarget={context.threadRef}
workspaceMutationId={null}
visible
/>
</div>
</RegistryContext.Provider>,
);
// 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 = () => (
<RegistryContext.Provider value={context.registry}>
<div style={{ height: 600, width: 600, display: "flex", flexDirection: "column" }}>
<DiffPanel
mode="embedded"
composerDraftTarget={context.threadRef}
workspaceMutationId={null}
visible={false}
/>
</div>
</RegistryContext.Provider>
);
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" },
Expand Down
98 changes: 50 additions & 48 deletions apps/web/src/components/DiffPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -69,7 +72,6 @@ import {
useThreadCheckpointSummaries,
useQuietThreadShell,
useQuietThreadVisibleTurnItems,
useQuietThreadProjection,
} from "../state/entities";
import { useClientSettings, updateClientSettings } from "../hooks/useSettings";
import { formatRelativeTimeLabel, formatShortTimestamp } from "../timestampFormat";
Expand Down Expand Up @@ -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";
Expand All @@ -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";
Expand All @@ -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<typeof threadChangedRepositories> = Object.freeze([]);
const NO_TURN_DIFF_SECTIONS: ReadonlyArray<TurnDiffSection> = [];
const DIFF_FILE_TREE_STORAGE_KEY = "t3code.diffFileTreeOpen";

Expand Down Expand Up @@ -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<string | null>(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);
Expand Down Expand Up @@ -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 } : {}),
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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}` : "";
Expand Down Expand Up @@ -1180,12 +1180,12 @@ export default function DiffPanel({
<DropdownMenu>
<DropdownMenuTrigger
render={<Button size="xs" variant="ghost-muted" />}
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 })}
>
<span className="truncate">{gitRepository?.name ?? threadFolderName}</span>
<span className="truncate">{gitRepositoryLabel}</span>
<ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="max-h-80 max-w-72">
Expand All @@ -1204,7 +1204,9 @@ export default function DiffPanel({
value={repository.repositoryPath}
closeOnClick
>
<span className="min-w-0 truncate">{repository.name}</span>
<span className="min-w-0 truncate">
{threadGitRepositoryLabel(repository, activeProject?.workspaceRoot ?? null)}
</span>
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
Expand Down
Loading
Loading