diff --git a/CHANGELOG b/CHANGELOG index b6ae075e..8f7fa134 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -12,6 +12,7 @@ * Navigate app: Location indicator rotates based on the compass * Navigate app: Add saved home/work and recent address settings * Navigate app: Darken the map background color +* EvenHub app: Add New, Search, and Updates tabs * Timer app: Fully rewritten, with new better UI ## 0.6.4 - 2026-09-02 diff --git a/app/apps/evenhub/even-api.ts b/app/apps/evenhub/even-api.ts index 00655752..971a10ec 100644 --- a/app/apps/evenhub/even-api.ts +++ b/app/apps/evenhub/even-api.ts @@ -20,6 +20,7 @@ const API_HOST = "https://api.evenrealities.com"; const PUBLIC_CDN_HOST = "https://cdn-pub.evenhub.evenrealities.com"; const SIGN_KEY = "a7964f42c39200cfa25c258b7a311b106e20232173667e543c34ced91d63b404"; const REQUEST_TIMEOUT_MS = 30_000; +const PAGE_SIZE = 40; export type EvenHubStoreApp = { id: number; @@ -80,17 +81,31 @@ export class EvenHubApiClient { private loginPromise: Promise | null = null; async listApps(page = 1, category = ""): Promise { - const query: Record = { page, page_size: 40 }; + const query: Record = { page, page_size: PAGE_SIZE }; if (category) query.category = category; const data = await this.authenticatedRequest("GET", "/v2/evenhub/leaderboard", { query }); - const root = asRecord(data); - const list = Array.isArray(root.list) ? root.list : []; - return { - apps: list.map(parseStoreApp).filter((app): app is EvenHubStoreApp => app !== null), - total: finiteNumber(root.total), - page: finiteNumber(root.page) || page, - pageSize: finiteNumber(root.page_size) || 40, - }; + return parseStorePage(data, page); + } + + /** + * Public apps ordered by first publication, newest first. The official app + * requests `/ranking?sort_by=first_published_at`; whether the endpoint pages + * is unverified, so callers must tolerate a repeated (or complete) list and + * a missing total. + */ + async listNewApps(page = 1): Promise { + const data = await this.authenticatedRequest("GET", "/v2/evenhub/ranking", { + query: { sort_by: "first_published_at", page, page_size: PAGE_SIZE }, + }); + return parseStorePage(data, page); + } + + /** Full-text storefront search (`/search?q=`), with the same paging caveats as listNewApps. */ + async searchApps(queryText: string, page = 1): Promise { + const data = await this.authenticatedRequest("GET", "/v2/evenhub/search", { + query: { q: queryText, page, page_size: PAGE_SIZE }, + }); + return parseStorePage(data, page); } async getAppDetail(packageId: string): Promise> { @@ -364,6 +379,25 @@ export function getPhoneOpenUdid(): string { return openUdid; } +/** + * Parse a list response. The leaderboard returns `{list, total, page, + * page_size}`; the ranking/search endpoints were only recovered from the + * client's request paths, so accept a bare array or the other common + * wrapper keys too. A missing total comes back as 0 ("unknown"). + */ +function parseStorePage(data: unknown, requestedPage: number): EvenHubStorePage { + const root = asRecord(data); + const list = Array.isArray(data) + ? data + : [root.list, root.apps, root.items, root.data, root.results].find(Array.isArray) ?? []; + return { + apps: list.map(parseStoreApp).filter((app): app is EvenHubStoreApp => app !== null), + total: finiteNumber(root.total), + page: finiteNumber(root.page) || requestedPage, + pageSize: finiteNumber(root.page_size) || PAGE_SIZE, + }; +} + function parseStoreApp(value: unknown): EvenHubStoreApp | null { const item = asRecord(value); const version = asRecord(item.version); diff --git a/app/apps/evenhub/index.ts b/app/apps/evenhub/index.ts index d938c123..f7968676 100644 --- a/app/apps/evenhub/index.ts +++ b/app/apps/evenhub/index.ts @@ -14,6 +14,7 @@ import { launchPackage, launchUrl, normalizeAppUrl } from "./manager"; import { createInProcessWindow, type InProcessWindow } from "../../ui/shell/in-process-window"; import { renderEvenRealitiesLogo } from "../../graphics/even-realities-logo"; import { makeImageWindowIcon, windowIcon } from "../../ui/shell/chrome-layer"; +import { type InstalledEvenHubApp } from "./installed-apps"; const EVENHUB_STORE_WINDOW_ID = "evenhub:store"; const EVENHUB_STORE_SURFACE_ID = "window:evenhub:store"; @@ -40,45 +41,71 @@ export function isLoadableAppUrl(url: string): boolean { return normalizeAppUrl(url) !== null; } +/** The open store window, so a second launch focuses it and deep links can reach its layer. */ +let storeWindow: { window: InProcessWindow; store: EvenHubStoreLayer } | null = null; + +/** Open the store window, or focus the one already open. */ +async function ensureStoreWindow(ctx: AppContext): Promise<{ window: InProcessWindow; store: EvenHubStoreLayer }> { + if (storeWindow && shell.getWindows().some((window) => window.windowId === EVENHUB_STORE_WINDOW_ID)) { + shell.focusWindow(EVENHUB_STORE_WINDOW_ID); + ctx.requestShellRender(); + return storeWindow; + } + let created: InProcessWindow | null = null; + const store = new EvenHubStoreLayer({ + launchApp: (appId) => ctx.launchApp(appId), + appendLog: ctx.appendLog, + }); + await ctx.launchInProcessApp(EVENHUB_STORE_WINDOW_ID, EVENHUB_STORE_SURFACE_ID, (options) => { + created = createInProcessWindow({ + appId: "evenhub", + windowId: EVENHUB_STORE_WINDOW_ID, + title: "EvenHub", + iconLetter: "EH", + icon: "package", + drawIcon: makeImageWindowIcon(renderEvenRealitiesLogo, windowIcon("package", "EH")), + closeable: true, + menuItems: () => (created?.stack.isAtBase() ? store.buildMenuItems() : []), + actions: options.actions, + // Dictated text runs a store search (when the store page itself is on top). + receiveTextInput: (text) => { + if (created?.stack.receiveTextInput(text)) created.requestRender(); + }, + baseLayer: store, + submitFrame: options.submitFrame, + setSurfaceVisible: options.setSurfaceVisible, + removeSurface: options.removeSurface, + onClosed: () => { + store.onWindowClosed(options.actions); + if (storeWindow?.store === store) storeWindow = null; + options.onClosed(); + }, + }); + return created; + }); + if (!created) throw new Error("EvenHub store window was not created."); + storeWindow = { window: created, store }; + return storeWindow; +} + +/** + * Open the store on an installed app's page. The launcher uses it when the + * registry lists a package whose EHPK is gone (a settings import after a + * reinstall), so the tap lands on a Reinstall button instead of failing. + */ +export async function openEvenHubStoreForPackage(ctx: AppContext, installed: InstalledEvenHubApp): Promise { + const { window, store } = await ensureStoreWindow(ctx); + store.showInstalledPackage(window.stack, installed); + window.requestRender(); +} + const evenhubApp: AppDefinition = { appId: "evenhub", title: "EvenHub", icon: "package", renderIcon: renderEvenRealitiesLogo, launch: async (ctx) => { - const existing = shell.getWindows().find((window) => window.windowId === EVENHUB_STORE_WINDOW_ID); - if (existing) { - shell.focusWindow(existing.windowId); - ctx.requestShellRender(); - return; - } - let created: InProcessWindow | null = null; - const store = new EvenHubStoreLayer({ - launchApp: (appId) => ctx.launchApp(appId), - appendLog: ctx.appendLog, - }); - await ctx.launchInProcessApp(EVENHUB_STORE_WINDOW_ID, EVENHUB_STORE_SURFACE_ID, (options) => { - created = createInProcessWindow({ - appId: "evenhub", - windowId: EVENHUB_STORE_WINDOW_ID, - title: "EvenHub", - iconLetter: "EH", - icon: "package", - drawIcon: makeImageWindowIcon(renderEvenRealitiesLogo, windowIcon("package", "EH")), - closeable: true, - menuItems: () => (created?.stack.isAtBase() ? store.buildMenuItems() : []), - actions: options.actions, - baseLayer: store, - submitFrame: options.submitFrame, - setSurfaceVisible: options.setSurfaceVisible, - removeSurface: options.removeSurface, - onClosed: () => { - store.onWindowClosed(options.actions); - options.onClosed(); - }, - }); - return created; - }); + await ensureStoreWindow(ctx); }, }; diff --git a/app/apps/evenhub/store-detail-layer.ts b/app/apps/evenhub/store-detail-layer.ts index 9eeffad6..ab179023 100644 --- a/app/apps/evenhub/store-detail-layer.ts +++ b/app/apps/evenhub/store-detail-layer.ts @@ -8,13 +8,12 @@ import { TextViewerLayer } from "../files/text-viewer"; import { evenHubApi, type EvenHubStoreApp } from "./even-api"; import { getInstalledEvenHubApp, - installEvenHubPackageBytes, installedEvenHubAppId, - readEvenHubPackageManifestBytes, setInstalledEvenHubIcon, - type EvenHubInstallIcon, + type InstalledEvenHubApp, } from "./installed-apps"; -import { EvenHubPermissionDialogLayer } from "./permission-dialog"; +import { cleanError, installStoreApp } from "./store-install"; +import { describeUpdate } from "./updates"; import { lineStep, listRowHeight } from "../../ui/metrics"; const X = 18; @@ -22,6 +21,8 @@ const X = 18; export type EvenHubStoreDetailOptions = { launchApp: (appId: string) => Promise | void; appendLog: (message: string) => void; + /** A package was installed, updated, or reinstalled from this page. */ + onInstalled?: (app: InstalledEvenHubApp) => void; }; /** Storefront metadata and the Install/Launch action for one public app. */ @@ -46,7 +47,7 @@ export class EvenHubStoreDetailLayer implements Layer { const actionRowH = listRowHeight(font) + 4; const installed = getInstalledEvenHubApp(this.app.packageId); - const actions = ["About", "What's New", this.working ? "Installing..." : installed ? "Launch" : "Install"]; + const actions = ["About", "What's New", this.working ? "Installing..." : this.primaryActionLabel(installed)]; // Detail lines as (text, shade, extra gap below); built per candidate // width so the layout choice below can measure before drawing. @@ -70,7 +71,13 @@ export class EvenHubStoreDetailLayer implements Layer { lines.push({ text: truncateText(font, line, textWidth), value: 125, gapAfter: 0 }); } if (installed && !this.status) { - lines.push({ text: `Installed version ${installed.version}`, value: 155, gapAfter: 0 }); + const standing = describeUpdate(installed, this.app); + const note = standing.packageMissing + ? " · package missing, reinstall" + : standing.updateAvailable + ? " · update available" + : ""; + lines.push({ text: truncateText(font, `Installed version ${installed.version}${note}`, textWidth), value: 155, gapAfter: 0 }); } if (this.status) { lines.push({ text: truncateText(font, this.status, textWidth), value: 180, gapAfter: 0 }); @@ -138,77 +145,39 @@ export class EvenHubStoreDetailLayer implements Layer { } const installed = getInstalledEvenHubApp(this.app.packageId); - if (installed) { + if (installed && this.primaryActionLabel(installed) === "Launch") { await this.options.launchApp(installedEvenHubAppId(installed.packageId)); return; } - await this.prepareInstall(ctx); + await this.install(ctx); } - private async prepareInstall(ctx: LayerContext): Promise { + /** Install for a new app; Update / Reinstall when the installed copy is stale or gone. */ + private primaryActionLabel(installed: InstalledEvenHubApp | null): string { + if (!installed) return "Install"; + const standing = describeUpdate(installed, this.app); + if (standing.packageMissing) return "Reinstall"; + return standing.updateAvailable ? "Update" : "Launch"; + } + + private async install(ctx: LayerContext): Promise { this.working = true; - this.status = `Downloading ${this.app.name}...`; ctx.actions.requestRender(); try { - const [download, icon] = await Promise.all([ - evenHubApi.downloadApp(this.app.packageId), - this.app.iconPath - ? evenHubApi.downloadPublicAsset(this.app.iconPath).catch((error) => { - this.options.appendLog(`evenhub store: icon unavailable for ${this.app.packageId}: ${cleanError(error)}`); - return undefined; - }) - : Promise.resolve(undefined), - ]); - const manifest = readEvenHubPackageManifestBytes(download.bytes); - if (!manifest) throw new Error("The downloaded EHPK manifest could not be read."); - const privacyPolicyUrl = download.privacyPolicyUrl || manifest.privacyPolicyUrl; - this.working = false; - this.status = ""; - ctx.actions.requestRender(); - if (manifest.permissions.length > 0 || privacyPolicyUrl) { - ctx.stack.push( - new EvenHubPermissionDialogLayer( - manifest.name, - manifest.permissions, - privacyPolicyUrl, - () => { - void this.installAndLaunch(ctx, download.bytes, icon); - }, - () => { - this.status = "Installation canceled."; - ctx.actions.requestRender(); - }, - ), - ); + const result = await installStoreApp(ctx, this.app, { + appendLog: this.options.appendLog, + onStatus: (status) => { + this.status = status; + ctx.actions.requestRender(); + }, + }); + if (!result) { + this.status = "Installation canceled."; return; } - await this.installAndLaunch(ctx, download.bytes, icon); - } catch (error) { - this.working = false; - this.status = cleanError(error); - this.options.appendLog(`evenhub store: ${this.status}`); - ctx.actions.requestRender(); - } - } - - private async installAndLaunch( - ctx: LayerContext, - bytes: Uint8Array, - icon: EvenHubInstallIcon | undefined, - ): Promise { - this.working = true; - this.status = "Installing..."; - ctx.actions.requestRender(); - try { - const result = installEvenHubPackageBytes(bytes, { - expectedPackageId: this.app.packageId, - icon, - }); - this.options.appendLog( - `evenhub store: installed ${result.packageId} ${result.version} (${bytes.length} bytes)`, - ); this.status = "Installed"; + this.options.onInstalled?.(result); ctx.actions.requestRender(); await this.options.launchApp(installedEvenHubAppId(result.packageId)); } catch (error) { @@ -258,7 +227,3 @@ function formatBytes(value: number): string { if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`; return `${(value / (1024 * 1024)).toFixed(1)} MB`; } - -function cleanError(error: unknown): string { - return String((error as Error)?.message ?? error).replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim(); -} diff --git a/app/apps/evenhub/store-install.ts b/app/apps/evenhub/store-install.ts new file mode 100644 index 00000000..5c63e1a9 --- /dev/null +++ b/app/apps/evenhub/store-install.ts @@ -0,0 +1,97 @@ +/** + * The storefront install pipeline shared by the app detail page and the + * Updates tab: download the package and its icon, confirm permissions when + * that is warranted, close running instances, and store the package. + */ +import { type LayerContext } from "../../ui/layers"; +import { evenHubApi, type EvenHubStoreApp } from "./even-api"; +import { type EvenHubManifest } from "./ehpk"; +import { + installEvenHubPackageBytes, + installedEvenHubPackagePath, + readEvenHubPackageManifest, + readEvenHubPackageManifestBytes, + type InstalledEvenHubApp, +} from "./installed-apps"; +import { closeRunningPackage } from "./manager"; +import { EvenHubPermissionDialogLayer } from "./permission-dialog"; + +export type StoreInstallOptions = { + appendLog: (message: string) => void; + /** Progress text for the caller's status line ("Downloading X...", "Installing..."). */ + onStatus: (status: string) => void; +}; + +/** + * Install (or update/reinstall) one storefront app. Resolves to the new + * registry entry, or null when the user declined the permission dialog. + * Failures throw with a user-presentable message. + * + * The permission dialog is shown for a first install, and for an update + * whose manifest declares permissions the currently installed package did + * not (or a privacy policy it did not); an update that asks for nothing new + * goes straight through. + */ +export async function installStoreApp( + ctx: LayerContext, + app: EvenHubStoreApp, + options: StoreInstallOptions, +): Promise { + options.onStatus(`Downloading ${app.name}...`); + const [download, icon] = await Promise.all([ + evenHubApi.downloadApp(app.packageId), + app.iconPath + ? evenHubApi.downloadPublicAsset(app.iconPath).catch((error) => { + options.appendLog(`evenhub store: icon unavailable for ${app.packageId}: ${cleanError(error)}`); + return undefined; + }) + : Promise.resolve(undefined), + ]); + const manifest = readEvenHubPackageManifestBytes(download.bytes); + if (!manifest) throw new Error("The downloaded EHPK manifest could not be read."); + const privacyPolicyUrl = download.privacyPolicyUrl || manifest.privacyPolicyUrl; + const needsPrompt = (manifest.permissions.length > 0 || privacyPolicyUrl) + && !alreadyGranted(app.packageId, manifest); + if (needsPrompt) { + options.onStatus(""); + ctx.actions.requestRender(); + const accepted = await new Promise((resolve) => { + ctx.stack.push( + new EvenHubPermissionDialogLayer( + manifest.name, + manifest.permissions, + privacyPolicyUrl, + () => resolve(true), + () => resolve(false), + ), + ); + }); + if (!accepted) return null; + } + + options.onStatus("Installing..."); + ctx.actions.requestRender(); + // A running instance would keep serving the old unpacked runtime; every + // launch re-unpacks from the stored EHPK, so closing it is enough. + closeRunningPackage(app.packageId); + const result = installEvenHubPackageBytes(download.bytes, { expectedPackageId: app.packageId, icon }); + options.appendLog(`evenhub store: installed ${result.packageId} ${result.version} (${download.bytes.length} bytes)`); + return result; +} + +/** + * Whether the installed package already declares every permission the new + * manifest asks for. (The store's privacy-policy link is not compared: the + * download metadata carries it as a CDN path while the installed app.json + * usually has none, so comparing would re-prompt on every update.) + */ +function alreadyGranted(packageId: string, manifest: EvenHubManifest): boolean { + const current = readEvenHubPackageManifest(installedEvenHubPackagePath(packageId)); + if (!current) return false; + const granted = new Set(current.permissions); + return manifest.permissions.every((permission) => granted.has(permission)); +} + +export function cleanError(error: unknown): string { + return String((error as Error)?.message ?? error).replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim(); +} diff --git a/app/apps/evenhub/store-layer.ts b/app/apps/evenhub/store-layer.ts index 55a7f49c..82df0fee 100644 --- a/app/apps/evenhub/store-layer.ts +++ b/app/apps/evenhub/store-layer.ts @@ -3,39 +3,119 @@ import { GrayImage, type UiFont } from "../../graphics/image"; import { truncateText, wrapText } from "../../graphics/textwrap"; import { clamp } from "../../util/numeric-util"; import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures"; -import { type Layer, type LayerActions, type LayerContext } from "../../ui/layers"; +import { type Layer, type LayerActions, type LayerContext, type LayerStack } from "../../ui/layers"; import { drawListScrollbar, drawSelectionHighlight, scrollToKeepSelectionVisible, type MenuItem } from "../../ui/menu"; import { shell } from "../../ui/shell/shell"; -import { evenHubApi, EvenHubAuthenticationError, isEvenHubStoreConfigured, type EvenHubStoreApp } from "./even-api"; +import { ConfigSettingString } from "../../ui/dashboard-settings"; +import { evenHubApi, EvenHubAuthenticationError, isEvenHubStoreConfigured, type EvenHubStoreApp, type EvenHubStorePage } from "./even-api"; import { clearEvenHubLoginForm, clearEvenHubSession, clearTransientEvenHubSession, evenHubLoginEmailSetting, evenHubLoginPasswordSetting, evenHubRememberMeSetting, resetEvenHubLoginForm } from "./credentials"; +import { getInstalledEvenHubApps, uninstallEvenHubPackage, type InstalledEvenHubApp } from "./installed-apps"; import { EvenHubStoreDetailLayer } from "./store-detail-layer"; +import { cleanError, installStoreApp } from "./store-install"; +import { checkForEvenHubUpdates, describeUpdate, type EvenHubAppUpdate } from "./updates"; import { lineStep } from "../../ui/metrics"; const LIST_X = 18; +/** Horizontal gap between tab labels. */ +const TAB_GAP = 18; -/** Header: title line, then the status/subtitle line, then a small gap. */ +/** Header: title + tabs line, then the status/subtitle line, then a small gap. */ function headerHeight(font: UiFont): number { return 8 + lineStep(font) + font.lineHeight + 6; } +/** Last search typed on the phone; kept so reopening the store shows it again. */ +export const evenHubSearchQuerySetting = new ConfigSettingString({ + id: "evenhub-search-query", + label: "Search", + storageKey: "evenhub.store.searchQuery", + defaultValue: "", + editorTitle: "Search EvenHub", + glassesEditTitle: "Search EvenHub", + normalize: (value) => (value ?? "").replace(/\s+/g, " ").trim(), +}); + +type StoreTab = "top" | "new" | "search" | "updates"; + +const TABS: { id: StoreTab; label: string }[] = [ + { id: "top", label: "Top" }, + { id: "new", label: "New" }, + { id: "search", label: "Search" }, + { id: "updates", label: "Updates" }, +]; + +type StoreRow = + /** A storefront app; `update` is set on the Updates tab. */ + | { kind: "app"; app: EvenHubStoreApp; update?: EvenHubAppUpdate } + /** The Search tab's first row: shows the query and opens the phone editor. */ + | { kind: "search-query" } + /** A registry entry whose package is gone and which the store no longer lists. */ + | { kind: "orphan"; update: EvenHubAppUpdate }; + +type TabState = { + rows: StoreRow[]; + /** Server-reported total, or 0 when unknown. */ + total: number; + nextPage: number; + /** No further pages: the total was reached, or a page added nothing new. */ + exhausted: boolean; + /** A load has completed (or failed) at least once. */ + loaded: boolean; + loading: boolean; + /** Progress or error text for the subtitle line. */ + status: string; + selectedIndex: number; + scrollRow: number; + /** Search only: the query the rows belong to. */ + query: string; +}; + +function emptyTab(): TabState { + return { + rows: [], + total: 0, + nextPage: 1, + exhausted: false, + loaded: false, + loading: false, + status: "", + selectedIndex: 0, + scrollRow: 0, + query: "", + }; +} + export type EvenHubStoreLayerOptions = { launchApp: (appId: string) => Promise | void; appendLog: (message: string) => void; }; -/** Browse the public EvenHub leaderboard and download one package to run. */ +/** + * The EvenHub storefront: Top (leaderboard), New (by first publication), + * Search, and Updates (installed apps that are stale or whose package is + * missing). The tab row is its own focus level above the list: double-click + * in the list focuses the tabs, scrolling there switches tabs, and a click + * returns to the list. + */ export class EvenHubStoreLayer implements Layer { - private apps: EvenHubStoreApp[] = []; - private selectedIndex = 0; - private scrollRow = 0; - private total = 0; - private nextPage = 1; + private readonly tabs: Record = { + top: emptyTab(), + new: emptyTab(), + search: emptyTab(), + updates: emptyTab(), + }; + private activeTab: StoreTab = "top"; + private focus: "list" | "tabs" = "list"; private started = false; - private loading = false; private showingLogin = !isEvenHubStoreConfigured(); - private status = this.showingLogin ? "Sign in to browse public apps." : ""; - private credentialEditorOpen = false; + private loginStatus = this.showingLogin ? "Sign in to browse public apps." : ""; + private loginBusy = false; + private phoneEditor: "none" | "credentials" | "search" = "none"; private closed = false; + /** Serializes the Update All action; also blocks per-row installs meanwhile. */ + private updatingAll = false; + /** An app page requested while the login form was up; opened once signed in. */ + private pendingPackage: InstalledEvenHubApp | null = null; constructor(private readonly options: EvenHubStoreLayerOptions) { if (this.showingLogin) resetEvenHubLoginForm(); @@ -47,7 +127,7 @@ export class EvenHubStoreLayer implements Layer { if (this.showingLogin) { this.openCredentialEditor(ctx); } else { - void this.reload(ctx); + void this.ensureTabLoaded(ctx, this.activeTab); } } @@ -57,11 +137,9 @@ export class EvenHubStoreLayer implements Layer { const headerH = headerHeight(font); image.drawText(font, LIST_X, 8, "EvenHub", 220); - const subtitle = this.status || (this.total ? `${this.apps.length} of ${this.total} public apps` : "Public apps"); - image.drawText(font, LIST_X, 8 + lineStep(font), truncateText(font, subtitle, width - LIST_X * 2), 125); - if (this.showingLogin) { - const message = this.loading + image.drawText(font, LIST_X, 8 + lineStep(font), truncateText(font, this.loginStatus, width - LIST_X * 2), 125); + const message = this.loginBusy ? "Signing in..." : "Enter your Even account email and password in the phone app."; for (const [index, line] of wrapText(font, message, width - LIST_X * 2).entries()) { @@ -71,69 +149,181 @@ export class EvenHubStoreLayer implements Layer { return image; } - if (this.apps.length === 0) { - const message = this.loading ? "Loading apps..." : this.status || "No apps returned."; - image.drawText(font, LIST_X, headerH + 22, truncateText(font, message, width - LIST_X * 2), 190); - } else { - this.selectedIndex = clamp(this.selectedIndex, 0, this.apps.length - 1); - const rowH = Math.max(30, 2 * lineStep(font) + 4); - const visibleRows = Math.max(1, Math.floor((height - headerH - 4) / rowH)); - this.scrollRow = scrollToKeepSelectionVisible( - this.scrollRow, - this.selectedIndex, - visibleRows, - this.apps.length, - ); - const last = Math.min(this.apps.length, this.scrollRow + visibleRows); - for (let index = this.scrollRow; index < last; index++) { - const app = this.apps[index]!; - const y = headerH + (index - this.scrollRow) * rowH; - const selected = index === this.selectedIndex; - if (selected) { - drawSelectionHighlight(image, LIST_X - 6, y, width - LIST_X * 2 + 12, rowH - 2, ctx.stack.isFocused(), 5); - } - image.drawText(font, LIST_X, y + 2, truncateText(font, app.name, width - LIST_X * 2), 215); - const detail = app.tagline || `${app.creatorName} · ${formatCount(app.installCount)} installs`; - image.drawText(font, LIST_X, y + 2 + lineStep(font), truncateText(font, detail, width - LIST_X * 2), 115); - } - if (this.apps.length > visibleRows) { - drawListScrollbar(image, width - 5, headerH, visibleRows * rowH - 3, this.scrollRow, visibleRows, this.apps.length); + this.paintTabs(image, font, ctx); + + const tab = this.tabs[this.activeTab]; + const subtitle = tab.status || this.subtitle(this.activeTab, tab); + image.drawText(font, LIST_X, 8 + lineStep(font), truncateText(font, subtitle, width - LIST_X * 2), 125); + + if (tab.rows.length === 0) { + const message = tab.loading ? "Loading..." : this.emptyMessage(this.activeTab, tab); + for (const [index, line] of wrapText(font, message, width - LIST_X * 2).slice(0, 3).entries()) { + image.drawText(font, LIST_X, headerH + 22 + index * lineStep(font), line, 190); } + return image; } + tab.selectedIndex = clamp(tab.selectedIndex, 0, tab.rows.length - 1); + const rowH = Math.max(30, 2 * lineStep(font) + 4); + const visibleRows = Math.max(1, Math.floor((height - headerH - 4) / rowH)); + tab.scrollRow = scrollToKeepSelectionVisible(tab.scrollRow, tab.selectedIndex, visibleRows, tab.rows.length); + const last = Math.min(tab.rows.length, tab.scrollRow + visibleRows); + const listFocused = ctx.stack.isFocused() && this.focus === "list"; + for (let index = tab.scrollRow; index < last; index++) { + const row = tab.rows[index]!; + const y = headerH + (index - tab.scrollRow) * rowH; + if (index === tab.selectedIndex) { + drawSelectionHighlight(image, LIST_X - 6, y, width - LIST_X * 2 + 12, rowH - 2, listFocused, 5); + } + const { title, detail, titleValue } = this.rowText(row); + image.drawText(font, LIST_X, y + 2, truncateText(font, title, width - LIST_X * 2), titleValue); + image.drawText(font, LIST_X, y + 2 + lineStep(font), truncateText(font, detail, width - LIST_X * 2), 115); + } + if (tab.rows.length > visibleRows) { + drawListScrollbar(image, width - 5, headerH, visibleRows * rowH - 3, tab.scrollRow, visibleRows, tab.rows.length); + } return image; } + /** Tab labels to the right of the title; the active one is bright and underlined. */ + private paintTabs(image: GrayImage, font: UiFont, ctx: LayerContext): void { + const tabsFocused = ctx.stack.isFocused() && this.focus === "tabs"; + let x = LIST_X + font.measureText("EvenHub") + 28; + for (const tab of TABS) { + const label = this.tabLabel(tab.id); + const w = font.measureText(label); + const active = tab.id === this.activeTab; + if (active) { + if (tabsFocused) { + drawSelectionHighlight(image, x - 6, 5, w + 12, font.lineHeight + 6, true, 4); + } else { + image.fillRect(x, 8 + font.lineHeight + 1, w, 1, 150); + } + } + image.drawText(font, x, 8, label, active ? 235 : 120); + x += w + TAB_GAP; + } + } + + private tabLabel(tab: StoreTab): string { + const label = TABS.find((entry) => entry.id === tab)!.label; + if (tab !== "updates") return label; + const updates = this.tabs.updates; + const count = updates.rows.filter((row) => row.kind !== "search-query").length; + return updates.loaded && count > 0 ? `${label} (${count})` : label; + } + + private subtitle(tab: StoreTab, state: TabState): string { + const count = state.rows.length; + switch (tab) { + case "top": + return state.total ? `${count} of ${state.total} public apps` : count ? `${count} public apps` : "Public apps by popularity"; + case "new": + return count ? `${count} newest apps` : "Recently published apps"; + case "search": { + const results = count - 1; + if (!state.query) return "Search public apps"; + return results === 1 ? `1 result for "${state.query}"` : `${results} results for "${state.query}"`; + } + case "updates": + if (!state.loaded) return "Installed apps with newer versions"; + return count === 0 ? "All installed apps are up to date" : count === 1 ? "1 app needs attention" : `${count} apps need attention`; + } + } + + private emptyMessage(tab: StoreTab, state: TabState): string { + if (state.status) return state.status; + switch (tab) { + case "updates": + return getInstalledEvenHubApps().length === 0 + ? "No apps are installed from EvenHub." + : "Every installed app is at its latest version."; + default: + return "No apps returned."; + } + } + + private rowText(row: StoreRow): { title: string; detail: string; titleValue: number } { + switch (row.kind) { + case "search-query": { + const query = evenHubSearchQuerySetting.get(); + return { + title: query ? `Search: ${query}` : "Search: (enter a query)", + detail: "Click to type on the phone, or use voice input.", + titleValue: 200, + }; + } + case "orphan": + return { + title: row.update.installed.name, + detail: row.update.error + ? `Package missing · store lookup failed: ${row.update.error}` + : "Package missing · not in the store · click to forget", + titleValue: 170, + }; + case "app": { + const { app, update } = row; + if (!update) { + return { + title: app.name, + detail: app.tagline || `${app.creatorName} · ${formatCount(app.installCount)} installs`, + titleValue: 215, + }; + } + const detail = update.packageMissing + ? `Package missing · reinstall ${app.version ? `version ${app.version}` : ""}`.trim() + : `Version ${update.installed.version} installed · ${app.version} available`; + return { title: app.name, detail, titleValue: 215 }; + } + } + } + async handleInput(event: InputEvent, ctx: LayerContext): Promise { if (this.showingLogin) { - if (event.type === "click" && !this.loading) { + if (event.type === "click" && !this.loginBusy) { this.openCredentialEditor(ctx); } else if (event.type === "double-click") { shell.yieldFocusToSidebar(); } return; } + if (this.focus === "tabs") { + await this.handleTabInput(event, ctx); + return; + } + const tab = this.tabs[this.activeTab]; switch (event.type) { case "scroll-up": - this.selectedIndex = Math.max(0, this.selectedIndex - 1); + tab.selectedIndex = Math.max(0, tab.selectedIndex - 1); return; case "scroll-down": - this.selectedIndex = Math.min(Math.max(0, this.apps.length - 1), this.selectedIndex + 1); - if (this.selectedIndex >= this.apps.length - 4 && this.apps.length < this.total) { - void this.loadNextPage(ctx); - } + tab.selectedIndex = Math.min(Math.max(0, tab.rows.length - 1), tab.selectedIndex + 1); + if (tab.selectedIndex >= tab.rows.length - 4) void this.loadNextPage(ctx, this.activeTab); return; case "click": - if (!this.loading) { - const app = this.apps[this.selectedIndex]; - if (app) { - ctx.stack.push( - new EvenHubStoreDetailLayer(app, { - launchApp: this.options.launchApp, - appendLog: this.options.appendLog, - }), - ); - } + await this.activateRow(ctx, tab.rows[tab.selectedIndex]); + return; + case "double-click": + this.focus = "tabs"; + return; + default: + return; + } + } + + private async handleTabInput(event: InputEvent, ctx: LayerContext): Promise { + const index = TABS.findIndex((tab) => tab.id === this.activeTab); + switch (event.type) { + case "scroll-up": + this.switchTab(ctx, TABS[Math.max(0, index - 1)]!.id); + return; + case "scroll-down": + this.switchTab(ctx, TABS[Math.min(TABS.length - 1, index + 1)]!.id); + return; + case "click": + this.focus = "list"; + if (this.activeTab === "search" && !evenHubSearchQuerySetting.get()) { + this.openSearchEditor(ctx); } return; case "double-click": @@ -144,107 +334,366 @@ export class EvenHubStoreLayer implements Layer { } } - buildMenuItems(): MenuItem[] { - if (this.showingLogin) return []; - return [ - { - label: "Refresh", - onSelect: (ctx) => { - ctx.stack.pop(); - void this.reload(ctx); - }, - }, - { - label: "Log Out", - onSelect: (ctx) => { - ctx.stack.pop(); - clearEvenHubSession(); - this.enterLogin(ctx, "Signed out."); - }, - }, - ]; + private switchTab(ctx: LayerContext, tab: StoreTab): void { + if (tab === this.activeTab) return; + if (this.activeTab === "search") this.closePhoneEditor(ctx.actions, "search"); + this.activeTab = tab; + void this.ensureTabLoaded(ctx, tab); } - closeCredentialEditor(actions: Pick): void { - if (!this.credentialEditorOpen) return; - this.credentialEditorOpen = false; - void actions.endTextSettingEdit(); + private async activateRow(ctx: LayerContext, row: StoreRow | undefined): Promise { + if (!row) return; + switch (row.kind) { + case "search-query": + this.openSearchEditor(ctx); + return; + case "orphan": { + // Nothing can be reinstalled; the only useful action is to drop the + // dead registry entry so the launcher stops offering it. + const { packageId, name } = row.update.installed; + if (uninstallEvenHubPackage(packageId)) { + this.options.appendLog(`evenhub store: forgot missing package ${packageId}`); + this.removeUpdateRow(packageId); + this.tabs.updates.status = `Forgot ${name}.`; + } + return; + } + case "app": + if (this.updatingAll) return; + ctx.stack.push( + new EvenHubStoreDetailLayer(row.app, { + launchApp: this.options.launchApp, + appendLog: this.options.appendLog, + onInstalled: (installed) => this.onInstalled(installed), + }), + ); + return; + } + } + + /** + * Jump to an installed app's store page (the launcher's route for a package + * whose file is missing). Any page already open above the list is replaced. + * Store metadata is filled in by the detail page itself; until then a + * placeholder built from the registry entry stands in. + */ + showInstalledPackage(stack: LayerStack, installed: InstalledEvenHubApp): void { + if (this.showingLogin) { + this.pendingPackage = installed; + return; + } + this.pendingPackage = null; + stack.clearToBase(); + stack.push( + new EvenHubStoreDetailLayer(placeholderStoreApp(installed), { + launchApp: this.options.launchApp, + appendLog: this.options.appendLog, + onInstalled: (result) => this.onInstalled(result), + }), + ); + } + + /** Dictated text becomes a search (the shell's "Type Into App" / voice input). */ + receiveTextInput(text: string, ctx: LayerContext): void { + if (this.showingLogin) return; + const query = evenHubSearchQuerySetting.set(text); + if (!query) return; + this.closePhoneEditor(ctx.actions, "search"); + this.activeTab = "search"; + this.focus = "list"; + void this.runSearch(ctx, query); + } + + buildMenuItems(): MenuItem[] { + if (this.showingLogin) return []; + const items: MenuItem[] = []; + if (this.activeTab === "search") { + items.push({ + label: "Search...", + onSelect: (ctx) => { + ctx.stack.pop(); + this.focus = "list"; + this.openSearchEditor(ctx); + }, + }); + } + if (this.activeTab === "updates" && this.updatableRows().length > 0) { + items.push({ + label: this.updatingAll ? "Updating..." : "Update All", + disabled: () => this.updatingAll, + onSelect: (ctx) => { + ctx.stack.pop(); + void this.updateAll(ctx); + }, + }); + } + items.push({ + label: this.activeTab === "updates" ? "Check Again" : "Refresh", + onSelect: (ctx) => { + ctx.stack.pop(); + void this.reload(ctx, this.activeTab); + }, + }); + items.push({ + label: "Log Out", + onSelect: (ctx) => { + ctx.stack.pop(); + clearEvenHubSession(); + this.enterLogin(ctx, "Signed out."); + }, + }); + return items; } onWindowClosed(actions: Pick): void { this.closed = true; - this.closeCredentialEditor(actions); + this.closePhoneEditor(actions); clearTransientEvenHubSession(); } - private async reload(ctx: LayerContext): Promise { - if (this.loading) return; - this.apps = []; - this.total = 0; - this.nextPage = 1; - this.selectedIndex = 0; - this.scrollRow = 0; - this.status = ""; + // ---- loading ----------------------------------------------------------- + + private ensureTabLoaded(ctx: LayerContext, tab: StoreTab): Promise { + const state = this.tabs[tab]; + if (state.loaded || state.loading) return Promise.resolve(); + return this.reload(ctx, tab); + } + + private async reload(ctx: LayerContext, tab: StoreTab): Promise { if (!isEvenHubStoreConfigured()) { this.enterLogin(ctx); return; } - await this.loadNextPage(ctx); + if (this.tabs[tab].loading) return; + switch (tab) { + case "top": + case "new": + this.tabs[tab] = emptyTab(); + await this.loadNextPage(ctx, tab); + return; + case "search": + await this.runSearch(ctx, evenHubSearchQuerySetting.get()); + return; + case "updates": + await this.checkUpdates(ctx); + return; + } } - private async loadNextPage(ctx: LayerContext): Promise { - if (this.loading || (this.total > 0 && this.apps.length >= this.total)) return; - this.loading = true; - this.status = this.apps.length ? "Loading more apps..." : "Loading apps..."; + private async loadNextPage(ctx: LayerContext, tab: StoreTab): Promise { + const state = this.tabs[tab]; + if (state.loading || state.exhausted) return; + if (tab === "search" && !state.query) return; + if (tab === "updates") return; + state.loading = true; + state.status = state.rows.length ? "Loading more apps..." : "Loading apps..."; ctx.actions.requestRender(); try { - const page = await evenHubApi.listApps(this.nextPage); - const seen = new Set(this.apps.map((app) => app.packageId)); - this.apps.push(...page.apps.filter((app) => !seen.has(app.packageId))); - this.total = page.total; - this.nextPage = page.page + 1; - this.status = ""; - } catch (error) { - const message = cleanError(error); - if (error instanceof EvenHubAuthenticationError) { - this.options.appendLog(`evenhub store login failed: ${message}`); - this.enterLogin(ctx, `Login failed: ${message}`); - return; + const page = await this.fetchPage(tab, state.nextPage, state.query); + const seen = new Set(state.rows.map((row) => (row.kind === "app" ? row.app.packageId : ""))); + const fresh = page.apps.filter((app) => !seen.has(app.packageId)); + state.rows.push(...fresh.map((app): StoreRow => ({ kind: "app", app }))); + state.total = page.total; + state.nextPage = page.page + 1; + // A page that adds nothing (or a short page with no known total) means + // the endpoint has no more to give — or ignores paging altogether. + state.exhausted = (state.total > 0 && state.rows.length >= state.total) + || fresh.length === 0 + || (state.total === 0 && page.apps.length < page.pageSize); + state.status = ""; + if (tab === "top" && state.nextPage === 2 && !this.tabs.updates.loaded && !this.tabs.updates.loading) { + // Quietly find out whether the Updates tab deserves a count. + void this.checkUpdates(ctx, true); } - this.status = message; - this.options.appendLog(`evenhub store: ${this.status}`); + } catch (error) { + if (this.handleAuthError(ctx, error)) return; + state.status = cleanError(error); + this.options.appendLog(`evenhub store: ${state.status}`); } finally { - this.loading = false; + state.loaded = true; + state.loading = false; + if (!this.closed) ctx.actions.requestRender(); + } + } + + private fetchPage(tab: StoreTab, page: number, query: string): Promise { + switch (tab) { + case "new": + return evenHubApi.listNewApps(page); + case "search": + return evenHubApi.searchApps(query, page); + default: + return evenHubApi.listApps(page); + } + } + + private async runSearch(ctx: LayerContext, query: string): Promise { + const state = emptyTab(); + state.query = query; + state.rows = [{ kind: "search-query" }]; + state.loaded = !query; + // Keep the cursor on the first result once there are some. + state.selectedIndex = query ? 1 : 0; + this.tabs.search = state; + ctx.actions.requestRender(); + if (query) await this.loadNextPage(ctx, "search"); + } + + private async checkUpdates(ctx: LayerContext, quiet = false): Promise { + const state = this.tabs.updates; + if (state.loading) return; + state.loading = true; + state.status = ""; + const installedCount = getInstalledEvenHubApps().length; + if (!quiet) { + state.status = installedCount ? `Checking ${installedCount} installed apps...` : ""; ctx.actions.requestRender(); } + try { + const updates = await checkForEvenHubUpdates((done, total) => { + if (quiet) return; + state.status = `Checking installed apps (${done}/${total})...`; + ctx.actions.requestRender(); + }); + const rows: StoreRow[] = updates.map((update) => + update.latest ? { kind: "app", app: update.latest, update } : { kind: "orphan", update }, + ); + state.rows = rows; + state.selectedIndex = 0; + state.scrollRow = 0; + state.status = ""; + state.exhausted = true; + } catch (error) { + if (this.handleAuthError(ctx, error)) return; + state.status = cleanError(error); + this.options.appendLog(`evenhub store: update check failed: ${state.status}`); + } finally { + state.loaded = true; + state.loading = false; + if (!this.closed) ctx.actions.requestRender(); + } + } + + private updatableRows(): Extract[] { + return this.tabs.updates.rows.filter( + (row): row is Extract => row.kind === "app" && row.update !== undefined, + ); + } + + /** Install every pending update in turn; a declined permission dialog skips that app. */ + private async updateAll(ctx: LayerContext): Promise { + if (this.updatingAll) return; + this.updatingAll = true; + const state = this.tabs.updates; + const pending = this.updatableRows(); + let installed = 0; + const failures: string[] = []; + try { + for (const [index, row] of pending.entries()) { + if (this.closed) return; + const prefix = `${index + 1}/${pending.length} ${row.app.name}: `; + try { + const result = await installStoreApp(ctx, row.app, { + appendLog: this.options.appendLog, + onStatus: (status) => { + state.status = prefix + (status || "Confirm permissions on the glasses..."); + ctx.actions.requestRender(); + }, + }); + if (result) { + installed++; + this.onInstalled(result); + } else { + failures.push(`${row.app.name} (declined)`); + } + } catch (error) { + const message = cleanError(error); + this.options.appendLog(`evenhub store: update of ${row.app.packageId} failed: ${message}`); + failures.push(row.app.name); + } + } + state.status = failures.length + ? `Updated ${installed}; skipped ${failures.join(", ")}` + : installed === 1 ? "Updated 1 app." : `Updated ${installed} apps.`; + } finally { + this.updatingAll = false; + if (!this.closed) ctx.actions.requestRender(); + } + } + + /** After any install, drop the Updates row it satisfied (from the detail page or Update All). */ + private onInstalled(installed: InstalledEvenHubApp): void { + const row = this.tabs.updates.rows.find( + (entry) => entry.kind === "app" && entry.app.packageId === installed.packageId, + ); + if (row?.kind !== "app" || !row.update) return; + const standing = describeUpdate(installed, row.app); + if (!standing.updateAvailable && !standing.packageMissing) this.removeUpdateRow(installed.packageId); + } + + private removeUpdateRow(packageId: string): void { + const state = this.tabs.updates; + state.rows = state.rows.filter((row) => + row.kind === "search-query" ? true : row.kind === "app" ? row.app.packageId !== packageId : row.update.installed.packageId !== packageId, + ); + state.selectedIndex = clamp(state.selectedIndex, 0, Math.max(0, state.rows.length - 1)); + } + + // ---- login and phone editors -------------------------------------------- + + /** Route a rejected session back to the login form; true if it was one. */ + private handleAuthError(ctx: LayerContext, error: unknown): boolean { + if (!(error instanceof EvenHubAuthenticationError)) return false; + const message = cleanError(error); + this.options.appendLog(`evenhub store login failed: ${message}`); + this.enterLogin(ctx, `Login failed: ${message}`); + return true; } private enterLogin(ctx: LayerContext, status = "Sign in to browse public apps."): void { const wasShowingLogin = this.showingLogin; + this.closePhoneEditor(ctx.actions, "search"); this.showingLogin = true; - this.loading = false; - this.apps = []; - this.total = 0; - this.status = status; + this.loginBusy = false; + this.loginStatus = status; + for (const tab of TABS) this.tabs[tab.id] = emptyTab(); + this.focus = "list"; if (!wasShowingLogin) resetEvenHubLoginForm(); this.openCredentialEditor(ctx); ctx.actions.requestRender(); } private openCredentialEditor(ctx: LayerContext): void { - if (this.credentialEditorOpen) return; - this.credentialEditorOpen = true; + if (this.phoneEditor !== "none") return; + this.phoneEditor = "credentials"; void ctx.actions.startTextSettingsEdit( [evenHubLoginEmailSetting, evenHubLoginPasswordSetting], "Sign in to EvenHub", () => { - this.credentialEditorOpen = false; + this.phoneEditor = "none"; void this.submitCredentials(ctx); }, { setting: evenHubRememberMeSetting, label: "Remember me" }, ); } + private openSearchEditor(ctx: LayerContext): void { + if (this.phoneEditor !== "none") return; + this.phoneEditor = "search"; + void ctx.actions.startTextSettingsEdit([evenHubSearchQuerySetting], "Search EvenHub", () => { + this.phoneEditor = "none"; + if (this.closed) return; + void this.runSearch(ctx, evenHubSearchQuerySetting.get()); + }); + } + + /** Close the phone editor if one is open (optionally only a given kind). */ + private closePhoneEditor(actions: Pick, kind?: "credentials" | "search"): void { + if (this.phoneEditor === "none" || (kind && this.phoneEditor !== kind)) return; + this.phoneEditor = "none"; + void actions.endTextSettingEdit(); + } + private async submitCredentials(ctx: LayerContext): Promise { const email = evenHubLoginEmailSetting.get(); const password = evenHubLoginPasswordSetting.get(); @@ -252,8 +701,8 @@ export class EvenHubStoreLayer implements Layer { this.enterLogin(ctx, "Email and password are required."); return; } - this.loading = true; - this.status = "Signing in..."; + this.loginBusy = true; + this.loginStatus = "Signing in..."; ctx.actions.requestRender(); try { await evenHubApi.signIn(email, password, evenHubRememberMeSetting.get()); @@ -263,26 +712,43 @@ export class EvenHubStoreLayer implements Layer { } this.showingLogin = false; clearEvenHubLoginForm(); - this.loading = false; - await this.reload(ctx); + this.loginBusy = false; + const pending = this.pendingPackage; + if (pending) this.showInstalledPackage(ctx.stack, pending); + await this.reload(ctx, this.activeTab); } catch (error) { if (this.closed) return; const message = cleanError(error); this.options.appendLog(`evenhub store login failed: ${message}`); - this.status = `Login failed: ${message}`; + this.loginStatus = `Login failed: ${message}`; evenHubLoginPasswordSetting.set(""); this.openCredentialEditor(ctx); } finally { evenHubLoginPasswordSetting.set(""); - this.loading = false; + this.loginBusy = false; if (!this.closed) ctx.actions.requestRender(); } } - } -function cleanError(error: unknown): string { - return String((error as Error)?.message ?? error).replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim(); +/** A registry entry dressed as a store record, for pages opened before the store record arrives. */ +function placeholderStoreApp(installed: InstalledEvenHubApp): EvenHubStoreApp { + return { + id: 0, + packageId: installed.packageId, + name: installed.name, + creatorName: "", + tagline: "", + description: "", + categories: [], + installCount: 0, + likeCount: 0, + firstPublishedAt: "", + iconPath: "", + version: "", + changelog: "", + fileSize: 0, + }; } function formatCount(value: number): string { diff --git a/app/apps/evenhub/updates.ts b/app/apps/evenhub/updates.ts new file mode 100644 index 00000000..05139c4c --- /dev/null +++ b/app/apps/evenhub/updates.ts @@ -0,0 +1,100 @@ +/** + * Update detection for installed EvenHub apps. + * + * Two situations need the user's attention: the store has a newer version + * than the one installed, and the registry lists a package whose EHPK is no + * longer on disk (a settings export imported after a reinstall carries the + * registry but not the files). + */ +import { statPath } from "../../native/file-access"; +import { evenHubApi, EvenHubAuthenticationError, type EvenHubStoreApp } from "./even-api"; +import { + getInstalledEvenHubApps, + installedEvenHubPackagePath, + type InstalledEvenHubApp, +} from "./installed-apps"; + +export type EvenHubAppUpdate = { + installed: InstalledEvenHubApp; + /** Storefront record, or null when the store no longer lists the package. */ + latest: EvenHubStoreApp | null; + /** The registry entry has no package file behind it. */ + packageMissing: boolean; + /** The store's version is newer than the installed one. */ + updateAvailable: boolean; + /** Why the store lookup failed, when it did. */ + error?: string; +}; + +/** Whether an installed package's EHPK is actually present on disk. */ +export function isInstalledPackagePresent(packageId: string): boolean { + const entry = statPath(installedEvenHubPackagePath(packageId)); + return entry !== null && !entry.isDirectory && entry.sizeBytes > 0; +} + +/** + * Whether `candidate` is a newer version than `current`. Dotted numeric + * components compare numerically; non-numeric versions (or ones that agree + * numerically but differ textually, e.g. "1.0.0-beta" vs "1.0.0") are not + * treated as newer, so a stray tag never nags forever. + */ +export function isNewerVersion(candidate: string, current: string): boolean { + const a = versionComponents(candidate); + const b = versionComponents(current); + if (a.length === 0 || b.length === 0) return false; + for (let i = 0; i < Math.max(a.length, b.length); i++) { + const delta = (a[i] ?? 0) - (b[i] ?? 0); + if (delta !== 0) return delta > 0; + } + return false; +} + +function versionComponents(version: string): number[] { + const match = version.trim().match(/^v?(\d+(?:\.\d+)*)/i); + return match ? match[1]!.split(".").map(Number) : []; +} + +/** Describe an installed app's standing against the store record it was fetched with. */ +export function describeUpdate(installed: InstalledEvenHubApp, latest: EvenHubStoreApp | null): EvenHubAppUpdate { + return { + installed, + latest, + packageMissing: !isInstalledPackagePresent(installed.packageId), + updateAvailable: latest !== null && isNewerVersion(latest.version, installed.version), + }; +} + +/** + * Look up every installed app in the store and return the ones needing + * action (a newer version, or a missing package). Lookups run a few at a + * time; `onProgress` reports how many have completed so far. + */ +export async function checkForEvenHubUpdates( + onProgress?: (done: number, total: number) => void, +): Promise { + const installed = getInstalledEvenHubApps(); + const results: EvenHubAppUpdate[] = new Array(installed.length); + let next = 0; + let done = 0; + const worker = async () => { + while (next < installed.length) { + const index = next++; + const app = installed[index]!; + try { + results[index] = describeUpdate(app, await evenHubApi.getStoreAppDetail(app.packageId)); + } catch (error) { + // A rejected session affects every lookup: let the caller re-login. + if (error instanceof EvenHubAuthenticationError) throw error; + results[index] = { ...describeUpdate(app, null), error: cleanError(error) }; + } + done++; + onProgress?.(done, installed.length); + } + }; + await Promise.all(Array.from({ length: Math.min(4, installed.length) }, worker)); + return results.filter((update) => update.updateAvailable || update.packageMissing); +} + +function cleanError(error: unknown): string { + return String((error as Error)?.message ?? error).replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim(); +} diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index 4ea2ae05..c0d76ac6 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -74,6 +74,8 @@ import { uninstallEvenHubPackage, } from "../apps/evenhub/installed-apps"; import { closeRunningPackage, launchInstalledPackage } from "../apps/evenhub/manager"; +import { openEvenHubStoreForPackage } from "../apps/evenhub"; +import { isInstalledPackagePresent } from "../apps/evenhub/updates"; import { wearerVerificationOptions } from "../apps/microphones/speakers"; import { micSession } from "../apps/microphones/mic-session"; import { glassesDisplayLabel } from "./glasses-display-state"; @@ -2251,6 +2253,13 @@ class DashboardController { const installed = getInstalledEvenHubAppById(appId); if (installed) { const host = ALL_APPS.find((entry) => entry.appId === "evenhub")!; + if (!isInstalledPackagePresent(installed.packageId)) { + // The registry knows the app but its package is gone (a settings + // import after a reinstall): offer the store's Reinstall page. + this.appendLog(`evenhub: package missing for ${installed.packageId}; opening store page`); + await openEvenHubStoreForPackage(this.buildAppContext(host), installed); + return; + } await launchInstalledPackage(this.buildAppContext({ ...host, appId }), installed); return; }