From 25e164877ca552263ed72810c7b54a2ac0e537fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E6=80=9D=E6=96=87?= <> Date: Tue, 1 Dec 2026 09:01:46 +0800 Subject: [PATCH 1/2] Release Doca 0.3.2 and Android 0.1.1 --- README.es.md | 2 +- README.fr.md | 2 +- README.ja.md | 2 +- README.ko.md | 2 +- README.md | 6 +- README.ru.md | 2 +- README.zh-CN.md | 6 +- README.zh-Hant.md | 2 +- apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- apps/mobile/app.json | 12 +- apps/mobile/app/(tabs)/_layout.tsx | 145 ++++-- apps/mobile/app/(tabs)/ai.tsx | 35 +- apps/mobile/app/(tabs)/index.tsx | 144 +++--- apps/mobile/app/_layout.tsx | 142 +++--- apps/mobile/app/account.tsx | 4 +- apps/mobile/app/ai/[id].tsx | 422 +++++++++++++----- apps/mobile/app/extensions.tsx | 154 +++---- apps/mobile/app/me.tsx | 118 +++++ apps/mobile/app/notifications.tsx | 151 +++++++ apps/mobile/app/scan.tsx | 2 +- apps/mobile/app/settings.tsx | 190 ++++---- apps/mobile/package.json | 2 +- apps/mobile/src/ai-reference-picker.tsx | 97 ++++ apps/mobile/src/api.ts | 10 +- apps/mobile/src/app-drawer.tsx | 2 + apps/mobile/src/auth.tsx | 34 +- apps/mobile/src/chrome.tsx | 10 + apps/mobile/src/folder-browser.tsx | 96 ++-- apps/mobile/src/plugins/navigation.tsx | 164 ++++--- apps/mobile/src/query-cache.ts | 51 +-- apps/mobile/src/resource-list.tsx | 206 ++++++--- apps/mobile/src/session.ts | 91 ++-- apps/server/src/app/create-app.ts | 12 +- apps/server/src/app/mobile-client.ts | 2 + apps/server/src/main.ts | 1 + apps/server/src/plugins/store.ts | 3 +- apps/server/src/routes/release-check.ts | 81 ++++ apps/server/src/services/release-check.ts | 213 +++++++++ apps/web/src/features/admin/admin.css | 32 ++ apps/web/src/features/admin/admin.tsx | 2 + .../features/admin/release-check-settings.tsx | 143 ++++++ .../src/features/files/file-interactions.ts | 25 -- apps/web/src/features/files/files.css | 17 + apps/web/src/features/files/files.tsx | 299 ++++++------- compose.yaml | 4 +- docs/README.es.md | 4 +- docs/README.fr.md | 4 +- docs/README.ja.md | 4 +- docs/README.ko.md | 4 +- docs/README.md | 4 +- docs/README.ru.md | 4 +- docs/README.zh-CN.md | 4 +- docs/README.zh-Hant.md | 4 +- docs/api.md | 4 + docs/api.zh-CN.md | 4 + docs/configuration.es.md | 2 + docs/configuration.fr.md | 2 + docs/configuration.ja.md | 2 + docs/configuration.ko.md | 2 + docs/configuration.md | 2 + docs/configuration.ru.md | 2 + docs/configuration.zh-CN.md | 2 + docs/configuration.zh-Hant.md | 2 + docs/deployment-without-github.es.md | 40 +- docs/deployment-without-github.fr.md | 40 +- docs/deployment-without-github.ja.md | 40 +- docs/deployment-without-github.ko.md | 40 +- docs/deployment-without-github.md | 40 +- docs/deployment-without-github.ru.md | 40 +- docs/deployment-without-github.zh-CN.md | 40 +- docs/deployment-without-github.zh-Hant.md | 40 +- docs/deployment.es.md | 2 +- docs/deployment.fr.md | 2 +- docs/deployment.ja.md | 2 +- docs/deployment.ko.md | 2 +- docs/deployment.md | 12 +- docs/deployment.ru.md | 2 +- docs/deployment.zh-CN.md | 12 +- docs/deployment.zh-Hant.md | 2 +- docs/desktop-client.es.md | 2 +- docs/desktop-client.fr.md | 2 +- docs/desktop-client.ja.md | 2 +- docs/desktop-client.ko.md | 2 +- docs/desktop-client.md | 2 +- docs/desktop-client.ru.md | 2 +- docs/desktop-client.zh-CN.md | 2 +- docs/desktop-client.zh-Hant.md | 2 +- docs/doca-release-check-protocol.md | 68 +++ docs/plugin-native.md | 2 + docs/plugin-native.zh-CN.md | 2 + docs/plugin-store-protocol.md | 2 + docs/plugin-store-protocol.zh-CN.md | 2 + docs/releases/0.3.2.es.md | 7 + docs/releases/0.3.2.fr.md | 7 + docs/releases/0.3.2.ja.md | 7 + docs/releases/0.3.2.ko.md | 7 + docs/releases/0.3.2.md | 16 + docs/releases/0.3.2.ru.md | 7 + docs/releases/0.3.2.zh-CN.md | 16 + docs/releases/0.3.2.zh-Hant.md | 7 + docs/site/assets/site.js | 2 +- docs/site/navigation.json | 6 + docs/user-guide.es.md | 2 +- docs/user-guide.fr.md | 2 +- docs/user-guide.ja.md | 2 +- docs/user-guide.ko.md | 2 +- docs/user-guide.md | 2 +- docs/user-guide.ru.md | 2 +- docs/user-guide.zh-CN.md | 2 +- docs/user-guide.zh-Hant.md | 2 +- package.json | 2 +- packages/i18n/src/catalogs/en.ts | 28 ++ packages/i18n/src/catalogs/es.json | 28 ++ packages/i18n/src/catalogs/fr.json | 28 ++ packages/i18n/src/catalogs/ja.json | 28 ++ packages/i18n/src/catalogs/ko.json | 28 ++ packages/i18n/src/catalogs/ru.json | 28 ++ packages/i18n/src/catalogs/zh-Hant.json | 28 ++ packages/i18n/src/catalogs/zh.ts | 28 ++ .../web-plugin-registry/src/navigation.ts | 2 +- specs/019-folder-loading/spec.md | 43 ++ specs/025-compact-workspace-browsing/spec.md | 2 +- specs/031-doca-store-release-check/plan.md | 23 + specs/031-doca-store-release-check/spec.md | 26 ++ specs/031-doca-store-release-check/tasks.md | 8 + .../validation.md | 27 ++ specs/032-mobile-app-mvp/spec.md | 97 ++++ specs/033-doca-release-check/plan.md | 24 + specs/033-doca-release-check/spec.md | 26 ++ specs/033-doca-release-check/tasks.md | 8 + specs/033-doca-release-check/validation.md | 29 ++ specs/034-mobile-query-cache/plan.md | 7 + specs/034-mobile-query-cache/spec.md | 24 + specs/034-mobile-query-cache/tasks.md | 7 + specs/034-mobile-query-cache/validation.md | 8 + specs/035-android-session-lifetime/plan.md | 7 + specs/035-android-session-lifetime/spec.md | 24 + specs/035-android-session-lifetime/tasks.md | 7 + .../validation.md | 8 + tests/android-session-lifetime.test.ts | 90 ++++ tests/cloud.test.ts | 16 + tests/file-explorer-loading.test.ts | 161 +++++++ tests/file-interactions.test.ts | 12 +- tests/navigation-layout.test.ts | 13 + tests/release-check.test.ts | 187 ++++++++ 148 files changed, 3682 insertions(+), 1180 deletions(-) create mode 100644 apps/mobile/app/me.tsx create mode 100644 apps/mobile/app/notifications.tsx create mode 100644 apps/mobile/src/ai-reference-picker.tsx create mode 100644 apps/server/src/routes/release-check.ts create mode 100644 apps/server/src/services/release-check.ts create mode 100644 apps/web/src/features/admin/release-check-settings.tsx create mode 100644 docs/doca-release-check-protocol.md create mode 100644 docs/releases/0.3.2.es.md create mode 100644 docs/releases/0.3.2.fr.md create mode 100644 docs/releases/0.3.2.ja.md create mode 100644 docs/releases/0.3.2.ko.md create mode 100644 docs/releases/0.3.2.md create mode 100644 docs/releases/0.3.2.ru.md create mode 100644 docs/releases/0.3.2.zh-CN.md create mode 100644 docs/releases/0.3.2.zh-Hant.md create mode 100644 specs/019-folder-loading/spec.md create mode 100644 specs/031-doca-store-release-check/plan.md create mode 100644 specs/031-doca-store-release-check/spec.md create mode 100644 specs/031-doca-store-release-check/tasks.md create mode 100644 specs/031-doca-store-release-check/validation.md create mode 100644 specs/032-mobile-app-mvp/spec.md create mode 100644 specs/033-doca-release-check/plan.md create mode 100644 specs/033-doca-release-check/spec.md create mode 100644 specs/033-doca-release-check/tasks.md create mode 100644 specs/033-doca-release-check/validation.md create mode 100644 specs/034-mobile-query-cache/plan.md create mode 100644 specs/034-mobile-query-cache/spec.md create mode 100644 specs/034-mobile-query-cache/tasks.md create mode 100644 specs/034-mobile-query-cache/validation.md create mode 100644 specs/035-android-session-lifetime/plan.md create mode 100644 specs/035-android-session-lifetime/spec.md create mode 100644 specs/035-android-session-lifetime/tasks.md create mode 100644 specs/035-android-session-lifetime/validation.md create mode 100644 tests/android-session-lifetime.test.ts create mode 100644 tests/file-explorer-loading.test.ts create mode 100644 tests/release-check.test.ts diff --git a/README.es.md b/README.es.md index 93bf0ede..c71805fc 100644 --- a/README.es.md +++ b/README.es.md @@ -37,7 +37,7 @@ Capturas de una instalación aislada de Doca 0.3.0 con la interfaz y los documen Necesitas Docker Engine, Docker Compose y una dirección HTTP(S) para el sitio. Descarga el archivo Compose, configura `DOCA_ORIGIN` y genera una clave maestra de credenciales exclusiva antes de arrancar. El primer arranque inicializa la cuenta de administración. ```sh -curl -fL https://github.com/workhold/doca/releases/download/v0.3.1/doca-compose-v0.3.1.yaml -o compose.yaml +curl -fL https://github.com/workhold/doca/releases/download/v0.3.2/doca-compose-v0.3.2.yaml -o compose.yaml ``` ```sh diff --git a/README.fr.md b/README.fr.md index 5b78302f..32530d21 100644 --- a/README.fr.md +++ b/README.fr.md @@ -37,7 +37,7 @@ Captures réalisées dans une instance isolée de Doca 0.3.0. L’interface et l Prévoyez Docker Engine, Docker Compose et une URL HTTP(S) pour le site. Téléchargez le fichier Compose, renseignez `DOCA_ORIGIN` et générez une clé maîtresse dédiée pour les identifiants avant de démarrer. Le premier démarrage initialise le compte administrateur. ```sh -curl -fL https://github.com/workhold/doca/releases/download/v0.3.1/doca-compose-v0.3.1.yaml -o compose.yaml +curl -fL https://github.com/workhold/doca/releases/download/v0.3.2/doca-compose-v0.3.2.yaml -o compose.yaml ``` ```sh diff --git a/README.ja.md b/README.ja.md index c6660622..94ba35a8 100644 --- a/README.ja.md +++ b/README.ja.md @@ -37,7 +37,7 @@ Doca は、個人や小規模チーム向けのオープンソースのドキュ Docker Engine、Docker Compose、サイトを公開する HTTP(S) の URL を用意します。Compose ファイルをダウンロードし、`DOCA_ORIGIN` と専用に生成した資格情報用のマスターキーを設定してから起動します。初回起動時に管理者が初期化されます。 ```sh -curl -fL https://github.com/workhold/doca/releases/download/v0.3.1/doca-compose-v0.3.1.yaml -o compose.yaml +curl -fL https://github.com/workhold/doca/releases/download/v0.3.2/doca-compose-v0.3.2.yaml -o compose.yaml ``` ```sh diff --git a/README.ko.md b/README.ko.md index c9059d95..0bfc0e8e 100644 --- a/README.ko.md +++ b/README.ko.md @@ -37,7 +37,7 @@ Doca는 개인과 소규모 팀을 위한 오픈 소스 문서 및 지식 관리 Docker Engine, Docker Compose 및 사이트의 HTTP(S) 주소를 준비합니다. Compose 파일을 내려받고 `DOCA_ORIGIN`과 새로 생성한 자격 증명용 마스터 키를 설정한 뒤 실행합니다. 처음 실행할 때 관리자 계정이 초기화됩니다. ```sh -curl -fL https://github.com/workhold/doca/releases/download/v0.3.1/doca-compose-v0.3.1.yaml -o compose.yaml +curl -fL https://github.com/workhold/doca/releases/download/v0.3.2/doca-compose-v0.3.2.yaml -o compose.yaml ``` ```sh diff --git a/README.md b/README.md index 6e109ba3..7951552f 100644 --- a/README.md +++ b/README.md @@ -116,12 +116,12 @@ Installers are available from [GitHub Releases](https://github.com/workhold/doca ## Quick start with Docker -Requires Docker Engine, Docker Compose, and an HTTP(S) origin served by a reverse proxy. A fresh SQLite/local-storage installation needs only one YAML file: no Git, no source checkout, no seccomp JSON, and no external initialization scripts. Existing installations must read the [release requirements](https://workhold.github.io/doca/#/en/releases/0.3.1) and retain their project name, volumes, databases, attachments and master key. +Requires Docker Engine, Docker Compose, and an HTTP(S) origin served by a reverse proxy. A fresh SQLite/local-storage installation needs only one YAML file: no Git, no source checkout, no seccomp JSON, and no external initialization scripts. Existing installations must read the [release requirements](https://workhold.github.io/doca/#/en/releases/0.3.2) and retain their project name, volumes, databases, attachments and master key. ```sh # 1. Download the standalone configuration into a permanent deployment directory mkdir doca && cd doca -curl -fL https://github.com/workhold/doca/releases/download/v0.3.1/doca-compose-v0.3.1.yaml -o compose.yaml +curl -fL https://github.com/workhold/doca/releases/download/v0.3.2/doca-compose-v0.3.2.yaml -o compose.yaml # 2. Generate the master key with openssl rand -hex 32 # Edit compose.yaml: fill in DOCA_ORIGIN and DOCA_CREDENTIAL_MASTER_KEY @@ -168,7 +168,7 @@ Open `http://127.0.0.1:39130`. Initialize the administrator with `bash scripts/b - [Deployment and configuration](https://workhold.github.io/doca/#/en/operations/deployment) - [Plugin development](https://workhold.github.io/doca/#/en/plugins/plugin-development) - [HTTP API](https://workhold.github.io/doca/#/en/reference/api); the running application also provides `/api/openapi.json`. -- [Release notes](https://workhold.github.io/doca/#/en/releases/0.3.1) +- [Release notes](https://workhold.github.io/doca/#/en/releases/0.3.2) - [Documentation source](docs/README.md) For a documentation preview, run `pnpm docs:dev` and open `http://127.0.0.1:39140/#/en/`. `pnpm docs:check` verifies language editions and local links. See the GitHub Pages setup in [documentation maintenance](docs/documentation.md). diff --git a/README.ru.md b/README.ru.md index 240cac56..a4c50c5b 100644 --- a/README.ru.md +++ b/README.ru.md @@ -37,7 +37,7 @@ Doca — рабочее пространство с открытым исход Подготовьте Docker Engine, Docker Compose и адрес сайта по HTTP(S). Скачайте файл Compose, задайте `DOCA_ORIGIN` и сгенерируйте отдельный мастер-ключ учётных данных. Затем запустите сервис. Учётная запись администратора инициализируется при первом запуске. ```sh -curl -fL https://github.com/workhold/doca/releases/download/v0.3.1/doca-compose-v0.3.1.yaml -o compose.yaml +curl -fL https://github.com/workhold/doca/releases/download/v0.3.2/doca-compose-v0.3.2.yaml -o compose.yaml ``` ```sh diff --git a/README.zh-CN.md b/README.zh-CN.md index cbe62c53..fddd5570 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -114,12 +114,12 @@ Doca 桌面客户端(Windows、macOS)连接你部署的 Doca 服务:工作 ## Docker 快速开始 -需要 Docker Engine、Docker Compose,以及通过反向代理访问的 HTTP(S) 地址。全新 SQLite/本地存储安装只需一个 YAML,无需 Git、源码、seccomp JSON 或外部初始化脚本。已有部署更换版本前,先阅读[发行要求](https://workhold.github.io/doca/#/zh-cn/releases/0.3.1),保留原项目名、持久卷、数据库、附件和主密钥。 +需要 Docker Engine、Docker Compose,以及通过反向代理访问的 HTTP(S) 地址。全新 SQLite/本地存储安装只需一个 YAML,无需 Git、源码、seccomp JSON 或外部初始化脚本。已有部署更换版本前,先阅读[发行要求](https://workhold.github.io/doca/#/zh-cn/releases/0.3.2),保留原项目名、持久卷、数据库、附件和主密钥。 ```sh # 1. 在固定部署目录下载单文件配置 mkdir doca && cd doca -curl -fL https://github.com/workhold/doca/releases/download/v0.3.1/doca-compose-v0.3.1.yaml -o compose.yaml +curl -fL https://github.com/workhold/doca/releases/download/v0.3.2/doca-compose-v0.3.2.yaml -o compose.yaml # 2. 用 openssl rand -hex 32 生成主密钥 # 编辑 compose.yaml,填写 DOCA_ORIGIN 和 DOCA_CREDENTIAL_MASTER_KEY @@ -166,7 +166,7 @@ pnpm dev - [部署与配置](https://workhold.github.io/doca/#/zh-cn/operations/deployment) - [插件开发](https://workhold.github.io/doca/#/zh-cn/plugins/plugin-development) - [HTTP API](https://workhold.github.io/doca/#/zh-cn/reference/api),运行中的应用还提供 `/api/openapi.json`。 -- [发行记录](https://workhold.github.io/doca/#/zh-cn/releases/0.3.1) +- [发行记录](https://workhold.github.io/doca/#/zh-cn/releases/0.3.2) - [文档源码](docs/README.zh-CN.md) 预览文档时,执行 `pnpm docs:dev` 并打开 `http://127.0.0.1:39140/#/zh-cn/`。`pnpm docs:check` 校验语言版本和本地链接。GitHub Pages 设置见[文档维护](docs/documentation.zh-CN.md)。 diff --git a/README.zh-Hant.md b/README.zh-Hant.md index 35f1ccc6..f3ae9725 100644 --- a/README.zh-Hant.md +++ b/README.zh-Hant.md @@ -37,7 +37,7 @@ Doca 是面向個人和小型團隊的開放原始碼文件與知識管理工作 請準備 Docker Engine、Docker Compose 以及網站的 HTTP(S) 公開位址。下載 Compose 檔案,填寫 `DOCA_ORIGIN` 並產生專用的憑證主金鑰,再啟動服務。首次啟動會初始化管理員。 ```sh -curl -fL https://github.com/workhold/doca/releases/download/v0.3.1/doca-compose-v0.3.1.yaml -o compose.yaml +curl -fL https://github.com/workhold/doca/releases/download/v0.3.2/doca-compose-v0.3.2.yaml -o compose.yaml ``` ```sh diff --git a/apps/desktop/package.json b/apps/desktop/package.json index d845937a..0c2cc3a0 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@doca/desktop", - "version": "0.3.3", + "version": "0.3.4", "license": "MIT", "private": true, "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index f3bae604..bb52b0ed 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -1020,7 +1020,7 @@ dependencies = [ [[package]] name = "doca-desktop" -version = "0.3.3" +version = "0.3.4" dependencies = [ "aes-gcm", "axum", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 81aef92b..761fa70d 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "doca-desktop" -version = "0.3.3" +version = "0.3.4" description = "Doca desktop client" authors = ["Doca"] edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index d093d957..1011978a 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Doca", - "version": "0.3.3", + "version": "0.3.4", "identifier": "com.smartdoca.desktop", "build": { "beforeDevCommand": "pnpm exec vite --host 127.0.0.1 --port 1420 --strictPort", diff --git a/apps/mobile/app.json b/apps/mobile/app.json index 56064a9e..8a2e87c2 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -3,9 +3,12 @@ "name": "Doca", "slug": "zhangxiaojia", "scheme": "doca", - "version": "0.1.0", + "version": "0.1.1", "orientation": "portrait", "userInterfaceStyle": "light", + "developmentClient": { + "silentLaunch": true + }, "newArchEnabled": true, "ios": { "supportsTablet": true, @@ -14,11 +17,12 @@ "NSAppTransportSecurity": { "NSAllowsArbitraryLoads": true }, - "NSCameraUsageDescription": "允许 Doca 扫描网页登录二维码。" + "NSCameraUsageDescription": "允许 Doca 扫描网页登录二维码或拍照上传。" } }, "android": { "package": "app.doca.mobile", + "versionCode": 2, "usesCleartextTraffic": true, "adaptiveIcon": { "backgroundColor": "#f7f4ee" @@ -36,13 +40,13 @@ "expo-image-picker", { "photosPermission": "允许 Doca 读取相册,以便上传图片。", - "cameraPermission": "允许 Doca 拍摄图片,以便发送给 AI 助手。" + "cameraPermission": "允许 Doca 拍摄图片,以便上传或发送给 AI 助手。" } ], [ "expo-camera", { - "cameraPermission": "允许 Doca 扫描网页登录二维码。" + "cameraPermission": "允许 Doca 扫描网页登录二维码或拍照上传。" } ] ], diff --git a/apps/mobile/app/(tabs)/_layout.tsx b/apps/mobile/app/(tabs)/_layout.tsx index 05707a47..bea8e42e 100644 --- a/apps/mobile/app/(tabs)/_layout.tsx +++ b/apps/mobile/app/(tabs)/_layout.tsx @@ -1,68 +1,115 @@ -import { MobileNavigationArea } from "../../src/plugins/navigation"; -import { Tabs } from "expo-router"; -import { BookOpen, FolderOpen, Home, Sparkles } from "lucide-react-native"; +import { Tabs, useRouter, useSegments } from "expo-router"; +import { BookOpen, MessageSquare, Sparkles, UserRound } from "lucide-react-native"; +import { useEffect, useState } from "react"; +import { Keyboard, Platform, Pressable, StyleSheet, Text, View } from "react-native"; import { IconButton } from "react-native-paper"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useAppDrawer } from "../../src/app-drawer"; +import { useAuth } from "../../src/auth"; import { colors } from "../../src/chrome"; import { useI18n } from "../../src/locale"; -import { - mobilePluginMessage, - mobilePluginRegistry, -} from "../../src/plugins/registry"; +import { MobileNavigationArea } from "../../src/plugins/navigation"; +import { mobilePluginMessage, mobilePluginRegistry } from "../../src/plugins/registry"; + +const homeToolbarExclusions = ["doca.search"]; export default function TabsLayout() { const drawer = useAppDrawer(); - const { locale } = useI18n(); - const librariesTab = - mobilePluginRegistry.tabs.getByConflictKey("libraries"); + const [keyboardVisible, setKeyboardVisible] = useState(false); + const isAi = useSegments().includes("ai"); + const { locale, t } = useI18n(); + const { session } = useAuth(); + const router = useRouter(); + const insets = useSafeAreaInsets(); + const libraryTab = mobilePluginRegistry.tabs.getByConflictKey("libraries"); const filesTab = mobilePluginRegistry.tabs.getByConflictKey("files"); + const avatar = session?.name.trim().slice(0, 1); + useEffect(() => { + const showing = Keyboard.addListener(Platform.OS === "ios" ? "keyboardWillShow" : "keyboardDidShow", () => setKeyboardVisible(true)); + const hiding = Keyboard.addListener(Platform.OS === "ios" ? "keyboardWillHide" : "keyboardDidHide", () => setKeyboardVisible(false)); + return () => { + showing.remove(); + hiding.remove(); + }; + }, []); + + function headerRight(home = false, showHistory = false) { + return ( + + + {showHistory ? ( + + + + ) : null} + router.push("/me")} style={styles.headerButton}> + + {avatar ? {avatar} : } + + + + ); + } + return ( null} + tabBar={() => drawer.hasBrowseRail || (isAi && keyboardVisible) ? null : ( + + + + )} screenOptions={{ + headerTitleAlign: "left", headerTintColor: colors.ink, - headerStyle: { backgroundColor: "#fff" }, + headerStyle: { backgroundColor: colors.card }, headerShadowVisible: false, sceneStyle: { backgroundColor: colors.bg }, - tabBarActiveTintColor: colors.accent, - tabBarInactiveTintColor: colors.muted, - tabBarStyle: { backgroundColor: "#fff", borderTopColor: colors.lineSoft }, - headerRight: () => , - headerLeft: () => , + headerRight: () => headerRight(), + headerLeft: drawer.hasBrowseRail + ? () => + : undefined, }} > - , - }} - /> - , - }} - /> - , - }} - /> - , - }} - /> + ( + + + + Doca + {session ? {session.origin.replace(/^https?:\/\//, "")} : null} + + + ), + headerRight: () => headerRight(true), + }} /> + + + ( + + + {t("nav.assistant")} + + ), + headerRight: () => headerRight(false, true), + }} /> ); } + +const styles = StyleSheet.create({ + tabBar: { backgroundColor: colors.card, borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: colors.line, paddingTop: 3, paddingHorizontal: 8 }, + headerActions: { flexDirection: "row", alignItems: "center", marginRight: 8 }, + headerButton: { minWidth: 46, minHeight: 46, justifyContent: "center", alignItems: "center" }, + avatar: { width: 35, height: 35, borderRadius: 18, backgroundColor: colors.selected, alignItems: "center", justifyContent: "center" }, + avatarText: { color: colors.accent, fontSize: 15, fontWeight: "700" }, + brand: { flexDirection: "row", alignItems: "center", gap: 9 }, + brandMark: { width: 37, height: 37, borderRadius: 10, borderCurve: "continuous", backgroundColor: colors.accent, alignItems: "center", justifyContent: "center" }, + brandCopy: { minWidth: 0 }, + brandName: { color: colors.ink, fontSize: 22, fontWeight: "800", letterSpacing: -0.6 }, + brandOrigin: { color: colors.secondary, fontSize: 11 }, + assistantMark: { width: 32, height: 32, borderRadius: 9, borderCurve: "continuous", backgroundColor: colors.assistantSoft, alignItems: "center", justifyContent: "center" }, + assistantTitle: { color: colors.ink, fontSize: 17, fontWeight: "700", flexShrink: 1 }, +}); diff --git a/apps/mobile/app/(tabs)/ai.tsx b/apps/mobile/app/(tabs)/ai.tsx index 5d3402c5..b8ecff0f 100644 --- a/apps/mobile/app/(tabs)/ai.tsx +++ b/apps/mobile/app/(tabs)/ai.tsx @@ -1,10 +1,14 @@ import { useQueryClient } from "@tanstack/react-query"; +import { useRouter } from "expo-router"; import { useEffect, useRef, useState } from "react"; +import { View } from "react-native"; +import { Button } from "react-native-paper"; import { Conversation } from "../ai/[id]"; import { api } from "../../src/api"; import { getAiSession, setAiSession, subscribeAiSession } from "../../src/ai-session"; import { useAuth } from "../../src/auth"; import { EmptyState, LoadingState } from "../../src/chrome"; +import { useI18n } from "../../src/locale"; type SessionRow = { id: string; title: string }; type Options = { @@ -15,9 +19,12 @@ type Options = { export default function AI() { const client = useQueryClient(); + const router = useRouter(); + const { t } = useI18n(); const { session } = useAuth(); const [picked, setPicked] = useState(getAiSession()); const [error, setError] = useState(""); + const [attempt, setAttempt] = useState(0); const origin = session?.origin ?? ""; const seenOrigin = useRef(origin); @@ -35,30 +42,38 @@ export default function AI() { let cancel = false; void (async () => { try { - const data = await api("/ai/sessions?archived=false"); + const data = await api("/ai/sessions?archived=false", { session }); const rows = Array.isArray(data) ? data : data.items; if (cancel) return; if (rows[0]) { setAiSession(rows[0].id); return; } - const options = await api("/ai/options"); + const options = await api("/ai/options", { session }); const modelId = options.preferences?.default_model || options.defaultModel || options.models[0]?.id; - if (!modelId) throw new Error("还没有可用的模型"); - const created = await api<{ id: string }>("/ai/sessions", { body: { title: "新对话", modelId } }); + if (!modelId || !options.models.length) throw new Error(t("chat.noModel")); + const created = await api<{ id: string }>("/ai/sessions", { session, body: { title: t("chat.newChat"), modelId } }); if (cancel) return; await client.invalidateQueries({ queryKey: ["ai-sessions", session.origin] }); - setAiSession(created.id); + if (!cancel) setAiSession(created.id); } catch (reason) { - if (!cancel) setError(reason instanceof Error ? reason.message : "无法打开对话"); + if (!cancel) setError(reason instanceof Error ? reason.message : t("common.failed")); } })(); return () => { cancel = true; }; - }, [client, picked, session]); + }, [attempt, client, picked, session, t]); - if (error) return ; - if (!picked) return ; - return ; + if (error && !picked) { + return ( + + + + + + ); + } + if (!picked || seenOrigin.current !== origin) return ; + return ; } diff --git a/apps/mobile/app/(tabs)/index.tsx b/apps/mobile/app/(tabs)/index.tsx index 5314de4c..1a935728 100644 --- a/apps/mobile/app/(tabs)/index.tsx +++ b/apps/mobile/app/(tabs)/index.tsx @@ -1,72 +1,69 @@ -import { MobileNavigationArea } from "../../src/plugins/navigation"; +import type { MessageKey } from "@doca/i18n"; import { useRouter } from "expo-router"; import { Search } from "lucide-react-native"; import { useState } from "react"; import { Pressable, ScrollView, StyleSheet, View } from "react-native"; import { Text } from "react-native-paper"; import { colors } from "../../src/chrome"; +import { useI18n } from "../../src/locale"; +import { MobileNavigationArea } from "../../src/plugins/navigation"; import { ResourceList } from "../../src/resource-list"; -const tabs = [ - { - key: "recent", - label: "最近浏览", - empty: "还没有最近浏览的文档", - params: { scope: "recent", kind: "document", sort: "visited_at", order: "desc" }, - }, - { - key: "owned", - label: "我的文档", - empty: "还没有归你所有的文档", - params: { scope: "owned", kind: "document", sort: "updated_at", order: "desc" }, - }, - { - key: "shared", - label: "与我共享", - empty: "还没有共享给你的文档", - params: { scope: "shared", kind: "document", sort: "updated_at", order: "desc" }, - }, - { - key: "favorites", - label: "收藏文档", - empty: "还没有收藏的文档", - params: { scope: "favorites", kind: "document", sort: "updated_at", order: "desc" }, - }, - { - key: "libraries", - label: "收藏知识库", - empty: "还没有收藏的知识库", - params: { scope: "favorites", kind: "library", sort: "updated_at", order: "desc" }, - }, -] as const; +const filters = [ + { scope: "recent", label: "home.tab.recent", sort: "visited_at" }, + { scope: "owned", label: "home.mine", sort: "updated_at" }, + { scope: "favorites", label: "home.tab.favorites", sort: "updated_at" }, + { scope: "shared", label: "home.tab.shared", sort: "updated_at" }, + { scope: "favorites", label: "home.tab.libraries", sort: "updated_at" }, +] as const satisfies readonly { scope: string; label: MessageKey; sort: string }[]; export default function Home() { const router = useRouter(); - const [tab, setTab] = useState<(typeof tabs)[number]["key"]>("recent"); - const current = tabs.find((item) => item.key === tab) ?? tabs[0]; + const { t } = useI18n(); + const [selected, setSelected] = useState("home.tab.recent"); + const filter = filters.find((item) => item.label === selected) ?? filters[0]; return ( - - router.push("/search")}> - - 搜索文档、文件和邮件 - - + [styles.search, pressed && styles.pressed]} + onPress={() => router.push("/search")} > - {tabs.map((item) => { - const active = item.key === current.key; - return ( - setTab(item.key)} style={[styles.chip, active && styles.chipActive]}> - {item.label} - - ); - })} - - + + {t("mobile.home.search")} + + + {filters.map(({ label }) => ( + setSelected(label)} + style={[styles.filter, label === selected && styles.selected]} + > + {t(label)} + + ))} + + } + /> ); } @@ -74,31 +71,16 @@ export default function Home() { const styles = StyleSheet.create({ page: { flex: 1, backgroundColor: colors.bg }, search: { - height: 36, - marginHorizontal: 16, - marginTop: 8, - paddingHorizontal: 12, - borderRadius: 8, - backgroundColor: "#fff", - borderWidth: StyleSheet.hairlineWidth, - borderColor: colors.line, - flexDirection: "row", - alignItems: "center", - gap: 8, - }, - searchText: { color: colors.muted, fontSize: 14 }, - tabBar: { height: 48, flexGrow: 0, flexShrink: 0 }, - tabs: { alignItems: "center", paddingHorizontal: 16, paddingVertical: 8, gap: 8 }, - chip: { - alignSelf: "flex-start", - backgroundColor: "#fff", - borderRadius: 16, - borderWidth: StyleSheet.hairlineWidth, - borderColor: colors.line, - paddingHorizontal: 12, - paddingVertical: 6, + minHeight: 50, marginHorizontal: 18, marginTop: 10, marginBottom: 5, + paddingHorizontal: 14, borderRadius: 13, borderCurve: "continuous", + borderWidth: StyleSheet.hairlineWidth, borderColor: colors.line, + backgroundColor: colors.card, flexDirection: "row", alignItems: "center", gap: 10, }, - chipActive: { backgroundColor: colors.selected, borderColor: colors.selected }, - chipText: { color: colors.secondary, fontSize: 14 }, - chipTextActive: { color: colors.accent, fontWeight: "600" }, + pressed: { opacity: 0.72 }, + searchText: { color: colors.secondary, flex: 1, fontSize: 15 }, + filters: { paddingHorizontal: 16, gap: 8, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: colors.line }, + filter: { minHeight: 48, borderBottomWidth: 2, borderBottomColor: "transparent", paddingHorizontal: 8, justifyContent: "center" }, + selected: { borderBottomColor: colors.accent }, + filterText: { color: colors.secondary, fontSize: 13 }, + selectedText: { color: colors.accent, fontWeight: "700" }, }); diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx index 553bc5e7..c9ddec97 100644 --- a/apps/mobile/app/_layout.tsx +++ b/apps/mobile/app/_layout.tsx @@ -3,14 +3,14 @@ import { BottomSheetModalProvider } from "@gorhom/bottom-sheet"; import { QueryClientProvider, useQuery, useQueryClient } from "@tanstack/react-query"; import { Stack, usePathname, useRouter, useSegments } from "expo-router"; import { StatusBar } from "expo-status-bar"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { GestureHandlerRootView } from "react-native-gesture-handler"; -import { View, Pressable, ScrollView, StyleSheet, Text } from "react-native"; +import { View, Pressable, ScrollView, StyleSheet, Text, useWindowDimensions } from "react-native"; import MaterialCommunityIcons from "@expo/vector-icons/MaterialCommunityIcons"; -import { MD3LightTheme, PaperProvider } from "react-native-paper"; +import { Button, MD3LightTheme, PaperProvider } from "react-native-paper"; import { SafeAreaProvider, useSafeAreaInsets } from "react-native-safe-area-context"; import { Drawer } from "react-native-drawer-layout"; -import { ChevronRight, Sparkles } from "lucide-react-native"; +import { ChevronRight, MessageSquare } from "lucide-react-native"; import { AuthProvider, useAuth } from "../src/auth"; import { MobileNavigationArea } from "../src/plugins/navigation"; import { @@ -20,9 +20,9 @@ import { import { AppDrawerContext } from "../src/app-drawer"; import { api } from "../src/api"; import { setAiSession } from "../src/ai-session"; -import { colors } from "../src/chrome"; +import { colors, EmptyState, LoadingState } from "../src/chrome"; import { LocaleProvider, useI18n } from "../src/locale"; -import { persistQueryCache, queryClient, restoreQueryCache } from "../src/query-cache"; +import { discardLegacyQueryCache, queryClient } from "../src/query-cache"; const theme = { ...MD3LightTheme, @@ -66,8 +66,9 @@ function AccountMenu({ close }: { close: () => void }) { const router = useRouter(); const insets = useSafeAreaInsets(); const { session } = useAuth(); - const { locale } = useI18n(); - const initial = (session?.name || "我").slice(0, 1); + const { t } = useI18n(); + if (!session) return null; + const initial = session.name.slice(0, 1); function open(path: "/account" | "/settings") { close(); @@ -81,9 +82,9 @@ function AccountMenu({ close }: { close: () => void }) { {initial} - {session?.name || "未登录"} + {session.name} - 个人信息 + {t("account.profile")} @@ -99,11 +100,14 @@ function SessionMenu({ close }: { close: () => void }) { const client = useQueryClient(); const insets = useSafeAreaInsets(); const { session } = useAuth(); + const { t } = useI18n(); + const [busy, setBusy] = useState(false); const [menuError, setMenuError] = useState(""); + const creating = useRef(false); const sessions = useQuery({ queryKey: ["ai-sessions", session?.origin], enabled: !!session, - queryFn: () => api("/ai/sessions?archived=false"), + queryFn: () => api("/ai/sessions?archived=false", { session }), }); function openSession(id: string) { @@ -113,47 +117,59 @@ function SessionMenu({ close }: { close: () => void }) { } async function createSession() { + if (!session || creating.current) return; + creating.current = true; + setBusy(true); setMenuError(""); try { const options = await api<{ defaultModel: string; models: { id: string }[]; preferences?: { default_model?: string | null }; - }>("/ai/options"); + }>("/ai/options", { session }); const modelId = options.preferences?.default_model || options.defaultModel || options.models[0]?.id; - if (!modelId) { - setMenuError("还没有可用的模型"); - return; - } - const created = await api<{ id: string }>("/ai/sessions", { body: { title: "新对话", modelId } }); - await client.invalidateQueries({ queryKey: ["ai-sessions", session?.origin] }); + if (!modelId || !options.models.length) throw new Error(t("chat.noModel")); + const created = await api<{ id: string }>("/ai/sessions", { + session, + body: { title: t("chat.newChat"), modelId }, + }); + await client.invalidateQueries({ queryKey: ["ai-sessions", session.origin] }); openSession(created.id); } catch (reason) { - setMenuError(reason instanceof Error ? reason.message : "无法新建对话"); + setMenuError(reason instanceof Error ? reason.message : t("common.failed")); + } finally { + creating.current = false; + setBusy(false); } } return ( - - - - 对话 - void createSession()}> - 新对话 - + + + {t("chat.history")} + - {menuError ? {menuError} : null} - - {(sessions.data ?? []).map((item) => ( - openSession(item.id)}> - - - {item.title || "新对话"} - - - ))} - - + {menuError ? {menuError} : null} + {sessions.isPending ? : null} + {sessions.isError ? ( + <> + {sessions.error.message} + + + ) : null} + {!sessions.isPending && !sessions.isError && !sessions.data?.length ? : null} + {sessions.data?.map((item) => ( + openSession(item.id)}> + + {item.title || t("chat.newChat")} + + + ))} + + ); } @@ -164,30 +180,40 @@ function SessionMenu({ close }: { close: () => void }) { function RootShell() { const [drawerOpen, setDrawerOpen] = useState(false); const segments = useSegments(); + const { session } = useAuth(); + const hasBrowseRail = useWindowDimensions().width >= 600; const inTabs = segments[0] === "(tabs)"; const ai = segments.includes("ai"); - const controls = useMemo(() => ({ open: () => setDrawerOpen(true) }), []); + const canOpenDrawer = !!session && inTabs && (ai || hasBrowseRail); + const controls = useMemo(() => ({ open: () => setDrawerOpen(true), hasBrowseRail }), [hasBrowseRail]); + useEffect(() => { + setDrawerOpen(false); + }, [session?.origin, inTabs, ai, hasBrowseRail]); const closeDrawer = () => setDrawerOpen(false); const { t } = useI18n(); return ( setDrawerOpen(true)} onClose={closeDrawer} swipeEdgeWidth={28} - swipeEnabled={inTabs} + swipeEnabled={canOpenDrawer} drawerStyle={menuStyles.drawer} renderDrawerContent={() => - ai ? : + canOpenDrawer && drawerOpen + ? ai ? : + : null } > + - + {hasBrowseRail ? : null} + + @@ -240,32 +268,18 @@ const menuStyles = StyleSheet.create({ userCopy: { flex: 1 }, name: { color: colors.ink, fontSize: 16, fontWeight: "600" }, origin: { color: colors.muted, fontSize: 12, marginTop: 2 }, - section: { color: colors.muted, fontSize: 12, marginBottom: 8 }, - sessionHead: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", marginTop: 18 }, - link: { color: colors.accent, fontSize: 13, marginBottom: 8 }, - error: { color: colors.danger, fontSize: 12, marginBottom: 8 }, - item: { - flexDirection: "row", - alignItems: "center", - gap: 10, - paddingVertical: 12, - paddingHorizontal: 8, - borderRadius: 8, - }, - itemText: { color: colors.ink, fontSize: 16 }, + drawerPage: { flex: 1, backgroundColor: colors.card }, + sessionHeading: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 12 }, + sessionTitle: { color: colors.ink, fontSize: 17, fontWeight: "700" }, + session: { minHeight: 49, paddingVertical: 6, paddingHorizontal: 8, flexDirection: "row", alignItems: "center", gap: 9 }, + sessionLabel: { color: colors.ink, fontSize: 14, flex: 1 }, + error: { color: colors.danger, padding: 10 }, }); export default function RootLayout() { - const [ready, setReady] = useState(false); useEffect(() => { - let stop: () => void = () => undefined; - void restoreQueryCache().finally(() => { - stop = persistQueryCache(); - setReady(true); - }); - return () => stop(); + void discardLegacyQueryCache(); }, []); - if (!ready) return null; return ( diff --git a/apps/mobile/app/account.tsx b/apps/mobile/app/account.tsx index a83f76ba..2361ef46 100644 --- a/apps/mobile/app/account.tsx +++ b/apps/mobile/app/account.tsx @@ -260,7 +260,9 @@ export default function Account() { } await api("/auth/password", { body: { newPassword: nextPassword } }); Alert.alert("密码已修改", "所有设备上的登录已退出,请用新密码重新登录。", [ - { text: "确定", onPress: () => void signOut() }, + { text: "确定", onPress: () => { + void signOut().catch((error) => Alert.alert("退出登录失败", error instanceof Error ? error.message : undefined)); + } }, ]); } diff --git a/apps/mobile/app/ai/[id].tsx b/apps/mobile/app/ai/[id].tsx index dae2c568..977e021f 100644 --- a/apps/mobile/app/ai/[id].tsx +++ b/apps/mobile/app/ai/[id].tsx @@ -1,19 +1,22 @@ import { useQuery } from "@tanstack/react-query"; +import type { AssistantLaunchDraft } from "@smartdoca/plugin-sdk/web"; import * as DocumentPicker from "expo-document-picker"; import * as FileSystem from "expo-file-system"; import { Image } from "expo-image"; import * as ImagePicker from "expo-image-picker"; import { useLocalSearchParams, useNavigation, useRouter } from "expo-router"; import * as Sharing from "expo-sharing"; -import { ArrowUp, Paperclip } from "lucide-react-native"; +import { ArrowUp, AtSign, Check, ChevronDown, FileText, Globe, Plus, Square } from "lucide-react-native"; import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; -import { Alert, Dimensions, Pressable, ScrollView, StyleSheet, Text, View } from "react-native"; +import { Pressable, ScrollView, StyleSheet, Text, useWindowDimensions, View } from "react-native"; import { Composer, GiftedChat, InputToolbar, type IMessage } from "react-native-gifted-chat"; -import { IconButton } from "react-native-paper"; +import { Button, Dialog, IconButton, Portal } from "react-native-paper"; import EventSource from "react-native-sse"; import { useSafeAreaInsets } from "react-native-safe-area-context"; -import { api, uuid } from "../../src/api"; +import { api, uuid, type Resource } from "../../src/api"; import { AnswerBody, ApprovalCards, type ApprovalItem } from "../../src/ai-answer"; +import { openDocument } from "../../src/ai-open"; +import { ReferencePicker } from "../../src/ai-reference-picker"; import { AiTrace, type TraceEvent, type TraceOperation } from "../../src/ai-trace"; import { systemErrorMessage } from "../../src/system-errors"; import { useI18n } from "../../src/locale"; @@ -29,14 +32,16 @@ type ChatAttachment = { size: number; uri?: string; }; +type ChatReference = AssistantLaunchDraft["references"][number]; type ApiMessage = { id: string; role: string; text: string; createdAt: string; attachments?: ChatAttachment[]; + references?: ChatReference[]; }; -type ChatMessage = IMessage & { attachments?: ChatAttachment[]; revision?: number }; +type ChatMessage = IMessage & { attachments?: ChatAttachment[]; references?: ChatReference[]; revision?: number }; type PendingFile = { localId: string; name: string; @@ -66,7 +71,7 @@ type Detail = { type Options = { defaultModel: string; webSearchAvailable: boolean; - models: { id: string }[]; + models: { id: string; name: string }[]; preferences?: { default_model?: string | null }; }; type JobEvent = { @@ -101,6 +106,7 @@ function toMessages(rows: ApiMessage[]): ChatMessage[] { createdAt: new Date(row.createdAt), user: row.role === "user" ? { _id: "me", name: "我" } : { _id: "ai", name: "Doca" }, attachments: row.attachments?.filter((file) => file.id && file.filename), + references: row.references, })); } @@ -140,9 +146,11 @@ function linkedJob(id: string | number) { } const prompts = ["帮我列一个提纲", "把这段话写得更清楚", "总结今天要做的事"]; -const screenWidth = Dimensions.get("window").width; - -export function Conversation({ sessionId, heading }: { sessionId?: string; heading?: string }) { +export function Conversation({ sessionId, heading, inTabs = false }: { + sessionId?: string; + heading?: string; + inTabs?: boolean; +}) { const { t } = useI18n(); const params = useLocalSearchParams<{ id: string; title?: string; launch?: string }>(); const id = sessionId || (typeof params.id === "string" ? params.id : ""); @@ -150,12 +158,22 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi const navigation = useNavigation(); const router = useRouter(); const insets = useSafeAreaInsets(); + const { width } = useWindowDimensions(); const { session } = useAuth(); const [launch, setLaunch] = useState>(null); const [composerText, setComposerText] = useState(""); - const [references, setReferences] = useState["references"]>([]); + const [references, setReferences] = useState([]); const [messages, setMessages] = useState([]); const [pending, setPending] = useState([]); + const [pickingAttachment, setPickingAttachment] = useState(false); + const [pickingReference, setPickingReference] = useState(false); + const [pickingModel, setPickingModel] = useState(false); + const [chosenModel, setChosenModel] = useState(null); + const [changingModel, setChangingModel] = useState(false); + const [webChoice, setWebChoice] = useState(null); + const [sending, setSending] = useState(false); + const sendPending = useRef(false); + const [stopping, setStopping] = useState(false); const draftScope = `${session?.origin}:${session?.token}:${id}`; const previousDraftScope = useRef(draftScope); useEffect(() => { @@ -165,6 +183,8 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi setComposerText(""); setReferences([]); setPending([]); + setChosenModel(null); + setWebChoice(null); } const draft = consumeAssistantDraft(session, params.launch, id); if (!draft) return; @@ -194,12 +214,12 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi queryKey: ["ai-session", session?.origin, id], enabled: !!session && !!id, staleTime: 0, - queryFn: () => api(`/ai/sessions/${id}`), + queryFn: ({ signal }) => api(`/ai/sessions/${id}`, { session, signal }), }); const options = useQuery({ queryKey: ["ai-options", session?.origin], enabled: !!session, - queryFn: () => api("/ai/options"), + queryFn: ({ signal }) => api("/ai/options", { session, signal }), }); const refetch = detail.refetch; useEffect(() => { @@ -210,18 +230,23 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi setTraces(next); }, []); const modelId = - launch?.modelId || detail.data?.session.model_id || + chosenModel || launch?.modelId || detail.data?.session.model_id || options.data?.preferences?.default_model || options.data?.defaultModel || options.data?.models[0]?.id || ""; + const webSearchAvailable = !!options.data?.webSearchAvailable; + const webSearch = webSearchAvailable && (webChoice ?? true); + const currentModel = options.data?.models.find((model) => model.id === modelId); + const hasActiveJob = jobs.some((job) => activeStatus.has(job.status)); useLayoutEffect(() => { + if (inTabs) return; navigation.setOptions({ - title: detail.data?.session.title || title || "对话", - headerRight: () => router.push("/ai/settings")} />, + title: detail.data?.session.title || title || t("mobile.screen.conversation"), + headerRight: () => router.push("/ai/settings")} />, }); - }, [detail.data?.session.title, navigation, router, title]); + }, [detail.data?.session.title, inTabs, navigation, router, t, title]); const stopStream = useCallback(() => { running.current = false; @@ -469,7 +494,7 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi async function pickImages() { const permission = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (!permission.granted) { - setError("需要相册权限才能选择图片"); + setError(t("mobile.files.album.permission")); return; } const picked = await ImagePicker.launchImageLibraryAsync({ @@ -492,7 +517,7 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi async function takePhoto() { const permission = await ImagePicker.requestCameraPermissionsAsync(); if (!permission.granted) { - setError("需要相机权限才能拍照"); + setError(t("mobile.files.camera.permission")); return; } const picked = await ImagePicker.launchCameraAsync({ mediaTypes: ["images"], quality: 0.9 }); @@ -521,13 +546,68 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi ); } - function openAttachMenu() { - Alert.alert("添加附件", undefined, [ - { text: "相册", onPress: () => void pickImages() }, - { text: "拍照", onPress: () => void takePhoto() }, - { text: "文件", onPress: () => void pickDocuments() }, - { text: "取消", style: "cancel" }, - ]); + async function chooseAttachment(pick: () => Promise) { + setPickingAttachment(false); + setError(""); + try { + await pick(); + } catch (reason) { + setError(reason instanceof Error ? reason.message : t("common.failed")); + } + } + + function addReference(document: Resource) { + if (references.some((reference) => reference.resourceId === document.id)) { + setPickingReference(false); + return; + } + if (references.length >= 20) { + setError(t("chat.referenceLimit")); + setPickingReference(false); + return; + } + setReferences((current) => [...current, { + resourceId: document.id, + label: document.title || t("shell.untitled"), + format: document.format, + }]); + setPickingReference(false); + } + + async function selectModel(next: string) { + if (!session || changingModel) return; + if (next === modelId) { + setPickingModel(false); + return; + } + setChangingModel(true); + setError(""); + try { + await api(`/ai/sessions/${id}`, { method: "PATCH", body: { modelId: next }, session }); + setChosenModel(next); + setPickingModel(false); + await refetch(); + } catch (reason) { + setError(reason instanceof Error ? reason.message : t("common.failed")); + } finally { + setChangingModel(false); + } + } + + async function stopJobs() { + if (!session || stopping) return; + setStopping(true); + setError(""); + try { + await Promise.all(jobs.filter((job) => activeStatus.has(job.status)).map((job) => + api(`/ai/jobs/${job.id}/cancel`, { method: "POST", session }), + )); + await refetch(); + } catch (reason) { + setError(reason instanceof Error ? reason.message : t("common.failed")); + } finally { + setStopping(false); + } } async function openAttachment(file: ChatAttachment) { @@ -548,21 +628,18 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi } } - async function onSend(outgoing: ChatMessage[]) { - const typed = outgoing[0]?.text.trim() ?? ""; - if (pending.some((item) => item.status === "uploading")) { - setError("请等待附件上传完成"); - return; - } - if (pending.some((item) => item.status === "error")) { - setError("请移除上传失败的文件"); + async function sendText(input: string) { + if (!session || sendPending.current) return; + const typed = input.trim(); + if (pending.some((item) => item.status !== "done")) { + setError(t("chat.waitUpload")); return; } const ready = pending.filter((item) => item.status === "done" && item.id); - const text = typed || (ready.length ? "请分析这些附件" : ""); + const text = typed || (ready.length ? t("chat.analyzeAttachments") : ""); if (!text || !id) return; - if (!modelId) { - setError("还没有可用的模型"); + if (!currentModel) { + setError(t("chat.noModel")); return; } const attachments: ChatAttachment[] = ready.map((item) => ({ @@ -573,17 +650,20 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi uri: item.uri, })); const messageId = uuid(); + sendPending.current = true; + setSending(true); watch.current.add(messageId); setError(""); setMessages((current) => GiftedChat.append(current, [ - { _id: messageId, text, createdAt: new Date(), user: { _id: "me", name: "我" }, attachments }, + { _id: messageId, text, createdAt: new Date(), user: { _id: "me", name: "我" }, attachments, references }, ]), ); setTyping(true); running.current = true; try { await api(`/ai/sessions/${id}/messages`, { + session, body: { id: messageId, text, @@ -593,7 +673,7 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi attachments: attachments.map((file) => file.id), files: [], skillIds: [], - webSearch: !!options.data?.webSearchAvailable, + webSearch, }, }); setPending([]); @@ -601,10 +681,15 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi setComposerText(""); startStream(); } catch (reason) { - running.current = false; + watch.current.delete(messageId); + running.current = watch.current.size > 0; setTyping(false); setComposerText(typed); - setError(reason instanceof Error ? reason.message : "发送失败"); + setMessages((current) => current.filter((message) => message._id !== messageId)); + setError(reason instanceof Error ? reason.message : t("chat.sendFailed")); + } finally { + sendPending.current = false; + setSending(false); } } @@ -640,59 +725,79 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi } if (detail.isLoading) { - return 正在加载…; + return {t("common.loading")}; } - if (detail.isError) { - return {detail.error instanceof Error ? detail.error.message : "加载失败"}; + if (!detail.data && detail.isError) { + return ( + + {detail.error.message} + + + ); } + const canSend = !!currentModel && !sending && !changingModel + && !!(composerText.trim() || pending.some((item) => item.status === "done")) + && !pending.some((item) => item.status !== "done"); return ( - text={composerText} messages={messages} - onSend={(items) => void onSend(items)} + onSend={(items) => void sendText(items[0]?.text ?? "")} user={{ _id: "me", name: "我" }} - placeholder="发消息…" + placeholder={t("mobile.ai.placeholder")} alwaysShowSend isTyping={false} - bottomOffset={insets.bottom} + bottomOffset={inTabs ? -insets.bottom : insets.bottom} renderAvatar={null} renderTime={() => null} minComposerHeight={44} maxComposerHeight={120} - messagesContainerStyle={{ backgroundColor: colors.bg }} + messagesContainerStyle={{ backgroundColor: colors.card }} onLongPress={() => undefined} textInputProps={{ placeholderTextColor: colors.muted }} listViewProps={{ keyboardShouldPersistTaps: "handled", removeClippedSubviews: false }} renderBubble={(props) => { - const text = props.currentMessage?.text ?? ""; - const jobId = linkedJob(props.currentMessage?._id ?? ""); + const message = props.currentMessage as ChatMessage | undefined; + const text = message?.text ?? ""; + const jobId = linkedJob(message?._id ?? ""); const events = jobId ? traces[jobId] ?? [] : []; const operations = jobId ? (detail.data?.operations ?? []).filter((item) => item.job_id === jobId) : []; if (props.position === "left") { return ( - - Doca + + {text ? {t("nav.assistant")} : null} ); } return ( - + void openAttachment(file)} /> + {message?.references?.map((reference) => ( + openDocument(router, reference.resourceId)} + > + + @{reference.label} + + ))} {text ? {text} : null} ); @@ -700,12 +805,12 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi renderMessageText={() => null} renderChatEmpty={() => ( - 你好 - 我可以帮你写文档、整理邮件、回答问题。 + {t("chat.welcome")} + {t("chat.welcomeHelp")} )} renderFooter={() => - typing ? 正在思考… : jobs.some(job => job.status === "awaiting_dependency") ? {t("ai.progress.phase.waitingBackground")} : null + typing ? {t("chat.thinking")} : jobs.some(job => job.status === "awaiting_dependency") ? {t("ai.progress.phase.waitingBackground")} : null } renderChatFooter={() => ( @@ -735,7 +840,7 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi {file.name} - {file.status === "uploading" ? "上传中" : file.status === "error" ? "上传失败" : fileSize(file.size)} + {file.status === "uploading" ? t("common.uploading") : file.status === "error" ? t("fileManager.uploadFailed") : fileSize(file.size)} setPending((current) => current.filter((item) => item.localId !== file.localId))}> @@ -763,11 +868,7 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi - void onSend([ - { _id: uuid(), text: prompt, createdAt: new Date(), user: { _id: "me", name: "我" } }, - ]) - } + onPress={() => void sendText(prompt)} > {prompt} @@ -775,6 +876,9 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi ) : null} {error ? {systemErrorMessage(error, t)} : null} + {!error && options.isError ? ( + + ) : null} )} renderInputToolbar={(props) => ( @@ -782,6 +886,7 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi {...props} containerStyle={styles.toolbar} primaryStyle={styles.toolbarRow} + accessoryStyle={styles.toolbarAccessory} /> )} renderComposer={(props) => ( @@ -790,44 +895,113 @@ export function Conversation({ sessionId, heading }: { sessionId?: string; headi onTextChanged={setComposerText} textInputStyle={styles.composer} placeholderTextColor={colors.muted} + textInputProps={{ ...props.textInputProps, editable: !sending, accessibilityLabel: t("mobile.ai.placeholder") }} /> )} - renderActions={() => ( - - - - )} - renderSend={(props) => { - const typed = props.text?.trim() ?? ""; - const ready = pending.some((item) => item.status === "done"); - const uploading = pending.some((item) => item.status === "uploading"); - const failed = pending.some((item) => item.status === "error"); - const enabled = (!!typed || ready) && !uploading && !failed; - return ( + renderSend={() => <>} + renderAccessory={() => ( + + setPickingAttachment(true)} + > + + + setPickingReference(true)}> + + + setWebChoice(!webSearch)} + > + + + setPickingModel(true)} + > + {currentModel?.name || t("chat.noModel")} + + { - if (pending.some((item) => item.status === "uploading")) { - setError("请等待附件上传完成"); - return; - } - if (pending.some((item) => item.status === "error")) { - setError("请移除上传失败的文件"); - return; - } - if (!typed && !pending.some((item) => item.status === "done")) return; - props.onSend?.({ text: typed || "请分析这些附件" }, false); + if (hasActiveJob) void stopJobs(); + else void sendText(composerText); }} > - - + + {hasActiveJob ? + : } - ); - }} + + )} /> + {pickingReference ? ( + reference.resourceId))} + onSelect={addReference} + onDismiss={() => setPickingReference(false)} + /> + ) : null} + + setPickingAttachment(false)} style={styles.modelDialog}> + {t("chat.upload")} + + {[ + { label: t("mobile.files.album"), pick: pickImages }, + { label: t("mobile.files.camera"), pick: takePhoto }, + { label: t("search.files"), pick: pickDocuments }, + ].map(({ label, pick }) => ( + void chooseAttachment(pick)} style={styles.modelRow}> + {label} + + ))} + + + + setPickingModel(false)} style={styles.modelDialog}> + {t("chat.selectModel")} + {error && pickingModel ? {error} : null} + + + {options.data?.models.map((model) => ( + void selectModel(model.id)} + style={styles.modelRow} + > + {model.name} + {model.id === modelId ? : null} + + ))} + {!options.data?.models.length ? {t("chat.noModel")} : null} + + + + + + + + ); } @@ -874,22 +1048,26 @@ function MessageFiles({ } const styles = StyleSheet.create({ - page: { flex: 1, backgroundColor: colors.bg }, + page: { flex: 1, backgroundColor: colors.card }, status: { margin: 24, color: colors.muted }, - assistant: { width: screenWidth - 32, paddingHorizontal: 4, paddingVertical: 10 }, - assistantName: { color: colors.accent, fontSize: 13, fontWeight: "600", marginBottom: 6 }, + assistant: { paddingHorizontal: 4, paddingVertical: 10 }, + assistantName: { color: colors.ink, fontSize: 13, fontWeight: "700", marginBottom: 6 }, userBubble: { alignSelf: "flex-end", - maxWidth: screenWidth * 0.78, marginRight: 12, marginVertical: 6, - backgroundColor: colors.selected, + backgroundColor: colors.userBubble, borderRadius: 18, - borderBottomRightRadius: 6, + borderCurve: "continuous", paddingHorizontal: 14, paddingVertical: 10, }, - userText: { color: colors.ink, fontSize: 16, lineHeight: 22 }, + userText: { color: colors.ink, fontSize: 15, lineHeight: 22 }, + sentReference: { + flexDirection: "row", minHeight: 42, alignItems: "center", gap: 6, marginBottom: 5, + paddingHorizontal: 8, borderRadius: 8, backgroundColor: colors.card, + }, + sentReferenceLabel: { color: colors.accent, flexShrink: 1, fontSize: 12 }, fileList: { gap: 8, marginBottom: 8 }, userImage: { width: 180, height: 120, borderRadius: 12, backgroundColor: "#fff" }, fileChip: { maxWidth: 220, backgroundColor: "#fff", borderRadius: 10, paddingHorizontal: 10, paddingVertical: 8 }, @@ -903,7 +1081,7 @@ const styles = StyleSheet.create({ flexDirection: "row", alignItems: "center", gap: 8, - backgroundColor: "#fff", + backgroundColor: colors.assistantSoft, borderRadius: 10, paddingLeft: 8, paddingRight: 10, @@ -913,7 +1091,6 @@ const styles = StyleSheet.create({ pendingName: { color: colors.ink, fontSize: 13, maxWidth: 120 }, pendingMeta: { color: colors.muted, fontSize: 11, marginTop: 1 }, pendingRemove: { color: colors.secondary, fontSize: 18, lineHeight: 20 }, - attach: { width: 36, height: 36, marginBottom: 4, marginRight: 4, alignItems: "center", justifyContent: "center" }, empty: { transform: [{ scaleY: -1 }], paddingHorizontal: 28, paddingTop: 72 }, hello: { fontSize: 32, fontWeight: "600", color: colors.ink }, emptyText: { marginTop: 8, fontSize: 16, lineHeight: 24, color: colors.secondary }, @@ -930,37 +1107,46 @@ const styles = StyleSheet.create({ promptText: { color: colors.ink, fontSize: 14 }, error: { color: colors.danger, paddingHorizontal: 16, paddingBottom: 8 }, toolbar: { - backgroundColor: colors.bg, - borderTopWidth: 0, - paddingHorizontal: 12, - paddingTop: 6, - paddingBottom: 8, + backgroundColor: colors.card, + borderWidth: 1, + borderColor: colors.assistantLine, + borderRadius: 21, + borderCurve: "continuous", + marginHorizontal: 13, + marginBottom: 7, + paddingHorizontal: 5, }, - toolbarRow: { alignItems: "flex-end" }, + toolbarRow: { alignItems: "center", paddingTop: 4 }, + toolbarAccessory: { height: 48 }, composer: { - backgroundColor: "#fff", - borderWidth: StyleSheet.hairlineWidth, - borderColor: colors.line, - borderRadius: 22, - paddingHorizontal: 16, - paddingTop: 10, - paddingBottom: 10, - marginLeft: 0, - marginRight: 8, + backgroundColor: colors.card, + paddingHorizontal: 9, + paddingTop: 7, + paddingBottom: 7, + marginHorizontal: 0, fontSize: 16, lineHeight: 22, color: colors.ink, }, - sendWrap: { justifyContent: "center", marginBottom: 4, marginRight: 2 }, + actions: { flexDirection: "row", alignItems: "center", minHeight: 46 }, + tool: { width: 44, minHeight: 44, borderRadius: 10, alignItems: "center", justifyContent: "center" }, + toolSelected: { backgroundColor: colors.assistantSoft }, + toolDisabled: { opacity: 0.42 }, + modelButton: { flex: 1, minWidth: 0, minHeight: 44, flexDirection: "row", alignItems: "center", justifyContent: "flex-end", gap: 4 }, + modelName: { flexShrink: 1, color: colors.ink, fontSize: 12 }, + modelDialog: { backgroundColor: colors.card }, + modelRow: { minHeight: 48, flexDirection: "row", alignItems: "center", justifyContent: "space-between", gap: 8 }, + modelLabel: { color: colors.ink, flex: 1, paddingVertical: 8 }, + sendWrap: { width: 44, minHeight: 44, alignItems: "center", justifyContent: "center" }, send: { width: 34, height: 34, borderRadius: 17, - backgroundColor: colors.accent, + backgroundColor: colors.assistant, alignItems: "center", justifyContent: "center", }, - sendIdle: { backgroundColor: "#c9cdd4" }, + sendIdle: { opacity: 0.43 }, }); export default function ConversationRoute() { diff --git a/apps/mobile/app/extensions.tsx b/apps/mobile/app/extensions.tsx index 16ed2872..49c64287 100644 --- a/apps/mobile/app/extensions.tsx +++ b/apps/mobile/app/extensions.tsx @@ -1,93 +1,95 @@ -import { Stack } from "expo-router"; -import { useState } from "react"; -import { Linking, Pressable, ScrollView, StyleSheet, Text, View } from "react-native"; -import { ExternalLink, Package } from "lucide-react-native"; import { navigationTitle } from "@doca/i18n"; +import { Redirect, Stack } from "expo-router"; +import * as WebBrowser from "expo-web-browser"; +import { ArrowUpRight, Package } from "lucide-react-native"; +import { useState } from "react"; +import { Pressable, ScrollView, StyleSheet, View } from "react-native"; +import { Text } from "react-native-paper"; import { useAuth } from "../src/auth"; -import { colors } from "../src/chrome"; +import { colors, EmptyState, LoadingState } from "../src/chrome"; import { useI18n } from "../src/locale"; -import { - MobileNavigationArea, - mobileNavigationIcons, - useMobileNavigation, -} from "../src/plugins/navigation"; +import { MobileNavigationArea, mobileNavigationIcons, useMobileNavigation } from "../src/plugins/navigation"; -/** Site sections without a native screen: a labelled same-origin browser open, no credential handoff. */ -function SiteSections() { +const nativeEntries = ["doca.home", "doca.libraries", "doca.files", "doca.ai", "doca.account", "doca.preferences"]; +const slots = ["mobile.more", "mobile.drawer", "mobile.account"] as const; + +export default function Extensions() { + const { t, locale } = useI18n(); + const { ready, session } = useAuth(); const { data } = useMobileNavigation(); - const { session } = useAuth(); - const { locale, t } = useI18n(); - const [openError, setOpenError] = useState(""); - const entries = data.entries.filter( - (entry) => !entry.pluginId && entry.webPath && !entry.mobilePath, - ); - if (!session || entries.length === 0) return null; + const [error, setError] = useState(""); + if (!ready) return ; + if (!session) return ; const origin = session.origin; - async function openInBrowser(path: string) { - if (!origin) return; - setOpenError(""); + const visibleSlots = slots.filter((slot) => + data.layout.placements.some((item) => item.slot === slot && !nativeEntries.includes(item.entryId)), + ); + const webTools = data.layout.placements.flatMap((placement) => { + const isTicketShortcut = placement.slot === "web.topRight" && placement.entryId === "doca.tickets"; + if ((!isTicketShortcut && placement.slot !== "web.user") || nativeEntries.includes(placement.entryId)) return []; + const entry = data.entries.find((item) => item.id === placement.entryId); + return entry?.webPath?.startsWith("/") + ? [{ id: entry.id, path: entry.webPath, title: navigationTitle(locale, entry, placement.title), Icon: mobileNavigationIcons[entry.icon] ?? Package }] + : []; + }); + const visibleWebIds = new Set(webTools.map(({ id }) => id)); + for (const entry of data.entries) { + if (entry.pluginId || entry.mobilePath || !entry.webPath?.startsWith("/") || visibleWebIds.has(entry.id)) continue; + webTools.push({ id: entry.id, path: entry.webPath, title: navigationTitle(locale, entry), Icon: mobileNavigationIcons[entry.icon] ?? Package }); + } + const browserAssistant = webTools.some((tool) => tool.id === "doca.mcp"); + if (browserAssistant) { + webTools.push({ id: "doca.browser-assistant", path: "/browser-assistant", title: t("clipper.title"), Icon: mobileNavigationIcons.mcp! }); + } + + async function openWeb(path: string) { + setError(""); try { - await Linking.openURL(origin + path); - } catch { - setOpenError(t("navigation.openFailed")); + await WebBrowser.openBrowserAsync(`${origin}/#${path}`); + } catch (reason) { + setError(reason instanceof Error ? reason.message : t("common.failed")); } } - return ( - - {t("navigation.webOnly")} - {openError ? {openError} : null} - {entries.map((entry) => { - const Icon = mobileNavigationIcons[entry.icon] ?? Package; - const title = navigationTitle(locale, entry); - return ( - [ - styles.row, - pressed ? { backgroundColor: colors.bg } : undefined, - ]} - onPress={() => void openInBrowser(entry.webPath!)} - accessibilityLabel={`${title}, ${t("navigation.openInBrowser")}`} - > - - - {title} - - - {t("navigation.openInBrowser")} - - ); - })} - - ); -} -export default function Extensions() { - const { t } = useI18n(); return ( - <> + - - - - - + {error ? {error} : null} + {visibleSlots.map((slot) => ( + + + + ))} + {!!webTools.length && ( + + {t("navigation.webOnly")} + {webTools.map(({ id, path, title, Icon }) => ( + void openWeb(path)} + style={styles.row} + > + + {title} + {t("navigation.openInBrowser")} + + + ))} + + )} + {!visibleSlots.length && !webTools.length ? : null} + ); } const styles = StyleSheet.create({ - page: { paddingVertical: 12, paddingHorizontal: 16, gap: 4 }, - section: { marginTop: 16 }, - heading: { color: colors.muted, fontSize: 12, marginBottom: 4 }, - row: { - flexDirection: "row", - alignItems: "center", - gap: 10, - paddingVertical: 12, - paddingHorizontal: 8, - borderRadius: 8, - }, - rowTitle: { color: colors.ink, fontSize: 16, flex: 1 }, - rowAction: { color: colors.accent, fontSize: 13 }, - error: { color: colors.danger, fontSize: 12, marginBottom: 8 }, + page: { flex: 1, backgroundColor: colors.bg }, + content: { padding: 18, gap: 12 }, + panel: { backgroundColor: colors.card, borderRadius: 14, borderCurve: "continuous", paddingHorizontal: 12 }, + row: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", gap: 10, minHeight: 50, paddingVertical: 7 }, + heading: { color: colors.secondary, fontSize: 12, paddingTop: 12 }, + webAction: { color: colors.secondary, fontSize: 12 }, + label: { flex: 1, color: colors.ink, fontSize: 15, fontWeight: "600" }, }); diff --git a/apps/mobile/app/me.tsx b/apps/mobile/app/me.tsx new file mode 100644 index 00000000..3270b7a6 --- /dev/null +++ b/apps/mobile/app/me.tsx @@ -0,0 +1,118 @@ +import { localeLabel } from "@doca/i18n"; +import { Redirect, Stack, useRouter } from "expo-router"; +import { Bell, ChevronRight, Ellipsis, Languages, LogOut, ScanLine, Server, Settings, UserRound } from "lucide-react-native"; +import { Alert, Pressable, ScrollView, StyleSheet, View } from "react-native"; +import { Button, Text } from "react-native-paper"; +import { useAuth } from "../src/auth"; +import { colors, LoadingState } from "../src/chrome"; +import { useI18n } from "../src/locale"; + +function MenuRow({ + label, + detail, + Icon, + onPress, +}: { + label: string; + detail?: string; + Icon: typeof UserRound; + onPress: () => void; +}) { + return ( + [styles.row, pressed && styles.pressed]} + > + + + {label} + {detail ? {detail} : null} + + + + ); +} + +export default function MyAccount() { + const router = useRouter(); + const { ready, session, signOut } = useAuth(); + const { t, locale } = useI18n(); + + if (!ready) return ; + if (!session) return ; + + function confirmSignOut() { + Alert.alert(t("mobile.settings.signOutTitle"), t("mobile.settings.signOutBody"), [ + { text: t("common.cancel"), style: "cancel" }, + { text: t("account.signOut"), style: "destructive", onPress: () => { + void signOut().catch((error) => Alert.alert(t("common.failed"), error instanceof Error ? error.message : undefined)); + } }, + ]); + } + + return ( + + + + + + {session.name.trim() ? {session.name.trim().slice(0, 1)} : } + + + {session.name} + {session.origin} + + + + router.push({ pathname: "/settings", params: { section: "servers" } })} + /> + + + router.push("/notifications")} /> + + router.push({ pathname: "/settings", params: { section: "language" } })} + /> + + + router.push("/account")} /> + + router.push("/settings")} /> + + router.push("/scan")} /> + + router.push("/extensions")} /> + + + + ); +} + +const styles = StyleSheet.create({ + page: { flex: 1, backgroundColor: colors.bg }, + content: { padding: 18, paddingBottom: 28, gap: 13 }, + panel: { + backgroundColor: colors.card, borderRadius: 16, borderCurve: "continuous", + paddingHorizontal: 12, borderWidth: StyleSheet.hairlineWidth, borderColor: colors.line, + }, + identity: { flexDirection: "row", alignItems: "center", gap: 12, paddingVertical: 14 }, + avatar: { width: 48, height: 48, borderRadius: 24, backgroundColor: colors.selected, alignItems: "center", justifyContent: "center" }, + avatarText: { fontSize: 20, fontWeight: "700", color: colors.accent }, + name: { fontSize: 18, fontWeight: "700", color: colors.ink }, + line: { height: StyleSheet.hairlineWidth, backgroundColor: colors.line }, + row: { minHeight: 54, flexDirection: "row", alignItems: "center", paddingVertical: 7, gap: 10 }, + rowIcon: { width: 34, height: 34, borderRadius: 9, borderCurve: "continuous", backgroundColor: colors.bg, alignItems: "center", justifyContent: "center" }, + rowCopy: { flex: 1, minWidth: 0, gap: 3 }, + rowLabel: { fontSize: 15, fontWeight: "600", color: colors.ink }, + detail: { color: colors.secondary, fontSize: 12 }, + pressed: { opacity: 0.65 }, +}); diff --git a/apps/mobile/app/notifications.tsx b/apps/mobile/app/notifications.tsx new file mode 100644 index 00000000..42ab5c8c --- /dev/null +++ b/apps/mobile/app/notifications.tsx @@ -0,0 +1,151 @@ +import { QueryClient, useInfiniteQuery } from "@tanstack/react-query"; +import { Redirect, Stack, useFocusEffect, useRouter } from "expo-router"; +import { Bell, ChevronRight } from "lucide-react-native"; +import { useCallback, useRef, useState } from "react"; +import { FlatList, Pressable, StyleSheet, View } from "react-native"; +import { Button, Text } from "react-native-paper"; +import { api } from "../src/api"; +import { useAuth } from "../src/auth"; +import { colors, EmptyState, LoadingState } from "../src/chrome"; +import { useI18n } from "../src/locale"; +import type { Session } from "../src/session"; + +type Notice = { + id: string; + title: string | null; + description?: string; + actorName?: string | null; + href?: string; + resource_id: string | null; + ticket_id?: string | null; + read_at: string | null; + type: string; +}; +type NoticePage = { items: Notice[]; unread: number; nextOffset: number | null }; + +function documentTarget(item: Notice) { + if (item.href || item.ticket_id || item.type === "resource.invited" || item.type.startsWith("access.")) return null; + return item.resource_id; +} + +export default function Notifications() { + const { ready, session } = useAuth(); + const { t } = useI18n(); + if (!ready) return ; + if (!session) return ; + return ; +} + +function NoticeList({ session }: { session: Session }) { + const { t } = useI18n(); + const router = useRouter(); + // Keep notification data in this screen's memory rather than the app's disk query cache. + const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: 1 } } })); + const query = useInfiniteQuery({ + queryKey: ["notifications", session.origin], + initialPageParam: 0, + queryFn: ({ pageParam, signal }) => api(`/notifications?offset=${pageParam}`, { session, signal }), + getNextPageParam: (page) => page.nextOffset ?? undefined, + }, client); + const [busy, setBusy] = useState(false); + const marking = useRef(false); + const focused = useRef(false); + useFocusEffect(useCallback(() => { + focused.current = true; + return () => { focused.current = false; }; + }, [])); + const [error, setError] = useState(""); + const rows = query.data?.pages.flatMap((page) => page.items) ?? []; + const unread = query.data?.pages[0]?.unread ?? 0; + + function openNotice(item: Notice) { + const id = documentTarget(item); + if (id && focused.current) router.push({ pathname: "/document/[id]", params: { id, title: item.title ?? "" } }); + } + + async function mark(item?: Notice) { + if (marking.current) return; + if (item?.read_at) { + openNotice(item); + return; + } + marking.current = true; + setBusy(true); + setError(""); + try { + await api(item ? "/notifications/read" : "/notifications/read-all", { + session, + body: item ? { ids: [item.id] } : {}, + }); + await query.refetch(); + if (item) openNotice(item); + } catch (reason) { + setError(reason instanceof Error ? reason.message : t("common.failed")); + } finally { + marking.current = false; + setBusy(false); + } + } + + return ( + + + + {t("shell.unread", { count: unread })} + + + {error || query.isError ? ( + + {error || query.error?.message} + {query.isError ? : null} + + ) : null} + item.id} + contentInsetAdjustmentBehavior="automatic" + contentContainerStyle={styles.list} + refreshing={query.isRefetching} + onRefresh={() => void query.refetch()} + ListEmptyComponent={ + query.isPending ? + : !query.isError ? : null + } + ListFooterComponent={query.hasNextPage ? ( + + ) : null} + renderItem={({ item }) => { + const linked = !!documentTarget(item); + const description = item.description || item.actorName; + return ( + void mark(item)} + style={[styles.row, !item.read_at && styles.unread]} + > + + + {item.title || t("notify.fallback")} + {description && description !== item.title ? {description} : null} + + {linked ? : null} + + ); + }} + /> + + ); +} + +const styles = StyleSheet.create({ + page: { flex: 1, backgroundColor: colors.bg }, + toolbar: { marginHorizontal: 16, alignItems: "center", gap: 10, flexDirection: "row", justifyContent: "space-between" }, + muted: { color: colors.secondary, fontSize: 13 }, + error: { color: colors.danger, flex: 1 }, + list: { padding: 16, paddingTop: 4, gap: 8 }, + row: { flexDirection: "row", alignItems: "center", gap: 10, minHeight: 58, padding: 12, borderRadius: 12, borderCurve: "continuous", backgroundColor: colors.card }, + unread: { backgroundColor: colors.selected }, + copy: { flex: 1, gap: 3 }, + title: { color: colors.ink, fontWeight: "600" }, +}); diff --git a/apps/mobile/app/scan.tsx b/apps/mobile/app/scan.tsx index 6659ace0..5b44da42 100644 --- a/apps/mobile/app/scan.tsx +++ b/apps/mobile/app/scan.tsx @@ -54,7 +54,7 @@ export default function ScanLogin() { locked.current = false; } catch (reason) { if (reason instanceof ApiError && reason.status === 401) { - await removeAccount(account.origin); + await removeAccount(account.origin, account.token); await refresh(); setPending(null); locked.current = false; diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsx index cbcc5786..21b3b2f3 100644 --- a/apps/mobile/app/settings.tsx +++ b/apps/mobile/app/settings.tsx @@ -1,5 +1,5 @@ -import { useNavigation, useRouter } from "expo-router"; -import { useLayoutEffect, useState } from "react"; +import { Stack, useLocalSearchParams, useRouter } from "expo-router"; +import { useRef, useState } from "react"; import { Alert, Pressable, ScrollView, StyleSheet, TextInput, View } from "react-native"; import { Text } from "react-native-paper"; import { htmlLang, localeLabel, locales } from "@doca/i18n"; @@ -9,23 +9,40 @@ import { useI18n } from "../src/locale"; import { normalizeOrigin } from "../src/session"; export default function Settings() { - const navigation = useNavigation(); const router = useRouter(); + const { section } = useLocalSearchParams<{ section?: string }>(); const { session, accounts, switchServer, signOut } = useAuth(); const { locale, setLocale, t } = useI18n(); const [draft, setDraft] = useState(""); const [error, setError] = useState(""); + const [switching, setSwitching] = useState(false); + const switchPending = useRef(false); + const showLanguage = section !== "servers"; + const showServers = section !== "language"; + const title = section === "servers" ? t("mobile.me.backends") + : section === "language" ? t("settings.language") : t("mobile.me.settings"); - useLayoutEffect(() => { - navigation.setOptions({ title: t("mobile.settings.title") }); - }, [navigation, t]); + async function chooseServer(origin: string) { + if (switchPending.current || session?.origin === origin) return; + switchPending.current = true; + setSwitching(true); + setError(""); + try { + await switchServer(origin); + } catch (reason) { + setError(reason instanceof Error ? reason.message : t("common.failed")); + } finally { + switchPending.current = false; + setSwitching(false); + } + } async function addServer() { setError(""); try { const origin = normalizeOrigin(draft); if (accounts.some((account) => account.origin === origin)) { - await switchServer(origin); + await chooseServer(origin); return; } router.push({ pathname: "/login", params: { add: "1", origin } }); @@ -37,80 +54,99 @@ export default function Settings() { function logout() { Alert.alert(t("mobile.settings.signOutTitle"), t("mobile.settings.signOutBody"), [ { text: t("mobile.settings.cancel"), style: "cancel" }, - { text: t("mobile.settings.signOut"), style: "destructive", onPress: () => void signOut() }, + { text: t("mobile.settings.signOut"), style: "destructive", onPress: () => { + void signOut().catch((error) => Alert.alert(t("common.failed"), error instanceof Error ? error.message : undefined)); + } }, ]); } return ( - - {t("settings.language")} - - {locales.map((code) => ( - void setLocale(code)} - > - {t(localeLabel[code])} - {locale === code ? t("mobile.settings.current") : ""} - - ))} - {t("settings.language.hint")} - - {t("mobile.settings.currentServer")} - - {session?.name || t("mobile.settings.signedOut")} - {session?.origin} - - {t("mobile.settings.savedServers")} - - {accounts.map((account) => { - const current = account.origin === session?.origin; - return ( - void switchServer(account.origin)} - > - - {account.name} - {account.origin} - - {current ? t("mobile.settings.current") : t("mobile.settings.switch")} + + + {showLanguage ? ( + <> + {t("settings.language")} + + {locales.map((code) => ( + void setLocale(code)} + > + {t(localeLabel[code])} + {locale === code ? t("mobile.settings.current") : ""} + + ))} + {t("settings.language.hint")} + + + ) : null} + {showServers ? ( + <> + {t("mobile.settings.currentServer")} + + {session?.name || t("mobile.settings.signedOut")} + {session?.origin} + + {t("mobile.settings.savedServers")} + + {accounts.map((account) => { + const current = account.origin === session?.origin; + return ( + void chooseServer(account.origin)} + > + + {account.name} + {account.origin} + + {current ? t("mobile.settings.current") : t("mobile.settings.switch")} + + ); + })} + {!accounts.length ? {t("mobile.settings.noneSaved")} : null} + + {t("mobile.settings.addServer")} + + + {error ? {error} : null} + void addServer()}> + {t("mobile.settings.add")} - ); - })} - {!accounts.length ? {t("mobile.settings.noneSaved")} : null} - - {t("mobile.settings.addServer")} - - - {error ? {error} : null} - void addServer()}> - {t("mobile.settings.add")} - - {t("mobile.settings.addNote")} - - router.push("/account")}> - {t("account.profile")} - - router.push("/scan")}> - {t("mobile.settings.scan")} - - - {t("mobile.settings.signOutServer")} - + {t("mobile.settings.addNote")} + + + ) : null} + {showLanguage && showServers ? ( + <> + router.push("/account")}> + {t("account.profile")} + + router.push("/scan")}> + {t("mobile.settings.scan")} + + + {t("mobile.settings.signOutServer")} + + + ) : null} ); } @@ -119,7 +155,7 @@ const styles = StyleSheet.create({ page: { flex: 1, backgroundColor: colors.bg }, content: { padding: 16, paddingBottom: 40 }, section: { color: colors.muted, fontSize: 12, marginTop: 16, marginBottom: 8, marginLeft: 4 }, - card: { backgroundColor: colors.card, borderRadius: 8, paddingHorizontal: 14, paddingVertical: 12 }, + card: { backgroundColor: colors.card, borderRadius: 14, borderCurve: "continuous", paddingHorizontal: 14, paddingVertical: 12 }, row: { minHeight: 56, flexDirection: "row", alignItems: "center", gap: 12 }, rowCopy: { flex: 1 }, name: { color: colors.ink, fontSize: 16, fontWeight: "600" }, diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 9d52e2b3..a7660cec 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -1,6 +1,6 @@ { "name": "@doca/mobile", - "version": "0.1.0", + "version": "0.1.1", "license": "MIT", "private": true, "main": "expo-router/entry", diff --git a/apps/mobile/src/ai-reference-picker.tsx b/apps/mobile/src/ai-reference-picker.tsx new file mode 100644 index 00000000..875a81c8 --- /dev/null +++ b/apps/mobile/src/ai-reference-picker.tsx @@ -0,0 +1,97 @@ +import { QueryClient, useQuery } from "@tanstack/react-query"; +import { Check, FileText } from "lucide-react-native"; +import { useEffect, useState } from "react"; +import { Pressable, ScrollView, StyleSheet, View } from "react-native"; +import { Button, Dialog, Portal, Text, TextInput } from "react-native-paper"; +import { api, type Resource } from "./api"; +import { colors, EmptyState, LoadingState } from "./chrome"; +import { useI18n } from "./locale"; +import type { Session } from "./session"; + +export function ReferencePicker({ + session, + visible, + selected, + onSelect, + onDismiss, +}: { + session: Session | null; + visible: boolean; + selected: ReadonlySet; + onSelect: (item: Resource) => void; + onDismiss: () => void; +}) { + const { t } = useI18n(); + const [input, setInput] = useState(""); + const [keyword, setKeyword] = useState(""); + const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: 1 } } })); + useEffect(() => { + const timer = setTimeout(() => setKeyword(input.trim()), 250); + return () => clearTimeout(timer); + }, [input]); + const text = new URLSearchParams({ q: keyword, mode: "keyword", scope: keyword ? "all" : "recent" }).toString(); + const query = useQuery({ + queryKey: ["reference-search", session?.origin, text], + enabled: !!session && visible, + queryFn: ({ signal }) => api<{ items: Resource[] }>(`/search/documents?${text}`, { session, signal }), + }, client); + const documents = query.data?.items.filter((item) => item.kind === "document") ?? []; + + return ( + + + {t("mobile.ai.pick.document")} + + + + + + {query.isPending ? : null} + {query.isError ? ( + <> + {query.error.message} + + + ) : null} + {!query.isPending && !query.isError && !documents.length ? ( + + ) : null} + {documents.map((document) => { + const included = selected.has(document.id); + return ( + onSelect(document)} + > + + {document.title || t("shell.untitled")} + {included ? : } + + ); + })} + + + + + + ); +} + +const styles = StyleSheet.create({ + dialog: { backgroundColor: colors.card }, + results: { paddingHorizontal: 18 }, + row: { minHeight: 50, paddingVertical: 8, flexDirection: "row", alignItems: "center", gap: 10 }, + title: { color: colors.ink, flex: 1, minWidth: 0 }, + error: { color: colors.danger, paddingTop: 10 }, +}); diff --git a/apps/mobile/src/api.ts b/apps/mobile/src/api.ts index 48b9c4ad..8ab7d153 100644 --- a/apps/mobile/src/api.ts +++ b/apps/mobile/src/api.ts @@ -15,6 +15,7 @@ type Options = { session?: Session | null; raw?: BodyInit; contentType?: string; + signal?: AbortSignal; }; let onUnauthorized: (() => void) | null = null; @@ -28,6 +29,8 @@ export async function api(path: string, options: Options = {}): Promise { const headers: Record = { accept: "application/json", authorization: `Bearer ${session.token}`, + // The authenticated logout route can report a revoked session even when no bearer is accepted. + ...(path === "/auth/logout" ? { origin: session.origin } : {}), }; let body: BodyInit | undefined; if (options.raw !== undefined) { @@ -41,24 +44,25 @@ export async function api(path: string, options: Options = {}): Promise { method: options.method ?? (body ? "POST" : "GET"), headers, body, + signal: options.signal, }); const text = await response.text(); const data = text ? JSON.parse(text) : {}; - if (response.status === 401) { - await removeAccount(session.origin); + if (response.status === 401 && await removeAccount(session.origin, session.token)) { onUnauthorized?.(); } if (!response.ok) throw new ApiError(response.status, apiErrorMessage(data.message ?? "请求失败")); return data as T; } -export async function login(origin: string, loginName: string, password: string) { +export async function login(origin: string, loginName: string, password: string, android = false) { const response = await fetch(origin + "/api/v1/auth/login", { method: "POST", headers: { accept: "application/json", "content-type": "application/json", "x-doca-client": "mobile", + ...(android ? { "x-doca-client-platform": "android" } : {}), }, body: JSON.stringify({ login: loginName, password }), }); diff --git a/apps/mobile/src/app-drawer.tsx b/apps/mobile/src/app-drawer.tsx index 72062a17..27f70aa7 100644 --- a/apps/mobile/src/app-drawer.tsx +++ b/apps/mobile/src/app-drawer.tsx @@ -6,10 +6,12 @@ import { createContext, useContext } from "react"; */ export type AppDrawerControls = { open: () => void; + hasBrowseRail: boolean; }; export const AppDrawerContext = createContext({ open: () => undefined, + hasBrowseRail: false, }); export function useAppDrawer(): AppDrawerControls { diff --git a/apps/mobile/src/auth.tsx b/apps/mobile/src/auth.tsx index 12fd898b..c3dff7be 100644 --- a/apps/mobile/src/auth.tsx +++ b/apps/mobile/src/auth.tsx @@ -1,9 +1,11 @@ import type { ResolvedNavigation } from "@smartdoca/web-plugin-registry"; import { type Href } from "expo-router"; -import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from "react"; +import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react"; import { useRouter } from "expo-router"; -import { api, login as requestLogin, setUnauthorizedHandler } from "./api"; -import { clearQueryCache } from "./query-cache"; +import { Platform } from "react-native"; +import { api, ApiError, login as requestLogin, setUnauthorizedHandler } from "./api"; +import { queryClient } from "./query-cache"; +import { setAiSession } from "./ai-session"; import { loadVault, normalizeOrigin, @@ -31,8 +33,16 @@ export function AuthProvider({ children }: { children: ReactNode }) { const [session, setSession] = useState(null); const [accounts, setAccounts] = useState([]); + const activeSession = useRef(null); + const applyVault = useCallback(async () => { const vault = await loadVault(); + const previous = activeSession.current; + if (previous?.origin !== vault.session?.origin || previous?.token !== vault.session?.token) { + queryClient.clear(); + setAiSession(null); + } + activeSession.current = vault.session; setSession(vault.session); setAccounts(vault.accounts); return vault; @@ -52,7 +62,6 @@ export function AuthProvider({ children }: { children: ReactNode }) { setUnauthorizedHandler(() => { void (async () => { const vault = await applyVault(); - await clearQueryCache(); router.replace(vault.session ? "/" : "/login"); })(); }); @@ -66,8 +75,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { destination?: "back", ) => { const normalized = normalizeOrigin(origin); - const result = await requestLogin(normalized, loginName, password); - await clearQueryCache(); + const result = await requestLogin(normalized, loginName, password, Platform.OS === "android"); await saveSession({ origin: normalized, token: result.token, name: result.name }); await applyVault(); if (destination === "back" && router.canGoBack()) router.back(); @@ -79,21 +87,21 @@ export function AuthProvider({ children }: { children: ReactNode }) { const switchServer = useCallback(async (origin: string) => { if (session?.origin === origin) return; await switchOrigin(origin); - await clearQueryCache(); await applyVault(); router.replace("/"); }, [applyVault, router, session?.origin]); const signOut = useCallback(async () => { - const current = session; + if (!session) return; try { - await api("/auth/logout", { method: "POST" }); - } catch { - // A rejected session is already dropped. Local removal still continues. + await api("/auth/logout", { method: "POST", session }); + } catch (error) { + if (Platform.OS === "android" && !(error instanceof ApiError && error.status === 401)) { + throw error; + } } - if (current) await removeAccount(current.origin); + await removeAccount(session.origin, session.token); const vault = await applyVault(); - await clearQueryCache(); if (!vault.session) router.replace("/login"); }, [applyVault, router, session]); diff --git a/apps/mobile/src/chrome.tsx b/apps/mobile/src/chrome.tsx index bf1c83ad..b061c320 100644 --- a/apps/mobile/src/chrome.tsx +++ b/apps/mobile/src/chrome.tsx @@ -14,6 +14,16 @@ export const colors = { accentPressed: "#245bdb", selected: "#e1eaff", danger: "#f54a45", + onAccent: "#ffffff", + feature: "#203e8d", + featureDetail: "#dbe7ff", + featurePaper: "#eaf1ff", + featureLine: "#b3c8ee", + assistant: "#7859b8", + assistantInk: "#5f429a", + assistantSoft: "#f4f0ff", + assistantLine: "#ddd3f3", + userBubble: "#eaf3ff", }; export function Card({ children }: { children: ReactNode }) { diff --git a/apps/mobile/src/folder-browser.tsx b/apps/mobile/src/folder-browser.tsx index 353fdaee..50165bdc 100644 --- a/apps/mobile/src/folder-browser.tsx +++ b/apps/mobile/src/folder-browser.tsx @@ -1,4 +1,3 @@ -import { BottomSheetBackdrop, BottomSheetModal, BottomSheetView, type BottomSheetBackdropProps } from "@gorhom/bottom-sheet"; import { FlashList } from "@shopify/flash-list"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import * as DocumentPicker from "expo-document-picker"; @@ -7,7 +6,7 @@ import { Image } from "expo-image"; import * as ImagePicker from "expo-image-picker"; import { useRouter } from "expo-router"; import * as Sharing from "expo-sharing"; -import { useCallback, useRef, useState } from "react"; +import { useCallback, useState } from "react"; import { Alert, Modal, Platform, Pressable, RefreshControl, ScrollView, StyleSheet, View } from "react-native"; import { Swipeable } from "react-native-gesture-handler"; import { Button, Dialog, FAB, IconButton, List, Portal, Snackbar, Text, TextInput } from "react-native-paper"; @@ -17,6 +16,7 @@ import { api } from "./api"; import { useAuth } from "./auth"; import { Card, EmptyState, LoadingState, colors } from "./chrome"; import { fileSize } from "./format"; +import { useI18n } from "./locale"; import { usePull } from "./query-cache"; type ParentType = "system" | "folder" | "document"; @@ -94,10 +94,11 @@ export function FolderBrowser({ parentId: string; }) { const router = useRouter(); + const { t } = useI18n(); const insets = useSafeAreaInsets(); const client = useQueryClient(); const { session } = useAuth(); - const sheet = useRef(null); + const [addMenu, setAddMenu] = useState(false); const [prompt, setPrompt] = useState(null); const [name, setName] = useState(""); const [notice, setNotice] = useState(""); @@ -108,7 +109,7 @@ export function FolderBrowser({ const query = useQuery({ queryKey: ["files", session?.origin, parentType, parentId], enabled: !!session && !!parentId, - queryFn: () => api(`/files?parentType=${parentType}&parentId=${encodeURIComponent(parentId)}`), + queryFn: ({ signal }) => api(`/files?parentType=${parentType}&parentId=${encodeURIComponent(parentId)}`, { session, signal }), }); const refresh = useCallback(async () => { @@ -173,7 +174,6 @@ export function FolderBrowser({ async function upload(uri: string, filename: string) { if (!session) return; setBusy(true); - sheet.current?.dismiss(); try { const url = `${session.origin}/api/v1/files/items?parentType=${parentType}` + @@ -203,23 +203,35 @@ export function FolderBrowser({ } async function pickDocument() { - const picked = await DocumentPicker.getDocumentAsync({ copyToCacheDirectory: true, multiple: false }); - if (picked.canceled || !picked.assets[0]) return; - const asset = picked.assets[0]; - await upload(asset.uri, asset.name || "未命名文件"); + setAddMenu(false); + try { + const picked = await DocumentPicker.getDocumentAsync({ copyToCacheDirectory: true, multiple: false }); + if (picked.canceled || !picked.assets[0]) return; + const asset = picked.assets[0]; + await upload(asset.uri, asset.name || "未命名文件"); + } catch (reason) { + fail(reason); + } } - async function pickImage() { - const permission = await ImagePicker.requestMediaLibraryPermissionsAsync(); - if (!permission.granted) { - setNotice("需要相册权限才能选择图片"); - return; + async function pickImage(source: "library" | "camera") { + setAddMenu(false); + try { + const camera = source === "camera"; + const permission = camera + ? await ImagePicker.requestCameraPermissionsAsync() + : await ImagePicker.requestMediaLibraryPermissionsAsync(); + if (!permission.granted) { + setNotice(t(camera ? "mobile.files.camera.permission" : "mobile.files.album.permission")); + return; + } + const options: ImagePicker.ImagePickerOptions = { mediaTypes: ["images"], quality: 1 }; + const picked = camera ? await ImagePicker.launchCameraAsync(options) : await ImagePicker.launchImageLibraryAsync(options); + const asset = picked.assets?.[0]; + if (!picked.canceled && asset) await upload(asset.uri, asset.fileName || `图片-${Date.now()}.jpg`); + } catch (reason) { + fail(reason); } - const picked = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ["images"], quality: 1 }); - if (picked.canceled || !picked.assets[0]) return; - const asset = picked.assets[0]; - const filename = asset.fileName || `图片-${Date.now()}.jpg`; - await upload(asset.uri, filename); } async function downloadFile(item: FileItem) { @@ -277,11 +289,6 @@ export function FolderBrowser({ } } - const backdrop = useCallback( - (props: BottomSheetBackdropProps) => , - [], - ); - if (query.isLoading) return ; if (query.isError) { return ; @@ -297,7 +304,7 @@ export function FolderBrowser({ ]; function openPrompt(next: Prompt) { - sheet.current?.dismiss(); + setAddMenu(false); setName(next.kind === "rename" ? next.target.name : ""); setPrompt(next); } @@ -379,25 +386,27 @@ export function FolderBrowser({ }} /> {writable ? ( - sheet.current?.present()} /> + setAddMenu(true)} /> ) : null} - - - - 文件夹 - - - - - - + setAddMenu(false)} style={styles.addDialog}> + {t("chat.addFiles")} + + + + + + + + setPrompt(null)}> {prompt?.kind === "delete" ? "移到回收站" : prompt?.kind === "rename" ? "重命名" : "新建文件夹"} @@ -492,7 +501,8 @@ export function FolderBrowser({ const styles = StyleSheet.create({ page: { flex: 1, backgroundColor: colors.bg }, fab: { position: "absolute", right: 16, bottom: 16, backgroundColor: colors.accent }, - sheet: { padding: 20, gap: 12 }, + addDialog: { backgroundColor: colors.card }, + addActions: { gap: 10 }, swipe: { flexDirection: "row", alignItems: "stretch", marginTop: 8, marginRight: 12 }, swipeButton: { justifyContent: "center", paddingHorizontal: 16 }, rename: { backgroundColor: colors.selected }, diff --git a/apps/mobile/src/plugins/navigation.tsx b/apps/mobile/src/plugins/navigation.tsx index 8142eb8a..7a90fefd 100644 --- a/apps/mobile/src/plugins/navigation.tsx +++ b/apps/mobile/src/plugins/navigation.tsx @@ -1,7 +1,7 @@ import { navigationTitle } from "@doca/i18n"; import { useQuery } from "@tanstack/react-query"; import { useEffect, useState, Fragment } from "react"; -import { AppState, Pressable, View } from "react-native"; +import { AppState, Pressable, StyleSheet, View } from "react-native"; import { Text } from "react-native-paper"; import { usePathname, useRouter, type Href } from "expo-router"; import { @@ -42,7 +42,7 @@ export function useMobileNavigation() { const query = useQuery({ queryKey: ["navigation", session?.origin, session?.token], enabled: !!session, - queryFn: () => api("/navigation"), + queryFn: ({ signal }) => api("/navigation", { session, signal }), refetchInterval: 30000, }); useEffect(() => { @@ -93,98 +93,118 @@ export function MobileNavigationArea({ slot, close, horizontal = false, + exclude, iconOnly = false, }: { slot: NavigationSlot; close?: () => void; horizontal?: boolean; + exclude?: readonly string[]; iconOnly?: boolean; }) { const { data } = useMobileNavigation(), { locale, t } = useI18n(), - router = useRouter(), - pathname = usePathname(); + router = useRouter(); + const pathname = usePathname(); const [collapsed, setCollapsed] = useState>({}); - const placements = data.layout.placements.filter((p) => p.slot === slot); + const placements = data.layout.placements.filter((p) => p.slot === slot && !exclude?.includes(p.entryId)); + const tabs = slot === "mobile.bottom" && horizontal; + const toolbar = slot === "mobile.topRight"; return ( - {data.layout.placements - .filter((p) => p.slot === slot) - .map((p, index) => { - const entry = data.entries.find((e) => e.id === p.entryId); - if (!entry) return null; - const Icon = mobileNavigationIcons[p.icon ?? entry.icon] ?? Package, - title = navigationTitle(locale, entry, p.title), - target = mobileEntryPath(entry), - active = pathname === target || (target !== "/" && pathname.startsWith(`${target}/`)); - const group = p.group ?? ""; - const first = - group && !placements.slice(0, index).some((x) => x.group === group); - const folded = collapsed[group] ?? p.collapsed ?? false; - return ( - - {!horizontal && !iconOnly && first && ( - - setCollapsed({ ...collapsed, [group]: !folded }) - } - > - - {group} {folded ? "+" : "−"} + {placements.map((p, index) => { + const entry = data.entries.find((e) => e.id === p.entryId); + if (!entry) return null; + const Icon = mobileNavigationIcons[p.icon ?? entry.icon] ?? Package, + title = navigationTitle(locale, entry, p.title); + const path = mobileEntryPath(entry); + const active = pathname === path || (path !== "/" && pathname.startsWith(`${path}/`)); + const accent = entry.id === "doca.ai" ? colors.assistantInk : colors.accent; + const tint = (tabs || iconOnly) && !active ? colors.secondary : accent; + const group = p.group ?? ""; + const first = + group && !placements.slice(0, index).some((x) => x.group === group); + const folded = collapsed[group] ?? p.collapsed ?? false; + return ( + + {!horizontal && first && ( + + setCollapsed({ ...collapsed, [group]: !folded }) + } + > + + {group} {folded ? "+" : "−"} + + + )} + {(horizontal || !group || !folded) && ( + { + close?.(); + router.navigate(path); + }} + style={({ pressed }) => [ + tabs ? styles.tab : toolbar ? styles.toolbarButton : styles.entry, + !tabs && !toolbar && horizontal && styles.shortcut, + iconOnly && styles.railEntry, + iconOnly && active && styles.railActive, + pressed && styles.pressed, + ]} + > + {(iconOnly || p.display !== "text") && ( + + + + )} + {!iconOnly && p.display !== "icon" && ( + + {title} - - )} - {(horizontal || !group || !folded || iconOnly) && ( - { - close?.(); - router.navigate(mobileEntryPath(entry)); - }} - style={({ pressed }) => ({ - padding: iconOnly ? 9 : 12, - flexDirection: horizontal ? "column" : "row", - gap: iconOnly ? 0 : 8, - alignItems: "center", - justifyContent: iconOnly || horizontal ? "center" : "flex-start", - flex: horizontal ? 1 : undefined, - borderRadius: 9, - backgroundColor: active ? colors.selected : pressed ? colors.bg : "transparent", - })} - > - {(iconOnly || p.display !== "text") && ( - - )} - {p.display !== "icon" && !iconOnly && {title}} - - )} - - ); - })} - {slot === "mobile.bottom" && ( + )} + + )} + + ); + })} + {slot === "mobile.bottom" && iconOnly ? ( router.navigate("/extensions" as Href)} + accessibilityRole="button" accessibilityLabel={t("navigation.more")} - style={({ pressed }) => ({ - padding: iconOnly ? 9 : 12, - alignItems: "center", - justifyContent: "center", - flex: horizontal ? 1 : undefined, - borderRadius: 9, - backgroundColor: pathname === "/extensions" && iconOnly ? colors.selected : pressed ? colors.bg : "transparent", - })} + onPress={() => router.navigate("/extensions")} + style={({ pressed }) => [styles.entry, styles.railEntry, pathname === "/extensions" && styles.railActive, pressed && styles.pressed]} > - - {!iconOnly && {t("navigation.more")}} + - )} + ) : null} ); } + +const styles = StyleSheet.create({ + tab: { flex: 1, minHeight: 52, minWidth: 0, alignItems: "center", justifyContent: "center", gap: 2 }, + tabIcon: { width: 46, height: 27, borderRadius: 15, alignItems: "center", justifyContent: "center" }, + tabText: { fontSize: 11, textAlign: "center" }, + tabActive: { fontWeight: "700" }, + toolbarButton: { minWidth: 44, minHeight: 44, paddingHorizontal: 4, alignItems: "center", justifyContent: "center" }, + entry: { minHeight: 48, padding: 11, flexDirection: "row", alignItems: "center", gap: 8 }, + railEntry: { minHeight: 44, padding: 8, justifyContent: "center", borderRadius: 9, marginHorizontal: 4 }, + railActive: { backgroundColor: colors.selected }, + shortcut: { flex: 1, flexDirection: "column" }, + pressed: { opacity: 0.7 }, +}); diff --git a/apps/mobile/src/query-cache.ts b/apps/mobile/src/query-cache.ts index 0826edc4..aba3cf0c 100644 --- a/apps/mobile/src/query-cache.ts +++ b/apps/mobile/src/query-cache.ts @@ -1,8 +1,7 @@ import { useState } from "react"; -import { QueryClient, dehydrate, hydrate } from "@tanstack/react-query"; +import { QueryClient } from "@tanstack/react-query"; import * as FileSystem from "expo-file-system"; -const file = () => (FileSystem.documentDirectory ? FileSystem.documentDirectory + "doca-query-cache.json" : null); const maxAge = 24 * 60 * 60 * 1000; export const queryClient = new QueryClient({ @@ -16,48 +15,12 @@ export const queryClient = new QueryClient({ }, }); -export async function restoreQueryCache() { - const path = file(); - if (!path) return; - try { - const info = await FileSystem.getInfoAsync(path); - if (!info.exists) return; - const saved = JSON.parse(await FileSystem.readAsStringAsync(path)) as { - timestamp?: number; - clientState?: unknown; - }; - if (!saved.timestamp || Date.now() - saved.timestamp > maxAge || !saved.clientState) return; - hydrate(queryClient, saved.clientState as never); - } catch { - // A damaged cache should not block the next launch. - } -} - -export function persistQueryCache() { - const path = file(); - if (!path) return () => undefined; - let timer: ReturnType | null = null; - const save = () => { - const clientState = dehydrate(queryClient, { - shouldDehydrateQuery: (query) => query.state.status === "success", - }); - void FileSystem.writeAsStringAsync(path, JSON.stringify({ timestamp: Date.now(), clientState })).catch(() => undefined); - }; - const unsubscribe = queryClient.getQueryCache().subscribe(() => { - if (timer) clearTimeout(timer); - timer = setTimeout(save, 700); - }); - return () => { - if (timer) clearTimeout(timer); - unsubscribe(); - }; -} - -export async function clearQueryCache() { - queryClient.clear(); - const path = file(); - if (!path) return; - await FileSystem.deleteAsync(path, { idempotent: true }).catch(() => undefined); +export async function discardLegacyQueryCache() { + if (!FileSystem.documentDirectory) return; + await FileSystem.deleteAsync( + `${FileSystem.documentDirectory}doca-query-cache.json`, + { idempotent: true }, + ).catch(() => undefined); } export function usePull(refetch: () => Promise) { diff --git a/apps/mobile/src/resource-list.tsx b/apps/mobile/src/resource-list.tsx index 8f6a3551..6d2cd193 100644 --- a/apps/mobile/src/resource-list.tsx +++ b/apps/mobile/src/resource-list.tsx @@ -1,38 +1,44 @@ import { FlashList } from "@shopify/flash-list"; import { useInfiniteQuery } from "@tanstack/react-query"; -import { useRouter } from "expo-router"; -import { RefreshControl, View } from "react-native"; -import { List } from "react-native-paper"; +import { useFocusEffect, useRouter } from "expo-router"; +import { ArrowUpRight, BookOpen, ChevronRight, FileCode, FileText, LayoutDashboard, Presentation, Table2 } from "lucide-react-native"; +import { useCallback, type ReactNode } from "react"; +import { Pressable, RefreshControl, StyleSheet, View } from "react-native"; +import { Button, Text } from "react-native-paper"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { api, formatLabel, type Resource } from "./api"; import { useAuth } from "./auth"; -import { Card, EmptyState, LoadingState, colors } from "./chrome"; +import { colors, EmptyState, LoadingState } from "./chrome"; import { relativeTime } from "./format"; +import { useI18n } from "./locale"; import { usePull } from "./query-cache"; -const formatIcon: Record = { - rich_text: "file-document-outline", - markdown: "language-markdown", - spreadsheet: "table", - presentation: "presentation", - canvas: "draw", -}; +const formats = { + rich_text: { Icon: FileText, bg: colors.selected, ink: colors.accent }, + markdown: { Icon: FileCode, bg: colors.assistantSoft, ink: colors.assistantInk }, + spreadsheet: { Icon: Table2, bg: "#e6f4ed", ink: "#257456" }, + presentation: { Icon: Presentation, bg: "#fbf1df", ink: "#875417" }, + canvas: { Icon: LayoutDashboard, bg: colors.assistantSoft, ink: colors.assistantInk }, +} satisfies Record; + +type ResourcePage = { items: Resource[]; nextCursor?: string | null }; export function ResourceList({ params, empty, + header, + featureLatest = false, }: { params: Record; empty: string; + header?: ReactNode; + featureLatest?: boolean; }) { const router = useRouter(); const { session } = useAuth(); + const { t } = useI18n(); const insets = useSafeAreaInsets(); const queryText = new URLSearchParams(params).toString(); - type ResourcePage = { - items: Resource[]; - nextCursor?: string | null; - }; const query = useInfiniteQuery({ queryKey: ["resources", session?.origin, queryText], enabled: !!session, @@ -40,57 +46,135 @@ export function ResourceList({ queryFn: ({ pageParam }) => api( `/resources?${queryText}${pageParam ? `&cursor=${encodeURIComponent(pageParam)}` : ""}`, + { session }, ), getNextPageParam: (page) => page.nextCursor ?? undefined, }); - const pull = usePull(() => query.refetch()); - if (query.isLoading) return ; - if (query.isError) { - return ; - } + const { refetch } = query; + useFocusEffect(useCallback(() => { + if (featureLatest && session) void refetch(); + }, [featureLatest, session, refetch])); + const pull = usePull(refetch); const items = query.data?.pages.flatMap((page) => page.items) ?? []; + const featured = featureLatest ? items[0] : undefined; + const error = query.error instanceof Error ? query.error.message : t("common.failed"); + + function open(item: Resource) { + router.push({ + pathname: item.kind === "library" ? "/library/[id]" : "/document/[id]", + params: { id: item.id, title: item.title }, + }); + } + + function updated(item: Resource) { + return relativeTime(params.sort === "visited_at" ? item.visited_at || item.updated_at : item.updated_at); + } + return ( - - { - if (query.hasNextPage && !query.isFetchingNextPage) - void query.fetchNextPage(); - }} - refreshControl={ - - } - ListEmptyComponent={} - renderItem={({ item }) => ( - - ( - - )} - onPress={() => { - if (item.kind === "library") { - router.push({ pathname: "/library/[id]", params: { id: item.id, title: item.title } }); - return; - } - router.push({ pathname: "/document/[id]", params: { id: item.id, title: item.title } }); - }} - /> - - )} - /> + + item.id} + estimatedItemSize={65} + contentContainerStyle={{ paddingBottom: Math.max(22, insets.bottom + 12) }} + onEndReachedThreshold={0.5} + onEndReached={() => { + if (query.hasNextPage && !query.isFetching) void query.fetchNextPage(); + }} + refreshControl={} + ListHeaderComponent={ + <> + {featured ? ( + open(featured)} + style={({ pressed }) => [styles.feature, pressed && styles.pressed]} + > + + + {t("mobile.home.resume")} + + + {featured.title || t("shell.untitled")} + {updated(featured)} + + + + + + + + + ) : null} + {header} + {query.isError ? ( + + {error} + + + ) : null} + + } + ListEmptyComponent={ + query.isPending ? + : !featured && !query.isError ? : null + } + renderItem={({ item }) => { + const library = item.kind === "library"; + const { Icon, bg, ink } = library + ? { Icon: BookOpen, bg: colors.selected, ink: colors.accent } + : formats[item.format]; + return ( + open(item)} + style={({ pressed }) => [styles.row, pressed && styles.pressed]} + > + + + + + {item.title || t("shell.untitled")} + {library ? t("nav.libraries") : formatLabel[item.format]} · {updated(item)} + + + + ); + }} + /> ); } + +const styles = StyleSheet.create({ + page: { flex: 1, backgroundColor: colors.bg }, + pressed: { opacity: 0.72 }, + feature: { + minHeight: 132, overflow: "hidden", marginHorizontal: 18, marginTop: 12, marginBottom: 6, + borderRadius: 17, borderCurve: "continuous", backgroundColor: colors.feature, + flexDirection: "row", alignItems: "center", padding: 16, gap: 12, + }, + featureCopy: { flex: 1, gap: 6 }, + featureAction: { flexDirection: "row", alignItems: "center", gap: 5 }, + featureTitle: { color: colors.onAccent, fontSize: 21, fontWeight: "700" }, + featureMeta: { color: colors.featureDetail, fontSize: 12 }, + paper: { + width: 72, minHeight: 88, gap: 7, padding: 10, + borderRadius: 12, borderCurve: "continuous", backgroundColor: colors.featurePaper, + transform: [{ rotate: "12deg" }, { translateY: 17 }], + }, + paperLine: { height: 4, borderRadius: 3, backgroundColor: colors.featureLine }, + paperTitle: { width: "60%", backgroundColor: colors.accent }, + paperShort: { width: "75%" }, + row: { + minHeight: 65, marginHorizontal: 18, paddingVertical: 8, + borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: colors.line, + flexDirection: "row", alignItems: "center", gap: 10, + }, + icon: { width: 40, height: 40, borderRadius: 11, borderCurve: "continuous", alignItems: "center", justifyContent: "center" }, + copy: { flex: 1, gap: 2 }, + title: { color: colors.ink, fontSize: 15, fontWeight: "600" }, + meta: { color: colors.secondary, fontSize: 12 }, + problem: { paddingHorizontal: 18, paddingVertical: 6, flexDirection: "row", alignItems: "center", gap: 8 }, +}); diff --git a/apps/mobile/src/session.ts b/apps/mobile/src/session.ts index 0c9a387c..8eeeb7ca 100644 --- a/apps/mobile/src/session.ts +++ b/apps/mobile/src/session.ts @@ -32,7 +32,15 @@ async function writeIndex(index: Index) { await SecureStore.setItemAsync(indexKey, JSON.stringify(index)); } -export async function loadVault() { +let vaultOperation = Promise.resolve(); + +function withVault(operation: () => Promise) { + const next = vaultOperation.then(operation); + vaultOperation = next.then(() => undefined, () => undefined); + return next; +} + +async function readVault() { const index = await readIndex(); const accounts: Session[] = []; for (const origin of index.origins) { @@ -51,51 +59,62 @@ export async function loadVault() { }; } +export function loadVault() { + return withVault(readVault); +} + export async function loadSession() { return (await loadVault()).session; } -export async function saveSession(session: Session) { - const vault = await loadVault(); - await SecureStore.setItemAsync( - accountKey(session.origin), - JSON.stringify(session), - ); - const origins = vault.accounts.some( - (account) => account.origin === session.origin, - ) - ? vault.accounts.map((account) => account.origin) - : [...vault.accounts.map((account) => account.origin), session.origin]; - await writeIndex({ current: session.origin, origins }); +export function saveSession(session: Session) { + return withVault(async () => { + const vault = await readVault(); + await SecureStore.setItemAsync( + accountKey(session.origin), + JSON.stringify(session), + ); + const origins = vault.accounts.some( + (account) => account.origin === session.origin, + ) + ? vault.accounts.map((account) => account.origin) + : [...vault.accounts.map((account) => account.origin), session.origin]; + await writeIndex({ current: session.origin, origins }); + }); } -export async function switchOrigin(origin: string) { - const vault = await loadVault(); - const next = vault.accounts.find((account) => account.origin === origin); - if (!next) throw new Error("这个服务器还没有保存的登录"); - await writeIndex({ - current: origin, - origins: vault.accounts.map((account) => account.origin), +export function switchOrigin(origin: string) { + return withVault(async () => { + const vault = await readVault(); + const next = vault.accounts.find((account) => account.origin === origin); + if (!next) throw new Error("这个服务器还没有保存的登录"); + await writeIndex({ + current: origin, + origins: vault.accounts.map((account) => account.origin), + }); + return next; }); - return next; } -export async function removeAccount(origin: string) { - const vault = await loadVault(); - await SecureStore.deleteItemAsync(accountKey(origin)); - await clearPluginCache(origin); - const accounts = vault.accounts.filter( - (account) => account.origin !== origin, - ); - const current = - vault.session?.origin === origin - ? (accounts[0]?.origin ?? "") - : (vault.session?.origin ?? ""); - await writeIndex({ - current, - origins: accounts.map((account) => account.origin), +export function removeAccount(origin: string, token: string) { + return withVault(async () => { + const vault = await readVault(); + if (!vault.accounts.some((account) => account.origin === origin && account.token === token)) return false; + await SecureStore.deleteItemAsync(accountKey(origin)); + await clearPluginCache(origin); + const accounts = vault.accounts.filter( + (account) => account.origin !== origin, + ); + const current = + vault.session?.origin === origin + ? (accounts[0]?.origin ?? "") + : (vault.session?.origin ?? ""); + await writeIndex({ + current, + origins: accounts.map((account) => account.origin), + }); + return true; }); - return accounts.find((account) => account.origin === current) ?? null; } export function normalizeOrigin(value: string) { diff --git a/apps/server/src/app/create-app.ts b/apps/server/src/app/create-app.ts index 0fb5dd65..1be86e5a 100644 --- a/apps/server/src/app/create-app.ts +++ b/apps/server/src/app/create-app.ts @@ -17,12 +17,15 @@ import { emitIntegrationEvent } from "@core/modules/automation/events.js"; import { bearerSession, mobileSession, + persistentAndroidExpiry, registerMobileClient, renewMobileSession, sessionExpiresAt, startMobilePush, } from "./mobile-client.js"; import { registerRuntimeSettings } from "../routes/runtime-settings.js"; +import { registerReleaseCheck } from "../routes/release-check.js"; +import type { ReleaseCheckOptions } from "../services/release-check.js"; import { registerSiteBranding } from "../routes/site-branding.js"; import { readSiteLogo } from "../services/site-logo.js"; import type { registerAI } from "../routes/ai.js"; @@ -121,6 +124,7 @@ export interface CreateAppOptions { webhookDispatch?: boolean; webhookResolve?: WebhookResolve; webhookPost?: WebhookPost; + releaseCheck?: ReleaseCheckOptions; } export async function createApp(db: DB, options: CreateAppOptions) { @@ -419,6 +423,7 @@ export async function createApp(db: DB, options: CreateAppOptions) { return a; }; const runtime = await registerRuntimeSettings(api, db, admin, options); + registerReleaseCheck(api, db, admin, options.releaseCheck); const historyWorker = createHistoryWorker(db, runtime.storage); let historyProcessing: Promise | undefined; let historyTimer: ReturnType | undefined; @@ -706,6 +711,9 @@ export async function createApp(db: DB, options: CreateAppOptions) { await passwordAllowed(db); if (user.status === "pending") return { status: "pending" }; if (user.status !== "active") fail(401, "账号或密码错误"); + const persistentAndroid = + req.headers["x-doca-client"] === "mobile" && + req.headers["x-doca-client-platform"] === "android"; const token = randomBytes(32).toString("hex"); await transact(db, async (tx) => { await passwordAllowed(tx); @@ -730,12 +738,12 @@ export async function createApp(db: DB, options: CreateAppOptions) { .values({ id: tokenHash(token), user_id: user.id, - expires_at: sessionExpiresAt(req), + expires_at: persistentAndroid ? persistentAndroidExpiry : sessionExpiresAt(req), }) .execute(); await recordLogin(tx, user.id); }); - reply.header("Set-Cookie", cookie(token)); + if (!persistentAndroid) reply.header("Set-Cookie", cookie(token)); return mobileSession(req, token, { user: publicUser(user) }); }, ); diff --git a/apps/server/src/app/mobile-client.ts b/apps/server/src/app/mobile-client.ts index 431d5672..cbc2db12 100644 --- a/apps/server/src/app/mobile-client.ts +++ b/apps/server/src/app/mobile-client.ts @@ -12,6 +12,8 @@ import { sessionDurations } from "./session-policy.js"; const sessionPattern = /^[a-f0-9]{64}$/; const qrCodePattern = /^[a-f0-9]{64}$/; +// A reserved ISO value fits the existing indexed expiry column and timed-session readers. +export const persistentAndroidExpiry = "9999-12-31T23:59:59.999Z"; export function sessionExpiresAt(req: { headers: FastifyRequest["headers"] }) { const mobile = req.headers["x-doca-client"] === "mobile"; diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 521d2422..8cbb745a 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -29,6 +29,7 @@ try { logging: true, webhookDatabase: webhookDb, webhookDispatch: true, + releaseCheck: {}, redisUrl: cfg.redisUrl, redisPrefix: cfg.redisPrefix, instanceId: cfg.instanceId, diff --git a/apps/server/src/plugins/store.ts b/apps/server/src/plugins/store.ts index ed2d35e0..3fd6b3fd 100644 --- a/apps/server/src/plugins/store.ts +++ b/apps/server/src/plugins/store.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import { downloadNpm } from "./npm.js"; export class StoreCursorExpired extends Error {} export const MAX_PLUGIN_BYTES = 32 * 1024 * 1024; +export const OFFICIAL_PLUGIN_STORE_ORIGIN = "https://store.smartdoca.cc"; const id = z .string() .regex(/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/) @@ -98,7 +99,7 @@ export const storeQuerySchema = z .strict(); export function pluginStoreUrl() { const url = new URL( - process.env.DOCA_PLUGIN_STORE_URL?.trim() || "https://store.smartdoca.cc", + process.env.DOCA_PLUGIN_STORE_URL?.trim() || OFFICIAL_PLUGIN_STORE_ORIGIN, ); if ( !["http:", "https:"].includes(url.protocol) || diff --git a/apps/server/src/routes/release-check.ts b/apps/server/src/routes/release-check.ts new file mode 100644 index 00000000..fd5c7011 --- /dev/null +++ b/apps/server/src/routes/release-check.ts @@ -0,0 +1,81 @@ +import { Type } from "@sinclair/typebox"; +import type { Actor } from "@core/modules/identity/passwords.js"; +import type { DB } from "@db/index.js"; +import type { FastifyInstance, FastifyRequest } from "fastify"; +import { + createReleaseChecker, + type ReleaseCheckOptions, +} from "../services/release-check.js"; + +export function registerReleaseCheck( + api: FastifyInstance, + db: DB, + admin: (req: FastifyRequest) => Actor, + options?: ReleaseCheckOptions, +) { + const releaseCheck = createReleaseChecker(db, options); + const path = "/api/v1/admin/release-check"; + const administration = { + tags: ["Administration"], + security: [{ session: [] }], + }; + let running = false; + let work: Promise | undefined; + function checkWhenDue() { + if (running && !work) + work = releaseCheck + .check() + .catch(() => api.log.warn("Doca release check state unavailable")) + .finally(() => { + work = undefined; + }); + } + + api.get( + path, + { + schema: { + ...administration, + summary: "Read server release check status", + }, + }, + async (req) => { + admin(req); + return releaseCheck.status(); + }, + ); + api.put<{ Body: { enabled: boolean } }>( + path, + { + schema: { + ...administration, + summary: "Enable or disable server release checks", + body: Type.Object( + { enabled: Type.Boolean() }, + { additionalProperties: false }, + ), + }, + }, + async (req) => { + admin(req); + const settings = await releaseCheck.setEnabled(req.body.enabled); + if (settings.enabled) checkWhenDue(); + return settings; + }, + ); + + if (!options) return; + let timer: ReturnType | undefined; + api.addHook("onReady", async () => { + running = true; + checkWhenDue(); + timer = setInterval(checkWhenDue, 60_000); + timer.unref(); + }); + api.addHook("preClose", async () => { + running = false; + clearInterval(timer); + releaseCheck.cancel(); + await work; + }); +} diff --git a/apps/server/src/services/release-check.ts b/apps/server/src/services/release-check.ts new file mode 100644 index 00000000..000feb81 --- /dev/null +++ b/apps/server/src/services/release-check.ts @@ -0,0 +1,213 @@ +import { randomUUID } from "node:crypto"; +import type { DB } from "@db/index.js"; +import { fail } from "@core/shared/errors.js"; +import { comparePluginVersions } from "@smartdoca/plugin-contracts"; +import { z } from "zod"; +import { HOST_VERSION } from "../app/version.js"; +import { OFFICIAL_PLUGIN_STORE_ORIGIN, readBounded } from "../plugins/store.js"; + +const settingsId = "software-release-check"; +const intervalMs = 60 * 60 * 1000; +const numericVersion = /^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})/; +const stableVersion = z.string().regex(new RegExp(numericVersion.source + "$")); +const hostVersion = z + .string() + .max(80) + .regex( + new RegExp( + numericVersion.source + + "(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$", + ), + ); + +const officialResponse = z.strictObject({ + protocolVersion: z.literal(1), + latestVersion: stableVersion, +}); +const stateSchema = z.strictObject({ + enabled: z.boolean(), + deploymentId: z.uuidv4(), + lastAttemptAt: z.number().int().nonnegative().nullable(), + result: z.union([stableVersion, z.literal("unavailable"), z.null()]), +}); +type State = z.infer; +type StoredState = { revision: number; config: State }; + +export type ReleaseCheckStatus = { + currentVersion: string; + enabled: boolean; + status: "disabled" | "waiting" | "unavailable" | "current" | "update"; + update: { version: string; image: string; releaseUrl: string } | null; +}; + +export type ReleaseCheckOptions = { + fetch?: typeof fetch; + now?: () => number; +}; + +async function requestRelease( + fetcher: typeof fetch, + deploymentId: string, + signal: AbortSignal, +) { + const response = await fetcher( + new URL("/api/v1/doca/releases/check", OFFICIAL_PLUGIN_STORE_ORIGIN), + { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + }, + body: JSON.stringify({ + protocolVersion: 1, + currentVersion: hostVersion.parse(HOST_VERSION), + deploymentId, + }), + redirect: "error", + credentials: "omit", + signal: AbortSignal.any([signal, AbortSignal.timeout(5_000)]), + }, + ); + const contentType = response.headers + .get("content-type") + ?.split(";")[0] + ?.trim() + .toLowerCase(); + if (response.status !== 200 || contentType !== "application/json") { + await response.body?.cancel(); + throw new Error("Invalid Doca release check response"); + } + const data = JSON.parse( + (await readBounded(response, 4 * 1024)).toString("utf8"), + ); + return officialResponse.parse(data).latestVersion; +} + +function status(config?: State): ReleaseCheckStatus { + const base = { + currentVersion: HOST_VERSION, + enabled: config?.enabled ?? true, + update: null, + }; + if (!base.enabled) return { ...base, status: "disabled" }; + const version = config?.result; + if (!version) return { ...base, status: "waiting" }; + if (version === "unavailable") return { ...base, status: "unavailable" }; + if (comparePluginVersions(version, HOST_VERSION) <= 0) + return { ...base, status: "current" }; + return { + ...base, + status: "update", + update: { + version, + image: `docker.io/smartdoca/doca:${version}`, + releaseUrl: `https://github.com/workhold/doca/releases/tag/v${version}`, + }, + }; +} + +export function createReleaseChecker( + db: DB, + { fetch: fetcher = fetch, now = Date.now }: ReleaseCheckOptions = {}, +) { + let active: AbortController | undefined; + + async function read(): Promise { + const row = await db + .selectFrom("account_settings") + .select(["config", "revision"]) + .where("id", "=", settingsId) + .executeTakeFirst(); + if (row) + return { + revision: row.revision, + config: stateSchema.parse(JSON.parse(row.config)), + }; + } + + async function initialize(): Promise { + const row = await read(); + if (row) return row; + const config: State = { + enabled: true, + deploymentId: randomUUID(), + lastAttemptAt: null, + result: null, + }; + await db + .insertInto("account_settings") + .values({ id: settingsId, config: JSON.stringify(config), revision: 1 }) + .onConflict((oc) => oc.column("id").doNothing()) + .execute(); + const saved = await read(); + if (!saved) + throw new Error("Doca release check settings could not be initialized"); + return saved; + } + + async function replace(revision: number, config: State) { + const changed = await db + .updateTable("account_settings") + .set({ config: JSON.stringify(config), revision: revision + 1 }) + .where("id", "=", settingsId) + .where("revision", "=", revision) + .executeTakeFirst(); + return Boolean(changed.numUpdatedRows); + } + + return { + async status() { + return status((await read())?.config); + }, + + async setEnabled(enabled: boolean) { + for (let attempt = 0; attempt < 5; attempt++) { + const { revision, config } = await initialize(); + const next = + config.enabled === enabled + ? config + : { ...config, enabled, result: null }; + if (next !== config && !(await replace(revision, next))) continue; + if (!enabled) active?.abort(); + return status(next); + } + fail(409, "release_check_settings_changed"); + }, + + async check() { + if (active) return; + const controller = new AbortController(); + active = controller; + try { + const { revision, config } = await initialize(); + const time = now(); + if ( + !config.enabled || + controller.signal.aborted || + (config.lastAttemptAt !== null && + time - config.lastAttemptAt < intervalMs) + ) + return; + + // Claim the hourly slot before sending. This revision also guards the + // result against a later settings change on any server replica. + const claimed = { ...config, lastAttemptAt: time }; + if (!(await replace(revision, claimed)) || controller.signal.aborted) + return; + const result = await requestRelease( + fetcher, + config.deploymentId, + controller.signal, + ).catch(() => "unavailable" as const); + if (!controller.signal.aborted) + await replace(revision + 1, { ...claimed, result }); + } finally { + active = undefined; + } + }, + + cancel() { + active?.abort(); + }, + }; +} diff --git a/apps/web/src/features/admin/admin.css b/apps/web/src/features/admin/admin.css index af19d362..0296c046 100644 --- a/apps/web/src/features/admin/admin.css +++ b/apps/web/src/features/admin/admin.css @@ -487,6 +487,38 @@ font-size: 12px; line-height: 1.7; } +.admin-release-version { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px 16px; + margin: 12px 0; + font-size: 13px; + overflow-wrap: anywhere; +} +.admin-release-toggle, +.admin-release-upgrade { + border-top: 1px solid var(--line-soft); + padding-top: 14px; + margin-top: 14px; +} +.admin-release-toggle { + cursor: pointer; +} +.admin-release-upgrade { + font-size: 13px; + overflow-wrap: anywhere; +} +.admin-release-upgrade p { + margin: 0 0 8px; +} +.admin-release-upgrade .admin-code-example { + white-space: pre-wrap; +} +.admin-release-upgrade .admin-inline-actions { + align-items: center; + margin-bottom: 0; +} .section-divider { height: 1px; background: var(--line-soft); diff --git a/apps/web/src/features/admin/admin.tsx b/apps/web/src/features/admin/admin.tsx index 31f92d1c..03fb280b 100644 --- a/apps/web/src/features/admin/admin.tsx +++ b/apps/web/src/features/admin/admin.tsx @@ -50,6 +50,7 @@ import { UserCardSettings } from "@web/features/settings/user-card-settings.js"; import { DistributionSettings } from "@web/features/settings/distribution-settings.js"; import { FileRecognitionSettings } from "@web/features/admin/file-recognition-settings.js"; import { SiteLogoSettings } from "./site-logo-settings.js"; +import { ReleaseCheckSettings } from "./release-check-settings.js"; import { useI18n } from "@web/shared/i18n.js"; import type { MessageKey } from "@doca/i18n"; import { webPluginRegistry } from "@web/plugins/registry.js"; @@ -859,6 +860,7 @@ export function Admin({ ))} + {platformTab === "general" && } {platformTab === "general" && settings && ( <> diff --git a/apps/web/src/features/admin/release-check-settings.tsx b/apps/web/src/features/admin/release-check-settings.tsx new file mode 100644 index 00000000..2188ff0c --- /dev/null +++ b/apps/web/src/features/admin/release-check-settings.tsx @@ -0,0 +1,143 @@ +import { useEffect, useId, useState } from "react"; +import type { ReleaseCheckStatus } from "@server/services/release-check.js"; +import { api } from "@web/shared/api.js"; +import { writeClipboardText } from "@web/shared/clipboard.js"; +import { notifyFeedback } from "@web/shared/components/feedback.js"; +import { useI18n } from "@web/shared/i18n.js"; + +const path = "/admin/release-check"; +const composeCommand = + "docker compose pull doca && docker compose up -d --no-deps doca"; + +export function ReleaseCheckSettings() { + const { t } = useI18n(); + const titleId = useId(); + const toggleId = useId(); + const [settings, setSettings] = useState(); + const [loadFailed, setLoadFailed] = useState(false); + const [saving, setSaving] = useState(false); + const enabled = settings?.enabled; + + useEffect(() => { + if (saving || enabled === false) return; + const controller = new AbortController(); + async function refresh() { + try { + const result = await api( + path, + "GET", + undefined, + controller.signal, + ); + if (controller.signal.aborted) return; + setSettings(result); + setLoadFailed(false); + } catch { + if (!controller.signal.aborted) setLoadFailed(true); + } + } + if (enabled === undefined) { + void refresh(); + return () => controller.abort(); + } + const timer = setInterval(() => void refresh(), 60_000); + return () => { + clearInterval(timer); + controller.abort(); + }; + }, [enabled, saving]); + + async function toggle(enabled: boolean) { + setSaving(true); + try { + setSettings(await api(path, "PUT", { enabled })); + setLoadFailed(false); + } catch { + notifyFeedback(t("admin.release.saveFailed"), "error"); + } finally { + setSaving(false); + } + } + + async function copyCommand() { + try { + await writeClipboardText(composeCommand); + notifyFeedback(t("mcp.copied"), "success"); + } catch { + notifyFeedback(t("mcp.copyFailed"), "error"); + } + } + + return ( +
+
+

