diff --git a/.github/workflows/octop-desktop.yml b/.github/workflows/octop-desktop.yml index 78e866700c..d325a36732 100644 --- a/.github/workflows/octop-desktop.yml +++ b/.github/workflows/octop-desktop.yml @@ -1,9 +1,18 @@ name: Octop Desktop Package # 正式发版:Auto Tag 在打 v* 后与 Release / Docker Publish 一并 dispatch。 -# 产物 upsert 到同一 GitHub Release,再上传到 COS octop/release//。 +# 每个原生 runner 打便携 zip + Electron 安装包,upsert 到同一 GitHub Release, +# 再上传到 COS octop/release//。 # 手工补包:workflow_dispatch + release_tag(不必跑在 v* ref 上)。 # attach_from_run 只挂已有 artifact、不重打。 +# +# 镜像固定到 ubuntu-24.04 而不是 ubuntu-latest:`latest` 已经公告要迁到 +# 26.04,发版机器的底层镜像不该由 GitHub 的时间表决定。 +# +# action 一律挑 `runs.using: node24` 的主版本(setup-uv@v7、 +# pnpm/action-setup@v6、action-gh-release@v3)。跑在 node20 上的版本会在 +# 每次运行里刷 "Node.js 20 is deprecated" 而不报错,属于会一直烂在那里的 +# 警告——升级时以 action.yml 里的 `runs.using` 为准,别看版本号大小猜。 on: push: @@ -59,13 +68,15 @@ jobs: frontend: name: Build dashboard if: github.event_name != 'workflow_dispatch' || github.event.inputs.attach_from_run == '' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v5 - uses: actions/setup-node@v5 with: - node-version: "24" + # Dashboard stays on Node 20 (same as docker/Dockerfile + release.yml). + # Node 24 is a desktop/electron-only pin and nothing here builds it. + node-version: "20" cache: npm cache-dependency-path: dashboard/package-lock.json @@ -84,7 +95,7 @@ jobs: select-platforms: name: Select platforms if: github.event_name != 'workflow_dispatch' || github.event.inputs.attach_from_run == '' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 outputs: matrix: ${{ steps.set.outputs.matrix }} steps: @@ -99,9 +110,9 @@ jobs: import os all_plats = [ - {"plat": "linux-amd64", "arch": "amd64", "os": "ubuntu-latest"}, + {"plat": "linux-amd64", "arch": "amd64", "os": "ubuntu-24.04"}, {"plat": "linux-arm64", "arch": "arm64", "os": "ubuntu-24.04-arm"}, - {"plat": "darwin-arm64", "arch": "arm64", "os": "macos-14"}, + {"plat": "darwin-arm64", "arch": "arm64", "os": "macos-15"}, {"plat": "darwin-amd64", "arch": "amd64", "os": "macos-15-intel"}, {"plat": "windows-amd64", "arch": "amd64", "os": "windows-latest"}, {"plat": "windows-arm64", "arch": "arm64", "os": "windows-11-arm"}, @@ -112,16 +123,16 @@ jobs: sel = os.environ.get("PLATFORMS", "all").lower().replace(" ", "") known = {row["plat"] for row in all_plats} if sel == "all": - include = all_plats + selected = all_plats else: wanted = {part for part in sel.split(",") if part} unknown = wanted - known if unknown: raise SystemExit(f"unknown platform(s): {', '.join(sorted(unknown))}") - include = [row for row in all_plats if row["plat"] in wanted] - if not include: + selected = [row for row in all_plats if row["plat"] in wanted] + if not selected: raise SystemExit(f"no platforms selected: {sel}") - matrix = json.dumps({"include": include}, separators=(",", ":")) + matrix = json.dumps({"include": selected}, separators=(",", ":")) with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as fh: fh.write(f"matrix={matrix}\n") print(matrix) @@ -133,6 +144,7 @@ jobs: runs-on: ${{ matrix.os }} # Matrix runners are native for each plat; pin host detection so x64 Git Bash # on windows-11-arm does not mis-classify the job as windows-amd64 cross-build. + # Installers are unsigned and not notarized. env: GREEN_HOST_PLAT: ${{ matrix.plat }} strategy: @@ -156,7 +168,7 @@ jobs: name: dashboard-dist path: src/octop/dashboard - - uses: astral-sh/setup-uv@v6 + - uses: astral-sh/setup-uv@v7 with: enable-cache: true python-version: "3.12" @@ -217,100 +229,150 @@ jobs: verify_no_homebrew_dylibs "${staging}/packages" "${{ matrix.plat }}" fi - - uses: actions/setup-go@v6 + # archive: false — upload the prebuilt zip as-is. Default archive=true would + # wrap it again, so Actions UI / "Download artifact" becomes zip-in-zip. + # With archive:false, artifact name is the filename (name: is ignored). + - uses: actions/upload-artifact@v7 with: - go-version: "1.25.x" - cache-dependency-path: desktop/src/go.sum + path: desktop/portable/release/Octop-portable-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.zip + archive: false + if-no-files-found: error + retention-days: 14 - - name: Install Linux desktop build dependencies - if: runner.os == 'Linux' + - name: Stage Electron runtime run: | - sudo apt-get update - sudo apt-get install -y libgtk-4-dev libwebkitgtk-6.0-dev + set -euo pipefail + plat="${{ matrix.plat }}" + zip="desktop/portable/release/Octop-portable-${plat}-${OCTOP_VERSION}.zip" + rm -rf desktop/src/resources/portable + mkdir -p desktop/src/resources/portable + # The shell serves packages/octop/dashboard from this tree. There is + # no second copy under resources/dashboard. + test -f "desktop/portable/release/Octop-${plat}/packages/octop/dashboard/index.html" + # Windows keeps one zip; NSIS extracts it with tar.exe. Packing the + # ~40k files into NSIS is slower. macOS (DMG) and Linux (deb/rpm) + # copy the tree package.sh already assembled. No zip in those apps. + if [[ "$plat" == windows-* ]]; then + cp "$zip" desktop/src/resources/portable/ + else + inner="desktop/portable/release/Octop-${plat}" + if [[ ! -f "$inner/launch.py" ]]; then + echo "expanded portable tree has no launch.py under ${inner}" >&2 + exit 1 + fi + shopt -s dotglob + cp -a "$inner"/. desktop/src/resources/portable/ + shopt -u dotglob + test -x desktop/src/resources/portable/runtime/bin/python3 + test ! -e desktop/src/resources/portable/*.zip + fi + if [[ "$plat" == windows-* ]]; then py=python; else py=python3; fi + "$py" - "$zip" "$OCTOP_VERSION" <<'PY' + import hashlib + import json + import pathlib + import sys + import zipfile + + path = pathlib.Path(sys.argv[1]) + if not zipfile.is_zipfile(path): + raise SystemExit(f"not a portable zip: {path}") + manifest = {"version": sys.argv[2], "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} + dest = pathlib.Path("desktop/src/resources/portable/portable-version.json") + dest.write_text(json.dumps(manifest) + "\n", encoding="utf-8") + print(f"Bundled {path.name} with SHA-256 {manifest['sha256']}") + PY + if [[ "$plat" != windows-* ]]; then + test -f desktop/src/resources/portable/packages/octop/dashboard/index.html + fi + + - uses: actions/setup-node@v5 + with: + node-version: "24" - - name: Install Wails v3 CLI - run: go install github.com/wailsapp/wails/v3/cmd/wails3@v3.0.0-beta.13 + # v6 起改用 node24 运行时;`run_install` 仍存在,留着 false 是为了让 + # 下一步那个显式的 `pnpm install --frozen-lockfile` 是唯一一次安装。 + - uses: pnpm/action-setup@v6 + with: + version: 12.15.0 + run_install: false - - name: Install NSIS - if: runner.os == 'Windows' - shell: pwsh + - name: Install and check Electron shell + working-directory: desktop/src run: | - $nsisDir = "${env:ProgramFiles(x86)}\NSIS" - $makensis = Join-Path $nsisDir "makensis.exe" - function Test-Makensis { Test-Path -LiteralPath $makensis } - - if (-not (Test-Makensis)) { - $installed = $false - for ($i = 1; $i -le 5; $i++) { - Write-Host "choco install nsis (attempt $i/5)" - try { - choco install nsis --yes --no-progress --execution-timeout=600 - } catch { - Write-Warning "choco attempt $i failed: $_" - } - if (Test-Makensis) { $installed = $true; break } - Start-Sleep -Seconds ([Math]::Min(60, 10 * $i)) - } - - if (-not $installed) { - Write-Host "Chocolatey unavailable; downloading NSIS setup from SourceForge" - $setup = Join-Path $env:RUNNER_TEMP "nsis-setup.exe" - $urls = @( - "https://downloads.sourceforge.net/project/nsis/NSIS%203/3.11/nsis-3.11-setup.exe", - "https://sourceforge.net/projects/nsis/files/NSIS%203/3.11/nsis-3.11-setup.exe/download" - ) - $downloaded = $false - foreach ($url in $urls) { - try { - Invoke-WebRequest -Uri $url -OutFile $setup -UseBasicParsing -TimeoutSec 180 - if ((Test-Path -LiteralPath $setup) -and ((Get-Item $setup).Length -gt 1MB)) { - $downloaded = $true - break - } - } catch { - Write-Warning "NSIS download failed from $url : $_" - } - } - if (-not $downloaded) { - throw "NSIS install failed (Chocolatey and direct download)" - } - Start-Process -FilePath $setup -ArgumentList "/S" -Wait - } - } - - if (-not (Test-Makensis)) { - throw "makensis.exe missing after NSIS install" - } - Add-Content -Path $env:GITHUB_PATH -Value $nsisDir - - - name: Package desktop app with bundled portable runtime + pnpm install --frozen-lockfile + pnpm run typecheck + pnpm run test + + - name: Build native Electron installers working-directory: desktop/src - run: >- - wails3 task package - ARCH=${{ matrix.arch }} - VERSION=${{ env.OCTOP_VERSION }} - PORTABLE_ZIP=../portable/release/Octop-portable-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.zip + env: + OCTOP_PLATFORM: ${{ matrix.plat }} + # Empty, not omitted: a CSC_LINK in the runner environment overrides + # mac.identity: null and electron-builder tries to sign. + CSC_LINK: "" + CSC_KEY_PASSWORD: "" + WIN_CSC_LINK: "" + WIN_CSC_KEY_PASSWORD: "" + APPLE_ID: "" + APPLE_APP_SPECIFIC_PASSWORD: "" + APPLE_TEAM_ID: "" + run: | + set -euo pipefail + pnpm run build + case "${{ matrix.plat }}" in + darwin-*) target=--mac ;; + windows-*) target=--win ;; + linux-*) target=--linux ;; + *) echo "Unsupported Electron target: ${{ matrix.plat }}" >&2; exit 1 ;; + esac + if [[ "${{ matrix.arch }}" == amd64 ]]; then arch=--x64; else arch=--arm64; fi + pnpm exec electron-builder --config electron-builder.config.ts "$target" "$arch" --publish never + + # archive:false preserves each installer; different formats must be uploaded + # separately (one file per artifact), not wrapped in an extra Actions zip. + - uses: actions/upload-artifact@v7 + if: startsWith(matrix.plat, 'darwin-') + with: + path: desktop/src/release/Octop-desktop-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.dmg + archive: false + if-no-files-found: error + retention-days: 14 - # archive: false — upload the prebuilt zip as-is. Default archive=true would - # wrap it again, so Actions UI / "Download artifact" becomes zip-in-zip. - # With archive:false, artifact name is the filename (name: is ignored). - uses: actions/upload-artifact@v7 + if: startsWith(matrix.plat, 'darwin-') with: - path: desktop/portable/release/Octop-portable-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.zip + path: desktop/src/release/Octop-desktop-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.zip archive: false if-no-files-found: error retention-days: 14 - - name: Upload bundled desktop package - uses: actions/upload-artifact@v7 + - uses: actions/upload-artifact@v7 + if: startsWith(matrix.plat, 'windows-') + with: + path: desktop/src/release/Octop-desktop-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.exe + archive: false + if-no-files-found: error + retention-days: 14 + + - uses: actions/upload-artifact@v7 + if: startsWith(matrix.plat, 'linux-') + with: + path: desktop/src/release/Octop-desktop-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.deb + archive: false + if-no-files-found: error + retention-days: 14 + + - uses: actions/upload-artifact@v7 + if: startsWith(matrix.plat, 'linux-') with: - path: desktop/src/bin/Octop-desktop-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.* + path: desktop/src/release/Octop-desktop-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.rpm archive: false if-no-files-found: error retention-days: 14 release: - name: Attach zips to GitHub Release + name: Attach packages to GitHub Release needs: package outputs: tag: ${{ steps.rel.outputs.tag }} @@ -330,7 +392,7 @@ jobs: (github.event_name == 'workflow_dispatch' && github.event.inputs.attach_release == 'true'))) ) - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 permissions: contents: write actions: read @@ -350,8 +412,8 @@ jobs: echo "tag=${tag}" >> "$GITHUB_OUTPUT" # v8 required for archive:false artifacts. skip-decompress keeps the - # uploaded .zip / .tar.gz / .dmg / .exe intact — default unzip turns portable - # zips into directories, so files: release-assets/* would skip them. + # uploaded .zip / .dmg / .exe intact — default unzip turns portable zips + # into directories, so files: release-assets/* would skip them. - uses: actions/download-artifact@v8 with: pattern: Octop-* @@ -373,7 +435,7 @@ jobs: fi - name: Upload to GitHub Release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v3 with: tag_name: ${{ steps.rel.outputs.tag }} files: release-assets/* @@ -390,7 +452,7 @@ jobs: uses: ./.github/workflows/upload-release-cos.yml with: tag: ${{ needs.release.outputs.tag }} - patterns: "Octop-desktop-*,Octop-portable-*" + patterns: "Octop-portable-*,Octop-desktop-*" secrets: RELEASE_COS_SECRET_ID: ${{ secrets.RELEASE_COS_SECRET_ID }} RELEASE_COS_SECRET_KEY: ${{ secrets.RELEASE_COS_SECRET_KEY }} diff --git a/.gitignore b/.gitignore index 9918065cd4..47ab4b023f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # Build build/ +# NSIS include lives here; the blanket build/ rule would hide it. !desktop/src/build/ !desktop/src/build/** dist/ @@ -53,7 +54,9 @@ coverage.xml .hypothesis/ # IDE / editors -.vscode/ +.vscode/* +!.vscode/settings.json +!.vscode/css-custom-data.json .idea/ .codebuddy *.swp diff --git a/.vscode/css-custom-data.json b/.vscode/css-custom-data.json new file mode 100644 index 0000000000..3dcaa52978 --- /dev/null +++ b/.vscode/css-custom-data.json @@ -0,0 +1,19 @@ +{ + "version": 1.1, + "properties": [ + { + "name": "app-region", + "status": "nonstandard", + "description": "Electron/Chromium window drag region. `drag` makes the element a window drag handle; `no-drag` keeps a control clickable inside a drag region.", + "syntax": "drag | no-drag", + "values": [{ "name": "drag" }, { "name": "no-drag" }] + }, + { + "name": "-webkit-app-region", + "status": "nonstandard", + "description": "Vendor-prefixed form of `app-region`. Chromium uses this name for frameless-window dragging.", + "syntax": "drag | no-drag", + "values": [{ "name": "drag" }, { "name": "no-drag" }] + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000000..a8a0a1add5 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "css.customData": [".vscode/css-custom-data.json"], + "less.customData": [".vscode/css-custom-data.json"] +} diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b01a8c67f..1a0e83dbd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,24 @@ ## [Unreleased] +## [1.0.3b5] - 2026-11-11 + +### 新增 +- 桌面客户端改为 Electron 壳,登录过期后自动续上 +- 自定义 MCP 可填写 OAuth 应用凭证并完成授权 +- 新增 `octop migrate openclaw` / `octop migrate hermes`,把原有助手迁到一个专家 +- 知识库内的文档和文件夹可以移动。共享专家上可以分享对话 +- 专家市场默认打开「精选」。管理员可按用户查看用量 + +### 变更 +- 桌面端不再使用 Wails +- 升级 octop-harness 至 1.0.9、octop-memory 至 1.0.4 + +### 修复 +- 下线 history v2,启动时把已有归档迁回原有历史表 +- 云端协同不再因心跳超时反复断开 +- 共享会话的回复不再重叠。聊天里的模型和提问顺序保持正确 + ## [1.0.3b4] - 2026-11-06 ### 新增 @@ -38,6 +56,7 @@ - 超长图片先缩小再发送。失效的默认模型会自动换掉 - 升级记忆库:长会话分批提炼,重启后不重跑 - 安装清理不再删掉运行环境。PostgreSQL 上的知识库检索和关怀去重恢复正常 +- IM 通道的对话请求也会带上配置的推理强度,和 Dashboard 路径一致 ### 变更 - 升级 octop-harness 至 1.0.7 @@ -70,6 +89,7 @@ - 表单和对话可以让 AI 润色。搜索增加 DeepSeek 与元宝,模型支持 OpenAI Responses API ### 修复 +- 记忆配置 API 支持独立开关自动记录对话与自动注入召回结果,显式关闭时正确传递到运行时,避免配置被静默忽略(#2282)。 - 云端协同共享后可以直接对话。回复进行中不会被刷新冲掉,也不能删掉这场会话 - 手机截图写到专家自己的工作区。只改定时任务文案时,间隔任务不再重新计时 - 浏览器工作台恢复中文输入。主动关怀等对话安静后再发 diff --git a/Makefile b/Makefile index afc0a00f76..293e8dc509 100644 --- a/Makefile +++ b/Makefile @@ -97,7 +97,8 @@ build-frontend: @echo "[build-frontend] Installing npm dependencies..." cd $(DASHBOARD_DIR) && npm ci @echo "[build-frontend] Building dashboard (output: $(DASHBOARD_DEST))..." - cd $(DASHBOARD_DIR) && NODE_ENV=production NODE_OPTIONS="--max-old-space-size=2048" npm run build + # Render peaks above 2GB (Full GC, then OOM at 2048 on GitHub runners). + cd $(DASHBOARD_DIR) && NODE_ENV=production NODE_OPTIONS="--max-old-space-size=4096" npm run build @echo "[build-frontend] Done." .PHONY: build-wheel diff --git a/README.md b/README.md index 4e98889a6a..ba771bd325 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@

