diff --git a/packages/app/component-tests/ssh-reconnect.spec.ts b/packages/app/component-tests/ssh-reconnect.spec.ts index 7abb39824b6..c2afa5a84e7 100644 --- a/packages/app/component-tests/ssh-reconnect.spec.ts +++ b/packages/app/component-tests/ssh-reconnect.spec.ts @@ -15,6 +15,23 @@ story("settings menu reconnect retains its prompt handler across server updates" await expect(component.getByRole("button", { name: "Authenticate", exact: true })).toHaveCount(0) }) +story("cancelling a sign-in from Home offers it again at once", async ({ mount, page }) => { + const component = await mount("app-dialog-ssh--authentication-required") + const projects = component.getByRole("button", { name: "Projects" }) + const authenticate = page.getByRole("button", { name: "Authenticate", exact: true }) + const dialog = page.getByRole("dialog", { name: "Connect to linuxbook" }) + await projects.click() + await authenticate.click() + await expect(dialog.getByRole("textbox")).toBeVisible() + await dialog.getByRole("button", { name: "Cancel", exact: true }).click() + await expect(dialog).toHaveCount(0) + // The sign-in that waited on the dialog ends with it, instead of showing the server as connecting. + await projects.click() + await expect(authenticate).toBeEnabled() + await authenticate.click() + await expect(dialog.getByRole("textbox")).toBeVisible() +}) + story("cancelling a version mismatch permits reconnecting again", async ({ mount, page }) => { const component = await mount("app-dialog-ssh--incompatible-session") await component.getByRole("button", { name: "Reconnect", exact: true }).click() diff --git a/packages/gui-plugins/src/ssh/bootstrap.ts b/packages/gui-plugins/src/ssh/bootstrap.ts index fee6c65838d..7e38a0de574 100644 --- a/packages/gui-plugins/src/ssh/bootstrap.ts +++ b/packages/gui-plugins/src/ssh/bootstrap.ts @@ -79,7 +79,6 @@ export const bootstrap = Effect.fn("Ssh.bootstrap")(function* (input: { development?: boolean env: NodeJS.ProcessEnv replace?: boolean - stage: (stage: "checking" | "downloading" | "uploading" | "starting") => Effect.Effect }) { const run = (script: string) => runSsh({ @@ -88,17 +87,13 @@ export const bootstrap = Effect.fn("Ssh.bootstrap")(function* (input: { stdin: script, }) - yield* input.stage("checking") const registered = parseRegistration(yield* run(discoverScript)) - if (registered && (input.development || registered.version === input.version)) { - yield* input.stage("starting") - + if (registered && (input.development || registered.version === input.version)) return yield* Effect.try({ try: () => connectionAddress(registered.url, registered.password), catch: SshFailure.from, }) - } if (registered && !input.replace) return yield* Effect.fail(new SshFailure("version", registered.version)) const destination = yield* Effect.try({ try: () => binaryPath(input.version), catch: SshFailure.from }) @@ -121,11 +116,9 @@ export const bootstrap = Effect.fn("Ssh.bootstrap")(function* (input: { ?.split("=")[1] const url = yield* Effect.try({ try: () => RemoteCli.archiveUrl(target ?? "", version), catch: SshFailure.from }) - yield* input.stage("downloading") yield* run(RemoteCli.installScript({ ...setup, source: { type: "download", url } })).pipe( Effect.catch( Effect.fnUntraced(function* (error) { - yield* input.stage("uploading") const http = yield* HttpClient.HttpClient const response = yield* http.get(url).pipe(Effect.mapError(SshFailure.from)) @@ -153,7 +146,6 @@ export const bootstrap = Effect.fn("Ssh.bootstrap")(function* (input: { ) } - yield* input.stage("starting") const registration = parseRegistration(yield* run(startScript(version, input.replace))) if (!registration) return yield* Effect.fail(new SshFailure("service")) diff --git a/packages/gui-plugins/src/ssh/contract.ts b/packages/gui-plugins/src/ssh/contract.ts index 9e925909842..1e0c5317ff4 100644 --- a/packages/gui-plugins/src/ssh/contract.ts +++ b/packages/gui-plugins/src/ssh/contract.ts @@ -12,10 +12,6 @@ export type SshHttp = typeof SshHttp.Type export const SshStage = Schema.Literals([ "disconnected", "connecting", - "checking", - "downloading", - "uploading", - "starting", "ready", "authentication", "incompatible", @@ -28,28 +24,35 @@ export const SshPrompt = Schema.Struct({ confirm: Schema.Boolean, }) +export type SshPrompt = typeof SshPrompt.Type + +export const SshError = Schema.Literals([ + "connection", + "input", + "platform", + "version", + "install", + "service", + "host-key", + "ssh-missing", + "unpublished", +]) + +export type SshError = typeof SshError.Type + export const SshItem = Schema.Struct({ config: SshConfig, saved: Schema.Boolean, destination: Schema.optional(Schema.String), stage: SshStage, + /** Set only while `stage` is `ready`. */ http: Schema.optional(SshHttp), prompt: Schema.optional(SshPrompt), authenticatingElsewhere: Schema.optional(Schema.Boolean), + /** A `failed` server that main reconnects by itself; without it, the server waits for the user. */ + retrying: Schema.optional(Schema.Boolean), detail: Schema.String, - error: Schema.optional( - Schema.Literals([ - "connection", - "input", - "platform", - "version", - "install", - "service", - "host-key", - "ssh-missing", - "unpublished", - ]), - ), + error: Schema.optional(SshError), }) export type SshItem = typeof SshItem.Type diff --git a/packages/gui-plugins/src/ssh/controller.ts b/packages/gui-plugins/src/ssh/controller.ts index 0cf01096ab1..8e641499264 100644 --- a/packages/gui-plugins/src/ssh/controller.ts +++ b/packages/gui-plugins/src/ssh/controller.ts @@ -17,20 +17,20 @@ import { } from "effect" import { HttpClient } from "effect/http" import { ChildProcess, ChildProcessSpawner } from "effect/process" -import type { SshConfig, SshHttp, SshItem, SshStart, SshState } from "./contract" +import type { SshConfig, SshHttp, SshStart, SshState } from "./contract" import { createAskpass } from "./askpass" import { bootstrap } from "./bootstrap" import { parseTarget, quote, runSsh, sshArgs, sshExecutable, tunnelArgs, SshFailure } from "./command" +import { + createSshMainState, + selectSshAuthenticating, + selectSshServers, + transitionSshMain, + type SshMainEffect, + type SshMainEvent, +} from "./main-machine" -type Connection = { - owner?: number - before?: SshItem - ready: Deferred.Deferred - respond?: (id: string, value: string) => Effect.Effect -} - -type Attempt = Connection & { fiber: Fiber.Fiber } - +/** Runs the SSH machine's effects and reports their outcomes back to it; the machine alone decides what is current. */ export const createSshController = Effect.fn("Ssh.controller")(function* (input: { version: string development?: boolean @@ -48,48 +48,113 @@ export const createSshController = Effect.fn("Ssh.controller")(function* (input: const changed = yield* PubSub.unbounded() yield* Scope.addFinalizer(lifetime, PubSub.shutdown(changed)) - const items = new Map( - input.configs.map((config) => [config.id, { config, saved: true, stage: "disconnected", detail: "" }]), - ) + const current = { machine: createSshMainState(input.configs) } + // Handles by attempt, for stopping and answering them only. + const connections = new Map }>() + const responders = new Map Effect.Effect>() + const timers = new Map>() + const waiters = new Map>() + const issued = { waiter: 0 } - const configs = new Map(input.configs.map((config) => [config.id, config])) - const attempts = new Map() - const paused = new Set(items.keys()) - const failures = new Map() - const lifecycle = { closed: false } - const emit = PubSub.publish(changed, undefined).pipe(Effect.asVoid) + const dispatch = (event: SshMainEvent): Effect.Effect => + Effect.suspend(() => { + const transition = transitionSshMain(current.machine, event) + const updated = transition.state !== current.machine + current.machine = transition.state - const state = (owner?: number): Effect.Effect> => - Effect.sync(() => ({ - servers: [...items.values()].map((item) => ({ - ...item, - prompt: attempts.get(item.config.id)?.owner === owner ? item.prompt : undefined, - authenticatingElsewhere: - item.stage === "authentication" && - attempts.get(item.config.id)?.owner !== undefined && - attempts.get(item.config.id)?.owner !== owner, - })), - })) + return Effect.forEach(transition.effects, run, { discard: true }).pipe( + Effect.andThen(updated ? PubSub.publish(changed, undefined) : Effect.void), + Effect.asVoid, + ) + }).pipe(Effect.uninterruptible) - const update = Effect.fnUntraced(function* (id: string, value: Partial) { - const item = items.get(id) + const run = (effect: SshMainEffect): Effect.Effect => { + if (effect.type === "attempt.start") return startAttempt(effect) - if (!item) return - items.set(id, { ...item, ...value }) - yield* emit - }) + if (effect.type === "attempt.stop") { + const connection = connections.get(effect.attempt) - // A saved server's item takes its current saved config along with the change. - const withSavedConfig = (id: string, value: Partial): Partial => { - const config = configs.get(id) + // Stopping runs its finalizers (askpass, tunnel, control master) while the machine moves on; whatever the + // stopped attempt reports meanwhile carries its attempt and is ignored. + return connection ? Fiber.interrupt(connection.fiber).pipe(Effect.forkIn(lifetime), Effect.asVoid) : Effect.void + } - return config ? { ...value, config } : value + if (effect.type === "attempt.respond") + return responders.get(effect.attempt)?.(effect.promptID, effect.value) ?? Effect.void + + if (effect.type === "retry.schedule") + return Effect.sleep(effect.delayMs).pipe( + Effect.andThen(dispatch({ type: "retry.due", id: effect.id, attempt: effect.attempt })), + Effect.ensuring(Effect.sync(() => timers.delete(effect.attempt))), + Effect.forkIn(lifetime), + Effect.map((fiber) => void timers.set(effect.attempt, fiber)), + ) + + if (effect.type === "retry.cancel") { + const timer = timers.get(effect.attempt) + + return timer ? Fiber.interrupt(timer).pipe(Effect.asVoid) : Effect.void + } + + if (effect.type === "health.probe") + return checkHealth(effect.http).pipe( + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.flatMap((healthy) => + dispatch({ type: "health.probed", id: effect.id, attempt: effect.attempt, waiter: effect.waiter, healthy }), + ), + Effect.forkIn(lifetime), + Effect.asVoid, + ) + + if (effect.type === "waiters.resolve") + return Effect.forEach( + effect.waiters, + (id) => { + const waiter = waiters.get(id) + waiters.delete(id) + + return waiter ? Deferred.succeed(waiter, effect.http) : Effect.void + }, + { discard: true }, + ) + + return input + .save(effect.configs) + .pipe(Effect.catch((error) => Effect.logError("Failed to save SSH servers", error))) } - const run = (options: Parameters[0]) => + const startAttempt = Effect.fnUntraced(function* (effect: Extract) { + // The attempt this one replaces finishes stopping first. + const previous = [...connections.values()].filter((connection) => connection.id === effect.id) + + const fiber = yield* Effect.forEach(previous, (connection) => Fiber.interrupt(connection.fiber), { + discard: true, + }).pipe( + Effect.andThen(connect(effect.config, effect.attempt, effect.replace)), + Effect.catchCause((cause) => { + if (Cause.hasInterruptsOnly(cause)) return Effect.void + const failure = SshFailure.from(Cause.squash(cause)) + + return dispatch({ + type: "attempt.failed", + id: effect.id, + attempt: effect.attempt, + code: failure.code, + detail: failure.message, + }) + }), + Effect.ensuring(Effect.sync(() => connections.delete(effect.attempt))), + Effect.forkIn(lifetime, { uninterruptible: false }), + ) + + connections.set(effect.attempt, { id: effect.id, fiber }) + }) + + const exec = (options: Parameters[0]) => runSsh(options).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)) - const connect = Effect.fn("Ssh.connect")(function* (config: SshConfig, connection: Connection, replace = false) { + const connect = Effect.fn("Ssh.connect")(function* (config: SshConfig, attempt: number, replace: boolean) { + const id = config.id const target = yield* Effect.try({ try: () => parseTarget(config.target), catch: SshFailure.from }) const directory = yield* fs.makeTempDirectoryScoped({ prefix: "oc-ssh-" }) const control = path.join(directory, "s") @@ -109,35 +174,21 @@ export const createSshController = Effect.fn("Ssh.controller")(function* (input: // Close only our local SSH master. The remote OpenCode service owns its // own lifetime and must survive disconnect, failure, and app shutdown. yield* Effect.addFinalizer(() => - run({ args: ["-o", `ControlPath=${control}`, "-O", "exit", target.host], timeout: 2000 }).pipe(Effect.ignore), + exec({ args: ["-o", `ControlPath=${control}`, "-O", "exit", target.host], timeout: 2000 }).pipe(Effect.ignore), ) } - const authentication = yield* Deferred.make() - const askpass = yield* createAskpass({ binary: helper, - prompt: Effect.fnUntraced(function* (prompt) { - if (connection.owner === undefined) { - paused.add(config.id) - yield* update(config.id, { stage: "authentication" }) - yield* Deferred.succeed(authentication, undefined) - - return - } - - yield* update(config.id, { stage: "authentication", prompt }) - }), - clear: (id) => - items.get(config.id)?.prompt?.id === id - ? update(config.id, { prompt: undefined, stage: "connecting" }) - : Effect.void, + prompt: (prompt) => dispatch({ type: "prompt.received", id, attempt, prompt }), + clear: (promptID) => dispatch({ type: "prompt.cleared", id, attempt, promptID }), }) - connection.respond = askpass.respond + responders.set(attempt, askpass.respond) + yield* Effect.addFinalizer(() => Effect.sync(() => responders.delete(attempt))) yield* Effect.gen(function* () { - const resolved = yield* run({ args: [...sshArgs(target), "-G", target.host], timeout: 10_000 }).pipe( + const resolved = yield* exec({ args: [...sshArgs(target), "-G", target.host], timeout: 10_000 }).pipe( Effect.orElseSucceed(() => ""), ) @@ -150,7 +201,10 @@ export const createSshController = Effect.fn("Ssh.controller")(function* (input: ) if (fields.has("hostname")) - yield* update(config.id, { + yield* dispatch({ + type: "destination.resolved", + id, + attempt, destination: `${fields.get("user") ?? ""}@${fields.get("hostname")}:${fields.get("port") ?? "22"}`, }) @@ -160,7 +214,6 @@ export const createSshController = Effect.fn("Ssh.controller")(function* (input: development: input.development, env: askpass.env, replace, - stage: (stage) => update(config.id, { stage, prompt: undefined }), }).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(HttpClient.HttpClient, httpClient), @@ -198,192 +251,60 @@ export const createSshController = Effect.fn("Ssh.controller")(function* (input: ) }) - yield* waitReady(http, () => items.get(config.id)?.stage === "authentication").pipe( + yield* waitReady(http, () => selectSshAuthenticating(current.machine, id, attempt)).pipe( Effect.provideService(HttpClient.HttpClient, httpClient), Effect.catch(() => Ref.get(detail).pipe(Effect.flatMap((detail) => Effect.fail(new SshFailure("service", detail)))), ), Effect.raceFirst(closed), ) - const saved = new Map(configs).set(config.id, config) - yield* input.save([...saved.values()]) - configs.set(config.id, config) - failures.delete(config.id) - yield* update(config.id, { http, stage: "ready", saved: true, detail: "", prompt: undefined, error: undefined }) - yield* Deferred.succeed(connection.ready, http) + yield* dispatch({ type: "attempt.ready", id, attempt, http }) + // The tunnel closing fails the attempt, which the machine reads as a ready server that dropped. yield* closed - }).pipe( - Effect.raceFirst(askpass.closed), - Effect.raceFirst(Deferred.await(authentication).pipe(Effect.andThen(Effect.interrupt))), - ) + }).pipe(Effect.raceFirst(askpass.closed)) }, Effect.scoped) - const start = Effect.fn("Ssh.start")(function* (request: SshStart, owner?: number) { - const id = request.id - - if (lifecycle.closed || !/^[a-zA-Z0-9-]{1,80}$/.test(id)) return - const previous = attempts.get(id) - - // A second window must not replace an interactive attempt while its owner - // is connecting or answering a challenge. - if (previous?.owner !== undefined && previous.owner !== owner && items.get(id)?.stage !== "ready") return - const config = { id, target: request.target.trim(), name: request.name.trim() } - - const connection: Connection = { - owner, - before: items.get(id), - ready: yield* Deferred.make(), - } - - const admitted = yield* Deferred.make() - - const fiber = yield* Effect.gen(function* () { - yield* Deferred.await(admitted) - - if (previous) yield* Fiber.interrupt(previous.fiber) - yield* connect(config, connection, request.replace) - }).pipe( - Effect.catchCause( - Effect.fnUntraced(function* (cause) { - if (Cause.hasInterruptsOnly(cause) || paused.has(id) || attempts.get(id)?.ready !== connection.ready) return - const failure = SshFailure.from(Cause.squash(cause)) - failures.set(id, (failures.get(id) ?? 0) + 1) - - const code = /REMOTE HOST IDENTIFICATION HAS CHANGED|Host key verification failed/.test(failure.message) - ? "host-key" - : /spawn .*ENOENT/.test(failure.message) - ? "ssh-missing" - : failure.code - - if ( - ["version", "input", "unpublished", "platform", "host-key", "ssh-missing"].includes(code) || - /Permission denied/.test(failure.message) || - (failures.get(id) ?? 0) >= 5 - ) - paused.add(id) - yield* update( - id, - withSavedConfig(id, { - stage: code === "version" ? "incompatible" : "failed", - error: code, - detail: failure.message, - prompt: undefined, - }), - ) + const close = dispatch({ type: "close" }).pipe( + Effect.andThen( + Effect.suspend(() => + Effect.forEach([...connections.values()], (connection) => Fiber.interrupt(connection.fiber), { + concurrency: "unbounded", + discard: true, }), ), - Effect.ensuring( - Effect.gen(function* () { - yield* Deferred.succeed(connection.ready, null) - - if (attempts.get(id)?.ready !== connection.ready) return - attempts.delete(id) - yield* update(id, { prompt: undefined }) - }), - ), - Effect.forkIn(lifetime, { uninterruptible: false }), - ) - - attempts.set(id, Object.assign(connection, { fiber })) - items.set(id, { - config, - saved: items.get(id)?.saved ?? false, - http: items.get(id)?.http, - stage: "connecting", - detail: "", - }) - paused.delete(id) - - if (!request.background) failures.delete(id) - yield* emit - yield* Deferred.succeed(admitted, undefined) - }, Effect.uninterruptible) - - const disconnect = Effect.fn("Ssh.disconnect")(function* (id: string) { - paused.add(id) - const attempt = attempts.get(id) - yield* update(id, withSavedConfig(id, { stage: "disconnected", prompt: undefined })) - - if (attempt) yield* Fiber.interrupt(attempt.fiber) - }) - - const cancel = Effect.fn("Ssh.cancel")(function* (id: string, owner: number) { - const attempt = attempts.get(id) - - if (!attempt || attempt.owner !== owner) return - paused.add(id) - // Restore before interrupting: askpass cleanup must not transition the - // cancelled attempt back to connecting or expose an expired prompt. - const before = attempt.before - yield* update(id, { - ...before, - stage: - before?.stage === "authentication" || before?.stage === "failed" || before?.stage === "incompatible" - ? before.stage - : "disconnected", - prompt: undefined, - error: before?.error, - detail: before?.detail ?? "", - }) - yield* Fiber.interrupt(attempt.fiber) - }) - - const close = Effect.gen(function* () { - if (lifecycle.closed) return - lifecycle.closed = true - yield* Effect.forEach([...attempts.keys()], disconnect, { concurrency: "unbounded", discard: true }) - yield* Scope.close(lifetime, Exit.void) - }) + ), + Effect.andThen(Scope.close(lifetime, Exit.void)), + ) yield* Effect.addFinalizer(() => close) + const state = (owner?: number): Effect.Effect> => + Effect.sync(() => ({ servers: selectSshServers(current.machine, owner) })) + return { state, changes: (owner?: number) => Stream.fromPubSub(changed).pipe(Stream.mapEffect(() => state(owner))), - start, + start: (request: SshStart, owner?: number) => dispatch({ type: "start", request, owner }), + /** Waits until the server is ready, or until main stops reconnecting it by itself (`null`). */ resolve: Effect.fn("Ssh.resolve")(function* (id: string) { - const item = items.get(id) + const waiter = ++issued.waiter + const deferred = yield* Deferred.make() + waiters.set(waiter, deferred) + yield* dispatch({ type: "resolve.requested", id, waiter }) - if (lifecycle.closed || !item || paused.has(id)) return null - - if (item.stage === "ready" && item.http) { - const healthy = yield* checkHealth(item.http).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)) - - if (lifecycle.closed || paused.has(id)) return null - - // Another window may already have replaced this tunnel during the probe. - if (items.get(id) === item) { - if (healthy) return item.http - yield* start({ ...item.config, background: true }) - } - } - - if (!attempts.has(id) && items.has(id)) yield* start({ ...item.config, background: true }) - const attempt = attempts.get(id) - - return attempt ? yield* Deferred.await(attempt.ready) : null - }), - respond: Effect.fn("Ssh.respond")(function* (id: string, prompt: string, value: string, owner: number) { - const attempt = attempts.get(id) - - if (attempt?.owner === owner && attempt.respond) yield* attempt.respond(prompt, value) - }), - disconnect, - cancel, - forget: Effect.fn("Ssh.forget")(function* (id: string) { - yield* disconnect(id) - items.delete(id) - configs.delete(id) - yield* input.save([...configs.values()]) - yield* emit - }), - detach: Effect.fn("Ssh.detach")(function* (owner: number) { - yield* Effect.forEach( - [...attempts].filter(([id, attempt]) => attempt.owner === owner && items.get(id)?.stage !== "ready"), - ([id]) => cancel(id, owner), - { concurrency: "unbounded", discard: true }, + return yield* Deferred.await(deferred).pipe( + Effect.onInterrupt(() => + Effect.sync(() => waiters.delete(waiter)).pipe( + Effect.andThen(dispatch({ type: "resolve.aborted", id, waiter })), + ), + ), ) }), + respond: (id: string, prompt: string, value: string, owner: number) => + dispatch({ type: "respond", id, promptID: prompt, value, owner }), + cancel: (id: string, owner: number) => dispatch({ type: "cancel", id, owner }), + forget: (id: string) => dispatch({ type: "forget", id }), + detach: (owner: number) => dispatch({ type: "window.detached", owner }), close, } }) diff --git a/packages/gui-plugins/src/ssh/cover.tsx b/packages/gui-plugins/src/ssh/cover.tsx index 09a9cc2c1f7..5d9e0858fd9 100644 --- a/packages/gui-plugins/src/ssh/cover.tsx +++ b/packages/gui-plugins/src/ssh/cover.tsx @@ -4,7 +4,7 @@ import { Icon } from "@opencode/ui/icon" import { Loader } from "@opencode/ui/loader" import { Show } from "solid-js" import { createKeyed, usePlugin } from "@opencode/plugin/gui" -import { isSshConnecting, sshName } from "./name" +import { sshName } from "./name" import type { SshController } from "./state" /** The visit to a routed tab in which authentication was offered. Shared by the window's covers. */ @@ -36,7 +36,7 @@ export function SshCover(props: { id: string; visit: object; ssh: SshController; return ( {(item) => { - const connecting = () => props.ssh.pending(props.id) || isSshConnecting(item().stage) + const connecting = () => props.ssh.pending(props.id) return (
ssh.submitting(id) || (state.started && !ssh.error(id) && isSshConnecting(item()?.stage ?? "connecting")), + () => ssh.submitting(id) || (state.started && !ssh.error(id) && (item()?.stage ?? "connecting") === "connecting"), ) const prompt = createMemo((previous) => item()?.prompt ?? (busy() ? previous : undefined)) diff --git a/packages/gui-plugins/src/ssh/main-machine.test.ts b/packages/gui-plugins/src/ssh/main-machine.test.ts new file mode 100644 index 00000000000..ef001062e3d --- /dev/null +++ b/packages/gui-plugins/src/ssh/main-machine.test.ts @@ -0,0 +1,335 @@ +import { describe, expect, test } from "bun:test" +import { Schema } from "effect" +import { SshStart, type SshConfig } from "./contract" +import { + createSshMainState, + selectSshServers, + SSH_RETRY_DELAY_MS, + SSH_RETRY_LIMIT, + transitionSshMain, + type SshMainEffect, + type SshMainEvent, + type SshMainState, +} from "./main-machine" + +const box: SshConfig = { id: "box", target: "ssh box", name: "Box" } + +const http = { url: "http://127.0.0.1:4100", password: "secret" } + +const prompt = { id: "password", text: "box's password:", confirm: false } + +// Windows call `start` through the Ipc, whose input main decodes. +const start = (input: typeof SshStart.Encoded, owner?: number): SshMainEvent => ({ + type: "start", + request: Schema.decodeUnknownSync(SshStart)(input), + owner, +}) + +function replay(state: SshMainState, events: readonly SshMainEvent[]) { + return events.reduce<{ state: SshMainState; effects: SshMainEffect[] }>( + (result, event) => { + const next = transitionSshMain(result.state, event) + + return { state: next.state, effects: [...result.effects, ...next.effects] } + }, + { state, effects: [] }, + ) +} + +function item(state: SshMainState, viewer?: number) { + return selectSshServers(state, viewer).find((item) => item.config.id === box.id) +} + +/** A saved server, ready on attempt 1 after a background restore. */ +function ready() { + return replay(createSshMainState([box]), [ + start({ ...box, background: true }), + { type: "attempt.ready", id: box.id, attempt: 1, http }, + ]).state +} + +describe("ssh main connection", () => { + test("an endpoint never outlives the ready tunnel it belongs to", () => { + const dropped = replay(ready(), [ + { type: "attempt.failed", id: box.id, attempt: 1, code: "connection", detail: "closed" }, + ]).state + + expect(item(dropped)).toMatchObject({ stage: "failed", retrying: true }) + expect(item(dropped)?.http).toBeUndefined() + + const restarted = replay(ready(), [start(box, 1)]).state + expect(item(restarted, 1)).toMatchObject({ stage: "connecting" }) + expect(item(restarted, 1)?.http).toBeUndefined() + + const cancelled = replay(restarted, [{ type: "cancel", id: box.id, owner: 1 }]).state + expect(item(cancelled, 1)).toMatchObject({ stage: "disconnected" }) + expect(item(cancelled, 1)?.http).toBeUndefined() + }) + + test("only the window that started an attempt sees its prompt", () => { + const prompted = replay(createSshMainState([box]), [ + start(box, 1), + { type: "prompt.received", id: box.id, attempt: 1, prompt }, + ]).state + + expect(item(prompted, 1)).toMatchObject({ stage: "authentication", prompt, authenticatingElsewhere: false }) + expect(item(prompted, 2)).toMatchObject({ stage: "authentication", authenticatingElsewhere: true }) + expect(item(prompted, 2)?.prompt).toBeUndefined() + }) + + test("closing the window that was adding a server removes the server and stops its attempt", () => { + const added = replay(createSshMainState([]), [ + start({ id: "new", target: " ssh devbox ", name: "" }, 7), + { type: "prompt.received", id: "new", attempt: 1, prompt }, + ]).state + + expect(selectSshServers(added, 7)).toHaveLength(1) + + const detached = transitionSshMain(added, { type: "window.detached", owner: 7 }) + expect(selectSshServers(detached.state)).toEqual([]) + expect(detached.effects).toEqual([{ type: "attempt.stop", attempt: 1 }]) + }) + + test("cancelling restores where a saved server was and ignores its cancelled attempt", () => { + const failed = replay(createSshMainState([box]), [ + start({ ...box, background: true }), + { type: "attempt.failed", id: box.id, attempt: 1, code: "service", detail: "Permission denied" }, + ]).state + + const edited = replay(failed, [ + start(box, 1), + { type: "destination.resolved", id: box.id, attempt: 2, destination: "me@box:22" }, + { type: "prompt.received", id: box.id, attempt: 2, prompt }, + { type: "cancel", id: box.id, owner: 1 }, + ]) + + expect(item(edited.state, 1)).toMatchObject({ + config: box, + saved: true, + destination: "me@box:22", + stage: "failed", + error: "service", + detail: "Permission denied", + }) + expect(item(edited.state, 1)?.prompt).toBeUndefined() + expect(item(edited.state, 1)?.retrying).toBeUndefined() + expect(edited.effects).toContainEqual({ type: "attempt.stop", attempt: 2 }) + // The cancelled attempt's askpass cleanup clears its prompt after the restore. + + const late = transitionSshMain(edited.state, { + type: "prompt.cleared", + id: box.id, + attempt: 2, + promptID: prompt.id, + }) + + expect(late.state).toBe(edited.state) + }) + + test("results of a superseded attempt change nothing", () => { + const superseded = replay(createSshMainState([box]), [start(box, 1), start(box, 1)]) + expect(superseded.effects).toContainEqual({ type: "attempt.stop", attempt: 1 }) + + const stale: SshMainEvent[] = [ + { type: "destination.resolved", id: box.id, attempt: 1, destination: "me@box:22" }, + { type: "prompt.received", id: box.id, attempt: 1, prompt }, + { type: "attempt.ready", id: box.id, attempt: 1, http }, + { type: "attempt.failed", id: box.id, attempt: 1, code: "connection", detail: "" }, + ] + + stale.forEach((event) => expect(transitionSshMain(superseded.state, event).state).toBe(superseded.state)) + }) + + test("another window cannot replace an attempt its owner is answering", () => { + const prompted = replay(createSshMainState([box]), [ + start(box, 1), + { type: "prompt.received", id: box.id, attempt: 1, prompt }, + ]).state + + expect(transitionSshMain(prompted, start(box, 2)).state).toBe(prompted) + expect(transitionSshMain(prompted, start({ ...box, background: true })).state).toBe(prompted) + }) +}) + +describe("ssh reconnect budget", () => { + test("main reconnects a dropped tunnel by itself until the budget runs out", () => { + const waiting = replay(ready(), [ + { type: "attempt.failed", id: box.id, attempt: 1, code: "connection", detail: "closed" }, + { type: "resolve.requested", id: box.id, waiter: 1 }, + ]) + + expect(waiting.effects).toEqual([{ type: "retry.schedule", id: box.id, attempt: 2, delayMs: SSH_RETRY_DELAY_MS }]) + + const exhausted = Array.from({ length: SSH_RETRY_LIMIT - 1 }).reduce<{ + state: SshMainState + effects: SshMainEffect[] + }>( + (result) => { + const phase = result.state.servers[0]?.phase + const retry = phase?.status === "failed" ? phase.retry : undefined + + if (!retry) throw new Error("expected a scheduled retry") + + const next = replay(result.state, [ + { type: "retry.due", id: box.id, attempt: retry.attempt }, + { type: "attempt.failed", id: box.id, attempt: retry.attempt + 1, code: "connection", detail: "refused" }, + ]) + + return { state: next.state, effects: [...result.effects, ...next.effects] } + }, + { state: waiting.state, effects: [] }, + ) + + expect(item(exhausted.state)).toMatchObject({ stage: "failed", error: "connection" }) + expect(item(exhausted.state)?.retrying).toBeUndefined() + expect(exhausted.effects.filter((effect) => effect.type === "attempt.start")).toHaveLength(SSH_RETRY_LIMIT - 1) + expect(exhausted.effects.at(-1)).toEqual({ type: "waiters.resolve", waiters: [1], http: null }) + + // The user asking again starts a new budget. + const retried = replay(exhausted.state, [ + start(box, 1), + { type: "attempt.failed", id: box.id, attempt: 10, code: "connection", detail: "refused" }, + ]) + + expect(item(retried.state)).toMatchObject({ stage: "failed", retrying: true }) + }) + + test("failures another try cannot fix wait for the user", () => { + const failures: [string, SshMainEvent][] = [ + [ + "host key", + { type: "attempt.failed", id: box.id, attempt: 2, code: "connection", detail: "Host key verification failed." }, + ], + [ + "missing ssh", + { type: "attempt.failed", id: box.id, attempt: 2, code: "connection", detail: "spawn ssh ENOENT" }, + ], + [ + "rejected key", + { type: "attempt.failed", id: box.id, attempt: 2, code: "service", detail: "Permission denied (publickey)" }, + ], + ["version", { type: "attempt.failed", id: box.id, attempt: 2, code: "version", detail: "1.0.0" }], + ["prompt", { type: "prompt.received", id: box.id, attempt: 2, prompt }], + ] + + failures.forEach(([name, event]) => { + const result = replay(ready(), [ + { type: "resolve.requested", id: box.id, waiter: 1 }, + { type: "health.probed", id: box.id, attempt: 1, waiter: 1, healthy: false }, + event, + ]) + + expect(item(result.state)?.retrying, name).toBeUndefined() + expect(item(result.state)?.stage, name).not.toBe("connecting") + expect( + result.effects.filter((effect) => effect.type === "retry.schedule"), + name, + ).toEqual([]) + expect(result.effects.at(-1), name).toEqual({ type: "waiters.resolve", waiters: [1], http: null }) + }) + }) + + test("a server that waits for the user answers resolve at once", () => { + const signedOut = replay(ready(), [ + { type: "attempt.failed", id: box.id, attempt: 1, code: "connection", detail: "closed" }, + { type: "retry.due", id: box.id, attempt: 2 }, + { type: "prompt.received", id: box.id, attempt: 3, prompt }, + ]).state + + expect(item(signedOut)?.stage).toBe("authentication") + + const resolved = transitionSshMain(signedOut, { type: "resolve.requested", id: box.id, waiter: 4 }) + expect(resolved.effects).toEqual([{ type: "waiters.resolve", waiters: [4], http: null }]) + }) + + test("a stale unhealthy probe answers with the tunnel that replaced it instead of restarting it", () => { + const probing = transitionSshMain(ready(), { type: "resolve.requested", id: box.id, waiter: 1 }) + expect(probing.effects).toEqual([{ type: "health.probe", id: box.id, attempt: 1, http, waiter: 1 }]) + + const replaced = replay(probing.state, [ + start(box, 2), + { type: "attempt.ready", id: box.id, attempt: 2, http: { ...http, password: "next" } }, + ]) + + expect(replaced.effects).toContainEqual({ + type: "waiters.resolve", + waiters: [1], + http: { ...http, password: "next" }, + }) + + const stale = transitionSshMain(replaced.state, { + type: "health.probed", + id: box.id, + attempt: 1, + waiter: 1, + healthy: false, + }) + + expect(stale.state).toBe(replaced.state) + expect(stale.effects).toEqual([]) + }) + + test("an unhealthy tunnel restarts in the background and answers the waiter once ready", () => { + const result = replay(ready(), [ + { type: "resolve.requested", id: box.id, waiter: 1 }, + { type: "health.probed", id: box.id, attempt: 1, waiter: 1, healthy: false }, + { type: "attempt.ready", id: box.id, attempt: 2, http }, + ]) + + expect(result.effects).toEqual([ + { type: "health.probe", id: box.id, attempt: 1, http, waiter: 1 }, + { type: "attempt.stop", attempt: 1 }, + { type: "attempt.start", id: box.id, attempt: 2, config: box, replace: false }, + { type: "configs.save", configs: [box] }, + { type: "waiters.resolve", waiters: [1], http }, + ]) + }) + + test("closing stops every connection and retry and answers every waiter", () => { + const busy = replay(createSshMainState([box, { ...box, id: "two" }]), [ + start({ ...box, background: true }), + { type: "resolve.requested", id: box.id, waiter: 1 }, + start({ ...box, id: "two", background: true }), + { type: "attempt.failed", id: "two", attempt: 2, code: "connection", detail: "" }, + ]).state + + const closed = transitionSshMain(busy, { type: "close" }) + expect(closed.effects).toEqual([ + { type: "attempt.stop", attempt: 1 }, + { type: "retry.cancel", attempt: 3 }, + { type: "waiters.resolve", waiters: [1], http: null }, + ]) + expect(transitionSshMain(closed.state, start(box, 1)).state).toBe(closed.state) + expect(transitionSshMain(closed.state, { type: "resolve.requested", id: box.id, waiter: 2 }).effects).toEqual([ + { type: "waiters.resolve", waiters: [2], http: null }, + ]) + }) + + test("forgetting a saved server stops its retry and saves the rest", () => { + const other = { ...box, id: "other" } + + const failed = replay(ready(), [ + { type: "attempt.failed", id: box.id, attempt: 1, code: "connection", detail: "" }, + ]).state + + const forgotten = transitionSshMain( + { + ...failed, + servers: [ + ...failed.servers, + { config: other, savedConfig: other, phase: { status: "disconnected" }, waiters: [] }, + ], + }, + { + type: "forget", + id: box.id, + }, + ) + + expect(forgotten.effects).toEqual([ + { type: "retry.cancel", attempt: 2 }, + { type: "configs.save", configs: [other] }, + ]) + expect(selectSshServers(forgotten.state).map((item) => item.config.id)).toEqual(["other"]) + }) +}) diff --git a/packages/gui-plugins/src/ssh/main-machine.ts b/packages/gui-plugins/src/ssh/main-machine.ts new file mode 100644 index 00000000000..b4b55d9d82f --- /dev/null +++ b/packages/gui-plugins/src/ssh/main-machine.ts @@ -0,0 +1,532 @@ +import type { SshConfig, SshError, SshHttp, SshItem, SshPrompt, SshStart } from "./contract" + +/** Failures in a row after which main stops reconnecting a saved server by itself. */ +export const SSH_RETRY_LIMIT = 5 + +export const SSH_RETRY_DELAY_MS = 3_000 + +/** Where a saved server returns when the window that started an attempt cancels it. */ +export type SshResting = + | { readonly status: "disconnected" } + | { readonly status: "authentication" } + | { readonly status: "incompatible"; readonly detail: string } + | { readonly status: "failed"; readonly code: SshError; readonly detail: string; readonly failures: number } + +/** + * One server's connection. `attempt` fences every result of a connect: a result for any other attempt is stale. + * `owner` is the window that started an interactive attempt; only it sees and answers the prompt. A background + * attempt has none and pauses in `authentication` at its first prompt. A `failed` server with `retry` reconnects by + * itself once the retry is due; without it, it waits for the user. + */ +export type SshServerPhase = + | { readonly status: "disconnected" } + | { readonly status: "authentication" } + | { readonly status: "incompatible"; readonly detail: string } + | { + readonly status: "connecting" + readonly attempt: number + readonly owner?: number + readonly failures: number + readonly resting: SshResting + } + | { + readonly status: "authenticating" + readonly attempt: number + readonly owner: number + readonly failures: number + readonly resting: SshResting + readonly prompt: SshPrompt + } + | { readonly status: "ready"; readonly attempt: number; readonly http: SshHttp } + | { + readonly status: "failed" + readonly code: SshError + readonly detail: string + readonly failures: number + readonly retry?: { readonly attempt: number } + } + +export type SshServerRecord = { + readonly config: SshConfig + /** The config last saved; a saved server keeps it while an attempt tries another target or name. */ + readonly savedConfig?: SshConfig + readonly destination?: string + readonly phase: SshServerPhase + /** `resolve` calls waiting for the server to be ready, or to stop reconnecting by itself. */ + readonly waiters: readonly number[] +} + +/** Open until the plugin stops for good; a closed machine starts nothing. */ +export type SshMainState = { + readonly status: "open" | "closed" + readonly issued: number + readonly servers: readonly SshServerRecord[] +} + +export type SshMainEvent = + | { readonly type: "start"; readonly request: SshStart; readonly owner?: number } + | { + readonly type: "destination.resolved" + readonly id: string + readonly attempt: number + readonly destination: string + } + | { readonly type: "prompt.received"; readonly id: string; readonly attempt: number; readonly prompt: SshPrompt } + | { readonly type: "prompt.cleared"; readonly id: string; readonly attempt: number; readonly promptID: string } + | { + readonly type: "respond" + readonly id: string + readonly promptID: string + readonly value: string + readonly owner: number + } + | { readonly type: "attempt.ready"; readonly id: string; readonly attempt: number; readonly http: SshHttp } + /** A connect failed, or the tunnel of a ready server closed. */ + | { + readonly type: "attempt.failed" + readonly id: string + readonly attempt: number + readonly code: SshError + readonly detail: string + } + | { readonly type: "retry.due"; readonly id: string; readonly attempt: number } + | { readonly type: "resolve.requested"; readonly id: string; readonly waiter: number } + | { readonly type: "resolve.aborted"; readonly id: string; readonly waiter: number } + | { + readonly type: "health.probed" + readonly id: string + readonly attempt: number + readonly waiter: number + readonly healthy: boolean + } + | { readonly type: "cancel"; readonly id: string; readonly owner: number } + | { readonly type: "forget"; readonly id: string } + | { readonly type: "window.detached"; readonly owner: number } + | { readonly type: "close" } + +export type SshMainEffect = + | { + readonly type: "attempt.start" + readonly id: string + readonly attempt: number + readonly config: SshConfig + readonly replace: boolean + } + | { readonly type: "attempt.stop"; readonly attempt: number } + | { readonly type: "attempt.respond"; readonly attempt: number; readonly promptID: string; readonly value: string } + | { readonly type: "retry.schedule"; readonly id: string; readonly attempt: number; readonly delayMs: number } + | { readonly type: "retry.cancel"; readonly attempt: number } + | { + readonly type: "health.probe" + readonly id: string + readonly attempt: number + readonly http: SshHttp + readonly waiter: number + } + | { readonly type: "waiters.resolve"; readonly waiters: readonly number[]; readonly http: SshHttp | null } + | { readonly type: "configs.save"; readonly configs: readonly SshConfig[] } + +export type SshMainTransition = { + readonly state: SshMainState + readonly effects: readonly SshMainEffect[] +} + +type Active = Extract + +const DISCONNECTED: SshServerPhase = { status: "disconnected" } + +export function createSshMainState(configs: readonly SshConfig[]): SshMainState { + return { + status: "open", + issued: 0, + servers: configs.map((config) => ({ config, savedConfig: config, phase: DISCONNECTED, waiters: [] })), + } +} + +export function transitionSshMain(state: SshMainState, event: SshMainEvent): SshMainTransition { + if (state.status === "closed") { + if (event.type === "resolve.requested") return { state, effects: [resolved([event.waiter], null)] } + + return unchanged(state) + } + + if (event.type === "start") return start(state, event.request, event.owner) + + if (event.type === "close") return close(state) + + if (event.type === "window.detached") + return state.servers.reduce((result, server) => { + const next = cancel(result.state, server.config.id, event.owner) + + return { state: next.state, effects: [...result.effects, ...next.effects] } + }, unchanged(state)) + + if (event.type === "cancel") return cancel(state, event.id, event.owner) + + const server = state.servers.find((item) => item.config.id === event.id) + + if (!server) { + if (event.type === "resolve.requested") return { state, effects: [resolved([event.waiter], null)] } + + return unchanged(state) + } + + const phase = server.phase + + if (event.type === "forget") + return { + state: { ...state, servers: state.servers.filter((item) => item !== server) }, + effects: [ + ...halt(phase), + ...release(server.waiters), + ...(server.savedConfig ? [save(state.servers.filter((item) => item !== server))] : []), + ], + } + + if (event.type === "resolve.requested") { + if (phase.status === "ready") + return { + state: put(state, { ...server, waiters: [...server.waiters, event.waiter] }), + effects: [ + { type: "health.probe", id: event.id, attempt: phase.attempt, http: phase.http, waiter: event.waiter }, + ], + } + + if (isActive(phase) || (phase.status === "failed" && phase.retry)) + return { state: put(state, { ...server, waiters: [...server.waiters, event.waiter] }), effects: [] } + + return { state, effects: [resolved([event.waiter], null)] } + } + + if (event.type === "resolve.aborted") { + if (!server.waiters.includes(event.waiter)) return unchanged(state) + + return { state: put(state, { ...server, waiters: without(server.waiters, event.waiter) }), effects: [] } + } + + if (event.type === "health.probed") { + if (!server.waiters.includes(event.waiter) || phase.status !== "ready") return unchanged(state) + + // Another attempt already replaced the probed tunnel and is ready: its endpoint answers. + if (event.healthy || phase.attempt !== event.attempt) + return { + state: put(state, { ...server, waiters: without(server.waiters, event.waiter) }), + effects: [resolved([event.waiter], phase.http)], + } + + const attempt = state.issued + 1 + + return { + state: put( + { ...state, issued: attempt }, + { + ...server, + phase: { status: "connecting", attempt, failures: 0, resting: { status: "disconnected" } }, + }, + ), + effects: [ + { type: "attempt.stop", attempt: phase.attempt }, + { type: "attempt.start", id: event.id, attempt, config: server.config, replace: false }, + ], + } + } + + if (event.type === "retry.due") { + if (phase.status !== "failed" || phase.retry?.attempt !== event.attempt) return unchanged(state) + const attempt = state.issued + 1 + + return { + state: put( + { ...state, issued: attempt }, + { + ...server, + phase: { + status: "connecting", + attempt, + failures: phase.failures, + resting: { status: "failed", code: phase.code, detail: phase.detail, failures: phase.failures }, + }, + }, + ), + effects: [{ type: "attempt.start", id: event.id, attempt, config: server.config, replace: false }], + } + } + + if (event.type === "respond") { + if (phase.status !== "authenticating" || phase.owner !== event.owner || phase.prompt.id !== event.promptID) + return unchanged(state) + + return { + state, + effects: [{ type: "attempt.respond", attempt: phase.attempt, promptID: event.promptID, value: event.value }], + } + } + + if (event.type === "attempt.failed") { + if ((!isActive(phase) && phase.status !== "ready") || phase.attempt !== event.attempt) return unchanged(state) + + return failed(state, server, event.code, event.detail, (phase.status === "ready" ? 0 : phase.failures) + 1) + } + + if (!isActive(phase) || phase.attempt !== event.attempt) return unchanged(state) + + if (event.type === "destination.resolved") + return { state: put(state, { ...server, destination: event.destination }), effects: [] } + + if (event.type === "prompt.received") { + // A background attempt has nobody to answer its prompt: the server waits for the user to sign in. + if (phase.owner === undefined) + return { + state: put(state, { ...server, phase: { status: "authentication" }, waiters: [] }), + effects: [{ type: "attempt.stop", attempt: phase.attempt }, ...release(server.waiters)], + } + + return { + state: put(state, { + ...server, + phase: { ...phase, status: "authenticating", owner: phase.owner, prompt: event.prompt }, + }), + effects: [], + } + } + + if (event.type === "prompt.cleared") { + if (phase.status !== "authenticating" || phase.prompt.id !== event.promptID) return unchanged(state) + + return { + state: put(state, { + ...server, + phase: { + status: "connecting", + attempt: phase.attempt, + owner: phase.owner, + failures: phase.failures, + resting: phase.resting, + }, + }), + effects: [], + } + } + + const ready = put(state, { + ...server, + savedConfig: server.config, + phase: { status: "ready", attempt: phase.attempt, http: event.http }, + waiters: [], + }) + + return { + state: ready, + effects: [save(ready.servers), ...(server.waiters.length ? [resolved(server.waiters, event.http)] : [])], + } +} + +/** Every window's view of the servers; a prompt reaches only the window that started its attempt. */ +export function selectSshServers(state: SshMainState, viewer?: number): SshItem[] { + return state.servers.map((server) => { + const phase = server.phase + + return { + config: server.config, + saved: !!server.savedConfig, + destination: server.destination, + stage: phase.status === "authenticating" ? "authentication" : phase.status, + // Only a ready server has an endpoint. + http: phase.status === "ready" ? phase.http : undefined, + prompt: phase.status === "authenticating" && phase.owner === viewer ? phase.prompt : undefined, + authenticatingElsewhere: phase.status === "authenticating" && phase.owner !== viewer, + retrying: phase.status === "failed" && phase.retry ? true : undefined, + detail: phase.status === "failed" || phase.status === "incompatible" ? phase.detail : "", + error: error(phase), + } + }) +} + +function error(phase: SshServerPhase): SshError | undefined { + if (phase.status === "failed") return phase.code + + if (phase.status === "incompatible") return "version" + + return undefined +} + +/** An interactive attempt waits on its prompt; the remote service may take that long to answer. */ +export function selectSshAuthenticating(state: SshMainState, id: string, attempt: number) { + const phase = state.servers.find((server) => server.config.id === id)?.phase + + return phase?.status === "authenticating" && phase.attempt === attempt +} + +function start(state: SshMainState, request: SshStart, owner: number | undefined): SshMainTransition { + const id = request.id + + if (!/^[a-zA-Z0-9-]{1,80}$/.test(id)) return unchanged(state) + const server = state.servers.find((item) => item.config.id === id) + const phase = server?.phase ?? DISCONNECTED + + // A second window must not replace an interactive attempt while its owner connects or answers a challenge. + if (isActive(phase) && phase.owner !== undefined && phase.owner !== owner) return unchanged(state) + + // A background restore joins a server that is already connecting or ready. + if (request.background && (isActive(phase) || phase.status === "ready")) return unchanged(state) + const attempt = state.issued + 1 + const config = { id, target: request.target.trim(), name: request.name.trim() } + + return { + state: put( + { ...state, issued: attempt }, + { + config, + savedConfig: server?.savedConfig, + destination: server?.destination, + phase: { + status: "connecting", + attempt, + owner: request.background ? undefined : owner, + // The user asking again starts a new retry budget; a background restore keeps the one it had. + failures: request.background && phase.status === "failed" ? phase.failures : 0, + resting: resting(phase), + }, + waiters: server?.waiters ?? [], + }, + ), + effects: [...halt(phase), { type: "attempt.start", id, attempt, config, replace: !!request.replace }], + } +} + +function failed( + state: SshMainState, + server: SshServerRecord, + reported: SshError, + detail: string, + failures: number, +): SshMainTransition { + const code = /REMOTE HOST IDENTIFICATION HAS CHANGED|Host key verification failed/.test(detail) + ? "host-key" + : /spawn .*ENOENT/.test(detail) + ? "ssh-missing" + : reported + + // A failed attempt shows the saved server again, not the target it tried. + const config = server.savedConfig ?? server.config + + if (code === "version") + return { + state: put(state, { ...server, config, phase: { status: "incompatible", detail }, waiters: [] }), + effects: release(server.waiters), + } + + // Only a saved server reconnects by itself, and only from failures that another try can fix. + const retry = + !!server.savedConfig && + failures < SSH_RETRY_LIMIT && + !["input", "platform", "unpublished", "host-key", "ssh-missing"].includes(code) && + !/Permission denied/.test(detail) + + if (!retry) + return { + state: put(state, { ...server, config, phase: { status: "failed", code, detail, failures }, waiters: [] }), + effects: release(server.waiters), + } + + const attempt = state.issued + 1 + + return { + state: put( + { ...state, issued: attempt }, + { ...server, config, phase: { status: "failed", code, detail, failures, retry: { attempt } } }, + ), + effects: [{ type: "retry.schedule", id: server.config.id, attempt, delayMs: SSH_RETRY_DELAY_MS }], + } +} + +function cancel(state: SshMainState, id: string, owner: number): SshMainTransition { + const server = state.servers.find((item) => item.config.id === id) + const phase = server?.phase + + if (!server || !phase || !isActive(phase) || phase.owner !== owner) return unchanged(state) + const effects = [{ type: "attempt.stop", attempt: phase.attempt } as const, ...release(server.waiters)] + + // A server the window was adding is gone with its attempt. + if (!server.savedConfig) + return { state: { ...state, servers: state.servers.filter((item) => item !== server) }, effects } + + return { + state: put(state, { ...server, config: server.savedConfig, phase: phase.resting, waiters: [] }), + effects, + } +} + +function close(state: SshMainState): SshMainTransition { + return { + state: { + ...state, + status: "closed", + servers: state.servers.map((server) => ({ ...server, phase: DISCONNECTED, waiters: [] })), + }, + effects: [ + ...state.servers.flatMap((server) => halt(server.phase)), + ...release(state.servers.flatMap((server) => server.waiters)), + ], + } +} + +function resting(phase: SshServerPhase): SshResting { + if (isActive(phase)) return phase.resting + + if (phase.status === "authentication") return phase + + if (phase.status === "incompatible") return { status: "incompatible", detail: phase.detail } + + if (phase.status === "failed") + return { status: "failed", code: phase.code, detail: phase.detail, failures: phase.failures } + + return { status: "disconnected" } +} + +/** Stops whatever runs for the server: its connect, its tunnel, or its scheduled retry. */ +function halt(phase: SshServerPhase): SshMainEffect[] { + if (isActive(phase) || phase.status === "ready") return [{ type: "attempt.stop", attempt: phase.attempt }] + + if (phase.status === "failed" && phase.retry) return [{ type: "retry.cancel", attempt: phase.retry.attempt }] + + return [] +} + +function isActive(phase: SshServerPhase): phase is Active { + return phase.status === "connecting" || phase.status === "authenticating" +} + +function put(state: SshMainState, server: SshServerRecord): SshMainState { + const found = state.servers.some((item) => item.config.id === server.config.id) + + return { + ...state, + servers: found + ? state.servers.map((item) => (item.config.id === server.config.id ? server : item)) + : [...state.servers, server], + } +} + +function save(servers: readonly SshServerRecord[]): SshMainEffect { + return { + type: "configs.save", + configs: servers.flatMap((server) => (server.savedConfig ? [server.savedConfig] : [])), + } +} + +function release(waiters: readonly number[]): SshMainEffect[] { + return waiters.length ? [resolved(waiters, null)] : [] +} + +function resolved(waiters: readonly number[], http: SshHttp | null): SshMainEffect { + return { type: "waiters.resolve", waiters, http } +} + +function without(waiters: readonly number[], waiter: number) { + return waiters.filter((item) => item !== waiter) +} + +function unchanged(state: SshMainState): SshMainTransition { + return { state, effects: [] } +} diff --git a/packages/gui-plugins/src/ssh/name.ts b/packages/gui-plugins/src/ssh/name.ts index a880e5cc55c..1db4898ba1b 100644 --- a/packages/gui-plugins/src/ssh/name.ts +++ b/packages/gui-plugins/src/ssh/name.ts @@ -16,19 +16,9 @@ export function sshName(config: Pick) { return config.name || sshHostname(config.target) } -export function isSshConnecting(stage: SshItem["stage"]) { - return ( - stage === "connecting" || - stage === "checking" || - stage === "downloading" || - stage === "uploading" || - stage === "starting" - ) -} - /** Another window answering the challenge reads as connecting here, not as a prompt of its own. */ export function sshServerState(item: SshItem): ServerState { - if (isSshConnecting(item.stage) || item.authenticatingElsewhere) return "starting" + if (item.stage === "connecting" || item.authenticatingElsewhere) return "starting" if (item.stage === "authentication") return "auth" diff --git a/packages/gui-plugins/src/ssh/renderer.tsx b/packages/gui-plugins/src/ssh/renderer.tsx index 29ef5e04f64..46ee8535245 100644 --- a/packages/gui-plugins/src/ssh/renderer.tsx +++ b/packages/gui-plugins/src/ssh/renderer.tsx @@ -32,23 +32,22 @@ const setup: Plugin.Setup = (ctx) => { const ssh = createSshController({ items: () => state()?.servers ?? [], api: client, - // Resolves once main publishes the revision; disabling the plugin resolves it early. - refresh: (revision) => + // Resolves once main publishes the revision. Disabling the plugin, the attempt ending, or the main side going away + // (a restarted main starts its revisions again) resolves it early. + refresh: (revision, signal) => new Promise((resolve) => createRoot((dispose) => { const done = () => { + ctx.signal.removeEventListener("abort", done) + signal.removeEventListener("abort", done) dispose() resolve() } + if (ctx.signal.aborted || signal.aborted) return done() ctx.signal.addEventListener("abort", done, { once: true }) - createKeyed( - () => (state()?.revision ?? 0) >= revision, - () => { - ctx.signal.removeEventListener("abort", done) - done() - }, - ) + signal.addEventListener("abort", done, { once: true }) + createKeyed(() => ipc().status !== "active" || (state()?.revision ?? 0) >= revision, done) }), ), error: () => showToast({ variant: "error", title: ctx.t("common.requestFailed") }), @@ -60,13 +59,16 @@ const setup: Plugin.Setup = (ctx) => { const styled = { added: false } const byKey = (key: string) => (key.startsWith("ssh:") ? ssh.item(key.slice(4)) : undefined) + const open = (module: Awaited>, render: () => JSX.Element) => { + if (!styled.added) ctx.add(Style, module.css) + styled.added = true + dialog.open(render) + } + const show = (render: (module: Awaited>) => JSX.Element) => void loadDialog().then((module) => { if (ctx.signal.aborted) return - - if (!styled.added) ctx.add(Style, module.css) - styled.added = true - dialog.open(() => render(module)) + open(module, () => render(module)) }) const add = (openProject: boolean) => @@ -175,31 +177,25 @@ const setup: Plugin.Setup = (ctx) => { }), ) - // Reconnect saved servers in the background once per window. Mark active - // connections too, so a later manual disconnect is respected. - const restored = new Set() - - createKeyed( - () => { - const unseen = (state()?.servers ?? []).filter((item) => item.saved && !restored.has(item.config.id)) - - return unseen.length > 0 ? unseen : undefined - }, - (unseen) => - unseen.forEach((item) => { - restored.add(item.config.id) - - if (item.stage === "disconnected") void ssh.restore(item.config) - }), - ) - - // Challenges of an attempt started without its dialog open one of their own. + // Challenges of an attempt started without its dialog open one of their own. The attempt holds the dialog while its + // chunk loads, and a chunk that fails to load ends the attempt. createKeyed( () => (dialog.active() ? undefined : ssh.dialog.next()), - (item) => { - ssh.dialog.opened(item.config.id) - const config = item.config - show((module) => ) + (target) => { + const id = target.item.config.id + const config = target.item.config + ssh.dialog.loading(id, target.attempt) + void loadDialog().then( + (module) => { + if (ctx.signal.aborted || !ssh.dialog.canOpen(id, target.attempt)) return + ssh.dialog.opened(id, target.attempt) + open(module, () => ) + }, + () => ssh.dialog.failed(id, target.attempt), + ) + }, + { + equals: (previous, next) => previous.item.config.id === next.item.config.id && previous.attempt === next.attempt, }, ) } diff --git a/packages/gui-plugins/src/ssh/row.tsx b/packages/gui-plugins/src/ssh/row.tsx index 1d6a6c3db7c..042029dde1f 100644 --- a/packages/gui-plugins/src/ssh/row.tsx +++ b/packages/gui-plugins/src/ssh/row.tsx @@ -5,7 +5,7 @@ import { Menu } from "@opencode/ui/menu" import { Loader } from "@opencode/ui/loader" import { Show } from "solid-js" import { usePlugin, type ServerRow } from "@opencode/plugin/gui" -import { isSshConnecting, sshName } from "./name" +import { sshName } from "./name" import type { SshController } from "./state" export default function SshRow(props: { row: ServerRow; id: string; ssh: SshController }) { @@ -30,7 +30,7 @@ export default function SshRow(props: { row: ServerRow; id: string; ssh: SshCont
diff --git a/packages/gui-plugins/src/ssh/state.ts b/packages/gui-plugins/src/ssh/state.ts index 2fc6d0adab5..b7038bf1567 100644 --- a/packages/gui-plugins/src/ssh/state.ts +++ b/packages/gui-plugins/src/ssh/state.ts @@ -1,209 +1,190 @@ -import { Effect, Fiber, Schedule } from "effect" -import { onCleanup, type Accessor } from "solid-js" -import { createStore } from "solid-js/store" +import { createRoot, createSignal, onCleanup, untrack, type Accessor } from "solid-js" import { createKeyed, type IpcClient } from "@opencode/plugin/gui" -import type { Ssh, SshConfig, SshItem } from "./contract" -import { isSshConnecting } from "./name" +import type { Ssh, SshConfig, SshHttp, SshItem } from "./contract" +import { + createSshWindowState, + selectSshAnswered, + selectSshCanOpenDialog, + selectSshError, + selectSshPending, + selectSshPromptTarget, + selectSshResolvable, + selectSshSubmitting, + transitionSshWindow, + type SshWindowEffect, + type SshWindowEvent, +} from "./window-machine" export type SshController = ReturnType +type SshApi = IpcClient<(typeof Ssh)["spec"]> + +/** Runs this window's SSH attempts through the machine in `./window-machine`; main owns the connections. */ export function createSshController(input: { items: () => readonly SshItem[] /** Undefined while the main side is loading or gone. */ - api: Accessor | undefined> - /** Resolves once this window's state includes `revision`. */ - refresh: (revision: number) => Promise + api: Accessor + /** Resolves once this window's state includes `revision`, the main side goes away, or `signal` aborts. */ + refresh: (revision: number, signal: AbortSignal) => Promise error: () => void }) { - const [attempts, setAttempts] = createStore< - Record< - string, - | { - active: boolean - submitting: boolean - prompted: boolean - answered?: string - error: boolean - onConnected?: (ready: boolean) => void - } - | undefined - > - >({}) - - const tasks = new Map>() + // The machine state is immutable; each transition replaces it whole. + const [machine, setMachine] = createSignal(createSshWindowState()) + // Aborts the wait for an admitted attempt's state, per server. + const tasks = new Map() + const lifetime = new AbortController() const item = (id: string) => input.items().find((item) => item.config.id === id) + const current = (id: string) => untrack(() => item(id)) - const settle = (id: string) => { - const attempt = attempts[id] + const dispatch = (event: SshWindowEvent) => { + const previous = untrack(machine) + const next = transitionSshWindow(previous, event) - if (!attempt?.active) return - const onConnected = attempt.onConnected - setAttempts(id, { active: false, onConnected: undefined }) - const ready = item(id)?.stage === "ready" - - if (onConnected) queueMicrotask(() => onConnected(ready)) + if (next.state !== previous) setMachine(next.state) + next.effects.forEach(run) } - const run = (id: string, effect: Effect.Effect) => { - setAttempts(id, { submitting: true, error: false }) - tasks.set( - id, - Effect.runFork( - effect.pipe( - Effect.asVoid, - Effect.catch(() => - Effect.sync(() => { - setAttempts(id, "error", true) + const run = (effect: SshWindowEffect) => { + if (effect.type === "task.abort") { + tasks.get(effect.id)?.abort() + tasks.delete(effect.id) - if (!attempts[id]?.prompted) input.error() - }), - ), - Effect.ensuring( - Effect.sync(() => { - tasks.delete(id) - setAttempts(id, "submitting", false) - }), - ), - ), - ), + return + } + + if (effect.type === "toast.error") return input.error() + + if (effect.type === "waiters.notify") + return queueMicrotask(() => effect.waiters.forEach((waiter) => waiter(effect.ready))) + const api = untrack(input.api) + + // Restores and cancels answer nobody; a main side that went away has nothing left to restore or cancel. + if (effect.type === "rpc.restore") return void api?.start({ ...effect.config, background: true }).catch(() => {}) + + if (effect.type === "rpc.cancel") + return void api + ?.cancel({ id: effect.id }) + .then(() => (effect.forget ? api.forget({ id: effect.id }) : undefined)) + .catch(() => {}) + + if (effect.type === "rpc.respond") { + const attempt = effect.attempt + + if (!api) return dispatch({ type: "respond.failed", id: effect.id, attempt }) + + return void api.respond({ id: effect.id, prompt: effect.prompt, value: effect.value }).then( + () => dispatch({ type: "respond.succeeded", id: effect.id, attempt, item: current(effect.id) }), + () => dispatch({ type: "respond.failed", id: effect.id, attempt }), + ) + } + + const id = effect.id + const attempt = effect.attempt + + if (!api) return dispatch({ type: "start.failed", id, attempt }) + const abort = new AbortController() + tasks.set(id, abort) + + void api + .start({ ...effect.config, replace: effect.replace }) + // Observe admission before treating an older disconnected snapshot as the attempt's outcome. + .then((revision) => input.refresh(revision, AbortSignal.any([abort.signal, lifetime.signal]))) + .then( + () => dispatch({ type: "start.confirmed", id, attempt, item: current(id) }), + () => dispatch({ type: "start.failed", id, attempt }), + ) + .finally(() => { + if (tasks.get(id) === abort) tasks.delete(id) + }) + } + + /** Waits until a call to main can answer with the server's endpoint: never while main or the server is paused. */ + const resolvable = (id: string, seen: readonly SshItem[] | undefined, signal: AbortSignal) => + new Promise((done, fail) => + createRoot((dispose) => { + const aborted = () => { + dispose() + fail(signal.reason) + } + + if (signal.aborted) return aborted() + signal.addEventListener("abort", aborted, { once: true }) + createKeyed( + () => { + const items = input.items() + const api = input.api() + + // After a `null`, only a newer state can change the answer. + if (items === seen || !api) return undefined + + return selectSshResolvable( + true, + items.find((item) => item.config.id === id), + ) + ? api + : undefined + }, + (api) => { + signal.removeEventListener("abort", aborted) + dispose() + done(api) + }, + ) + }), ) - } - // Without the main side nothing can connect or answer: the attempt fails at once, as one main rejects. - const unavailable = (id: string, onConnected?: (ready: boolean) => void) => { - setAttempts(id, { active: false, submitting: false, error: true, onConnected: undefined }) - input.error() + const resolve = (id: string, signal: AbortSignal, seen?: readonly SshItem[]): Promise => + resolvable(id, seen, signal).then((api) => { + const items = untrack(input.items) - if (onConnected) queueMicrotask(() => onConnected(false)) - } + return api.resolve({ id }, { signal }).then((http) => http ?? resolve(id, signal, items)) + }) onCleanup(() => { - Effect.runFork(Effect.forEach([...tasks.values()], Fiber.interrupt, { discard: true })) + lifetime.abort() + dispatch({ type: "disposed" }) }) - // Attempts whose server reached an outcome in main's state: they settle and tell whoever waits on them. + + // Follows main's state: attempts it shows an outcome for settle, and saved servers this window has not seen restore. createKeyed( - () => { - const done = input.items().flatMap((item) => { - const attempt = attempts[item.config.id] - - if (!attempt?.active || attempt.submitting) return [] - - return item.stage === "ready" || - item.stage === "failed" || - item.stage === "disconnected" || - item.authenticatingElsewhere || - (attempt.prompted && item.stage === "authentication" && !item.prompt) - ? [item.config.id] - : [] - }) - - return done.length > 0 ? done : undefined - }, - (done) => done.forEach(settle), + () => ({ ipcActive: !!input.api(), items: input.items() }), + (synced) => dispatch({ type: "items.synced", ipcActive: synced.ipcActive, items: synced.items }), + { equals: (previous, next) => previous.ipcActive === next.ipcActive && previous.items === next.items }, ) return { item, - submitting: (id: string) => !!attempts[id]?.submitting, - error: (id: string) => !!attempts[id]?.error, - answered: (id: string) => - !!item(id)?.prompt && !attempts[id]?.error && attempts[id]?.answered === item(id)?.prompt?.id, - pending: (id: string) => - !!attempts[id]?.submitting || - !!item(id)?.authenticatingElsewhere || - isSshConnecting(item(id)?.stage ?? "disconnected"), + submitting: (id: string) => selectSshSubmitting(machine(), id), + error: (id: string) => selectSshError(machine(), id), + answered: (id: string) => selectSshAnswered(machine(), id, item(id)), + pending: (id: string) => selectSshPending(machine(), id, item(id)), dialog: { - next: () => - input.items().find((item) => { - const attempt = attempts[item.config.id] - - return ( - attempt?.active && - !attempt.submitting && - !attempt.prompted && - !attempt.error && - (item.prompt || item.stage === "incompatible") - ) - }), - opened: (id: string) => setAttempts(id, "prompted", true), + /** The attempt whose prompt needs a dialog of its own. */ + next: () => selectSshPromptTarget(machine(), input.items()), + loading: (id: string, attempt: number) => dispatch({ type: "dialog.loading", id, attempt }), + canOpen: (id: string, attempt: number) => selectSshCanOpenDialog(untrack(machine), id, attempt), + opened: (id: string, attempt: number) => dispatch({ type: "dialog.opened", id, attempt }), + failed: (id: string, attempt: number) => + dispatch({ type: "dialog.failed", id, attempt, saved: !!current(id)?.saved }), }, /** `onConnected` runs once the attempt settles, with whether the server is ready. */ connect: ( config: SshConfig, options?: { dialog?: boolean; replace?: boolean; onConnected?: (ready: boolean) => void }, - ) => { - const api = input.api() - - if (!api) return unavailable(config.id, options?.onConnected) - - if (item(config.id)?.authenticatingElsewhere) return - - if ( - attempts[config.id]?.submitting || - (attempts[config.id]?.active && !attempts[config.id]?.error && !options?.replace) - ) - return - setAttempts(config.id, { - active: true, - submitting: true, - prompted: !!options?.dialog, - answered: undefined, - error: false, - onConnected: options?.onConnected ?? (options?.replace ? attempts[config.id]?.onConnected : undefined), - }) - run( - config.id, - Effect.gen(function* () { - const revision = yield* Effect.tryPromise(() => api.start({ ...config, replace: options?.replace })) - // Observe admission before treating an older disconnected snapshot as cancellation. - yield* Effect.tryPromise(() => input.refresh(revision)) - }), - ) - }, - respond: (id: string, prompt: string, value: string) => { - const api = input.api() - - if (!api) return unavailable(id) - - if (item(id)?.prompt?.id !== prompt || attempts[id]?.submitting) return - - if (attempts[id]?.answered === prompt && !attempts[id]?.error) return - setAttempts(id, "answered", prompt) - run( - id, - Effect.tryPromise(() => api.respond({ id, prompt, value })), - ) - }, - cancel: (id: string) => { - const task = tasks.get(id) - const api = input.api() - Effect.runFork( - Effect.gen(function* () { - if (task) yield* Fiber.interrupt(task) - setAttempts(id, undefined) - - if (!api) return - yield* Effect.tryPromise(() => api.cancel({ id })) - - if (!item(id)?.saved) yield* Effect.tryPromise(() => api.forget({ id })) - }).pipe(Effect.ignore), - ) - }, - restore: (config: SshConfig) => input.api()?.start({ ...config, background: true }), - /** Waits for a healthy tunnel, starting one in the background when the last one dropped. */ - resolve: (id: string, signal: AbortSignal) => - Effect.runPromise( - Effect.tryPromise((abort) => { - const api = input.api() - - if (!api) return Promise.resolve(null) - - return api.resolve({ id }, { signal: abort }) - }).pipe( - Effect.repeat({ until: (http) => http !== null, schedule: Schedule.spaced(3000) }), - Effect.flatMap((http) => (http === null ? Effect.interrupt : Effect.succeed(http))), - ), - { signal }, - ), + ) => + dispatch({ + type: "connect.requested", + config, + ipcActive: !!untrack(input.api), + item: current(config.id), + dialog: options?.dialog, + replace: options?.replace, + onConnected: options?.onConnected, + }), + respond: (id: string, prompt: string, value: string) => + dispatch({ type: "respond.requested", id, prompt, value, ipcActive: !!untrack(input.api), item: current(id) }), + cancel: (id: string) => dispatch({ type: "cancel.requested", id, saved: !!current(id)?.saved }), + /** Waits for a healthy tunnel; main reconnects a dropped one by itself. */ + resolve: (id: string, signal: AbortSignal) => resolve(id, AbortSignal.any([signal, lifetime.signal])), } } diff --git a/packages/gui-plugins/src/ssh/window-machine.test.ts b/packages/gui-plugins/src/ssh/window-machine.test.ts new file mode 100644 index 00000000000..14538886eb4 --- /dev/null +++ b/packages/gui-plugins/src/ssh/window-machine.test.ts @@ -0,0 +1,243 @@ +import { describe, expect, test } from "bun:test" +import { Schema } from "effect" +import { SshItem, SshState } from "./contract" +import { + createSshWindowState, + selectSshError, + selectSshPromptTarget, + selectSshResolvable, + transitionSshWindow, + type SshWindowEffect, + type SshWindowEvent, + type SshWindowState, +} from "./window-machine" + +const config = { id: "box", target: "ssh box", name: "Box" } + +const prompt = { id: "password", text: "box's password:", confirm: false } + +// Main's state reaches the window through the Ipc, which decodes it. +function server(fields: Partial): SshItem { + const state = Schema.decodeUnknownSync(SshState)({ + revision: 1, + servers: [{ config, saved: true, detail: "", ...fields }], + }) + + const item = state.servers[0] + + if (!item) throw new Error("expected a server") + + return item +} + +function replay(state: SshWindowState, events: readonly SshWindowEvent[]) { + return events.reduce<{ state: SshWindowState; effects: SshWindowEffect[] }>( + (result, event) => { + const next = transitionSshWindow(result.state, event) + + return { state: next.state, effects: [...result.effects, ...next.effects] } + }, + { state, effects: [] }, + ) +} + +function connect( + onConnected?: (ready: boolean) => void, + fields?: { readonly item?: SshItem; readonly dialog?: boolean }, +): SshWindowEvent { + return { + type: "connect.requested", + config, + ipcActive: true, + item: fields?.item ?? server({ stage: "authentication" }), + dialog: fields?.dialog, + onConnected, + } +} + +describe("ssh window attempt", () => { + test("cancelling the prompt tells the sign-in that waits on it", () => { + const signIn = (_ready: boolean) => {} + + const result = replay(createSshWindowState(), [ + connect(signIn), + { type: "start.confirmed", id: config.id, attempt: 1, item: server({ stage: "authentication", prompt }) }, + { type: "cancel.requested", id: config.id, saved: true }, + ]) + + expect(result.effects).toEqual([ + { type: "rpc.start", id: config.id, attempt: 1, config, replace: false }, + { type: "waiters.notify", waiters: [signIn], ready: false }, + { type: "rpc.cancel", id: config.id, forget: false }, + ]) + expect(result.state.attempts.size).toBe(0) + }) + + test("a second request joins the attempt in progress and both learn its outcome", () => { + const first = (_ready: boolean) => {} + + const second = (_ready: boolean) => {} + + const joined = replay(createSshWindowState(), [ + connect(first), + connect(second), + { type: "start.confirmed", id: config.id, attempt: 1, item: server({ stage: "connecting" }) }, + ]) + + expect(joined.effects.filter((effect) => effect.type === "rpc.start")).toHaveLength(1) + + const settled = transitionSshWindow(joined.state, { + type: "items.synced", + ipcActive: true, + items: [server({ stage: "ready", http: { url: "http://127.0.0.1:1", password: "p" } })], + }) + + expect(settled.effects).toEqual([{ type: "waiters.notify", waiters: [first, second], ready: true }]) + }) + + test("a request while another window signs in is told at once and leaves this window alone", () => { + const waiter = (_ready: boolean) => {} + + const state = createSshWindowState() + + const result = transitionSshWindow( + state, + connect(waiter, { item: server({ stage: "authentication", authenticatingElsewhere: true }) }), + ) + + expect(result.state).toBe(state) + expect(result.effects).toEqual([{ type: "waiters.notify", waiters: [waiter], ready: false }]) + }) + + test("a prompt dialog that fails to load ends the attempt instead of wedging the server", () => { + const waiter = (_ready: boolean) => {} + + const prompted = replay(createSshWindowState(), [ + connect(waiter), + { type: "start.confirmed", id: config.id, attempt: 1, item: server({ stage: "authentication", prompt }) }, + ]).state + + const items = [server({ stage: "authentication", prompt })] + expect(selectSshPromptTarget(prompted, items)).toEqual({ item: items[0], attempt: 1 }) + + const loading = transitionSshWindow(prompted, { type: "dialog.loading", id: config.id, attempt: 1 }).state + expect(selectSshPromptTarget(loading, items)).toBeUndefined() + + const failed = transitionSshWindow(loading, { type: "dialog.failed", id: config.id, attempt: 1, saved: true }) + expect(failed.effects).toEqual([ + { type: "waiters.notify", waiters: [waiter], ready: false }, + { type: "toast.error" }, + { type: "rpc.cancel", id: config.id, forget: false }, + ]) + expect(selectSshError(failed.state, config.id)).toBe(true) + + const again = transitionSshWindow(failed.state, connect()) + expect(again.effects).toEqual([{ type: "rpc.start", id: config.id, attempt: 2, config, replace: false }]) + }) + + test("a cancelled attempt's late call results do not settle the next attempt", () => { + const waiter = (_ready: boolean) => {} + + const next = replay(createSshWindowState(), [ + connect(), + { type: "cancel.requested", id: config.id, saved: true }, + connect(waiter), + ]).state + + // Main admitted the first attempt before the cancel, then restored the server. + const late: SshWindowEvent[] = [ + { type: "start.confirmed", id: config.id, attempt: 1, item: server({ stage: "disconnected" }) }, + { type: "start.failed", id: config.id, attempt: 1 }, + ] + + late.forEach((event) => expect(transitionSshWindow(next, event).state).toBe(next)) + }) + + test("an answer that fails can be sent again", () => { + const item = server({ stage: "authentication", prompt }) + + const result = replay(createSshWindowState(), [ + connect(undefined, { dialog: true }), + { type: "start.confirmed", id: config.id, attempt: 1, item }, + { type: "respond.requested", id: config.id, prompt: prompt.id, value: "a", ipcActive: true, item }, + { type: "respond.failed", id: config.id, attempt: 2 }, + { type: "respond.requested", id: config.id, prompt: prompt.id, value: "b", ipcActive: true, item }, + ]) + + expect(result.effects.filter((effect) => effect.type === "rpc.respond")).toEqual([ + { type: "rpc.respond", id: config.id, attempt: 2, prompt: prompt.id, value: "a" }, + { type: "rpc.respond", id: config.id, attempt: 3, prompt: prompt.id, value: "b" }, + ]) + // The dialog shows the failure inline instead of a toast. + expect(result.effects).not.toContainEqual({ type: "toast.error" }) + }) + + test("a server that leaves main's state ends its attempt", () => { + const waiter = (_ready: boolean) => {} + + const waiting = replay(createSshWindowState(), [ + connect(waiter), + { type: "start.confirmed", id: config.id, attempt: 1, item: server({ stage: "connecting" }) }, + ]).state + + expect(transitionSshWindow(waiting, { type: "items.synced", ipcActive: false, items: [] }).effects).toEqual([ + { type: "waiters.notify", waiters: [waiter], ready: false }, + ]) + }) + + test("each saved server restores once per window, and only while disconnected", () => { + const first = transitionSshWindow(createSshWindowState(), { + type: "items.synced", + ipcActive: true, + items: [server({ stage: "disconnected" }), { ...server({ stage: "ready" }), config: { ...config, id: "up" } }], + }) + + expect(first.effects).toEqual([{ type: "rpc.restore", config }]) + + const again = transitionSshWindow(first.state, { + type: "items.synced", + ipcActive: true, + items: [server({ stage: "disconnected" })], + }) + + expect(again.state).toBe(first.state) + expect(again.effects).toEqual([]) + }) + + test("disposing tells every waiter and later requests at once", () => { + const waiter = (_ready: boolean) => {} + + const later = (_ready: boolean) => {} + + const disposed = replay(createSshWindowState(), [connect(waiter), { type: "disposed" }]) + + expect(disposed.effects.slice(1)).toEqual([ + { type: "task.abort", id: config.id }, + { type: "waiters.notify", waiters: [waiter], ready: false }, + ]) + expect(transitionSshWindow(disposed.state, connect(later)).effects).toEqual([ + { type: "waiters.notify", waiters: [later], ready: false }, + ]) + }) +}) + +describe("ssh resolve", () => { + test("asks main only while it can answer with an endpoint", () => { + const cases: [string, boolean, SshItem | undefined, boolean][] = [ + ["main gone", false, server({ stage: "ready", http: { url: "u", password: "p" } }), false], + ["unknown server", true, undefined, false], + ["disconnected", true, server({ stage: "disconnected" }), false], + ["signing in here", true, server({ stage: "authentication" }), false], + ["incompatible", true, server({ stage: "incompatible", error: "version" }), false], + ["failed for good", true, server({ stage: "failed", error: "connection" }), false], + ["ready", true, server({ stage: "ready", http: { url: "u", password: "p" } }), true], + ["connecting", true, server({ stage: "connecting" }), true], + ["signing in elsewhere", true, server({ stage: "authentication", authenticatingElsewhere: true }), true], + ["reconnecting", true, server({ stage: "failed", error: "connection", retrying: true }), true], + ] + + cases.forEach(([name, ipcActive, item, expected]) => + expect(selectSshResolvable(ipcActive, item), name).toBe(expected), + ) + }) +}) diff --git a/packages/gui-plugins/src/ssh/window-machine.ts b/packages/gui-plugins/src/ssh/window-machine.ts new file mode 100644 index 00000000000..7f5f2af57e0 --- /dev/null +++ b/packages/gui-plugins/src/ssh/window-machine.ts @@ -0,0 +1,459 @@ +import type { SshConfig, SshItem } from "./contract" + +/** Who shows the attempt's prompts: nobody yet, a prompt dialog whose chunk is loading, or an open dialog. */ +export type SshDialogSlot = "none" | "loading" | "owned" + +type Waiter = (ready: boolean) => void + +/** + * This window's connect attempt for one server. `starting` and `answering` wait on a call to main; `waiting` follows + * main's state until the server is ready, fails, or stops. `attempt` fences the call results: a result for any other + * attempt is stale. `waiters` are told once, whichever way the attempt ends. `failed` is a call that failed; it + * shows as an error until the next attempt. + */ +export type SshAttemptState = + | { + readonly status: "starting" + readonly attempt: number + readonly dialog: SshDialogSlot + readonly waiters: readonly Waiter[] + } + | { + readonly status: "waiting" + readonly attempt: number + readonly dialog: SshDialogSlot + /** The prompt this window answered; main has not asked anything since. */ + readonly answered?: string + /** The last answer failed to reach main. */ + readonly error: boolean + readonly waiters: readonly Waiter[] + } + | { + readonly status: "answering" + readonly attempt: number + readonly dialog: SshDialogSlot + readonly prompt: string + readonly waiters: readonly Waiter[] + } + | { readonly status: "failed" } + +type Active = Exclude + +export type SshWindowState = { + readonly status: "open" | "disposed" + readonly issued: number + readonly attempts: ReadonlyMap + /** Saved servers this window has seen, each restored once. */ + readonly restored: ReadonlySet +} + +export type SshWindowEvent = + | { + readonly type: "connect.requested" + readonly config: SshConfig + readonly ipcActive: boolean + readonly item?: SshItem + readonly dialog?: boolean + readonly replace?: boolean + readonly onConnected?: Waiter + } + | { readonly type: "start.confirmed"; readonly id: string; readonly attempt: number; readonly item?: SshItem } + | { readonly type: "start.failed"; readonly id: string; readonly attempt: number } + | { + readonly type: "respond.requested" + readonly id: string + readonly prompt: string + readonly value: string + readonly ipcActive: boolean + readonly item?: SshItem + } + | { readonly type: "respond.succeeded"; readonly id: string; readonly attempt: number; readonly item?: SshItem } + | { readonly type: "respond.failed"; readonly id: string; readonly attempt: number } + | { readonly type: "dialog.loading"; readonly id: string; readonly attempt: number } + | { readonly type: "dialog.opened"; readonly id: string; readonly attempt: number } + | { readonly type: "dialog.failed"; readonly id: string; readonly attempt: number; readonly saved: boolean } + | { readonly type: "cancel.requested"; readonly id: string; readonly saved: boolean } + | { readonly type: "items.synced"; readonly ipcActive: boolean; readonly items: readonly SshItem[] } + | { readonly type: "disposed" } + +export type SshWindowEffect = + | { + readonly type: "rpc.start" + readonly id: string + readonly attempt: number + readonly config: SshConfig + readonly replace: boolean + } + | { + readonly type: "rpc.respond" + readonly id: string + readonly attempt: number + readonly prompt: string + readonly value: string + } + | { readonly type: "rpc.cancel"; readonly id: string; readonly forget: boolean } + | { readonly type: "rpc.restore"; readonly config: SshConfig } + | { readonly type: "task.abort"; readonly id: string } + | { readonly type: "toast.error" } + | { readonly type: "waiters.notify"; readonly waiters: readonly Waiter[]; readonly ready: boolean } + +export type SshWindowTransition = { + readonly state: SshWindowState + readonly effects: readonly SshWindowEffect[] +} + +export function createSshWindowState(): SshWindowState { + return { status: "open", issued: 0, attempts: new Map(), restored: new Set() } +} + +export function transitionSshWindow(state: SshWindowState, event: SshWindowEvent): SshWindowTransition { + if (state.status === "disposed") { + if (event.type === "connect.requested" && event.onConnected) + return { state, effects: [notify([event.onConnected], false)] } + + return unchanged(state) + } + + if (event.type === "disposed") { + const active = [...state.attempts.values()].filter(isActive) + + return { + state: { ...state, status: "disposed", attempts: new Map() }, + effects: [ + ...[...state.attempts].flatMap(([id, attempt]) => (isCalling(attempt) ? [abort(id)] : [])), + ...notifyAll( + active.flatMap((attempt) => attempt.waiters), + false, + ), + ], + } + } + + if (event.type === "items.synced") return synced(state, event.ipcActive, event.items) + + if (event.type === "connect.requested") return connect(state, event) + + const current = state.attempts.get(event.id) + + if (event.type === "cancel.requested") { + const effects: SshWindowEffect[] = [{ type: "rpc.cancel", id: event.id, forget: !event.saved }] + + if (!current) return { state, effects } + + return { + state: remove(state, event.id), + effects: [ + ...(isCalling(current) ? [abort(event.id)] : []), + ...(isActive(current) ? notifyAll(current.waiters, false) : []), + ...effects, + ], + } + } + + if (event.type === "respond.requested") { + if (current?.status !== "waiting") return unchanged(state) + + // Without the main side nothing can answer: the attempt fails at once, as one main rejects. + if (!event.ipcActive) + return { + state: put(state, event.id, { status: "failed" }), + effects: [{ type: "toast.error" }, ...notifyAll(current.waiters, false)], + } + + if (event.item?.prompt?.id !== event.prompt || (current.answered === event.prompt && !current.error)) + return unchanged(state) + const attempt = state.issued + 1 + + return { + state: put({ ...state, issued: attempt }, event.id, { + status: "answering", + attempt, + dialog: current.dialog, + prompt: event.prompt, + waiters: current.waiters, + }), + effects: [{ type: "rpc.respond", id: event.id, attempt, prompt: event.prompt, value: event.value }], + } + } + + if (!current || current.status === "failed" || current.attempt !== event.attempt) return unchanged(state) + + if (event.type === "start.confirmed") { + if (current.status !== "starting") return unchanged(state) + + return wait(state, event.id, { ...current, status: "waiting", error: false }, event.item) + } + + if (event.type === "start.failed") { + if (current.status !== "starting") return unchanged(state) + + return { + state: put(state, event.id, { status: "failed" }), + effects: [...notifyAll(current.waiters, false), ...(current.dialog === "none" ? [toast] : [])], + } + } + + if (event.type === "respond.succeeded") { + if (current.status !== "answering") return unchanged(state) + + return wait( + state, + event.id, + { + status: "waiting", + attempt: current.attempt, + dialog: current.dialog, + answered: current.prompt, + error: false, + waiters: current.waiters, + }, + event.item, + ) + } + + if (event.type === "respond.failed") { + if (current.status !== "answering") return unchanged(state) + + return { + state: put(state, event.id, { + status: "waiting", + attempt: current.attempt, + dialog: current.dialog, + error: true, + waiters: current.waiters, + }), + effects: current.dialog === "none" ? [toast] : [], + } + } + + if (current.status !== "waiting") return unchanged(state) + + if (event.type === "dialog.loading") { + if (current.dialog !== "none") return unchanged(state) + + return { state: put(state, event.id, { ...current, dialog: "loading" }), effects: [] } + } + + if (current.dialog !== "loading") return unchanged(state) + + if (event.type === "dialog.opened") + return { state: put(state, event.id, { ...current, dialog: "owned" }), effects: [] } + + // The prompt dialog could not load: nobody can answer, so the attempt ends instead of waiting forever. + return { + state: put(state, event.id, { status: "failed" }), + effects: [...notifyAll(current.waiters, false), toast, { type: "rpc.cancel", id: event.id, forget: !event.saved }], + } +} + +/** A call to main for the attempt is in flight. */ +export function selectSshSubmitting(state: SshWindowState, id: string) { + const attempt = state.attempts.get(id) + + return attempt?.status === "starting" || attempt?.status === "answering" +} + +export function selectSshError(state: SshWindowState, id: string) { + const attempt = state.attempts.get(id) + + return attempt?.status === "failed" || (attempt?.status === "waiting" && attempt.error) +} + +/** This window answered the prompt main shows now. */ +export function selectSshAnswered(state: SshWindowState, id: string, item: SshItem | undefined) { + const attempt = state.attempts.get(id) + + return !!item?.prompt && attempt?.status === "waiting" && !attempt.error && attempt.answered === item.prompt.id +} + +/** The server connects, here or in another window, and a new connect would only join it. */ +export function selectSshPending(state: SshWindowState, id: string, item: SshItem | undefined) { + return selectSshSubmitting(state, id) || !!item?.authenticatingElsewhere || item?.stage === "connecting" +} + +/** The next attempt whose prompt or update step needs a dialog of its own, while no other dialog shows. */ +export function selectSshPromptTarget(state: SshWindowState, items: readonly SshItem[]) { + return items.flatMap((item) => { + const attempt = state.attempts.get(item.config.id) + + return attempt?.status === "waiting" && + attempt.dialog === "none" && + !attempt.error && + (item.prompt || item.stage === "incompatible") + ? [{ item, attempt: attempt.attempt }] + : [] + })[0] +} + +/** The prompt dialog may open for the attempt: it is still the one that started loading it. */ +export function selectSshCanOpenDialog(state: SshWindowState, id: string, attempt: number) { + const current = state.attempts.get(id) + + return current?.status === "waiting" && current.attempt === attempt && current.dialog === "loading" +} + +/** + * Whether asking main for the server's endpoint can answer now. While main is gone, or the server waits for the + * user (disconnected, signing in here, incompatible, or failed for good), a call would only return `null`. + */ +export function selectSshResolvable(ipcActive: boolean, item: SshItem | undefined) { + if (!ipcActive || !item) return false + + return ( + item.stage === "ready" || + item.stage === "connecting" || + !!item.authenticatingElsewhere || + (item.stage === "failed" && !!item.retrying) + ) +} + +function connect( + state: SshWindowState, + event: Extract, +): SshWindowTransition { + const id = event.config.id + const current = state.attempts.get(id) + + const waiters = [ + ...(current && isActive(current) ? current.waiters : []), + ...(event.onConnected ? [event.onConnected] : []), + ] + + // Without the main side nothing can connect: the attempt fails at once, as one main rejects. + if (!event.ipcActive) + return { + state: put(state, id, { status: "failed" }), + effects: [...(current && isCalling(current) ? [abort(id)] : []), toast, ...notifyAll(waiters, false)], + } + + // Another window answers the server's prompt; this one cannot join it. + if (event.item?.authenticatingElsewhere) + return { state, effects: event.onConnected ? [notify([event.onConnected], false)] : [] } + + // A second request joins the attempt in progress; a dialog that opens for it shows its prompts. + if (current && isActive(current) && !event.replace && !(current.status === "waiting" && current.error)) + return { + state: put(state, id, { + ...current, + dialog: event.dialog && current.dialog === "none" ? "owned" : current.dialog, + waiters, + }), + effects: [], + } + const attempt = state.issued + 1 + + return { + state: put({ ...state, issued: attempt }, id, { + status: "starting", + attempt, + dialog: event.dialog ? "owned" : current && isActive(current) ? current.dialog : "none", + waiters, + }), + effects: [ + ...(current && isCalling(current) ? [abort(id)] : []), + { type: "rpc.start", id, attempt, config: event.config, replace: !!event.replace }, + ], + } +} + +function synced(state: SshWindowState, ipcActive: boolean, items: readonly SshItem[]): SshWindowTransition { + // Saved servers reconnect in the background once per window. Connected ones count as seen too, so a later + // disconnect is respected. + const unseen = items.filter((item) => item.saved && !state.restored.has(item.config.id)) + + const settled = [...state.attempts].flatMap(([id, attempt]) => { + if (attempt.status !== "waiting") return [] + + const outcome = settle( + attempt, + items.find((item) => item.config.id === id), + ) + + return outcome === undefined ? [] : [{ id, waiters: attempt.waiters, ready: outcome }] + }) + + if (unseen.length === 0 && settled.length === 0) return unchanged(state) + const attempts = new Map(state.attempts) + settled.forEach((item) => attempts.delete(item.id)) + + return { + state: { + ...state, + attempts, + restored: unseen.length ? new Set([...state.restored, ...unseen.map((item) => item.config.id)]) : state.restored, + }, + effects: [ + ...(ipcActive + ? unseen.flatMap((item): SshWindowEffect[] => + item.stage === "disconnected" ? [{ type: "rpc.restore", config: item.config }] : [], + ) + : []), + ...settled.flatMap((item) => notifyAll(item.waiters, item.ready)), + ], + } +} + +/** Waits on main's state, or settles at once when it already shows the outcome. */ +function wait( + state: SshWindowState, + id: string, + attempt: Extract, + item: SshItem | undefined, +): SshWindowTransition { + const outcome = settle(attempt, item) + + if (outcome === undefined) return { state: put(state, id, attempt), effects: [] } + + return { state: remove(state, id), effects: notifyAll(attempt.waiters, outcome) } +} + +/** Whether main's state ends the attempt, and whether the server is ready then. */ +function settle(attempt: Extract, item: SshItem | undefined) { + if (!item) return false + + if (item.stage === "ready") return true + + if (item.stage === "failed" || item.stage === "disconnected" || item.authenticatingElsewhere) return false + + // The prompt this window showed went away without the server connecting. + if (attempt.dialog !== "none" && item.stage === "authentication" && !item.prompt) return false + + return undefined +} + +function isActive(attempt: SshAttemptState): attempt is Active { + return attempt.status !== "failed" +} + +function isCalling(attempt: SshAttemptState) { + return attempt.status === "starting" || attempt.status === "answering" +} + +function put(state: SshWindowState, id: string, attempt: SshAttemptState): SshWindowState { + return { ...state, attempts: new Map(state.attempts).set(id, attempt) } +} + +function remove(state: SshWindowState, id: string): SshWindowState { + const attempts = new Map(state.attempts) + attempts.delete(id) + + return { ...state, attempts } +} + +const toast: SshWindowEffect = { type: "toast.error" } + +function abort(id: string): SshWindowEffect { + return { type: "task.abort", id } +} + +function notify(waiters: readonly Waiter[], ready: boolean): SshWindowEffect { + return { type: "waiters.notify", waiters, ready } +} + +function notifyAll(waiters: readonly Waiter[], ready: boolean): SshWindowEffect[] { + return waiters.length ? [notify(waiters, ready)] : [] +} + +function unchanged(state: SshWindowState): SshWindowTransition { + return { state, effects: [] } +}