Skip to content
Merged
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
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,24 @@ one in a new window, without leaving the editor.
- A Spinbox account, with an SSH key of this machine added to it. If none is, Spinbox says so and
offers to add one.

## Spinbox's own connection

With `spin-stack.open-remote-ssh` installed and allowed VS Code's proposed API, Spinbox opens a
workspace as `vscode-remote://spin+<workspace>/...` instead of over Remote-SSH: the connection is
Spinbox's, so a workspace that does not open says why, in VS Code, with what to do. Its server
comes from your installation, never a download.

VS Code, VSCodium and the other editors let a third-party extension use a proposed API only when
`argv.json` names it. Run **Preferences: Configure Runtime Arguments**, add this line inside the
object it opens, and restart the editor:

```jsonc
"enable-proposed-api": ["spin-stack.open-remote-ssh"]
```

Spinbox checks for it on every open: until the resolver activates, workspaces open over Remote-SSH,
and Spinbox says once what is missing.

The extension carries the `spin` CLI it needs, for Linux and macOS on x64 and arm64: there is
nothing else to install.

Expand All @@ -22,7 +40,8 @@ nothing else to install.
2. Open **Spinbox Workspaces** in the Explorer and select **Sign In**, or run
**Spinbox: Sign In** from the Command Palette. Spinbox then shows in the Accounts menu.
3. Select a workspace's **Open Workspace** action. A stopped workspace is started first; it opens
in a new window over Remote-SSH.
in a new window, through Spinbox's own connection where it is enabled (above), otherwise over
Remote-SSH.

## Features

Expand Down
5 changes: 4 additions & 1 deletion Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,13 @@ tasks:
- pnpm test:cli

test:integration:
desc: test:cli, then the extension activated in a real VS Code, downloaded into .vscode-test/. Under xvfb-run when it is installed, which CI's runner has; otherwise on the display there is.
desc: test:cli, then the extension activated in a real VS Code, downloaded into .vscode-test/ - the one engines.vscode names, and versions.yaml's vscode for the resolver's detection. Under xvfb-run when it is installed, which CI's runner has; otherwise on the display there is.
vars:
XVFB:
sh: command -v xvfb-run || true
env:
VSCODE_GATED:
sh: versions version vscode
cmds:
- task: test:cli
- task: build
Expand Down
22 changes: 15 additions & 7 deletions src/open/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as vscode from "vscode"
import { showCliError } from "../errors"
import { ensureRemoteExtension } from "../remote/extension"
import { openThrough } from "../remote/resolver"
import { trace } from "../telemetry/vscode"
import { readCommit } from "./editor"
import { type OpenCli, type OpenDeps, type OpenUi, openWorkspace, pickAndOpen } from "./open"
Expand Down Expand Up @@ -45,24 +45,31 @@ const ui: OpenUi = {
},
}