Python 3.12+ License: MIT - Version + Version PyPI Code Style: Ruff GitHub stars @@ -231,6 +231,8 @@ See [scripts/README.md](scripts/README.md) for all install options (`--version`, | Linux | `Octop-desktop-linux-amd64-.tar.gz` / `Octop-desktop-linux-arm64-.tar.gz` | | FnOS NAS | `Octop-fnos-docker-lite-.fpk` (smaller image) / `Octop-fnos-docker-.fpk` (full: desktop, OCR, local models) / `Octop-fnos-native-amd64-.fpk` (x86_64, no Docker) / `Octop-fnos-native-arm64-.fpk` (ARM64 fallback if no Docker) — install via App Center | +Desktop installers bundle the `browser` extra only. Desktop control, OCR, and local embedding stay on the Docker image tag `:-full`. + See [desktop/README.md](desktop/README.md) for the desktop shell and [fnos/README.md](fnos/README.md) for the FnOS packaging guide. **Alternative — PyPI** (if you already manage Python yourself): @@ -429,6 +431,7 @@ Full catalog, auth kinds, and MCP modes: **[docs/connectors.md](docs/connectors. | `octop skills` | Enable/disable per-agent skills | | `octop plugin` | Install and manage third-party plugins | | `octop backup` | Export / restore backups | +| `octop migrate` | Migrate an OpenClaw or Hermes Agent setup into an expert | | `octop clean` | Remove CLI state or wipe `~/.octop/` | | `octop memory list` | List running agents eligible for memory maintenance; no database changes. | | `octop memory slim [--agent ID]` | Back up and slim SQLite memory through the running host; uses the selected agent or prompts by number. Shows terminal and dashboard progress. [Details](docs/memory-slim.md) | diff --git a/README_CN.md b/README_CN.md index 7f59607b4a..61b2c1c0ca 100644 --- a/README_CN.md +++ b/README_CN.md @@ -15,7 +15,7 @@

Python 3.12+ License: MIT - Version + Version PyPI Code Style: Ruff GitHub stars @@ -233,6 +233,8 @@ curl -fsSL https://download.octop.cloud/octop/scripts/install.sh | bash -s -- -- | Linux | `Octop-desktop-linux-amd64-.tar.gz` / `Octop-desktop-linux-arm64-.tar.gz` | | 飞牛 NAS(FnOS) | `Octop-fnos-docker-lite-.fpk`(精简镜像)/ `Octop-fnos-docker-.fpk`(完整版:桌面、OCR、本地向量)/ `Octop-fnos-native-amd64-.fpk`(x86_64,无需 Docker)/ `Octop-fnos-native-arm64-.fpk`(ARM64,无 Docker 时再用)— 通过应用中心安装 | +桌面安装包只带 `browser`。桌面控制、OCR 和本地向量留在 Docker 镜像标签 `:-full`。 + 桌面客户端说明见 [desktop/README.md](desktop/README.md),飞牛打包指南见 [fnos/README.md](fnos/README.md)。 **备选 — PyPI**(若你已自行管理 Python 环境): @@ -426,6 +428,7 @@ OpenAI 兼容 API、DashScope(千问)、Ollama 等预设 — 在控制台或 | `octop skills` | 按 Agent 启用/禁用 Skill | | `octop plugin` | 安装并管理第三方插件 | | `octop backup` | 导出 / 恢复备份 | +| `octop migrate` | 把 OpenClaw 或 Hermes Agent 的配置迁移到一个专家 | | `octop clean` | 清理 CLI 状态或清空 `~/.octop/` | | `octop memory list` | 列出可参与记忆维护的运行中 Agent;不改动数据库。 | | `octop memory slim [--agent ID]` | 通过运行中的宿主备份并精简 SQLite 记忆;使用指定 Agent 或按提示选择。在终端与控制台显示进度。[详情](docs/memory-slim.md) | diff --git a/dashboard/index.html b/dashboard/index.html index 872fa7bc34..359ab10edd 100644 --- a/dashboard/index.html +++ b/dashboard/index.html @@ -35,6 +35,12 @@ the splash CSS keys off html[data-theme], not prefers-color-scheme, so a stored "light" preference wins over an OS dark setting. Storage shape matches appearanceStorage.ts (THEME_STORAGE_KEY = "theme"). + + The desktop shell loads this page with ?octopTheme=system|light|dark + (DASHBOARD_THEME_QUERY in desktop/src/main/windows/chrome.ts). That + device preference wins over localStorage and is written back, then the + query is removed so a later reload keeps the stored value. Browser + loads have no query and keep using localStorage alone. --> +

+
-
+
diff --git a/dashboard/package-lock.json b/dashboard/package-lock.json index 5e9b3167ee..c983222eb0 100644 --- a/dashboard/package-lock.json +++ b/dashboard/package-lock.json @@ -9,6 +9,7 @@ "version": "0.1.0", "dependencies": { "@aiden0z/pptx-renderer": "^1.2.4", + "@ant-design/icons": "^5.6.1", "@mermaid-js/parser": "^1.1.0", "@monaco-editor/react": "^4.7.0", "@xterm/addon-fit": "0.10.0", @@ -19,9 +20,11 @@ "antd-style": "^3.7.1", "build": "^0.1.4", "classnames": "^2.5.1", + "dayjs": "^1.11.23", "docx-preview": "^0.3.2", "i18next": "^25.8.4", "jszip": "^3.10.1", + "katex": "^0.16.47", "lucide-react": "^0.562.0", "mermaid": "^11.13.0", "monaco-editor": "0.57.0", @@ -68,6 +71,7 @@ "typescript-eslint": "^8.30.1", "vite": "^6.3.5", "vite-plugin-pwa": "^0.21.2", + "vite-plugin-svgr": "^5.2.0", "vitest": "^3.2.6" } }, @@ -169,7 +173,6 @@ "version": "5.6.1", "resolved": "https://registry.npmjs.org/@ant-design/icons/-/icons-5.6.1.tgz", "integrity": "sha512-0/xS39c91WjPAZOWsvi1//zjx6kAp4kxWwctR6kuU6p133w8RU0D2dSCvZC19uQyharg/sAvYxGYWl01BbZZfg==", - "license": "MIT", "dependencies": { "@ant-design/colors": "^7.0.0", "@ant-design/icons-svg": "^4.4.0", @@ -3827,6 +3830,271 @@ "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==", "license": "MIT" }, + "node_modules/@svgr/babel-plugin-add-jsx-attribute": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-add-jsx-attribute/-/babel-plugin-add-jsx-attribute-8.0.0.tgz", + "integrity": "sha512-b9MIk7yhdS1pMCZM8VeNfUlSKVRhsHZNMl5O9SfaX0l0t5wjdgu4IDzGB8bpnGBBOjGST3rRFVsaaEtI4W6f7g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-remove-jsx-attribute": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-remove-jsx-attribute/-/babel-plugin-remove-jsx-attribute-8.0.0.tgz", + "integrity": "sha512-BcCkm/STipKvbCl6b7QFrMh/vx00vIP63k2eM66MfHJzPr6O2U0jYEViXkHJWqXqQYjdeA9cuCl5KWmlwjDvbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-remove-jsx-empty-expression": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-remove-jsx-empty-expression/-/babel-plugin-remove-jsx-empty-expression-8.0.0.tgz", + "integrity": "sha512-5BcGCBfBxB5+XSDSWnhTThfI9jcO5f0Ai2V24gZpG+wXF14BzwxxdDb4g6trdOux0rhibGs385BeFMSmxtS3uA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-replace-jsx-attribute-value": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-replace-jsx-attribute-value/-/babel-plugin-replace-jsx-attribute-value-8.0.0.tgz", + "integrity": "sha512-KVQ+PtIjb1BuYT3ht8M5KbzWBhdAjjUPdlMtpuw/VjT8coTrItWX6Qafl9+ji831JaJcu6PJNKCV0bp01lBNzQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-svg-dynamic-title": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-svg-dynamic-title/-/babel-plugin-svg-dynamic-title-8.0.0.tgz", + "integrity": "sha512-omNiKqwjNmOQJ2v6ge4SErBbkooV2aAWwaPFs2vUY7p7GhVkzRkJ00kILXQvRhA6miHnNpXv7MRnnSjdRjK8og==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-svg-em-dimensions": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-svg-em-dimensions/-/babel-plugin-svg-em-dimensions-8.0.0.tgz", + "integrity": "sha512-mURHYnu6Iw3UBTbhGwE/vsngtCIbHE43xCRK7kCw4t01xyGqb2Pd+WXekRRoFOBIY29ZoOhUCTEweDMdrjfi9g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-transform-react-native-svg": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-transform-react-native-svg/-/babel-plugin-transform-react-native-svg-8.1.0.tgz", + "integrity": "sha512-Tx8T58CHo+7nwJ+EhUwx3LfdNSG9R2OKfaIXXs5soiy5HtgoAEkDay9LIimLOcG8dJQH1wPZp/cnAv6S9CrR1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-transform-svg-component": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-transform-svg-component/-/babel-plugin-transform-svg-component-8.0.0.tgz", + "integrity": "sha512-DFx8xa3cZXTdb/k3kfPeaixecQLgKh5NVBMwD0AQxOzcZawK4oo1Jh9LbrcACUivsCA7TLG8eeWgrDXjTMhRmw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-preset": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@svgr/babel-preset/-/babel-preset-8.1.0.tgz", + "integrity": "sha512-7EYDbHE7MxHpv4sxvnVPngw5fuR6pw79SkcrILHJ/iMpuKySNCl5W1qcwPEpU+LgyRXOaAFgH0KhwD18wwg6ug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@svgr/babel-plugin-add-jsx-attribute": "8.0.0", + "@svgr/babel-plugin-remove-jsx-attribute": "8.0.0", + "@svgr/babel-plugin-remove-jsx-empty-expression": "8.0.0", + "@svgr/babel-plugin-replace-jsx-attribute-value": "8.0.0", + "@svgr/babel-plugin-svg-dynamic-title": "8.0.0", + "@svgr/babel-plugin-svg-em-dimensions": "8.0.0", + "@svgr/babel-plugin-transform-react-native-svg": "8.1.0", + "@svgr/babel-plugin-transform-svg-component": "8.0.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/core": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@svgr/core/-/core-8.1.0.tgz", + "integrity": "sha512-8QqtOQT5ACVlmsvKOJNEaWmRPmcojMOzCz4Hs2BGG/toAp/K38LcsMRyLp349glq5AzJbCEeimEoxaX6v/fLrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.21.3", + "@svgr/babel-preset": "8.1.0", + "camelcase": "^6.2.0", + "cosmiconfig": "^8.1.3", + "snake-case": "^3.0.4" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + } + }, + "node_modules/@svgr/core/node_modules/cosmiconfig": { + "version": "8.3.6", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-8.3.6.tgz", + "integrity": "sha512-kcZ6+W5QzcJ3P1Mt+83OUv/oHFqZHIx8DuxG6eZ5RGMERoLqp4BuGjhHLYGK+Kf5XVkQvqBSmAy/nGWN3qDgEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "import-fresh": "^3.3.0", + "js-yaml": "^4.1.0", + "parse-json": "^5.2.0", + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/d-fischer" + }, + "peerDependencies": { + "typescript": ">=4.9.5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@svgr/hast-util-to-babel-ast": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@svgr/hast-util-to-babel-ast/-/hast-util-to-babel-ast-8.0.0.tgz", + "integrity": "sha512-EbDKwO9GpfWP4jN9sGdYwPBU0kdomaPIL2Eu4YwmgP+sJeXT+L7bMwJUBnhzfH8Q2qMBqZ4fJwpCyYsAN3mt2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.21.3", + "entities": "^4.4.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + } + }, + "node_modules/@svgr/hast-util-to-babel-ast/node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/@svgr/plugin-jsx": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@svgr/plugin-jsx/-/plugin-jsx-8.1.0.tgz", + "integrity": "sha512-0xiIyBsLlr8quN+WyuxooNW9RJ0Dpr8uOnH/xrCVO8GLUcwHISwj1AG0k+LFzteTkAA0GbX0kj9q6Dk70PTiPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.21.3", + "@svgr/babel-preset": "8.1.0", + "@svgr/hast-util-to-babel-ast": "8.0.0", + "svg-parser": "^2.0.4" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@svgr/core": "*" + } + }, "node_modules/@testing-library/dom": { "version": "10.4.1", "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz", @@ -5499,6 +5767,19 @@ "node": ">=6" } }, + "node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/caniuse-lite": { "version": "1.0.30001793", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001793.tgz", @@ -6550,9 +6831,9 @@ } }, "node_modules/dayjs": { - "version": "1.11.21", - "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.21.tgz", - "integrity": "sha512-98IT+HOahAisibz/yjKbzuOBwYcjJ7BCLPzARyHiyEBmRz4fatF+KPJszEHXsGYjUG234aH/cOjW1wwTbKUZlA==" + "version": "1.11.23", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz", + "integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==" }, "node_modules/debug": { "version": "4.4.3", @@ -6735,6 +7016,17 @@ "@types/trusted-types": "^2.0.7" } }, + "node_modules/dot-case": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/dot-case/-/dot-case-3.0.4.tgz", + "integrity": "sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "no-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -9457,6 +9749,16 @@ "dev": true, "license": "MIT" }, + "node_modules/lower-case": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-2.0.2.tgz", + "integrity": "sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.0.3" + } + }, "node_modules/lowlight": { "version": "1.20.0", "resolved": "https://registry.npmjs.org/lowlight/-/lowlight-1.20.0.tgz", @@ -10716,6 +11018,17 @@ "node": ">= 4.4.x" } }, + "node_modules/no-case": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/no-case/-/no-case-3.0.4.tgz", + "integrity": "sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==", + "dev": true, + "license": "MIT", + "dependencies": { + "lower-case": "^2.0.2", + "tslib": "^2.0.3" + } + }, "node_modules/node-releases": { "version": "2.0.46", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.46.tgz", @@ -12935,6 +13248,17 @@ "node": ">=20.0.0" } }, + "node_modules/snake-case": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/snake-case/-/snake-case-3.0.4.tgz", + "integrity": "sha512-LAOh4z89bGQvl9pFfNF8V146i7o7/CqFPbqzYgP+yYzDIDeS9HaNFtXABamRW+AQzEVODcvE79ljJ+8a9YSdMg==", + "dev": true, + "license": "MIT", + "dependencies": { + "dot-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, "node_modules/source-map": { "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", @@ -13328,6 +13652,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/svg-parser": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/svg-parser/-/svg-parser-2.1.0.tgz", + "integrity": "sha512-bwLf38YmY+TDYHJw1Ex0Co8c4yeXuJAo8YnXGZrscxrvYoVVIvLeniEkV1Ks/54VteMnL4FtyN1+P+TZJdUPmQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/symbol-tree": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", @@ -14474,6 +14808,21 @@ } } }, + "node_modules/vite-plugin-svgr": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/vite-plugin-svgr/-/vite-plugin-svgr-5.2.0.tgz", + "integrity": "sha512-qj2eAKF8C6PZWemVTvQA0xgQIcP1hHU6Buh7fl6BhvayWwnuxE+z417miKxeDvRWbDrupQ1oK99hfxElopJ3sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.3.0", + "@svgr/core": "^8.1.0", + "@svgr/plugin-jsx": "^8.1.0" + }, + "peerDependencies": { + "vite": ">=3.0.0" + } + }, "node_modules/vitest": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.6.tgz", diff --git a/dashboard/package.json b/dashboard/package.json index 8320c9ccb0..ce10b61dd5 100644 --- a/dashboard/package.json +++ b/dashboard/package.json @@ -22,6 +22,7 @@ }, "dependencies": { "@aiden0z/pptx-renderer": "^1.2.4", + "@ant-design/icons": "^5.6.1", "@mermaid-js/parser": "^1.1.0", "@monaco-editor/react": "^4.7.0", "@xterm/addon-fit": "0.10.0", @@ -32,9 +33,11 @@ "antd-style": "^3.7.1", "build": "^0.1.4", "classnames": "^2.5.1", + "dayjs": "^1.11.23", "docx-preview": "^0.3.2", "i18next": "^25.8.4", "jszip": "^3.10.1", + "katex": "^0.16.47", "lucide-react": "^0.562.0", "mermaid": "^11.13.0", "monaco-editor": "0.57.0", @@ -85,6 +88,7 @@ "typescript-eslint": "^8.30.1", "vite": "^6.3.5", "vite-plugin-pwa": "^0.21.2", + "vite-plugin-svgr": "^5.2.0", "vitest": "^3.2.6" } } diff --git a/dashboard/public/logo_mark.svg b/dashboard/public/logo_mark.svg new file mode 100644 index 0000000000..dd6179ae21 --- /dev/null +++ b/dashboard/public/logo_mark.svg @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dashboard/public/offline.html b/dashboard/public/offline.html index aea84eda44..eef133a82c 100644 --- a/dashboard/public/offline.html +++ b/dashboard/public/offline.html @@ -1,5 +1,5 @@ - + Octop — 离线中 + -
- +
+

