From 35f7496d3fdbc92003495f2209d1c0604f921766 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Thu, 12 Nov 2026 18:40:01 -0300 Subject: [PATCH 1/2] Ready a Spinbox workspace before Remote-SSH connects to it Spinbox activates on onResolveRemoteAuthority:ssh-remote, which VS Code waits for before Remote-SSH resolves, as Coder's extension does. For a window whose folder is ssh-remote+spin. - a reload, a reconnect, a recent folder - it runs `spin code --start` under a progress notification: the workspace started, this VS Code's server attached, the ssh config written, and one connection made through it, which runs ssh-prepare and its launch-claim check. A failure is the CLI's error with its action (add a key, sign in, start); unless its retry succeeds, the window leaves the remote (workbench.action.remote.close), so Remote-SSH does not fail its own way. Then it reads spin ssh-proxy's status file of the connection while Remote-SSH connects: each step in the status bar, and a failure shown with its action, closing the remote. The file is being built in spin; its layout here is provisional, behind ProxyStatusSource, and tested with fixtures. The authority is read from the window's folder: env.remoteAuthority is the resolvers proposal's. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++ package.json | 1 + src/extension.ts | 6 +- src/remote/connect.ts | 81 +++++++++++++++++++++++ src/remote/index.ts | 86 +++++++++++++++++++++++++ src/remote/proxy.ts | 113 ++++++++++++++++++++++++++++++++ test/unit/connect.test.ts | 129 +++++++++++++++++++++++++++++++++++++ test/unit/manifest.test.ts | 5 ++ test/unit/proxy.test.ts | 95 +++++++++++++++++++++++++++ 9 files changed, 519 insertions(+), 1 deletion(-) create mode 100644 src/remote/connect.ts create mode 100644 src/remote/index.ts create mode 100644 src/remote/proxy.ts create mode 100644 test/unit/connect.test.ts create mode 100644 test/unit/proxy.test.ts diff --git a/README.md b/README.md index ab5d09c..bbc4417 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,10 @@ and Spinbox says once what is missing. Sign Out, under **Spinbox** in the Command Palette. - **Links**: `vscode://spin-stack.spinbox/open?workspace=` opens a workspace from a browser, and `&path=` a folder inside it. +- **Reconnects that start the workspace**: a window reopening a workspace over Remote-SSH, by a + reload or from the recent list, has Spinbox start it and attach your VS Code's server first; a + refusal is shown with what fixes it, and the window leaves the remote instead of Remote-SSH + failing on its own. - **Errors you can act on**: an outdated CLI, a missing SSH key or no room for a workspace each say what fixes it, with a button for it where there is one. diff --git a/package.json b/package.json index 9e7c6a5..69fc95f 100644 --- a/package.json +++ b/package.json @@ -49,6 +49,7 @@ "main": "./dist/extension.js", "activationEvents": [ "onStartupFinished", + "onResolveRemoteAuthority:ssh-remote", "onUri", "onCommand:spinbox.openWorkspace", "onCommand:spinbox.signIn", diff --git a/src/extension.ts b/src/extension.ts index e53d6a4..7ba98d4 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -3,10 +3,13 @@ import { registerAuth } from "./auth" import { createSpin } from "./cli/vscode" import { configureErrors } from "./errors" import { registerOpen } from "./open" +import { connectWindow } from "./remote" import { registerStatus } from "./status" import { registerViews } from "./views" -export function activate(context: vscode.ExtensionContext): void { +// activate resolves once a window connecting to a Spinbox workspace over Remote-SSH has it ready: +// VS Code waits for it before Remote-SSH resolves (src/remote/connect.ts). +export async function activate(context: vscode.ExtensionContext): Promise { const spin = createSpin(context) configureErrors({ cli: spin.cli, @@ -20,6 +23,7 @@ export function activate(context: vscode.ExtensionContext): void { // Signing in or out from the Accounts menu changes what the view lists. context.subscriptions.push(auth.onDidChangeSessions(() => void tree.refresh())) registerStatus(context, spin.cli) + await connectWindow(spin.cli) } export function deactivate(): void {} diff --git a/src/remote/connect.ts b/src/remote/connect.ts new file mode 100644 index 0000000..a6bc3af --- /dev/null +++ b/src/remote/connect.ts @@ -0,0 +1,81 @@ +import type { SpinCli } from "../cli/client" +import { parseSpinRemote } from "../status/authority" +import type { Trace } from "../telemetry" + +// Remote-SSH connects a window to ssh-remote+spin. by itself: on a reconnect, a reload +// or a recent folder, nothing of Spinbox's ran first, and a stopped workspace or a refused key is +// an opaque Remote-SSH error. So Spinbox activates on onResolveRemoteAuthority:ssh-remote, which +// VS Code waits for before Remote-SSH resolves, and readies the workspace first, as Coder's +// extension does (coder/vscode-coder docs/ARCHITECTURE.md): `spin code --start` starts it, +// attaches this VS Code's server, writes the ssh config, and connects once through it - which runs +// `spin ssh-prepare` and its launch-claim check - so a refusal is the CLI's error, with its action, +// here. A failure closes the remote, so Remote-SSH does not go on to fail its own way. + +export type ConnectCli = Pick + +export interface ConnectUi { + // Runs task under a cancelable notification, as OpenUi's progress. + progress( + title: string, + task: (signal: AbortSignal, report: (message: string) => void) => Promise, + ): Promise + // The CLI's failure with its action, resolving once it is answered and the action has run. + showCliError(error: unknown, retry: () => Promise): Promise + // workbench.action.remote.close: the window leaves the remote it was connecting to. + closeRemote(): Promise +} + +export interface ConnectDeps { + cli: ConnectCli + ui: ConnectUi + commit(): Promise + vscodeVersion: string + trace: Trace +} + +// prepareConnection readies the workspace this window is resolving over Remote-SSH. It answers +// undefined for an authority that is no Spinbox workspace, having done nothing; true when Remote-SSH +// may connect; false when it closed the remote: the open failed and its retry did not take, or the +// person cancelled. +export async function prepareConnection( + deps: ConnectDeps, + remoteName: string | undefined, + authority: string | undefined, +): Promise { + const remote = remoteName === "ssh-remote" ? parseSpinRemote(remoteName, authority) : undefined + if (remote === undefined) { + return undefined + } + let ready = false + const attempt = async (): Promise => { + const commit = await deps.commit() + const traceparent = deps.trace() + ready = await deps.ui.progress(`Connecting to ${remote.workspace}`, async (signal, report) => { + try { + await deps.cli.code(remote.workspace, undefined, commit, { + start: true, + vscodeVersion: deps.vscodeVersion, + signal, + traceparent, + onPreparing: (p) => + report(`Preparing VS Code ${p.vscode_version} for this installation (once): ${p.step}`), + }) + return true + } catch (err) { + if (signal.aborted) { + return false + } + throw err + } + }) + } + try { + await attempt() + } catch (err) { + await deps.ui.showCliError(err, attempt) + } + if (!ready) { + await deps.ui.closeRemote() + } + return ready +} diff --git a/src/remote/index.ts b/src/remote/index.ts new file mode 100644 index 0000000..9f67b6b --- /dev/null +++ b/src/remote/index.ts @@ -0,0 +1,86 @@ +import { homedir } from "node:os" +import { join } from "node:path" +import * as vscode from "vscode" +import { CliError } from "../cli/client" +import { showCliError } from "../errors" +import { readCommit } from "../open/editor" +import { parseSpinRemote } from "../status/authority" +import { trace } from "../telemetry/vscode" +import { type ConnectCli, prepareConnection } from "./connect" +import { fileProxyStatus, type ProxyStatus, watchProxy } from "./proxy" + +export const CLOSE_REMOTE = "workbench.action.remote.close" + +// How often, and how long, the proxy's status is read while Remote-SSH connects. +const PROXY_INTERVAL_MS = 1_000 +const PROXY_TIMEOUT_MS = 120_000 + +const closeRemote = async (): Promise => { + await vscode.commands.executeCommand(CLOSE_REMOTE) +} + +// connectWindow readies the Spinbox workspace this window is resolving over Remote-SSH, if it is +// one (connect.ts), and then follows the connection Remote-SSH makes (proxy.ts). Activation waits +// on it, and Remote-SSH on activation, so it returns before following. +export async function connectWindow(cli: ConnectCli): Promise { + // The window's folder names the authority it resolves: env.remoteAuthority is the resolvers + // proposal's, which this extension does not have. + const authority = (vscode.workspace.workspaceFolders?.[0]?.uri ?? vscode.workspace.workspaceFile) + ?.authority + const since = Date.now() + const ready = await prepareConnection( + { + cli, + ui: { + progress: (title, task) => + Promise.resolve( + vscode.window.withProgress( + { location: vscode.ProgressLocation.Notification, title, cancellable: true }, + (progress, token) => { + const abort = new AbortController() + token.onCancellationRequested(() => abort.abort()) + return task(abort.signal, (message) => progress.report({ message })) + }, + ), + ), + showCliError, + closeRemote, + }, + commit: () => readCommit(vscode.env.appRoot), + vscodeVersion: vscode.version, + trace, + }, + vscode.env.remoteName, + authority, + ) + const remote = parseSpinRemote(vscode.env.remoteName, authority) + if (ready === true && remote !== undefined) { + void followProxy(join(homedir(), ".spin", "ssh", "hosts", remote.host), since) + } +} + +async function followProxy(dir: string, since: number): Promise { + let said: vscode.Disposable | undefined + const status = await watchProxy(fileProxyStatus(dir, since), { + intervalMs: PROXY_INTERVAL_MS, + timeoutMs: PROXY_TIMEOUT_MS, + report: (message) => { + said?.dispose() + said = vscode.window.setStatusBarMessage(`$(sync~spin) Spinbox: ${message}`) + }, + }) + said?.dispose() + if (status?.state === "failed") { + await showProxyFailure(status) + await closeRemote() + } +} + +// A failure the CLI has a code for is shown with its action; any other with what it said. +async function showProxyFailure(status: ProxyStatus): Promise { + if (status.error !== undefined) { + await showCliError(new CliError({ error: status.error })) + return + } + await vscode.window.showErrorMessage(`Spinbox could not connect: ${status.message}`) +} diff --git a/src/remote/proxy.ts b/src/remote/proxy.ts new file mode 100644 index 0000000..19ef633 --- /dev/null +++ b/src/remote/proxy.ts @@ -0,0 +1,113 @@ +import { readdir, readFile, stat } from "node:fs/promises" +import { join } from "node:path" +import { type ErrorEnvelope, isErrorEnvelope } from "../cli/contract" + +// While Remote-SSH connects, `spin ssh-proxy` carries the connection, and writes what happens to +// it - connecting, connected, or why it failed - to a status file of that connection. Spinbox reads +// it, says each step under the connecting notification, and shows a failure with what resolves it, +// where Remote-SSH would show only that ssh exited. +// +// The file is spin's (branch ssh-proxy-status): its layout and schema here are provisional until +// that lands, and change in readProxyStatus and fileProxyStatus alone. + +export type ProxyState = "connecting" | "connected" | "failed" + +export interface ProxyStatus { + state: ProxyState + // What is happening, or what failed, as the person reads it. + message: string + // A failure the CLI has a code for, with its action. + error?: ErrorEnvelope["error"] +} + +export interface ProxyStatusSource { + // The status of the connection being made, or undefined while there is none to read. + read(): Promise +} + +const STATES: readonly ProxyState[] = ["connecting", "connected", "failed"] + +// readProxyStatus parses one status file's body, or answers undefined for one that is not a +// status - half written, or another file. +export function readProxyStatus(body: string): ProxyStatus | undefined { + let v: unknown + try { + v = JSON.parse(body) + } catch { + return undefined + } + if (typeof v !== "object" || v === null) { + return undefined + } + const { state, message } = v as { state?: unknown; message?: unknown } + if (!STATES.includes(state as ProxyState) || typeof message !== "string") { + return undefined + } + const status: ProxyStatus = { state: state as ProxyState, message } + if (isErrorEnvelope(v)) { + status.error = v.error + } + return status +} + +// fileProxyStatus reads the newest *.status file in dir - ~/.spin/ssh/hosts//, where +// ssh-prepare leaves its session - written at or after since, so a connection made before this one +// is never read as its. +export function fileProxyStatus(dir: string, since: number): ProxyStatusSource { + return { + read: async () => { + let names: string[] + try { + names = (await readdir(dir)).filter((n) => n.endsWith(".status")) + } catch { + return undefined + } + let newest: { at: number; path: string } | undefined + for (const name of names) { + const path = join(dir, name) + const at = (await stat(path).catch(() => undefined))?.mtimeMs + if (at !== undefined && at >= since && (newest === undefined || at > newest.at)) { + newest = { at, path } + } + } + if (newest === undefined) { + return undefined + } + return readProxyStatus(await readFile(newest.path, "utf8").catch(() => "")) + }, + } +} + +export interface WatchOptions { + intervalMs: number + // How long to read before giving up quietly: Remote-SSH says by then what it has. + timeoutMs: number + // Hears each new message while connecting. + report(message: string): void + signal?: AbortSignal +} + +// watchProxy reads source every intervalMs until it says connected or failed, and answers that +// status; or undefined at timeoutMs, or once signal aborts. +export async function watchProxy( + source: ProxyStatusSource, + opts: WatchOptions, +): Promise { + const end = Date.now() + opts.timeoutMs + let said: string | undefined + while (opts.signal?.aborted !== true) { + const status = await source.read() + if (status !== undefined && status.state !== "connecting") { + return status + } + if (status !== undefined && status.message !== said) { + said = status.message + opts.report(status.message) + } + if (Date.now() >= end) { + return undefined + } + await new Promise((resolve) => setTimeout(resolve, opts.intervalMs)) + } + return undefined +} diff --git a/test/unit/connect.test.ts b/test/unit/connect.test.ts new file mode 100644 index 0000000..2624456 --- /dev/null +++ b/test/unit/connect.test.ts @@ -0,0 +1,129 @@ +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { afterEach, describe, expect, it, vi } from "vitest" +import { type CliError, ProcessSpinCli } from "../../src/cli/client" +import { type ConnectDeps, prepareConnection } from "../../src/remote/connect" +import { FAKE_SPIN } from "./fake-spin" + +const COMMIT = "c".repeat(40) + +afterEach(() => { + vi.unstubAllEnvs() +}) + +interface Seen { + closed: number + errors: unknown[] + reported: string[] + invocations(): string[][] +} + +// setup runs the fake spin with env, and records what the UI was asked to do. answer is what the +// person does with a shown error: nothing, or run its retry, which the test arranges to succeed. +function setup( + env: Record = {}, + opts: { cancel?: boolean; retryWith?: Record } = {}, +): { deps: ConnectDeps; seen: Seen } { + const log = join(mkdtempSync(join(tmpdir(), "connect-")), "log") + writeFileSync(log, "") + for (const [k, v] of Object.entries({ FAKE_SPIN_LOG: log, ...env })) { + vi.stubEnv(k, v) + } + const seen: Seen = { + closed: 0, + errors: [], + reported: [], + invocations: () => + readFileSync(log, "utf8") + .split("\n") + .filter((l) => l !== "") + .map((l) => JSON.parse(l) as string[]), + } + const deps: ConnectDeps = { + cli: new ProcessSpinCli({ binary: () => Promise.resolve(FAKE_SPIN), log: () => {} }), + ui: { + progress: (_title, task) => { + const abort = new AbortController() + if (opts.cancel === true) { + setTimeout(() => abort.abort(), 50) + } + return task(abort.signal, (m) => seen.reported.push(m)) + }, + showCliError: async (error, retry) => { + seen.errors.push(error) + if (opts.retryWith !== undefined) { + vi.unstubAllEnvs() + for (const [k, v] of Object.entries({ FAKE_SPIN_LOG: log, ...opts.retryWith })) { + vi.stubEnv(k, v) + } + await retry().catch(() => undefined) + } + }, + closeRemote: async () => { + seen.closed++ + }, + }, + commit: async () => COMMIT, + vscodeVersion: "1.146.0", + trace: () => undefined, + } + return { deps, seen } +} + +describe("prepareConnection", () => { + it("starts the workspace with this VS Code's server before Remote-SSH connects", async () => { + const { deps, seen } = setup() + expect(await prepareConnection(deps, "ssh-remote", "ssh-remote+spin.my-ws")).toBe(true) + expect(seen.invocations()).toEqual([ + [ + "code", + "my-ws", + "--no-open", + "--vscode-commit", + COMMIT, + "--vscode-version", + "1.146.0", + "--start", + "-o", + "json", + ], + ]) + expect(seen.closed).toBe(0) + }) + + it.each([ + ["another host", "ssh-remote", "ssh-remote+devbox"], + ["a local window", undefined, undefined], + ["Spinbox Remote's authority, which resolves itself", "spin", "spin+my-ws"], + ])("does nothing for %s", async (_what, remoteName, authority) => { + const { deps, seen } = setup() + expect(await prepareConnection(deps, remoteName, authority)).toBeUndefined() + expect(seen.invocations()).toEqual([]) + expect(seen.closed).toBe(0) + }) + + it("shows a refusal with its action, then closes the remote", async () => { + const { deps, seen } = setup({ FAKE_SPIN_ERROR: "no_key_held" }) + expect(await prepareConnection(deps, "ssh-remote", "ssh-remote+spin.my-ws")).toBe(false) + expect(seen.errors).toHaveLength(1) + expect((seen.errors[0] as CliError).code).toBe("no_key_held") + expect(seen.closed).toBe(1) + }) + + it("lets Remote-SSH go on when the error's retry succeeds", async () => { + const { deps, seen } = setup({ FAKE_SPIN_ERROR: "not_signed_in" }, { retryWith: {} }) + expect(await prepareConnection(deps, "ssh-remote", "ssh-remote+spin.my-ws")).toBe(true) + expect(seen.invocations()).toHaveLength(2) + expect(seen.closed).toBe(0) + }) + + it("closes the remote when the person cancels", async () => { + const file = join(mkdtempSync(join(tmpdir(), "connect-scenario-")), "scenario.json") + writeFileSync(file, JSON.stringify({ code: { stdout: [{}], delayMs: 10_000 } })) + const { deps, seen } = setup({ FAKE_SPIN_SCENARIO: file }, { cancel: true }) + expect(await prepareConnection(deps, "ssh-remote", "ssh-remote+spin.my-ws")).toBe(false) + expect(seen.errors).toEqual([]) + expect(seen.closed).toBe(1) + }) +}) diff --git a/test/unit/manifest.test.ts b/test/unit/manifest.test.ts index 80f093e..9591e1e 100644 --- a/test/unit/manifest.test.ts +++ b/test/unit/manifest.test.ts @@ -12,4 +12,9 @@ describe("package.json", () => { expect(manifest.activationEvents).toContain(`onCommand:${id}`) } }) + + // VS Code waits for this activation before Remote-SSH resolves (src/remote/connect.ts). + it("activates when a window resolves over Remote-SSH", () => { + expect(manifest.activationEvents).toContain("onResolveRemoteAuthority:ssh-remote") + }) }) diff --git a/test/unit/proxy.test.ts b/test/unit/proxy.test.ts new file mode 100644 index 0000000..f1cd3ba --- /dev/null +++ b/test/unit/proxy.test.ts @@ -0,0 +1,95 @@ +import { mkdtempSync, utimesSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { describe, expect, it } from "vitest" +import { + fileProxyStatus, + type ProxyStatus, + type ProxyStatusSource, + readProxyStatus, + watchProxy, +} from "../../src/remote/proxy" + +// A source that answers each status in turn, then the last one again. +function fixture(...statuses: (ProxyStatus | undefined)[]): ProxyStatusSource { + let i = 0 + return { read: async () => statuses[Math.min(i++, statuses.length - 1)] } +} + +const connecting = (message: string): ProxyStatus => ({ state: "connecting", message }) + +describe("readProxyStatus", () => { + it("reads a failure with the CLI's error", () => { + const body = JSON.stringify({ + state: "failed", + message: "refused", + error: { code: "no_key_held", action: "add_key", message: "no key" }, + }) + expect(readProxyStatus(body)).toEqual({ + state: "failed", + message: "refused", + error: { code: "no_key_held", action: "add_key", message: "no key" }, + }) + }) + + it.each([ + ["half written", '{"state": "conn'], + ["an unknown state", JSON.stringify({ state: "maybe", message: "x" })], + ["no message", JSON.stringify({ state: "connected" })], + ["not an object", "3"], + ])("is nothing for %s", (_what, body) => { + expect(readProxyStatus(body)).toBeUndefined() + }) +}) + +describe("fileProxyStatus", () => { + it("reads the newest status written since the connection began", async () => { + const dir = mkdtempSync(join(tmpdir(), "proxy-")) + const since = Date.now() + const write = (name: string, status: ProxyStatus, at: number) => { + writeFileSync(join(dir, name), JSON.stringify(status)) + utimesSync(join(dir, name), at / 1000, at / 1000) + } + write("100.status", { state: "failed", message: "an earlier connection" }, since - 60_000) + expect(await fileProxyStatus(dir, since).read()).toBeUndefined() + write("200.status", connecting("relay"), since + 1_000) + write("300.status", { state: "connected", message: "up" }, since + 2_000) + writeFileSync(join(dir, "300.tunnel"), "not a status") + expect(await fileProxyStatus(dir, since).read()).toEqual({ state: "connected", message: "up" }) + }) + + it("is nothing for a directory that is not there", async () => { + expect(await fileProxyStatus(join(tmpdir(), "no-such-dir-x"), 0).read()).toBeUndefined() + }) +}) + +describe("watchProxy", () => { + const opts = (said: string[]) => ({ + intervalMs: 1, + timeoutMs: 1_000, + report: (m: string) => said.push(m), + }) + + it("says each new step, and answers the failure", async () => { + const said: string[] = [] + const failed: ProxyStatus = { state: "failed", message: "refused" } + const got = await watchProxy( + fixture(undefined, connecting("relay"), connecting("relay"), connecting("sshd"), failed), + opts(said), + ) + expect(got).toEqual(failed) + expect(said).toEqual(["relay", "sshd"]) + }) + + it("answers connected", async () => { + const got = await watchProxy(fixture({ state: "connected", message: "up" }), opts([])) + expect(got?.state).toBe("connected") + }) + + it("gives up quietly when nothing is written", async () => { + const said: string[] = [] + const got = await watchProxy(fixture(undefined), { ...opts(said), timeoutMs: 20 }) + expect(got).toBeUndefined() + expect(said).toEqual([]) + }) +}) From 64872905eff7f2a400a88cb7419a8b4b994ae439 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Thu, 12 Nov 2026 18:50:19 -0300 Subject: [PATCH 2/2] Read ssh-proxy's status file as spin#1180 writes it ~/.spin/ssh/status/.json, version 1 (any other refused): phase resolving, connecting, connected, refused or failed, the host, and on a refusal the CLI's error envelope. Of the files there, the one last updated for the window's spin. whose connection began after spin code returned is this window's: spin code's own ssh, and the shared connection it leaves, began before. Resolving and connecting are said in the status bar once each; refused and failed are shown and close the remote - with the CLI's action when the contract knows the code, and otherwise its message and the page it names. Co-Authored-By: Claude Opus 5.5 --- src/remote/index.ts | 33 +++++--- src/remote/proxy.ts | 156 ++++++++++++++++++++++++++------------ test/unit/proxy.test.ts | 164 ++++++++++++++++++++++++++++++---------- 3 files changed, 252 insertions(+), 101 deletions(-) diff --git a/src/remote/index.ts b/src/remote/index.ts index 9f67b6b..7dbfde5 100644 --- a/src/remote/index.ts +++ b/src/remote/index.ts @@ -7,7 +7,7 @@ import { readCommit } from "../open/editor" import { parseSpinRemote } from "../status/authority" import { trace } from "../telemetry/vscode" import { type ConnectCli, prepareConnection } from "./connect" -import { fileProxyStatus, type ProxyStatus, watchProxy } from "./proxy" +import { fileProxyStatus, type ProxyFailure, proxyFailure, watchProxy } from "./proxy" export const CLOSE_REMOTE = "workbench.action.remote.close" @@ -27,7 +27,6 @@ export async function connectWindow(cli: ConnectCli): Promise { // proposal's, which this extension does not have. const authority = (vscode.workspace.workspaceFolders?.[0]?.uri ?? vscode.workspace.workspaceFile) ?.authority - const since = Date.now() const ready = await prepareConnection( { cli, @@ -55,13 +54,15 @@ export async function connectWindow(cli: ConnectCli): Promise { ) const remote = parseSpinRemote(vscode.env.remoteName, authority) if (ready === true && remote !== undefined) { - void followProxy(join(homedir(), ".spin", "ssh", "hosts", remote.host), since) + // From now: spin code's own ssh, and the shared connection it leaves, began before. + void followProxy(remote.host, Date.now()) } } -async function followProxy(dir: string, since: number): Promise { +async function followProxy(host: string, since: number): Promise { let said: vscode.Disposable | undefined - const status = await watchProxy(fileProxyStatus(dir, since), { + const dir = join(homedir(), ".spin", "ssh", "status") + const status = await watchProxy(fileProxyStatus(dir, host, since), { intervalMs: PROXY_INTERVAL_MS, timeoutMs: PROXY_TIMEOUT_MS, report: (message) => { @@ -70,17 +71,25 @@ async function followProxy(dir: string, since: number): Promise { }, }) said?.dispose() - if (status?.state === "failed") { - await showProxyFailure(status) + const failure = status === undefined ? undefined : proxyFailure(status) + if (failure !== undefined) { + await showProxyFailure(failure) await closeRemote() } } -// A failure the CLI has a code for is shown with its action; any other with what it said. -async function showProxyFailure(status: ProxyStatus): Promise { - if (status.error !== undefined) { - await showCliError(new CliError({ error: status.error })) +const OPEN = "Open" + +async function showProxyFailure(failure: ProxyFailure): Promise { + if ("envelope" in failure) { + await showCliError(new CliError(failure.envelope)) return } - await vscode.window.showErrorMessage(`Spinbox could not connect: ${status.message}`) + const pick = await vscode.window.showErrorMessage( + failure.message, + ...(failure.url === undefined ? [] : [OPEN]), + ) + if (pick === OPEN && failure.url !== undefined) { + await vscode.env.openExternal(vscode.Uri.parse(failure.url)) + } } diff --git a/src/remote/proxy.ts b/src/remote/proxy.ts index 19ef633..59fb675 100644 --- a/src/remote/proxy.ts +++ b/src/remote/proxy.ts @@ -1,23 +1,40 @@ -import { readdir, readFile, stat } from "node:fs/promises" +import { readdir, readFile } from "node:fs/promises" import { join } from "node:path" import { type ErrorEnvelope, isErrorEnvelope } from "../cli/contract" -// While Remote-SSH connects, `spin ssh-proxy` carries the connection, and writes what happens to -// it - connecting, connected, or why it failed - to a status file of that connection. Spinbox reads -// it, says each step under the connecting notification, and shows a failure with what resolves it, -// where Remote-SSH would show only that ssh exited. -// -// The file is spin's (branch ssh-proxy-status): its layout and schema here are provisional until -// that lands, and change in readProxyStatus and fileProxyStatus alone. +// While Remote-SSH connects, `spin ssh-prepare` and `spin ssh-proxy` - children of its ssh - write +// what happens to that connection to ~/.spin/ssh/status/.json (spin-stack/spin#1180), +// atomically. Spinbox reads it, says each phase, and shows a refusal with what resolves it, where +// Remote-SSH would show only that ssh exited. -export type ProxyState = "connecting" | "connected" | "failed" +export const STATUS_VERSION = 1 -export interface ProxyStatus { - state: ProxyState - // What is happening, or what failed, as the person reads it. +export type ProxyPhase = "resolving" | "connecting" | "connected" | "refused" | "failed" + +const PHASES: readonly ProxyPhase[] = ["resolving", "connecting", "connected", "refused", "failed"] + +// The CLI's -o json error envelope's error, as written: its code may be one this extension's +// contract does not know yet, so it is not narrowed to ErrorCode here. +export interface ProxyError { + code: string + action: string message: string - // A failure the CLI has a code for, with its action. - error?: ErrorEnvelope["error"] + release?: string + workspace_id?: string + url?: string +} + +export interface ProxyStatus { + version: typeof STATUS_VERSION + host: string + ssh_pid: number + phase: ProxyPhase + // ssh reuses an open connection, and no proxy runs. + shared?: boolean + workspace_id?: string + error?: ProxyError + started_at: string + updated_at: string } export interface ProxyStatusSource { @@ -25,10 +42,8 @@ export interface ProxyStatusSource { read(): Promise } -const STATES: readonly ProxyState[] = ["connecting", "connected", "failed"] - -// readProxyStatus parses one status file's body, or answers undefined for one that is not a -// status - half written, or another file. +// readProxyStatus parses one status file, or answers undefined for one that is not a status of +// the version this extension reads. export function readProxyStatus(body: string): ProxyStatus | undefined { let v: unknown try { @@ -39,70 +54,115 @@ export function readProxyStatus(body: string): ProxyStatus | undefined { if (typeof v !== "object" || v === null) { return undefined } - const { state, message } = v as { state?: unknown; message?: unknown } - if (!STATES.includes(state as ProxyState) || typeof message !== "string") { + const s = v as Record + if ( + s.version !== STATUS_VERSION || + typeof s.host !== "string" || + typeof s.ssh_pid !== "number" || + !PHASES.includes(s.phase as ProxyPhase) || + !isTime(s.started_at) || + !isTime(s.updated_at) || + (s.error !== undefined && !isProxyError(s.error)) + ) { return undefined } - const status: ProxyStatus = { state: state as ProxyState, message } - if (isErrorEnvelope(v)) { - status.error = v.error + return s as unknown as ProxyStatus +} + +function isTime(v: unknown): v is string { + return typeof v === "string" && !Number.isNaN(Date.parse(v)) +} + +function isProxyError(v: unknown): v is ProxyError { + if (typeof v !== "object" || v === null) { + return false } - return status + const e = v as Record + return typeof e.code === "string" && typeof e.action === "string" && typeof e.message === "string" } -// fileProxyStatus reads the newest *.status file in dir - ~/.spin/ssh/hosts//, where -// ssh-prepare leaves its session - written at or after since, so a connection made before this one -// is never read as its. -export function fileProxyStatus(dir: string, since: number): ProxyStatusSource { +// fileProxyStatus reads, of the status files in dir (~/.spin/ssh/status), the one last updated for +// host whose connection began at or after since: a connection to another workspace, or one made +// before this window's, is never read as its. +export function fileProxyStatus(dir: string, host: string, since: number): ProxyStatusSource { return { read: async () => { let names: string[] try { - names = (await readdir(dir)).filter((n) => n.endsWith(".status")) + names = (await readdir(dir)).filter((n) => n.endsWith(".json")) } catch { return undefined } - let newest: { at: number; path: string } | undefined + let newest: ProxyStatus | undefined for (const name of names) { - const path = join(dir, name) - const at = (await stat(path).catch(() => undefined))?.mtimeMs - if (at !== undefined && at >= since && (newest === undefined || at > newest.at)) { - newest = { at, path } + const s = readProxyStatus(await readFile(join(dir, name), "utf8").catch(() => "")) + if ( + s !== undefined && + s.host === host && + Date.parse(s.started_at) >= since && + (newest === undefined || Date.parse(s.updated_at) > Date.parse(newest.updated_at)) + ) { + newest = s } } - if (newest === undefined) { - return undefined - } - return readProxyStatus(await readFile(newest.path, "utf8").catch(() => "")) + return newest }, } } +// What a refused or failed connection shows: the CLI's error, with its action, when its code is one +// the contract knows; otherwise its message, and the page that resolves it when it names one. +export type ProxyFailure = { envelope: ErrorEnvelope } | { message: string; url?: string } + +export function proxyFailure(status: ProxyStatus): ProxyFailure | undefined { + if (status.phase !== "refused" && status.phase !== "failed") { + return undefined + } + const error = status.error + if (error === undefined) { + return { message: `Spinbox could not connect to ${status.host}.` } + } + const envelope = { error } + if (isErrorEnvelope(envelope)) { + return { envelope } + } + const message = `Spinbox could not connect to ${status.host}: ${error.message}` + return error.url === undefined ? { message } : { message, url: error.url } +} + +// What each phase on the way says, as the person reads it. +export const SAYS: Record<"resolving" | "connecting", string> = { + resolving: "finding the workspace", + connecting: "connecting to the workspace", +} + export interface WatchOptions { intervalMs: number // How long to read before giving up quietly: Remote-SSH says by then what it has. timeoutMs: number - // Hears each new message while connecting. + // Hears each phase on the way, once. report(message: string): void signal?: AbortSignal } -// watchProxy reads source every intervalMs until it says connected or failed, and answers that -// status; or undefined at timeoutMs, or once signal aborts. +// watchProxy reads source every intervalMs until it is connected, refused or failed, and answers +// that status; or undefined at timeoutMs, or once signal aborts. export async function watchProxy( source: ProxyStatusSource, opts: WatchOptions, ): Promise { const end = Date.now() + opts.timeoutMs - let said: string | undefined + let said: ProxyPhase | undefined while (opts.signal?.aborted !== true) { const status = await source.read() - if (status !== undefined && status.state !== "connecting") { - return status - } - if (status !== undefined && status.message !== said) { - said = status.message - opts.report(status.message) + if (status !== undefined) { + if (status.phase !== "resolving" && status.phase !== "connecting") { + return status + } + if (status.phase !== said) { + said = status.phase + opts.report(SAYS[status.phase]) + } } if (Date.now() >= end) { return undefined diff --git a/test/unit/proxy.test.ts b/test/unit/proxy.test.ts index f1cd3ba..e9380bd 100644 --- a/test/unit/proxy.test.ts +++ b/test/unit/proxy.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, utimesSync, writeFileSync } from "node:fs" +import { mkdtempSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" import { describe, expect, it } from "vitest" @@ -6,60 +6,137 @@ import { fileProxyStatus, type ProxyStatus, type ProxyStatusSource, + proxyFailure, readProxyStatus, + SAYS, watchProxy, } from "../../src/remote/proxy" +const HOST = "spin.my-ws" +const T0 = Date.parse("2026-11-12T22:00:00Z") +const at = (ms: number) => new Date(T0 + ms).toISOString() + +// A status file as spin#1180 writes it, version 1: shared, workspace_id and error left out when +// they have no value. +function status(phase: ProxyStatus["phase"], o: Partial = {}): ProxyStatus { + return { + version: 1, + host: HOST, + ssh_pid: 4242, + phase, + started_at: at(0), + updated_at: at(1), + ...o, + } +} + +const KEY_NOT_ENROLLED = { + code: "key_not_enrolled", + message: "this machine's key is not enrolled", + action: "add_key", + url: "https://app.spinbox.test/settings/keys", +} + // A source that answers each status in turn, then the last one again. function fixture(...statuses: (ProxyStatus | undefined)[]): ProxyStatusSource { let i = 0 return { read: async () => statuses[Math.min(i++, statuses.length - 1)] } } -const connecting = (message: string): ProxyStatus => ({ state: "connecting", message }) - describe("readProxyStatus", () => { - it("reads a failure with the CLI's error", () => { + it("reads a refusal with the CLI's error envelope", () => { const body = JSON.stringify({ - state: "failed", - message: "refused", - error: { code: "no_key_held", action: "add_key", message: "no key" }, - }) - expect(readProxyStatus(body)).toEqual({ - state: "failed", - message: "refused", - error: { code: "no_key_held", action: "add_key", message: "no key" }, + version: 1, + host: HOST, + ssh_pid: 4242, + phase: "refused", + workspace_id: "ws-1", + error: KEY_NOT_ENROLLED, + started_at: "2026-11-12T22:00:00.123456789Z", + updated_at: "2026-11-12T22:00:01.5Z", }) + expect(readProxyStatus(body)?.error).toEqual(KEY_NOT_ENROLLED) + }) + + it("reads a shared connection", () => { + expect(readProxyStatus(JSON.stringify(status("connected", { shared: true })))).toEqual( + status("connected", { shared: true }), + ) }) it.each([ - ["half written", '{"state": "conn'], - ["an unknown state", JSON.stringify({ state: "maybe", message: "x" })], - ["no message", JSON.stringify({ state: "connected" })], - ["not an object", "3"], - ])("is nothing for %s", (_what, body) => { - expect(readProxyStatus(body)).toBeUndefined() + ["another version", { ...status("connected"), version: 2 }], + ["no version", { ...status("connected"), version: undefined }], + ["an unknown phase", { ...status("connected"), phase: "maybe" }], + ["no host", { ...status("connected"), host: undefined }], + ["no pid", { ...status("connected"), ssh_pid: "4242" }], + ["a time that is no time", { ...status("connected"), updated_at: "soon" }], + ["an error that is no envelope", { ...status("refused"), error: { code: "x" } }], + ])("is nothing for %s", (_what, v) => { + expect(readProxyStatus(JSON.stringify(v))).toBeUndefined() + }) + + it("is nothing for a file that is not JSON", () => { + expect(readProxyStatus('{"version": 1, "ho')).toBeUndefined() }) }) describe("fileProxyStatus", () => { - it("reads the newest status written since the connection began", async () => { - const dir = mkdtempSync(join(tmpdir(), "proxy-")) - const since = Date.now() - const write = (name: string, status: ProxyStatus, at: number) => { - writeFileSync(join(dir, name), JSON.stringify(status)) - utimesSync(join(dir, name), at / 1000, at / 1000) + function dir(files: Record): string { + const d = mkdtempSync(join(tmpdir(), "proxy-status-")) + for (const [name, v] of Object.entries(files)) { + writeFileSync(join(d, name), typeof v === "string" ? v : JSON.stringify(v)) } - write("100.status", { state: "failed", message: "an earlier connection" }, since - 60_000) - expect(await fileProxyStatus(dir, since).read()).toBeUndefined() - write("200.status", connecting("relay"), since + 1_000) - write("300.status", { state: "connected", message: "up" }, since + 2_000) - writeFileSync(join(dir, "300.tunnel"), "not a status") - expect(await fileProxyStatus(dir, since).read()).toEqual({ state: "connected", message: "up" }) + return d + } + + it("reads the window's host's connection, last updated, begun since the window began", async () => { + const d = dir({ + "100.json": status("failed", { + ssh_pid: 100, + started_at: at(-60_000), + updated_at: at(-59_000), + }), + "200.json": status("connected", { ssh_pid: 200, host: "spin.other", updated_at: at(9_000) }), + "300.json": status("resolving", { ssh_pid: 300, updated_at: at(1_000) }), + "400.json": status("connecting", { ssh_pid: 400, updated_at: at(2_000) }), + "500.json": { ...status("connected", { ssh_pid: 500, updated_at: at(8_000) }), version: 2 }, + "notes.txt": "not a status", + }) + expect((await fileProxyStatus(d, HOST, T0).read())?.ssh_pid).toBe(400) + }) + + it("is nothing before any connection of the host is written", async () => { + const d = dir({ "100.json": status("failed", { started_at: at(-1) }) }) + expect(await fileProxyStatus(d, HOST, T0).read()).toBeUndefined() }) it("is nothing for a directory that is not there", async () => { - expect(await fileProxyStatus(join(tmpdir(), "no-such-dir-x"), 0).read()).toBeUndefined() + expect(await fileProxyStatus(join(tmpdir(), "no-such-status"), HOST, 0).read()).toBeUndefined() + }) +}) + +describe("proxyFailure", () => { + it("is the CLI's envelope for a code the contract knows", () => { + const error = { code: "no_capacity", action: "retry", message: "full" } + expect(proxyFailure(status("failed", { error }))).toEqual({ envelope: { error } }) + }) + + it("is the message and its page for a code the contract does not know", () => { + expect(proxyFailure(status("refused", { error: KEY_NOT_ENROLLED }))).toEqual({ + message: `Spinbox could not connect to ${HOST}: ${KEY_NOT_ENROLLED.message}`, + url: KEY_NOT_ENROLLED.url, + }) + }) + + it("names the host when there is no error", () => { + expect(proxyFailure(status("failed"))).toEqual({ + message: `Spinbox could not connect to ${HOST}.`, + }) + }) + + it.each(["resolving", "connecting", "connected"] as const)("is nothing while %s", (phase) => { + expect(proxyFailure(status(phase))).toBeUndefined() }) }) @@ -70,26 +147,31 @@ describe("watchProxy", () => { report: (m: string) => said.push(m), }) - it("says each new step, and answers the failure", async () => { + it("says each phase once, and answers the refusal", async () => { const said: string[] = [] - const failed: ProxyStatus = { state: "failed", message: "refused" } + const refused = status("refused", { error: KEY_NOT_ENROLLED }) const got = await watchProxy( - fixture(undefined, connecting("relay"), connecting("relay"), connecting("sshd"), failed), + fixture( + undefined, + status("resolving"), + status("resolving"), + status("connecting"), + status("connecting"), + refused, + ), opts(said), ) - expect(got).toEqual(failed) - expect(said).toEqual(["relay", "sshd"]) + expect(got).toEqual(refused) + expect(said).toEqual([SAYS.resolving, SAYS.connecting]) }) - it("answers connected", async () => { - const got = await watchProxy(fixture({ state: "connected", message: "up" }), opts([])) - expect(got?.state).toBe("connected") + it.each(["connected", "failed"] as const)("answers %s", async (phase) => { + expect((await watchProxy(fixture(status(phase)), opts([])))?.phase).toBe(phase) }) it("gives up quietly when nothing is written", async () => { const said: string[] = [] - const got = await watchProxy(fixture(undefined), { ...opts(said), timeoutMs: 20 }) - expect(got).toBeUndefined() + expect(await watchProxy(fixture(undefined), { ...opts(said), timeoutMs: 20 })).toBeUndefined() expect(said).toEqual([]) }) })