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..7dbfde5 --- /dev/null +++ b/src/remote/index.ts @@ -0,0 +1,95 @@ +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 ProxyFailure, proxyFailure, 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 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) { + // From now: spin code's own ssh, and the shared connection it leaves, began before. + void followProxy(remote.host, Date.now()) + } +} + +async function followProxy(host: string, since: number): Promise { + let said: vscode.Disposable | undefined + 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) => { + said?.dispose() + said = vscode.window.setStatusBarMessage(`$(sync~spin) Spinbox: ${message}`) + }, + }) + said?.dispose() + const failure = status === undefined ? undefined : proxyFailure(status) + if (failure !== undefined) { + await showProxyFailure(failure) + await closeRemote() + } +} + +const OPEN = "Open" + +async function showProxyFailure(failure: ProxyFailure): Promise { + if ("envelope" in failure) { + await showCliError(new CliError(failure.envelope)) + return + } + 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 new file mode 100644 index 0000000..59fb675 --- /dev/null +++ b/src/remote/proxy.ts @@ -0,0 +1,173 @@ +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-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 const STATUS_VERSION = 1 + +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 + 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 { + // The status of the connection being made, or undefined while there is none to read. + read(): Promise +} + +// 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 { + v = JSON.parse(body) + } catch { + return undefined + } + if (typeof v !== "object" || v === null) { + return undefined + } + 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 + } + 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 + } + const e = v as Record + return typeof e.code === "string" && typeof e.action === "string" && typeof e.message === "string" +} + +// 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(".json")) + } catch { + return undefined + } + let newest: ProxyStatus | undefined + for (const name of names) { + 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 + } + } + 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 phase on the way, once. + report(message: string): void + signal?: AbortSignal +} + +// 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: ProxyPhase | undefined + while (opts.signal?.aborted !== true) { + const status = await source.read() + 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 + } + 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..e9380bd --- /dev/null +++ b/test/unit/proxy.test.ts @@ -0,0 +1,177 @@ +import { mkdtempSync, 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, + 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)] } +} + +describe("readProxyStatus", () => { + it("reads a refusal with the CLI's error envelope", () => { + const body = JSON.stringify({ + 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([ + ["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", () => { + 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)) + } + 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-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() + }) +}) + +describe("watchProxy", () => { + const opts = (said: string[]) => ({ + intervalMs: 1, + timeoutMs: 1_000, + report: (m: string) => said.push(m), + }) + + it("says each phase once, and answers the refusal", async () => { + const said: string[] = [] + const refused = status("refused", { error: KEY_NOT_ENROLLED }) + const got = await watchProxy( + fixture( + undefined, + status("resolving"), + status("resolving"), + status("connecting"), + status("connecting"), + refused, + ), + opts(said), + ) + expect(got).toEqual(refused) + expect(said).toEqual([SAYS.resolving, SAYS.connecting]) + }) + + 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[] = [] + expect(await watchProxy(fixture(undefined), { ...opts(said), timeoutMs: 20 })).toBeUndefined() + expect(said).toEqual([]) + }) +})