diff --git a/README.md b/README.md index 372c9e4..bfbd245 100644 --- a/README.md +++ b/README.md @@ -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+/...` 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. @@ -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 diff --git a/Taskfile.yml b/Taskfile.yml index 6b80e26..bdbb75f 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -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 diff --git a/src/open/index.ts b/src/open/index.ts index efa5104..e39a9db 100644 --- a/src/open/index.ts +++ b/src/open/index.ts @@ -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" @@ -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 { + 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=&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({ @@ -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) } }, }), diff --git a/src/open/open.ts b/src/open/open.ts index d91a31f..b149c20 100644 --- a/src/open/open.ts +++ b/src/open/open.ts @@ -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" @@ -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+, which SPIN_RESOLVER resolves, not over Remote-SSH. + spin: boolean } // openWorkspace runs `spin code [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+ 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 { await open(deps, target, deps.trace()) @@ -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}`, ) @@ -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. host.`, + ) + return + } + await deps.ui.openFolder(uri) } try { await attempt(traceparent) diff --git a/src/remote/extension.ts b/src/remote/extension.ts index 621098f..fd533c7 100644 --- a/src/remote/extension.ts +++ b/src/remote/extension.ts @@ -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" diff --git a/src/remote/resolver.ts b/src/remote/resolver.ts new file mode 100644 index 0000000..6b0058e --- /dev/null +++ b/src/remote/resolver.ts @@ -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+ 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 { + 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 { + 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(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, + ) +} diff --git a/src/status/authority.ts b/src/status/authority.ts index 3e5bfa8..bf26fda 100644 --- a/src/status/authority.ts +++ b/src/status/authority.ts @@ -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., or spin+, which spin-stack.open-remote-ssh resolves. export interface SpinRemote { // The SSH host spin code wrote into the SSH config: spin.. host: string @@ -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+ (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": ""}: 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.), 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. +// , as the same folder under spin+, 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., 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 { diff --git a/test/integration/run.mjs b/test/integration/run.mjs index 3364523..d828975 100644 --- a/test/integration/run.mjs +++ b/test/integration/run.mjs @@ -1,6 +1,14 @@ -// 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" @@ -8,10 +16,22 @@ 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], + }) +} diff --git a/test/integration/suite.ts b/test/integration/suite.ts index b2fd739..34e615c 100644 --- a/test/integration/suite.ts +++ b/test/integration/suite.ts @@ -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 { @@ -30,4 +31,9 @@ export async function run(): Promise { 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 }) } diff --git a/test/integration/testdata/resolver/extension.cjs b/test/integration/testdata/resolver/extension.cjs new file mode 100644 index 0000000..19b52e9 --- /dev/null +++ b/test/integration/testdata/resolver/extension.cjs @@ -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") + }, + }), + ) +} diff --git a/test/integration/testdata/resolver/package.json b/test/integration/testdata/resolver/package.json new file mode 100644 index 0000000..dd763e0 --- /dev/null +++ b/test/integration/testdata/resolver/package.json @@ -0,0 +1,21 @@ +{ + "name": "open-remote-ssh", + "displayName": "A stand-in for spin-stack.open-remote-ssh", + "description": "Registers the spin resolver as spin-stack.open-remote-ssh does, so the suite checks Spinbox's detection of it against a real VS Code.", + "version": "0.0.0", + "publisher": "spin-stack", + "private": true, + "engines": { + "vscode": "^1.120.0" + }, + "extensionKind": [ + "ui" + ], + "main": "./extension.cjs", + "enabledApiProposals": [ + "resolvers" + ], + "activationEvents": [ + "onResolveRemoteAuthority:spin" + ] +} diff --git a/test/unit/open.test.ts b/test/unit/open.test.ts index b92ccc1..cca1dc1 100644 --- a/test/unit/open.test.ts +++ b/test/unit/open.test.ts @@ -28,7 +28,11 @@ interface Seen { // progress as soon as it starts, as the notification's Cancel does. function setup( env: Record = {}, - opts: { cancel?: boolean; pick?: (ws: Workspace[]) => Workspace | undefined } = {}, + opts: { + cancel?: boolean + pick?: (ws: Workspace[]) => Workspace | undefined + spin?: boolean + } = {}, ): { deps: OpenDeps; seen: Seen } { const dir = mkdtempSync(join(tmpdir(), "open-")) const log = join(dir, "log") @@ -80,6 +84,7 @@ function setup( commit: async () => COMMIT, vscodeVersion: "1.120.0", trace: () => undefined, + spin: opts.spin === true, } return { deps, seen } } @@ -170,6 +175,78 @@ describe("openWorkspace", () => { expect(seen.opened).toEqual(["vscode-remote://ssh-remote+spin.my-ws/root"]) }) + it("through the resolver, runs the same spin code and opens its folder as spin+", async () => { + const { deps, seen } = setup({}, { spin: true }) + await openWorkspace(deps, { workspace: "ws-1", path: "/root/src" }) + expect(seen.invocations()).toEqual([ + [ + "code", + "ws-1", + "/root/src", + "--no-open", + "--vscode-commit", + COMMIT, + "--vscode-version", + "1.120.0", + "--start", + "-o", + "json", + ], + ]) + expect(seen.opened).toEqual(["vscode-remote://spin+my-ws/root"]) + expect(seen.errors).toEqual([]) + }) + + // The resolver downloads no server: it refuses the workspace itself, saying what to do, so a + // warning that VS Code downloads one would be untrue. + it("through the resolver, does not say VS Code downloads a server", async () => { + const { deps, seen } = setup( + { + FAKE_SPIN_SCENARIO: scenario({ + code: { + stdout: [ + { + workspace_id: "ws-1", + host: "spin.my-ws", + folder_uri: "vscode-remote://ssh-remote+spin.my-ws/root", + server: "missing", + not_given: "no server", + }, + ], + }, + }), + }, + { spin: true }, + ) + await openWorkspace(deps, { workspace: "ws-1" }) + expect(seen.warnings).toEqual([]) + expect(seen.opened).toEqual(["vscode-remote://spin+my-ws/root"]) + }) + + it("through the resolver, says so and opens nothing when spin names a host that is no workspace", async () => { + const { deps, seen } = setup( + { + FAKE_SPIN_SCENARIO: scenario({ + code: { + stdout: [ + { + workspace_id: "ws-1", + host: "devbox", + folder_uri: "vscode-remote://ssh-remote+devbox/root", + server: "carried", + }, + ], + }, + }), + }, + { spin: true }, + ) + await openWorkspace(deps, { workspace: "ws-1" }) + expect(seen.opened).toEqual([]) + expect(seen.errors).toHaveLength(1) + expect(seen.errors[0]).toContain("vscode-remote://ssh-remote+devbox/root") + }) + it("hands a failure to the errors module with a retry that runs it again, and opens nothing", async () => { const { deps, seen } = setup({ FAKE_SPIN_ERROR: "access_needs_signature" }) await openWorkspace(deps, { workspace: "ws-1" }) diff --git a/test/unit/resolver.test.ts b/test/unit/resolver.test.ts new file mode 100644 index 0000000..414bcb5 --- /dev/null +++ b/test/unit/resolver.test.ts @@ -0,0 +1,172 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" + +// The vscode API the modules reach: the installed extensions, each with its activation events and +// what its activation does, as a map the test controls. +const vscode = vi.hoisted(() => { + const installed = new Map< + string, + { packageJSON: { activationEvents: string[] }; activate: () => Promise } + >() + return { + installed, + env: { appName: "Visual Studio Code" }, + extensions: { + getExtension: (id: string) => installed.get(id), + onDidChange: () => ({ dispose: () => {} }), + }, + window: { + showInformationMessage: + vi.fn<(message: string, ...items: string[]) => Promise>(), + showWarningMessage: + vi.fn<(message: string, ...items: string[]) => Promise>(), + showErrorMessage: + vi.fn<(message: string, ...items: string[]) => Promise>(), + }, + commands: { + executeCommand: vi.fn<(command: string, ...args: unknown[]) => Promise>(), + }, + } +}) +vi.mock("vscode", () => vscode) + +import type { Memento } from "vscode" +import { MICROSOFT_REMOTE_SSH } from "../../src/remote/extension" +import { ENABLE_PROPOSED_API, openThrough, route, TOLD_KEY } from "../../src/remote/resolver" +import { SPIN_RESOLVER } from "../../src/status/authority" + +// The resolver, installed: one that answers spin+ unless events say otherwise, and whose +// activation rejects as it does when VS Code withholds the proposed API. +function installResolver( + opts: { events?: string[]; refused?: boolean } = {}, +): ReturnType { + const activate = vi.fn(async () => { + if (opts.refused === true) { + throw new Error("Extension 'spin-stack.open-remote-ssh' CANNOT use API proposal: resolvers.") + } + }) + vscode.installed.set(SPIN_RESOLVER, { + packageJSON: { + activationEvents: opts.events ?? [ + "onResolveRemoteAuthority:ssh-remote", + "onResolveRemoteAuthority:spin", + ], + }, + activate, + }) + return activate +} + +function memento(): Memento & { values: Map } { + const values = new Map() + return { + values, + keys: () => [...values.keys()], + get: (key: string, fallback?: T) => (values.has(key) ? (values.get(key) as T) : fallback), + update: async (key: string, value: unknown) => { + values.set(key, value) + }, + } as Memento & { values: Map } +} + +beforeEach(() => { + vscode.installed.clear() + vscode.window.showInformationMessage.mockReset() + vscode.window.showWarningMessage.mockReset() + vscode.window.showErrorMessage.mockReset() + vscode.commands.executeCommand.mockReset() +}) + +describe("route", () => { + it("goes through the resolver once it activates", async () => { + const activate = installResolver() + expect(await route()).toEqual({ spin: true }) + expect(activate).toHaveBeenCalledOnce() + }) + + it("falls back when the resolver is not installed", async () => { + expect(await route()).toEqual({ spin: false, because: "missing" }) + }) + + // A build of open-remote-ssh from before the resolver activates fine and answers no spin+. + it("falls back, without activating it, when the build installed answers no spin+", async () => { + const activate = installResolver({ events: ["onResolveRemoteAuthority:ssh-remote"] }) + expect(await route()).toEqual({ spin: false, because: "missing" }) + expect(activate).not.toHaveBeenCalled() + }) + + it("falls back when VS Code does not let the resolver activate", async () => { + installResolver({ refused: true }) + expect(await route()).toEqual({ spin: false, because: "disabled" }) + }) +}) + +describe("openThrough", () => { + it("opens through the resolver without asking for Remote-SSH or telling anything", async () => { + installResolver() + const state = memento() + expect(await openThrough(state)).toBe(true) + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() + expect(state.values.size).toBe(0) + }) + + it("opens over Remote-SSH and says, with the exact argv.json line, what the resolver needs", async () => { + installResolver({ refused: true }) + vscode.installed.set(MICROSOFT_REMOTE_SSH, { + packageJSON: { activationEvents: [] }, + activate: async () => {}, + }) + vscode.window.showInformationMessage.mockResolvedValue(undefined) + expect(await openThrough(memento())).toBe(false) + expect(vscode.window.showInformationMessage).toHaveBeenCalledOnce() + const [message] = vscode.window.showInformationMessage.mock.calls[0] ?? [] + expect(ENABLE_PROPOSED_API).toBe('"enable-proposed-api": ["spin-stack.open-remote-ssh"]') + expect(message).toContain(ENABLE_PROPOSED_API) + expect(message).toContain("does not let") + }) + + it("tells each reason once", async () => { + vscode.installed.set(MICROSOFT_REMOTE_SSH, { + packageJSON: { activationEvents: [] }, + activate: async () => {}, + }) + vscode.window.showInformationMessage.mockResolvedValue(undefined) + const state = memento() + await openThrough(state) + await openThrough(state) + expect(vscode.window.showInformationMessage).toHaveBeenCalledOnce() + expect(vscode.window.showInformationMessage.mock.calls[0]?.[0]).toContain( + `install ${SPIN_RESOLVER}`, + ) + expect(state.values.get(TOLD_KEY)).toBe("missing") + + // Installed since, and held back by VS Code: a new reason, told once too. + installResolver({ refused: true }) + await openThrough(state) + await openThrough(state) + expect(vscode.window.showInformationMessage).toHaveBeenCalledTimes(2) + expect(state.values.get(TOLD_KEY)).toBe("disabled") + }) + + it("opens argv.json when the person asks", async () => { + vscode.installed.set(MICROSOFT_REMOTE_SSH, { + packageJSON: { activationEvents: [] }, + activate: async () => {}, + }) + vscode.window.showInformationMessage.mockImplementation(async (_m, ...items) => items[0]) + await openThrough(memento()) + await vi.waitFor(() => + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "workbench.action.configureRuntimeArguments", + ), + ) + }) + + it("opens nothing, and tells nothing, when there is no resolver and no Remote-SSH is installed", async () => { + vscode.window.showWarningMessage.mockResolvedValue(undefined) + const state = memento() + expect(await openThrough(state)).toBeUndefined() + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() + expect(state.values.size).toBe(0) + }) +}) diff --git a/test/unit/status-authority.test.ts b/test/unit/status-authority.test.ts index ef3a7b1..a65e6b4 100644 --- a/test/unit/status-authority.test.ts +++ b/test/unit/status-authority.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest" -import { parseSpinRemote } from "../../src/status/authority" +import { parseSpinRemote, spinFolderUri } from "../../src/status/authority" const hex = (host: string) => Buffer.from(JSON.stringify({ hostName: host })).toString("hex") @@ -18,7 +18,18 @@ describe("parseSpinRemote", () => { }) }) + it("reads the workspace from the resolver's authority spin+", () => { + expect(parseSpinRemote("spin", "spin+My_WS")).toEqual({ + host: "spin.My_WS", + workspace: "My_WS", + }) + }) + it.each([ + ["a resolver's workspace that is a flag", "spin", "spin+-oProxyCommand"], + ["a resolver's authority with no workspace", "spin", "spin+"], + ["a resolver's workspace with a dot", "spin", "spin+my-ws.example.com"], + ["the resolver's authority under Remote-SSH", "ssh-remote", "spin+my-ws"], ["another remote", "wsl", "ssh-remote+spin.my-ws"], ["a local window", undefined, undefined], ["no folder", "ssh-remote", undefined], @@ -32,3 +43,23 @@ describe("parseSpinRemote", () => { expect(parseSpinRemote(remoteName, authority)).toBeUndefined() }) }) + +describe("spinFolderUri", () => { + it.each([ + ["vscode-remote://ssh-remote+spin.my-ws/root/src", "vscode-remote://spin+my-ws/root/src"], + [`vscode-remote://ssh-remote+${hex("spin.My_WS")}/root`, "vscode-remote://spin+My_WS/root"], + ["vscode-remote://ssh-remote+spin.my-ws", "vscode-remote://spin+my-ws/"], + ])("opens %s as %s", (folder, want) => { + expect(spinFolderUri(folder)).toBe(want) + }) + + it.each([ + ["another host", "vscode-remote://ssh-remote+devbox/root"], + ["a host under spin's", "vscode-remote://ssh-remote+spin.my-ws.example.com/root"], + ["a flag", "vscode-remote://ssh-remote+spin.-oProxyCommand/root"], + ["another remote", "vscode-remote://wsl+spin.my-ws/root"], + ["a local folder", "file:///root"], + ])("is nothing for %s", (_what, folder) => { + expect(spinFolderUri(folder)).toBeUndefined() + }) +}) diff --git a/test/unit/telemetry.test.ts b/test/unit/telemetry.test.ts index 00a6d4c..a5a0065 100644 --- a/test/unit/telemetry.test.ts +++ b/test/unit/telemetry.test.ts @@ -64,6 +64,7 @@ function openDeps(cli: ProcessSpinCli, enabled: boolean): OpenDeps { commit: async () => "a".repeat(40), vscodeVersion: "1.120.0", trace: tracer(() => enabled), + spin: false, } } diff --git a/versions.yaml b/versions.yaml index 98e5120..594875e 100644 --- a/versions.yaml +++ b/versions.yaml @@ -40,3 +40,16 @@ note: >- The Task `go tool task` runs (go-tools' cmd/task), for every platform a person or a runner works on: no repository compiles it. + +- name: vscode + kind: git + source: https://github.com/microsoft/vscode + version: 1.145.2 + pin: c4453f8ea430795f941c1b2ff6c9321135a74a02 + track: github-release + note: >- + The VS Code stable test:integration checks the resolver's detection against + (test/integration/run.mjs), downloaded by @vscode/test-electron. It has to be a release that + withholds a proposed API from an extension argv.json does not name: up to at least 1.128, + isProposedApiEnabled answered true for any extension that declared one, so the stand-in + activates either way and the run without the flag fails. A bump is test:integration green.