function deps(cli: OpenCli): OpenDeps {
// deps answers what opening needs, or nothing when no extension is there to open what spin answers.
async function deps(context: vscode.ExtensionContext, cli: OpenCli): Promise<OpenDeps | undefined> {
const spin = await openThrough(context.globalState)
if (spin === undefined) {
return undefined
}
return {
cli,
ui,
commit: () => readCommit(vscode.env.appRoot),
vscodeVersion: vscode.version,
trace,
spin,
}
}

// registerOpen registers spinbox.openWorkspace and the handler of
// vscode://spin-stack.spinbox/open?workspace=<id>&path=<absolute path>. Neither runs spin until
// a Remote-SSH extension is there to open what it answers.
// the resolver or a Remote-SSH extension is there to open what it answers.
export function registerOpen(context: vscode.ExtensionContext, cli: OpenCli): void {
context.subscriptions.push(
vscode.commands.registerCommand("spinbox.openWorkspace", async (arg?: unknown) => {
if (await ensureRemoteExtension()) {
await pickAndOpen(deps(cli), typeof arg === "string" ? arg : undefined)
const d = await deps(context, cli)
if (d !== undefined) {
await pickAndOpen(d, typeof arg === "string" ? arg : undefined)
}
}),
vscode.window.registerUriHandler({
Expand All @@ -72,8 +79,9 @@ export function registerOpen(context: vscode.ExtensionContext, cli: OpenCli): vo
ui.showError(`Spinbox cannot open this link: ${parsed.reason}.`)
return
}
if (await ensureRemoteExtension()) {
await openWorkspace(deps(cli), parsed.target)
const d = await deps(context, cli)
if (d !== undefined) {
await openWorkspace(d, parsed.target)
}
},
}),
Expand Down
20 changes: 16 additions & 4 deletions src/open/open.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { SpinCli } from "../cli/client"
import type { Workspace } from "../cli/contract"
import { SPIN_RESOLVER, spinFolderUri } from "../status/authority"
import type { Trace } from "../telemetry"
import { checkTarget, type OpenTarget } from "./target"

Expand Down Expand Up @@ -35,10 +36,12 @@ export interface OpenDeps {
// The traceparent of a new trace for one operation, which every spin command it runs joins;
// undefined with telemetry off (src/telemetry).
trace: Trace
// Open the folder as spin+<workspace>, which SPIN_RESOLVER resolves, not over Remote-SSH.
spin: boolean
}

// openWorkspace runs `spin code <workspace> [path] --no-open --start --vscode-commit ...` and
// opens the folder it answers in a new window. Every failure is shown, the CLI's with its action
// opens the folder it answers in a new window, as spin+<workspace> when deps.spin. Every failure is shown, the CLI's with its action
// and a retry that runs it again; cancelling shows nothing. Each attempt is a trace of its own.
export async function openWorkspace(deps: OpenDeps, target: OpenTarget): Promise<void> {
await open(deps, target, deps.trace())
Expand Down Expand Up @@ -78,7 +81,8 @@ async function open(
`Preparing VS Code ${p.vscode_version} for this installation (once): ${p.step}`,
),
})
if (r.not_given !== undefined) {
// The resolver never downloads a server: it refuses, and says what to do, itself.
if (r.not_given !== undefined && !deps.spin) {
deps.ui.showWarning(
`VS Code downloads its own server into ${target.workspace} (about 220 MB): the installation could not prepare it. ${r.not_given}`,
)
Expand All @@ -92,9 +96,17 @@ async function open(
}
},
)
if (folderUri !== undefined) {
await deps.ui.openFolder(folderUri)
if (folderUri === undefined) {
return
}
const uri = deps.spin ? spinFolderUri(folderUri) : folderUri
if (uri === undefined) {
deps.ui.showError(
`Spinbox cannot open ${target.workspace} through ${SPIN_RESOLVER}: spin answered ${folderUri}, which names no spin.<workspace> host.`,
)
return
}
await deps.ui.openFolder(uri)
}
try {
await attempt(traceparent)
Expand Down
4 changes: 2 additions & 2 deletions src/remote/extension.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as vscode from "vscode"

// Spinbox opens a workspace through a vscode-remote://ssh-remote+ URI, which only a Remote-SSH
// extension answers. Microsoft's is on the Visual Studio Marketplace alone; every other editor
// Without the resolver (resolver.ts), Spinbox opens a workspace through a
// vscode-remote://ssh-remote+ URI, which only a Remote-SSH extension answers. Microsoft's is on the Visual Studio Marketplace alone; every other editor
// (VSCodium, Cursor, ...) installs from Open VSX, where open-remote-ssh is the one there is.
export const MICROSOFT_REMOTE_SSH = "ms-vscode-remote.remote-ssh"
export const OPEN_REMOTE_SSH = "jeanp413.open-remote-ssh"
Expand Down
74 changes: 74 additions & 0 deletions src/remote/resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import * as vscode from "vscode"
import { SPIN_RESOLVER } from "../status/authority"
import { ensureRemoteExtension } from "./extension"

// spin-stack/open-remote-ssh resolves vscode-remote://spin+<workspace> through the spin CLI, and
// shows what refuses the connection, which Remote-SSH leaves in its log. It runs on VS Code's
// proposed resolvers API, which an editor grants a third-party extension only when argv.json
// names it. So it is no extensionDependencies of this extension: a dependency that fails to
// activate keeps the extension that depends on it from activating, and Remote-SSH with it.

// The line argv.json needs for the resolver to run.
export const ENABLE_PROPOSED_API = `"enable-proposed-api": ["${SPIN_RESOLVER}"]`

// A build of the resolver that answers spin+ activates on it (its package.json).
const RESOLVES_SPIN = "onResolveRemoteAuthority:spin"

// Where Spinbox keeps the last reason it told the person, so each is told once.
export const TOLD_KEY = "spinbox.resolverHint"

const OPEN_ARGV = "Open argv.json"

// Why a workspace opens over Remote-SSH: no build of the resolver that answers spin+ is installed,
// or one is and VS Code did not let it activate.
export type Fallback = "missing" | "disabled"

export type Route = { spin: true } | { spin: false; because: Fallback }

// route answers whether the resolver is there and active. Activating it is the check: without the
// proposed API, its registerRemoteAuthorityResolver throws, and the activation rejects.
export async function route(): Promise<Route> {
const ext = vscode.extensions.getExtension(SPIN_RESOLVER)
const events: unknown = ext?.packageJSON?.activationEvents
if (ext === undefined || !Array.isArray(events) || !events.includes(RESOLVES_SPIN)) {
return { spin: false, because: "missing" }
}
try {
await ext.activate()
} catch {
return { spin: false, because: "disabled" }
}
return { spin: true }
}

// openThrough answers how to open a workspace: through the resolver (true), over Remote-SSH
// (false), or not at all (undefined), when there is neither and the person installs no Remote-SSH
// extension. Falling back, it says once per reason how to have the resolver instead.
export async function openThrough(state: vscode.Memento): Promise<boolean | undefined> {
const r = await route()
if (r.spin) {
return true
}
if (!(await ensureRemoteExtension())) {
return undefined
}
tellOnce(state, r.because)
return false
}

function tellOnce(state: vscode.Memento, because: Fallback): void {
if (state.get<Fallback>(TOLD_KEY) === because) {
return
}
void state.update(TOLD_KEY, because)
const enable = `add ${ENABLE_PROPOSED_API} to argv.json and restart VS Code`
const message =
because === "disabled"
? `Spinbox opens workspaces over Remote-SSH: VS Code does not let ${SPIN_RESOLVER} use the proposed API it opens them with. To open them through Spinbox's own connection, which says why one does not open, ${enable}.`
: `Spinbox opens workspaces over Remote-SSH. To open them through Spinbox's own connection, which says why one does not open, install ${SPIN_RESOLVER}, ${enable}.`
void Promise.resolve(vscode.window.showInformationMessage(message, OPEN_ARGV)).then((pick) =>
pick === OPEN_ARGV
? vscode.commands.executeCommand("workbench.action.configureRuntimeArguments")
: undefined,
)
}
53 changes: 46 additions & 7 deletions src/status/authority.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// The Spinbox workspace a Remote-SSH window is connected to, read from its remote authority.
// The Spinbox workspace a window is connected to, read from its remote authority: Remote-SSH's
// ssh-remote+spin.<workspace>, or spin+<workspace>, which spin-stack.open-remote-ssh resolves.
export interface SpinRemote {
// The SSH host spin code wrote into the SSH config: spin.<workspace>.
host: string
Expand All @@ -9,26 +10,64 @@ export interface SpinRemote {

const PREFIX = "ssh-remote+"

// sshHostPrefix and hostSafeRe in spin's cmd/cli/cmd/sshconfig.go.
const HOST = /^spin\.([A-Za-z0-9][A-Za-z0-9_-]*)$/
// The extension that resolves spin+<workspace> (src/remote/resolver.ts).
export const SPIN_RESOLVER = "spin-stack.open-remote-ssh"

// The authority its src/spin/authority.ts resolves, a workspace by the same rule.
const SPIN_PREFIX = "spin+"

// hostSafeRe in spin's cmd/cli/cmd/sshconfig.go.
const WORKSPACE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/

// sshHostPrefix in spin's cmd/cli/cmd/sshconfig.go.
const HOST_PREFIX = "spin."

const FOLDER_PREFIX = `vscode-remote://${PREFIX}`

// Remote-SSH writes a host that is not all lower case as the hex of {"hostName": "<host>"}: a URI
// authority is compared without case.
const HEX = /^(?:[0-9a-f]{2})+$/

// parseSpinRemote answers the workspace a window is connected to, from vscode.env.remoteName and
// the authority of its folder's URI (ssh-remote+spin.<workspace>), or nothing when the window is
// not a Spinbox workspace over Remote-SSH.
// the authority of its folder's URI, or nothing when the window is not a Spinbox workspace.
export function parseSpinRemote(
remoteName: string | undefined,
authority: string | undefined,
): SpinRemote | undefined {
if (remoteName === "spin" && authority?.startsWith(SPIN_PREFIX)) {
const workspace = authority.slice(SPIN_PREFIX.length)
return WORKSPACE.test(workspace) ? { host: HOST_PREFIX + workspace, workspace } : undefined
}
if (remoteName !== "ssh-remote" || authority === undefined || !authority.startsWith(PREFIX)) {
return undefined
}
const host = decodeHost(authority.slice(PREFIX.length))
const m = HOST.exec(host)
return m?.[1] === undefined ? undefined : { host, workspace: m[1] }
const workspace = workspaceOf(host)
return workspace === undefined ? undefined : { host, workspace }
}

// spinFolderUri answers the folder spin code names, vscode-remote://ssh-remote+spin.<workspace>
// <path>, as the same folder under spin+<workspace>, or nothing when it names another host.
export function spinFolderUri(folderUri: string): string | undefined {
if (!folderUri.startsWith(FOLDER_PREFIX)) {
return undefined
}
const rest = folderUri.slice(FOLDER_PREFIX.length)
const slash = rest.indexOf("/")
const workspace = workspaceOf(decodeHost(slash < 0 ? rest : rest.slice(0, slash)))
if (workspace === undefined) {
return undefined
}
return `vscode-remote://${SPIN_PREFIX}${workspace}${slash < 0 ? "/" : rest.slice(slash)}`
}

// workspaceOf answers the workspace of the SSH host spin.<workspace>, or nothing for another host.
function workspaceOf(host: string): string | undefined {
if (!host.startsWith(HOST_PREFIX)) {
return undefined
}
const workspace = host.slice(HOST_PREFIX.length)
return WORKSPACE.test(workspace) ? workspace : undefined
}

function decodeHost(host: string): string {
Expand Down
38 changes: 29 additions & 9 deletions test/integration/run.mjs
Original file line number Diff line number Diff line change
@@ -1,17 +1,37 @@
// Starts a VS Code, downloaded into .vscode-test/ at the version engines.vscode names, with this
// extension loaded and the suite dist-test/suite.js run in its extension host. Needs a display:
// CI runs it under xvfb-run.
// Starts VS Code stable, downloaded into .vscode-test/, with this extension loaded and the suite
// dist-test/suite.js run in its extension host, three times:
//
// - at the version engines.vscode names, alone: the resolver is missing;
// - at VSCODE_GATED (versions.yaml's vscode, set by task test:integration) with the stand-in
// for spin-stack.open-remote-ssh in testdata/resolver/, as VS Code is installed: it withholds
// the proposed API, so the resolver is disabled;
// - the same with --enable-proposed-api for the stand-in, which is what argv.json's
// enable-proposed-api line gives: the resolver is active.
//
// Needs a display: CI runs it under xvfb-run.
import { readFileSync } from "node:fs"
import { dirname, resolve } from "node:path"
import { fileURLToPath } from "node:url"
import { runTests } from "@vscode/test-electron"

const root = resolve(dirname(fileURLToPath(import.meta.url)), "../..")
const { engines } = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8"))
const gated = process.env.VSCODE_GATED
if (!gated) {
throw new Error("VSCODE_GATED names no VS Code version: run it as task test:integration")
}
const resolver = resolve(root, "test/integration/testdata/resolver")

await runTests({
version: engines.vscode.replace(/^\^/, ""),
extensionDevelopmentPath: root,
extensionTestsPath: resolve(root, "dist-test/suite.js"),
launchArgs: ["--disable-extensions", "--disable-workspace-trust"],
})
for (const [route, version, extensions, flags] of [
["missing", engines.vscode.replace(/^\^/, ""), [root], []],
["disabled", gated, [root, resolver], []],
["spin", gated, [root, resolver], ["--enable-proposed-api", "spin-stack.open-remote-ssh"]],
]) {
await runTests({
version,
extensionDevelopmentPath: extensions,
extensionTestsPath: resolve(root, "dist-test/suite.js"),
extensionTestsEnv: { SPINBOX_WANT_ROUTE: route },
launchArgs: ["--disable-extensions", "--disable-workspace-trust", ...flags],
})
}
6 changes: 6 additions & 0 deletions test/integration/suite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as assert from "node:assert/strict"
import { join } from "node:path"
import * as vscode from "vscode"
import { COMMANDS } from "../../src/commands"
import { route } from "../../src/remote/resolver"

// Run in VS Code's extension host by @vscode/test-electron: a rejection fails the run.
export async function run(): Promise<void> {
Expand Down Expand Up @@ -30,4 +31,9 @@ export async function run(): Promise<void> {
accounts.map((a) => a.label),
["dev@example.com"],
)

// The resolver is detected by its activation, which only the proposed API lets through
// (run.mjs says which of missing, disabled and spin each run is).
const want = process.env.SPINBOX_WANT_ROUTE
assert.deepEqual(await route(), want === "spin" ? { spin: true } : { spin: false, because: want })
}
13 changes: 13 additions & 0 deletions test/integration/testdata/resolver/extension.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// What spin-stack.open-remote-ssh's activation does first that the proposed API decides: register
// a remote authority resolver. VS Code throws here when the API is withheld.
const vscode = require("vscode")

exports.activate = (context) => {
context.subscriptions.push(
vscode.workspace.registerRemoteAuthorityResolver("spin", {
resolve: () => {
throw new Error("the stand-in resolves nothing")
},
}),
)
}
Loading
Loading