Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(frontend): isolate per-conversation working directories (#90)

Hiep Le1cc616921f1b
diff --git a/.env.sample b/.env.sample
index 445b473ffe..4ef207574a 100644
--- a/.env.sample
+++ b/.env.sample
@@ -6,7 +6,7 @@
VITE_BACKEND_HOST="127.0.0.1:8000" # Host:port used by the Vite dev proxy
VITE_BACKEND_BASE_URL="http://127.0.0.1:8000" # Base URL used by browser-side direct requests
# VITE_SESSION_API_KEY="" # Set to the same value as backend SESSION_API_KEY or OH_SESSION_API_KEYS_0 when auth is enabled
-# VITE_WORKING_DIR="/workspace/project/agent-server-gui" # Repo root used when starting conversations
+# VITE_WORKING_DIR="/workspace/project/agent-server-gui" # Base dir for per-conversation working_dirs. Each conversation's working_dir is <VITE_WORKING_DIR>/<id_hex>. Defaults to <OH_GUI_SAFE_STATE_DIR>/workspaces, which is the sibling of the agent server's <state_dir>/conversations/ persistence dir β€” both share the same <id_hex> per conversation.
# VITE_WORKER_URLS="" # Optional comma-separated worker URLs for the Browser tab
# VITE_ENABLE_BROWSER_TOOLS="true" # Set to false to omit BrowserToolSet from new conversations
@@ -18,3 +18,8 @@ VITE_INSECURE_SKIP_VERIFY="false" # Skip TLS certificate verification for proxie
# Mocking / test helpers
VITE_MOCK_API="false" # Enable/disable API mocking with MSW
# VITE_GITHUB_TOKEN="" # GitHub token for repository access (used in some tests)
+
+# `npm run dev` (scripts/dev-safe.mjs) β€” isolated local backend
+# OH_GUI_SAFE_BACKEND_PORT="18000" # Port the spawned agent-server listens on
+# OH_GUI_SAFE_VSCODE_PORT="18001" # Port forwarded to the embedded VS Code (defaults to backend port + 1)
+# OH_GUI_SAFE_STATE_DIR="$HOME/.openhands/agent-server-gui" # Where conversations, tmux sockets, and bash events are stored
diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.ts
index 2bcf6441f3..fcf6b71f66 100644
--- a/__tests__/api/agent-server-adapter.test.ts
+++ b/__tests__/api/agent-server-adapter.test.ts
@@ -109,6 +109,28 @@ describe("buildStartConversationRequest", () => {
});
});
+ it("uses the supplied conversationId and workingDir overrides", () => {
+ const conversationId = "11111111-1111-4111-8111-111111111111";
+ const workingDir = `/base/${conversationId}`;
+ const payload = buildStartConversationRequest({
+ settings: {
+ ...DEFAULT_SETTINGS,
+ agent_settings: {
+ ...DEFAULT_SETTINGS.agent_settings,
+ llm: { model: "nested-model" },
+ },
+ },
+ conversationId,
+ workingDir,
+ }) as {
+ conversation_id?: string;
+ workspace: { working_dir: string };
+ };
+
+ expect(payload.conversation_id).toBe(conversationId);
+ expect(payload.workspace.working_dir).toBe(workingDir);
+ });
+
it("forwards supported conversation runtime fields from nested settings", () => {
const payload = buildStartConversationRequest({
settings: {
diff --git a/__tests__/api/agent-server-config.test.ts b/__tests__/api/agent-server-config.test.ts
index b582175864..a976a2966b 100644
--- a/__tests__/api/agent-server-config.test.ts
+++ b/__tests__/api/agent-server-config.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import {
AGENT_SERVER_CONFIG_STORAGE_KEY,
DEFAULT_WORKING_DIR,
+ buildConversationWorkingDir,
getAgentServerBaseUrl,
getAgentServerFormDefaults,
getAgentServerSessionApiKey,
@@ -63,6 +64,14 @@ describe("agent server config", () => {
expect(getAgentServerWorkingDir()).toBe(DEFAULT_WORKING_DIR);
});
+ it("nests each conversation's working dir under the configured base using the hex id (matching the server's persistence dir name)", () => {
+ vi.stubEnv("VITE_WORKING_DIR", "/srv/workspaces/");
+
+ expect(
+ buildConversationWorkingDir("4a8dca37-3bf0-48de-a0af-949d711c3d48"),
+ ).toBe("/srv/workspaces/4a8dca373bf048dea0af949d711c3d48");
+ });
+
it("lets saved interface settings override environment defaults", () => {
vi.stubEnv("VITE_BACKEND_BASE_URL", "https://env-agent.example.com");
vi.stubEnv("VITE_SESSION_API_KEY", "env-session-key");
diff --git a/__tests__/api/v1-conversation-service.test.ts b/__tests__/api/v1-conversation-service.test.ts
index 0a66e1b01a..816a668ae0 100644
--- a/__tests__/api/v1-conversation-service.test.ts
+++ b/__tests__/api/v1-conversation-service.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
-import { DEFAULT_WORKING_DIR } from "#/api/agent-server-config";
import V1ConversationService from "#/api/conversation-service/v1-conversation-service.api";
const {
@@ -8,12 +7,14 @@ const {
mockFileUpload,
mockCreateHttpClient,
mockCreateRemoteWorkspace,
+ mockGetSettings,
} = vi.hoisted(() => ({
mockHttpGet: vi.fn(),
mockHttpPost: vi.fn(),
mockFileUpload: vi.fn(),
mockCreateHttpClient: vi.fn(),
mockCreateRemoteWorkspace: vi.fn(),
+ mockGetSettings: vi.fn(),
}));
vi.mock("#/api/typescript-client", () => ({
@@ -27,9 +28,18 @@ vi.mock("#/api/agent-server-config", () => ({
getAgentServerBaseUrl: vi.fn(() => "http://localhost:54928"),
getAgentServerSessionApiKey: vi.fn(() => "test-api-key"),
getAgentServerWorkingDir: vi.fn(() => "/workspace/project/agent-server-gui"),
+ buildConversationWorkingDir: vi.fn(
+ (id: string) => `/state/workspaces/${id.replace(/-/g, "")}`,
+ ),
getConfiguredWorkerUrls: vi.fn(() => []),
}));
+vi.mock("#/api/settings-service/settings-service.api", () => ({
+ default: {
+ getSettings: mockGetSettings,
+ },
+}));
+
describe("V1ConversationService", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -49,27 +59,91 @@ describe("V1ConversationService", () => {
});
describe("readConversationFile", () => {
- it("downloads the default plan path when filePath is not provided", async () => {
+ it("downloads the plan from the conversation's own working_dir when no filePath is provided", async () => {
const encodedPlan = new TextEncoder().encode("# PLAN content").buffer;
- mockHttpGet.mockResolvedValue({ data: encodedPlan });
+ mockHttpGet.mockImplementation((url: string) => {
+ if (url === "/api/conversations") {
+ return Promise.resolve({
+ data: [
+ {
+ id: "conv-123",
+ created_at: "2024-01-01",
+ updated_at: "2024-01-01",
+ workspace: {
+ working_dir: "/workspace/project/agent-server-gui/conv-123",
+ },
+ },
+ ],
+ });
+ }
+ return Promise.resolve({ data: encodedPlan });
+ });
- const content = await V1ConversationService.readConversationFile("conv-123");
+ const content =
+ await V1ConversationService.readConversationFile("conv-123");
expect(content).toBe("# PLAN content");
- expect(mockCreateHttpClient).toHaveBeenCalledTimes(1);
expect(mockHttpGet).toHaveBeenCalledWith(
"/api/file/download",
expect.objectContaining({
- params: { path: `${DEFAULT_WORKING_DIR}/.agents_tmp/PLAN.md` },
+ params: {
+ path: "/workspace/project/agent-server-gui/conv-123/.agents_tmp/PLAN.md",
+ },
responseType: "arrayBuffer",
}),
);
});
});
+ describe("createConversation", () => {
+ it("generates a unique conversation_id and isolated working_dir per call", async () => {
+ mockGetSettings.mockResolvedValue({
+ agent_settings: { llm: { model: "gpt-4o" } },
+ conversation_settings: {},
+ });
+ mockHttpPost.mockResolvedValue({
+ data: {
+ id: "ignored-server-id",
+ created_at: "2024-01-01",
+ updated_at: "2024-01-01",
+ },
+ });
+
+ await V1ConversationService.createConversation();
+ await V1ConversationService.createConversation();
+
+ expect(mockHttpPost).toHaveBeenCalledTimes(2);
+ const [firstCall, secondCall] = mockHttpPost.mock.calls;
+ const firstPayload = firstCall[1] as {
+ conversation_id: string;
+ workspace: { working_dir: string };
+ };
+ const secondPayload = secondCall[1] as {
+ conversation_id: string;
+ workspace: { working_dir: string };
+ };
+
+ expect(firstPayload.conversation_id).toBeTruthy();
+ expect(secondPayload.conversation_id).toBeTruthy();
+ expect(firstPayload.conversation_id).not.toBe(
+ secondPayload.conversation_id,
+ );
+ const firstHex = firstPayload.conversation_id.replace(/-/g, "");
+ const secondHex = secondPayload.conversation_id.replace(/-/g, "");
+ expect(firstPayload.workspace.working_dir).toBe(
+ `/state/workspaces/${firstHex}`,
+ );
+ expect(secondPayload.workspace.working_dir).toBe(
+ `/state/workspaces/${secondHex}`,
+ );
+ });
+ });
+
describe("uploadFile", () => {
it("uses query params for file upload path", async () => {
- const file = new File(["test content"], "test.txt", { type: "text/plain" });
+ const file = new File(["test content"], "test.txt", {
+ type: "text/plain",
+ });
const uploadPath = "/workspace/custom/path.txt";
await V1ConversationService.uploadFile(
@@ -86,7 +160,9 @@ describe("V1ConversationService", () => {
});
it("uses default workspace path when no path provided", async () => {
- const file = new File(["test content"], "myfile.txt", { type: "text/plain" });
+ const file = new File(["test content"], "myfile.txt", {
+ type: "text/plain",
+ });
await V1ConversationService.uploadFile(
"http://localhost:54928/api/conversations/conv-123",
@@ -94,11 +170,16 @@ describe("V1ConversationService", () => {
file,
);
- expect(mockFileUpload).toHaveBeenCalledWith(file, "/workspace/myfile.txt");
+ expect(mockFileUpload).toHaveBeenCalledWith(
+ file,
+ "/workspace/myfile.txt",
+ );
});
it("passes through the selected session key for uploads", async () => {
- const file = new File(["test content"], "test.txt", { type: "text/plain" });
+ const file = new File(["test content"], "test.txt", {
+ type: "text/plain",
+ });
await V1ConversationService.uploadFile(
"http://localhost:54928/api/conversations/conv-123",
diff --git a/__tests__/scripts/dev-safe.test.ts b/__tests__/scripts/dev-safe.test.ts
index 401345f7b7..08d6551fb0 100644
--- a/__tests__/scripts/dev-safe.test.ts
+++ b/__tests__/scripts/dev-safe.test.ts
@@ -1,5 +1,6 @@
import { spawn } from "node:child_process";
import { once } from "node:events";
+import { homedir } from "node:os";
import path from "node:path";
import process from "node:process";
import { setTimeout as delay } from "node:timers/promises";
@@ -16,7 +17,6 @@ const repoRoot = path.resolve(
"../..",
);
-
describe("formatMissingAgentServerGuidance", () => {
it("includes install, PATH, README, and fallback workflow hints", () => {
const guidance = formatMissingAgentServerGuidance(
@@ -48,14 +48,17 @@ describe("buildSafeDevConfig", () => {
expect(config.vscodePort).toBe(18001);
expect(config.backendBaseUrl).toBe("http://127.0.0.1:18000");
expect(config.backendHost).toBe("127.0.0.1:18000");
- expect(config.workingDir).toBe(cwd);
+ expect(config.workingDir).toBe(config.workspacesPath);
expect(config.stateDir).toBe(
- path.resolve(cwd, ".openhands-dev", "safe-dev-18000"),
+ path.join(homedir(), ".openhands", "agent-server-gui"),
);
expect(config.tmuxTmpDir).toBe(path.join(config.stateDir, "tmux"));
expect(config.conversationsPath).toBe(
path.join(config.stateDir, "conversations"),
);
+ expect(config.workspacesPath).toBe(
+ path.join(config.stateDir, "workspaces"),
+ );
expect(config.bashEventsDir).toBe(
path.join(config.stateDir, "bash_events"),
);
diff --git a/package.json b/package.json
index ace700d549..08376a587d 100644
--- a/package.json
+++ b/package.json
@@ -52,7 +52,7 @@
},
"scripts": {
"dev": "npm run dev:safe",
- "dev:safe": "node scripts/dev-safe.mjs",
+ "dev:safe": "node --env-file-if-exists=.env scripts/dev-safe.mjs",
"dev:frontend": "npm run make-i18n && cross-env VITE_MOCK_API=false react-router dev",
"dev:mock": "npm run make-i18n && cross-env VITE_MOCK_API=true react-router dev",
"build": "npm run build:app",
diff --git a/scripts/dev-safe.mjs b/scripts/dev-safe.mjs
index ae94a7d5d3..d7910a84e7 100644
--- a/scripts/dev-safe.mjs
+++ b/scripts/dev-safe.mjs
@@ -1,5 +1,6 @@
import { spawn } from "node:child_process";
import { mkdirSync } from "node:fs";
+import { homedir } from "node:os";
import path from "node:path";
import process from "node:process";
import { setTimeout as delay } from "node:timers/promises";
@@ -10,8 +11,11 @@ const DEFAULT_WAIT_TIMEOUT_MS = 30_000;
function isEnoentError(error) {
return Boolean(
- (error && typeof error === "object" && "code" in error && error.code === "ENOENT") ||
- /ENOENT/.test(String(error)),
+ (error &&
+ typeof error === "object" &&
+ "code" in error &&
+ error.code === "ENOENT") ||
+ /ENOENT/.test(String(error)),
);
}
@@ -52,12 +56,18 @@ function parsePort(value, fallback) {
}
export function buildSafeDevConfig(cwd = process.cwd(), env = process.env) {
- const backendPort = parsePort(env.OH_GUI_SAFE_BACKEND_PORT, DEFAULT_BACKEND_PORT);
+ const backendPort = parsePort(
+ env.OH_GUI_SAFE_BACKEND_PORT,
+ DEFAULT_BACKEND_PORT,
+ );
const vscodePort = parsePort(env.OH_GUI_SAFE_VSCODE_PORT, backendPort + 1);
const stateDir = path.resolve(
cwd,
- env.OH_GUI_SAFE_STATE_DIR || path.join(".openhands-dev", `safe-dev-${backendPort}`),
+ env.OH_GUI_SAFE_STATE_DIR ||
+ path.join(homedir(), ".openhands", "agent-server-gui"),
);
+ const conversationsPath = path.join(stateDir, "conversations");
+ const workspacesPath = path.join(stateDir, "workspaces");
return {
cwd,
@@ -65,11 +75,12 @@ export function buildSafeDevConfig(cwd = process.cwd(), env = process.env) {
vscodePort,
stateDir,
tmuxTmpDir: path.join(stateDir, "tmux"),
- conversationsPath: path.join(stateDir, "conversations"),
+ conversationsPath,
+ workspacesPath,
bashEventsDir: path.join(stateDir, "bash_events"),
backendBaseUrl: `http://127.0.0.1:${backendPort}`,
backendHost: `127.0.0.1:${backendPort}`,
- workingDir: env.VITE_WORKING_DIR || cwd,
+ workingDir: env.VITE_WORKING_DIR || workspacesPath,
};
}
@@ -125,7 +136,9 @@ function spawnProcess(command, args, options) {
if (isEnoentError(error) && command === "agent-server") {
console.error(formatMissingAgentServerGuidance(options?.cwd));
} else if (isEnoentError(error)) {
- console.error(`Failed to start ${command}. Make sure it is installed and on your PATH.`);
+ console.error(
+ `Failed to start ${command}. Make sure it is installed and on your PATH.`,
+ );
} else {
console.error(`Failed to start ${command}:`, error);
}
@@ -141,6 +154,7 @@ async function main() {
config.stateDir,
config.tmuxTmpDir,
config.conversationsPath,
+ config.workspacesPath,
config.bashEventsDir,
]) {
mkdirSync(dir, { recursive: true });
@@ -235,7 +249,10 @@ async function main() {
});
}
-if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
main().catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exit(1);
diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.ts
index 5d71bae3e9..7875c041a1 100644
--- a/src/api/agent-server-adapter.ts
+++ b/src/api/agent-server-adapter.ts
@@ -283,8 +283,10 @@ function buildConfiguredConversationSettings(options: {
query?: string;
conversationInstructions?: string;
plugins?: PluginSpec[];
+ workingDir?: string;
}): SettingsRecord {
- const { settings, query, conversationInstructions, plugins } = options;
+ const { settings, query, conversationInstructions, plugins, workingDir } =
+ options;
const conversationSettings = toRecord(settings.conversation_settings);
const initialMessage = buildInitialMessage(query, conversationInstructions);
@@ -296,7 +298,7 @@ function buildConfiguredConversationSettings(options: {
...conversationSettings,
workspace: {
kind: "LocalWorkspace",
- working_dir: getAgentServerWorkingDir(),
+ working_dir: workingDir ?? getAgentServerWorkingDir(),
},
...(initialMessage ? { initial_message: initialMessage } : {}),
...(plugins?.length
@@ -316,6 +318,8 @@ export function buildStartConversationRequest(options: {
query?: string;
conversationInstructions?: string;
plugins?: PluginSpec[];
+ conversationId?: string;
+ workingDir?: string;
}) {
const agentSettings = buildConfiguredAgentSettings(options.settings);
const agent = createAgentFromSettings(agentSettings);
@@ -334,6 +338,10 @@ export function buildStartConversationRequest(options: {
autotitle: true,
};
+ if (options.conversationId) {
+ payload.conversation_id = options.conversationId;
+ }
+
const securityAnalyzer =
getConversationSecurityAnalyzer(conversationSettings);
if (securityAnalyzer) {
diff --git a/src/api/agent-server-config.ts b/src/api/agent-server-config.ts
index a35b476b43..ef4e6944eb 100644
--- a/src/api/agent-server-config.ts
+++ b/src/api/agent-server-config.ts
@@ -157,6 +157,12 @@ export function getAgentServerWorkingDir(): string {
return DEFAULT_WORKING_DIR;
}
+export function buildConversationWorkingDir(conversationId: string): string {
+ const base = getAgentServerWorkingDir().replace(/\/+$/, "");
+ const hex = conversationId.replace(/-/g, "");
+ return `${base}/${hex}`;
+}
+
export function getConfiguredWorkerUrls(): string[] {
const raw = import.meta.env.VITE_WORKER_URLS?.trim();
if (!raw) return [];
diff --git a/src/api/conversation-service/conversation-service.api.ts b/src/api/conversation-service/conversation-service.api.ts
index 8ac7af8ca0..ab3dfd1918 100644
--- a/src/api/conversation-service/conversation-service.api.ts
+++ b/src/api/conversation-service/conversation-service.api.ts
@@ -40,14 +40,19 @@ class ConversationService {
}
static async getVSCodeUrl(
- _conversationId: string,
+ conversationId: string,
): Promise<GetVSCodeUrlResponse> {
+ const workspaceDir =
+ this.currentConversation?.id === conversationId
+ ? (this.currentConversation?.workspace?.working_dir ??
+ getAgentServerWorkingDir())
+ : getAgentServerWorkingDir();
const vscode_url = await createVSCodeClient(
this.getClientOverrides(),
).getUrl({
baseUrl:
typeof window !== "undefined" ? window.location.origin : undefined,
- workspaceDir: getAgentServerWorkingDir(),
+ workspaceDir,
});
return { vscode_url };
diff --git a/src/api/conversation-service/v1-conversation-service.api.ts b/src/api/conversation-service/v1-conversation-service.api.ts
index 6c6fba355a..0eac4b1a98 100644
--- a/src/api/conversation-service/v1-conversation-service.api.ts
+++ b/src/api/conversation-service/v1-conversation-service.api.ts
@@ -1,7 +1,7 @@
import { Provider } from "#/types/settings";
import { SuggestedTask } from "#/utils/types";
import {
- DEFAULT_WORKING_DIR,
+ buildConversationWorkingDir,
getAgentServerBaseUrl,
getAgentServerWorkingDir,
} from "../agent-server-config";
@@ -56,11 +56,15 @@ class V1ConversationService {
plugins?: PluginSpec[],
): Promise<V1AppConversationStartTask> {
const settings = await SettingsService.getSettings();
+ const conversationId = crypto.randomUUID();
+ const workingDir = buildConversationWorkingDir(conversationId);
const payload = buildStartConversationRequest({
settings,
query: initialUserMsg,
conversationInstructions,
plugins,
+ conversationId,
+ workingDir,
});
const response = await createHttpClient().post<DirectConversationInfo>(
@@ -100,19 +104,30 @@ class V1ConversationService {
}
static async getVSCodeUrl(
- _conversationId: string,
+ conversationId: string,
_conversationUrl: string | null | undefined,
sessionApiKey?: string | null,
): Promise<GetVSCodeUrlResponse> {
+ const workspaceDir =
+ await this.resolveConversationWorkingDir(conversationId);
const vscode_url = await createVSCodeClient({ sessionApiKey }).getUrl({
baseUrl:
typeof window !== "undefined" ? window.location.origin : undefined,
- workspaceDir: getAgentServerWorkingDir(),
+ workspaceDir,
});
return { vscode_url };
}
+ static async resolveConversationWorkingDir(
+ conversationId: string,
+ ): Promise<string> {
+ const [conversation] = await this.batchGetAppConversations([
+ conversationId,
+ ]);
+ return conversation?.workspace?.working_dir ?? getAgentServerWorkingDir();
+ }
+
static async pauseConversation(
conversationId: string,
_conversationUrl: string | null | undefined,
@@ -199,10 +214,15 @@ class V1ConversationService {
}
static async readConversationFile(
- _conversationId: string,
- filePath: string = `${DEFAULT_WORKING_DIR}/.agents_tmp/PLAN.md`,
+ conversationId: string,
+ filePath?: string,
): Promise<string> {
- return downloadTextFile(filePath);
+ if (filePath) {
+ return downloadTextFile(filePath);
+ }
+
+ const workingDir = await this.resolveConversationWorkingDir(conversationId);
+ return downloadTextFile(`${workingDir}/.agents_tmp/PLAN.md`);
}
static async downloadConversation(conversationId: string): Promise<Blob> {
diff --git a/src/api/git-service/git-service.api.ts b/src/api/git-service/git-service.api.ts
index 8656de694c..3a38995b56 100644
--- a/src/api/git-service/git-service.api.ts
+++ b/src/api/git-service/git-service.api.ts
@@ -1,6 +1,6 @@
import { RepositoryPage, BranchPage, InstallationPage } from "#/types/git";
import { GitChange, GitChangeDiff } from "../open-hands.types";
-import { getAgentServerWorkingDir } from "../agent-server-config";
+import V1ConversationService from "../conversation-service/v1-conversation-service.api";
import { createRemoteWorkspace } from "../typescript-client";
import { mapAnyGitStatusToV0Status } from "#/utils/git-status-mapper";
@@ -68,9 +68,11 @@ class GitService {
return { items: [], next_page_id: null };
}
- static async getGitChanges(_conversationId: string): Promise<GitChange[]> {
- const changes = await createRemoteWorkspace().gitChanges(
- getAgentServerWorkingDir(),
+ static async getGitChanges(conversationId: string): Promise<GitChange[]> {
+ const workingDir =
+ await V1ConversationService.resolveConversationWorkingDir(conversationId);
+ const changes = await createRemoteWorkspace({ workingDir }).gitChanges(
+ workingDir,
);
return changes.map((change) => ({