当前处于离线状态

-

无法连接到 Octop 服务端。
请检查网络连接后重试。

- +

无法连接到 Octop 服务端,请检查网络连接后重试。

+
+ diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx index d278fadbbf..1f40bc8d18 100644 --- a/dashboard/src/App.tsx +++ b/dashboard/src/App.tsx @@ -5,11 +5,11 @@ import enUS from "antd/locale/en_US"; import dayjs from "dayjs"; import "dayjs/locale/zh-cn"; import { useEffect } from "react"; -import DesktopWindowControls from "./components/DesktopWindowControls"; import { DesktopChromeProvider, useDesktopChrome, } from "./hooks/useDesktopChrome"; +import { useNativeWindowChrome } from "./hooks/useNativeWindowChrome"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import { routerBasename } from "./utils/publicUrl"; import { useTranslation } from "react-i18next"; @@ -19,8 +19,12 @@ import OidcComplete from "./pages/Login/OidcComplete"; import SetupPage from "./pages/Setup"; import InvitePage from "./pages/Invite"; import AuthGuard from "./components/AuthGuard"; +import PwaUpdatePrompt from "./components/PwaUpdatePrompt"; +import DesktopWindowDragBand from "./components/DesktopWindowDragBand"; +import WindowsAppMenu from "./components/WindowsAppMenu"; import OctopSpinner from "./components/OctopSpinner"; import { AntdAppProvider } from "./components/AntdAppProvider"; +import { popupLayer } from "./utils/overlayLayers"; import GlobalErrorBoundary from "./components/ErrorBoundary"; import { ThemeProvider, useTheme } from "./context/ThemeContext"; import { AgentProvider } from "./context/AgentContext"; @@ -28,7 +32,6 @@ import { LayoutModeProvider } from "./context/LayoutModeContext"; import { VoiceOutputProvider } from "./context/VoiceOutputContext"; import { useIsMobile } from "./hooks/useIsMobile"; import { useUnauthorizedRedirect } from "./hooks/useUnauthorizedRedirect"; -import { installDesktopExternalLinks } from "./utils/desktopExternalLinks"; import { brandTokensFor } from "./styles/themePalettes"; import "./styles/theme-vars.css"; import "./styles/layout.css"; @@ -47,6 +50,8 @@ function ThemedApp() { const { t, i18n } = useTranslation(); const isMobile = useIsMobile(); const desktopChrome = useDesktopChrome(); + // Native window buttons follow the app theme. Linux draws square ones. + useNativeWindowChrome(); const brandTokens = brandTokensFor(palette, isDark, customColor); // Make antd built-ins (Popconfirm OK/Cancel, Modal default footer, Empty, // Pagination, DatePicker, Table… ) follow the current UI language. @@ -57,8 +62,6 @@ function ThemedApp() { useUnauthorizedRedirect(); - useEffect(() => installDesktopExternalLinks(), []); - // Set document title based on current language useEffect(() => { document.title = t("app.pageTitle"); @@ -125,13 +128,16 @@ function ThemedApp() { theme={themeConfig} prefixCls="octop" locale={antdLocale} + getPopupContainer={popupLayer} spin={{ indicator: }} > - {desktopChrome ? ( - - ) : null} + + {/* Login, setup and invite sit outside MainLayout, so the drag + strip has to live above the router, not only inside the shell. */} + + } /> } /> diff --git a/dashboard/src/api/config.ts b/dashboard/src/api/config.ts index baa464153b..4207a22064 100644 --- a/dashboard/src/api/config.ts +++ b/dashboard/src/api/config.ts @@ -1,3 +1,4 @@ +import { resolveWsUrl } from "../utils/desktopWsUrl"; import { routerBasename } from "../utils/publicUrl"; declare const BASE_URL: string; @@ -35,7 +36,7 @@ export function getWsUrl(path: string): string { return httpUrl.replace("https://", "wss://"); } - // Relative URL — derive from current page location - const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; - return `${protocol}//${window.location.host}${httpUrl}`; + // Relative URL — derive from the page origin, or from the shell's relay when + // the page is served by the desktop shell (§5.2). + return resolveWsUrl(httpUrl); } diff --git a/dashboard/src/api/desktopSession.ts b/dashboard/src/api/desktopSession.ts new file mode 100644 index 0000000000..0c3b8d4bbc --- /dev/null +++ b/dashboard/src/api/desktopSession.ts @@ -0,0 +1,114 @@ +/** + * Desktop session bridge (§7 accounts). + * + * Desktop builds have no password a user could type, so the shell owns a device + * credential and can mint a fresh JWT on demand. The renderer only sees the + * token that comes back — never the credential itself. + * + * On the web `window.octopDesktop` is undefined and every helper here is a + * no-op, which is why the rest of the Dashboard needs no build flag. + */ + +import { + getDesktopBridge, + type DesktopIssuedSession, + type DesktopSessionBridge, +} from "../utils/desktopBridge"; + +export type IssuedSession = DesktopIssuedSession; + +/** The shell's session bridge, when this page is running inside the app. */ +function bridge(): DesktopSessionBridge | undefined { + return getDesktopBridge()?.session; +} + +/** Desktop wizard default. Only this username skips the login screen. */ +export const LOCAL_DESKTOP_USERNAME = "local"; + +const LOCAL_SIGNOUT_KEY = "octop:desktop-local-signed-out"; + +/** + * Claim of a JWT. Returns null when the token is not a decodable JWT or the + * claim is absent. + */ +function claimOf(token: string, key: "sub" | "uname"): string | null { + const parts = token.split("."); + if (parts.length < 2) return null; + try { + const payload = parts[1].replace(/-/g, "+").replace(/_/g, "/"); + const padded = payload + "=".repeat((4 - (payload.length % 4)) % 4); + const claims = JSON.parse(atob(padded)) as { + sub?: unknown; + uname?: unknown; + }; + const value = claims[key]; + return typeof value === "string" ? value : null; + } catch { + return null; + } +} + +/** Subject claim, used to notice a different user signing in. */ +function subjectOf(token: string): string | null { + return claimOf(token, "sub"); +} + +/** True when this JWT belongs to the desktop local account. */ +export function isLocalDesktopUser(accessToken: string): boolean { + return claimOf(accessToken, "uname") === LOCAL_DESKTOP_USERNAME; +} + +/** + * Logout of `local` sets this for the current window so the login page stays + * up and another account can sign in. A new app launch clears it. + */ +export function holdDesktopLocalAutoLogin(): void { + sessionStorage.setItem(LOCAL_SIGNOUT_KEY, "1"); +} + +/** The local-account button signs back in, so the logout hold no longer applies. */ +export function releaseDesktopLocalAutoLogin(): void { + sessionStorage.removeItem(LOCAL_SIGNOUT_KEY); +} + +export function desktopLocalAutoLoginHeld(): boolean { + return sessionStorage.getItem(LOCAL_SIGNOUT_KEY) === "1"; +} + +// The credential is bound to a user, not to a token, so registering once per +// page load (per user) is enough — sliding renewal rotates the JWT constantly +// and must not trigger a write each time. +let registeredSubject: string | null = null; + +/** + * Bind the shell's device credential to the signed-in user. + * + * Fire-and-forget: a failure only means the next cold start falls back to the + * login screen, which is exactly what happened before this existed. + */ +export async function registerDeviceSession( + accessToken: string, +): Promise { + const session = bridge(); + if (!session || !accessToken || !isLocalDesktopUser(accessToken)) return; + const subject = subjectOf(accessToken) ?? accessToken; + if (registeredSubject === subject) return; + try { + if (await session.register(accessToken)) { + registeredSubject = subject; + } + } catch { + // Keep registeredSubject unset so the next request retries. + } +} + +/** Ask the shell for a new JWT; null when the credential is gone or refused. */ +export async function renewDesktopSession(): Promise { + const session = bridge(); + if (!session) return null; + try { + return await session.renew(); + } catch { + return null; + } +} diff --git a/dashboard/src/api/modules/auth.ts b/dashboard/src/api/modules/auth.ts index d3b66f966a..5a8066185b 100644 --- a/dashboard/src/api/modules/auth.ts +++ b/dashboard/src/api/modules/auth.ts @@ -33,6 +33,8 @@ import type { export interface AuthStatus { /** True when no admin exists yet — UI must redirect to /setup. */ setup_required: boolean; + /** Desktop shell only: a user named ``local`` already exists. */ + local_account: boolean; /** Legacy alias of ``!setup_required`` kept for compat. */ setup_done: boolean; /** Octop always requires auth; kept true so legacy components don't unguard. */ @@ -270,6 +272,7 @@ export interface SetupBody { interface RawSetupStatus { setup_required: boolean; + local_account?: boolean; wizard_password_required?: boolean; wizard_password_exists?: boolean; wizard_password_path?: string; @@ -338,6 +341,7 @@ export const authApi = { const raw = await request("/setup/status"); const value: AuthStatus = { setup_required: raw.setup_required, + local_account: raw.local_account ?? false, setup_done: !raw.setup_required, enabled: true, has_password: true, diff --git a/dashboard/src/api/modules/connectors.ts b/dashboard/src/api/modules/connectors.ts index 589d3c4d17..cae6218da3 100644 --- a/dashboard/src/api/modules/connectors.ts +++ b/dashboard/src/api/modules/connectors.ts @@ -120,6 +120,8 @@ export interface ConnectorProbeResult { status_code?: number; oauth?: { available: boolean; + /** The authorization server has no dynamic registration: needs `oauth_client`. */ + client_required?: boolean; issuer?: string; resource?: string; }; @@ -139,6 +141,17 @@ export interface CustomMcpOAuthPreview { expires_at?: number; } +/** Pre-registered OAuth app for servers without dynamic client registration. */ +export interface CustomMcpOAuthClient { + client_id: string; + /** Write-only: omit to keep the saved secret. */ + client_secret?: string; + has_client_secret?: boolean; + scope?: string; + authorization_endpoint?: string; + token_endpoint?: string; +} + export interface CustomMcpServerSpec { transport: CustomMcpTransport; url?: string; @@ -153,6 +166,7 @@ export interface CustomMcpServerSpec { default_open?: boolean; shared?: boolean; oauth?: CustomMcpOAuthPreview; + oauth_client?: CustomMcpOAuthClient; } export type OAuthStartTarget = diff --git a/dashboard/src/api/modules/expertMarket.ts b/dashboard/src/api/modules/expertMarket.ts index 1e2b701129..44d73ace36 100644 --- a/dashboard/src/api/modules/expertMarket.ts +++ b/dashboard/src/api/modules/expertMarket.ts @@ -26,6 +26,8 @@ export interface MarketExpert { skill_slugs?: string[]; skill_count?: number; source?: string; + /** True when this card is a template that ships with Octop. */ + featured?: boolean; content?: LocalizedText; quick_prompts?: ExpertMarketQuickPrompt[]; task_examples?: { zh?: string[]; en?: string[] } | null; diff --git a/dashboard/src/api/modules/knowledgeBases.ts b/dashboard/src/api/modules/knowledgeBases.ts index fb75821574..99f5fa69ce 100644 --- a/dashboard/src/api/modules/knowledgeBases.ts +++ b/dashboard/src/api/modules/knowledgeBases.ts @@ -354,4 +354,14 @@ export const knowledgeBasesApi = { body: JSON.stringify({ new_name: newName }), }, ), + + /** Move a file or folder into another folder of the same base ("" is the root). */ + moveDocument: (id: string, documentId: string, targetFolder: string) => + request( + `/knowledge-bases/${id}/documents/${documentId}/move`, + { + method: "POST", + body: JSON.stringify({ target_folder: targetFolder }), + }, + ), }; diff --git a/dashboard/src/api/modules/memoryDashboard.ts b/dashboard/src/api/modules/memoryDashboard.ts index 2caa8060d0..e12a237adc 100644 --- a/dashboard/src/api/modules/memoryDashboard.ts +++ b/dashboard/src/api/modules/memoryDashboard.ts @@ -456,6 +456,12 @@ export interface MemoryStorageInspection { wal_size: number | null; reclaimable_bytes: number | null; auto_vacuum_enabled: boolean | null; + checkpoint_retention_enabled?: boolean | null; + checkpoint_keep_last?: number | null; + checkpoint_keep_days?: number | null; + checkpoint_backup_before_prune?: "first" | "always" | "off" | null; + checkpoint_backup_keep_days?: number | null; + checkpoint_vacuum_recommended?: boolean | null; tables: { table: string; exists: boolean; diff --git a/dashboard/src/api/modules/octopThreads.ts b/dashboard/src/api/modules/octopThreads.ts index 75fa014ec7..7f5d39ff0b 100644 --- a/dashboard/src/api/modules/octopThreads.ts +++ b/dashboard/src/api/modules/octopThreads.ts @@ -67,6 +67,10 @@ export interface OctopThread { turn_active?: boolean; /** True when this thread is paused on a HITL approval or question. */ awaiting_user?: boolean; + /** Shared with other users who can open this expert. */ + contributed?: boolean; + /** False when the thread was contributed by someone else. */ + owned?: boolean; } export interface OctopThreadHistory { @@ -117,6 +121,7 @@ export interface ThreadDeleteResult { export interface OctopThreadPatch { title?: string; pinned?: boolean; + contributed?: boolean; model_ref?: string | null; reasoning_mode?: "auto" | "enabled" | "disabled" | null; reasoning_effort?: string | null; @@ -240,6 +245,8 @@ export const octopThreadsApi = { thread_id: string; title: string | null; pinned?: boolean; + contributed?: boolean; + owned?: boolean; model_ref?: string | null; reasoning_mode?: "auto" | "enabled" | "disabled" | null; reasoning_effort?: string | null; diff --git a/dashboard/src/api/modules/teams.ts b/dashboard/src/api/modules/teams.ts index a285a2f66e..99533a7398 100644 --- a/dashboard/src/api/modules/teams.ts +++ b/dashboard/src/api/modules/teams.ts @@ -36,6 +36,10 @@ export interface TeamWriteBody { icon_url?: string | null; welcome_message?: string | null; member_ids?: string[]; + /** Create only. Matches the id segment of the default workspace path. */ + agent_id?: string; + /** Create only: backend and, for a filesystem root, optional workspace_dir. */ + config?: Record; } export interface TeamTemplateFile { diff --git a/dashboard/src/api/modules/update.ts b/dashboard/src/api/modules/update.ts index eacde5c7b5..2765a24bb1 100644 --- a/dashboard/src/api/modules/update.ts +++ b/dashboard/src/api/modules/update.ts @@ -7,7 +7,7 @@ export interface UpdateStatus { is_editable: boolean; /** Non-null when the process was launched via `octop service start` (systemd or launchd). */ service_mode: "systemd" | "launchd" | null; - /** True when Octop is spawned by the Wails desktop shell (or ``OCTOP_DESKTOP=1``). */ + /** True when Octop is spawned by the desktop shell (or ``OCTOP_DESKTOP=1``). */ desktop?: boolean; error: string | null; /** Stable error code (e.g. "pypi_unreachable") for localized UI messages; null on success. */ diff --git a/dashboard/src/api/modules/wsChat.ts b/dashboard/src/api/modules/wsChat.ts index e75ad72c19..fa283bdcaa 100644 --- a/dashboard/src/api/modules/wsChat.ts +++ b/dashboard/src/api/modules/wsChat.ts @@ -1,10 +1,10 @@ import { getAuthToken } from "../request"; +import { resolveWsUrl } from "../../utils/desktopWsUrl"; export function buildDashboardChatWsUrl(agentId: string): string { const token = getAuthToken(); - const protocol = window.location.protocol === "https:" ? "wss" : "ws"; const encoded = encodeURIComponent(agentId); - const base = `${protocol}://${window.location.host}/api/agents/${encoded}/chat/ws`; + const base = resolveWsUrl(`/api/agents/${encoded}/chat/ws`); const params = new URLSearchParams(); if (token) params.set("token", token); return params.toString() ? `${base}?${params.toString()}` : base; diff --git a/dashboard/src/api/request.desktopSession.test.ts b/dashboard/src/api/request.desktopSession.test.ts new file mode 100644 index 0000000000..d792067281 --- /dev/null +++ b/dashboard/src/api/request.desktopSession.test.ts @@ -0,0 +1,157 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("./config", () => ({ + getApiUrl: (path: string) => `/api${path}`, +})); + +vi.mock("../i18n", () => ({ + default: { language: "zh" }, +})); + +/** + * A desktop session must survive its JWT expiring: the shell holds a device + * credential, so the 401 path renews once and retries instead of landing on a + * login screen the user could never fill in. + */ + +function tokenExpiredResponse(): Response { + return new Response( + JSON.stringify({ error: { code: "TOKEN_EXPIRED", message: "expired" } }), + { status: 401, headers: { "content-type": "application/json" } }, + ); +} + +function okResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { + status: 200, + headers: { "content-type": "application/json" }, + }); +} + +function tokenFor(uname: string): string { + const payload = btoa(JSON.stringify({ sub: "1", uname })) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); + return `h.${payload}.s`; +} + +interface Bridge { + register: ReturnType; + renew: ReturnType; + revoke: ReturnType; +} + +function installBridge(renewedToken: string | null): Bridge { + const session = { + register: vi.fn().mockResolvedValue(true), + renew: vi + .fn() + .mockResolvedValue( + renewedToken ? { access_token: renewedToken, expires_in: 86400 } : null, + ), + revoke: vi.fn().mockResolvedValue(true), + }; + (globalThis as unknown as { octopDesktop: unknown }).octopDesktop = { + session, + }; + return session; +} + +describe("desktop device session", () => { + const replace = vi.fn(); + let fetchMock: ReturnType; + let mod: typeof import("./request"); + + beforeEach(async () => { + vi.resetModules(); + localStorage.clear(); + sessionStorage.clear(); + replace.mockClear(); + delete (globalThis as unknown as { octopDesktop?: unknown }).octopDesktop; + Object.defineProperty(window, "location", { + configurable: true, + value: { pathname: "/chat", replace }, + }); + fetchMock = vi.fn(); + vi.stubGlobal("fetch", fetchMock); + mod = await import("./request"); + }); + + it("renews an expired local session and retries once", async () => { + const renewed = tokenFor("local"); + const session = installBridge(renewed); + mod.setAuthToken(tokenFor("local")); + fetchMock + .mockResolvedValueOnce(tokenExpiredResponse()) + .mockResolvedValueOnce(okResponse({ items: [] })); + + await expect(mod.request("/agents")).resolves.toEqual({ items: [] }); + + expect(session.renew).toHaveBeenCalledOnce(); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(mod.getAuthToken()).toBe(renewed); + expect(replace).not.toHaveBeenCalled(); + // The retry must carry the new token, not the stale one. + const retryInit = fetchMock.mock.calls[1][1] as RequestInit; + expect((retryInit.headers as Record).Authorization).toBe( + `Bearer ${renewed}`, + ); + }); + + it("does not renew a password account into the desktop session", async () => { + const session = installBridge(tokenFor("local")); + mod.setAuthToken(tokenFor("admin")); + fetchMock.mockResolvedValue(tokenExpiredResponse()); + + await expect(mod.request("/agents")).rejects.toThrow(); + expect(session.renew).not.toHaveBeenCalled(); + expect(replace).toHaveBeenCalledWith("/login"); + }); + + it("registers the device credential for the local account only", async () => { + const session = installBridge("unused"); + const localToken = tokenFor("local"); + mod.setAuthToken(localToken); + // A Response body can only be read once, so give each call a fresh one. + fetchMock.mockImplementation(() => + Promise.resolve(okResponse({ ok: true })), + ); + + await mod.request("/agents"); + await mod.request("/agent-groups"); + + expect(session.register).toHaveBeenCalledOnce(); + expect(session.register).toHaveBeenCalledWith(localToken); + + session.register.mockClear(); + mod.setAuthToken(tokenFor("admin")); + await mod.request("/settings"); + expect(session.register).not.toHaveBeenCalled(); + }); + + it("falls through to the login path when there is no bridge", async () => { + mod.setAuthToken("stale-token"); + fetchMock.mockResolvedValue(tokenExpiredResponse()); + + await expect(mod.request("/agents")).rejects.toThrow(); + expect(fetchMock).toHaveBeenCalledOnce(); + expect(mod.getAuthToken()).toBe(""); + expect(replace).toHaveBeenCalledWith("/login"); + }); + + it("does not retry a rejected login", async () => { + const session = installBridge("renewed-token"); + const unauthorized = new Response( + JSON.stringify({ error: { code: "AUTH_FAILED", message: "bad" } }), + { status: 401, headers: { "content-type": "application/json" } }, + ); + fetchMock.mockResolvedValue(unauthorized); + + await expect( + mod.request("/auth/login", { method: "POST", body: "{}" }), + ).rejects.toThrow(); + expect(session.renew).not.toHaveBeenCalled(); + expect(fetchMock).toHaveBeenCalledOnce(); + }); +}); diff --git a/dashboard/src/api/request.ts b/dashboard/src/api/request.ts index 7afb709d76..b799d36405 100644 --- a/dashboard/src/api/request.ts +++ b/dashboard/src/api/request.ts @@ -1,4 +1,9 @@ import { getApiUrl } from "./config"; +import { + isLocalDesktopUser, + registerDeviceSession, + renewDesktopSession, +} from "./desktopSession"; import i18n from "../i18n"; import { markNavigatingAway } from "../utils/reloadOnStaleChunk"; @@ -379,6 +384,43 @@ async function throwIfUnauthorized( throw new Error(message); } +/** + * Retry a 401 once with a JWT minted by the desktop shell. + * + * A desktop user has no password to type, so an expired session used to be a + * dead end. The shell holds a device credential and can issue a new token; on + * the web this returns null immediately and the caller falls through to the + * ordinary login redirect. + */ +async function retryWithDesktopSession( + path: string, + url: string, + options: RequestInit, + response: Response, +): Promise { + if (response.status !== 401) return null; + // A rejected login is a credential problem, not an expired session. + if (path.startsWith("/auth/login") || path.startsWith("/auth/device/")) { + return null; + } + // Business 401s (peer login, setup guards) would only be retried in vain. + const code = await errorCodeOf(response); + if (code && !SESSION_UNAUTHORIZED_CODES.has(code)) return null; + const current = getAuthToken(); + // A password account's expired token must land on the login page. Only the + // desktop local user is renewed in place. + if (current && !isLocalDesktopUser(current)) return null; + const issued = await renewDesktopSession(); + if (!issued?.access_token || !isLocalDesktopUser(issued.access_token)) { + return null; + } + setAuthToken(issued.access_token, !isSessionOnlyAuth()); + return fetch(url, { + ...options, + headers: buildHeaders(path, options.headers), + }); +} + export async function request( path: string, options: RequestInit = {}, @@ -389,17 +431,23 @@ export async function request( const headers = buildHeaders(path, options.headers); - const response = await fetch(url, { + let response = await fetch(url, { ...options, headers, }); + const retried = await retryWithDesktopSession(path, url, options, response); + if (retried) response = retried; + if (await check503ForSetupRequired(path, response)) { throw new SetupRequiredError(); } await throwIfUnauthorized(path, response); applyRenewedAccessToken(response); + // Desktop: bind the shell's device credential the first chance we get, so the + // next cold start can renew instead of landing on /login. + if (response.ok) void registerDeviceSession(getAuthToken()); if (!response.ok) { if (response.status === 403 && isAgentScopedPath(path)) { diff --git a/dashboard/src/assets/window-controls/close.svg b/dashboard/src/assets/window-controls/close.svg new file mode 100644 index 0000000000..527da8d81c --- /dev/null +++ b/dashboard/src/assets/window-controls/close.svg @@ -0,0 +1,3 @@ + + + diff --git a/dashboard/src/assets/window-controls/maximize.svg b/dashboard/src/assets/window-controls/maximize.svg new file mode 100644 index 0000000000..b83f8e55e5 --- /dev/null +++ b/dashboard/src/assets/window-controls/maximize.svg @@ -0,0 +1,3 @@ + + + diff --git a/dashboard/src/assets/window-controls/minimize.svg b/dashboard/src/assets/window-controls/minimize.svg new file mode 100644 index 0000000000..c1bbb898b2 --- /dev/null +++ b/dashboard/src/assets/window-controls/minimize.svg @@ -0,0 +1,3 @@ + + + diff --git a/dashboard/src/assets/window-controls/restore.svg b/dashboard/src/assets/window-controls/restore.svg new file mode 100644 index 0000000000..782fe6304f --- /dev/null +++ b/dashboard/src/assets/window-controls/restore.svg @@ -0,0 +1,3 @@ + + + diff --git a/dashboard/src/components/AntdAppProvider.tsx b/dashboard/src/components/AntdAppProvider.tsx index 5683f05df0..36626c217d 100644 --- a/dashboard/src/components/AntdAppProvider.tsx +++ b/dashboard/src/components/AntdAppProvider.tsx @@ -2,6 +2,7 @@ import { App } from "antd"; import { useEffect, type ReactNode } from "react"; import { bindAntdMessage, unbindAntdMessage } from "../utils/antdMessage"; import { bindAntdModal, unbindAntdModal } from "../utils/antdModal"; +import { popupLayer } from "../utils/overlayLayers"; /** Captures App.useApp() APIs for non-hook call sites (utils). */ function AntdAppApiBinder() { @@ -20,7 +21,10 @@ function AntdAppApiBinder() { /** Wrap under ConfigProvider so message/modal/notification follow theme. */ export function AntdAppProvider({ children }: { children: ReactNode }) { return ( - + {children} diff --git a/dashboard/src/components/AuthGuard.tsx b/dashboard/src/components/AuthGuard.tsx index 4a4c3af4d9..76f4be97f5 100644 --- a/dashboard/src/components/AuthGuard.tsx +++ b/dashboard/src/components/AuthGuard.tsx @@ -1,12 +1,13 @@ import { useEffect, useRef, useState } from "react"; import { useNavigate } from "react-router-dom"; -import { Spin } from "antd"; import { clearAuthToken, getAuthToken } from "../api/request"; import { authApi, type OctopUser } from "../api/modules/auth"; import { applyUserLocale } from "../utils/locale"; import { isNetworkFetchError } from "../utils/networkError"; import { CurrentUserProvider } from "../hooks/useCurrentUser"; +import { useTheme } from "../context/ThemeContext"; import BootOfflinePanel from "./BootOfflinePanel"; +import BrandLoading from "./BrandLoading"; interface AuthGuardProps { children: React.ReactNode; @@ -42,6 +43,11 @@ export default function AuthGuard({ children }: AuthGuardProps) { const [checking, setChecking] = useState(true); const [authed, setAuthed] = useState(false); const [user, setUser] = useState(null); + const { bindUser } = useTheme(); + useEffect(() => { + bindUser(user?.id ?? null); + return () => bindUser(null); + }, [user?.id, bindUser]); const [offline, setOffline] = useState(false); const [retryKey, setRetryKey] = useState(0); @@ -127,19 +133,7 @@ export default function AuthGuard({ children }: AuthGuardProps) { } if (checking || !authed) { - return ( -
- -
- ); + return ; } return ( diff --git a/dashboard/src/components/AvatarDropdown.tsx b/dashboard/src/components/AvatarDropdown.tsx index 1aa5dec28e..920bd0142a 100644 --- a/dashboard/src/components/AvatarDropdown.tsx +++ b/dashboard/src/components/AvatarDropdown.tsx @@ -30,7 +30,9 @@ import { useTranslation } from "react-i18next"; import cx from "classnames"; import { authApi } from "../api/modules/auth"; import { preferencesApi } from "../api/modules/preferences"; +import { holdDesktopLocalAutoLogin } from "../api/desktopSession"; import { clearAuthToken } from "../api/request"; +import { isDesktopShell } from "../utils/desktopBridge"; import { applyGuestLocale, applyUserLocale } from "../utils/locale"; import { apiErrorMessage } from "../utils/apiError"; import { isSsoPopupMessage, openSsoPopup } from "../utils/ssoPopup"; @@ -110,11 +112,14 @@ export default function AvatarDropdown({ const handleLogout = useCallback(async () => { setMenuOpen(false); + if (isDesktopShell() && user?.username === "local") { + holdDesktopLocalAutoLogin(); + } await authApi.logout(); clearAuthToken(); await applyGuestLocale(); navigate("/login", { replace: true }); - }, [navigate]); + }, [navigate, user?.username]); const handleSaveProfile = async (values: { display_name: string }) => { setSaving(true); diff --git a/dashboard/src/components/AvatarPicker/index.ts b/dashboard/src/components/AvatarPicker/index.ts index 9979d59150..625f7f9993 100644 --- a/dashboard/src/components/AvatarPicker/index.ts +++ b/dashboard/src/components/AvatarPicker/index.ts @@ -15,7 +15,11 @@ export { } from "./url"; export { USER_AVATAR_PRESETS } from "./presets/user"; export { ROLE_AVATAR_PRESETS } from "./presets/role"; -export { EXPERT_AVATAR_PRESETS, expertPresetSrc } from "./presets/expert"; +export { + EXPERT_AVATAR_PRESETS, + canonicalExpertPresetId, + expertPresetSrc, +} from "./presets/expert"; export { TEAM_AVATAR_PRESETS } from "./presets/team"; export { SKILL_PACKAGE_AVATAR_PRESETS } from "./presets/skillPackage"; export { KNOWLEDGE_AVATAR_PRESETS } from "./presets/knowledge"; diff --git a/dashboard/src/components/AvatarPicker/presets/expert.ts b/dashboard/src/components/AvatarPicker/presets/expert.ts index bd73eb5833..33244e103e 100644 --- a/dashboard/src/components/AvatarPicker/presets/expert.ts +++ b/dashboard/src/components/AvatarPicker/presets/expert.ts @@ -18,10 +18,22 @@ const EXPERT_PORTRAIT_IDS = [ "scene-ecommerce", "ai-coding-coach", "stock-assistant", - "news-trend", "parenting-companion", ] as const; +/** + * Portraits that are the same drawing as another preset. The file stays so + * existing experts keep their URL; the picker shows the canonical tile. + */ +const PRESET_ALIASES: Record = { + "news-trend": "scene-media", +}; + +export function canonicalExpertPresetId(id: string | null): string | null { + if (!id || id === "default") return null; + return PRESET_ALIASES[id] ?? id; +} + export function expertPresetSrc(id: string): string { return `/experts/avatars/${id}.svg`; } diff --git a/dashboard/src/components/BrandLoading/BrandLoading.module.less b/dashboard/src/components/BrandLoading/BrandLoading.module.less new file mode 100644 index 0000000000..b3042162c5 --- /dev/null +++ b/dashboard/src/components/BrandLoading/BrandLoading.module.less @@ -0,0 +1,69 @@ +.host { + display: flex; + flex: 1; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; + min-height: 0; + box-sizing: border-box; + padding: 32px 24px; + background: + radial-gradient( + 720px 380px at 50% -8%, + color-mix(in srgb, var(--fn-color-brand) 11%, transparent), + transparent 68% + ), + var(--fn-bg-layout, #f5f6f8); +} + +.viewport { + min-height: 100dvh; +} + +.stack { + display: flex; + flex-direction: column; + align-items: center; + animation: brandLoadingIn 420ms ease-out both; +} + +.logo { + display: block; + height: 72px; + width: auto; + max-width: min(260px, 75vw); + object-fit: contain; +} + +.status { + --octop-spinner-size: 22px; + --octop-spinner-ring-width: 2px; + + display: flex; + align-items: center; + gap: 12px; + margin: 24px 0 0; + font-size: 16px; + font-weight: 500; + line-height: 1; + letter-spacing: 0.01em; + color: var(--fn-text-secondary, #4b5563); +} + +@keyframes brandLoadingIn { + from { + opacity: 0; + transform: translateY(6px); + } + to { + opacity: 1; + transform: none; + } +} + +@media (prefers-reduced-motion: reduce) { + .stack { + animation: none; + } +} diff --git a/dashboard/src/components/BrandLoading/index.tsx b/dashboard/src/components/BrandLoading/index.tsx new file mode 100644 index 0000000000..fb1ad89236 --- /dev/null +++ b/dashboard/src/components/BrandLoading/index.tsx @@ -0,0 +1,48 @@ +import { useTranslation } from "react-i18next"; + +import { useTheme } from "../../context/ThemeContext"; +import { publicUrl } from "../../utils/publicUrl"; +import OctopSpinner from "../OctopSpinner"; +import styles from "./BrandLoading.module.less"; + +interface BrandLoadingProps { + /** Status line beside the arc. Defaults to the shared loading label. */ + label?: string; + /** Cover the viewport. Route fallbacks fill their parent instead. */ + viewport?: boolean; +} + +/** + * Full-page wait: the horizontal lockup above the shared arc and a status + * line. Same composition as the shell splash and the first-paint boot + * screen in index.html. + */ +export default function BrandLoading({ label, viewport }: BrandLoadingProps) { + const { t } = useTranslation(); + const { mode } = useTheme(); + const logoSrc = + mode === "dark" + ? publicUrl("logo_horizontal_white.png") + : publicUrl("logo_horizontal_dark.png"); + + return ( +
+
+ Octop +

+ + {label ?? t("common.loading")} +

+
+
+ ); +} diff --git a/dashboard/src/components/BrowserWorkspace/ChatDockPanelShell.test.tsx b/dashboard/src/components/BrowserWorkspace/ChatDockPanelShell.test.tsx index 0e4aac74d9..a4612d2fed 100644 --- a/dashboard/src/components/BrowserWorkspace/ChatDockPanelShell.test.tsx +++ b/dashboard/src/components/BrowserWorkspace/ChatDockPanelShell.test.tsx @@ -3,9 +3,9 @@ import { describe, expect, it, vi } from "vitest"; import { DesktopChromeProvider } from "../../hooks/useDesktopChrome"; import { DOCK_WINDOW_CONTROLS_PAD_PX, - WINDOW_CONTROLS_INSET, WINDOW_CONTROLS_SPACER_ATTR, resolveDesktopChromeStyle, + windowControlsInset, } from "../../utils/desktopChrome"; import ChatDockPanelShell from "./ChatDockPanelShell"; @@ -27,7 +27,9 @@ function renderShell( } function expectedDockSpacer(chrome: "mac" | "windows"): string { - return `${WINDOW_CONTROLS_INSET[chrome] - DOCK_WINDOW_CONTROLS_PAD_PX}px`; + return `${ + windowControlsInset(chrome, "end") - DOCK_WINDOW_CONTROLS_PAD_PX + }px`; } function spacerWidth(container: HTMLElement): string | undefined { @@ -38,9 +40,20 @@ function spacerWidth(container: HTMLElement): string | undefined { } describe("ChatDockPanelShell chrome inset", () => { - it("inserts a pixel spacer so right-dock and popup toolbars clear window controls", () => { - const { container, rerender } = renderShell("right", "mac"); - expect(spacerWidth(container)).toBe(expectedDockSpacer("mac")); + it("reserves caption-button space on Windows only", () => { + // Windows caption buttons sit over the dock's toolbar, so the toolbar gets + // a spacer; macOS traffic lights are on the opposite edge. + const { container, rerender } = renderShell("right", "windows"); + expect(spacerWidth(container)).toBe(expectedDockSpacer("windows")); + + rerender( + + + , + ); + expect( + container.querySelector(`[${WINDOW_CONTROLS_SPACER_ATTR}]`), + ).toBeNull(); rerender( @@ -50,7 +63,7 @@ describe("ChatDockPanelShell chrome inset", () => { expect(spacerWidth(container)).toBe(expectedDockSpacer("windows")); rerender( - + , ); @@ -117,20 +130,26 @@ describe("ChatDockPanelShell chrome inset", () => { ).toBeInTheDocument(); }); - it("still inserts the spacer from the Wails bridge when chrome context is missing", () => { - Object.defineProperty(window, "_wails", { + it("still inserts the spacer from the preload bridge when chrome context is missing", () => { + // Without a provider the panel falls back to the platform UA; pin it to + // Windows so the expectation does not depend on the jsdom default. + vi.spyOn(navigator, "userAgent", "get").mockReturnValue( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0", + ); + Object.defineProperty(window, "octopDesktop", { configurable: true, - value: { invoke: () => undefined }, + value: {}, }); const { container } = render( , ); expect(spacerWidth(container)).toBe( `${ - WINDOW_CONTROLS_INSET[resolveDesktopChromeStyle()] - + windowControlsInset(resolveDesktopChromeStyle(), "end") - DOCK_WINDOW_CONTROLS_PAD_PX }px`, ); - delete (window as Window & { _wails?: unknown })._wails; + delete (window as Window & { octopDesktop?: unknown }).octopDesktop; + vi.restoreAllMocks(); }); }); diff --git a/dashboard/src/components/BrowserWorkspace/ChatDockPanelShell.tsx b/dashboard/src/components/BrowserWorkspace/ChatDockPanelShell.tsx index 2e0a66de85..96910452ca 100644 --- a/dashboard/src/components/BrowserWorkspace/ChatDockPanelShell.tsx +++ b/dashboard/src/components/BrowserWorkspace/ChatDockPanelShell.tsx @@ -24,11 +24,11 @@ import type { PanelMode } from "./index"; import { useDesktopChromeStyle } from "../../hooks/useDesktopChrome"; import { DOCK_WINDOW_CONTROLS_PAD_PX, - isDesktopShell, resolveDesktopChromeStyle, WINDOW_CONTROLS_SPACER_ATTR, windowControlsEndSpacerPx, } from "../../utils/desktopChrome"; +import { isDesktopShell } from "../../utils/desktopBridge"; import styles from "./ChatBrowserPanel.module.less"; interface ChatDockPanelShellProps { diff --git a/dashboard/src/components/DesktopWindowControls/DesktopWindowControls.module.less b/dashboard/src/components/DesktopWindowControls/DesktopWindowControls.module.less deleted file mode 100644 index be66f27a4c..0000000000 --- a/dashboard/src/components/DesktopWindowControls/DesktopWindowControls.module.less +++ /dev/null @@ -1,104 +0,0 @@ -.mac, -.windows { - position: fixed; - top: 0; - right: 0; - z-index: 10000; - display: flex; - align-items: center; - height: 32px; - flex-shrink: 0; - user-select: none; - -webkit-app-region: no-drag; -} - -.mac { - gap: 8px; - padding: 0 12px 0 8px; -} - -.light { - width: 12px; - height: 12px; - padding: 0; - border: 0.5px solid transparent; - border-radius: 50%; - cursor: pointer; - position: relative; - appearance: none; - flex-shrink: 0; - display: inline-flex; - align-items: center; - justify-content: center; - line-height: 0; - - &:focus-visible { - outline: 2px solid currentColor; - outline-offset: 2px; - } -} - -.glyph { - opacity: 0; - display: block; - font-size: 9px; - font-weight: 700; - line-height: 1; - color: inherit; - pointer-events: none; - transform: translateY(-0.5px); -} - -.mac:hover .glyph { - opacity: 0.85; -} - -.zoom { - background: #28c840; - border-color: #12a12a; - color: #003a08; -} - -.min { - background: #febc2e; - border-color: #d89e19; - color: #5c3b00; -} - -.close { - background: #ff5f57; - border-color: #e0443e; - color: #4d0000; -} - -.windows { - height: 32px; -} - -.winBtn { - width: 46px; - height: 32px; - padding: 0; - border: none; - background: transparent; - color: var(--fn-text-secondary, #4b5563); - display: inline-flex; - align-items: center; - justify-content: center; - cursor: pointer; -} - -.winBtn:hover { - background: var(--fn-bg-hover, rgba(0, 0, 0, 0.06)); - color: var(--fn-text-primary, #111827); -} - -.winBtn:focus-visible { - outline: 2px solid var(--fn-color-brand, #1677ff); - outline-offset: -2px; -} - -.winClose:hover { - background: #e81123; - color: #fff; -} diff --git a/dashboard/src/components/DesktopWindowControls/DesktopWindowControls.test.tsx b/dashboard/src/components/DesktopWindowControls/DesktopWindowControls.test.tsx deleted file mode 100644 index 0b24d15dad..0000000000 --- a/dashboard/src/components/DesktopWindowControls/DesktopWindowControls.test.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import { render, screen } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import DesktopWindowControls from "./DesktopWindowControls"; - -const { emitDesktopWindowAction } = vi.hoisted(() => ({ - emitDesktopWindowAction: vi.fn(), -})); - -vi.mock("../../utils/desktopChrome", async (importOriginal) => { - const actual = await importOriginal< - typeof import("../../utils/desktopChrome") - >(); - return { ...actual, emitDesktopWindowAction }; -}); - -describe("DesktopWindowControls", () => { - it("renders traffic lights with close on the far right", async () => { - const user = userEvent.setup(); - render(); - - const buttons = screen.getAllByRole("button"); - expect(buttons).toHaveLength(3); - expect(buttons[0]).toHaveAccessibleName(/maximize/i); - expect(buttons[1]).toHaveAccessibleName(/minimize/i); - expect(buttons[2]).toHaveAccessibleName(/close/i); - - await user.click(buttons[2]); - expect(emitDesktopWindowAction).toHaveBeenCalledWith("close"); - }); - - it("renders Windows caption buttons in min / max / close order", async () => { - const user = userEvent.setup(); - render(); - - const buttons = screen.getAllByRole("button"); - expect(buttons[0]).toHaveAccessibleName(/minimize/i); - expect(buttons[1]).toHaveAccessibleName(/maximize/i); - expect(buttons[2]).toHaveAccessibleName(/close/i); - - await user.click(buttons[0]); - expect(emitDesktopWindowAction).toHaveBeenCalledWith("minimise"); - }); -}); diff --git a/dashboard/src/components/DesktopWindowControls/DesktopWindowControls.tsx b/dashboard/src/components/DesktopWindowControls/DesktopWindowControls.tsx deleted file mode 100644 index 2c3eb6cf96..0000000000 --- a/dashboard/src/components/DesktopWindowControls/DesktopWindowControls.tsx +++ /dev/null @@ -1,93 +0,0 @@ -import type { DesktopChromeStyle } from "../../utils/desktopChrome"; -import { emitDesktopWindowAction } from "../../utils/desktopChrome"; -import { Minus, Square, X } from "lucide-react"; -import { useTranslation } from "react-i18next"; -import cx from "classnames"; -import styles from "./DesktopWindowControls.module.less"; - -interface DesktopWindowControlsProps { - chrome: DesktopChromeStyle; -} - -export default function DesktopWindowControls({ - chrome, -}: DesktopWindowControlsProps) { - const { t } = useTranslation(); - const minimise = t("desktopChrome.minimize", "Minimize"); - const maximise = t("desktopChrome.maximize", "Maximize"); - const close = t("desktopChrome.close", "Close"); - - if (chrome === "mac") { - return ( -
- - - -
- ); - } - - return ( -
- - - -
- ); -} diff --git a/dashboard/src/components/DesktopWindowControls/index.ts b/dashboard/src/components/DesktopWindowControls/index.ts deleted file mode 100644 index a1f4752832..0000000000 --- a/dashboard/src/components/DesktopWindowControls/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default } from "./DesktopWindowControls"; diff --git a/dashboard/src/components/DesktopWindowDragBand.test.tsx b/dashboard/src/components/DesktopWindowDragBand.test.tsx new file mode 100644 index 0000000000..42470a3f8e --- /dev/null +++ b/dashboard/src/components/DesktopWindowDragBand.test.tsx @@ -0,0 +1,63 @@ +import { cleanup, render } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { DesktopChromeProvider } from "../hooks/useDesktopChrome"; +import { + MAC_TITLEBAR_HEIGHT, + WINDOW_CONTROLS_INSET, + type DesktopChromeStyle, +} from "../utils/desktopChrome"; +import DesktopWindowDragBand from "./DesktopWindowDragBand"; + +const state = vi.hoisted(() => ({ fullscreen: false })); + +vi.mock("../hooks/useWindowFullscreen", () => ({ + useWindowFullscreen: () => state.fullscreen, +})); + +afterEach(() => { + state.fullscreen = false; + cleanup(); +}); + +function renderBand(chrome: DesktopChromeStyle | null) { + return render( + + + , + ); +} + +describe("窗口顶部拖拽条", () => { + it("浏览器里不出现", () => { + const { container } = renderBand(null); + expect(container.querySelector(".octop-shell-drag-band")).toBeNull(); + }); + + it("macOS 只在常规标题栏高度内可拖动,并避开交通灯", () => { + const { container } = renderBand("mac"); + const band = container.querySelector(".octop-shell-drag-band"); + + expect(band).not.toBeNull(); + expect(band).toHaveClass("octop-desktop-drag"); + expect(band).toHaveAttribute("aria-hidden", "true"); + expect(band).toHaveStyle({ + position: "fixed", + top: "0px", + height: `${MAC_TITLEBAR_HEIGHT}px`, + left: `${WINDOW_CONTROLS_INSET.mac}px`, + right: "0px", + pointerEvents: "none", + }); + }); + + it("Windows 不在页面上放拖动条", () => { + const { container } = renderBand("windows"); + expect(container.querySelector(".octop-shell-drag-band")).toBeNull(); + }); + + it("全屏时移除拖拽条", () => { + state.fullscreen = true; + const { container } = renderBand("mac"); + expect(container.querySelector(".octop-shell-drag-band")).toBeNull(); + }); +}); diff --git a/dashboard/src/components/DesktopWindowDragBand.tsx b/dashboard/src/components/DesktopWindowDragBand.tsx new file mode 100644 index 0000000000..aafc712c9a --- /dev/null +++ b/dashboard/src/components/DesktopWindowDragBand.tsx @@ -0,0 +1,38 @@ +import { useDesktopChromeStyle } from "../hooks/useDesktopChrome"; +import { useWindowFullscreen } from "../hooks/useWindowFullscreen"; +import { + chromeTopBandPx, + DESKTOP_DRAG_REGION_CLASS, + windowControlsInset, +} from "../utils/desktopChrome"; + +/** + * macOS title-bar hit target, beside the traffic lights. Windows does not use + * this strip: the caption menu row is the only place you can hold and drag + * the window. `pointer-events: none` lets clicks reach controls underneath; + * those controls opt out of dragging via the `no-drag` rules in `layout.css`. + */ +export default function DesktopWindowDragBand({ + position = "fixed", +}: { + position?: "fixed" | "absolute"; +}) { + const desktopChrome = useDesktopChromeStyle(); + const windowFullscreen = useWindowFullscreen(); + if (desktopChrome !== "mac" || windowFullscreen) return null; + + return ( +
+ ); +} diff --git a/dashboard/src/components/ErrorBoundary/ErrorFallback.module.less b/dashboard/src/components/ErrorBoundary/ErrorFallback.module.less new file mode 100644 index 0000000000..587906bdd5 --- /dev/null +++ b/dashboard/src/components/ErrorBoundary/ErrorFallback.module.less @@ -0,0 +1,136 @@ +.wrap { + display: flex; + align-items: center; + justify-content: center; + min-height: 100dvh; + padding: 24px; + box-sizing: border-box; +} + +.inner { + display: flex; + flex-direction: column; + align-items: center; + text-align: center; + max-width: 460px; +} + +.mascot { + display: block; + margin: 0 auto; +} + +.title { + margin: 8px 0 0; + font-size: 22px; + font-weight: 600; + line-height: 1.4; + color: var(--fn-text-primary); +} + +.subtitle { + margin: 8px 0 0; + font-size: 14px; + line-height: 1.6; + color: var(--fn-text-secondary); +} + +.actions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 10px; + margin-top: 22px; +} + +/* Hand-rolled so the page keeps the product's accent without a ConfigProvider + above it (see the component comment). */ +.button { + height: 36px; + padding: 0 18px; + border-radius: 10px; + border: 1px solid var(--fn-border-secondary, rgba(0, 0, 0, 0.1)); + background: transparent; + color: var(--fn-text-primary); + font-family: inherit; + font-size: 14px; + font-weight: 500; + line-height: 1; + cursor: pointer; + transition: + background-color 0.15s ease, + border-color 0.15s ease, + opacity 0.15s ease; +} + +.button:hover { + border-color: var(--fn-color-brand, #e85d75); + color: var(--fn-color-brand, #e85d75); +} + +.button:focus-visible { + outline: 2px solid var(--fn-color-brand, #e85d75); + outline-offset: 2px; +} + +.buttonPrimary { + border-color: transparent; + background: var(--fn-color-brand, #e85d75); + color: #fff; +} + +.buttonPrimary:hover { + border-color: transparent; + background: var(--fn-color-brand, #e85d75); + color: #fff; + opacity: 0.88; +} + +.details { + margin-top: 26px; + width: 100%; +} + +/* A disclosure, not a button: it reads as "there is more, if you want it". */ +.summary { + cursor: pointer; + list-style: none; + font-size: 12.5px; + color: var(--fn-text-tertiary); + user-select: none; +} + +.summary::-webkit-details-marker { + display: none; +} + +.summary::before { + content: "›"; + display: inline-block; + margin-inline-end: 6px; + transition: transform 0.15s ease; +} + +.details[open] .summary::before { + transform: rotate(90deg); +} + +.summary:hover { + color: var(--fn-text-secondary); +} + +.detail { + margin: 10px 0 0; + padding: 10px 12px; + border-radius: 8px; + background: var(--fn-fill-tertiary, rgba(0, 0, 0, 0.04)); + color: var(--fn-text-secondary); + font-size: 12px; + line-height: 1.55; + text-align: start; + white-space: pre-wrap; + word-break: break-word; + max-height: 180px; + overflow: auto; +} diff --git a/dashboard/src/components/ErrorBoundary/ErrorFallback.tsx b/dashboard/src/components/ErrorBoundary/ErrorFallback.tsx new file mode 100644 index 0000000000..f4a19e1c85 --- /dev/null +++ b/dashboard/src/components/ErrorBoundary/ErrorFallback.tsx @@ -0,0 +1,77 @@ +import { OctopEmptyMascot } from "../EmptyState/OctopEmptyMascot"; +import styles from "./ErrorFallback.module.less"; + +export interface ErrorFallbackAction { + label: string; + onClick: () => void; + /** ``primary`` is the one action the page wants you to take. */ + variant?: "primary" | "default"; +} + +interface ErrorFallbackProps { + title: string; + subtitle: string; + /** What the app actually threw. Hidden unless asked for — it is for a bug + * report, not for the person staring at the screen. */ + detail?: string | null; + /** Label for the disclosure that hides ``detail``. */ + detailsLabel: string; + /** Buttons, in reading order. */ + actions: ErrorFallbackAction[]; +} + +/** + * Full-viewport failure surface: mascot, one title, one sentence, actions. + * + * It follows the same shape as the boot splash, the offline panel and the 404 + * page, because four failure renders that each invent their own layout is what + * makes an app feel assembled from parts. The raw exception is deliberately + * demoted into a disclosure — it used to be the subtitle, which meant a user + * whose tab lost a chunk was greeted by "Failed to fetch dynamically imported + * module". + * + * The buttons are plain ones rather than antd's: this component renders *above* + * the ConfigProvider, so an antd Button here inherits none of the app's theme + * and arrives in stock blue with the stock prefix. A crash page is the last + * place that should look like a different product — and the last place worth + * depending on the theme layer, which may itself be what broke. + */ +export default function ErrorFallback({ + title, + subtitle, + detail, + detailsLabel, + actions, +}: ErrorFallbackProps) { + return ( +
+
+ +

{title}

+

{subtitle}

+
+ {actions.map((action) => ( + + ))} +
+ {detail ? ( +
+ {detailsLabel} +
{detail}
+
+ ) : null} +
+
+ ); +} diff --git a/dashboard/src/components/ErrorBoundary/index.test.tsx b/dashboard/src/components/ErrorBoundary/index.test.tsx index b41eb53861..efb6d0c0fa 100644 --- a/dashboard/src/components/ErrorBoundary/index.test.tsx +++ b/dashboard/src/components/ErrorBoundary/index.test.tsx @@ -57,3 +57,44 @@ describe("GlobalErrorBoundary chunk failures", () => { expect(screen.getByRole("button", { name: /reload/i })).toBeInTheDocument(); }); }); + +function Detonate() { + throw new Error("Cannot read properties of undefined (reading 'rows')"); +} + +describe("GlobalErrorBoundary unexpected failures", () => { + beforeEach(() => { + vi.restoreAllMocks(); + tryReloadOnStaleChunk.mockReset(); + tryReloadOnStaleChunk.mockReturnValue(false); + }); + + it("leads with copy a person can act on, not the raw exception", () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + render( + + + , + ); + + expect(screen.getByRole("heading")).toHaveTextContent( + "errors.unexpectedTitle", + ); + // The message still exists — it just is not the headline any more. + expect(screen.getByText(/reading 'rows'/)).toBeInTheDocument(); + }); + + it("keeps the exception behind a disclosure", () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + render( + + + , + ); + + const details = screen.getByText(/reading 'rows'/).closest("details"); + expect(details).not.toBeNull(); + expect(details?.open).toBe(false); + expect(screen.getByText("errors.details")).toBeInTheDocument(); + }); +}); diff --git a/dashboard/src/components/ErrorBoundary/index.tsx b/dashboard/src/components/ErrorBoundary/index.tsx index 156080366e..33dc3f89d8 100644 --- a/dashboard/src/components/ErrorBoundary/index.tsx +++ b/dashboard/src/components/ErrorBoundary/index.tsx @@ -1,10 +1,10 @@ import { Component, type ReactNode } from "react"; -import { Result, Button, Space } from "antd"; import i18n from "../../i18n"; import { isChunkLoadError, tryReloadOnStaleChunk, } from "../../utils/reloadOnStaleChunk"; +import ErrorFallback, { type ErrorFallbackAction } from "./ErrorFallback"; interface Props { children: ReactNode; @@ -71,47 +71,43 @@ export default class GlobalErrorBoundary extends Component { return null; } const canRetry = !isChunkError && this.state.retryCount < MAX_RETRIES; + // A stale chunk has one honest fix (reload); an unexpected throw offers + // "try again" first, because a re-render is often all it takes. + const actions: ErrorFallbackAction[] = []; + if (isChunkError) { + actions.push({ + label: i18n.t("errors.reload"), + onClick: this.handleReload, + variant: "primary", + }); + } + if (canRetry) { + actions.push({ + label: i18n.t("errors.retry"), + onClick: this.handleRetry, + variant: "primary", + }); + } + actions.push({ + label: i18n.t("errors.backHome"), + onClick: this.handleHome, + }); return ( -
- - {isChunkError && ( - - )} - {canRetry && ( - - )} - - - } - /> -
+ ); } return this.props.children; diff --git a/dashboard/src/components/LinuxWindowControls.test.tsx b/dashboard/src/components/LinuxWindowControls.test.tsx new file mode 100644 index 0000000000..79abb63a74 --- /dev/null +++ b/dashboard/src/components/LinuxWindowControls.test.tsx @@ -0,0 +1,112 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { cleanup, render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { DesktopChromeProvider } from "../hooks/useDesktopChrome"; +import LinuxWindowControls from "./LinuxWindowControls"; +import WindowsAppMenu from "./WindowsAppMenu"; + +const state = vi.hoisted(() => ({ + fullscreen: false, + maximized: false, + minimize: vi.fn(), + toggleMaximize: vi.fn(), + close: vi.fn(), + onMaximized: null as ((maximized: boolean) => void) | null, +})); + +vi.mock("../hooks/useWindowFullscreen", () => ({ + useWindowFullscreen: () => state.fullscreen, +})); + +vi.mock("../utils/desktopBridge", () => ({ + isLinuxDesktopShell: () => true, + getDesktopBridge: () => ({ + windowControls: { + minimize: state.minimize, + toggleMaximize: state.toggleMaximize, + close: state.close, + isMaximized: async () => state.maximized, + onMaximizedChange: (cb: (maximized: boolean) => void) => { + state.onMaximized = cb; + return () => { + state.onMaximized = null; + }; + }, + }, + windowsMenu: { + model: async () => ({ titles: ["文件"], menus: [[]] }), + invoke: vi.fn(), + }, + }), +})); + +afterEach(() => { + state.fullscreen = false; + state.maximized = false; + state.minimize.mockClear(); + state.toggleMaximize.mockClear(); + state.close.mockClear(); + cleanup(); +}); + +describe("Linux 方形窗口按钮", () => { + it("画在标题栏右侧,关闭按钮单独成组", async () => { + render( + + + , + ); + const close = await screen.findByRole("button", { name: "关闭" }); + expect(close).toHaveClass("octop-linux-controls-close"); + expect(close.parentElement).toHaveClass("octop-linux-controls"); + expect(screen.getByRole("button", { name: "最小化" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "最大化" })).toBeInTheDocument(); + }); + + it("方形且关闭悬停变红", () => { + const css = readFileSync( + resolve(__dirname, "../styles/layout.css"), + "utf8", + ); + expect(css).toMatch( + /\.octop-linux-controls button \{[^}]*border-radius:\s*0/, + ); + expect(css).toMatch( + /\.octop-linux-controls-close:hover[\s\S]*background:\s*#e81123/, + ); + expect(css).not.toMatch( + /\.octop-linux-controls button \{[^}]*border-radius:\s*50%/, + ); + }); + + it("点击分别最小化、最大化、关闭", async () => { + const user = userEvent.setup(); + render(); + await user.click(screen.getByRole("button", { name: "最小化" })); + await user.click(screen.getByRole("button", { name: "最大化" })); + await user.click(screen.getByRole("button", { name: "关闭" })); + expect(state.minimize).toHaveBeenCalledOnce(); + expect(state.toggleMaximize).toHaveBeenCalledOnce(); + expect(state.close).toHaveBeenCalledOnce(); + }); + + it("最大化后按钮改成还原", async () => { + state.maximized = true; + render(); + expect( + await screen.findByRole("button", { name: "还原" }), + ).toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "最大化" }), + ).not.toBeInTheDocument(); + }); + + it("全屏不占那一角", () => { + state.fullscreen = true; + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); +}); diff --git a/dashboard/src/components/LinuxWindowControls.tsx b/dashboard/src/components/LinuxWindowControls.tsx new file mode 100644 index 0000000000..771675a85f --- /dev/null +++ b/dashboard/src/components/LinuxWindowControls.tsx @@ -0,0 +1,88 @@ +import { useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; + +import { useWindowFullscreen } from "../hooks/useWindowFullscreen"; +import { getDesktopBridge, isLinuxDesktopShell } from "../utils/desktopBridge"; +import CloseIcon from "../assets/window-controls/close.svg?react"; +import MaximizeIcon from "../assets/window-controls/maximize.svg?react"; +import MinimizeIcon from "../assets/window-controls/minimize.svg?react"; +import RestoreIcon from "../assets/window-controls/restore.svg?react"; + +const GLYPH = { + minimize: MinimizeIcon, + maximize: MaximizeIcon, + restore: RestoreIcon, + close: CloseIcon, +} as const; + +/** + * Square caption buttons for the Linux shell. Electron's title-bar overlay + * paints Adwaita circles, so that overlay stays off and these sit in the + * reserved corner of the menu row. Close turns red on hover. + */ +export default function LinuxWindowControls() { + const { t } = useTranslation(); + const fullscreen = useWindowFullscreen(); + const [maximized, setMaximized] = useState(false); + const linux = isLinuxDesktopShell(); + + useEffect(() => { + if (!linux) return; + const controls = getDesktopBridge()?.windowControls; + if (!controls) return; + let cancelled = false; + void controls.isMaximized().then((value) => { + if (!cancelled) setMaximized(value); + }); + const unsubscribe = controls.onMaximizedChange(setMaximized); + return () => { + cancelled = true; + unsubscribe(); + }; + }, [linux]); + + if (!linux || fullscreen || !getDesktopBridge()?.windowControls) return null; + + const controls = getDesktopBridge()?.windowControls; + const restoreLabel = t("layout.windowRestore", "还原"); + const maximizeLabel = t("layout.windowMaximize", "最大化"); + + return ( +
+ + + +
+ ); +} + +function CaptionGlyph({ kind }: { kind: keyof typeof GLYPH }) { + const Icon = GLYPH[kind]; + return