Skip to content

Commit ec97098

Browse files
committed
feat(commands): close the empty window when the folder is open elsewhere
1 parent ea5a979 commit ec97098

7 files changed

Lines changed: 134 additions & 16 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020
another window.
2121
- Opening a dev container that is already open in another window now offers
2222
the same choices as opening a workspace.
23+
- Opening a folder that is already open in another window from an empty
24+
window, such as the one VS Code opens for a dashboard link, now closes the
25+
empty window instead of leaving it behind.
2326

2427
### Fixed
2528

‎src/commands.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1792,17 +1792,36 @@ export class Commands {
17921792
}
17931793

17941794
private async openRemoteFolder(folder: vscode.Uri): Promise<void> {
1795+
const reuseWindow = canReuseWindow();
17951796
const otherWindow = this.duplicateWorkspaceIpc.sendPing(folder.authority);
17961797
await vscode.commands.executeCommand(
17971798
"vscode.openFolder",
17981799
folder,
1799-
!canReuseWindow(),
1800+
!reuseWindow,
18001801
);
18011802
void otherWindow.then((pong) =>
1802-
this.notifyIfOpenElsewhere(pong, folder.authority),
1803+
reuseWindow
1804+
? this.closeIfOpenElsewhere(pong, folder)
1805+
: this.notifyIfOpenElsewhere(pong, folder.authority),
18031806
);
18041807
}
18051808