{t("admin.release.heading")}

+
+ {loadFailed &&

{t("admin.release.loadFailed")}

} + {!settings && !loadFailed &&

{t("common.loading")}

} + {settings && ( + <> +
+ + {t("admin.release.installed")}{" "} + {settings.currentVersion} + + + {t(`admin.release.${settings.status}`, { + version: settings.update?.version ?? "", + })} + +
+ + {settings.update && ( +
+

{t("admin.release.composeHelp")}

+ {settings.update.image} +
+                {composeCommand}
+              
+
+ + + {t("admin.release.notes")} + +
+
+ )} + + )} +
+ ); +} diff --git a/apps/web/src/features/files/file-interactions.ts b/apps/web/src/features/files/file-interactions.ts index 3408d1a6..1683b338 100644 --- a/apps/web/src/features/files/file-interactions.ts +++ b/apps/web/src/features/files/file-interactions.ts @@ -188,19 +188,6 @@ export function sameTrail(a: ColumnLocation[], b: ColumnLocation[]) { return a.length === b.length && a.every((item, index) => locationKey(item) === locationKey(b[index]!)); } -export function reusedColumnPrefix( - trail: ColumnLocation[], - columns: T[], -): T[] { - const reused: T[] = []; - for (let index = 0; index < trail.length; index++) { - const existing = columns[index]; - if (!existing || locationKey(existing.location) !== locationKey(trail[index]!)) break; - reused.push(existing); - } - return reused; -} - export type DroppedUpload = { path: string; file?: File; @@ -303,15 +290,3 @@ export async function materializeExternalDrop( } return captured.files.filter((item) => item.path !== ".DS_Store" && !item.path.endsWith("/.DS_Store")); } - -export function replaceColumnPage( - columns: T[], - location: ColumnLocation, - page: T["page"], -): T[] { - const index = columns.findIndex((column) => locationKey(column.location) === locationKey(location)); - if (index < 0) return columns; - const next = columns.slice(); - next[index] = { ...next[index]!, page }; - return next; -} diff --git a/apps/web/src/features/files/files.css b/apps/web/src/features/files/files.css index ed4005cc..3f553e0b 100644 --- a/apps/web/src/features/files/files.css +++ b/apps/web/src/features/files/files.css @@ -1036,6 +1036,23 @@ } .files-empty strong { color: #505b6c; } .files-empty span { color: #9aa2ae; font-size: 12px; } +.files-loading { + min-height: 220px; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 12px; + box-sizing: border-box; + color: var(--text-secondary); + font-size: 13px; + text-align: center; +} +.files-column .files-loading { min-height: 88px; } +.files-loading svg { flex: none; } +@media (prefers-reduced-motion: no-preference) { + .files-loading svg { animation: file-parse-spin .8s linear infinite; } +} .file-preview-panel { width: min(380px, 34%); border: 1px solid #e5e8ed; diff --git a/apps/web/src/features/files/files.tsx b/apps/web/src/features/files/files.tsx index 77fae8d0..b6bf6609 100644 --- a/apps/web/src/features/files/files.tsx +++ b/apps/web/src/features/files/files.tsx @@ -65,13 +65,12 @@ import { isExternalFileDrag, isInternalFileDrag, idsInMarquee, + locationKey, materializeExternalDrop, nextAvailableName, normalizeRect, orderedRange, readFileDrag, - replaceColumnPage, - reusedColumnPrefix, sameTrail, toggleSelectedId, trailAfterRemovedFolders, @@ -137,6 +136,16 @@ function compareFiles(a: FileItem, b: FileItem, mode: SortMode, locale: string) } const root: Location = { type: "system", id: "root", name: "我的文件夹" }; + +function readFolderPage({ type, id }: Location) { + const params = new URLSearchParams({ parentType: type, parentId: id }); + return api(`/files?${params}`); +} + +function isFolderNotFound(error: unknown) { + return typeof error === "object" && error !== null && "status" in error && error.status === 404; +} + function readFocusId() { if (typeof window === "undefined") return null; return new URLSearchParams(window.location.hash.split("?")[1] ?? "").get("focus",); @@ -513,7 +522,8 @@ export function FilesExplorer({ ); const [trail, setTrail] = useState(initialTrail); const [future, setFuture] = useState([]); - const [loadedPage, setLoadedPage] = useState<{ key: string; page: FilePage } | null>(null); + const [folderPages, setFolderPages] = useState(() => new Map()); + const [failedLocationKey, setFailedLocationKey] = useState(null); const [selection, setSelection] = useState(null); const [selectedIds, setSelectedIds] = useState>(new Set()); const [anchorId, setAnchorId] = useState(null); @@ -592,7 +602,6 @@ export function FilesExplorer({ window.removeEventListener("doca-page-state", onPageState); }; }, []); - const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const [notice, setNotice] = useState(""); const [downloading, setDownloading] = useState(false); @@ -625,22 +634,25 @@ export function FilesExplorer({ const [recognitionConfirm, setRecognitionConfirm] = useState<{ target: Selectable | null; } | null>(null); - const [columnPages, setColumnPages] = useState< - Array<{ location: Location; page: FilePage }> - >([]); const [focusId, setFocusId] = useState(() => readFocusId()); const appliedFocus = useRef(null); const [columnsRev, setColumnsRev] = useState(0); - const columnPagesRef = useRef(columnPages); - const currentColumnRef = useRef(null); + const currentColumnTitleRef = useRef(null); const refreshColumnsRef = useRef(false); - columnPagesRef.current = columnPages; const navigationKey = trailKey(trail); - const currentLocationKey = `${location.type}:${location.id}`; + const currentLocationKey = locationKey(location); const currentLocationRef = useRef(currentLocationKey); currentLocationRef.current = currentLocationKey; const loadSequence = useRef(0); - const data = loadedPage?.key === currentLocationKey ? loadedPage.page : null; + const data = folderPages.get(currentLocationKey); + const loading = !data && failedLocationKey !== currentLocationKey; + const columnPages = useMemo( + () => trail.flatMap((item) => { + const page = folderPages.get(locationKey(item)); + return page ? [page] : []; + }), + [folderPages, trail], + ); const setAIFileContext = ai?.setFileContext; useEffect(() => { if (!setAIFileContext) return; @@ -708,14 +720,14 @@ export function FilesExplorer({ if (fromCurrent.length === selectedIds.size) return fromCurrent; const seen = new Set(fromCurrent.map((value) => value.value.id)); const extra: Selectable[] = []; - for (const column of columnPages) { - for (const folder of column.page.folders) { + for (const page of columnPages) { + for (const folder of page.folders) { if (selectedIds.has(folder.id) && !seen.has(folder.id)) { seen.add(folder.id); extra.push({ kind: "folder", value: folder }); } } - for (const file of column.page.files) { + for (const file of page.files) { if (selectedIds.has(file.id) && !seen.has(file.id)) { seen.add(file.id); extra.push({ kind: "file", value: file }); @@ -760,23 +772,16 @@ export function FilesExplorer({ const atSystemRoot = trail.length <= 1 && systemReadonly; async function load(next = location, options?: { refreshColumns?: boolean }) { + const requestedKey = locationKey(next); + if (currentLocationRef.current !== requestedKey) return; const sequence = ++loadSequence.current; - const requestedKey = `${next.type}:${next.id}`; const current = () => sequence === loadSequence.current && currentLocationRef.current === requestedKey; - const keepColumns = view === "columns" && columnPagesRef.current.length > 0; - // Keep the current folder visible while refreshing upload and parsing status. - if (loadedPage?.key !== requestedKey && !keepColumns) setLoading(true); + setFailedLocationKey(null); setError(""); try { - const params = new URLSearchParams({ - parentType: next.type, - parentId: next.id, - }); - const page = await api(`/files?${params}`); + const page = await readFolderPage(next); if (!current()) return; - setLoadedPage({ key: requestedKey, page }); - if (view === "columns") - setColumnPages((old) => replaceColumnPage(old, next, page)); + setFolderPages((old) => new Map(old).set(requestedKey, page)); if (options?.refreshColumns) { refreshColumnsRef.current = true; setColumnsRev((value) => value + 1); @@ -785,12 +790,7 @@ export function FilesExplorer({ if (!current()) return; const message = e instanceof Error ? e.message : t("fileManager.loadFailed"); - if ( - typeof e === "object" && - e !== null && - "status" in e && - e.status === 404 - ) { + if (isFolderNotFound(e)) { const nextTrail = trailAfterRemovedFolders(trail, [next.id]); if (nextTrail.kind === "parent") { setFuture([]); @@ -807,14 +807,21 @@ export function FilesExplorer({ return; } } + setFailedLocationKey(requestedKey); setError(fileLocationError(message, t)); - } finally { - if (current()) setLoading(false); } } useEffect(() => { void load(); - }, [location.type, location.id]); + return () => { loadSequence.current++; }; + }, [currentLocationKey]); + useEffect(() => { + const pathKeys = new Set(trail.map(locationKey)); + setFolderPages((old) => { + const pages = [...old].filter(([key]) => pathKeys.has(key)); + return pages.length === old.size ? old : new Map(pages); + }); + }, [navigationKey]); useEffect(() => { if (trail[0]?.type !== "system" || trail[0].id !== "ai") return; const changed = (event: Event) => { @@ -828,7 +835,6 @@ export function FilesExplorer({ setSelectedIds(new Set()); setLargePreview(null); navigateTrail(recovered.trail); - void load(recovered.trail[recovered.trail.length - 1]!, { refreshColumns: true }); return; } } @@ -865,7 +871,7 @@ export function FilesExplorer({ const file = data?.files.find((item) => item.id === focusId) ?? columnPages - .flatMap((column) => column.page.files) + .flatMap((page) => page.files) .find((item) => item.id === focusId); if (!file) return; appliedFocus.current = focusId; @@ -877,33 +883,20 @@ export function FilesExplorer({ useEffect(() => { if (view !== "columns") return; let cancelled = false; - const nextTrail = trail; const force = refreshColumnsRef.current; refreshColumnsRef.current = false; void (async () => { - const current = columnPagesRef.current; - const reused = - force && current.length ? [] : reusedColumnPrefix(nextTrail, current); - const pages = - force && current.length - ? current.slice(0, nextTrail.length) - : [...reused]; - if (!force && reused.length !== current.length) setColumnPages(reused); - const start = force && current.length ? 0 : reused.length; - for (let index = start; index < nextTrail.length; index++) { - const item = nextTrail[index]!; + for (let index = 0; index < trail.length - 1; index++) { + const item = trail[index]!; + const key = locationKey(item); + if (!force && folderPages.has(key)) continue; try { - const params = new URLSearchParams({ - parentType: item.type, - parentId: item.id, - }); - const page = await api(`/files?${params}`); - if (cancelled) return; - pages[index] = { location: item, page }; - setColumnPages(pages.slice(0, index + 1)); - } catch { - if (!cancelled && index > 0) { - const recovered = trailAfterRemovedFolders(nextTrail, [item.id]); + const page = await readFolderPage(item); + if (cancelled || currentLocationRef.current === key) return; + setFolderPages((old) => new Map(old).set(key, page)); + } catch (error) { + if (!cancelled && index > 0 && isFolderNotFound(error)) { + const recovered = trailAfterRemovedFolders(trail, [item.id]); if (recovered.kind === "parent") { setFuture([]); navigateTrail(recovered.trail); @@ -918,7 +911,7 @@ export function FilesExplorer({ }; }, [columnsRev, navigationKey, view]); useEffect(() => { - if (view === "columns") currentColumnRef.current?.scrollIntoView({ block: "nearest", inline: "end" }); + if (view === "columns") currentColumnTitleRef.current?.scrollIntoView({ block: "nearest", inline: "end" }); }, [navigationKey, view, columnPages.length]); useEffect(() => { const close = () => { @@ -1372,11 +1365,11 @@ export function FilesExplorer({ renaming.kind === "folder" ? (data?.folders.find((folder) => folder.id === renaming.id) ?? columnPages - .flatMap((column) => column.page.folders) + .flatMap((page) => page.folders) .find((folder) => folder.id === renaming.id)) : (data?.files.find((file) => file.id === renaming.id) ?? columnPages - .flatMap((column) => column.page.files) + .flatMap((page) => page.files) .find((file) => file.id === renaming.id)); const name = renaming.draft.trim(); if (!current || !name) { @@ -1403,12 +1396,6 @@ export function FilesExplorer({ setTrail(nextTrail); setLocation(renamed(location)); setFuture((old) => old.map(renamed)); - setColumnPages((old) => - old.map((column) => ({ - ...column, - location: renamed(column.location), - })), - ); if ( trail.some((item) => item.type === "folder" && item.id === current.id) ) @@ -1818,10 +1805,10 @@ export function FilesExplorer({ } function columnSelectable(id?: string) { if (!id) return null; - for (const column of columnPages) { - const folder = column.page.folders.find((item) => item.id === id); + for (const page of columnPages) { + const folder = page.folders.find((item) => item.id === id); if (folder) return { kind: "folder" as const, value: folder }; - const file = column.page.files.find((item) => item.id === id); + const file = page.files.find((item) => item.id === id); if (file) return { kind: "file" as const, value: file }; } return allValues.find((value) => value.value.id === id) ?? null; @@ -2143,11 +2130,12 @@ export function FilesExplorer({ ...files.map((value) => ({ kind: "file" as const, value })), ]; }; - const renderedColumns = columnPages.length - ? columnPages - : data - ? [{ location, page: data }] - : []; + const loadingStatus = loading && ( +
+
+ ); return (