Using the code cli in VS Code Remote extension

VS Code (Dall-e generated)

One of the major reasons I switched to VS Code completely some years back is its excellent extension system, in particular the seamless remote SSH editing extension.

Remote SSH extension is really cool!

Using a local editor on a remote filesystem without fiddling with sshfs or the like, managing to use extensions like Python, Go and Copilot, all setup and configured locally but running on content on a remote system has been pretty cool. It helps me keep my office and personal content separate - I edit my personal codebase on my personal computers using vscode on my office laptop when I need to.

The annoyance about the code cli

But one of the most annoying thing while using the VS Code remote ssh extension was the VS Code cli, which I use a lot. I spend a lot of time on the terminal inside VS Code, and sometimes it is just easier to open a file from the command line using code FILE instead of reaching for the mouse to click on the file in the explorer.

Here is where it gets tricky.

If you have a VS Code installation on the remote computer, and you used it to install the CLI, that CLI executable (On Mac installed in /usr/local/bin/code ) will always open files in that local VS Code installation. It will not open the file in the remote SSH VS Code workspace that you have open.

TLDR: Use the script at the end of this post instead of the code cli in path if you want to open files in the remote ssh extension workspace.

This has something to do with how the CLI discovers the “server” instance - the VS Code instance that is running on machine and which hosts the editor. The communication happens via a socket, and the path to the socket is discovered using a combination of the CLI path and environment variables.

So if you use the code cli in the terminal of the remote SSH workspace, it will open the file in the local VS Code.

Incidentally, the remote SSH extension installs a VS Code installation on the remote server in the home directory, and it has its own cli executable. If you use this cli instead of the one in the path, it will discover the remote ssh workspace correctly and open the file in it.

So all we have to do is to discover this cli path correctly and use it instead of the one in the path. I found a suitable environment variable set by the core Git extension which can be used to find this. I used the bash function below in my bashrc to add a command (code_remote) that I now use instead for opening files in the terminal of remote SSH extension workspaces.

tech
Using Giscus for commenting on this blog