π OpenHands: AI-Driven Development
fix(canvas): persist workspace grouping via server-side conversation tags (#18722)
Vasco Schiavo2c7193ed2a42
diff --git a/.pr/17386-workspace-tags/after-full.png b/.pr/17386-workspace-tags/after-full.pngnew file mode 100644index 0000000000..ded59da0cfBinary files /dev/null and b/.pr/17386-workspace-tags/after-full.png differdiff --git a/.pr/17386-workspace-tags/after-sidebar.png b/.pr/17386-workspace-tags/after-sidebar.pngnew file mode 100644index 0000000000..7f4c1b9580Binary files /dev/null and b/.pr/17386-workspace-tags/after-sidebar.png differdiff --git a/.pr/17386-workspace-tags/before-full.png b/.pr/17386-workspace-tags/before-full.pngnew file mode 100644index 0000000000..1f4eb7a56cBinary files /dev/null and b/.pr/17386-workspace-tags/before-full.png differdiff --git a/.pr/17386-workspace-tags/before-sidebar.png b/.pr/17386-workspace-tags/before-sidebar.pngnew file mode 100644index 0000000000..b402877f04Binary files /dev/null and b/.pr/17386-workspace-tags/before-sidebar.png differdiff --git a/.pr/17386-workspace-tags/evidence.mjs b/.pr/17386-workspace-tags/evidence.mjsnew file mode 100644index 0000000000..a4b5d3b88b--- /dev/null+++ b/.pr/17386-workspace-tags/evidence.mjs@@ -0,0 +1,149 @@+#!/usr/bin/env node+/**+ * Headless running-Canvas evidence for #17386 (workspace grouping persisted+ * via the server-side `workspace` conversation tag). No agent-server or LLM:+ * the frontend runs against its MSW mock API.+ *+ * Usage (from the repo root):+ * VITE_MOCK_API=true npx react-router dev --port 5199 --strictPort+ * node .pr/17386-workspace-tags/evidence.mjs --label after # this branch+ * node .pr/17386-workspace-tags/evidence.mjs --label before # main's src/+ *+ * Scenario (identical for both labels):+ * - local backend selected, sidebar in "grouped" mode+ * - workspace `/workspace/project` registered on the (mock) agent-server+ * - conversation "My New Project" carries the server tag+ * `workspace=/workspace/project`; the three `/workspace/project`+ * fixtures are legacy local_repo conversations with no tag+ * - `openhands-agent-server-conversation-metadata` is empty, i.e. another+ * browser / device / cleared site data+ * main groups everything under "No workspace"; the branch regroups the tagged+ * conversation via the tag and the legacy ones via their working_dir.+ */+import { chromium } from "../../node_modules/playwright/index.mjs";++const argv = process.argv.slice(2);+const arg = (name, fallback) => {+ const i = argv.indexOf(`--${name}`);+ return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;+};+const label = arg("label", "after");+const base = arg("url", "http://localhost:5199");+const outDir = arg("out", new URL(".", import.meta.url).pathname);++const WORKSPACE = {+ id: "project",+ name: "project",+ path: "/workspace/project",+};++const browser = await chromium.launch();+const context = await browser.newContext({+ viewport: { width: 1440, height: 900 },+ deviceScaleFactor: 2,+});++await context.addInitScript(() => {+ const backend = {+ id: "local-1",+ name: "Local agent-server",+ host: location.origin,+ apiKey: "mock-key",+ kind: "local",+ };+ localStorage.setItem("openhands-onboarded", "1");+ localStorage.setItem(+ "openhands-sidebar-onboarding-checklist-dismissed",+ "true",+ );+ localStorage.setItem("openhands-backends", JSON.stringify([backend]));+ // Grouped sidebar: the mode that shows workspace folders.+ localStorage.setItem(+ "conversation-panel-preferences",+ JSON.stringify({ state: { organizeMode: "grouped" }, version: 0 }),+ );+ const selection = JSON.stringify({ backendId: backend.id, orgId: null });+ localStorage.setItem("openhands-active-backend", selection);+ sessionStorage.setItem("openhands-active-backend", selection);+ // The state under test: no client-side conversation metadata cache.+ localStorage.removeItem("openhands-agent-server-conversation-metadata");+ // The mock API has no event socket; keep the client from retrying.+ class NeverOpenSocket {+ constructor() {+ this.readyState = 0;+ }+ send() {}+ close() {}+ addEventListener() {}+ removeEventListener() {}+ }+ window.WebSocket = NeverOpenSocket;+});++const page = await context.newPage();+await page.goto(`${base}/`, { waitUntil: "domcontentloaded" });+await page.waitForSelector('[data-testid="conversation-panel"]', {+ timeout: 60_000,+});+// The analytics consent dialog opens once the backend settings resolve.+const confirm = page.getByRole("button", { name: "Confirm preferences" });+await confirm.waitFor({ state: "visible", timeout: 15_000 }).catch(() => {});+if (await confirm.isVisible().catch(() => false)) {+ await confirm.click();+ await confirm.waitFor({ state: "hidden", timeout: 10_000 }).catch(() => {});+}++await page.evaluate(async (workspace) => {+ const json = { "content-type": "application/json" };+ await fetch("/api/workspaces", {+ method: "POST",+ headers: json,+ body: JSON.stringify({ workspaces: [workspace] }),+ });+ await fetch("/api/conversations/1", {+ method: "PATCH",+ headers: json,+ body: JSON.stringify({ tags: { workspace: workspace.path } }),+ });+ const prefs =+ await import("/src/stores/conversation-panel-preferences-store.ts");+ prefs.useConversationPanelPreferencesStore+ .getState()+ .setOrganizeMode("grouped");+ const { queryClient } = await import("/src/query-client-config.ts");+ await queryClient.invalidateQueries();+}, WORKSPACE);++// Conversation rows always render; folders only exist in grouped mode when+// there is more than one group, so wait for rows and give folders a moment.+await page.waitForSelector('a[href^="/conversations/"]', { timeout: 30_000 });+await page+ .waitForSelector('[data-testid^="thread-folder-"]', { timeout: 45_000 })+ .catch(() => {});+await page.waitForTimeout(2_000);+const organizeMode = await page.evaluate(async () => {+ const prefs =+ await import("/src/stores/conversation-panel-preferences-store.ts");+ return prefs.useConversationPanelPreferencesStore.getState().organizeMode;+});+console.log(JSON.stringify({ label, organizeMode }));++const folders = await page.$$eval('[data-testid^="thread-folder-"]', (els) =>+ els+ .filter((el) => el.tagName === "SECTION")+ .map((el) => ({+ id: el.getAttribute("data-testid"),+ title: el+ .querySelector("h2, h3, [id^='thread-folder-']")+ ?.textContent?.trim(),+ conversations: el.querySelectorAll('a[href^="/conversations/"]').length,+ })),+);+console.log(JSON.stringify({ label, folders }, null, 2));++await page.screenshot({ path: `${outDir}/${label}-full.png` });+await page.screenshot({+ path: `${outDir}/${label}-sidebar.png`,+ clip: { x: 0, y: 0, width: 360, height: 900 },+});+await browser.close();diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.tsindex 381682bbc2..dda338dcca 100644--- a/__tests__/api/agent-server-adapter.test.ts+++ b/__tests__/api/agent-server-adapter.test.ts@@ -9,6 +9,8 @@ import {ACP_SERVER_TAG_KEY,AGENT_CANVAS_SOURCE,CLIENT_SOURCE_TAG_KEY,+ WORKSPACE_TAG_KEY,+ buildWorkspaceTags,buildRuntimeServicesSystemSuffix,buildStartConversationRequest,buildStartConversationRequestWithEncryptedSettings,@@ -605,6 +607,27 @@ describe("getDefaultConversationTitle", () => {});});+describe("buildWorkspaceTags (#17386)", () => {+ it("emits the workspace tag with a normalized path", () => {+ expect(buildWorkspaceTags("/Users/jane/projects/openhands/")).toEqual({+ [WORKSPACE_TAG_KEY]: "/Users/jane/projects/openhands",+ });+ });++ it("returns an empty object for null/empty/whitespace input", () => {+ expect(buildWorkspaceTags(null)).toEqual({});+ expect(buildWorkspaceTags(undefined)).toEqual({});+ expect(buildWorkspaceTags(" ")).toEqual({});+ });++ it("only ever emits keys the agent-server accepts (`^[a-z0-9]+$`)", () => {+ const tags = buildWorkspaceTags("/Users/jane/projects/openhands");+ for (const key of Object.keys(tags)) {+ expect(key).toMatch(/^[a-z0-9]+$/);+ }+ });+});+describe("toAppConversation", () => {const baseInfo: DirectConversationInfo = {id: "372eb-1234-5678-9abc",@@ -612,6 +635,49 @@ describe("toAppConversation", () => {updated_at: "2026-01-01T00:00:00Z",};+ describe("server-side workspace tag fallback (#17386)", () => {+ afterEach(() => {+ removeStoredConversationMetadata(baseInfo.id);+ });++ it("uses a key the agent-server will accept (lowercase alphanumeric)", () => {+ // The agent-server rejects tag keys that are not `^[a-z0-9]+$` (SDK+ // conversation/types.py), which would 422 the create request.+ expect(WORKSPACE_TAG_KEY).toMatch(/^[a-z0-9]+$/);+ });++ it("hydrates selected_workspace from the tag when localStorage has none", () => {+ const result = toAppConversation({+ ...baseInfo,+ tags: { [WORKSPACE_TAG_KEY]: "/Users/jane/projects/openhands" },+ });++ expect(result.selected_workspace).toBe("/Users/jane/projects/openhands");+ });++ it("prefers stored metadata over the tag (warm cache for the creating client)", () => {+ setStoredConversationMetadata(baseInfo.id, {+ selected_repository: null,+ selected_branch: null,+ git_provider: null,+ selected_workspace: "/Users/jane/projects/local-fork",+ });++ const result = toAppConversation({+ ...baseInfo,+ tags: { [WORKSPACE_TAG_KEY]: "/Users/jane/projects/openhands" },+ });++ expect(result.selected_workspace).toBe("/Users/jane/projects/local-fork");+ });++ it("stays null when neither localStorage nor the tag has a workspace", () => {+ const result = toAppConversation({ ...baseInfo, tags: {} });++ expect(result.selected_workspace).toBeNull();+ });+ });+it("uses the archived status for a missing runtime that cannot resume", () => {const result = toAppConversation({...baseInfo,diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.tsindex 90309ac0fe..cc4f79f100 100644--- a/__tests__/api/agent-server-conversation-service.test.ts+++ b/__tests__/api/agent-server-conversation-service.test.ts@@ -8,6 +8,7 @@ import {import { http, HttpResponse } from "msw";import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";import { server } from "#/mocks/node";+import { WORKSPACE_TAG_KEY } from "#/api/agent-server-adapter";import {__resetActiveStoreForTests,setActiveSelection,@@ -845,6 +846,68 @@ describe("AgentServerConversationService", () => {expect(payload.worktree).toBe(false);});+ it("stamps the selected workspace as a server-valid conversation tag (#17386)", async () => {+ mockGetSettings.mockResolvedValue({+ agent_settings: { llm: { model: "gpt-4o" } },+ conversation_settings: {},+ });+ mockGetSettingsForConversation.mockResolvedValue({+ agentSettings: { llm: { model: "gpt-4o" } },+ conversationSettings: {},+ secretsEncrypted: true,+ });+ mockHttpPost.mockResolvedValue({+ data: {+ id: "ignored-server-id",+ created_at: "2024-01-01",+ updated_at: "2024-01-01",+ },+ });++ await AgentServerConversationService.createConversation({+ agentProfileId: "profile-1",+ workingDirOverride: "/Users/jane/projects/foo/",+ });++ const [payloadCall] = mockHttpPost.mock.calls;+ const payload = payloadCall[1] as { tags?: Record<string, string> };+ // Normalized path, under a key the agent-server's `^[a-z0-9]+$`+ // validator accepts (an underscored key would 422 the create).+ expect(payload.tags).toMatchObject({+ [WORKSPACE_TAG_KEY]: "/Users/jane/projects/foo",+ });+ for (const key of Object.keys(payload.tags ?? {})) {+ expect(key).toMatch(/^[a-z0-9]+$/);+ }+ });++ it("sends no workspace tag when no workspace was selected (#17386)", async () => {+ mockGetSettings.mockResolvedValue({+ agent_settings: { llm: { model: "gpt-4o" } },+ conversation_settings: {},+ });+ mockGetSettingsForConversation.mockResolvedValue({+ agentSettings: { llm: { model: "gpt-4o" } },+ conversationSettings: {},+ secretsEncrypted: true,+ });+ mockHttpPost.mockResolvedValue({+ data: {+ id: "ignored-server-id",+ created_at: "2024-01-01",+ updated_at: "2024-01-01",+ },+ });++ await AgentServerConversationService.createConversation({+ agentProfileId: "profile-1",+ });++ const [payloadCall] = mockHttpPost.mock.calls;+ const payload = payloadCall[1] as { tags?: Record<string, string> };+ expect(payload.tags?.[WORKSPACE_TAG_KEY]).toBeUndefined();+ });+it("honors an explicit new-worktree mode for a selected workspace", async () => {mockGetSettings.mockResolvedValue({agent_settings: { llm: { model: "gpt-4o" } },diff --git a/__tests__/components/features/conversation-panel/conversation-panel-list-helpers.test.ts b/__tests__/components/features/conversation-panel/conversation-panel-list-helpers.test.tsindex e8dfc40a95..5e98b0e23f 100644--- a/__tests__/components/features/conversation-panel/conversation-panel-list-helpers.test.ts+++ b/__tests__/components/features/conversation-panel/conversation-panel-list-helpers.test.ts@@ -831,6 +831,54 @@ describe("conversation-panel-list-helpers", () => {).map((c) => c.id),).toEqual(["untagged", "slack", "alice", "both"]);});++ it("recovers a legacy local_repo conversation by matching working_dir to a known workspace (#17386)", () => {+ // No selected_workspace (localStorage was cleared / another browser), but+ // the runtime working_dir equals a registered workspace folder.+ const legacy: AppConversation = {+ ...base,+ id: "legacy-local-repo",+ title: "legacy",+ selected_workspace: null,+ workspace: { working_dir: "/Users/jane/projects/openhands/" },+ };+ // A worktree conversation's working_dir is unique and matches nothing, so+ // it stays under "No workspace" until its server tag regroups it.+ const worktree: AppConversation = {+ ...base,+ id: "legacy-worktree",+ title: "worktree",+ selected_workspace: null,+ workspace: { working_dir: "/Users/jane/projects/openhands/wt-abc" },+ };++ const groups = groupConversations(+ [legacy, worktree],+ "local",+ "updated",+ { emptyWorkspace: "No workspace", emptyRepository: "No repository" },+ [+ {+ id: "ws1",+ name: "openhands",+ path: "/Users/jane/projects/openhands",+ },+ ],+ );++ const byId = new Map(groups.map((g) => [g.id, g]));+ expect(byId.get("ws:/Users/jane/projects/openhands")?.label).toBe(+ "openhands",+ );+ expect(+ byId+ .get("ws:/Users/jane/projects/openhands")+ ?.conversations.map((c) => c.id),+ ).toEqual(["legacy-local-repo"]);+ expect(+ byId.get("__none_workspace")?.conversations.map((c) => c.id),+ ).toEqual(["legacy-worktree"]);+ });});describe("partitionByCutoff", () => {diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.tsindex 85927be874..0fba3a9174 100644--- a/src/api/agent-server-adapter.ts+++ b/src/api/agent-server-adapter.ts@@ -425,7 +425,11 @@ export function toAppConversation(selected_repository: metadata?.selected_repository ?? null,selected_branch: metadata?.selected_branch ?? null,git_provider: metadata?.git_provider ?? null,- selected_workspace: metadata?.selected_workspace ?? null,+ // Prefer the creating client's localStorage metadata; fall back to the+ // server-side workspace tag so local sidebar grouping survives on another+ // browser, device, or after cleared site data (#17386).+ selected_workspace:+ metadata?.selected_workspace ?? info.tags?.[WORKSPACE_TAG_KEY] ?? null,active_profile: metadata?.active_profile ?? null,title: info.title?.trim()? info.title@@ -537,6 +541,32 @@ export const ACP_SERVER_TAG_KEY = "acpserver";export const CLIENT_SOURCE_TAG_KEY = "clientsource";export const AGENT_CANVAS_SOURCE = "agentcanvas";+/**+ * Server-side conversation tag that persists the home-page workspace selection+ * on the agent-server, so local sidebar grouping survives a different browser,+ * device, or cleared localStorage (the localStorage metadata store stays the+ * warm cache for the creating client). See #17386.+ *+ * The agent-server validates tag keys against `^[a-z0-9]+$` (SDK+ * `conversation/types.py`), so the key must stay lowercase alphanumeric with+ * no separators β an underscored key like `selected_workspace` would make the+ * create request 422. It is already in {@link RESERVED_CONVERSATION_TAG_KEYS},+ * so it never appears as an editable chip.+ */+export const WORKSPACE_TAG_KEY = "workspace";++/**+ * Build the workspace tag to stamp at conversation creation, normalizing the+ * path and returning an empty object when there is nothing to persist (so the+ * caller can skip adding a `tags` payload entirely).+ */+export function buildWorkspaceTags(+ selectedWorkspace?: string | null,+): Record<string, string> {+ const workspace = selectedWorkspace?.trim().replace(/\/+$/, "");+ return workspace ? { [WORKSPACE_TAG_KEY]: workspace } : {};+}+export const AUTOMATION_TRIGGER_TAG_KEY = "automationtrigger";export const AUTOMATION_ID_TAG_KEY = "automationid";export const AUTOMATION_NAME_TAG_KEY = "automationname";diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.tsindex 1237717681..17968bd964 100644--- a/src/api/conversation-service/agent-server-conversation-service.api.ts+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts@@ -44,6 +44,7 @@ import {buildRouterAtStartSystemSuffix,buildStartConversationRequestWithEncryptedSettings,buildStartPlanningConversationRequestWithEncryptedSettings,+ buildWorkspaceTags,emptyHooksResponse,fetchBackendExecutionRuntime,getDefaultConversationTitle,@@ -641,6 +642,19 @@ class AgentServerConversationService {titleLlmProfile,});+ // Persist the selected workspace as a server-side conversation tag so local+ // sidebar grouping survives on another browser, device, or after cleared+ // localStorage (#17386). localStorage below stays the warm cache for the+ // creating client.+ const workspaceTags = buildWorkspaceTags(workingDirOverride);+ if (Object.keys(workspaceTags).length > 0) {+ const existingTags =+ payload.tags && typeof payload.tags === "object"+ ? (payload.tags as Record<string, string>)+ : {};+ payload.tags = { ...existingTags, ...workspaceTags };+ }+const telemetryDistinctId = await getTelemetryDistinctId();const data = await new ConversationClient(getAgentServerClientOptions({ timeout: CREATE_CONVERSATION_TIMEOUT_MS }),diff --git a/src/components/features/conversation-panel/conversation-panel-list-helpers.ts b/src/components/features/conversation-panel/conversation-panel-list-helpers.tsindex 9bad00677f..45d4c96bdc 100644--- a/src/components/features/conversation-panel/conversation-panel-list-helpers.ts+++ b/src/components/features/conversation-panel/conversation-panel-list-helpers.ts@@ -563,20 +563,45 @@ export function groupConversations({ label: string; conversations: AppConversation[] }>();+ // Index the registered workspace folders by normalized path so legacy+ // conversations created before workspace tags existed can be recovered by+ // matching their runtime `working_dir` against a known workspace (#17386).+ const knownWorkspacePaths = new Map<string, string>();if (backendKind === "local" && knownWorkspaces) {for (const ws of knownWorkspaces) {const normalized = ws.path.trim().replace(/\/+$/, "");if (normalized) {+ knownWorkspacePaths.set(normalized, ws.name);byId.set(`ws:${normalized}`, { label: ws.name, conversations: [] });}}}+ // A `local_repo` conversation runs directly in its workspace folder, so its+ // `working_dir` equals a registered workspace path and can be recovered. A+ // `new_worktree` conversation runs in a unique generated worktree that never+ // matches a registered path, so only its server tag (read in+ // `toAppConversation`) can regroup it β pre-tag worktree conversations stay+ // under "No workspace".+ const recoverWorkspaceGroup = (+ c: AppConversation,+ ): { id: string; label: string } | null => {+ if (backendKind !== "local" || knownWorkspacePaths.size === 0) return null;+ const runtimeDir = c.workspace?.working_dir?.trim().replace(/\/+$/, "");+ if (!runtimeDir) return null;+ const name = knownWorkspacePaths.get(runtimeDir);+ return name ? { id: `ws:${runtimeDir}`, label: name } : null;+ };+for (const c of items) {- const { id, label: rawLabel } = getConversationGroupIdentity(- c,- backendKind,- );+ let { id, label: rawLabel } = getConversationGroupIdentity(c, backendKind);+ if (id === "__none_workspace") {+ const recovered = recoverWorkspaceGroup(c);+ if (recovered) {+ id = recovered.id;+ rawLabel = recovered.label;+ }+ }const label =id === "__none_workspace"? labels.emptyWorkspace