Browse Source

feat(update): v1.0.2 App 内更新能力从零建立

老更新接口 app_update 在当前集群已 404,导致更新功能整体失效 ——
用户装上去后永远停在旧版本,修复送不到手上。本版重建整条链路。

服务端
- 新建云函数 fmode-app-update(Function 表 kTPtIM9YTQ,Module API 动态执行)
  按 appid 返回版本/下载地址/更新说明/是否强制;支持 minVersionCode 服务端强制升级
- 刻意不让客户端直连 App 表:避免绑死表结构,更新功能失效时形成升级死锁

客户端
- AppUpdateService:读原生真实版本、比对 versionCode、探测更新
- AppInstallService + AppUpdatePlugin(Java):DownloadManager 下载、通知栏进度、
  FileProvider 转 content URI 拉起安装器,全程不跳浏览器
- 更新弹窗:普通/强制两态,下载进度,可后台继续
- 「我的」页新增「关于与版本」,显示版本号 + 有新版本红点

工程
- Manifest 补 REQUEST_INSTALL_PACKAGES 与安装器包可见性声明
- file_paths 暴露更新包目录,避免 FileProvider 抛异常
- deploy-cloud-fn.mjs 收录新函数,便于热更
liuyuyang 8 hours ago
parent
commit
c188eb191b

+ 17 - 0
android/app/src/main/AndroidManifest.xml

@@ -2,10 +2,27 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools">
 
+    <!--
+      安装更新包权限(2026-11-23)
+      REQUEST_INSTALL_PACKAGES 是 Android 8+ 拉起安装器的前提。
+      声明后系统仍会要求用户在「安装未知应用」里对本 App 单独授权,
+      代码侧用 AppUpdatePlugin.canInstall() 探测、requestInstallPermission() 引导。
+    -->
+    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
+    <!-- 下载更新包,同时保持前台服务不被回收 -->
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.WAKE_LOCK" />
+
     <queries>
         <package android:name="com.miui.powerkeeper" />
         <intent><action android:name="android.settings.APP_NOTIFICATION_SETTINGS" /></intent>
         <intent><action android:name="android.settings.APPLICATION_DETAILS_SETTINGS" /><data android:scheme="package" /></intent>
+        <!-- 安装器查询(2026-11-23):Android 11+ 包可见性限制下,
+             不声明就查不到系统安装器,ACTION_VIEW 会静默失败 -->
+        <intent>
+            <action android:name="android.intent.action.VIEW" />
+            <data android:mimeType="application/vnd.android.package-archive" />
+        </intent>
     </queries>
 
     <application

+ 331 - 0
android/app/src/main/java/cn/fmode/app/AppUpdatePlugin.java

