From 9f409e32cf7812482592fe799df5a9d636142fb4 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Thu, 26 Nov 2026 01:32:33 +0530 Subject: [PATCH] feat: update VM Bridge from the dashboard, and show Workers how to update The background service's dashboard gets an Update button. It runs `vmbridge update` outside the service (its own process group on macOS, a transient systemd unit on Linux) so the update can stop and start the service. A failed install shows its last line under the button. A Worker now checks for releases too, and its notice opens the git commands that put the release in the user's GitHub copy while keeping their wrangler.jsonc. The dashboard reloads itself once a new version is running. --- README.md | 8 ++- apps/cli/src/index.ts | 9 ++- apps/cli/src/service.ts | 35 +++++++++++- apps/cli/src/update.ts | 17 +++++- apps/server/src/admin.ts | 36 +++++++++++- apps/server/src/index.ts | 34 +++++------- apps/server/src/release.ts | 26 +++++++++ apps/server/src/workers/bridge.ts | 8 ++- apps/server/test/update.test.ts | 91 +++++++++++++++++++++++++++++++ apps/web/src/Canvas.tsx | 81 +++++++++++++++++++++++---- apps/web/src/api.ts | 10 +++- docs/cloudflare.md | 23 ++++++++ packages/contracts/src/index.ts | 17 +++++- 13 files changed, 351 insertions(+), 44 deletions(-) create mode 100644 apps/server/test/update.test.ts diff --git a/README.md b/README.md index d197b2d..78a6acc 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,9 @@ To update, run `vmbridge update`. It downloads the latest release for this machi the release's `SHA256SUMS` (and its build attestation too, when the GitHub CLI is installed and signed in), replaces the installed file and restarts the background service, and devices reconnect on their own. `vmbridge update --check` only says whether there is a newer release. The dashboard shows when -one is out. Running the install command again also updates. +one is out. When VM Bridge runs as the background service, its **Update** button does the same as +`vmbridge update` and reloads the page on the new version. Running the install command again also +updates. Or run it on Cloudflare, with no machine of your own: see [Cloudflare Workers](#cloudflare-workers). @@ -246,6 +248,10 @@ you add to it) is the only one. To change the password, change the secret under There is no machine to read skills or `AGENTS.md` from, so upload skills and paste instructions under **Skills**. How it works, limits and costs: [docs/cloudflare.md](docs/cloudflare.md). +The Worker deploys from your copy on GitHub, so it updates when that copy gets a new release. The +dashboard shows when one is out, with the commands under **How to update**. See +[Updating](docs/cloudflare.md#updating). + ## Commands ``` diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts index 6f20116..8f7903f 100644 --- a/apps/cli/src/index.ts +++ b/apps/cli/src/index.ts @@ -2,10 +2,10 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { parseArgs } from "node:util"; -import { dashboardKey, dataDir, defaultPort, start, version } from "@vmbridge/server"; +import { compiled, dashboardKey, dataDir, defaultPort, start, version } from "@vmbridge/server"; import { pidFile, restartSignal, runningPid, stopProcess } from "./process.ts"; import { logPath, protectLog, service, serviceAddresses } from "./service.ts"; -import { update } from "./update.ts"; +import { update, updateFromDashboard } from "./update.ts"; const help = `VM Bridge ${version} @@ -116,7 +116,10 @@ async function run(options: { host?: string; port: number }) { await stopProcess(existing, restartSignal, restartDeadlineMs + 5_000); } await ensureKey({ ask: false }); - const server = await start(options); + // The dashboard installs updates only for the background service, which the update starts again. A terminal's VM + // Bridge would end with nothing to start it, so its dashboard shows `vmbridge update` instead. + const asService = compiled && (await service.pid()) === process.pid; + const server = await start({ ...options, ...(asService ? { installUpdate: updateFromDashboard } : {}) }); mkdirSync(dataDir(), { recursive: true, mode: 0o700 }); writeFileSync(pidFile(), String(process.pid)); // A service installed by an older version left its log readable by everyone. diff --git a/apps/cli/src/service.ts b/apps/cli/src/service.ts index cf46735..2c29a7a 100644 --- a/apps/cli/src/service.ts +++ b/apps/cli/src/service.ts @@ -1,4 +1,5 @@ -import { chmodSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { spawn } from "node:child_process"; +import { chmodSync, closeSync, existsSync, mkdirSync, openSync, rmSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { childEnv, compiled, dataDir } from "@vmbridge/server"; @@ -44,6 +45,9 @@ function environment() { }; } +/** What a command run outside the service needs: VM Bridge's own update finds the data directory with it. */ +const detachedEnv = () => childEnv(process.env.VMBRIDGE_HOME ? { VMBRIDGE_HOME: process.env.VMBRIDGE_HOME } : {}); + async function exec(args: string[]) { const child = Bun.spawn(args, { stdout: "pipe", stderr: "pipe", stdin: "ignore", env: childEnv() }); const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); @@ -129,6 +133,20 @@ ${env} await must(["launchctl", "kickstart", `${this.domain()}/${label}`]); }, + /** + * Runs `args` with its output appended to `log`, and resolves with its exit code. It runs in its own process group, + * which launchd leaves running when the service exits, so it can stop and start the service. + */ + detached(args: string[], log: string) { + const out = openSync(log, "a", 0o600); + const child = spawn(args[0]!, args.slice(1), { detached: true, stdio: ["ignore", out, out], env: detachedEnv() }); + closeSync(out); + return new Promise((resolve) => { + child.on("error", () => resolve(1)); + child.on("exit", (code) => resolve(code ?? 1)); + }); + }, + async uninstall() { await this.stop(); rmSync(this.plist(), { force: true }); @@ -186,6 +204,20 @@ WantedBy=default.target await must(["systemctl", "--user", "start", "vmbridge.service"]); }, + /** + * Runs `args` with its output appended to `log`, and resolves with its exit code. It runs as its own transient unit: + * systemd stops everything in the service's unit when it exits, which would end a plain child halfway. + */ + async detached(args: string[], log: string) { + const env = Object.entries(detachedEnv()).map(([key, value]) => `--setenv=${key}=${value}`); + const output = [`--property=StandardOutput=append:${log}`, `--property=StandardError=append:${log}`]; + const child = Bun.spawn(["systemd-run", "--user", "--collect", "--quiet", "--wait", ...output, ...env, "--", ...args], { + stdio: ["ignore", "ignore", "ignore"], + env: childEnv(), + }); + return await child.exited; + }, + async uninstall() { if (!existsSync(this.unit())) return; await exec(["systemctl", "--user", "disable", "--now", "vmbridge.service"]); @@ -201,6 +233,7 @@ const unsupported = { stop: async () => false, pid: async (): Promise => null, start: async () => {}, + detached: async (_: string[], __: string) => 1, uninstall: async () => {}, }; diff --git a/apps/cli/src/update.ts b/apps/cli/src/update.ts index 13274d3..c025129 100644 --- a/apps/cli/src/update.ts +++ b/apps/cli/src/update.ts @@ -1,6 +1,6 @@ -import { realpathSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import { checksumFor, childEnv, compiled, isNewer, latestVersion, releaseRepo, version } from "@vmbridge/server"; +import { checksumFor, childEnv, compiled, dataDir, isNewer, latestVersion, releaseRepo, version } from "@vmbridge/server"; import { pidFile, restartSignal, runningPid, stopProcess } from "./process.ts"; import { service } from "./service.ts"; @@ -94,3 +94,16 @@ export async function update({ check }: { check: boolean }) { console.log(`Updated VM Bridge from ${version} to ${latest}.`); await restart(latest); } + +/** + * The dashboard's Update button, in the background service: runs `vmbridge update` outside the service, since the + * update stops the service and starts it again on the new release. Rejects with the update's last line when it fails; + * when it works, this process is stopped first. + */ +export async function updateFromDashboard() { + const log = join(dataDir(), "update.log"); + writeFileSync(log, "", { mode: 0o600 }); + const code = await service.detached([process.execPath, "update"], log); + const last = readFileSync(log, "utf8").trim().split("\n").at(-1); + throw new Error(last || (code === 0 ? "The update finished, but VM Bridge did not restart." : "The update failed.")); +} diff --git a/apps/server/src/admin.ts b/apps/server/src/admin.ts index 8f31a4e..bc17fea 100644 --- a/apps/server/src/admin.ts +++ b/apps/server/src/admin.ts @@ -12,6 +12,7 @@ import { type RepoRule, type VmInfo, type VmSize, + type BridgeUpdate, } from "@vmbridge/contracts"; import { analyticsReport } from "./analytics.ts"; import { InvalidSignIn, type AgentAuth, type TokenInput } from "./agent-auth/profiles.ts"; @@ -62,8 +63,8 @@ export interface AdminDeps { network: BridgeNetwork; /** Where the dashboard password is set instead of the dashboard, such as a Worker's secret. Null when it can be changed here. */ passwordSource: string | null; - /** A newer VM Bridge release that `vmbridge update` installs, or null. */ - availableUpdate: () => string | null; + /** A newer VM Bridge release, or null, how this runtime moves to it, and the install the Update button runs, if it has one. */ + update: { available: () => string | null; how: BridgeUpdate["how"]; install: (() => Promise) | null }; settings: Settings; secrets: Secrets; store: Store; @@ -126,6 +127,10 @@ function timeRange(request: Request) { * Secret values go in and never come out: responses only say whether each one is set. */ export class Admin { + /** The dashboard's install of a new release is running. A second Update click while it runs does nothing. */ + private installing = false; + private installError: string | null = null; + constructor(private readonly deps: AdminDeps) {} async fetch(request: Request, origin: RequestOrigin): Promise { @@ -195,6 +200,25 @@ export class Admin { return json({ ok: true }); } if (path === "/overview" && method === "GET") return json(this.overview()); + if (path === "/update" && method === "POST") { + const { install, available } = this.deps.update; + if (!install || !available()) throw new BadRequest("There is no update to install from the dashboard."); + if (!this.installing) { + this.installing = true; + this.installError = null; + // When the install works, VM Bridge restarts on the new release before this settles. + void install() + .catch((error) => { + this.installError = message(error); + }) + .finally(() => { + this.installing = false; + fleet.emit("changed"); + }); + fleet.emit("changed"); + } + return json({ ok: true }, 202); + } if (path === "/events" && method === "GET") return this.events(request); if (path === "/traffic" && method === "GET") return json(this.deps.traffic.recent); if (path === "/usage" && method === "GET") { @@ -628,6 +652,12 @@ export class Admin { this.deps.hub.emit("config"); } + private availableUpdate(): BridgeUpdate | null { + const version = this.deps.update.available(); + if (!version) return null; + return { version, how: this.deps.update.how, installing: this.installing, error: this.installError }; + } + overview(): Overview { const { settings, secrets, store, fleet, hub, clients, gateway } = this.deps; const defaultProvider = settings.get("defaultProvider"); @@ -680,7 +710,7 @@ export class Admin { }; }); return { - bridge: { id: settings.get("bridgeId"), version: this.deps.version, startedAt: this.deps.startedAt, update: this.deps.availableUpdate() }, + bridge: { id: settings.get("bridgeId"), version: this.deps.version, startedAt: this.deps.startedAt, update: this.availableUpdate() }, setup: { provider: Boolean(defaultProvider), github: secrets.has("github.token"), diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index b43808f..9f1597f 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -27,7 +27,7 @@ import { networkInfo, wantedHosts } from "./bun/network.ts"; import { Secrets, type Plaintext } from "./settings.ts"; import type { Sql } from "./sql.ts"; import { CloudflareTunnel, requestOrigin } from "./bun/tunnel.ts"; -import { isNewer, latestVersion, releaseCheckMs } from "./release.ts"; +import { releaseCheck } from "./release.ts"; import { isWatchPath, type Viewer } from "./watch/watch.ts"; /** A T3 client's RPC socket, or a relayed stream's: a watch page's or a preview tab's. */ @@ -80,6 +80,11 @@ export interface StartOptions { /** Listen on this one address instead of loopback, Tailscale and the local network switch. 0.0.0.0 is every network. */ host?: string; port?: number; + /** + * Installs the latest release and restarts VM Bridge on it, for the dashboard's Update button. It rejects when the + * install fails; when it works, this process is stopped before it settles. Without it the dashboard shows the command. + */ + installUpdate?: () => Promise; } export async function start(options: StartOptions = {}) { @@ -111,11 +116,14 @@ export async function start(options: StartOptions = {}) { let listeners: Listeners; const served = () => ({ hosts: listeners.hosts(), port: listeners.port, fixed: host !== undefined, localNetwork: settings.get("localNetwork") }); network = new BunNetwork({ served, applyAddresses: () => listeners.apply(), settings, secrets, tunnel: () => tunnel }); - const availableUpdate = () => { - const latest = settings.get("latestRelease")?.version; - return latest && isNewer(latest, version) ? latest : null; + // Only the release binary checks (below): from source, `git pull` updates. + const release = releaseCheck(settings, version); + const update = { + available: release.available, + how: options.installUpdate ? ("dashboard" as const) : ("command" as const), + install: options.installUpdate ?? null, }; - const admin = new Admin({ ...bridge, version, startedAt: Date.now(), network, passwordSource: null, availableUpdate }); + const admin = new Admin({ ...bridge, version, startedAt: Date.now(), network, passwordSource: null, update }); // A relayed stream's socket carries its viewer; any other is a T3 client's RPC socket, so the casts only drop the viewer case. const websocket: WebSocketHandler = { maxPayloadLength: 16 * 1024 * 1024, @@ -209,24 +217,12 @@ export async function start(options: StartOptions = {}) { }; // Follows Tailscale coming up or changing address, and the local network appearing or changing. const addresses = { name: "addresses", everyMs: 5_000, run: () => listeners.apply() }; - // The dashboard's update notice. Only the release binary checks: from source, `git pull` updates. - const releaseCheck = { - name: "release check", - everyMs: 60 * 60_000, - run: async () => { - const saved = settings.get("latestRelease"); - if (saved && Date.now() - saved.checkedAt < releaseCheckMs) return; - // Offline or limited by GitHub: the next hourly run tries again. - const latest = await latestVersion().catch(() => null); - if (latest) settings.set("latestRelease", { version: latest, checkedAt: Date.now() }); - }, - }; - if (compiled) void releaseCheck.run(); + if (compiled) void release.job.run(); const stopJobs = runJobs([ ...bridgeJobs({ hub, fleet, stats, usage, budget, traffic, watch }), localSkills, ...(host ? [] : [addresses]), - ...(compiled ? [releaseCheck] : []), + ...(compiled ? [release.job] : []), ]); void fleet.resume(); // Accounts saved by older versions lack the details the dashboard shows. diff --git a/apps/server/src/release.ts b/apps/server/src/release.ts index aa12b10..46c7918 100644 --- a/apps/server/src/release.ts +++ b/apps/server/src/release.ts @@ -1,5 +1,8 @@ // VM Bridge's own releases on GitHub: the dashboard's update notice and `vmbridge update` both read them. +import type { Job } from "./jobs.ts"; +import type { Settings } from "./settings.ts"; + export const releaseRepo = "vkpdeveloper/vmbridge"; /** Checked at most this often for the dashboard, since GitHub limits requests without a token to 60 an hour. */ @@ -43,3 +46,26 @@ export function checksumFor(sums: string, file: string): string | null { } return null; } + +/** + * The dashboard's update notice: a job that asks GitHub for the latest release at most every releaseCheckMs and saves + * the answer, and the newer release it found, if any. + */ +export function releaseCheck(settings: Settings, current: string, fetcher: Fetcher = fetch) { + const job: Job = { + name: "release check", + everyMs: 60 * 60_000, + run: async () => { + const saved = settings.get("latestRelease"); + if (saved && Date.now() - saved.checkedAt < releaseCheckMs) return; + // Offline or limited by GitHub: the next hourly run tries again. + const latest = await latestVersion(fetcher).catch(() => null); + if (latest) settings.set("latestRelease", { version: latest, checkedAt: Date.now() }); + }, + }; + const available = () => { + const latest = settings.get("latestRelease")?.version; + return latest && isNewer(latest, current) ? latest : null; + }; + return { job, available }; +} diff --git a/apps/server/src/workers/bridge.ts b/apps/server/src/workers/bridge.ts index fcc21b3..87254a5 100644 --- a/apps/server/src/workers/bridge.ts +++ b/apps/server/src/workers/bridge.ts @@ -8,6 +8,7 @@ import { keyFromText, keyVariable } from "../encryption.ts"; import { message } from "../fleet.ts"; import type { Upgrade } from "../gateway/http.ts"; import { bridgeJobs } from "../jobs.ts"; +import { releaseCheck } from "../release.ts"; import { isWatchPath, type WatchUpgrade } from "../watch/watch.ts"; import { workersFetchCompat } from "../providers/workers-fetch.ts"; import { withSecurityHeaders } from "../security-headers.ts"; @@ -95,8 +96,11 @@ export class BridgeObject extends DurableObject { secrets.set(passwordSourceSecret, source); } - const admin = new Admin({ ...bridge, version: packageJson.version, startedAt: Date.now(), network: workerNetwork, passwordSource: `the Worker's ${passwordVariable} secret`, availableUpdate: () => null }); - const jobs = new AlarmJobs(this.ctx.storage, bridgeJobs({ hub, fleet, stats, usage, budget, traffic, watch })); + // A Worker updates when its GitHub repository gets the new release, so the dashboard shows how instead of a button. + const release = releaseCheck(bridge.settings, packageJson.version); + const update = { available: release.available, how: "cloudflare" as const, install: null }; + const admin = new Admin({ ...bridge, version: packageJson.version, startedAt: Date.now(), network: workerNetwork, passwordSource: `the Worker's ${passwordVariable} secret`, update }); + const jobs = new AlarmJobs(this.ctx.storage, [...bridgeJobs({ hub, fleet, stats, usage, budget, traffic, watch }), release.job]); // A recreated Durable Object already knows its address; without this, links would read as off until the next alarm. await watch.refresh(); void fleet.resume(); diff --git a/apps/server/test/update.test.ts b/apps/server/test/update.test.ts new file mode 100644 index 0000000..04b2d41 --- /dev/null +++ b/apps/server/test/update.test.ts @@ -0,0 +1,91 @@ +import { afterEach, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { Overview } from "@vmbridge/contracts"; +import { openDatabase } from "../src/bun/sqlite.ts"; +import { dashboardKey, databasePath, start, type StartOptions } from "../src/index.ts"; +import { releaseCheck, releaseCheckMs } from "../src/release.ts"; +import { Settings } from "../src/settings.ts"; + +const password = "update test password"; +const cleanups: (() => Promise)[] = []; + +afterEach(async () => { + for (const cleanup of cleanups.splice(0)) await cleanup(); +}); + +/** A bridge whose last release check found 99.0.0, with a logged-in dashboard. */ +async function bridgeWithRelease(options: Pick) { + const dir = mkdtempSync(join(tmpdir(), "vmbridge-update-")); + const keys = dashboardKey(dir); + await keys.set(password); + keys.close(); + const db = openDatabase(databasePath(dir)); + new Settings(db).set("latestRelease", { version: "99.0.0", checkedAt: Date.now() }); + db.close(); + const bridge = await start({ dir, host: "127.0.0.1", port: 0, ...options }); + cleanups.push(async () => { + await bridge.stop(); + rmSync(dir, { recursive: true, force: true }); + }); + const base = `http://127.0.0.1:${bridge.port}`; + const login = await fetch(`${base}/admin/api/login`, { method: "POST", headers: { "content-type": "application/json", origin: base }, body: JSON.stringify({ key: password }) }); + const cookie = login.headers.get("set-cookie")!.split(";")[0]!; + const headers = { "content-type": "application/json", origin: base, cookie }; + return { + update: async () => ((await (await fetch(`${base}/admin/api/overview`, { headers })).json()) as Overview).bridge.update, + install: () => fetch(`${base}/admin/api/update`, { method: "POST", headers, body: "{}" }), + }; +} + +test("the Update button installs once at a time, and shows why an install failed", async () => { + let installs = 0; + let fail = (_: Error) => {}; + const dashboard = await bridgeWithRelease({ + installUpdate: () => { + installs++; + return new Promise((_, reject) => (fail = reject)); + }, + }); + expect(await dashboard.update()).toEqual({ version: "99.0.0", how: "dashboard", installing: false, error: null }); + + expect((await dashboard.install()).status).toBe(202); + expect((await dashboard.install()).status).toBe(202); + expect(installs).toBe(1); + expect(await dashboard.update()).toMatchObject({ installing: true, error: null }); + + fail(new Error("The download does not match its checksum. Nothing was changed.")); + await Bun.sleep(10); + expect(await dashboard.update()).toMatchObject({ installing: false, error: "The download does not match its checksum. Nothing was changed." }); + expect((await dashboard.install()).status).toBe(202); + expect(installs).toBe(2); +}); + +test("without an install, as in a terminal's VM Bridge, the dashboard shows the command and refuses to install", async () => { + const dashboard = await bridgeWithRelease({}); + expect(await dashboard.update()).toMatchObject({ version: "99.0.0", how: "command" }); + expect((await dashboard.install()).status).toBe(400); +}); + +test("the release check asks GitHub at most every few hours and offers only a newer release", async () => { + const settings = new Settings(openDatabase(":memory:")); + let asked = 0; + let latest = "v1.2.0"; + const check = releaseCheck(settings, "1.1.0", async () => { + asked++; + return Response.json({ tag_name: latest }); + }); + expect(check.available()).toBeNull(); + await check.job.run(); + expect(check.available()).toBe("1.2.0"); + latest = "v1.3.0"; + await check.job.run(); + expect(asked).toBe(1); + + settings.set("latestRelease", { version: "1.2.0", checkedAt: Date.now() - releaseCheckMs }); + await check.job.run(); + expect(asked).toBe(2); + expect(check.available()).toBe("1.3.0"); + expect(releaseCheck(settings, "1.3.0").available()).toBeNull(); +}); diff --git a/apps/web/src/Canvas.tsx b/apps/web/src/Canvas.tsx index 4c1d65e..275fcac 100644 --- a/apps/web/src/Canvas.tsx +++ b/apps/web/src/Canvas.tsx @@ -17,7 +17,7 @@ import { } from "@xyflow/react"; import { HugeiconsIcon } from "@hugeicons/react"; import { Add01Icon, Alert02Icon, Cancel01Icon, CenterFocusIcon, Delete02Icon, Folder01Icon, InformationCircleIcon, LaptopIcon, Message01Icon, Moon02Icon, PowerIcon, ZoomInIcon, ZoomOutIcon } from "@hugeicons/core-free-icons"; -import { vmSizes, type ClientInfo, type Overview, type ProjectInfo, type ProviderId, type TrafficEvent, type Usage, type VmInfo, type VmSize, type VmState, type VmStats } from "@vmbridge/contracts"; +import { vmSizes, type BridgeUpdate, type ClientInfo, type Overview, type ProjectInfo, type ProviderId, type TrafficEvent, type Usage, type VmInfo, type VmSize, type VmState, type VmStats } from "@vmbridge/contracts"; import { AlertDialog, AlertDialogAction, @@ -42,6 +42,7 @@ import { ContextMenuTrigger, } from "@/components/ui/context-menu"; import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { ButtonGroup } from "@/components/ui/button-group"; import { Field, FieldLabel } from "@/components/ui/field"; import { Item, ItemActions, ItemContent, ItemDescription, ItemGroup, ItemMedia, ItemTitle } from "@/components/ui/item"; @@ -147,21 +148,81 @@ function BridgeCard({ data }: NodeProps) {
v{overview.bridge.version}
- {overview.bridge.update && ( -
-
-
VM Bridge {overview.bridge.update} is available
- vmbridge update -
- -
- )} + {overview.bridge.update && } {overview.providers.length === 0 &&
No provider yet
} ); } +/** The new release's notice, and the way to it this runtime has. The page reloads once the new version runs (useLive). */ +function UpdateRow({ update }: { update: BridgeUpdate }) { + const action = useAction(); + const error = action.error ?? update.error; + if (update.how === "command") { + return ( +
+
+
VM Bridge {update.version} is available
+ vmbridge update +
+ +
+ ); + } + return ( +
+
+
{update.installing ? `Updating to ${update.version}...` : `VM Bridge ${update.version} is available`}
+ {update.how === "cloudflare" && } + {update.how === "dashboard" && !update.installing && ( + + )} +
+ {error && !update.installing &&
{error}
} +
+ ); +} + +/** A Worker deploys from the user's own copy of the repository, so the update is a commit there. */ +function CloudflareUpdate({ version }: { version: string }) { + const commands = [ + "git clone https://github.com/YOUR-NAME/YOUR-REPOSITORY.git vmbridge-worker", + "cd vmbridge-worker", + `git fetch --no-tags https://github.com/vkpdeveloper/vmbridge.git refs/tags/v${version}`, + "git read-tree -u --reset FETCH_HEAD", + "git checkout HEAD -- wrangler.jsonc", + `git commit -m "VM Bridge ${version}"`, + "git push", + ].join("\n"); + return ( + + + + + + + Update to {version} + + This Worker deploys from your copy of VM Bridge on GitHub. Run these with your repository's address, keeping your wrangler.jsonc. Cloudflare + deploys the push, and this page reloads within a few minutes. + + +
+
{commands}
+
+ +
+
+
+
+ ); +} + function VmCard({ data }: NodeProps) { const { vm, projects, selected } = data; const state = vmStates[vm.state]; diff --git a/apps/web/src/api.ts b/apps/web/src/api.ts index 1b2651d..7281ef5 100644 --- a/apps/web/src/api.ts +++ b/apps/web/src/api.ts @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import type { LiveMessage, Overview, TrafficEvent } from "@vmbridge/contracts"; export class ApiError extends Error { @@ -53,6 +53,14 @@ export function useLive() { const [traffic, setTraffic] = useState([]); const [online, setOnline] = useState(true); + // A new version of VM Bridge has a new dashboard, so the page reloads once one is running, as after an update. + const version = overview?.bridge.version; + const firstVersion = useRef(version); + useEffect(() => { + firstVersion.current ??= version; + if (version && version !== firstVersion.current) location.reload(); + }, [version]); + useEffect(() => { let cancelled = false; let streaming = false; diff --git a/docs/cloudflare.md b/docs/cloudflare.md index c1dde9c..83477a2 100644 --- a/docs/cloudflare.md +++ b/docs/cloudflare.md @@ -20,6 +20,29 @@ within five minutes, and T3 reconnects on its own. If a secret is missing or too weak, every page shows "VM Bridge needs setup" and the API does nothing until you set it under the Worker's **Settings**, **Variables and Secrets**. +## Updating + +Your Worker runs whatever is in your copy of the repository, so a new VM Bridge release reaches it +only when you put the release there. The dashboard checks for releases every few hours and shows +**VM Bridge X is available** with a **How to update** button, which gives these commands for that +version (1.2.0 here): + +```sh +git clone https://github.com/YOUR-NAME/YOUR-REPOSITORY.git vmbridge-worker +cd vmbridge-worker +git fetch --no-tags https://github.com/vkpdeveloper/vmbridge.git refs/tags/v1.2.0 +git read-tree -u --reset FETCH_HEAD +git checkout HEAD -- wrangler.jsonc +git commit -m "VM Bridge 1.2.0" +git push +``` + +`read-tree` makes your copy's files match the release, including files the release removed, whether +or not your copy shares this repository's history. `checkout` then keeps +your own `wrangler.jsonc`, which holds the Worker name you chose when deploying. The push deploys the +release, and the dashboard reloads on it within a few minutes. Your saved data stays in the Durable +Object, so nothing has to be set up again. + ## The secrets - `VMBRIDGE_PASSWORD`: the dashboard password, at least 12 characters. Changing the secret changes diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index ce72cc3..ec785b0 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -410,9 +410,22 @@ export interface BridgeSettings { agentFeedback: AgentFeedbackMode; } +/** A newer VM Bridge release. Only the release binary and a Worker check, so it is null when run from source. */ +export interface BridgeUpdate { + version: string; + /** + * How to move to it. "dashboard": the dashboard installs it and restarts the background service. "command": + * `vmbridge update` in a terminal. "cloudflare": bring the release into the Worker's GitHub repository, which deploys it. + */ + how: "dashboard" | "command" | "cloudflare"; + /** The dashboard started installing it, and VM Bridge has not restarted yet. */ + installing: boolean; + /** Why the last install from the dashboard failed. */ + error: string | null; +} + export interface Overview { - /** `update` is a newer release `vmbridge update` installs. Only the release binary checks, so it is null from source. */ - bridge: { id: string; version: string; startedAt: number; update: string | null }; + bridge: { id: string; version: string; startedAt: number; update: BridgeUpdate | null }; setup: Setup; /** Added providers, in the order they were added. */ providers: ProviderInfo[];