Skip to content

Commit 85ab73b

Browse files
authored
feat(den): gate desktop updates by supported version (anomalyco#1476)
Co-authored-by: src-opn <[email protected]>
1 parent ac7e082 commit 85ab73b

10 files changed

Lines changed: 212 additions & 1 deletion

File tree

‎apps/app/src/app/lib/den.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,11 @@ export type DenDesktopHandoffExchange = {
158158
token: string | null;
159159
};
160160

161+
export type DenAppVersionMetadata = {
162+
minAppVersion: string;
163+
latestAppVersion: string;
164+
};
165+
161166
type RawJsonResponse<T> = {
162167
ok: boolean;
163168
status: number;
@@ -182,6 +187,20 @@ function isRecord(value: unknown): value is Record<string, unknown> {
182187
return typeof value === "object" && value !== null;
183188
}
184189

190+
function getDenAppVersionMetadata(payload: unknown): DenAppVersionMetadata | null {
191+
if (!isRecord(payload)) return null;
192+
193+
const latestAppVersion =
194+
typeof payload.latestAppVersion === "string" ? payload.latestAppVersion.trim() : "";
195+
if (!latestAppVersion) return null;
196+
197+
return {
198+
minAppVersion:
199+
typeof payload.minAppVersion === "string" ? payload.minAppVersion.trim() : "",
200+
latestAppVersion,
201+
};
202+
}
203+
185204
export function normalizeDenBaseUrl(input: string | null | undefined): string | null {
186205
const value = (input ?? "").trim();
187206
if (!value) return null;
@@ -911,6 +930,17 @@ export function createDenClient(options: { baseUrl: string; token?: string | nul
911930
return user;
912931
},
913932

933+
async getAppVersionMetadata(): Promise<DenAppVersionMetadata> {
934+
const payload = await requestJson<unknown>(baseUrls, "/v1/app-version", {
935+
method: "GET",
936+
});
937+
const appVersionMetadata = getDenAppVersionMetadata(payload);
938+
if (!appVersionMetadata) {
939+
throw new DenApiError(500, "invalid_app_version_payload", "App version response was missing version details.");
940+
}
941+
return appVersionMetadata;
942+
},
943+
914944
async exchangeDesktopHandoff(grant: string): Promise<DenDesktopHandoffExchange> {
915945
const payload = await requestJson<unknown>(baseUrls, "/v1/auth/desktop-handoff/exchange", {
916946
method: "POST",

‎apps/app/src/app/system-state.ts‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import type {
1818
import { addOpencodeCacheHint, isTauriRuntime, safeStringify } from "./utils";
1919
import { filterProviderList, mapConfigProvidersToList } from "./utils/providers";
2020
import { createUpdaterState, type UpdateStatus } from "./context/updater";
21+
import { createDenClient, readDenSettings } from "./lib/den";
2122
import {
2223
resetOpenworkState,
2324
resetOpencodeCache,
@@ -65,6 +66,84 @@ function forcedDevUpdateStatus(): UpdateStatus | null {
6566
};
6667
}
6768

69+
function parseComparableVersion(value: string): { release: number[]; prerelease: string[] } | null {
70+
const normalized = value.trim().replace(/^v/i, "");
71+
if (!normalized) return null;
72+
73+
const [versionCore] = normalized.split("+", 1);
74+
if (!versionCore) return null;
75+
76+
const [releasePart, prereleasePart = ""] = versionCore.split("-", 2);
77+
const release = releasePart.split(".").map((segment) => Number(segment));
78+
if (!release.length || release.some((segment) => !Number.isInteger(segment) || segment < 0)) {
79+
return null;
80+
}
81+
82+
const prerelease = prereleasePart
83+
.split(".")
84+
.map((segment) => segment.trim())
85+
.filter(Boolean);
86+
87+
return { release, prerelease };
88+
}
89+
90+
function comparePrereleaseIdentifiers(left: string[], right: string[]): number {
91+
if (!left.length && !right.length) return 0;
92+
if (!left.length) return 1;
93+
if (!right.length) return -1;
94+
95+
const count = Math.max(left.length, right.length);
96+
for (let index = 0; index < count; index += 1) {
97+
const leftPart = left[index];
98+
const rightPart = right[index];
99+
if (leftPart === undefined) return -1;
100+
if (rightPart === undefined) return 1;
101+
102+
const leftNumeric = /^\d+$/.test(leftPart) ? Number(leftPart) : null;
103+
const rightNumeric = /^\d+$/.test(rightPart) ? Number(rightPart) : null;
104+
105+
if (leftNumeric !== null && rightNumeric !== null) {
106+
if (leftNumeric !== rightNumeric) return leftNumeric < rightNumeric ? -1 : 1;
107+
continue;
108+
}
109+
110+
if (leftNumeric !== null) return -1;
111+
if (rightNumeric !== null) return 1;
112+
113+
const comparison = leftPart.localeCompare(rightPart);
114+
if (comparison !== 0) return comparison < 0 ? -1 : 1;
115+
}
116+
117+
return 0;
118+
}
119+
120+
function compareVersions(left: string, right: string): number | null {
121+
const parsedLeft = parseComparableVersion(left);
122+
const parsedRight = parseComparableVersion(right);
123+
if (!parsedLeft || !parsedRight) return null;
124+
125+
const count = Math.max(parsedLeft.release.length, parsedRight.release.length);
126+
for (let index = 0; index < count; index += 1) {
127+
const leftPart = parsedLeft.release[index] ?? 0;
128+
const rightPart = parsedRight.release[index] ?? 0;
129+
if (leftPart !== rightPart) return leftPart < rightPart ? -1 : 1;
130+
}
131+
132+
return comparePrereleaseIdentifiers(parsedLeft.prerelease, parsedRight.prerelease);
133+
}
134+
135+
async function isUpdateSupportedByDen(updateVersion: string) {
136+
try {
137+
const settings = readDenSettings();
138+
const client = createDenClient({ baseUrl: settings.baseUrl });
139+
const metadata = await client.getAppVersionMetadata();
140+
const comparison = compareVersions(updateVersion, metadata.latestAppVersion);
141+
return comparison !== null && comparison <= 0;
142+
} catch {
143+
return false;
144+
}
145+
}
146+
68147
export function createSystemState(options: {
69148
client: Accessor<Client | null>;
70149
sessions: Accessor<Session[]>;
@@ -444,6 +523,13 @@ export function createSystemState(options: {
444523
}
445524

446525
const notes = typeof update.body === "string" ? update.body : undefined;
526+
527+
if (!(await isUpdateSupportedByDen(update.version))) {
528+
setPendingUpdate(null);
529+
setUpdateStatus({ state: "idle", lastCheckedAt: checkedAt });
530+
return;
531+
}
532+
447533
setPendingUpdate({ update, version: update.version, notes });
448534
setUpdateStatus({
449535
state: "available",

‎ee/apps/den-api/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"scripts": {
66
"dev": "OPENWORK_DEV_MODE=1 tsx watch src/server.ts",
77
"dev:local": "sh -lc 'OPENWORK_DEV_MODE=1 PORT=${DEN_API_PORT:-8790} tsx watch src/server.ts'",
8-
"build": "pnpm run build:den-db && tsc -p tsconfig.json",
8+
"build": "node ./scripts/build.mjs",
99
"build:den-db": "pnpm --filter @openwork-ee/den-db build",
1010
"start": "node dist/server.js"
1111
},

‎ee/apps/den-api/scripts/build.mjs‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { spawnSync } from "node:child_process"
2+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
3+
import path from "node:path"
4+
import { fileURLToPath } from "node:url"
5+
6+
const scriptDir = path.dirname(fileURLToPath(import.meta.url))
7+
const serviceDir = path.resolve(scriptDir, "..")
8+
const repoRoot = path.resolve(serviceDir, "..", "..", "..")
9+
const desktopPackagePath = path.join(repoRoot, "apps", "desktop", "package.json")
10+
const generatedVersionPath = path.join(serviceDir, "src", "generated", "app-version.ts")
11+
const pnpmCommand = process.platform === "win32" ? "pnpm.cmd" : "pnpm"
12+
13+
function readDesktopVersion() {
14+
const packageJson = JSON.parse(readFileSync(desktopPackagePath, "utf8"))
15+
const version = packageJson.version?.trim()
16+
17+
if (!version) {
18+
throw new Error(`Desktop version missing in ${desktopPackagePath}`)
19+
}
20+
21+
return version
22+
}
23+
24+
function writeGeneratedVersionFile(latestAppVersion) {
25+
mkdirSync(path.dirname(generatedVersionPath), { recursive: true })
26+
writeFileSync(
27+
generatedVersionPath,
28+
`export const BUILD_LATEST_APP_VERSION = ${JSON.stringify(latestAppVersion)} as const\n`,
29+
)
30+
}
31+
32+
function run(command, args) {
33+
const result = spawnSync(command, args, {
34+
cwd: serviceDir,
35+
env: process.env,
36+
stdio: "inherit",
37+
})
38+
39+
if (result.status !== 0) {
40+
process.exit(result.status ?? 1)
41+
}
42+
}
43+
44+
process.env.DEN_API_LATEST_APP_VERSION = readDesktopVersion()
45+
writeGeneratedVersionFile(process.env.DEN_API_LATEST_APP_VERSION)
46+
47+
run(pnpmCommand, ["run", "build:den-db"])
48+
run(pnpmCommand, ["exec", "tsc", "-p", "tsconfig.json"])

‎ee/apps/den-api/src/app.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { registerAdminRoutes } from "./routes/admin/index.js"
1515
import { registerAuthRoutes } from "./routes/auth/index.js"
1616
import { registerMeRoutes } from "./routes/me/index.js"
1717
import { registerOrgRoutes } from "./routes/org/index.js"
18+
import { registerVersionRoutes } from "./routes/version/index.js"
1819
import { registerWorkerRoutes } from "./routes/workers/index.js"
1920
import type { AuthContextVariables } from "./session.js"
2021
import { sessionMiddleware } from "./session.js"
@@ -106,6 +107,7 @@ registerAdminRoutes(app)
106107
registerAuthRoutes(app)
107108
registerMeRoutes(app)
108109
registerOrgRoutes(app)
110+
registerVersionRoutes(app)
109111
registerWorkerRoutes(app)
110112

111113
app.get(
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const BUILD_LATEST_APP_VERSION = "0.11.207" as const

‎ee/apps/den-api/src/routes/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ This folder groups Den API endpoints by product surface instead of keeping one l
88
- `me/`: current-user routes that describe the signed-in user and their org access
99
- `org/`: organization routes split into focused files by concern
1010
- `admin/`: admin-only operational endpoints
11+
- `version/`: public app version metadata for desktop update checks
1112
- `workers/`: worker lifecycle, runtime, billing, and heartbeat routes
1213

1314
## Conventions
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Version Routes
2+
3+
This folder contains public Den API routes that expose app version metadata for desktop clients.
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import type { Env, Hono } from "hono"
2+
import { describeRoute } from "hono-openapi"
3+
import { z } from "zod"
4+
import { jsonResponse } from "../../openapi.js"
5+
import { denApiAppVersion } from "../../version.js"
6+
7+
const appVersionResponseSchema = z.object({
8+
minAppVersion: z.string(),
9+
latestAppVersion: z.string().min(1),
10+
}).meta({ ref: "DenAppVersionResponse" })
11+
12+
export function registerVersionRoutes<T extends Env>(app: Hono<T>) {
13+
app.get(
14+
"/v1/app-version",
15+
describeRoute({
16+
tags: ["System"],
17+
summary: "Get desktop app version metadata",
18+
description: "Returns the minimum supported desktop app version and the latest desktop app version published with this Den API build.",
19+
responses: {
20+
200: jsonResponse("Desktop app version metadata returned successfully.", appVersionResponseSchema),
21+
},
22+
}),
23+
(c) => {
24+
return c.json(denApiAppVersion)
25+
},
26+
)
27+
}

‎ee/apps/den-api/src/version.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { BUILD_LATEST_APP_VERSION } from "./generated/app-version.js";
2+
3+
const MIN_APP_VERSION = "0.11.207";
4+
5+
function normalizeVersion(value: string | undefined | null) {
6+
const trimmed = value?.trim() ?? "";
7+
return trimmed || null;
8+
}
9+
10+
export const denApiAppVersion = {
11+
minAppVersion: MIN_APP_VERSION,
12+
latestAppVersion: normalizeVersion(BUILD_LATEST_APP_VERSION) ?? "0.0.0",
13+
} as const;

0 commit comments

Comments
 (0)