From 4449c11e741c0549b261465afb6f9a3a51de634b Mon Sep 17 00:00:00 2001 From: Ehab Younes Date: Tue, 1 Dec 2026 11:22:31 +0000 Subject: [PATCH 1/3] fix(commands): reuse an empty window for "Open Without Folder" --- CHANGELOG.md | 6 ++ src/commands.ts | 6 +- test/unit/commands.openWorkspace.test.ts | 71 +++++++++++++++++++++--- 3 files changed, 73 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa56f31662..36cfae19f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ including options that used to stop the connection, are skipped with a warning. To keep any of them, add them to `coder.sshConfig`. +### Changed + +- When a workspace is already open in another window, **Open Without Folder** + now uses the current window if it has no folder open, instead of opening + another window. + ### Fixed - On Linux and macOS, workspaces connect when `HOME` points somewhere other diff --git a/src/commands.ts b/src/commands.ts index 7d25a9f956..d9a5ea12b0 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -1835,7 +1835,7 @@ export class Commands { } else if (choice === openEmptyAction) { await vscode.commands.executeCommand("vscode.newWindow", { remoteAuthority, - reuseWindow: false, + reuseWindow: canReuseWindow(), }); } }) @@ -1848,6 +1848,10 @@ export class Commands { } } +function canReuseWindow(): boolean { + return !vscode.workspace.workspaceFolders?.length; +} + function recordOpenResult( telemetry: WorkspaceOpenTrace, selection: { readonly workspace: Workspace; readonly agent: WorkspaceAgent }, diff --git a/test/unit/commands.openWorkspace.test.ts b/test/unit/commands.openWorkspace.test.ts index ba1d6e9b26..ee670b2416 100644 --- a/test/unit/commands.openWorkspace.test.ts +++ b/test/unit/commands.openWorkspace.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, onTestFinished, vi } from "vitest"; import * as vscode from "vscode"; import { @@ -40,12 +40,19 @@ const DEVIN = "ssh-remote+coder-devin.dev.coder.com--foo--bar.main"; */ async function openFromSidebar( recents: string[], - path = FOLDER, - kind?: "folder" | "workspaceFile", + { + path = FOLDER, + kind, + services, + }: { + path?: string; + kind?: "folder" | "workspaceFile"; + services?: Record; + } = {}, ): Promise { new MockConfigurationProvider(); mockRecentlyOpened(recents, path, kind); - const commands = createTestCommands({ baseUrl: BASE_URL }); + const commands = createTestCommands({ baseUrl: BASE_URL, services }); const { AgentTreeItem } = await import("@/workspace/workspacesProvider"); await commands.openFromSidebar( new AgentTreeItem( @@ -122,11 +129,10 @@ describe("openWorkspace", () => { it("reopens a multi-root workspace on the host its file used", async () => { expect( - await openFromSidebar( - [LEGACY], - "/home/foo/project.code-workspace", - "workspaceFile", - ), + await openFromSidebar([LEGACY], { + path: "/home/foo/project.code-workspace", + kind: "workspaceFile", + }), ).toBe(LEGACY); }); @@ -142,6 +148,53 @@ describe("openWorkspace", () => { }); }); +describe("opening a workspace that is open in another window", () => { + beforeEach(() => { + vi.clearAllMocks(); + useEditor("cursor"); + }); + + async function openFromWindow({ + folders = [], + choice, + }: { + folders?: unknown[]; + choice?: string; + }): Promise { + const previous = { ...vscode.workspace }; + Object.assign(vscode.workspace, { workspaceFolders: folders }); + onTestFinished(() => { + Object.assign(vscode.workspace, previous); + }); + vi.mocked(vscode.window.showInformationMessage).mockResolvedValueOnce( + choice as never, + ); + const pong = { type: "pong", id: "1", sessionId: "other" }; + const sendPing = vi.fn().mockResolvedValue(pong); + await openFromSidebar([CURSOR], { + services: { getDuplicateWorkspaceIpc: { sendPing } }, + }); + } + + it.each([ + { label: "this window when it has no folder", folders: [], reuse: true }, + { + label: "a new window when this one has a folder", + folders: [{ uri: vscode.Uri.file("/local") }], + reuse: false, + }, + ])("opens without a folder in $label", async ({ folders, reuse }) => { + await openFromWindow({ folders, choice: "Open Without Folder" }); + + await vi.waitFor(() => + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "vscode.newWindow", + { remoteAuthority: CURSOR, reuseWindow: reuse }, + ), + ); + }); +}); + describe("openWorkspaceInDashboard", () => { it.each([ ["workspace", ""], From ce161162e6124e4a25e4c59b6839ae4b8efcccfa Mon Sep 17 00:00:00 2001 From: Ehab Younes Date: Tue, 1 Dec 2026 11:39:33 +0000 Subject: [PATCH 2/3] feat(commands): offer the already-open choices for dev containers --- CHANGELOG.md | 2 + src/commands.ts | 61 ++++++++++----------- test/unit/commands.openDevContainer.test.ts | 24 +++++++- 3 files changed, 54 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36cfae19f7..1faf8d492b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,8 @@ - When a workspace is already open in another window, **Open Without Folder** now uses the current window if it has no folder open, instead of opening another window. +- Opening a dev container that is already open in another window now offers + the same choices as opening a workspace. ### Fixed diff --git a/src/commands.ts b/src/commands.ts index d9a5ea12b0..e3972d28b4 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -1305,11 +1305,6 @@ export class Commands { const type = localWorkspaceFolder ? "dev-container" : "attached-container"; const target = `${type}+${devContainer}@${remoteAuthority}`; - let newWindow = true; - if (!vscode.workspace.workspaceFolders?.length) { - newWindow = false; - } - const { entries } = await this.recentlyOpened(); const authority = this.reusableAuthority(entries, target); @@ -1317,14 +1312,12 @@ export class Commands { // Only set the memento when opening a new folder await this.mementoManager.setStartupMode("start"); - await vscode.commands.executeCommand( - "vscode.openFolder", + await this.openRemoteFolder( vscode.Uri.from({ scheme: "vscode-remote", authority, path: devContainerFolder, }), - newWindow, ); } @@ -1731,11 +1724,6 @@ export class Commands { agent.name, ); - let newWindow = true; - // Open in the existing window if no workspaces are open. - if (!vscode.workspace.workspaceFolders?.length) { - newWindow = false; - } if (!folderPath && useDefaultDirectory) { folderPath = agent.expanded_directory; } @@ -1773,19 +1761,6 @@ export class Commands { // Only set the memento when opening a new folder/window await this.mementoManager.setStartupMode("start"); - // Best-effort check for an already-connected window. Runs in the - // background so it never delays openFolder. - this.duplicateWorkspaceIpc - .sendPing(remoteAuthority) - .then((pong) => { - if (pong) { - this.showMultiWindowNotification(pong, remoteAuthority); - } - }) - .catch((err: unknown) => { - this.logger.error(`IPC ping failed for ${remoteAuthority}`, err); - }); - this.logger.info("Opening remote workspace", { remoteAuthority, workspace: `${workspace.owner_name}/${workspace.name}`, @@ -1794,27 +1769,49 @@ export class Commands { }); if (folderPath) { - await vscode.commands.executeCommand( - "vscode.openFolder", + await this.openRemoteFolder( vscode.Uri.from({ scheme: "vscode-remote", authority: remoteAuthority, path: folderPath, }), - // Open this in a new window! - newWindow, ); return { status: "opened", handoff: "folder" }; } + const otherWindow = this.duplicateWorkspaceIpc.sendPing(remoteAuthority); // This opens the workspace without an active folder opened. await vscode.commands.executeCommand("vscode.newWindow", { - remoteAuthority: remoteAuthority, - reuseWindow: !newWindow, + remoteAuthority, + reuseWindow: canReuseWindow(), }); + void otherWindow.then((pong) => + this.notifyIfOpenElsewhere(pong, remoteAuthority), + ); return { status: "opened", handoff: "empty_window" }; } + private async openRemoteFolder(folder: vscode.Uri): Promise { + const otherWindow = this.duplicateWorkspaceIpc.sendPing(folder.authority); + await vscode.commands.executeCommand( + "vscode.openFolder", + folder, + !canReuseWindow(), + ); + void otherWindow.then((pong) => + this.notifyIfOpenElsewhere(pong, folder.authority), + ); + } + + private notifyIfOpenElsewhere( + pong: PongMessage | undefined, + remoteAuthority: string, + ): void { + if (pong) { + this.showMultiWindowNotification(pong, remoteAuthority); + } + } + // VS Code may dismiss a non-modal info message without resolving the // thenable, so this must not be awaited from the open path. private showMultiWindowNotification( diff --git a/test/unit/commands.openDevContainer.test.ts b/test/unit/commands.openDevContainer.test.ts index 6cdc9365f3..450af2cb17 100644 --- a/test/unit/commands.openDevContainer.test.ts +++ b/test/unit/commands.openDevContainer.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; import { createTestCommands } from "../mocks/commands"; import { @@ -34,10 +35,14 @@ const LEGACY = authorityFor("vscode"); */ async function openDevContainer( recents: string[], + services?: Record, ): Promise { new MockConfigurationProvider(); mockRecentlyOpened(recents, FOLDER); - const commands = createTestCommands({ baseUrl: "https://dev.coder.com" }); + const commands = createTestCommands({ + baseUrl: "https://dev.coder.com", + services, + }); await commands.openDevContainer( "foo", "bar", @@ -67,4 +72,21 @@ describe("openDevContainer", () => { ])("reopens the devcontainer on $label", async ({ recents, expected }) => { expect(await openDevContainer(recents)).toBe(expected); }); + + it("says when the devcontainer is open in another window", async () => { + const sendPing = vi + .fn() + .mockResolvedValue({ type: "pong", id: "1", sessionId: "other" }); + + await openDevContainer([], { getDuplicateWorkspaceIpc: { sendPing } }); + + expect(sendPing).toHaveBeenCalledWith(CURSOR); + await vi.waitFor(() => + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( + "This workspace is already open in another window.", + "Duplicate Window", + "Open Without Folder", + ), + ); + }); }); From 7524c299847e4ee7e2434df27fd75501046994c7 Mon Sep 17 00:00:00 2001 From: Ehab Younes Date: Tue, 1 Dec 2026 11:41:27 +0000 Subject: [PATCH 3/3] feat(commands): close the empty window when the folder is open elsewhere --- CHANGELOG.md | 3 + src/commands.ts | 23 +++++++- src/extension.ts | 6 +- src/workspace/duplicateWorkspaceIpc.ts | 15 ++++- test/mocks/vscode.runtime.ts | 1 + test/unit/commands.openWorkspace.test.ts | 55 ++++++++++++++++++- .../workspace/duplicateWorkspaceIpc.test.ts | 47 +++++++++++++--- 7 files changed, 134 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1faf8d492b..be6db87037 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,9 @@ another window. - Opening a dev container that is already open in another window now offers the same choices as opening a workspace. +- Opening a folder that is already open in another window from an empty + window, such as the one VS Code opens for a dashboard link, now closes the + empty window instead of leaving it behind. ### Fixed diff --git a/src/commands.ts b/src/commands.ts index e3972d28b4..74c6b08e7f 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -1792,17 +1792,36 @@ export class Commands { } private async openRemoteFolder(folder: vscode.Uri): Promise { + const reuseWindow = canReuseWindow(); const otherWindow = this.duplicateWorkspaceIpc.sendPing(folder.authority); await vscode.commands.executeCommand( "vscode.openFolder", folder, - !canReuseWindow(), + !reuseWindow, ); void otherWindow.then((pong) => - this.notifyIfOpenElsewhere(pong, folder.authority), + reuseWindow + ? this.closeIfOpenElsewhere(pong, folder) + : this.notifyIfOpenElsewhere(pong, folder.authority), ); } + private async closeIfOpenElsewhere( + pong: PongMessage | undefined, + folder: vscode.Uri, + ): Promise { + const otherWindowHasFolder = pong?.workspaceUri === folder.toString(); + const hasUnsavedChanges = vscode.workspace.textDocuments.some( + (doc) => doc.isDirty, + ); + if (otherWindowHasFolder && !hasUnsavedChanges) { + this.logger.info("Folder is open in another window, closing this one"); + await vscode.commands.executeCommand("workbench.action.closeWindow"); + } else { + this.notifyIfOpenElsewhere(pong, folder.authority); + } + } + private notifyIfOpenElsewhere( pong: PongMessage | undefined, remoteAuthority: string, diff --git a/src/extension.ts b/src/extension.ts index 3cef29c3d2..ead6b8cdb8 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -442,7 +442,11 @@ async function doActivate( } if (msg.type === "ping" && msg.authority === currentAuthority) { - await duplicateWorkspaceIpc.sendPong(msg.id, vscode.env.sessionId); + await duplicateWorkspaceIpc.sendPong( + msg.id, + vscode.env.sessionId, + vscode.workspace, + ); } if ( diff --git a/src/workspace/duplicateWorkspaceIpc.ts b/src/workspace/duplicateWorkspaceIpc.ts index f456e24fda..3686da471b 100644 --- a/src/workspace/duplicateWorkspaceIpc.ts +++ b/src/workspace/duplicateWorkspaceIpc.ts @@ -3,7 +3,7 @@ import { z } from "zod"; import { WindowBroadcast } from "../ipc/windowBroadcast"; -import type { Disposable, SecretStorage } from "vscode"; +import type { Disposable, SecretStorage, workspace } from "vscode"; import type { Logger } from "../logging/logger"; @@ -22,6 +22,7 @@ const PongMessageSchema = z.object({ type: z.literal("pong"), id: z.string(), sessionId: z.string(), + workspaceUri: z.string().optional(), }); const DuplicateMessageSchema = z.object({ @@ -108,11 +109,21 @@ export class DuplicateWorkspaceIpc { }); } - async sendPong(pingId: string, sessionId: string): Promise { + async sendPong( + pingId: string, + sessionId: string, + { + workspaceFile, + workspaceFolders, + }: Pick, + ): Promise { + const singleFolder = + workspaceFolders?.length === 1 ? workspaceFolders[0] : undefined; await this.responses.send({ type: "pong", id: pingId, sessionId, + workspaceUri: (workspaceFile ?? singleFolder?.uri)?.toString(), }); } diff --git a/test/mocks/vscode.runtime.ts b/test/mocks/vscode.runtime.ts index e40d7036f1..537350dc99 100644 --- a/test/mocks/vscode.runtime.ts +++ b/test/mocks/vscode.runtime.ts @@ -261,6 +261,7 @@ export const commands = { export const workspace = { getConfiguration: vi.fn(), // your helpers override this workspaceFolders: [] as unknown[], + textDocuments: [] as unknown[], workspaceFile: undefined as Uri | undefined, fs: { readFile: vi.fn(), diff --git a/test/unit/commands.openWorkspace.test.ts b/test/unit/commands.openWorkspace.test.ts index ee670b2416..042517c133 100644 --- a/test/unit/commands.openWorkspace.test.ts +++ b/test/unit/commands.openWorkspace.test.ts @@ -149,6 +149,14 @@ describe("openWorkspace", () => { }); describe("opening a workspace that is open in another window", () => { + const TARGET = vscode.Uri.from({ + scheme: "vscode-remote", + authority: CURSOR, + path: FOLDER, + }).toString(); + const LOCAL_FOLDERS = [{ uri: vscode.Uri.file("/local") }]; + const CLOSE_WINDOW = "workbench.action.closeWindow"; + beforeEach(() => { vi.clearAllMocks(); useEditor("cursor"); @@ -156,20 +164,27 @@ describe("opening a workspace that is open in another window", () => { async function openFromWindow({ folders = [], + textDocuments = [], + workspaceUri, choice, }: { folders?: unknown[]; + textDocuments?: unknown[]; + workspaceUri?: string; choice?: string; }): Promise { const previous = { ...vscode.workspace }; - Object.assign(vscode.workspace, { workspaceFolders: folders }); + Object.assign(vscode.workspace, { + workspaceFolders: folders, + textDocuments, + }); onTestFinished(() => { Object.assign(vscode.workspace, previous); }); vi.mocked(vscode.window.showInformationMessage).mockResolvedValueOnce( choice as never, ); - const pong = { type: "pong", id: "1", sessionId: "other" }; + const pong = { type: "pong", id: "1", sessionId: "other", workspaceUri }; const sendPing = vi.fn().mockResolvedValue(pong); await openFromSidebar([CURSOR], { services: { getDuplicateWorkspaceIpc: { sendPing } }, @@ -180,7 +195,7 @@ describe("opening a workspace that is open in another window", () => { { label: "this window when it has no folder", folders: [], reuse: true }, { label: "a new window when this one has a folder", - folders: [{ uri: vscode.Uri.file("/local") }], + folders: LOCAL_FOLDERS, reuse: false, }, ])("opens without a folder in $label", async ({ folders, reuse }) => { @@ -193,6 +208,40 @@ describe("opening a workspace that is open in another window", () => { ), ); }); + + it("closes this empty window when another has the folder open", async () => { + await openFromWindow({ workspaceUri: TARGET }); + + await vi.waitFor(() => + expect(vscode.commands.executeCommand).toHaveBeenCalledWith(CLOSE_WINDOW), + ); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + }); + + it.each([ + { label: "the other window is an older version", state: {} }, + { + label: "the other window has another folder", + state: { workspaceUri: `${TARGET}-other` }, + }, + { + label: "this window has a folder", + state: { workspaceUri: TARGET, folders: LOCAL_FOLDERS }, + }, + { + label: "this window has unsaved changes", + state: { workspaceUri: TARGET, textDocuments: [{ isDirty: true }] }, + }, + ])("keeps this window and offers choices when $label", async ({ state }) => { + await openFromWindow(state); + + await vi.waitFor(() => + expect(vscode.window.showInformationMessage).toHaveBeenCalled(), + ); + expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith( + CLOSE_WINDOW, + ); + }); }); describe("openWorkspaceInDashboard", () => { diff --git a/test/unit/workspace/duplicateWorkspaceIpc.test.ts b/test/unit/workspace/duplicateWorkspaceIpc.test.ts index e3e7189f2a..b2fdd6d47f 100644 --- a/test/unit/workspace/duplicateWorkspaceIpc.test.ts +++ b/test/unit/workspace/duplicateWorkspaceIpc.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import * as vscode from "vscode"; import { DuplicateWorkspaceIpc } from "@/workspace/duplicateWorkspaceIpc"; @@ -7,6 +8,8 @@ import { createMockLogger, } from "../../mocks/testHelpers"; +const EMPTY_WINDOW = { workspaceFile: undefined, workspaceFolders: undefined }; + function makeIpcPair() { const secrets = new InMemorySecretStorage(); return { @@ -20,22 +23,50 @@ describe("DuplicateWorkspaceIpc", () => { beforeEach(() => vi.useFakeTimers()); afterEach(() => vi.useRealTimers()); - it("returns the PONG when another window responds to a PING", async () => { + const uri = (path: string) => + vscode.Uri.from({ scheme: "vscode-remote", authority: "a", path }); + const folders = (...paths: string[]) => + paths.map((path, index) => ({ uri: uri(path), name: path, index })); + const file = uri("/x.code-workspace"); + + it.each([ + { + label: "the workspace file", + opened: { workspaceFile: file, workspaceFolders: folders("/x") }, + workspaceUri: file.toString(), + }, + { + label: "the single folder", + opened: { workspaceFile: undefined, workspaceFolders: folders("/x") }, + workspaceUri: uri("/x").toString(), + }, + { + label: "no workspace for several folders without a file", + opened: { + workspaceFile: undefined, + workspaceFolders: folders("/x", "/y"), + }, + workspaceUri: undefined, + }, + { + label: "no workspace for an empty window", + opened: EMPTY_WINDOW, + workspaceUri: undefined, + }, + ])("answers a PING with $label", async ({ opened, workspaceUri }) => { const { sender, receiver } = makeIpcPair(); receiver.onRequest(async (msg) => { if (msg.type === "ping") { - await receiver.sendPong(msg.id, "session-abc"); + await receiver.sendPong(msg.id, "session-abc", opened); } }); const promise = sender.sendPing("ssh-remote+my-host", 2000); await vi.advanceTimersByTimeAsync(50); - const pong = await promise; - expect(pong).toMatchObject({ - type: "pong", - sessionId: "session-abc", - }); + const pong = await promise; + expect(pong?.sessionId).toBe("session-abc"); + expect(pong?.workspaceUri).toBe(workspaceUri); }); it("resolves to undefined when no window answers within the timeout", async () => { @@ -53,7 +84,7 @@ describe("DuplicateWorkspaceIpc", () => { const peer = new DuplicateWorkspaceIpc(secrets, createMockLogger()); peer.onRequest(async (msg) => { if (msg.type === "ping" && msg.authority === "ssh-remote+host") { - await peer.sendPong(msg.id, "win-a"); + await peer.sendPong(msg.id, "win-a", EMPTY_WINDOW); } else if (msg.type === "duplicate" && msg.targetSessionId === "win-a") { duplicateReceived(); }