π OpenHands: AI-Driven Development
fix: keep the diff view populated after the agent commits (#1649)
Hiep Lef774cb903ff2
diff --git a/__tests__/api/agent-server-git-service.test.ts b/__tests__/api/agent-server-git-service.test.tsindex d47c23e745..7cdb89b881 100644--- a/__tests__/api/agent-server-git-service.test.ts+++ b/__tests__/api/agent-server-git-service.test.ts@@ -64,9 +64,9 @@ describe("AgentServerGitService", () => {apiKey: "my-session-key",workingDir: "workspace/project",});- expect(mockGitChanges).toHaveBeenCalledWith("/workspace/project", {- ref: "HEAD",- });+ // No `ref`: the server auto-detects the base so committed (and+ // pushed) changes stay visible.+ expect(mockGitChanges).toHaveBeenCalledWith("/workspace/project");});test("preserves slashes in path when using workspace helper", async () => {@@ -80,9 +80,7 @@ describe("AgentServerGitService", () => {pathWithSlashes,);- expect(mockGitChanges).toHaveBeenCalledWith(pathWithSlashes, {- ref: "HEAD",- });+ expect(mockGitChanges).toHaveBeenCalledWith(pathWithSlashes);});test("maps V1 git statuses to V0 format", async () => {@@ -127,9 +125,8 @@ describe("AgentServerGitService", () => {apiKey: "test-api-key",workingDir: "workspace/project",});- expect(mockGitDiff).toHaveBeenCalledWith("/workspace/project/file.ts", {- ref: "HEAD",- });+ // No `ref`: must match getGitChanges' auto-detected base.+ expect(mockGitDiff).toHaveBeenCalledWith("/workspace/project/file.ts");});test("preserves slashes in file path when using workspace helper", async () => {@@ -143,7 +140,7 @@ describe("AgentServerGitService", () => {filePath,);- expect(mockGitDiff).toHaveBeenCalledWith(filePath, { ref: "HEAD" });+ expect(mockGitDiff).toHaveBeenCalledWith(filePath);});test("returns the diff data from the response", async () => {diff --git a/__tests__/hooks/use-auto-refresh-files-on-edit.test.tsx b/__tests__/hooks/use-auto-refresh-files-on-edit.test.tsxindex f68d7cf7dc..a94bbe4201 100644--- a/__tests__/hooks/use-auto-refresh-files-on-edit.test.tsx+++ b/__tests__/hooks/use-auto-refresh-files-on-edit.test.tsx@@ -72,6 +72,55 @@ describe("useAutoRefreshFilesOnEdit", () => {expect(invalidatedKeys).toContain("workspace-files");expect(invalidatedKeys).toContain("workspace-file-content");expect(invalidatedKeys).toContain("file_changes");+ expect(invalidatedKeys).toContain("file_diff");+ });++ it.each(["ExecuteBashObservation", "TerminalObservation"])(+ "refreshes only the git diff queries when a %s arrives",+ (kind) => {+ // Arrange+ const client = new QueryClient();+ const spy = vi.spyOn(client, "invalidateQueries");+ renderHook(() => useAutoRefreshFilesOnEdit(), {+ wrapper: makeWrapper(client),+ });++ // Act β bash observations are how `git commit` / shell file edits+ // reach the event stream.+ act(() => {+ useEventStore+ .getState()+ .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).+ const invalidatedKeys = spy.mock.calls.map(+ (call) => (call[0] as { queryKey: unknown[] }).queryKey[0],+ );+ expect(invalidatedKeys).toEqual(["file_changes", "file_diff"]);+ },+ );++ it("does not apply the file-editor read-only filter to bash commands", () => {+ // Arrange β `READ_ONLY_COMMANDS` matches editor sub-commands; for bash+ // observations `command` is a whole shell command line and must not be+ // filtered even if it collides with an editor sub-command name.+ const client = new QueryClient();+ const spy = vi.spyOn(client, "invalidateQueries");+ renderHook(() => useAutoRefreshFilesOnEdit(), {+ wrapper: makeWrapper(client),+ });++ // Act+ act(() => {+ useEventStore+ .getState()+ .addEvent(makeObservationEvent("1", "ExecuteBashObservation", "view"));+ });++ // Assert+ expect(spy).toHaveBeenCalled();});it("ignores read-only `view` observations", () => {@@ -91,7 +140,7 @@ describe("useAutoRefreshFilesOnEdit", () => {expect(spy).not.toHaveBeenCalled();});- it("ignores non-file observation kinds", () => {+ it("ignores observation kinds that are neither file-editor nor bash", () => {const client = new QueryClient();const spy = vi.spyOn(client, "invalidateQueries");@@ -102,9 +151,7 @@ describe("useAutoRefreshFilesOnEdit", () => {act(() => {useEventStore.getState()- .addEvent(- makeObservationEvent("1", "ExecuteBashObservation", "ls"),- );+ .addEvent(makeObservationEvent("1", "BrowserObservation", "navigate"));});expect(spy).not.toHaveBeenCalled();diff --git a/src/api/git-service/agent-server-git-service.api.ts b/src/api/git-service/agent-server-git-service.api.tsindex 907e8cab19..a7d168b498 100644--- a/src/api/git-service/agent-server-git-service.api.ts+++ b/src/api/git-service/agent-server-git-service.api.ts@@ -68,9 +68,13 @@ class AgentServerGitService {}));}+ // No `ref`: let the server auto-detect the base (origin branch /+ // merge-base), so changes the agent has already committed still show+ // up. `ref: "HEAD"` would go blank after every `git commit` β and the+ // cloud-proxy branch above already omits `ref`.const changes = await new RemoteWorkspace(getAgentServerClientOptions({ conversationUrl, sessionApiKey }),- ).gitChanges(path, { ref: "HEAD" });+ ).gitChanges(path);if (!Array.isArray(changes)) {throw new Error(@@ -111,9 +115,11 @@ class AgentServerGitService {} as GitChangeDiff;}+ // No `ref` for the same reason as getGitChanges: the base must match+ // the one the change list was computed against.const diff = (await new RemoteWorkspace(getAgentServerClientOptions({ conversationUrl, sessionApiKey }),- ).gitDiff(path, { ref: "HEAD" })) as GitChangeDiff & { diff?: string };+ ).gitDiff(path)) as GitChangeDiff & { diff?: string };return {modified: diff.modified ?? "",diff --git a/src/api/git-service/git-service.api.ts b/src/api/git-service/git-service.api.tsindex 55081eb60e..8208d0f7ee 100644--- a/src/api/git-service/git-service.api.ts+++ b/src/api/git-service/git-service.api.ts@@ -148,7 +148,7 @@ class GitService {);const changes = await new RemoteWorkspace(getAgentServerClientOptions({ workingDir }),- ).gitChanges(workingDir, { ref: "HEAD" });+ ).gitChanges(workingDir);return changes.map((change) => ({path: change.path,@@ -166,7 +166,7 @@ class GitService {): Promise<GitChangeDiff> {const diff = await new RemoteWorkspace(getAgentServerClientOptions(),- ).gitDiff(path, { ref: "HEAD" });+ ).gitDiff(path);return {modified: diff.modified ?? "",diff --git a/src/hooks/use-auto-refresh-files-on-edit.ts b/src/hooks/use-auto-refresh-files-on-edit.tsindex 05d110af50..284a4d037e 100644--- a/src/hooks/use-auto-refresh-files-on-edit.ts+++ b/src/hooks/use-auto-refresh-files-on-edit.ts@@ -15,6 +15,15 @@ const FILE_EDIT_OBSERVATION_KINDS = new Set([// disk. We don't want to invalidate caches for those.const READ_ONLY_COMMANDS = new Set(["view"]);+// Bash observations are how `git commit` / `git push` (and any file edit+// done through the shell) arrive, so they must refresh the Diff view too.+// Legacy agent-servers emit `ExecuteBashObservation`; the current SDK+// emits `TerminalObservation`.+const BASH_OBSERVATION_KINDS = new Set([+ "ExecuteBashObservation",+ "TerminalObservation",+]);+function isFileMutationObservation(event: OHEvent): boolean {// ObservationEvents have `source: "environment"` and an `observation`// field β narrow to that shape without pulling in the whole event union.@@ -26,6 +35,18 @@ function isFileMutationObservation(event: OHEvent): boolean {return true;}+// Note: `READ_ONLY_COMMANDS` intentionally doesn't apply here β for bash+// observations `command` is the whole shell command line, not a+// file-editor sub-command.+function isBashObservation(event: OHEvent): boolean {+ const obs = (event as { observation?: { kind?: string } }).observation;+ return (+ !!obs &&+ typeof obs.kind === "string" &&+ BASH_OBSERVATION_KINDS.has(obs.kind)+ );+}+/*** Watches the conversation event stream and invalidates the workspace file* queries whenever the agent commits a file-editor mutation (create / edit /@@ -33,6 +54,15 @@ function isFileMutationObservation(event: OHEvent): boolean {* diff view in sync with what the agent has actually written to disk,* without requiring the user to click refresh manually.*+ * Bash observations also refresh the git-diff queries (`file_changes` /+ * `file_diff`) β a `git commit` or `git push` changes what the Diff view+ * should display, and shell commands can edit files too. They deliberately+ * do NOT touch the workspace file queries or the workspace mutation+ * counter: bumping the counter reloads canvas iframes, and doing that for+ * every shell command the agent runs would cause constant flicker.+ * Invalidation only refetches actively-mounted queries, so the cost is+ * limited to when the Files tab is open.+ ** Mount this hook inside any component that should drive auto-refresh β* the Files tab is the obvious caller. Multiple mounts are safe because* React Query coalesces overlapping invalidations.@@ -73,7 +103,8 @@ export function useAutoRefreshFilesOnEdit(): void {const processedEventsRef = useRef<WeakSet<OHEvent>>(new WeakSet());useEffect(() => {- const newMutationEvents: OHEvent[] = [];+ let hasNewFileEdits = false;+ let hasNewBashCommands = false;for (const event of events) {const id: string | number | undefined ="id" in event ? event.id : undefined;@@ -88,21 +119,28 @@ export function useAutoRefreshFilesOnEdit(): void {} else {processedEventsRef.current.add(event);}- if (isFileMutationObservation(event)) newMutationEvents.push(event);+ if (isFileMutationObservation(event)) hasNewFileEdits = true;+ else if (isBashObservation(event)) hasNewBashCommands = true;}}- if (newMutationEvents.length === 0) return;+ if (!hasNewFileEdits && !hasNewBashCommands) return;- queryClient.invalidateQueries({ queryKey: ["workspace-files"] });- queryClient.invalidateQueries({ queryKey: ["workspace-file-content"] });+ // Editor and bash mutations both change what the git Diff view shows β+ // including the per-file diff content of an already-expanded file.queryClient.invalidateQueries({ queryKey: ["file_changes"] });- // Force iframes / <img> tags pointing at the static workspace- // fileserver to re-fetch. Without this they happily keep showing the- // stale (browser-cached) bytes even after the agent has rewritten the- // file on disk β e.g. tweaking style.css would silently have no- // visible effect on the rendered index.html until the user reloaded- // the whole canvas.- bumpWorkspaceMutationCounter();+ queryClient.invalidateQueries({ queryKey: ["file_diff"] });++ if (hasNewFileEdits) {+ queryClient.invalidateQueries({ queryKey: ["workspace-files"] });+ queryClient.invalidateQueries({ queryKey: ["workspace-file-content"] });+ // Force iframes / <img> tags pointing at the static workspace+ // fileserver to re-fetch. Without this they happily keep showing the+ // stale (browser-cached) bytes even after the agent has rewritten the+ // file on disk β e.g. tweaking style.css would silently have no+ // visible effect on the rendered index.html until the user reloaded+ // the whole canvas.+ bumpWorkspaceMutationCounter();+ }}, [events, queryClient, bumpWorkspaceMutationCounter]);}