diff --git a/packages/gui-plugins/src/pairing/copy-machine.test.ts b/packages/gui-plugins/src/pairing/copy-machine.test.ts new file mode 100644 index 00000000000..1b6350a69cd --- /dev/null +++ b/packages/gui-plugins/src/pairing/copy-machine.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, test } from "bun:test" +import { + COPY_FEEDBACK_MS, + COPY_TIMEOUT_MS, + createCopyState, + transitionCopy, + viewCopy, + type CopyEvent, + type CopyState, +} from "./copy-machine" + +const FIRST = "https://pair.example/auth/connect/first" + +const SECOND = "https://pair.example/auth/connect/second" + +const replay = (events: readonly CopyEvent[], state: CopyState = createCopyState()) => + events.reduce((current, event) => transitionCopy(current, event).state, state) + +describe("transitionCopy", () => { + test("a code that replaces the link drops Copied and the copy error for the old link", () => { + const copied = replay([ + { type: "copy.requested", url: FIRST }, + { type: "copy.succeeded", attempt: 1 }, + ]) + + expect(viewCopy(copied, FIRST)).toMatchObject({ icon: "check", label: "common.copied" }) + expect(viewCopy(copied, SECOND)).toEqual({ icon: "copy", label: "copyLink", disabled: false, error: false }) + + const failed = replay([ + { type: "copy.requested", url: FIRST }, + { type: "copy.failed", attempt: 1 }, + ]) + + expect(viewCopy(failed, FIRST).error).toBe(true) + expect(viewCopy(failed, SECOND).error).toBe(false) + expect(viewCopy(failed, undefined).error).toBe(false) + }) + + test("a copy that finishes after Refresh code never shows Copied", () => { + const copying = replay([{ type: "copy.requested", url: FIRST }]) + const reset = transitionCopy(copying, { type: "reset" }) + + expect(reset.effects).toEqual([{ type: "cancel-timer" }]) + expect(transitionCopy(reset.state, { type: "copy.succeeded", attempt: 1 }).state).toBe(reset.state) + expect(viewCopy(reset.state, FIRST).icon).toBe("copy") + }) + + test("copying the new link while the old copy runs starts a new attempt", () => { + const copying = replay([{ type: "copy.requested", url: FIRST }]) + + expect(viewCopy(copying, FIRST).disabled).toBe(true) + expect(viewCopy(copying, SECOND).disabled).toBe(false) + expect(transitionCopy(copying, { type: "copy.requested", url: FIRST }).state).toBe(copying) + + const next = transitionCopy(copying, { type: "copy.requested", url: SECOND }) + + expect(next.effects).toEqual([ + { type: "cancel-timer" }, + { type: "write", attempt: 2, url: SECOND, timeoutMs: COPY_TIMEOUT_MS }, + ]) + expect(transitionCopy(next.state, { type: "copy.succeeded", attempt: 1 }).state).toBe(next.state) + }) + + test("copying again during Copied restarts the feedback and ignores the first timer", () => { + const copied = replay([ + { type: "copy.requested", url: FIRST }, + { type: "copy.succeeded", attempt: 1 }, + ]) + + const again = transitionCopy(copied, { type: "copy.requested", url: FIRST }).state + + expect(transitionCopy(again, { type: "feedback.ended", attempt: 1 }).state).toBe(again) + + const done = transitionCopy(again, { type: "copy.succeeded", attempt: 2 }) + + expect(done.effects).toEqual([ + { type: "cancel-timer" }, + { type: "schedule-feedback", attempt: 2, delayMs: COPY_FEEDBACK_MS }, + ]) + expect(transitionCopy(done.state, { type: "feedback.ended", attempt: 2 }).state).toEqual({ + status: "idle", + attempt: 2, + }) + }) + + test("a failed or timed-out write shows the error and can be tried again", () => { + const failed = replay([ + { type: "copy.requested", url: FIRST }, + { type: "copy.failed", attempt: 1 }, + ]) + + expect(viewCopy(failed, FIRST)).toEqual({ icon: "copy", label: "copyLink", disabled: false, error: true }) + expect(transitionCopy(failed, { type: "copy.requested", url: FIRST }).state).toEqual({ + status: "copying", + attempt: 2, + url: FIRST, + }) + }) + + test("disposing cancels the timer and ignores later answers", () => { + const copying = replay([{ type: "copy.requested", url: FIRST }]) + const disposed = transitionCopy(copying, { type: "disposed" }) + + expect(disposed.effects).toEqual([{ type: "cancel-timer" }]) + expect(transitionCopy(disposed.state, { type: "copy.succeeded", attempt: 1 }).state).toBe(disposed.state) + expect(transitionCopy(disposed.state, { type: "copy.requested", url: FIRST }).state).toBe(disposed.state) + }) +}) diff --git a/packages/gui-plugins/src/pairing/copy-machine.ts b/packages/gui-plugins/src/pairing/copy-machine.ts new file mode 100644 index 00000000000..5781723c82a --- /dev/null +++ b/packages/gui-plugins/src/pairing/copy-machine.ts @@ -0,0 +1,107 @@ +/** How long "Copied" shows after a copy. */ +export const COPY_FEEDBACK_MS = 2_000 + +/** How long one clipboard write may take before it counts as failed. */ +export const COPY_TIMEOUT_MS = 5_000 + +/** + * The copy link button. Every phase but `idle` names the link it copied, so a code that replaces the link never + * shows "Copied" or the copy error for it. `attempt` is the last copy handed out. + */ +export type CopyState = + | { readonly status: "idle"; readonly attempt: number } + | { readonly status: "copying"; readonly attempt: number; readonly url: string } + | { readonly status: "copied"; readonly attempt: number; readonly url: string } + | { readonly status: "failed"; readonly attempt: number; readonly url: string } + | { readonly status: "disposed" } + +export type CopyEvent = + | { readonly type: "copy.requested"; readonly url: string } + | { readonly type: "copy.succeeded"; readonly attempt: number } + /** The write failed or timed out. */ + | { readonly type: "copy.failed"; readonly attempt: number } + | { readonly type: "feedback.ended"; readonly attempt: number } + /** The user asked for a new code. */ + | { readonly type: "reset" } + | { readonly type: "disposed" } + +export type CopyEffect = + /** Writes the link and arms its timeout in the button's one timer. */ + | { readonly type: "write"; readonly attempt: number; readonly url: string; readonly timeoutMs: number } + /** Arms the end of "Copied" in the button's one timer. */ + | { readonly type: "schedule-feedback"; readonly attempt: number; readonly delayMs: number } + | { readonly type: "cancel-timer" } + +export type CopyTransition = { readonly state: CopyState; readonly effects: readonly CopyEffect[] } + +const NONE: readonly CopyEffect[] = [] + +export function createCopyState(): CopyState { + return { status: "idle", attempt: 0 } +} + +export function transitionCopy(state: CopyState, event: CopyEvent): CopyTransition { + if (state.status === "disposed") return { state, effects: NONE } + + if (event.type === "disposed") return { state: { status: "disposed" }, effects: [{ type: "cancel-timer" }] } + + if (event.type === "copy.requested") { + if (state.status === "copying" && state.url === event.url) return { state, effects: NONE } + + const attempt = state.attempt + 1 + + return { + state: { status: "copying", attempt, url: event.url }, + effects: [{ type: "cancel-timer" }, { type: "write", attempt, url: event.url, timeoutMs: COPY_TIMEOUT_MS }], + } + } + + if (event.type === "copy.succeeded" || event.type === "copy.failed") { + if (state.status !== "copying" || state.attempt !== event.attempt) return { state, effects: NONE } + + if (event.type === "copy.failed") + return { + state: { status: "failed", attempt: state.attempt, url: state.url }, + effects: [{ type: "cancel-timer" }], + } + + return { + state: { status: "copied", attempt: state.attempt, url: state.url }, + effects: [ + { type: "cancel-timer" }, + { type: "schedule-feedback", attempt: state.attempt, delayMs: COPY_FEEDBACK_MS }, + ], + } + } + + if (event.type === "feedback.ended") { + if (state.status !== "copied" || state.attempt !== event.attempt) return { state, effects: NONE } + + return { state: { status: "idle", attempt: state.attempt }, effects: NONE } + } + + if (state.status === "idle") return { state, effects: NONE } + + return { state: { status: "idle", attempt: state.attempt }, effects: [{ type: "cancel-timer" }] } +} + +/** The event that reports an effect that threw, so a copy still ends. */ +export function copyEffectFailed(effect: CopyEffect): CopyEvent | undefined { + return effect.type === "write" ? { type: "copy.failed", attempt: effect.attempt } : undefined +} + +/** What the copy button shows for the link on screen now. */ +export function viewCopy(state: CopyState, url: string | undefined): CopyView { + const phase = state.status !== "idle" && state.status !== "disposed" && state.url === url ? state.status : "idle" + + if (phase === "copied") return { icon: "check", label: "common.copied", disabled: false, error: false } + + return { icon: "copy", label: "copyLink", disabled: phase === "copying", error: phase === "failed" } +} + +export type CopyView = { + readonly icon: "check" | "copy" + readonly label: "common.copied" | "copyLink" + readonly disabled: boolean + readonly error: boolean +} diff --git a/packages/gui-plugins/src/pairing/dispatch.test.ts b/packages/gui-plugins/src/pairing/dispatch.test.ts new file mode 100644 index 00000000000..f14b6be51c1 --- /dev/null +++ b/packages/gui-plugins/src/pairing/dispatch.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, test } from "bun:test" +import { copyEffectFailed, createCopyState, transitionCopy } from "./copy-machine" +import { createDispatch } from "./dispatch" +import { createPairingState, pairingEffectFailed, transitionPairing, type PairingEffect } from "./machine" + +// A rejection reaches its handler one microtask later. +const flush = () => Promise.resolve() + +describe("createDispatch", () => { + test("an effect that throws reports its failure, and later events still apply", async () => { + const ran: PairingEffect["type"][] = [] + const box = { state: createPairingState() } + + const dispatch = createDispatch({ + read: () => box.state, + write: (state) => void (box.state = state), + transition: transitionPairing, + run: (effect) => { + ran.push(effect.type) + + // `dialogs.open` or a client call that throws before it returns a promise. + if (effect.type === "read-remote" || effect.type === "open-dialog") throw new Error("Ipc is gone") + }, + failed: pairingEffectFailed, + }) + + dispatch({ type: "server.changed", available: true }) + dispatch({ type: "main.changed", main: { status: "active", generation: 1 } }) + await flush() + + // The read that threw counts as a failed read, which waits and tries again. + expect(box.state.remote).toMatchObject({ status: "loading", step: "waiting", failures: 1 }) + + dispatch({ type: "dialog.opened" }) + await flush() + + // The dialog that never opened reads as closed, so Pair device opens it again. + expect(box.state.dialog).toEqual({ status: "closed" }) + expect(ran).toEqual(["read-remote", "abort", "wait", "open-dialog"]) + + dispatch({ type: "dialog.opened" }) + + expect(box.state.dialog).toEqual({ status: "turning-on" }) + + dispatch({ type: "disposed" }) + + expect(box.state.remote).toEqual({ status: "disposed" }) + }) + + test("an event an effect dispatches synchronously applies after the current one", () => { + const order: string[] = [] + const box = { state: createCopyState() } + + const dispatch = createDispatch({ + read: () => box.state, + write: (state) => void (box.state = state), + transition: transitionCopy, + run: (effect) => { + order.push(`${effect.type}:${box.state.status}`) + + if (effect.type === "write") dispatch({ type: "copy.succeeded", attempt: effect.attempt }) + }, + failed: copyEffectFailed, + }) + + dispatch({ type: "copy.requested", url: "https://pair.example/auth/connect/a" }) + + expect(order).toEqual(["cancel-timer:copying", "write:copying", "cancel-timer:copied", "schedule-feedback:copied"]) + expect(box.state).toMatchObject({ status: "copied", attempt: 1 }) + }) +}) diff --git a/packages/gui-plugins/src/pairing/dispatch.ts b/packages/gui-plugins/src/pairing/dispatch.ts new file mode 100644 index 00000000000..3e08a6338ed --- /dev/null +++ b/packages/gui-plugins/src/pairing/dispatch.ts @@ -0,0 +1,42 @@ +/** + * The driver loop of a machine: applies one event at a time and runs its effects. An effect may dispatch + * synchronously; its event waits until the current one has applied. A transition or effect that throws never stalls + * the queue: a throwing effect reports `failed(effect)` back to the machine, and an error without such an event, or + * from the transition, surfaces as an unhandled rejection while later events keep applying. + */ +export function createDispatch(machine: { + readonly read: () => State + readonly write: (state: State) => void + readonly transition: (state: State, event: Event) => { readonly state: State; readonly effects: readonly Effect[] } + readonly run: (effect: Effect) => void + readonly failed: (effect: Effect) => Event | undefined +}) { + const queue: Event[] = [] + + const apply = (event: Event) => { + const next = machine.transition(machine.read(), event) + + machine.write(next.state) + next.effects.forEach((effect) => { + void Promise.try(() => machine.run(effect)).catch((cause: unknown) => { + const failure = machine.failed(effect) + + if (!failure) throw cause + dispatch(failure) + }) + }) + } + + const dispatch = (event: Event) => { + queue.push(event) + + if (queue.length > 1) return + + while (queue.length > 0) { + void Promise.try(apply, queue[0]) + queue.shift() + } + } + + return dispatch +} diff --git a/packages/gui-plugins/src/pairing/machine.test.ts b/packages/gui-plugins/src/pairing/machine.test.ts new file mode 100644 index 00000000000..e560a05fe37 --- /dev/null +++ b/packages/gui-plugins/src/pairing/machine.test.ts @@ -0,0 +1,431 @@ +import { describe, expect, test } from "bun:test" +import { + CODE_TIMEOUT_MS, + REMOTE_CHANGE_TIMEOUT_MS, + REMOTE_READ_RETRIES, + REMOTE_READ_TIMEOUT_MS, + TUNNEL_RETRIES, + TUNNEL_RETRY_DELAY_MS, + TUNNEL_TIMEOUT_MS, + createPairingState, + dialogUrl, + remainingSeconds, + transitionPairing, + viewDialog, + viewPairingPage, + type PairingEffect, + type PairingEvent, + type PairingState, +} from "./machine" + +const TUNNEL = "https://pair.example" + +// Folds the events in order, keeping every effect the machine asked for. +const replay = (events: readonly PairingEvent[], state: PairingState = createPairingState()) => + events.reduce<{ state: PairingState; effects: readonly PairingEffect[] }>( + (last, event) => { + const next = transitionPairing(last.state, event) + + return { state: next.state, effects: [...last.effects, ...next.effects] } + }, + { state, effects: [] }, + ) + +const step = (state: PairingState, event: PairingEvent) => transitionPairing(state, event) + +// Fails every read, and ends every wait between them, until the machine stops reading. +const failReads = (state: PairingState) => + Array.from({ length: (REMOTE_READ_RETRIES + 1) * 2 }).reduce<{ + state: PairingState + effects: readonly PairingEffect[] + }>( + (last) => { + const remote = last.state.remote + + if (remote.status !== "loading") return last + + const next = step( + last.state, + remote.step === "reading" + ? { type: "read.failed", attempt: remote.attempt } + : { type: "wait.ended", for: "read", attempt: remote.attempt }, + ) + + return { state: next.state, effects: [...last.effects, ...next.effects] } + }, + { state, effects: [] }, + ) + +// Main generation 1 is active and the server is listed; the first read is attempt 1. +const started = replay([ + { type: "server.changed", available: true }, + { type: "main.changed", main: { status: "active", generation: 1 } }, +]).state + +const setRemote = (attempt: number, enabled: boolean, restart: boolean): PairingEffect => ({ + type: "set-remote", + generation: 1, + attempt, + enabled, + restart, + timeoutMs: REMOTE_CHANGE_TIMEOUT_MS, +}) + +// Remote access is on and the dialog polls for the tunnel with attempt 2. +const polling = replay( + [{ type: "dialog.opened" }, { type: "read.succeeded", attempt: 1, enabled: true }], + started, +).state + +// The dialog shows a code that expires 60 s after it loaded at 1000. +const ready = replay( + [ + { type: "tunnel.found", attempt: 2, tunnel: TUNNEL }, + { type: "code.loaded", attempt: 3, code: "abc", expiresIn: 60, now: 1_000 }, + ], + polling, +).state + +describe("transitionPairing", () => { + test("starting reads the setting through the active generation", () => { + expect(started.remote).toEqual({ status: "loading", generation: 1, attempt: 1, step: "reading", failures: 0 }) + expect( + step(replay([{ type: "server.changed", available: true }]).state, { + type: "main.changed", + main: { status: "active", generation: 1 }, + }).effects, + ).toEqual([{ type: "read-remote", generation: 1, attempt: 1, timeoutMs: REMOTE_READ_TIMEOUT_MS }]) + }) + + test("main going inactive while the dialog turns remote access on shows unavailable, not an endless spinner", () => { + const turning = replay([{ type: "dialog.opened" }, { type: "read.succeeded", attempt: 1, enabled: false }], started) + + expect(turning.effects).toContainEqual(setRemote(2, true, false)) + expect(viewDialog(turning.state.dialog)).toEqual({ kind: "loading", setup: true }) + + const inactive = step(turning.state, { type: "main.changed", main: { status: "inactive" } }) + + expect(inactive.effects).toEqual([{ type: "abort", attempt: 2 }]) + expect(viewDialog(inactive.state.dialog)).toEqual({ kind: "unavailable" }) + expect(viewPairingPage(inactive.state)).toMatchObject({ unavailable: true, pairDisabled: true, mainActive: false }) + + // Main coming back reads the setting again and sets up pairing. + const back = replay( + [ + { type: "main.changed", main: { status: "active", generation: 2 } }, + { type: "read.succeeded", attempt: 3, enabled: true }, + ], + inactive.state, + ) + + expect(back.state.dialog).toEqual({ status: "tunnel", attempt: 4, step: "polling", retries: 0 }) + }) + + test("a failed read tries again three times with backoff, as the query's default retries did", () => { + const failed = step(started, { type: "read.failed", attempt: 1 }) + + expect(failed.state.remote).toEqual({ status: "loading", generation: 1, attempt: 2, step: "waiting", failures: 1 }) + expect(failed.effects).toEqual([ + { type: "abort", attempt: 1 }, + { type: "wait", for: "read", attempt: 2, delayMs: 1_000 }, + ]) + // The page keeps the row loading meanwhile, without the error. + expect(viewPairingPage(failed.state)).toMatchObject({ remoteError: false, remoteDisabled: true }) + // A late answer from the failed read changes nothing. + expect(step(failed.state, { type: "read.succeeded", attempt: 1, enabled: true }).state).toBe(failed.state) + + const again = step(failed.state, { type: "wait.ended", for: "read", attempt: 2 }) + + expect(again.effects).toEqual([ + { type: "abort", attempt: 2 }, + { type: "read-remote", generation: 1, attempt: 3, timeoutMs: REMOTE_READ_TIMEOUT_MS }, + ]) + expect(step(again.state, { type: "read.succeeded", attempt: 3, enabled: true }).state.remote).toEqual({ + status: "ready", + generation: 1, + enabled: true, + }) + + const exhausted = failReads(started) + + expect(exhausted.effects.flatMap((effect) => (effect.type === "wait" ? [effect.delayMs] : []))).toEqual([ + 1_000, 2_000, 4_000, + ]) + expect(exhausted.effects.filter((effect) => effect.type === "read-remote")).toHaveLength(REMOTE_READ_RETRIES) + expect(exhausted.state.remote).toEqual({ status: "failed", generation: 1, previous: undefined }) + }) + + test("a tunnel wait that ends while main restarts and the setting is read again still polls", () => { + const waiting = step(polling, { type: "tunnel.missing", attempt: 2 }) + + expect(waiting.effects).toContainEqual({ type: "wait", for: "tunnel", attempt: 3, delayMs: TUNNEL_RETRY_DELAY_MS }) + + // Main restarts: the dialog keeps its tunnel wait while the new generation reads the setting, and that read fails. + const reading = step(waiting.state, { type: "main.changed", main: { status: "active", generation: 2 } }).state + const retrying = step(reading, { type: "read.failed", attempt: 4 }).state + + expect(retrying.remote).toMatchObject({ status: "loading", step: "waiting", attempt: 5 }) + expect(retrying.dialog).toEqual({ status: "tunnel", attempt: 3, step: "waiting", retries: 1 }) + + // The tunnel wait ends during the read, and during the read's own wait: neither swallows it. + ;[reading, retrying].forEach((state) => { + const polled = step(state, { type: "wait.ended", for: "tunnel", attempt: 3 }) + + expect(polled.state.dialog).toEqual({ status: "tunnel", attempt: state.issued + 1, step: "polling", retries: 1 }) + expect(polled.effects).toContainEqual({ + type: "poll-tunnel", + attempt: state.issued + 1, + timeoutMs: TUNNEL_TIMEOUT_MS, + }) + expect(polled.state.remote).toBe(state.remote) + }) + + // The read's wait ends on its own branch and leaves the tunnel wait alone. + const reread = step(retrying, { type: "wait.ended", for: "read", attempt: 5 }) + + expect(reread.state.dialog).toBe(retrying.dialog) + expect(reread.effects).toContainEqual({ + type: "read-remote", + generation: 2, + attempt: 6, + timeoutMs: REMOTE_READ_TIMEOUT_MS, + }) + // A wait for one phase never ends the other with the same attempt number. + expect(step(retrying, { type: "wait.ended", for: "read", attempt: 3 }).state).toBe(retrying) + expect(step(retrying, { type: "wait.ended", for: "tunnel", attempt: 5 }).state).toBe(retrying) + }) + + test("after reads give up, the switch still works: its change reads the setting first", () => { + const failed = failReads(started).state + + expect(viewPairingPage(failed)).toMatchObject({ remoteError: true, remoteDisabled: false, remoteChecked: false }) + + const toggled = step(failed, { type: "toggled", enabled: true }) + + expect(toggled.effects).toEqual([setRemote(failed.issued + 1, true, false)]) + expect(viewPairingPage(toggled.state)).toMatchObject({ remoteError: false, remoteChecked: true }) + + const on = step(toggled.state, { type: "change.succeeded", attempt: failed.issued + 1 }).state + + expect(on.remote).toEqual({ status: "ready", generation: 1, enabled: true }) + }) + + test("main going inactive turns a failed dialog unavailable, so Try again cannot call a missing main", () => { + const failed = failReads(step(started, { type: "dialog.opened" }).state).state + + expect(viewDialog(failed.dialog)).toEqual({ kind: "failed" }) + + const inactive = step(failed, { type: "main.changed", main: { status: "inactive" } }).state + + expect(viewDialog(inactive.dialog)).toEqual({ kind: "unavailable" }) + expect(step(inactive, { type: "retry" })).toEqual({ state: inactive, effects: [] }) + }) + + test("the local server going away ends the code refresh and shows unavailable", () => { + const refreshing = step(ready, { type: "code.refresh" }).state + const gone = step(refreshing, { type: "server.changed", available: false }) + + expect(gone.effects).toEqual([{ type: "abort", attempt: 4 }]) + expect(viewDialog(gone.state.dialog)).toEqual({ kind: "unavailable" }) + expect(viewPairingPage(gone.state).unavailable).toBe(true) + }) + + test("a failure after the code loaded replaces the QR code instead of stacking under it", () => { + expect(viewDialog(ready.dialog)).toMatchObject({ kind: "ready", url: `${TUNNEL}/auth/connect/abc` }) + + const reading = step(ready, { type: "main.changed", main: { status: "active", generation: 2 } }).state + + // Retries keep the code on screen; only the read that gives up replaces it. + expect(step(reading, { type: "read.failed", attempt: 4 }).state.dialog).toBe(ready.dialog) + + const failed = failReads(reading).state + + expect(viewDialog(failed.dialog)).toEqual({ kind: "failed" }) + expect(dialogUrl(failed.dialog)).toBeUndefined() + }) + + test("a failed switch change does not open the dialog into a failure: opening tries again", () => { + const failed = replay( + [ + { type: "read.succeeded", attempt: 1, enabled: false }, + { type: "toggled", enabled: true }, + { type: "change.failed", attempt: 2 }, + ], + started, + ).state + + expect(viewPairingPage(failed)).toMatchObject({ remoteError: true, remoteChecked: false, remoteDisabled: false }) + + const opened = step(failed, { type: "dialog.opened" }) + + expect(opened.effects).toEqual([{ type: "open-dialog" }, setRemote(3, true, false)]) + expect(viewDialog(opened.state.dialog)).toEqual({ kind: "loading", setup: true }) + + const on = step(opened.state, { type: "change.succeeded", attempt: 3 }).state + + expect(viewPairingPage(on).remoteError).toBe(false) + expect(on.dialog).toEqual({ status: "tunnel", attempt: 4, step: "polling", retries: 0 }) + }) + + test("Try again after the tunnel never connected restarts the service and polls afresh", () => { + const exhausted = Array.from({ length: TUNNEL_RETRIES * 2 + 1 }).reduce((state) => { + const dialog = state.dialog + + if (dialog.status !== "tunnel") return state + + return step( + state, + dialog.step === "polling" + ? { type: "tunnel.missing", attempt: dialog.attempt } + : { type: "wait.ended", for: "tunnel", attempt: dialog.attempt }, + ).state + }, polling) + + expect(exhausted.dialog).toEqual({ status: "failed", reason: "tunnel" }) + + // Remote access is still on: the failure waits for the user instead of polling again. + const reread = replay( + [ + { type: "main.changed", main: { status: "active", generation: 2 } }, + { type: "read.succeeded", attempt: exhausted.issued + 1, enabled: true }, + ], + exhausted, + ).state + + expect(reread.dialog).toEqual({ status: "failed", reason: "tunnel" }) + + const retry = step(exhausted, { type: "retry" }) + + expect(retry.effects).toEqual([setRemote(exhausted.issued + 1, true, true)]) + // The old tunnel failure no longer shows while the service restarts. + expect(viewDialog(retry.state.dialog)).toEqual({ kind: "loading", setup: true }) + + // A second click on the gone button changes nothing. + expect(step(retry.state, { type: "retry" }).state).toBe(retry.state) + + const restarted = step(retry.state, { type: "change.succeeded", attempt: exhausted.issued + 1 }) + + expect(restarted.state.dialog).toMatchObject({ status: "tunnel", step: "polling", retries: 0 }) + expect(viewDialog(restarted.state.dialog)).toEqual({ kind: "loading", setup: true }) + }) + + test("Pair device during the first read waits for it instead of changing the setting alongside", () => { + const opened = step(started, { type: "dialog.opened" }) + + expect(opened.effects).toEqual([{ type: "open-dialog" }]) + + const on = step(opened.state, { type: "read.succeeded", attempt: 1, enabled: true }) + + expect(on.effects).toEqual([ + { type: "abort", attempt: 1 }, + { type: "poll-tunnel", attempt: 2, timeoutMs: TUNNEL_TIMEOUT_MS }, + ]) + + const off = step(opened.state, { type: "read.succeeded", attempt: 1, enabled: false }) + + expect(off.effects).toEqual([{ type: "abort", attempt: 1 }, setRemote(2, true, false)]) + expect(step(off.state, { type: "dialog.opened" }).state).toBe(off.state) + }) + + test("main restarting is a suspension: the code stays on screen", () => { + const pending = step(ready, { type: "main.changed", main: { status: "pending" } }).state + + expect(pending.dialog).toBe(ready.dialog) + expect(viewPairingPage(pending).mainActive).toBe(false) + + const back = replay( + [ + { type: "main.changed", main: { status: "active", generation: 2 } }, + { type: "read.succeeded", attempt: 4, enabled: true }, + ], + pending, + ).state + + expect(back.dialog).toBe(ready.dialog) + }) + + test("a refresh keeps the code on screen, and a failed one offers to try again", () => { + const refreshing = step(ready, { type: "code.refresh" }) + + expect(refreshing.effects).toEqual([{ type: "fetch-code", attempt: 4, timeoutMs: CODE_TIMEOUT_MS }]) + expect(viewDialog(refreshing.state.dialog)).toMatchObject({ kind: "ready", refreshing: true }) + expect(step(refreshing.state, { type: "code.refresh" }).state).toBe(refreshing.state) + + const failed = step(refreshing.state, { type: "code.failed", attempt: 4 }).state + + expect(viewDialog(failed.dialog)).toEqual({ kind: "code-error" }) + + const again = step(failed, { type: "code.refresh" }) + + expect(again.effects).toEqual([{ type: "fetch-code", attempt: 5, timeoutMs: CODE_TIMEOUT_MS }]) + expect(viewDialog(again.state.dialog)).toEqual({ kind: "loading", setup: false }) + + const loaded = step(again.state, { type: "code.loaded", attempt: 5, code: "def", expiresIn: 60, now: 2_000 }) + + expect(dialogUrl(loaded.state.dialog)).toBe(`${TUNNEL}/auth/connect/def`) + }) + + test("the clock replaces a code once it expires, even after the window slept past it", () => { + expect(remainingSeconds(ready.dialog, 1_000)).toBe(60) + expect(remainingSeconds(ready.dialog, 500)).toBe(60) + expect(step(ready, { type: "tick", now: 60_999 }).state).toBe(ready) + + const expired = step(ready, { type: "tick", now: 600_000 }) + + expect(remainingSeconds(ready.dialog, 600_000)).toBe(0) + expect(expired.effects).toEqual([{ type: "fetch-code", attempt: 4, timeoutMs: CODE_TIMEOUT_MS }]) + expect(step(expired.state, { type: "tick", now: 601_000 }).state).toBe(expired.state) + }) + + test("answers for another attempt change nothing", () => { + expect(step(started, { type: "read.succeeded", attempt: 9, enabled: true }).state).toBe(started) + expect(step(polling, { type: "tunnel.found", attempt: 1, tunnel: TUNNEL }).state).toBe(polling) + expect(step(polling, { type: "wait.ended", for: "tunnel", attempt: 2 }).state).toBe(polling) + expect(step(ready, { type: "code.loaded", attempt: 3, code: "x", expiresIn: 60, now: 0 }).state).toBe(ready) + expect(step(ready, { type: "change.succeeded", attempt: 1 }).state).toBe(ready) + expect(step(started, { type: "main.changed", main: { status: "active", generation: 1 } }).state).toBe(started) + }) + + test("closing the dialog ends its requests; the setting keeps changing", () => { + const turning = replay( + [{ type: "dialog.opened" }, { type: "read.succeeded", attempt: 1, enabled: false }], + started, + ).state + + const closed = step(turning, { type: "dialog.closed" }).state + + expect(closed.dialog).toEqual({ status: "closed" }) + expect(closed.remote).toMatchObject({ status: "changing", enabled: true }) + expect(step(polling, { type: "dialog.closed" }).effects).toEqual([{ type: "abort", attempt: 2 }]) + }) + + test("the switch cannot open pairing while it turns remote access off", () => { + const off = replay( + [ + { type: "read.succeeded", attempt: 1, enabled: true }, + { type: "toggled", enabled: false }, + ], + started, + ) + + expect(off.effects).toContainEqual(setRemote(2, false, false)) + expect(viewPairingPage(off.state)).toMatchObject({ pairDisabled: true, remoteChecked: false, remoteDisabled: true }) + expect(step(off.state, { type: "toggled", enabled: true }).state).toBe(off.state) + }) + + test("disposing ends every request, closes the dialog and ignores later answers", () => { + const refreshing = step(ready, { type: "code.refresh" }).state + const reading = step(refreshing, { type: "main.changed", main: { status: "active", generation: 2 } }).state + const disposed = step(reading, { type: "disposed" }) + + expect(disposed.effects).toEqual([ + { type: "abort", attempt: 5 }, + { type: "abort", attempt: 4 }, + { type: "close-dialog" }, + ]) + expect(step(disposed.state, { type: "code.loaded", attempt: 4, code: "x", expiresIn: 1, now: 0 }).state).toBe( + disposed.state, + ) + expect(step(disposed.state, { type: "dialog.opened" }).state).toBe(disposed.state) + }) +}) diff --git a/packages/gui-plugins/src/pairing/machine.ts b/packages/gui-plugins/src/pairing/machine.ts new file mode 100644 index 00000000000..bf035fea560 --- /dev/null +++ b/packages/gui-plugins/src/pairing/machine.ts @@ -0,0 +1,643 @@ +/** How long one read of the remote access setting may take. */ +export const REMOTE_READ_TIMEOUT_MS = 15_000 + +/** How many times a failed read of the setting is tried again, as a query's default retries did. */ +export const REMOTE_READ_RETRIES = 3 + +/** The wait before read retry `failures`: 1, 2, then 4 seconds, a query's default backoff. */ +export function remoteReadDelay(failures: number) { + return Math.min(1_000 * 2 ** failures, 30_000) +} + +/** How long turning remote access on or off may take: the first time creates the tunnel, which can take a minute. */ +export const REMOTE_CHANGE_TIMEOUT_MS = 180_000 + +/** + * The service attaches the tunnel in the background after it starts, so the dialog asks again this many times, a + * second apart, about three minutes, as `opencode pair --remote` waits. + */ +export const TUNNEL_RETRIES = 180 + +export const TUNNEL_RETRY_DELAY_MS = 1_000 + +/** How long one request for the server's addresses may take before it counts as one more try. */ +export const TUNNEL_TIMEOUT_MS = 10_000 + +/** How long one request for a pairing code may take. */ +export const CODE_TIMEOUT_MS = 15_000 + +/** Pairing's main side as the page reads it: remote access changes only through it. */ +export type MainStatus = + | { readonly status: "active"; readonly generation: number } + /** The main side is starting or restarting. */ + | { readonly status: "pending" } + /** The main side is disabled or failed, or this is the web. */ + | { readonly status: "inactive" } + +/** The remote access setting, read and changed through one generation of pairing's main side. */ +export type RemoteState = + | { readonly status: "pending" } + | { readonly status: "inactive" } + | { + readonly status: "loading" + readonly generation: number + readonly attempt: number + /** A read runs, or the wait before the next read after a failure. */ + readonly step: "reading" | "waiting" + readonly failures: number + } + | { readonly status: "ready"; readonly generation: number; readonly enabled: boolean } + | { + readonly status: "changing" + readonly generation: number + readonly attempt: number + readonly enabled: boolean + /** Restarts the service even when the setting already matches, as a tunnel that never connected needs. */ + readonly restart: boolean + /** The setting before the change, when it was known. */ + readonly previous: boolean | undefined + } + | { readonly status: "failed"; readonly generation: number; readonly previous: boolean | undefined } + | { readonly status: "disposed" } + +/** The "Pair a device" dialog. Exactly one variant owns its body. */ +export type DialogState = + | { readonly status: "closed" } + /** Neither the local server nor pairing's main side can set up pairing. */ + | { readonly status: "unavailable" } + /** Remote access is being read or turned on. */ + | { readonly status: "turning-on" } + /** Remote access is on; the dialog asks the server for its tunnel address until it advertises one. */ + | { + readonly status: "tunnel" + readonly attempt: number + readonly step: "polling" | "waiting" + readonly retries: number + } + | { readonly status: "code"; readonly attempt: number; readonly tunnel: string } + | { + readonly status: "ready" + readonly tunnel: string + readonly code: string + readonly url: string + readonly expiresIn: number + readonly loadedAt: number + /** The attempt fetching the next code while this one stays on screen. */ + readonly refreshing: number | undefined + } + | { readonly status: "code-error"; readonly tunnel: string } + | { readonly status: "failed"; readonly reason: "remote" | "tunnel" } + +/** + * The pairing page: the remote access setting and the dialog that turns it on. One transition owns both, so the + * dialog follows every change of the setting in the same event. `issued` is the last attempt handed out. + */ +export type PairingState = { + readonly issued: number + /** Whether the local server is listed. Codes come from it, so they never wait for main. */ + readonly server: boolean + readonly remote: RemoteState + readonly dialog: DialogState +} + +export type PairingEvent = + | { readonly type: "main.changed"; readonly main: MainStatus } + | { readonly type: "server.changed"; readonly available: boolean } + | { readonly type: "read.succeeded"; readonly attempt: number; readonly enabled: boolean } + /** The read failed or timed out. */ + | { readonly type: "read.failed"; readonly attempt: number } + /** The user flipped the remote access switch. */ + | { readonly type: "toggled"; readonly enabled: boolean } + | { readonly type: "change.succeeded"; readonly attempt: number } + /** The change failed or timed out. */ + | { readonly type: "change.failed"; readonly attempt: number } + /** The user clicked "Pair device". */ + | { readonly type: "dialog.opened" } + | { readonly type: "dialog.closed" } + | { readonly type: "tunnel.found"; readonly attempt: number; readonly tunnel: string } + /** The server advertises no tunnel yet, or the request failed or timed out. */ + | { readonly type: "tunnel.missing"; readonly attempt: number } + /** A `wait` effect's delay ended; `for` names the phase it belongs to, as the effect did. */ + | { readonly type: "wait.ended"; readonly for: "read" | "tunnel"; readonly attempt: number } + | { + readonly type: "code.loaded" + readonly attempt: number + readonly code: string + readonly expiresIn: number + readonly now: number + } + /** The code request failed or timed out. */ + | { readonly type: "code.failed"; readonly attempt: number } + | { readonly type: "code.refresh" } + | { readonly type: "retry" } + /** The dialog's clock: a code that expired, even while the window slept, is replaced. */ + | { readonly type: "tick"; readonly now: number } + | { readonly type: "disposed" } + +export type PairingEffect = + | { readonly type: "read-remote"; readonly generation: number; readonly attempt: number; readonly timeoutMs: number } + | { + readonly type: "set-remote" + readonly generation: number + readonly attempt: number + readonly enabled: boolean + readonly restart: boolean + readonly timeoutMs: number + } + | { readonly type: "poll-tunnel"; readonly attempt: number; readonly timeoutMs: number } + /** + * Waits before the next read of the setting or the next ask for the tunnel; ends with `wait.ended` for the same + * phase, so a read retry and a tunnel retry that wait at once never take each other's event. + */ + | { readonly type: "wait"; readonly for: "read" | "tunnel"; readonly attempt: number; readonly delayMs: number } + | { readonly type: "fetch-code"; readonly attempt: number; readonly timeoutMs: number } + /** Ends an attempt's request and timer. */ + | { readonly type: "abort"; readonly attempt: number } + | { readonly type: "open-dialog" } + | { readonly type: "close-dialog" } + +export type PairingTransition = { readonly state: PairingState; readonly effects: readonly PairingEffect[] } + +const NONE: readonly PairingEffect[] = [] + +export function createPairingState(): PairingState { + return { issued: 0, server: false, remote: { status: "pending" }, dialog: { status: "closed" } } +} + +export function transitionPairing(state: PairingState, event: PairingEvent): PairingTransition { + const remote = state.remote + const dialog = state.dialog + + if (remote.status === "disposed") return { state, effects: NONE } + + if (event.type === "disposed") { + const close: readonly PairingEffect[] = dialog.status === "closed" ? [] : [{ type: "close-dialog" }] + + return { + state: { ...state, remote: { status: "disposed" }, dialog: { status: "closed" } }, + effects: [...abortRemote(remote), ...abortDialog(dialog), ...close], + } + } + + if (event.type === "main.changed") { + const main = event.main + + if (main.status !== "active") { + if (remote.status === main.status) return { state, effects: NONE } + + return settle({ ...state, remote: { status: main.status } }, abortRemote(remote)) + } + + if ("generation" in remote && remote.generation === main.generation) return { state, effects: NONE } + + const attempt = state.issued + 1 + + return settle( + { + ...state, + issued: attempt, + remote: { status: "loading", generation: main.generation, attempt, step: "reading", failures: 0 }, + }, + [ + ...abortRemote(remote), + { type: "read-remote", generation: main.generation, attempt, timeoutMs: REMOTE_READ_TIMEOUT_MS }, + ], + ) + } + + if (event.type === "server.changed") { + if (state.server === event.available) return { state, effects: NONE } + + return settle({ ...state, server: event.available }, NONE) + } + + if (event.type === "read.succeeded" || event.type === "read.failed") { + if (remote.status !== "loading" || remote.step !== "reading" || remote.attempt !== event.attempt) + return { state, effects: NONE } + + const effects: readonly PairingEffect[] = [{ type: "abort", attempt: event.attempt }] + + if (event.type === "read.succeeded") + return settle( + { ...state, remote: { status: "ready", generation: remote.generation, enabled: event.enabled } }, + effects, + ) + + if (remote.failures >= REMOTE_READ_RETRIES) + return settle( + { ...state, remote: { status: "failed", generation: remote.generation, previous: undefined } }, + effects, + ) + + const attempt = state.issued + 1 + + return { + state: { + ...state, + issued: attempt, + remote: { ...remote, attempt, step: "waiting", failures: remote.failures + 1 }, + }, + effects: [...effects, { type: "wait", for: "read", attempt, delayMs: remoteReadDelay(remote.failures) }], + } + } + + if (event.type === "wait.ended" && event.for === "read") { + if (remote.status !== "loading" || remote.step !== "waiting" || remote.attempt !== event.attempt) + return { state, effects: NONE } + + const attempt = state.issued + 1 + + return { + state: { ...state, issued: attempt, remote: { ...remote, attempt, step: "reading" } }, + effects: [ + { type: "abort", attempt: event.attempt }, + { type: "read-remote", generation: remote.generation, attempt, timeoutMs: REMOTE_READ_TIMEOUT_MS }, + ], + } + } + + if (event.type === "toggled") { + if (remote.status === "ready" && remote.enabled !== event.enabled) + return settle(...change(state, NONE, event.enabled, false)) + + // A change reads the setting before it writes, so the switch also works after a read that never answered. + if (remote.status === "failed") return settle(...change(state, NONE, event.enabled, false)) + + return { state, effects: NONE } + } + + if (event.type === "change.succeeded" || event.type === "change.failed") { + if (remote.status !== "changing" || remote.attempt !== event.attempt) return { state, effects: NONE } + + return settle( + { + ...state, + remote: + event.type === "change.succeeded" + ? { status: "ready", generation: remote.generation, enabled: remote.enabled } + : { status: "failed", generation: remote.generation, previous: remote.previous }, + }, + [{ type: "abort", attempt: event.attempt }], + ) + } + + if (event.type === "dialog.opened") { + if (dialog.status !== "closed") return { state, effects: NONE } + + const opened: PairingState = { ...state, dialog: { status: "turning-on" } } + const effects: readonly PairingEffect[] = [{ type: "open-dialog" }] + + // Every pairing goes through remote access, so opening the dialog tries again after a failure. + if (remote.status === "failed") return settle(...change(opened, effects, true, false)) + + return settle(opened, effects) + } + + if (event.type === "dialog.closed") return toDialog(state, NONE, { status: "closed" }) + + if (event.type === "retry") { + if (dialog.status !== "failed") return { state, effects: NONE } + + const retrying: PairingState = { ...state, dialog: { status: "turning-on" } } + + // A tunnel that never connected comes back when the service starts it again. + if (remote.status === "ready" || remote.status === "failed") + return settle(...change(retrying, NONE, true, dialog.reason === "tunnel")) + + return settle(retrying, NONE) + } + + return transitionCode(state, event) +} + +/** The dialog's own requests: the tunnel address, then the code and its replacements. */ +function transitionCode(state: PairingState, event: PairingEvent): PairingTransition { + const dialog = state.dialog + const attempt = state.issued + 1 + + if (event.type === "tunnel.found") { + if (dialog.status !== "tunnel" || dialog.step !== "polling" || dialog.attempt !== event.attempt) + return { state, effects: NONE } + + return { + state: { ...state, issued: attempt, dialog: { status: "code", attempt, tunnel: event.tunnel } }, + effects: [ + { type: "abort", attempt: event.attempt }, + { type: "fetch-code", attempt, timeoutMs: CODE_TIMEOUT_MS }, + ], + } + } + + if (event.type === "tunnel.missing") { + if (dialog.status !== "tunnel" || dialog.step !== "polling" || dialog.attempt !== event.attempt) + return { state, effects: NONE } + + if (dialog.retries >= TUNNEL_RETRIES) + return { state: { ...state, dialog: { status: "failed", reason: "tunnel" } }, effects: abortDialog(dialog) } + + return { + state: { + ...state, + issued: attempt, + dialog: { status: "tunnel", attempt, step: "waiting", retries: dialog.retries + 1 }, + }, + effects: [ + { type: "abort", attempt: event.attempt }, + { type: "wait", for: "tunnel", attempt, delayMs: TUNNEL_RETRY_DELAY_MS }, + ], + } + } + + if (event.type === "wait.ended" && event.for === "tunnel") { + if (dialog.status !== "tunnel" || dialog.step !== "waiting" || dialog.attempt !== event.attempt) + return { state, effects: NONE } + + return { + state: { + ...state, + issued: attempt, + dialog: { status: "tunnel", attempt, step: "polling", retries: dialog.retries }, + }, + effects: [ + { type: "abort", attempt: event.attempt }, + { type: "poll-tunnel", attempt, timeoutMs: TUNNEL_TIMEOUT_MS }, + ], + } + } + + if (event.type === "code.loaded" || event.type === "code.failed") { + const current = + (dialog.status === "code" && dialog.attempt === event.attempt) || + (dialog.status === "ready" && dialog.refreshing === event.attempt) + + if (!current) return { state, effects: NONE } + + const url = event.type === "code.loaded" ? URL.parse(`/auth/connect/${event.code}`, dialog.tunnel)?.href : undefined + + return { + state: { + ...state, + dialog: + event.type === "code.loaded" && url + ? { + status: "ready", + tunnel: dialog.tunnel, + code: event.code, + url, + expiresIn: event.expiresIn, + loadedAt: event.now, + refreshing: undefined, + } + : { status: "code-error", tunnel: dialog.tunnel }, + }, + effects: [{ type: "abort", attempt: event.attempt }], + } + } + + if (event.type === "code.refresh") { + if (dialog.status === "code-error") + return { + state: { ...state, issued: attempt, dialog: { status: "code", attempt, tunnel: dialog.tunnel } }, + effects: [{ type: "fetch-code", attempt, timeoutMs: CODE_TIMEOUT_MS }], + } + + if (dialog.status !== "ready" || dialog.refreshing !== undefined) return { state, effects: NONE } + + return refreshCode(state, dialog) + } + + if (event.type === "tick") { + // Codes are single-use, so replace the link as soon as the server forgets the current code. + if (dialog.status !== "ready" || dialog.refreshing !== undefined || remainingSeconds(dialog, event.now) > 0) + return { state, effects: NONE } + + return refreshCode(state, dialog) + } + + return { state, effects: NONE } +} + +function refreshCode(state: PairingState, dialog: Extract): PairingTransition { + const attempt = state.issued + 1 + + return { + state: { ...state, issued: attempt, dialog: { ...dialog, refreshing: attempt } }, + effects: [{ type: "fetch-code", attempt, timeoutMs: CODE_TIMEOUT_MS }], + } +} + +/** Turns remote access on or off; the caller checked that no read or change is in flight. */ +function change( + state: PairingState, + effects: readonly PairingEffect[], + enabled: boolean, + restart: boolean, +): [PairingState, readonly PairingEffect[]] { + const remote = state.remote + + if (remote.status !== "ready" && remote.status !== "failed") return [state, effects] + + const attempt = state.issued + 1 + + return [ + { + ...state, + issued: attempt, + remote: { + status: "changing", + generation: remote.generation, + attempt, + enabled, + restart, + previous: remote.status === "ready" ? remote.enabled : remote.previous, + }, + }, + [ + ...effects, + { + type: "set-remote", + generation: remote.generation, + attempt, + enabled, + restart, + timeoutMs: REMOTE_CHANGE_TIMEOUT_MS, + }, + ], + ] +} + +/** Moves an open dialog to the phase that follows from remote access and the server, after either changed. */ +function settle(state: PairingState, effects: readonly PairingEffect[]): PairingTransition { + const dialog = state.dialog + const remote = state.remote + + if (dialog.status === "closed") return { state, effects } + + // Codes and the tunnel address come from the local server. + if (!state.server) return toDialog(state, effects, { status: "unavailable" }) + + if ( + dialog.status === "tunnel" || + dialog.status === "code" || + dialog.status === "ready" || + dialog.status === "code-error" + ) { + if (remote.status === "failed") return toDialog(state, effects, { status: "failed", reason: "remote" }) + + // Main going away or restarting is a suspension: the code needs only the server. + if (remote.status !== "changing" && !(remote.status === "ready" && !remote.enabled)) return { state, effects } + + return setUp(state, effects) + } + + if (dialog.status === "failed") { + if (remote.status === "inactive") return toDialog(state, effects, { status: "unavailable" }) + + if (remote.status === "changing") return toDialog(state, effects, { status: "turning-on" }) + + if (remote.status === "failed") return toDialog(state, effects, { status: "failed", reason: "remote" }) + + // A tunnel that never connected waits for "Try again", which restarts the service. + if (dialog.reason === "remote" && remote.status === "ready" && remote.enabled) return startTunnel(state, effects) + + return { state, effects } + } + + return setUp(state, effects) +} + +function setUp(state: PairingState, effects: readonly PairingEffect[]): PairingTransition { + const remote = state.remote + + if (remote.status === "inactive") return toDialog(state, effects, { status: "unavailable" }) + + if (remote.status === "failed") return toDialog(state, effects, { status: "failed", reason: "remote" }) + + if (remote.status === "ready" && remote.enabled) return startTunnel(state, effects) + + if (remote.status === "ready") return toDialog(...change(state, effects, true, false), { status: "turning-on" }) + + return toDialog(state, effects, { status: "turning-on" }) +} + +function startTunnel(state: PairingState, effects: readonly PairingEffect[]): PairingTransition { + const attempt = state.issued + 1 + + return { + state: { ...state, issued: attempt, dialog: { status: "tunnel", attempt, step: "polling", retries: 0 } }, + effects: [...effects, ...abortDialog(state.dialog), { type: "poll-tunnel", attempt, timeoutMs: TUNNEL_TIMEOUT_MS }], + } +} + +function toDialog( + state: PairingState, + effects: readonly PairingEffect[], + next: Extract, +): PairingTransition { + const dialog = state.dialog + + const same = + dialog.status === "failed" + ? next.status === "failed" && dialog.reason === next.reason + : dialog.status === next.status + + if (same) return { state, effects } + + return { state: { ...state, dialog: next }, effects: [...effects, ...abortDialog(dialog)] } +} + +function abortRemote(remote: RemoteState): readonly PairingEffect[] { + return remote.status === "loading" || remote.status === "changing" ? [{ type: "abort", attempt: remote.attempt }] : [] +} + +function abortDialog(dialog: DialogState): readonly PairingEffect[] { + if (dialog.status === "tunnel" || dialog.status === "code") return [{ type: "abort", attempt: dialog.attempt }] + + if (dialog.status === "ready" && dialog.refreshing !== undefined) + return [{ type: "abort", attempt: dialog.refreshing }] + + return [] +} + +/** The event that reports an effect that threw before it could answer, so its phase still ends. */ +export function pairingEffectFailed(effect: PairingEffect): PairingEvent | undefined { + if (effect.type === "read-remote") return { type: "read.failed", attempt: effect.attempt } + + if (effect.type === "set-remote") return { type: "change.failed", attempt: effect.attempt } + + if (effect.type === "poll-tunnel") return { type: "tunnel.missing", attempt: effect.attempt } + + if (effect.type === "wait") return { type: "wait.ended", for: effect.for, attempt: effect.attempt } + + if (effect.type === "fetch-code") return { type: "code.failed", attempt: effect.attempt } + + if (effect.type === "open-dialog") return { type: "dialog.closed" } + + return undefined +} + +/** What the pairing settings page shows. */ +export function viewPairingPage(state: PairingState) { + const remote = state.remote + const mainActive = remote.status !== "pending" && remote.status !== "inactive" && remote.status !== "disposed" + + return { + mainActive, + pairDisabled: !mainActive || !state.server || (remote.status === "changing" && !remote.enabled), + // A change shows its target; a failed one shows the setting it left. + remoteChecked: + ((remote.status === "changing" || remote.status === "ready") && remote.enabled) || + (remote.status === "failed" && remote.previous === true), + remoteDisabled: remote.status !== "ready" && remote.status !== "failed", + remoteError: remote.status === "failed", + // Pending main is still starting; anything else that leaves it inactive keeps pairing from turning on. + unavailable: remote.status === "inactive" || !state.server, + } +} + +export type DialogView = + | { readonly kind: "unavailable" } + /** `setup` says remote access is still being set up, rather than a code loading. */ + | { readonly kind: "loading"; readonly setup: boolean } + | { + readonly kind: "ready" + readonly url: string + /** The QR code's content, as `opencode pair --remote` prints it: {"code","urls"} JSON the app's scanner reads. */ + readonly qr: string + readonly refreshing: boolean + } + | { readonly kind: "code-error" } + | { readonly kind: "failed" } + +export function viewDialog(dialog: DialogState): DialogView { + if (dialog.status === "turning-on" || dialog.status === "tunnel") return { kind: "loading", setup: true } + + if (dialog.status === "code") return { kind: "loading", setup: false } + + if (dialog.status === "ready") + return { + kind: "ready", + url: dialog.url, + qr: JSON.stringify({ code: dialog.code, urls: [dialog.tunnel] }), + refreshing: dialog.refreshing !== undefined, + } + + if (dialog.status === "code-error") return { kind: "code-error" } + + if (dialog.status === "failed") return { kind: "failed" } + + return { kind: "unavailable" } +} + +/** The link the dialog shows, which the copy button copies. */ +export function dialogUrl(dialog: DialogState) { + return dialog.status === "ready" ? dialog.url : undefined +} + +/** Whole seconds until the shown code expires. */ +export function remainingSeconds(dialog: DialogState, now: number) { + if (dialog.status !== "ready") return 0 + + // The clock can lag a fresh code by up to a second; a negative age would show one second too many. + return Math.max(0, dialog.expiresIn - Math.floor(Math.max(0, now - dialog.loadedAt) / 1000)) +} diff --git a/packages/gui-plugins/src/pairing/page.tsx b/packages/gui-plugins/src/pairing/page.tsx index b6c90c84685..741a0d16f8a 100644 --- a/packages/gui-plugins/src/pairing/page.tsx +++ b/packages/gui-plugins/src/pairing/page.tsx @@ -2,15 +2,36 @@ import { Button } from "@opencode/ui/button" import { Dialog, DialogBody, DialogHeader, DialogTitleGroup } from "@opencode/ui/dialog" import { Loader } from "@opencode/ui/loader" import { useMutation, useQuery, useQueryClient } from "@tanstack/solid-query" -import { createMemo, createSignal, onCleanup, Show, type Accessor } from "solid-js" +import { createMemo, createSignal, Match, onCleanup, Show, Switch, untrack, type Accessor } from "solid-js" import { renderSVG } from "@opencode/util/qr" -import { usePlugin, type Live, type IpcClient } from "@opencode/plugin/gui" +import { createKeyed, usePlugin, type DialogHandle, type Live, type IpcClient } from "@opencode/plugin/gui" import type { Pairing } from "./contract" +import { copyEffectFailed, createCopyState, transitionCopy, viewCopy, type CopyEffect } from "./copy-machine" +import { createDispatch } from "./dispatch" import type definition from "./index" +import { + createPairingState, + dialogUrl, + pairingEffectFailed, + remainingSeconds, + transitionPairing, + viewDialog, + viewPairingPage, + type DialogState, + type MainStatus, + type PairingEffect, + type PairingEvent, +} from "./machine" import { remoteAddress } from "./remote" type Client = IpcClient +/** The open "Pair a device" dialog, closed with the page. */ +type OpenedDialog = { dialog?: DialogHandle } + +/** The pending clipboard timeout, or the return from "Copied" to the copy label. */ +type CopyTimer = { id?: ReturnType } + /** * The parts of the local server's `ServerRef` the page uses. The renderer passes the live ref, so `client` is read * on every call and follows a restarted server. @@ -24,9 +45,6 @@ export type PairingServer = { } } -/** Where remote access stands for a pairing: turning on, on, or failed to turn on. */ -type Setup = "pending" | "ready" | "failed" - export default function PairingPage(props: { server: Accessor pairing: Accessor> @@ -44,76 +62,131 @@ export default function PairingPage(props: { return live.status === "active" ? live : undefined } - const remoteKey = () => [ctx.id, "remote", main()?.generation] + const [pairingState, setPairingState] = createSignal(createPairingState()) + const pageView = createMemo(() => viewPairingPage(pairingState())) + // Each attempt's request and its timeout or retry delay. + const requests = new Map }>() + const opened: OpenedDialog = {} - const remote = useQuery(() => ({ - queryKey: remoteKey(), - queryFn: (input) => { + const dispatch = createDispatch({ + read: () => untrack(pairingState), + write: setPairingState, + transition: transitionPairing, + run: (effect: PairingEffect) => run(effect), + failed: pairingEffectFailed, + }) + + // Starts an attempt whose timer ends it with `expire`; returns the signal for its request. + const start = (attempt: number, ms: number, expire: () => void) => { + const controller = new AbortController() + + requests.set(attempt, { controller, timer: setTimeout(expire, ms) }) + + return AbortSignal.any([ctx.signal, controller.signal]) + } + + const run = (effect: PairingEffect) => { + if (effect.type === "abort") { + const request = requests.get(effect.attempt) + + requests.delete(effect.attempt) + clearTimeout(request?.timer) + request?.controller.abort() + + return + } + + if (effect.type === "open-dialog") { + opened.dialog = dialogs.open(() => pairingState().dialog} onEvent={dispatch} />) + + return + } + + if (effect.type === "close-dialog") return opened.dialog?.close() + + if (effect.type === "read-remote" || effect.type === "set-remote") { + const attempt = effect.attempt + const fail = () => dispatch({ type: effect.type === "read-remote" ? "read.failed" : "change.failed", attempt }) const live = main() - if (!live) throw new Error("Pairing's main side is not active") + if (live?.generation !== effect.generation) return fail() - return live.value.remote({ signal: input.signal }) - }, - enabled: !!main(), - gcTime: 0, - })) + const signal = start(attempt, effect.timeoutMs, fail) - // Main restarts the background service on every change, so a setting that already matches is left alone unless - // `restart` asks for it, as a tunnel that never connected needs. - const change = useMutation(() => ({ - mutationFn: async (input: { enabled: boolean; restart?: boolean }) => { - const live = main() + if (effect.type === "read-remote") + return void live.value + .remote({ signal }) + .then((enabled) => dispatch({ type: "read.succeeded", attempt, enabled }), fail) - if (!live) throw new Error("Pairing's main side is not active") + // Main restarts the background service on every change, so a setting that already matches is left alone unless + // `restart` asks for it, as a tunnel that never connected needs. + return void (async () => { + if (effect.restart || (await live.value.remote({ signal })) !== effect.enabled) + await live.value.setRemote(effect.enabled, { signal }) + })().then(() => dispatch({ type: "change.succeeded", attempt }), fail) + } - if (input.restart || (await live.value.remote()) !== input.enabled) await live.value.setRemote(input.enabled) - }, - onSuccess: (_, input) => queryClient.setQueryData(remoteKey(), input.enabled), - })) + if (effect.type === "wait") { + const attempt = effect.attempt - const setup = (): Setup => { - if (change.isPending) return "pending" + const phase = effect.for - if (change.isError && change.variables?.enabled) return "failed" + return void start(attempt, effect.delayMs, () => dispatch({ type: "wait.ended", for: phase, attempt })) + } - if (remote.data === true) return "ready" - - return remote.isError ? "failed" : "pending" - } - - const tunnel = async (signal: AbortSignal) => { + const attempt = effect.attempt const server = props.server() - if (!server) throw new Error("The local server is not listed") - const address = remoteAddress((await server.client.server.info({ signal })).urls) + if (effect.type === "poll-tunnel") { + const missing = () => dispatch({ type: "tunnel.missing", attempt }) - if (!address) throw new Error("The remote access tunnel is not connected yet") + if (!server) return missing() - return address + return void server.client.server.info({ signal: start(attempt, effect.timeoutMs, missing) }).then((info) => { + const tunnel = remoteAddress(info.urls) + + dispatch(tunnel ? { type: "tunnel.found", attempt, tunnel } : { type: "tunnel.missing", attempt }) + }, missing) + } + + const failed = () => dispatch({ type: "code.failed", attempt }) + + if (!server) return failed() + + void server.client.server.pair({ signal: start(attempt, effect.timeoutMs, failed) }).then( + (pairing) => + dispatch({ + type: "code.loaded", + attempt, + code: pairing.code, + expiresIn: pairing.expires_in, + now: Date.now(), + }), + failed, + ) } - const code = async (signal: AbortSignal) => { - const server = props.server() + // Follows pairing's main side through its generations, and its pending and inactive states, which a `Live` + // source to `createKeyed` would not tell apart. + createKeyed( + (): MainStatus => { + const live = props.pairing() - if (!server) throw new Error("The local server is not listed") - const pairing = await server.client.server.pair({ signal }) - - return { code: pairing.code, expiresIn: pairing.expires_in } - } - - // Every pairing goes through remote access, so pairing turns it on first. - const pair = () => { - if (remote.data !== true && !change.isPending) change.mutate({ enabled: true }) - dialogs.open(() => ( - change.mutate({ enabled: true, restart })} - tunnel={tunnel} - code={code} - /> - )) - } + return live.status === "active" ? { status: "active", generation: live.generation } : { status: live.status } + }, + (status) => dispatch({ type: "main.changed", main: status }), + { + equals: (previous, next) => + previous.status === next.status && + (previous.status !== "active" || next.status !== "active" || previous.generation === next.generation), + }, + ) + createKeyed( + () => ({ available: !!props.server() }), + (server) => dispatch({ type: "server.changed", available: server.available }), + { equals: (previous, next) => previous.available === next.available }, + ) + onCleanup(() => dispatch({ type: "disposed" })) const screenActive = useQuery(() => ({ queryKey: [ctx.id, "screen-active", main()?.generation], @@ -144,18 +217,17 @@ export default function PairingPage(props: { - + - + - {/* Pending main is still starting; anything else that leaves it inactive keeps pairing from turning on. */} - + @@ -164,14 +236,11 @@ export default function PairingPage(props: { } > - + dispatch({ type: "dialog.opened" })}> {ctx.t("pair.open")} - + change.mutate({ enabled })} + checked={pageView().remoteChecked} + disabled={pageView().remoteDisabled} + onChange={(enabled) => dispatch({ type: "toggled", enabled })} /> } - function DialogPairing(props: { - setup: Accessor - /** Turns remote access on again; `restart` restarts the service even when it is already on. */ - onRetry: (restart: boolean) => void - tunnel: (signal: AbortSignal) => Promise - code: (signal: AbortSignal) => Promise<{ readonly code: string; readonly expiresIn: number }> + dialog: Accessor + onEvent: (event: Extract) => void }) { const ctx = usePlugin() const system = ctx.system + const view = createMemo(() => viewDialog(props.dialog())) + const url = createMemo(() => dialogUrl(props.dialog())) - // The service attaches the tunnel in the background after it starts, so ask until the server advertises it, for - // about three minutes, as `opencode pair --remote` waits. - const tunnel = useQuery(() => ({ - queryKey: [ctx.id, "tunnel"], - queryFn: (input) => props.tunnel(input.signal), - enabled: props.setup() === "ready", - gcTime: 0, - staleTime: Infinity, - retry: 180, - retryDelay: 1000, - })) - - // Codes are single-use, so replace the link as soon as the server forgets the current code. - const code = useQuery(() => ({ - queryKey: [ctx.id, "code", tunnel.data], - queryFn: (input) => props.code(input.signal), - enabled: tunnel.isSuccess, - gcTime: 0, - refetchInterval: (query) => (query.state.data?.expiresIn ?? 60) * 1000, - // A minimized window must not come back to a code that expired while it was hidden. - refetchIntervalInBackground: true, - })) - - // The countdown is the only clock on the page. + // The countdown is the only clock on the page. A window that slept or was hidden ticks again as it comes back, so it + // replaces a code that expired meanwhile at once. const [now, setNow] = createSignal(Date.now()) - const clock = setInterval(() => setNow(Date.now()), 1000) - onCleanup(() => clearInterval(clock)) - const remaining = () => { - if (!code.isSuccess) return 0 + const tick = () => { + const time = Date.now() - // The clock can lag a fresh code by up to a second; a negative age would show one second too many. - return Math.max(0, code.data.expiresIn - Math.floor(Math.max(0, now() - code.dataUpdatedAt) / 1000)) + setNow(time) + props.onEvent({ type: "tick", now: time }) } - const url = createMemo(() => { - if (!code.isSuccess || !tunnel.isSuccess) return - - return new URL(`/auth/connect/${code.data.code}`, tunnel.data).href + const clock = setInterval(tick, 1000) + document.addEventListener("visibilitychange", tick) + onCleanup(() => { + clearInterval(clock) + document.removeEventListener("visibilitychange", tick) + props.onEvent({ type: "dialog.closed" }) }) - // A tunnel error from before a retry stays on the disabled query, so it counts only once setup is ready again. - const failed = () => props.setup() === "failed" || (props.setup() === "ready" && tunnel.isError) + const [copyState, setCopyState] = createSignal(createCopyState()) + const copyView = createMemo(() => viewCopy(copyState(), url())) + const copyTimer: CopyTimer = {} - // "Copied" shows for two seconds after each copy. - const copied: CopiedTimer = {} - onCleanup(() => clearTimeout(copied.timeout)) + const dispatchCopy = createDispatch({ + read: () => untrack(copyState), + write: setCopyState, + transition: transitionCopy, + run: (effect: CopyEffect) => runCopy(effect), + failed: copyEffectFailed, + }) - const copy = useMutation(() => ({ - mutationFn: async () => { - const value = url() + const runCopy = (effect: CopyEffect) => { + if (effect.type === "cancel-timer") return clearTimeout(copyTimer.id) - if (!value) return - await system.copy(value) - }, - onMutate: () => clearTimeout(copied.timeout), - onSuccess: () => { - copied.timeout = setTimeout(() => copy.reset(), 2000) - }, - })) + const attempt = effect.attempt - const refresh = () => ( + if (effect.type === "schedule-feedback") { + copyTimer.id = setTimeout(() => dispatchCopy({ type: "feedback.ended", attempt }), effect.delayMs) + + return + } + + copyTimer.id = setTimeout(() => dispatchCopy({ type: "copy.failed", attempt }), effect.timeoutMs) + void Promise.try(() => system.copy(effect.url)).then( + () => dispatchCopy({ type: "copy.succeeded", attempt }), + () => dispatchCopy({ type: "copy.failed", attempt }), + ) + } + + onCleanup(() => dispatchCopy({ type: "disposed" })) + + const refresh = (disabled: () => boolean) => ( ) - // The QR code carries the remote address as `opencode pair --remote` prints it, {"code","urls"} JSON, which the - // app's scanner reads. - const qr = createMemo(() => { - if (!code.isSuccess || !tunnel.isSuccess) return + const ready = createMemo(() => { + const current = view() - return renderSVG(JSON.stringify({ code: code.data.code, urls: [tunnel.data] }), { - border: 4, - blackColor: "currentColor", - whiteColor: "transparent", - }) + return current.kind === "ready" ? current : undefined + }) + + const loading = createMemo(() => { + const current = view() + + return current.kind === "loading" ? current : undefined + }) + + // The QR code carries the remote address as `opencode pair --remote` prints it, {"code","urls"} JSON, which the + // app's scanner reads. Keyed by its content, so the countdown and a refresh in flight never draw it again. + const payload = createMemo(() => ready()?.qr) + + const qr = createMemo(() => { + const value = payload() + + if (!value) return + + return renderSVG(value, { border: 4, blackColor: "currentColor", whiteColor: "transparent" }) }) // The QR code's frame, which also holds the setup progress and its failure, so the dialog keeps its size. @@ -314,74 +380,90 @@ function DialogPairing(props: { - -
svg]:size-full`} - role="img" - aria-label={ctx.t("qr")} - innerHTML={qr()} - /> -
- - {ctx.t("expires", { time: countdown(remaining()) })} - - {/* The actions wrap together, so a narrow dialog keeps them in one row, right-aligned under the countdown. */} -
- {refresh()} - +
+
+ + )} + + + {(current) => ( +
- {ctx.t(copy.isSuccess ? "common.copied" : "copyLink")} + + + + {ctx.t("setup.title")} + + + {ctx.t("setup.description")} + + +
+ )} +
+ +
+ +
-
-
- -
- - - - {ctx.t("setup.title")} - - - {ctx.t("setup.description")} - - -
-
- -
- - {/* A tunnel that never connected comes back when the service starts it again. */} - -
-
- {/* A failed code fetch hides the link, so the way to try again stays next to the error. */} - -
- - {refresh()} -
-
- + + {/* A failed code fetch hides the link, so the way to try again stays next to the error. */} + +
+ + {refresh(() => false)} +
+
+ +
+ +
+
+ +