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 ( + + + { setError(""); setAttempt((current) => current + 1); }}>{t("shell.retry")} + router.push("/ai/settings")}>{t("chat.preferences")} + + ); + } + 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")} + void createSession()}>{t("chat.newChat")} - {menuError ? {menuError} : null} - - {(sessions.data ?? []).map((item) => ( - openSession(item.id)}> - - - {item.title || "新对话"} - - - ))} - - + {menuError ? {menuError} : null} + {sessions.isPending ? : null} + {sessions.isError ? ( + <> + {sessions.error.message} + void sessions.refetch()}>{t("shell.retry")} + > + ) : 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} + void refetch()}>{t("shell.retry")} + + ); } + 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 ? ( + void options.refetch()}>{t("shell.retry")} + ) : 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} + + ))} + + setPickingAttachment(false)}>{t("common.cancel")} + + 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} + + + + { setPickingModel(false); router.push("/ai/settings"); }}>{t("chat.preferences")} + setPickingModel(false)}>{t("dialog.close")} + + + ); } @@ -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")} /> + + } textColor={colors.danger} onPress={confirmSignOut}> + {t("account.signOut")} + + + ); +} + +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 })} + void mark()}>{t("shell.markRead")} + + {error || query.isError ? ( + + {error || query.error?.message} + {query.isError ? void query.refetch()}>{t("shell.retry")} : 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 ? ( + void query.fetchNextPage()}>{t("navigation.more")} + ) : 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} + void query.refetch()}>{t("shell.retry")} + > + ) : 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 ? : } + + ); + })} + + + {t("dialog.close")} + + + ); +} + +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} - - - - 文件夹 - - openPrompt({ kind: "create" })}> - 新建文件夹 - - void pickDocument()}> - 上传文件 - - void pickImage()}> - 从相册选择 - - - + setAddMenu(false)} style={styles.addDialog}> + {t("chat.addFiles")} + + openPrompt({ kind: "create" })}> + {t("fileManager.newFolder")} + + void pickDocument()}> + {t("fileManager.uploadLocal")} + + void pickImage("camera")}> + {t("mobile.files.camera")} + + void pickImage("library")}> + {t("mobile.files.album")} + + + setAddMenu(false)}>{t("common.cancel")} + 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} + void refetch()}>{t("shell.retry")} + + ) : 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 ?? "", + })} + + + + + {t("admin.release.automatic")} + + {t("admin.release.disclosure")} + + + void toggle(event.target.checked)} + /> + + {settings.update && ( + + {t("admin.release.composeHelp")} + {settings.update.image} + + {composeCommand} + + + void copyCommand()} + > + {t("admin.release.copyCommand")} + + + {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 && ( + + + {t("fileManager.loading")} + + ); return ( 0 && allValues.every((value) => selectedIds.has(value.value.id))} > @@ -2428,9 +2416,11 @@ export function FilesExplorer({ )} - - {t("fileManager.itemCount", { count: items.length })} - + {data && ( + + {t("fileManager.itemCount", { count: items.length })} + + )} )} - {loading && !(view === "columns" && renderedColumns.length) ? ( - {t("fileManager.loading")} - ) : !items.length && - !(view === "columns" && renderedColumns.length) ? ( + {view === "columns" ? ( + + {trail.map((item, index) => { + const key = locationKey(item); + const page = folderPages.get(key); + const isCurrent = index === trail.length - 1; + if (!page && !isCurrent) return null; + const values = page ? columnValues(page, isCurrent) : []; + const title = fileLocationLabel(item, t); + return ( + { + event.stopPropagation(); + handleCanvasDragOver(event, item.id); + }} + onDrop={(event) => handleCanvasDrop(event, item)} + > + + {title} + + {page ? ( + + {values.map((value) => + row(value, `${item.id}:${value.value.id}`, { + openFolder: (folder) => openInColumn(folder, index), + openFolderOnClick: true, + pathSelected: trail[index + 1]?.id === value.value.id, + ordered: values, + columnIndex: index, + lastColumn: isCurrent, + }), + )} + {!values.length && ( + + {t("fileManager.emptyFolder")} + + )} + + ) : loadingStatus} + + ); + })} + + ) : !data ? ( + loadingStatus + ) : !items.length ? ( @@ -2555,87 +2589,22 @@ export function FilesExplorer({ : t("fileManager.emptyHelp")} - ) : ( + ) : view === "list" ? ( <> - {view === "list" ? ( - <> - - {t("shell.name")} - {t("fileManager.modifiedDate")} - {t("fileManager.size")} - {t("fileManager.kind")} - - - {visibleFolders.map((folder) => - row({ kind: "folder", value: folder }, folder.id), - )} - {visibleFiles.map((file) => - row({ kind: "file", value: file }, file.id), - )} - - > - ) : view === "grid" ? ( - - {visibleFolders.map((folder) => - row({ kind: "folder", value: folder }, folder.id), - )} - {visibleFiles.map((file) => - row({ kind: "file", value: file }, file.id), - )} - - ) : ( - - {renderedColumns.map((column, index) => { - const values = columnValues( - column.page, - index === renderedColumns.length - 1, - ); - return ( - { - event.stopPropagation(); - handleCanvasDragOver(event, column.location.id); - }} - onDrop={(event) => - handleCanvasDrop(event, column.location) - } - > - - {fileLocationLabel(column.location, t)} - - - {values.map((value) => - row( - value, - `${column.location.id}:${value.value.id}`, - { - openFolder: (folder) => - openInColumn(folder, index), - openFolderOnClick: true, - pathSelected: - trail[index + 1]?.id === value.value.id, - ordered: values, - columnIndex: index, - lastColumn: - index === renderedColumns.length - 1, - }, - ), - )} - {!values.length && ( - - {t("fileManager.emptyFolder")} - - )} - - - ); - })} - - )} + + {t("shell.name")} + {t("fileManager.modifiedDate")} + {t("fileManager.size")} + {t("fileManager.kind")} + + + {allValues.map((value) => row(value, value.value.id))} + > + ) : ( + + {allValues.map((value) => row(value, value.value.id))} + )} {view === "columns" && ( diff --git a/compose.yaml b/compose.yaml index 83f28644..6626e11e 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,14 +1,14 @@ # Production-oriented single-host deployment. # Put the browser-facing HTTP(S) DOCA_ORIGIN in .env. # Use a reverse proxy for HTTPS or internal HTTP; forward to 127.0.0.1:39120. -# The published image is docker.io/smartdoca/doca:0.3.1. +# The published image is docker.io/smartdoca/doca:0.3.2. # `docker compose up -d` pulls that tag. Add `--build` to build from this checkout. services: doca: build: context: . dockerfile: Dockerfile - image: docker.io/smartdoca/doca:0.3.1 + image: docker.io/smartdoca/doca:0.3.2 pull_policy: always restart: unless-stopped init: true diff --git a/docs/README.es.md b/docs/README.es.md index af8142b1..4ba3eb67 100644 --- a/docs/README.es.md +++ b/docs/README.es.md @@ -4,7 +4,7 @@ [English](README.md) · [简体中文](README.zh-CN.md) · [繁體中文](README.zh-Hant.md) · [日本語](README.ja.md) · [Français](README.fr.md) · [한국어](README.ko.md) · [Español](README.es.md) · [Русский](README.ru.md) -Doca es un espacio de trabajo para gestionar documentos y conocimiento, diseñado para personas y equipos pequeños. Estas guías explican cómo instalar, usar, administrar y ampliar Doca. Consulta las [Notas de la versión 0.3.1](releases/0.3.1.es.md) antes de instalar o actualizar. +Doca es un espacio de trabajo para gestionar documentos y conocimiento, diseñado para personas y equipos pequeños. Estas guías explican cómo instalar, usar, administrar y ampliar Doca. Consulta las [Notas de la versión 0.3.2](releases/0.3.2.es.md) antes de instalar o actualizar. [Sitio oficial](https://i.smartdoca.cc) · [Demostración en línea](https://d.smartdoca.cc) · [Mercado de complementos](https://store.smartdoca.cc) @@ -70,7 +70,7 @@ Doca es un espacio de trabajo para gestionar documentos y conocimiento, diseñad - [Contrato de almacenamiento de complementos](plugin-horizontal-scaling.es.md) - [Contrato de colaboración](collaboration-sdk-contract.es.md) - [Intercambio de archivos](editor-file-exchange-contract.es.md) -- [Notas de la versión](releases/0.3.1.es.md) +- [Notas de la versión](releases/0.3.2.es.md) - [Mantenimiento de la documentación](documentation.es.md) - [Registros de investigación y verificación](research.es.md) diff --git a/docs/README.fr.md b/docs/README.fr.md index 7cfcfc22..3fb875c5 100644 --- a/docs/README.fr.md +++ b/docs/README.fr.md @@ -4,7 +4,7 @@ [English](README.md) · [简体中文](README.zh-CN.md) · [繁體中文](README.zh-Hant.md) · [日本語](README.ja.md) · [Français](README.fr.md) · [한국어](README.ko.md) · [Español](README.es.md) · [Русский](README.ru.md) -Doca est un espace de travail pour gérer des documents et des connaissances, conçu pour les particuliers et les petites équipes. Ces guides couvrent l’installation, l’utilisation, l’exploitation et les extensions. Consultez les [Notes de version 0.3.1](releases/0.3.1.fr.md) avant d’installer ou de mettre à jour Doca. +Doca est un espace de travail pour gérer des documents et des connaissances, conçu pour les particuliers et les petites équipes. Ces guides couvrent l’installation, l’utilisation, l’exploitation et les extensions. Consultez les [Notes de version 0.3.2](releases/0.3.2.fr.md) avant d’installer ou de mettre à jour Doca. [Site officiel](https://i.smartdoca.cc) · [Démo en ligne](https://d.smartdoca.cc) · [Catalogue de plugins](https://store.smartdoca.cc) @@ -70,7 +70,7 @@ Doca est un espace de travail pour gérer des documents et des connaissances, co - [Contrat de stockage des plugins](plugin-horizontal-scaling.fr.md) - [Contrat de collaboration](collaboration-sdk-contract.fr.md) - [Échange de fichiers](editor-file-exchange-contract.fr.md) -- [Notes de version](releases/0.3.1.fr.md) +- [Notes de version](releases/0.3.2.fr.md) - [Maintenance de la documentation](documentation.fr.md) - [Études et rapports de vérification](research.fr.md) diff --git a/docs/README.ja.md b/docs/README.ja.md index db1957a7..8c909dce 100644 --- a/docs/README.ja.md +++ b/docs/README.ja.md @@ -4,7 +4,7 @@ [English](README.md) · [简体中文](README.zh-CN.md) · [繁體中文](README.zh-Hant.md) · [日本語](README.ja.md) · [Français](README.fr.md) · [한국어](README.ko.md) · [Español](README.es.md) · [Русский](README.ru.md) -Doca は個人や小規模チームで文書とナレッジを管理するためのワークスペースです。ここでは導入、利用、運用、拡張方法を説明します。インストールや更新の前に[リリースノート 0.3.1](releases/0.3.1.ja.md)をご確認ください。 +Doca は個人や小規模チームで文書とナレッジを管理するためのワークスペースです。ここでは導入、利用、運用、拡張方法を説明します。インストールや更新の前に[リリースノート 0.3.2](releases/0.3.2.ja.md)をご確認ください。 [公式サイト](https://i.smartdoca.cc) · [オンラインデモ](https://d.smartdoca.cc) · [プラグインストア](https://store.smartdoca.cc) @@ -70,7 +70,7 @@ Doca は個人や小規模チームで文書とナレッジを管理するため - [プラグインのストレージ仕様](plugin-horizontal-scaling.ja.md) - [共同編集の仕様](collaboration-sdk-contract.ja.md) - [ファイル交換](editor-file-exchange-contract.ja.md) -- [リリースノート](releases/0.3.1.ja.md) +- [リリースノート](releases/0.3.2.ja.md) - [ドキュメントの保守](documentation.ja.md) - [調査・検証記録](research.ja.md) diff --git a/docs/README.ko.md b/docs/README.ko.md index 32e8fa6f..5a0c8581 100644 --- a/docs/README.ko.md +++ b/docs/README.ko.md @@ -4,7 +4,7 @@ [English](README.md) · [简体中文](README.zh-CN.md) · [繁體中文](README.zh-Hant.md) · [日本語](README.ja.md) · [Français](README.fr.md) · [한국어](README.ko.md) · [Español](README.es.md) · [Русский](README.ru.md) -Doca는 개인과 소규모 팀이 문서와 지식을 관리하는 작업 공간입니다. 이 문서에서는 설치, 사용, 운영, 확장 방법을 안내합니다. 설치하거나 업데이트하기 전에 [릴리스 노트 0.3.1](releases/0.3.1.ko.md)를 확인하세요. +Doca는 개인과 소규모 팀이 문서와 지식을 관리하는 작업 공간입니다. 이 문서에서는 설치, 사용, 운영, 확장 방법을 안내합니다. 설치하거나 업데이트하기 전에 [릴리스 노트 0.3.2](releases/0.3.2.ko.md)를 확인하세요. [공식 웹사이트](https://i.smartdoca.cc) · [온라인 데모](https://d.smartdoca.cc) · [플러그인 마켓](https://store.smartdoca.cc) @@ -70,7 +70,7 @@ Doca는 개인과 소규모 팀이 문서와 지식을 관리하는 작업 공 - [플러그인 저장소 규약](plugin-horizontal-scaling.ko.md) - [공동 편집 규약](collaboration-sdk-contract.ko.md) - [파일 교환](editor-file-exchange-contract.ko.md) -- [릴리스 노트](releases/0.3.1.ko.md) +- [릴리스 노트](releases/0.3.2.ko.md) - [문서 관리](documentation.ko.md) - [조사 및 검증 기록](research.ko.md) diff --git a/docs/README.md b/docs/README.md index 2a2977ec..90c27573 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,7 +2,7 @@ **English** · [简体中文](README.zh-CN.md) · [繁體中文](README.zh-Hant.md) · [日本語](README.ja.md) · [Français](README.fr.md) · [한국어](README.ko.md) · [Español](README.es.md) · [Русский](README.ru.md) -Doca is a document and knowledge workspace for individuals and small teams. These guides track current source; follow the [0.3.1 release notes](releases/0.3.1.md) for installation and upgrades. Package contracts identify their own implementation limits. +Doca is a document and knowledge workspace for individuals and small teams. These guides track current source; follow the [0.3.2 release notes](releases/0.3.2.md) for installation and upgrades. Package contracts identify their own implementation limits. [Website](https://i.smartdoca.cc) · [Live demo](https://d.smartdoca.cc) · [Plugin marketplace](https://store.smartdoca.cc) @@ -35,6 +35,6 @@ Doca is a document and knowledge workspace for individuals and small teams. Thes ## Reference and project records -[HTTP API](api.md) · [Database](database.md) · [Plugin SDK contract](plugin-sdk-contract.md) · [Plugin storage contract](plugin-horizontal-scaling.md) · [Collaboration contract](collaboration-sdk-contract.md) · [File exchange](editor-file-exchange-contract.md) · [Release notes](releases/0.3.1.md) · [Documentation maintenance](documentation.md) · [Research and acceptance records](research.md) +[HTTP API](api.md) · [Database](database.md) · [Plugin SDK contract](plugin-sdk-contract.md) · [Plugin storage contract](plugin-horizontal-scaling.md) · [Collaboration contract](collaboration-sdk-contract.md) · [File exchange](editor-file-exchange-contract.md) · [Release notes](releases/0.3.2.md) · [Documentation maintenance](documentation.md) · [Research and acceptance records](research.md) The running application provides `/api/openapi.json`. Proposed capabilities are labeled in the relevant contract; a design record does not establish that an API is exported. Research records retain their original language and date. diff --git a/docs/README.ru.md b/docs/README.ru.md index a661a6b5..1fb80d56 100644 --- a/docs/README.ru.md +++ b/docs/README.ru.md @@ -4,7 +4,7 @@ [English](README.md) · [简体中文](README.zh-CN.md) · [繁體中文](README.zh-Hant.md) · [日本語](README.ja.md) · [Français](README.fr.md) · [한국어](README.ko.md) · [Español](README.es.md) · [Русский](README.ru.md) -Doca — рабочее пространство для документов и базы знаний, рассчитанное на частных пользователей и небольшие команды. В этих руководствах описано, как установить, использовать, администрировать и расширять Doca. Перед установкой или обновлением прочтите [Примечания к выпуску 0.3.1](releases/0.3.1.ru.md). +Doca — рабочее пространство для документов и базы знаний, рассчитанное на частных пользователей и небольшие команды. В этих руководствах описано, как установить, использовать, администрировать и расширять Doca. Перед установкой или обновлением прочтите [Примечания к выпуску 0.3.2](releases/0.3.2.ru.md). [Официальный сайт](https://i.smartdoca.cc) · [Онлайн-демо](https://d.smartdoca.cc) · [Каталог плагинов](https://store.smartdoca.cc) @@ -70,7 +70,7 @@ Doca — рабочее пространство для документов и - [Контракт хранения данных плагинов](plugin-horizontal-scaling.ru.md) - [Контракт совместного редактирования](collaboration-sdk-contract.ru.md) - [Обмен файлами](editor-file-exchange-contract.ru.md) -- [Примечания к выпуску](releases/0.3.1.ru.md) +- [Примечания к выпуску](releases/0.3.2.ru.md) - [Сопровождение документации](documentation.ru.md) - [Материалы исследований и проверок](research.ru.md) diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md index fb5afec6..f1537a98 100644 --- a/docs/README.zh-CN.md +++ b/docs/README.zh-CN.md @@ -2,7 +2,7 @@ [English](README.md) · **简体中文** · [繁體中文](README.zh-Hant.md) · [日本語](README.ja.md) · [Français](README.fr.md) · [한국어](README.ko.md) · [Español](README.es.md) · [Русский](README.ru.md) -Doca 是面向个人和小团队的文档与知识工作台。本套文档随当前源码维护;安装与升级请对照 [0.3.1 发行说明](releases/0.3.1.zh-CN.md),组件契约另行注明实现限制。 +Doca 是面向个人和小团队的文档与知识工作台。本套文档随当前源码维护;安装与升级请对照 [0.3.2 发行说明](releases/0.3.2.zh-CN.md),组件契约另行注明实现限制。 [官网](https://i.smartdoca.cc) · [Demo 体验](https://d.smartdoca.cc) · [插件商城](https://store.smartdoca.cc) @@ -35,6 +35,6 @@ Doca 是面向个人和小团队的文档与知识工作台。本套文档随当 ## 技术参考与项目记录 -[HTTP API](api.zh-CN.md) · [数据库](database.zh-CN.md) · [插件 SDK 契约](plugin-sdk-contract.zh-CN.md) · [插件存储契约](plugin-horizontal-scaling.zh-CN.md) · [协同契约](collaboration-sdk-contract.zh-CN.md) · [文件交换](editor-file-exchange-contract.zh-CN.md) · [发行说明](releases/0.3.1.zh-CN.md) · [文档维护](documentation.zh-CN.md) · [研发与验收资料](research.zh-CN.md) +[HTTP API](api.zh-CN.md) · [数据库](database.zh-CN.md) · [插件 SDK 契约](plugin-sdk-contract.zh-CN.md) · [插件存储契约](plugin-horizontal-scaling.zh-CN.md) · [协同契约](collaboration-sdk-contract.zh-CN.md) · [文件交换](editor-file-exchange-contract.zh-CN.md) · [发行说明](releases/0.3.2.zh-CN.md) · [文档维护](documentation.zh-CN.md) · [研发与验收资料](research.zh-CN.md) 运行中的应用提供 `/api/openapi.json`。相关契约会标明拟议能力;设计记录不代表接口已经导出。研发资料保留原始语言和日期。 diff --git a/docs/README.zh-Hant.md b/docs/README.zh-Hant.md index 7c25ecca..e5899d97 100644 --- a/docs/README.zh-Hant.md +++ b/docs/README.zh-Hant.md @@ -4,7 +4,7 @@ [English](README.md) · [简体中文](README.zh-CN.md) · [繁體中文](README.zh-Hant.md) · [日本語](README.ja.md) · [Français](README.fr.md) · [한국어](README.ko.md) · [Español](README.es.md) · [Русский](README.ru.md) -Doca 是為個人和小型團隊設計的文件與知識工作區。這份文件涵蓋安裝、使用、部署與擴充。安裝或升級前,請先閱讀[版本說明 0.3.1](releases/0.3.1.zh-Hant.md)。 +Doca 是為個人和小型團隊設計的文件與知識工作區。這份文件涵蓋安裝、使用、部署與擴充。安裝或升級前,請先閱讀[版本說明 0.3.2](releases/0.3.2.zh-Hant.md)。 [網站](https://i.smartdoca.cc) · [線上展示](https://d.smartdoca.cc) · [外掛市集](https://store.smartdoca.cc) @@ -70,7 +70,7 @@ Doca 是為個人和小型團隊設計的文件與知識工作區。這份文件 - [外掛儲存規範](plugin-horizontal-scaling.zh-Hant.md) - [協作規範](collaboration-sdk-contract.zh-Hant.md) - [檔案交換](editor-file-exchange-contract.zh-Hant.md) -- [版本說明](releases/0.3.1.zh-Hant.md) +- [版本說明](releases/0.3.2.zh-Hant.md) - [文件維護](documentation.zh-Hant.md) - [研究與驗收記錄](research.zh-Hant.md) diff --git a/docs/api.md b/docs/api.md index f951dd4f..530f6d00 100644 --- a/docs/api.md +++ b/docs/api.md @@ -8,6 +8,8 @@ This is an index of principal host 0.2.23 routes. The running `/api/openapi.json Table paths have the `/api/v1` prefix. Browsers use HttpOnly session cookies; writes require the configured Host and same-origin Origin. Native clients use host-authenticated Bearer sessions; plugin WebViews use scoped plugin sessions. Public resources expose only their authorized read paths. +Android 0.1.1 sends `x-doca-client: mobile` and `x-doca-client-platform: android` to `POST /auth/login`. Doca 0.3.2 returns the native `sessionToken` without setting a browser cookie. The token has no automatic expiry. Existing timed sessions and server-side revocation continue under the original rules. + Metadata `version`, configuration `revision`, and content `seq`/`epochId` have different roles. Read current values before writing. A 409 indicates a conflict or unsupported protocol/state, never permission to overwrite. Pagination varies by route; follow `nextCursor` or `nextOffset`. Missing content access generally returns 404; system administration grants no private-content access. ## Accounts and administration @@ -24,6 +26,8 @@ Metadata `version`, configuration `revision`, and content `seq`/`epochId` have d | `GET /admin/registration-reviews` | Administrator review list | | `POST /admin/registration-reviews/:id` | `{decision:approved\|rejected,message?}`, dedicated review | | `GET /admin/stats` | Aggregate statistics without content permission | +| `GET /admin/release-check` | Read locally stored server version check status. System administrators only | +| `PUT /admin/release-check` | Set `{enabled: boolean}` for the deployment and return its status. System administrators only | | `GET /admin/users/:id/resource-handover` | Disabled-account resource inventory; administrator only | | `POST /admin/users/:id/resource-handover/preview`, `POST /admin/users/:id/resource-handover/execute` | Preview / confirm selected ownership and grants; see [resource handover](admin-resource-handover.md) | diff --git a/docs/api.zh-CN.md b/docs/api.zh-CN.md index c582d735..17dbb95f 100644 --- a/docs/api.zh-CN.md +++ b/docs/api.zh-CN.md @@ -8,6 +8,8 @@ 下表路径以 `/api/v1` 为前缀。浏览器使用 HttpOnly 会话 Cookie;写请求要求配置的 Host 和同源 Origin。原生客户端使用宿主认证 Bearer 会话,插件 WebView 使用受限的插件会话。公开资源只开放其实际允许的读入口。 +Android 0.1.1 在 `POST /auth/login` 上发送 `x-doca-client: mobile` 和 `x-doca-client-platform: android`。Doca 0.3.2 返回不会自动到期的原生 `sessionToken`,不设置浏览器 Cookie。旧会话继续按原有效期使用,服务端仍可撤销令牌。 + 元数据 `version`、配置 `revision`、正文 `seq`/`epochId` 各有职责;读取最新值后提交。409 表示冲突或协议/状态不支持,不自动强制覆盖。分页参数因接口而异,按 `nextCursor` 或 `nextOffset` 继续。无内容阅读权通常返回 404,系统管理权不会授予私有正文访问。 ## 账号与管理 @@ -24,6 +26,8 @@ | `GET /admin/registration-reviews` | 管理员审批列表 | | `POST /admin/registration-reviews/:id` | `{decision:approved\|rejected,message?}`,独立审批 | | `GET /admin/stats` | 聚合统计,不授予内容权限 | +| `GET /admin/release-check` | 读取本地版本检查状态,仅限系统管理员 | +| `PUT /admin/release-check` | 用 `{enabled: boolean}` 修改部署级开关并返回状态,仅限系统管理员 | | `GET /admin/users/:id/resource-handover` | 停用账号的资源清单,仅管理员可用 | | `POST /admin/users/:id/resource-handover/preview`、`POST /admin/users/:id/resource-handover/execute` | 预览/确认所选所有权和授权变更,见[资源交接](admin-resource-handover.zh-CN.md) | diff --git a/docs/configuration.es.md b/docs/configuration.es.md index cf162d49..2e20c4fa 100644 --- a/docs/configuration.es.md +++ b/docs/configuration.es.md @@ -100,6 +100,8 @@ DOCA_SESSION_TTL_SECONDS=86400 DOCA_MOBILE_SESSION_TTL_SECONDS=15552000 ``` +Los nuevos inicios de sesión de Android 0.1.1 en Doca 0.3.2 no caducan automáticamente. Las sesiones existentes y otros inicios móviles conservan el plazo configurado. + Reiniciar para aplicar los cambios de despliegue. Las sesiones de navegador ya emitidas conservan su fecha de expiración almacenada; los nuevos inicios de sesión utilizan el nuevo período de vida, y las renovaciones móviles aplican el período de vida móvil configurado. No se convierten filas de sesión ni formatos persistentes. Los cookies de sesión y de flujo de autenticación se usan `Secure` En HTTPS, mientras que HTTP sigue `HttpOnly` y la política actual de SameSite. Los sitios HTTP utilizan `ws` Para conexiones en tiempo real. El adaptador de navegador HTTP aprobado proporciona UUID v4. `crypto.getRandomValues` cuando `crypto.randomUUID` Está ausente, y solo proporciona SHA-256 `crypto.subtle.digest` a través de los anclados `@noble/hashes` cuando `crypto.subtle` está ausente. Las implementaciones nativas permanecen en uso cuando están presentes. El digest coincide con los bytes nativos; los IDs existentes, los sumas de cálculo de hoja de cálculo y los formatos de documento no se convierten. Esto no permite otras operaciones de WebCrypto. diff --git a/docs/configuration.fr.md b/docs/configuration.fr.md index 8d14353d..f65c08e5 100644 --- a/docs/configuration.fr.md +++ b/docs/configuration.fr.md @@ -100,6 +100,8 @@ DOCA_SESSION_TTL_SECONDS=86400 DOCA_MOBILE_SESSION_TTL_SECONDS=15552000 ``` +Une nouvelle connexion Android 0.1.1 à Doca 0.3.2 n’expire pas automatiquement. Les sessions existantes et les autres connexions mobiles restent soumises à la durée configurée. + Redémarrer pour appliquer les modifications de déploiement. Les sessions navigateur déjà créées conservent leur durée de validité stockée ; les nouveaux accès utilisent la nouvelle durée de vie, et les renouvellements mobiles utilisent la durée de vie mobile configurée. Aucune ligne de session ou format persistant n’est converti. Les cookies de session et de flux d’authentification sont utilisés. `Secure` Sur HTTPS, tandis que HTTP continue `HttpOnly` et la politique SameSite existante. Les sites HTTP utilisent `ws` pour les connexions en temps réel. L’adaptateur de navigateur HTTP approuvé fournit un UUID v4. `crypto.getRandomValues` quand `crypto.randomUUID` Manque, et fournit uniquement SHA-256 `crypto.subtle.digest` à travers les ancrages `@noble/hashes` quand `crypto.subtle` manque. Les implémentations natives restent en usage lorsqu’elles sont présentes. Le digest correspond aux bytes natifs ; les IDs existants, les sommes de contrôle de feuille de calcul et les formats de document ne sont pas convertis. Cela ne permet pas d’utiliser d’autres opérations WebCrypto. diff --git a/docs/configuration.ja.md b/docs/configuration.ja.md index fe202f0c..63ffe241 100644 --- a/docs/configuration.ja.md +++ b/docs/configuration.ja.md @@ -100,6 +100,8 @@ DOCA_SESSION_TTL_SECONDS=86400 DOCA_MOBILE_SESSION_TTL_SECONDS=15552000 ``` +Android 0.1.1 で Doca 0.3.2 に新たにログインすると自動で期限切れになりません。既存のセッションを含む他のモバイルセッションには引き続き有効期限が適用されます。 + デプロイの変更を適用するために再起動する。既に発行されたブラウザセッションは保存された有効期限が保持される。新規ログインは新しい有効期間を使用し、モバイルの更新は設定されたモバイル有効期間を使用する。セッション行や保存されたフォーマットは変換されない。セッションおよび認証フロークッキーは使用される。 `Secure` HTTPSでは、HTTPとは異なります `HttpOnly` そして既存のSameSiteポリシー。HTTPサイトは使用する `ws` リアルタイム接続のために。 承認されたHTTPブラウザアダプターはUUID v4を提供する `crypto.getRandomValues` 時々 `crypto.randomUUID` 欠落しており、SHA-256のみを提供している `crypto.subtle.digest` ピン固定されたまま `@noble/hashes` 時々 `crypto.subtle` 欠落している。ネイティブ実装は存在する限り使用される。ダイジェストはネイティブバイトと一致する。既存のID、スプレッドシートのチェックサム、文書形式は変換されない。これにより他のWebCrypto操作は実行されない。 diff --git a/docs/configuration.ko.md b/docs/configuration.ko.md index 35a376b3..a37bf530 100644 --- a/docs/configuration.ko.md +++ b/docs/configuration.ko.md @@ -100,6 +100,8 @@ DOCA_SESSION_TTL_SECONDS=86400 DOCA_MOBILE_SESSION_TTL_SECONDS=15552000 ``` +Android 0.1.1에서 Doca 0.3.2에 새로 로그인하면 세션이 자동 만료되지 않습니다. 기존 세션과 다른 모바일 로그인에는 설정된 만료 시간이 적용됩니다. + 배포 변경 사항을 적용하려면 다시 시작하세요. 이미 발행된 브라우저 세션은 저장된 만료일을 그대로 유지하며, 새로운 로그인은 새로운 기간을 사용하고, 모바일 재활성화는 설정된 모바일 기간을 사용합니다. 세션 행이나 저장된 형식은 변환되지 않습니다. 세션 및 인증-플로우 쿠키는 사용됩니다. `Secure` HTTPS에서는, HTTP는 그대로 유지됩니다. `HttpOnly` 그리고 기존의 SameSite 정책도. HTTP 사이트는 사용합니다. `ws` 실시간 연결을 위해. 승인된 HTTP 브라우저 어댑터는 UUID v4를 제공합니다. `crypto.getRandomValues` 때에 `crypto.randomUUID` 누락되어 있으며, SHA-256만 제공됩니다. `crypto.subtle.digest` 핀된 것을 통과하여 `@noble/hashes` 때에 `crypto.subtle` 누락되어 있습니다. 네이티브 구현은 존재할 경우 계속 사용됩니다. 디그래스는 네이티브 바이트와 일치하며, 기존 ID, 스프레드시트 체크섬 및 문서 형식은 변환되지 않습니다. 이는 다른 WebCrypto 작업을 지원하지 않습니다. diff --git a/docs/configuration.md b/docs/configuration.md index e05aae65..ae8bb27e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -86,6 +86,8 @@ DOCA_SESSION_TTL_SECONDS=86400 DOCA_MOBILE_SESSION_TTL_SECONDS=15552000 ``` +New Android 0.1.1 password sign-ins to Doca 0.3.2 use a native session with no automatic expiry. The configured mobile time limit still applies to previously issued sessions and other mobile sign-ins. Sign out while connected, so the server can revoke the credential. + Restart to apply deployment changes. Already issued browser sessions retain their stored expiry; new logins use the new lifetime, and mobile renewals use the configured mobile lifetime. No session rows or persisted formats are converted. Session and authentication-flow cookies use `Secure` on HTTPS, while HTTP keeps `HttpOnly` and the existing SameSite policy. HTTP sites use `ws` for realtime connections. The approved HTTP browser adapter supplies UUID v4 through `crypto.getRandomValues` when `crypto.randomUUID` is missing, and supplies only SHA-256 `crypto.subtle.digest` through pinned `@noble/hashes` when `crypto.subtle` is missing. Native implementations stay in use when present. The digest matches native bytes; existing IDs, spreadsheet checksums and document formats are not converted. This does not provide other WebCrypto operations. diff --git a/docs/configuration.ru.md b/docs/configuration.ru.md index 873ff1f7..8f68a9e5 100644 --- a/docs/configuration.ru.md +++ b/docs/configuration.ru.md @@ -100,6 +100,8 @@ DOCA_SESSION_TTL_SECONDS=86400 DOCA_MOBILE_SESSION_TTL_SECONDS=15552000 ``` +Новые сеансы Android 0.1.1 на Doca 0.3.2 не истекают автоматически. Для ранее выданных и других мобильных сеансов продолжает действовать настроенный срок. + Перезапустите для применения изменений в развертывании. Уже выданные сессии браузера сохраняют своё хранимое истечение срока; новые входы используют новый срок действия, а обновления для мобильных устройств — конфигурированный срок действия для мобильных устройств. Ни строки сессий, ни хранящиеся форматы не конвертируются. Куки сессий и flow аутентификации не изменяются. `Secure` В HTTPS, в то время как HTTP остается `HttpOnly` и существующая политика SameSite. Сайты HTTP используют `ws` для реального времени соединений. Утвержденный адаптер браузера для HTTP предоставляет UUID v4. `crypto.getRandomValues` когда `crypto.randomUUID` Отсутствует, и предоставляется только SHA-256 `crypto.subtle.digest` через закрепленное `@noble/hashes` когда `crypto.subtle` Отсутствует. Нативные реализации остаются в использовании, когда они есть. Дigest соответствует нативным байтам; существующие идентификаторы, суммы электронных таблиц и форматы документов не конвертируются. Это не предоставляет возможности для других операций WebCrypto. diff --git a/docs/configuration.zh-CN.md b/docs/configuration.zh-CN.md index f934ab0d..d038727f 100644 --- a/docs/configuration.zh-CN.md +++ b/docs/configuration.zh-CN.md @@ -84,6 +84,8 @@ DOCA_SESSION_TTL_SECONDS=86400 DOCA_MOBILE_SESSION_TTL_SECONDS=15552000 ``` +Android 0.1.1 在 Doca 0.3.2 上新登录时,原生会话不会自动到期。现有会话及其他移动登录仍使用原有效期。主动退出需要连通服务端,以撤销令牌。 + 修改后重启服务。已签发的浏览器会话保留数据库中原有到期时间,新登录使用新期限,手机续期使用配置的手机期限;不转换会话记录或持久格式。登录和认证流程 Cookie 在 HTTPS 下加 `Secure`,HTTP 下保留 `HttpOnly` 和原有 SameSite 规则。HTTP 站点实时连接使用 `ws`。 经明确同意的 HTTP 浏览器适配在 `crypto.randomUUID` 缺失时通过 `crypto.getRandomValues` 提供 UUID v4;在 `crypto.subtle` 缺失时通过固定版本的 `@noble/hashes` 仅提供 SHA-256 `digest`。存在原生实现时继续使用原生接口;摘要与原生字节一致,不转换已有 ID、表格校验值或文档格式,也不提供其他 WebCrypto 加密操作。 diff --git a/docs/configuration.zh-Hant.md b/docs/configuration.zh-Hant.md index 0c8a0bba..40d752e7 100644 --- a/docs/configuration.zh-Hant.md +++ b/docs/configuration.zh-Hant.md @@ -98,6 +98,8 @@ DOCA_SESSION_TTL_SECONDS=86400 DOCA_MOBILE_SESSION_TTL_SECONDS=15552000 ``` +Android 0.1.1 在 Doca 0.3.2 上重新登入後,新工作階段不會自動到期。既有工作階段及其他手機登入依原期限運作。 + 修改後重啟服務。已簽發的瀏覽器會話保留資料庫中原有到期時間,新登入使用新期限,手機續期使用配置的手機期限;不轉換會話記錄或持久格式。登入和認證流程 Cookie 在 HTTPS 下加 `Secure`,HTTP 下保留 `HttpOnly` 和原有 SameSite 規則。HTTP 站點實時連線使用 `ws`。 經明確同意的 HTTP 瀏覽器適配在 `crypto.randomUUID` 缺失時透過 `crypto.getRandomValues` 提供 UUID v4;在 `crypto.subtle` 缺失時透過固定版本的 `@noble/hashes` 僅提供 SHA-256 `digest`。存在原生實現時繼續使用原生介面;摘要與原生位元組一致,不轉換已有 ID、表格校驗值或文件格式,也不提供其他 WebCrypto 加密操作。 diff --git a/docs/deployment-without-github.es.md b/docs/deployment-without-github.es.md index 33113c77..5a9224e4 100644 --- a/docs/deployment-without-github.es.md +++ b/docs/deployment-without-github.es.md @@ -4,13 +4,13 @@ [简体中文](deployment-without-github.zh-CN.md) -El servidor empresarial no necesita un checkout de fuente, Git, Node.js o pnpm. Instale Docker Engine, el complemento Docker Compose, Bash y OpenSSL de antemano, luego transfiera los archivos de despliegue, prepare la imagen, inicie Doca e inicialice al administrador. Esta guía instala Doca 0.3.1 en un servidor único nuevo con SQLite y almacenamiento de archivos local. Las instalaciones existentes deben revisar… [requisitos de liberación](releases/0.3.1.es.md) y preservar sus bases de datos, archivos, configuración y clave maestra de credenciales. +El servidor empresarial no necesita un checkout de fuente, Git, Node.js o pnpm. Instale Docker Engine, el complemento Docker Compose, Bash y OpenSSL de antemano, luego transfiera los archivos de despliegue, prepare la imagen, inicie Doca e inicialice al administrador. Esta guía instala Doca 0.3.2 en un servidor único nuevo con SQLite y almacenamiento de archivos local. Las instalaciones existentes deben revisar… [requisitos de liberación](releases/0.3.2.es.md) y preservar sus bases de datos, archivos, configuración y clave maestra de credenciales. ## Instalación nueva desde un YAML -`node scripts/pack-deployment.mjs` también genera resultados `doca-compose-vVERSION.yaml` y su checksum. Transfiera el YAML, guárdelo como `compose.yaml` En un directorio de despliegue permanente, edita `DOCA_ORIGIN` y tu generación `DOCA_CREDENTIAL_MASTER_KEY`, protegerlo con `chmod 600 compose.yaml`, entonces ejecuta `docker compose up -d`. No `.env`Se necesita un archivo JSON o un script de administrador externo. Utilice la imagen 0.3.1 correspondiente; el YAML independiente y el checksum también se encuentran en el repositorio GitHub. +`node scripts/pack-deployment.mjs` también genera resultados `doca-compose-vVERSION.yaml` y su checksum. Transfiera el YAML, guárdelo como `compose.yaml` En un directorio de despliegue permanente, edita `DOCA_ORIGIN` y tu generación `DOCA_CREDENTIAL_MASTER_KEY`, protegerlo con `chmod 600 compose.yaml`, entonces ejecuta `docker compose up -d`. No `.env`Se necesita un archivo JSON o un script de administrador externo. Utilice la imagen 0.3.2 correspondiente; el YAML independiente y el checksum también se encuentran en el repositorio GitHub. Después de que el servicio esté sano, ejecuta. `docker compose exec doca bash docker/admin.sh bootstrap`; usar `reset-password` Para el restablecimiento de contraseña. La entrada de contraseña está oculta y no se incluye en el YAML. Este ejemplo es solo para instalaciones nuevas de SQLite/local-storage. Los sitios existentes conservan su nombre de proyecto, volúmenes y clave. Los respaldos incluyen el YAML protegido. Los requisitos del reverse-proxy siguen siendo los descritos a continuación. @@ -27,22 +27,22 @@ cd doca node scripts/pack-deployment.mjs ``` -Los nombres de los archivos y las etiquetas de imagen a continuación utilizan 0.3.1 como ejemplo. Utilice los nombres de archivo impresos por el paquete y la imagen especificada en el archivo Compose generado. +Los nombres de los archivos y las etiquetas de imagen a continuación utilizan 0.3.2 como ejemplo. Utilice los nombres de archivo impresos por el paquete y la imagen especificada en el archivo Compose generado. -Transferencia `doca-deploy-v0.3.1.tar.gz` y su `.sha256` Verificación de checksum a través de un servicio de archivos empresarial, una URL de descarga interna o almacenamiento extraíble. El empaquetador solo lee archivos de despliegue públicos y no incluye ningún contenido local. `.env`Datos de usuario o imagen de contenedor. La publicación de GitHub para la etiqueta correspondiente incluye el paquete y el checksum. +Transferencia `doca-deploy-v0.3.2.tar.gz` y su `.sha256` Verificación de checksum a través de un servicio de archivos empresarial, una URL de descarga interna o almacenamiento extraíble. El empaquetador solo lee archivos de despliegue públicos y no incluye ningún contenido local. `.env`Datos de usuario o imagen de contenedor. La publicación de GitHub para la etiqueta correspondiente incluye el paquete y el checksum. Coloque ambos archivos en el mismo directorio del servidor empresarial, verifíquelos y extraiga los datos: ```sh -sha256sum -c doca-deploy-v0.3.1.tar.gz.sha256 -tar -xzf doca-deploy-v0.3.1.tar.gz -cd doca-deploy-v0.3.1 +sha256sum -c doca-deploy-v0.3.2.tar.gz.sha256 +tar -xzf doca-deploy-v0.3.2.tar.gz +cd doca-deploy-v0.3.2 ``` -En macOS, utiliza `shasum -a 256 -c doca-deploy-v0.3.1.tar.gz.sha256`. Ejecute los comandos de despliegue siguientes desde este directorio: +En macOS, utiliza `shasum -a 256 -c doca-deploy-v0.3.2.tar.gz.sha256`. Ejecute los comandos de despliegue siguientes desde este directorio: ```text -doca-deploy-v0.3.1/ +doca-deploy-v0.3.2/ compose.yaml docker.env.example README.zh-CN.md @@ -64,7 +64,7 @@ Para una transferencia de texto, guarde esta configuración de un solo servidor. ```yaml services: doca: - image: docker.io/smartdoca/doca:0.3.1 + image: docker.io/smartdoca/doca:0.3.2 pull_policy: missing restart: unless-stopped init: true @@ -155,21 +155,21 @@ docker compose pull doca El proveedor prepara un archivo de imágenes en una máquina con acceso al registro. Primero, confirme la arquitectura de la CPU objetivo. Este ejemplo utiliza Linux x86-64.`linux/amd64`); para ARM64, utilice `linux/arm64` Y etiqueta los archivos entregados correspondientemente: ```sh -docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.1 -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' -docker save -o doca-image-v0.3.1-linux-amd64.tar docker.io/smartdoca/doca:0.3.1 -sha256sum doca-image-v0.3.1-linux-amd64.tar > doca-image-v0.3.1-linux-amd64.tar.sha256 +docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.2 +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' +docker save -o doca-image-v0.3.2-linux-amd64.tar docker.io/smartdoca/doca:0.3.2 +sha256sum doca-image-v0.3.2-linux-amd64.tar > doca-image-v0.3.2-linux-amd64.tar.sha256 ``` Transfiera la imagen `.tar` y el checksum juntos. De su directorio en el servidor empresarial: ```sh -sha256sum -c doca-image-v0.3.1-linux-amd64.tar.sha256 -docker load -i doca-image-v0.3.1-linux-amd64.tar -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' +sha256sum -c doca-image-v0.3.2-linux-amd64.tar.sha256 +docker load -i doca-image-v0.3.2-linux-amd64.tar +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' ``` -Confirme que la etiqueta cargada está `smartdoca/doca:0.3.1` Y si la arquitectura coincide con el objetivo, luego regresar al directorio de despliegue. Un registro interno es otra opción de entrega: el proveedor empuja la misma imagen de lanzamiento y el equipo de negocios modifica Compose. `image` A la dirección de registro interno antes de extraerlo. Mantenga el paquete, la imagen y los scripts de inicialización en la misma versión. +Confirme que la etiqueta cargada está `smartdoca/doca:0.3.2` Y si la arquitectura coincide con el objetivo, luego regresar al directorio de despliegue. Un registro interno es otra opción de entrega: el proveedor empuja la misma imagen de lanzamiento y el equipo de negocios modifica Compose. `image` A la dirección de registro interno antes de extraerlo. Mantenga el paquete, la imagen y los scripts de inicialización en la misma versión. @@ -192,7 +192,7 @@ Espera para `docker compose ps` para mostrar `healthy`Una comprobación manual d curl -fsS -H 'Host: docs.example.com' http://127.0.0.1:39120/health ``` -Esperar `{"status":"ok","version":"0.3.1"}`Para el ejemplo interno, utilice `Host: doca.internal`Las solicitudes de bucle de retorno en blanco fallan en la validación del host. Inspeccionar los fallos de inicio. `docker compose logs --tail=100 doca`. +Esperar `{"status":"ok","version":"0.3.2"}`Para el ejemplo interno, utilice `Host: doca.internal`Las solicitudes de bucle de retorno en blanco fallan en la validación del host. Inspeccionar los fallos de inicio. `docker compose logs --tail=100 doca`. @@ -221,4 +221,4 @@ Esto no crea una cuenta. Si la base de datos está bloqueada, ejecuta `docker co Usa `docker compose restart` Para reinicios ordinarios. Mantenga el directorio de despliegue y el nombre del proyecto Compose para que sea el mismo `doca_data` Se utiliza el volumen; cambiar cualquiera de ellos puede accidentalmente iniciar un sitio vacío separado. Realice una copia de seguridad de todas las bases de datos y el almacenamiento de archivos en el volumen persistente, además del contenido protegido. `.env` y clave maestra. `docker compose down -v` Se elimina el volumen y no debe utilizarse para un reinicio o actualización ordinario. -Revisar [requisitos de liberación](releases/0.3.1.es.md) Antes de actualizar, entregue un paquete e imagen correspondiente. Esta guía inicializa sitios nuevos y no convierte datos existentes. El inicio de sesión con contraseña y los servicios de documentos locales no requieren acceso a GitHub; los servicios externos configurados para IA, inicio de sesión externo, instalación de complementos o almacenamiento en la nube deben seguir siendo accesibles. Verifique la renderización de documentos en el host de destino por separado: solo la salud de la aplicación no garantiza la corrección de la renderización de PDF, Canvas y Office. Véase [Renderizado de documentos de Docker](docker-rendering.es.md). +Revisar [requisitos de liberación](releases/0.3.2.es.md) Antes de actualizar, entregue un paquete e imagen correspondiente. Esta guía inicializa sitios nuevos y no convierte datos existentes. El inicio de sesión con contraseña y los servicios de documentos locales no requieren acceso a GitHub; los servicios externos configurados para IA, inicio de sesión externo, instalación de complementos o almacenamiento en la nube deben seguir siendo accesibles. Verifique la renderización de documentos en el host de destino por separado: solo la salud de la aplicación no garantiza la corrección de la renderización de PDF, Canvas y Office. Véase [Renderizado de documentos de Docker](docker-rendering.es.md). diff --git a/docs/deployment-without-github.fr.md b/docs/deployment-without-github.fr.md index a1c3352c..d463acb4 100644 --- a/docs/deployment-without-github.fr.md +++ b/docs/deployment-without-github.fr.md @@ -4,13 +4,13 @@ [简体中文](deployment-without-github.zh-CN.md) -Le serveur d’entreprise n’a pas besoin de checkout source, de Git, de Node.js ou de pnpm. Installez d’abord Docker Engine, le plugin Docker Compose, Bash et OpenSSL, puis transférez les fichiers de déploiement, préparez l’image, lancez Doca et initialisez l’administrateur. Ce guide installe Doca 0.3.1 sur un serveur unique neuf avec SQLite et stockage de fichiers local. Les installations existantes doivent consulter… [exigences de libération](releases/0.3.1.fr.md) et préserver leurs bases de données, fichiers, configuration et clé maîtresse des identifiants. +Le serveur d’entreprise n’a pas besoin de checkout source, de Git, de Node.js ou de pnpm. Installez d’abord Docker Engine, le plugin Docker Compose, Bash et OpenSSL, puis transférez les fichiers de déploiement, préparez l’image, lancez Doca et initialisez l’administrateur. Ce guide installe Doca 0.3.2 sur un serveur unique neuf avec SQLite et stockage de fichiers local. Les installations existantes doivent consulter… [exigences de libération](releases/0.3.2.fr.md) et préserver leurs bases de données, fichiers, configuration et clé maîtresse des identifiants. ## Installation récente à partir d’un YAML -`node scripts/pack-deployment.mjs` également en sortie `doca-compose-vVERSION.yaml` et son checksum. Transférez le YAML, enregistrez-le sous `compose.yaml` Dans un répertoire de déploiement permanent, éditer `DOCA_ORIGIN` et votre génération `DOCA_CREDENTIAL_MASTER_KEY`, le protéger avec `chmod 600 compose.yaml`, puis exécuter `docker compose up -d`. Non `.env`Un fichier JSON ou un script d’administrateur externe est nécessaire. Utilisez l’image 0.3.1 correspondante ; les fichiers YAML autonomes et les checksums sont également attachés à la version de GitHub. +`node scripts/pack-deployment.mjs` également en sortie `doca-compose-vVERSION.yaml` et son checksum. Transférez le YAML, enregistrez-le sous `compose.yaml` Dans un répertoire de déploiement permanent, éditer `DOCA_ORIGIN` et votre génération `DOCA_CREDENTIAL_MASTER_KEY`, le protéger avec `chmod 600 compose.yaml`, puis exécuter `docker compose up -d`. Non `.env`Un fichier JSON ou un script d’administrateur externe est nécessaire. Utilisez l’image 0.3.2 correspondante ; les fichiers YAML autonomes et les checksums sont également attachés à la version de GitHub. Après que la situation est saine, courir `docker compose exec doca bash docker/admin.sh bootstrap`; utiliser `reset-password` Pour réinitialiser le mot de passe. La saisie du mot de passe est cachée et ne figure pas dans le YAML. Cet exemple est uniquement destiné aux installations récentes de SQLite/local-storage. Les sites existants conservent leur nom de projet, leurs volumes et leurs clés. Les sauvegardes incluent le YAML protégé. Les exigences de reverse-proxy restent telles que définies ci-dessous. @@ -27,22 +27,22 @@ cd doca node scripts/pack-deployment.mjs ``` -Les noms des archives et les étiquettes d’image ci-dessous utilisent 0.3.1 comme exemple. Utilisez les noms de fichiers générés par le packager et l’image spécifiée dans le fichier Compose créé. +Les noms des archives et les étiquettes d’image ci-dessous utilisent 0.3.2 comme exemple. Utilisez les noms de fichiers générés par le packager et l’image spécifiée dans le fichier Compose créé. -Transfert `doca-deploy-v0.3.1.tar.gz` et son `.sha256` Vérification via un service de fichiers d'entreprise, une URL de téléchargement interne ou un stockage amovible. Le packer ne lit que les fichiers de déploiement publics et ne contient aucun fichier local. `.env`données utilisateur, ou image de conteneur. La version de GitHub pour la étiquette correspondante inclut le bundle et le checksum. +Transfert `doca-deploy-v0.3.2.tar.gz` et son `.sha256` Vérification via un service de fichiers d'entreprise, une URL de téléchargement interne ou un stockage amovible. Le packer ne lit que les fichiers de déploiement publics et ne contient aucun fichier local. `.env`données utilisateur, ou image de conteneur. La version de GitHub pour la étiquette correspondante inclut le bundle et le checksum. Placer les deux fichiers dans le même dossier sur le serveur d'entreprise, vérifier et extraire : ```sh -sha256sum -c doca-deploy-v0.3.1.tar.gz.sha256 -tar -xzf doca-deploy-v0.3.1.tar.gz -cd doca-deploy-v0.3.1 +sha256sum -c doca-deploy-v0.3.2.tar.gz.sha256 +tar -xzf doca-deploy-v0.3.2.tar.gz +cd doca-deploy-v0.3.2 ``` -Sur macOS, utilisez `shasum -a 256 -c doca-deploy-v0.3.1.tar.gz.sha256`Exécutez les commandes de déploiement suivantes depuis ce dossier : +Sur macOS, utilisez `shasum -a 256 -c doca-deploy-v0.3.2.tar.gz.sha256`Exécutez les commandes de déploiement suivantes depuis ce dossier : ```text -doca-deploy-v0.3.1/ +doca-deploy-v0.3.2/ compose.yaml docker.env.example README.zh-CN.md @@ -64,7 +64,7 @@ Pour un transfert de texte, enregistrez cette configuration à un seul serveur. ```yaml services: doca: - image: docker.io/smartdoca/doca:0.3.1 + image: docker.io/smartdoca/doca:0.3.2 pull_policy: missing restart: unless-stopped init: true @@ -155,21 +155,21 @@ docker compose pull doca Le fournisseur prépare un archivage d’images sur une machine ayant accès au registre. Vérifiez d’abord l’architecture de la CPU cible. Cet exemple utilise Linux x86-64.`linux/amd64`); pour ARM64, utilisez `linux/arm64` Et étiquetez les fichiers livrés en conséquence : ```sh -docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.1 -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' -docker save -o doca-image-v0.3.1-linux-amd64.tar docker.io/smartdoca/doca:0.3.1 -sha256sum doca-image-v0.3.1-linux-amd64.tar > doca-image-v0.3.1-linux-amd64.tar.sha256 +docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.2 +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' +docker save -o doca-image-v0.3.2-linux-amd64.tar docker.io/smartdoca/doca:0.3.2 +sha256sum doca-image-v0.3.2-linux-amd64.tar > doca-image-v0.3.2-linux-amd64.tar.sha256 ``` Transférer l’image `.tar` et le checksum ensemble. D’après leur répertoire sur le serveur d’entreprise : ```sh -sha256sum -c doca-image-v0.3.1-linux-amd64.tar.sha256 -docker load -i doca-image-v0.3.1-linux-amd64.tar -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' +sha256sum -c doca-image-v0.3.2-linux-amd64.tar.sha256 +docker load -i doca-image-v0.3.2-linux-amd64.tar +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' ``` -Confirmer que l’étiquette chargée est correcte `smartdoca/doca:0.3.1` Et si l’architecture correspond au cible, alors retourner au dossier de déploiement. Un registre interne est une autre option de livraison : le fournisseur met à jour la même image de version, et l’équipe métier modifie Compose. `image` À l’adresse de registre interne avant de tirer. Conservez le bundle, l’image et les scripts d’initialisation sur la même version. +Confirmer que l’étiquette chargée est correcte `smartdoca/doca:0.3.2` Et si l’architecture correspond au cible, alors retourner au dossier de déploiement. Un registre interne est une autre option de livraison : le fournisseur met à jour la même image de version, et l’équipe métier modifie Compose. `image` À l’adresse de registre interne avant de tirer. Conservez le bundle, l’image et les scripts d’initialisation sur la même version. @@ -192,7 +192,7 @@ Attendez. `docker compose ps` pour montrer `healthy`Un contrôle manuel doit uti curl -fsS -H 'Host: docs.example.com' http://127.0.0.1:39120/health ``` -Attendez `{"status":"ok","version":"0.3.1"}`Pour l’exemple interne, utilisez `Host: doca.internal`Les demandes de loopback invalides échouent à la validation du hôte. Examinez les échecs de démarrage. `docker compose logs --tail=100 doca`. +Attendez `{"status":"ok","version":"0.3.2"}`Pour l’exemple interne, utilisez `Host: doca.internal`Les demandes de loopback invalides échouent à la validation du hôte. Examinez les échecs de démarrage. `docker compose logs --tail=100 doca`. @@ -221,4 +221,4 @@ Cela ne crée pas de compte. Si la base de données est verrouillée, exécutez. Utilisez `docker compose restart` pour les redémarrages ordinaires. Conservez le dossier de déploiement et le nom du projet Compose afin que tout soit identique `doca_data` Le volume est utilisé ; changer l’un ou l’autre peut accidentellement déclencher la création d’un site vide distinct. Faire une sauvegarde de toutes les bases de données et des stockages de fichiers dans le volume persistant, ainsi que des données protégées. `.env` et clé maîtresse. `docker compose down -v` Supprime le volume et ne doit pas être utilisé pour une restauration ou une mise à niveau ordinaire. -Réexaminer [exigences de libération](releases/0.3.1.fr.md) Avant l’upgrade, fournissez un bundle et une image correspondants. Ce guide initialise des sites neufs et ne convertit pas les données existantes. Le login par mot de passe et les services de documents locaux n’ont pas besoin d’accès GitHub ; les services externes configurés pour l’IA, le login externe, l’installation d’extension ou le stockage en cloud doivent néanmoins être accessibles. Vérifiez séparément la rédaction des documents sur l’hôte cible : la santé de l’application seule ne garantit pas la qualité de rédaction des PDF, du Canvas et de Office. Voir [Rénder de documents Docker](docker-rendering.fr.md). +Réexaminer [exigences de libération](releases/0.3.2.fr.md) Avant l’upgrade, fournissez un bundle et une image correspondants. Ce guide initialise des sites neufs et ne convertit pas les données existantes. Le login par mot de passe et les services de documents locaux n’ont pas besoin d’accès GitHub ; les services externes configurés pour l’IA, le login externe, l’installation d’extension ou le stockage en cloud doivent néanmoins être accessibles. Vérifiez séparément la rédaction des documents sur l’hôte cible : la santé de l’application seule ne garantit pas la qualité de rédaction des PDF, du Canvas et de Office. Voir [Rénder de documents Docker](docker-rendering.fr.md). diff --git a/docs/deployment-without-github.ja.md b/docs/deployment-without-github.ja.md index cd88dc9d..28f84c07 100644 --- a/docs/deployment-without-github.ja.md +++ b/docs/deployment-without-github.ja.md @@ -4,13 +4,13 @@ [简体中文](deployment-without-github.zh-CN.md) -ビジネスサーバーにはソースチェックアウト、Git、Node.js、またはpnpmは不要です。先にDocker Engine、Docker Composeプラグイン、Bash、OpenSSLをインストールし、デプロイファイルを転送し、イメージを準備し、Docaを起動し、管理者を初期化します。このガイドでは、SQLiteとローカルファイルストレージを使用した新しい単一サーバー上でDoca 0.3.1をインストールします。既存のインストールについては、再度確認が必要です。 [リリース要件](releases/0.3.1.ja.md) そして、彼らのデータベース、ファイル、設定、および認証キーマスターキーを保護する。 +ビジネスサーバーにはソースチェックアウト、Git、Node.js、またはpnpmは不要です。先にDocker Engine、Docker Composeプラグイン、Bash、OpenSSLをインストールし、デプロイファイルを転送し、イメージを準備し、Docaを起動し、管理者を初期化します。このガイドでは、SQLiteとローカルファイルストレージを使用した新しい単一サーバー上でDoca 0.3.2をインストールします。既存のインストールについては、再度確認が必要です。 [リリース要件](releases/0.3.2.ja.md) そして、彼らのデータベース、ファイル、設定、および認証キーマスターキーを保護する。 ## YAMLからの新しいインストール -`node scripts/pack-deployment.mjs` また出力する `doca-compose-vVERSION.yaml` およびそのチェックサム。YAMLを転送し、保存してください。 `compose.yaml` 永続的なデプロイディレクトリ内で編集する `DOCA_ORIGIN` そして、あなたが生成したもの `DOCA_CREDENTIAL_MASTER_KEY`それを保護する `chmod 600 compose.yaml`それから実行する `docker compose up -d`。いいえ `.env`seccomp JSONや外部の管理者スクリプトが必要です。対応する0.3.1のイメージを使用してください。スタンドアロン版のYAMLとチェックサムもGitHub Releaseに添付されています。 +`node scripts/pack-deployment.mjs` また出力する `doca-compose-vVERSION.yaml` およびそのチェックサム。YAMLを転送し、保存してください。 `compose.yaml` 永続的なデプロイディレクトリ内で編集する `DOCA_ORIGIN` そして、あなたが生成したもの `DOCA_CREDENTIAL_MASTER_KEY`それを保護する `chmod 600 compose.yaml`それから実行する `docker compose up -d`。いいえ `.env`seccomp JSONや外部の管理者スクリプトが必要です。対応する0.3.2のイメージを使用してください。スタンドアロン版のYAMLとチェックサムもGitHub Releaseに添付されています。 サービスが正常になった後、実行する `docker compose exec doca bash docker/admin.sh bootstrap`;使用 `reset-password` パスワードリセットのためです。パスワードの入力は隠され、YAMLに記載されません。この例は新しいSQLite/local-storageインストールの場合のみです。既存のサイトは、プロジェクト名、ボリューム、キーが保持されます。バックアップには保護されたYAMLが含まれます。リバースプロキシの要件は、以下で説明されている通りです。 @@ -27,22 +27,22 @@ cd doca node scripts/pack-deployment.mjs ``` -以下のアーカイブ名と画像タグは0.3.1を例として使用しています。パッカーが出力するファイル名と、生成されたComposeファイルで指定される画像を使用してください。 +以下のアーカイブ名と画像タグは0.3.2を例として使用しています。パッカーが出力するファイル名と、生成されたComposeファイルで指定される画像を使用してください。 -移転 `doca-deploy-v0.3.1.tar.gz` そして、それ `.sha256` エンタープライズファイルサービス、内部ダウンロードURL、またはリムーバブルストレージを通じてチェックサムを確認する。パッカーは公開されたデプロイファイルのみを読み取り、ローカルファイルは含まない。 `.env`ユーザーデータやコンテナイメージです。対応するタグのGitHub Releaseには、バンドルとチェックサムが含まれています。 +移転 `doca-deploy-v0.3.2.tar.gz` そして、それ `.sha256` エンタープライズファイルサービス、内部ダウンロードURL、またはリムーバブルストレージを通じてチェックサムを確認する。パッカーは公開されたデプロイファイルのみを読み取り、ローカルファイルは含まない。 `.env`ユーザーデータやコンテナイメージです。対応するタグのGitHub Releaseには、バンドルとチェックサムが含まれています。 ビジネスサーバーの同じディレクトリに両方のファイルを置き、確認し、抽出します。 ```sh -sha256sum -c doca-deploy-v0.3.1.tar.gz.sha256 -tar -xzf doca-deploy-v0.3.1.tar.gz -cd doca-deploy-v0.3.1 +sha256sum -c doca-deploy-v0.3.2.tar.gz.sha256 +tar -xzf doca-deploy-v0.3.2.tar.gz +cd doca-deploy-v0.3.2 ``` -macOSでは、使用する `shasum -a 256 -c doca-deploy-v0.3.1.tar.gz.sha256`このディレクトリから続くデプロイコマンドを実行してください: +macOSでは、使用する `shasum -a 256 -c doca-deploy-v0.3.2.tar.gz.sha256`このディレクトリから続くデプロイコマンドを実行してください: ```text -doca-deploy-v0.3.1/ +doca-deploy-v0.3.2/ compose.yaml docker.env.example README.zh-CN.md @@ -64,7 +64,7 @@ doca-deploy-v0.3.1/ ```yaml services: doca: - image: docker.io/smartdoca/doca:0.3.1 + image: docker.io/smartdoca/doca:0.3.2 pull_policy: missing restart: unless-stopped init: true @@ -155,21 +155,21 @@ docker compose pull doca サプライヤーはレジストリにアクセスできるマシン上で画像アーカイブを作成する。まず、対象のCPUアーキテクチャを確認する。この例ではLinux x86-64を使用している。`linux/amd64`); ARM64の場合は、使用する `linux/arm64` 送信されたファイルに適切にラベルを付けましょう: ```sh -docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.1 -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' -docker save -o doca-image-v0.3.1-linux-amd64.tar docker.io/smartdoca/doca:0.3.1 -sha256sum doca-image-v0.3.1-linux-amd64.tar > doca-image-v0.3.1-linux-amd64.tar.sha256 +docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.2 +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' +docker save -o doca-image-v0.3.2-linux-amd64.tar docker.io/smartdoca/doca:0.3.2 +sha256sum doca-image-v0.3.2-linux-amd64.tar > doca-image-v0.3.2-linux-amd64.tar.sha256 ``` 画像を転送する `.tar` チェックサムと一緒に。ビジネスサーバーのディレクトリから: ```sh -sha256sum -c doca-image-v0.3.1-linux-amd64.tar.sha256 -docker load -i doca-image-v0.3.1-linux-amd64.tar -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' +sha256sum -c doca-image-v0.3.2-linux-amd64.tar.sha256 +docker load -i doca-image-v0.3.2-linux-amd64.tar +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' ``` -ロードされたタグが正しいか確認する `smartdoca/doca:0.3.1` アーキテクチャがターゲットに合致したら、デプロイディレクトリに戻ります。内部レジストリも別の配布方法です。サプライヤーが同じリリースイメージを配布し、ビジネスチームがComposeを変更します。 `image` プルインする前に、その内部レジストリアドレスに保存してください。バンドル、イメージ、初期化スクリプトを同じリリースに保持します。 +ロードされたタグが正しいか確認する `smartdoca/doca:0.3.2` アーキテクチャがターゲットに合致したら、デプロイディレクトリに戻ります。内部レジストリも別の配布方法です。サプライヤーが同じリリースイメージを配布し、ビジネスチームがComposeを変更します。 `image` プルインする前に、その内部レジストリアドレスに保存してください。バンドル、イメージ、初期化スクリプトを同じリリースに保持します。 @@ -192,7 +192,7 @@ docker compose ps curl -fsS -H 'Host: docs.example.com' http://127.0.0.1:39120/health ``` -期待する `{"status":"ok","version":"0.3.1"}`内部の例については、使用してください。 `Host: doca.internal`バレルループバックリクエストはホスト検証に失敗する。起動失敗を調査する `docker compose logs --tail=100 doca`. +期待する `{"status":"ok","version":"0.3.2"}`内部の例については、使用してください。 `Host: doca.internal`バレルループバックリクエストはホスト検証に失敗する。起動失敗を調査する `docker compose logs --tail=100 doca`. @@ -221,4 +221,4 @@ bash scripts/reset-admin-password.sh 使用する `docker compose restart` 通常の再起動のため。デプロイディレクトリとComposeプロジェクト名を保持しておくことで、同じものが使えます `doca_data` ボリュームが使用されているため、どちらを変更しても誤って別の空のサイトが作成される可能性があります。永続ボリューム内のすべてのデータベースやファイルストレージ、および保護されたものをバックアップしてください。 `.env` そしてマスターキー。 `docker compose down -v` ボリュームを削除し、通常の再起動やアップグレードには使用できない。 -レビューをする [リリース要件](releases/0.3.1.ja.md) アップグレードする前に、対応するバンドルと画像を提供してください。このガイドでは新しいサイトを初期化するだけで、既存のデータは変換されません。パスワードログインやローカル文書サービスにはGitHubアクセスは不要ですが、AI、外部ログイン、プラグインのインストール、クラウドストレージ用の外部サービスは依然としてアクセス可能でなければなりません。ターゲットホストでの文書レンダリングを別途確認してください。アプリケーションの健康状態だけではPDF、キャンバス、Officeのレンダリングの正確性は確立されません。詳細は [Dockerドキュメントのレンダリング](docker-rendering.ja.md). +レビューをする [リリース要件](releases/0.3.2.ja.md) アップグレードする前に、対応するバンドルと画像を提供してください。このガイドでは新しいサイトを初期化するだけで、既存のデータは変換されません。パスワードログインやローカル文書サービスにはGitHubアクセスは不要ですが、AI、外部ログイン、プラグインのインストール、クラウドストレージ用の外部サービスは依然としてアクセス可能でなければなりません。ターゲットホストでの文書レンダリングを別途確認してください。アプリケーションの健康状態だけではPDF、キャンバス、Officeのレンダリングの正確性は確立されません。詳細は [Dockerドキュメントのレンダリング](docker-rendering.ja.md). diff --git a/docs/deployment-without-github.ko.md b/docs/deployment-without-github.ko.md index f1a512e5..b9918ae1 100644 --- a/docs/deployment-without-github.ko.md +++ b/docs/deployment-without-github.ko.md @@ -4,13 +4,13 @@ [简体中文](deployment-without-github.zh-CN.md) -비즈니스 서버에는 소스 체크아웃, Git, Node.js 또는 pnpm이 필요하지 않습니다. 먼저 Docker Engine, Docker Compose 플러그인, Bash 및 OpenSSL을 설치한 다음 배포 파일을 전송하고 이미지를 준비한 후 Doca를 시작하고 관리자 계정을 초기화합니다. 이 가이드는 SQLite와 로컬 파일 저장소가 있는 새로 생긴 단일 서버에 Doca 0.3.1을 설치합니다. 기존 설치된 경우 확인해야 합니다. [출시 요구사항](releases/0.3.1.ko.md) 그들의 데이터베이스, 파일, 설정, 그리고 자격 증명 마스터 키를 보존합니다. +비즈니스 서버에는 소스 체크아웃, Git, Node.js 또는 pnpm이 필요하지 않습니다. 먼저 Docker Engine, Docker Compose 플러그인, Bash 및 OpenSSL을 설치한 다음 배포 파일을 전송하고 이미지를 준비한 후 Doca를 시작하고 관리자 계정을 초기화합니다. 이 가이드는 SQLite와 로컬 파일 저장소가 있는 새로 생긴 단일 서버에 Doca 0.3.2을 설치합니다. 기존 설치된 경우 확인해야 합니다. [출시 요구사항](releases/0.3.2.ko.md) 그들의 데이터베이스, 파일, 설정, 그리고 자격 증명 마스터 키를 보존합니다. ## YAML 파일을 이용한 신규 설치 -`node scripts/pack-deployment.mjs` 또한 출력됨 `doca-compose-vVERSION.yaml` 그리고 그 체크섬. YAML 파일을 전송하여 저장하세요. `compose.yaml` 영구 배포 디렉터리에서 수정하기 `DOCA_ORIGIN` 그리고 당신이 생성한 것 `DOCA_CREDENTIAL_MASTER_KEY`, 그것을 보호하세요 `chmod 600 compose.yaml`그런 다음 실행하세요 `docker compose up -d`. 아니요 `.env`seccomp JSON 또는 외부 관리자 스크립트가 필요합니다. 해당 0.3.1 이미지를 사용하세요; 독립형 YAML 및 체크섬도 GitHub Release에 함께 제공됩니다. +`node scripts/pack-deployment.mjs` 또한 출력됨 `doca-compose-vVERSION.yaml` 그리고 그 체크섬. YAML 파일을 전송하여 저장하세요. `compose.yaml` 영구 배포 디렉터리에서 수정하기 `DOCA_ORIGIN` 그리고 당신이 생성한 것 `DOCA_CREDENTIAL_MASTER_KEY`, 그것을 보호하세요 `chmod 600 compose.yaml`그런 다음 실행하세요 `docker compose up -d`. 아니요 `.env`seccomp JSON 또는 외부 관리자 스크립트가 필요합니다. 해당 0.3.2 이미지를 사용하세요; 독립형 YAML 및 체크섬도 GitHub Release에 함께 제공됩니다. 서비스가 건강한 후에 실행하세요. `docker compose exec doca bash docker/admin.sh bootstrap`; 사용하기 `reset-password` 비밀번호 재설정을 위한 것입니다. 비밀번호 입력은 숨겨져 있으며 YAML 파일에 저장되지 않습니다. 이 예시는 새로 설치된 SQLite/local-storage 환경에만 적용됩니다. 기존 사이트는 프로젝트 이름, 볼륨 및 키를 그대로 유지합니다. 백업에는 보호된 YAML 파일이 포함됩니다. 리버스 프로킷 관련 요구 사항은 아래에 설명된 대로 유지됩니다. @@ -27,22 +27,22 @@ cd doca node scripts/pack-deployment.mjs ``` -아래의 아카이브 이름과 이미지 태그는 0.3.1을 예시로 사용합니다. 패키저가 생성한 파일명과 생성된 Compose 파일에 지정된 이미지를 사용하세요. +아래의 아카이브 이름과 이미지 태그는 0.3.2을 예시로 사용합니다. 패키저가 생성한 파일명과 생성된 Compose 파일에 지정된 이미지를 사용하세요. -전송 `doca-deploy-v0.3.1.tar.gz` 그리고 그것 `.sha256` 기업 파일 서비스, 내부 다운로드 URL 또는 이동식 저장소를 통한 체크섬을 확인합니다. 패키저는 공개된 배포 파일만 읽고 로컬 파일은 포함하지 않습니다. `.env`사용자 데이터나 컨테이너 이미지입니다. 해당 태그에 대한 GitHub Release에는 번들과 체크섬이 포함되어 있습니다. +전송 `doca-deploy-v0.3.2.tar.gz` 그리고 그것 `.sha256` 기업 파일 서비스, 내부 다운로드 URL 또는 이동식 저장소를 통한 체크섬을 확인합니다. 패키저는 공개된 배포 파일만 읽고 로컬 파일은 포함하지 않습니다. `.env`사용자 데이터나 컨테이너 이미지입니다. 해당 태그에 대한 GitHub Release에는 번들과 체크섬이 포함되어 있습니다. 비즈니스 서버의 동일한 디렉터리에 두 파일을 넣고 확인한 후 추출합니다. ```sh -sha256sum -c doca-deploy-v0.3.1.tar.gz.sha256 -tar -xzf doca-deploy-v0.3.1.tar.gz -cd doca-deploy-v0.3.1 +sha256sum -c doca-deploy-v0.3.2.tar.gz.sha256 +tar -xzf doca-deploy-v0.3.2.tar.gz +cd doca-deploy-v0.3.2 ``` -macOS에서는 사용하세요. `shasum -a 256 -c doca-deploy-v0.3.1.tar.gz.sha256`이 디렉터리에서 다음 배포 명령을 실행하세요: +macOS에서는 사용하세요. `shasum -a 256 -c doca-deploy-v0.3.2.tar.gz.sha256`이 디렉터리에서 다음 배포 명령을 실행하세요: ```text -doca-deploy-v0.3.1/ +doca-deploy-v0.3.2/ compose.yaml docker.env.example README.zh-CN.md @@ -64,7 +64,7 @@ doca-deploy-v0.3.1/ ```yaml services: doca: - image: docker.io/smartdoca/doca:0.3.1 + image: docker.io/smartdoca/doca:0.3.2 pull_policy: missing restart: unless-stopped init: true @@ -155,21 +155,21 @@ docker compose pull doca 공급업체는 레지스트리 접근이 가능한 기계에서 이미지 아카이브를 준비합니다. 먼저 대상 CPU 아키텍처를 확인하세요. 이 예제에서는 Linux x86-64를 사용합니다.`linux/amd64`); ARM64의 경우, 사용하세요 `linux/arm64` 전달된 파일에 해당하는 라벨을 붙이세요: ```sh -docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.1 -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' -docker save -o doca-image-v0.3.1-linux-amd64.tar docker.io/smartdoca/doca:0.3.1 -sha256sum doca-image-v0.3.1-linux-amd64.tar > doca-image-v0.3.1-linux-amd64.tar.sha256 +docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.2 +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' +docker save -o doca-image-v0.3.2-linux-amd64.tar docker.io/smartdoca/doca:0.3.2 +sha256sum doca-image-v0.3.2-linux-amd64.tar > doca-image-v0.3.2-linux-amd64.tar.sha256 ``` 이미지를 전송하세요. `.tar` 그리고 체크섬을 함께 사용합니다. 비즈니스 서버의 그들의 디렉터리에서입니다. ```sh -sha256sum -c doca-image-v0.3.1-linux-amd64.tar.sha256 -docker load -i doca-image-v0.3.1-linux-amd64.tar -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' +sha256sum -c doca-image-v0.3.2-linux-amd64.tar.sha256 +docker load -i doca-image-v0.3.2-linux-amd64.tar +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' ``` -로드된 태그가 맞는지 확인하세요. `smartdoca/doca:0.3.1` 아키텍처가 목표와 일치하면 배포 디렉터리로 돌아갑니다. 내부 레지스트리는 또 다른 전달 옵션입니다: 공급업체가 동일한 릴리스 이미지를 전송하고 비즈니스 팀이 Compose를 변경합니다. `image` 풀기 전에 그 내부 레지스트리 주소를 사용하세요. 번들, 이미지, 초기화 스크립트를 동일한 릴리스에 유지하세요. +로드된 태그가 맞는지 확인하세요. `smartdoca/doca:0.3.2` 아키텍처가 목표와 일치하면 배포 디렉터리로 돌아갑니다. 내부 레지스트리는 또 다른 전달 옵션입니다: 공급업체가 동일한 릴리스 이미지를 전송하고 비즈니스 팀이 Compose를 변경합니다. `image` 풀기 전에 그 내부 레지스트리 주소를 사용하세요. 번들, 이미지, 초기화 스크립트를 동일한 릴리스에 유지하세요. @@ -192,7 +192,7 @@ docker compose ps curl -fsS -H 'Host: docs.example.com' http://127.0.0.1:39120/health ``` -예상할 것 `{"status":"ok","version":"0.3.1"}`내부 예시를 위해서는 사용하세요. `Host: doca.internal`바레 루프백 요청은 호스트 검증에 실패합니다. 시작 실패를 확인하세요. `docker compose logs --tail=100 doca`. +예상할 것 `{"status":"ok","version":"0.3.2"}`내부 예시를 위해서는 사용하세요. `Host: doca.internal`바레 루프백 요청은 호스트 검증에 실패합니다. 시작 실패를 확인하세요. `docker compose logs --tail=100 doca`. @@ -221,4 +221,4 @@ bash scripts/reset-admin-password.sh 사용하기 `docker compose restart` 일반적인 재시작에 해당합니다. 배포 디렉터리와 Compose 프로젝트 이름을 그대로 유지하세요. `doca_data` 볼륨이 사용되고 있으므로, 둘 중 하나를 변경하면 실수로 별도의 빈 사이트가 생길 수 있습니다. 영구 볼륨 내의 모든 데이터베이스와 파일 저장소, 그리고 보호된 내용도 모두 백업하세요. `.env` 그리고 마스터 키. `docker compose down -v` 볼륨을 삭제했으므로 일반적인 재시작이나 업그레이드에는 사용할 수 없습니다. -검토해 보세요. [출시 요구사항](releases/0.3.1.ko.md) 업그레이드하기 전에 맞는 번들과 이미지를 제공해야 합니다. 이 가이드는 새로 시작하는 사이트를 초기화하며 기존 데이터는 변환하지 않습니다. 비밀번호 로그인 및 로컬 문서 서비스는 GitHub 접근이 필요하지 않습니다; AI, 외부 로그인, 플러그인 설치 또는 클라우드 스토리지를 위한 외부 서비스는 여전히 접근 가능해야 합니다. 대상 호스트에서 문서 렌더링을 별도로 확인하십시오: 애플리케이션의 건강 상태만으로는 PDF, 캔버스 및 오피스 렌더링의 정확성을 보장할 수 없습니다. 참조하십시오. [Docker 문서 렌더링](docker-rendering.ko.md). +검토해 보세요. [출시 요구사항](releases/0.3.2.ko.md) 업그레이드하기 전에 맞는 번들과 이미지를 제공해야 합니다. 이 가이드는 새로 시작하는 사이트를 초기화하며 기존 데이터는 변환하지 않습니다. 비밀번호 로그인 및 로컬 문서 서비스는 GitHub 접근이 필요하지 않습니다; AI, 외부 로그인, 플러그인 설치 또는 클라우드 스토리지를 위한 외부 서비스는 여전히 접근 가능해야 합니다. 대상 호스트에서 문서 렌더링을 별도로 확인하십시오: 애플리케이션의 건강 상태만으로는 PDF, 캔버스 및 오피스 렌더링의 정확성을 보장할 수 없습니다. 참조하십시오. [Docker 문서 렌더링](docker-rendering.ko.md). diff --git a/docs/deployment-without-github.md b/docs/deployment-without-github.md index c43d2613..ed4f5ee3 100644 --- a/docs/deployment-without-github.md +++ b/docs/deployment-without-github.md @@ -2,11 +2,11 @@ **English** · [简体中文](deployment-without-github.zh-CN.md) · [繁體中文](deployment-without-github.zh-Hant.md) · [日本語](deployment-without-github.ja.md) · [Français](deployment-without-github.fr.md) · [한국어](deployment-without-github.ko.md) · [Español](deployment-without-github.es.md) · [Русский](deployment-without-github.ru.md) -The business server does not need a source checkout, Git, Node.js, or pnpm. Install Docker Engine, the Docker Compose plugin, Bash, and OpenSSL beforehand, then transfer deployment files, prepare the image, start Doca, and initialize the administrator. This guide installs Doca 0.3.1 on a fresh single server with SQLite and local file storage. Existing installations must review the [release requirements](releases/0.3.1.md) and preserve their databases, files, configuration, and credential master key. +The business server does not need a source checkout, Git, Node.js, or pnpm. Install Docker Engine, the Docker Compose plugin, Bash, and OpenSSL beforehand, then transfer deployment files, prepare the image, start Doca, and initialize the administrator. This guide installs Doca 0.3.2 on a fresh single server with SQLite and local file storage. Existing installations must review the [release requirements](releases/0.3.2.md) and preserve their databases, files, configuration, and credential master key. ## Fresh installation from one YAML -`node scripts/pack-deployment.mjs` also outputs `doca-compose-vVERSION.yaml` and its checksum. Transfer the YAML, save it as `compose.yaml` in a permanent deployment directory, edit `DOCA_ORIGIN` and your generated `DOCA_CREDENTIAL_MASTER_KEY`, protect it with `chmod 600 compose.yaml`, then run `docker compose up -d`. No `.env`, seccomp JSON or external administrator script is needed. Use the matching 0.3.1 image; the standalone YAML and checksum are also attached to the GitHub Release. +`node scripts/pack-deployment.mjs` also outputs `doca-compose-vVERSION.yaml` and its checksum. Transfer the YAML, save it as `compose.yaml` in a permanent deployment directory, edit `DOCA_ORIGIN` and your generated `DOCA_CREDENTIAL_MASTER_KEY`, protect it with `chmod 600 compose.yaml`, then run `docker compose up -d`. No `.env`, seccomp JSON or external administrator script is needed. Use the matching 0.3.2 image; the standalone YAML and checksum are also attached to the GitHub Release. After the service is healthy, run `docker compose exec doca bash docker/admin.sh bootstrap`; use `reset-password` for password reset. Password entry is hidden and does not go into the YAML. This example is only for fresh SQLite/local-storage installations. Existing sites retain their project name, volumes and key. Backups include the protected YAML. Reverse-proxy requirements remain as described below. @@ -20,22 +20,22 @@ cd doca node scripts/pack-deployment.mjs ``` -The archive names and image tag below use 0.3.1 as an example. Use the filenames printed by the packer and the image specified in the generated Compose file. +The archive names and image tag below use 0.3.2 as an example. Use the filenames printed by the packer and the image specified in the generated Compose file. -Transfer `doca-deploy-v0.3.1.tar.gz` and its `.sha256` checksum through an enterprise file service, an internal download URL, or removable storage. The packer reads only public deployment files and includes no local `.env`, user data, or container image. The GitHub Release for the corresponding tag includes the bundle and checksum. +Transfer `doca-deploy-v0.3.2.tar.gz` and its `.sha256` checksum through an enterprise file service, an internal download URL, or removable storage. The packer reads only public deployment files and includes no local `.env`, user data, or container image. The GitHub Release for the corresponding tag includes the bundle and checksum. Place both files in the same directory on the business server, verify, and extract: ```sh -sha256sum -c doca-deploy-v0.3.1.tar.gz.sha256 -tar -xzf doca-deploy-v0.3.1.tar.gz -cd doca-deploy-v0.3.1 +sha256sum -c doca-deploy-v0.3.2.tar.gz.sha256 +tar -xzf doca-deploy-v0.3.2.tar.gz +cd doca-deploy-v0.3.2 ``` -On macOS, use `shasum -a 256 -c doca-deploy-v0.3.1.tar.gz.sha256`. Run subsequent deployment commands from this directory: +On macOS, use `shasum -a 256 -c doca-deploy-v0.3.2.tar.gz.sha256`. Run subsequent deployment commands from this directory: ```text -doca-deploy-v0.3.1/ +doca-deploy-v0.3.2/ compose.yaml docker.env.example README.zh-CN.md @@ -55,7 +55,7 @@ For a text handoff, save this single-server configuration as `compose.yaml` and ```yaml services: doca: - image: docker.io/smartdoca/doca:0.3.1 + image: docker.io/smartdoca/doca:0.3.2 pull_policy: missing restart: unless-stopped init: true @@ -136,21 +136,21 @@ docker compose pull doca The supplier prepares an image archive on a machine with registry access. Confirm the target CPU architecture first. This example uses Linux x86-64 (`linux/amd64`); for ARM64, use `linux/arm64` and label the delivered files accordingly: ```sh -docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.1 -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' -docker save -o doca-image-v0.3.1-linux-amd64.tar docker.io/smartdoca/doca:0.3.1 -sha256sum doca-image-v0.3.1-linux-amd64.tar > doca-image-v0.3.1-linux-amd64.tar.sha256 +docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.2 +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' +docker save -o doca-image-v0.3.2-linux-amd64.tar docker.io/smartdoca/doca:0.3.2 +sha256sum doca-image-v0.3.2-linux-amd64.tar > doca-image-v0.3.2-linux-amd64.tar.sha256 ``` Transfer the image `.tar` and checksum together. From their directory on the business server: ```sh -sha256sum -c doca-image-v0.3.1-linux-amd64.tar.sha256 -docker load -i doca-image-v0.3.1-linux-amd64.tar -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' +sha256sum -c doca-image-v0.3.2-linux-amd64.tar.sha256 +docker load -i doca-image-v0.3.2-linux-amd64.tar +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' ``` -Confirm the loaded tag is `smartdoca/doca:0.3.1` and the architecture matches the target, then return to the deployment directory. An internal registry is another delivery option: the supplier pushes the same release image and the business team changes Compose's `image` to that internal registry address before pulling. Keep the bundle, image, and initialization scripts on the same release. +Confirm the loaded tag is `smartdoca/doca:0.3.2` and the architecture matches the target, then return to the deployment directory. An internal registry is another delivery option: the supplier pushes the same release image and the business team changes Compose's `image` to that internal registry address before pulling. Keep the bundle, image, and initialization scripts on the same release. ## 4. Start and initialize the database @@ -170,7 +170,7 @@ Wait for `docker compose ps` to show `healthy`. A manual check must use the Host curl -fsS -H 'Host: docs.example.com' http://127.0.0.1:39120/health ``` -Expect `{"status":"ok","version":"0.3.1"}`. For the internal example, use `Host: doca.internal`. Bare loopback requests fail Host validation. Inspect startup failures with `docker compose logs --tail=100 doca`. +Expect `{"status":"ok","version":"0.3.2"}`. For the internal example, use `Host: doca.internal`. Bare loopback requests fail Host validation. Inspect startup failures with `docker compose logs --tail=100 doca`. ## 5. Initialize the administrator @@ -194,4 +194,4 @@ This does not create an account. If the database is locked, run `docker compose Use `docker compose restart` for ordinary restarts. Keep the deployment directory and Compose project name so the same `doca_data` volume is used; changing either can accidentally start a separate empty site. Back up all databases and file storage in the persistent volume, plus the protected `.env` and master key. `docker compose down -v` deletes the volume and must not be used for an ordinary restart or upgrade. -Review the [release requirements](releases/0.3.1.md) before upgrading and deliver a matching bundle and image. This guide initializes fresh sites and does not convert existing data. Password login and local document services need no GitHub access; configured external services for AI, external login, plugin installation, or cloud storage must still be reachable. Verify document rendering on the target host separately: application health alone does not establish PDF, Canvas and Office rendering correctness. See [Docker document rendering](docker-rendering.md). +Review the [release requirements](releases/0.3.2.md) before upgrading and deliver a matching bundle and image. This guide initializes fresh sites and does not convert existing data. Password login and local document services need no GitHub access; configured external services for AI, external login, plugin installation, or cloud storage must still be reachable. Verify document rendering on the target host separately: application health alone does not establish PDF, Canvas and Office rendering correctness. See [Docker document rendering](docker-rendering.md). diff --git a/docs/deployment-without-github.ru.md b/docs/deployment-without-github.ru.md index c4abf0cd..dc017169 100644 --- a/docs/deployment-without-github.ru.md +++ b/docs/deployment-without-github.ru.md @@ -4,13 +4,13 @@ [简体中文](deployment-without-github.zh-CN.md) -Бизнес-сервер не нуждается в источнике скачивания, Git, Node.js или pnpm. Сначала установите Docker Engine, плагин Docker Compose, Bash и OpenSSL, затем передайте файлы развёртывания, подготовьте изображение, запустите Doca и инициализируйте администратора. Этот руководство устанавливает Doca 0.3.1 на свежий одноплатформенный сервер с SQLite и локальным хранением файлов. Уже существующие установки должны проверить… [требования к выпуску](releases/0.3.1.ru.md) и сохранять их базы данных, файлы, конфигурацию и главный ключ учетных данных. +Бизнес-сервер не нуждается в источнике скачивания, Git, Node.js или pnpm. Сначала установите Docker Engine, плагин Docker Compose, Bash и OpenSSL, затем передайте файлы развёртывания, подготовьте изображение, запустите Doca и инициализируйте администратора. Этот руководство устанавливает Doca 0.3.2 на свежий одноплатформенный сервер с SQLite и локальным хранением файлов. Уже существующие установки должны проверить… [требования к выпуску](releases/0.3.2.ru.md) и сохранять их базы данных, файлы, конфигурацию и главный ключ учетных данных. ## Новая установка из YAML-файла -`node scripts/pack-deployment.mjs` также выводит `doca-compose-vVERSION.yaml` и его контрольный сумма. Перенесите YAML-файл и сохраните его как `compose.yaml` В постоянном каталоге развёртывания измените `DOCA_ORIGIN` и ваша генерированная `DOCA_CREDENTIAL_MASTER_KEY`Защитить его `chmod 600 compose.yaml`, затем запустите `docker compose up -d`Нет `.env`Необходимо использовать JSON-файл seccomp или скрипт внешнего администратора. Используйте соответствующий образ версии 0.3.1; отдельный YAML-файл и контрольный сумма также прилагаются к релизу на GitHub. +`node scripts/pack-deployment.mjs` также выводит `doca-compose-vVERSION.yaml` и его контрольный сумма. Перенесите YAML-файл и сохраните его как `compose.yaml` В постоянном каталоге развёртывания измените `DOCA_ORIGIN` и ваша генерированная `DOCA_CREDENTIAL_MASTER_KEY`Защитить его `chmod 600 compose.yaml`, затем запустите `docker compose up -d`Нет `.env`Необходимо использовать JSON-файл seccomp или скрипт внешнего администратора. Используйте соответствующий образ версии 0.3.2; отдельный YAML-файл и контрольный сумма также прилагаются к релизу на GitHub. После того как процесс здоров, запустите. `docker compose exec doca bash docker/admin.sh bootstrap`; использовать `reset-password` Для сброса пароля. Введение пароля скрыто и не попадает в YAML. Этот пример предназначен только для новых установок SQLite/local-storage. Существующие сайты сохраняют свое имя проекта, объемы данных и ключи. Бэкапы включают защищенный YAML. Требования к реверс-прокси остаются такими же, как описано ниже. @@ -27,22 +27,22 @@ cd doca node scripts/pack-deployment.mjs ``` -Названия архивов и метки изображений ниже используют 0.3.1 в качестве примера. Используйте имена файлов, указанные пакером, и изображение, указанное в созданном файле Compose. +Названия архивов и метки изображений ниже используют 0.3.2 в качестве примера. Используйте имена файлов, указанные пакером, и изображение, указанное в созданном файле Compose. -Передача `doca-deploy-v0.3.1.tar.gz` и его `.sha256` Сумма контроля через сервис предприятия, внутреную URL скачивания или удаляемое хранилище. Пакер читает только публичные файлы развертывания и не включает локальные файлы. `.env`Пользовательские данные или изображение контейнера. GitHub Release для соответствующего тега включает бандл и проверочный код. +Передача `doca-deploy-v0.3.2.tar.gz` и его `.sha256` Сумма контроля через сервис предприятия, внутреную URL скачивания или удаляемое хранилище. Пакер читает только публичные файлы развертывания и не включает локальные файлы. `.env`Пользовательские данные или изображение контейнера. GitHub Release для соответствующего тега включает бандл и проверочный код. Поместите оба файла в один и тот же каталог на бизнес-сервере, проверьте и извлеките. ```sh -sha256sum -c doca-deploy-v0.3.1.tar.gz.sha256 -tar -xzf doca-deploy-v0.3.1.tar.gz -cd doca-deploy-v0.3.1 +sha256sum -c doca-deploy-v0.3.2.tar.gz.sha256 +tar -xzf doca-deploy-v0.3.2.tar.gz +cd doca-deploy-v0.3.2 ``` -На macOS используйте `shasum -a 256 -c doca-deploy-v0.3.1.tar.gz.sha256`Выполняйте последующие команды развертывания из этого директория: +На macOS используйте `shasum -a 256 -c doca-deploy-v0.3.2.tar.gz.sha256`Выполняйте последующие команды развертывания из этого директория: ```text -doca-deploy-v0.3.1/ +doca-deploy-v0.3.2/ compose.yaml docker.env.example README.zh-CN.md @@ -64,7 +64,7 @@ doca-deploy-v0.3.1/ ```yaml services: doca: - image: docker.io/smartdoca/doca:0.3.1 + image: docker.io/smartdoca/doca:0.3.2 pull_policy: missing restart: unless-stopped init: true @@ -155,21 +155,21 @@ docker compose pull doca Поставщик готовит архив изображений на устройстве с доступом к реестру. Сначала необходимо подтвердить архитектуру целевой процессора. В этом примере используется Linux x86-64.`linux/amd64`); для ARM64 используйте `linux/arm64` и обозначите доставленные файлы соответствующим образом: ```sh -docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.1 -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' -docker save -o doca-image-v0.3.1-linux-amd64.tar docker.io/smartdoca/doca:0.3.1 -sha256sum doca-image-v0.3.1-linux-amd64.tar > doca-image-v0.3.1-linux-amd64.tar.sha256 +docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.2 +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' +docker save -o doca-image-v0.3.2-linux-amd64.tar docker.io/smartdoca/doca:0.3.2 +sha256sum doca-image-v0.3.2-linux-amd64.tar > doca-image-v0.3.2-linux-amd64.tar.sha256 ``` Перенесите изображение `.tar` и сложные проверочные коды вместе. Из их директории на бизнес-сервере: ```sh -sha256sum -c doca-image-v0.3.1-linux-amd64.tar.sha256 -docker load -i doca-image-v0.3.1-linux-amd64.tar -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' +sha256sum -c doca-image-v0.3.2-linux-amd64.tar.sha256 +docker load -i doca-image-v0.3.2-linux-amd64.tar +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' ``` -Подтвердите, что загруженный тег существует. `smartdoca/doca:0.3.1` Если архитектура соответствует целевой версии, то возвращаемся в директорию развертывания. Внутренний реестр — еще один вариант доставки: поставщик публикует ту же версию изображения, а бизнес-команда меняет Compose. `image` Имейте в виду адрес внутреннего реестра перед выполнением. Сохраняйте пакет, изображение и скрипты инициализации в одном и том же релизе. +Подтвердите, что загруженный тег существует. `smartdoca/doca:0.3.2` Если архитектура соответствует целевой версии, то возвращаемся в директорию развертывания. Внутренний реестр — еще один вариант доставки: поставщик публикует ту же версию изображения, а бизнес-команда меняет Compose. `image` Имейте в виду адрес внутреннего реестра перед выполнением. Сохраняйте пакет, изображение и скрипты инициализации в одном и том же релизе. @@ -192,7 +192,7 @@ docker compose ps curl -fsS -H 'Host: docs.example.com' http://127.0.0.1:39120/health ``` -Ожидайте `{"status":"ok","version":"0.3.1"}`Для внутреннего примера используйте `Host: doca.internal`Запросы типа “bare loopback” не проходят проверку хоста. Исследуйте ошибки запуска. `docker compose logs --tail=100 doca`. +Ожидайте `{"status":"ok","version":"0.3.2"}`Для внутреннего примера используйте `Host: doca.internal`Запросы типа “bare loopback” не проходят проверку хоста. Исследуйте ошибки запуска. `docker compose logs --tail=100 doca`. @@ -221,4 +221,4 @@ bash scripts/reset-admin-password.sh Используйте `docker compose restart` Для обычных перезапусков. Сохраняйте директорию развёртывания и имя проекта Compose, чтобы все было одинаково. `doca_data` Используется объем диска; изменение любого из них может случайно вызвать создание отдельного пустого сайта. Сделайте резервную копию всех баз данных и файловых хранилищ в постоянном объеме диска, а также защищенных данных. `.env` и главный ключ. `docker compose down -v` Удаляет том, и его нельзя использовать для обычного перезапуска или обновления. -Проанализировать [требования к выпуску](releases/0.3.1.ru.md) Перед обновлением необходимо предоставить соответствующий пакет и изображение. Этот руководство инициализирует новые сайты и не конвертирует существующие данные. Вход по паролю и локальные сервисы документов не требуют доступа к GitHub; внешние сервисы для ИИ, внешний вход, установка плагинов или хранение в облаке должны все еще быть доступными. Проверьте отображение документов на целевом хосте отдельно: само состояние приложения не гарантирует корректность отображения PDF, Canvas и Office. Смотрите. [Отображение документа в Docker](docker-rendering.ru.md). +Проанализировать [требования к выпуску](releases/0.3.2.ru.md) Перед обновлением необходимо предоставить соответствующий пакет и изображение. Этот руководство инициализирует новые сайты и не конвертирует существующие данные. Вход по паролю и локальные сервисы документов не требуют доступа к GitHub; внешние сервисы для ИИ, внешний вход, установка плагинов или хранение в облаке должны все еще быть доступными. Проверьте отображение документов на целевом хосте отдельно: само состояние приложения не гарантирует корректность отображения PDF, Canvas и Office. Смотрите. [Отображение документа в Docker](docker-rendering.ru.md). diff --git a/docs/deployment-without-github.zh-CN.md b/docs/deployment-without-github.zh-CN.md index 521f0a62..9f027150 100644 --- a/docs/deployment-without-github.zh-CN.md +++ b/docs/deployment-without-github.zh-CN.md @@ -2,11 +2,11 @@ [English](deployment-without-github.md) · **简体中文** · [繁體中文](deployment-without-github.zh-Hant.md) · [日本語](deployment-without-github.ja.md) · [Français](deployment-without-github.fr.md) · [한국어](deployment-without-github.ko.md) · [Español](deployment-without-github.es.md) · [Русский](deployment-without-github.ru.md) -业务服务器无需拉取源码,也无需安装 Git、Node.js 或 pnpm。准备好 Docker Engine、Docker Compose 插件、Bash 和 OpenSSL 后,复制部署文件、准备镜像、启动并初始化管理员即可。本指南用于全新单机安装 Doca 0.3.1,采用 SQLite 和本地文件存储;已有部署先阅读[发行要求](releases/0.3.1.zh-CN.md),保留原数据库、文件、配置和凭证主密钥。 +业务服务器无需拉取源码,也无需安装 Git、Node.js 或 pnpm。准备好 Docker Engine、Docker Compose 插件、Bash 和 OpenSSL 后,复制部署文件、准备镜像、启动并初始化管理员即可。本指南用于全新单机安装 Doca 0.3.2,采用 SQLite 和本地文件存储;已有部署先阅读[发行要求](releases/0.3.2.zh-CN.md),保留原数据库、文件、配置和凭证主密钥。 ## 单 YAML 全新安装 -`node scripts/pack-deployment.mjs` 另输出 `doca-compose-v版本.yaml` 和校验文件。交付此 YAML,保存为固定部署目录下的 `compose.yaml`,在文件中填写 `DOCA_ORIGIN` 与自行生成的 `DOCA_CREDENTIAL_MASTER_KEY`,执行 `chmod 600 compose.yaml` 后运行 `docker compose up -d`。无需 `.env`、seccomp JSON 或外部初始化脚本。使用匹配的 0.3.1 镜像;GitHub Release 也提供该独立 YAML 与校验文件。 +`node scripts/pack-deployment.mjs` 另输出 `doca-compose-v版本.yaml` 和校验文件。交付此 YAML,保存为固定部署目录下的 `compose.yaml`,在文件中填写 `DOCA_ORIGIN` 与自行生成的 `DOCA_CREDENTIAL_MASTER_KEY`,执行 `chmod 600 compose.yaml` 后运行 `docker compose up -d`。无需 `.env`、seccomp JSON 或外部初始化脚本。使用匹配的 0.3.2 镜像;GitHub Release 也提供该独立 YAML 与校验文件。 服务健康后执行 `docker compose exec doca bash docker/admin.sh bootstrap`;重置密码用 `docker compose exec doca bash docker/admin.sh reset-password`。密码在终端隐藏输入,不写进 YAML。该示例仅用于全新 SQLite/本地存储安装,已有站点继续使用原项目名、持久卷和密钥;备份须包含受保护的 YAML。反向代理要求与下文一致。 @@ -20,22 +20,22 @@ cd doca node scripts/pack-deployment.mjs ``` -下文用 0.3.1 的文件名和镜像标签举例。实际以打包命令输出的文件名和生成的 Compose 镜像为准。 +下文用 0.3.2 的文件名和镜像标签举例。实际以打包命令输出的文件名和生成的 Compose 镜像为准。 -把生成的 `doca-deploy-v0.3.1.tar.gz` 和同名 `.sha256` 校验文件,通过企业文件服务、内网下载地址或移动存储转交给业务方。打包只读取公开部署文件。对应标签的 GitHub Release 附带部署包和校验文件。 +把生成的 `doca-deploy-v0.3.2.tar.gz` 和同名 `.sha256` 校验文件,通过企业文件服务、内网下载地址或移动存储转交给业务方。打包只读取公开部署文件。对应标签的 GitHub Release 附带部署包和校验文件。 在业务服务器上将两个文件放到同一目录,校验并解压: ```sh -sha256sum -c doca-deploy-v0.3.1.tar.gz.sha256 -tar -xzf doca-deploy-v0.3.1.tar.gz -cd doca-deploy-v0.3.1 +sha256sum -c doca-deploy-v0.3.2.tar.gz.sha256 +tar -xzf doca-deploy-v0.3.2.tar.gz +cd doca-deploy-v0.3.2 ``` -macOS 校验可用 `shasum -a 256 -c doca-deploy-v0.3.1.tar.gz.sha256`。部署目录如下,后续命令均在此目录执行: +macOS 校验可用 `shasum -a 256 -c doca-deploy-v0.3.2.tar.gz.sha256`。部署目录如下,后续命令均在此目录执行: ```text -doca-deploy-v0.3.1/ +doca-deploy-v0.3.2/ compose.yaml docker.env.example README.zh-CN.md @@ -55,7 +55,7 @@ doca-deploy-v0.3.1/ ```yaml services: doca: - image: docker.io/smartdoca/doca:0.3.1 + image: docker.io/smartdoca/doca:0.3.2 pull_policy: missing restart: unless-stopped init: true @@ -136,21 +136,21 @@ docker compose pull doca 由交付方在可拉取镜像的机器上准备镜像文件。先确认业务服务器的 CPU 架构;以下以 Linux x86-64(`linux/amd64`)为例,ARM64 服务器把平台改为 `linux/arm64`,并在交付文件名中相应标明: ```sh -docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.1 -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' -docker save -o doca-image-v0.3.1-linux-amd64.tar docker.io/smartdoca/doca:0.3.1 -sha256sum doca-image-v0.3.1-linux-amd64.tar > doca-image-v0.3.1-linux-amd64.tar.sha256 +docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.2 +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' +docker save -o doca-image-v0.3.2-linux-amd64.tar docker.io/smartdoca/doca:0.3.2 +sha256sum doca-image-v0.3.2-linux-amd64.tar > doca-image-v0.3.2-linux-amd64.tar.sha256 ``` 把镜像 `.tar` 和校验文件一起转交。业务方在这两个文件所在目录执行: ```sh -sha256sum -c doca-image-v0.3.1-linux-amd64.tar.sha256 -docker load -i doca-image-v0.3.1-linux-amd64.tar -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' +sha256sum -c doca-image-v0.3.2-linux-amd64.tar.sha256 +docker load -i doca-image-v0.3.2-linux-amd64.tar +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' ``` -确认导入的标签是 `smartdoca/doca:0.3.1`,架构与目标服务器一致,再回到部署目录。内网镜像仓库也是可选交付方式:交付方推送同版本镜像,业务方将 Compose 的 `image` 改为内网镜像完整地址并拉取;部署包、镜像和初始化脚本保持同一版本。 +确认导入的标签是 `smartdoca/doca:0.3.2`,架构与目标服务器一致,再回到部署目录。内网镜像仓库也是可选交付方式:交付方推送同版本镜像,业务方将 Compose 的 `image` 改为内网镜像完整地址并拉取;部署包、镜像和初始化脚本保持同一版本。 ## 4. 启动与数据库初始化 @@ -170,7 +170,7 @@ docker compose ps curl -fsS -H 'Host: docs.example.com' http://127.0.0.1:39120/health ``` -应返回 `{"status":"ok","version":"0.3.1"}`。内网站点改用 `Host: doca.internal`。裸回环请求会被 Host 校验拒绝。启动失败可运行 `docker compose logs --tail=100 doca` 查看日志。 +应返回 `{"status":"ok","version":"0.3.2"}`。内网站点改用 `Host: doca.internal`。裸回环请求会被 Host 校验拒绝。启动失败可运行 `docker compose logs --tail=100 doca` 查看日志。 ## 5. 初始化管理员 @@ -194,4 +194,4 @@ bash scripts/reset-admin-password.sh 日常重启使用 `docker compose restart`,保留部署目录和 Compose 项目名,以继续使用同一个 `doca_data` 卷;不要通过改目录或项目名意外启动另一个空站点。备份覆盖持久卷中的全部数据库、文件存储以及受保护的 `.env` 和主密钥。`docker compose down -v` 会删除卷,不用于普通重启或升级。 -后续升级先确认[发行要求](releases/0.3.1.zh-CN.md),交付匹配版本的部署包和镜像;本流程只初始化全新站点,不转换已有数据。基础密码登录和本地文档服务无需 GitHub;AI、外部登录、插件安装及云存储等配置的外部服务仍需业务网络可达。文档导出还需在目标宿主机验证渲染器,应用健康不等于 PDF、画板和 Office 渲染效果已验证,见 [Docker 文档渲染器](docker-rendering.zh-CN.md)。 +后续升级先确认[发行要求](releases/0.3.2.zh-CN.md),交付匹配版本的部署包和镜像;本流程只初始化全新站点,不转换已有数据。基础密码登录和本地文档服务无需 GitHub;AI、外部登录、插件安装及云存储等配置的外部服务仍需业务网络可达。文档导出还需在目标宿主机验证渲染器,应用健康不等于 PDF、画板和 Office 渲染效果已验证,见 [Docker 文档渲染器](docker-rendering.zh-CN.md)。 diff --git a/docs/deployment-without-github.zh-Hant.md b/docs/deployment-without-github.zh-Hant.md index f5f91ca3..75aa6332 100644 --- a/docs/deployment-without-github.zh-Hant.md +++ b/docs/deployment-without-github.zh-Hant.md @@ -4,13 +4,13 @@ [English](deployment-without-github.md) -業務伺服器無需拉取原始碼,也無需安裝 Git、Node.js 或 pnpm。準備好 Docker Engine、Docker Compose 外掛、Bash 和 OpenSSL 後,複製部署檔案、準備映象、啟動並初始化管理員即可。本指南用於全新單機安裝 Doca 0.3.1,採用 SQLite 和本地檔案儲存;已有部署先閱讀[發行要求](releases/0.3.1.zh-Hant.md),保留原資料庫、檔案、配置和憑證主金鑰。 +業務伺服器無需拉取原始碼,也無需安裝 Git、Node.js 或 pnpm。準備好 Docker Engine、Docker Compose 外掛、Bash 和 OpenSSL 後,複製部署檔案、準備映象、啟動並初始化管理員即可。本指南用於全新單機安裝 Doca 0.3.2,採用 SQLite 和本地檔案儲存;已有部署先閱讀[發行要求](releases/0.3.2.zh-Hant.md),保留原資料庫、檔案、配置和憑證主金鑰。 ## 單 YAML 全新安裝 -`node scripts/pack-deployment.mjs` 另輸出 `doca-compose-v版本.yaml` 和校驗檔案。交付此 YAML,儲存為固定部署目錄下的 `compose.yaml`,在檔案中填寫 `DOCA_ORIGIN` 與自行生成的 `DOCA_CREDENTIAL_MASTER_KEY`,執行 `chmod 600 compose.yaml` 後執行 `docker compose up -d`。無需 `.env`、seccomp JSON 或外部初始化指令碼。使用匹配的 0.3.1 映象;GitHub Release 也提供該獨立 YAML 與校驗檔案。 +`node scripts/pack-deployment.mjs` 另輸出 `doca-compose-v版本.yaml` 和校驗檔案。交付此 YAML,儲存為固定部署目錄下的 `compose.yaml`,在檔案中填寫 `DOCA_ORIGIN` 與自行生成的 `DOCA_CREDENTIAL_MASTER_KEY`,執行 `chmod 600 compose.yaml` 後執行 `docker compose up -d`。無需 `.env`、seccomp JSON 或外部初始化指令碼。使用匹配的 0.3.2 映象;GitHub Release 也提供該獨立 YAML 與校驗檔案。 服務健康後執行 `docker compose exec doca bash docker/admin.sh bootstrap`;重置密碼用 `docker compose exec doca bash docker/admin.sh reset-password`。密碼在終端隱藏輸入,不寫進 YAML。該示例僅用於全新 SQLite/本地儲存安裝,已有站點繼續使用原專案名、持久卷和金鑰;備份須包含受保護的 YAML。反向代理要求與下文一致。 @@ -27,22 +27,22 @@ cd doca node scripts/pack-deployment.mjs ``` -下文用 0.3.1 的檔名和映象標籤舉例。實際以打包命令輸出的檔名和生成的 Compose 映象為準。 +下文用 0.3.2 的檔名和映象標籤舉例。實際以打包命令輸出的檔名和生成的 Compose 映象為準。 -把生成的 `doca-deploy-v0.3.1.tar.gz` 和同名 `.sha256` 校驗檔案,透過企業檔案服務、內網下載地址或移動儲存轉交給業務方。打包只讀取公開部署檔案。對應標籤的 GitHub Release 附帶部署包和校驗檔案。 +把生成的 `doca-deploy-v0.3.2.tar.gz` 和同名 `.sha256` 校驗檔案,透過企業檔案服務、內網下載地址或移動儲存轉交給業務方。打包只讀取公開部署檔案。對應標籤的 GitHub Release 附帶部署包和校驗檔案。 在業務伺服器上將兩個檔案放到同一目錄,校驗並解壓: ```sh -sha256sum -c doca-deploy-v0.3.1.tar.gz.sha256 -tar -xzf doca-deploy-v0.3.1.tar.gz -cd doca-deploy-v0.3.1 +sha256sum -c doca-deploy-v0.3.2.tar.gz.sha256 +tar -xzf doca-deploy-v0.3.2.tar.gz +cd doca-deploy-v0.3.2 ``` -macOS 校驗可用 `shasum -a 256 -c doca-deploy-v0.3.1.tar.gz.sha256`。部署目錄如下,後續命令均在此目錄執行: +macOS 校驗可用 `shasum -a 256 -c doca-deploy-v0.3.2.tar.gz.sha256`。部署目錄如下,後續命令均在此目錄執行: ```text -doca-deploy-v0.3.1/ +doca-deploy-v0.3.2/ compose.yaml docker.env.example README.zh-CN.md @@ -64,7 +64,7 @@ doca-deploy-v0.3.1/ ```yaml services: doca: - image: docker.io/smartdoca/doca:0.3.1 + image: docker.io/smartdoca/doca:0.3.2 pull_policy: missing restart: unless-stopped init: true @@ -155,21 +155,21 @@ docker compose pull doca 由交付方在可拉取映象的機器上準備映象檔案。先確認業務伺服器的 CPU 架構;以下以 Linux x86-64(`linux/amd64`)為例,ARM64 伺服器把平臺改為 `linux/arm64`,並在交付檔名中相應標明: ```sh -docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.1 -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' -docker save -o doca-image-v0.3.1-linux-amd64.tar docker.io/smartdoca/doca:0.3.1 -sha256sum doca-image-v0.3.1-linux-amd64.tar > doca-image-v0.3.1-linux-amd64.tar.sha256 +docker pull --platform linux/amd64 docker.io/smartdoca/doca:0.3.2 +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' +docker save -o doca-image-v0.3.2-linux-amd64.tar docker.io/smartdoca/doca:0.3.2 +sha256sum doca-image-v0.3.2-linux-amd64.tar > doca-image-v0.3.2-linux-amd64.tar.sha256 ``` 把映象 `.tar` 和校驗檔案一起轉交。業務方在這兩個檔案所在目錄執行: ```sh -sha256sum -c doca-image-v0.3.1-linux-amd64.tar.sha256 -docker load -i doca-image-v0.3.1-linux-amd64.tar -docker image inspect docker.io/smartdoca/doca:0.3.1 --format '{{.Os}}/{{.Architecture}}' +sha256sum -c doca-image-v0.3.2-linux-amd64.tar.sha256 +docker load -i doca-image-v0.3.2-linux-amd64.tar +docker image inspect docker.io/smartdoca/doca:0.3.2 --format '{{.Os}}/{{.Architecture}}' ``` -確認匯入的標籤是 `smartdoca/doca:0.3.1`,架構與目標伺服器一致,再回到部署目錄。內網映象倉庫也是可選交付方式:交付方推送同版本映象,業務方將 Compose 的 `image` 改為內網映象完整地址並拉取;部署包、映象和初始化指令碼保持同一版本。 +確認匯入的標籤是 `smartdoca/doca:0.3.2`,架構與目標伺服器一致,再回到部署目錄。內網映象倉庫也是可選交付方式:交付方推送同版本映象,業務方將 Compose 的 `image` 改為內網映象完整地址並拉取;部署包、映象和初始化指令碼保持同一版本。 @@ -192,7 +192,7 @@ docker compose ps curl -fsS -H 'Host: docs.example.com' http://127.0.0.1:39120/health ``` -應返回 `{"status":"ok","version":"0.3.1"}`。內網站點改用 `Host: doca.internal`。裸迴環請求會被 Host 校驗拒絕。啟動失敗可執行 `docker compose logs --tail=100 doca` 檢視日誌。 +應返回 `{"status":"ok","version":"0.3.2"}`。內網站點改用 `Host: doca.internal`。裸迴環請求會被 Host 校驗拒絕。啟動失敗可執行 `docker compose logs --tail=100 doca` 檢視日誌。 @@ -221,4 +221,4 @@ bash scripts/reset-admin-password.sh 日常重啟使用 `docker compose restart`,保留部署目錄和 Compose 專案名,以繼續使用同一個 `doca_data` 卷;不要透過改目錄或專案名意外啟動另一個空站點。備份覆蓋持久卷中的全部資料庫、檔案儲存以及受保護的 `.env` 和主金鑰。`docker compose down -v` 會刪除卷,不用於普通重啟或升級。 -後續升級先確認[發行要求](releases/0.3.1.zh-Hant.md),交付匹配版本的部署包和映象;本流程只初始化全新站點,不轉換已有資料。基礎密碼登入和本地文件服務無需 GitHub;AI、外部登入、外掛安裝及雲端儲存等配置的外部服務仍需業務網路可達。文件匯出還需在目標宿主機驗證渲染器,應用健康不等於 PDF、畫板和 Office 渲染效果已驗證,見 [Docker 文件渲染器](docker-rendering.zh-Hant.md)。 +後續升級先確認[發行要求](releases/0.3.2.zh-Hant.md),交付匹配版本的部署包和映象;本流程只初始化全新站點,不轉換已有資料。基礎密碼登入和本地文件服務無需 GitHub;AI、外部登入、外掛安裝及雲端儲存等配置的外部服務仍需業務網路可達。文件匯出還需在目標宿主機驗證渲染器,應用健康不等於 PDF、畫板和 Office 渲染效果已驗證,見 [Docker 文件渲染器](docker-rendering.zh-Hant.md)。 diff --git a/docs/deployment.es.md b/docs/deployment.es.md index f6fdc1c6..8c630f80 100644 --- a/docs/deployment.es.md +++ b/docs/deployment.es.md @@ -38,7 +38,7 @@ Editar `.env` antes del primer inicio. El almacenamiento de archivos también requiere `DOCA_FILE_STORE_ID` y `DOCA_FILE_STORES_JSON`, según lo estipulado `docker.env.example`. Los caminos y credenciales del backend se leen del entorno; la página de administración es de solo lectura. Ver [almacenamiento de archivos](storage.es.md). -El anfitrión actual utiliza generación `doca-2026-10-12-book-payload-storage-v1`La startup alinea automáticamente las bases de datos 0.1.22 liberadas. `doca-2026-10-09-history-storage-v1` A través de la revisión/reconciliación de DDL actual y registra la nueva generación. Todas las filas antiguas permanecen, incluyendo los resultados del libro SQL; no se añaden conversiones, limpiezas ni adaptadores para cuerpos antiguos. Los registros residuales del libro antiguo pueden requerir manejo manual. Los datos de objetos de la versión 0.1.23 existentes permanecen. Ver [Evolución de la estructura de la base de datos](database-schema-evolution.es.md) y [Requisitos de lanzamiento actuales](releases/0.3.1.es.md)La base exacta 0.1.13 `doca-2026-10-08-knowledge-books-v2` Todavía se necesita la actualización explícita de historial a continuación. Preserve las bases de datos, los objetos privados, la configuración y la clave maestra de credenciales original. +El anfitrión actual utiliza generación `doca-2026-10-12-book-payload-storage-v1`La startup alinea automáticamente las bases de datos 0.1.22 liberadas. `doca-2026-10-09-history-storage-v1` A través de la revisión/reconciliación de DDL actual y registra la nueva generación. Todas las filas antiguas permanecen, incluyendo los resultados del libro SQL; no se añaden conversiones, limpiezas ni adaptadores para cuerpos antiguos. Los registros residuales del libro antiguo pueden requerir manejo manual. Los datos de objetos de la versión 0.1.23 existentes permanecen. Ver [Evolución de la estructura de la base de datos](database-schema-evolution.es.md) y [Requisitos de lanzamiento actuales](releases/0.3.2.es.md)La base exacta 0.1.13 `doca-2026-10-08-knowledge-books-v2` Todavía se necesita la actualización explícita de historial a continuación. Preserve las bases de datos, los objetos privados, la configuración y la clave maestra de credenciales original. `DOCA_ORIGIN` Es el origen de los usuarios que se escribe en el navegador. Se aceptan HTTP y HTTPS, incluso en producción. Se debe usar únicamente el origen sin subruta, consulta o fragmento; la barra final en la raíz se normaliza. diff --git a/docs/deployment.fr.md b/docs/deployment.fr.md index d4b2312b..e3271f0e 100644 --- a/docs/deployment.fr.md +++ b/docs/deployment.fr.md @@ -38,7 +38,7 @@ cp docker.env.example .env Le stockage de fichiers nécessite également `DOCA_FILE_STORE_ID` et `DOCA_FILE_STORES_JSON`, comme indiqué `docker.env.example`. Les chemins et les identifiants du backend sont lus depuis l'environnement ; la page d'administration est uniquement consultable. Voir [stockage de fichiers](storage.fr.md). -L’hôte actuel utilise la génération `doca-2026-10-12-book-payload-storage-v1`Le startup aligne automatiquement les bases de données 0.1.22 libérées. `doca-2026-10-09-history-storage-v1` Grâce à l’examen/reconciliation des DDL actuels, la nouvelle génération est enregistrée. Toutes les lignes anciennes restent, y compris les résultats du livre SQL ; aucune conversion, nettoyage ou adaptateur pour les anciens objets n’est ajouté. Les enregistrements de livres anciens résiduels peuvent nécessiter une manipulation manuelle. Les données des objets de version 0.1.23 existantes restent intactes. Voir [évolution de la structure de la base de données](database-schema-evolution.fr.md) et [exigences de sortie actuelle](releases/0.3.1.fr.md)La valeur de base exacte 0.1.13 `doca-2026-10-08-knowledge-books-v2` Il est encore nécessaire d’appliquer l’amélioration de l’histoire explicite ci-dessous. Il faut conserver les bases de données, les objets privés, la configuration et la clé maîtresse des credences originale. +L’hôte actuel utilise la génération `doca-2026-10-12-book-payload-storage-v1`Le startup aligne automatiquement les bases de données 0.1.22 libérées. `doca-2026-10-09-history-storage-v1` Grâce à l’examen/reconciliation des DDL actuels, la nouvelle génération est enregistrée. Toutes les lignes anciennes restent, y compris les résultats du livre SQL ; aucune conversion, nettoyage ou adaptateur pour les anciens objets n’est ajouté. Les enregistrements de livres anciens résiduels peuvent nécessiter une manipulation manuelle. Les données des objets de version 0.1.23 existantes restent intactes. Voir [évolution de la structure de la base de données](database-schema-evolution.fr.md) et [exigences de sortie actuelle](releases/0.3.2.fr.md)La valeur de base exacte 0.1.13 `doca-2026-10-08-knowledge-books-v2` Il est encore nécessaire d’appliquer l’amélioration de l’histoire explicite ci-dessous. Il faut conserver les bases de données, les objets privés, la configuration et la clé maîtresse des credences originale. `DOCA_ORIGIN` C’est l’origine des utilisateurs saisie dans le navigateur. Les protocoles HTTP et HTTPS sont acceptés, y compris en production. Utilisez uniquement l’origine sans sous-réseau, sans requête ou sans fragment ; la barre finale “/” est normalisée. diff --git a/docs/deployment.ja.md b/docs/deployment.ja.md index de44ef30..94a8151d 100644 --- a/docs/deployment.ja.md +++ b/docs/deployment.ja.md @@ -38,7 +38,7 @@ cp docker.env.example .env ファイルストレージも必要です `DOCA_FILE_STORE_ID` そして `DOCA_FILE_STORES_JSON`、提供されている通り `docker.env.example`. サーバー内のパスと認証情報は環境から読み取られる。管理ページは読み取り専用である。詳細はこちらを参照。 [ファイルストレージ](storage.ja.md). -現在のホストは生成を使用している `doca-2026-10-12-book-payload-storage-v1`スタートアップは自動的に0.1.22版のデータベースを整列します。 `doca-2026-10-09-history-storage-v1` 現在のDDLレビュー/調整を通じて新しい世代が記録される。SQLブックの結果を含む、すべての古い行は保持される。何の変換、クリーンアップ、または古い体アダプターも追加されない。残存する古いブック記録は手動で処理が必要になる可能性がある。既存の0.1.23オブジェクトデータは保持される。詳細は [データベース構造の進化](database-schema-evolution.ja.md) そして [現在のリリース要件](releases/0.3.1.ja.md)正確な0.1.13のベースライン `doca-2026-10-08-knowledge-books-v2` 以下の明示的な歴史アップグレードがまだ必要です。データベース、プライベートオブジェクト、設定、および元の認証マスターキーを保持してください。 +現在のホストは生成を使用している `doca-2026-10-12-book-payload-storage-v1`スタートアップは自動的に0.1.22版のデータベースを整列します。 `doca-2026-10-09-history-storage-v1` 現在のDDLレビュー/調整を通じて新しい世代が記録される。SQLブックの結果を含む、すべての古い行は保持される。何の変換、クリーンアップ、または古い体アダプターも追加されない。残存する古いブック記録は手動で処理が必要になる可能性がある。既存の0.1.23オブジェクトデータは保持される。詳細は [データベース構造の進化](database-schema-evolution.ja.md) そして [現在のリリース要件](releases/0.3.2.ja.md)正確な0.1.13のベースライン `doca-2026-10-08-knowledge-books-v2` 以下の明示的な歴史アップグレードがまだ必要です。データベース、プライベートオブジェクト、設定、および元の認証マスターキーを保持してください。 `DOCA_ORIGIN` ブラウザでオリジンを入力する。HTTPとHTTPSが受け入れられ、実際の運用でも同様です。サブパス、クエリ、フラグメントを含まないオリジンのみを使用し、ルートのトレーリングスラッシュは正規化されます。 diff --git a/docs/deployment.ko.md b/docs/deployment.ko.md index 3d444a16..c962f773 100644 --- a/docs/deployment.ko.md +++ b/docs/deployment.ko.md @@ -38,7 +38,7 @@ cp docker.env.example .env 파일 저장도 필요합니다. `DOCA_FILE_STORE_ID` 그리고 `DOCA_FILE_STORES_JSON`제시된 대로 `docker.env.example`. 서버 경로와 자격 정보는 환경에서 읽어오며, 관리 페이지는 읽기 전용입니다. 참조하세요. [파일 저장](storage.ko.md). -현재 호스트는 génération을 사용합니다. `doca-2026-10-12-book-payload-storage-v1`스타트업은 자동으로 0.1.22 버전의 데이터베이스를 정렬합니다. `doca-2026-10-09-history-storage-v1` 현재의 DDL 검토/조정을 거쳐 새로운 세대가 기록됩니다. SQL 책의 결과를 포함한 모든 기존 행은 그대로 유지됩니다; 어떠한 변환, 정리 또는 기존 객체 어댑터도 추가되지 않습니다. 남아있는 기존 책 기록은 수동 처리가 필요할 수 있습니다. 기존의 0.1.23 객체 데이터는 그대로 유지됩니다. 참고하세요. [데이터베이스 구조의 발전](database-schema-evolution.ko.md) 그리고 [현재 출시 요구 사항](releases/0.3.1.ko.md)정확한 0.1.13 기준값 `doca-2026-10-08-knowledge-books-v2` 아래의 명시적인 역사 업그레이드가 여전히 필요합니다. 데이터베이스, 개인 정보, 설정 및 원본 자격 증명 마스터 키를 보존해야 합니다. +현재 호스트는 génération을 사용합니다. `doca-2026-10-12-book-payload-storage-v1`스타트업은 자동으로 0.1.22 버전의 데이터베이스를 정렬합니다. `doca-2026-10-09-history-storage-v1` 현재의 DDL 검토/조정을 거쳐 새로운 세대가 기록됩니다. SQL 책의 결과를 포함한 모든 기존 행은 그대로 유지됩니다; 어떠한 변환, 정리 또는 기존 객체 어댑터도 추가되지 않습니다. 남아있는 기존 책 기록은 수동 처리가 필요할 수 있습니다. 기존의 0.1.23 객체 데이터는 그대로 유지됩니다. 참고하세요. [데이터베이스 구조의 발전](database-schema-evolution.ko.md) 그리고 [현재 출시 요구 사항](releases/0.3.2.ko.md)정확한 0.1.13 기준값 `doca-2026-10-08-knowledge-books-v2` 아래의 명시적인 역사 업그레이드가 여전히 필요합니다. 데이터베이스, 개인 정보, 설정 및 원본 자격 증명 마스터 키를 보존해야 합니다. `DOCA_ORIGIN` 브라우저에서 원본 origin을 입력합니다. 프로덕션 환경에서도 HTTP와 HTTPS가 허용됩니다. 서브패스, 쿼리, 프래그먼트가 없는 원본만 사용하세요; 루트에 trailing slash는 정규화됩니다. diff --git a/docs/deployment.md b/docs/deployment.md index ab8a853e..563e75e8 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -30,7 +30,7 @@ Edit `.env` before the first start. File storage also requires `DOCA_FILE_STORE_ID` and `DOCA_FILE_STORES_JSON`, as provided by `docker.env.example`. Backend paths and credentials are read from the environment; the administration page is read-only. See [file storage](storage.md). -The current host uses generation `doca-2026-10-12-book-payload-storage-v1`. Startup automatically aligns released 0.1.22 databases on `doca-2026-10-09-history-storage-v1` through current-DDL review/reconciliation and records the new generation. All old rows remain, including SQL book outcomes; no body conversion, cleanup or old-body adapter is added. Residual old book records can require manual handling. Existing 0.1.23 object data remains. See [database structure evolution](database-schema-evolution.md) and [current release requirements](releases/0.3.1.md). The exact 0.1.13 baseline `doca-2026-10-08-knowledge-books-v2` still needs the explicit history upgrade below. Preserve databases, private objects, configuration and the original credential master key. +The current host uses generation `doca-2026-10-12-book-payload-storage-v1`. Startup automatically aligns released 0.1.22 databases on `doca-2026-10-09-history-storage-v1` through current-DDL review/reconciliation and records the new generation. All old rows remain, including SQL book outcomes; no body conversion, cleanup or old-body adapter is added. Residual old book records can require manual handling. Existing 0.1.23 object data remains. See [database structure evolution](database-schema-evolution.md) and [current release requirements](releases/0.3.2.md). The exact 0.1.13 baseline `doca-2026-10-08-knowledge-books-v2` still needs the explicit history upgrade below. Preserve databases, private objects, configuration and the original credential master key. `DOCA_ORIGIN` is the origin users type in the browser. HTTP and HTTPS are accepted, including in production. Use only the origin without a subpath, query, or fragment; a root trailing slash is normalized. @@ -82,6 +82,16 @@ Document rendering also needs its deployment checks: this checkout adds LibreOff SQLite, uploaded files, and the AI database are stored in the `doca_data` volume. The database must be empty on first start. A non-empty database must use a supported compatibility generation; reviewed additive changes are reconciled automatically, while destructive or semantic differences are reported for review. Do not delete a database that already contains users. +## Server release checks + +In **Administration → Site and services → Site profile**, Doca shows the installed server version. Automatic checks are on by default. When due, the host sends its version and a random deployment ID to the official plugin store at most once per hour. Turn off the switch to stop new requests. The local setting and ID are shared by replicas using the same database. The official store endpoint is specified for a separate rollout. [Release check protocol](doca-release-check-protocol.md) + +When a newer release is available, read its release notes and back up the deployment. Update the `image` of the `doca` service in your existing Compose file to the exact tag shown. Keep the original project name, volumes and credentials. Run the command below from the original deployment directory. + +```sh +docker compose pull doca && docker compose up -d --no-deps doca +``` + ## Reverse proxy Terminate TLS in Caddy or Nginx on the same host and forward to `127.0.0.1:39120`. diff --git a/docs/deployment.ru.md b/docs/deployment.ru.md index 7e103475..978219be 100644 --- a/docs/deployment.ru.md +++ b/docs/deployment.ru.md @@ -38,7 +38,7 @@ cp docker.env.example .env Хранение файлов также требует `DOCA_FILE_STORE_ID` и `DOCA_FILE_STORES_JSON`, как указано `docker.env.example`Пути и учетные данные сервера считываются из окружения; страница управления доступна только для чтения. Смотрите [хранение файлов](storage.ru.md). -Текущий хост использует генерацию `doca-2026-10-12-book-payload-storage-v1`Стартап автоматически синхронизирует выпущенные базы данных версии 0.1.22. `doca-2026-10-09-history-storage-v1` После обзора/согласования текущих DDL-запросов и регистрации нового поколения. Все старые строки остаются, включая результаты работы SQL-книги; никаких преобразований, очисток или адаптеров старых данных добавлено не производится. Остатки старых записей из книги могут требовать ручной обработки. Существующие данные объектов версии 0.1.23 остаются. Смотрите. [Эволюция структуры базы данных](database-schema-evolution.ru.md) и [Требования к текущему выпуску](releases/0.3.1.ru.md)Точный базовый вариант 0.1.13 `doca-2026-10-08-knowledge-books-v2` Требуется явная обновление истории ниже. Необходимо сохранить базы данных, приватные объекты, конфигурацию и оригинальный ключ-мастер. +Текущий хост использует генерацию `doca-2026-10-12-book-payload-storage-v1`Стартап автоматически синхронизирует выпущенные базы данных версии 0.1.22. `doca-2026-10-09-history-storage-v1` После обзора/согласования текущих DDL-запросов и регистрации нового поколения. Все старые строки остаются, включая результаты работы SQL-книги; никаких преобразований, очисток или адаптеров старых данных добавлено не производится. Остатки старых записей из книги могут требовать ручной обработки. Существующие данные объектов версии 0.1.23 остаются. Смотрите. [Эволюция структуры базы данных](database-schema-evolution.ru.md) и [Требования к текущему выпуску](releases/0.3.2.ru.md)Точный базовый вариант 0.1.13 `doca-2026-10-08-knowledge-books-v2` Требуется явная обновление истории ниже. Необходимо сохранить базы данных, приватные объекты, конфигурацию и оригинальный ключ-мастер. `DOCA_ORIGIN` Источник — это тип, указанный пользователем в браузере. Принимаются HTTP и HTTPS, включая случаи использования в продакшене. Используйте только источник без подпатрона, запроса или фрагмента; корневой слеш в конце считается нормальным. diff --git a/docs/deployment.zh-CN.md b/docs/deployment.zh-CN.md index 5ca7ed2c..f17812a0 100644 --- a/docs/deployment.zh-CN.md +++ b/docs/deployment.zh-CN.md @@ -28,7 +28,7 @@ cp docker.env.example .env 文件存储还需要 `DOCA_FILE_STORE_ID` 和 `DOCA_FILE_STORES_JSON`,示例见 `docker.env.example`。后端路径和密钥通过环境变量提供,管理页只读展示。见[文件存储](storage.zh-CN.md)。 -当前宿主使用数据库代际 `doca-2026-10-12-book-payload-storage-v1`。对已发布 0.1.22 的 `doca-2026-10-09-history-storage-v1`,启动时以最新 DDL 检查并对齐结构、记录新代际;旧 SQL 知识册成果等全部业务行原样保留,不增加正文转换、单独清理或旧正文适配。残留旧知识册记录可能需人工处理,已有 0.1.23 对象存储数据保留。见[数据库结构演进](database-schema-evolution.zh-CN.md)及[当前发行要求](releases/0.3.1.zh-CN.md)。0.1.13 的准确基线 `doca-2026-10-08-knowledge-books-v2` 仍需按下方步骤显式升级历史存储。保留原数据库、私有对象、配置和凭证主密钥。 +当前宿主使用数据库代际 `doca-2026-10-12-book-payload-storage-v1`。对已发布 0.1.22 的 `doca-2026-10-09-history-storage-v1`,启动时以最新 DDL 检查并对齐结构、记录新代际;旧 SQL 知识册成果等全部业务行原样保留,不增加正文转换、单独清理或旧正文适配。残留旧知识册记录可能需人工处理,已有 0.1.23 对象存储数据保留。见[数据库结构演进](database-schema-evolution.zh-CN.md)及[当前发行要求](releases/0.3.2.zh-CN.md)。0.1.13 的准确基线 `doca-2026-10-08-knowledge-books-v2` 仍需按下方步骤显式升级历史存储。保留原数据库、私有对象、配置和凭证主密钥。 `DOCA_ORIGIN` 是用户在浏览器里打开的地址。包括生产环境在内,均支持 HTTP 和 HTTPS。不要加子路径、查询参数或片段;根路径末尾斜杠会被规范化。 @@ -80,6 +80,16 @@ curl -fsS -H 'Host: docs.example.com' http://127.0.0.1:39120/health SQLite、上传文件和 AI 数据库保存在 `doca_data` 卷。首次启动时数据库必须是空的。非空数据库必须属于支持的兼容代际;已审定的新增结构会自动补齐,破坏性或语义差异会报告待确认。不要删除已经有用户的数据库。 +## 服务端版本检查 + +在**管理后台 → 站点与服务 → 站点信息**查看已安装的服务端版本。自动检查默认开启,宿主每小时最多向官方插件商店发送一次当前版本和随机部署标识。关闭开关后停止发起新的请求。使用同一数据库的所有副本共享开关和标识。正式商店接口按协议另行上线。[版本检查协议](doca-release-check-protocol.md) + +发现新版本时,先阅读发布说明并备份。将现有 Compose 文件里 `doca` 服务的 `image` 改为页面给出的镜像标签,保留项目名、存储卷和凭据。在原部署目录运行以下命令。 + +```sh +docker compose pull doca && docker compose up -d --no-deps doca +``` + ## 反向代理 在同一台机器上用 Caddy 或 Nginx 终止 TLS,并转发到 `127.0.0.1:39120`。 diff --git a/docs/deployment.zh-Hant.md b/docs/deployment.zh-Hant.md index 8a99db76..6d49f9c4 100644 --- a/docs/deployment.zh-Hant.md +++ b/docs/deployment.zh-Hant.md @@ -36,7 +36,7 @@ cp docker.env.example .env 檔案儲存還需要 `DOCA_FILE_STORE_ID` 和 `DOCA_FILE_STORES_JSON`,示例見 `docker.env.example`。後端路徑和金鑰透過環境變數提供,管理頁只讀展示。見[檔案儲存](storage.zh-Hant.md)。 -當前宿主使用資料庫代際 `doca-2026-10-12-book-payload-storage-v1`。對已釋出 0.1.22 的 `doca-2026-10-09-history-storage-v1`,啟動時以最新 DDL 檢查並對齊結構、記錄新代際;舊 SQL 知識冊成果等全部業務行原樣保留,不增加正文轉換、單獨清理或舊正文適配。殘留舊知識冊記錄可能需人工處理,已有 0.1.23 物件儲存資料保留。見[資料庫結構演進](database-schema-evolution.zh-Hant.md)及[當前發行要求](releases/0.3.1.zh-Hant.md)。0.1.13 的準確基線 `doca-2026-10-08-knowledge-books-v2` 仍需按下方步驟顯式升級歷史儲存。保留原資料庫、私有物件、配置和憑證主金鑰。 +當前宿主使用資料庫代際 `doca-2026-10-12-book-payload-storage-v1`。對已釋出 0.1.22 的 `doca-2026-10-09-history-storage-v1`,啟動時以最新 DDL 檢查並對齊結構、記錄新代際;舊 SQL 知識冊成果等全部業務行原樣保留,不增加正文轉換、單獨清理或舊正文適配。殘留舊知識冊記錄可能需人工處理,已有 0.1.23 物件儲存資料保留。見[資料庫結構演進](database-schema-evolution.zh-Hant.md)及[當前發行要求](releases/0.3.2.zh-Hant.md)。0.1.13 的準確基線 `doca-2026-10-08-knowledge-books-v2` 仍需按下方步驟顯式升級歷史儲存。保留原資料庫、私有物件、配置和憑證主金鑰。 `DOCA_ORIGIN` 是使用者在瀏覽器裡開啟的地址。包括生產環境在內,均支援 HTTP 和 HTTPS。不要加子路徑、查詢引數或片段;根路徑末尾斜槓會被規範化。 diff --git a/docs/desktop-client.es.md b/docs/desktop-client.es.md index 4b0ce98f..2555edde 100644 --- a/docs/desktop-client.es.md +++ b/docs/desktop-client.es.md @@ -8,7 +8,7 @@ El cliente de escritorio de Doca usa Tauri 2. Incluye la interfaz web de Doca y ## Instalación y conexión -Descarga el instalador para macOS (DMG) o Windows (NSIS o MSI) desde la [versión 0.3.3 de Doca Desktop](https://github.com/workhold/doca/releases/tag/desktop-v0.3.3). Los instaladores se distribuyen sin firma ni notarización. En el primer inicio en macOS, haz clic derecho en la aplicación y selecciona **Abrir**. Windows puede mostrar un aviso de SmartScreen. +Descarga el instalador para macOS (DMG) o Windows (NSIS o MSI) desde la [versión 0.3.4 de Doca Desktop](https://github.com/workhold/doca/releases/tag/desktop-v0.3.4). Los instaladores se distribuyen sin firma ni notarización. En el primer inicio en macOS, haz clic derecho en la aplicación y selecciona **Abrir**. Windows puede mostrar un aviso de SmartScreen.  diff --git a/docs/desktop-client.fr.md b/docs/desktop-client.fr.md index 68550046..83f63756 100644 --- a/docs/desktop-client.fr.md +++ b/docs/desktop-client.fr.md @@ -8,7 +8,7 @@ Le client de bureau Doca utilise Tauri 2. Il embarque l’interface Web de Doca ## Installation et connexion -Téléchargez le programme d’installation pour macOS (DMG) ou Windows (NSIS ou MSI) depuis la [page de Doca Desktop 0.3.3](https://github.com/workhold/doca/releases/tag/desktop-v0.3.3). Ces exécutables sont distribués sans signature ni notarisation. Sur macOS, faites un clic droit puis sélectionnez **Ouvrir** au premier lancement. Windows peut afficher une invitation SmartScreen. +Téléchargez le programme d’installation pour macOS (DMG) ou Windows (NSIS ou MSI) depuis la [page de Doca Desktop 0.3.4](https://github.com/workhold/doca/releases/tag/desktop-v0.3.4). Ces exécutables sont distribués sans signature ni notarisation. Sur macOS, faites un clic droit puis sélectionnez **Ouvrir** au premier lancement. Windows peut afficher une invitation SmartScreen.  diff --git a/docs/desktop-client.ja.md b/docs/desktop-client.ja.md index e224421c..835b083a 100644 --- a/docs/desktop-client.ja.md +++ b/docs/desktop-client.ja.md @@ -8,7 +8,7 @@ Doca デスクトップクライアントは Tauri 2 を使用しています。 ## インストールと接続 -[Doca デスクトップ 0.3.3 のリリースページ](https://github.com/workhold/doca/releases/tag/desktop-v0.3.3)から、macOS 用(DMG)または Windows 用(NSIS/MSI)のインストーラーをダウンロードしてください。このビルドには署名と公証がありません。macOS では初回起動時にアプリを右クリックして**開く**を選びます。Windows では SmartScreen が確認を求める場合があります。 +[Doca デスクトップ 0.3.4 のリリースページ](https://github.com/workhold/doca/releases/tag/desktop-v0.3.4)から、macOS 用(DMG)または Windows 用(NSIS/MSI)のインストーラーをダウンロードしてください。このビルドには署名と公証がありません。macOS では初回起動時にアプリを右クリックして**開く**を選びます。Windows では SmartScreen が確認を求める場合があります。  diff --git a/docs/desktop-client.ko.md b/docs/desktop-client.ko.md index 8702778f..7e7131c0 100644 --- a/docs/desktop-client.ko.md +++ b/docs/desktop-client.ko.md @@ -8,7 +8,7 @@ Doca 데스크톱 클라이언트는 Tauri 2를 사용합니다. Doca 웹 화면 ## 설치 및 연결 -[Doca 데스크톱 0.3.3 릴리스](https://github.com/workhold/doca/releases/tag/desktop-v0.3.3)에서 macOS용(DMG) 또는 Windows용(NSIS 또는 MSI) 설치 파일을 다운로드하세요. 이 빌드는 서명 및 공증 없이 배포됩니다. macOS에서는 처음 실행할 때 앱을 마우스 오른쪽 버튼으로 클릭한 뒤 **열기**를 선택합니다. Windows에서 SmartScreen 메시지가 표시될 수 있습니다. +[Doca 데스크톱 0.3.4 릴리스](https://github.com/workhold/doca/releases/tag/desktop-v0.3.4)에서 macOS용(DMG) 또는 Windows용(NSIS 또는 MSI) 설치 파일을 다운로드하세요. 이 빌드는 서명 및 공증 없이 배포됩니다. macOS에서는 처음 실행할 때 앱을 마우스 오른쪽 버튼으로 클릭한 뒤 **열기**를 선택합니다. Windows에서 SmartScreen 메시지가 표시될 수 있습니다.  diff --git a/docs/desktop-client.md b/docs/desktop-client.md index 67306bbc..4fcb2001 100644 --- a/docs/desktop-client.md +++ b/docs/desktop-client.md @@ -6,7 +6,7 @@ The desktop client in `apps/desktop` uses Tauri 2. It packages the Doca Web fron ## Install and connect -Download the macOS (DMG) or Windows (NSIS/MSI) installer from the [Doca Desktop 0.3.3 release](https://github.com/workhold/doca/releases/tag/desktop-v0.3.3). Current builds are unsigned and lack notarization. On macOS, right-click the app and choose **Open** the first time. Windows may show a SmartScreen prompt. +Download the macOS (DMG) or Windows (NSIS/MSI) installer from the [Doca Desktop 0.3.4 release](https://github.com/workhold/doca/releases/tag/desktop-v0.3.4). Current builds are unsigned and lack notarization. On macOS, right-click the app and choose **Open** the first time. Windows may show a SmartScreen prompt.  diff --git a/docs/desktop-client.ru.md b/docs/desktop-client.ru.md index 0d7a4070..05fc38f0 100644 --- a/docs/desktop-client.ru.md +++ b/docs/desktop-client.ru.md @@ -8,7 +8,7 @@ ## Установка и подключение -Скачайте установщик для macOS (DMG) или Windows (NSIS либо MSI) со [страницы Doca Desktop 0.3.3](https://github.com/workhold/doca/releases/tag/desktop-v0.3.3). Сборки распространяются без подписи и нотариального заверения. При первом запуске на macOS щёлкните по приложению правой кнопкой и выберите **Открыть**. В Windows может появиться предупреждение SmartScreen. +Скачайте установщик для macOS (DMG) или Windows (NSIS либо MSI) со [страницы Doca Desktop 0.3.4](https://github.com/workhold/doca/releases/tag/desktop-v0.3.4). Сборки распространяются без подписи и нотариального заверения. При первом запуске на macOS щёлкните по приложению правой кнопкой и выберите **Открыть**. В Windows может появиться предупреждение SmartScreen.  diff --git a/docs/desktop-client.zh-CN.md b/docs/desktop-client.zh-CN.md index a9c6d8ad..e6028989 100644 --- a/docs/desktop-client.zh-CN.md +++ b/docs/desktop-client.zh-CN.md @@ -6,7 +6,7 @@ ## 安装与连接 -从 [Doca 桌面版 0.3.3](https://github.com/workhold/doca/releases/tag/desktop-v0.3.3) 下载 macOS(DMG)或 Windows(NSIS/MSI)安装包。当前安装包未做签名与公证。macOS 首次打开可使用右键 →「打开」,Windows 可能出现 SmartScreen 提示。 +从 [Doca 桌面版 0.3.4](https://github.com/workhold/doca/releases/tag/desktop-v0.3.4) 下载 macOS(DMG)或 Windows(NSIS/MSI)安装包。当前安装包未做签名与公证。macOS 首次打开可使用右键 →「打开」,Windows 可能出现 SmartScreen 提示。  diff --git a/docs/desktop-client.zh-Hant.md b/docs/desktop-client.zh-Hant.md index cb274b7c..ea9c5ad7 100644 --- a/docs/desktop-client.zh-Hant.md +++ b/docs/desktop-client.zh-Hant.md @@ -8,7 +8,7 @@ Doca 桌面用戶端使用 Tauri 2,內建 Doca 網頁前端和連線管理員 ## 安裝與連線 -從 [Doca 桌面版 0.3.3](https://github.com/workhold/doca/releases/tag/desktop-v0.3.3) 下載 macOS(DMG)或 Windows(NSIS/MSI)安裝程式。此版本尚未簽署或公證。首次在 macOS 啟動時,以右鍵按一下應用程式並選擇**打開**。Windows 可能顯示 SmartScreen 提示。 +從 [Doca 桌面版 0.3.4](https://github.com/workhold/doca/releases/tag/desktop-v0.3.4) 下載 macOS(DMG)或 Windows(NSIS/MSI)安裝程式。此版本尚未簽署或公證。首次在 macOS 啟動時,以右鍵按一下應用程式並選擇**打開**。Windows 可能顯示 SmartScreen 提示。  diff --git a/docs/doca-release-check-protocol.md b/docs/doca-release-check-protocol.md new file mode 100644 index 00000000..8483943a --- /dev/null +++ b/docs/doca-release-check-protocol.md @@ -0,0 +1,68 @@ +# Doca 服务端版本检查协议 v1 + +此文档供 Doca 宿主和官方插件商店实现同一接口。商店接口已在插件商店代码中实现,生产启用需要发布商店服务。Doca 独立维护当前版本、每小时检查的频率和站点开关。 + +## 请求 + +`POST https://store.smartdoca.cc/api/v1/doca/releases/check` + +使用 HTTPS,`Content-Type: application/json`,请求体上限 1 KiB。客户端由 Doca 服务端发起调用。商店无需登录、Cookie、授权头或浏览器 CORS。请求体只接受以下三个字段。 + +```json +{ + "protocolVersion": 1, + "currentVersion": "0.3.1", + "deploymentId": "003b8c8c-a25d-4797-a06b-0f8dc622a7fb" +} +``` + +| 字段 | 约束 | +| --- | --- | +| `protocolVersion` | 整数 `1` | +| `currentVersion` | Doca 服务端实际运行的 SemVer 字符串,上限 80 字符。使用三段数字,不加 `v`。每段最多 9 位,允许预发布后缀和构建元数据 | +| `deploymentId` | 全小写 UUID v4。Doca 随机生成并保存在站点数据库。同一数据库的服务器副本和重启共用该值 | + +站点默认开启。一次请求尝试之后至少等 60 分钟才发下一次,包括超时和失败。管理员关停后,宿主停止领取新的检查任务,关闭前已经领取的检查仍可能到达商店。客户端不跟随重定向。站点地址、名称、账号、文档、令牌和环境变量均不在请求中。 + +## 响应 + +HTTP 200 设置 `Content-Type: application/json`,响应体上限 4 KiB。正文只包含以下两个字段。即使当前版本已经相同或更高,仍返回最新正式版。 + +```json +{ + "protocolVersion": 1, + "latestVersion": "0.4.0" +} +``` + +`latestVersion` 是 Doca **服务端**已正式发布且 Docker 镜像已就绪的最高稳定版本。以正式服务器发布记录和 `docker.io/smartdoca/doca:<版本>` 的发布结果为准。格式为 `X.Y.Z`,每段最多 9 位且无前导零。排除桌面版本、预发布、候选镜像和已经撤回的版本。宿主负责版本比较,并从验证后的版本号生成升级命令与发布说明链接。 + +商店启动时及每 15 分钟刷新版本。读取 Doca 主分支 `compose.yaml` 的 `services.doca.image`,核对正式发布记录和镜像标签,将验证后的版本缓存到本地。缓存自最近一次验证起有效 1 小时,确认发布或镜像失效后移除对应版本。检查请求直接从本地读取。[Doca Compose](https://github.com/workhold/doca/blob/main/compose.yaml) + +| HTTP 状态 | 条件 | 商店行为 | +| --- | --- | --- | +| 400 | JSON 无效、字段不匹配或协议版本不支持 | 拒绝并跳过计数 | +| 413 | 请求体超过限制 | 拒绝并跳过计数 | +| 429 | 请求超过商店的公开接口速率限制 | 拒绝并跳过计数 | +| 503 | 正式版元数据或心跳存储不可用 | 返回暂不可用 | + +错误响应沿用商店的 `{"protocolVersion":1,"error":{"code":"…","message":"…"}}` 格式。宿主对非 200、超时或响应校验失败显示暂不可用,等下一个检查周期。 + +## 在线部署数量 + +商店每接受一次有效检查,按 `deploymentId` 原子更新一个最后见到时间,再返回 HTTP 200。使用商店接收时间,不采信客户端时间。同一个标识的请求只延长有效期。 + +运营端查询最近 3 小时内见到的不同部署数。`lastSeenAt > now - 3h` 为在线,存储应自动过期或定期清理超时记录。只保存去重标识和时间。计数只提供给商店的运营侧,请求地址和账号信息不用于识别部署。公开响应不含计数或其他部署数据。 + +该数字是仍在报告的部署估计值。关停检查、关机或无法访问商店的部署会在最后一次报告满 3 小时后退出统计。复制包含此设置的数据库会复用同一标识。 + +商店管理员还可查询按北京时间计算的今日去重上报数。两项统计只通过商店管理员页面和管理员会话保护的 `GET /api/admin/doca/deployments` 提供。每日去重只保存当天日期和按日计算的标识哈希,次日由定时任务清理。 + +### 商店接入验收 + +- 相同 ID 的重复和并发报告算 1 个。两个不同 ID 即使来自同一地址也算 2 个。 +- 超时满 3 小时的 ID 不计入在线。再次收到有效报告后重新计入。 +- 无效请求不会刷新心跳。客户端版本等于或高于最新版本时仍正常记心跳。 +- 正式服务器版本、桌面版和预发布同时存在时,只返回有正式镜像的服务器稳定版。 + +现有插件目录与更新协议见 [插件商店协议](plugin-store-protocol.zh-CN.md)。 diff --git a/docs/plugin-native.md b/docs/plugin-native.md index 18596ea1..c1b044a0 100644 --- a/docs/plugin-native.md +++ b/docs/plugin-native.md @@ -2,6 +2,8 @@ **English** · [简体中文](plugin-native.zh-CN.md) · [繁體中文](plugin-native.zh-Hant.md) · [日本語](plugin-native.ja.md) · [Français](plugin-native.fr.md) · [한국어](plugin-native.ko.md) · [Español](plugin-native.es.md) · [Русский](plugin-native.ru.md) +The app keeps native query results in memory. Android 0.1.1 removes the obsolete `doca-query-cache.json` query file on startup. + In the native plugin container, `host.ai.open` uses `assistant.open` to open the native personal assistant. Parameters and errors follow the [launch contract](plugin-assistant.md). Prompts and context stay out of navigation URLs; account credentials stay out of the WebView. Prefill requests are consumed in memory under the current account and a one-time launch identifier. Public types come from `@smartdoca/plugin-sdk/native`, exposed through `PluginWebHost.native`. This property is null on Web. The App plugin container provides: diff --git a/docs/plugin-native.zh-CN.md b/docs/plugin-native.zh-CN.md index ce7b0b7b..b1d16ff5 100644 --- a/docs/plugin-native.zh-CN.md +++ b/docs/plugin-native.zh-CN.md @@ -2,6 +2,8 @@ [English](plugin-native.md) · **简体中文** · [繁體中文](plugin-native.zh-Hant.md) · [日本語](plugin-native.ja.md) · [Français](plugin-native.fr.md) · [한국어](plugin-native.ko.md) · [Español](plugin-native.es.md) · [Русский](plugin-native.ru.md) +App 的原生查询结果只保存在内存中。Android 0.1.1 启动时清理旧版 `doca-query-cache.json` 查询文件。 + `host.ai.open` 在原生插件容器通过新增的 `assistant.open` 操作打开原生个人助手。参数和错误语义见[启动契约](plugin-assistant.md)。提示词/上下文不进入导航 URL,账号凭据不进入 WebView;预填请求在内存中按账号和一次性启动标识消费。 公开类型来自 `@smartdoca/plugin-sdk/native`,通过 `PluginWebHost.native` 使用。在 Web 为 null;App 插件容器中提供: diff --git a/docs/plugin-store-protocol.md b/docs/plugin-store-protocol.md index fdab330f..9663283f 100644 --- a/docs/plugin-store-protocol.md +++ b/docs/plugin-store-protocol.md @@ -8,6 +8,8 @@ ZIP/npm installation, shared archives, multi-instance startup restoration, remot ## 1. Responsibilities and deployment +The official store's Doca server release checks and deployment heartbeats use a dedicated endpoint. [Doca release check protocol](doca-release-check-protocol.md) + - The npm registry distributes complete precompiled packages. The store has no ZIP-download endpoint; review must inspect actual npm package bytes. - The remote store owns metadata, categories, releases, approval/withdrawal, likes/download statistics, and rich-text details. - Doca owns administrator authorization, installation transactions, integrity verification, shared archives, running versions, Web/App entries, and layouts. diff --git a/docs/plugin-store-protocol.zh-CN.md b/docs/plugin-store-protocol.zh-CN.md index 3d21a003..8585c049 100644 --- a/docs/plugin-store-protocol.zh-CN.md +++ b/docs/plugin-store-protocol.zh-CN.md @@ -8,6 +8,8 @@ ## 1. 职责和部署 +官方商店通过独立接口提供 Doca 服务端版本检查和部署心跳。[Doca 版本检查协议](doca-release-check-protocol.md) + - npm registry 分发完整、预编译的插件包。商城不提供 ZIP 下载接口,但审核系统必须检查具体 npm 包字节。 - 远端商城维护插件资料、分类、版本目录、审核/撤回状态、点赞与下载统计、富文本详情。 - Doca 维护管理员权限、安装事务、完整性校验、共享归档、运行版本、Web/App 入口和布局配置。 diff --git a/docs/releases/0.3.2.es.md b/docs/releases/0.3.2.es.md new file mode 100644 index 00000000..305197d8 --- /dev/null +++ b/docs/releases/0.3.2.es.md @@ -0,0 +1,7 @@ +# Doca 0.3.2 · Móvil, espacio de trabajo y actualizaciones + +Android 0.1.1 incorpora la lectura reciente, un menú de cuenta, el cambio de servidor, notificaciones, carga de fotos y referencias a documentos en el asistente. Descarga **Doca-Android-0.1.1.apk** desde la publicación de GitHub. + +El espacio de trabajo se adapta a pantallas pequeñas. Toca dos veces una celda para editarla. Las carpetas indican el progreso al abrirse y el panel de administración muestra las actualizaciones del servidor. + +Un nuevo inicio de sesión de Android no caduca automáticamente. Las sesiones anteriores conservan su plazo. El cierre de sesión, el cambio de contraseña y la revocación administrativa siguen aplicándose. Usa el proyecto de Compose, los volúmenes, la base de datos y la clave existentes con `smartdoca/doca:0.3.2`. diff --git a/docs/releases/0.3.2.fr.md b/docs/releases/0.3.2.fr.md new file mode 100644 index 00000000..e7e3e672 --- /dev/null +++ b/docs/releases/0.3.2.fr.md @@ -0,0 +1,7 @@ +# Doca 0.3.2 · Mobile, espace de travail et mises à jour + +Android 0.1.1 propose la reprise de lecture, un menu de compte, le changement de serveur, les notifications, l’envoi de photos et les références aux documents dans l’assistant IA. Téléchargez **Doca-Android-0.1.1.apk** depuis la publication GitHub. + +L’espace de travail adopte une disposition compacte sur les petits écrans. Touchez deux fois une cellule pour la modifier. L’ouverture d’un dossier affiche sa progression et l’administration indique les mises à jour du serveur. + +Une nouvelle connexion Android n’expire pas automatiquement. Les sessions précédentes gardent leur durée de vie. La déconnexion, le changement de mot de passe et la révocation restent applicables. Utilisez le projet Compose, les volumes, la base de données et la clé existants avec `smartdoca/doca:0.3.2`. diff --git a/docs/releases/0.3.2.ja.md b/docs/releases/0.3.2.ja.md new file mode 100644 index 00000000..f17e448f --- /dev/null +++ b/docs/releases/0.3.2.ja.md @@ -0,0 +1,7 @@ +# Doca 0.3.2 · モバイル、ワークスペース、更新確認 + +Android 0.1.1 に閲覧再開、アカウントメニュー、サーバー切り替え、通知、写真のアップロード、AI チャットでの文書参照を追加しました。GitHub Release から **Doca-Android-0.1.1.apk** を入手できます。 + +狭い画面にはコンパクトなレイアウトを使います。セルのダブルタップで編集でき、フォルダーを開くと読み込み状態が表示されます。管理画面でサーバーの更新を確認できます。 + +Android から新たにログインすると自動で期限切れになりません。既存セッションの期限は継続し、ログアウト、パスワード変更、管理者による取り消しが適用されます。既存の Compose プロジェクト、ボリューム、データベース、鍵を使って `smartdoca/doca:0.3.2` に更新します。 diff --git a/docs/releases/0.3.2.ko.md b/docs/releases/0.3.2.ko.md new file mode 100644 index 00000000..5da438da --- /dev/null +++ b/docs/releases/0.3.2.ko.md @@ -0,0 +1,7 @@ +# Doca 0.3.2 · 모바일, 작업 공간 및 버전 확인 + +Android 0.1.1에서 이어 읽기, 계정 메뉴, 서버 전환, 알림, 사진 업로드와 AI 문서 참조를 사용할 수 있습니다. GitHub 릴리스에서 **Doca-Android-0.1.1.apk**를 다운로드하세요. + +작은 화면에 맞춰 작업 공간이 간결해집니다. 셀을 두 번 눌러 편집하고 폴더를 여는 동안 진행 상태를 확인할 수 있습니다. 관리 화면에서 서버 업데이트를 확인할 수 있습니다. + +Android에서 새로 로그인하면 자동 만료되지 않습니다. 기존 세션은 원래 만료 정책을 따르며 로그아웃, 비밀번호 변경과 관리자의 세션 취소는 계속 적용됩니다. 기존 Compose 프로젝트, 볼륨, 데이터베이스와 키를 사용하여 `smartdoca/doca:0.3.2`로 업그레이드하세요. diff --git a/docs/releases/0.3.2.md b/docs/releases/0.3.2.md new file mode 100644 index 00000000..67d2bc54 --- /dev/null +++ b/docs/releases/0.3.2.md @@ -0,0 +1,16 @@ +# Doca 0.3.2 · Mobile, workspace and release checks + +[简体中文](https://workhold.github.io/doca/#/zh-cn/releases/0.3.2) · [繁體中文](https://workhold.github.io/doca/#/zh-hant/releases/0.3.2) · [日本語](https://workhold.github.io/doca/#/ja/releases/0.3.2) · [Français](https://workhold.github.io/doca/#/fr/releases/0.3.2) · [한국어](https://workhold.github.io/doca/#/ko/releases/0.3.2) · [Español](https://workhold.github.io/doca/#/es/releases/0.3.2) · [Русский](https://workhold.github.io/doca/#/ru/releases/0.3.2) + +- The Android app adds Continue reading, an account menu with backend switching and notifications, camera and photo uploads, and document references in the AI assistant. Install **Doca-Android-0.1.1.apk** from the GitHub release. +- On small screens the workspace uses a compact layout. Touch users can pan a spreadsheet and double-tap a cell to edit it. File views show progress while opening a folder. +- Site information in administration displays the installed server version and checks the official plugin store for a stable update. Administrators can turn off scheduled checks. +- The desktop installers include the updated workspace in Doca Desktop 0.3.4. + +## Upgrade + +Use `smartdoca/doca:0.3.2` with the existing Compose project name, volumes, database, private files and credential master key. [Deployment guide](https://workhold.github.io/doca/#/en/operations/deployment) + +Android 0.1.1 rebuilds native queries in memory and removes the disposable query file from previous installations. Saved backends and logins, plugin data and documents are retained. + +New Android 0.1.1 password sign-ins on Doca 0.3.2 have no automatic expiry. Sign out while connected so the server can revoke the credential. Password changes and administrator revocation still apply. Previously issued sessions retain their original lifetime. Sign in again on Android to use the new policy. diff --git a/docs/releases/0.3.2.ru.md b/docs/releases/0.3.2.ru.md new file mode 100644 index 00000000..0c15332b --- /dev/null +++ b/docs/releases/0.3.2.ru.md @@ -0,0 +1,7 @@ +# Doca 0.3.2 · Мобильное приложение, рабочая область и обновления + +В Android 0.1.1 появились продолжение чтения, меню аккаунта, переключение серверов, уведомления, загрузка фотографий и ссылки на документы в чате с ИИ. Скачайте **Doca-Android-0.1.1.apk** из релиза GitHub. + +Для небольших экранов используется компактная рабочая область. Ячейки можно редактировать двойным касанием. При открытии папок отображается загрузка, а в панели администратора — обновления сервера. + +Новый сеанс Android автоматически не истекает. Ранее выданные сеансы сохраняют свой срок. Выход, смена пароля и отзыв администратором продолжают действовать. Используйте прежние проект Compose, тома, базу данных и ключ с образом `smartdoca/doca:0.3.2`. diff --git a/docs/releases/0.3.2.zh-CN.md b/docs/releases/0.3.2.zh-CN.md new file mode 100644 index 00000000..fe7f5018 --- /dev/null +++ b/docs/releases/0.3.2.zh-CN.md @@ -0,0 +1,16 @@ +# Doca 0.3.2 · 手机端、工作台与版本检查 + +[English](https://workhold.github.io/doca/#/en/releases/0.3.2) · [繁體中文](https://workhold.github.io/doca/#/zh-hant/releases/0.3.2) · [日本語](https://workhold.github.io/doca/#/ja/releases/0.3.2) · [Français](https://workhold.github.io/doca/#/fr/releases/0.3.2) · [한국어](https://workhold.github.io/doca/#/ko/releases/0.3.2) · [Español](https://workhold.github.io/doca/#/es/releases/0.3.2) · [Русский](https://workhold.github.io/doca/#/ru/releases/0.3.2) + +- Android App 新增「继续阅读」、「我的」、后端切换和通知,支持拍照或从相册上传文件,也可以给 AI 助手添加文档引用。从 GitHub Release 下载 **Doca-Android-0.1.1.apk** 安装。 +- 窄屏工作台采用紧凑布局。触屏可以滑动浏览表格,双击单元格进入编辑。打开文件夹时显示加载进度。 +- 管理后台「站点信息」显示当前服务端版本,并通过官方插件商店检查稳定版。管理员可以关闭自动检查。 +- 桌面版 0.3.4 随安装包提供更新后的工作台。 + +## 升级 + +切换到 `smartdoca/doca:0.3.2`,沿用原 Compose 项目名、持久卷、数据库、私有文件和凭据主密钥。[部署指南](https://workhold.github.io/doca/#/zh-cn/operations/deployment) + +Android 0.1.1 启动时清理旧版可重建的查询文件,之后在内存中维护查询缓存。已保存的后端和会话、插件数据及文档会保留。 + +Android 0.1.1 在 Doca 0.3.2 上新登录后,会话不会自动到期。主动退出需要连通服务端,由服务端撤销令牌。改密和管理员撤销仍然生效。升级前签发的会话按原有效期继续使用,重新登录一次即可使用新规则。 diff --git a/docs/releases/0.3.2.zh-Hant.md b/docs/releases/0.3.2.zh-Hant.md new file mode 100644 index 00000000..dcfc3823 --- /dev/null +++ b/docs/releases/0.3.2.zh-Hant.md @@ -0,0 +1,7 @@ +# Doca 0.3.2 · 手機端、工作台與版本檢查 + +Android 0.1.1 新增繼續閱讀、帳號選單、後端切換、通知、拍照上傳,以及 AI 文件引用。從 GitHub Release 下載 **Doca-Android-0.1.1.apk**。 + +窄螢幕工作台採用緊湊版面。觸控可滑動表格、點兩下儲存格進入編輯。開啟資料夾時顯示載入進度,管理員可以在站點資訊查看服務端更新。 + +Android 新登入的工作階段不會自動到期。舊工作階段維持原期限,登出、變更密碼和管理員撤銷仍然有效。使用原本的 Compose 專案、持久卷、資料庫和金鑰切換到 `smartdoca/doca:0.3.2`。 diff --git a/docs/site/assets/site.js b/docs/site/assets/site.js index 71233d26..eaec446c 100644 --- a/docs/site/assets/site.js +++ b/docs/site/assets/site.js @@ -50,7 +50,7 @@ }, search: { paths: "auto", - namespace: "doca-docs-0.3.1", + namespace: "doca-docs-0.3.2", pathNamespaces: languages.map(code => "/" + code), placeholder: localizedConfig("search", editions.en.search), noData: localizedConfig("noResults", editions.en.noResults), diff --git a/docs/site/navigation.json b/docs/site/navigation.json index c2aae39f..b44b49af 100644 --- a/docs/site/navigation.json +++ b/docs/site/navigation.json @@ -316,6 +316,12 @@ "en": "Releases", "zh": "发行记录", "pages": [ + [ + "releases/0.3.2", + "0.3.2 · Mobile, workspace and release checks", + "0.3.2 · 手机端、工作台与版本检查", + true + ], [ "releases/0.3.1", "0.3.1 · Administration translations and layout", diff --git a/docs/user-guide.es.md b/docs/user-guide.es.md index e97a4abe..acf77cc1 100644 --- a/docs/user-guide.es.md +++ b/docs/user-guide.es.md @@ -28,7 +28,7 @@ El descubrimiento público, las colecciones personales, los favoritos y las visi ## Archivos, comentarios y notificaciones -En las ventanas estrechas, la vista en columnas del gestor de archivos comienza con el contenido de la carpeta. Seleccione un archivo para previsualizarlo y use el botón de cierre para volver a la carpeta. +El gestor de archivos muestra un indicador mientras carga el contenido de una carpeta. En la vista en columnas, el indicador aparece en la columna de la carpeta abierta y las columnas superiores ya cargadas siguen disponibles. En las ventanas estrechas, la vista en columnas muestra primero el contenido de la carpeta actual. Seleccione un archivo para previsualizarlo y use el botón de cierre para volver a la carpeta. Utilice archivos personales o carpetas compartidas para archivos ordinarios. Las descargas requieren autorización; un ID de objeto no constituye un enlace de descarga público. Los documentos pueden referenciar archivos sin hacer que el directorio de almacenamiento físico sea público. Véase [almacenamiento de archivos](storage.es.md). diff --git a/docs/user-guide.fr.md b/docs/user-guide.fr.md index 1a00b82a..48d64a9b 100644 --- a/docs/user-guide.fr.md +++ b/docs/user-guide.fr.md @@ -28,7 +28,7 @@ La découverte publique, les collections personnelles, les favoris et les visite ## Fichiers, commentaires et notifications -Dans les fenêtres étroites, la vue en colonne du gestionnaire de fichiers commence par le contenu des dossiers. Sélectionnez un fichier pour le visualiser, puis utilisez le bouton « Fermer » pour revenir au dossier. +Le gestionnaire de fichiers affiche un indicateur pendant le chargement du contenu d’un dossier. Dans la vue en colonnes, cet indicateur apparaît dans la colonne du dossier ouvert. Les colonnes parentes déjà chargées restent accessibles. Dans les fenêtres étroites, la vue en colonnes affiche d’abord le contenu du dossier actif. Sélectionnez un fichier pour le visualiser, puis utilisez le bouton « Fermer » pour revenir au dossier. Utilisez des fichiers personnels ou des dossiers partagés pour les fichiers ordinaires. Les téléchargements nécessitent une autorisation ; un ID d’objet n’est pas un lien de téléchargement public. Les documents peuvent faire référence à des fichiers sans rendre le dossier de stockage physique public. Voir [stockage de fichiers](storage.fr.md). diff --git a/docs/user-guide.ja.md b/docs/user-guide.ja.md index cf0579d1..12c2e5f4 100644 --- a/docs/user-guide.ja.md +++ b/docs/user-guide.ja.md @@ -28,7 +28,7 @@ ## ファイル、コメント、通知 -狭いウィンドウでは、ファイルマネージャーの列表示がフォルダ内の内容から始まります。ファイルを選択してプレビューし、閉じるボタンを使ってフォルダに戻ります。 +フォルダを開くと、内容の読み込み中にインジケーターが表示されます。列表示では、開いたフォルダの列にインジケーターが表示され、読み込み済みの親フォルダも引き続き参照できます。狭いウィンドウでは、現在のフォルダの内容が最初に表示されます。ファイルを選択してプレビューし、閉じるボタンを使ってフォルダに戻ります。 通常のファイルには個人用ファイルや共有フォルダを使用しましょう。ダウンロードには承認が必要です。オブジェクトIDは公開されたダウンロードリンクではありません。文書は物理的な保存ディレクトリを公開せずにファイルを参照することができます。詳細は [ファイルストレージ](storage.ja.md). diff --git a/docs/user-guide.ko.md b/docs/user-guide.ko.md index dda7b310..3397d3c8 100644 --- a/docs/user-guide.ko.md +++ b/docs/user-guide.ko.md @@ -28,7 +28,7 @@ ## 파일, 댓글, 알림 -좁은 창에서는 파일 관리자의 열 보기가 폴더 내용으로 시작됩니다. 파일을 선택하여 미리 보고, 닫기 버튼을 사용하여 폴더로 돌아갈 수 있습니다. +폴더를 열면 내용을 불러오는 동안 로딩 표시가 나타납니다. 열 보기에서는 해당 폴더의 열에 표시가 나타나며 이미 불러온 상위 폴더도 계속 탐색할 수 있습니다. 좁은 창에서는 열 보기가 현재 폴더의 내용부터 표시합니다. 파일을 선택하여 미리 보고, 닫기 버튼을 사용하여 폴더로 돌아갈 수 있습니다. 일반 파일은 개인 파일이나 공유 폴더를 사용하세요. 다운로드는 승인이 필요하며, 객체 ID는 공개 다운로드 링크가 아닙니다. 문서는 물리적 저장 디렉터리를 공개하지 않고도 파일을 참조할 수 있습니다. 자세한 내용은... [파일 저장](storage.ko.md). diff --git a/docs/user-guide.md b/docs/user-guide.md index 9e1ffe81..2ce2b8a2 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -20,7 +20,7 @@ Public discovery, personal collections, favorites, and recent visits serve diffe ## Files, comments, and notifications -In narrow windows, the file manager's column view starts with the folder contents. Select a file to preview it and use the close button to return to the folder. +The file manager shows a loading indicator while it retrieves the folder contents. In column view, the indicator appears in the folder's own column and the loaded parent columns remain available. In narrow windows, column view starts with the folder contents. Select a file to preview it and use the close button to return to the folder. Use personal files or shared folders for ordinary files. Downloads pass authorization; an object ID is not a public download link. Documents can reference files without making the physical storage directory public. See [file storage](storage.md). diff --git a/docs/user-guide.ru.md b/docs/user-guide.ru.md index 471c7458..26d45fdc 100644 --- a/docs/user-guide.ru.md +++ b/docs/user-guide.ru.md @@ -28,7 +28,7 @@ ## Файлы, комментарии и уведомления -В узких окнах колоночный вид менеджера файлов начинается с содержимого папки. Выберите файл для предварительного просмотра и нажмите кнопку «Закрыть», чтобы вернуться в папку. +При открытии папки менеджер файлов показывает индикатор загрузки её содержимого. В режиме столбцов индикатор появляется в столбце открываемой папки, а загруженные родительские папки остаются доступны. В узких окнах сначала отображается содержимое текущей папки. Выберите файл для предварительного просмотра и нажмите кнопку «Закрыть», чтобы вернуться в папку. Для обычных файлов используйте личные файлы или общие папки. Загрузки требуют разрешения; ID объекта не является публичным ссылкой на загрузку. Документы могут ссылаться на файлы, не раскрывая физический каталог хранения. Смотрите [хранение файлов](storage.ru.md). diff --git a/docs/user-guide.zh-CN.md b/docs/user-guide.zh-CN.md index 3f5cbbb7..8783579c 100644 --- a/docs/user-guide.zh-CN.md +++ b/docs/user-guide.zh-CN.md @@ -20,7 +20,7 @@ ## 文件、评论与通知 -窄窗口下,文件管理的分栏视图先显示文件夹内容。选中文件可预览,点击关闭按钮回到文件夹。 +打开文件夹时,内容区会显示加载提示。分栏视图在目标文件夹的分栏里显示提示,已加载的父目录仍可浏览。窄窗口下,分栏视图先显示当前文件夹的内容。选中文件可预览,点击关闭按钮回到文件夹。 普通文件放在个人文件或共享文件夹中。下载经过授权,对象 ID 不是公开下载链接。文档可以引用文件,不需要公开物理存储目录。详见[文件存储](storage.zh-CN.md)。 diff --git a/docs/user-guide.zh-Hant.md b/docs/user-guide.zh-Hant.md index 36d44ede..67895223 100644 --- a/docs/user-guide.zh-Hant.md +++ b/docs/user-guide.zh-Hant.md @@ -29,7 +29,7 @@ ## 檔案、評論與通知 -窄視窗下,檔案管理的分欄檢視先顯示資料夾內容。選中檔案可預覽,點選關閉按鈕回到資料夾。 +開啟資料夾時,內容區會顯示載入提示。分欄檢視會在該資料夾所在的欄位顯示提示,仍可瀏覽已載入的上層資料夾。窄視窗下,分欄檢視先顯示目前資料夾的內容。選中檔案可預覽,點選關閉按鈕回到資料夾。 普通檔案放在個人檔案或共享資料夾中。下載經過授權,物件 ID 不是公開下載連結。文件可以引用檔案,不需要公開物理儲存目錄。詳見[檔案儲存](storage.zh-Hant.md)。 diff --git a/package.json b/package.json index 2ab52e9e..0d4d1c94 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "doca", - "version": "0.3.1", + "version": "0.3.2", "license": "MIT", "private": true, "type": "module", diff --git a/packages/i18n/src/catalogs/en.ts b/packages/i18n/src/catalogs/en.ts index 46f39ece..75cc7606 100644 --- a/packages/i18n/src/catalogs/en.ts +++ b/packages/i18n/src/catalogs/en.ts @@ -2838,6 +2838,20 @@ export const en = { "settings.language.hint": "Changes interface text only. Documents, comments, and mail stay as written.", ...localeMessages, + "mobile.home.title": "Home", + "mobile.home.search": "Search documents and files", + "mobile.home.resume": "Continue reading", + "mobile.me.title": "My account", + "mobile.me.backends": "Switch server", + "mobile.me.settings": "Personal settings", + "mobile.me.no.shortcuts": "No additional shortcuts", + "mobile.ai.placeholder": "Send a message…", + "mobile.ai.no.sessions": "No conversations yet", + "mobile.ai.pick.document": "Reference a document", + "mobile.files.album": "Photo library", + "mobile.files.album.permission": "Photo library permission is required to choose images.", + "mobile.files.camera": "Take photo", + "mobile.files.camera.permission": "Camera permission is required to take a photo.", "mobile.settings.title": "Settings", "mobile.settings.currentServer": "Current server", "mobile.settings.signedOut": "Signed out", @@ -3585,6 +3599,20 @@ export const en = { "admin.defaultTimezoneHint": "Used for site date boundaries and shared time rules.", "admin.siteInfo": "Site profile", + "admin.release.heading": "Software version", + "admin.release.installed": "Installed version", + "admin.release.automatic": "Check for updates automatically", + "admin.release.disclosure": "Doca sends its version and a random deployment ID to the official plugin store every hour to check for updates and count online deployments.", + "admin.release.waiting": "Waiting for the next check", + "admin.release.disabled": "Version checks are off", + "admin.release.unavailable": "The official plugin store could not provide release information.", + "admin.release.current": "No newer stable version", + "admin.release.update": "Version {version} is available", + "admin.release.composeHelp": "Read the release notes and back up the deployment. Set the doca service’s image in your existing Compose file to the tag below, then run the command from the original deployment directory.", + "admin.release.copyCommand": "Copy command", + "admin.release.notes": "Release notes", + "admin.release.loadFailed": "Could not load version check settings.", + "admin.release.saveFailed": "Could not save the version check setting.", "admin.experience": "Experience", "admin.files": "Files and storage", "admin.search": "Search", diff --git a/packages/i18n/src/catalogs/es.json b/packages/i18n/src/catalogs/es.json index 9c756c7f..9948ad0b 100644 --- a/packages/i18n/src/catalogs/es.json +++ b/packages/i18n/src/catalogs/es.json @@ -2625,6 +2625,20 @@ "settings.saved": "Salvado", "settings.language": "Idioma", "settings.language.hint": "Solo se modifica el texto de la interfaz. Los documentos, comentarios y correos permanecen tal como están.", + "mobile.home.title": "Inicio", + "mobile.home.search": "Buscar documentos y archivos", + "mobile.home.resume": "Seguir leyendo", + "mobile.me.title": "Mi cuenta", + "mobile.me.backends": "Cambiar de servidor", + "mobile.me.settings": "Configuración personal", + "mobile.me.no.shortcuts": "No hay más accesos directos", + "mobile.ai.placeholder": "Enviar un mensaje…", + "mobile.ai.no.sessions": "Todavía no hay conversaciones", + "mobile.ai.pick.document": "Referenciar un documento", + "mobile.files.album": "Fototeca", + "mobile.files.album.permission": "Se requiere permiso para elegir fotos.", + "mobile.files.camera": "Hacer una foto", + "mobile.files.camera.permission": "Se requiere permiso para usar la cámara.", "mobile.settings.title": "Configuración", "mobile.settings.currentServer": "Servidor actual", "mobile.settings.signedOut": "Desconectado", @@ -3311,6 +3325,20 @@ "admin.defaultTimezone": "Zona horaria predeterminada", "admin.defaultTimezoneHint": "Se utiliza para los límites de fecha del sitio y las reglas de tiempo compartido.", "admin.siteInfo": "Perfil del sitio", + "admin.release.heading": "Versión del software", + "admin.release.installed": "Versión instalada", + "admin.release.automatic": "Buscar actualizaciones automáticamente", + "admin.release.disclosure": "Cada hora, Doca envía su versión y un ID de despliegue aleatorio a la tienda oficial de complementos para buscar actualizaciones y contar los despliegues en línea.", + "admin.release.waiting": "Esperando la próxima comprobación", + "admin.release.disabled": "La comprobación de versiones está desactivada", + "admin.release.unavailable": "La tienda oficial de complementos no pudo proporcionar información sobre la versión.", + "admin.release.current": "No hay una versión estable más reciente", + "admin.release.update": "La versión {version} está disponible", + "admin.release.composeHelp": "Lee las notas de la versión y haz una copia de seguridad del despliegue. En el archivo Compose existente, cambia la imagen del servicio doca por la etiqueta de abajo. Luego ejecuta el comando desde el directorio original del despliegue.", + "admin.release.copyCommand": "Copiar comando", + "admin.release.notes": "Notas de la versión", + "admin.release.loadFailed": "No se pudo cargar la configuración de comprobación de versiones.", + "admin.release.saveFailed": "No se pudo guardar el ajuste de comprobación de versiones.", "admin.experience": "Experiencia", "admin.files": "Archivos y almacenamiento", "admin.search": "Buscar", diff --git a/packages/i18n/src/catalogs/fr.json b/packages/i18n/src/catalogs/fr.json index ba8b454f..d52b49a8 100644 --- a/packages/i18n/src/catalogs/fr.json +++ b/packages/i18n/src/catalogs/fr.json @@ -2625,6 +2625,20 @@ "settings.saved": "Sauvegardé", "settings.language": "Langue", "settings.language.hint": "Seules les textes de l’interface sont modifiés. Les documents, les commentaires et les e-mails restent tels qu’ils étaient.", + "mobile.home.title": "Accueil", + "mobile.home.search": "Rechercher des documents et des fichiers", + "mobile.home.resume": "Reprendre la lecture", + "mobile.me.title": "Mon compte", + "mobile.me.backends": "Changer de serveur", + "mobile.me.settings": "Paramètres personnels", + "mobile.me.no.shortcuts": "Aucun autre raccourci", + "mobile.ai.placeholder": "Envoyer un message…", + "mobile.ai.no.sessions": "Aucune conversation pour le moment", + "mobile.ai.pick.document": "Référencer un document", + "mobile.files.album": "Photothèque", + "mobile.files.album.permission": "L’accès à la photothèque est requis pour choisir des images.", + "mobile.files.camera": "Prendre une photo", + "mobile.files.camera.permission": "L’accès à l’appareil photo est requis pour prendre une photo.", "mobile.settings.title": "Paramètres", "mobile.settings.currentServer": "Serveur actuel", "mobile.settings.signedOut": "Déconnecté", @@ -3311,6 +3325,20 @@ "admin.defaultTimezone": "Fuseau horaire par défaut", "admin.defaultTimezoneHint": "Utilisé pour les limites de date du site et les règles de temps partagé.", "admin.siteInfo": "Profil du site", + "admin.release.heading": "Version du logiciel", + "admin.release.installed": "Version installée", + "admin.release.automatic": "Vérifier automatiquement les mises à jour", + "admin.release.disclosure": "Toutes les heures, Doca envoie sa version et un identifiant de déploiement aléatoire à la boutique officielle de plugins pour vérifier les mises à jour et compter les déploiements en ligne.", + "admin.release.waiting": "En attente de la prochaine vérification", + "admin.release.disabled": "La vérification des mises à jour est désactivée", + "admin.release.unavailable": "La boutique officielle de plugins n’a pas pu fournir les informations de version.", + "admin.release.current": "Aucune version stable plus récente", + "admin.release.update": "La version {version} est disponible", + "admin.release.composeHelp": "Lisez les notes de version et sauvegardez le déploiement. Dans votre fichier Compose existant, attribuez au service doca l’image ci-dessous, puis exécutez la commande depuis le répertoire de déploiement d’origine.", + "admin.release.copyCommand": "Copier la commande", + "admin.release.notes": "Notes de version", + "admin.release.loadFailed": "Impossible de charger les paramètres de vérification des mises à jour.", + "admin.release.saveFailed": "Impossible d’enregistrer le paramètre de vérification des mises à jour.", "admin.experience": "Expérience", "admin.files": "Fichiers et stockage", "admin.search": "Rechercher", diff --git a/packages/i18n/src/catalogs/ja.json b/packages/i18n/src/catalogs/ja.json index d3ebfbde..db20398f 100644 --- a/packages/i18n/src/catalogs/ja.json +++ b/packages/i18n/src/catalogs/ja.json @@ -2625,6 +2625,20 @@ "settings.saved": "救われた", "settings.language": "言語", "settings.language.hint": "インターフェースのテキストのみを変更します。文書、コメント、メールはそのまま保持されます。", + "mobile.home.title": "ホーム", + "mobile.home.search": "文書やファイルを検索", + "mobile.home.resume": "続きを読む", + "mobile.me.title": "マイページ", + "mobile.me.backends": "サーバーを切り替える", + "mobile.me.settings": "個人設定", + "mobile.me.no.shortcuts": "他のショートカットはありません", + "mobile.ai.placeholder": "メッセージを送信…", + "mobile.ai.no.sessions": "会話はまだありません", + "mobile.ai.pick.document": "文書を参照", + "mobile.files.album": "写真ライブラリ", + "mobile.files.album.permission": "写真を選ぶにはライブラリへのアクセスを許可してください。", + "mobile.files.camera": "写真を撮る", + "mobile.files.camera.permission": "写真を撮るにはカメラへのアクセスを許可してください。", "mobile.settings.title": "設定", "mobile.settings.currentServer": "現在のサーバー", "mobile.settings.signedOut": "ログアウト中", @@ -3311,6 +3325,20 @@ "admin.defaultTimezone": "デフォルト時区", "admin.defaultTimezoneHint": "サイトの日付境界や共有時間ルールに使用されます。", "admin.siteInfo": "サイトプロフィール", + "admin.release.heading": "ソフトウェアのバージョン", + "admin.release.installed": "現在のバージョン", + "admin.release.automatic": "更新を自動で確認", + "admin.release.disclosure": "Doca は 1 時間ごとに現在のバージョンとランダムなデプロイ ID を公式プラグインストアへ送信し、更新の確認と稼働中のデプロイの集計を行います。", + "admin.release.waiting": "次回の確認を待機中", + "admin.release.disabled": "更新の確認はオフです", + "admin.release.unavailable": "公式プラグインストアからバージョン情報を取得できませんでした。", + "admin.release.current": "新しい安定版はありません", + "admin.release.update": "バージョン {version} を利用できます", + "admin.release.composeHelp": "リリースノートを確認し、バックアップを取ってください。既存の Compose ファイルで doca サービスのイメージを下のタグに変更し、元のデプロイディレクトリでコマンドを実行します。", + "admin.release.copyCommand": "コマンドをコピー", + "admin.release.notes": "リリースノート", + "admin.release.loadFailed": "更新確認の設定を読み込めませんでした。", + "admin.release.saveFailed": "更新確認の設定を保存できませんでした。", "admin.experience": "経験", "admin.files": "ファイルとストレージ", "admin.search": "検索", diff --git a/packages/i18n/src/catalogs/ko.json b/packages/i18n/src/catalogs/ko.json index 74787f82..b0448f1b 100644 --- a/packages/i18n/src/catalogs/ko.json +++ b/packages/i18n/src/catalogs/ko.json @@ -2625,6 +2625,20 @@ "settings.saved": "구조됨", "settings.language": "언어", "settings.language.hint": "인터페이스 텍스트만 변경됩니다. 문서, 코멘트, 이메일은 그대로 유지됩니다.", + "mobile.home.title": "홈", + "mobile.home.search": "문서 및 파일 검색", + "mobile.home.resume": "계속 읽기", + "mobile.me.title": "내 계정", + "mobile.me.backends": "서버 전환", + "mobile.me.settings": "개인 설정", + "mobile.me.no.shortcuts": "추가 바로가기가 없습니다", + "mobile.ai.placeholder": "메시지 보내기…", + "mobile.ai.no.sessions": "아직 대화가 없습니다", + "mobile.ai.pick.document": "문서 참조", + "mobile.files.album": "사진 보관함", + "mobile.files.album.permission": "이미지를 선택하려면 사진 접근 권한이 필요합니다.", + "mobile.files.camera": "사진 찍기", + "mobile.files.camera.permission": "사진을 찍으려면 카메라 권한이 필요합니다.", "mobile.settings.title": "설정", "mobile.settings.currentServer": "현재 서버", "mobile.settings.signedOut": "로그아웃됨", @@ -3311,6 +3325,20 @@ "admin.defaultTimezone": "기본 시간대", "admin.defaultTimezoneHint": "사이트 기간 경계와 공유 시간 규칙에 사용됩니다.", "admin.siteInfo": "사이트 프로필", + "admin.release.heading": "소프트웨어 버전", + "admin.release.installed": "설치된 버전", + "admin.release.automatic": "자동으로 업데이트 확인", + "admin.release.disclosure": "Doca는 매시간 현재 버전과 무작위 배포 ID를 공식 플러그인 스토어에 보내 업데이트를 확인하고 온라인 배포 수를 집계합니다.", + "admin.release.waiting": "다음 확인 대기 중", + "admin.release.disabled": "버전 확인이 꺼져 있습니다", + "admin.release.unavailable": "공식 플러그인 스토어에서 버전 정보를 가져오지 못했습니다.", + "admin.release.current": "더 새로운 안정 버전이 없습니다", + "admin.release.update": "버전 {version}을 사용할 수 있습니다", + "admin.release.composeHelp": "릴리스 정보를 읽고 배포를 백업하세요. 기존 Compose 파일에서 doca 서비스의 이미지를 아래 태그로 변경한 뒤 원래 배포 디렉터리에서 명령을 실행하세요.", + "admin.release.copyCommand": "명령 복사", + "admin.release.notes": "릴리스 정보", + "admin.release.loadFailed": "버전 확인 설정을 불러오지 못했습니다.", + "admin.release.saveFailed": "버전 확인 설정을 저장하지 못했습니다.", "admin.experience": "경험", "admin.files": "파일과 저장소", "admin.search": "검색", diff --git a/packages/i18n/src/catalogs/ru.json b/packages/i18n/src/catalogs/ru.json index ee603522..8569c13c 100644 --- a/packages/i18n/src/catalogs/ru.json +++ b/packages/i18n/src/catalogs/ru.json @@ -2625,6 +2625,20 @@ "settings.saved": "Спасено", "settings.language": "Язык", "settings.language.hint": "Изменяются только тексты интерфейса. Документы, комментарии и электронные письма остаются такими, какие были.", + "mobile.home.title": "Главная", + "mobile.home.search": "Поиск документов и файлов", + "mobile.home.resume": "Продолжить чтение", + "mobile.me.title": "Мой аккаунт", + "mobile.me.backends": "Сменить сервер", + "mobile.me.settings": "Личные настройки", + "mobile.me.no.shortcuts": "Других ярлыков нет", + "mobile.ai.placeholder": "Отправить сообщение…", + "mobile.ai.no.sessions": "Пока нет чатов", + "mobile.ai.pick.document": "Добавить ссылку на документ", + "mobile.files.album": "Фотогалерея", + "mobile.files.album.permission": "Чтобы выбрать изображение, разрешите доступ к фотогалерее.", + "mobile.files.camera": "Сделать фото", + "mobile.files.camera.permission": "Чтобы сделать фото, разрешите доступ к камере.", "mobile.settings.title": "Настройки", "mobile.settings.currentServer": "Текущий сервер", "mobile.settings.signedOut": "Выключен", @@ -3311,6 +3325,20 @@ "admin.defaultTimezone": "Подстановочный часовой пояс", "admin.defaultTimezoneHint": "Используется для границ дат сайта и правил совместного времени.", "admin.siteInfo": "Профиль сайта", + "admin.release.heading": "Версия программы", + "admin.release.installed": "Установленная версия", + "admin.release.automatic": "Автоматически проверять обновления", + "admin.release.disclosure": "Каждый час Doca отправляет текущую версию и случайный идентификатор развёртывания в официальный магазин плагинов для проверки обновлений и подсчёта работающих развёртываний.", + "admin.release.waiting": "Ожидание следующей проверки", + "admin.release.disabled": "Проверка обновлений отключена", + "admin.release.unavailable": "Официальный магазин плагинов не предоставил сведения о версии.", + "admin.release.current": "Более новой стабильной версии нет", + "admin.release.update": "Доступна версия {version}", + "admin.release.composeHelp": "Прочитайте примечания к выпуску и создайте резервную копию. Укажите приведённый ниже образ для сервиса doca в существующем файле Compose, затем выполните команду из исходного каталога развёртывания.", + "admin.release.copyCommand": "Копировать команду", + "admin.release.notes": "Примечания к выпуску", + "admin.release.loadFailed": "Не удалось загрузить настройки проверки обновлений.", + "admin.release.saveFailed": "Не удалось сохранить настройку проверки обновлений.", "admin.experience": "Опыт", "admin.files": "Файлы и хранение", "admin.search": "Поиск", diff --git a/packages/i18n/src/catalogs/zh-Hant.json b/packages/i18n/src/catalogs/zh-Hant.json index 98d703bf..d4ee8a5b 100644 --- a/packages/i18n/src/catalogs/zh-Hant.json +++ b/packages/i18n/src/catalogs/zh-Hant.json @@ -2625,6 +2625,20 @@ "settings.saved": "已自動儲存", "settings.language": "語言", "settings.language.hint": "只切換介面文字,不翻譯文件、評論和郵件正文。", + "mobile.home.title": "首頁", + "mobile.home.search": "搜尋文件和檔案", + "mobile.home.resume": "繼續閱讀", + "mobile.me.title": "我的", + "mobile.me.backends": "切換後端", + "mobile.me.settings": "個人設定", + "mobile.me.no.shortcuts": "暫無其他入口", + "mobile.ai.placeholder": "傳送訊息…", + "mobile.ai.no.sessions": "暫無對話", + "mobile.ai.pick.document": "引用文件", + "mobile.files.album": "從相簿選擇", + "mobile.files.album.permission": "需要相簿權限才能選擇圖片。", + "mobile.files.camera": "拍照", + "mobile.files.camera.permission": "需要相機權限才能拍照。", "mobile.settings.title": "設定", "mobile.settings.currentServer": "當前伺服器", "mobile.settings.signedOut": "未登入", @@ -3311,6 +3325,20 @@ "admin.defaultTimezone": "預設時區", "admin.defaultTimezoneHint": "用於站點日期邊界及通用時間規則。", "admin.siteInfo": "站點資訊", + "admin.release.heading": "軟體版本", + "admin.release.installed": "目前版本", + "admin.release.automatic": "自動檢查更新", + "admin.release.disclosure": "每小時向官方外掛市集傳送目前版本和隨機部署識別碼,用於檢查更新並統計線上部署。", + "admin.release.waiting": "等待下一次檢查", + "admin.release.disabled": "已關閉版本檢查", + "admin.release.unavailable": "暫時無法從官方外掛市集取得版本資訊。", + "admin.release.current": "目前沒有更新的正式版", + "admin.release.update": "有新版本 {version} 可用", + "admin.release.composeHelp": "請先閱讀發行說明並備份。將現有 Compose 檔案中 doca 服務的映像改成下方標籤,再從原部署目錄執行命令。", + "admin.release.copyCommand": "複製命令", + "admin.release.notes": "發行說明", + "admin.release.loadFailed": "無法讀取版本檢查設定。", + "admin.release.saveFailed": "無法儲存版本檢查設定。", "admin.experience": "使用者體驗", "admin.files": "檔案與儲存", "admin.search": "搜尋與發現", diff --git a/packages/i18n/src/catalogs/zh.ts b/packages/i18n/src/catalogs/zh.ts index de6cfb4b..756f4ca3 100644 --- a/packages/i18n/src/catalogs/zh.ts +++ b/packages/i18n/src/catalogs/zh.ts @@ -2628,6 +2628,20 @@ export const zh = { "settings.language": "语言", "settings.language.hint": "只切换界面文字,不翻译文档、评论和邮件正文。", ...localeMessages, + "mobile.home.title": "首页", + "mobile.home.search": "搜索文档和文件", + "mobile.home.resume": "继续阅读", + "mobile.me.title": "我的", + "mobile.me.backends": "切换后端", + "mobile.me.settings": "个人设置", + "mobile.me.no.shortcuts": "暂无更多入口", + "mobile.ai.placeholder": "发消息…", + "mobile.ai.no.sessions": "暂无会话", + "mobile.ai.pick.document": "引用文档", + "mobile.files.album": "从相册选择", + "mobile.files.album.permission": "需要相册权限才能选择图片。", + "mobile.files.camera": "拍照", + "mobile.files.camera.permission": "需要相机权限才能拍照。", "mobile.settings.title": "设置", "mobile.settings.currentServer": "当前服务器", "mobile.settings.signedOut": "未登录", @@ -3357,6 +3371,20 @@ export const zh = { "admin.defaultTimezone": "默认时区", "admin.defaultTimezoneHint": "用于站点日期边界及通用时间规则。", "admin.siteInfo": "站点信息", + "admin.release.heading": "软件版本", + "admin.release.installed": "当前版本", + "admin.release.automatic": "自动检查更新", + "admin.release.disclosure": "每小时向官方插件商店发送当前版本和随机部署标识,用于检查更新和统计在线部署。", + "admin.release.waiting": "等待下一次检查", + "admin.release.disabled": "已关闭版本检查", + "admin.release.unavailable": "暂时无法从官方插件商店获取版本信息。", + "admin.release.current": "暂无更新的正式版", + "admin.release.update": "新版本 {version} 可用", + "admin.release.composeHelp": "请先阅读发布说明并备份。将现有 Compose 文件中 doca 服务的镜像改为下方标签,再在原部署目录执行命令。", + "admin.release.copyCommand": "复制命令", + "admin.release.notes": "发布说明", + "admin.release.loadFailed": "无法读取版本检查设置。", + "admin.release.saveFailed": "未能保存版本检查设置。", "admin.experience": "用户体验", "admin.files": "文件与存储", "admin.search": "搜索与发现", diff --git a/packages/web-plugin-registry/src/navigation.ts b/packages/web-plugin-registry/src/navigation.ts index 52a913ab..2fb0e8cd 100644 --- a/packages/web-plugin-registry/src/navigation.ts +++ b/packages/web-plugin-registry/src/navigation.ts @@ -130,6 +130,7 @@ builtinNavigation.push( ); for (const [key, zh, en] of [ ["overview", "数据概览", "Overview"], + ["platform", "站点与服务", "Site settings"], ["login", "登录与注册", "Login"], ["users", "用户管理", "Users"], ["registration", "注册审核", "Registration"], @@ -137,7 +138,6 @@ for (const [key, zh, en] of [ ["ai", "AI 能力", "AI"], ["mcp", "公司 MCP 服务", "Company MCP services"], ["file-recognition", "文件识别", "File recognition"], - ["platform", "站点与服务", "Site settings"], ["uploads", "上传限制", "Upload limits"], ["plugins", "插件商店", "Plugins"], ["navigation", "导航管理", "Navigation"], diff --git a/specs/019-folder-loading/spec.md b/specs/019-folder-loading/spec.md new file mode 100644 index 00000000..80914d93 --- /dev/null +++ b/specs/019-folder-loading/spec.md @@ -0,0 +1,43 @@ +# 文件夹加载提示 + +**Level**: standard +**Status**: verified +**Created**: 2026-11-29 +**Decision**: 用户要求进入文件夹后立即看到加载反馈。此变更涉及文件管理的可见交互,按 standard 记录。 + +## Scope + +Doca 0.3.1 的 Web 与桌面共用文件管理界面,包括个人和共享文件夹的分栏、列表和图标视图。 + +## Acceptance + +- **AC-001**: 等待目标文件夹的内容时,内容区显示可被辅助技术识别的「正在加载文件夹…」。分栏视图在目标分栏显示提示,已加载的父目录仍可浏览。 +- **AC-002**: 请求成功后用对应文件夹的内容或空状态替换加载提示。请求失败时结束加载并显示现有错误提示,刷新可以重试。切换文件夹后,旧响应不会影响当前界面。 +- **AC-003**: 刷新已显示内容的文件夹时,已有条目保持可见。删除或失效文件夹仍按现有 404 导航规则处理。 + +## Architecture and contracts + +更新[用户指南](../../docs/user-guide.zh-CN.md)的文件管理说明。共用文件管理组件继续使用 `GET /files` 和已有的本地化加载文案。 + +## Compatibility decision + +仅涉及当前界面的内存状态和显示逻辑,无版本或存储格式转换。 + +## Design + +按位置关联已加载的目录数据和加载结果。当前目录的请求负责更新三种视图,分栏额外读取路径上的父目录。分栏在请求完成前也能显示目标位置,界面在成功读取后才显示内容或空状态。刷新时复用当前路径中已加载的数据。 + +## Tasks + +- [x] T001 为三种视图显示目标文件夹的加载提示,并按请求结果更新内容。(AC-001、AC-002) +- [x] T002 保持已有列表及 404 导航行为,验证快速切换、失败重试和后台刷新。(AC-002、AC-003) +- [x] T003 更新用户指南并记录相关验证结果。(AC-001、AC-002、AC-003) + +## Validation + +**Result**: passed + +- **AC-001**:使用 Chromium 158 和受控的慢响应验证 Doca 0.3.1 Web 生产构建。个人及共享文件夹显示中文加载提示,分栏保留父目录,列表和图标视图也显示提示。390 px 窄窗口中,从已滚到末尾的父目录打开子文件夹时提示仍在可见区域。减少动态效果时保留文案并停用旋转动画。 +- **AC-002**:浏览器中释放响应后,提示替换为对应条目。组件回归覆盖三种视图、成功空目录、快速切换时迟到的响应和 503 后刷新重试。 +- **AC-003**:组件回归验证待刷新内容仍可见,以及 404 后返回父目录。文件路由、文件操作、共享和语言相关测试一同运行。 +- `pnpm typecheck`、60 项相关 Vitest 测试、Web 生产构建、`pnpm sdd:check` 和 `pnpm docs:check` 通过。浏览器使用独立账号和文件夹的模拟响应,截图及执行记录位于 `artifacts/verification/folder-loading/`。 diff --git a/specs/025-compact-workspace-browsing/spec.md b/specs/025-compact-workspace-browsing/spec.md index 842a34af..e321d23b 100644 --- a/specs/025-compact-workspace-browsing/spec.md +++ b/specs/025-compact-workspace-browsing/spec.md @@ -1,6 +1,6 @@ # Compact workspace browsing in Harness and on mobile -> The selection of the compact layout and the narrow document header were later changed by [029-compact-layout-narrow-viewport](../029-compact-layout-narrow-viewport/spec.md): a phone-sized viewport is compact by default, so the scope line and the final clause of AC-001 ("a new unmarked tab stays regular") no longer hold for such a viewport — the explicit opt-out marker of AC-001 still works — and the narrow layout of AC-002 is described by 029. The coverage of the workspace routes and the native rail are unchanged. +> The selection of the compact layout and the narrow document header were later changed by [029-compact-layout-narrow-viewport](../029-compact-layout-narrow-viewport/spec.md): a phone-sized viewport is compact by default, so the scope line and the final clause of AC-001 ("a new unmarked tab stays regular") no longer hold for such a viewport — the explicit opt-out marker of AC-001 still works — and the narrow layout of AC-002 is described by 029. The coverage of the workspace routes is unchanged. The later [mobile app release](../032-mobile-app-mvp/spec.md) uses native bottom tabs on narrow screens and the browse rail on wider screens. **Level**: standard **Status**: implemented diff --git a/specs/031-doca-store-release-check/plan.md b/specs/031-doca-store-release-check/plan.md new file mode 100644 index 00000000..f5b1f06b --- /dev/null +++ b/specs/031-doca-store-release-check/plan.md @@ -0,0 +1,23 @@ +# 商店接入实施计划 + +**Spec**: [范围与验收](spec.md) +**Date**: 2026-12-01 + +## 实现 + +- 在插件商店已有限流之后处理公开 `POST /api/v1/doca/releases/check`。为该接口使用独立的 1 KiB JSON 解析和严格字段校验。`GET /api/admin/doca/deployments` 经已有管理员会话校验后返回聚合数量,供现有管理员页面显示。 +- 使用 `${DATABASE_PATH}.release-check.sqlite`。版本缓存保留验证时间,心跳以 UUID 为主键,按最后出现时间索引。使用单语句 upsert 去重,查询使用严格大于三小时截止点的条件。相同事务内写入以北京时间日期和当日哈希标识去重的上报记录,每日只查询当日数据。 +- 启动时及每 15 分钟后台清理过期心跳并刷新版本。解析 `main/compose.yaml` 的 `services.doca.image`。通过 GitHub 正式服务端发布记录确定稳定候选版本,再验证 Docker Hub 对应 `smartdoca/doca:<版本>` 标签。按 SemVer 降序选取最高可用版本。 +- 路由只访问本地 SQLite。上游短暂失败时保留尚未过期且未确认撤回的缓存,缓存截止时间为最后验证后 1 小时。已确认失效的发布记录或镜像标签使对应缓存失效。 + +## 验证 + +| 验收 | 检查 | +| --- | --- | +| AC-001 | 通过 HTTP 验证成功响应、严格校验、大小边界、商店现有限流及错误响应 | +| AC-002 | 验证管理员权限、同一 UUID 并发去重、不同 UUID、三小时边界、重新计入、持久化和定时清理 | +| AC-003 | 使用固定响应覆盖分页、桌面及预发布过滤、主分支版本偏差、镜像未就绪和已撤回版本;另用实际公开上游做隔离验证 | +| AC-004 | 验证缓存时效、重启沿用、上游异常和 SQLite 不可用 | +| AC-005 | 验证跨北京时间午夜、同日重复上报、管理员界面权限与展示 | + +只使用隔离数据库验证,原始产物位于 `artifacts/verification/doca-store-release-check/`。在 Doca 仓库运行 `pnpm sdd:check` 和 `pnpm docs:check`,在插件商店执行测试及构建检查。 diff --git a/specs/031-doca-store-release-check/spec.md b/specs/031-doca-store-release-check/spec.md new file mode 100644 index 00000000..c929f705 --- /dev/null +++ b/specs/031-doca-store-release-check/spec.md @@ -0,0 +1,26 @@ +# 商店接入 Doca 服务端版本检查 + +**Level**: full +**Status**: verified +**Created**: 2026-12-01 +**Decision**: 用户要求插件商店实现已有的版本检查协议,定期从 Doca 的 GitHub 主分支读取并缓存发布版本,并将实时在线和每天上报数量仅向管理员提供。 + +## Scope + +在独立的 `doca-plugin-store` 仓库(基线 0.1.17)接入 Doca 0.3.1 宿主已定义的请求。新增公开版本检查 API、商店管理员查询和独立的短期状态存储,因此按 full 处理。宿主版本检查和商店生产上线分别记录。 + +## Acceptance + +- **AC-001**: 商店接受符合 v1 约定且不超过 1024 字节的匿名 JSON 请求。符合条件的请求返回协议版本和正式服务器版本。400、413、429、503 均返回协议错误,且不更新心跳。 +- **AC-002**: 心跳按部署 UUID 原子去重,只记录标识和商店收到报告的时间。管理员可查询过去 3 小时内报告的部署数。恰好满 3 小时的报告退出统计,之后收到有效检查可重新进入,定时任务清理到期记录。 +- **AC-003**: 商店启动时及之后定时核对 Doca `main` 的 Compose 配置、GitHub 正式发布和 Docker Hub 的精确稳定标签。从本地缓存返回可发布的最高服务端版本,涵盖主分支配置与发布进度不一致的情况。撤回的版本从后续结果移除。 +- **AC-004**: 已验证的本地缓存可在短暂上游故障和商店进程重启后继续使用,最长 1 小时。没有有效缓存或心跳存储不可用时,公开检查返回 503。 +- **AC-005**: 商店管理员页面显示在线数量和按北京时间统计的今日去重上报数量。匿名访客和普通用户无法访问统计接口或查看数字。到期的每日去重记录由定时任务清理。 + +## Architecture and contracts + +[Doca 服务端版本检查协议](../../docs/doca-release-check-protocol.md)定义宿主请求、商店响应和在线定义。本次在插件商店的 `server/app.ts` 和 `server/index.ts` 接入,运营查询复用商店管理员会话。 + +## Compatibility decision + +商店首次启用版本检查和心跳,使用自己的新 SQLite 文件。既有商城业务数据库和宿主数据库继续使用各自现行结构。请求沿用已定义的单一 v1 格式,没有旧数据或旧协议转换。 diff --git a/specs/031-doca-store-release-check/tasks.md b/specs/031-doca-store-release-check/tasks.md new file mode 100644 index 00000000..79d4d801 --- /dev/null +++ b/specs/031-doca-store-release-check/tasks.md @@ -0,0 +1,8 @@ +# 商店接入任务 + +**Spec**: [范围与验收](spec.md) + +- [x] T001 实现插件商店公开检查接口和管理员数量查询,复用商店限流及管理员会话。AC-001、AC-002、AC-005。 +- [x] T002 实现独立本地存储、版本来源核对、后台刷新、心跳与每日去重记录清理。AC-002、AC-003、AC-004、AC-005。 +- [x] T003 在商店管理员页面显示在线数量和当日去重上报数量。AC-002、AC-005。 +- [x] T004 验证请求、心跳、发布筛选和缓存故障,记录实际结果并更新协议入口及商店文档。AC-001、AC-002、AC-003、AC-004、AC-005。 diff --git a/specs/031-doca-store-release-check/validation.md b/specs/031-doca-store-release-check/validation.md new file mode 100644 index 00000000..cf770395 --- /dev/null +++ b/specs/031-doca-store-release-check/validation.md @@ -0,0 +1,27 @@ +# 商店接入验证 + +**Spec**: [范围与验收](spec.md) +**Result**: passed + +## 验证范围 + +2026-12-01,插件商店 0.1.17(`670e7a3`)和宿主 0.3.1(`6fdfb75`)的本地工作区。运行环境为 Node.js 24.15.0、SQLite 3.51.3 和 Chrome 158.0.8127.37。编译后的商店通过回环地址提供 HTTP 接口,使用一次性数据库。商店从公开发布源取得版本,宿主检查器使用正常请求格式连到本地商店。 + +| 验收 | 执行与结果 | +| --- | --- | +| AC-001 | 协议测试确认合法请求的两字段响应,验证 1024 字节边界和 400、413、429、503 的拒绝路径。真实宿主发送的 JSON 通过商店校验。 | +| AC-002 | 测试覆盖并发重复 UUID、同源地址的不同 UUID、三小时边界、重新上报、定期清理和备选版本等于或低于宿主时的心跳。真实宿主重复上报与另一个 UUID 共计两个部署。 | +| AC-003 | 固定响应覆盖分页、SemVer 排序、主分支已落后或已提前的情况、桌面版、预发布和候选镜像过滤、发布记录及镜像撤回。启动时用 GitHub `main/compose.yaml`、GitHub 发布记录和实际 Docker Hub 标签确认并返回 `0.3.1`。 | +| AC-004 | 测试覆盖持久缓存重启后可用、短暂上游故障、满一小时归为不可用,以及 SQLite 打开或写入失败。写入失败时整条上报事务回滚。 | +| AC-005 | 测试覆盖北京时间午夜归零、当日重复上报去重和历史去重记录清理。真实商店会话的访客接口返回 401、普通用户返回 403,页面均不请求统计。管理员在 1440 和 390 像素宽度看到两项统计。 | + +## 命令与契约 + +- 插件商店 `npm test` 通过 73 项测试,`npm run check` 和 `npm run build` 通过。 +- Doca 宿主 `pnpm test tests/release-check.test.ts` 通过 11 项测试。`pnpm sdd:check`、`pnpm test:sdd` 和 `pnpm docs:check` 通过。 +- 联调脚本、日志和截图位于插件商店的 `artifacts/verification/doca-store-release-check/`。生产发布属于后续验收。 +- 更新 [版本检查协议](../../docs/doca-release-check-protocol.md) 和插件商店 README。独立的版本检查数据库为本功能首次创建的短期状态存储。 + +## 流程观察 + +调查阶段发现 GitHub 的默认 Latest 指向桌面发行,主分支镜像配置与正式发布进度也可能不同。将版本源交叉校验和北京时间午夜拆成独立验收,均有回归测试。未计调查和文档维护时间。 diff --git a/specs/032-mobile-app-mvp/spec.md b/specs/032-mobile-app-mvp/spec.md new file mode 100644 index 00000000..b050a371 --- /dev/null +++ b/specs/032-mobile-app-mvp/spec.md @@ -0,0 +1,97 @@ +# Doca 手机 App 内测版 + +**Level**: standard +**Status**: accepted +**Created**: 2026-11-29 +**Decision**: 用户选择从右上角头像进入「我的」,并于 2026-11-30 要求开发可运行版本。首轮在现有宿主接口上实现首页、我的、后端切换和 AI 的手机界面,复用现有文档、文件及通知能力。 + +## Scope + +用户离开电脑后,可以迅速找到资料,修改几行文字,上传手边的图片或文件,或带着资料继续问 AI。首轮面向手机竖屏和在线操作,覆盖登录、首页、搜索、知识库、文档、文件和 AI。安装与真机验收使用受控测试实例。 + +源码基线为 Doca 0.3.1 工作区的 [`@doca/mobile` 0.1.0](../../apps/mobile/package.json),锁定 Expo 53.0.27 和 React Native 0.79.5。密码登录、多实例切换、网页扫码确认以及四个主要页面已有代码。当前登录表单默认填写开发机回环地址。文档经 WebView 打开 Web 编辑器,文件已有选取、上传、部分格式预览和系统分享,AI 已接入流式任务、拍照和附件。上述范围以源码和下方本地检查为准。 + +## User Scenarios & Testing + +- **继续上次的工作**。登录自己部署的实例,在首页打开最近文档。需要修改时,用系统输入法完成少量文字编辑,随后在 Web 端查看同步结果。 +- **临时查资料**。用关键词找到文档或文件,或从知识库进入文档树。返回时还能接着浏览之前的列表。 +- **把现场材料带回 Doca**。进入目标文件夹,拍照或选择附件,确认上传结果。进入 AI 后,可以选择图片、附件或有权限的文档来提问。 + +## Acceptance + +- **AC-001**: iOS 和 Android 真机可安装内测包。首次打开可填写实例地址,使用现有密码方式登录。网络不可达时可返回修改地址或重试。重新打开、切换实例、退出和会话失效时正确反馈当前身份,页面只显示当前实例与账号可访问的数据。 +- **AC-002**: 首页可直接打开最近浏览项,并切换我的文档、收藏和共享给我的文档。搜索按文档和文件展示结果,点开文档或定位文件所在目录。返回恢复列表或搜索位置。加载中、部分结果加载失败、空结果与整体失败有各自的反馈。 +- **AC-003**: 五类文档可在手机上打开并按各自方式浏览。富文本和 Markdown 支持有编辑权限的用户在线修改普通段落,覆盖中文输入、键盘避让以及收到保存确认后从 Web 读回。表格可查看单元格,画布可缩放平移,演示可翻页。只读和失去访问权限的场景按宿主权限显示。 +- **AC-004**: 可选取文件、相册图片或拍照上传到当前有写权限的文件夹。上传目标和状态可见。失败后保留当前选择,结果不确定时可先核对目录。图片可预览。不能内嵌查看的格式可使用系统操作,上传和分享状态以已确认的结果为准。 +- **AC-005**: 配置模型的实例可发起文本会话、从已有会话继续提问、添加有权限的文档引用或发图片。回前台及网络恢复后能查看原任务结果。模型不可用时给出明确状态。 +- **AC-006**: 涉及的可见文案使用宿主语言字典。中英文真机检查覆盖关键路径,同时验证八种语言的键完整性、大字体、屏幕阅读器标签、安全区和系统返回。 +- **AC-007**: 主页面右上角头像打开「我的」,集中展示通知、界面语言、个人信息、个人设置、更多和退出登录。更多入口按当前账号权限显示。「切换后端」标明当前实例并可选择已登录实例。切换后打开目标实例首页,返回先前实例时使用其已保存会话。 + +## Architecture and contracts + +- 原生页面沿用 Expo Router 和 React Query,连接当前实例现有资源、搜索、文件及 AI 接口。窄屏底栏呈现首页、知识库、文件和 AI。宽屏保留已合入的左侧浏览栏。两者读取宿主导航配置。「我的」通过右上角头像进入。参考 [Web 账号菜单](../../apps/web/src/features/account/account-menu.tsx),按宿主权限显示「更多」入口,并复用 App 的[后端会话切换](../../apps/mobile/src/auth.tsx)。见 [App 插件契约](../../docs/plugin-native.zh-CN.md)。 +- 文档进入现有[手机文档路由](../../apps/mobile/app/document/[id].tsx)。宿主签发短期一次性票据,由 WebView 兑换 Web 会话。编辑、协同确认和权限检查由已有 Web 适配器及宿主负责。轻编辑验收使用实际服务器确认和另一客户端读回。见[编辑器集成](../../docs/editor-integration.zh-CN.md)和[协作契约](../../docs/collaboration-sdk-contract.zh-CN.md)。 +- 移动端 UI 使用现有 `LocaleProvider` 和稳定的英文消息键。搜索只描述当前支持的结果类型。见[界面语言约定](../../docs/i18n.zh-CN.md)。 + +## Compatibility decision + +首轮体验任务使用已实现的接口和页面状态。影响存量安装的数据、会话和连接策略的工作另按 full 记录,先就受影响的数据、验证与回退取得具体同意。 + +- 0.1.0 的实例索引和会话记录按服务器地址存放在 SecureStore。现有应用配置允许明文 HTTP,自托管实例的连接策略需要结合实际部署确认。首轮验收样本使用两个 HTTPS 测试实例。见[会话存储](../../apps/mobile/src/session.ts)和[应用配置](../../apps/mobile/app.json)。 +- 0.1.0 的 `doca-query-cache.json` 会写入成功查询的状态,导航查询键含会话令牌。Android 0.1.1 按[已确认的缓存处置](../034-mobile-query-cache/spec.md)单独验证旧查询缓存和账号隔离。见[查询缓存](../../apps/mobile/src/query-cache.ts)和[移动端导航查询](../../apps/mobile/src/plugins/navigation.tsx)。 +- 插件缓存现有持久目录和账号隔离规则,插件 IndexedDB 由插件自身管理。现有[离线工作台验收](../../docs/access-offline-events.md)覆盖 Web 和桌面。如规划手机端离线阅读或编辑,需单独验证 WebView 生命周期、权限撤销和待同步编辑的保存。 + +## Design + +| 默认入口 | 内容和交互 | +| --- | --- | +| 首页 | 实例入口、搜索、最近浏览、我的文档、收藏、与我共享。打开最近文档从列表直接进入。 | +| 知识库 | 知识库列表、逐级浏览文档树,返回到进入时的节点和位置。 | +| 文件 | 文件夹浏览、预览和分享。当前文件夹中的上传入口提供拍照、相册、选文件。 | +| AI | 继续会话、新对话、选文档或加附件,看任务进度和结果。 | +| 右上角头像 → 我的 | 汇集 Web 全局的通知、语言、账号及更多入口,提供切换后端。网页需要时可用现有扫码确认。 | + +### Web 助手和桌面缓存的对齐方向 + +- App 当前使用 RN 渲染对话并连接宿主任务流。原型参考 Web 的回答排版、执行过程、`+` 添加附件、`@` 引用和模型选择。如果需要在两端使用同一套 Markdown、表格、公式、图表和交付卡片,优先评估在 RN 内打开移动版 Web 助手并共用 [Web 聊天组件](../../apps/web/src/features/ai/ai-chat-host.tsx)。现有 [WebView 票据入口](../../apps/web/src/features/mobile/ticket-redeem.tsx)识别文档及插件路径,助手入口与会话衔接需另立 full 规格。 +- 「我的」原型展示「离线文档」和「缓存管理」。与[桌面客户端](../../docs/desktop-client.zh-CN.md#连接与认证)对齐时,设备上的数据按后端和账号隔离。列表、搜索、临时预览和可重新下载的 AI 会话缓存可释放。离线正文、待同步编辑、AI 草稿及待发送消息需保留。文档待同步修改按原身份提交,以服务端持久化确认出队。见[离线文档规则](../../docs/access-offline-events.md#离线文档入口)。 +- App 0.1.0 原生查询缓存建议停用旧格式读取,用当前登录身份从服务端重建可重新下载的数据。保留实例配置、已保存会话、插件数据和可恢复的本地修改。旧查询文件的处置与其中凭据的会话处理需取得具体同意。验证覆盖同设备账号与后端切换、旧数据保留、异常退出和回退。移动 WebView 离线打开及同步需双端真机验收。 + +### 交付顺序 + +本地预览以首页继续阅读、右上角头像和「我的」、已登录后端切换、通知、文件拍照入口以及 Web 风格的 RN AI 界面为范围。保留现有 App 入口和宿主接口。共用 Web 助手与桌面式缓存属于上节列明的后续边界。 + +1. **真机基线**。从当前 Expo 工程产出 iOS 和 Android 可安装包,接隔离实例走一次登录、打开文档、上传和 AI。记录设备、构建工具链、宿主版本和失败点。优先核对旧查询缓存及账号切换隔离。 +2. **完成高频路径**。先做首页、搜索和文档阅读,再做富文本及 Markdown 轻编辑、拍照上传、AI 附件。弱网、切后台、软键盘和失败重试随对应路径一起验收。 +3. **小范围内测**。收集首开首页、打开文档和上传的耗时以及失败原因,使用两端真机回归后再扩大范围。现有 [EAS preview 配置](../../apps/mobile/eas.json)是内部包的起点。若采用 TestFlight 或 Google Play,先用目标工具链验证构建和签名。见 [Expo 内部分发](https://docs.expo.dev/build/internal-distribution/)、[Apple 提交要求](https://developer.apple.com/news/upcoming-requirements/)和 [Google Play 目标 API 要求](https://developer.android.com/google/play/requirements/target-sdk)。 + +按一名开发、已有测试实例及设备估算,首轮工作量约 3–4 周。存量缓存处置和必要的工具链升级在真机基线后估算。 + +内测后的优先候选是系统分享进 Doca 和快速记录到现有文档。移动端离线数据和 Web 助手复用按前述边界另立规格,SSO 和复杂文档编辑根据内测需求评估。历史独立的随手记已从核心移除,快速记录需以当前文档能力为基础。见[历史随手记记录](../../docs/quick-notes.md)和[浏览器快速追加契约](../../docs/browser-quick-note.md)。 + +## Tasks + +- [ ] T001 检查双平台可安装包和测试实例。验证登录、已有实例切换、退出和无权限状态,记录缓存前置工作的范围。(AC-001) +- [ ] T002 改善 `apps/mobile` 首页、搜索、知识库列表与返回后的页面位置,检查加载、空态及重试。(AC-002) +- [ ] T003 检查手机文档页面的五类浏览行为,完成富文本和 Markdown 的在线轻编辑验收。(AC-003) +- [ ] T004 补齐文件页的拍照上传和状态反馈,验收内嵌预览及系统分享。(AC-004) +- [ ] T005 验收 AI 文档引用、图片提问和前后台恢复,补齐当前任务的反馈。(AC-005) +- [ ] T006 验证语言与无障碍。记录双端真机验证结果并更新用户可见说明。(AC-001、AC-002、AC-003、AC-004、AC-005、AC-006) +- [ ] T007 在四个主页面的右上角提供「我的」入口,核对 Web 全局菜单及权限,接入已保存后端的切换。(AC-007) + +## Validation + +**Result**: partial + +- 当前工作区基线的 `pnpm --filter @doca/mobile typecheck` 已通过。在 `apps/mobile` 运行 `pnpm exec expo export --platform ios --platform android`,两端均生成 Hermes bundle,文件在 `artifacts/verification/mobile-app-baseline/run.sxMnUBib/export/`。 +- 2026-11-30 本地预览重新通过移动端类型检查,导出 iOS 和 Android 的 Hermes bundle。针对界面语言、移动会话、错误反馈和原生插件的 5 个测试文件共 34 项通过。 +- iPhone 17(iOS 27.0,Expo Go SDK 53)连接两个隔离的 SQLite 测试实例。验证密码登录、保留两个后端的会话、切回已保存的后端并显示该实例的首页数据,以及通过右上角头像打开「我的」。通知从一条未读更新为零条未读,点开通知进入对应文档。(AC-001、AC-002、AC-007) +- 从首页「继续阅读」打开隔离 Markdown 文档,在 WebView 里用屏幕键盘输入一个字符,服务端重新读取了已保存内容。富文本与其他格式的真机及重连检查待完成。(AC-003) +- 文件菜单使用应用内对话框,覆盖新建文件夹、本地文件、拍照和相册四个入口。更换菜单后,在 iPhone 模拟器从相册选取测试 PNG,服务端目录返回已上传的文件。真机相机和系统分享待验证。(AC-004) +- 在 AI 页选择分析模型,添加一篇测试文档并发送消息。本地合成模型返回流式 Markdown,服务端记录任务完成,并保留用户消息中的文档引用。(AC-005) +- 本地预览截图和导出日志位于 `artifacts/verification/mobile-app-preview/`。测试实例仅供本机验证,真机安装、相机实拍、双平台无障碍和正式发布待验收。 +- AC-001、AC-002、AC-006 使用两个受控实例、各自的登录身份和不同资料,覆盖错误地址、网络中断、已过期会话、返回导航及系统语言设置。记录 iOS、Android、App 和宿主版本。 +- AC-003 使用隔离文档及同时打开的 Web 客户端,覆盖五种文档格式、只读权限、中文输入、服务器确认和重连后的读回。 +- AC-004、AC-005 使用测试图片和文件,覆盖拒绝权限、取消、断网、重复点击、切到后台及回前台。记录 AI 配置及任务结果。 +- AC-007 从各主页面点头像进入「我的」,使用有管理权限和普通账号检查菜单,再在两个已登录实例之间往返切换。 +- 后续验收输出放在 `artifacts/verification/mobile-app/`。性能基线、真机验收和发布状态待记录。 diff --git a/specs/033-doca-release-check/plan.md b/specs/033-doca-release-check/plan.md new file mode 100644 index 00000000..9b8c3d67 --- /dev/null +++ b/specs/033-doca-release-check/plan.md @@ -0,0 +1,24 @@ +# Doca server release check implementation + +**Spec**: [Feature specification](spec.md) +**Date**: 2026-11-30 + +## Decisions and boundaries + +- The built-in navigation registry supplies the default entry order. Retain explicit published navigation placements and reuse the existing Site information route. +- Use a dedicated `account_settings` key for the toggle, random deployment UUID, last attempt time and latest result. Reuse revision-checked writes. An atomic attempt claim applies to the shared deployment database, including PostgreSQL hosts with multiple replicas. Claim before network I/O so an interrupted attempt still consumes its hourly slot. +- Check from the production server entry point with a bounded timeout. Admin reads return local state. A site-wide disable clears the result, cancels local in-flight work and prevents an older claim from writing a result. Pending transport failures resolve to an unavailable status. +- Pin the destination to the official HTTPS store origin. The outbound payload has only the protocol version, server version and deployment UUID. The Web UI polls local state while enabled, with full host locale coverage. +- Generate the Docker image and release URL locally from the strict stable release version. Use the existing Compose service and deployment instructions. Preserve the original Compose project and storage. + +## Verification + +| Acceptance | Verification | +| --- | --- | +| AC-001 | Resolve default and customized navigation; exercise the Site information card in an isolated browser session | +| AC-002 | Simulate concurrent checks, restart, failure and time advancement against an isolated database and stub store | +| AC-003 | Exercise permissions, persisted disable, and a late response after changing the setting | +| AC-004 | Exercise older, equal, newer and malformed responses; inspect the exact upgrade image and copy action | +| AC-005 | Compare the JSON and fixed endpoint used by the host to the handoff document; run documentation checks | + +Raw verification output goes under `artifacts/verification/doca-release-check/`. The store service is outside local validation. diff --git a/specs/033-doca-release-check/spec.md b/specs/033-doca-release-check/spec.md new file mode 100644 index 00000000..c86c2ed3 --- /dev/null +++ b/specs/033-doca-release-check/spec.md @@ -0,0 +1,26 @@ +# Doca server release checks + +**Level**: full +**Status**: verified +**Created**: 2026-11-30 +**Decision**: The user requested hourly release checks, a default-on admin control, an upgrade command and deployment counting. The user selected the official plugin store for the endpoint and reserved implementation of the store side for later. + +## Scope + +Move the existing Site and services entry directly below Overview in the default administration navigation. Its default tab is Site information. Add the release check to this tab. The baseline host in this checkout reports `0.3.1` from the root package. The new external protocol and the new deployment-scoped state make this a full change. + +## Acceptance + +- **AC-001**: The default administrator navigation places Site and services immediately after Overview and opens Site information. The site info card always shows the installed server version when local state is readable. +- **AC-002**: An enabled deployment makes a check at startup when due and attempts at most one every 60 minutes across reloads, restarts and host replicas. The store receives the actual server version and a deployment-scoped random ID. +- **AC-003**: An administrator can persistently turn off checks. Saved disabled state stops scheduled outbound traffic and browser status polling. An earlier request cannot overwrite the new setting. Ordinary users cannot read or write the setting. +- **AC-004**: A validated newer stable release produces an update notice and a copyable Compose command with the exact image tag displayed alongside. An equal or older release produces a current-version status. Remote errors keep the management page usable. +- **AC-005**: The handoff protocol fixes the public request and response, data minimization, and the store's 3-hour deduplicated counting rule. The official store implementation and rollout are outside this change. + +## Architecture and contracts + +Doca owns the admin routes, scheduler and presentation. The official store owns stable release discovery and the deployment count. The [release check protocol](../../docs/doca-release-check-protocol.md) defines the new interface. [Deployment](../../docs/deployment.md) explains the manual upgrade procedure. + +## Compatibility decision + +No existing column, configuration record, API payload or persisted format is changed. The release checker uses a new key in the existing revisioned settings table, where there was no prior version-check state. All previous records retain their existing readers and values. diff --git a/specs/033-doca-release-check/tasks.md b/specs/033-doca-release-check/tasks.md new file mode 100644 index 00000000..d18376d9 --- /dev/null +++ b/specs/033-doca-release-check/tasks.md @@ -0,0 +1,8 @@ +# Doca server release check tasks + +**Spec**: [Feature specification](spec.md) + +- [x] T001 Move the default navigation entry and add a localized version card to Site information. AC-001, AC-004. +- [x] T002 Add admin-only status and settings routes plus a shared, persistent hourly check in the server. AC-002, AC-003, AC-004. +- [x] T003 Document the official store handoff and the Compose upgrade steps. AC-004, AC-005. +- [x] T004 Run isolated navigation, service and UI checks and record the results. AC-001, AC-002, AC-003, AC-004, AC-005. diff --git a/specs/033-doca-release-check/validation.md b/specs/033-doca-release-check/validation.md new file mode 100644 index 00000000..88e33232 --- /dev/null +++ b/specs/033-doca-release-check/validation.md @@ -0,0 +1,29 @@ +# Doca server release check validation + +**Spec**: [Feature specification](spec.md) +**Result**: passed + +## Scope + +On 2026-12-01, the local feature diff on host 0.3.1 (`6fdfb75`) used Node 24.15.0, SQLite 3.53.4, and isolated PostgreSQL 17.11 and 18.6. The Chrome run used a real Doca host with the production Web build, a disposable SQLite database and a stub of the official store protocol. + +## Acceptance results + +| Acceptance | Check | Outcome | +| --- | --- | --- | +| AC-001 | Navigation, locale tests and Chrome | The default second entry opens Site information. Published custom ordering remains effective. The current server version appears in the card. All eight catalogs pass key and placeholder checks. | +| AC-002 | `tests/release-check.test.ts` on all three database engines and Chrome | One outbound attempt with two concurrent workers. Restarted checkers retain the ID and cooldown. A network or protocol failure consumes its slot and the retry is deferred. The real host starts the check without a browser trigger. | +| AC-003 | Service tests, `tests/cloud.test.ts` and Chrome | Anonymous and ordinary users are denied. Disable persists and stops requests, cancels a local in-flight request, and discards a late response from another worker. Chrome observes no polling after disable and the disabled state after reopening the database and restarting the host. | +| AC-004 | Service tests and Chrome at 1440 px and 390 px | Equal and older stable versions show no update. Invalid, oversized and unreachable responses yield the unavailable state. A simulated newer version displays its exact tag and release link. Chrome copies the expected command and the narrow card fits. | +| AC-005 | Request assertions and `pnpm docs:check` | The three-field request, origin and path match the [protocol](../../docs/doca-release-check-protocol.md). The counting window and store-side acceptance are documented. | + +## Commands and scope + +- `pnpm test tests/release-check.test.ts tests/cloud.test.ts tests/navigation-layout.test.ts tests/i18n.test.ts` passed 76 tests on SQLite. +- `DOCA_TEST_POSTGRES= pnpm test tests/release-check.test.ts` passed 11 tests on each PostgreSQL version. +- `pnpm typecheck`, `pnpm build`, `pnpm sdd:check`, `pnpm test:sdd` and `pnpm docs:check` passed. +- Screenshots, the isolated Chrome script and run logs are under `artifacts/verification/doca-release-check/`. The store endpoint, live heartbeats and production deployments were outside this validation. + +## Contracts and compatibility + +Updated the [administrator API index](../../docs/api.md), [deployment guide](../../docs/deployment.md) and [plugin store protocol entry](../../docs/plugin-store-protocol.md). The feature adds its own record in the existing settings table. There is no schema migration or reader for a previous release-check format. diff --git a/specs/034-mobile-query-cache/plan.md b/specs/034-mobile-query-cache/plan.md new file mode 100644 index 00000000..f4cc1a98 --- /dev/null +++ b/specs/034-mobile-query-cache/plan.md @@ -0,0 +1,7 @@ +# Plan + +**Spec**: [Feature specification](spec.md) + +1. Remove native query-file hydration and persistence. Call the idempotent cleanup on app startup. (AC-001) +2. Clear in-memory queries before publishing a changed active session. Keep the existing SecureStore and plugin storage contracts. (AC-002) +3. Increment the Android build code, build with the existing signing key and test upgrade, startup and account transitions on Android. (AC-002, AC-003) diff --git a/specs/034-mobile-query-cache/spec.md b/specs/034-mobile-query-cache/spec.md new file mode 100644 index 00000000..9368b865 --- /dev/null +++ b/specs/034-mobile-query-cache/spec.md @@ -0,0 +1,24 @@ +# Mobile query cache for the Android release + +**Level**: full +**Status**: accepted +**Created**: 2026-12-01 +**Decision**: The owner approved retiring the 0.1.0 on-device query file before distributing the Android 0.1.1 APK, including the exact file to remove, the retained data and the rollback procedure. + +## Scope + +The Expo app's native query client, its account transition handling, and the Android 0.1.0 to 0.1.1 upgrade. The native UI follows the [mobile app spec](../032-mobile-app-mvp/spec.md). + +## Acceptance + +- **AC-001**: On startup, discard only `doca-query-cache.json`. A missing or unreadable file does not stop startup. The app never reads, repopulates or persists that query cache. +- **AC-002**: Saved backends, credentials in SecureStore, native plugin data and documents survive the upgrade. A session change clears the old in-memory queries before showing the new account. +- **AC-003**: The Android APK keeps `app.doca.mobile` and the existing EAS signing identity, advances version code from 1 to 2, and installs and starts on an isolated Android device or emulator. + +## Architecture and contracts + +Native queries use the existing React Query client with memory-only retention. See [native plugin storage](../../docs/plugin-native.md) for the separate app storage and scope of explicit sign-out. + +## Compatibility decision + +The owner explicitly agreed on 2026-12-01 to remove the exact disposable file without reading it and to rebuild online query results in memory. No saved session is revoked as part of upgrade. If deletion fails, startup still never reads the file and retries deletion on the next launch. To roll the UI back, rebuild the older UI with this policy, the same signing key and a higher Android version code. Do not restore the old query file. diff --git a/specs/034-mobile-query-cache/tasks.md b/specs/034-mobile-query-cache/tasks.md new file mode 100644 index 00000000..55bfd192 --- /dev/null +++ b/specs/034-mobile-query-cache/tasks.md @@ -0,0 +1,7 @@ +# Tasks + +**Spec**: [Feature specification](spec.md) + +- [x] T001 Remove native query persistence and run exact-file cleanup. (AC-001) +- [x] T002 Clear the in-memory cache before publishing a new active session. (AC-002) +- [ ] T003 Build the signed release package and verify Android startup, cache cleanup and account isolation. (AC-001, AC-002, AC-003) diff --git a/specs/034-mobile-query-cache/validation.md b/specs/034-mobile-query-cache/validation.md new file mode 100644 index 00000000..0bf4b11c --- /dev/null +++ b/specs/034-mobile-query-cache/validation.md @@ -0,0 +1,8 @@ +# Validation + +**Spec**: [Feature specification](spec.md) +**Result**: pending + +- AC-001: Seed the old query file in an isolated Android installation and verify deletion, repeated launch and absence of a replacement after queries complete. +- AC-002: Check retained backends and plugin files and switch between two isolated accounts. +- AC-003: Verify Android package name, code and signing certificate, installation and launch. diff --git a/specs/035-android-session-lifetime/plan.md b/specs/035-android-session-lifetime/plan.md new file mode 100644 index 00000000..afc65922 --- /dev/null +++ b/specs/035-android-session-lifetime/plan.md @@ -0,0 +1,7 @@ +# Plan + +**Spec**: [Feature specification](spec.md) + +1. Request the platform-specific policy on Android sign-in and issue it in the host password route. (AC-001, AC-003) +2. Keep SecureStore persistence and make Android logout depend on confirmed revocation. Guard against a superseded token's delayed rejection. (AC-001, AC-002) +3. Verify time limits, future dates, restart, account revocation and upgrade against isolated host and Android fixtures. (AC-001, AC-002, AC-003) diff --git a/specs/035-android-session-lifetime/spec.md b/specs/035-android-session-lifetime/spec.md new file mode 100644 index 00000000..360e3d23 --- /dev/null +++ b/specs/035-android-session-lifetime/spec.md @@ -0,0 +1,24 @@ +# Android session lifetime + +**Level**: full +**Status**: accepted +**Created**: 2026-12-01 +**Decision**: The owner explicitly approved non-expiring new Android 0.1.1 password logins on the new server, preserving previously issued sessions and their current expiry policy. + +## Scope + +Password sign-in from Android 0.1.1 to Doca 0.3.2 and handling of the native session through server requests, app restarts, explicit sign-out and server-side revocation. + +## Acceptance + +- **AC-001**: Android 0.1.1 signals its platform on password sign-in. Doca 0.3.2 issues a bearer-only session with no inactivity expiry or renewal requirement. The app still uses SecureStore and can restart and reconnect with the same valid login. +- **AC-002**: Explicit sign-out revokes the token on the host before the app forgets it. Password changes, administrative revocation and inactive user status take effect through the existing server checks. A network failure or a delayed response from an earlier login does not clear a valid login. +- **AC-003**: Previous sessions retain their expiry policy. Upgrading of the app and host preserves those logins. A fresh sign-in obtains the new behavior. Web and other mobile clients retain configured time limits. Older servers ignore the extra request header and use their existing timed mobile policy. + +## Architecture and contracts + +The existing password route receives `x-doca-client-platform: android` alongside `x-doca-client: mobile`. It stores a reserved far-future ISO marker in `sessions.expires_at` for these new sessions, returns the existing JSON bearer credential, and omits a browser cookie. The normal per-request permission and revocation checks apply. See the [HTTP API](../../docs/api.md) and [configuration](../../docs/configuration.md). + +## Compatibility decision + +On 2026-12-01 the owner explicitly approved keeping all previous expiry values and issuing the new policy only on a fresh Android sign-in. Keep the original column, hash/token format, SecureStore records and user data. No batch update or DDL is required. Before reverting the server policy, set a finite expiry only on rows bearing the new marker. Preserve all other rows and data and recheck that each adjusted session obeys the finite policy on the rollback build. diff --git a/specs/035-android-session-lifetime/tasks.md b/specs/035-android-session-lifetime/tasks.md new file mode 100644 index 00000000..e7763028 --- /dev/null +++ b/specs/035-android-session-lifetime/tasks.md @@ -0,0 +1,7 @@ +# Tasks + +**Spec**: [Feature specification](spec.md) + +- [x] T001 Implement Android sign-in with the server-side lifetime policy and document the API. (AC-001, AC-003) +- [x] T002 Confirm Android logout and retain the session across transient failures. (AC-002) +- [ ] T003 Run regression checks for the new and previous sessions and verify the Android release against the host. (AC-001, AC-002, AC-003) diff --git a/specs/035-android-session-lifetime/validation.md b/specs/035-android-session-lifetime/validation.md new file mode 100644 index 00000000..7c9b2d03 --- /dev/null +++ b/specs/035-android-session-lifetime/validation.md @@ -0,0 +1,8 @@ +# Validation + +**Spec**: [Feature specification](spec.md) +**Result**: pending + +- AC-001: Compare stored expiry and authorization before and after advancing the host clock. Launch the signed APK against an isolated Doca host and restart it after signing in. +- AC-002: Verify explicit logout, revocation and inactive accounts. Check that a transient bad response cannot remove a valid saved login. +- AC-003: Compare browser, earlier mobile and new Android sign-in. Test an old Android query-cache fixture separately under the [cache spec](../034-mobile-query-cache/validation.md). diff --git a/tests/android-session-lifetime.test.ts b/tests/android-session-lifetime.test.ts new file mode 100644 index 00000000..f7c38c47 --- /dev/null +++ b/tests/android-session-lifetime.test.ts @@ -0,0 +1,90 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { createApp } from "@server/app/create-app.js"; +import { persistentAndroidExpiry } from "@server/app/mobile-client.js"; +import { createUser, tokenHash } from "@core/modules/identity/passwords.js"; +import { openTestDatabase } from "./database.js"; + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllEnvs(); +}); + +it("keeps new Android sessions through a long absence and honors logout and administrative revocation", async () => { + vi.stubEnv("DOCA_SESSION_TTL_SECONDS", "3600"); + vi.stubEnv("DOCA_MOBILE_SESSION_TTL_SECONDS", "7200"); + const origin = "https://doca.example.test"; + const headers = { host: "doca.example.test" }; + const db = await openTestDatabase({ driver: "sqlite", path: ":memory:" }); + let app: Awaited> | undefined; + try { + const password = "android-session-fixture-password"; + const admin = await createUser(db, { login: "owner", displayName: "Owner", password }, { bootstrap: true }); + const member = await createUser(db, { login: "member", displayName: "Member", password }, { actor: admin }); + app = await createApp(db, { origin }); + + async function login(account: string, extra: Record) { + const response = await app!.inject({ + method: "POST", + url: "/api/v1/auth/login", + headers: { ...headers, ...extra }, + payload: { login: account, password }, + }); + expect(response.statusCode, response.body).toBe(200); + return response; + } + const expiry = async (token: string) => (await db.selectFrom("sessions").select("expires_at") + .where("id", "=", tokenHash(token)).executeTakeFirst())?.expires_at; + const bearer = (token: string) => ({ ...headers, authorization: `Bearer ${token}` }); + const me = (token: string) => app!.inject({ url: "/api/v1/me", headers: bearer(token) }); + const oldMobile = (await login("member", { "x-doca-client": "mobile" })).json().sessionToken; + const oldExpiry = await expiry(oldMobile); + const ios = (await login("member", { "x-doca-client": "mobile", "x-doca-client-platform": "ios" })).json().sessionToken; + const browser = await login("owner", { origin, "x-doca-client-platform": "android" }); + expect(browser.json().sessionToken).toBeUndefined(); + expect(browser.headers["set-cookie"]).toContain("Max-Age=3600"); + + const android = { "x-doca-client": "mobile", "x-doca-client-platform": "android" }; + const reply = await login("member", android); + expect(reply.headers["set-cookie"]).toBeUndefined(); + const token = reply.json().sessionToken; + expect(await expiry(token)).toBe(persistentAndroidExpiry); + expect(await expiry(oldMobile)).toBe(oldExpiry); + expect(await expiry(ios)).not.toBe(persistentAndroidExpiry); + + vi.useFakeTimers({ now: new Date("2040-02-01T00:00:00.000Z"), toFake: ["Date"] }); + expect((await me(token)).statusCode).toBe(200); + expect(await expiry(token)).toBe(persistentAndroidExpiry); + expect((await me(oldMobile)).statusCode).toBe(401); + expect((await me(ios)).statusCode).toBe(401); + const logout = await app.inject({ method: "POST", url: "/api/v1/auth/logout", headers: bearer(token) }); + expect(logout.statusCode, logout.body).toBe(200); + expect(await expiry(token)).toBeUndefined(); + expect((await me(token)).statusCode).toBe(401); + + const revoked = (await login("member", android)).json().sessionToken; + const administrator = (await login("owner", android)).json().sessionToken; + const disabled = await app.inject({ + method: "PATCH", + url: `/api/v1/admin/users/${member.id}`, + headers: bearer(administrator), + payload: { status: "disabled" }, + }); + expect(disabled.statusCode, disabled.body).toBe(200); + expect((await me(revoked)).statusCode).toBe(401); + expect(await expiry(revoked)).toBeUndefined(); + await db.updateTable("users").where("id", "=", member.id).set({ status: "active" }).execute(); + const passwordToken = (await login("member", android)).json().sessionToken; + const reset = await app.inject({ + method: "POST", + url: `/api/v1/admin/users/${member.id}/password`, + headers: bearer(administrator), + payload: { password: "android-new-fixture-password" }, + }); + expect(reset.statusCode, reset.body).toBe(200); + expect((await me(passwordToken)).statusCode).toBe(401); + expect(await expiry(passwordToken)).toBeUndefined(); + } finally { + await app?.close(); + await db.destroy(); + } +}); diff --git a/tests/cloud.test.ts b/tests/cloud.test.ts index 46fdb5d9..db77dd46 100644 --- a/tests/cloud.test.ts +++ b/tests/cloud.test.ts @@ -127,6 +127,22 @@ afterEach(async () => { }); describe("cloud baseline", () => { + it("only lets a system administrator read and change release checks", async () => { + const path = "/admin/release-check"; + expect((await request("GET", path)).statusCode).toBe(401); + expect((await request("GET", path, alice)).statusCode).toBe(403); + expect((await request("PUT", path, alice, { enabled: false })).statusCode).toBe(403); + expect((await request("PUT", path, adminCookie, {})).statusCode).toBe(400); + + const initial = (await request("GET", path, adminCookie)).json(); + expect(initial).toMatchObject({ enabled: true, status: "waiting" }); + expect(initial.deploymentId).toBeUndefined(); + const disabled = await request("PUT", path, adminCookie, { enabled: false }); + expect(disabled.statusCode).toBe(200); + expect(disabled.json()).toMatchObject({ enabled: false, status: "disabled" }); + expect((await request("GET", path, adminCookie)).json()).toEqual(disabled.json()); + }); + it("filters document sources with type and scope while respecting access", async () => { const library = await create(alice, { kind: "library", title: "Source library" }); const personal = await create(alice, { format: "markdown" }); diff --git a/tests/file-explorer-loading.test.ts b/tests/file-explorer-loading.test.ts new file mode 100644 index 00000000..662f3622 --- /dev/null +++ b/tests/file-explorer-loading.test.ts @@ -0,0 +1,161 @@ +// @vitest-environment jsdom +import { JSDOM } from "jsdom"; +import { act, createElement } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { FilesExplorer } from "@web/features/files/files.js"; +import type { FileFolder, FilePage } from "@web/shared/api.js"; + +const { api } = vi.hoisted(() => ({ api: vi.fn() })); +vi.mock("@web/shared/api.js", async (importOriginal) => ({ + ...await importOriginal(), + api, +})); +vi.mock("@web/shared/i18n.js", async () => { + const { createTranslator } = await import("@doca/i18n"); + const t = createTranslator("en"); + return { useI18n: () => ({ t, locale: "en" }) }; +}); +vi.mock("@web/features/ai/ai-context.js", () => ({ useAI: () => null })); +vi.mock("@web/plugins/extensions.js", () => ({ PluginSlot: () => null })); +vi.mock("@web/features/creation-resources/pickers.js", () => ({ MaterialPicker: () => null })); + +function folder(id: string, name: string): FileFolder { + return { id, name, parent_id: null, type: "folder", virtual: false, locked: false, version: 1 }; +} + +function filePage(id: string, ...folders: FileFolder[]): FilePage { + return { parent: { type: id === "root" ? "system" : "folder", id }, folders, files: [] }; +} + +const reports = folder("reports", "Reports"); +const notes = folder("notes", "Notes"); +const archive = folder("archive", "Archive"); +let pages: Map>; +let host: HTMLDivElement; +let root: ReturnType; +let storageWindow: JSDOM["window"]; + +function holdFolder(id: string) { + let resolve!: (page: FilePage) => void; + let reject!: (error: Error) => void; + pages.set(id, new Promise((done, fail) => { resolve = done; reject = fail; })); + return { resolve, reject }; +} + +function entry(id: string) { + return host.querySelector(`.file-entry[data-id="${id}"]`); +} + +function status() { + return host.querySelector('[role="status"]'); +} + +async function render(view: "columns" | "list" | "grid") { + localStorage.setItem("doca.files.view", view); + await act(() => root.render(createElement(FilesExplorer))); +} + +beforeEach(() => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + storageWindow = new JSDOM("", { url: "https://doca.test" }).window; + vi.stubGlobal("localStorage", storageWindow.localStorage); + Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { configurable: true, value: vi.fn() }); + window.history.replaceState(null, "", "#/files"); + pages = new Map([["root", filePage("root", reports, notes)]]); + api.mockImplementation(async (path: string) => { + if (path.startsWith("/me/page-state")) return { item: null }; + const url = new URL(path, location.origin); + const page = pages.get(url.searchParams.get("parentId") ?? ""); + if (url.pathname === "/files" && page) return page; + throw new Error(`Unexpected request ${path}`); + }); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); +}); + +afterEach(async () => { + await act(() => root.unmount()); + host.remove(); + storageWindow.close(); + api.mockReset(); + vi.unstubAllGlobals(); +}); + +it.each(["columns", "list", "grid"] as const)("shows the loading state when opening a folder in %s view", async (view) => { + const pending = holdFolder(reports.id); + await render(view); + await act(() => { + const row = entry(reports.id)!; + if (view === "columns") row.click(); + else row.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); + }); + + expect(status()?.textContent).toBe("Loading folder…"); + expect(host.querySelector(".files-empty, .files-column-empty")).toBeNull(); + if (view === "columns") { + expect(status()?.closest(".files-column")?.querySelector(".files-column-title")?.textContent).toBe(reports.name); + expect(entry(notes.id)).not.toBeNull(); + expect(api.mock.calls.filter(([path]) => path === "/files?parentType=system&parentId=root")).toHaveLength(1); + } + + await act(() => pending.resolve(filePage(reports.id, archive))); + expect(status()).toBeNull(); + expect(entry(archive.id)).not.toBeNull(); +}); + +it("keeps the new folder's loading state when an earlier response arrives", async () => { + const earlier = holdFolder(reports.id); + const current = holdFolder(notes.id); + await render("columns"); + await act(() => entry(reports.id)!.click()); + await act(() => entry(notes.id)!.click()); + await act(() => earlier.resolve(filePage(reports.id, archive))); + + expect(status()?.closest(".files-column")?.querySelector(".files-column-title")?.textContent).toBe(notes.name); + expect(entry(archive.id)).toBeNull(); + await act(() => current.resolve(filePage(notes.id))); + expect(status()).toBeNull(); + expect(host.querySelector(".files-column-empty")?.textContent).toBe("This folder is empty"); +}); + +it("shows errors and retries while keeping already loaded rows during refresh", async () => { + const pending = holdFolder(reports.id); + await render("columns"); + await act(() => entry(reports.id)!.click()); + await act(() => pending.reject(Object.assign(new Error("Temporary failure"), { status: 503 }))); + + expect(status()).toBeNull(); + expect(host.querySelector('[role="alert"]')?.textContent).toBe("Temporary failure"); + expect(host.querySelector(".files-column-empty")).toBeNull(); + + const retry = holdFolder(reports.id); + const refresh = host.querySelector(".files-refresh")!; + await act(() => refresh.click()); + expect(status()?.textContent).toBe("Loading folder…"); + await act(() => retry.resolve(filePage(reports.id, archive))); + expect(entry(archive.id)).not.toBeNull(); + + const update = holdFolder(reports.id); + await act(() => refresh.click()); + expect(status()).toBeNull(); + expect(entry(archive.id)).not.toBeNull(); + await act(() => update.resolve(filePage(reports.id))); + expect(entry(archive.id)).toBeNull(); + expect(host.querySelector(".files-column-empty")).not.toBeNull(); +}); + +it("returns to the parent if the folder no longer exists", async () => { + const pending = holdFolder(reports.id); + await render("columns"); + await act(() => entry(reports.id)!.click()); + pages.set("root", filePage("root", notes)); + await act(() => pending.reject(Object.assign(new Error("Folder not found"), { status: 404 }))); + + expect(status()).toBeNull(); + expect(host.querySelector('[role="alert"]')).toBeNull(); + expect(host.querySelectorAll(".files-column")).toHaveLength(1); + expect(entry(reports.id)).toBeNull(); + expect(entry(notes.id)).not.toBeNull(); +}); diff --git a/tests/file-interactions.test.ts b/tests/file-interactions.test.ts index 744eb8d6..f38a4229 100644 --- a/tests/file-interactions.test.ts +++ b/tests/file-interactions.test.ts @@ -12,8 +12,6 @@ import { nextAvailableName, orderedRange, parseFileDragItems, - replaceColumnPage, - reusedColumnPrefix, sameTrail, serializeFileDrag, toggleSelectedId, @@ -88,18 +86,10 @@ it("leaves column-view navigation before a trashed open folder", () => { expect(trailAfterRemovedFolders(trail, ["root"])).toEqual({ kind: "leave-root" }); }); -it("reuses matching column prefix instead of refetching parent columns", () => { +it("compares trails by the ordered location types and IDs", () => { const documents = { type: "system", id: "documents" }; const personal = { type: "system", id: "documents-personal" }; const doc = { type: "document", id: "doc-1" }; - const columns = [ - { location: documents, page: 1 }, - { location: personal, page: 2 }, - { location: doc, page: 3 }, - ]; - expect(reusedColumnPrefix([documents, personal, doc], columns)).toEqual(columns); - expect(reusedColumnPrefix([documents, { type: "system", id: "documents-shared" }], columns)).toEqual([columns[0]]); - expect(replaceColumnPage(columns, doc, 9)[2]).toEqual({ location: doc, page: 9 }); expect(sameTrail([documents, personal], [documents, personal])).toBe(true); expect(sameTrail([documents, personal], [documents, doc])).toBe(false); }); diff --git a/tests/navigation-layout.test.ts b/tests/navigation-layout.test.ts index bdbc77bf..7f856e9e 100644 --- a/tests/navigation-layout.test.ts +++ b/tests/navigation-layout.test.ts @@ -16,6 +16,19 @@ import { pluginNavigationSchema, navigationConfigSchema, } from "@server/plugins/navigation-schema.js"; + +it("places Site and services immediately after Overview in the default admin navigation", () => { + const actor = { id: "a", admin: true }; + const site = "doca.admin.platform"; + const overview = "doca.admin.overview"; + const order = (placements: NavigationConfig["layout"]["placements"]) => + resolveNavigation(builtinNavigation, { schemaVersion: 1, layout: { placements } }, actor) + .layout.placements.filter((p) => p.slot === "web.admin").map((p) => p.entryId); + + expect(order([]).slice(0, 2)).toEqual([overview, site]); + expect(order([{ entryId: site, slot: "web.admin", order: 1000 }]).at(-1)).toBe(site); +}); + it("uses one global layout, preserves admin boundaries and does not mutate published configuration during overflow", () => { const entries: NavigationEntry[] = Array.from({ length: 8 }, (_, i) => ({ id: `example.p${i}`, diff --git a/tests/release-check.test.ts b/tests/release-check.test.ts new file mode 100644 index 00000000..0d9a0ae2 --- /dev/null +++ b/tests/release-check.test.ts @@ -0,0 +1,187 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { HOST_VERSION } from "@server/app/version.js"; +import { createReleaseChecker } from "@server/services/release-check.js"; +import { openTestDatabase } from "./database.js"; + +const hour = 60 * 60 * 1000; +const nextVersion = `${Number(HOST_VERSION.split(".")[0]) + 1}.0.0`; +let db: Awaited>; +let time: number; + +beforeEach(async () => { + db = await openTestDatabase({ driver: "sqlite", path: ":memory:" }); + time = 1_000; +}); + +afterEach(async () => { + await db.destroy(); +}); + +function releaseResponse(version = nextVersion) { + return Response.json({ protocolVersion: 1, latestVersion: version }); +} + +it("claims the hourly slot once across concurrent workers and retains the deployment ID", async () => { + const fetch = vi.fn(async () => releaseResponse()); + const options = { fetch, now: () => time }; + const first = createReleaseChecker(db, options); + const second = createReleaseChecker(db, options); + + expect(await first.status()).toEqual({ + enabled: true, + currentVersion: HOST_VERSION, + status: "waiting", + update: null, + }); + expect(fetch).not.toHaveBeenCalled(); + await Promise.all([first.check(), second.check()]); + expect(fetch).toHaveBeenCalledTimes(1); + const [url, request] = fetch.mock.calls[0]!; + expect(String(url)).toBe( + "https://store.smartdoca.cc/api/v1/doca/releases/check", + ); + expect(request).toMatchObject({ + method: "POST", + headers: { "Content-Type": "application/json", Accept: "application/json" }, + redirect: "error", + credentials: "omit", + }); + const sent = JSON.parse(String(request?.body)); + expect(sent).toEqual({ + protocolVersion: 1, + currentVersion: HOST_VERSION, + deploymentId: expect.stringMatching(/^[0-9a-f-]{36}$/), + }); + expect(await second.status()).toEqual({ + enabled: true, + currentVersion: HOST_VERSION, + status: "update", + update: { + version: nextVersion, + image: `docker.io/smartdoca/doca:${nextVersion}`, + releaseUrl: `https://github.com/workhold/doca/releases/tag/v${nextVersion}`, + }, + }); + + const restarted = createReleaseChecker(db, options); + time += hour - 1; + await restarted.check(); + expect(fetch).toHaveBeenCalledTimes(1); + time++; + await restarted.check(); + expect(fetch).toHaveBeenCalledTimes(2); + expect(JSON.parse(String(fetch.mock.calls[1]?.[1]?.body))).toEqual(sent); +}); + +it("persists disable across workers and ignores an earlier response", async () => { + const fetch = vi.fn(async () => releaseResponse()); + const options = { fetch, now: () => time }; + const worker = createReleaseChecker(db, options); + const admin = createReleaseChecker(db, options); + await worker.check(); + time += hour; + + let reply!: (response: Response) => void; + fetch.mockImplementationOnce( + () => + new Promise((resolve) => { + reply = resolve; + }), + ); + const pending = worker.check(); + await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2)); + expect(await admin.setEnabled(false)).toMatchObject({ + enabled: false, + status: "disabled", + update: null, + }); + reply(releaseResponse()); + await pending; + expect(await worker.status()).toMatchObject({ + status: "disabled", + update: null, + }); + + const restarted = createReleaseChecker(db, options); + await restarted.check(); + expect(await restarted.setEnabled(true)).toMatchObject({ + status: "waiting", + update: null, + }); + await restarted.check(); + expect(fetch).toHaveBeenCalledTimes(2); + time += hour; + await restarted.check(); + expect(fetch).toHaveBeenCalledTimes(3); + expect(await restarted.status()).toMatchObject({ status: "update" }); +}); + +it("aborts its local request on disable", async () => { + const fetch = vi.fn( + (_, init) => + new Promise((_, reject) => { + const signal = init!.signal!; + signal.addEventListener("abort", () => reject(signal.reason), { + once: true, + }); + }), + ); + const checker = createReleaseChecker(db, { fetch, now: () => time }); + const pending = checker.check(); + await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(1)); + await checker.setEnabled(false); + await pending; + expect(fetch.mock.calls[0]?.[1]?.signal?.aborted).toBe(true); + expect(await checker.status()).toMatchObject({ status: "disabled" }); +}); + +it.each([HOST_VERSION, "0.0.0"])( + "does not offer an update to %s", + async (version) => { + const checker = createReleaseChecker(db, { + fetch: async () => releaseResponse(version), + now: () => time, + }); + await checker.check(); + expect(await checker.status()).toMatchObject({ + status: "current", + update: null, + }); + }, +); + +it.each([ + ["an unavailable endpoint", () => new Response(null, { status: 404 })], + ["a prerelease", () => releaseResponse("20.0.0-rc.1")], + [ + "a response from an unsupported protocol", + () => Response.json({ protocolVersion: 2, latestVersion: nextVersion }), + ], + [ + "an oversized response", + () => + new Response(" ".repeat(4097), { + headers: { "Content-Type": "application/json" }, + }), + ], + ["an invalid image tag", () => releaseResponse("20.0.0; echo bad")], + [ + "a failed request", + () => { + throw new Error("Connection lost"); + }, + ], +] as const)( + "handles %s without retrying before the hourly slot", + async (_, response) => { + const fetch = vi.fn(async () => response()); + const checker = createReleaseChecker(db, { fetch, now: () => time }); + await checker.check(); + expect(await checker.status()).toMatchObject({ + status: "unavailable", + update: null, + }); + await checker.check(); + expect(fetch).toHaveBeenCalledTimes(1); + }, +); From 071fac504a1626f89f7b8291e79cf37e018d722d 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:07:40 +0800 Subject: [PATCH 2/2] Correct release regression fixture types --- tests/android-session-lifetime.test.ts | 2 +- tests/file-explorer-loading.test.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/android-session-lifetime.test.ts b/tests/android-session-lifetime.test.ts index f7c38c47..7815802a 100644 --- a/tests/android-session-lifetime.test.ts +++ b/tests/android-session-lifetime.test.ts @@ -19,7 +19,7 @@ it("keeps new Android sessions through a long absence and honors logout and admi try { const password = "android-session-fixture-password"; const admin = await createUser(db, { login: "owner", displayName: "Owner", password }, { bootstrap: true }); - const member = await createUser(db, { login: "member", displayName: "Member", password }, { actor: admin }); + const member = await createUser(db, { login: "member", displayName: "Member", password }, { actor: { ...admin, admin: 1 } }); app = await createApp(db, { origin }); async function login(account: string, extra: Record) { diff --git a/tests/file-explorer-loading.test.ts b/tests/file-explorer-loading.test.ts index 662f3622..7d85c8b3 100644 --- a/tests/file-explorer-loading.test.ts +++ b/tests/file-explorer-loading.test.ts @@ -1,4 +1,5 @@ // @vitest-environment jsdom +// @ts-expect-error jsdom is a runtime-only fixture dependency in this workspace. import { JSDOM } from "jsdom"; import { act, createElement } from "react"; import { createRoot } from "react-dom/client";
{t("admin.release.loadFailed")}
{t("common.loading")}
{settings.currentVersion}
{t("admin.release.composeHelp")}
{settings.update.image}
+ {composeCommand} +
{composeCommand}
{t("fileManager.loading")}