1809+
private async closeIfOpenElsewhere(
1810+
pong: PongMessage | undefined,
1811+
folder: vscode.Uri,
1812+
): Promise<void> {
1813+
const otherWindowHasFolder = pong?.workspaceUri === folder.toString();
1814+
const hasUnsavedChanges = vscode.workspace.textDocuments.some(
1815+
(doc) => doc.isDirty,
1816+
);
1817+
if (otherWindowHasFolder && !hasUnsavedChanges) {
1818+
this.logger.info("Folder is open in another window, closing this one");
1819+
await vscode.commands.executeCommand("workbench.action.closeWindow");
1820+
} else {
1821+
this.notifyIfOpenElsewhere(pong, folder.authority);
1822+
}
1823+
}
1824+
18061825
private notifyIfOpenElsewhere(
18071826
pong: PongMessage | undefined,
18081827
remoteAuthority: string,

‎src/extension.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -442,7 +442,11 @@ async function doActivate(
442442
}
443443

444444
if (msg.type === "ping" && msg.authority === currentAuthority) {
445-
await duplicateWorkspaceIpc.sendPong(msg.id, vscode.env.sessionId);
445+
await duplicateWorkspaceIpc.sendPong(
446+
msg.id,
447+
vscode.env.sessionId,
448+
vscode.workspace,
449+
);
446450
}
447451

448452
if (

‎src/workspace/duplicateWorkspaceIpc.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { z } from "zod";
33

44
import { WindowBroadcast } from "../ipc/windowBroadcast";
55

6-
import type { Disposable, SecretStorage } from "vscode";
6+
import type { Disposable, SecretStorage, workspace } from "vscode";
77

88
import type { Logger } from "../logging/logger";
99

@@ -22,6 +22,7 @@ const PongMessageSchema = z.object({
2222
type: z.literal("pong"),
2323
id: z.string(),
2424
sessionId: z.string(),
25+
workspaceUri: z.string().optional(),
2526
});
2627

2728
const DuplicateMessageSchema = z.object({
@@ -108,11 +109,21 @@ export class DuplicateWorkspaceIpc {
108109
});
109110
}
110111

111-
async sendPong(pingId: string, sessionId: string): Promise<void> {
112+
async sendPong(
113+
pingId: string,
114+
sessionId: string,
115+
{
116+
workspaceFile,
117+
workspaceFolders,
118+
}: Pick<typeof workspace, "workspaceFile" | "workspaceFolders">,
119+
): Promise<void> {
120+
const singleFolder =
121+
workspaceFolders?.length === 1 ? workspaceFolders[0] : undefined;
112122
await this.responses.send({
113123
type: "pong",
114124
id: pingId,
115125
sessionId,
126+
workspaceUri: (workspaceFile ?? singleFolder?.uri)?.toString(),
116127
});
117128
}
118129

‎test/mocks/vscode.runtime.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ export const commands = {
261261
export const workspace = {
262262
getConfiguration: vi.fn(), // your helpers override this
263263
workspaceFolders: [] as unknown[],
264+
textDocuments: [] as unknown[],
264265
workspaceFile: undefined as Uri | undefined,
265266
fs: {
266267
readFile: vi.fn(),

‎test/unit/commands.openWorkspace.test.ts‎

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -149,27 +149,42 @@ describe("openWorkspace", () => {
149149
});
150150

151151
describe("opening a workspace that is open in another window", () => {
152+
const TARGET = vscode.Uri.from({
153+
scheme: "vscode-remote",
154+
authority: CURSOR,
155+
path: FOLDER,
156+
}).toString();
157+
const LOCAL_FOLDERS = [{ uri: vscode.Uri.file("/local") }];
158+
const CLOSE_WINDOW = "workbench.action.closeWindow";
159+
152160
beforeEach(() => {
153161
vi.clearAllMocks();
154162
useEditor("cursor");
155163
});
156164

157165
async function openFromWindow({
158166
folders = [],
167+
textDocuments = [],
168+
workspaceUri,
159169
choice,
160170
}: {
161171
folders?: unknown[];
172+
textDocuments?: unknown[];
173+
workspaceUri?: string;
162174
choice?: string;
163175
}): Promise<void> {
164176
const previous = { ...vscode.workspace };
165-
Object.assign(vscode.workspace, { workspaceFolders: folders });
177+
Object.assign(vscode.workspace, {
178+
workspaceFolders: folders,
179+
textDocuments,
180+
});
166181
onTestFinished(() => {
167182
Object.assign(vscode.workspace, previous);
168183
});
169184
vi.mocked(vscode.window.showInformationMessage).mockResolvedValueOnce(
170185
choice as never,
171186
);
172-
const pong = { type: "pong", id: "1", sessionId: "other" };
187+
const pong = { type: "pong", id: "1", sessionId: "other", workspaceUri };
173188
const sendPing = vi.fn().mockResolvedValue(pong);
174189
await openFromSidebar([CURSOR], {
175190
services: { getDuplicateWorkspaceIpc: { sendPing } },
@@ -180,7 +195,7 @@ describe("opening a workspace that is open in another window", () => {
180195
{ label: "this window when it has no folder", folders: [], reuse: true },
181196
{
182197
label: "a new window when this one has a folder",
183-
folders: [{ uri: vscode.Uri.file("/local") }],
198+
folders: LOCAL_FOLDERS,
184199
reuse: false,
185200
},
186201
])("opens without a folder in $label", async ({ folders, reuse }) => {
@@ -193,6 +208,40 @@ describe("opening a workspace that is open in another window", () => {
193208
),
194209
);
195210
});
211+
212+
it("closes this empty window when another has the folder open", async () => {
213+
await openFromWindow({ workspaceUri: TARGET });
214+
215+
await vi.waitFor(() =>
216+
expect(vscode.commands.executeCommand).toHaveBeenCalledWith(CLOSE_WINDOW),
217+
);
218+
expect(vscode.window.showInformationMessage).not.toHaveBeenCalled();
219+
});
220+
221+
it.each([
222+
{ label: "the other window is an older version", state: {} },
223+
{
224+
label: "the other window has another folder",
225+
state: { workspaceUri: `${TARGET}-other` },
226+
},
227+
{
228+
label: "this window has a folder",
229+
state: { workspaceUri: TARGET, folders: LOCAL_FOLDERS },
230+
},
231+
{
232+
label: "this window has unsaved changes",
233+
state: { workspaceUri: TARGET, textDocuments: [{ isDirty: true }] },
234+
},
235+
])("keeps this window and offers choices when $label", async ({ state }) => {
236+
await openFromWindow(state);
237+
238+
await vi.waitFor(() =>
239+
expect(vscode.window.showInformationMessage).toHaveBeenCalled(),
240+
);
241+
expect(vscode.commands.executeCommand).not.toHaveBeenCalledWith(
242+
CLOSE_WINDOW,
243+
);
244+
});
196245
});
197246

198247
describe("openWorkspaceInDashboard", () => {

‎test/unit/workspace/duplicateWorkspaceIpc.test.ts‎

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2+
import * as vscode from "vscode";
23

34
import { DuplicateWorkspaceIpc } from "@/workspace/duplicateWorkspaceIpc";
45

@@ -7,6 +8,8 @@ import {
78
createMockLogger,
89
} from "../../mocks/testHelpers";
910

11+
const EMPTY_WINDOW = { workspaceFile: undefined, workspaceFolders: undefined };
12+
1013
function makeIpcPair() {
1114
const secrets = new InMemorySecretStorage();
1215
return {
@@ -20,22 +23,50 @@ describe("DuplicateWorkspaceIpc", () => {
2023
beforeEach(() => vi.useFakeTimers());
2124
afterEach(() => vi.useRealTimers());
2225

23-
it("returns the PONG when another window responds to a PING", async () => {
26+
const uri = (path: string) =>
27+
vscode.Uri.from({ scheme: "vscode-remote", authority: "a", path });
28+
const folders = (...paths: string[]) =>
29+
paths.map((path, index) => ({ uri: uri(path), name: path, index }));
30+
const file = uri("/x.code-workspace");
31+
32+
it.each([
33+
{
34+
label: "the workspace file",
35+
opened: { workspaceFile: file, workspaceFolders: folders("/x") },
36+
workspaceUri: file.toString(),
37+
},
38+
{
39+
label: "the single folder",
40+
opened: { workspaceFile: undefined, workspaceFolders: folders("/x") },
41+
workspaceUri: uri("/x").toString(),
42+
},
43+
{
44+
label: "no workspace for several folders without a file",
45+
opened: {
46+
workspaceFile: undefined,
47+
workspaceFolders: folders("/x", "/y"),
48+
},
49+
workspaceUri: undefined,
50+
},
51+
{
52+
label: "no workspace for an empty window",
53+
opened: EMPTY_WINDOW,
54+
workspaceUri: undefined,
55+
},
56+
])("answers a PING with $label", async ({ opened, workspaceUri }) => {
2457
const { sender, receiver } = makeIpcPair();
2558
receiver.onRequest(async (msg) => {
2659
if (msg.type === "ping") {
27-
await receiver.sendPong(msg.id, "session-abc");
60+
await receiver.sendPong(msg.id, "session-abc", opened);
2861
}
2962
});
3063

3164
const promise = sender.sendPing("ssh-remote+my-host", 2000);
3265
await vi.advanceTimersByTimeAsync(50);
33-
const pong = await promise;
3466

35-
expect(pong).toMatchObject({
36-
type: "pong",
37-
sessionId: "session-abc",
38-
});
67+
const pong = await promise;
68+
expect(pong?.sessionId).toBe("session-abc");
69+
expect(pong?.workspaceUri).toBe(workspaceUri);
3970
});
4071

4172
it("resolves to undefined when no window answers within the timeout", async () => {
@@ -53,7 +84,7 @@ describe("DuplicateWorkspaceIpc", () => {
5384
const peer = new DuplicateWorkspaceIpc(secrets, createMockLogger());
5485
peer.onRequest(async (msg) => {
5586
if (msg.type === "ping" && msg.authority === "ssh-remote+host") {
56-
await peer.sendPong(msg.id, "win-a");
87+
await peer.sendPong(msg.id, "win-a", EMPTY_WINDOW);
5788
} else if (msg.type === "duplicate" && msg.targetSessionId === "win-a") {
5889
duplicateReceived();
5990
}

0 commit comments

Comments
 (0)