@@ -0,0 +1,331 @@
+package cn.fmode.app;
+
+import android.app.DownloadManager;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Environment;
+import android.provider.Settings;
+
+import androidx.core.content.FileProvider;
+
+import com.getcapacitor.JSObject;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.CapacitorPlugin;
+
+import java.io.File;
+
+/**
+ * App 内更新安装插件(2026-11-23 新建)
+ *
+ * ## 为什么必须做成原生
+ *
+ * WebView 里点下载链接,Android 会把这个 Intent 交给系统浏览器 ——
+ * 用户在浏览器里下完、装完,还得自己找回 App,体验是断的。
+ *
+ * 要做到「App 内点击 → 通知栏看进度 → 下完自动弹安装器」,
+ * 只有三个系统能力能配合完成,且都在原生侧:
+ *
+ *   1. DownloadManager  —— 系统级下载,切后台/息屏都会继续,自带断点续传
+ *   2. FileProvider     —— Android 7+ 禁止用 file:// 传文件给别的 App,
+ *                          必须转成 content:// URI,否则 FileUriExposedException
+ *   3. ACTION_VIEW      —— 用 MIME application/vnd.android.package-archive
+ *                          拉起系统安装器
+ *
+ * ## 权限
+ *
+ * Android 8+ 需要「安装未知应用」权限(REQUEST_INSTALL_PACKAGES 清单声明 +
+ * 用户在设置里逐次授权)。没授权时安装器打不开,所以先 canInstall() 探一下,
+ * 没有就跳到授权页,避免用户下完一堆 MB 才发现装不了。
+ */
+@CapacitorPlugin(name = "AppUpdate")
+public class AppUpdatePlugin extends Plugin {
+
+    private static final String APK_MIME = "application/vnd.android.package-archive";
+    private static final String DOWNLOAD_DIR = "fmode-update";
+
+    /** 下载完成广播接收器,注册后随插件生命周期存活 */
+    private BroadcastReceiver completeReceiver;
+
+    /**
+     * 开始下载。返回 DownloadManager 分配的 downloadId,前端靠它查进度。
+     */
+    @PluginMethod
+    public void download(PluginCall call) {
+        String url = call.getString("url");
+        if (url == null || url.isEmpty()) {
+            call.reject("缺少下载地址");
+            return;
+        }
+        String fileName = call.getString("fileName", "fmode-update.apk");
+        String title = call.getString("title", "飞马SI 更新");
+
+        try {
+            /*
+             * 下载前先清掉同名的旧包。
+             * 不清的话 DownloadManager 会存成 xxx-1.apk,安装时找错文件。
+             */
+            final File dir = downloadDir();
+            if (dir != null) {
+                File old = new File(dir, fileName);
+                if (old.exists()) {
+                    //noinspection ResultOfMethodCallIgnored
+                    old.delete();
+                }
+            }
+
+            DownloadManager.Request req = new DownloadManager.Request(Uri.parse(url));
+            req.setTitle(title);
+            req.setDescription("正在下载新版本");
+            req.setNotificationVisibility(
+                DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
+            req.setMimeType(APK_MIME);
+
+            /*
+             * 目标路径:应用专属外部目录。
+             * 用 getExternalFilesDir 而不是公共 Downloads:
+             *   · 不需要存储权限(Android 10+ 分区存储下公共目录反而麻烦)
+             *   · 卸载 App 时自动清掉,不留垃圾
+             */
+            if (dir != null) {
+                req.setDestinationInExternalFilesDir(
+                    getContext(), Environment.DIRECTORY_DOWNLOADS, DOWNLOAD_DIR + "/" + fileName);
+            } else {
+                /*
+                 * 拿不到专属目录时退回公共下载目录。
+                 * 这条路径在 Android 10+ 需要额外存储权限,
+                 * 属于极端兜底 —— 正常情况下走不到这里。
+                 */
+                req.setDestinationInExternalPublicDir(
+                    Environment.DIRECTORY_DOWNLOADS, fileName);
+            }
+
+            DownloadManager dm =
+                (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
+            if (dm == null) {
+                call.reject("系统下载服务不可用");
+                return;
+            }
+            long id = dm.enqueue(req);
+
+            registerCompleteReceiver(id);
+
+            JSObject ret = new JSObject();
+            ret.put("id", id);
+            call.resolve(ret);
+        } catch (Exception e) {
+            call.reject("启动下载失败:" + e.getMessage(), e);
+        }
+    }
+
+    /**
+     * 查下载进度。
+     *
+     * DownloadManager 的状态码是拼写常量不是枚举,这里翻译成前端好判断的字符串。
+     */
+    @PluginMethod
+    public void getProgress(PluginCall call) {
+        Long id = call.getLong("id");
+        if (id == null) {
+            call.reject("缺少下载 id");
+            return;
+        }
+
+        DownloadManager dm =
+            (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
+        if (dm == null) {
+            call.reject("系统下载服务不可用");
+            return;
+        }
+
+        DownloadManager.Query q = new DownloadManager.Query();
+        q.setFilterById(id);
+
+        Cursor c = null;
+        try {
+            c = dm.query(q);
+            if (c == null || !c.moveToFirst()) {
+                call.reject("找不到下载任务");
+                return;
+            }
+
+            int statusIdx = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
+            int downloadedIdx = c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
+            int totalIdx = c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
+
+            int status = statusIdx >= 0 ? c.getInt(statusIdx) : DownloadManager.STATUS_PENDING;
+            long downloaded = downloadedIdx >= 0 ? c.getLong(downloadedIdx) : 0;
+            long total = totalIdx >= 0 ? c.getLong(totalIdx) : -1;
+
+            JSObject ret = new JSObject();
+            ret.put("status", statusToString(status));
+            ret.put("downloadedBytes", downloaded);
+            ret.put("totalBytes", total);
+            /*
+             * total 为 -1 表示服务器没给 Content-Length。
+             * 这时算不出百分比,返回 -1 让前端显示不确定进度条,
+             * 不要瞎填 0(会看着像卡住)。
+             */
+            ret.put("progress", total > 0 ? (downloaded * 100.0 / total) : -1);
+            call.resolve(ret);
+        } catch (Exception e) {
+            call.reject("查询进度失败:" + e.getMessage(), e);
+        } finally {
+            if (c != null) c.close();
+        }
+    }
+
+    /**
+     * 拉起系统安装器。
+     *
+     * 关键点:必须用 FileProvider 生成 content:// URI。
+     * Android 7.0 起 file:// 跨进程传递会直接抛 FileUriExposedException。
+     */
+    @PluginMethod
+    public void install(PluginCall call) {
+        String url = call.getString("url");
+        if (url == null || url.isEmpty()) {
+            call.reject("缺少安装包地址");
+            return;
+        }
+
+        try {
+            String fileName = Uri.parse(url).getLastPathSegment();
+            if (fileName == null) {
+                //noinspection SpellCheckingInspection
+                fileName = "fmode-update.apk";
+            }
+
+            File dir = downloadDir();
+            File apk = new File(dir, fileName);
+            if (!apk.exists()) {
+                call.reject("安装包不存在,请重新下载");
+                return;
+            }
+
+            /*
+             * authority 必须与 AndroidManifest 里 FileProvider 的声明完全一致,
+             * 否则会抛 IllegalArgumentException。
+             */
+            Uri apkUri = FileProvider.getUriForFile(
+                getContext(), getContext().getPackageName() + ".fileprovider", apk);
+
+            Intent intent = new Intent(Intent.ACTION_VIEW);
+            intent.setDataAndType(apkUri, APK_MIME);
+            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
+
+            getContext().startActivity(intent);
+            call.resolve();
+        } catch (Exception e) {
+            call.reject("启动安装失败:" + e.getMessage(), e);
+        }
+    }
+
+    /** 检查「安装未知应用」权限(Android 8+ 才有这个概念) */
+    @PluginMethod
+    public void canInstall(PluginCall call) {
+        JSObject ret = new JSObject();
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+            ret.put("granted", getContext().getPackageManager().canRequestPackageInstalls());
+        } else {
+            ret.put("granted", true);
+        }
+        call.resolve(ret);
+    }
+
+    /** 跳到「安装未知应用」授权页 */
+    @PluginMethod
+    public void requestInstallPermission(PluginCall call) {
+        try {
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
+                    .setData(Uri.parse("package:" + getContext().getPackageName()));
+                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+                getContext().startActivity(intent);
+            }
+            call.resolve();
+        } catch (Exception e) {
+            call.reject("打开授权页失败:" + e.getMessage(), e);
+        }
+    }
+
+    // ───────────────────────────── 内部方法 ─────────────────────────────
+
+    private File downloadDir() {
+        try {
+            File d = getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
+            if (d == null) return null;
+            File sub = new File(d, DOWNLOAD_DIR);
+            if (!sub.exists() && !sub.mkdirs()) return null;
+            return sub;
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    private String statusToString(int status) {
+        switch (status) {
+            case DownloadManager.STATUS_SUCCESSFUL: return "successful";
+            case DownloadManager.STATUS_FAILED: return "failed";
+            case DownloadManager.STATUS_RUNNING: return "running";
+            case DownloadManager.STATUS_PAUSED: return "paused";
+            case DownloadManager.STATUS_PENDING: return "pending";
+            default: return "unknown";
+        }
+    }
+
+    /**
+     * 注册下载完成接收器。
+     *
+     * 只关心本次 enqueue 的 id,其他下载完成不打扰。
+     */
+    private void registerCompleteReceiver(long downloadId) {
+        try {
+            unregisterCompleteReceiver();
+            completeReceiver = new BroadcastReceiver() {
+                @Override
+                public void onReceive(Context context, Intent intent) {
+                    long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
+                    if (id != downloadId) return;
+                    JSObject data = new JSObject();
+                    data.put("id", id);
+                    notifyListeners("downloadComplete", data);
+                }
+            };
+            IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+                /* Android 13+ 必须显式声明导出标志 */
+                getContext().registerReceiver(
+                    completeReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
+            } else {
+                getContext().registerReceiver(completeReceiver, filter);
+            }
+        } catch (Exception ignored) {
+            /* 注册失败不影响下载本身,前端还有轮询兜底 */
+        }
+    }
+
+    private void unregisterCompleteReceiver() {
+        if (completeReceiver != null) {
+            try {
+                getContext().unregisterReceiver(completeReceiver);
+            } catch (Exception ignored) {
+                /* 未注册时忽略 */
+            }
+            completeReceiver = null;
+        }
+    }
+
+    @Override
+    protected void handleOnDestroy() {
+        unregisterCompleteReceiver();
+        super.handleOnDestroy();
+    }
+}

+ 1 - 0
android/app/src/main/java/cn/fmode/app/MainActivity.java

@@ -19,6 +19,7 @@ public class MainActivity extends BridgeActivity {
         // 注册自定义插件(2026-11-15)
         registerPlugin(AppSettingsPlugin.class);   // 跳系统设置页引导开通知权限
         registerPlugin(FmodeNotifyPlugin.class);   // 发系统通知(替代 @capacitor/local-notifications)
+        registerPlugin(AppUpdatePlugin.class);     // App 内下载并安装更新(2026-11-23)
 
         /*
          * 冷启动:App 没在运行时点通知,Intent 在 onCreate 才到达。

+ 16 - 1
android/app/src/main/res/xml/file_paths.xml

@@ -1,5 +1,20 @@
 <?xml version="1.0" encoding="utf-8"?>
+<!--
+  FileProvider 暴露路径(2026-11-23 补)
+
+  Android 7+ 禁止把 file:// 传给别的 App,必须用 FileProvider 转成 content://。
+  AppUpdatePlugin 拉起安装器时,用的就是这里的路径映射。
+
+  原有两条(my_images / my_cache_images)是给分享功能用的。
+  新增 external-files-path 一条专门给更新包:
+    getExternalFilesDir(DOWNLOADS)/fmode-update/
+  —— 这是 DownloadManager 保存 APK 的位置,必须能被 FileProvider 检索到,
+     否则 FileProvider.getUriForFile() 会抛 IllegalArgumentException。
+-->
 <paths xmlns:android="http://schemas.android.com/apk/res/android">
     <external-path name="my_images" path="." />
     <cache-path name="my_cache_images" path="." />
-</paths>
+
+    <!-- 更新包目录:${external-files}/Download/fmode-update/ -->
+    <external-files-path name="fmode_update" path="Download/fmode-update/" />
+</paths>

+ 135 - 0
cloud/functions/fmode-app-update-db.js

@@ -0,0 +1,135 @@
+// fmode-app-update v1.0.0 — App 版本更新检查
+//
+// 部署方式:写入 Parse 库的 `Function` 表(Fmode Module API,数据库存代码、平台动态执行)。
+// 不放在项目的 cloud/ 目录 —— 那套是老机制,当前集群已不加载。
+//
+// ## 为什么需要它
+//
+// 老接口 `app_update` 在当前集群上已经不存在(实测 GET/POST 均 404)。
+// App 侧的更新检查因此完全失效:用户装上去之后,除非自己去下载页重装,
+// 否则永远停留旧版本,形成「想修 bug 但用户升不上来」的死锁。
+//
+// ## 为什么客户端不直连 App 表
+//
+// 能连,但那样客户端就绑死了 Parse 的 REST 格式、class 名、字段名。
+// 将来加灰度、换存储、改字段,都要发新版客户端 —— 而更新检查本身失效时
+// 用户根本升不上来。所以客户端只认这个接口的契约,服务端内部随便改。
+//
+// ## 调用
+//
+//   POST /api/functions
+//   { "path": "/fmode-app-update", "params": { "appid": "cn.fmode.app", "currentVersionCode": 101 } }
+//
+// 返回(平台会包一层么?不会 —— response.json 原样返回):
+//   { "code": 200, "data": { appid, name, version, versionCode, url, changelog,
+//                            changelogUrl, isForce, size, platform, logo } }
+//   { "code": 404, "msg": "未登记的 App" }
+//   { "code": 400, "msg": "缺少 appid 参数" }
+//
+// 不需要登录:更新检查发生在登录前,返回的都是公开信息。
+
+/** 进程内小缓存,避免每次启动都打数据库 */
+var _cache = {};
+var CACHE_TTL_MS = 60 * 1000;
+
+/**
+ * 把 "1.0.12" 解析成可比较的整数:主*10000 + 次*100 + 修订。
+ * 这样 1.0.9 < 1.0.10 能正确比较 —— 字符串直接比会判错。
+ */
+function _parseVersionCode(v) {
+  if (!v) return 0;
+  var m = String(v).match(/(\d+)\.(\d+)\.(\d+)/);
+  if (!m) return 0;
+  return Number(m[1]) * 10000 + Number(m[2]) * 100 + Number(m[3]);
+}
+
+function _ok(response, data) {
+  response.status(200).json({ code: 200, data: data });
+}
+
+function _fail(response, code, msg) {
+  response.status(200).json({ code: code, msg: msg });
+}
+
+async function handler(request, response) {
+  /*
+   * 参数取法:Module API 把用户传的参数放在 request.body.params。
+   * 同时兼容直接 query(?appid=xxx)的调用方式,方便浏览器里手工验证。
+   */
+  var p = (request.body && request.body.params) || {};
+  var appid = p.appid || p.appId || (request.query && (request.query.appid || request.query.appId));
+
+  if (!appid) {
+    _fail(response, 400, '缺少 appid 参数');
+    return;
+  }
+  appid = String(appid).trim();
+
+  var currentCode = Number(p.currentVersionCode) || 0;
+
+  // 命中缓存
+  var hit = _cache[appid];
+  if (hit && Date.now() - hit.at < CACHE_TTL_MS && hit.currentCode === currentCode) {
+    _ok(response, hit.data);
+    return;
+  }
+
+  var row;
+  try {
+    var q = new Parse.Query('App');
+    q.equalTo('appid', appid);
+    q.descending('updatedAt');
+    q.limit(1);
+    row = await q.first({ useMasterKey: true });
+  } catch (e) {
+    _fail(response, 502, '查询失败:' + (e && e.message ? e.message : e));
+    return;
+  }
+
+  if (!row) {
+    _fail(response, 404, '未登记的 App:' + appid);
+    return;
+  }
+
+  // 下架的应用不推送更新
+  if (row.get('isEnabled') === false) {
+    _fail(response, 404, '该 App 已下架');
+    return;
+  }
+
+  var version = row.get('version') || '';
+  var versionCode = Number(row.get('versionCode')) || _parseVersionCode(version);
+
+  /*
+   * 强制更新判断(两级):
+   *   1. 表里 isForce=true  → 无条件强制
+   *   2. 表里配了 minVersionCode 且客户端版本低于它 → 强制
+   * 第二条的价值:服务端改一个字段就能让所有低版本用户强制升级,
+   * 不用发新版客户端。
+   */
+  var isForce = row.get('isForce') === true;
+  var minCode = Number(row.get('minVersionCode')) || 0;
+  if (currentCode > 0 && minCode > 0 && currentCode < minCode) {
+    isForce = true;
+  }
+
+  var data = {
+    appid: appid,
+    name: row.get('name') || '',
+    version: version,
+    versionCode: versionCode,
+    // 历史数据 apkUrl / downUrl 写法不统一,按优先级取
+    url: row.get('apkUrl') || row.get('downUrl') || '',
+    changelog: row.get('changelog') || row.get('content') || '',
+    changelogUrl: row.get('changelogUrl') || '',
+    isForce: isForce,
+    size: Number(row.get('size')) || 0,
+    platform: row.get('platform') || ['android'],
+    logo: row.get('logo') || '',
+    bgImg: row.get('bgImg') || '',
+    publishedAt: row.updatedAt ? row.updatedAt.toISOString() : '',
+  };
+
+  _cache[appid] = { at: Date.now(), currentCode: currentCode, data: data };
+  _ok(response, data);
+}

+ 174 - 0
cloud/functions/fmode-app-update.js

@@ -0,0 +1,174 @@
+// fmode-app-update v1.0.0 — App 版本更新检查(2026-11-23 新建)
+//
+// ## 为什么重写
+//
+// 老接口 `app_update` 在当前集群上**已经不存在**(实测 GET /parse/functions/app_update
+// 与 POST 均 404)。App 侧的更新检查因此完全失效 —— 用户装上去之后,
+// 除非自己去下载页重装,否则永远停留旧版本。
+//
+// 本函数接管这件事,职责单一:给一个 appid,返回该 App 的最新版本信息。
+//
+// ## 为什么不让客户端直接查 App 表
+//
+// 能查(App 表 public-read),但那样客户端就绑死了 Parse 的 REST 格式、
+// 绑死了 class 名和字段名,将来换存储或加灰度逻辑就要改客户端、发版、用户升级……
+// 而现在更新检查本身失效时,用户连升级都做不到,形成死锁。
+// 所以:**客户端只认这个接口的契约,服务端想怎么变都行。**
+//
+// ## 接口
+//
+//   GET  /api/functions/fmode-app-update?appid=cn.fmode.app
+//   或   POST /api/functions { id:<FunctionId>, params:{ appid, currentVersionCode } }
+//
+// 返回:
+//   { code: 200, data: { appid, name, version, versionCode, url, changelog,
+//                        changelogUrl, isForce, size, platform, publishedAt } }
+//   或 { code: 404, msg: '未登记的 App' }
+//
+// 本函数**不需要登录**:更新检查发生在登录前(比如启动时),
+// 且返回的都是公开信息,不涉及用户数据。
+//
+// ## 设计要点
+//
+//   · 只返回 isEnabled != false 的记录(下架的应用不该推给用户)
+//   · url 优先 apkUrl,回落 downUrl —— 历史数据两者写法不统一
+//   · versionCode 缺失时用 version 解析补齐,保证客户端能正确比较
+//   · 支持灰度:传 currentVersionCode 时,若服务端配了 minVersionCode
+//     且当前版本低于它,返回 isForce=true(强制更新)
+//   · 强缓存 60s:更新检查可能频繁调用,但也不能缓存太久,
+//     否则发了新版用户要等很久才能查到
+
+var APP_CLASS = 'App';
+var CACHE_TTL_MS = 60 * 1000;
+
+/** 进程内小缓存:{ appid: { at, data } } */
+var _cache = {};
+
+function _ok(response, data) {
+  response.status(200).json({ code: 200, data: data });
+}
+
+function _fail(response, code, msg) {
+  response.status(200).json({ code: code, msg: msg });
+}
+
+/**
+ * 把 "1.0.12" 解析成可比较的整数。
+ *
+ * 规则:主*10000 + 次*100 + 修订。
+ * 这样 1.0.9 < 1.0.10 能正确比较 —— 字符串直接比会判错。
+ */
+function _parseVersionCode(v) {
+  if (!v) return 0;
+  var m = String(v).match(/(\d+)\.(\d+)\.(\d+)/);
+  if (!m) return 0;
+  return Number(m[1]) * 10000 + Number(m[2]) * 100 + Number(m[3]);
+}
+
+/** 取请求参数:GET 走 query,POST 走全局 params */
+function _param(request, name) {
+  if (request && request.query && request.query[name] != null) {
+    return request.query[name];
+  }
+  try {
+    if (typeof params !== 'undefined' && params && params[name] != null) {
+      return params[name];
+    }
+  } catch (e) {
+    /* params 未注入时忽略 */
+  }
+  return null;
+}
+
+async function _fetchApp(appid) {
+  /*
+   * 用平台注入的 Parse 全局对象查询 —— 现有云函数都是这么做的
+   * (fmodeagent-status / fmode-file-hub 均如此),不要自己拼 REST 请求:
+   * 服务端内部地址和 master key 都不该硬编码在函数里。
+   *
+   * useMasterKey 是必须的:App 表虽公开可读,但走 master key
+   * 能避开 ACL 差异,行为更稳定。
+   */
+  var q = new Parse.Query('App');
+  q.equalTo('appid', appid);
+  q.descending('updatedAt');
+  q.limit(1);
+  return await q.first({ useMasterKey: true });
+}
+
+async function handler(request, response) {
+  var appid = _param(request, 'appid') || _param(request, 'appId');
+
+  if (!appid) {
+    _fail(response, 400, '缺少 appid 参数');
+    return;
+  }
+
+  appid = String(appid).trim();
+
+  // 命中缓存直接返回
+  var hit = _cache[appid];
+  if (hit && Date.now() - hit.at < CACHE_TTL_MS) {
+    _ok(response, hit.data);
+    return;
+  }
+
+  var row;
+  try {
+    row = await _fetchApp(appid);
+  } catch (e) {
+    _fail(response, 502, '查询失败:' + (e && e.message ? e.message : e));
+    return;
+  }
+
+  if (!row) {
+    _fail(response, 404, '未登记的 App:' + appid);
+    return;
+  }
+
+  // 下架的应用不推送更新
+  if (row.isEnabled === false) {
+    _fail(response, 404, '该 App 已下架');
+    return;
+  }
+
+  var versionCode = Number(row.versionCode) || _parseVersionCode(row.version);
+
+  /*
+   * 灰度/强制更新:客户端把当前 versionCode 带上来,
+   * 若低于服务端配置的 minVersionCode,则强制更新。
+   * 这样服务端改一个字段就能让所有人升级,不用发新版客户端。
+   */
+  var currentCode = Number(_param(request, 'currentVersionCode')) || 0;
+  var minCode = Number(row.minVersionCode) || 0;
+  var isForce = row.isForce === true;
+  if (currentCode > 0 && minCode > 0 && currentCode < minCode) {
+    isForce = true;
+  }
+
+  var data = {
+    appid: row.appid,
+    name: row.name || '',
+    version: row.version || '',
+    versionCode: versionCode,
+    // 历史数据 apkUrl / downUrl 写法不统一,按优先级取
+    url: row.apkUrl || row.downUrl || '',
+    changelog: row.changelog || row.content || '',
+    changelogUrl: row.changelogUrl || '',
+    isForce: isForce,
+    size: Number(row.size) || 0,
+    platform: row.platform || ['android'],
+    publishedAt: row.updatedAt || '',
+    // 图标与开机图,供客户端做更新卡片
+    logo: row.logo || '',
+    bgImg: row.bgImg || '',
+  };
+
+  _cache[appid] = { at: Date.now(), data: data };
+  _ok(response, data);
+}
+
+// 平台约定:必须显式导出 handler
+if (typeof module !== 'undefined' && module.exports) {
+  module.exports = { handler: handler };
+}

+ 11 - 0
scripts/deploy-cloud-fn.mjs

@@ -55,6 +55,17 @@ const ONLY = (process.argv.find((a) => a.startsWith('--only=')) ?? '').slice('--
  * 需要把它写回 `src/app/core/api/parse-api.ts` 的 `FN` 常量。
  */
 const TARGETS = [
+  {
+    /*
+     * 2026-11-23 新建:App 版本更新检查。
+     * 老接口 app_update 在当前集群已 404,导致更新功能整体失效 —— 本函数接管。
+     * 调用方式用函数 id(按 path 调用实测返回「云函数不存在」)。
+     */
+    file: 'cloud/functions/fmode-app-update-db.js',
+    id: 'kTPtIM9YTQ',
+    name: 'fmode-app-update',
+    version: '1.0.0',
+  },
   {
     file: 'cloud/functions/fmodeagent-chatthreads.js',
     id: 'oR5O67i1Cm',

+ 251 - 0
src/app/core/app-install.service.ts

@@ -0,0 +1,251 @@
+import { Injectable, signal } from '@angular/core';
+import { Capacitor, registerPlugin } from '@capacitor/core';
+import { LocalNotifications } from '@capacitor/local-notifications';
+
+/**
+ * App 内更新安装(2026-11-23 新建)
+ *
+ * 需求:在 App 里点「立即更新」就能下载并安装,不要跳到浏览器。
+ *
+ * 为什么需要原生插件:
+ *   WebView 里 `<a download>` 或 `window.open` 都会把 Android 的 Intent
+ *   交给系统浏览器,用户装完回来还得自己找 App。
+ *   要「下载完成 → 直接拉起安装器 → 装完回到 App」,必须走原生:
+ *
+ *     1. DownloadManager 交给系统下载(能后台继续、断点续传、省电)
+ *     2. 监听下载完成广播
+ *     3. FileProvider 把 apk 转成 content:// URI(Android 7+ 必须)
+ *     4. ACTION_VIEW + application/vnd.android.package-archive 拉起安装器
+ *
+ * 插件实现在 android/app/src/main/java/cn/fmode/app/AppUpdatePlugin.java
+ */
+
+export interface DownloadState {
+  status: 'idle' | 'downloading' | 'done' | 'installing' | 'error';
+  /** 0–100,未知进度时为 -1 */
+  progress: number;
+  /** 已下载字节 */
+  bytes: number;
+  /** 总字节,未知为 -1 */
+  total: number;
+  message?: string;
+}
+
+interface AppUpdatePluginApi {
+  /**
+   * 开始下载 APK。
+   * 下载在系统 DownloadManager 里进行,App 退到后台也会继续。
+   */
+  download(options: { url: string; fileName?: string; title?: string }): Promise<{ id: number }>;
+
+  /** 查询下载进度 */
+  getProgress(options: { id: number }): Promise<{
+    status: string;
+    downloadedBytes: number;
+    totalBytes: number;
+    progress: number;
+  }>;
+
+  /** 拉起系统安装器 */
+  install(options: { url: string }): Promise<void>;
+
+  /** 检查「安装未知应用」权限是否已授予 */
+  canInstall(): Promise<{ granted: boolean }>;
+
+  /** 跳到「安装未知应用」授权页 */
+  requestInstallPermission(): Promise<void>;
+
+  /** 监听下载完成 */
+  addListener(
+    event: 'downloadComplete',
+    cb: (data: { id: number }) => void,
+  ): Promise<{ remove: () => void }>;
+}
+
+const AppUpdate = registerPlugin<AppUpdatePluginApi>('AppUpdate');
+
+@Injectable({ providedIn: 'root' })
+export class AppInstallService {
+  readonly state = signal<DownloadState>({
+    status: 'idle',
+    progress: 0,
+    bytes: 0,
+    total: -1,
+  });
+
+  private downloadId: number | null = null;
+  private pollTimer: ReturnType<typeof setInterval> | null = null;
+
+  /**
+   * 当前下载任务对应的 APK 地址。
+   *
+   * 下载完成后要靠它告诉原生插件「安装哪个包」。
+   * 之所以自己存一份而不是让原生回传,是因为 DownloadManager 的
+   * 本地 URI 在部分 ROM 上不可靠,用原始 http 地址重新定位更稳。
+   */
+  private currentUrl = '';
+
+  /**
+   * 下载并安装更新。
+   *
+   * 流程:
+   *   1. 检查「安装未知应用」权限,没有就引导去开(这一步跳过会让下载白做)
+   *   2. 交给系统 DownloadManager 下载,同时挂通知
+   *   3. 轮询进度更新 UI
+   *   4. 下载完成 → 自动拉起安装器
+   */
+  async downloadAndInstall(url: string, version: string): Promise<void> {
+    if (!Capacitor.isNativePlatform()) {
+      /* 浏览器环境没有安装能力,直接开新窗口兜底 */
+      window.open(url, '_blank');
+      return;
+    }
+
+    this.state.set({ status: 'downloading', progress: 0, bytes: 0, total: -1 });
+
+    try {
+      /*
+       * 权限先行。Android 8+ 每个来源都要单独授权,
+       * 没权限的话下载完拉不起安装器,用户会以为下载失败。
+       */
+      const perm = await AppUpdate.canInstall();
+      if (!perm.granted) {
+        await AppUpdate.requestInstallPermission();
+        /*
+         * 授权页返回后无法可靠判断用户是否真的开了(不同 ROM 行为不一),
+         * 所以这里不阻断,继续下载 —— 等真到安装那步再失败,至少包已经下好了。
+         */
+      }
+
+      const fileName = `fmode-${version}.apk`;
+      /* 先存 URL,下载完成回调里靠它定位安装包 */
+      this.currentUrl = url;
+      const { id } = await AppUpdate.download({
+        url,
+        fileName,
+        title: `飞马SI ${version}`,
+      });
+      this.downloadId = id;
+
+      /* 通知栏挂一条「下载中」,用户切出去也能看到进度 */
+      void this.notifyProgress(version);
+
+      this.startPolling(version);
+    } catch (e: unknown) {
+      this.fail(e instanceof Error ? e.message : '下载失败');
+    }
+  }
+
+  /**
+   * 轮询下载进度。
+   *
+   * 为什么轮询而不是纯事件:DownloadManager 的进度广播在部分 ROM 上
+   * 不可靠(尤其被省电策略限制时)。500ms 轮询一次成本很低,
+   * 且能保证 UI 一定跟得上。
+   */
+  private startPolling(version: string): void {
+    this.stopPolling();
+    this.pollTimer = setInterval(async () => {
+      if (this.downloadId == null) return;
+      try {
+        const p = await AppUpdate.getProgress({ id: this.downloadId });
+
+        this.state.update((s) => ({
+          ...s,
+          progress: p.progress >= 0 ? Math.round(p.progress) : -1,
+          bytes: p.downloadedBytes,
+          total: p.totalBytes,
+        }));
+
+        /* DownloadManager 状态:8=成功,16=失败 */
+        if (p.status === 'successful') {
+          this.stopPolling();
+          this.state.update((s) => ({ ...s, status: 'installing', progress: 100 }));
+          await this.notifyDone(version);
+          await this.install(this.stateUrl());
+        } else if (p.status === 'failed') {
+          this.stopPolling();
+          this.fail('下载失败,请检查网络后重试');
+        }
+      } catch {
+        /* 单次查询失败不中断轮询 */
+      }
+    }, 500);
+  }
+
+  /** 记录当前下载的 URL,安装时要用 */
+  private stateUrl(): string {
+    return this.currentUrl;
+  }
+
+  /**
+   * 拉起系统安装器。
+   *
+   * 走原生插件而不是 window.open:原生会用 FileProvider 生成
+   * content:// URI,这是 Android 7+ 的硬性要求,
+   * 直接传 file:// 会被 FileUriExposedException 崩掉。
+   */
+  async install(url: string): Promise<void> {
+    try {
+      await AppUpdate.install({ url });
+    } catch (e: unknown) {
+      this.fail(e instanceof Error ? e.message : '无法启动安装');
+    }
+  }
+
+  private async notifyProgress(version: string): Promise<void> {
+    try {
+      await LocalNotifications.schedule({
+        notifications: [
+          {
+            id: 9001,
+            title: `飞马SI ${version} 下载中`,
+            body: '下载完成后会自动提示安装',
+            ongoing: true,
+            autoCancel: false,
+          },
+        ],
+      });
+    } catch {
+      /* 通知权限被拒不影响下载本身 */
+    }
+  }
+
+  private async notifyDone(version: string): Promise<void> {
+    try {
+      await LocalNotifications.cancel({ notifications: [{ id: 9001 }] });
+      await LocalNotifications.schedule({
+        notifications: [
+          {
+            id: 9002,
+            title: `飞马SI ${version} 已下载`,
+            body: '点击开始安装',
+            autoCancel: true,
+          },
+        ],
+      });
+    } catch {
+      /* 同上 */
+    }
+  }
+
+  private fail(msg: string): void {
+    this.stopPolling();
+    this.state.set({ status: 'error', progress: 0, bytes: 0, total: -1, message: msg });
+  }
+
+  private stopPolling(): void {
+    if (this.pollTimer) {
+      clearInterval(this.pollTimer);
+      this.pollTimer = null;
+    }
+  }
+
+  /** 重置状态,关闭弹窗时调用 */
+  reset(): void {
+    this.stopPolling();
+    this.downloadId = null;
+    this.currentUrl = '';
+    this.state.set({ status: 'idle', progress: 0, bytes: 0, total: -1 });
+  }
+}

+ 233 - 0
src/app/core/app-update.service.ts

@@ -0,0 +1,233 @@
+import { Injectable, signal, computed, inject } from '@angular/core';
+import { App } from '@capacitor/app';
+import { Capacitor } from '@capacitor/core';
+
+/**
+ * 版本与更新服务(2026-11-23 新建)
+ *
+ * 背景:这个 App 之前**完全没有**更新检查能力 —— 用户装上去之后,
+ * 除非自己去下载页重装,否则永远停留在旧版本。
+ *
+ * 设计要点:
+ *
+ * 1. **版本单一事实源**
+ *    原生 versionName / versionCode 从 `@capacitor/app` 的 getInfo() 读,
+ *    不在前端硬编码。读不到(纯浏览器)时回退到构建期注入的常量。
+ *
+ * 2. **更新元数据走平台云函数**
+ *    `app_update?appId=<包名>` 返回最新版本信息。这个接口是平台既有的,
+ *    和 nova-admin 那套完全一致,不需要新增后端。
+ *
+ * 3. **更新日志内嵌在返回体**
+ *    `App` 表 record 里有 `content` 字段存更新说明,
+ *    所以「查看更新了什么」不需要额外请求。
+ *
+ * 4. **强制更新能力**
+ *    `isForce` 为真时弹窗不可关闭,必须更新才能继续用。
+ */
+
+export interface UpdateInfo {
+  /** 最新版本名,如 1.0.2 */
+  version: string;
+  /** 最新版本号,用于数值比较 */
+  versionCode: number;
+  /** APK 直链 */
+  url: string;
+  /** 更新说明(纯文本或简单 markdown) */
+  content: string;
+  /** 是否强制更新 */
+  isForce: boolean;
+  /** 更新说明详情页(可选,更丰富的排版) */
+  changelogUrl?: string;
+  /** APK 体积(字节,可选,用于展示) */
+  size?: number;
+}
+
+export interface LocalVersion {
+  versionName: string;
+  versionCode: number;
+  appName: string;
+  packageName: string;
+}
+
+/** 包名 —— 与 capacitor.config.ts 保持一致 */
+const APP_ID = 'cn.fmode.app';
+
+/**
+ * 更新服务接口(2026-11-23)
+ *
+ * 走自建云函数 `fmode-app-update`(Fmode Module API,代码存在数据库里动态执行)。
+ * 老接口 `app_update` 在当前集群已不存在(实测 404),是更新整体失效的根因。
+ *
+ * 为什么不再直连 App 表:
+ *   直连会把客户端绑死在 Parse 的 REST 格式、class 名、字段名上。
+ *   将来加灰度、改字段、换存储都要发新版客户端 —— 而更新功能本身失效时,
+ *   用户根本升不上来,形成死锁。云函数这层契约解耦了这个风险。
+ *
+ * 调用方式用 **函数 id** 而非 path:
+ *   实测按 path 调用返回「云函数不存在」,按 id 稳定可用。
+ *   函数 id 由部署时生成,写死在这里(服务端换实现不需要改这个 id)。
+ */
+const UPDATE_FN_URL = 'https://server.fmode.cn/api/functions';
+const UPDATE_FN_ID = 'kTPtIM9YTQ';
+
+@Injectable({ providedIn: 'root' })
+export class AppUpdateService {
+  /** 本机当前版本 */
+  readonly local = signal<LocalVersion | null>(null);
+
+  /** 服务端返回的最新版本(null = 还没查到或已是最新) */
+  readonly remote = signal<UpdateInfo | null>(null);
+
+  /** 网络/解析错误信息 */
+  readonly error = signal<string | null>(null);
+
+  /** 是否正在检查 */
+  readonly checking = signal(false);
+
+  /** 是否有可用更新 —— 只比较 versionCode,这是唯一可靠依据 */
+  readonly hasUpdate = computed(() => {
+    const l = this.local();
+    const r = this.remote();
+    if (!l || !r) return false;
+    return r.versionCode > l.versionCode;
+  });
+
+  /** 更新是否为强制 */
+  readonly isForce = computed(() => this.remote()?.isForce === true);
+
+  private infoLoaded = false;
+
+  /**
+   * 读本机版本。
+   *
+   * 原生环境走 Capacitor App.getInfo(),拿真实的 versionName/versionCode;
+   * 浏览器环境没有这些,用构建期常量兜底,保证页面不崩。
+   */
+  async loadLocalVersion(): Promise<LocalVersion> {
+    if (this.infoLoaded && this.local()) return this.local()!;
+
+    let info: LocalVersion = {
+      versionName: '1.0.1',
+      versionCode: 101,
+      appName: '飞马SI',
+      packageName: APP_ID,
+    };
+
+    if (Capacitor.isNativePlatform()) {
+      try {
+        const v = await App.getInfo();
+        info = {
+          versionName: v.version || info.versionName,
+          /*
+           * getInfo() 的 build 字段就是 Android 的 versionCode,
+           * 但它是字符串。解析失败就退回默认值,绝不 NaN。
+           */
+          versionCode: Number.parseInt(v.build, 10) || info.versionCode,
+          appName: v.name || info.appName,
+          packageName: v.id || APP_ID,
+        };
+      } catch {
+        /* 读不到就用兜底值,不阻塞 */
+      }
+    }
+
+    this.local.set(info);
+    this.infoLoaded = true;
+    return info;
+  }
+
+  /**
+   * 检查更新。
+   *
+   * 返回 true 表示有更新。调用方据此决定是否弹窗 ——
+   * 服务本身不弹窗,保持无 UI 副作用,方便在启动、进「我的」页、
+   * 用户手动点击等多种时机复用。
+   */
+  async check(): Promise<boolean> {
+    this.checking.set(true);
+    this.error.set(null);
+
+    try {
+      const local = await this.loadLocalVersion();
+
+      /*
+       * 调用云函数(POST,参数在 params 里)。
+       *
+       * 带上 currentVersionCode:服务端可据此判断是否低于 minVersionCode,
+       * 从而把某次更新升级为强制更新 —— 服务端改字段即可,不用发新版客户端。
+       */
+      const res = await fetch(UPDATE_FN_URL, {
+        method: 'POST',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({
+          id: UPDATE_FN_ID,
+          params: {
+            appid: APP_ID,
+            currentVersionCode: local.versionCode,
+            currentVersion: local.versionName,
+          },
+        }),
+        /* 更新检查绝不能命中任何缓存,否则发了新版用户永远查不到 */
+        cache: 'no-store',
+      });
+
+      if (!res.ok) {
+        this.error.set(`更新服务返回 ${res.status}`);
+        return false;
+      }
+
+      const json = await res.json();
+
+      /*
+       * 云函数返回 { code: 200, data: {...} }。
+       * code 404 = 这个包还没在 App 表登记,视为「无更新」而不是错误。
+       */
+      if (json?.code !== 200 || !json.data) {
+        this.remote.set(null);
+        return false;
+      }
+
+      const row = json.data;
+      const info: UpdateInfo = {
+        version: String(row.version ?? ''),
+        /*
+         * 云函数已把 versionCode 补齐;万一缺失,
+         * 用 version 解析出数字来比较,否则没法判断新旧。
+         */
+        versionCode: Number(row.versionCode) || this.parseVersionCode(String(row.version ?? '')),
+        url: row.url ?? '',
+        content: row.changelog ?? '',
+        isForce: row.isForce === true,
+        changelogUrl: row.changelogUrl || undefined,
+        size: Number(row.size) || undefined,
+      };
+
+      if (!info.url || !info.version) {
+        this.remote.set(null);
+        return false;
+      }
+
+      this.remote.set(info);
+      return info.versionCode > local.versionCode;
+    } catch (e: unknown) {
+      this.error.set(e instanceof Error ? e.message : '检查更新失败');
+      return false;
+    } finally {
+      this.checking.set(false);
+    }
+  }
+
+  /**
+   * 把 "1.0.12" 解析成可用于比较的整数 10012。
+   *
+   * 规则:主.次.修订 → 主*10000 + 次*100 + 修订。
+   * 这样 1.0.9 < 1.0.10 能正确比较(字符串比较会判错)。
+   * 服务端没给 versionCode 时用这个兜底。
+   */
+  private parseVersionCode(v: string): number {
+    const m = v.match(/(\d+)\.(\d+)\.(\d+)/);
+    if (!m) return 0;
+    return Number(m[1]) * 10000 + Number(m[2]) * 100 + Number(m[3]);
+  }
+}

+ 313 - 0
src/app/mobile/components/m-update-dialog/m-update-dialog.ts

@@ -0,0 +1,313 @@
+import { Component, ChangeDetectionStrategy, inject, computed, signal, OnInit } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { AppUpdateService } from '../../../core/app-update.service';
+import { AppInstallService } from '../../../core/app-install.service';
+
+/**
+ * 更新提示弹窗(2026-11-23 新建)
+ *
+ * 三种形态:
+ *   1. **强制更新**:遮罩不可点、无关闭按钮,只有一个「立即更新」
+ *   2. **普通更新**:「稍后再说」+「立即更新」
+ *   3. **下载中**:进度条 + 字节数,可后台继续(关掉弹窗不影响下载)
+ *
+ * 下载走 AppInstallService:App 内直接下、挂通知、下完拉安装器,
+ * 不跳浏览器。这是用户明确要求的体验。
+ */
+@Component({
+  selector: 'app-update-dialog',
+  standalone: true,
+  imports: [CommonModule],
+  changeDetection: ChangeDetectionStrategy.OnPush,
+  template: `
+    @if (visible() && info(); as u) {
+      <div class="m-update-mask" [class.is-force]="u.isForce" (click)="onMaskClick(u.isForce)">
+        <div class="m-update-card" role="dialog" aria-modal="true" aria-labelledby="upd-title">
+
+          @if (install.state().status === 'downloading') {
+            <!-- ───────── 下载中 ───────── -->
+            <div class="m-update-head">
+              <h3 id="upd-title">正在下载更新</h3>
+              <p class="m-update-ver">{{ u.version }}</p>
+            </div>
+
+            <div class="m-progress-wrap">
+              <div class="m-progress-bar">
+                <div class="m-progress-fill"
+                     [style.width.%]="install.state().progress >= 0 ? install.state().progress : 0">
+                </div>
+              </div>
+              <div class="m-progress-meta">
+                <span>{{ progressText() }}</span>
+                <span>{{ percentText() }}</span>
+              </div>
+            </div>
+
+            <p class="m-update-hint">
+              下载会在后台继续,可以先把 App 放到一边。下载完成后会自动弹出安装。
+            </p>
+
+            @if (!u.isForce) {
+              <button type="button" class="m-btn m-btn-ghost" (click)="close()">
+                后台继续,先不看
+              </button>
+            }
+          } @else {
+            <!-- ───────── 更新说明 ───────── -->
+            <div class="m-update-head">
+              <div class="m-update-badge" [class.force]="u.isForce">
+                {{ u.isForce ? '必须更新' : '有新版本' }}
+              </div>
+              <h3 id="upd-title">飞马SI {{ u.version }}</h3>
+              <p class="m-update-ver">
+                当前版本 {{ localVersion() }}
+                @if (u.size) { · {{ sizeText(u.size) }} }
+              </p>
+            </div>
+
+            @if (u.content) {
+              <div class="m-update-log">
+                @for (line of contentLines(u.content); track $index) {
+                  <p>{{ line }}</p>
+                }
+              </div>
+            }
+
+            @if (install.state().status === 'error') {
+              <p class="m-update-err">{{ install.state().message }}</p>
+            }
+
+            <div class="m-update-actions">
+              <button type="button" class="m-btn m-btn-primary"
+                      (click)="startUpdate(u.url, u.version)">
+                立即更新
+              </button>
+              @if (!u.isForce) {
+                <button type="button" class="m-btn m-btn-ghost" (click)="close()">
+                  稍后再说
+                </button>
+              }
+            </div>
+          }
+
+        </div>
+      </div>
+    }
+  `,
+  styles: [`
+    .m-update-mask {
+      position: fixed;
+      inset: 0;
+      z-index: 9999;
+      display: flex;
+      align-items: center;
+      justify-content: center;
+      padding: 24px;
+      background: rgba(8, 13, 24, 0.72);
+      backdrop-filter: blur(6px);
+      animation: fadeIn 0.2s ease;
+    }
+    .m-update-mask.is-force {
+      /* 强制更新时遮罩更实,视觉上明确「这个不能跳过」 */
+      background: rgba(8, 13, 24, 0.9);
+    }
+    @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
+
+    .m-update-card {
+      width: 100%;
+      max-width: 380px;
+      background: #fff;
+      border-radius: 20px;
+      padding: 26px 24px 22px;
+      box-shadow: 0 24px 64px rgba(0, 0, 0, 0.4);
+      animation: slideUp 0.26s cubic-bezier(0.16, 1, 0.3, 1);
+      /* 内容多时可滚动,避免小屏溢出 */
+      max-height: 82vh;
+      overflow-y: auto;
+    }
+    @keyframes slideUp {
+      from { opacity: 0; transform: translateY(16px) scale(0.98) }
+      to { opacity: 1; transform: translateY(0) scale(1) }
+    }
+
+    .m-update-head { margin-bottom: 18px; }
+    .m-update-badge {
+      display: inline-block;
+      padding: 4px 11px;
+      border-radius: 999px;
+      font-size: 12px;
+      font-weight: 600;
+      background: #EFF6FF;
+      color: #2563EB;
+      margin-bottom: 12px;
+    }
+    .m-update-badge.force {
+      background: #FEF2F2;
+      color: #DC2626;
+    }
+    .m-update-head h3 {
+      font-size: 20px;
+      font-weight: 700;
+      color: #0F172A;
+      margin: 0 0 6px;
+      letter-spacing: -0.01em;
+    }
+    .m-update-ver {
+      font-size: 13px;
+      color: #64748B;
+      margin: 0;
+    }
+
+    .m-update-log {
+      background: #F8FAFC;
+      border-radius: 12px;
+      padding: 14px 16px;
+      margin-bottom: 20px;
+      max-height: 220px;
+      overflow-y: auto;
+    }
+    .m-update-log p {
+      font-size: 13.5px;
+      line-height: 1.7;
+      color: #334155;
+      margin: 0 0 6px;
+    }
+    .m-update-log p:last-child { margin-bottom: 0; }
+
+    .m-progress-wrap { margin-bottom: 18px; }
+    .m-progress-bar {
+      height: 8px;
+      border-radius: 999px;
+      background: #E2E8F0;
+      overflow: hidden;
+      margin-bottom: 8px;
+    }
+    .m-progress-fill {
+      height: 100%;
+      border-radius: 999px;
+      background: linear-gradient(90deg, #6D28D9, #06B6D4);
+      transition: width 0.3s ease;
+    }
+    .m-progress-meta {
+      display: flex;
+      justify-content: space-between;
+      font-size: 12.5px;
+      color: #64748B;
+      font-variant-numeric: tabular-nums;
+    }
+
+    .m-update-hint {
+      font-size: 12.5px;
+      line-height: 1.7;
+      color: #64748B;
+      margin: 0 0 18px;
+    }
+    .m-update-err {
+      font-size: 13px;
+      color: #DC2626;
+      margin: 0 0 14px;
+    }
+
+    .m-update-actions {
+      display: flex;
+      flex-direction: column;
+      gap: 9px;
+    }
+    .m-btn {
+      width: 100%;
+      padding: 14px;
+      border-radius: 13px;
+      border: none;
+      font-size: 15.5px;
+      font-weight: 600;
+      cursor: pointer;
+      transition: transform 0.12s;
+    }
+    .m-btn:active { transform: scale(0.98); }
+    .m-btn-primary {
+      background: linear-gradient(135deg, #6D28D9, #06B6D4);
+      color: #fff;
+      box-shadow: 0 8px 24px rgba(109, 40, 217, 0.32);
+    }
+    .m-btn-ghost {
+      background: transparent;
+      color: #64748B;
+      font-weight: 500;
+    }
+  `],
+})
+export class UpdateDialogComponent implements OnInit {
+  private readonly update = inject(AppUpdateService);
+  readonly install = inject(AppInstallService);
+
+  /** 用户主动关掉后不再自动弹(非强制更新时) */
+  private readonly dismissed = signal(false);
+
+  readonly visible = computed(() => {
+    if (this.dismissed()) return false;
+    const s = this.install.state().status;
+    /* 下载中或安装中必须继续显示,即使 hasUpdate 已经被清 */
+    if (s === 'downloading' || s === 'installing' || s === 'error') return true;
+    return this.update.hasUpdate();
+  });
+
+  readonly info = computed(() => this.update.remote());
+
+  readonly localVersion = computed(() => this.update.local()?.versionName ?? '');
+
+  async ngOnInit(): Promise<void> {
+    /*
+     * 组件挂载即检查更新。
+     * 放在这里而不是 App 启动钩子,是因为弹窗组件本身就代表「该检查了」,
+     * 而且懒加载 —— 用户没进到含弹窗的页面就不会发请求。
+     */
+    await this.update.check();
+  }
+
+  /** 下载中显示:已下载 / 总量 */
+  progressText(): string {
+    const s = this.install.state();
+    if (s.total <= 0) return `已下载 ${this.sizeText(s.bytes)}`;
+    return `${this.sizeText(s.bytes)} / ${this.sizeText(s.total)}`;
+  }
+
+  percentText(): string {
+    const p = this.install.state().progress;
+    return p >= 0 ? `${p}%` : '计算中…';
+  }
+
+  sizeText(bytes: number): string {
+    if (!bytes || bytes <= 0) return '0 MB';
+    const mb = bytes / 1024 / 1024;
+    return mb >= 1 ? `${mb.toFixed(1)} MB` : `${(bytes / 1024).toFixed(0)} KB`;
+  }
+
+  /** 更新说明按行拆开渲染,保留原有的空行分段 */
+  contentLines(content: string): string[] {
+    return content
+      .split(/\r?\n/)
+      .map((l) => l.trim())
+      .filter((l) => l.length > 0);
+  }
+
+  async startUpdate(url: string, version: string): Promise<void> {
+    await this.install.downloadAndInstall(url, version);
+  }
+
+  close(): void {
+    this.dismissed.set(true);
+    /*
+     * 只关弹窗,**不中断下载** —— 下载在系统 DownloadManager 里,
+     * App 关了也会继续。用户下次回来看「我的」页还能看到进度。
+     */
+    if (this.install.state().status === 'idle') {
+      this.install.reset();
+    }
+  }
+
+  /** 点遮罩关闭。强制更新时点遮罩无效 */
+  onMaskClick(isForce: boolean): void {
+    if (isForce) return;
+    this.close();
+  }
+}

+ 89 - 1
src/app/mobile/pages/mine/mine.ts

@@ -14,6 +14,8 @@ import { MAppBarComponent } from '../../components/m-app-bar/m-app-bar';
 import { MAvatarComponent } from '../../components/m-avatar/m-avatar';
 import { MDrawerComponent } from '../../components/m-drawer/m-drawer';
 import { MConfirmComponent } from '../../components/m-confirm/m-confirm';
+import { AppUpdateService } from '../../../core/app-update.service';
+import { UpdateDialogComponent } from '../../components/m-update-dialog/m-update-dialog';
 
 /**
  * 我的 / 设置(Demo 16)
@@ -27,7 +29,7 @@ import { MConfirmComponent } from '../../components/m-confirm/m-confirm';
 @Component({
   selector: 'app-mb-mine-page',
   changeDetection: ChangeDetectionStrategy.OnPush,
-  imports: [MAppBarComponent, MAvatarComponent, MDrawerComponent, MConfirmComponent],
+  imports: [MAppBarComponent, MAvatarComponent, MDrawerComponent, MConfirmComponent, UpdateDialogComponent],
   template: `
     <div class="m-page--scroll">
       <app-m-app-bar title="我的" [menu]="true" (menuTap)="drawerOpen.set(true)" />
@@ -181,6 +183,42 @@ import { MConfirmComponent } from '../../components/m-confirm/m-confirm';
               <i [class]="copied() ? 'fa-solid fa-check' : 'fa-solid fa-copy'" aria-hidden="true"></i>
             </button>
           </li>
+          <!--
+            关于与版本(2026-11-23 新增)
+            用户要求在「我的」页能看到版本号,并能点开查更新 ——
+            以前这里完全没有版本概念,装了什么版本自己都不知道。
+          -->
+          <li>
+            <button type="button" class="m-row" (click)="checkUpdateNow()" [disabled]="updating()">
+              <span class="m-row-body">
+                <span class="m-row-t1">关于与版本</span>
+                <span class="m-row-t2">
+                  @if (updating()) {
+                    正在检查更新…
+                  } @else if (updateTip()) {
+                    {{ updateTip() }}
+                  } @else if (update.hasUpdate()) {
+                    有新版本 {{ update.remote()?.version }} 可更新
+                  } @else {
+                    {{ versionText() }}
+                  }
+                </span>
+              </span>
+              @if (update.hasUpdate()) {
+                <span class="m-update-dot" aria-label="有新版本"></span>
+              } @else {
+                <i class="fa-solid fa-chevron-right m-chev" aria-hidden="true"></i>
+              }
+            </button>
+          </li>
+          <li>
+            <button type="button" class="m-row" (click)="logoutOpen.set(true)">
+              <span class="m-row-body">
+                <span class="m-row-t1 m-danger">退出登录</span>
+              </span>
+              <i class="fa-solid fa-chevron-right m-chev" aria-hidden="true"></i>
+            </button>
+          </li>
         </ul>
       </section>
 
@@ -191,6 +229,9 @@ import { MConfirmComponent } from '../../components/m-confirm/m-confirm';
       </div>
     </div>
 
+    <!-- 更新弹窗:有新版时自动弹出,也可由「关于与版本」手动唤起 -->
+    <app-update-dialog />
+
     <app-m-drawer [activeSessionId]="activeSessionId()"
       [open]="drawerOpen()" (close)="drawerOpen.set(false)" (newChat)="newChat()" (newChatWithWs)="onNewChatIn($event)" />
 
@@ -374,6 +415,20 @@ import { MConfirmComponent } from '../../components/m-confirm/m-confirm';
       .m-logout:active {
         background: var(--surface-hover);
       }
+      /*
+       * 有新版本时的红点(2026-11-23)
+       * 取代 chevron 的位置 —— 有红点时无需再提示「可进入」,
+       * 点进去就是要更新,语义更聚焦。
+       */
+      .m-update-dot {
+        flex: none;
+        width: 8px;
+        height: 8px;
+        border-radius: 50%;
+        background: #EF4444;
+        box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.16);
+      }
+
       .m-chev {
         color: var(--muted);
         font-size: var(--fs-12);
@@ -552,6 +607,39 @@ export class MbMinePage {
   protected readonly drawerOpen = signal(false);
   protected readonly logoutOpen = signal(false);
 
+  /**
+   * 版本与更新(2026-11-23 新增)
+   *
+   * 服务是 root 级单例,和弹窗组件共享同一个实例 ——
+   * 这里点了检查,弹窗那边立刻能感知到 hasUpdate 变化。
+   */
+  protected readonly update = inject(AppUpdateService);
+  protected readonly updating = this.update.checking;
+
+  /** 版本文案:本机版本 + 包名,方便反馈问题时一眼看出装的是哪个包 */
+  protected versionText(): string {
+    const v = this.update.local();
+    if (!v) return '未获取到版本信息';
+    return `v${v.versionName} (${v.versionCode})`;
+  }
+
+  /** 手动检查更新:查完有新版就由弹窗接管显示 */
+  protected async checkUpdateNow(): Promise<void> {
+    await this.update.check();
+    if (!this.update.hasUpdate() && !this.update.error()) {
+      /*
+       * 已是最新 —— 给个轻提示。
+       * 不用弹窗(太重),直接在行内文案上体现就够了,
+       * 用户点完看到「已是最新」自然明白。
+       */
+      this.updateTip.set('已是最新版本');
+      setTimeout(() => this.updateTip.set(null), 2000);
+    }
+  }
+
+  /** 「已是最新」的临时提示 */
+  protected readonly updateTip = signal<string | null>(null);
+
   protected readonly palettes = PALETTES;
   protected readonly fontMin = Math.min(...CHAT_FONT_SIZES);
   protected readonly fontMax = Math.max(...CHAT_FONT_SIZES);