🙌 OpenHands: AI-Driven Development
feat: commits view — commit history with per-commit diffs (#1651)
Hiep Le96071cbd6fd4
diff --git a/__tests__/api/agent-server-git-service.test.ts b/__tests__/api/agent-server-git-service.test.tsindex 7cdb89b881..fa5dc5dd1c 100644--- a/__tests__/api/agent-server-git-service.test.ts+++ b/__tests__/api/agent-server-git-service.test.ts@@ -1,4 +1,5 @@import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";+import { AxiosError } from "axios";import { describe, test, expect, vi, beforeEach, afterEach } from "vitest";import {__resetActiveStoreForTests,@@ -7,11 +8,13 @@ import {} from "#/api/backend-registry/active-store";import { callCloudProxy } from "#/api/cloud/proxy";import type { Backend } from "#/api/backend-registry/types";+import { buildHttpBaseUrl } from "#/utils/websocket-url";import AgentServerGitService from "../../src/api/git-service/agent-server-git-service.api";-const { mockGitChanges, mockGitDiff } = vi.hoisted(() => ({+const { mockGitChanges, mockGitDiff, mockClientGet } = vi.hoisted(() => ({mockGitChanges: vi.fn(),mockGitDiff: vi.fn(),+ mockClientGet: vi.fn(),}));vi.mock("@openhands/typescript-client/workspace/remote-workspace", () => ({@@ -19,6 +22,9 @@ vi.mock("@openhands/typescript-client/workspace/remote-workspace", () => ({return {gitChanges: mockGitChanges,gitDiff: mockGitDiff,+ // The commit endpoints go through the SDK's raw HttpClient (the+ // typed wrappers don't know them).+ client: { get: mockClientGet },};}),}));@@ -32,6 +38,7 @@ describe("AgentServerGitService", () => {vi.clearAllMocks();mockGitChanges.mockReset();mockGitDiff.mockReset();+ mockClientGet.mockReset();vi.mocked(RemoteWorkspace).mockClear();});@@ -164,6 +171,121 @@ describe("AgentServerGitService", () => {});});+ describe("getGitCommits", () => {+ test("fetches recent commits via the raw client and maps to camelCase", async () => {+ // Arrange+ mockClientGet.mockResolvedValue({+ data: {+ commits: [+ {+ sha: "a".repeat(40),+ short_sha: "aaaaaaa",+ subject: "add logging",+ author: "Agent",+ timestamp: "2026-07-10T12:00:00+07:00",+ },+ ],+ has_more: true,+ },+ });++ // Act+ const page = await AgentServerGitService.getGitCommits(+ "http://localhost:3000/api/conversations/123",+ "test-api-key",+ "/workspace/project",+ );++ // Assert+ expect(mockClientGet).toHaveBeenCalledWith("/api/git/commits", {+ params: { path: "/workspace/project", limit: "50" },+ });+ expect(page).toEqual({+ commits: [+ {+ sha: "a".repeat(40),+ shortSha: "aaaaaaa",+ subject: "add logging",+ author: "Agent",+ timestamp: "2026-07-10T12:00:00+07:00",+ },+ ],+ hasMore: true,+ });+ });++ test("resolves null when the agent server predates the endpoint (404)", async () => {+ // Arrange — the SDK HttpClient throws a raw HttpError carrying status.+ mockClientGet.mockRejectedValue(+ Object.assign(new Error("Not Found"), {+ name: "HttpError",+ status: 404,+ }),+ );++ // Act+ const page = await AgentServerGitService.getGitCommits(+ "http://localhost:3000/api/conversations/123",+ "test-api-key",+ "/workspace/project",+ );++ // Assert+ expect(page).toBeNull();+ });+ });++ describe("getCommitChanges", () => {+ test("fetches a commit's files and maps statuses to the client format", async () => {+ // Arrange+ const sha = "b".repeat(40);+ mockClientGet.mockResolvedValue({+ data: [{ status: "DELETED", path: "doomed.txt" }],+ });++ // Act+ const changes = await AgentServerGitService.getCommitChanges(+ "http://localhost:3000/api/conversations/123",+ "test-api-key",+ "/workspace/project",+ sha,+ );++ // Assert+ expect(mockClientGet).toHaveBeenCalledWith(+ `/api/git/commits/${sha}/changes`,+ { params: { path: "/workspace/project" } },+ );+ expect(changes).toEqual([{ status: "D", path: "doomed.txt" }]);+ });+ });++ describe("getGitChangeDiff with commit", () => {+ test("fetches the per-commit diff via the raw client, not the wrapper", async () => {+ // Arrange+ const sha = "c".repeat(40);+ mockClientGet.mockResolvedValue({+ data: { modified: "", original: "contents" },+ });++ // Act+ const diff = await AgentServerGitService.getGitChangeDiff(+ "123",+ "http://localhost:3000/api/conversations/123",+ "test-api-key",+ "/workspace/project/doomed.txt",+ sha,+ );++ // Assert+ expect(mockClientGet).toHaveBeenCalledWith("/api/git/diff", {+ params: { path: "/workspace/project/doomed.txt", commit: sha },+ });+ expect(mockGitDiff).not.toHaveBeenCalled();+ expect(diff).toEqual({ modified: "", original: "contents" });+ });+ });+describe("cloud backend", () => {const cloudBackend: Backend = {id: "cloud-1",@@ -266,6 +388,53 @@ describe("AgentServerGitService", () => {});});+ describe("getGitCommits", () => {+ test("reaches the runtime through the generic cloud-proxy envelope", async () => {+ // Arrange+ vi.mocked(callCloudProxy).mockResolvedValue({+ commits: [],+ has_more: false,+ });++ // Act+ await AgentServerGitService.getGitCommits(+ runtimeConversationUrl,+ "session-key",+ "workspace/project",+ );++ // Assert — session-api-key envelope to the conversation's runtime+ // host, with the git path normalized to an absolute runtime path.+ expect(callCloudProxy).toHaveBeenCalledWith({+ backend: cloudBackend,+ method: "GET",+ hostOverride: buildHttpBaseUrl(runtimeConversationUrl),+ path: "/api/git/commits?path=%2Fworkspace%2Fproject&limit=50",+ authMode: "session-api-key",+ sessionApiKey: "session-key",+ });+ });++ test("resolves null when the runtime predates the endpoint (404)", async () => {+ // Arrange — the proxy hop surfaces upstream failures as AxiosErrors.+ vi.mocked(callCloudProxy).mockRejectedValue(+ Object.assign(new AxiosError("Not Found"), {+ response: { status: 404 },+ }),+ );++ // Act+ const page = await AgentServerGitService.getGitCommits(+ runtimeConversationUrl,+ "session-key",+ "workspace/project",+ );++ // Assert+ expect(page).toBeNull();+ });+ });+test("does not touch the runtime workspace SDK on cloud backends", async () => {// Arrangevi.mocked(callCloudProxy).mockResolvedValue([]);diff --git a/__tests__/components/features/diff-viewer/file-diff-viewer.test.tsx b/__tests__/components/features/diff-viewer/file-diff-viewer.test.tsxindex b8daf90561..8f3a49622f 100644--- a/__tests__/components/features/diff-viewer/file-diff-viewer.test.tsx+++ b/__tests__/components/features/diff-viewer/file-diff-viewer.test.tsx@@ -167,6 +167,25 @@ describe("FileDiffViewer", () => {expect(screen.queryByTestId("view-mode-new")).not.toBeInTheDocument();});+ it("renders a deleted file's diff content in commit mode instead of the placeholder", async () => {+ // Arrange — in per-commit mode both sides come from git objects, so a+ // deleted file has real content to show (original vs empty).+ mockDiff = { original: "old content", modified: "" };+ const user = userEvent.setup();+ render(+ <FileDiffViewer path="src/removed.ts" type="D" commit={"a".repeat(40)} />,+ );++ // Act+ await expand(user);++ // Assert+ expect(+ screen.queryByTestId("file-deleted-message"),+ ).not.toBeInTheDocument();+ expect(screen.getByTestId("file-diff-viewer")).toBeInTheDocument();+ });+it("reflects the active view mode via aria-pressed on the toggle buttons", async () => {const user = userEvent.setup();render(<FileDiffViewer path="src/index.ts" type="M" />);diff --git a/__tests__/hooks/query/use-unified-git-commits.test.tsx b/__tests__/hooks/query/use-unified-git-commits.test.tsxnew file mode 100644index 0000000000..064133b8dc--- /dev/null+++ b/__tests__/hooks/query/use-unified-git-commits.test.tsx@@ -0,0 +1,83 @@+import React from "react";+import { describe, it, expect, vi, beforeEach } from "vitest";+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import { useUnifiedGitCommits } from "#/hooks/query/use-unified-git-commits";+import AgentServerGitService from "#/api/git-service/agent-server-git-service.api";++const conversation = {+ conversation_url: "http://localhost:18000/api/conversations/c1",+ session_api_key: "test-key",+ workspace: { working_dir: "/workspace/project" },+};++vi.mock("#/hooks/use-conversation-id", () => ({+ useConversationId: () => ({ conversationId: "c1" }),+}));+vi.mock("#/hooks/query/use-active-conversation", () => ({+ useActiveConversation: () => ({ data: conversation }),+}));+vi.mock("#/hooks/use-runtime-is-ready", () => ({+ useRuntimeIsReady: () => true,+}));++function makeWrapper() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+}++describe("useUnifiedGitCommits", () => {+ const getGitCommitsSpy = vi.spyOn(AgentServerGitService, "getGitCommits");++ beforeEach(() => {+ getGitCommitsSpy.mockReset();+ });++ it("exposes the service's commit page for the active conversation", async () => {+ // Arrange+ const commit = {+ sha: "a".repeat(40),+ shortSha: "aaaaaaa",+ subject: "add logging",+ author: "Agent",+ timestamp: "2026-07-10T12:00:00+07:00",+ };+ getGitCommitsSpy.mockResolvedValue({ commits: [commit], hasMore: true });++ // Act+ const { result } = renderHook(() => useUnifiedGitCommits(), {+ wrapper: makeWrapper(),+ });++ // Assert+ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(getGitCommitsSpy).toHaveBeenCalledWith(+ conversation.conversation_url,+ conversation.session_api_key,+ "/workspace/project",+ 50,+ );+ expect(result.current.commits).toEqual([commit]);+ expect(result.current.hasMore).toBe(true);+ expect(result.current.isUnsupported).toBe(false);+ });++ it("marks the feature unsupported when the service resolves null (old server)", async () => {+ // Arrange+ getGitCommitsSpy.mockResolvedValue(null);++ // Act+ const { result } = renderHook(() => useUnifiedGitCommits(), {+ wrapper: makeWrapper(),+ });++ // Assert+ await waitFor(() => expect(result.current.isUnsupported).toBe(true));+ expect(result.current.commits).toEqual([]);+ });+});diff --git a/__tests__/hooks/use-auto-refresh-files-on-edit.test.tsx b/__tests__/hooks/use-auto-refresh-files-on-edit.test.tsxindex a94bbe4201..a0ef5817c5 100644--- a/__tests__/hooks/use-auto-refresh-files-on-edit.test.tsx+++ b/__tests__/hooks/use-auto-refresh-files-on-edit.test.tsx@@ -93,12 +93,17 @@ describe("useAutoRefreshFilesOnEdit", () => {.addEvent(makeObservationEvent("1", kind, "git commit -m 'done'"));});- // Assert — the diff queries refresh, and nothing else does (workspace- // file queries on every shell command would churn the Files tab).+ // Assert — the diff and commit-list queries refresh, and nothing+ // else does (workspace file queries on every shell command would+ // churn the Files tab; per-commit queries are immutable).const invalidatedKeys = spy.mock.calls.map((call) => (call[0] as { queryKey: unknown[] }).queryKey[0],);- expect(invalidatedKeys).toEqual(["file_changes", "file_diff"]);+ expect(invalidatedKeys).toEqual([+ "file_changes",+ "file_diff",+ "git_commits",+ ]);},);diff --git a/__tests__/routes/commits-tab.test.tsx b/__tests__/routes/commits-tab.test.tsxnew file mode 100644index 0000000000..37872f092f--- /dev/null+++ b/__tests__/routes/commits-tab.test.tsx@@ -0,0 +1,161 @@+import React from "react";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { describe, it, expect, vi, beforeEach } from "vitest";+import { MemoryRouter } from "react-router";++import GitCommits from "#/routes/commits-tab";+import AgentServerGitService from "#/api/git-service/agent-server-git-service.api";+import { useAgentState } from "#/hooks/use-agent-state";+import { AgentState } from "#/types/agent-state";+import type { GitCommit } from "#/api/open-hands.types";++const conversation = {+ conversation_url: "http://localhost:18000/api/conversations/c1",+ session_api_key: "test-key",+ workspace: { working_dir: "/workspace/project" },+};++vi.mock("#/hooks/use-agent-state");+vi.mock("#/hooks/use-conversation-id", () => ({+ useConversationId: () => ({ conversationId: "c1" }),+}));+vi.mock("#/hooks/query/use-active-conversation", () => ({+ useActiveConversation: () => ({ data: conversation }),+}));+vi.mock("#/hooks/use-runtime-is-ready", () => ({+ useRuntimeIsReady: () => true,+}));++const makeCommit = (overrides: Partial<GitCommit> = {}): GitCommit => ({+ sha: "a".repeat(40),+ shortSha: "aaaaaaa",+ subject: "add logging",+ author: "Agent",+ timestamp: "2026-07-10T12:00:00+07:00",+ ...overrides,+});++const wrapper = ({ children }: { children: React.ReactNode }) => (+ <MemoryRouter>+ <QueryClientProvider+ client={+ new QueryClient({ defaultOptions: { queries: { retry: false } } })+ }+ >+ {children}+ </QueryClientProvider>+ </MemoryRouter>+);++describe("Commits Tab", () => {+ const getGitCommitsSpy = vi.spyOn(AgentServerGitService, "getGitCommits");+ const getCommitChangesSpy = vi.spyOn(+ AgentServerGitService,+ "getCommitChanges",+ );++ beforeEach(() => {+ getGitCommitsSpy.mockReset();+ getCommitChangesSpy.mockReset();+ vi.mocked(useAgentState).mockReturnValue({+ curAgentState: AgentState.RUNNING,+ });+ });++ it("shows the waiting state while the runtime is inactive", () => {+ // Arrange+ vi.mocked(useAgentState).mockReturnValue({+ curAgentState: AgentState.ERROR,+ });+ getGitCommitsSpy.mockResolvedValue({ commits: [], hasMore: false });++ // Act+ render(<GitCommits />, { wrapper });++ // Assert+ expect(screen.getByTestId("commits-tab-status")).toBeInTheDocument();+ });++ it("shows the empty state when the repository has no commits", async () => {+ // Arrange+ getGitCommitsSpy.mockResolvedValue({ commits: [], hasMore: false });++ // Act+ render(<GitCommits />, { wrapper });++ // Assert+ expect(+ await screen.findByText("DIFF_VIEWER$NO_COMMITS"),+ ).toBeInTheDocument();+ });++ it("lists the commits returned by the server", async () => {+ // Arrange+ getGitCommitsSpy.mockResolvedValue({+ commits: [+ makeCommit({ sha: "a".repeat(40), subject: "add logging" }),+ makeCommit({+ sha: "b".repeat(40),+ shortSha: "bbbbbbb",+ subject: "fix tests",+ }),+ ],+ hasMore: false,+ });++ // Act+ render(<GitCommits />, { wrapper });++ // Assert+ expect(await screen.findByText("add logging")).toBeInTheDocument();+ expect(screen.getByText("fix tests")).toBeInTheDocument();+ expect(screen.getByText("aaaaaaa")).toBeInTheDocument();+ });++ it("expanding a commit fetches and lists the files it changed", async () => {+ // Arrange+ const user = userEvent.setup();+ const sha = "a".repeat(40);+ getGitCommitsSpy.mockResolvedValue({+ commits: [makeCommit({ sha })],+ hasMore: false,+ });+ getCommitChangesSpy.mockResolvedValue([+ { status: "D", path: "doomed.txt" },+ ]);+ render(<GitCommits />, { wrapper });+ await screen.findByText("add logging");++ // Act+ await user.click(screen.getByTestId("commit-row-toggle"));++ // Assert — the commit's file list is fetched by sha and rendered.+ await waitFor(() =>+ expect(getCommitChangesSpy).toHaveBeenCalledWith(+ conversation.conversation_url,+ conversation.session_api_key,+ "/workspace/project",+ sha,+ ),+ );+ expect(await screen.findByText("doomed.txt")).toBeInTheDocument();+ });++ it("shows the cap notice when the history was truncated", async () => {+ // Arrange+ getGitCommitsSpy.mockResolvedValue({+ commits: [makeCommit()],+ hasMore: true,+ });++ // Act+ render(<GitCommits />, { wrapper });++ // Assert+ expect(+ await screen.findByTestId("commit-list-cap-notice"),+ ).toBeInTheDocument();+ });+});diff --git a/__tests__/routes/files-tab.test.tsx b/__tests__/routes/files-tab.test.tsxindex 03d08424d6..0319b0ba3a 100644--- a/__tests__/routes/files-tab.test.tsx+++ b/__tests__/routes/files-tab.test.tsx@@ -12,6 +12,7 @@ import { NavigationProvider } from "#/context/navigation-context";// Mocks must be declared before the SUT is imported.const useHasAttachedSourceMock = vi.fn();const useHasGitCommitsMock = vi.fn();+const useUnifiedGitCommitsMock = vi.fn();const useWorkspaceFilesMock = vi.fn();const useWorkspaceFileContentMock = vi.fn();const refetchGitChangesMock = vi.fn();@@ -25,6 +26,10 @@ vi.mock("#/hooks/query/use-has-git-commits", () => ({useHasGitCommitsMock(opts),}));+vi.mock("#/hooks/query/use-unified-git-commits", () => ({+ useUnifiedGitCommits: () => useUnifiedGitCommitsMock(),+}));+vi.mock("#/hooks/query/use-workspace-files", () => ({useWorkspaceFiles: () => useWorkspaceFilesMock(),}));@@ -45,6 +50,10 @@ vi.mock("#/routes/changes-tab", () => ({default: () => <div data-testid="changes-tab-content">Diff View</div>,}));+vi.mock("#/routes/commits-tab", () => ({+ default: () => <div data-testid="commits-tab-content">Commits View</div>,+}));+function renderTab(conversationId: string | null = null) {const client = new QueryClient({defaultOptions: { queries: { retry: false } },@@ -82,6 +91,7 @@ describe("FilesTab", () => {useHasAttachedSourceMock.mockReset();useHasGitCommitsMock.mockReset();+ useUnifiedGitCommitsMock.mockReset();useWorkspaceFilesMock.mockReset();useWorkspaceFileContentMock.mockReset();refetchGitChangesMock.mockReset();@@ -91,6 +101,17 @@ describe("FilesTab", () => {hasCommits: true,isLoading: false,});+ // Default: the agent server supports the commits API (the third toggle+ // segment is offered) but the conversation has no commits yet.+ useUnifiedGitCommitsMock.mockReturnValue({+ commits: [],+ hasMore: false,+ isUnsupported: false,+ isLoading: false,+ isFetching: false,+ isSuccess: true,+ isError: false,+ });useWorkspaceFilesMock.mockReturnValue({data: ["index.html", "src/main.ts", "README.md"],@@ -589,4 +610,72 @@ describe("FilesTab", () => {expect(useWorkspaceFileContentMock).not.toHaveBeenCalledWith("demo.html");});});++ describe("commits view", () => {+ it("offers the Commits toggle option when the server supports the commits API", () => {+ // Arrange — beforeEach default: commits supported.+ useHasAttachedSourceMock.mockReturnValue({+ hasAttachedSource: true,+ isLoading: false,+ });++ // Act+ renderTab();++ // Assert+ expect(+ screen.getByTestId("files-tab-diff-toggle-option-commits"),+ ).toBeInTheDocument();+ });++ it("hides the Commits toggle option against an older agent server", () => {+ // Arrange — the commits endpoint 404'd: server too old.+ useHasAttachedSourceMock.mockReturnValue({+ hasAttachedSource: true,+ isLoading: false,+ });+ useUnifiedGitCommitsMock.mockReturnValue({+ commits: [],+ hasMore: false,+ isUnsupported: true,+ isLoading: false,+ isFetching: false,+ isSuccess: true,+ isError: false,+ });++ // Act+ renderTab();++ // Assert+ expect(+ screen.queryByTestId("files-tab-diff-toggle-option-commits"),+ ).not.toBeInTheDocument();+ });++ it("switches the panel to the commits view when the Commits option is selected", async () => {+ // Arrange+ const user = userEvent.setup();+ useHasAttachedSourceMock.mockReturnValue({+ hasAttachedSource: true,+ isLoading: false,+ });+ renderTab();++ // Act+ await user.click(+ screen.getByTestId("files-tab-diff-toggle-option-commits"),+ );++ // Assert — the commits view replaces the diff view; the file-browser+ // controls (Rich/Plain) stay hidden.+ expect(screen.getByTestId("commits-tab-content")).toBeInTheDocument();+ expect(+ screen.queryByTestId("changes-tab-content"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("files-tab-content-mode-toggle"),+ ).not.toBeInTheDocument();+ });+ });});diff --git a/src/api/git-service/agent-server-git-service.api.ts b/src/api/git-service/agent-server-git-service.api.tsindex a7d168b498..07ae22ec61 100644--- a/src/api/git-service/agent-server-git-service.api.ts+++ b/src/api/git-service/agent-server-git-service.api.ts@@ -1,15 +1,35 @@import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";+import { isAxiosError } from "axios";import { mapAnyGitStatusToClientStatus } from "#/utils/git-status-mapper";-import type { GitChange, GitChangeDiff } from "../open-hands.types";+import { buildHttpBaseUrl } from "#/utils/websocket-url";+import type {+ GitChange,+ GitChangeDiff,+ GitCommitsPage,+} from "../open-hands.types";import { getActiveBackend } from "../backend-registry/active-store";import { callCloudProxy } from "../cloud/proxy";import { getAgentServerClientOptions } from "../agent-server-client-options";+import { isSdkHttpStatusError } from "../agent-server-compatibility";interface AgentServerGitChange {status: string;path: string;}+interface AgentServerGitCommit {+ sha: string;+ short_sha: string;+ subject: string;+ author: string;+ timestamp: string;+}++interface AgentServerGitCommitsPage {+ commits: AgentServerGitCommit[];+ has_more: boolean;+}+/*** Git operations for agent-server conversations.*@@ -36,6 +56,57 @@ function toAbsoluteRuntimePath(path: string): string {return path.startsWith("/") ? path : `/${path}`;}+/**+ * GET an arbitrary runtime git endpoint in both backend modes. Local mode+ * uses the SDK's public `HttpClient` (the typed `gitChanges`/`gitDiff`+ * wrappers don't know the newer endpoints/params, and they re-wrap errors,+ * dropping the `.status` needed for 404 feature-detection). Cloud mode goes+ * through the generic cloud-proxy envelope with the sandbox's session API+ * key — the same hop `executeCommand`/`downloadFile` use — so no dedicated+ * cloud API endpoints are required.+ */+async function getFromRuntime<T>(+ conversationUrl: string | null | undefined,+ sessionApiKey: string | null | undefined,+ apiPath: string,+ params: { path: string } & Record<string, string>,+): Promise<T> {+ const active = getActiveBackend().backend;++ if (active.kind === "cloud" && conversationUrl) {+ const search = new URLSearchParams({+ ...params,+ path: toAbsoluteRuntimePath(params.path),+ });+ return callCloudProxy<T>({+ backend: active,+ method: "GET",+ hostOverride: buildHttpBaseUrl(conversationUrl),+ path: `${apiPath}?${search.toString()}`,+ authMode: "session-api-key",+ sessionApiKey: sessionApiKey ?? undefined,+ });+ }++ const response = await new RemoteWorkspace(+ getAgentServerClientOptions({ conversationUrl, sessionApiKey }),+ ).client.get<T>(apiPath, { params });+ return response.data;+}++/**+ * The commit endpoints are newer than some deployed agent servers. A 404+ * (route absent) means "server too old" — callers hide the commits section+ * instead of surfacing an error. Local calls throw the SDK's `HttpError`;+ * cloud-proxy calls throw an `AxiosError`.+ */+function isEndpointMissingError(error: unknown): boolean {+ return (+ isSdkHttpStatusError(error, 404) ||+ (isAxiosError(error) && error.response?.status === 404)+ );+}+class AgentServerGitService {static async getGitChanges(conversationId: string,@@ -92,12 +163,90 @@ class AgentServerGitService {}));}+ /**+ * List the conversation's commits (display-base..HEAD, newest first).+ * Resolves to `null` when the agent server predates the endpoint (404),+ * so callers can hide the commits section instead of erroring.+ */+ static async getGitCommits(+ conversationUrl: string | null | undefined,+ sessionApiKey: string | null | undefined,+ path: string,+ limit = 50,+ ): Promise<GitCommitsPage | null> {+ try {+ const page = await getFromRuntime<AgentServerGitCommitsPage>(+ conversationUrl,+ sessionApiKey,+ "/api/git/commits",+ { path, limit: String(limit) },+ );+ return {+ commits: (page?.commits ?? []).map((commit) => ({+ sha: commit.sha,+ shortSha: commit.short_sha,+ subject: commit.subject,+ author: commit.author,+ timestamp: commit.timestamp,+ })),+ hasMore: Boolean(page?.has_more),+ };+ } catch (error) {+ if (isEndpointMissingError(error)) return null;+ throw error;+ }+ }++ /** Files changed by a single commit (vs its first parent). */+ static async getCommitChanges(+ conversationUrl: string | null | undefined,+ sessionApiKey: string | null | undefined,+ path: string,+ sha: string,+ ): Promise<GitChange[]> {+ const changes = await getFromRuntime<AgentServerGitChange[]>(+ conversationUrl,+ sessionApiKey,+ `/api/git/commits/${encodeURIComponent(sha)}/changes`,+ { path },+ );++ if (!Array.isArray(changes)) {+ throw new Error(+ "Invalid response from runtime - runtime may be unavailable",+ );+ }++ return changes.map((change) => ({+ status: mapAnyGitStatusToClientStatus(+ String(change.status) as Parameters<+ typeof mapAnyGitStatusToClientStatus+ >[0],+ ),+ path: change.path,+ }));+ }+static async getGitChangeDiff(conversationId: string,conversationUrl: string | null | undefined,sessionApiKey: string | null | undefined,path: string,+ commit?: string,): Promise<GitChangeDiff> {+ if (commit) {+ // Per-commit diff: both sides come from git objects on the server,+ // so files the commit deleted still render.+ const commitDiff = await getFromRuntime<+ GitChangeDiff & { diff?: string }+ >(conversationUrl, sessionApiKey, "/api/git/diff", { path, commit });+ return {+ modified: commitDiff?.modified ?? "",+ original: commitDiff?.original ?? "",+ ...(commitDiff?.diff ? { diff: commitDiff.diff } : {}),+ } as GitChangeDiff;+ }+const active = getActiveBackend().backend;if (active.kind === "cloud" && conversationId) {diff --git a/src/api/open-hands.types.ts b/src/api/open-hands.types.tsindex 8928daa5a8..072a1e8078 100644--- a/src/api/open-hands.types.ts+++ b/src/api/open-hands.types.ts@@ -108,6 +108,20 @@ export interface GitChangeDiff {original: string;}+export interface GitCommit {+ sha: string;+ shortSha: string;+ subject: string;+ author: string;+ // ISO 8601 author date with UTC offset (git log %aI).+ timestamp: string;+}++export interface GitCommitsPage {+ commits: GitCommit[];+ hasMore: boolean;+}+export interface InputMetadata {name: string;description: string;diff --git a/src/components/features/diff-viewer/commit-list.tsx b/src/components/features/diff-viewer/commit-list.tsxnew file mode 100644index 0000000000..9822cf0a78--- /dev/null+++ b/src/components/features/diff-viewer/commit-list.tsx@@ -0,0 +1,51 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { GitCommit } from "#/api/open-hands.types";+import { I18nKey } from "#/i18n/declaration";+import { CommitRow } from "./commit-row";++export interface CommitListProps {+ commits: GitCommit[];+ /** True when the server capped the page — surfaces the cap notice. */+ hasMore: boolean;+}++/**+ * The workspace's recent commit history (newest first). Single-open+ * accordion: expanding a commit collapses the previously expanded one.+ * Empty/loading/waiting states are the host view's job+ * (see routes/commits-tab.tsx).+ */+export function CommitList({ commits, hasMore }: CommitListProps) {+ const { t } = useTranslation("openhands");+ const [expandedSha, setExpandedSha] = React.useState<string | null>(null);++ // Author is noise when every commit has the same one (the usual+ // single-agent conversation); show it only when authors differ.+ const showAuthor = new Set(commits.map((commit) => commit.author)).size > 1;++ return (+ <section data-testid="commit-list" className="w-full flex flex-col">+ {commits.map((commit) => (+ <CommitRow+ key={commit.sha}+ commit={commit}+ showAuthor={showAuthor}+ isExpanded={expandedSha === commit.sha}+ onToggle={() =>+ setExpandedSha((prev) => (prev === commit.sha ? null : commit.sha))+ }+ />+ ))}++ {hasMore && (+ <div+ data-testid="commit-list-cap-notice"+ className="px-3 py-2.5 text-xs text-[var(--oh-muted)]"+ >+ {t(I18nKey.DIFF_VIEWER$COMMITS_CAP, { count: commits.length })}+ </div>+ )}+ </section>+ );+}diff --git a/src/components/features/diff-viewer/commit-row.tsx b/src/components/features/diff-viewer/commit-row.tsxnew file mode 100644index 0000000000..829943e9d0--- /dev/null+++ b/src/components/features/diff-viewer/commit-row.tsx@@ -0,0 +1,94 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { GitCommit } from "#/api/open-hands.types";+import { I18nKey } from "#/i18n/declaration";+import { cn } from "#/utils/utils";+import { formatTimeDelta } from "#/utils/format-time-delta";+import ChevronUp from "#/icons/chveron-up.svg?react";+import { useCommitChanges } from "#/hooks/query/use-commit-changes";+import { FileDiffViewer } from "./file-diff-viewer";+import { LoadingSpinner } from "./loading-spinner";++export interface CommitRowProps {+ commit: GitCommit;+ /** Only shown when the listed commits have more than one author. */+ showAuthor: boolean;+ isExpanded: boolean;+ onToggle: () => void;+}++/**+ * One collapsible commit: header row (short SHA, subject, relative time),+ * expanding into the files that commit changed, each rendered with the+ * regular FileDiffViewer in per-commit mode.+ */+export function CommitRow({+ commit,+ showAuthor,+ isExpanded,+ onToggle,+}: CommitRowProps) {+ const { t } = useTranslation("openhands");++ // Only fetch a commit's file list once the row is expanded.+ const {+ data: changes,+ isLoading,+ isSuccess,+ } = useCommitChanges(commit.sha, { enabled: isExpanded });++ return (+ <div data-testid="commit-row" className="w-full flex flex-col">+ <button+ type="button"+ onClick={onToggle}+ aria-expanded={isExpanded}+ data-testid="commit-row-toggle"+ className="w-full flex items-center gap-2 px-3 py-2.5 border-b border-[var(--oh-border)] text-sm text-content text-left hover:cursor-pointer"+ >+ <code className="font-mono text-xs text-[var(--oh-muted)] flex-shrink-0">+ {commit.shortSha}+ </code>+ <strong className="flex-1 truncate font-medium">+ {commit.subject}+ </strong>+ {showAuthor && (+ <span className="text-xs text-[var(--oh-muted)] truncate max-w-32 flex-shrink-0">+ {commit.author}+ </span>+ )}+ <span className="text-xs text-[var(--oh-muted)] flex-shrink-0">+ {`${formatTimeDelta(commit.timestamp)} ${t(I18nKey.CONVERSATION$AGO)}`}+ </span>+ <ChevronUp+ className={cn(+ "w-4 h-4 transition-transform flex-shrink-0",+ !isExpanded && "transform rotate-180",+ )}+ />+ </button>++ {isExpanded && (+ <div+ data-testid="commit-row-content"+ className="w-full flex flex-col pl-6"+ >+ {isLoading && (+ <div className="p-3">+ <LoadingSpinner className="w-4 h-4" />+ </div>+ )}+ {isSuccess &&+ changes?.map((change) => (+ <FileDiffViewer+ key={change.path}+ path={change.path}+ type={change.status}+ commit={commit.sha}+ />+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/src/components/features/diff-viewer/file-diff-viewer.tsx b/src/components/features/diff-viewer/file-diff-viewer.tsxindex 7b4924e2ce..c5b3fe1b57 100644--- a/src/components/features/diff-viewer/file-diff-viewer.tsx+++ b/src/components/features/diff-viewer/file-diff-viewer.tsx@@ -72,9 +72,15 @@ const beforeMount = (monaco: Monaco) => {export interface FileDiffViewerProps {path: string;type: GitChangeStatus;+ /**+ * When set, show the file's diff as changed by this commit instead of+ * the working-tree-vs-base diff. Deleted files render their content in+ * commit mode (both sides come from git objects).+ */+ commit?: string;}-export function FileDiffViewer({ path, type }: FileDiffViewerProps) {+export function FileDiffViewer({ path, type, commit }: FileDiffViewerProps) {const { t } = useTranslation("openhands");const [isCollapsed, setIsCollapsed] = React.useState(true);const [editorHeight, setEditorHeight] = React.useState(400);@@ -102,6 +108,7 @@ export function FileDiffViewer({ path, type }: FileDiffViewerProps) {filePath,type,enabled: !isCollapsed,+ commit,});const updateEditorHeight = React.useCallback(() => {@@ -249,7 +256,7 @@ export function FileDiffViewer({ path, type }: FileDiffViewerProps) {</span></div>- {!isCollapsed && isDeleted && (+ {!isCollapsed && isDeleted && !commit && (<divdata-testid="file-deleted-message"className="w-full border-b border-[var(--oh-border)] p-4 bg-base text-[var(--oh-text-dim)] text-sm"@@ -258,7 +265,7 @@ export function FileDiffViewer({ path, type }: FileDiffViewerProps) {</div>)}- {!isCollapsed && !isDeleted && isSuccess && renderContent()}+ {!isCollapsed && (!isDeleted || !!commit) && isSuccess && renderContent()}</div>);}diff --git a/src/hooks/query/use-commit-changes.ts b/src/hooks/query/use-commit-changes.tsnew file mode 100644index 0000000000..5a3cb5954b--- /dev/null+++ b/src/hooks/query/use-commit-changes.ts@@ -0,0 +1,60 @@+import React from "react";+import { useQuery } from "@tanstack/react-query";+import AgentServerGitService from "#/api/git-service/agent-server-git-service.api";+import { useConversationId } from "#/hooks/use-conversation-id";+import { useActiveConversation } from "#/hooks/query/use-active-conversation";+import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";+import { getGitPath } from "#/utils/get-git-path";++type UseCommitChangesConfig = {+ enabled: boolean;+};++export const useCommitChanges = (+ sha: string,+ config: UseCommitChangesConfig,+) => {+ const { conversationId } = useConversationId();+ const { data: conversation } = useActiveConversation();+ const runtimeIsReady = useRuntimeIsReady();++ const conversationUrl = conversation?.conversation_url;+ const sessionApiKey = conversation?.session_api_key;+ const selectedRepository = conversation?.selected_repository;+ const workingDir = conversation?.workspace?.working_dir?.trim();++ const gitPath = React.useMemo(+ () => getGitPath(selectedRepository, workingDir),+ [selectedRepository, workingDir],+ );++ return useQuery({+ queryKey: [+ "commit_changes",+ conversationId,+ conversationUrl,+ sessionApiKey,+ gitPath,+ sha,+ ],+ queryFn: async () => {+ if (!conversationId) throw new Error("No conversation ID");++ return AgentServerGitService.getCommitChanges(+ conversationUrl,+ sessionApiKey,+ gitPath,+ sha,+ );+ },+ // A commit's change list is sha-addressed and immutable — never stale,+ // and deliberately not invalidated by the bash-observation refresh.+ staleTime: Infinity,+ gcTime: 1000 * 60 * 15, // 15 minutes+ retry: false,+ enabled: config.enabled && runtimeIsReady && !!conversationId,+ meta: {+ disableToast: true,+ },+ });+};diff --git a/src/hooks/query/use-unified-git-commits.ts b/src/hooks/query/use-unified-git-commits.tsnew file mode 100644index 0000000000..d8007e1053--- /dev/null+++ b/src/hooks/query/use-unified-git-commits.ts@@ -0,0 +1,65 @@+import React from "react";+import { useQuery } from "@tanstack/react-query";+import AgentServerGitService from "#/api/git-service/agent-server-git-service.api";+import { useConversationId } from "#/hooks/use-conversation-id";+import { useActiveConversation } from "#/hooks/query/use-active-conversation";+import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";+import { getGitPath } from "#/utils/get-git-path";++export const COMMITS_PAGE_LIMIT = 50;++export const useUnifiedGitCommits = () => {+ const { conversationId } = useConversationId();+ const { data: conversation } = useActiveConversation();+ const runtimeIsReady = useRuntimeIsReady();++ const conversationUrl = conversation?.conversation_url;+ const sessionApiKey = conversation?.session_api_key;+ const selectedRepository = conversation?.selected_repository;+ const workingDir = conversation?.workspace?.working_dir?.trim();++ const gitPath = React.useMemo(+ () => getGitPath(selectedRepository, workingDir),+ [selectedRepository, workingDir],+ );++ const result = useQuery({+ queryKey: [+ "git_commits",+ conversationId,+ conversationUrl,+ sessionApiKey,+ gitPath,+ ],+ queryFn: async () => {+ if (!conversationId) throw new Error("No conversation ID");++ return AgentServerGitService.getGitCommits(+ conversationUrl,+ sessionApiKey,+ gitPath,+ COMMITS_PAGE_LIMIT,+ );+ },+ retry: false,+ staleTime: 1000 * 60 * 5, // 5 minutes+ gcTime: 1000 * 60 * 15, // 15 minutes+ refetchOnMount: "always",+ enabled: runtimeIsReady && !!conversationId,+ meta: {+ disableToast: true,+ },+ });++ return {+ commits: result.data?.commits ?? [],+ hasMore: result.data?.hasMore ?? false,+ // `null` data = the endpoint 404'd: the agent server predates the+ // commits API. Hide the section rather than rendering an empty state.+ isUnsupported: result.data === null,+ isLoading: result.isLoading,+ isFetching: result.isFetching,+ isSuccess: result.isSuccess,+ isError: result.isError,+ };+};diff --git a/src/hooks/query/use-unified-git-diff.ts b/src/hooks/query/use-unified-git-diff.tsindex 1d3aafe8a9..df546ddc04 100644--- a/src/hooks/query/use-unified-git-diff.ts+++ b/src/hooks/query/use-unified-git-diff.ts@@ -10,6 +10,11 @@ type UseUnifiedGitDiffConfig = {filePath: string;type: GitChangeStatus;enabled: boolean;+ /**+ * When set, fetch the file's diff as changed by this commit (both sides+ * from git objects) instead of the working-tree-vs-base diff.+ */+ commit?: string;};export const useUnifiedGitDiff = (config: UseUnifiedGitDiffConfig) => {@@ -29,17 +34,33 @@ export const useUnifiedGitDiff = (config: UseUnifiedGitDiffConfig) => {// Deleted files no longer exist on disk, so the agent server's// `/api/git/diff` endpoint returns a `GitPathError` (HTTP 400) for them.// Skip the request entirely and let the UI render a "file deleted"- // placeholder instead of triggering an error toast.+ // placeholder instead of triggering an error toast. Per-commit diffs are+ // exempt: both sides come from git objects, so deleted files render.const isDeleted = config.type === "D";+ // Per-commit diffs get their own cache root: they must not collide with+ // the working-tree diff of the same file, and — being sha-addressed and+ // immutable — must not be refetched by the bash-observation invalidation+ // of ["file_diff"].+ const queryKey = config.commit+ ? [+ "commit_file_diff",+ conversationId,+ conversationUrl,+ sessionApiKey,+ config.commit,+ absoluteFilePath,+ ]+ : [+ "file_diff",+ conversationId,+ conversationUrl,+ sessionApiKey,+ absoluteFilePath,+ ];+return useQuery({- queryKey: [- "file_diff",- conversationId,- conversationUrl,- sessionApiKey,- absoluteFilePath,- ],+ queryKey,queryFn: async () => {if (!conversationId) throw new Error("No conversation ID");@@ -48,10 +69,11 @@ export const useUnifiedGitDiff = (config: UseUnifiedGitDiffConfig) => {conversationUrl,sessionApiKey,absoluteFilePath,+ config.commit,);},- enabled: config.enabled && !isDeleted,- staleTime: 1000 * 60 * 5, // 5 minutes+ enabled: config.enabled && (!isDeleted || !!config.commit),+ staleTime: config.commit ? Infinity : 1000 * 60 * 5, // 5 minutesgcTime: 1000 * 60 * 15, // 15 minutes});};diff --git a/src/hooks/use-auto-refresh-files-on-edit.ts b/src/hooks/use-auto-refresh-files-on-edit.tsindex 284a4d037e..5901c24d44 100644--- a/src/hooks/use-auto-refresh-files-on-edit.ts+++ b/src/hooks/use-auto-refresh-files-on-edit.ts@@ -128,8 +128,13 @@ export function useAutoRefreshFilesOnEdit(): void {// Editor and bash mutations both change what the git Diff view shows —// including the per-file diff content of an already-expanded file.+ // The commits list refreshes too (a `git commit` arrives as a bash+ // observation); per-commit queries (`commit_changes` /+ // `commit_file_diff`) are sha-addressed and immutable, so they are+ // deliberately NOT invalidated.queryClient.invalidateQueries({ queryKey: ["file_changes"] });queryClient.invalidateQueries({ queryKey: ["file_diff"] });+ queryClient.invalidateQueries({ queryKey: ["git_commits"] });if (hasNewFileEdits) {queryClient.invalidateQueries({ queryKey: ["workspace-files"] });diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 176aa82566..b86318cb05 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -19498,6 +19498,57 @@"uk": "Очікування початку виконання...","ca": "Esperant que l'entorn d'execució s'iniciï..."},+ "DIFF_VIEWER$COMMITS": {+ "en": "Commits",+ "ja": "コミット",+ "zh-CN": "提交记录",+ "zh-TW": "提交記錄",+ "ko-KR": "커밋",+ "no": "Commits",+ "it": "Commit",+ "pt": "Commits",+ "es": "Commits",+ "ar": "الإيداعات",+ "fr": "Commits",+ "tr": "Commit'ler",+ "de": "Commits",+ "uk": "Коміти",+ "ca": "Commits"+ },+ "DIFF_VIEWER$NO_COMMITS": {+ "en": "No commits yet",+ "ja": "コミットはまだありません",+ "zh-CN": "暂无提交",+ "zh-TW": "尚無提交",+ "ko-KR": "아직 커밋이 없습니다",+ "no": "Ingen commits ennå",+ "it": "Ancora nessun commit",+ "pt": "Nenhum commit ainda",+ "es": "Aún no hay commits",+ "ar": "لا توجد إيداعات بعد",+ "fr": "Aucun commit pour le moment",+ "tr": "Henüz commit yok",+ "de": "Noch keine Commits",+ "uk": "Ще немає комітів",+ "ca": "Encara no hi ha commits"+ },+ "DIFF_VIEWER$COMMITS_CAP": {+ "en": "Showing the latest {{count}} commits",+ "ja": "最新の{{count}}件のコミットを表示しています",+ "zh-CN": "显示最新的 {{count}} 个提交",+ "zh-TW": "顯示最新的 {{count}} 個提交",+ "ko-KR": "최신 커밋 {{count}}개를 표시 중",+ "no": "Viser de siste {{count}} commitene",+ "it": "Visualizzazione degli ultimi {{count}} commit",+ "pt": "Mostrando os últimos {{count}} commits",+ "es": "Mostrando los últimos {{count}} commits",+ "ar": "عرض أحدث {{count}} إيداعًا",+ "fr": "Affichage des {{count}} derniers commits",+ "tr": "En son {{count}} commit gösteriliyor",+ "de": "Die letzten {{count}} Commits werden angezeigt",+ "uk": "Показано останні {{count}} комітів",+ "ca": "Es mostren els darrers {{count}} commits"+ },"SYSTEM_MESSAGE_MODAL$TITLE": {"en": "Agent Tools & Metadata","zh-CN": "代理工具和元数据",diff --git a/src/routes/commits-tab.tsx b/src/routes/commits-tab.tsxnew file mode 100644index 0000000000..a998ee81d8--- /dev/null+++ b/src/routes/commits-tab.tsx@@ -0,0 +1,66 @@+import { useTranslation } from "react-i18next";+import { CommitList } from "#/components/features/diff-viewer/commit-list";+import { DiffDrawerIcon } from "#/components/features/diff-viewer/diff-drawer-icon";+import { useUnifiedGitCommits } from "#/hooks/query/use-unified-git-commits";+import { useConversationId } from "#/hooks/use-conversation-id";+import { I18nKey } from "#/i18n/declaration";+import { RUNTIME_INACTIVE_STATES } from "#/types/agent-state";+import { useAgentState } from "#/hooks/use-agent-state";+import { RuntimeWaitingState } from "#/components/features/conversation-panel/runtime-waiting-state";+import { ConversationTabEmptyState } from "#/components/features/conversation/conversation-tab-empty-state";++/**+ * The Files tab's "Commits" view: the workspace's recent commit history+ * (newest first), each commit expandable into its per-file diffs. Sits+ * behind the third segment of the Diff/Files toggle, which is only+ * offered when the agent server supports the commits API.+ */+function GitCommits() {+ const { t } = useTranslation("openhands");+ const { conversationId } = useConversationId();+ const { commits, hasMore, isUnsupported, isLoading, isSuccess } =+ useUnifiedGitCommits();++ const { curAgentState } = useAgentState();+ const runtimeIsActive = !RUNTIME_INACTIVE_STATES.includes(curAgentState);++ const showList = isSuccess && !isUnsupported && commits.length > 0;++ return (+ <main className="h-full w-full flex flex-col items-stretch">+ {showList ? (+ <div className="h-full overflow-y-auto flex flex-col items-stretch custom-scrollbar-always">+ {/* Keyed by conversation so switching conversations collapses any+ expanded commit. */}+ <CommitList+ key={conversationId}+ commits={commits}+ hasMore={hasMore}+ />+ </div>+ ) : (+ <div className="flex-1 flex items-center justify-center">+ {!runtimeIsActive && (+ <RuntimeWaitingState+ testId="commits-tab-status"+ messageKey={I18nKey.DIFF_VIEWER$WAITING_FOR_RUNTIME}+ />+ )}+ {runtimeIsActive && isLoading && (+ <RuntimeWaitingState+ testId="commits-tab-status"+ messageKey={I18nKey.DIFF_VIEWER$LOADING}+ />+ )}+ {runtimeIsActive && !isLoading && (+ <ConversationTabEmptyState icon={<DiffDrawerIcon />}>+ {t(I18nKey.DIFF_VIEWER$NO_COMMITS)}+ </ConversationTabEmptyState>+ )}+ </div>+ )}+ </main>+ );+}++export default GitCommits;diff --git a/src/routes/files-tab.tsx b/src/routes/files-tab.tsxindex 4e6cbb36f8..9a4812d701 100644--- a/src/routes/files-tab.tsx+++ b/src/routes/files-tab.tsx@@ -25,7 +25,9 @@ import { SegmentedToggle } from "#/components/features/files-tab/segmented-togglimport type { ViewMode } from "#/components/features/files-tab/view-mode";import RefreshIcon from "#/icons/u-refresh.svg?react";import LinkExternalIcon from "#/icons/link-external.svg?react";+import { useUnifiedGitCommits } from "#/hooks/query/use-unified-git-commits";import GitChanges from "./changes-tab";+import GitCommits from "./commits-tab";function FilesTab() {const { t } = useTranslation("openhands");@@ -63,6 +65,18 @@ function FilesTab() {const diffViewEnabled = persistedState.filesTabDiffView ?? diffViewDefault;const contentViewMode = persistedState.filesTabContentViewMode;+ // Commit history gets a third toggle segment, offered only when the+ // agent server supports the commits API (older servers 404 → the toggle+ // stays two-way and the tab looks exactly as it did before). The+ // selection is session-local; the persisted diff/files preference is+ // untouched so falling out of the commits view restores it.+ const { isSuccess: commitsIsSuccess, isUnsupported: commitsUnsupported } =+ useUnifiedGitCommits();+ const showCommitsOption = commitsIsSuccess && !commitsUnsupported;+ const [commitsViewSelected, setCommitsViewSelected] = useState(false);+ let activeView: "on" | "off" | "commits" = diffViewEnabled ? "on" : "off";+ if (commitsViewSelected && showCommitsOption) activeView = "commits";+// Collapsed by default — the quick-access pill row at the top is usually// enough; the user can expand the tree on demand.const [isTreeVisible, setIsTreeVisible] = useState(false);@@ -125,6 +139,7 @@ function FilesTab() {refetchGitChanges();queryClient.invalidateQueries({ queryKey: ["workspace-files"] });queryClient.invalidateQueries({ queryKey: ["workspace-file-content"] });+ queryClient.invalidateQueries({ queryKey: ["git_commits"] });};return (@@ -135,18 +150,33 @@ function FilesTab() {{/* Top toolbar: diff/files + rich/plain toggles (left-aligned) plusthe refresh button on the right. */}<div className="flex items-center gap-3 px-3 py-1.5 border-b border-[var(--oh-border)]">- <SegmentedToggle<"on" | "off">+ <SegmentedToggle<"on" | "off" | "commits">ariaLabel={t(I18nKey.FILES$DIFF_VIEW)}testId="files-tab-diff-toggle"- value={diffViewEnabled ? "on" : "off"}+ value={activeView}options={[{ value: "on", label: t(I18nKey.FILES$DIFF_VIEW) },{ value: "off", label: t(I18nKey.COMMON$FILES) },+ ...(showCommitsOption+ ? [+ {+ value: "commits" as const,+ label: t(I18nKey.DIFF_VIEWER$COMMITS),+ },+ ]+ : []),]}- onChange={(value) => setFilesTabDiffView(value === "on")}+ onChange={(value) => {+ if (value === "commits") {+ setCommitsViewSelected(true);+ } else {+ setCommitsViewSelected(false);+ setFilesTabDiffView(value === "on");+ }+ }}/>- {!diffViewEnabled && (+ {activeView === "off" && (<SegmentedToggle<ViewMode>ariaLabel={t(I18nKey.FILES$RICH)}testId="files-tab-content-mode-toggle"@@ -163,7 +193,7 @@ function FilesTab() {{/* Open the currently-selected file in a new browser tab. Onlymeaningful while we're showing a file (not the diff view) andwe've resolved its staticUrl from the workspace fileserver. */}- {!diffViewEnabled && selectedFileStaticUrl && (+ {activeView === "off" && selectedFileStaticUrl && (<ahref={selectedFileStaticUrl}target="_blank"@@ -195,11 +225,17 @@ function FilesTab() {</div></div>- {diffViewEnabled ? (+ {activeView === "on" && (<div className="flex-1 min-h-0"><GitChanges /></div>- ) : (+ )}+ {activeView === "commits" && (+ <div className="flex-1 min-h-0">+ <GitCommits />+ </div>+ )}+ {activeView === "off" && (<div className="flex flex-1 flex-col min-h-0">{filesQuery.isLoading ? (<div className="flex flex-1 items-center justify-center text-sm text-[var(--oh-muted)]">