π OpenHands: AI-Driven Development
test: strengthen workspace path resolution (#17356)
aivong-openhands013fa501406d
diff --git a/__tests__/api/workspace-upload-path.test.ts b/__tests__/api/workspace-upload-path.test.tsindex b1797d82e9..1f1cc42298 100644--- a/__tests__/api/workspace-upload-path.test.ts+++ b/__tests__/api/workspace-upload-path.test.ts@@ -6,6 +6,11 @@ import {resolveConversationUploadWorkingDir,} from "#/api/workspace-upload-path";import { clearAgentServerHomeDirCache } from "#/api/agent-server-home";+import { DEFAULT_WORKING_DIR } from "#/api/agent-server-config";+import {+ removeStoredConversationMetadata,+ setStoredConversationMetadata,+} from "#/api/conversation-metadata-store";const mockGetHome = vi.fn();@@ -95,6 +100,19 @@ describe("workspace-upload-path", () => {expect(getSafeUploadFileName("../../evil.txt")).toBe("evil.txt");});+ it("ignores trailing separators when choosing the upload file name", () => {+ expect(getSafeUploadFileName("folder/file.txt//")).toBe("file.txt");+ });++ it.each(["", ".", "..", "path/to/.."])(+ "rejects invalid upload file name %j",+ async (fileName) => {+ await expect(+ buildWorkspaceUploadPath(fileName, "/workspace/project"),+ ).rejects.toThrow("Invalid file name");+ },+ );+// @spec WUP-001 β buildWorkspaceUploadPath uses the resolver and a safe leaf.it("builds an absolute upload path from a relative working dir", async () => {const upload = await buildWorkspaceUploadPath("a.txt", "workspace/project");@@ -120,12 +138,78 @@ describe("workspace-upload-path", () => {it("prefers the active conversation workspace when ids match", async () => {const dir = await resolveConversationUploadWorkingDir("conv-uuid", {id: "conv-uuid",- workspace: { working_dir: "/workspace/project/custom" },+ workspace: { working_dir: " /workspace/project/custom " },} as never);expect(dir).toBe("/workspace/project/custom");});+ it.each([undefined, " "])(+ "uses the configured working directory when the active workspace is %j",+ async (workingDir) => {+ const dir = await resolveConversationUploadWorkingDir(+ "named-conversation",+ {+ id: "named-conversation",+ workspace:+ workingDir === undefined ? {} : { working_dir: workingDir },+ } as never,+ );++ expect(dir).toBe(DEFAULT_WORKING_DIR);+ },+ );++ it("uses the configured working directory when the active conversation has no workspace", async () => {+ const dir = await resolveConversationUploadWorkingDir(+ "named-conversation",+ { id: "named-conversation" } as never,+ );++ expect(dir).toBe(DEFAULT_WORKING_DIR);+ });++ it("uses the stored workspace when the active conversation does not match", async () => {+ const conversationId = "stored-conversation";+ setStoredConversationMetadata(conversationId, {+ selected_repository: null,+ selected_branch: null,+ git_provider: null,+ selected_workspace: " /workspace/project/stored ",+ });++ try {+ const dir = await resolveConversationUploadWorkingDir(conversationId, {+ id: "different-conversation",+ workspace: { working_dir: "/workspace/project/active" },+ } as never);++ expect(dir).toBe("/workspace/project/stored");+ } finally {+ removeStoredConversationMetadata(conversationId);+ }+ });++ it.each([undefined, " "])(+ "uses the configured working directory when the stored workspace is %j",+ async (selectedWorkspace) => {+ const conversationId = "stored-without-workspace";+ setStoredConversationMetadata(conversationId, {+ selected_repository: null,+ selected_branch: null,+ git_provider: null,+ selected_workspace: selectedWorkspace,+ });++ try {+ const dir = await resolveConversationUploadWorkingDir(conversationId);+ expect(dir).toBe(DEFAULT_WORKING_DIR);+ } finally {+ removeStoredConversationMetadata(conversationId);+ }+ },+ );+it("resolves per-conversation dirs for UUID ids", async () => {const dir = await resolveConversationUploadWorkingDir("550e8400-e29b-41d4-a716-446655440000",@@ -134,4 +218,10 @@ describe("workspace-upload-path", () => {expect(dir).toBe("/workspace/project/550e8400e29b41d4a716446655440000");});++ it("uses the configured working directory for non-UUID conversations", async () => {+ const dir = await resolveConversationUploadWorkingDir("named-conversation");++ expect(dir).toBe(DEFAULT_WORKING_DIR);+ });});diff --git a/src/api/workspace-path-resolution.test.ts b/src/api/workspace-path-resolution.test.tsnew file mode 100644index 0000000000..36082aa6bb--- /dev/null+++ b/src/api/workspace-path-resolution.test.ts@@ -0,0 +1,189 @@+import { describe, expect, it, vi } from "vitest";++const {+ fileClientConstructorMock,+ getAgentServerClientOptionsMock,+ getHomeMock,+} = vi.hoisted(() => ({+ fileClientConstructorMock: vi.fn(),+ getAgentServerClientOptionsMock: vi.fn(),+ getHomeMock: vi.fn(),+}));++vi.mock("@openhands/typescript-client/clients", () => ({+ FileClient: class {+ constructor(options: unknown) {+ fileClientConstructorMock(options);+ }++ getHome() {+ return getHomeMock();+ }+ },+}));++vi.mock("./agent-server-client-options", () => ({+ getAgentServerClientOptions: getAgentServerClientOptionsMock,+}));++import {+ clearAgentServerHomeDirCache,+ getAgentServerHomeDir,+ resolveAbsoluteAgentServerPath,+} from "./agent-server-home";++const defaultClientOptions = {+ host: "https://agent.example.com",+ apiKey: "agent-key",+ workingDir: "workspace/project",+};++function arrangeHomeLookup(): void {+ clearAgentServerHomeDirCache();+ vi.resetAllMocks();+ getAgentServerClientOptionsMock.mockReturnValue(defaultClientOptions);+}++describe("agent-server workspace path resolution", () => {+ it("looks up the server home with the resolved client options and normalizes its separator", async () => {+ arrangeHomeLookup();+ getHomeMock.mockResolvedValue({ home: "/Users/alice///" });+ const overrides = {+ conversationUrl: "wss://runtime.example.com/conversations/1",+ sessionApiKey: "session-key",+ };++ await expect(getAgentServerHomeDir(overrides)).resolves.toBe(+ "/Users/alice",+ );++ expect(getAgentServerClientOptionsMock).toHaveBeenCalledWith(overrides);+ expect(fileClientConstructorMock).toHaveBeenCalledWith(+ defaultClientOptions,+ );+ expect(getHomeMock).toHaveBeenCalledOnce();+ });++ it("shares one in-flight home lookup between callers for the same host", async () => {+ arrangeHomeLookup();+ getHomeMock.mockResolvedValue({ home: "/home/agent" });++ await expect(+ Promise.all([getAgentServerHomeDir(), getAgentServerHomeDir()]),+ ).resolves.toEqual(["/home/agent", "/home/agent"]);++ expect(getHomeMock).toHaveBeenCalledOnce();+ });++ it("caches home directories independently for each agent-server host", async () => {+ arrangeHomeLookup();+ getAgentServerClientOptionsMock.mockImplementation(+ (overrides: { host?: string } = {}) => ({+ ...defaultClientOptions,+ host: overrides.host ?? defaultClientOptions.host,+ }),+ );+ getHomeMock+ .mockResolvedValueOnce({ home: "/home/first" })+ .mockResolvedValueOnce({ home: "/home/second" });++ await expect(+ Promise.all([+ getAgentServerHomeDir({ host: "https://first.example.com" }),+ getAgentServerHomeDir({ host: "https://second.example.com" }),+ ]),+ ).resolves.toEqual(["/home/first", "/home/second"]);+ await expect(+ getAgentServerHomeDir({ host: "https://first.example.com" }),+ ).resolves.toBe("/home/first");++ expect(getHomeMock).toHaveBeenCalledTimes(2);+ });++ it("retries a home lookup after a transient failure", async () => {+ arrangeHomeLookup();+ getHomeMock+ .mockRejectedValueOnce(new Error("agent server unavailable"))+ .mockResolvedValueOnce({ home: "/home/recovered" });++ await expect(getAgentServerHomeDir()).rejects.toThrow(+ "agent server unavailable",+ );+ await expect(getAgentServerHomeDir()).resolves.toBe("/home/recovered");++ expect(getHomeMock).toHaveBeenCalledTimes(2);+ });++ it.each([undefined, null, "", 0, 42])(+ "rejects an invalid home directory response (%s)",+ async (home) => {+ arrangeHomeLookup();+ getHomeMock.mockResolvedValue({ home });++ await expect(getAgentServerHomeDir()).rejects.toThrow(+ "Agent server returned an empty home directory",+ );+ },+ );++ it("clears a successful cached lookup on request", async () => {+ arrangeHomeLookup();+ getHomeMock+ .mockResolvedValueOnce({ home: "/home/first" })+ .mockResolvedValueOnce({ home: "/home/refreshed" });++ await expect(getAgentServerHomeDir()).resolves.toBe("/home/first");+ clearAgentServerHomeDirCache();+ await expect(getAgentServerHomeDir()).resolves.toBe("/home/refreshed");++ expect(getHomeMock).toHaveBeenCalledTimes(2);+ });++ it.each([+ ["/workspace/project///", "/workspace/project"],+ ["C:\\workspace\\project\\", "C:\\workspace\\project"],+ ["D:/workspace/project///", "D:/workspace/project"],+ ["\\\\server\\share\\", "\\\\server\\share"],+ ])(+ "keeps the absolute path %s without a home lookup",+ async (path, expected) => {+ arrangeHomeLookup();++ await expect(resolveAbsoluteAgentServerPath(path)).resolves.toBe(+ expected,+ );++ expect(getAgentServerClientOptionsMock).not.toHaveBeenCalled();+ expect(getHomeMock).not.toHaveBeenCalled();+ },+ );++ it.each(["", "/", "\\", "///", "\\\\"])(+ "resolves an empty path (%s) to the server home",+ async (path) => {+ arrangeHomeLookup();+ getHomeMock.mockResolvedValue({ home: "/home/agent/" });++ await expect(resolveAbsoluteAgentServerPath(path)).resolves.toBe(+ "/home/agent",+ );++ expect(getHomeMock).toHaveBeenCalledOnce();+ },+ );++ it("anchors a relative workspace below the server home", async () => {+ arrangeHomeLookup();+ getHomeMock.mockResolvedValue({ home: "/Users/alice///" });+ const overrides = {+ host: "https://runtime.example.com/",+ sessionApiKey: "session-key",+ };++ await expect(+ resolveAbsoluteAgentServerPath("workspace/project///", overrides),+ ).resolves.toBe("/Users/alice/workspace/project");++ expect(getAgentServerClientOptionsMock).toHaveBeenCalledWith(overrides);+ });+});