diff --git a/.gitignore b/.gitignore
index 00b49e20..602f0a65 100644
--- a/.gitignore
+++ b/.gitignore
@@ -70,3 +70,18 @@ memory/
# Python byte-code from local scripts
__pycache__/
*.pyc
+
+# Roadshow decks and prompts: pitch material for one audience, not product docs.
+/微信流路演/
+/路演PPT提示词.md
+
+# Third-party signing library; save_video.py/sign.mjs fetch it from its origin
+# on first run, so the repository never redistributes someone else's code.
+shared/Skills/wechat-video-download/scripts/enc.js
+
+# Icon exploration rounds stay local; only the brief and the final masters ship.
+/design/chatbridge-icon/*
+!/design/chatbridge-icon/v3/
+/design/chatbridge-icon/v3/*
+!/design/chatbridge-icon/v3/brief.md
+!/design/chatbridge-icon/v3/final/
diff --git a/PRODUCT_CAPABILITIES.zh-CN.md b/PRODUCT_CAPABILITIES.zh-CN.md
index d1dfee90..d85d7a98 100644
--- a/PRODUCT_CAPABILITIES.zh-CN.md
+++ b/PRODUCT_CAPABILITIES.zh-CN.md
@@ -1,12 +1,12 @@
# 微信流(WeChatBridge)产品能力文档
-> 基于 main 分支当前代码整理
-> 平台:macOS 13 及以上
-> 文档日期:2026-09-20
+> 基于 v0.1.16 代码整理
+> 平台:macOS 13 及以上(本文只描述 macOS 版)
+> 文档日期:2026-11-24
## 1. 产品定义
-微信流是一个完全本地运行的 macOS 微信聊天记录转发与归档工具。它把微信“转发到其他应用”产生的 ZIP、TXT 和媒体文件,送到 Codex、Claude、豆包、千问办公、WorkBuddy、WeSight、Obsidian、其他应用或剪贴板。
+微信流是一个以本地接收和归档为基础的 macOS 微信聊天记录转发工具,可选接入云端技能。它把微信“转发到其他应用”产生的 ZIP、TXT 和媒体文件,送到 Codex、Claude、豆包、千问办公、WorkBuddy、WeSight、DeepSeek Harness、Obsidian、本地文件夹、其他应用或剪贴板。
核心价值:
@@ -177,7 +177,9 @@
### 8.2 网络
-- 除软件更新外不联网。
+- 默认本地转发与归档不上传整份聊天。
+- 用户启用云端账号/技能后,App 和签名 wcb 访问所配置服务。执行只提交经用户授权的必要输入;账号、目录、报价与授权元数据也会联网。
+- 目标 Agent 是独立的数据处理方,其保存行为不由微信流控制。
- 十二个 Share Extension 均在沙盒中运行。
- 扩展没有网络权限。
@@ -200,7 +202,7 @@
- 支持 Universal 2,即 `arm64` 和 `x86_64`。
- 使用 Developer ID Application 签名。
- App 和 DMG 支持 Apple 公证与 stapling。
-- 提供 DMG、Homebrew Cask、SHA-256 校验文件。
+- 提供 DMG 与 SHA-256 校验文件(Homebrew Cask 仍在路线图中)。
- 支持 Sparkle 更新源。
- MIT 许可证。
@@ -212,7 +214,7 @@
4. 自动粘贴依赖辅助功能权限、目标 App 可激活性和窗口焦点。
5. 场景识别群名依赖屏幕录制权限和微信标题栏可读性。
6. Codex/Claude 转发进入目标应用的输入区域,不等于官方 API 建场景。
-7. 不提供 Windows、iOS、Android 或云端版本。
+7. 本文只覆盖 macOS 版。Windows 版见 `windows/docs/`,iOS 版(信息桥)尚未正式发布,不提供 Android 版;云端技能是可选能力,默认不启用。
8. 不提供多设备同步、团队共享空间或服务端搜索。
## 11. 关键实现位置
@@ -221,7 +223,7 @@
|---|---|
| 十二个分享入口 | `macos/Scripts/share-slots.sh` |
| Share Extension 接入 | `macos/Sources/WeChatBridgeShare/ShareViewController.swift` |
-| 附件复制与命名 | `macos/Sources/WeChatBridgeShare/AttachmentImporter.swift` |
+| 附件复制与命名 | `macos/Sources/WeChatBridgeCore/AttachmentImporter.swift` |
| 目标应用定义 | `macos/Sources/WeChatBridgeCore/ShareAction.swift` |
| 自定义目标 | `macos/Sources/WeChatBridgeCore/ForwardTarget.swift` |
| 激活和自动粘贴 | `macos/Sources/WeChatBridgeApp/AutoPaste.swift` |
@@ -229,8 +231,10 @@
| 场景匹配与快捷键 | `macos/Sources/WeChatBridgeCore/Scene.swift`、`macos/Sources/WeChatBridgeApp/SceneShortcutController.swift` |
| 技能模型与安装 | `macos/Sources/WeChatBridgeCore/AgentID.swift`、`macos/Sources/WeChatBridgeApp/SkillLibrary.swift` |
| 技能页面 | `macos/Sources/WeChatBridgeApp/Views/Settings/SkillsPane.swift` |
-| Obsidian 投递 | `macos/Sources/WeChatBridgeApp/KnowledgeDelivery.swift`、`macos/Sources/WeChatBridgeCore/ObsidianNote.swift` |
+| Obsidian 投递 | `macos/Sources/WeChatBridgeCore/KnowledgeDelivery.swift`、`macos/Sources/WeChatBridgeCore/ObsidianNote.swift` |
| 批次状态 | `macos/Sources/WeChatBridgeCore/BatchState.swift` |
| 共享目录 | `macos/Sources/WeChatBridgeCore/Inbox.swift` |
+| 云端账号与付费技能(可选) | `macos/Sources/WeChatBridgeApp/CloudAccount.swift`、`macos/Sources/WeChatBridgeCore/Commerce.swift`、`macos/Sources/WeChatBridgeCore/SkillMonetization.swift` |
+| 命令行桥 wcb | `macos/Sources/wcb/main.swift` |
| App 打包和签名 | `macos/Scripts/make-app.sh` |
| 发布和公证 | `macos/Scripts/release.sh` |
diff --git a/README.md b/README.md
index 61a54f89..98991de3 100644
--- a/README.md
+++ b/README.md
@@ -2,10 +2,10 @@
WeChatBridge(微信流)
群里几百条消息没空翻?多选、转发,一步交给 AI 总结,或存进你的知识库。
- 在微信「转发到其他应用」里直接选 Codex、Claude、豆包、千问、Obsidian……不读数据库、不注入微信,全程本地。
+ 在微信「转发到其他应用」里直接选 Codex、Claude、豆包、千问、Obsidian……不读数据库、不注入微信,聊天记录默认留在本地,可选接入云端技能。
-
+
@@ -69,8 +69,9 @@
| --- | --- | --- |
| macOS 13+(Apple Silicon 与 Intel) | [wwbsr.lanzout.com/b0umjur8h](https://wwbsr.lanzout.com/b0umjur8h) | `向明` |
| Windows | [wwbsr.lanzout.com/b0umjur4d](https://wwbsr.lanzout.com/b0umjur4d) | `向明` |
+| Android 8.0+(`1.0.0-beta1`) | [wwbsr.lanzout.com/b0umpq8mj](https://wwbsr.lanzout.com/b0umpq8mj) | `向明` |
-macOS 版打开 DMG,把「微信流」拖入「应用程序」即可(图标带 🚫 或提示「无法验证」见[常见问题](USAGE.zh-CN.md#常见问题));Windows 版解压后按目录内说明运行。iOS 版正在开发中,进群可以第一时间知道进展。
+macOS 版打开 DMG,把「微信流」拖入「应用程序」即可(图标带 🚫 或提示「无法验证」见[常见问题](USAGE.zh-CN.md#常见问题));Windows 版解压后按目录内说明运行;Android 版(`1.0.0-beta1`,支持 Android 8.0 ~ Android 16,纯本地无联网权限)也可在 [GitHub Releases](https://github.com/freestylefly/WeChatBridge/releases/tag/v1.0.0-android-beta1) 下载,详情见 [android/README.md](android/README.md)。iOS 版正在开发中,进群可以第一时间知道进展。
## 加入交流群
@@ -188,7 +189,8 @@ flowchart LR
- 聊天内容只来自微信主动导出的文件。
- 不读取微信数据库,不解密、不注入、不修改微信进程。
-- 聊天归档、场景和记录保存在本机。
+- 聊天归档、场景和记录默认保存在本机。
+- 可选云端技能会访问用户配置的服务:账号、技能目录与执行授权需要联网;按量执行只提交用户授权的必要输入。
- Share Extension 在 macOS 沙盒中运行且没有网络权限。
- 屏幕录制权限只用于识别微信标题栏中的聊天名,图像仅在内存中处理。
- 辅助功能权限只用于激活目标应用和执行粘贴。
@@ -205,7 +207,7 @@ flowchart LR
苍何 |
-  |
+  |
 |
@@ -216,7 +218,7 @@ flowchart LR
### 从源码构建
-需要 macOS 14+,以及 Xcode 16 或兼容 Swift 6 的 Command Line Tools。
+构建需要 Xcode 16 或兼容 Swift 6 的 Command Line Tools(Xcode 16 本身要求 macOS 14.5+);构建出的 App 可在 macOS 13+ 运行。
```bash
git clone https://github.com/freestylefly/WeChatBridge.git
@@ -248,6 +250,9 @@ Scripts/dev-preview.sh # 构建、安装并打开开发
# Windows
dotnet test windows/WeChatBridge.Windows.sln -c Release
+
+# Android(需 JDK 21 与 Android SDK)
+bash android/scripts/verify.sh --release
```
@@ -265,6 +270,11 @@ macos/ # macOS 端 — 完整 SwiftPM 包
ios/ # iOS 端(开发中)— XcodeGen 工程,复用 WeChatBridgeCore
+android/ # Android 端(1.0.0-beta1)— Gradle / Jetpack Compose 工程
+├── core/ # 纯 Kotlin/JVM 核心逻辑(Inbox 契约、归档解析、场景与笔记导出)
+├── app/ # Android 主应用、分享接收、投递编排、悬浮球与快捷磁贴
+└── scripts/ # 一键构建、单测、lint 与权限白名单校验脚本
+
windows/ # Windows 端 — .NET WPF 解决方案
├── src/WeChatBridge.Windows/ # 主程序(WPF)
├── src/WeChatBridge.Windows.Core/ # Inbox 契约、投递、场景、技能(无 UI 依赖)
@@ -283,7 +293,7 @@ shared/ # 多端共用的资产与契约
site/ # Sparkle 更新源与版本说明
```
-项目使用 Swift Package Manager 管理 macOS 源码和 Sparkle 依赖。`macos/Scripts/make-app.sh` 会把主程序与十二个 Share Extension 组装成完整的 `.app`。iOS 侧见 `ios/project.yml`,Windows 侧见 `windows/AGENTS.md` 与 `windows/docs/README.zh-CN.md`。
+项目使用 Swift Package Manager 管理 macOS 源码和 Sparkle 依赖。`macos/Scripts/make-app.sh` 会把主程序与十二个 Share Extension 组装成完整的 `.app`。iOS 侧见 `ios/project.yml`,Windows 侧见 `windows/docs/README.zh-CN.md`。
@@ -308,6 +318,7 @@ site/ # Sparkle 更新源与版本说明
- [x] Universal 2 构建、签名与公证流程
- [x] 首个公开 DMG Release
- [x] Windows 版
+- [x] Android 版(`1.0.0-beta1`)
- [ ] iOS 版
- [ ] Homebrew Cask
- [ ] 更多社区场景和技能包
diff --git a/README_EN.md b/README_EN.md
index d8f438a4..090456fd 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -2,7 +2,7 @@
WeChatBridge (微信流)
Hundreds of unread group messages? Select, forward, and hand them to AI for a summary—or save them to your knowledge base.
- Pick Codex, Claude, Doubao, QwenWork, Obsidian, and more straight from WeChat's “Forward to other apps” menu. No database access, no injection into WeChat, fully local.
+ Pick Codex, Claude, Doubao, QwenWork, Obsidian, and more straight from WeChat's “Forward to other apps” menu. No database access, no injection into WeChat. Chats stay local by default, with optional cloud skills.
@@ -184,11 +184,12 @@ When collecting in batches, select each batch in WeChat and share it to “Colle
## Privacy by design
-Your conversations only move around on your own computer:
+By default your conversations stay on your own computer:
- Conversation content only comes from files explicitly exported by WeChat.
- The app does not read WeChat databases, decrypt data, inject code, or modify WeChat.
-- Archives, scenes, and history stay on your computer.
+- Archives, scenes, and history stay on your computer by default.
+- Optional cloud skills (in development) talk to a service you configure: accounts, the skill catalog and execution grants need the network, and metered runs submit only the inputs you authorize. Local archives are never uploaded in bulk, and cloud credentials are kept separate between the app and its signed `wcb` CLI.
- Every Share Extension runs inside the macOS sandbox without network access.
- Screen Recording is used only to recognize the chat name in WeChat's title bar; images are processed in memory.
- Accessibility is used only to activate a destination and perform the paste action.
@@ -203,7 +204,7 @@ For project updates and tips, follow our WeChat Official Account or add us on We
苍何 |
-  |
+  |
 |
@@ -214,7 +215,7 @@ For project updates and tips, follow our WeChat Official Account or add us on We
### Build from source
-Requires macOS 14+ and Xcode 16 or Command Line Tools with Swift 6 support.
+Building requires Xcode 16 or Command Line Tools with Swift 6 support (Xcode 16 itself needs macOS 14.5+); the built app runs on macOS 13+.
```bash
git clone https://github.com/freestylefly/WeChatBridge.git
@@ -263,7 +264,7 @@ shared/ # Agent logos, design assets, screenshots, demos, and
site/ # Sparkle update feed and release notes
```
-Swift Package Manager owns the macOS source layout and the Sparkle dependency. `macos/Scripts/make-app.sh` assembles the host executable and twelve Share Extensions into a complete `.app` bundle. For iOS see `ios/project.yml`; for Windows see `windows/AGENTS.md` and `windows/docs/README.zh-CN.md`.
+Swift Package Manager owns the macOS source layout and the Sparkle dependency. `macos/Scripts/make-app.sh` assembles the host executable and twelve Share Extensions into a complete `.app` bundle. For iOS see `ios/project.yml`; for Windows see `windows/docs/README.zh-CN.md`.
diff --git a/README_JA.md b/README_JA.md
index ef14d87c..535e7fdc 100644
--- a/README_JA.md
+++ b/README_JA.md
@@ -2,7 +2,7 @@
WeChatBridge (微信流)
グループの未読メッセージが何百件も? 選んで転送し、AI に要約を任せるか、ナレッジベースに保存しましょう。
- WeChat の「Forward to other apps」メニューから、Codex、Claude、Doubao、QwenWork、Obsidian などを直接選べます。データベースへのアクセスも、WeChat へのインジェクションもなく、すべてローカルで動きます。
+ WeChat の「Forward to other apps」メニューから、Codex、Claude、Doubao、QwenWork、Obsidian などを直接選べます。データベースへのアクセスも、WeChat へのインジェクションもありません。会話は既定でローカルにとどまり、クラウドスキルは任意で利用できます。
@@ -67,7 +67,7 @@ macOS 版 WeChat 4.1.13 以降が必要です。詳しい手順、権限、ト
| プラットフォーム | ダウンロード | パスワード |
| --- | --- | --- |
-| macOS 14+(Apple Silicon と Intel) | [wwbsr.lanzout.com/b0umjur8h](https://wwbsr.lanzout.com/b0umjur8h) | `向明` |
+| macOS 13+(Apple Silicon と Intel) | [wwbsr.lanzout.com/b0umjur8h](https://wwbsr.lanzout.com/b0umjur8h) | `向明` |
| Windows | [wwbsr.lanzout.com/b0umjur4d](https://wwbsr.lanzout.com/b0umjur4d) | `向明` |
macOS では、DMG を開いて WeChatBridge を「アプリケーション」にドラッグします。Windows では、アーカイブを展開して中の手順に従ってください。iOS 版は開発中です。グループに参加すると、いち早く情報を受け取れます。
@@ -176,11 +176,12 @@ flowchart LR
## プライバシーを考えた設計
-会話はあなた自身のコンピューターの中でしか移動しません:
+会話は既定であなた自身のコンピューターの中にとどまります:
- 会話の内容は、WeChat が明示的に書き出したファイルからしか取得しません。
- アプリは WeChat のデータベースを読んだり、データを復号したり、コードをインジェクションしたり、WeChat を改変したりしません。
-- アーカイブ、シーン、履歴はコンピューターの中にとどまります。
+- アーカイブ、シーン、履歴は既定でコンピューターの中にとどまります。
+- 任意のクラウドスキル(開発中)は、ユーザーが設定したサービスにアクセスします。アカウント、スキル一覧、実行の許可にはネットワークが必要で、従量制の実行では許可した入力だけを送信します。
- すべての Share Extension は、ネットワークにアクセスできない macOS のサンドボックス内で動きます。
- 画面収録は、WeChat のタイトルバーにあるチャット名を認識するためだけに使い、画像はメモリ内で処理します。
- アクセシビリティは、送り先を起動して貼り付けの操作を行うためだけに使います。
@@ -206,7 +207,7 @@ flowchart LR
### ソースからビルドする
-macOS 14+ と、Swift 6 に対応した Xcode 16 または Command Line Tools が必要です。
+ビルドには Swift 6 に対応した Xcode 16 または Command Line Tools が必要です(Xcode 16 自体は macOS 14.5+ が必要)。ビルドしたアプリは macOS 13+ で動作します。
```bash
git clone https://github.com/freestylefly/WeChatBridge.git
@@ -255,7 +256,7 @@ shared/ # Agent logos, design assets, screenshots, demos, and
site/ # Sparkle update feed and release notes
```
-macOS のソースの構成と Sparkle の依存関係は Swift Package Manager で管理しています。`macos/Scripts/make-app.sh` は、ホストの実行ファイルと 12 個の Share Extension を組み立てて、完全な `.app` バンドルにします。iOS については `ios/project.yml` を、Windows については `windows/AGENTS.md` と `windows/docs/README.zh-CN.md` を参照してください。
+macOS のソースの構成と Sparkle の依存関係は Swift Package Manager で管理しています。`macos/Scripts/make-app.sh` は、ホストの実行ファイルと 12 個の Share Extension を組み立てて、完全な `.app` バンドルにします。iOS については `ios/project.yml` を、Windows については `windows/docs/README.zh-CN.md` を参照してください。
diff --git a/android/.gitignore b/android/.gitignore
new file mode 100644
index 00000000..beb32c90
--- /dev/null
+++ b/android/.gitignore
@@ -0,0 +1,20 @@
+# Gradle / 构建产物
+.gradle/
+.kotlin/
+build/
+**/build/
+captures/
+.externalNativeBuild/
+.cxx/
+
+# 本机配置
+local.properties
+signing.properties
+keystore.properties
+*.keystore
+*.jks
+
+# IDE
+.idea/
+*.iml
+.DS_Store
diff --git a/android/README.md b/android/README.md
new file mode 100644
index 00000000..f8e59a02
--- /dev/null
+++ b/android/README.md
@@ -0,0 +1,61 @@
+# WeChatBridge(微信流)Android
+
+> **当前版本**:`1.0.0-beta1`(`versionCode = 1`)
+> **支持系统**:Android 8.0 ~ Android 16(`minSdk = 26`,`targetSdk = 35`,`compileSdk = 36`)
+> **安装包下载**:[蓝奏云直链](https://wwbsr.lanzout.com/b0umpq8mj)(提取密码:`向明`) · [GitHub Releases (`v1.0.0-android-beta1`)](https://github.com/freestylefly/WeChatBridge/releases/tag/v1.0.0-android-beta1)
+
+微信流 Android 版承接微信原生分享,让你在手机上把群聊记录、图片、文件一步整理并投递给常用 AI 应用或本地知识库(Obsidian / 文件夹),全程本地流转,**不申请网络权限**。
+
+## 核心能力
+
+- **微信原生分享接收**:在微信多选聊天记录 → 转发/更多 → 其他应用 → 选择「微信流」或「分批收集到微信流」,自动解析原生聊天 ZIP(含发言人、时间与图片附件);同时支持文件、相册多图、链接与剪贴板收入。
+- **分批收集**:超过单次转发上限时连续收多批,收齐后合并一次投递。
+- **AI 与知识库投递**:支持投递到 ChatGPT、Claude、Gemini、元宝、豆包、千问、DeepSeek、飞书、语雀、Obsidian 以及任意本地文件夹(SAF 导出为 Markdown 与附件)。
+- **场景提示词**:为不同群聊保存常用提示词,投递时一键附带。
+- **悬浮边缘条 & 快捷设置磁贴**:在其他应用上方随时展开暂存清单,支持拖拽填入、一键复制,以及可选的无障碍「一键填入」输入框(仅填入不自动发送)。
+- **双语界面**:完整支持简体中文与 English。
+
+## 隐私与权限边界
+
+APK 经过自动化脚本(`scripts/verify.sh --release`)与 `aapt2` 白名单校验,**不包含 `INTERNET` 权限**,也不申请通用存储或 `QUERY_ALL_PACKAGES` 权限:
+
+| 权限 | 用途 | 是否必需 |
+| --- | --- | --- |
+| `POST_NOTIFICATIONS` | 分批收集常驻通知与快捷投递通知(Android 13+ 运行时授权) | 可选 |
+| `SYSTEM_ALERT_WINDOW` | 悬浮边缘条与暂存面板显示在其他应用上层 | 仅开启悬浮球时需要 |
+| `FOREGROUND_SERVICE` / `FOREGROUND_SERVICE_SPECIAL_USE` | 保持用户主动开启的悬浮边缘条不被系统回收 | 仅开启悬浮球时需要 |
+| 无障碍服务(系统设置中手动开启) | 点击「填入」时将暂存内容写入当前应用输入框,绝不自动发送 | 可选 |
+
+## 从源码构建与验证
+
+环境要求:JDK 21(`verify.sh` 会自动探测 Zulu 21 / `JAVA_HOME`)与 Android SDK(`compileSdk = 36`)。
+
+```bash
+cd android
+
+# 运行 :core 单测、:app 单测、debug 构建与 Manifest 权限检查
+bash scripts/verify.sh
+
+# 构建 release APK(R8 压缩混淆)、lintRelease 并用 aapt2 校验权限白名单
+bash scripts/verify.sh --release
+```
+
+### Release 正式签名配置
+
+1. 复制 `keystore.properties.example` 为 `keystore.properties`(已被 `.gitignore` 忽略,切勿入库)。
+2. 填入你的 `.jks` 路径、别名与密码。
+3. 运行 `bash scripts/verify.sh --release`,产物输出至 `app/build/outputs/apk/release/app-release.apk`。
+
+> 未配置 `keystore.properties` 时,release 构建会退回使用 debug 签名,仅供本机测试,不可对外分发。
+
+## 模块结构
+
+```text
+android/
+├── core/ # 纯 Kotlin/JVM 核心逻辑(ZIP 解析、批次合并、场景、Markdown 导出),全量单测
+├── app/ # Jetpack Compose UI、分享接收、投递编排、悬浮球、快捷磁贴与无障碍填入
+├── scripts/ # verify.sh、真机 Intent 抓包与目标探测脚本
+└── keystore.properties.example
+```
+
+更多设计、验收与上架说明见 `docs/design/android-*.zh-CN.md`。
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts
new file mode 100644
index 00000000..6a47280d
--- /dev/null
+++ b/android/app/build.gradle.kts
@@ -0,0 +1,132 @@
+import java.util.Properties
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+
+// :app —— AGP 9 内置 Kotlin 支持,无需再应用 org.jetbrains.kotlin.android。
+plugins {
+ alias(libs.plugins.android.application)
+ alias(libs.plugins.kotlin.compose)
+ alias(libs.plugins.kotlin.serialization)
+}
+
+// release 签名:密钥只在本机 android/keystore.properties(git 忽略,模板见 keystore.properties.example)。
+// 文件不存在时 release 退回 debug 签名,只能本机测试,不能对外分发。
+val keystorePropertiesFile = rootProject.file("keystore.properties")
+val keystoreProperties: Properties? = keystorePropertiesFile.takeIf { it.isFile }?.let { file ->
+ Properties().apply { file.inputStream().use { load(it) } }
+}
+if (keystoreProperties == null &&
+ gradle.startParameter.taskNames.any { it.contains("release", ignoreCase = true) }
+) {
+ logger.warn("w: 未找到 keystore.properties,release 用 debug 签名,仅供本机测试")
+}
+
+android {
+ namespace = "com.xiangming.wechatbridge"
+ compileSdk = 36
+
+ defaultConfig {
+ applicationId = "com.xiangming.wechatbridge"
+ minSdk = 26
+ targetSdk = 35
+ versionCode = 1
+ versionName = "1.0.0-beta1"
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
+ }
+
+ signingConfigs {
+ if (keystoreProperties != null) {
+ create("release") {
+ storeFile = rootProject.file(keystoreProperties.getProperty("storeFile"))
+ storePassword = keystoreProperties.getProperty("storePassword")
+ keyAlias = keystoreProperties.getProperty("keyAlias")
+ keyPassword = keystoreProperties.getProperty("keyPassword")
+ }
+ }
+ }
+
+ buildTypes {
+ release {
+ isMinifyEnabled = true
+ isShrinkResources = true
+ signingConfig = signingConfigs.findByName("release") ?: signingConfigs.getByName("debug")
+ proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ buildFeatures {
+ compose = true
+ }
+
+ lint {
+ // values-en 已补齐(A4.8):缺译重新算 error,新增中文文案必须同时写英文。
+ error += "MissingTranslation"
+ }
+
+ testOptions {
+ unitTests.isIncludeAndroidResources = true
+ }
+}
+
+// R8 打开后 Compose 插件会额外拉 compose-group-mapping 生成混淆映射(只用于 Android Studio
+// 还原 Compose 组名);离线构建拿不到它,release 栈另有 mapping.txt,这里关掉。
+composeCompiler {
+ includeComposeMappingFile.set(false)
+}
+
+kotlin {
+ compilerOptions {
+ jvmTarget.set(JvmTarget.JVM_17)
+ }
+}
+
+// lint 规则类路径(只找依赖里打包的 lint.jar)不带 Android 平台属性,会把 material-icons-core
+// 解析成 -desktop 变体;该变体不含 lint 规则也不进 APK,离线缓存里没有,排除即可。
+configurations.matching { it.name.endsWith("LintChecksClasspath") }.configureEach {
+ exclude(group = "androidx.compose.material", module = "material-icons-core-desktop")
+}
+
+dependencies {
+ implementation(project(":core"))
+
+ implementation(libs.androidx.core.ktx)
+ implementation(libs.androidx.activity.compose)
+ implementation(libs.androidx.lifecycle.runtime.ktx)
+ implementation(libs.androidx.lifecycle.runtime.compose)
+ implementation(libs.androidx.lifecycle.viewmodel.compose)
+
+ implementation(platform(libs.androidx.compose.bom))
+ implementation(libs.androidx.compose.ui)
+ implementation(libs.androidx.compose.ui.graphics)
+ implementation(libs.androidx.compose.ui.tooling.preview)
+ implementation(libs.androidx.compose.material3)
+ implementation(libs.androidx.compose.material.icons.core)
+ implementation(libs.androidx.navigation.compose)
+
+ implementation(libs.androidx.datastore.preferences)
+ implementation(libs.coil.compose)
+ implementation(libs.kotlinx.serialization.json)
+ implementation(libs.kotlinx.coroutines.android)
+
+ debugImplementation(libs.androidx.compose.ui.tooling)
+ debugImplementation(libs.androidx.compose.ui.test.manifest)
+
+ testImplementation(libs.junit4)
+ testImplementation(libs.robolectric)
+ testImplementation(libs.androidx.test.core)
+ testImplementation(libs.kotlinx.coroutines.test)
+
+ // 中转站搜索栏的界面行为单测(Robolectric + Compose 语义树)。
+ testImplementation(platform(libs.androidx.compose.bom))
+ testImplementation(libs.androidx.compose.ui.test.junit4)
+
+ androidTestImplementation(platform(libs.androidx.compose.bom))
+ androidTestImplementation(libs.androidx.test.ext.junit)
+ androidTestImplementation(libs.androidx.test.runner)
+ androidTestImplementation(libs.androidx.test.espresso.core)
+ androidTestImplementation(libs.androidx.compose.ui.test.junit4)
+}
diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro
new file mode 100644
index 00000000..5a9ad666
--- /dev/null
+++ b/android/app/proguard-rules.pro
@@ -0,0 +1,47 @@
+# 微信流 release 的 R8 规则(A4.9)。
+# 依赖库(kotlinx.serialization 1.7+、DataStore、Compose、Coil、AndroidX)自带 consumer 规则;
+# 这里只补本项目自身需要的,以及对序列化的保守兜底——JSON 字段名要与 Mac / iOS 一致,
+# 混淆掉 @Serializable 类会导致跨端清单(manifest.json、state.json、scenes.json…)读写失败。
+
+# 崩溃栈可读:保留行号,源文件名统一成 SourceFile。
+-keepattributes SourceFile,LineNumberTable
+-renamesourcefileattribute SourceFile
+
+# ---- kotlinx.serialization(:core 与 :app 的 @Serializable 类)----
+-keepattributes *Annotation*, InnerClasses, Signature, Exceptions, EnclosingMethod
+-dontnote kotlinx.serialization.**
+
+# 生成的 $serializer 与 Companion.serializer()
+-keepclassmembers @kotlinx.serialization.Serializable class com.xiangming.wechatbridge.** {
+ static ** Companion;
+ static **$* *;
+ *** Companion;
+ kotlinx.serialization.KSerializer serializer(...);
+}
+-keepclassmembers class com.xiangming.wechatbridge.**$Companion {
+ kotlinx.serialization.KSerializer serializer(...);
+}
+-keep,includedescriptorclasses class com.xiangming.wechatbridge.**$$serializer { *; }
+# 枚举的 @SerialName 通过生成的描述符读取,保留枚举值名以防万一。
+-keepclassmembers enum com.xiangming.wechatbridge.** {
+ ;
+ public static **[] values();
+ public static ** valueOf(java.lang.String);
+}
+
+# ---- Manifest 组件:activity-alias 的 targetActivity、receiver、provider ----
+# AAPT 会为 Manifest 里的类生成 keep 规则;这里显式再写一遍,避免以后改成反射/字符串引用时漏掉。
+-keep class com.xiangming.wechatbridge.App { (); }
+-keep class com.xiangming.wechatbridge.MainActivity { (); }
+-keep class com.xiangming.wechatbridge.receive.ShareReceiverActivity { (); }
+-keep class com.xiangming.wechatbridge.deliver.ShareFileProvider { (); }
+-keep class com.xiangming.wechatbridge.notify.CollectActionReceiver { (); }
+
+# ---- DataStore Preferences ----
+# DataStore 的 protobuf-lite 实现靠字段名反射;库自带规则,这里兜底。
+-keepclassmembers class * extends androidx.datastore.preferences.protobuf.GeneratedMessageLite {
+ ;
+}
+
+# ---- Compose ----
+# Compose 运行时与 Material3 自带规则,无需额外配置。
diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml
new file mode 100644
index 00000000..2682348a
--- /dev/null
+++ b/android/app/src/debug/AndroidManifest.xml
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
diff --git a/android/app/src/debug/assets/fixtures/files-only.zip b/android/app/src/debug/assets/fixtures/files-only.zip
new file mode 100644
index 00000000..41fa009d
Binary files /dev/null and b/android/app/src/debug/assets/fixtures/files-only.zip differ
diff --git a/android/app/src/debug/assets/fixtures/group-a-later.zip b/android/app/src/debug/assets/fixtures/group-a-later.zip
new file mode 100644
index 00000000..4fd730e2
Binary files /dev/null and b/android/app/src/debug/assets/fixtures/group-a-later.zip differ
diff --git a/android/app/src/debug/assets/fixtures/group-a.zip b/android/app/src/debug/assets/fixtures/group-a.zip
new file mode 100644
index 00000000..2fc1e6ce
Binary files /dev/null and b/android/app/src/debug/assets/fixtures/group-a.zip differ
diff --git a/android/app/src/debug/assets/fixtures/interleave.zip b/android/app/src/debug/assets/fixtures/interleave.zip
new file mode 100644
index 00000000..14f99a98
Binary files /dev/null and b/android/app/src/debug/assets/fixtures/interleave.zip differ
diff --git a/android/app/src/debug/assets/fixtures/text-note.zip b/android/app/src/debug/assets/fixtures/text-note.zip
new file mode 100644
index 00000000..40f69765
Binary files /dev/null and b/android/app/src/debug/assets/fixtures/text-note.zip differ
diff --git a/android/app/src/debug/kotlin/com/xiangming/wechatbridge/debug/ProbeActivity.kt b/android/app/src/debug/kotlin/com/xiangming/wechatbridge/debug/ProbeActivity.kt
new file mode 100644
index 00000000..f3273cd1
--- /dev/null
+++ b/android/app/src/debug/kotlin/com/xiangming/wechatbridge/debug/ProbeActivity.kt
@@ -0,0 +1,190 @@
+package com.xiangming.wechatbridge.debug
+
+import androidx.activity.ComponentActivity
+import android.os.Bundle
+import android.util.Log
+import android.widget.ScrollView
+import android.widget.TextView
+import androidx.lifecycle.lifecycleScope
+import com.xiangming.wechatbridge.App
+import com.xiangming.wechatbridge.core.archive.WeChatArchive
+import com.xiangming.wechatbridge.core.deliver.BuiltInTargets
+import com.xiangming.wechatbridge.core.inbox.LoadStrategy
+import com.xiangming.wechatbridge.deliver.DeliveryRequest
+import com.xiangming.wechatbridge.deliver.Destination
+import com.xiangming.wechatbridge.deliver.DispatchResult
+import com.xiangming.wechatbridge.deliver.IntentDispatcher
+import com.xiangming.wechatbridge.deliver.OutgoingFile
+import com.xiangming.wechatbridge.deliver.PromptClipboard
+import com.xiangming.wechatbridge.deliver.ShareFileProvider
+import com.xiangming.wechatbridge.deliver.TargetResolver
+import com.xiangming.wechatbridge.receive.ImportOutcome
+import com.xiangming.wechatbridge.receive.ShareItem
+import kotlinx.coroutines.launch
+import java.io.File
+import java.io.InputStream
+
+/**
+ * Delivery probe, debug builds only (android-plan A0.5). Driven from adb:
+ *
+ * ```
+ * adb shell am start -n com.xiangming.wechatbridge/.debug.ProbeActivity \
+ * --es target chatgpt --es format zip --es fixture group-a.zip
+ * ```
+ *
+ * Send extras:
+ * - `target`: a built-in id (`chatgpt`, `claude`, `gemini`, …; `other` = chooser),
+ * or omit it and give `pkg` (+ optional `activity`) for any app.
+ * - `format`: `zip` (application/zip), `octet` (the ZIP as octet-stream),
+ * `txt` (the transcript file), `images` (the images, SEND_MULTIPLE image wildcard),
+ * `mixed` (TXT + images, SEND_MULTIPLE full wildcard), `inline` (transcript as EXTRA_TEXT).
+ * - `fixture`: a file in `assets/fixtures/` (default `group-a.zip`).
+ * - `prompt`: EXTRA_TEXT alongside the files, also copied to the clipboard.
+ * - `--ez chooser true`: skip straight to the system chooser.
+ *
+ * Import extras: `--es import ` takes `/`
+ * (push it to `/sdcard/Android/data/com.xiangming.wechatbridge/files/`) as
+ * one received share through `UriImporter`; `--ez collect true` for the
+ * collect entry.
+ *
+ * Every line is logged under tag `WBProbe`.
+ */
+class ProbeActivity : ComponentActivity() {
+ private lateinit var output: TextView
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ output = TextView(this).apply { setPadding(32, 96, 32, 32); textSize = 14f }
+ setContentView(ScrollView(this).apply { addView(output) })
+ if (savedInstanceState != null) return
+ run()
+ }
+
+ /** A second `am start` while the probe is on top lands here instead of onCreate. */
+ override fun onNewIntent(intent: android.content.Intent) {
+ super.onNewIntent(intent)
+ setIntent(intent)
+ output.text = ""
+ run()
+ }
+
+ private fun run() {
+ val importPath = intent.getStringExtra("import")
+ if (importPath != null) runImport(importPath, intent.getBooleanExtra("collect", false))
+ else runSend()
+ }
+
+ private fun log(line: String) {
+ Log.i(TAG, line)
+ output.append(line + "\n")
+ }
+
+ // MARK: send
+
+ private fun runSend() {
+ val targetId = intent.getStringExtra("target")
+ val pkg = intent.getStringExtra("pkg")
+ val format = intent.getStringExtra("format") ?: "zip"
+ val fixture = intent.getStringExtra("fixture") ?: "group-a.zip"
+ val prompt = intent.getStringExtra("prompt")
+ val forceChooser = intent.getBooleanExtra("chooser", false)
+
+ val destination: Destination = when {
+ forceChooser -> Destination.Chooser
+ pkg != null -> Destination.App(listOf(pkg), intent.getStringExtra("activity"))
+ targetId != null -> {
+ val profile = BuiltInTargets.byId(targetId) ?: return log("ERROR unknown target $targetId")
+ Destination.of(profile) ?: return log("ERROR target $targetId is a SAF writer, not an Intent target")
+ }
+ else -> return log("ERROR give --es target or --es pkg ")
+ }
+ log("send target=${targetId ?: pkg} format=$format fixture=$fixture destination=$destination")
+
+ val request = try {
+ prepare(format, fixture, prompt)
+ } catch (e: Exception) {
+ return log("ERROR preparing fixture: ${e.javaClass.simpleName}: ${e.message}")
+ }
+ log("files=${request.files.map { "${it.displayName ?: it.file.name} (${it.mimeType})" }} text=${request.text?.length ?: 0} chars")
+
+ if (prompt != null) log("clipboard: ${PromptClipboard(this).copy(prompt)}")
+
+ val result = IntentDispatcher(TargetResolver(this)).dispatch(this, request, destination)
+ log("RESULT $result")
+ if (result is DispatchResult.Sent) finish()
+ }
+
+ private fun prepare(format: String, fixture: String, prompt: String?): DeliveryRequest {
+ require(!fixture.contains('/')) { "fixture is a file name in assets/fixtures/" }
+ val dir = ShareFileProvider.newDeliveryDir(this, "probe-${System.currentTimeMillis()}")
+ val zip = File(dir, fixture)
+ assets.open("fixtures/$fixture").use { input -> zip.outputStream().use { input.copyTo(it) } }
+ if (format == "zip" || format == "octet") {
+ val mime = if (format == "zip") "application/zip" else "application/octet-stream"
+ return DeliveryRequest(listOf(OutgoingFile(zip, mime)), text = prompt)
+ }
+
+ val unpacked = File(dir, "unpacked").apply { mkdirs() }
+ val paths = WeChatArchive.extract(zip, unpacked)
+ val files = paths.map { File(unpacked, it) }.filter { it.isFile }
+ val txt = files.filter { it.extension.equals("txt", ignoreCase = true) }
+ val images = files.filter { imageMime(it) != null }
+ fun outgoingTxt() = txt.map { OutgoingFile(it, "text/plain") }
+ fun outgoingImages() = images.map { OutgoingFile(it, imageMime(it)!!) }
+ return when (format) {
+ "txt" -> DeliveryRequest(outgoingTxt(), text = prompt)
+ "images" -> DeliveryRequest(outgoingImages(), text = prompt)
+ "mixed" -> DeliveryRequest(outgoingTxt() + outgoingImages(), text = prompt)
+ "inline" -> {
+ val body = txt.joinToString("\n\n") { it.readText() }
+ DeliveryRequest(emptyList(), text = listOfNotNull(prompt, body).joinToString("\n\n"))
+ }
+ else -> throw IllegalArgumentException("unknown format $format")
+ }
+ }
+
+ private fun imageMime(file: File): String? = when (file.extension.lowercase()) {
+ "png" -> "image/png"
+ "jpg", "jpeg" -> "image/jpeg"
+ "gif" -> "image/gif"
+ "webp" -> "image/webp"
+ "heic" -> "image/heic"
+ else -> null
+ }
+
+ // MARK: import
+
+ private fun runImport(relative: String, collect: Boolean) {
+ val root = getExternalFilesDir(null) ?: return log("ERROR no external files dir")
+ val file = File(root, relative)
+ val inside = runCatching { file.canonicalPath.startsWith(root.canonicalPath + File.separator) }.getOrDefault(false)
+ if (!inside) return log("ERROR $relative is outside ${root.path}")
+ if (!file.isFile) return log("ERROR not a file: ${file.path}")
+ log("import ${file.name} (${file.length()} B) collect=$collect")
+
+ val item = object : ShareItem.Stream {
+ override val mimeType: String? = when (file.extension.lowercase()) {
+ "zip" -> "application/zip"
+ "txt" -> "text/plain"
+ else -> imageMime(file) ?: "application/octet-stream"
+ }
+ override val loadStrategy = LoadStrategy.FILE_URL
+ override fun displayName(): String = file.name
+ override fun open(): InputStream = file.inputStream()
+ }
+ val importer = (application as App).container.uriImporter
+ lifecycleScope.launch {
+ when (val outcome = importer.import(listOf(item), collect)) {
+ is ImportOutcome.Saved -> log(
+ "RESULT Saved batch=${outcome.batchId} items=${outcome.items.size} " +
+ "archives=${outcome.archives} records=${outcome.records.size} dir=${outcome.directory.path}",
+ )
+ is ImportOutcome.Failed -> log("RESULT Failed ${outcome.failure}")
+ }
+ }
+ }
+
+ private companion object {
+ const val TAG = "WBProbe"
+ }
+}
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
new file mode 100644
index 00000000..ca4853bd
--- /dev/null
+++ b/android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,236 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/App.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/App.kt
new file mode 100644
index 00000000..d9df766d
--- /dev/null
+++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/App.kt
@@ -0,0 +1,19 @@
+package com.xiangming.wechatbridge
+
+import android.app.Application
+import com.xiangming.wechatbridge.bubble.BubbleService
+import com.xiangming.wechatbridge.notify.CollectNotification
+
+class App : Application() {
+ lateinit var container: AppContainer
+ private set
+
+ override fun onCreate() {
+ super.onCreate()
+ container = AppContainer(this)
+ // 进行中的收集在进程重启后恢复常驻通知,之后通知跟着收集记录走。
+ CollectNotification.restore(this)
+ // 悬浮球开着且有悬浮窗权限:拉起前台服务(后台启动被系统拒绝时,下次回到前台再试)。
+ BubbleService.sync(this)
+ }
+}
diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/AppContainer.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/AppContainer.kt
new file mode 100644
index 00000000..7892240e
--- /dev/null
+++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/AppContainer.kt
@@ -0,0 +1,91 @@
+package com.xiangming.wechatbridge
+
+import android.content.Context
+import android.webkit.MimeTypeMap
+import androidx.core.content.pm.PackageInfoCompat
+import com.xiangming.wechatbridge.bubble.BubbleSettings
+import com.xiangming.wechatbridge.core.inbox.Inbox
+import com.xiangming.wechatbridge.data.Preferences
+import com.xiangming.wechatbridge.data.RelayStore
+import com.xiangming.wechatbridge.data.SceneStore
+import com.xiangming.wechatbridge.data.SummaryCache
+import com.xiangming.wechatbridge.receive.UriImporter
+import com.xiangming.wechatbridge.saf.TreeStore
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.first
+import java.io.File
+import com.xiangming.wechatbridge.deliver.Dispatch
+import com.xiangming.wechatbridge.deliver.IntentDispatch
+import com.xiangming.wechatbridge.deliver.IntentDispatcher
+import com.xiangming.wechatbridge.deliver.PromptClipboard
+import com.xiangming.wechatbridge.deliver.TargetResolver
+
+/**
+ * 手写依赖容器(不引入 Hilt / KSP)。
+ *
+ * 槽位由骨架任务 A0.2 一次预留;后续任务只在自己负责的槽位里填实现,
+ * 需要新增槽位时向主线执行者提出(见 android-plan §5.8)。
+ */
+class AppContainer(context: Context) {
+ val appContext: Context = context.applicationContext
+
+ /** Process-lifetime scope for work that must outlive screens (store loads, the undo timer). */
+ val appScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+
+ // data/ —— RelayStore:中转站批次读写(A2.1)。首次取用时加载并按保留天数清理一次。
+ val relayStore: RelayStore by lazy {
+ RelayStore(
+ inbox = inbox,
+ relayFilesRoot = File(appContext.cacheDir, "Relay"),
+ deliveriesDirectory = File(appContext.cacheDir, "deliveries"),
+ scope = appScope,
+ summaryCache = summaryCache,
+ ).also { store -> store.start { preferences.retentionDays.first() } }
+ }
+
+ // data/ —— Preferences:DataStore 偏好(目标顺序、隐藏、格式覆盖、最近目标、保留天数、引导)(A2.1)
+ val preferences: Preferences by lazy { Preferences.create(appContext) }
+
+ // data/ —— SummaryCache:卡片摘要缓存(与 iOS 一致,放在批次目录的 relay-cache.json)(A2.1)
+ val summaryCache: SummaryCache by lazy { SummaryCache() }
+
+ // receive/ —— Inbox:/inbox(staging / ready / diagnostics,android-plan §3.3)(A1.10)
+ val inbox: Inbox by lazy { Inbox(File(appContext.filesDir, "inbox")) }
+
+ // receive/ —— UriImporter:接收分享并写入 staging(A1.10)
+ val uriImporter: UriImporter by lazy {
+ UriImporter(
+ inbox = inbox,
+ buildVersion = buildVersion(),
+ extensionLookup = { MimeTypeMap.getSingleton().getExtensionFromMimeType(it) },
+ )
+ }
+
+ /** versionCode, like iOS CFBundleVersion in diagnostics; "?" when unreadable. */
+ private fun buildVersion(): String = runCatching {
+ @Suppress("DEPRECATION")
+ val info = appContext.packageManager.getPackageInfo(appContext.packageName, 0)
+ PackageInfoCompat.getLongVersionCode(info).toString()
+ }.getOrDefault("?")
+
+ // deliver/ —— TargetResolver / IntentDispatcher:投递目标与 Intent 发送(A3.x)
+ val targetResolver: TargetResolver by lazy { TargetResolver(appContext) }
+ val intentDispatcher: IntentDispatcher by lazy { IntentDispatcher(targetResolver) }
+ val promptClipboard: PromptClipboard by lazy { PromptClipboard(appContext) }
+
+ /** What DeliverViewModel sends through; replaceable in tests (A3.4). */
+ val dispatch: Dispatch by lazy { IntentDispatch(intentDispatcher) }
+
+ // saf/ —— TreeStore:Obsidian 库与默认文件夹的 SAF 目录、持久授权与失效检测(A4.1)
+ // 读写走 ContentResolver:调用方在 IO 线程上用。
+ val treeStore: TreeStore by lazy { TreeStore.create(appContext) }
+
+ // scene/ —— 场景与群记忆存储(/scenes.json、group-memories.json,JSON 与 iOS 一致)(A3.4)
+ // 首次读文件发生在第一次调用时;调用方在 IO 线程上用。
+ val sceneStore: SceneStore by lazy { SceneStore(appContext.filesDir) }
+
+ // bubble/ —— 悬浮球开关与位置(SharedPreferences,接收入口和 App 启动时同步读)
+ val bubbleSettings: BubbleSettings by lazy { BubbleSettings(appContext) }
+}
diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/AppNav.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/AppNav.kt
new file mode 100644
index 00000000..66c86c8f
--- /dev/null
+++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/AppNav.kt
@@ -0,0 +1,487 @@
+package com.xiangming.wechatbridge
+
+import androidx.annotation.StringRes
+import androidx.compose.animation.AnimatedContentTransitionScope
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.EnterTransition
+import androidx.compose.animation.ExitTransition
+import androidx.compose.animation.animateColorAsState
+import androidx.compose.animation.core.animateDpAsState
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.tween
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.scaleIn
+import androidx.compose.animation.scaleOut
+import androidx.compose.animation.slideInVertically
+import androidx.compose.animation.slideOutVertically
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.asPaddingValues
+import androidx.compose.foundation.layout.navigationBars
+import androidx.compose.foundation.layout.defaultMinSize
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.Icon
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.staticCompositionLocalOf
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.selected
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.navigation.NavBackStackEntry
+import androidx.navigation.NavHostController
+import androidx.navigation.NavType
+import androidx.navigation.compose.NavHost
+import androidx.navigation.compose.composable
+import androidx.navigation.compose.currentBackStackEntryAsState
+import androidx.navigation.compose.rememberNavController
+import androidx.navigation.navArgument
+import com.xiangming.wechatbridge.receive.DeliverLaunch
+import com.xiangming.wechatbridge.ui.collection.CollectionScreen
+import com.xiangming.wechatbridge.ui.deliver.DeliverScreen
+import com.xiangming.wechatbridge.ui.detail.DetailScreen
+import com.xiangming.wechatbridge.ui.onboarding.OnboardingScreen
+import com.xiangming.wechatbridge.ui.relay.RelayScreen
+import com.xiangming.wechatbridge.ui.scenes.ScenesScreen
+import com.xiangming.wechatbridge.ui.settings.SettingsScreen
+import com.xiangming.wechatbridge.ui.settings.TargetsScreen
+import com.xiangming.wechatbridge.ui.theme.AppIcons
+import com.xiangming.wechatbridge.ui.theme.AppMotion
+import com.xiangming.wechatbridge.ui.theme.BridgeBottomBarScrim
+import com.xiangming.wechatbridge.ui.theme.BridgeGlassSurface
+import com.xiangming.wechatbridge.ui.theme.LocalAppColors
+import com.xiangming.wechatbridge.ui.theme.pressScale
+
+/**
+ * 全部路由与底部 3 Tab 导航壳。
+ */
+object Routes {
+ const val RELAY = "relay"
+ const val DETAIL = "detail/{batchId}"
+ const val DELIVER = "deliver/{batchIds}"
+ const val SCENES = "scenes"
+ const val SETTINGS = "settings"
+ const val TARGETS = "settings/targets"
+ const val ONBOARDING = "onboarding"
+ const val COLLECTION = "collection/{id}"
+
+ const val ARG_BATCH_ID = "batchId"
+ const val ARG_BATCH_IDS = "batchIds"
+ const val ARG_COLLECTION_ID = "id"
+
+ /** 批次 ID 是 UUID,不含逗号,用逗号连接多个。 */
+ private const val ID_SEPARATOR = ","
+
+ fun detail(batchId: String) = "detail/$batchId"
+ fun deliver(batchIds: List) = "deliver/" + batchIds.joinToString(ID_SEPARATOR)
+ fun collection(id: String) = "collection/$id"
+
+ fun parseBatchIds(raw: String?): List =
+ raw.orEmpty().split(ID_SEPARATOR).filter { it.isNotBlank() }
+}
+
+private val TopLevelRoutes = setOf(Routes.RELAY, Routes.SCENES, Routes.SETTINGS)
+
+private data class BottomTabItem(
+ val route: String,
+ @param:StringRes val labelRes: Int,
+ val icon: ImageVector,
+)
+
+private val BottomTabs = listOf(
+ BottomTabItem(Routes.RELAY, R.string.nav_relay, AppIcons.NavRelay),
+ BottomTabItem(Routes.SCENES, R.string.nav_scenes, AppIcons.NavScenes),
+ BottomTabItem(Routes.SETTINGS, R.string.nav_settings, AppIcons.NavSettings),
+)
+
+/**
+ * The target the delivery panel should preselect when it was opened by
+ * 「投给上次目标」 (a [DeliverLaunch]); null otherwise. Provided around
+ * `DeliverScreen`, which passes it to `DeliverViewModel.create(initialTargetId = ...)`.
+ */
+val LocalInitialTargetId = staticCompositionLocalOf { null }
+
+/** Key in the deliver entry's SavedStateHandle, so the preselection survives recreation. */
+private const val INITIAL_TARGET_KEY = "initialTargetId"
+
+@Composable
+fun AppNav(
+ container: AppContainer,
+ navController: NavHostController = rememberNavController(),
+ startDestination: String = Routes.RELAY,
+ /** Open the delivery panel on arrival (receipt 「投给上次目标」); [onLaunchConsumed] then clears it. */
+ launch: DeliverLaunch? = null,
+ onLaunchConsumed: () -> Unit = {},
+) {
+ if (launch != null) {
+ LaunchedEffect(launch) {
+ navController.navigate(Routes.deliver(launch.batchIds)) { launchSingleTop = true }
+ navController.currentBackStackEntry?.savedStateHandle?.set(INITIAL_TARGET_KEY, launch.targetId)
+ onLaunchConsumed()
+ }
+ }
+
+ val backStackEntry by navController.currentBackStackEntryAsState()
+ val currentRoute = backStackEntry?.destination?.route
+ val showBottomBar = currentRoute in TopLevelRoutes
+
+ val entries by container.relayStore.entries.collectAsStateWithLifecycle()
+ val undeliveredCount = remember(entries) { entries.count { !it.isDelivered } }
+
+ fun switchTab(route: String) {
+ if (navController.currentDestination?.route == route) return
+ if (route == Routes.RELAY) {
+ if (navController.popBackStack(Routes.RELAY, inclusive = false)) return
+ navController.navigate(Routes.RELAY) {
+ launchSingleTop = true
+ }
+ return
+ }
+ navController.navigate(route) {
+ popUpTo(Routes.RELAY) {
+ saveState = true
+ }
+ launchSingleTop = true
+ restoreState = true
+ }
+ }
+
+ Box(modifier = Modifier.fillMaxSize()) {
+ NavHost(
+ navController = navController,
+ startDestination = startDestination,
+ modifier = Modifier.fillMaxSize(),
+ ) {
+ composable(
+ route = Routes.RELAY,
+ enterTransition = { topLevelEnter() },
+ exitTransition = { topLevelExit() },
+ popEnterTransition = { topLevelPopEnter() },
+ popExitTransition = { topLevelPopExit() },
+ ) {
+ RelayScreen(
+ onOpenBatch = { navController.navigate(Routes.detail(it)) },
+ onDeliver = { navController.navigate(Routes.deliver(it)) },
+ onOpenCollection = { navController.navigate(Routes.collection(it)) },
+ onOpenScenes = { switchTab(Routes.SCENES) },
+ onOpenSettings = { switchTab(Routes.SETTINGS) },
+ )
+ }
+ composable(
+ route = Routes.DETAIL,
+ arguments = listOf(navArgument(Routes.ARG_BATCH_ID) { type = NavType.StringType }),
+ enterTransition = { AppMotion.pushEnter },
+ exitTransition = {
+ if (targetState.destination.route == Routes.DELIVER) ExitTransition.None else AppMotion.pushExit
+ },
+ popEnterTransition = {
+ if (initialState.destination.route == Routes.DELIVER) EnterTransition.None else AppMotion.popEnter
+ },
+ popExitTransition = { AppMotion.popExit },
+ ) { entry ->
+ DetailScreen(
+ batchId = entry.arguments?.getString(Routes.ARG_BATCH_ID).orEmpty(),
+ onBack = { navController.popBackStack() },
+ onDeliver = { navController.navigate(Routes.deliver(listOf(it))) },
+ )
+ }
+ composable(
+ route = Routes.DELIVER,
+ arguments = listOf(navArgument(Routes.ARG_BATCH_IDS) { type = NavType.StringType }),
+ enterTransition = { AppMotion.sheetEnter },
+ exitTransition = { AppMotion.sheetExit },
+ popEnterTransition = { AppMotion.sheetEnter },
+ popExitTransition = { AppMotion.sheetExit },
+ ) { entry ->
+ CompositionLocalProvider(
+ LocalInitialTargetId provides entry.savedStateHandle.get(INITIAL_TARGET_KEY),
+ ) {
+ DeliverScreen(
+ batchIds = Routes.parseBatchIds(entry.arguments?.getString(Routes.ARG_BATCH_IDS)),
+ onBack = { navController.popBackStack() },
+ onDone = { navController.popBackStack(Routes.RELAY, inclusive = false) },
+ )
+ }
+ }
+ composable(
+ route = Routes.SCENES,
+ enterTransition = { topLevelEnter() },
+ exitTransition = { topLevelExit() },
+ popEnterTransition = { topLevelPopEnter() },
+ popExitTransition = { topLevelPopExit() },
+ ) {
+ ScenesScreen(onBack = { switchTab(Routes.RELAY) })
+ }
+ composable(
+ route = Routes.SETTINGS,
+ enterTransition = { topLevelEnter() },
+ exitTransition = { topLevelExit() },
+ popEnterTransition = { topLevelPopEnter() },
+ popExitTransition = { topLevelPopExit() },
+ ) {
+ SettingsScreen(
+ onBack = { switchTab(Routes.RELAY) },
+ onOpenScenes = { switchTab(Routes.SCENES) },
+ onOpenOnboarding = { navController.navigate(Routes.ONBOARDING) },
+ onOpenTargets = { navController.navigate(Routes.TARGETS) },
+ )
+ }
+ composable(
+ route = Routes.TARGETS,
+ enterTransition = { AppMotion.pushEnter },
+ exitTransition = { AppMotion.pushExit },
+ popEnterTransition = { AppMotion.popEnter },
+ popExitTransition = { AppMotion.popExit },
+ ) {
+ TargetsScreen(onBack = { navController.popBackStack() })
+ }
+ composable(
+ route = Routes.ONBOARDING,
+ enterTransition = { AppMotion.pushEnter },
+ exitTransition = { AppMotion.pushExit },
+ popEnterTransition = { AppMotion.popEnter },
+ popExitTransition = { AppMotion.popExit },
+ ) {
+ OnboardingScreen(
+ onFinish = {
+ // 从设置里重开的引导:回到设置;首装的引导:换成中转站。
+ if (navController.previousBackStackEntry != null) {
+ navController.popBackStack()
+ return@OnboardingScreen
+ }
+ navController.navigate(Routes.RELAY) {
+ popUpTo(Routes.ONBOARDING) { inclusive = true }
+ launchSingleTop = true
+ }
+ },
+ )
+ }
+ composable(
+ route = Routes.COLLECTION,
+ arguments = listOf(navArgument(Routes.ARG_COLLECTION_ID) { type = NavType.StringType }),
+ enterTransition = { AppMotion.pushEnter },
+ exitTransition = {
+ if (targetState.destination.route == Routes.DELIVER) ExitTransition.None else AppMotion.pushExit
+ },
+ popEnterTransition = {
+ if (initialState.destination.route == Routes.DELIVER) EnterTransition.None else AppMotion.popEnter
+ },
+ popExitTransition = { AppMotion.popExit },
+ ) { entry ->
+ CollectionScreen(
+ collectionId = entry.arguments?.getString(Routes.ARG_COLLECTION_ID).orEmpty(),
+ onBack = { navController.popBackStack() },
+ onDeliver = { navController.navigate(Routes.deliver(it)) },
+ )
+ }
+ }
+
+ if (showBottomBar) {
+ val navBottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()
+ BridgeBottomBarScrim(
+ height = 100.dp + navBottom,
+ modifier = Modifier.align(Alignment.BottomCenter),
+ )
+ }
+ AnimatedVisibility(
+ visible = showBottomBar,
+ enter = slideInVertically(tween(AppMotion.PAGE_SLIDE_MS)) { it } + fadeIn(tween(150)),
+ exit = slideOutVertically(tween(200)) { it } + fadeOut(tween(120)),
+ modifier = Modifier
+ .align(Alignment.BottomCenter)
+ .navigationBarsPadding()
+ .padding(horizontal = 24.dp, vertical = 10.dp),
+ ) {
+ AppBottomBar(
+ currentRoute = currentRoute,
+ undeliveredCount = undeliveredCount,
+ onSelect = { switchTab(it) },
+ )
+ }
+ }
+}
+
+private fun AnimatedContentTransitionScope.topLevelEnter(): EnterTransition =
+ if (initialState.destination.route in TopLevelRoutes) AppMotion.tabEnter else AppMotion.popEnter
+
+private fun AnimatedContentTransitionScope.topLevelExit(): ExitTransition =
+ when (targetState.destination.route) {
+ in TopLevelRoutes -> AppMotion.tabExit
+ Routes.DELIVER -> ExitTransition.None
+ else -> AppMotion.pushExit
+ }
+
+private fun AnimatedContentTransitionScope.topLevelPopEnter(): EnterTransition =
+ when (initialState.destination.route) {
+ in TopLevelRoutes -> AppMotion.tabEnter
+ Routes.DELIVER -> EnterTransition.None
+ else -> AppMotion.popEnter
+ }
+
+private fun AnimatedContentTransitionScope.topLevelPopExit(): ExitTransition =
+ if (targetState.destination.route in TopLevelRoutes) AppMotion.tabExit else AppMotion.popExit
+
+@Composable
+private fun AppBottomBar(
+ currentRoute: String?,
+ undeliveredCount: Int,
+ onSelect: (String) -> Unit,
+) {
+ BridgeGlassSurface(
+ shape = CircleShape,
+ shadowElevation = 14.dp,
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(64.dp),
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(horizontal = 8.dp, vertical = 5.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ for (tab in BottomTabs) {
+ val isSelected = currentRoute == tab.route
+ val badgeCount = if (tab.route == Routes.RELAY) undeliveredCount else 0
+ BottomTabButton(
+ tab = tab,
+ selected = isSelected,
+ badgeCount = badgeCount,
+ onClick = { onSelect(tab.route) },
+ modifier = Modifier.weight(1f),
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun BottomTabButton(
+ tab: BottomTabItem,
+ selected: Boolean,
+ badgeCount: Int,
+ onClick: () -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ val appColors = LocalAppColors.current
+ val interactionSource = remember { MutableInteractionSource() }
+ val contentColor by animateColorAsState(
+ targetValue = if (selected) MaterialTheme.colorScheme.primary else appColors.onSurfaceMuted,
+ animationSpec = tween(160),
+ label = "tabColor",
+ )
+ val pillWidth by animateDpAsState(
+ targetValue = if (selected) 56.dp else 20.dp,
+ animationSpec = AppMotion.snappySpring(),
+ label = "tabPillWidth",
+ )
+ val pillAlpha by animateFloatAsState(
+ targetValue = if (selected) 1f else 0f,
+ animationSpec = tween(150),
+ label = "tabPillAlpha",
+ )
+ val label = stringResource(tab.labelRes)
+
+ Column(
+ modifier = modifier
+ .fillMaxHeight()
+ .clickable(
+ interactionSource = interactionSource,
+ indication = null,
+ role = Role.Tab,
+ onClick = onClick,
+ )
+ .semantics { this.selected = selected }
+ .pressScale(interactionSource, targetScale = 0.94f),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.Center,
+ ) {
+ Box(
+ modifier = Modifier.height(30.dp),
+ contentAlignment = Alignment.Center,
+ ) {
+ Box(
+ modifier = Modifier
+ .width(pillWidth)
+ .height(30.dp)
+ .alpha(pillAlpha)
+ .clip(CircleShape)
+ .background(appColors.primarySoft),
+ )
+ Icon(
+ imageVector = tab.icon,
+ contentDescription = null,
+ tint = contentColor,
+ modifier = Modifier.size(21.dp),
+ )
+ androidx.compose.animation.AnimatedVisibility(
+ visible = badgeCount > 0,
+ enter = scaleIn(AppMotion.playfulSpring()) + fadeIn(tween(120)),
+ exit = scaleOut(tween(120)) + fadeOut(tween(120)),
+ modifier = Modifier
+ .align(Alignment.TopEnd)
+ .offset(x = 12.dp, y = (-2).dp),
+ ) {
+ Box(
+ modifier = Modifier
+ .defaultMinSize(minWidth = 16.dp, minHeight = 16.dp)
+ .clip(CircleShape)
+ .background(MaterialTheme.colorScheme.primary)
+ .padding(horizontal = 4.dp),
+ contentAlignment = Alignment.Center,
+ ) {
+ Text(
+ text = if (badgeCount > 99) "99+" else badgeCount.toString(),
+ color = MaterialTheme.colorScheme.onPrimary,
+ fontSize = 10.sp,
+ lineHeight = 12.sp,
+ fontWeight = FontWeight.SemiBold,
+ maxLines = 1,
+ )
+ }
+ }
+ }
+ Spacer(Modifier.height(2.dp))
+ Text(
+ text = label,
+ style = MaterialTheme.typography.labelSmall,
+ fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal,
+ color = contentColor,
+ maxLines = 1,
+ )
+ }
+}
diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/MainActivity.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/MainActivity.kt
new file mode 100644
index 00000000..66581803
--- /dev/null
+++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/MainActivity.kt
@@ -0,0 +1,110 @@
+package com.xiangming.wechatbridge
+
+import android.content.Intent
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.activity.enableEdgeToEdge
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Surface
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.produceState
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Modifier
+import androidx.lifecycle.DefaultLifecycleObserver
+import androidx.lifecycle.LifecycleOwner
+import androidx.lifecycle.lifecycleScope
+import com.xiangming.wechatbridge.bubble.BubbleService
+import com.xiangming.wechatbridge.notify.CollectNotification
+import com.xiangming.wechatbridge.notify.QuickDeliverNotification
+import com.xiangming.wechatbridge.receive.ActivityDropPermissions
+import com.xiangming.wechatbridge.receive.DeliverLaunch
+import com.xiangming.wechatbridge.receive.DropReceiver
+import com.xiangming.wechatbridge.ui.drop.DropHost
+import com.xiangming.wechatbridge.ui.drop.LocalDropHost
+import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme
+
+class MainActivity : ComponentActivity() {
+ /** A 「投给上次目标」 request not yet acted on; cleared once AppNav has navigated. */
+ private val pendingLaunch = mutableStateOf(null)
+
+ /**
+ * Drops from other apps (small window, split screen). Scoped to this
+ * Activity: the URI grants end with it, so a copy still running when it is
+ * destroyed is cancelled and its staging discarded.
+ */
+ private val dropHost: DropHost by lazy {
+ val container = (application as App).container
+ DropHost(
+ receiver = DropReceiver(
+ importer = container.uriImporter,
+ scope = lifecycleScope,
+ reload = container.relayStore::reload,
+ joinCollection = container.relayStore::joinCollection,
+ onCollected = { CollectNotification.sync(application, container.relayStore) },
+ ),
+ permissions = ActivityDropPermissions(this),
+ context = this,
+ )
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ enableEdgeToEdge()
+ val container = (application as App).container
+ // A recreated Activity has its back stack restored; the request was handled already.
+ if (savedInstanceState == null) pendingLaunch.value = DeliverLaunch.parse(intent)?.let(::consume)
+ // Pick up batches received while away; commit a pending delete before
+ // the process can be killed, or it would come back.
+ lifecycle.addObserver(object : DefaultLifecycleObserver {
+ override fun onStart(owner: LifecycleOwner) {
+ container.relayStore.refresh()
+ // In front now, so a bubble start the system refused from the background goes through.
+ BubbleService.sync(this@MainActivity)
+ }
+ override fun onStop(owner: LifecycleOwner) = container.relayStore.flushDeletion()
+ })
+ setContent {
+ WeChatBridgeTheme {
+ // 首装先走引导;读偏好要一点时间,读完前只画背景,免得中转站闪一下。
+ // 带着投递请求进来(通知、收据卡)时直接去投递,不拦引导。
+ val onboardingDone by produceState(null) {
+ value = runCatching { container.preferences.current().onboardingDone }.getOrDefault(true)
+ }
+ when (val done = onboardingDone) {
+ null -> Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {}
+ else -> CompositionLocalProvider(LocalDropHost provides dropHost) {
+ AppNav(
+ container = container,
+ startDestination = remember {
+ if (done || pendingLaunch.value != null) Routes.RELAY else Routes.ONBOARDING
+ },
+ launch = pendingLaunch.value,
+ onLaunchConsumed = { pendingLaunch.value = null },
+ )
+ }
+ }
+ }
+ }
+ }
+
+ /** singleTask: a receipt tap while the app is open arrives here. */
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ setIntent(intent)
+ DeliverLaunch.parse(intent)?.let { pendingLaunch.value = consume(it) }
+ }
+
+ /**
+ * Dismisses the quick-deliver notification and marks the batches used. A
+ * relaunch from recents (nothing first-time) opens the panel without
+ * preselecting the target, so it never sends twice.
+ */
+ private fun consume(launch: DeliverLaunch): DeliverLaunch {
+ val fresh = QuickDeliverNotification.onLaunched(this, launch)
+ return if (fresh.isEmpty() && launch.targetId != null) launch.copy(targetId = null) else launch
+ }
+}
diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleDrag.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleDrag.kt
new file mode 100644
index 00000000..3d21654d
--- /dev/null
+++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleDrag.kt
@@ -0,0 +1,150 @@
+package com.xiangming.wechatbridge.bubble
+
+import android.view.WindowManager
+import com.xiangming.wechatbridge.core.deliver.DeliveryFormat
+import com.xiangming.wechatbridge.core.deliver.DeliveryPlanException
+import com.xiangming.wechatbridge.core.deliver.DeliveryPlanner
+import com.xiangming.wechatbridge.core.deliver.Evidence
+import com.xiangming.wechatbridge.core.deliver.TargetKind
+import com.xiangming.wechatbridge.core.deliver.TargetProfile
+import com.xiangming.wechatbridge.core.scene.GroupName
+import com.xiangming.wechatbridge.core.scene.ScenePrompt
+import com.xiangming.wechatbridge.core.summary.RelaySummary
+import com.xiangming.wechatbridge.core.summary.ShareOrigin
+import com.xiangming.wechatbridge.core.transcript.BatchInsights
+import com.xiangming.wechatbridge.data.RelayEntry
+import com.xiangming.wechatbridge.data.SceneStore
+import com.xiangming.wechatbridge.deliver.SceneBinding
+import java.io.File
+import java.time.ZoneId
+import com.xiangming.wechatbridge.core.deliver.DeliveryRequest as PlanRequest
+
+/** What a long press on a staged row (or 「全部合并投递」) can drag out. */
+sealed interface DragText {
+ data class Ready(val text: String) : DragText
+
+ /** Only attachments: nothing readable to drop into an input box. */
+ data object NoText : DragText
+
+ /** Over [DeliveryPlanner.INLINE_TEXT_LIMIT], where delivery would send a file instead. */
+ data object TooLarge : DragText
+
+ /** Reading the batch failed. */
+ data object Failed : DragText
+}
+
+/**
+ * The text a drag (or the row's copy button) carries: exactly what the
+ * delivery panel puts in `EXTRA_TEXT` on the inline-text route — the scene
+ * prompt, a blank line, then [DeliveryPlanner]'s inline body (one transcript,
+ * several merged by time, or a shared text / link note as it is).
+ */
+object BubbleDragText {
+ /**
+ * A text-only target for [DeliveryPlanner]: inline text, no images. Never
+ * shown or sent to; it only selects the route.
+ */
+ internal val TEXT_ONLY = TargetProfile(
+ id = "bubble-drag",
+ displayNameKey = null,
+ kind = TargetKind.CHOOSER,
+ formats = listOf(DeliveryFormat.INLINE_TEXT),
+ formatEvidence = Evidence.DECLARED,
+ )
+
+ /**
+ * Known to hold nothing readable: summarized as plain files (no
+ * transcript) and no shared text / link note. A batch not summarized yet
+ * is not judged here; [build] finds out.
+ */
+ fun isTextless(entry: RelayEntry): Boolean {
+ if (entry.batch.items.isEmpty()) return true
+ val summary = entry.summary ?: return false
+ if (summary.kind != RelaySummary.Kind.FILES) return false
+ return entry.batch.items.none { it.contentType == ShareOrigin.NOTE_CONTENT_TYPE }
+ }
+
+ /** Every one textless: say so without starting a drag. */
+ fun allTextless(entries: List): Boolean = entries.all(::isTextless)
+
+ /** 「全部合并投递」's order: oldest first, as [BubbleStaging.mergeIds]. */
+ fun mergeOrder(staged: List): List = staged.sortedBy { it.batch.createdAt }
+
+ /** The delivery panel's `EXTRA_TEXT`: prompt (trimmed, if any), a blank line, the body. */
+ fun join(prompt: String?, body: String): String =
+ listOfNotNull(prompt?.trim()?.takeIf { it.isNotEmpty() }, body).joinToString("\n\n")
+
+ /** Chat records get a scene prompt; texts and links go as they are. */
+ internal fun isChat(entries: List, insights: BatchInsights): Boolean =
+ entries.any { it.summary?.kind == RelaySummary.Kind.CHAT } ||
+ (entries.any { it.summary == null } && insights.senders.isNotEmpty())
+
+ /**
+ * The scene prompt the delivery panel would open with for [entries]:
+ * [SceneBinding.open] on the chat name or summary title and the speakers,
+ * falling back to the default scene; then `ScenePrompt.render` with the
+ * group's last summary boundary. Blocking (reads the scene files).
+ */
+ internal fun prompt(entries: List, scenes: SceneStore, insights: BatchInsights, zone: ZoneId): String? {
+ val snapshot = scenes.current()
+ val chatName = entries.firstNotNullOfOrNull { it.batch.chatName }
+ val title = entries.mapNotNull { it.summary }.firstOrNull { it.kind == RelaySummary.Kind.CHAT }?.title
+ val opening = SceneBinding(scenes).open(chatName, title, snapshot.settings, snapshot.memories, insights.senders)
+ val scene = opening.resolution.scene ?: return null
+ val memory = opening.group.name?.let { snapshot.memories[GroupName.normalize(it)] }
+ return ScenePrompt.render(scene, memory?.lastSummaryAt, insights.end, zone = zone)?.trim()?.ifEmpty { null }
+ }
+
+ /**
+ * Builds the drag text for [entries] (one batch, or the merge in the
+ * order given). Textless batches are left out of a merge. Blocking file
+ * IO: call on an IO dispatcher. [newWorkDirectory] is a fresh scratch
+ * directory, removed again before returning.
+ */
+ fun build(
+ entries: List,
+ scenes: SceneStore,
+ newWorkDirectory: () -> File,
+ zone: ZoneId = ZoneId.systemDefault(),
+ ): DragText {
+ val readable = entries.filterNot(::isTextless)
+ if (readable.isEmpty()) return DragText.NoText
+ var work: File? = null
+ return try {
+ val batches = readable.map { it.batch }
+ val insights = runCatching { BatchInsights.read(batches.flatMap { b -> b.items.map { it.file } }, zone) }
+ .getOrDefault(BatchInsights.EMPTY)
+ val prompt = if (isChat(readable, insights)) runCatching { prompt(readable, scenes, insights, zone) }.getOrNull() else null
+ val dir = newWorkDirectory().also { work = it }
+ val planned = DeliveryPlanner.plan(PlanRequest(batches, TEXT_ONLY, prompt, DeliveryFormat.INLINE_TEXT, zone), dir)
+ val body = planned.inlineText
+ when {
+ body != null -> DragText.Ready(join(prompt, body))
+ planned.inlineFellBackToFile -> DragText.TooLarge
+ else -> DragText.NoText
+ }
+ } catch (e: DeliveryPlanException) {
+ if (e.reason == DeliveryPlanException.Reason.NO_ARCHIVE) DragText.NoText else DragText.Failed
+ } catch (_: Exception) {
+ DragText.Failed
+ } finally {
+ work?.deleteRecursively()
+ }
+ }
+}
+
+/**
+ * Window flags while a drag is out: the panel and the ball must let the drop
+ * through to the app underneath (not touchable) and must not hold focus, or
+ * the target's input box cannot take it. Afterwards the panel takes focus
+ * again (back closes it); the ball never does.
+ */
+object DragWindowFlags {
+ private const val DRAG_BITS = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+
+ fun flags(current: Int, dragging: Boolean, focusableAtRest: Boolean): Int = when {
+ dragging -> current or DRAG_BITS
+ focusableAtRest -> current and DRAG_BITS.inv()
+ else -> (current and WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE.inv()) or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+ }
+}
diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleDragShadow.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleDragShadow.kt
new file mode 100644
index 00000000..5aad185c
--- /dev/null
+++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleDragShadow.kt
@@ -0,0 +1,53 @@
+package com.xiangming.wechatbridge.bubble
+
+import android.content.Context
+import android.graphics.Canvas
+import android.graphics.Paint
+import android.graphics.Point
+import android.graphics.RectF
+import android.text.TextPaint
+import android.text.TextUtils
+import android.util.TypedValue
+import android.view.View
+import kotlin.math.ceil
+import kotlin.math.roundToInt
+
+/** Colours for the drag card, taken from the Compose theme by the panel. */
+internal data class DragShadowStyle(val background: Int, val foreground: Int)
+
+/**
+ * The shadow under the finger while a batch is dragged out: a small rounded
+ * card with the batch title (one line, ellipsized), not a picture of the row.
+ */
+internal class DragCardShadow(context: Context, title: String, private val colors: DragShadowStyle) : View.DragShadowBuilder() {
+ private val metrics = context.resources.displayMetrics
+ private fun dp(value: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, metrics)
+
+ private val paddingX = dp(14f)
+ private val paddingY = dp(10f)
+ private val radius = dp(12f)
+ private val textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
+ color = colors.foreground
+ textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 14f, metrics)
+ }
+ private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = colors.background }
+ private val text: String = TextUtils.ellipsize(title, textPaint, dp(MAX_TEXT_DP), TextUtils.TruncateAt.END).toString()
+ private val width = (ceil(textPaint.measureText(text)) + paddingX * 2).roundToInt().coerceAtLeast(dp(48f).roundToInt())
+ private val height = (textPaint.fontMetrics.let { it.descent - it.ascent } + paddingY * 2).roundToInt()
+
+ override fun onProvideShadowMetrics(outShadowSize: Point, outShadowTouchPoint: Point) {
+ outShadowSize.set(width, height)
+ // The finger sits at the bottom edge of the card, so the card stays visible above it.
+ outShadowTouchPoint.set(width / 2, (height - 1).coerceAtLeast(0))
+ }
+
+ override fun onDrawShadow(canvas: Canvas) {
+ canvas.drawRoundRect(RectF(0f, 0f, width.toFloat(), height.toFloat()), radius, radius, backgroundPaint)
+ val baseline = paddingY - textPaint.fontMetrics.ascent
+ canvas.drawText(text, paddingX, baseline, textPaint)
+ }
+
+ private companion object {
+ const val MAX_TEXT_DP = 220f
+ }
+}
diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleLogic.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleLogic.kt
new file mode 100644
index 00000000..00a33d0d
--- /dev/null
+++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleLogic.kt
@@ -0,0 +1,232 @@
+package com.xiangming.wechatbridge.bubble
+
+import com.xiangming.wechatbridge.data.RelayEntry
+import com.xiangming.wechatbridge.receive.ReceiptUiState
+import java.time.Instant
+import java.util.UUID
+import kotlin.math.abs
+import kotlin.math.roundToInt
+
+/** Which screen edge the handle rests on. */
+enum class BubbleEdge { LEFT, RIGHT }
+
+/** Where the handle rests: an edge and how far down the usable height (0 = top, 1 = bottom). */
+data class BubblePlacement(val edge: BubbleEdge, val yFraction: Float) {
+ companion object {
+ val DEFAULT = BubblePlacement(BubbleEdge.RIGHT, 0.6f)
+ }
+}
+
+/**
+ * Pure geometry for dragging, inward swipe, and snapping, in window pixels. Kept apart from
+ * WindowManager so it can be unit tested; [BubbleWindow] feeds it the screen.
+ */
+object BubbleGeometry {
+ /** Outcome of a touch sequence on the docked edge handle. */
+ enum class EdgeGesture {
+ /** Short press without moving past touch slop: open the staged panel. */
+ TAP,
+
+ /** Deliberate inward horizontal swipe from the docked edge: open the staged panel. */
+ OPEN_PANEL,
+
+ /** Vertical move or cross-screen horizontal drag: snap to edge & remember position. */
+ REPOSITION,
+ }
+
+ /** Released left of the middle goes left; the middle itself goes right. */
+ fun edgeFor(centerX: Int, screenWidth: Int): BubbleEdge =
+ if (centerX * 2 < screenWidth) BubbleEdge.LEFT else BubbleEdge.RIGHT
+
+ fun xFor(edge: BubbleEdge, screenWidth: Int, windowSize: Int): Int = when (edge) {
+ BubbleEdge.LEFT -> 0
+ BubbleEdge.RIGHT -> (screenWidth - windowSize).coerceAtLeast(0)
+ }
+
+ /** Valid window tops: below [topInset], with the window above [bottomInset]. */
+ fun yRange(screenHeight: Int, windowSize: Int, topInset: Int, bottomInset: Int): IntRange {
+ val top = topInset.coerceAtLeast(0)
+ val bottom = (screenHeight - bottomInset - windowSize).coerceAtLeast(top)
+ return top..bottom
+ }
+
+ fun clampX(x: Int, screenWidth: Int, windowSize: Int): Int =
+ x.coerceIn(0, (screenWidth - windowSize).coerceAtLeast(0))
+
+ fun yFor(fraction: Float, range: IntRange): Int {
+ val f = if (fraction.isNaN()) BubblePlacement.DEFAULT.yFraction else fraction.coerceIn(0f, 1f)
+ return range.first + ((range.last - range.first) * f).roundToInt()
+ }
+
+ fun fractionFor(y: Int, range: IntRange): Float {
+ val span = range.last - range.first
+ if (span <= 0) return 0.5f
+ return (y.coerceIn(range) - range.first).toFloat() / span
+ }
+
+ /** Where a release at window position ([x], [y]) settles. */
+ fun snap(x: Int, y: Int, screenWidth: Int, windowSize: Int, range: IntRange): BubblePlacement =
+ BubblePlacement(edgeFor(x + windowSize / 2, screenWidth), fractionFor(y, range))
+
+ /** Moved further than the touch slop: a drag, not a tap. */
+ fun isDrag(dx: Float, dy: Float, slop: Int): Boolean = dx * dx + dy * dy > slop.toFloat() * slop
+
+ /**
+ * Classifies a touch release on the edge handle:
+ * - within [slop] -> [EdgeGesture.TAP]
+ * - mostly-horizontal inward pull between [swipeThreshold] and [crossThreshold] -> [EdgeGesture.OPEN_PANEL]
+ * - otherwise -> [EdgeGesture.REPOSITION] (vertical slide or cross-screen edge switch)
+ */
+ fun classifyRelease(
+ edge: BubbleEdge,
+ dx: Float,
+ dy: Float,
+ slop: Int,
+ swipeThreshold: Float,
+ crossThreshold: Float,
+ ): EdgeGesture {
+ if (!isDrag(dx, dy, slop)) return EdgeGesture.TAP
+ val inwardDx = if (edge == BubbleEdge.RIGHT) -dx else dx
+ val mostlyHorizontal = abs(dx) > abs(dy) * 1.3f
+ return if (inwardDx >= swipeThreshold && inwardDx < crossThreshold && mostlyHorizontal) {
+ EdgeGesture.OPEN_PANEL
+ } else {
+ EdgeGesture.REPOSITION
+ }
+ }
+}
+
+/**
+ * What the bubble counts: batches the relay would list under 「未投递」
+ * (`RelayFilter.UNDELIVERED`, i.e. no `delivered` outcome yet), newest first.
+ */
+object BubbleStaging {
+ /** The panel lists at most this many; 「全部合并投递」 still takes them all. */
+ const val PANEL_LIMIT = 30
+
+ fun staged(entries: List): List =
+ entries.filter { !it.isDelivered }.sortedByDescending { it.batch.createdAt }
+
+ /** Ids for 「全部合并投递」: oldest first, the order a merge reads in (as the relay's own selection). */
+ fun mergeIds(staged: List): List =
+ staged.sortedBy { it.batch.createdAt }.map { it.id.toString().uppercase() }
+
+ /** The badge: nothing for 0, the number up to 99, then 「99+」. */
+ fun badge(count: Int): String? = when {
+ count <= 0 -> null
+ count > 99 -> "99+"
+ else -> count.toString()
+ }
+
+ /**
+ * Bounce when a batch appears that was not there before and arrived after
+ * [since] (the service start), so loading the existing list does not bounce.
+ */
+ fun shouldPulse(previous: Set, current: List, since: Instant): Boolean =
+ current.any { it.id !in previous && !it.batch.createdAt.isBefore(since) }
+}
+
+/** Should the service run (and silent receive stay active)? */
+object BubbleGate {
+ fun shouldRun(enabled: Boolean, canDrawOverlays: Boolean): Boolean = enabled && canDrawOverlays
+}
+
+/**
+ * Whether the slim edge handle itself should be visible on screen.
+ * The foreground service and [SilentReceive] stay active even when the handle
+ * is hidden due to [autoHideWhenEmpty] or [zeroOverlayMode].
+ */
+object BubbleVisibility {
+ fun shouldShowHandle(
+ enabled: Boolean,
+ canDrawOverlays: Boolean,
+ stagedCount: Int,
+ autoHideWhenEmpty: Boolean,
+ zeroOverlayMode: Boolean,
+ panelOpen: Boolean = false,
+ ): Boolean {
+ if (!BubbleGate.shouldRun(enabled, canDrawOverlays)) return false
+ if (zeroOverlayMode) return false
+ if (panelOpen) return false
+ if (autoHideWhenEmpty && stagedCount <= 0) return false
+ return true
+ }
+
+ /**
+ * Whether an on-demand service instance (launched via QS Tile while the main switch is off)
+ * is safe to stop. Must stay alive while the panel is open or an async fill is in progress.
+ */
+ fun shouldStopOnDemand(
+ onDemandOnly: Boolean,
+ enabled: Boolean,
+ panelOpen: Boolean,
+ fillInProgress: Boolean = false,
+ ): Boolean = onDemandOnly && !enabled && !panelOpen && !fillInProgress
+}
+
+/**
+ * The share receiver with the bubble on: no receipt card, back to the sender
+ * as soon as the batch is in; only a failure says anything. Otherwise the
+ * receipt card behaves as before.
+ */
+object SilentReceive {
+ enum class Mode { RECEIPT, SILENT }
+
+ enum class Step {
+ /** Still copying: keep the Activity (the URI grant ends with it). */
+ WAIT,
+
+ /** Saved: finish at once; the bubble's count picks it up. */
+ FINISH,
+
+ /** Not saved: say why (Toast), then finish. */
+ FAIL,
+ }
+
+ /** The bubble must actually be able to show, or the user would get no sign at all. */
+ fun mode(bubbleEnabled: Boolean, canDrawOverlays: Boolean): Mode =
+ if (BubbleGate.shouldRun(bubbleEnabled, canDrawOverlays)) Mode.SILENT else Mode.RECEIPT
+
+ fun step(state: ReceiptUiState?): Step = when (state) {
+ null, is ReceiptUiState.Importing -> Step.WAIT
+ is ReceiptUiState.Saved -> Step.FINISH
+ is ReceiptUiState.NotSaved -> Step.FAIL
+ }
+
+ /** A long copy shows the progress card after this, so a quick one never flashes it. */
+ const val PROGRESS_DELAY_MILLIS = 400L
+}
+
+/** The settings switch. */
+object BubbleToggle {
+ enum class Action {
+ /** Save on and start the service. */
+ ENABLE,
+
+ /** Open the system overlay page; decide again on return. */
+ REQUEST_PERMISSION,
+
+ /** Save off and stop the service. */
+ DISABLE,
+ }
+
+ fun onSwitch(turnOn: Boolean, canDrawOverlays: Boolean): Action = when {
+ !turnOn -> Action.DISABLE
+ canDrawOverlays -> Action.ENABLE
+ else -> Action.REQUEST_PERMISSION
+ }
+
+ /** Back from the system page (or resumed) while waiting for the permission: enable if it was granted. */
+ fun onReturn(awaitingPermission: Boolean, canDrawOverlays: Boolean): Action? = when {
+ !awaitingPermission -> null
+ canDrawOverlays -> Action.ENABLE
+ else -> null
+ }
+
+ /** HyperOS / MIUI also gate overlays behind their own 「后台弹出界面」 and 「显示悬浮窗」. */
+ fun isXiaomi(manufacturer: String?, brand: String? = null): Boolean =
+ listOf(manufacturer, brand).any { value ->
+ val v = value?.lowercase().orEmpty()
+ v.contains("xiaomi") || v.contains("redmi") || v.contains("poco")
+ }
+}
diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleMedia.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleMedia.kt
new file mode 100644
index 00000000..b02bd5c5
--- /dev/null
+++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleMedia.kt
@@ -0,0 +1,150 @@
+package com.xiangming.wechatbridge.bubble
+
+import android.content.ClipData
+import android.content.ClipDescription
+import android.net.Uri
+import com.xiangming.wechatbridge.core.deliver.DeliveryPlanner
+import com.xiangming.wechatbridge.core.inbox.ReadyItem
+import com.xiangming.wechatbridge.core.summary.RelayFiles
+import com.xiangming.wechatbridge.core.summary.RelaySummary
+import com.xiangming.wechatbridge.core.summary.ShareOrigin
+import com.xiangming.wechatbridge.data.RelayEntry
+import java.io.File
+import java.nio.file.Files
+import java.util.Locale
+import java.util.UUID
+
+/** A file a drag can carry: where it is now, the name it goes out under, its MIME type. */
+data class DragFile(val file: File, val name: String, val mimeType: String)
+
+/**
+ * What a staged batch can drag out besides text: its images (loose files,
+ * or unpacked from a chat ZIP) and, for a native WeChat chat export, the
+ * original ZIP. Other attachments (PDF, video, a plain ZIP…) are not here.
+ */
+data class BatchMedia(val images: List, val archive: DragFile?) {
+ companion object {
+ val EMPTY = BatchMedia(emptyList(), null)
+ }
+}
+
+/** The images one drag takes: the first [files] of [total]. */
+data class ImageSelection(val files: List, val total: Int) {
+ val truncated: Boolean get() = total > files.size
+}
+
+object BubbleMedia {
+ /** Most images one drag carries; the rest are left out with a toast. */
+ const val MAX_IMAGES = 9
+
+ const val ZIP_MIME = "application/zip"
+
+ /** Directory-name prefix under `cacheDir/deliveries/` for drag copies (cleaned with the other deliveries). */
+ const val DIRECTORY_PREFIX = "bubble-drag-"
+
+ private fun isZip(name: String) = name.lowercase(Locale.ROOT).endsWith(".zip")
+
+ /**
+ * The native chat export of a chat batch: the summary's archive item, or
+ * the first ZIP. Null for anything else (a ZIP in a files batch stays an
+ * attachment).
+ */
+ fun chatArchive(entry: RelayEntry): ReadyItem? {
+ val summary = entry.summary ?: return null
+ if (summary.kind != RelaySummary.Kind.CHAT) return null
+ val items = entry.batch.items
+ val item = summary.archiveItemId?.let { id -> items.firstOrNull { it.id == id } }
+ ?: items.firstOrNull { isZip(it.file.name) || isZip(it.displayName) }
+ ?: return null
+ return item.takeIf { isZip(it.file.name) || isZip(it.displayName) }
+ }
+
+ /** The name a loose image goes out under, with an image extension; null when it is no image. */
+ fun imageName(displayName: String, fileName: String): String? {
+ val shown = displayName.substringAfterLast('/').trim()
+ if (shown.isNotEmpty() && DeliveryPlanner.isImage(shown)) return shown
+ if (!DeliveryPlanner.isImage(fileName)) return null
+ val ext = fileName.substringAfterLast('.')
+ val base = shown.substringBeforeLast('.').ifEmpty { fileName.substringBeforeLast('.') }.ifEmpty { "image" }
+ return "$base.$ext"
+ }
+
+ /** WeChat's suggested name, kept readable, always ending in `.zip`. */
+ fun archiveName(displayName: String): String {
+ val shown = displayName.substringAfterLast('/').trim().ifEmpty { "聊天记录.zip" }
+ return if (isZip(shown)) shown else "$shown.zip"
+ }
+
+ /** Images of [names] (archive entry paths; folders skipped) in [directory], in order. */
+ fun imagesIn(directory: File, names: List, skip: String? = null): List =
+ names.filter { it != skip && !it.endsWith("/") }.mapNotNull { path ->
+ val leaf = path.substringAfterLast('/')
+ if (!DeliveryPlanner.isImage(leaf)) null else DragFile(File(directory, path), leaf, DeliveryPlanner.mimeType(leaf))
+ }
+
+ /**
+ * Looks [entry] over (blocking file IO). The chat ZIP is unpacked with
+ * [extract] — by default [RelayFiles.extract], the cached copy the
+ * summary and the detail page already use.
+ */
+ fun scan(
+ entry: RelayEntry,
+ extract: (File, UUID) -> RelayFiles.Extracted = RelayFiles::extract,
+ ): BatchMedia {
+ val archiveItem = chatArchive(entry)
+ val images = mutableListOf()
+ for (item in entry.batch.items) {
+ if (item.id == archiveItem?.id) {
+ val unpacked = runCatching { extract(item.file, entry.batch.id) }.getOrNull() ?: continue
+ images += imagesIn(unpacked.directory, unpacked.names)
+ continue
+ }
+ if (item.contentType == ShareOrigin.NOTE_CONTENT_TYPE) continue
+ val name = imageName(item.displayName, item.file.name) ?: continue
+ images += DragFile(item.file, name, DeliveryPlanner.mimeType(name))
+ }
+ val archive = archiveItem?.takeIf { it.file.isFile }?.let {
+ DragFile(it.file, archiveName(it.displayName), ZIP_MIME)
+ }
+ return BatchMedia(images.filter { it.file.isFile }, archive)
+ }
+
+ /** At most [limit], in order. */
+ fun select(images: List, limit: Int = MAX_IMAGES): ImageSelection =
+ ImageSelection(images.take(limit), images.size)
+
+ /**
+ * Copies [files] into [directory] (under `cacheDir/deliveries/`, which the
+ * FileProvider serves): inbox originals never leave the app. Names are
+ * made unique (`a.png`, `a (2).png`) and keep their extensions.
+ */
+ fun stage(files: List, directory: File): List {
+ if (!directory.isDirectory && !directory.mkdirs()) throw java.io.IOException("cannot create $directory")
+ val used = HashSet()
+ return files.map { source ->
+ val name = DeliveryPlanner.uniqueName(source.name.replace('/', '_'), used)
+ val destination = File(directory, name)
+ Files.copy(source.file.toPath(), destination.toPath())
+ source.copy(file = destination, name = name)
+ }
+ }
+}
+
+/** What goes into a drag's ClipData: one item per URI, the distinct MIME types in order. */
+data class ClipPlan(val mimeTypes: List, val itemCount: Int)
+
+object DragClip {
+ fun plan(mimeTypes: List): ClipPlan = ClipPlan(mimeTypes.distinct(), mimeTypes.size)
+
+ /**
+ * URIs only, no text: an input box would paste a URI it finds next to
+ * text. Null when there is nothing to carry.
+ */
+ fun build(label: String, items: List>): ClipData? {
+ if (items.isEmpty()) return null
+ val plan = plan(items.map { it.second })
+ val clip = ClipData(ClipDescription(label, plan.mimeTypes.toTypedArray()), ClipData.Item(items.first().first))
+ items.drop(1).forEach { clip.addItem(ClipData.Item(it.first)) }
+ return clip
+ }
+}
diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleNotification.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleNotification.kt
new file mode 100644
index 00000000..776cef94
--- /dev/null
+++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleNotification.kt
@@ -0,0 +1,101 @@
+package com.xiangming.wechatbridge.bubble
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.app.Notification
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.os.Build
+import androidx.core.app.NotificationChannelCompat
+import androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationManagerCompat
+import androidx.core.content.ContextCompat
+import com.xiangming.wechatbridge.MainActivity
+import com.xiangming.wechatbridge.R
+
+/**
+ * The foreground service's quiet notification (channel `bubble`, minimum
+ * importance): keeps the process alive and serves as a zero-overlay trigger
+ * to open the staged panel directly over the foreground app.
+ */
+internal object BubbleNotification {
+ const val CHANNEL_ID = "bubble"
+ const val NOTIFICATION_ID = 0x0B0BB1E
+
+ private const val REQUEST_OPEN_APP = 1
+ private const val REQUEST_HIDE = 2
+ private const val REQUEST_OPEN_PANEL = 3
+
+ fun build(context: Context, stagedCount: Int): Notification {
+ ensureChannel(context)
+ val text = if (stagedCount > 0) {
+ context.resources.getQuantityString(R.plurals.bubble_notification_text, stagedCount, stagedCount)
+ } else {
+ context.getString(R.string.bubble_notification_text_empty)
+ }
+ return NotificationCompat.Builder(context, CHANNEL_ID)
+ .setSmallIcon(R.drawable.ic_stat_wechatbridge)
+ .setContentTitle(context.getString(R.string.bubble_notification_title))
+ .setContentText(text)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .setSilent(true)
+ .setShowWhen(false)
+ .setCategory(NotificationCompat.CATEGORY_SERVICE)
+ .setPriority(NotificationCompat.PRIORITY_MIN)
+ .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_DEFERRED)
+ .setContentIntent(openPanel(context))
+ .addAction(0, context.getString(R.string.bubble_notification_open_panel), openPanel(context))
+ .addAction(0, context.getString(R.string.bubble_notification_open_app), openApp(context))
+ .addAction(0, context.getString(R.string.bubble_notification_hide), hide(context))
+ .build()
+ }
+
+ /** Refreshes the count; skipped when notifications are not allowed. */
+ @SuppressLint("MissingPermission") // checked in canPost
+ fun update(context: Context, stagedCount: Int) {
+ if (!canPost(context)) return
+ runCatching { NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, build(context, stagedCount)) }
+ }
+
+ private fun canPost(context: Context): Boolean {
+ if (Build.VERSION.SDK_INT >= 33 &&
+ ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
+ ) {
+ return false
+ }
+ return NotificationManagerCompat.from(context).areNotificationsEnabled()
+ }
+
+ private fun ensureChannel(context: Context) {
+ val channel = NotificationChannelCompat.Builder(CHANNEL_ID, NotificationManagerCompat.IMPORTANCE_MIN)
+ .setName(context.getString(R.string.bubble_channel_name))
+ .setDescription(context.getString(R.string.bubble_channel_description))
+ .setShowBadge(false)
+ .build()
+ NotificationManagerCompat.from(context).createNotificationChannel(channel)
+ }
+
+ private fun openPanel(context: Context): PendingIntent = PendingIntent.getActivity(
+ context,
+ REQUEST_OPEN_PANEL,
+ BubblePanelTriggerActivity.intent(context),
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
+ )
+
+ private fun openApp(context: Context): PendingIntent = PendingIntent.getActivity(
+ context,
+ REQUEST_OPEN_APP,
+ Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
+ )
+
+ private fun hide(context: Context): PendingIntent = PendingIntent.getService(
+ context,
+ REQUEST_HIDE,
+ Intent(context, BubbleService::class.java).setAction(BubbleService.ACTION_HIDE),
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
+ )
+}
diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubblePanel.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubblePanel.kt
new file mode 100644
index 00000000..31c95029
--- /dev/null
+++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubblePanel.kt
@@ -0,0 +1,1098 @@
+package com.xiangming.wechatbridge.bubble
+
+import android.content.ClipData
+import android.content.Context
+import android.graphics.PixelFormat
+import android.os.Build
+import android.view.DragEvent
+import android.view.KeyEvent
+import android.view.View
+import android.view.WindowManager
+import android.widget.FrameLayout
+import android.widget.Toast
+import androidx.annotation.StringRes
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.tween
+import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.ExperimentalFoundationApi
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.combinedClickable
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.safeDrawingPadding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.itemsIndexed
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.ui.graphics.Color
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Close
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.BiasAlignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.TransformOrigin
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.hapticfeedback.HapticFeedbackType
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.platform.ComposeView
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalHapticFeedback
+import androidx.compose.ui.platform.LocalView
+import androidx.compose.ui.platform.ViewCompositionStrategy
+import androidx.compose.ui.res.pluralStringResource
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import com.xiangming.wechatbridge.R
+import com.xiangming.wechatbridge.data.RelayEntry
+import com.xiangming.wechatbridge.deliver.PromptClipboard
+import com.xiangming.wechatbridge.deliver.ShareFileProvider
+import com.xiangming.wechatbridge.fill.FillAccess
+import com.xiangming.wechatbridge.ui.relay.RelayCardText
+import com.xiangming.wechatbridge.ui.theme.AppMotion
+import com.xiangming.wechatbridge.ui.theme.LocalAppColors
+import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme
+import com.xiangming.wechatbridge.ui.theme.pressScale
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.async
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import java.io.File
+import java.util.UUID
+import java.time.Instant
+import java.time.ZoneId
+
+/** What the panel's buttons do; the service carries them out and closes the panel. */
+internal interface BubblePanelActions {
+ fun openBatch(entry: RelayEntry)
+ fun mergeAll(staged: List)
+ fun openApp()
+ fun hideBubble()
+ fun dismiss()
+
+ /** 「填入」: close the panel and put [text] into the input box of the app in front (never sends). */
+ fun fill(text: String)
+ fun openAccessibilitySettings()
+ fun openAppDetails()
+}
+
+/** What the panel needs from the service for dragging text out. */
+internal interface BubbleDragHost {
+ /** [BubbleDragText.build] for [entries]; blocking, called on an IO dispatcher. */
+ fun build(entries: List): DragText
+
+ /** [PromptClipboard.copy]. */
+ fun copy(text: String): PromptClipboard.Result
+
+ /** The ball window lets drops through while a drag is out. */
+ fun setBallDragging(dragging: Boolean)
+
+ /** [BubbleMedia.scan] for [entry]; blocking, called on an IO dispatcher. */
+ fun media(entry: RelayEntry): BatchMedia
+
+ /** A fresh, empty directory under `cacheDir/deliveries/` for one drag's copies. */
+ fun newMediaDirectory(): File
+
+ /** Whether the fill accessibility service is on and connected. */
+ fun fillState(): FillAccess.State
+}
+
+/** Long press and copy, from the panel's rows and the merge button to [BubblePanelWindow]. */
+internal interface BubbleDragActions {
+ fun drag(source: View, title: String, entries: List, style: DragShadowStyle)
+ fun copy(entries: List)
+
+ /** Up to [BubbleMedia.MAX_IMAGES] of the batch's images, as content URIs. */
+ fun dragImages(source: View, entry: RelayEntry, style: DragShadowStyle)
+
+ /** The batch's original chat ZIP, as one content URI. */
+ fun dragArchive(source: View, entry: RelayEntry, style: DragShadowStyle)
+
+ /** A tap on a capsule: say it takes a long press. */
+ fun capsuleHint()
+
+ /** 「填入」 / 「全部填入」: the same text as a drag, into the front app's input box. */
+ fun fill(entries: List)
+
+ /** Leaves the 「开启一键填入」 guide for the list again. */
+ fun closeFillGuide()
+
+ object None : BubbleDragActions {
+ override fun fill(entries: List) = Unit
+ override fun closeFillGuide() = Unit
+ override fun drag(source: View, title: String, entries: List, style: DragShadowStyle) = Unit
+ override fun copy(entries: List) = Unit
+ override fun dragImages(source: View, entry: RelayEntry, style: DragShadowStyle) = Unit
+ override fun dragArchive(source: View, entry: RelayEntry, style: DragShadowStyle) = Unit
+ override fun capsuleHint() = Unit
+ }
+}
+
+/**
+ * Real cross-window frosted glass on Android 12+. Older releases keep the opaque
+ * panel fill instead. Radius is converted from dp because WindowManager uses pixels.
+ */
+internal object BubbleWindowBlur {
+ private const val RADIUS_DP = 28
+
+ fun apply(params: WindowManager.LayoutParams, enabled: Boolean, density: Float) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return
+ params.flags = if (enabled) {
+ params.flags or WindowManager.LayoutParams.FLAG_BLUR_BEHIND
+ } else {
+ params.flags and WindowManager.LayoutParams.FLAG_BLUR_BEHIND.inv()
+ }
+ params.blurBehindRadius = if (enabled) (RADIUS_DP * density).toInt() else 0
+ }
+}
+
+/**
+ * The staged list, in a full-screen overlay window over whatever app is in
+ * front: a scrim (tap to close) and a card beside the ball's edge. The window
+ * takes focus so the back key closes it.
+ */
+internal class BubblePanelWindow(
+ private val context: Context,
+ private val windowManager: WindowManager,
+ private val owner: OverlayOwner,
+ private val staged: StateFlow>,
+ private val actions: BubblePanelActions,
+ private val host: BubbleDragHost,
+) : BubbleDragActions {
+ private var root: FrameLayout? = null
+ private var params: WindowManager.LayoutParams? = null
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+
+ /** Drag texts for this opening of the panel, by batch ids; built once each. */
+ private val texts = HashMap>()
+
+ /** Images and archive per batch, for this opening; the capsules show once known. */
+ private val scans = HashMap>()
+ private val media = MutableStateFlow