Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@
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.
- 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

- On Linux and macOS, workspaces connect when `HOME` points somewhere other
Expand Down
86 changes: 53 additions & 33 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1305,26 +1305,19 @@ 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);

this.logger.info("Opening devcontainer", { remoteAuthority: authority });

// 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,
);
}

Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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}`,
Expand All @@ -1794,27 +1769,68 @@ 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<void> {
const reuseWindow = canReuseWindow();
const otherWindow = this.duplicateWorkspaceIpc.sendPing(folder.authority);
await vscode.commands.executeCommand(
"vscode.openFolder",
folder,
!reuseWindow,
);
void otherWindow.then((pong) =>
reuseWindow
? this.closeIfOpenElsewhere(pong, folder)
: this.notifyIfOpenElsewhere(pong, folder.authority),
);
}

private async closeIfOpenElsewhere(
pong: PongMessage | undefined,
folder: vscode.Uri,
): Promise<void> {
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,
): 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(
Expand All @@ -1835,7 +1851,7 @@ export class Commands {
} else if (choice === openEmptyAction) {
await vscode.commands.executeCommand("vscode.newWindow", {
remoteAuthority,
reuseWindow: false,
reuseWindow: canReuseWindow(),
});
}
})
Expand All @@ -1848,6 +1864,10 @@ export class Commands {
}
}

function canReuseWindow(): boolean {
return !vscode.workspace.workspaceFolders?.length;
}

function recordOpenResult(
telemetry: WorkspaceOpenTrace,
selection: { readonly workspace: Workspace; readonly agent: WorkspaceAgent },
Expand Down
6 changes: 5 additions & 1 deletion src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
15 changes: 13 additions & 2 deletions src/workspace/duplicateWorkspaceIpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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({
Expand Down Expand Up @@ -108,11 +109,21 @@ export class DuplicateWorkspaceIpc {
});
}

async sendPong(pingId: string, sessionId: string): Promise<void> {
async sendPong(
pingId: string,
sessionId: string,
{
workspaceFile,
workspaceFolders,
}: Pick<typeof workspace, "workspaceFile" | "workspaceFolders">,
): Promise<void> {
const singleFolder =
workspaceFolders?.length === 1 ? workspaceFolders[0] : undefined;
await this.responses.send({
type: "pong",
id: pingId,
sessionId,
workspaceUri: (workspaceFile ?? singleFolder?.uri)?.toString(),
});
}

Expand Down
1 change: 1 addition & 0 deletions test/mocks/vscode.runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
24 changes: 23 additions & 1 deletion test/unit/commands.openDevContainer.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import * as vscode from "vscode";

import { createTestCommands } from "../mocks/commands";
import {
Expand Down Expand Up @@ -34,10 +35,14 @@ const LEGACY = authorityFor("vscode");
*/
async function openDevContainer(
recents: string[],
services?: Record<string, unknown>,
): Promise<string | undefined> {
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",
Expand Down Expand Up @@ -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",
),
);
});
});
Loading
Loading