From 7c84fced8cae6fc608e5b7e3915da2b09dc86104 Mon Sep 17 00:00:00 2001 From: Yoko <13830214+yokowu@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:00:08 +0800 Subject: [PATCH] =?UTF-8?q?Revert=20"feat(web):=20=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E8=BF=9C=E7=A8=8B=E8=AE=BE=E5=A4=87=E5=B7=A5=E4=BD=9C=E5=8F=B0?= =?UTF-8?q?=E4=B8=8E=E4=BC=9A=E8=AF=9D=E7=AE=A1=E7=90=86=20(#1599)"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit fab835f62ceaae09ce49aa1de9e6adca2e401259. --- monkeyai/web/package.json | 6 - monkeyai/web/pnpm-lock.yaml | 27 +- .../web/public/licenses/phosphor-icons.txt | 21 - monkeyai/web/scripts/check-chat-flow.mjs | 156 -- .../web/scripts/check-device-workspace.mjs | 340 ---- monkeyai/web/scripts/fixtures/chat-flow.jsx | 118 -- .../web/src/assets/composer-assistant.png | Bin 3857 -> 0 bytes .../web/src/assets/sidebar-design-expert.png | Bin 3650 -> 0 bytes .../src/assets/sidebar-general-assistant.png | Bin 3857 -> 0 bytes monkeyai/web/src/components/accent.css | 112 -- monkeyai/web/src/components/auth-provider.tsx | 8 +- .../web/src/components/branding-provider.tsx | 8 +- .../src/components/device-platform-icon.tsx | 26 - monkeyai/web/src/components/named-themes.css | 59 - .../web/src/components/theme-provider.tsx | 39 +- monkeyai/web/src/components/theme-toggle.tsx | 35 +- .../web/src/components/ui/color-selector.tsx | 230 --- monkeyai/web/src/components/ui/dialog.tsx | 15 +- .../web/src/components/ui/dropdown-menu.tsx | 9 +- monkeyai/web/src/components/ui/popover.tsx | 4 +- monkeyai/web/src/i18n/locales/ar.ts | 2 - monkeyai/web/src/i18n/locales/de-DE.ts | 2 - monkeyai/web/src/i18n/locales/en-US.ts | 2 - monkeyai/web/src/i18n/locales/es-419.ts | 2 - monkeyai/web/src/i18n/locales/fr-FR.ts | 2 - monkeyai/web/src/i18n/locales/ja-JP.ts | 2 - monkeyai/web/src/i18n/locales/ko-KR.ts | 2 - monkeyai/web/src/i18n/locales/ru-RU.ts | 2 - monkeyai/web/src/i18n/locales/zh-CN.ts | 2 - monkeyai/web/src/i18n/locales/zh-TW.ts | 2 - monkeyai/web/src/index.css | 31 - monkeyai/web/src/lib/accent.ts | 67 - monkeyai/web/src/lib/branding.ts | 1 - monkeyai/web/src/lib/client-callback.ts | 13 - monkeyai/web/src/lib/custom-accent.ts | 125 -- monkeyai/web/src/lib/device-chat-errors.ts | 37 - .../web/src/lib/device-composer-options.ts | 37 - monkeyai/web/src/lib/device-connection.ts | 489 ------ .../web/src/lib/device-engine-models.json | 1362 ----------------- monkeyai/web/src/lib/device-expert-color.ts | 84 - monkeyai/web/src/lib/device-message-quotes.ts | 115 -- .../device-model-brand/model-brand-icons.ts | 25 - .../src/lib/device-model-brand/model-brand.ts | 64 - monkeyai/web/src/lib/device-models.ts | 275 ---- .../web/src/lib/device-sidebar-actions.ts | 183 --- .../web/src/lib/device-sidebar-completions.ts | 116 -- monkeyai/web/src/lib/device-turn.ts | 88 -- monkeyai/web/src/lib/device-uploads.ts | 113 -- monkeyai/web/src/lib/device-user-markdown.ts | 193 --- monkeyai/web/src/lib/device-workspace.ts | 574 ------- monkeyai/web/src/lib/interface-size.ts | 40 - monkeyai/web/src/lib/themes.ts | 12 - monkeyai/web/src/lib/user-markdown.ts | 193 --- monkeyai/web/src/lib/workspace-balance.ts | 46 - monkeyai/web/src/lib/workspace-cloud.ts | 258 ---- monkeyai/web/src/lib/workspace-devices.ts | 76 - monkeyai/web/src/lib/workspace-oauth.ts | 230 --- monkeyai/web/src/pages/client-login-page.tsx | 45 +- .../web/src/pages/client/balance-card.tsx | 165 -- monkeyai/web/src/pages/client/client-page.tsx | 541 +------ .../src/pages/client/cloud-application.tsx | 386 ----- .../pages/client/composer-actions-menu.tsx | 138 -- .../src/pages/client/composer-controls.tsx | 501 ------ .../web/src/pages/client/composer-drafts.ts | 179 --- .../web/src/pages/client/composer-file.tsx | 54 - .../web/src/pages/client/composer-quotes.css | 139 -- .../web/src/pages/client/composer-quotes.tsx | 115 -- .../src/pages/client/device-chat-message.tsx | 826 ---------- monkeyai/web/src/pages/client/device-chat.css | 723 --------- .../web/src/pages/client/device-composer.css | 737 --------- .../web/src/pages/client/device-composer.tsx | 706 --------- .../pages/client/device-connection-page.tsx | 926 ----------- .../src/pages/client/device-conversation.tsx | 344 ----- .../src/pages/client/device-model-picker.tsx | 563 ------- .../src/pages/client/device-navigation.tsx | 734 --------- .../web/src/pages/client/device-queue.css | 212 --- .../web/src/pages/client/device-queue.tsx | 472 ------ .../pages/client/device-reply-activity.tsx | 77 - .../pages/client/device-session-avatar.tsx | 39 - .../src/pages/client/device-session-title.css | 40 - .../src/pages/client/device-session-title.tsx | 115 -- .../pages/client/device-sidebar-dialog.tsx | 365 ----- .../src/pages/client/device-sidebar-groups.ts | 11 - .../src/pages/client/device-sidebar-list.css | 227 --- .../pages/client/device-sidebar-remote.tsx | 235 --- .../pages/client/device-sidebar-search.css | 163 -- .../pages/client/device-sidebar-search.tsx | 271 ---- .../web/src/pages/client/device-task-plan.css | 118 -- .../web/src/pages/client/device-task-plan.tsx | 92 -- .../pages/client/device-thinking-depth.tsx | 137 -- .../web/src/pages/client/device-workspace.css | 867 ----------- .../src/pages/client/identity-preference.ts | 44 - .../web/src/pages/client/queue-recovery.tsx | 178 --- .../pages/client/use-device-model-catalog.ts | 45 - .../src/pages/client/user-markdown-body.tsx | 58 - .../pages/client/user-markdown-preference.ts | 36 - .../web/src/pages/client/workspace-accent.tsx | 65 - .../src/pages/client/workspace-appearance.tsx | 74 - .../src/pages/client/workspace-identity.tsx | 34 - .../pages/client/workspace-interface-size.tsx | 91 -- .../src/pages/client/workspace-settings.css | 90 -- .../src/pages/client/workspace-settings.tsx | 398 ----- monkeyai/web/src/pages/login-page.tsx | 14 +- monkeyai/web/test/device-chat-flow.test.mjs | 141 -- .../web/test/device-message-quotes.test.mjs | 92 -- monkeyai/web/test/device-new-model.test.mjs | 84 - monkeyai/web/test/device-plan.test.mjs | 37 - .../web/test/device-queue-recovery.test.mjs | 73 - .../web/test/device-sidebar-actions.test.mjs | 65 - .../test/device-sidebar-completions.test.mjs | 70 - monkeyai/web/test/device-uploads.test.mjs | 102 -- monkeyai/web/test/device-workspace.test.mjs | 104 -- monkeyai/web/test/workspace-balance.test.mjs | 44 - .../web/test/workspace-cloud-list.test.mjs | 100 -- monkeyai/web/test/workspace-devices.test.mjs | 200 --- monkeyai/web/vite.config.ts | 27 +- 116 files changed, 76 insertions(+), 19533 deletions(-) delete mode 100644 monkeyai/web/public/licenses/phosphor-icons.txt delete mode 100644 monkeyai/web/scripts/check-chat-flow.mjs delete mode 100644 monkeyai/web/scripts/check-device-workspace.mjs delete mode 100644 monkeyai/web/scripts/fixtures/chat-flow.jsx delete mode 100644 monkeyai/web/src/assets/composer-assistant.png delete mode 100644 monkeyai/web/src/assets/sidebar-design-expert.png delete mode 100644 monkeyai/web/src/assets/sidebar-general-assistant.png delete mode 100644 monkeyai/web/src/components/accent.css delete mode 100644 monkeyai/web/src/components/device-platform-icon.tsx delete mode 100644 monkeyai/web/src/components/named-themes.css delete mode 100644 monkeyai/web/src/components/ui/color-selector.tsx delete mode 100644 monkeyai/web/src/lib/accent.ts delete mode 100644 monkeyai/web/src/lib/custom-accent.ts delete mode 100644 monkeyai/web/src/lib/device-chat-errors.ts delete mode 100644 monkeyai/web/src/lib/device-composer-options.ts delete mode 100644 monkeyai/web/src/lib/device-connection.ts delete mode 100644 monkeyai/web/src/lib/device-engine-models.json delete mode 100644 monkeyai/web/src/lib/device-expert-color.ts delete mode 100644 monkeyai/web/src/lib/device-message-quotes.ts delete mode 100644 monkeyai/web/src/lib/device-model-brand/model-brand-icons.ts delete mode 100644 monkeyai/web/src/lib/device-model-brand/model-brand.ts delete mode 100644 monkeyai/web/src/lib/device-models.ts delete mode 100644 monkeyai/web/src/lib/device-sidebar-actions.ts delete mode 100644 monkeyai/web/src/lib/device-sidebar-completions.ts delete mode 100644 monkeyai/web/src/lib/device-turn.ts delete mode 100644 monkeyai/web/src/lib/device-uploads.ts delete mode 100644 monkeyai/web/src/lib/device-user-markdown.ts delete mode 100644 monkeyai/web/src/lib/device-workspace.ts delete mode 100644 monkeyai/web/src/lib/interface-size.ts delete mode 100644 monkeyai/web/src/lib/themes.ts delete mode 100644 monkeyai/web/src/lib/user-markdown.ts delete mode 100644 monkeyai/web/src/lib/workspace-balance.ts delete mode 100644 monkeyai/web/src/lib/workspace-cloud.ts delete mode 100644 monkeyai/web/src/lib/workspace-devices.ts delete mode 100644 monkeyai/web/src/lib/workspace-oauth.ts delete mode 100644 monkeyai/web/src/pages/client/balance-card.tsx delete mode 100644 monkeyai/web/src/pages/client/cloud-application.tsx delete mode 100644 monkeyai/web/src/pages/client/composer-actions-menu.tsx delete mode 100644 monkeyai/web/src/pages/client/composer-controls.tsx delete mode 100644 monkeyai/web/src/pages/client/composer-drafts.ts delete mode 100644 monkeyai/web/src/pages/client/composer-file.tsx delete mode 100644 monkeyai/web/src/pages/client/composer-quotes.css delete mode 100644 monkeyai/web/src/pages/client/composer-quotes.tsx delete mode 100644 monkeyai/web/src/pages/client/device-chat-message.tsx delete mode 100644 monkeyai/web/src/pages/client/device-chat.css delete mode 100644 monkeyai/web/src/pages/client/device-composer.css delete mode 100644 monkeyai/web/src/pages/client/device-composer.tsx delete mode 100644 monkeyai/web/src/pages/client/device-connection-page.tsx delete mode 100644 monkeyai/web/src/pages/client/device-conversation.tsx delete mode 100644 monkeyai/web/src/pages/client/device-model-picker.tsx delete mode 100644 monkeyai/web/src/pages/client/device-navigation.tsx delete mode 100644 monkeyai/web/src/pages/client/device-queue.css delete mode 100644 monkeyai/web/src/pages/client/device-queue.tsx delete mode 100644 monkeyai/web/src/pages/client/device-reply-activity.tsx delete mode 100644 monkeyai/web/src/pages/client/device-session-avatar.tsx delete mode 100644 monkeyai/web/src/pages/client/device-session-title.css delete mode 100644 monkeyai/web/src/pages/client/device-session-title.tsx delete mode 100644 monkeyai/web/src/pages/client/device-sidebar-dialog.tsx delete mode 100644 monkeyai/web/src/pages/client/device-sidebar-groups.ts delete mode 100644 monkeyai/web/src/pages/client/device-sidebar-list.css delete mode 100644 monkeyai/web/src/pages/client/device-sidebar-remote.tsx delete mode 100644 monkeyai/web/src/pages/client/device-sidebar-search.css delete mode 100644 monkeyai/web/src/pages/client/device-sidebar-search.tsx delete mode 100644 monkeyai/web/src/pages/client/device-task-plan.css delete mode 100644 monkeyai/web/src/pages/client/device-task-plan.tsx delete mode 100644 monkeyai/web/src/pages/client/device-thinking-depth.tsx delete mode 100644 monkeyai/web/src/pages/client/device-workspace.css delete mode 100644 monkeyai/web/src/pages/client/identity-preference.ts delete mode 100644 monkeyai/web/src/pages/client/queue-recovery.tsx delete mode 100644 monkeyai/web/src/pages/client/use-device-model-catalog.ts delete mode 100644 monkeyai/web/src/pages/client/user-markdown-body.tsx delete mode 100644 monkeyai/web/src/pages/client/user-markdown-preference.ts delete mode 100644 monkeyai/web/src/pages/client/workspace-accent.tsx delete mode 100644 monkeyai/web/src/pages/client/workspace-appearance.tsx delete mode 100644 monkeyai/web/src/pages/client/workspace-identity.tsx delete mode 100644 monkeyai/web/src/pages/client/workspace-interface-size.tsx delete mode 100644 monkeyai/web/src/pages/client/workspace-settings.css delete mode 100644 monkeyai/web/src/pages/client/workspace-settings.tsx delete mode 100644 monkeyai/web/test/device-chat-flow.test.mjs delete mode 100644 monkeyai/web/test/device-message-quotes.test.mjs delete mode 100644 monkeyai/web/test/device-new-model.test.mjs delete mode 100644 monkeyai/web/test/device-plan.test.mjs delete mode 100644 monkeyai/web/test/device-queue-recovery.test.mjs delete mode 100644 monkeyai/web/test/device-sidebar-actions.test.mjs delete mode 100644 monkeyai/web/test/device-sidebar-completions.test.mjs delete mode 100644 monkeyai/web/test/device-uploads.test.mjs delete mode 100644 monkeyai/web/test/device-workspace.test.mjs delete mode 100644 monkeyai/web/test/workspace-balance.test.mjs delete mode 100644 monkeyai/web/test/workspace-cloud-list.test.mjs delete mode 100644 monkeyai/web/test/workspace-devices.test.mjs diff --git a/monkeyai/web/package.json b/monkeyai/web/package.json index 88a458b4f..952da6e03 100644 --- a/monkeyai/web/package.json +++ b/monkeyai/web/package.json @@ -28,8 +28,6 @@ "test:browser:table-query": "node scripts/check-table-query.mjs", "test:browser:account-links": "node scripts/check-account-links.mjs", "test:browser:client-devices": "node scripts/check-client-devices.mjs", - "test:browser:device-workspace": "node scripts/check-device-workspace.mjs", - "test:browser:chat-flow": "node scripts/check-chat-flow.mjs", "test:browser:billing-users": "node scripts/check-billing-user-search.mjs", "test:browser:auth": "node scripts/check-client-authorization.mjs", "test:browser:branding": "node scripts/check-public-branding.mjs", @@ -62,13 +60,9 @@ "core-js": "^3.51.0", "css-has-pseudo": "^8.0.2", "date-fns": "^4.4.0", - "dompurify": "3.4.17", - "highlight.js": "11.12.0", "i18next": "^26.4.1", "jszip": "^3.10.1", "lucide-react": "^1.47.0", - "marked": "17.0.6", - "misans": "5.0.0", "motion": "^13.4.0", "pinyin-pro": "^3.29.4", "react": "^19.2.6", diff --git a/monkeyai/web/pnpm-lock.yaml b/monkeyai/web/pnpm-lock.yaml index f17e5e51e..1655d8113 100644 --- a/monkeyai/web/pnpm-lock.yaml +++ b/monkeyai/web/pnpm-lock.yaml @@ -79,12 +79,6 @@ importers: date-fns: specifier: ^4.4.0 version: 4.4.0 - dompurify: - specifier: 3.4.17 - version: 3.4.17 - highlight.js: - specifier: 11.12.0 - version: 11.12.0 i18next: specifier: ^26.4.1 version: 26.4.1(typescript@6.0.3) @@ -94,12 +88,6 @@ importers: lucide-react: specifier: ^1.47.0 version: 1.47.0(react@19.2.8) - marked: - specifier: 17.0.6 - version: 17.0.6 - misans: - specifier: 5.0.0 - version: 5.0.0 motion: specifier: ^13.4.0 version: 13.4.0(react-dom@19.2.8(react@19.2.8))(react@19.2.8) @@ -1459,36 +1447,42 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] + libc: [glibc] '@rolldown/binding-linux-arm64-musl@1.2.6': resolution: {integrity: sha512-muWCk27FVBEZtv0MsK8gnfSmgczA8KQ0uRVJbTABKhkRfQc38aUrcb7fhi3BNiyseFmgcRsoMfQsSNJ+DbZdSw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] + libc: [musl] '@rolldown/binding-linux-ppc64-gnu@1.2.6': resolution: {integrity: sha512-eWDoSfU7Co2qj3vgB3Dt4lj1mG6CoWbcJQkRMP3XJplyCMtuaq3LHvPFjS9QIPvMGWVadJC04Xiy0IdcVPtnwQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] + libc: [glibc] '@rolldown/binding-linux-s390x-gnu@1.2.6': resolution: {integrity: sha512-2bWNjRSIayvupRKxXUY2tWG9fYdoUlTqWywHRvE8Eq3GvuQ+f2HeIkve697fIt+IQs/PV8yFsdWuhp1aJ1PdnA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] + libc: [glibc] '@rolldown/binding-linux-x64-gnu@1.2.6': resolution: {integrity: sha512-KekI0gS0wLxe1UBSQSjenBVwou/JkcQPDzBPICGZjxUv9k3RteHDPBQaiOicZUFKRIH2wKEimGwVpnJsbPzu7w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] + libc: [glibc] '@rolldown/binding-linux-x64-musl@1.2.6': resolution: {integrity: sha512-TvtPnfVr+HtyGiDmPK4VWmlNm7QhNNAcK5Q9A7aOXsI8545yCyaoMaicXrFZ72JzeYjaUVk7yT243zT0jzjFKQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] + libc: [musl] '@rolldown/binding-openharmony-arm64@1.2.6': resolution: {integrity: sha512-iOo0VEay2XFhaCcH0sps5XIimkSuOnNaZrf6+ZkoSOQBJPKNU48RkmJv0/lSpipexu5P+ouFgafe5IGr/DiQfg==} @@ -3455,24 +3449,28 @@ packages: engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [glibc] lightningcss-linux-arm64-musl@1.33.0: resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [musl] lightningcss-linux-x64-gnu@1.33.0: resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [glibc] lightningcss-linux-x64-musl@1.33.0: resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [musl] lightningcss-win32-arm64-msvc@1.33.0: resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} @@ -3602,9 +3600,6 @@ packages: minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} - misans@5.0.0: - resolution: {integrity: sha512-8cNqn0n0f+NCuXFT9VMVcfO2/zPp3DA89AQKGJOVWdTM8qkYW7NT0+qGyn1j3PmXeGAc1sVJY6+unBWz01b1+g==} - motion-dom@13.3.0: resolution: {integrity: sha512-AmAnB6pHdZ1vHGzWzuzteG6Q3j1lHKeX/lbST6jGlgm0cjvLUgaCk1xhOuPMOy5SgovN6wnnUdwFrkcsus7Ftg==} @@ -8449,8 +8444,6 @@ snapshots: minimist@1.2.8: {} - misans@5.0.0: {} - motion-dom@13.3.0: dependencies: motion-utils: 13.3.0 diff --git a/monkeyai/web/public/licenses/phosphor-icons.txt b/monkeyai/web/public/licenses/phosphor-icons.txt deleted file mode 100644 index 78c981081..000000000 --- a/monkeyai/web/public/licenses/phosphor-icons.txt +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2023 Phosphor Icons - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/monkeyai/web/scripts/check-chat-flow.mjs b/monkeyai/web/scripts/check-chat-flow.mjs deleted file mode 100644 index 0828e283e..000000000 --- a/monkeyai/web/scripts/check-chat-flow.mjs +++ /dev/null @@ -1,156 +0,0 @@ -// 打包并注入真实组件,不启动服务,不访问设备。 -import assert from "node:assert/strict" -import { build } from "vite" -import { chromium } from "playwright-core" -const bundle = await build({ - publicDir: false, - build: { - write: false, - lib: { - entry: "scripts/fixtures/chat-flow.jsx", - formats: ["iife"], - name: "ChatFixture", - }, - }, - define: { "process.env.NODE_ENV": JSON.stringify("production") }, -}) -const output = (Array.isArray(bundle) ? bundle[0] : bundle).output -const browser = await chromium.launch({ - executablePath: process.env.CHROME_BIN, -}) -try { - const page = await browser.newPage({ viewport: { width: 650, height: 640 } }) - let release, requested - const pending = new Promise((r) => { - release = r - }), - started = new Promise((r) => { - requested = r - }) - await page.exposeFunction("waitOlder", () => { - requested() - return pending - }) - await page.setContent( - '
' - ) - for (const asset of output) - if (asset.type === "asset" && asset.fileName.endsWith(".css")) - await page.addStyleTag({ content: asset.source }) - for (const chunk of output) - if (chunk.type === "chunk") await page.addScriptTag({ content: chunk.code }) - const view = page.getByRole("region", { name: "会话消息" }), - active = page.locator('[data-message-id="active"]') - await active.waitFor() - await page.getByRole("heading", { name: "最终答复" }).waitFor() - assert.ok(await page.locator("pre .hljs-keyword").count()) - assert.equal(await page.getByText("先查记录").isVisible(), false) - const historyToggle = page - .locator('[data-message-id="reply"]') - .getByRole("button", { name: "执行过程" }) - await historyToggle.click() - await page.getByText("先查记录").waitFor() - assert.equal(await historyToggle.getAttribute("aria-expanded"), "true") - const batch = page.locator("details.dc-record").filter({ - has: page.locator("summary > .dc-step-label", { hasText: "批量执行" }), - }) - const child = batch - .locator(".dc-program-steps summary") - .filter({ hasText: "查看任务结果" }) - await child.focus() - const empty = batch.getByRole("button", { name: /Read/ }) - assert.ok(await empty.isDisabled()) - assert.equal(await empty.locator(".dc-chevron").count(), 0) - const failed = page.locator("summary").filter({ hasText: "失败子调用" }) - assert.match(await failed.textContent(), /失败子调用失败/) - assert.equal( - await failed.evaluate((el) => el.parentElement.dataset.status), - "failed" - ) - await page.keyboard.press("Enter") - await batch.getByText("子任务结果").waitFor() - assert.equal( - await child.evaluate((el) => getComputedStyle(el).outlineStyle), - "solid" - ) - await historyToggle.click() - await page.getByText("先查记录").waitFor({ state: "hidden" }) - assert.ok( - await page.getByText("记录缺失", { exact: false }).first().isVisible() - ) - assert.ok(await page.getByText("用时 3秒").isVisible()) - const stamp = page.locator('[data-message-id="reply"] time') - await stamp.hover() - await page - .locator('[data-slot="tooltip-content"]') - .filter({ hasText: /1970/ }) - .waitFor({ timeout: 5000 }) - await page.keyboard.press("Escape") - await active.locator("summary").click() - await active.getByText("已读取部分内容").waitFor() - if (process.env.CHAT_FLOW_SCREENSHOT) - await view.screenshot({ path: process.env.CHAT_FLOW_SCREENSHOT }) - await page.evaluate(() => window.connect(false)) - await active.getByText("上次同步时:执行中").waitFor() - assert.ok(await active.getByText("已读取部分内容").isVisible()) - await page.evaluate(() => window.connect(true)) - await active.getByText("执行中", { exact: true }).waitFor() - assert.ok(await active.getByText("已读取部分内容").isVisible()) - await view.evaluate((el) => { - el.scrollTop = 100 - }) - await Promise.race([ - started, - page.waitForFunction( - () => !!document.querySelector('[data-message-id="early"]'), - null, - { timeout: 5000 } - ), - ]) - const row = page.locator('[data-message-id="1"]'), - top = async () => (await row.boundingBox()).y, - before = await top() - release() - await page.locator('[data-message-id="early"]').waitFor() - assert.ok(Math.abs((await top()) - before) < 2, "前插消息后阅读位置改变") - await page.evaluate(() => window.append()) - await page.locator('[data-message-id="new"]').waitFor() - assert.ok(Math.abs((await top()) - before) < 2, "新回复抢滚动") - await page.evaluate(() => window.connect(false)) - await page.getByText("连接已断开,显示上次同步的记录。").waitFor() - await page.evaluate(() => { - window.advanceOffline() - window.connect(true) - }) - await page - .getByRole("alert") - .filter({ hasText: "设备报告的会话错误" }) - .waitFor() - assert.deepEqual( - await page - .locator('[data-message-id^="gap-"]') - .evaluateAll((rows) => rows.map((row) => row.dataset.messageId)), - Array.from({ length: 75 }, (_, i) => "gap-" + i) - ) - assert.ok(Math.abs((await top()) - before) < 2, "重连补多页后阅读位置改变") - await page.getByRole("button", { name: "回到最新消息" }).click() - assert.ok( - await view.evaluate( - (el) => el.scrollHeight - el.clientHeight - el.scrollTop < 2 - ) - ) - await page.setViewportSize({ width: 390, height: 700 }) - const user = page.getByRole("article", { name: "你" }).last() - await user.getByRole("button", { name: "展开消息" }).click() - assert.match(await user.innerText(), /最后一行/) - assert.ok( - await view.evaluate((el) => el.scrollWidth <= el.clientWidth), - "窄屏出现横向溢出" - ) - await user.getByRole("button", { name: "收起消息" }).click() - console.log( - "通过:代码高亮、过程折叠、错误和用时、断线重连、自动前插锚定、新回复不抢滚动。" - ) -} finally { - await browser.close() -} diff --git a/monkeyai/web/scripts/check-device-workspace.mjs b/monkeyai/web/scripts/check-device-workspace.mjs deleted file mode 100644 index 14063a121..000000000 --- a/monkeyai/web/scripts/check-device-workspace.mjs +++ /dev/null @@ -1,340 +0,0 @@ -// 使用独立浏览器上下文和协议夹具,不连接真实设备或提交真实任务。 -import assert from "node:assert/strict" -import { chromium } from "playwright-core" - -const origin = process.env.WEB_ORIGIN || "http://localhost:5173" -const machine = "00000000-0000-4000-8000-000000000001", - user = "workspace-test" -const connection = "00000000-0000-4000-8000-000000000002" -const browser = await chromium.launch({ - executablePath: process.env.CHROME_BIN, -}) -try { - const context = await browser.newContext(), - page = await context.newPage() - const pageErrors = [], - writes = [], - messages = new Map([ - [ - "existing", - [ - { - id: "old", - role: "assistant", - parts: [{ type: "text", text: "原有回复" }], - }, - ], - ], - ]) - let wrongTarget = false, - writable = true - let signedIn = false - const account = { - id: user, - name: "测试账号", - email: "test@example.test", - role: "user", - } - const projectFor = new Map() - page.on("pageerror", (e) => pageErrors.push(e.message)) - await page.route("**/api/**", async (route) => { - const req = route.request(), - path = new URL(req.url()).pathname - let result = {} - if (path === "/api/auth/v1/session") - result = { authenticated: signedIn, user: signedIn ? account : null } - else if (path === "/api/auth/v1/methods") - result = { password_enabled: true } - else if (path === "/api/auth/v1/providers") result = { providers: [] } - else if (path === "/api/auth/v1/login") { - signedIn = true - result = account - } else if (path === "/api/v1/me") result = account - else if (path === "/api/v1/endpoints") - result = { page: 1, items: [], total: 0 } - else if (path.endsWith("/connections")) { - const { scopes } = req.postDataJSON() - assert.deepEqual( - scopes, - writable ? ["session:read", "session:control"] : ["session:read"] - ) - result = { - machine_id: machine, - connection_id: connection, - http_base: origin + "/api/v1/endpoints/" + machine + "/proxy/", - ticket: "fixture", - expires_in: 900, - protocol: { acp: 1, runtime_api: 1 }, - scopes, - } - } else if (path.endsWith("/proxy/read/session")) { - assert.equal(req.headers().authorization, "Bearer fixture") - const { params } = req.postDataJSON() - result = { - target: { - userId: user, - machineId: wrongTarget ? "another-device" : machine, - }, - result: { - session: { id: params.sessionId, status: "idle" }, - messages: messages.get(params.sessionId) || [], - olderCursor: null, - }, - } - } - await route.fulfill({ json: result }) - }) - const requests = [] - await page.route("**/oauth/authorize?**", async (route) => { - requests.push(new URL(route.request().url()).searchParams) - await route.fulfill({ contentType: "text/html", body: "授权服务夹具" }) - }) - await page.route("**/oauth/token", (route) => - route.fulfill({ - json: { - access_token: "fixture", - token_type: "Bearer", - expires_in: 600, - scope: "device:connect session:read session:control", - }, - }) - ) - await page.goto(origin + "/client") - await page.waitForURL("**/login") - await page.locator('input[type="email"]').fill(account.email) - assert.equal(requests.length, 0) - await page.locator('input[type="password"]').fill("fixture-password") - await page.locator('button[type="submit"]').click() - await page.waitForURL("**/oauth/authorize?**") - assert.equal(requests.length, 1) - await page.goto(origin + "/client?authorization=cancelled") - await page.getByRole("button", { name: "重新授权" }).click() - await page.waitForURL("**/oauth/authorize?**") - assert.equal(requests.length, 2) - const callback = new URL(requests[1].get("redirect_uri")) - callback.search = new URLSearchParams({ - code: "fixture", - state: requests[1].get("state"), - }) - await page.goto(callback.href) - await page.getByText("暂无设备", { exact: true }).waitFor() - await page.reload() - await page.getByText("暂无设备", { exact: true }).waitFor() - assert.equal(requests.length, 2) - - await page.addInitScript( - ({ user }) => { - sessionStorage.setItem( - "monkeyai.web.device-grant", - JSON.stringify({ - user, - token: "fixture", - expiresAt: Date.now() + 600000, - canReadSessions: true, - canControlSessions: - sessionStorage.getItem("fixture-readonly") !== "yes", - }) - ) - const Native = window.WebSocket - window.WebSocket = class extends Native { - constructor(url, protocols) { - if (!String(url).endsWith("/proxy/acp")) - return new Native(url, protocols) - if (protocols.join(" ") !== "monkeyai.v1 monkeyai.token.fixture") - throw new Error("测试握手子协议不匹配") - const socket = { - protocol: "monkeyai.v1", - readyState: 0, - close() { - this.readyState = 3 - this.onclose?.() - }, - async send(frame) { - const { id, method, params } = JSON.parse(frame) - const result = await window.fixtureRPC(method, params) - if (this.readyState !== 1) return - this.onmessage({ - data: JSON.stringify({ jsonrpc: "2.0", id, result }), - }) - if (method === "_monkeyai/session/queue") - this.onmessage({ - data: JSON.stringify({ - jsonrpc: "2.0", - method: "_monkeyai/session/history_changed", - params: { sessionId: params.sessionId, eventSeq: 3 }, - }), - }) - }, - } - window.fixtureSocket = socket - queueMicrotask(() => { - if (socket.readyState === 0) { - socket.readyState = 1 - socket.onopen?.() - } - }) - return socket - } - } - }, - { user } - ) - await page.exposeFunction("fixtureRPC", (method, params) => { - if (method === "initialize") return { protocolVersion: 1 } - if (method === "session/list") - return { - sessions: [...messages.keys()].map((sessionId) => ({ - sessionId, - title: sessionId === "existing" ? "已有任务" : "新任务", - _meta: { projectId: projectFor.get(sessionId) }, - })), - } - if (method === "_monkeyai/projects/list") - return [{ id: "p", cwd: "/fixture", name: "测试项目" }] - if (method === "session/new") { - writes.push({ method, params }) - const sessionId = "created-" + writes.length - projectFor.set(sessionId, params._meta?.projectId) - messages.set(sessionId, []) - return { sessionId } - } - if (method === "_monkeyai/session/queue") { - writes.push({ method, params }) - messages.get(params.sessionId).push( - { - id: params.id, - role: "user", - parts: [{ type: "text", text: params.text }], - }, - { - id: params.id + "-reply", - role: "assistant", - parts: [{ type: "text", text: "收到:" + params.text }], - } - ) - return { sessionId: params.sessionId, eventSeq: 3 } - } - assert.equal(method, "_monkeyai/session/subscribe") - return {} - }) - const url = origin + "/client/devices/" + machine - const input = page.getByRole("textbox", { name: "任务内容" }), - send = page.getByRole("button", { name: "发送", exact: true }) - await page.goto(url) - await page.getByRole("button", { name: "已有任务" }).waitFor() - await page.getByText("有什么任务要交给这台设备?", { exact: true }).waitFor() - await page.getByRole("button", { name: "收起侧栏" }).click() - await page.getByRole("button", { name: "展开侧栏" }).click() - await page.getByRole("button", { name: "搜索项目和会话" }).click() - const search = page.getByRole("combobox", { name: "搜索项目和会话" }) - await search.fill("不匹配的会话") - await page.getByText("没有匹配的项目或会话。").waitFor() - await search.press("Escape") - await input.fill("第一条任务") - await input.press("Shift+Enter") - assert.equal(writes.length, 0) - await input.press("Enter") - await page.getByText("收到:第一条任务", { exact: true }).waitFor() - assert.equal(writes[0].params.cwd, "") - assert.equal(writes.length, 2) - assert.equal(new URL(page.url()).searchParams.get("session"), "created-1") - await page.getByRole("button", { name: "已有任务" }).click() - await page.getByText("原有回复", { exact: true }).waitFor() - await input.fill("保留草稿") - await page.reload() - await page.getByText("原有回复", { exact: true }).waitFor() - assert.equal(await input.inputValue(), "保留草稿") - await page.evaluate(() => window.fixtureSocket.close()) - await page.getByRole("button", { name: "重新连接" }).waitFor() - assert.equal(await send.isDisabled(), true) - assert.equal(await input.inputValue(), "保留草稿") - await page.getByText("原有回复", { exact: true }).waitFor() - await page.getByRole("button", { name: "重新连接" }).click() - await page.waitForFunction( - () => !document.querySelector('button[type="submit"]').disabled - ) - assert.equal(writes.length, 2) - await send.click() - await page.getByText("收到:保留草稿", { exact: true }).waitFor() - assert.equal(writes.length, 3) - assert.equal(writes[2].params.sessionId, "existing") - await page.getByRole("button", { name: "测试项目的项目操作" }).click() - await page.getByRole("menuitem", { name: "新建任务" }).click() - await page.getByText("工作区:测试项目", { exact: true }).waitFor() - await input.fill("项目任务") - await send.click() - await page.getByText("收到:项目任务", { exact: true }).waitFor() - assert.equal(writes[3].params.cwd, "/fixture") - assert.equal(writes[3].params._meta.projectId, "p") - await page - .getByRole("combobox", { name: "选择工作区" }) - .waitFor({ state: "hidden" }) - await page.setViewportSize({ width: 390, height: 844 }) - const trigger = page.getByRole("button", { name: "项目和会话", exact: true }) - await trigger.click() - const drawer = page.getByRole("dialog", { name: "项目和会话", exact: true }) - await drawer.waitFor() - await drawer.getByRole("button", { name: "搜索项目和会话" }).click() - await search.fill("/fixture") - await page - .getByRole("option", { name: /测试项目/ }) - .first() - .waitFor() - await search.press("Escape") - await drawer - .getByRole("button", { name: "新任务", exact: true }) - .filter({ visible: true }) - .first() - .waitFor() - await page.keyboard.press("Escape") - await drawer.waitFor({ state: "hidden" }) - assert.equal( - await trigger.evaluate((el) => el === document.activeElement), - true - ) - assert.ok( - await page.evaluate( - () => document.documentElement.scrollWidth <= innerWidth - ) - ) - await input.fill("手机草稿") - await input.press("Enter") - assert.equal(await input.inputValue(), "手机草稿\n") - assert.equal(writes.length, 5) - await page.setViewportSize({ width: 1280, height: 800 }) - const projectToggle = page.getByRole("button", { - name: "测试项目", - exact: true, - }) - const previous = page.url() - await projectToggle.click() - assert.equal(page.url(), previous) - await page.keyboard.press("Control+k") - await search.fill("新任务") - const projectResult = page.getByRole("option", { name: /新任务.*测试项目/ }) - await projectResult.click() - assert.equal(await projectToggle.getAttribute("aria-expanded"), "true") - await page.getByRole("button", { name: "新建会话", exact: true }).click() - await page.getByText("工作区:测试项目", { exact: true }).waitFor() - assert.equal(writes.length, 5) - await page.goto(previous) - wrongTarget = true - await page.reload() - await page.getByText(/设备返回的会话与当前目标不符/).waitFor() - await input.fill("不能发") - assert.equal(await send.isDisabled(), true) - wrongTarget = false - writable = false - await page.evaluate(() => sessionStorage.setItem("fixture-readonly", "yes")) - await page.reload() - await page.getByRole("button", { name: "授权访问会话" }).waitFor() - await page.getByText("收到:项目任务", { exact: true }).waitFor() - assert.equal(await send.isDisabled(), true) - assert.equal(context.pages().length, 1) - assert.deepEqual(pageErrors, []) - console.log( - "通过:同页新建、项目任务、旧会话续聊、刷新、断线草稿、重连不补发、目标隔离、只读授权。" - ) -} finally { - await browser.close() -} diff --git a/monkeyai/web/scripts/fixtures/chat-flow.jsx b/monkeyai/web/scripts/fixtures/chat-flow.jsx deleted file mode 100644 index b0246efd3..000000000 --- a/monkeyai/web/scripts/fixtures/chat-flow.jsx +++ /dev/null @@ -1,118 +0,0 @@ -import React from "react" -import { createRoot } from "react-dom/client" -import { DeviceConversation } from "../../src/pages/client/device-conversation" -import "../../src/index.css" -const root = createRoot(document.getElementById("root")), - ready = () => {} -const msg = (id, text) => ({ - id, - role: "assistant", - parts: [{ type: "text", text }], -}) -const messages = Array.from({ length: 29 }, (_, i) => - msg(String(i), "历史记录 " + i) -) -messages.push( - { - id: "reply", - role: "assistant", - startedAt: 1000, - endedAt: 4000, - parts: [ - { type: "text", text: "先查记录" }, - { type: "tool_call", toolCallId: "a" }, - { type: "tool_call", toolCallId: "batch" }, - { type: "tool_call", toolCallId: "child1" }, - { type: "tool_call", toolCallId: "child2" }, - { type: "tool_call", toolCallId: "single" }, - { type: "tool_call", toolCallId: "failedChild" }, - { type: "error", reason: "记录缺失", rawError: "原始诊断" }, - { type: "text", text: "## 最终答复\n~~~js\nconst n = 1\n~~~" }, - ], - }, - { - id: "active", - role: "assistant", - parts: [{ type: "tool_call", toolCallId: "b" }], - } -) -let listener -const channel = { - canWrite: false, - listen(fn) { - listener = fn - return () => {} - }, - async history(id, cursor) { - if (cursor) await window.waitOlder() - return { - session: { id, status: "running" }, - olderCursor: cursor ? null : "older", - messages: cursor ? [msg("early", "更早的记录")] : messages, - toolCalls: { - a: { name: "查找", status: "failed" }, - single: { name: "ExecuteCode", status: "completed" }, - failedChild: { - name: "Read", - title: "失败子调用", - parentToolCallId: "single", - status: "failed", - output: "没有找到文件", - }, - batch: { name: "ExecuteCode", status: "completed" }, - child1: { - parentToolCallId: "batch", - name: "TaskOutput", - status: "completed", - output: "子任务结果", - }, - child2: { - parentToolCallId: "batch", - name: "Read", - status: "completed", - }, - b: { - title: "读取文件", - status: "in_progress", - output: "已读取部分内容", - }, - }, - } - }, -} -window.connect = (online) => - root.render( - - ) -window.append = () => { - messages.push(msg("new", "新增回复")) - listener("session/update", "s") -} -// 模拟重连前后的普通历史页:设备每次最多返回 30 条,只有旧页给出上一页游标。 -window.advanceOffline = () => { - const base = [msg("early", "更早的记录"), ...messages] - const incoming = Array.from({ length: 75 }, (_, i) => - msg("gap-" + i, "补读消息 " + i) - ) - incoming[74] = { - ...incoming[74], - role: "user", - at: 1700000000000, - parts: [{ type: "text", text: "阅读上下文。".repeat(40) + "最后一行" }], - } - const all = [...base, ...incoming] - channel.history = async (id, cursor) => { - const end = cursor ? Number(cursor) : all.length, - start = Math.max(0, end - 30) - return { - session: { id, status: "idle", lastError: "设备报告的会话错误" }, - messages: all.slice(start, end), - olderCursor: start ? String(start) : null, - } - } -} -window.connect(true) diff --git a/monkeyai/web/src/assets/composer-assistant.png b/monkeyai/web/src/assets/composer-assistant.png deleted file mode 100644 index 99cfa3ccd034c208ae13fb1c8aa656ae27812ee3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3857 zcmV+s5AN`ZP)Px#L}ge>W=%~1DgXcg2mk?xX#fNO00031000^Q000001E2u_0{{R30RRC20H6W@ z1ONa40RR91JfH&r1ONa40RR91JOBUy0E^%0TmS$Ldr3q=RA>e5T3KvdAip2%dHt_lNRYSk(*Avhty5}XlR z52hlARCc3oU7_GjC#&GYxN#CKFzDGQ0PX^PHk*~wK>u;CtNqt=uDI=aQcbiN%O=1z znD4$Lm&-ksPNim7%cU?PNJLeEFtRAdR3p>|7kDh7D6+6e2#sUFhcVz{O2mG!Lhw*a z9Z9Ftu3sDsO9wyx<@_7&ebNvlzfTBod7$gMbT;=Y3~KegYA7L67{)QUgh@N`giIq= zd(dZqkigV2tdw;+Is=@c0>&&4F^yG<-mG9U89H%OZkRtEmOgs#o<(>6;vdwSv|vF= zR!Y5{i=1@kDVWgeSIVJquIdsq5>@o10d&K^p47lMYte2>$lN?82pUo%u^2Az9Lr2=H+J z$hveob$7K`jH1A%F>E6qtTeE}8p1wPw;(wu%{WMv&Jf^EZWOan#r)`qk&co>AE7zg zamXVPFO`X8&b-Y>AN}bX6_((Z2(S~S?r+Lunxnvn;ux?o&KM3`h+d84HmU&Xph0Oe zfh-(T!$w6~MQIc@lH@m}q@`fyg<;bkj3dp|lg)D%ZdUbBJU`CXxC_CEukSW za~{Kn!`|UPg%vMsN^4@PTUosw>bhaLeC*Ltwt4mZb+Z;*f^i=W0XuH$8%>!sBZ$^W;aS@ zbJL^dmKA6zgBdvxTq&lF(^n<1W(vi@?z(1_; zT)EgoF|6W7Le;4~93UBeV(Q8RTE}&wbT*3}GnFX94FO|`nirY_1}B+OsD|o|Hp4g( z*TuOv1@~~C>zt$m)XtF`aHiZ8>~?Tw!MTNCLt+CV#*8B%3*)Yb3NambBS1?I5U2U=etVq7ES2{a8C6i9evgOMq*D{SWicZnf zm{D%hN}UA-LFl(wqsDzS1RO>|ibB=Z6h+He(8q}6`}<_;^DoNoPY;P#^Cg$f$n7_6 zlv{7U5wzx9?7FGw=#j(nx947zBb_HSy0d4r%DtO!mn$}G5Z|7`3HJS+JLQE}wo89u zNLTOW7tWKP{P6p5&@v~$xt*HnK=WWz9m~#!SV-G=(TXIkUbH~@KpPK70>38Dz3{TU zzvqBtnwk-bRv7Qfb1(f{cJKLE@PYx%t_&9PvgMiQ<#6XI$!2rXoNJZ*P(}W_^(8sp z-L2`%6mD;8lc%@6B7-GQnwwjkrskX+_`F-5-uj|=UPV)$Mnknu7TU#hXP28wX&>w3 zm4<-1q|lpOxYVmgY=p%EY1btm?L8zdEiH5cuFy#VAO_`w-Jj@OWc$;-`=zU=Pg-+1 zrNb7d={h)6lF#-XWSt(AcXsZUiWjJ(IE|3Ul55UN+tDuR?l~bT3yKbhI(lBGidpki z#CTYBtZ^D}m9T}G1W>q`ts+CiMNQ*$8jBD+VF`*F>iL>}?301Qu%@w(cV~?Vi1=m% zu~7|l%mVTa3=S!X0DHay1`Ret4oQF;80xmvZQ>w`2~6C3_GiNgo5;cr{?qhPI~Bmf zMGK`RmlZBT0SxyMIbL4PlZ#fZ(3OggSiW=#0AZ|F!)Xm*&__^o+UnIS@I@nFO3Jb& zi=|SjL_Vg91s!>wCv#@akVOj?VqpR&GtKx`!6UkG2)-l1H)n@AGSV0@eQp&{xN3u= z1H43BaQ^vn$89%Bxm=b~sU+1(MTQCmxpeJnxo+dP0lbE91A(kXd(+k5!dxy$88l_k z7Er%o)75g(%9T=sBMACC*IpwlzP1#reF4BJvj``7viZ*2WyXx@be5UF)(#p*+j!$T zJp$|OwT3Be5Hg*(y;3lW=9Ytnq~_dw{ibO4>{;^q8*fXoSdz7CR?D4t+#=bg3;`=W z)APqaxJwoxBi{R97qTOgD>tl{TW{PXHAIjFsVmc`x5{sR^>caoU)$xtp>~S{urS^a5dY|lkXw~nxJvJT|jx~%hqES-6k4B;+IjBhMr#Wx$2%GY)ITWGJho zwJfM}mtcly0WprU_=>I50(Leo4FLzf-$g6bqm-wZ)B8W&&2 z@{zVu=(y3rwlUIHXuA&Sh}LujO%<=$8GDsvDLJSEMlV)+uF#%WmZnpk;#N!B*KgUC zXwhm2m_98H4?b2J8mNUqO&27dxNy;e*!sHR28=>bb zAbzR?nO#hIyhS6GJ#2l!z-hlQ&7II=eGl=dtP&bDnCfjWE2}6eVErY6Zw%t4_!c~@KSJE(Y1it z5?^MVuK=Jk@(n$fCUlv#Lw~r_qv?>Oy4u~^(L=|*u<|=&OR{@n!0W&JK&jSu;=XFB z_!+)p8a^8x8l*;Q+xS7Z3}ymfIAXBYK|D+-GL8c^3Ib@rqJwpvGW8$o5Y-TK7QcE( zX(%sY*CDrQ|E?-dG7nt(hu1rkK{Zr1Uy`$&Jn;UrGiIN6U%Be>P(*&3OFL;QHWb^Y zNb3LsG6m%Li`$l&&LX=4<(9;@e$t^t1WMNewwA{MAqZp-m@2|EtAS4*V_*F3rXwb8aEtxpKBo0<2c)@jq1mx}yd z*vu{NhXKyK{E!z^%TDA~_*D;BZHf}4COlz{6pgC-!}N36VxNVrFAZ3o9A|hyGJPi{ z)zft{93K3;gw@B_Jo(1S5lIuPsfr{lgI)Xa`(%1oDxF$dEmz=tyrkp8kK$79KjCD0 z4m-ig&In%v`tWLs(?2s*kH~Sx6A~k+s}fc|8(2I@f$z&ajE78VdiS-Rzt`(Gwj% z_Ux)H@9eaUW95uZ#j)dO(iii@v~ioXaUbiW``MmQ87*i+jFxz^{O6*RJm(BLaY~P| ztPb=M>;1iWUJOIf9&1dUc8rW9&9SnQ@O&XOV~u8;7Z+l^HjAX<`WN(!b)4x573Wqc z>|9H1$XNcdQ6b&fzOg*xwaGiy&U2Q>s7$7uP4U_KljxcZZxZ=aG*celOL< TJ}DK!00000NkvXXu0mjfE3+tS diff --git a/monkeyai/web/src/assets/sidebar-design-expert.png b/monkeyai/web/src/assets/sidebar-design-expert.png deleted file mode 100644 index 0b2c56d1e07fe5c2a93d0ec4b7d7461ba5fa5105..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3650 zcmV-I4!!Y-P)>s5+IOAUWS*vxvFlRzp7pWL7-c|{d@IUtJZt3a_ioG_u1#1Iyb;i zGy)j@(`+js)csBKo=g09V-W6hPiIQVn>I~+9?B0JgL#kA7xmgm92Cv@V?*a4B&$$18WAMW};9|ZU z(`|d!t507pKVof-5cV)9as)+qo~oGDuMI64mO;N6+*W^vHgCS47i#Snfx8P}Iv`8} z)4~}N_oj6_I`FYJ*=i_)340z6m0y)?ZsF|287?P z?k5rD7}{ilXk5lPB1V~+;;O!VrS}7*+zsJ<~DgK3H zXlbvOD~&}yd`7DK3{hZ#%(3G{9l(92wEzgIyTMvJe<5F-2-F7IKLlF46N<1Ra$j1X zOI=&kkMX!v0+A3L8pLIfN7{V+`^~Q$zVI?_e2PI;fmaXkL1|NkuRhM;wG;IK9_{mN z=iW_QrgVx)h-(%c9uXsmCW$K^*;U~zwUykwa4{?M*s2p(4gn}Oh{>NOrnFqI{X?z3 z(`SIe%o|;jNBb6xB6Z1F#j{`(_by7)+|vhfT0hlKTW8R^4h=rg$L$?GUZnHqYj-bB zYgKRT7fWCLCiky9INi!6Qfx$2MnvU-PpzCt(?3f|xptPacCUAAcyZwGTL2FmGYG<6 zQn?4#+tkbT-tN;+j&Pgrz%dTSCYs*u7wmijMlB+7E7ZkGR%T=}uvRZvrCaN?xaptp4 zz6DP_vJ8NvgVZy~{Xj}>TQ@Z54b@nEL`O3CWyZ1#f$%Vh!}~(?$lx|Rq6W050cZOT z+nTrY@R|`l(}zr-IlXbW-hjJG@mIQ_X|l))awLE;*5VP6s!}i`RI8lr&v&vCuS$OT z7JEE7RO`|rlD8c)%G9<;&v{K2&F?z#z1<@wL9nMo6J`X`-0l2%TlnOW6~sqFYSV(W zrb%GY;S3HZG)>V1LKHpK@OY})uYG>lmoqlJI}qj|)mMB4h=>+hl^twHI>>GZQ)Qw~ zy_hs?61Mr5o5&Q(Vz@t5*+@Wl%vLBu&A04h2;{4KYC?I1wa)A=1j|aFL5;nnVors^*6p z#Q2|Ew(5}&D$D-F80&L7Cx?)lYH(&q^hnSFqpTe$EZ%vs#6d8rf?8Q_=$2`In4%(? ziCnn&O(q(rw&Ms6QoU}UD3HdqkJmG8-2w*L&san>KpNn7g7q9g2n*NU%)qFQu$cbI zVypsHcobZyRtX-b30{x?zn3n5d|sc_`R!9vdFIKq+d359m<25-Z>qSj*q!(J<~>W` zB*_xanK>d19!CkjKX#6?&T$lqJy29+7vOaXg1+eH6@=_8g2e(RNjf%WEN`*^#YIq^ zE~F#`Bg`bC+RqI-6itJR6IFUO78lG|`&cXE%*wouN(s@4>d=>`{<;OwtV^dI+LD@} zF*KN(lEHIco+_rkpYa=2+o(;LIb;r8h2o|1Mxr^nBisr>C4xOak9?{M@$9$YrMJN1 z6G57uGr3VU^yJOL!ii3O4fR*85YnMLrKPIaU+6)Fk0Z>?Sce8dNC*)rA~YNV1Gujm zq7=r|DmQO8c(CQgaeH24j7_1uJYjxH%H1JNIa5TIx{>z;2EVy`=N?PbN7bwO=LL%h z#MMuN<604#CI=(cRSM7kKQJM#KA5Hwk-!)!1Vsjc7~CEbCeMME@DNPg15ps*@~H@s z1TeD+T#AI|xCj()gP^%VLI~8vQDkl0O*sDhHRX>@n%4|~!>E{bs|riqNX7PYsiOr4 z&z(GWF+SWPJ=V3eCYr7Ad7QAu)n})^ImM9D8bVMASVbv8_5qHHz^SfMheQg)f^@3Xko3qVH38@?foX*}k225iy0ao5y!=Q7v%|Oih}%)L;o>w!%DI*uM*%AMXIf zH6o0j219?6h2V7sKp9)rlK`tp6gq$~h_)TX%8me*#5;~74(M+@N(B(n4y1(vA)H0T z)KAv`tUl?z7vP}u9>Pq<)MsBAI=W4lPQgXF=jF)QSn1q{t6{bk0HrtJZ=C{gKd9Of zh+uLD5{UsyM^z(jBgF`S=7Ui69bic?Txz5v{nE#A1!Rc_j~&4T%>@Xd5X}~=@w__p z-kzk%^skM)7@e5ZzfIbUa9;d7JNiG*v4*Z9#Kp!SF6ki@Wc|$`Mi6V>8FWT;Z~-OX z(G2N0I1!Ubi)ah@ZUJgJz;*Wv0kBFLD5@7=i6sUFP&Ft%Z@?AOo_iQ%j4>TxSbS2$ z6hOxK1q+0&rPs-Q`3!=rfH^n>wt`&TD7b_MNsZuhI`xNs1deoqG;>G@2^O=YgW*Br zR5c_;6f_0QaTLsRS+7!{&=gR3CxBN#Fq;8qHA=4)UDRi>?hCz}!QUCFo}m#?FT7rS z1pHp8RTb>n+4Es@bAWR|6cJ1+&K=wbgoJ?%SJjC$(qlx@tO*H{Tv=|)J$965A32~2 z-U^eYQCG$zIzUUB3Et=>@T4iwlBRf7TIwt|hrM=q`Z%8cjz7 zCWuVmIr*Gbh)GI9%J4MUZ6!urM%If(-obrLaX27Jra&w(W`GmTR?QR=A{|(}CVyet z$QLH{8}o45fN`mdCyjgShm%KDYZxcaJ)qFmps+_l@C5=*6gf=6;@QIov%XevPEW2o zcYxmo&{X4|JfK?f_`DDp6GaoL<#zNQIUX)cIJoMEXtgrIUQA~W9e^n&7Nj$)Gbae# z6cH-@X~oi${bw!hvhsMr*1t2BpAFYe?6Q zAH?Tdw!Ni;$Qm2a%Uu9p*56a~6a$o&T`#%{$xMt1B>Q~`OGrSg!6V3KvoXd5#70N4 zvw!|0pr{Z;0h*@491$V>ka?W1TD)hB z>9$$}$tONp>mhP0?i<;v=Vp%HyYsyni}~8F@qE|#ZrYZhvErRFY~}%9o^ zTiT&bi!Tq4Lf^pY2@+>_ZZhH6hs#TdoZM)pDhnv@z^A^?mb|imc$hKH=$(IRuWSs= z$q6*z>0|rvBJXt~+2(UzIinI)@}paS%U5-d*Y=F>#@9WbsC~Bj4gD>T>n!_A^Howy z4Q8@FdDnL4j~NbUK_(F?q?Y8+p^SwW-X7jWnX}+vDiukHQ?f6H7ALbtqZ=zG`*I0e$|ow6tGzN~VJ}b~OKqM;7KD_(%=(yQG}>Y>T|Kb%eTS zVt4JG&T;(sC+j$IyTPIk(tR_BJFkAHkn5U)zxbD{C%z;ijdsi$L)!KJ| zUo~&}y|>a{dHrH`-rJeQSpaV8;Gk*jUwwA?KpQ^^qH=h#Q5ic%B5Y0nlyA2VY3+L^ z1Svlro134nGk@P>jsJI}I}4gdw}@(_f4RA7lT^4NLpm~fviP6!pMkm{{^fxF7a%l5 U@UIC=!TPx#L}ge>W=%~1DgXcg2mk?xX#fNO00031000^Q000001E2u_0{{R30RRC20H6W@ z1ONa40RR91JfH&r1ONa40RR91JOBUy0E^%0TmS$Ldr3q=RA>e5T3KvdAip2%dHt_lNRYSk(*Avhty5}XlR z52hlARCc3oU7_GjC#&GYxN#CKFzDGQ0PX^PHk*~wK>u;CtNqt=uDI=aQcbiN%O=1z znD4$Lm&-ksPNim7%cU?PNJLeEFtRAdR3p>|7kDh7D6+6e2#sUFhcVz{O2mG!Lhw*a z9Z9Ftu3sDsO9wyx<@_7&ebNvlzfTBod7$gMbT;=Y3~KegYA7L67{)QUgh@N`giIq= zd(dZqkigV2tdw;+Is=@c0>&&4F^yG<-mG9U89H%OZkRtEmOgs#o<(>6;vdwSv|vF= zR!Y5{i=1@kDVWgeSIVJquIdsq5>@o10d&K^p47lMYte2>$lN?82pUo%u^2Az9Lr2=H+J z$hveob$7K`jH1A%F>E6qtTeE}8p1wPw;(wu%{WMv&Jf^EZWOan#r)`qk&co>AE7zg zamXVPFO`X8&b-Y>AN}bX6_((Z2(S~S?r+Lunxnvn;ux?o&KM3`h+d84HmU&Xph0Oe zfh-(T!$w6~MQIc@lH@m}q@`fyg<;bkj3dp|lg)D%ZdUbBJU`CXxC_CEukSW za~{Kn!`|UPg%vMsN^4@PTUosw>bhaLeC*Ltwt4mZb+Z;*f^i=W0XuH$8%>!sBZ$^W;aS@ zbJL^dmKA6zgBdvxTq&lF(^n<1W(vi@?z(1_; zT)EgoF|6W7Le;4~93UBeV(Q8RTE}&wbT*3}GnFX94FO|`nirY_1}B+OsD|o|Hp4g( z*TuOv1@~~C>zt$m)XtF`aHiZ8>~?Tw!MTNCLt+CV#*8B%3*)Yb3NambBS1?I5U2U=etVq7ES2{a8C6i9evgOMq*D{SWicZnf zm{D%hN}UA-LFl(wqsDzS1RO>|ibB=Z6h+He(8q}6`}<_;^DoNoPY;P#^Cg$f$n7_6 zlv{7U5wzx9?7FGw=#j(nx947zBb_HSy0d4r%DtO!mn$}G5Z|7`3HJS+JLQE}wo89u zNLTOW7tWKP{P6p5&@v~$xt*HnK=WWz9m~#!SV-G=(TXIkUbH~@KpPK70>38Dz3{TU zzvqBtnwk-bRv7Qfb1(f{cJKLE@PYx%t_&9PvgMiQ<#6XI$!2rXoNJZ*P(}W_^(8sp z-L2`%6mD;8lc%@6B7-GQnwwjkrskX+_`F-5-uj|=UPV)$Mnknu7TU#hXP28wX&>w3 zm4<-1q|lpOxYVmgY=p%EY1btm?L8zdEiH5cuFy#VAO_`w-Jj@OWc$;-`=zU=Pg-+1 zrNb7d={h)6lF#-XWSt(AcXsZUiWjJ(IE|3Ul55UN+tDuR?l~bT3yKbhI(lBGidpki z#CTYBtZ^D}m9T}G1W>q`ts+CiMNQ*$8jBD+VF`*F>iL>}?301Qu%@w(cV~?Vi1=m% zu~7|l%mVTa3=S!X0DHay1`Ret4oQF;80xmvZQ>w`2~6C3_GiNgo5;cr{?qhPI~Bmf zMGK`RmlZBT0SxyMIbL4PlZ#fZ(3OggSiW=#0AZ|F!)Xm*&__^o+UnIS@I@nFO3Jb& zi=|SjL_Vg91s!>wCv#@akVOj?VqpR&GtKx`!6UkG2)-l1H)n@AGSV0@eQp&{xN3u= z1H43BaQ^vn$89%Bxm=b~sU+1(MTQCmxpeJnxo+dP0lbE91A(kXd(+k5!dxy$88l_k z7Er%o)75g(%9T=sBMACC*IpwlzP1#reF4BJvj``7viZ*2WyXx@be5UF)(#p*+j!$T zJp$|OwT3Be5Hg*(y;3lW=9Ytnq~_dw{ibO4>{;^q8*fXoSdz7CR?D4t+#=bg3;`=W z)APqaxJwoxBi{R97qTOgD>tl{TW{PXHAIjFsVmc`x5{sR^>caoU)$xtp>~S{urS^a5dY|lkXw~nxJvJT|jx~%hqES-6k4B;+IjBhMr#Wx$2%GY)ITWGJho zwJfM}mtcly0WprU_=>I50(Leo4FLzf-$g6bqm-wZ)B8W&&2 z@{zVu=(y3rwlUIHXuA&Sh}LujO%<=$8GDsvDLJSEMlV)+uF#%WmZnpk;#N!B*KgUC zXwhm2m_98H4?b2J8mNUqO&27dxNy;e*!sHR28=>bb zAbzR?nO#hIyhS6GJ#2l!z-hlQ&7II=eGl=dtP&bDnCfjWE2}6eVErY6Zw%t4_!c~@KSJE(Y1it z5?^MVuK=Jk@(n$fCUlv#Lw~r_qv?>Oy4u~^(L=|*u<|=&OR{@n!0W&JK&jSu;=XFB z_!+)p8a^8x8l*;Q+xS7Z3}ymfIAXBYK|D+-GL8c^3Ib@rqJwpvGW8$o5Y-TK7QcE( zX(%sY*CDrQ|E?-dG7nt(hu1rkK{Zr1Uy`$&Jn;UrGiIN6U%Be>P(*&3OFL;QHWb^Y zNb3LsG6m%Li`$l&&LX=4<(9;@e$t^t1WMNewwA{MAqZp-m@2|EtAS4*V_*F3rXwb8aEtxpKBo0<2c)@jq1mx}yd z*vu{NhXKyK{E!z^%TDA~_*D;BZHf}4COlz{6pgC-!}N36VxNVrFAZ3o9A|hyGJPi{ z)zft{93K3;gw@B_Jo(1S5lIuPsfr{lgI)Xa`(%1oDxF$dEmz=tyrkp8kK$79KjCD0 z4m-ig&In%v`tWLs(?2s*kH~Sx6A~k+s}fc|8(2I@f$z&ajE78VdiS-Rzt`(Gwj% z_Ux)H@9eaUW95uZ#j)dO(iii@v~ioXaUbiW``MmQ87*i+jFxz^{O6*RJm(BLaY~P| ztPb=M>;1iWUJOIf9&1dUc8rW9&9SnQ@O&XOV~u8;7Z+l^HjAX<`WN(!b)4x573Wqc z>|9H1$XNcdQ6b&fzOg*xwaGiy&U2Q>s7$7uP4U_KljxcZZxZ=aG*celOL< TJ}DK!00000NkvXXu0mjfE3+tS diff --git a/monkeyai/web/src/components/accent.css b/monkeyai/web/src/components/accent.css deleted file mode 100644 index e1d4165ab..000000000 --- a/monkeyai/web/src/components/accent.css +++ /dev/null @@ -1,112 +0,0 @@ -/* 桌面端预设色转换为网页使用的 sRGB 通道。 */ -:root[data-accent="ink"], -[data-accent="ink"] { - --primary-rgb: 23 23 23; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 161 161 161; -} -:root.dark[data-accent="ink"], -.dark [data-accent="ink"] { - --primary-rgb: 229 229 229; - --primary-foreground-rgb: 23 23 23; - --ring-rgb: 115 115 115; -} -:root[data-accent="clay"], -[data-accent="clay"] { - --primary-rgb: 165 92 51; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 201 124 84; -} -:root.dark[data-accent="clay"], -.dark [data-accent="clay"] { - --primary-rgb: 165 92 51; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 144 80 44; -} -:root[data-accent="green"], -[data-accent="green"] { - --primary-rgb: 16 127 65; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 40 173 94; -} -:root.dark[data-accent="green"], -.dark [data-accent="green"] { - --primary-rgb: 16 127 65; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 38 117 67; -} -:root[data-accent="teal"], -[data-accent="teal"] { - --primary-rgb: 18 124 115; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 27 168 156; -} -:root.dark[data-accent="teal"], -.dark [data-accent="teal"] { - --primary-rgb: 18 124 115; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 15 114 106; -} -:root[data-accent="blue"], -[data-accent="blue"] { - --primary-rgb: 14 106 222; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 71 144 251; -} -:root.dark[data-accent="blue"], -.dark [data-accent="blue"] { - --primary-rgb: 14 106 222; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 57 99 161; -} -:root[data-accent="indigo"], -[data-accent="indigo"] { - --primary-rgb: 91 93 228; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 122 131 251; -} -:root.dark[data-accent="indigo"], -.dark [data-accent="indigo"] { - --primary-rgb: 91 93 228; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 84 92 161; -} -:root[data-accent="purple"], -[data-accent="purple"] { - --primary-rgb: 146 73 215; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 175 104 248; -} -:root.dark[data-accent="purple"], -.dark [data-accent="purple"] { - --primary-rgb: 146 73 215; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 113 82 150; -} -:root[data-accent="pink"], -[data-accent="pink"] { - --primary-rgb: 200 45 122; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 234 80 150; -} -:root.dark[data-accent="pink"], -.dark [data-accent="pink"] { - --primary-rgb: 200 45 122; - --primary-foreground-rgb: 250 250 250; - --ring-rgb: 147 70 101; -} -:root.light[data-accent="custom"] { - --primary-rgb: var(--primary-light-custom); - --primary-foreground-rgb: var(--primary-foreground-light-custom); - --ring-rgb: var(--ring-light-custom); -} -:root.dark[data-accent="custom"] { - --primary-rgb: var(--primary-dark-custom); - --primary-foreground-rgb: var(--primary-foreground-dark-custom); - --ring-rgb: var(--ring-dark-custom); -} -:root[data-accent] { - --sidebar-primary-rgb: var(--primary-rgb); - --sidebar-primary-foreground-rgb: var(--primary-foreground-rgb); - --sidebar-ring-rgb: var(--ring-rgb); -} diff --git a/monkeyai/web/src/components/auth-provider.tsx b/monkeyai/web/src/components/auth-provider.tsx index c3ba05ed6..bc66e87a0 100644 --- a/monkeyai/web/src/components/auth-provider.tsx +++ b/monkeyai/web/src/components/auth-provider.tsx @@ -10,7 +10,6 @@ import { import { clearHostCommands } from "@/lib/host-command" import { api } from "@/lib/api" import { AuthContext, type AuthUser } from "@/lib/auth-context" -import { clearDeviceGrant, restoreDeviceGrant } from "@/lib/workspace-oauth" export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null) @@ -29,10 +28,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { }>("/api/auth/v1/session") if (request !== revision.current) return setSessionFailed(false) - const current = session.authenticated ? session.user : null - // 新账号不一定会打开设备页;在确认浏览器会话时就清理不匹配的授权。 - restoreDeviceGrant(current?.id ?? null) - setUser(current) + setUser(session.authenticated ? session.user : null) } catch { if (request === revision.current) setSessionFailed(true) } finally { @@ -49,7 +45,6 @@ export function AuthProvider({ children }: { children: ReactNode }) { const acceptLogin = useCallback((authenticated: AuthUser) => { revision.current++ - restoreDeviceGrant(authenticated.id) setUser(authenticated) setSessionFailed(false) setIsLoading(false) @@ -57,7 +52,6 @@ export function AuthProvider({ children }: { children: ReactNode }) { const logout = useCallback(async () => { await api("/api/auth/v1/logout", { method: "POST" }) - clearDeviceGrant() revision.current++ setSessionFailed(false) setIsLoading(false) diff --git a/monkeyai/web/src/components/branding-provider.tsx b/monkeyai/web/src/components/branding-provider.tsx index 7b8d3758b..02cd80d5f 100644 --- a/monkeyai/web/src/components/branding-provider.tsx +++ b/monkeyai/web/src/components/branding-provider.tsx @@ -9,7 +9,6 @@ import { export function BrandingProvider({ children }: { children: ReactNode }) { const [branding, setBranding] = useState(DEFAULT_BRANDING) - const [workspaceLabel, setWorkspaceLabel] = useState("") const [failedURL, setFailedURL] = useState("") const generation = useRef(0) const refreshBranding = useCallback(async (signal?: AbortSignal) => { @@ -20,7 +19,6 @@ export function BrandingProvider({ children }: { children: ReactNode }) { }) if (signal?.aborted || current !== generation.current) return setFailedURL("") - setWorkspaceLabel(value.workspace_name?.trim() || "") setBranding({ workspace_name: value.workspace_name?.trim() || DEFAULT_BRANDING.workspace_name, @@ -30,10 +28,8 @@ export function BrandingProvider({ children }: { children: ReactNode }) { has_commercial_license: value.has_commercial_license === true, }) } catch { - if (!signal?.aborted && current === generation.current) { + if (!signal?.aborted && current === generation.current) setBranding(DEFAULT_BRANDING) - setWorkspaceLabel("") - } } }, []) useEffect(() => { @@ -87,7 +83,7 @@ export function BrandingProvider({ children }: { children: ReactNode }) { }, [logoURL]) return ( {children} diff --git a/monkeyai/web/src/components/device-platform-icon.tsx b/monkeyai/web/src/components/device-platform-icon.tsx deleted file mode 100644 index ed8f1ef7c..000000000 --- a/monkeyai/web/src/components/device-platform-icon.tsx +++ /dev/null @@ -1,26 +0,0 @@ -/** - * [INPUT]: 依赖设备上报的平台名、宿主平台名和 Hugeicons 系统图标。 - * [OUTPUT]: 提供 DevicePlatformIcon,统一系统标识、尺寸与无障碍名称;未知平台保留通用电脑图标。 - * [POS]: 设置设备列表与工作台设备菜单共用的纯展示组件,不读取宿主或设备目录。 - * [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md - */ -import { HugeiconsIcon } from '@hugeicons/react' -import { AppleIcon, ComputerIcon, WindowsOldIcon } from '@hugeicons/core-free-icons' - -// Linux 图形来自 Simple Icons(CC0):https://github.com/simple-icons/simple-icons/blob/develop/icons/linux.svg -const linuxPath = 'M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.36.333.292.2.68.467 1.167.467.485 0 1.053-.267 1.398-.466.195-.135.445-.334.648-.467.156-.136.149-.267.279-.267.128.016.034.134-.147.332a8.097 8.097 0 01-.69.468zm-1.082-1.583V5.64c-.006-.02.013-.042.029-.05.074-.043.18-.027.26.004.063 0 .16.067.15.135-.006.049-.085.066-.135.066-.055 0-.092-.043-.141-.068-.052-.018-.146-.008-.163-.065zm-.551 0c-.02.058-.113.049-.166.066-.047.025-.086.068-.14.068-.05 0-.13-.02-.136-.068-.01-.066.088-.133.15-.133.08-.031.184-.047.259-.005.019.009.036.03.03.05v.02h.003z' - -export function DevicePlatformIcon({ platform, size = 20, className = '' }: { platform?: string; size?: number; className?: string }) { - const key = platform?.trim().toLowerCase() - const name = key === 'macos' || key === 'darwin' || key === 'mac' ? 'macOS' - : key === 'windows' || key === 'win32' ? 'Windows' - : key === 'linux' ? 'Linux' - : key === 'harmonyos' || key === 'ohos' ? 'HarmonyOS' - : platform?.trim() - const icon = name === 'macOS' ? AppleIcon : name === 'Windows' ? WindowsOldIcon : ComputerIcon - return - {name === 'Linux' - ? - : -} diff --git a/monkeyai/web/src/components/named-themes.css b/monkeyai/web/src/components/named-themes.css deleted file mode 100644 index 0b1cf95e1..000000000 --- a/monkeyai/web/src/components/named-themes.css +++ /dev/null @@ -1,59 +0,0 @@ -/* 桌面端 emboss.css 的纸面、外壳与控件色,转换为 Tailwind 使用的 sRGB 通道。 */ -:root[data-theme="century-blue"] { - color-scheme: light; - -webkit-font-smoothing: antialiased; - --theme-paper-rgb: 249 250 251; - --theme-shell-rgb: 232 236 240; - --theme-control-rgb: 236 239 243; - --theme-ink-rgb: 56 56 56; - --muted-foreground-rgb: 88 88 88; - --secondary-hover-rgb: 225 229 234; - --border-rgb: 186 190 195; - --radius: 1rem; - --settings-overlay: oklch(0.16 0.01 250 / 0.42); - --settings-edge: oklch(0.52 0.016 250); - --settings-shadow: none; -} - -:root[data-theme="textured-gray"] { - color-scheme: dark; - --theme-paper-rgb: 55 57 62; - --theme-shell-rgb: 44 46 50; - --theme-control-rgb: 63 65 69; - --theme-ink-rgb: 226 229 233; - --muted-foreground-rgb: 161 165 171; - --secondary-hover-rgb: 79 83 89; - --border-rgb: 74 77 83; - --settings-overlay: oklch(0.08 0.008 264 / 0.58); - --settings-edge: oklch(0.62 0.012 264 / 0.55); - --settings-shadow: inset 1px 1px 0 oklch(0.62 0.012 264 / 0.75), inset -1px -1px 0 oklch(0.08 0.01 264 / 0.7), -4px -4px 7px oklch(0.52 0.012 264 / 0.85), 4px 4px 8px oklch(0.08 0.01 264 / 0.5), 0 20px 48px oklch(0.02 0.008 264 / 0.5); - --theme-grain: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='160' height='160' filter='url(%23g)' opacity='0.2'/%3E%3C/svg%3E"); -} - -:root:is([data-theme="century-blue"], [data-theme="textured-gray"]) { - --background-rgb: var(--theme-paper-rgb); - --card-rgb: var(--theme-paper-rgb); - --popover-rgb: var(--theme-paper-rgb); - --foreground-rgb: var(--theme-ink-rgb); - --card-foreground-rgb: var(--theme-ink-rgb); - --popover-foreground-rgb: var(--theme-ink-rgb); - --secondary-foreground-rgb: var(--theme-ink-rgb); - --accent-foreground-rgb: var(--theme-ink-rgb); - --secondary-rgb: var(--theme-control-rgb); - --accent-rgb: var(--theme-control-rgb); - --muted-rgb: var(--theme-control-rgb); - --sidebar-rgb: var(--theme-shell-rgb); - --sidebar-foreground-rgb: var(--theme-ink-rgb); - --sidebar-accent-rgb: var(--theme-control-rgb); - --sidebar-accent-foreground-rgb: var(--theme-ink-rgb); - --border-alpha: 1; - --border: rgb(var(--border-rgb)); - --input-rgb: var(--border-rgb); - --input-alpha: 1; - --input: var(--border); -} - -:root[data-theme] :is(.workspace-device-shell, .dw-topbar, .dw-rail) { - background-color: rgb(var(--theme-shell-rgb)); - background-image: var(--theme-grain, none); -} diff --git a/monkeyai/web/src/components/theme-provider.tsx b/monkeyai/web/src/components/theme-provider.tsx index e0bb3288f..8c603de6b 100644 --- a/monkeyai/web/src/components/theme-provider.tsx +++ b/monkeyai/web/src/components/theme-provider.tsx @@ -1,11 +1,8 @@ /* eslint-disable react-refresh/only-export-components */ import * as React from "react" -import { isTheme, resolveTheme, type Theme } from "@/lib/themes" -import "./named-themes.css" -import { useAccentPreference } from "@/lib/accent" -import { initInterfaceSize } from "@/lib/interface-size" -import "./accent.css" +export type Theme = "dark" | "light" | "system" +type ResolvedTheme = "dark" | "light" type ThemeProviderProps = { children: React.ReactNode @@ -15,17 +12,33 @@ type ThemeProviderProps = { } type ThemeProviderState = { - accentPreference: ReturnType theme: Theme setTheme: (theme: Theme) => void } const COLOR_SCHEME_QUERY = "(prefers-color-scheme: dark)" +const THEME_VALUES: Theme[] = ["dark", "light", "system"] const ThemeProviderContext = React.createContext< ThemeProviderState | undefined >(undefined) +function isTheme(value: string | null): value is Theme { + if (value === null) { + return false + } + + return THEME_VALUES.includes(value as Theme) +} + +function getSystemTheme(): ResolvedTheme { + if (window.matchMedia(COLOR_SCHEME_QUERY).matches) { + return "dark" + } + + return "light" +} + function disableTransitionsTemporarily() { const style = document.createElement("style") style.appendChild( @@ -52,8 +65,6 @@ export function ThemeProvider({ disableTransitionOnChange = true, ...props }: ThemeProviderProps) { - const accentPreference = useAccentPreference() - React.useLayoutEffect(initInterfaceSize, []) const [theme, setThemeState] = React.useState(() => { const storedTheme = localStorage.getItem(storageKey) if (isTheme(storedTheme)) { @@ -74,15 +85,14 @@ export function ThemeProvider({ const applyTheme = React.useCallback( (nextTheme: Theme) => { const root = document.documentElement - const { mode, named } = resolveTheme(nextTheme, window.matchMedia(COLOR_SCHEME_QUERY).matches) + const resolvedTheme = + nextTheme === "system" ? getSystemTheme() : nextTheme const restoreTransitions = disableTransitionOnChange ? disableTransitionsTemporarily() : null root.classList.remove("light", "dark") - root.classList.add(mode) - if (named) root.dataset.theme = named - else delete root.dataset.theme + root.classList.add(resolvedTheme) if (restoreTransitions) { restoreTransitions() @@ -91,7 +101,7 @@ export function ThemeProvider({ [disableTransitionOnChange] ) - React.useLayoutEffect(() => { + React.useEffect(() => { applyTheme(theme) if (theme !== "system") { @@ -138,10 +148,9 @@ export function ThemeProvider({ const value = React.useMemo( () => ({ theme, - accentPreference, setTheme, }), - [theme, setTheme, accentPreference] + [theme, setTheme] ) return ( diff --git a/monkeyai/web/src/components/theme-toggle.tsx b/monkeyai/web/src/components/theme-toggle.tsx index e1e1b14f9..f8d8dc7ee 100644 --- a/monkeyai/web/src/components/theme-toggle.tsx +++ b/monkeyai/web/src/components/theme-toggle.tsx @@ -7,8 +7,7 @@ import { HugeiconsIcon } from "@hugeicons/react" import type { ComponentProps } from "react" import { useTranslation } from "react-i18next" -import { useTheme } from "@/components/theme-provider" -import { themes, type Theme } from "@/lib/themes" +import { useTheme, type Theme } from "@/components/theme-provider" import { Button } from "@/components/ui/button" import { DropdownMenu, @@ -19,13 +18,15 @@ import { DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" -const themeIcons = { - system: SunMoonIcon, - light: Sun03Icon, - dark: MoonSlowWindIcon, - "century-blue": Sun03Icon, - "textured-gray": MoonSlowWindIcon, -} satisfies Record +const themeOptions = [ + { value: "light", labelKey: "theme.light", icon: Sun03Icon }, + { value: "dark", labelKey: "theme.dark", icon: MoonSlowWindIcon }, + { value: "system", labelKey: "theme.system", icon: SunMoonIcon }, +] satisfies Array<{ + value: Theme + labelKey: "theme.light" | "theme.dark" | "theme.system" + icon: typeof Sun03Icon +}> type ThemeToggleProps = Pick, "variant" | "size"> @@ -35,6 +36,8 @@ export function ThemeToggle({ }: ThemeToggleProps = {}) { const { t } = useTranslation() const { theme, setTheme } = useTheme() + const currentTheme = + themeOptions.find((option) => option.value === theme) ?? themeOptions[2] return ( @@ -44,12 +47,12 @@ export function ThemeToggle({ variant={variant} size={size} aria-label={t("theme.change", { - theme: t(`theme.${theme}`), + theme: t(currentTheme.labelKey), })} /> } > - + setTheme(value)} > {t("theme.label")} - {themes.map((value) => ( + {themeOptions.map((option) => ( - - {t(`theme.${value}`)} + + {t(option.labelKey)} ))} diff --git a/monkeyai/web/src/components/ui/color-selector.tsx b/monkeyai/web/src/components/ui/color-selector.tsx deleted file mode 100644 index 84a80f4c1..000000000 --- a/monkeyai/web/src/components/ui/color-selector.tsx +++ /dev/null @@ -1,230 +0,0 @@ -"use client" -// beui.dev/components/motion/color-selector - -import { - arc, - LayoutGroup, - motion, - type Transition, - useReducedMotion, -} from "motion/react" -import { - type ComponentPropsWithRef, - createContext, - useContext, - useId, - useState, -} from "react" -import { cn } from "@/lib/utils" -const SPRING_LAYOUT = { - type: "spring", - stiffness: 360, - damping: 32, - mass: 0.6, -} as const -const SPRING_PRESS = { - type: "spring", - stiffness: 500, - damping: 30, - mass: 0.6, -} as const - -// The selection ring hops to the next swatch over a low arc instead of -// sliding. arc() bends with distance (apex at half of strength x distance): -// ~6px to a neighbour, under 40px across a row of eight. Automatic direction -// puts a horizontal bulge below the row; a negative strength mirrors it above -// in both directions of travel. -const SELECTION_HOP: Transition = { - ...SPRING_LAYOUT, - layout: { ...SPRING_LAYOUT, path: arc({ strength: -0.2 }) }, -} - -type ColorSelectorContextValue = { - value: string - select: (value: string) => void - name: string - disabled: boolean - required: boolean - form?: string -} - -const ColorSelectorContext = createContext( - null -) - -export interface ColorSelectorProps extends Omit< - ComponentPropsWithRef<"fieldset">, - "onChange" | "defaultValue" -> { - value?: string - defaultValue?: string - onValueChange?: (value: string) => void - /** The radio group name used in form submission. Generated when omitted. */ - name?: string - required?: boolean -} - -/** A single color choice. Give it a ColorSelectorLabel or an aria-label. */ -export function ColorSelector({ - value, - defaultValue = "", - onValueChange, - name, - disabled = false, - required = false, - form, - className, - children, - ...props -}: ColorSelectorProps) { - const id = useId() - const [internal, setInternal] = useState(defaultValue) - const current = value ?? internal - return ( - { - if (next === current) return - if (value === undefined) setInternal(next) - onValueChange?.(next) - }, - name: name ?? id, - disabled, - required, - form, - }} - > -
- {children} -
-
- ) -} - -export type ColorSelectorLabelProps = ComponentPropsWithRef<"legend"> - -export function ColorSelectorLabel({ - className, - ...props -}: ColorSelectorLabelProps) { - return ( - - ) -} - -export type ColorSelectorListProps = ComponentPropsWithRef<"div"> - -export function ColorSelectorList({ - className, - ...props -}: ColorSelectorListProps) { - return ( -
- ) -} - -export interface ColorSelectorItemProps extends Omit< - ComponentPropsWithRef<"input">, - | "type" - | "value" - | "defaultValue" - | "checked" - | "defaultChecked" - | "name" - | "children" - | "size" -> { - value: string - /** Any CSS color, including a custom property. */ - color: string - /** Accessible color name; selection never relies on color alone. */ - label: string - /** Applied to the visible swatch surface. */ - className?: string -} - -export function ColorSelectorItem({ - value, - color, - label, - disabled = false, - className, - style, - onChange, - ...props -}: ColorSelectorItemProps) { - const context = useContext(ColorSelectorContext) - const reduce = useReducedMotion() - if (!context) - throw new Error("ColorSelectorItem must be used within ColorSelector") - const selected = context.value === value - const unavailable = disabled || context.disabled - return ( - - { - onChange?.(event) - if (!event.defaultPrevented) context.select(value) - }} - className="peer sr-only" - /> - - ) -} diff --git a/monkeyai/web/src/components/ui/dialog.tsx b/monkeyai/web/src/components/ui/dialog.tsx index 67f4846d5..beb68ca16 100644 --- a/monkeyai/web/src/components/ui/dialog.tsx +++ b/monkeyai/web/src/components/ui/dialog.tsx @@ -25,16 +25,14 @@ function DialogClose({ ...props }: DialogPrimitive.Close.Props) { function DialogOverlay({ className, - fadeOnly = false, ...props -}: DialogPrimitive.Backdrop.Props & { fadeOnly?: boolean }) { +}: DialogPrimitive.Backdrop.Props) { return ( - + & { fadeOnly?: boolean }) { + >) { return ( diff --git a/monkeyai/web/src/components/ui/popover.tsx b/monkeyai/web/src/components/ui/popover.tsx index 6ebd0120e..87afa177f 100644 --- a/monkeyai/web/src/components/ui/popover.tsx +++ b/monkeyai/web/src/components/ui/popover.tsx @@ -18,12 +18,11 @@ function PopoverContent({ alignOffset = 0, side = "bottom", sideOffset = 4, - collisionAvoidance, ...props }: PopoverPrimitive.Popup.Props & Pick< PopoverPrimitive.Positioner.Props, - "align" | "alignOffset" | "side" | "sideOffset" | "collisionAvoidance" + "align" | "alignOffset" | "side" | "sideOffset" >) { return ( @@ -32,7 +31,6 @@ function PopoverContent({ alignOffset={alignOffset} side={side} sideOffset={sideOffset} - collisionAvoidance={collisionAvoidance} className="isolate z-50" > :not(#root) :is( - [data-slot="popover-content"], - [data-slot="tooltip-content"], - [data-slot="dropdown-menu-content"], - [data-slot="dropdown-menu-sub-content"], - [data-slot="select-content"], - [data-slot="dialog-content"] -) { - zoom: var(--workspace-scale, 1); -} - @layer components { .account-user-link:is(:enabled, :any-link):hover, .account-user-link:is(:enabled, :any-link):focus-visible { @@ -26,24 +13,6 @@ body > :not(#root) :is( } } -.ui-fade-only { - transition: opacity 120ms ease-out; -} -.ui-fade-only[data-starting-style], -.ui-fade-only[data-ending-style] { - opacity: 0; -} - -/* A sidebar action dialog can mount already open, without a starting-style frame. */ -@starting-style { - .ui-fade-only[data-open] { - opacity: 0; - } -} -@media (prefers-reduced-motion: reduce) { - .ui-fade-only { transition: none; } -} - @keyframes marquee { to { transform: translateX(calc(-100% - var(--gap))); diff --git a/monkeyai/web/src/lib/accent.ts b/monkeyai/web/src/lib/accent.ts deleted file mode 100644 index 32f8bd50d..000000000 --- a/monkeyai/web/src/lib/accent.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { useLayoutEffect, useState } from "react" -import { customAccentVars } from "./custom-accent" - -export const accents = { - ink: "墨色", - clay: "陶土", - green: "绿色", - teal: "青色", - blue: "蓝色", - indigo: "靛蓝", - purple: "紫色", - pink: "粉色", -} as const -export type Accent = keyof typeof accents | "custom" -const key = "workspace-accent" -const defaults = { accent: "ink" as Accent, color: "#7C3AED" } -function read() { - try { - const v = JSON.parse(localStorage.getItem(key) || "null") - if ( - v && - (Object.hasOwn(accents, v.accent) || v.accent === "custom") && - /^#[0-9a-f]{6}$/i.test(v.color) - ) - return { accent: v.accent as Accent, color: String(v.color) } - } catch { - /* 保留默认配色。 */ - } - return defaults -} -export function useAccentPreference() { - const [pref, setPref] = useState(read) - useLayoutEffect(() => { - const sync = (e: StorageEvent) => { - if (e.key === key || e.key === null) setPref(read()) - } - window.addEventListener("storage", sync) - return () => window.removeEventListener("storage", sync) - }, []) - useLayoutEffect(() => { - const root = document.documentElement - root.dataset.accent = pref.accent - if (pref.accent !== "custom") return - for (const dark of [false, true]) { - for (const [name, hex] of Object.entries( - customAccentVars(pref.color, dark) - )) { - root.style.setProperty( - name + (dark ? "-dark" : "-light") + "-custom", - [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)).join(" ") - ) - } - } - }, [pref]) - return { - ...pref, - setAccent(accent: Accent, color = pref.color) { - const next = { accent, color } - setPref(next) - try { - localStorage.setItem(key, JSON.stringify(next)) - } catch { - /* 本次会话仍然生效。 */ - } - }, - } -} diff --git a/monkeyai/web/src/lib/branding.ts b/monkeyai/web/src/lib/branding.ts index 7d41cd177..f86c65202 100644 --- a/monkeyai/web/src/lib/branding.ts +++ b/monkeyai/web/src/lib/branding.ts @@ -16,7 +16,6 @@ export const DEFAULT_BRANDING: Branding = { export const BrandingContext = createContext<{ branding: Branding - workspaceLabel?: string logoURL: string refreshBranding: () => Promise failLogo: () => void diff --git a/monkeyai/web/src/lib/client-callback.ts b/monkeyai/web/src/lib/client-callback.ts index f00b85e3b..1f4ba5e6b 100644 --- a/monkeyai/web/src/lib/client-callback.ts +++ b/monkeyai/web/src/lib/client-callback.ts @@ -2,7 +2,6 @@ const registeredCallbacks: Record = { "monkeyai-desktop": "monkeyai-desktop://oauth/callback", "monkeyai-mobile": "monkeyai-mobile://oauth/callback", } -const localWebCallback = "http://localhost:5173/client/oauth/callback" const localOrigin = /^(https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\]):[1-9]\d{0,4})(?:\/|$)/ @@ -11,18 +10,6 @@ export function isLocalRedirect(uri: string, origins: readonly string[] = []) { return !!match && !/[?#\\\s]/.test(uri) && origins.includes(match[1]) } -export function webDeviceListOnCancel(clientID: string, redirectURI: string) { - if ( - clientID !== "monkeyai-web" || - (redirectURI !== window.location.origin + "/client/oauth/callback" && - redirectURI !== localWebCallback) - ) - return null - return new URL("/client?authorization=cancelled", redirectURI).href -} - -// Mirror the server's native/loopback destinations, and bind the issued URL to -// the destination shown on the confirmation page. Never navigate arbitrary URLs. export function isSafeClientLaunchURL( clientID: string, redirectURI: string, diff --git a/monkeyai/web/src/lib/custom-accent.ts b/monkeyai/web/src/lib/custom-accent.ts deleted file mode 100644 index 35f0cc135..000000000 --- a/monkeyai/web/src/lib/custom-accent.ts +++ /dev/null @@ -1,125 +0,0 @@ -/** - * [INPUT]: 依赖六位十六进制色号和解析后的明暗状态。 - * [OUTPUT]: 生成自定义主题色的填充、悬停、文字和焦点变量。按钮与用户气泡优先保留所选原色,按对比度翻转字色,只有两种字色都不够时才微调填充;页面文字与焦点保留 HSL 色相和饱和度,只调明度以适配明暗底色,避免浅紫混黑后发灰。 - * [POS]: 外观自定义颜色与全局主题之间的纯函数接缝。 - * [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md - */ -type RGB = [number, number, number] - -function rgb(hex: string): RGB { - return [1, 3, 5].map((start) => - parseInt(hex.slice(start, start + 2), 16) - ) as RGB -} - -function hex(color: RGB): string { - return `#${color.map((channel) => Math.round(channel).toString(16).padStart(2, "0")).join("")}` -} - -function mix(color: RGB, target: RGB, amount: number): RGB { - return color.map( - (channel, index) => channel + (target[index]! - channel) * amount - ) as RGB -} - -function luminance(color: RGB): number { - const linear = color.map((channel) => { - const value = channel / 255 - return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4 - }) - return linear[0]! * 0.2126 + linear[1]! * 0.7152 + linear[2]! * 0.0722 -} - -// 在 sRGB 范围内朝黑/白微调,原色已可读时保持不变。 -function readable( - color: RGB, - target: RGB, - background: RGB, - ratio: number -): RGB { - const bg = luminance(background) - for (let step = 0; step <= 100; step++) { - const candidate = mix(color, target, step / 100).map(Math.round) as RGB - const value = luminance(candidate) - if ((Math.max(value, bg) + 0.05) / (Math.min(value, bg) + 0.05) >= ratio) - return candidate - } - return target -} - -function readableText(color: RGB, dark: boolean): RGB { - // 使用比实际浅色外壳稍暗、比深色卡片稍亮的参照底色,给不同主题留出余量。 - const background: RGB = dark ? [64, 64, 68] : [232, 234, 238] - if (contrast(color, background) >= 4.5) return color - const channels = color.map((value) => value / 255) - const lightness = (Math.max(...channels) + Math.min(...channels)) / 2 - const span = Math.min(lightness, 1 - lightness) - // 同比例缩放通道到明度的距离,可固定 HSL 色相与饱和度,不把浅色直接混成灰色。 - for (let step = 1; step <= 100; step++) { - const next = lightness + (((dark ? 1 : 0) - lightness) * step) / 100 - const scale = span ? Math.min(next, 1 - next) / span : 0 - const candidate = channels.map((value) => - Math.round((next + (value - lightness) * scale) * 255) - ) as RGB - if (contrast(candidate, background) >= 4.5) return candidate - } - return dark ? WHITE : BLACK -} - -export function customAccentVars( - value: string, - dark: boolean -): Record { - const color = rgb(value) - const { fill, foreground } = readableFill(color, 5) - // 悬停仍用同一字色;纯黑/纯白已无法继续加深/提亮时,反向轻调并守住对比度。 - const hoverTarget = foreground === WHITE ? BLACK : WHITE - let hover = mix(fill, hoverTarget, 0.12) - if (hex(hover) === hex(fill)) - hover = readable(mix(fill, foreground, 0.08), hoverTarget, foreground, 5) - const text = readableText(color, dark) - const primary = hex(fill) - const label = hex(foreground) - const ring = hex(text) - return { - "--primary": primary, - "--primary-foreground": label, - "--primary-hover": hex(hover), - "--primary-text": ring, - "--ring": ring, - "--sidebar-primary": primary, - "--sidebar-primary-foreground": label, - "--sidebar-ring": ring, - } -} - -const WHITE: RGB = [255, 255, 255] -const INK: RGB = [26, 26, 26] -const BLACK: RGB = [0, 0, 0] - -function contrast(color: RGB, other: RGB): number { - const left = luminance(color) - const right = luminance(other) - return (Math.max(left, right) + 0.05) / (Math.min(left, right) + 0.05) -} - -// 先换字色,不为迁就白字把浅色混成灰色。 -function readableFill( - picked: RGB, - ratio: number -): { fill: RGB; foreground: RGB } { - const onWhite = contrast(picked, WHITE) - const onInk = contrast(picked, INK) - let fill = picked - let foreground: RGB - if (onWhite >= ratio && onWhite >= onInk) foreground = WHITE - else if (onInk >= ratio) foreground = INK - else if (onWhite >= onInk) { - foreground = WHITE - fill = readable(picked, BLACK, WHITE, ratio) - } else { - foreground = INK - fill = readable(picked, WHITE, INK, ratio) - } - return { fill, foreground } -} diff --git a/monkeyai/web/src/lib/device-chat-errors.ts b/monkeyai/web/src/lib/device-chat-errors.ts deleted file mode 100644 index 493d2ae5c..000000000 --- a/monkeyai/web/src/lib/device-chat-errors.ts +++ /dev/null @@ -1,37 +0,0 @@ -const reasons = new Map([ - ["session_reads_unavailable", "当前设备不支持通过数据通道读取历史,请更新执行端。"], - ["session_read_failed", "会话正文读取失败,请重试。"], - ["session_read_too_large", "这次读取超出了正文大小限制。"], - ["session_read_busy", "正在读取的会话正文较多,请稍后重试。"], - ["runtime_not_ready", "运行时启动超时,请稍后重试。"], - ["runtime_exited", "运行时已退出,正在重新启动。"], - ["runtime_stopped", "运行时已停止。"], - ["device_offline", "目标设备暂时不可连接,请检查它是否在线并开启远程访问。"], - ["model_unavailable", "当前模型不可用。请选择其他可用模型,或在设置中刷新模型列表后再试。"], - ["project_folder_missing", "项目文件夹不见了,可能被改名、移走或删掉了。在侧栏的项目菜单里重新指定文件夹,或把它放回原位。"], - ["workspace_missing", "这个任务的工作目录不见了,可能被改名、移走或删掉了。"], - ["invalid_cwd", "这个文件夹不可用,请选择一个已存在的文件夹。"], - ["engine_cancelled", "本轮已停止。"], - ["engine_timeout", "等待上游响应超时,请重试。"], - ["engine_no_result", "引擎没有返回结果,请重试。"], - ["engine_internal", "引擎内部出错,请重试;反复出现可在诊断页查看日志。"], - ["session_running", "任务正在执行,请在结束后修改设置。"], - ["Session is busy; cannot change thinking while running", "任务正在执行,请在结束后修改设置。"], - ["Session is not running", "本轮已经结束,这条消息会作为新一轮接着发出。"], - ["Session is no longer accepting steer messages", "本轮已经结束,这条消息会作为新一轮接着发出。"], -]) - -export function friendlyError(reason: string) { - if (/^(internal error|unknown error)$/i.test(reason)) return "操作失败,未收到具体原因,请重试。" - return reasons.get(reason) ?? reason -} - -export function errorSummary(reason: string) { - const retry = /^provider retry limit reached after \d+ retries:\s*/i.exec(reason) - if (retry) { - const cause = reason.slice(retry[0].length).trim() - const reset = /^(?:Post|Get) "[^"\r\n]+": (?:read|write) tcp [^\r\n]+: (?:connection reset by peer|(?:wsarecv|wsasend): An existing connection was forcibly closed by the remote host\.?)$/i.test(cause) - return reset ? "模型服务连接中断,请稍后重试。" : "模型请求多次重试后仍未成功。" - } - return friendlyError(reason) -} diff --git a/monkeyai/web/src/lib/device-composer-options.ts b/monkeyai/web/src/lib/device-composer-options.ts deleted file mode 100644 index 9e52266be..000000000 --- a/monkeyai/web/src/lib/device-composer-options.ts +++ /dev/null @@ -1,37 +0,0 @@ -import type { DeviceChannel } from "./device-connection" - -export type ComposerChoice = { mode: string; expertId: string } -export type ComposerConfig = ComposerChoice & { revision?: number } -export function observedConfig( - session: Record -): ComposerConfig { - const rev = session.configurationRevision - return { - mode: typeof session.mode === "string" ? session.mode : "", - expertId: typeof session.expertId === "string" ? session.expertId : "", - revision: - typeof rev === "number" && Number.isSafeInteger(rev) && rev >= 0 - ? rev - : undefined, - } -} -export async function configureComposer( - ch: DeviceChannel, - sessionId: string, - revision: number, - change: { mode: string } | { expertId: string } -) { - if (!ch.canWrite || !Number.isSafeInteger(revision) || revision < 0) - throw new Error("当前无法更改会话设置。") - const permission = "mode" in change - if (permission && !["auto", "bypassPermissions"].includes(change.mode)) - throw new Error("不支持的执行权限。") - await ch.request( - permission ? "session/set_mode" : "_monkeyai/session/expert/set", - { - sessionId, - ...(permission ? { modeId: change.mode } : change), - _meta: { expectedRevision: revision }, - } - ) -} diff --git a/monkeyai/web/src/lib/device-connection.ts b/monkeyai/web/src/lib/device-connection.ts deleted file mode 100644 index 8c508eb6b..000000000 --- a/monkeyai/web/src/lib/device-connection.ts +++ /dev/null @@ -1,489 +0,0 @@ -import { validMachineId, type DeviceGrant } from "./workspace-oauth" -import { deviceQuoteLimit } from "./device-message-quotes" -import { - uploadFile, - uploadLimits, - type UploadLimits, - type UploadedFile, -} from "./device-uploads" -import { catalogModel, isRecord, type ChatModel } from "./device-models" - -export class DeviceConnectionError extends Error { - readonly needsAuthorization: boolean - constructor(message: string, needsAuthorization = false) { - super(message) - this.needsAuthorization = needsAuthorization - } -} - -export type ConnectionPhase = "connecting" | "connected" | "failed" -export type ConnectionStatus = { - phase: ConnectionPhase - detail: string - needsAuthorization?: boolean -} - -// 只缓存不具备鉴权能力的连接 ID;刷新时轮换票据,避免反复占用设备连接名额。 -async function connectionTicket( - user: string, - machine: string, - grant: DeviceGrant, - signal: AbortSignal -) { - if (!validMachineId(machine)) throw new Error("设备地址无效。") - if (!grant.canReadSessions || grant.expiresAt <= Date.now()) - throw new DeviceConnectionError("需要重新授权才能连接。", true) - const path = "/api/v1/endpoints/" + machine - const readFolders = grant.canControlSessions && grant.canReadFiles - const key = - "monkeyai.web.connection-id:" + - user + - ":" + - machine + - (grant.canControlSessions ? ":control" : "") + - (readFolders ? ":files" : "") + - (grant.canControlSessions && grant.canUploadFiles ? ":upload" : "") - const scopes = grant.canControlSessions - ? [ - "session:read", - "session:control", - ...(grant.canUploadFiles ? ["files:write"] : []), - ] - : ["session:read"] - if (readFolders) scopes.push("files:read") - const prior = sessionStorage.getItem(key) - const request = (id?: string) => - fetch(path + "/connections", { - method: "POST", - credentials: "omit", - cache: "no-store", - redirect: "error", - signal, - headers: { - Authorization: "Bearer " + grant.token, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - connection_id: id, - scopes, - supported_protocols: { acp: [1], runtime_api: [1] }, - }), - }) - let response = await request( - prior && validMachineId(prior) ? prior : undefined - ) - if ( - prior && - response.status === 401 && - ( - await response - .clone() - .json() - .catch(() => null) - )?.error?.code === "connection_expired" - ) { - sessionStorage.removeItem(key) - response = await request() - } - const body = await response.json().catch(() => null) - if (!response.ok) - throw new DeviceConnectionError( - body?.error?.message || "无法获取设备连接票据。", - response.status === 401 || body?.error?.code === "permission_denied" - ) - if ( - !body || - body.machine_id !== machine || - typeof body.connection_id !== "string" || - !validMachineId(body.connection_id) || - typeof body.ticket !== "string" || - !/^[A-Za-z0-9_-]{1,128}$/.test(body.ticket) || - typeof body.http_base !== "string" || - !Array.isArray(body.scopes) || - !scopes.every((s) => body.scopes.includes(s)) || - !Number.isFinite(body.expires_in) || - body.expires_in <= 0 || - body.protocol?.acp !== 1 || - body.protocol?.runtime_api !== 1 - ) - throw new Error("设备连接票据与请求不匹配。") - const base = new URL(body.http_base) - if ( - !["http:", "https:"].includes(base.protocol) || - base.pathname !== path + "/proxy/" || - base.search || - base.hash || - base.username || - base.password - ) - throw new Error("设备代理地址无效。") - sessionStorage.setItem(key, body.connection_id) - // 始终经过工作台自己的受信代理,不向响应中提供的其他主机发送票据。 - const endpoint = new URL(base.pathname + "acp", location.origin) - endpoint.protocol = location.protocol === "https:" ? "wss:" : "ws:" - return { - endpoint, - ticket: body.ticket as string, - expiresIn: body.expires_in as number, - } -} - -type SessionListener = ( - method: string, - sessionId: string, - params: Record -) => void -export interface DeviceChannel { - models(): Promise - canWrite: boolean - quoteLimit?: number - fileGrant?: boolean - uploads?: UploadLimits - upload?( - sessionId: string, - file: File, - progress: (offset: number) => void - ): Promise - queue(sessionId: string): Promise - canBrowseFolders: boolean - request(method: string, params?: Record): Promise - history(sessionId: string, cursor?: string): Promise - listen(listener: SessionListener): () => void -} - -function supportsFolders(result: Record): boolean { - const record = (v: unknown): v is Record => - !!v && typeof v === "object" - const caps = result.agentCapabilities - return ( - record(caps) && - record(caps._meta) && - record(caps._meta.directories) && - caps._meta.directories.version === 1 - ) -} - -export function connectWorkspaceDevice( - user: string, - machine: string, - grant: DeviceGrant, - update: (status: ConnectionStatus, channel?: DeviceChannel) => void -) { - const controller = new AbortController() - const { signal } = controller - let socket: WebSocket | undefined - let connected = false, - seq = 0, - ticket = "" - let renewal: ReturnType | undefined - const pending = new Map< - number, - { resolve(value: unknown): void; reject(error: Error): void } - >() - const listeners = new Set() - const stop = () => { - controller.abort() - clearTimeout(timer) - clearTimeout(renewal) - listeners.clear() - for (const p of pending.values()) - p.reject(new Error("设备连接已中断,请先核对会话记录。")) - pending.clear() - if (socket && socket.readyState < WebSocket.CLOSING) socket.close() - } - const fail = (detail: string, needsAuthorization = false) => { - if (signal.aborted) return - stop() - update({ phase: "failed", detail, needsAuthorization }) - } - const onError = (error: unknown) => - fail( - error instanceof Error ? error.message : "设备连接失败。", - error instanceof DeviceConnectionError && error.needsAuthorization - ) - const timer = setTimeout( - () => fail("设备未在规定时间内完成握手,请重试。"), - 20000 - ) - const request: DeviceChannel["request"] = (method, params = {}) => - new Promise((resolve, reject) => { - if (signal.aborted || socket?.readyState !== WebSocket.OPEN) - return reject(new Error("未连接设备。")) - const id = ++seq - const timeout = setTimeout(() => { - pending.delete(id) - reject(new Error("设备响应超时,请核对会话记录。")) - }, 120000) - pending.set(id, { - resolve: (value) => { - clearTimeout(timeout) - resolve(value) - }, - reject: (e) => { - clearTimeout(timeout) - reject(e) - }, - }) - try { - socket.send(JSON.stringify({ jsonrpc: "2.0", id, method, params })) - } catch { - pending.get(id)?.reject(new Error("请求未能送达设备。")) - pending.delete(id) - } - }) - async function readSession(method: string, params: Record) { - const response = await fetch( - "/api/v1/endpoints/" + machine + "/proxy/read/session", - { - method: "POST", - credentials: "omit", - cache: "no-store", - redirect: "error", - signal, - headers: { - Authorization: "Bearer " + ticket, - "Content-Type": "application/json", - }, - body: JSON.stringify({ method, params }), - } - ) - const body = await response.json().catch(() => null) - if (response.status === 403) - throw new Error( - "会话读取未获许可。请检查设备授权,以及服务端是否允许当前工作台来源。" - ) - if (!response.ok || body?.error) - throw new Error(body?.error?.message || "无法读取会话消息。") - if (body?.target?.machineId !== machine || body.target.userId !== user) - throw new Error("设备返回的会话与当前目标不符。") - return body.result - } - const channel: DeviceChannel = { - async models() { - const models: ChatModel[] = [] - for (let page = 1, seen = 0; ; page++) { - const res = await fetch( - "/api/v1/models?page=" + page + "&page_size=100", - { - headers: { Authorization: "Bearer " + grant.token }, - signal, - credentials: "omit", - redirect: "error", - cache: "no-store", - } - ) - if (!res.ok) - throw new Error("无法读取账号模型目录(" + res.status + ")。") - const data: unknown = await res.json() - if ( - !isRecord(data) || - !Array.isArray(data.models) || - typeof data.total_count !== "number" - ) - throw new Error("模型目录响应无效。") - // 和客户端一致:上游型号没有匹配项时,按网关主机查找思考档位。 - let gatewayHost: string | undefined - if ( - isRecord(data.model_gateway) && - typeof data.model_gateway.base_url === "string" - ) { - try { - gatewayHost = new URL( - data.model_gateway.base_url - ).hostname.toLowerCase() - } catch { - /* 缺少有效地址时只按型号匹配。 */ - } - } - models.push( - ...data.models.flatMap((m) => catalogModel(m, user, gatewayHost)) - ) - seen += data.models.length - if (seen >= data.total_count) return models - if (!data.models.length) throw new Error("模型目录分页不完整。") - } - }, - canWrite: grant.canControlSessions === true, - canBrowseFolders: false, - fileGrant: grant.canUploadFiles === true, - async upload(sessionId, file, progress) { - if ( - !channel.canWrite || - !channel.fileGrant || - !channel.uploads || - signal.aborted - ) - throw new Error("设备未授权或不支持上传附件。") - return uploadFile( - { - user, - machine, - limits: channel.uploads, - rpc: request, - chunk: async (id, s, offset, body) => { - const controller = new AbortController() - const abort = () => controller.abort() - if (signal.aborted) abort() - else signal.addEventListener("abort", abort) - const timer = setTimeout(abort, 35000) - try { - return await fetch( - "/api/v1/endpoints/" + machine + "/proxy/uploads/" + id, - { - method: "PUT", - body, - redirect: "error", - credentials: "omit", - cache: "no-store", - signal: controller.signal, - headers: { - Authorization: "Bearer " + ticket, - "Content-Type": "application/octet-stream", - "Upload-Session-ID": s, - "Upload-Offset": String(offset), - }, - } - ) - } finally { - clearTimeout(timer) - signal.removeEventListener("abort", abort) - } - }, - }, - sessionId, - file, - progress - ) - }, - request, - listen(fn) { - listeners.add(fn) - return () => { - listeners.delete(fn) - } - }, - queue(sessionId) { - return readSession("_monkeyai/session/queue", { - sessionId, - action: "get", - }) - }, - async history(sessionId, cursor) { - const page = await readSession("_monkeyai/session/messages", { - sessionId, - limit: 30, - ...(cursor ? { cursor, direction: "older" } : {}), - }) - if (page?.session?.id !== sessionId) - throw new Error("设备返回的会话与当前目标不符。") - return page - }, - } - async function issue() { - const result = await connectionTicket(user, machine, grant, signal) - if (!signal.aborted) { - ticket = result.ticket - renewal = setTimeout( - () => { - void issue().catch(onError) - }, - Math.max( - 1000, - Math.min(result.expiresIn * 800, grant.expiresAt - Date.now()) - ) - ) - } - return result.endpoint - } - void Promise.resolve() - .then(async () => { - if (signal.aborted) return - const endpoint = await issue() - if (signal.aborted) return - const ws = new WebSocket(endpoint.href, [ - "monkeyai.v1", - "monkeyai.token." + ticket, - ]) - socket = ws - ws.onmessage = ({ data }) => { - if (signal.aborted) return - let msg - try { - msg = JSON.parse(data) - } catch { - return fail("设备返回了无效的数据。") - } - if (msg?.jsonrpc !== "2.0") return - if (typeof msg.method === "string") { - // 本页不处理工具审批或宿主能力请求,绝不默认放行。 - if (msg.id != null) - ws.send( - JSON.stringify({ - jsonrpc: "2.0", - id: msg.id, - error: { code: -32601, message: "Method not supported" }, - }) - ) - else if (typeof msg.params?.sessionId === "string") - for (const fn of listeners) - fn(msg.method, msg.params.sessionId, msg.params) - return - } - const p = pending.get(msg.id) - if (!p) return - pending.delete(msg.id) - if (msg.error) - p.reject( - Object.assign( - new Error( - msg.error.data?.reason || msg.error.message || "设备请求失败。" - ), - { code: msg.error.code } - ) - ) - else p.resolve(msg.result) - } - ws.onopen = () => { - if (ws.protocol !== "monkeyai.v1") - return fail("设备未协商受支持的连接协议。") - void request("initialize", { - protocolVersion: 1, - clientCapabilities: { - _meta: { - historyHTTP: true, - messageSnapshots: true, - historyRefresh: true, - }, - }, - clientInfo: { name: "monkeyai-web", version: "0.0.1" }, - }) - .then((result) => { - if (signal.aborted) return - if ( - !result || - typeof result !== "object" || - !("protocolVersion" in result) || - result.protocolVersion !== 1 - ) - return fail("设备协议版本不兼容。") - channel.canBrowseFolders = - channel.canWrite && - grant.canReadFiles === true && - supportsFolders(result) - channel.quoteLimit = deviceQuoteLimit(result) - channel.uploads = uploadLimits(result) - connected = true - clearTimeout(timer) - update({ phase: "connected", detail: "已连接" }, channel) - }) - .catch(onError) - } - ws.onerror = () => fail("无法打开设备通道,请检查设备状态和访问权限。") - ws.onclose = () => - fail( - connected ? "与设备的连接已断开。" : "设备在握手完成前关闭了连接。" - ) - }) - .catch(onError) - return stop -} diff --git a/monkeyai/web/src/lib/device-engine-models.json b/monkeyai/web/src/lib/device-engine-models.json deleted file mode 100644 index db34bee94..000000000 --- a/monkeyai/web/src/lib/device-engine-models.json +++ /dev/null @@ -1,1362 +0,0 @@ -{ - "revision": "99af3d57a066e9a20d946c4c4b290ad04adf5c63", - "models": { - "profile:kimi-k3": { - "thinking_control": "effort", - "thinking_efforts": [ - "low", - "high", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": { - "thinking_control": "binary" - }, - "openai-responses": {} - } - }, - "profile:kimi-k2.6": { - "thinking_control": "binary", - "protocols": { - "openai-chat": {}, - "anthropic": { - "thinking_efforts": [] - } - } - }, - "profile:minimax-m3": { - "supports_images": true, - "thinking_control": "binary", - "protocols": { - "openai-chat": {}, - "anthropic": {}, - "openai-responses": {} - } - }, - "profile:minimax-m3.1": { - "supports_images": true, - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {}, - "openai-responses": {} - } - }, - "profile:alibaba": { - "thinking_control": "binary", - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {}, - "openai-responses": {} - } - }, - "gpt-4o": { - "context_window": 128000, - "max_output": 16384, - "supports_images": true, - "protocols": { - "anthropic": {} - } - }, - "gpt-4o-mini": { - "context_window": 128000, - "max_output": 16384, - "supports_images": true, - "protocols": { - "anthropic": {} - } - }, - "gpt-4.1": { - "context_window": 1047576, - "max_output": 32768, - "supports_images": true, - "protocols": { - "anthropic": {} - } - }, - "gpt-4.1-mini": { - "context_window": 1047576, - "max_output": 32768, - "supports_images": true, - "protocols": { - "anthropic": {} - } - }, - "gpt-4.1-nano": { - "context_window": 1047576, - "max_output": 32768, - "supports_images": true, - "protocols": { - "anthropic": {} - } - }, - "gpt-6.2-astra": { - "context_window": 1050000, - "max_output": 128000, - "supports_images": true, - "protocols": { - "openai-chat": { - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ] - }, - "openai-responses": { - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ] - } - } - }, - "gpt-6.2-sol": { - "context_window": 1050000, - "max_output": 128000, - "supports_images": true, - "protocols": { - "openai-chat": { - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ] - }, - "openai-responses": { - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ] - } - } - }, - "model:*gpt-6-astra*": { - "context_window": 1050000, - "max_output": 128000, - "supports_images": true, - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {} - } - }, - "model:*gpt-6.1-sol*": { - "context_window": 1050000, - "max_output": 128000, - "supports_images": true, - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*gpt-6.1-terra*": { - "context_window": 1050000, - "max_output": 128000, - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "anthropic": {} - } - }, - "model:*gpt-6-luna*": { - "context_window": 1050000, - "max_output": 128000, - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "anthropic": {} - } - }, - "o3": { - "context_window": 200000, - "max_output": 100000, - "supports_images": true, - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "o3-mini": { - "context_window": 200000, - "max_output": 100000, - "supports_images": false, - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "o4-mini": { - "context_window": 200000, - "max_output": 100000, - "supports_images": true, - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "claude-sonnet-4-20250514": { - "context_window": 200000, - "max_output": 16384, - "supports_images": true - }, - "claude-opus-4-20250514": { - "context_window": 200000, - "max_output": 16384, - "supports_images": true - }, - "claude-haiku-3-5-20241022": { - "context_window": 200000, - "max_output": 8192, - "supports_images": true - }, - "model:*claude-opus-5-5*": { - "context_window": 1000000, - "max_output": 128000, - "supports_images": true, - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {} - } - }, - "model:*claude-fable-5-2*": { - "context_window": 1000000, - "max_output": 128000, - "supports_images": true, - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {} - } - }, - "model:*claude-fable-5-1*": { - "context_window": 1000000, - "max_output": 128000, - "supports_images": true, - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {} - } - }, - "model:*claude-mythos-5-2*": { - "context_window": 1000000, - "max_output": 128000, - "supports_images": true, - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {} - } - }, - "model:*claude-mythos-5-1*": { - "context_window": 1000000, - "max_output": 128000, - "supports_images": true, - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {} - } - }, - "model:*claude-sonnet-5-5*": { - "context_window": 1000000, - "max_output": 128000, - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {} - } - }, - "model:*claude-haiku-5-5*": { - "context_window": 1000000, - "max_output": 128000, - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {} - } - }, - "host:token-plan.maas.qianwenaiapi.com": { - "protocols": { - "openai-chat": {}, - "openai-responses": {}, - "anthropic": {} - } - }, - "host:dashscope.aliyuncs.com": { - "protocols": { - "openai-chat": { - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ] - }, - "openai-responses": { - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ] - }, - "anthropic": { - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ] - } - } - }, - "host:dashscope-intl.aliyuncs.com": { - "protocols": { - "openai-chat": { - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ] - }, - "openai-responses": { - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ] - }, - "anthropic": { - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ] - } - } - }, - "host:*.cn-beijing.maas.aliyuncs.com": { - "protocols": { - "openai-chat": { - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ] - }, - "openai-responses": { - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ] - }, - "anthropic": { - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ] - } - } - }, - "host:*.ap-southeast-1.maas.aliyuncs.com": { - "protocols": { - "openai-chat": { - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ] - }, - "openai-responses": { - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ] - }, - "anthropic": { - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ] - } - } - }, - "host:ai-api-gateway.app.baizhi.cloud": { - "protocols": { - "openai-responses": {} - } - }, - "host:api.openai.com": { - "protocols": { - "openai-responses": {} - } - }, - "host:api.anthropic.com": { - "protocols": { - "anthropic": {} - } - }, - "host:api.x.ai": { - "protocols": { - "openai-responses": {} - } - }, - "host:us.api.x.ai": { - "protocols": { - "openai-responses": {} - } - }, - "host:open.bigmodel.cn": { - "protocols": { - "openai-chat": {}, - "openai-responses": { - "thinking_efforts": [ - "low", - "high", - "max" - ] - } - } - }, - "deepseek-v4-flash": { - "context_window": 1048576, - "max_output": 393216, - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "deepseek-chat": { - "context_window": 65536, - "max_output": 8192, - "supports_images": false, - "thinking_control": "binary", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "deepseek-coder": { - "context_window": 65536, - "max_output": 8192, - "supports_images": false, - "thinking_control": "binary", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "deepseek-reasoner": { - "context_window": 65536, - "max_output": 8192, - "supports_images": false, - "thinking_control": "binary", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*deepseek-v4.1-flash*": { - "context_window": 1048576, - "max_output": 393216, - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*deepseek-v4-flash-vision-exp*": { - "context_window": 1048576, - "max_output": 393216, - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*deepseek-v4-flash*": { - "context_window": 1048576, - "max_output": 393216, - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*deepseek-flash*": { - "context_window": 1048576, - "max_output": 393216, - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*deepseek*": { - "thinking_control": "binary", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "host:api.deepseek.com": { - "thinking_control": "binary", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "profile:deepseek": { - "protocols": { - "openai-chat": { - "thinking_control": "binary", - "thinking_efforts": [ - "low", - "high", - "max" - ] - }, - "openai-responses": { - "thinking_control": "binary", - "thinking_efforts": [ - "low", - "high", - "max" - ] - }, - "anthropic": { - "thinking_control": "binary", - "thinking_efforts": [ - "low", - "high", - "max" - ] - } - } - }, - "model:*kimi-k3*": { - "context_window": 1048576, - "max_output": 131072, - "supports_images": true, - "thinking_control": "effort", - "thinking_efforts": [ - "low", - "high", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*kimi-k2.7-code*": { - "context_window": 262144, - "supports_images": true, - "thinking_control": "always", - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*kimi-k2.6*": { - "context_window": 262144, - "supports_images": true, - "thinking_control": "binary", - "protocols": { - "anthropic": { - "thinking_control": "effort", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ] - }, - "openai-responses": {} - } - }, - "model:*kimi-k2.5*": { - "thinking_control": "binary", - "protocols": { - "anthropic": {} - } - }, - "model:*mimo-v2.6*": { - "context_window": 1048576, - "max_output": 131072, - "supports_images": true, - "thinking_control": "binary", - "protocols": { - "openai-chat": {}, - "openai-responses": {}, - "anthropic": {} - } - }, - "model:*agnes-3.0-flash*": { - "context_window": 512000, - "max_output": 65536, - "supports_images": true, - "thinking_control": "binary", - "protocols": { - "openai-chat": {}, - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*grok-*": { - "protocols": { - "anthropic": {}, - "openai-chat": {}, - "openai-responses": {} - } - }, - "model:*mimo-v2.5-pro*": { - "context_window": 1048576, - "max_output": 131072, - "supports_images": false, - "thinking_control": "binary", - "protocols": { - "anthropic": {} - } - }, - "model:*mimo-v2.5*": { - "context_window": 1048576, - "max_output": 131072, - "supports_images": true, - "thinking_control": "binary", - "protocols": { - "anthropic": {} - } - }, - "host:api.minimaxi.com": { - "protocols": { - "openai-chat": {}, - "openai-responses": {}, - "anthropic": {} - } - }, - "host:api.minimax.io": { - "protocols": { - "openai-chat": {}, - "openai-responses": {}, - "anthropic": {} - } - }, - "model:*minimax-m3.1-flash*": { - "context_window": 1000000, - "max_output": 524288, - "supports_images": true, - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "openai-responses": {}, - "anthropic": {}, - "openai-chat": {} - } - }, - "model:*minimax-m3*": { - "context_window": 1000000, - "supports_images": true, - "thinking_control": "binary", - "protocols": { - "openai-responses": {}, - "anthropic": {}, - "openai-chat": {} - } - }, - "model:*minimax-m2.7*": { - "thinking_control": "always", - "protocols": { - "anthropic": {}, - "openai-chat": {} - } - }, - "model:*minimax-m2.5*": { - "thinking_control": "always", - "protocols": { - "anthropic": {}, - "openai-chat": {} - } - }, - "qwen4-max": { - "context_window": 1000000, - "max_output": 131072, - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "low", - "high", - "xhigh" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*qwen4-max-preview*": { - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*qwen4.0-max-preview*": { - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "low", - "medium", - "xhigh" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*qwen3.8-max*": { - "context_window": 1000000, - "max_output": 131072, - "supports_images": true, - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*qwen3.8-27b*": { - "context_window": 1000000, - "max_output": 131072, - "supports_images": true, - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*qwen3.8-2.4t-a95b*": { - "context_window": 1000000, - "max_output": 131072, - "supports_images": true, - "thinking_control": "always", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*qwen3.8*": { - "context_window": 1000000, - "max_output": 131072, - "supports_images": true, - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*qwen3.7-max*": { - "supports_images": false, - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*qwen3.7*": { - "supports_images": true, - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*qwen3.6*": { - "supports_images": true, - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*qwen3.5*": { - "thinking_control": "binary", - "protocols": { - "anthropic": {} - } - }, - "model:*glm-5.3-flash*": { - "context_window": 1000000, - "max_output": 131072, - "supports_images": true, - "thinking_control": "always", - "thinking_efforts": [ - "low", - "high", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*glm-5.3*": { - "context_window": 1000000, - "max_output": 131072, - "supports_images": false, - "thinking_control": "always", - "thinking_efforts": [ - "low", - "high", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*glm-5.2*": { - "thinking_control": "binary", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high", - "xhigh", - "max" - ], - "protocols": { - "openai-chat": {}, - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*glm-5*": { - "thinking_control": "binary", - "protocols": { - "anthropic": {}, - "openai-responses": {} - } - }, - "model:*hy4*": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "high" - ], - "protocols": { - "openai-chat": {}, - "openai-responses": {}, - "anthropic": {} - } - }, - "hy4-preview": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "thinking_control": "binary", - "thinking_efforts": [ - "high" - ], - "protocols": { - "openai-chat": {}, - "openai-responses": {}, - "anthropic": {} - } - }, - "model:*hy3*": { - "thinking_control": "binary", - "protocols": { - "openai-chat": {}, - "openai-responses": {}, - "anthropic": {} - } - }, - "MiniMax-Text-01": { - "context_window": 1000000, - "max_output": 16384, - "supports_images": false - }, - "MiniMax-M1": { - "context_window": 1000000, - "max_output": 16384, - "supports_images": false, - "protocols": { - "anthropic": {}, - "openai-chat": {} - } - }, - "moonshot-v1-8k": { - "context_window": 8192, - "max_output": 4096, - "supports_images": false - }, - "moonshot-v1-32k": { - "context_window": 32768, - "max_output": 4096, - "supports_images": false - }, - "moonshot-v1-128k": { - "context_window": 131072, - "max_output": 4096, - "supports_images": false - }, - "glm-4-plus": { - "context_window": 128000, - "max_output": 4096, - "supports_images": true - }, - "glm-4-flash": { - "context_window": 128000, - "max_output": 4096, - "supports_images": true - }, - "qwen-max": { - "context_window": 32768, - "max_output": 8192, - "supports_images": false - }, - "qwen-plus": { - "context_window": 131072, - "max_output": 8192, - "supports_images": false - }, - "qwen-turbo": { - "context_window": 131072, - "max_output": 8192, - "supports_images": false - }, - "gemini-4-hydrogen": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "protocols": { - "gemini": { - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high", - "xhigh" - ] - } - } - }, - "gemini-4-carbon": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "protocols": { - "anthropic": {}, - "gemini": { - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high" - ] - } - } - }, - "gemini-4-argon": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "protocols": { - "anthropic": {}, - "gemini": { - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high" - ] - } - } - }, - "gemini-3.8-flash": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "protocols": { - "anthropic": {}, - "gemini": { - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high" - ] - } - } - }, - "gemini-3.6-flash": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "protocols": { - "anthropic": {}, - "gemini": { - "thinking_control": "always", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high" - ] - } - } - }, - "gemini-3.5-flash-lite": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "protocols": { - "anthropic": {}, - "gemini": { - "thinking_control": "always", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high" - ] - } - } - }, - "gemini-3.1-pro-preview": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "protocols": { - "anthropic": {}, - "gemini": { - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high" - ] - } - } - }, - "gemini-3.1-flash-lite": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "protocols": { - "anthropic": {}, - "gemini": { - "thinking_control": "always", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high" - ] - } - } - }, - "gemini-3-flash-preview": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "protocols": { - "anthropic": {}, - "gemini": { - "thinking_control": "always", - "thinking_efforts": [ - "minimal", - "low", - "medium", - "high" - ] - } - } - }, - "gemini-2.5-pro": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "protocols": { - "anthropic": {}, - "gemini": { - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high" - ] - } - } - }, - "gemini-2.5-flash": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "protocols": { - "anthropic": {}, - "gemini": { - "thinking_control": "always", - "thinking_efforts": [ - "low", - "medium", - "high" - ] - } - } - }, - "gemini-2.5-flash-lite": { - "context_window": 1048576, - "max_output": 65536, - "supports_images": true, - "protocols": { - "anthropic": {}, - "gemini": { - "thinking_control": "binary", - "thinking_efforts": [ - "low", - "medium", - "high" - ] - } - } - }, - "yi-large": { - "context_window": 32768, - "max_output": 4096, - "supports_images": false - } - } -} diff --git a/monkeyai/web/src/lib/device-expert-color.ts b/monkeyai/web/src/lib/device-expert-color.ts deleted file mode 100644 index f1eb7e4aa..000000000 --- a/monkeyai/web/src/lib/device-expert-color.ts +++ /dev/null @@ -1,84 +0,0 @@ -// 无状态配色 v2:固定散列与生成参数,新增专家不改变已有专家的计算结果。 -const ID_HASH_OFFSET = 0x811c9dc5 -const ID_HASH_PRIME = 0x01000193 -const ID_MIX_FIRST = 0x85ebca6b -const ID_MIX_SECOND = 0xc2b2ae35 -const SEED_SATURATION_MIN = 0.44 -const SEED_SATURATION_RANGE = 0.24 -const SEED_LIGHTNESS_MIN = 0.4 -const SEED_LIGHTNESS_RANGE = 0.18 - -function expertColor(id: string): string { - let hash = ID_HASH_OFFSET - for (let index = 0; index < id.length; index++) { - hash = Math.imul(hash ^ id.charCodeAt(index), ID_HASH_PRIME) - } - // 打散相似 ID 的后缀,避免相邻编号落到相邻色相。 - hash = Math.imul(hash ^ (hash >>> 16), ID_MIX_FIRST) - hash = Math.imul(hash ^ (hash >>> 13), ID_MIX_SECOND) - hash = (hash ^ (hash >>> 16)) >>> 0 - const hue = ((hash & 0xffff) / 0x10000) * 360 - const saturation = - SEED_SATURATION_MIN + - (((hash >>> 16) & 0xff) / 0xff) * SEED_SATURATION_RANGE - const lightness = - SEED_LIGHTNESS_MIN + ((hash >>> 24) / 0xff) * SEED_LIGHTNESS_RANGE - const amplitude = saturation * Math.min(lightness, 1 - lightness) - // HSL 转为 sRGB 色号,再使用固定的明暗对比度校正。 - const channels = [0, 8, 4].map((phase) => { - const position = (phase + hue / 30) % 12 - const channel = - lightness - - amplitude * Math.max(-1, Math.min(position - 3, 9 - position, 1)) - return Math.round(channel * 255) - .toString(16) - .padStart(2, "0") - }) - return "#" + channels.join("") -} - -// 头像颜色是稳定身份的一部分,固定 v2 校正规则,不跟随主题的文字调色策略。 -function expertTextColor(value: string, dark: boolean): string { - const color = [1, 3, 5].map((start) => - parseInt(value.slice(start, start + 2), 16) - ) - const luminance = (channels: number[]) => { - const linear = channels.map((channel) => { - const normalized = channel / 255 - return normalized <= 0.04045 - ? normalized / 12.92 - : ((normalized + 0.055) / 1.055) ** 2.4 - }) - return linear[0]! * 0.2126 + linear[1]! * 0.7152 + linear[2]! * 0.0722 - } - const background = luminance(dark ? [64, 64, 68] : [232, 234, 238]) - const target = dark ? 255 : 0 - for (let step = 0; step <= 100; step++) { - const amount = step / 100 - const candidate = color.map((channel) => - Math.round(channel + (target - channel) * amount) - ) - const light = luminance(candidate) - if ( - (Math.max(light, background) + 0.05) / - (Math.min(light, background) + 0.05) >= - 4.5 - ) { - return ( - "#" + - candidate - .map((channel) => channel.toString(16).padStart(2, "0")) - .join("") - ) - } - } - return dark ? "#ffffff" : "#000000" -} - -export function expertAvatarColors(id: string) { - const color = expertColor(id) - return { - "--dw-avatar-light": expertTextColor(color, false), - "--dw-avatar-dark": expertTextColor(color, true), - } -} diff --git a/monkeyai/web/src/lib/device-message-quotes.ts b/monkeyai/web/src/lib/device-message-quotes.ts deleted file mode 100644 index 67ed2130c..000000000 --- a/monkeyai/web/src/lib/device-message-quotes.ts +++ /dev/null @@ -1,115 +0,0 @@ -export type MessageQuote = { - sessionId: string - messageId: string - role: "user" | "assistant" - at: number - text: string -} -const record = (v: unknown): v is Record => - !!v && typeof v === "object" && !Array.isArray(v) -const validId = (v: unknown): v is string => - typeof v === "string" && - v.length > 0 && - Array.from(v).length <= 256 && - !/\p{Cc}/u.test(v) - -export function deviceQuoteLimit(handshake: unknown) { - const caps = record(handshake) && handshake.agentCapabilities - const meta = record(caps) && caps._meta - const support = record(meta) && meta.messageQuotes - return record(support) && support.version === 1 - ? support.multiple === true - ? 16 - : 1 - : 0 -} -export function validQuotes( - value: unknown, - session: string -): value is MessageQuote[] { - let total = 0 - return ( - Array.isArray(value) && - value.length <= 16 && - value.every((q) => { - if ( - !record(q) || - !validId(q.sessionId) || - q.sessionId !== session || - !validId(q.messageId) || - (q.role !== "assistant" && q.role !== "user") || - typeof q.at !== "number" || - !Number.isSafeInteger(q.at) || - q.at < 0 || - typeof q.text !== "string" || - !q.text.trim() || - Object.keys(q).some( - (k) => !["sessionId", "messageId", "role", "at", "text"].includes(k) - ) - ) - return false - total += Array.from(q.text).length - return total <= 64000 - }) - ) -} -export function appendQuote( - prior: MessageQuote[], - quote: MessageQuote, - session: string, - limit: number -) { - if ( - prior.some( - (q) => q.sessionId === quote.sessionId && q.messageId === quote.messageId - ) - ) - return prior - const next = [...prior, quote] - if (next.length > limit) - throw new Error( - limit === 1 - ? "当前设备一次只支持一条引用,请先移除已有引用。" - : "最多可引用 16 条消息。" - ) - if (!validQuotes(next, session)) - throw new Error("引用无效或超过 64000 字,请减少引用内容。") - return next -} -export function sourceText( - role: "user" | "assistant", - parts: Record[] -) { - return parts - .flatMap((p) => { - if (p.type !== "text" || typeof p.text !== "string") return [] - if (role !== "user") return [p.text] - if (/^(已选择设计风格|Selected design style)/.test(p.text.trimStart())) - return [] - return [ - p.text.split( - /\n\n(?:本次设计偏好:|设计偏好:|Design preferences: )/, - 1 - )[0], - ] - }) - .join("\n\n") -} -export function quoteFromMessage( - sessionId: string, - m: Record, - parts: Record[] -): MessageQuote | undefined { - if ( - typeof m.id !== "string" || - typeof m.at !== "number" || - !Number.isSafeInteger(m.at) || - m.at < 0 || - (m.role !== "user" && m.role !== "assistant") - ) - return - const text = sourceText(m.role, parts).trim() - return text - ? { sessionId, messageId: m.id, role: m.role, at: m.at, text } - : undefined -} diff --git a/monkeyai/web/src/lib/device-model-brand/model-brand-icons.ts b/monkeyai/web/src/lib/device-model-brand/model-brand-icons.ts deleted file mode 100644 index a855358bc..000000000 --- a/monkeyai/web/src/lib/device-model-brand/model-brand-icons.ts +++ /dev/null @@ -1,25 +0,0 @@ -// 由 scripts/model-brand-icons.mjs 生成,不要手改。 -// 图标来自 @lobehub/icons-static-svg@1.95.1(MIT)。增删品牌改脚本里的 ICONS 再重新生成。 - -export const MODEL_BRAND_ICONS: Record = { - baichuan: "Baichuan", - claude: "Claude", - cohere: "Cohere", - deepseek: "DeepSeek", - doubao: "Doubao", - gemini: "Gemini", - grok: "Grok", - hunyuan: "Hunyuan", - internlm: "InternLM", - kimi: "Kimi", - meta: "Meta", - minimax: "Minimax", - mistral: "Mistral", - openai: "OpenAI", - qwen: "Qwen", - spark: "Spark", - stepfun: "Stepfun", - wenxin: "Wenxin", - yi: "Yi", - zhipu: "Zhipu", -} diff --git a/monkeyai/web/src/lib/device-model-brand/model-brand.ts b/monkeyai/web/src/lib/device-model-brand/model-brand.ts deleted file mode 100644 index 7f69f7da1..000000000 --- a/monkeyai/web/src/lib/device-model-brand/model-brand.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * [INPUT]: 依赖生成的品牌图标和模型名称。 - * [OUTPUT]: 提供模型品牌匹配与隔离的图标 data URL。 - * [POS]: 模型展示的纯映射,图标资源由生成脚本维护。 - * [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md - */ -import { MODEL_BRAND_ICONS } from './model-brand-icons.ts' - -// 模型的品牌图标。图标来自 @lobehub/icons-static-svg,由 scripts/model-brand-icons.mjs -// 抽成内联字符串(见该脚本开头对选型的说明)。这里只做「型号名 → 品牌」的匹配。 - -/** 型号名里的品牌线索。数组有序,先写更具体的规则。 */ -const BRANDS: { pattern: RegExp; icon: string; name: string }[] = [ - { pattern: /deepseek/i, icon: 'deepseek', name: 'DeepSeek' }, - { pattern: /claude|anthropic/i, icon: 'claude', name: 'Claude' }, - { pattern: /gpt|openai|chatgpt|davinci|babbage|^o[1-9](?:[-.]|$)/i, icon: 'openai', name: 'OpenAI' }, - { pattern: /grok|\bxai\b/i, icon: 'grok', name: 'Grok' }, - { pattern: /kimi|moonshot/i, icon: 'kimi', name: 'Kimi' }, - { pattern: /qwen|qwq|tongyi/i, icon: 'qwen', name: 'Qwen' }, - { pattern: /minimax|\babab\b/i, icon: 'minimax', name: 'MiniMax' }, - { pattern: /glm|zhipu|chatglm/i, icon: 'zhipu', name: 'GLM' }, - { pattern: /hunyuan|^hy\d/i, icon: 'hunyuan', name: 'Hunyuan' }, - { pattern: /gemini|gemma|palm/i, icon: 'gemini', name: 'Gemini' }, - { pattern: /llama|meta-/i, icon: 'meta', name: 'Llama' }, - { pattern: /mistral|mixtral|codestral/i, icon: 'mistral', name: 'Mistral' }, - { pattern: /doubao|seed-/i, icon: 'doubao', name: 'Doubao' }, - { pattern: /ernie|wenxin/i, icon: 'wenxin', name: 'ERNIE' }, - { pattern: /baichuan/i, icon: 'baichuan', name: 'Baichuan' }, - { pattern: /spark|xinghuo/i, icon: 'spark', name: 'Spark' }, - { pattern: /\bstep-|stepfun/i, icon: 'stepfun', name: 'StepFun' }, - { pattern: /internlm|intern-/i, icon: 'internlm', name: 'InternLM' }, - { pattern: /command-[ar]|cohere/i, icon: 'cohere', name: 'Cohere' }, - { pattern: /(?:^|[^a-z])yi-/i, icon: 'yi', name: 'Yi' }, -] - -export interface ModelBrand { - /** 可直接放进 img 的 src */ - icon: string - name: string -} - -const urls = new Map() -/** SVG 走 data URL 而不是内联进页面:渐变用的 id 留在图片自己的文档里,不会互相覆盖 */ -function iconUrl(key: string): string | null { - const svg = MODEL_BRAND_ICONS[key] - if (!svg) return null - let url = urls.get(key) - if (!url) { - url = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg) - urls.set(key, url) - } - return url -} - -/** - * 按型号名猜品牌。传上游型号而不是显示名:显示名是用户自己起的。 - * 认不出返回 null,由调用方退回首字母。 - */ -export function modelBrand(model: string): ModelBrand | null { - if (!model) return null - const match = BRANDS.find((brand) => brand.pattern.test(model)) - const icon = match && iconUrl(match.icon) - return match && icon ? { icon, name: match.name } : null -} diff --git a/monkeyai/web/src/lib/device-models.ts b/monkeyai/web/src/lib/device-models.ts deleted file mode 100644 index e7b649e10..000000000 --- a/monkeyai/web/src/lib/device-models.ts +++ /dev/null @@ -1,275 +0,0 @@ -import catalog from "./device-engine-models.json" with { type: "json" } -import type { DeviceChannel } from "./device-connection" - -export type Thinking = { enabled: boolean; effort?: string } -export type Selection = { - model?: string - thinking?: Thinking - mediaModels?: { image?: string; video?: string } -} -export type ModelState = Selection & { - revision: number - context?: { used: number; size: number } -} -export type ChatModel = { - kind: "text" | "image" | "video" - upstream: string - owner: string - rate?: number - window: number - ready: boolean - id: string - name: string - group: string - levels: string[] -} -export type NewModelDraft = Pick & { - depths?: Record -} - -export function thinkingLevel(thinking: Thinking) { - return thinking.enabled ? (thinking.effort ?? "on") : "off" -} - -export function thinkingFromLevel(level: string): Thinking { - if (level === "off") return { enabled: false } - if (level === "on") return { enabled: true } - return { enabled: true, effort: level } -} - -export function newModelSelection( - models: ChatModel[], - draft: NewModelDraft -): Selection { - const available = models.filter((m) => m.ready && m.kind === "text") - // 远程目录不提供账号或专家的默认模型;未指定时沿用客户端的目录顺序回退。 - const chat = available.find((m) => m.id === draft.model) ?? available[0] - const selection: Selection = {} - if (chat) { - selection.model = chat.id - const preference = - draft.depths && Object.hasOwn(draft.depths, chat.id) - ? draft.depths[chat.id] - : undefined - const preferred = preference && thinkingLevel(preference) - const fallback = preferred === "off" ? "low" : "medium" - const level = - [preferred, fallback].find((l) => l && chat.levels.includes(l)) ?? - chat.levels.find((l) => l !== "off") ?? - chat.levels[0] - if (level) selection.thinking = thinkingFromLevel(level) - } - for (const kind of ["image", "video"] as const) { - const id = draft.mediaModels?.[kind] - if (id && models.some((m) => m.kind === kind && m.ready && m.id === id)) - (selection.mediaModels ??= {})[kind] = id - } - return selection -} - -const protocols: Record = { - anthropic: "anthropic", - openai_responses: "openai-responses", - openai_chat_completions: "openai-chat", -} -type Capability = { - context_window?: number - supports_images?: boolean - max_output?: number - thinking_control?: string - thinking_efforts?: string[] - protocols?: Record -} -const entries: Record = catalog.models -export const isRecord = (v: unknown): v is Record => - !!v && typeof v === "object" && !Array.isArray(v) -export function modelState(s: Record): ModelState { - const revision = s.configurationRevision ?? 0 - if ( - typeof revision !== "number" || - !Number.isSafeInteger(revision) || - revision < 0 - ) - throw new Error("会话配置版本无效。") - const t = s.thinking - return { - revision, - mediaModels: { - image: - typeof s.mediaImageModelId === "string" - ? s.mediaImageModelId - : undefined, - video: - typeof s.mediaVideoModelId === "string" - ? s.mediaVideoModelId - : undefined, - }, - context: - isRecord(s.context) && - typeof s.context.used === "number" && - s.context.used > 0 - ? { used: s.context.used, size: Number(s.context.window) || 0 } - : undefined, - model: typeof s.model === "string" ? s.model : undefined, - thinking: - isRecord(t) && typeof t.enabled === "boolean" - ? { - enabled: t.enabled, - effort: typeof t.effort === "string" ? t.effort : undefined, - } - : undefined, - } -} -export function catalogModel( - item: unknown, - user: string, - gatewayHost?: string -): ChatModel[] { - if ( - !isRecord(item) || - typeof item.id !== "string" || - !["text", "image", "video"].includes(String(item.kind ?? "text")) || - ((item.kind ?? "text") === "text" && - (typeof item.protocol !== "string" || - !Object.hasOwn(protocols, item.protocol) || - Number(item.context_window_tokens) <= 0)) - ) - return [] - const model = String(item.model ?? item.id), - suffix = "@" + item.id, - upstream = model.endsWith(suffix) ? model.slice(0, -suffix.length) : model - let entry = Object.hasOwn(entries, upstream) ? entries[upstream] : undefined - if (!entry) { - const key = Object.keys(entries) - .filter((k) => k.startsWith("model:")) - .sort((a, b) => b.length - a.length) - .find((k) => - new RegExp( - "^" + - k - .slice(6) - .split("*") - .map((s) => - Array.from(s, (c) => - c === "?" - ? "." - : String.fromCharCode(92) + - "u" + - c.charCodeAt(0).toString(16).padStart(4, "0") - ).join("") - ) - .join(".*") + - "$", - "i" - ).test(upstream) - ) - if (key) entry = entries[key] - else if (gatewayHost) entry = entries["host:" + gatewayHost] - } - const cap = { - ...entry, - ...entry?.protocols?.[protocols[String(item.protocol)]], - }, - efforts = cap.thinking_efforts ?? [ - "minimal", - "low", - "medium", - "high", - "xhigh", - ] - const levels = [ - ...(["effort", "always"].includes(cap.thinking_control ?? "") - ? [] - : ["off"]), - ...(efforts.length ? efforts : ["on"]), - ] - return [ - { - id: item.id, - kind: item.kind === "image" || item.kind === "video" ? item.kind : "text", - upstream, - ready: item.ready !== false, - owner: isRecord(item.user) - ? String(item.user.name || item.user.email || "") - : "", - rate: - typeof item.credit_multiplier === "number" - ? item.credit_multiplier - : undefined, - window: Number(item.context_window_tokens) || 0, - name: String(item.display_name || item.id), - group: - item.ownership_type !== "user" - ? "系统模型" - : isRecord(item.user) && item.user.id === user - ? "我的模型" - : "分享给我", - levels, - }, - ] -} -export async function switchSetting( - ch: DeviceChannel, - id: string, - state: ModelState, - change: Selection -) { - if (!ch.canWrite) throw new Error("需要会话控制权限。") - const media = change.mediaModels - const result = await ch.request( - media - ? "_monkeyai/session/media-models/set" - : change.model - ? "_monkeyai/session/model/set" - : "_monkeyai/session/thinking/set", - { - sessionId: id, - ...(media ?? change), - _meta: { - expectedRevision: state.revision, - operationId: crypto.randomUUID(), - }, - } - ) - if ( - !isRecord(result) || - !isRecord(result._meta) || - typeof result._meta.configurationRevision !== "number" || - !Number.isSafeInteger(result._meta.configurationRevision) || - result._meta.configurationRevision < state.revision - ) - throw new Error("设备未确认配置,请重新读取。") - if (media) { - if ( - typeof result.mediaImageModelId !== "string" || - typeof result.mediaVideoModelId !== "string" || - (media.image !== undefined && result.mediaImageModelId !== media.image) || - (media.video !== undefined && result.mediaVideoModelId !== media.video) - ) - throw new Error("设备未确认媒体模型,请重新读取。") - return { - ...state, - revision: result._meta.configurationRevision, - mediaModels: { - image: result.mediaImageModelId, - video: result.mediaVideoModelId, - }, - } - } - if ( - (change.model && result.model !== change.model) || - !("thinking" in result) - ) - throw new Error("设备未确认配置,请重新读取。") - const next = modelState({ - model: result.model ?? state.model, - thinking: result.thinking, - configurationRevision: result._meta.configurationRevision, - }) - return { - ...state, - model: next.model, - thinking: next.thinking, - revision: next.revision, - } -} diff --git a/monkeyai/web/src/lib/device-sidebar-actions.ts b/monkeyai/web/src/lib/device-sidebar-actions.ts deleted file mode 100644 index 351155dd7..000000000 --- a/monkeyai/web/src/lib/device-sidebar-actions.ts +++ /dev/null @@ -1,183 +0,0 @@ -import type { DeviceChannel } from "./device-connection" - -export type SidebarAction = - | { - kind: "renameSession" | "renameProject" | "relocate" - id: string - value: string - } - | { kind: "removeProject"; id: string } - | { - kind: "flag" - ids: string[] - field: "pinned" | "archived" - value: boolean - } - | { kind: "delete"; ids: string[]; operationId: string } - -const object = (v: unknown): v is Record => - !!v && typeof v === "object" && !Array.isArray(v) -export type SidebarActionResult = { - succeeded: string[] - failures: { id: string; reason: string }[] -} -export async function applySidebarAction( - ch: DeviceChannel, - op: SidebarAction -): Promise { - if (!ch.canWrite) throw new Error("当前设备连接为只读。") - const result: SidebarActionResult = { - succeeded: [], - failures: [], - } - switch (op.kind) { - case "renameSession": - await ch.request("_monkeyai/session/rename", { - sessionId: op.id, - title: op.value, - }) - break - case "renameProject": - await ch.request("_monkeyai/projects/update", { - id: op.id, - name: op.value, - }) - break - case "relocate": - await ch.request("_monkeyai/projects/update", { - id: op.id, - cwd: op.value, - }) - break - case "removeProject": - await ch.request("_monkeyai/projects/remove", { id: op.id }) - break - case "flag": { - const replies = await Promise.allSettled( - op.ids.map(async (id) => - ch.request("_monkeyai/session/flags", { - sessionId: id, - [op.field]: op.value, - }) - ) - ) - replies.forEach((reply, i) => { - if (reply.status === "fulfilled") result.succeeded.push(op.ids[i]) - else - result.failures.push({ - id: op.ids[i], - reason: - reply.reason instanceof Error - ? reply.reason.message - : "设备操作失败。", - }) - }) - break - } - case "delete": { - const _meta = { operationId: op.operationId } - if (op.ids.length === 1) { - const response = await ch.request("session/delete", { - sessionId: op.ids[0], - _meta, - }) - if ( - !object(response) || - response.sessionId !== op.ids[0] || - response.deleted !== true - ) - throw new Error("设备未确认删除,请刷新列表核对。") - result.succeeded.push(op.ids[0]) - break - } - const response = await ch.request("_monkeyai/sessions/delete", { - sessionIds: op.ids, - _meta, - }) - if ( - !object(response) || - !Array.isArray(response.deleted) || - !Array.isArray(response.failed) - ) - throw new Error("设备未确认批量删除结果。") - const pending = new Set(op.ids) - for (const id of response.deleted) { - if (typeof id !== "string" || !pending.delete(id)) - throw new Error("删除结果与所选会话不符。") - result.succeeded.push(id) - } - for (const f of response.failed) { - if ( - !object(f) || - typeof f.sessionId !== "string" || - typeof f.reason !== "string" || - !pending.delete(f.sessionId) - ) - throw new Error("删除结果与所选会话不符。") - result.failures.push({ id: f.sessionId, reason: f.reason }) - } - if (pending.size) throw new Error("设备未返回完整的删除结果。") - } - } - if ("id" in op) result.succeeded.push(op.id) - return result -} - -export type FolderPage = { - path: string - parent: string | null - entries: { name: string; path: string }[] - nextOffset: number | null - revision: string -} -export async function readSidebarFolder( - ch: DeviceChannel, - user: string, - machine: string, - path: string, - offset = 0, - revision?: string -): Promise { - if (!ch.canBrowseFolders) throw new Error("当前连接不支持浏览设备目录。") - const v = await ch.request("_monkeyai/directories/list", { - ...(path ? { path } : {}), - ...(offset ? { offset, revision } : {}), - }) - if ( - !object(v) || - !object(v.target) || - v.target.userId !== user || - v.target.machineId !== machine - ) - throw new Error("目录与当前设备不符。") - if ( - typeof v.path !== "string" || - !v.path || - (v.parent !== null && typeof v.parent !== "string") || - typeof v.revision !== "string" || - !v.revision || - (offset && revision !== v.revision) || - !Array.isArray(v.entries) || - (v.nextOffset !== null && - (typeof v.nextOffset !== "number" || - !Number.isSafeInteger(v.nextOffset) || - v.nextOffset <= offset)) - ) - throw new Error("设备目录已变化或返回数据无效,请重新打开。") - return { - path: v.path, - parent: v.parent, - revision: v.revision, - nextOffset: v.nextOffset, - entries: v.entries.map((e) => { - if ( - !object(e) || - typeof e.name !== "string" || - typeof e.path !== "string" || - !e.path - ) - throw new Error("设备目录条目无效。") - return { name: e.name, path: e.path } - }), - } -} diff --git a/monkeyai/web/src/lib/device-sidebar-completions.ts b/monkeyai/web/src/lib/device-sidebar-completions.ts deleted file mode 100644 index f5a908235..000000000 --- a/monkeyai/web/src/lib/device-sidebar-completions.ts +++ /dev/null @@ -1,116 +0,0 @@ -import type { Session } from "./device-workspace" - -type Turn = { - seq: number - version: number - goal: boolean - finished: boolean - at: number - seenAt: number -} -const record = (v: unknown): v is Record => - !!v && typeof v === "object" - -// 列表只说明设备当前是否空闲;只有这次连接收到的真实轮次结束事件才能产生未读提醒。 -export function sidebarCompletions() { - const turns = new Map() - let version = 0 - return { - get version() { - return version - }, - observe(id: string, params: Record) { - const { state, eventSeq: seq } = params - if ( - !record(state) || - typeof seq !== "number" || - !Number.isSafeInteger(seq) - ) - return - const old = turns.get(id) - if (old && seq <= old.seq) return - const turn = old ?? { - seq, - version, - goal: false, - finished: false, - at: NaN, - seenAt: 0, - } - const goal = params.goalSummary ?? state.goal - if (state.status === "running" && (turn.finished || !old)) - turn.goal = false - if (record(goal) && goal.is_current === true && goal.status === "active") - turn.goal = true - if ( - state.status === "running" || - state.status === "error" || - state.status === "interrupted" || - params.finish === true - ) { - turn.finished = - params.finish === true && - state.status === "idle" && - params.queueContinues !== true && - params.scheduleFinished !== true - turn.at = - typeof state.updatedAt === "string" - ? Date.parse(state.updatedAt) - : NaN - turn.seenAt = 0 - if (!turn.finished && state.status !== "running") turn.goal = false - } - turn.seq = seq - turn.version = ++version - turns.set(id, turn) - }, - read(id: string, updatedAt: string) { - const turn = turns.get(id) - const at = Date.parse(updatedAt) - if (!turn?.finished || !Number.isFinite(at)) return false - turn.seenAt = Math.max(turn.seenAt, at) - return turn.seenAt >= turn.at - }, - list(sessions: Session[], started: number) { - const ids = new Set(sessions.map((s) => s.id)), - completed = new Set() - for (const [id, turn] of turns) - if (!ids.has(id) && turn.version <= started) turns.delete(id) - for (const s of sessions) { - const turn = turns.get(s.id) - if (turn && turn.version > started) continue // 不用事件之前在途的列表判断已读或目标状态。 - if (s.goalStatus === "active") { - if (turn) turn.goal = true - else if (s.status === "running") - turns.set(s.id, { - seq: -1, - version: started, - goal: true, - finished: false, - at: NaN, - seenAt: 0, - }) - } - if (!turn?.finished) continue - if (!Number.isFinite(turn.at)) turn.at = Date.parse(s.updatedAt) - if ( - s.status !== "idle" || - Date.parse(s.readAt) >= turn.at || - turn.seenAt >= turn.at || - (turn.goal && - s.goalStatus !== "active" && - s.goalStatus !== "complete") - ) { - turn.finished = false - turn.goal = false - } else if ( - !s.agentsRunning && - !s.pendingInteraction && - s.goalStatus !== "active" - ) - completed.add(s.id) - } - return completed - }, - } -} diff --git a/monkeyai/web/src/lib/device-turn.ts b/monkeyai/web/src/lib/device-turn.ts deleted file mode 100644 index fc2ad895a..000000000 --- a/monkeyai/web/src/lib/device-turn.ts +++ /dev/null @@ -1,88 +0,0 @@ -import type { DeviceChannel } from "./device-connection" - -const validId = (v: unknown): v is string => - typeof v === "string" && - /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(v) -const record = (v: unknown): v is Record => - v !== null && typeof v === "object" && !Array.isArray(v) - -export type Turn = { - modelState?: import("./device-models").ModelState - status: string - executionId?: string - preparationSeq?: number -} -export type Preparation = { - channel: DeviceChannel - session: string - seq: number - id: string -} -export type StopTarget = { field: "executionId" | "preparationId"; id: string } - -export function readTurn(session: Record, seq: unknown): Turn { - const status = typeof session.status === "string" ? session.status : "" - const { goal, executionId } = session - // 缺少目标信息的设备不能证明这是普通轮次;不把暂停持续目标降级为取消会话。 - if ( - goal !== null && - (!record(goal) || - typeof goal.is_current !== "boolean" || - typeof goal.status !== "string" || - (goal.is_current && - goal.status === "active" && - (!executionId || - !validId(goal.current_execution_id) || - goal.current_execution_id === executionId))) - ) - return { status } - if (executionId != null && executionId !== "") - return status === "running" && validId(executionId) - ? { status, executionId } - : { status } - return typeof seq === "number" && Number.isSafeInteger(seq) && seq >= 0 - ? { status, preparationSeq: seq } - : { status } -} - -export function stopTarget( - channel: DeviceChannel | undefined, - session: string, - turn?: Turn, - preparation?: Preparation -): StopTarget | undefined { - if (!channel?.canWrite || !session || !turn) return - if (turn.executionId) return { field: "executionId", id: turn.executionId } - // 不把上一份队列的准备标识拼到另一轮的会话状态上。 - if ( - preparation && - preparation.channel === channel && - preparation.session === session && - turn.preparationSeq === preparation.seq && - validId(preparation.id) - ) - return { field: "preparationId", id: preparation.id } -} - -export async function stopTurn( - channel: DeviceChannel, - sessionId: string, - target: StopTarget -) { - if (!channel.canWrite || !validId(target.id)) - throw new Error("没有可停止的执行目标。") - const reply = await channel.request("session/cancel", { - sessionId, - _meta: { operationId: crypto.randomUUID(), [target.field]: target.id }, - }) - if ( - !record(reply) || - reply.sessionId !== sessionId || - reply[target.field] !== target.id || - typeof reply.matched !== "boolean" || - typeof reply.stopped !== "boolean" || - (!reply.matched && reply.stopped) - ) - throw new Error("设备未返回所选轮次的有效回执。") - return !reply.matched ? "expired" : reply.stopped ? "stopped" : "notStopped" -} diff --git a/monkeyai/web/src/lib/device-uploads.ts b/monkeyai/web/src/lib/device-uploads.ts deleted file mode 100644 index 525d82aca..000000000 --- a/monkeyai/web/src/lib/device-uploads.ts +++ /dev/null @@ -1,113 +0,0 @@ -export type UploadLimits = { maxFileBytes: number; maxChunkBytes: number } -export type UploadedFile = { uploadId: string; name: string } -export type DraftFile = { id: string; name: string; size: number; file?: File } -const obj = (v: unknown): v is Record => - !!v && typeof v === "object" && !Array.isArray(v) -const positive = (v: unknown): v is number => - typeof v === "number" && Number.isSafeInteger(v) && v > 0 -export function uploadLimits(handshake: unknown): UploadLimits | undefined { - const caps = obj(handshake) && handshake.agentCapabilities, - meta = obj(caps) && caps._meta, - u = obj(meta) && meta.uploads - if ( - obj(u) && - u.version === 1 && - positive(u.maxFileBytes) && - positive(u.maxChunkBytes) - ) - return { - maxFileBytes: Math.min(u.maxFileBytes, 64 * 1024 * 1024), - maxChunkBytes: Math.min(u.maxChunkBytes, 1024 * 1024), - } -} -export function validateFile(file: File, limits: UploadLimits) { - if ( - !file.name || - file.name === "." || - file.name === ".." || - [...file.name].length > 255 || - /[/\\\p{Cc}\ud800-\udfff]/u.test(file.name) - ) - throw new Error("附件名无效,请重命名后再添加。") - if (file.size > limits.maxFileBytes) - throw new Error( - "「" + - file.name + - "」超过设备的单文件上限(" + - Math.ceil(limits.maxFileBytes / 1024) + - " KB)。" - ) -} -type Transport = { - user: string - machine: string - limits: UploadLimits - rpc: (method: string, params: Record) => Promise - chunk: ( - id: string, - session: string, - offset: number, - body: Blob - ) => Promise -} -export async function uploadFile( - transport: Transport, - sessionId: string, - file: File, - progress: (offset: number) => void -): Promise { - validateFile(file, transport.limits) - if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(sessionId)) - throw new Error("上传目标会话无效。") - const digest = await crypto.subtle.digest("SHA-256", await file.arrayBuffer()) - const sha256 = Array.from(new Uint8Array(digest), (n) => - n.toString(16).padStart(2, "0") - ).join("") - const uploadId = crypto.randomUUID(), - ident = { sessionId, uploadId }, - request = { ...ident, name: file.name, size: file.size, sha256 } - function checked(v: unknown, completed: boolean) { - if ( - !obj(v) || - !obj(v.target) || - v.target.userId !== transport.user || - v.target.machineId !== transport.machine || - Object.entries(request).some(([k, x]) => v[k] !== x) || - v.purpose != null || - v.state !== (completed ? "completed" : "uploading") || - v.offset !== (completed ? file.size : 0) - ) - throw new Error("设备上传回执与文件或会话不匹配。") - } - try { - checked(await transport.rpc("_monkeyai/uploads/create", request), false) - for (let offset = 0; offset < file.size;) { - const end = Math.min(file.size, offset + transport.limits.maxChunkBytes) - const result = await transport.chunk( - uploadId, - sessionId, - offset, - file.slice(offset, end) - ) - if ( - result.status !== 204 || - result.headers.get("Upload-Offset") !== String(end) || - result.headers.get("Upload-Length") !== String(file.size) - ) - throw new Error("附件分块未获设备确认(HTTP " + result.status + ")。") - progress(end) - offset = end - } - checked( - await transport.rpc("_monkeyai/uploads/complete", { - ...ident, - _meta: { operationId: crypto.randomUUID() }, - }), - true - ) - return { uploadId, name: file.name } - } catch (e) { - void transport.rpc("_monkeyai/uploads/cancel", ident).catch(() => {}) - throw e - } -} diff --git a/monkeyai/web/src/lib/device-user-markdown.ts b/monkeyai/web/src/lib/device-user-markdown.ts deleted file mode 100644 index a863d2e12..000000000 --- a/monkeyai/web/src/lib/device-user-markdown.ts +++ /dev/null @@ -1,193 +0,0 @@ -/** - * [INPUT]: 用户消息原文。 - * [OUTPUT]: 只含标题、加粗、行内代码和围栏代码块的结构;其余记号保持原文。 - * [POS]: 用户气泡的受限 Markdown。不执行 HTML,不排列表、链接、公式和图片。 - * [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md - */ - -// 下划线不当格式:`file_name` 是提示词里的原文。一个或两个星号都加粗,中文斜体几乎看不出来。 -// 列表和链接也不排:`- 条目` 发出去后仍要能看清自己打了什么。行首 `# 标题` 会排成标题。 - -export type UserMarkdownInline = - | { type: "text"; text: string } - | { type: "code"; text: string } - | { type: "strong"; children: UserMarkdownInline[] } - -export type UserMarkdownBlock = - | { type: "text"; lines: UserMarkdownInline[][] } - | { - type: "heading" - level: 1 | 2 | 3 | 4 | 5 | 6 - children: UserMarkdownInline[] - } - | { type: "code"; text: string; language?: string } - -const LANGUAGE = /^[\w.+#-]{1,32}$/ - -/** 把原文拆成文本行和代码块。单个换行留在文本行里,不按标准 Markdown 合并成空格。 */ -export function parseUserMarkdown(source: string): UserMarkdownBlock[] { - const lines = source.replace(/\r\n?/g, "\n").split("\n") - const blocks: UserMarkdownBlock[] = [] - let text: UserMarkdownInline[][] | null = null - const flush = () => { - if (!text) return - blocks.push({ type: "text", lines: text }) - text = null - } - for (let i = 0; i < lines.length; i++) { - const heading = openingHeading(lines[i]!) - if (heading) { - flush() - blocks.push({ - type: "heading", - level: heading.level, - children: parseInlines(heading.content), - }) - continue - } - const open = openingFence(lines[i]!) - if (!open) { - text ??= [] - text.push(parseInlines(lines[i]!)) - continue - } - flush() - const body: string[] = [] - i++ - while (i < lines.length && !closingFence(lines[i]!, open.marker)) - body.push(lines[i++]!) - blocks.push({ - type: "code", - text: body.join("\n"), - ...(open.language ? { language: open.language } : {}), - }) - } - flush() - return blocks -} - -/** 只认行首的 `# 标题`。井号后必须有空格,行中间的 `#` 和代码块里的 `#` 保持原文。 */ -function openingHeading( - line: string -): { level: 1 | 2 | 3 | 4 | 5 | 6; content: string } | null { - const match = /^( {0,3})(#{1,6})[ \t]+(.*)$/.exec(line) - if (!match) return null - const content = match[3]!.replace(/[ \t]+#{1,6}[ \t]*$/, "").trim() - if (!content) return null - return { level: match[2]!.length as 1 | 2 | 3 | 4 | 5 | 6, content } -} - -function openingFence( - line: string -): { marker: string; language?: string } | null { - const match = /^( {0,3})(`{3,}|~{3,})(.*)$/.exec(line) - if (!match || (match[2]![0] === "`" && match[3]!.includes("`"))) return null - const token = match[3]!.trim().split(/[ \t]/)[0] ?? "" - return { - marker: match[2]!, - ...(LANGUAGE.test(token) ? { language: token } : {}), - } -} - -function closingFence(line: string, marker: string): boolean { - const match = /^( {0,3})(`{3,}|~{3,})[ \t]*$/.exec(line) - return Boolean( - match && match[2]![0] === marker[0] && match[2]!.length >= marker.length - ) -} - -function parseInlines(line: string): UserMarkdownInline[] { - return scan(line, 0, line.length, true) -} - -function scan( - line: string, - start: number, - end: number, - allowStrong: boolean -): UserMarkdownInline[] { - const out: UserMarkdownInline[] = [] - const pushText = (value: string) => { - if (!value) return - const last = out.at(-1) - if (last?.type === "text") last.text += value - else out.push({ type: "text", text: value }) - } - let i = start - while (i < end) { - if (line[i] === "\\" && i + 1 < end && "\\*`".includes(line[i + 1]!)) { - pushText(line[i + 1]!) - i += 2 - continue - } - if (line[i] === "`") { - const close = line.indexOf("`", i + 1) - if (close > i + 1 && close < end) { - out.push({ type: "code", text: line.slice(i + 1, close) }) - i = close + 1 - continue - } - } - if (allowStrong && line.startsWith("**", i)) { - const close = findStrongClose(line, i + 2, end) - if (close > i + 2) { - out.push({ type: "strong", children: scan(line, i + 2, close, false) }) - i = close + 2 - continue - } - } - if (allowStrong && line[i] === "*" && line[i + 1] !== "*") { - const close = findEmClose(line, i + 1, end) - if (close > i + 1) { - out.push({ type: "strong", children: scan(line, i + 1, close, false) }) - i = close + 1 - continue - } - } - pushText(line[i]!) - i++ - } - return out -} - -/** 结束符不能落在行内代码里,否则 `**a `b**` c**` 会在代码中间截断。 */ -function findStrongClose(line: string, start: number, end: number): number { - let i = start - while (i < end) { - if (line[i] === "\\" && i + 1 < end) { - i += 2 - continue - } - if (line[i] === "`") { - const close = line.indexOf("`", i + 1) - if (close !== -1 && close < end) { - i = close + 1 - continue - } - } - if (line.startsWith("**", i)) return i - i++ - } - return -1 -} - -/** 单个星号的结束符不能贴着另一个星号,否则会把 `**加粗**` 从中间拆开。 */ -function findEmClose(line: string, start: number, end: number): number { - let i = start - while (i < end) { - if (line[i] === "\\" && i + 1 < end) { - i += 2 - continue - } - if (line[i] === "`") { - const close = line.indexOf("`", i + 1) - if (close !== -1 && close < end) { - i = close + 1 - continue - } - } - if (line[i] === "*" && line[i - 1] !== "*" && line[i + 1] !== "*") return i - i++ - } - return -1 -} diff --git a/monkeyai/web/src/lib/device-workspace.ts b/monkeyai/web/src/lib/device-workspace.ts deleted file mode 100644 index f57370437..000000000 --- a/monkeyai/web/src/lib/device-workspace.ts +++ /dev/null @@ -1,574 +0,0 @@ -import type { DeviceChannel } from "./device-connection" -import type { UploadedFile } from "./device-uploads" -import { - quoteFromMessage, - sourceText, - validQuotes, - type MessageQuote, -} from "./device-message-quotes.ts" -import { - observedConfig, - type ComposerConfig, - type ComposerChoice, -} from "./device-composer-options.ts" -import { modelState, type Selection } from "./device-models.ts" -import { readTurn, type Turn } from "./device-turn.ts" - -export type Project = { - id: string - name: string - cwd: string - missing: boolean -} -export type Session = { - id: string - title: string - projectId: string - cwd: string - updatedAt: string - archivedAt: string - pinned: boolean - isDefaultWorkspace: boolean - status: string - readAt: string - agentsRunning: boolean - goalStatus: string - pendingInteraction: boolean - revision?: number - expertId: string - userTitle: boolean -} -export type ChatPart = - | { - type: - "text" | "thought" | "file" | "error" | "history_notice" | "compaction" - text: string - raw?: string - } - | { - type: "tool_call" - id: string - title: string - name: string - parentId?: string - status: string - input?: unknown - output?: string - truncated: boolean - } -export type Message = { - text: string - id: string - role: "user" | "assistant" - parts: ChatPart[] - quoteSource?: MessageQuote - hasFiles: boolean - recallText?: string - steer: boolean - at?: number - startedAt?: number - endedAt?: number -} -export function finalReplyIndex(message: Message, continued: boolean) { - if (message.endedAt === undefined || continued) return 0 - const parts = message.parts - let last = parts.length - 1 - while (last >= 0 && parts[last].type !== "text") last-- - const process = (p: ChatPart) => - p.type === "tool_call" || p.type === "thought" - return last > 0 && - parts.slice(0, last).some((p) => process(p) || p.type === "text") && - !parts.slice(last + 1).some(process) - ? last - : 0 -} -export type PlanStep = { - content: string - status: "pending" | "in_progress" | "completed" -} -export type SessionSnapshot = { - plan: PlanStep[] - turn: Turn - config: ComposerConfig -} -export type HistoryPage = SessionSnapshot & { - updatedAt: string - messages: Message[] - older: string | null - status: string - sessionError: string -} -const actionLabels: Record = { - Bash: "执行命令", - PowerShell: "执行命令", - Cmd: "执行命令", - Read: "读取文件", - Write: "写入文件", - Edit: "修改文件", - NotebookEdit: "修改笔记本", - apply_patch: "应用修改", - Glob: "查找文件", - Grep: "搜索内容", - LSP: "查看代码信息", - Agent: "委派任务", - TaskUpdate: "更新任务", - TaskOutput: "查看任务结果", - TaskStop: "停止任务", - WebFetch: "读取网页", - WebSearch: "搜索网页", - browser_research: "搜索网页", - mcp__monkeyai_browser__browser_research: "搜索网页", - mcp__monkey_browser__browser_research: "搜索网页", - browser_builtin_open: "读取网页", - mcp__monkeyai_browser__browser_builtin_open: "读取网页", - mcp__monkey_browser__browser_builtin_open: "读取网页", - Skill: "使用技能", - SkillLoad: "加载技能", - SkillSearch: "搜索技能", - ToolSearch: "搜索工具", - CapabilitySearch: "查找工具和技能", - ToolLoad: "加载工具", - McpListResources: "列出资源", - McpReadResource: "读取资源", - EnterPlanMode: "开始规划", - ExitPlanMode: "完成规划", - AskUserQuestion: "询问用户", - PresentFiles: "交付成果", - SendMessage: "发送协作消息", - SendUserMessage: "发送消息", - Workflow: "执行工作流", - EnterWorktree: "创建独立工作区", - ExitWorktree: "退出独立工作区", - MemoryRead: "读取记忆", - MemoryWrite: "保存记忆", - MemorySearch: "搜索记忆", - MemoryDelete: "删除记忆", - CronCreate: "创建定时任务", - ScheduleWakeup: "创建定时任务", - CronList: "查看定时任务", - CronDelete: "删除定时任务", - ReportFindings: "汇报发现", - StructuredOutput: "整理结果", - ExecuteCode: "运行程序", -} -export function replyActivity(status: string, last?: Message): string { - if (status !== "running") return "" - const parts = - last?.role === "assistant" && last.endedAt === undefined ? last.parts : [] - let tool: ChatPart | undefined - for (let i = parts.length - 1; i >= 0; i--) { - const part = parts[i] - if (part.type === "tool_call" && (part.status === "pending" || part.status === "in_progress")) { - tool = part - break - } - } - if (tool?.type === "tool_call") { - let action = Object.hasOwn(actionLabels, tool.name) - ? actionLabels[tool.name] - : "调用工具" - if ( - record(tool.input) && - tool.input.run_in_background === true && - (action === "执行命令" || action === "委派任务") - ) - action = action === "执行命令" ? "后台运行命令" : "后台委派任务" - return "正在" + action + "…" - } - const tail = parts.at(-1) - if (tail?.type === "thought") return "正在思考…" - if (tail?.type === "text") return "正在回复…" - return "正在调用模型…" -} -const record = (v: unknown): v is Record => - !!v && typeof v === "object" && !Array.isArray(v) -const str = (v: unknown) => (typeof v === "string" ? v : "") -function readPlan(value: unknown): PlanStep[] { - if (!Array.isArray(value)) return [] - const steps: PlanStep[] = [] - for (const entry of value) { - // 不让坏步骤阻断消息读取,也不展示缺行后分母失真的计划。 - if ( - !record(entry) || - typeof entry.content !== "string" || - (entry.status !== "pending" && - entry.status !== "in_progress" && - entry.status !== "completed") - ) - return [] - steps.push({ content: entry.content, status: entry.status }) - } - return steps -} -export async function directory(ch: DeviceChannel) { - const [p, s] = await Promise.all([ - ch.request("_monkeyai/projects/list"), - ch.request("session/list"), - ]) - if (!Array.isArray(p) || !record(s) || !Array.isArray(s.sessions)) - throw new Error("设备返回的项目或会话列表无效。") - const projects: Project[] = p.map((x) => { - if (!record(x) || !str(x.id) || !str(x.cwd)) - throw new Error("设备项目信息不完整。") - return { - id: str(x.id), - name: str(x.name) || str(x.cwd), - cwd: str(x.cwd), - missing: x.missing === true, - } - }) - const sessions: Session[] = s.sessions.flatMap((x) => { - if (!record(x) || !str(x.sessionId)) throw new Error("设备会话信息不完整。") - const meta = record(x._meta) ? x._meta : {} - return meta.parent - ? [] - : [ - { - id: str(x.sessionId), - title: - str(x.title) || - (meta.isDefaultWorkspace !== true && - str(x.cwd).split(/[\/]/).pop()) || - "新建会话", - cwd: str(x.cwd), - updatedAt: str(x.updatedAt), - archivedAt: str(meta.archivedAt), - pinned: meta.pinned === true, - isDefaultWorkspace: meta.isDefaultWorkspace === true, - status: str(meta.status), - readAt: str(meta.readAt), - agentsRunning: meta.agentsRunning === true, - goalStatus: - record(meta.goalSummary) && meta.goalSummary.is_current === true - ? str(meta.goalSummary.status) - : "", - pendingInteraction: !!meta.pendingInteraction, - expertId: str(meta.expertId), - userTitle: meta.titleSource === "user", - projectId: str(meta.projectId), - revision: observedConfig(meta).revision, - }, - ] - }) - return { projects, sessions } -} -export async function readHistory( - ch: DeviceChannel, - id: string, - cursor?: string -): Promise { - const page = await ch.history(id, cursor) - if ( - !record(page) || - !record(page.session) || - page.session.id !== id || - !Array.isArray(page.messages) - ) - throw new Error("设备返回的会话消息无效。") - const tools = record(page.toolCalls) ? page.toolCalls : {} - const messages: Message[] = page.messages.map((m) => { - if ( - !record(m) || - !str(m.id) || - !Array.isArray(m.parts) || - (m.role !== "assistant" && m.role !== "user") - ) - throw new Error("消息格式无效。") - const parts: ChatPart[] = [] - for (const part of m.parts.filter(record)) { - const type = part.type - if (type === "tool_call") { - const id = str(part.toolCallId), - value = tools[id], - tool = record(value) ? value : {} - parts.push({ - type, - id, - title: str(tool.title) || str(tool.name) || "工具调用", - name: str(tool.name), - parentId: str(tool.parentToolCallId) || undefined, - status: tool.isError === true ? "failed" : str(tool.status), - input: tool.input, - output: typeof tool.output === "string" ? tool.output : undefined, - truncated: tool.outputTruncated === true, - }) - } else if (type === "error") - parts.push({ - type, - text: str(part.reason) || "执行出错", - raw: str(part.rawError), - }) - else if (type === "file") - parts.push({ type, text: str(part.name) || "附件" }) - else if (type === "compaction") - parts.push({ type, text: str(part.text) || "上下文压缩记录" }) - else if (type === "history_notice" && m.role === "assistant") continue - else if ( - (type === "text" || type === "thought" || type === "history_notice") && - str(part.text).trim() - ) - parts.push({ type, text: str(part.text) }) - } - const timestamp = (v: unknown) => - typeof v === "number" && Number.isFinite(new Date(v).getTime()) - ? v - : undefined - const source = m.parts.filter(record) - const hasFiles = source.some((p) => p.type === "file") - return { - quoteSource: quoteFromMessage(id, m, source), - text: parts - .flatMap((p) => - p.type === "tool_call" - ? ["工具:" + p.title] - : p.type === "thought" - ? [] - : [p.text] - ) - .join("\n\n"), - hasFiles, - // 目前不能恢复附件,不能把带附件的输入悄悄降级为纯文字。 - recallText: - m.role === "user" && - !hasFiles && - !(record(m.origin) && m.origin.type === "notification") - ? sourceText(m.role, source) - : undefined, - id: str(m.id), - role: m.role, - parts, - steer: record(m.origin) && m.origin.type === "steer", - at: timestamp(m.at), - startedAt: timestamp(m.startedAt), - endedAt: timestamp(m.endedAt), - } - }) - return { - messages, - updatedAt: str(page.session.updatedAt), - older: str(page.olderCursor) || null, - plan: readPlan(page.session.plan), - turn: { - ...readTurn(page.session, page.eventSeq), - modelState: modelState(page.session), - }, - config: observedConfig(page.session), - status: str(page.session.status), - sessionError: - page.session.lastErrorInTranscript === true - ? "" - : str(page.session.lastError), - } -} -// 普通历史页的最新一页没有向后游标。沿这次返回的旧页游标找到交集后再发布整段,失败时保留原视图。 -export async function readJoinedHistory( - ch: DeviceChannel, - id: string, - known: ReadonlySet | undefined, - signal: AbortSignal -) { - const latest = await readHistory(ch, id) - let page = latest - const pages = [latest.messages], - seen = new Set() - while (known && page.older && !page.messages.some((m) => known.has(m.id))) { - if (signal.aborted) throw new DOMException("读取已取消", "AbortError") - if (seen.has(page.older)) - throw new Error("设备重复返回同一个历史游标,未能补齐消息。") - seen.add(page.older) - page = await readHistory(ch, id, page.older) - pages.push(page.messages) - } - const messages = - pages.length === 1 - ? latest.messages - : [ - ...new Map( - pages - .reverse() - .flat() - .map((m) => [m.id, m]) - ).values(), - ] - return { - ...latest, - older: page.older, - messages, - tailIds: new Set(latest.messages.map((m) => m.id)), - } -} -export type HistoryWindow = Pick -export function mergeLatest( - previous: HistoryWindow, - fresh: HistoryWindow -): HistoryWindow { - const first = fresh.messages[0] - const seam = - first && fresh.older - ? previous.messages.findIndex((m) => m.id === first.id) - : -1 - return seam > 0 - ? { - older: previous.older, - messages: [...previous.messages.slice(0, seam), ...fresh.messages], - } - : { older: fresh.older, messages: fresh.messages } -} -export async function createSession( - ch: DeviceChannel, - project?: Project, - choice?: ComposerChoice, - selection?: Selection -) { - if (!ch.canWrite) throw new Error("需要会话控制授权。") - const value = await ch.request("session/new", { - cwd: project?.cwd || "", - mcpServers: [], - _meta: { - operationId: crypto.randomUUID(), - ...(choice - ? { - mode: choice.mode, - ...(choice.expertId ? { profile: choice.expertId } : {}), - } - : {}), - ...selection, - ...(project ? { projectId: project.id } : {}), - }, - }) - if (!record(value) || !str(value.sessionId)) - throw new Error("设备未确认新会话,请核对会话列表。") - return str(value.sessionId) -} -export async function sendMessage( - ch: DeviceChannel, - sessionId: string, - text: string, - quotes: MessageQuote[] = [], - attachments: UploadedFile[] = [], - id: string = crypto.randomUUID() -) { - if (!ch.canWrite) throw new Error("需要会话控制授权。") - if (attachments.length && (!ch.fileGrant || !ch.uploads)) - throw new Error("没有附件上传权限。") - if ( - quotes.length && - (!text.trim() || - !validQuotes(quotes, sessionId) || - quotes.length > (ch.quoteLimit ?? 0)) - ) - throw new Error("当前连接无法发送这些引用,草稿已保留。") - const result = await ch.request("_monkeyai/session/queue", { - sessionId, - id, - text, - action: "add", - ...(attachments.length ? { attachments } : {}), - ...(quotes.length === 1 - ? { quote: quotes[0] } - : quotes.length - ? { quotes } - : {}), - sendIfIdle: true, - _meta: { operationId: id }, - }) - if (!record(result) || result.sessionId !== sessionId) - throw new Error("设备未确认接收,请先核对会话记录。") -} -export type QueueState = - | "pending" - | "accepted" - | "running" - | "completed" - | "failed" - | "outcome_unknown" - | "not_found" -export async function queueReceipt( - ch: DeviceChannel, - sessionId: string, - operationId: string, - user: string, - machine: string -): Promise { - let r: unknown - try { - r = await ch.request("_monkeyai/operations/get", { operationId }) - } catch (e) { - if (record(e) && e.code === -32002) return "not_found" - throw e - } - if ( - !record(r) || - r.version !== 1 || - r.operationId !== operationId || - r.method !== "_monkeyai/session/queue" || - !record(r.target) || - r.target.userId !== user || - r.target.machineId !== machine || - (r.sessionId !== undefined && r.sessionId !== sessionId) || - (r.clientMessageId !== undefined && r.clientMessageId !== operationId) - ) - throw new Error("设备回执与本次提交不匹配。") - if ( - r.state === "completed" && - record(r.result) && - r.sessionId === sessionId && - r.clientMessageId === operationId && - r.result.sessionId === sessionId && - r.result.action === "add" && - r.result.clientMessageId === operationId - ) - return r.state - if ( - r.state === "accepted" || - r.state === "running" || - ((r.state === "failed" || r.state === "outcome_unknown") && - record(r.error) && - typeof r.error.code === "number" && - typeof r.error.message === "string") - ) - return r.state - throw new Error("设备返回了无效的提交状态。") -} -// 一批连续通知只触发一次读取;读取中又有变化时,完成后再取最新快照。 -export function refreshedRead( - read: () => Promise, - apply: (value: T) => void, - error: (e: unknown) => void, - delay = 300 -) { - let active = true, - loading = false, - dirty = false, - timer: ReturnType | undefined - async function run() { - if (!active || loading) return - dirty = false - loading = true - try { - const value = await read() - if (active) apply(value) - } catch (e) { - if (active) error(e) - } finally { - loading = false - if (active && dirty) schedule() - } - } - function schedule() { - dirty = true - if (active && !loading && !timer) - timer = setTimeout(() => { - timer = undefined - void run() - }, delay) - } - return { - run, - schedule, - stop() { - active = false - clearTimeout(timer) - }, - } -} diff --git a/monkeyai/web/src/lib/interface-size.ts b/monkeyai/web/src/lib/interface-size.ts deleted file mode 100644 index 5583b9f24..000000000 --- a/monkeyai/web/src/lib/interface-size.ts +++ /dev/null @@ -1,40 +0,0 @@ -const key = "workspace-interface-size" -export const sizes = [85, 90, 95, 100, 110, 120] as const -export type InterfaceSize = (typeof sizes)[number] - -export function readInterfaceSize(): InterfaceSize { - try { - const stored = Number(localStorage.getItem(key)) - return sizes.find((size) => size === stored) ?? 100 - } catch { - return 100 - } -} - -function apply(size: InterfaceSize) { - const style = document.documentElement.style - style.setProperty("--workspace-scale", String(size / 100)) -} - -export function saveInterfaceSize(size: InterfaceSize) { - apply(size) - try { - localStorage.setItem(key, String(size)) - } catch { - /* 本次使用仍生效。 */ - } -} - -export function observeInterfaceSize(onChange: (size: InterfaceSize) => void) { - const sync = (e: StorageEvent) => { - if (e.storageArea === localStorage && (e.key === key || e.key === null)) - onChange(readInterfaceSize()) - } - window.addEventListener("storage", sync) - return () => window.removeEventListener("storage", sync) -} - -export function initInterfaceSize() { - apply(readInterfaceSize()) - return observeInterfaceSize(apply) -} diff --git a/monkeyai/web/src/lib/themes.ts b/monkeyai/web/src/lib/themes.ts deleted file mode 100644 index 62dd95402..000000000 --- a/monkeyai/web/src/lib/themes.ts +++ /dev/null @@ -1,12 +0,0 @@ -export const themes = ["system", "light", "dark", "century-blue", "textured-gray"] as const -export type Theme = (typeof themes)[number] - -export function isTheme(value: string | null): value is Theme { - return themes.some((theme) => theme === value) -} - -export function resolveTheme(theme: Theme, systemDark: boolean) { - const dark = theme === "dark" || theme === "textured-gray" || (theme === "system" && systemDark) - const named = theme === "century-blue" || theme === "textured-gray" ? theme : null - return { mode: dark ? "dark" : "light", named } as const -} diff --git a/monkeyai/web/src/lib/user-markdown.ts b/monkeyai/web/src/lib/user-markdown.ts deleted file mode 100644 index a863d2e12..000000000 --- a/monkeyai/web/src/lib/user-markdown.ts +++ /dev/null @@ -1,193 +0,0 @@ -/** - * [INPUT]: 用户消息原文。 - * [OUTPUT]: 只含标题、加粗、行内代码和围栏代码块的结构;其余记号保持原文。 - * [POS]: 用户气泡的受限 Markdown。不执行 HTML,不排列表、链接、公式和图片。 - * [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md - */ - -// 下划线不当格式:`file_name` 是提示词里的原文。一个或两个星号都加粗,中文斜体几乎看不出来。 -// 列表和链接也不排:`- 条目` 发出去后仍要能看清自己打了什么。行首 `# 标题` 会排成标题。 - -export type UserMarkdownInline = - | { type: "text"; text: string } - | { type: "code"; text: string } - | { type: "strong"; children: UserMarkdownInline[] } - -export type UserMarkdownBlock = - | { type: "text"; lines: UserMarkdownInline[][] } - | { - type: "heading" - level: 1 | 2 | 3 | 4 | 5 | 6 - children: UserMarkdownInline[] - } - | { type: "code"; text: string; language?: string } - -const LANGUAGE = /^[\w.+#-]{1,32}$/ - -/** 把原文拆成文本行和代码块。单个换行留在文本行里,不按标准 Markdown 合并成空格。 */ -export function parseUserMarkdown(source: string): UserMarkdownBlock[] { - const lines = source.replace(/\r\n?/g, "\n").split("\n") - const blocks: UserMarkdownBlock[] = [] - let text: UserMarkdownInline[][] | null = null - const flush = () => { - if (!text) return - blocks.push({ type: "text", lines: text }) - text = null - } - for (let i = 0; i < lines.length; i++) { - const heading = openingHeading(lines[i]!) - if (heading) { - flush() - blocks.push({ - type: "heading", - level: heading.level, - children: parseInlines(heading.content), - }) - continue - } - const open = openingFence(lines[i]!) - if (!open) { - text ??= [] - text.push(parseInlines(lines[i]!)) - continue - } - flush() - const body: string[] = [] - i++ - while (i < lines.length && !closingFence(lines[i]!, open.marker)) - body.push(lines[i++]!) - blocks.push({ - type: "code", - text: body.join("\n"), - ...(open.language ? { language: open.language } : {}), - }) - } - flush() - return blocks -} - -/** 只认行首的 `# 标题`。井号后必须有空格,行中间的 `#` 和代码块里的 `#` 保持原文。 */ -function openingHeading( - line: string -): { level: 1 | 2 | 3 | 4 | 5 | 6; content: string } | null { - const match = /^( {0,3})(#{1,6})[ \t]+(.*)$/.exec(line) - if (!match) return null - const content = match[3]!.replace(/[ \t]+#{1,6}[ \t]*$/, "").trim() - if (!content) return null - return { level: match[2]!.length as 1 | 2 | 3 | 4 | 5 | 6, content } -} - -function openingFence( - line: string -): { marker: string; language?: string } | null { - const match = /^( {0,3})(`{3,}|~{3,})(.*)$/.exec(line) - if (!match || (match[2]![0] === "`" && match[3]!.includes("`"))) return null - const token = match[3]!.trim().split(/[ \t]/)[0] ?? "" - return { - marker: match[2]!, - ...(LANGUAGE.test(token) ? { language: token } : {}), - } -} - -function closingFence(line: string, marker: string): boolean { - const match = /^( {0,3})(`{3,}|~{3,})[ \t]*$/.exec(line) - return Boolean( - match && match[2]![0] === marker[0] && match[2]!.length >= marker.length - ) -} - -function parseInlines(line: string): UserMarkdownInline[] { - return scan(line, 0, line.length, true) -} - -function scan( - line: string, - start: number, - end: number, - allowStrong: boolean -): UserMarkdownInline[] { - const out: UserMarkdownInline[] = [] - const pushText = (value: string) => { - if (!value) return - const last = out.at(-1) - if (last?.type === "text") last.text += value - else out.push({ type: "text", text: value }) - } - let i = start - while (i < end) { - if (line[i] === "\\" && i + 1 < end && "\\*`".includes(line[i + 1]!)) { - pushText(line[i + 1]!) - i += 2 - continue - } - if (line[i] === "`") { - const close = line.indexOf("`", i + 1) - if (close > i + 1 && close < end) { - out.push({ type: "code", text: line.slice(i + 1, close) }) - i = close + 1 - continue - } - } - if (allowStrong && line.startsWith("**", i)) { - const close = findStrongClose(line, i + 2, end) - if (close > i + 2) { - out.push({ type: "strong", children: scan(line, i + 2, close, false) }) - i = close + 2 - continue - } - } - if (allowStrong && line[i] === "*" && line[i + 1] !== "*") { - const close = findEmClose(line, i + 1, end) - if (close > i + 1) { - out.push({ type: "strong", children: scan(line, i + 1, close, false) }) - i = close + 1 - continue - } - } - pushText(line[i]!) - i++ - } - return out -} - -/** 结束符不能落在行内代码里,否则 `**a `b**` c**` 会在代码中间截断。 */ -function findStrongClose(line: string, start: number, end: number): number { - let i = start - while (i < end) { - if (line[i] === "\\" && i + 1 < end) { - i += 2 - continue - } - if (line[i] === "`") { - const close = line.indexOf("`", i + 1) - if (close !== -1 && close < end) { - i = close + 1 - continue - } - } - if (line.startsWith("**", i)) return i - i++ - } - return -1 -} - -/** 单个星号的结束符不能贴着另一个星号,否则会把 `**加粗**` 从中间拆开。 */ -function findEmClose(line: string, start: number, end: number): number { - let i = start - while (i < end) { - if (line[i] === "\\" && i + 1 < end) { - i += 2 - continue - } - if (line[i] === "`") { - const close = line.indexOf("`", i + 1) - if (close !== -1 && close < end) { - i = close + 1 - continue - } - } - if (line[i] === "*" && line[i - 1] !== "*" && line[i + 1] !== "*") return i - i++ - } - return -1 -} diff --git a/monkeyai/web/src/lib/workspace-balance.ts b/monkeyai/web/src/lib/workspace-balance.ts deleted file mode 100644 index 1e29f4ebc..000000000 --- a/monkeyai/web/src/lib/workspace-balance.ts +++ /dev/null @@ -1,46 +0,0 @@ -const cacheKey = "monkeyai.web.balance" - -export function readBalance(data: unknown, user: string) { - if (!data || typeof data !== "object") return null - const { user_id, balance, quota, period_end_at } = data as Record< - string, - unknown - > - if ( - user_id !== user || - typeof balance !== "string" || - !/^-?[0-9]+(?:[.][0-9]{1,6})?$/.test(balance) || - typeof quota !== "string" || - !/^[0-9]+(?:[.][0-9]{1,6})?$/.test(quota) || - (period_end_at != null && - (typeof period_end_at !== "string" || - !Number.isFinite(Date.parse(period_end_at)))) - ) - return null - return { - user_id: user, - balance, - quota, - period_end_at: period_end_at ?? undefined, - } -} - -type Balance = NonNullable> - -export function lastBalance(user: string) { - try { - const saved = sessionStorage.getItem(cacheKey) - return saved ? readBalance(JSON.parse(saved), user) : null - } catch { - return null - } -} - -export function rememberBalance(balance: Balance | null) { - try { - if (balance) sessionStorage.setItem(cacheKey, JSON.stringify(balance)) - else sessionStorage.removeItem(cacheKey) - } catch { - /* 存储不可用时仍显示本次请求结果。 */ - } -} diff --git a/monkeyai/web/src/lib/workspace-cloud.ts b/monkeyai/web/src/lib/workspace-cloud.ts deleted file mode 100644 index a2f81b132..000000000 --- a/monkeyai/web/src/lib/workspace-cloud.ts +++ /dev/null @@ -1,258 +0,0 @@ -import type { WorkspaceDevice } from "./workspace-devices" - -export type Environment = { - id: string - name: string - phase: string - reason?: string - connectable: boolean - machine_id: string | null - desired: string - generation: number - observed_generation: number - spec?: { runtime_package?: { architecture?: string } } - creationFailed?: boolean - billing_stop_reason?: string -} -export type Specification = { - id: string - version: number - cpu_millis: number - memory_bytes: number -} -type Image = { - id: string - display_name: string - architectures: string[] - is_default: boolean -} -type Host = { - id: string - name: string - architecture: string - available: boolean - billing: { - cpu_credits_per_core_hour: string - memory_credits_per_gib_hour: string - } -} -export type Application = { - name: string - specification_id: string - specification_version: number - image_id: string - host_id?: string - request_key: string -} - -const messages: Record = { - insufficient_credits: - "积分不足,无法预付一小时。请联系管理员补充积分后重试。", - specification_changed: "规格已变更,请重新选择。", - specification_unavailable: "规格已下架,请重新选择。", - image_unavailable: "系统镜像已下架,请刷新配置后重选。", - image_architecture_mismatch: "镜像与宿主机架构不匹配。", - host_access_denied: "当前账号没有该宿主机的使用权限,请联系管理员。", - host_unavailable: "宿主机不可用,请刷新配置。", - capacity_unavailable: "当前没有可用容量,请稍后重试或联系管理员。", - configuration_unavailable: "云电脑配置未就绪,请联系管理员。", -} -export class CloudError extends Error { - status: number - code: string - authorization: boolean - constructor(status: number, code: string) { - const authorization = - status === 401 || (status === 403 && code !== "host_access_denied") - super( - authorization - ? "当前授权缺少云电脑权限或已过期,请重新授权。" - : messages[code] || "无法完成云电脑请求,请重试。" - ) - this.status = status - this.code = code - this.authorization = authorization - } -} -async function request( - token: string, - path: string, - signal?: AbortSignal, - body?: Application -) { - const r = await fetch("/api/v1/" + path, { - signal, - credentials: "omit", - redirect: "error", - cache: "no-store", - headers: { - Authorization: "Bearer " + token, - ...(body ? { "Content-Type": "application/json" } : {}), - }, - ...(body ? { method: "POST", body: JSON.stringify(body) } : {}), - }) - if (!r.ok) { - const e = await r.json().catch(() => null) - throw new CloudError(r.status, e?.error?.code || e?.code || "") - } - return r.json() -} -async function items( - token: string, - path: string, - signal: AbortSignal, - paged = false -) { - const result = new Map() - for (let page = 1; ; page++) { - const data = await request( - token, - path + (paged ? "?page=" + page + "&page_size=100" : ""), - signal - ) - if (!Array.isArray(data.items) || (paged && data.page !== page)) - throw new Error("目录响应无效,请重试。") - for (const row of data.items) { - if (!row?.id) throw new Error("目录记录无效,请重试。") - result.set(row.id, row) - } - if (!paged || data.items.length < 100) return [...result.values()] - } -} -export async function environments( - token: string, - signal: AbortSignal, - failedCreates: Set -) { - const result = await items(token, "environments", signal, true) - return Promise.all( - result.map(async (env) => { - // 初次启动后发生的运行故障也可能处于第一代;只有创建操作失败才移除卡片。 - if ( - env.phase !== "failed" || - env.desired !== "running" || - env.generation !== 1 || - env.observed_generation !== env.generation - ) - return env - if (failedCreates.has(env.id)) return { ...env, creationFailed: true } - const ops = await items<{ - id: string - kind?: string - generation: number - desired: string - status: string - }>( - token, - "environments/" + encodeURIComponent(env.id) + "/operations", - signal, - true - ).catch((error: unknown) => { - if (signal.aborted) throw error - return null - }) - if (!ops) return env - const creationFailed = ops.some( - (op) => - (!op.kind || op.kind === "create") && - op.generation === 1 && - op.desired === "running" && - op.status === "failed" - ) - if (creationFailed) failedCreates.add(env.id) - return { ...env, creationFailed } - }) - ) -} - -export function workspaceDeviceList( - devices: WorkspaceDevice[], - clouds: Environment[] -) { - const byMachine = new Map( - clouds.filter((c) => c.machine_id).map((c) => [c.machine_id, c]) - ) - const registered = new Set(devices.map((d) => d.machine_id)) - function cloudRow(c: Environment, d?: WorkspaceDevice) { - const pending = - c.desired === "running" && - c.generation === 1 && - !c.connectable && - (["pending", "preparing", "starting"].includes(c.phase) || - (c.phase === "running" && (!d || d.status === "online"))) - const status = - c.connectable && c.machine_id - ? "online" - : pending - ? "applying" - : c.phase === "running" - ? d?.status === "offline" - ? "offline" - : "waiting" - : c.phase - return { - key: "cloud:" + c.id, - machine_id: c.machine_id || "", - display_name: d?.display_name || c.name, - platform: d?.platform || "linux", - arch: d?.arch || c.spec?.runtime_package?.architecture || "", - status, - cloud: true, - note: - c.billing_stop_reason === "insufficient_credits" - ? "积分不足以续费,请联系管理员" - : ["stopped", "failed"].includes(c.phase) - ? "如需处理,请联系管理员" - : "", - } - } - const rows = devices.flatMap((d) => { - const c = byMachine.get(d.machine_id) - if (!c) - return [{ ...d, key: "device:" + d.machine_id, cloud: false, note: "" }] - return c.creationFailed ? [] : [cloudRow(c, d)] - }) - for (const c of clouds) - if (!c.creationFailed && (!c.machine_id || !registered.has(c.machine_id))) - rows.push(cloudRow(c)) - const online = rows.filter((d) => d.status === "online").length - const applying = rows.filter((d) => d.status === "applying").length - const summary = [ - "共 " + rows.length + " 台设备", - ...(online || !applying ? [online + " 台在线"] : []), - ...(applying ? [applying + " 台申请中"] : []), - ].join(" · ") - return { rows, summary, applying } -} -export async function cloudCatalog(token: string, signal: AbortSignal) { - const [specs, images, hosts] = await Promise.all([ - items(token, "environment-specifications", signal), - items(token, "system-images", signal), - items(token, "environment-hosts", signal, true), - ]) - return { specs, images: images.filter((i) => i.architectures?.length), hosts } -} -export function estimate(spec: Specification, host: Host) { - const cpu = host.billing?.cpu_credits_per_core_hour, - mem = host.billing?.memory_credits_per_gib_hour - if ( - ![cpu, mem].every( - (v) => typeof v === "string" && /^\d+(\.\d{1,6})?$/.test(v) - ) - ) - return null - const rate = - (Number(cpu) * spec.cpu_millis) / 1000 + - (Number(mem) * spec.memory_bytes) / 1024 ** 3 - return Number.isFinite(rate) ? rate : null -} -export async function createEnvironment(token: string, body: Application) { - const data = await request(token, "environments", undefined, body) - if ( - !data.environment?.id || - !data.operation?.id || - data.operation.environment_id !== data.environment.id - ) - throw new Error("未能确认申请结果。") - return data.environment as Environment -} diff --git a/monkeyai/web/src/lib/workspace-devices.ts b/monkeyai/web/src/lib/workspace-devices.ts deleted file mode 100644 index 00f0077b8..000000000 --- a/monkeyai/web/src/lib/workspace-devices.ts +++ /dev/null @@ -1,76 +0,0 @@ -export type WorkspaceDevice = { - machine_id: string - display_name: string - platform: string - arch: string - status: string -} - -const states: Record = { - applying: "申请中", - online: "在线", - offline: "离线", - auth_required: "需要授权", - connecting: "连接中", - degraded: "运行受限", - starting: "启动中", -} -export const deviceStatus = (status: string) => - states[status] || status || "状态未知" -export const isDeviceOnline = (device: { status: string }) => device.status === "online" - -export class DirectoryError extends Error { - status: number - constructor(status: number, message: string) { - super(message) - this.status = status - } -} - -export async function listWorkspaceDevices(token: string, signal: AbortSignal) { - const devices = new Map() - const size = 100 - for (let page = 1; ; page++) { - const query = new URLSearchParams({ - capability: "execute", - page: String(page), - page_size: String(size), - }) - const response = await fetch("/api/v1/endpoints?" + query, { - headers: { Authorization: "Bearer " + token }, - credentials: "omit", - redirect: "error", - cache: "no-store", - signal, - }) - if (!response.ok) - throw new DirectoryError( - response.status, - response.status === 401 - ? "授权已失效,请重新授权。" - : response.status === 403 - ? "当前授权不允许查看设备。" - : "暂时无法更新设备列表,请稍后重试。" - ) - const body = await response.json() - if ( - !Array.isArray(body.items) || - !Number.isSafeInteger(body.total) || - body.total < 0 || - body.page !== page - ) - throw new Error("设备目录响应无效,请重试。") - for (const device of body.items) { - if ( - !device || - typeof device.machine_id !== "string" || - !device.machine_id || - typeof device.status !== "string" - ) - throw new Error("设备信息格式无效,请重试。") - devices.set(device.machine_id, device) - } - if (body.items.length < size || page * size >= body.total) - return [...devices.values()] - } -} diff --git a/monkeyai/web/src/lib/workspace-oauth.ts b/monkeyai/web/src/lib/workspace-oauth.ts deleted file mode 100644 index d449530d9..000000000 --- a/monkeyai/web/src/lib/workspace-oauth.ts +++ /dev/null @@ -1,230 +0,0 @@ -import { rememberBalance } from "./workspace-balance.ts" - -export const WEB_CLIENT_ID = "monkeyai-web" -export const CALLBACK_PATH = "/client/oauth/callback" -const PENDING_KEY = "monkeyai.web.device-authorization" -const GRANT_KEY = "monkeyai.web.device-grant" -const MAX_AGE = 10 * 60 * 1000 - -export type DeviceGrant = { - token: string - expiresAt: number - canReadSessions?: true - canControlSessions?: true - canReadFiles?: true - canUploadFiles?: true -} -export type DeviceTarget = { - machineId: string - name: string - sessionId?: string - projectId?: string -} -export function validMachineId(id: string) { - return /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(id) -} -type Pending = { - cloud?: boolean - state: string - verifier: string - user: string - created: number - target?: DeviceTarget -} - -export function clearDeviceGrant() { - rememberBalance(null) - try { - sessionStorage.removeItem(GRANT_KEY) - sessionStorage.removeItem("monkeyai.web.sidebar-index.v1") - } catch { - // 禁用浏览器存储时,授权只保留在页面内存中。 - } -} - -export function saveDeviceGrant( - user: string, - { - token, - expiresAt, - canReadSessions, - canControlSessions, - canReadFiles, - canUploadFiles, - }: DeviceGrant -) { - try { - sessionStorage.setItem( - GRANT_KEY, - JSON.stringify({ - user, - token, - expiresAt, - canReadSessions, - canControlSessions, - canReadFiles, - canUploadFiles, - }) - ) - } catch { - clearDeviceGrant() - } -} - -export function restoreDeviceGrant(user: string | null): DeviceGrant | null { - try { - const raw = sessionStorage.getItem(GRANT_KEY) - if (raw === null) return null - const saved = JSON.parse(raw) - if ( - user && - saved?.user === user && - typeof saved.token === "string" && - saved.token && - Number.isFinite(saved.expiresAt) && - saved.expiresAt > Date.now() - ) - return { - token: saved.token, - expiresAt: saved.expiresAt, - ...(saved.canReadSessions === true - ? { canReadSessions: true as const } - : {}), - ...(saved.canReadSessions === true && saved.canControlSessions === true - ? { canControlSessions: true as const } - : {}), - ...(saved.canReadFiles === true ? { canReadFiles: true as const } : {}), - ...(saved.canReadSessions === true && - saved.canControlSessions === true && - saved.canUploadFiles === true - ? { canUploadFiles: true as const } - : {}), - } - } catch { - // 缓存无效时走正常的授权流程。 - } - clearDeviceGrant() - return null -} - -function base64url(bytes: Uint8Array) { - return btoa(String.fromCharCode(...bytes)) - .replace(/=/g, "") - .replace(/\+/g, "-") - .replace(/\//g, "_") -} - -export async function beginDeviceAuthorization( - user: string, - target?: DeviceTarget, - cloud = false -) { - if (target && !validMachineId(target.machineId)) - throw new Error("设备地址无效。") - const state = base64url(crypto.getRandomValues(new Uint8Array(32))) - const verifier = base64url(crypto.getRandomValues(new Uint8Array(32))) - const data = new TextEncoder().encode(verifier) - const digest = crypto.subtle - ? new Uint8Array(await crypto.subtle.digest("SHA-256", data)) - : (await import("@noble/hashes/sha2.js")).sha256(data) - const pending: Pending = { - state, - verifier, - user, - created: Date.now(), - target, - cloud, - } - sessionStorage.setItem(PENDING_KEY, JSON.stringify(pending)) - const query = new URLSearchParams({ - client_id: WEB_CLIENT_ID, - response_type: "code", - redirect_uri: location.origin + CALLBACK_PATH, - scope: - "device:connect session:read session:control environment:read environment:manage files:read files:write", - state, - code_challenge: base64url(digest), - code_challenge_method: "S256", - }) - // 整页跳转,让浏览器打开授权服务器的页面,不在本地读取跨域响应。 - return "/oauth/authorize?" + query -} - -export async function completeDeviceAuthorization( - user: string, - query: URLSearchParams -): Promise { - const raw = sessionStorage.getItem(PENDING_KEY) - sessionStorage.removeItem(PENDING_KEY) - const pending: Pending | null = raw ? JSON.parse(raw) : null - if ( - !pending || - pending.user !== user || - query.getAll("state").length !== 1 || - query.get("state") !== pending.state || - Date.now() - pending.created > MAX_AGE - ) { - throw new Error("授权请求已失效或账号已切换,请重新授权。") - } - if ( - query.has("error") || - query.getAll("code").length !== 1 || - !query.get("code") - ) - throw new Error("未完成设备授权,可重新授权。") - const response = await fetch("/oauth/token", { - method: "POST", - credentials: "omit", - redirect: "error", - cache: "no-store", - referrerPolicy: "no-referrer", - body: new URLSearchParams({ - grant_type: "authorization_code", - client_id: WEB_CLIENT_ID, - redirect_uri: location.origin + CALLBACK_PATH, - code: query.get("code")!, - code_verifier: pending.verifier, - }), - }) - if (!response.ok) throw new Error("授权码未能兑换,请重新授权。") - const token = await response.json() - if ( - typeof token.access_token !== "string" || - !token.access_token || - token.token_type?.toLowerCase() !== "bearer" || - !(Number.isFinite(token.expires_in) && token.expires_in > 0) - ) - throw new Error("授权响应无效,请重新授权。") - // The approval screen allows switching accounts. Never show that account's devices inside the original user's workspace. - const me = await fetch("/api/v1/me", { - headers: { Authorization: "Bearer " + token.access_token }, - credentials: "omit", - redirect: "error", - cache: "no-store", - referrerPolicy: "no-referrer", - }) - if (!me.ok) throw new Error("未能验证设备授权,请重新授权。") - if ((await me.json()).id !== user) - throw new Error("授权账号与工作台账号不同。请点「重新授权」使用下方的工作台账号。不使用下方账号,则请到「设置」中退出登录。") - const scopes = typeof token.scope === "string" ? token.scope.split(" ") : [] - const canRead = - scopes.includes("session:read") && scopes.includes("device:connect") - if (pending.target && (!canRead || !validMachineId(pending.target.machineId))) - throw new Error("未获得连接设备和读取会话的权限。") - return { - token: token.access_token, - expiresAt: Date.now() + token.expires_in * 1000, - ...(canRead ? { canReadSessions: true as const } : {}), - ...(canRead && scopes.includes("session:control") - ? { canControlSessions: true as const } - : {}), - ...(pending.target ? { target: pending.target } : {}), - ...(pending.cloud ? { cloud: true } : {}), - ...(scopes.includes("files:read") ? { canReadFiles: true as const } : {}), - ...(canRead && - scopes.includes("session:control") && - scopes.includes("files:write") - ? { canUploadFiles: true as const } - : {}), - } -} diff --git a/monkeyai/web/src/pages/client-login-page.tsx b/monkeyai/web/src/pages/client-login-page.tsx index c31638c9f..4a4ce618a 100644 --- a/monkeyai/web/src/pages/client-login-page.tsx +++ b/monkeyai/web/src/pages/client-login-page.tsx @@ -34,11 +34,7 @@ import { Marker, MarkerContent } from "@/components/ui/marker" import { useAuth } from "@/hooks/use-auth" import { api } from "@/lib/api" import type { AuthUser } from "@/lib/auth-context" -import { - isLocalRedirect, - isSafeClientLaunchURL, - webDeviceListOnCancel, -} from "@/lib/client-callback" +import { isLocalRedirect, isSafeClientLaunchURL } from "@/lib/client-callback" import { TABLE_DATE_TIME_OPTIONS } from "@/lib/date-time" type Provider = { id: string; provider: string; name: string } @@ -78,9 +74,6 @@ export function ClientLoginPage() { const requestId = search.get("request_id") ?? "" const callbackError = search.get("error") ?? "" const [request, setRequest] = useState(null) - const returnToDevices = - request && - webDeviceListOnCancel(request.client.client_id, request.client.redirect_uri) const [productName, setProductName] = useState("MonkeyAI") const [workspaceName, setWorkspaceName] = useState("Monkey AI") const [hasEmailLogin, setHasEmailLogin] = useState(false) @@ -367,31 +360,6 @@ export function ClientLoginPage() {

授权后将返回本机地址:{request.client.redirect_uri}

)}
- {request.scopes.includes("session:read") && ( -

- 本次授权允许工作台读取设备会话。 -

- )} - {request.scopes.includes("session:control") && ( -

- 本次授权允许工作台在远程设备上创建会话并发送任务。 -

- )} - {request.scopes.includes("files:read") && ( -

- 本次授权允许工作台读取获准的设备文件,用于浏览工作区目录。 -

- )} - {request.scopes.includes("files:write") && ( -

- 本次授权允许工作台向设备上传附件。 -

- )} - {request.scopes.includes("environment:manage") && ( -

- 本次授权允许工作台创建和管理你自己的云电脑。 -

- )} - {returnToDevices && ( - - )} { diff --git a/monkeyai/web/src/pages/client/balance-card.tsx b/monkeyai/web/src/pages/client/balance-card.tsx deleted file mode 100644 index 83eb06274..000000000 --- a/monkeyai/web/src/pages/client/balance-card.tsx +++ /dev/null @@ -1,165 +0,0 @@ -import { Copy01Icon, InformationCircleIcon } from "@hugeicons/core-free-icons" -import { HugeiconsIcon } from "@hugeicons/react" -import { useAppToast } from "@/components/animated-toast-provider" -import { Badge } from "@/components/ui/badge" -import { Button } from "@/components/ui/button" -import { - Popover, - PopoverContent, - PopoverTitle, - PopoverTrigger, -} from "@/components/ui/popover" -import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from "@/components/ui/tooltip" - -// 接口以定点字符串传值;用整数计算,避免大额或微额余额在展示时丢失精度。 -function creditParts(value: string) { - const [whole, fraction = ""] = value.replace(/^-/, "").split(".") - const units = BigInt(whole + fraction.padEnd(6, "0")) - const sign = units !== 0n && value.startsWith("-") ? "−" : "" - const digits = fraction.replace(/0+$/, "") - const exact = - sign + BigInt(whole).toLocaleString("zh-CN") + (digits ? "." + digits : "") - const tiny = units > 0n && units < 10000n - const cents = tiny ? 1n : (units + 5000n) / 10000n - return { - exact, - integer: - (tiny ? (sign ? ">" : "<") : "") + - sign + - (cents / 100n).toLocaleString("zh-CN"), - fraction: "." + (cents % 100n).toString().padStart(2, "0"), - } -} - -function Hint({ label, text }: { label: string; text: string }) { - return ( - - - } - > - - {text} - - ) -} - -export function BalanceCard({ - balance, - quota, - periodEnd, - stale, -}: { - balance?: string - quota?: string - periodEnd?: string - stale: boolean -}) { - const amount = balance === undefined ? null : creditParts(balance) - const { showToast } = useAppToast() - async function copy() { - if (balance === undefined) return - try { - await navigator.clipboard.writeText(balance) - showToast({ status: "success", title: "精确余额已复制" }) - } catch { - showToast({ status: "error", title: "复制失败,请手动选择并复制余额。" }) - } - } - return ( -
-
-
- 当前余额 - -
-
- {amount ? ( - - - {amount.integer} - - {amount.fraction} - - - -
- - 精确余额 - - -
-

- {amount.exact}{" "} - - 积分 - -

-
-
- ) : ( - - — - - )} - 积分 - {stale && 数据暂未更新} -
-
-
-
- 本周期额度 - {periodEnd && ( - - )} -
-
- {quota === undefined ? "—" : creditParts(quota).exact} -
-
-
- ) -} diff --git a/monkeyai/web/src/pages/client/client-page.tsx b/monkeyai/web/src/pages/client/client-page.tsx index e08a3a99e..1a8b67405 100644 --- a/monkeyai/web/src/pages/client/client-page.tsx +++ b/monkeyai/web/src/pages/client/client-page.tsx @@ -1,543 +1,10 @@ -import { useEffect, useRef, useState } from "react" -import { useMatch, useNavigate } from "react-router-dom" -import { DeviceConnectionPage } from "./device-connection-page" -import { WorkspaceSettings } from "./workspace-settings" -import { WorkspaceIdentity } from "./workspace-identity" -import { CloudApplication } from "./cloud-application" -import { - environments, - workspaceDeviceList, - CloudError, - type Environment, -} from "@/lib/workspace-cloud" -import { LaptopIcon } from "@hugeicons/core-free-icons" -import { HugeiconsIcon } from "@hugeicons/react" -import { BrandLogo } from "@/components/brand-logo" -import { Button } from "@/components/ui/button" -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog" -import { Card, CardContent, CardDescription } from "@/components/ui/card" -import { - Item, - ItemContent, - ItemDescription, - ItemGroup, - ItemMedia, - ItemTitle, -} from "@/components/ui/item" -import { useAuth } from "@/hooks/use-auth" -import { useBranding } from "@/hooks/use-branding" -import { - beginDeviceAuthorization, - CALLBACK_PATH, - clearDeviceGrant, - completeDeviceAuthorization, - restoreDeviceGrant, - saveDeviceGrant, - type DeviceGrant, - type DeviceTarget, - validMachineId, -} from "@/lib/workspace-oauth" -import { - DirectoryError, - deviceStatus, - isDeviceOnline, - listWorkspaceDevices, - type WorkspaceDevice, -} from "@/lib/workspace-devices" - -const platforms: Record = { - darwin: "macOS", - macos: "macOS", - windows: "Windows", - win32: "Windows", - linux: "Linux", -} +import { useTranslation } from "react-i18next" export function ClientPage() { - const { user } = useAuth() - const device = useMatch("/client/devices/:machineId") - if (user && device?.params.machineId) - return ( - - ) - return user ? : null -} - -function Workspace({ user }: { user: string }) { - const navigate = useNavigate() - const { branding } = useBranding() - const [grant, setGrant] = useState(() => - location.pathname === CALLBACK_PATH ? null : restoreDeviceGrant(user) - ) - const [busy, setBusy] = useState(() => location.pathname === CALLBACK_PATH) - const [error, setError] = useState(() => - !grant && - location.pathname !== CALLBACK_PATH && - new URLSearchParams(location.search).get("authorization") === "cancelled" - ? "未完成设备授权,可重新授权。" - : "" - ) - const [rows, setRows] = useState(null) - const [updated, setUpdated] = useState(null) - const [revision, setRevision] = useState(0) - const [clouds, setClouds] = useState(null) - const [cloudIssue, setCloudIssue] = useState< - "unsupported" | "auth" | "error" | null - >(null) - const [form, setForm] = useState(false) - const seenKey = "monkeyai.web.cloud-failures:" + user - const [dismissed, setDismissed] = useState>(() => { - try { - return new Set(JSON.parse(sessionStorage.getItem(seenKey) || "[]")) - } catch { - return new Set() - } - }) - const [refreshSeconds, setRefreshSeconds] = useState(30) - const failedCreates = useRef(new Set()) - const list = workspaceDeviceList(rows ?? [], clouds ?? []) - const canApply = - rows !== null && - clouds !== null && - !error && - !cloudIssue && - !list.rows.length - const failures = - clouds?.filter((c) => c.creationFailed && !dismissed.has(c.id)) ?? [] - function dismissFailures() { - const next = new Set([...dismissed, ...failures.map((c) => c.id)]) - setDismissed(next) - try { - sessionStorage.setItem(seenKey, JSON.stringify([...next])) - } catch { - /* 同一页面仍只提示一次。 */ - } - } - const resumeForm = useRef(false) - const exchange = useRef | null>(null) - const initialAuthorization = useRef | null>(null) - - useEffect(() => { - if (!exchange.current && location.pathname === CALLBACK_PATH) { - const query = new URLSearchParams(location.search) - history.replaceState(history.state, "", "/client") - exchange.current = completeDeviceAuthorization(user, query) - } - if (!exchange.current) return - let active = true - exchange.current - .then((value) => { - if (active) { - saveDeviceGrant(user, value) - resumeForm.current = !!value.cloud - setGrant(value) - if (value.target) - navigate( - "/client/devices/" + - value.target.machineId + - (value.target.sessionId - ? "?" + - new URLSearchParams({ session: value.target.sessionId }) - : ""), - { - replace: true, - state: { - name: value.target.name, - projectId: value.target.projectId, - }, - } - ) - } - }) - .catch((reason: unknown) => { - if (active) { - setGrant(restoreDeviceGrant(user)) - setError( - reason instanceof Error - ? reason.message - : "未能完成当前账号的授权,请重新授权。" - ) - } - }) - .finally(() => { - if (active) setBusy(false) - }) - return () => { - active = false - } - }, [user, navigate]) - - useEffect(() => { - if (grant || busy || error || exchange.current) return - let active = true - // React 重跑 effect 时复用同一请求,避免覆盖待回调的 PKCE 状态。 - initialAuthorization.current ??= beginDeviceAuthorization(user) - initialAuthorization.current - .then((url) => { - if (active) location.replace(url) - }) - .catch((reason: unknown) => { - if (active) - setError( - reason instanceof Error ? reason.message : "暂时无法发起授权。" - ) - }) - return () => { - active = false - } - }, [user, grant, busy, error]) - - useEffect(() => { - if (!grant) return - const controller = new AbortController() - let timer: ReturnType - async function poll(current: DeviceGrant) { - setBusy(true) - let delay = 30_000 - try { - if (Date.now() >= current.expiresAt) - throw new DirectoryError(401, "授权已到期,请重新授权。") - const devices = await listWorkspaceDevices( - current.token, - controller.signal - ) - if (controller.signal.aborted) return - try { - const result = await environments( - current.token, - controller.signal, - failedCreates.current - ) - if (controller.signal.aborted) return - setClouds(result) - setCloudIssue(null) - const directory = workspaceDeviceList(devices, result) - if (directory.applying) delay = 3000 - if (directory.rows.length) { - setForm(false) - } else if (resumeForm.current) { - resumeForm.current = false - setForm(true) - } - } catch (e) { - if (controller.signal.aborted) return - setCloudIssue( - e instanceof CloudError && e.status === 404 - ? "unsupported" - : e instanceof CloudError && e.authorization - ? "auth" - : "error" - ) - } - setRows(devices) - setUpdated(new Date()) - setError("") - } catch (e) { - if (controller.signal.aborted) return - setError(e instanceof Error ? e.message : "无法获取设备列表。") - if ( - e instanceof DirectoryError && - (e.status === 401 || e.status === 403) - ) { - setRows(null) - setUpdated(null) - clearDeviceGrant() - setGrant(null) - return - } - } finally { - if (!controller.signal.aborted) { - setBusy(false) - setRefreshSeconds(delay / 1000) - } - } - if (!controller.signal.aborted) - timer = setTimeout(() => void poll(current), delay) - } - void poll(grant) - return () => { - controller.abort() - clearTimeout(timer) - } - }, [grant, revision]) - - async function authorize(target?: DeviceTarget, cloud = false) { - setBusy(true) - setError("") - try { - location.assign(await beginDeviceAuthorization(user, target, cloud)) - } catch (e) { - setBusy(false) - setError(e instanceof Error ? e.message : "暂时无法发起授权。") - } - } - if (!grant && !error) - return ( -
- 正在处理设备授权… -
- ) + const { t } = useTranslation() return ( -
- - -
- -

我的设备

- - {grant && rows != null - ? list.summary - : "查看当前账号已登记的执行设备。"} - -
- {grant && error && ( -

- {error} -

- )} - {!grant ? ( - - - - 设备授权未完成 - - {error} - - - - - ) : ( - <> - {rows === null && !error && ( -

- 正在获取设备列表… -

- )} - {error && !list.rows.length &&

未能确认设备列表,请重试。

} - {cloudIssue === "error" && !!list.rows.length && ( -

- 暂时无法更新云电脑状态,请重试。 -

- )} - {rows !== null && !list.rows.length && !error && ( - - - -

暂无设备

- - {cloudIssue === "auth" - ? "查看云电脑需要重新授权。" - : cloudIssue === "unsupported" - ? "当前服务器未开通云电脑,请联系管理员。" - : cloudIssue === "error" - ? "未能确认云电脑状态,请重试。" - : clouds === null - ? "正在确认云电脑状态…" - : "当前账号还没有设备。申请一台云电脑,即可从浏览器开始使用。"} - -
- {cloudIssue === "auth" ? ( - - ) : ( - canApply && ( - - ) - )} -
- )} - {failures.length > 0 && ( - { - if (!open) dismissFailures() - }} - > - - - 云电脑申请失败 - - {failures.map((c) => "「" + c.name + "」").join("、")} - 未能创建。 - {canApply - ? "可以重新申请;只有确认配置后才会提交。" - : "如需帮助,请联系管理员。"} - - - - - {canApply && ( - - )} - - - - )} - {form && canApply && failures.length === 0 && ( - setForm(false)} - authorize={() => void authorize(undefined, true)} - accepted={(env) => { - setClouds([env]) - setForm(false) - setRevision((n) => n + 1) - }} - /> - )} - {!!list.rows.length && ( - - {list.rows.map((d) => ( - - - - - - - {d.display_name || d.machine_id} - - - - {[platforms[d.platform] || d.platform, d.arch] - .filter(Boolean) - .join(" · ") || "系统未知"} - {d.note && " · " + d.note} - - - - - {isDeviceOnline(d) && - (!d.cloud || (!cloudIssue && !error)) && - validMachineId(d.machine_id) && ( - - )} - - ))} - - )} -
-

- {updated && <>上次更新 {updated.toLocaleTimeString()} · }每{" "} - {refreshSeconds} 秒自动刷新 -

- -
- - )} -
- - -
-
-
+
+

{t("webUi.clientInDevelopment")}

) } diff --git a/monkeyai/web/src/pages/client/cloud-application.tsx b/monkeyai/web/src/pages/client/cloud-application.tsx deleted file mode 100644 index ddee1f6e0..000000000 --- a/monkeyai/web/src/pages/client/cloud-application.tsx +++ /dev/null @@ -1,386 +0,0 @@ -import { useEffect, useId, useRef, useState } from "react" -import { Button } from "@/components/ui/button" -import { Input } from "@/components/ui/input" -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select" -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog" -import { - cloudCatalog, - CloudError, - createEnvironment, - estimate, - type Application, - type Environment, -} from "@/lib/workspace-cloud" - -type Props = { - token: string - user: string - close(): void - accepted(env: Environment): void - authorize(): void -} -const field = "grid min-w-0 gap-2 text-sm" -type Option = { value: string; label: string; disabled?: boolean } -function ApplicationSelect({ - label, - placeholder, - options, - value, - disabled, - onChange, -}: { - label: string - placeholder?: string - options: Option[] - value: string | null - disabled: boolean - onChange(value: string): void -}) { - const id = useId() - return ( -
- - -
- ) -} -export function CloudApplication({ - token, - user, - close, - accepted, - authorize, -}: Props) { - const key = "monkeyai.web.cloud-application:" + user - const nameInput = useRef(null) - const nameErrorId = useId() - const [pending, setPending] = useState(() => { - const raw = localStorage.getItem(key) - return raw ? JSON.parse(raw) : null - }) - const [name, setName] = useState(pending?.name || "我的云电脑"), - [choice, setChoice] = useState(""), - [imageId, setImage] = useState(null), - [hostId, setHost] = useState("") - const [catalog, setCatalog] = useState - > | null>(null), - [revision, reload] = useState(0) - const [error, setError] = useState(""), - [needAuth, setAuth] = useState(false), - [busy, setBusy] = useState(false), - lock = useRef(false) - useEffect(() => { - const c = new AbortController() - cloudCatalog(token, c.signal) - .then((data) => { - if (!c.signal.aborted) setCatalog(data) - }) - .catch((e) => { - if (!c.signal.aborted) { - setError(e.message) - setAuth(e instanceof CloudError && e.authorization) - } - }) - return () => c.abort() - }, [token, revision]) - const spec = catalog?.specs.find((s) => s.id + "/" + s.version === choice), - images = catalog?.images, - image = - imageId === null - ? images?.find((i) => i.is_default) || - (images?.length === 1 ? images[0] : undefined) - : images?.find((i) => i.id === imageId) - const host = catalog?.hosts.find( - (h) => - h.available && - (!hostId || h.id === hostId) && - (!image || image.architectures.includes(h.architecture)) - ) - const price = spec && host ? estimate(spec, host) : null - const issue = !catalog - ? "" - : !catalog.specs.length - ? "暂无可用规格,请联系管理员。" - : !images?.length - ? "暂无可用系统镜像,请联系管理员。" - : !catalog.hosts.some((h) => h.available) - ? "暂无可用宿主机,请联系管理员。" - : !host - ? "没有与所选镜像匹配的可用宿主机,请更换选择。" - : spec && price === null - ? "无法确认价格,请刷新配置。" - : "" - const validName = - !!name.trim() && - new TextEncoder().encode(name.trim()).length <= 128 && - !Array.from(name.trim()).some( - (c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127 - ) - function refresh() { - setCatalog(null) - setError("") - setAuth(false) - reload((n) => n + 1) - } - async function submit() { - if ( - lock.current || - (!pending && !(spec && image && host && validName && price !== null)) - ) - return - lock.current = true - setBusy(true) - setError("") - setAuth(false) - let submitted: Application | null = null - try { - // 保存原请求再发送;回执丢失时不能用一个新键重扣积分。 - const old = localStorage.getItem(key) - if (old && !pending) { - setPending(JSON.parse(old)) - return - } - const body = pending || { - name: name.trim(), - specification_id: spec!.id, - specification_version: spec!.version, - image_id: image!.id, - ...(hostId ? { host_id: hostId } : {}), - request_key: crypto.randomUUID(), - } - localStorage.setItem(key, JSON.stringify(body)) - submitted = body - const env = await createEnvironment(token, body) - localStorage.removeItem(key) - accepted(env) - } catch (e) { - if ( - e instanceof CloudError && - e.status >= 400 && - e.status < 500 && - e.status !== 408 - ) { - localStorage.removeItem(key) - setPending(null) - setAuth(e.authorization) - if (e.code.startsWith("specification_")) { - setChoice("") - refresh() - } - setError(e.message) - } else { - if (submitted) setPending(submitted) - setError("未能确认申请结果。请恢复原申请,不要重复申请。") - } - } finally { - lock.current = false - setBusy(false) - } - } - return ( - { - if (!v && !busy) close() - }} - > - - - 申请云电脑 - - {pending - ? "已有一笔申请等待确认。恢复时会使用原配置,不会重复扣费。" - : "为当前账号创建一台可从浏览器连接的云电脑。"} - - -
{ - e.preventDefault() - void submit() - }} - > - {pending ? ( -

待确认的云电脑:{pending.name}

- ) : ( -
- - {!validName && ( -

- 请输入有效名称,最多 128 字节。 -

- )} - ({ - value: s.id + "/" + s.version, - label: - s.cpu_millis / 1000 + - " 核 · " + - s.memory_bytes / 1024 ** 3 + - " GB", - }))} - /> - ({ - value: i.id, - label: i.display_name + (i.is_default ? "(默认)" : ""), - }))} - /> - ({ - value: h.id, - label: (h.name || h.id) + " · " + h.architecture, - disabled: !h.available, - })), - ]} - /> -
-

- {price === null ? ( - - {!catalog && !error - ? "正在获取可用配置…" - : !spec - ? "选择规格后显示预计费用" - : "暂无报价"} - - ) : price === 0 ? ( - "免费" - ) : ( - <> - 预计每小时{" "} - - {price} - {" "} - 积分 - - )} -

-

- 收费规格创建时预付一小时,提前停止或删除不退还已购小时。 -

-
-
- )} - {(error || issue) && ( -

- {error || issue} -

- )} - - {needAuth ? ( - - ) : ( - (issue || error) && - !pending && ( - - ) - )} - - - -
-
-
- ) -} diff --git a/monkeyai/web/src/pages/client/composer-actions-menu.tsx b/monkeyai/web/src/pages/client/composer-actions-menu.tsx deleted file mode 100644 index af1a11537..000000000 --- a/monkeyai/web/src/pages/client/composer-actions-menu.tsx +++ /dev/null @@ -1,138 +0,0 @@ -import { HugeiconsIcon } from "@hugeicons/react" -import { - Attachment01Icon, - AtIcon, - BookOpen01Icon, - CodeIcon, - GraduationCapIcon, - LibraryIcon, - McpServerIcon, - PlusSignIcon, - Shield01Icon, -} from "@hugeicons/core-free-icons" -import { Button } from "@/components/ui/button" -import { - DropdownMenu, - DropdownMenuCheckboxItem, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuSeparator, - DropdownMenuSub, - DropdownMenuSubTrigger, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu" -import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from "@/components/ui/tooltip" -import { useUserMarkdown, setUserMarkdown } from "./user-markdown-preference" - -const resources = [ - ["规则", Shield01Icon], - ["专家", GraduationCapIcon], - ["技能", BookOpen01Icon], - ["知识库", LibraryIcon], - ["连接器", McpServerIcon], -] as const - -export function ComposerActionsMenu({ - showMention, - pickFiles, - fileHint, -}: { - showMention: boolean - pickFiles?: () => void - fileHint?: string -}) { - const markdown = useUserMarkdown() - return ( - - - - } - /> - } - > - - - 更多操作 - - - - - - {fileHint || "添加附件"} - - - - 目标 - - {showMention && ( - - - 添加引用 - - )} - - {resources.map(([label, icon]) => ( - - - - {label} - - - ))} - - - - Markdown 排版 - - - - ) -} diff --git a/monkeyai/web/src/pages/client/composer-controls.tsx b/monkeyai/web/src/pages/client/composer-controls.tsx deleted file mode 100644 index 4c498b49b..000000000 --- a/monkeyai/web/src/pages/client/composer-controls.tsx +++ /dev/null @@ -1,501 +0,0 @@ -import { useRef, useState } from "react" -import { - Tooltip, - TooltipTrigger, - TooltipContent, -} from "@/components/ui/tooltip" -import { Button } from "@/components/ui/button" -import assistantAvatar from "@/assets/composer-assistant.png" -import { HugeiconsIcon } from "@hugeicons/react" -import { - ArrowDown01Icon, - FlashIcon, - ShieldPlusIcon, -} from "@hugeicons/core-free-icons" -import { ChevronDown, Folder, Sparkles } from "lucide-react" -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuGroup, - DropdownMenuItem, - DropdownMenuLabel, - DropdownMenuRadioGroup, - DropdownMenuRadioItem, - DropdownMenuSeparator, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu" -import type { DeviceChannel } from "@/lib/device-connection" -import { ComposerActionsMenu } from "./composer-actions-menu" -import type { ComposerChoice } from "@/lib/device-composer-options" -import type { Project } from "@/lib/device-workspace" - -const row = (v: unknown): v is Record => - !!v && typeof v === "object" && !Array.isArray(v) -const modes: Record = { - auto: "按需确认", - bypassPermissions: "完全信任", - default: "逐项确认", - plan: "仅规划", -} -const modeIcon = (id?: string) => - id === "bypassPermissions" ? FlashIcon : ShieldPlusIcon -const help: Record = { - default: "执行操作前向你请求确认。", - plan: "先分析任务并制定计划。", - auto: "常规操作自动执行,受保护的操作会先征求你的确认。", - bypassPermissions: "文件修改和命令自动执行,跳过常规授权确认。", -} -export function WorkspaceControl({ - projects, - project, - disabled, - onProject, -}: { - projects: Project[] - project: string - disabled: boolean - onProject: (v: string) => void -}) { - const active = projects.find((p) => p.id === project) - return ( - - - - {active?.name ?? (project ? "项目不可用" : "选择项目")} - - - - - - 不关联项目 - - - - 项目 - {projects.map((p) => ( - - - {p.name} - {p.missing && "(目录不可用)"} - - - ))} - {!projects.length && ( - 暂无可选择的项目 - )} - - - - - ) -} -export function PermissionControl({ - mode, - disabled, - home, - onChange, -}: { - mode?: string - disabled: boolean - home: boolean - onChange: (v: string) => void -}) { - const name = mode ? (modes[mode] ?? mode) : "权限未确认" - const label = "执行权限:" + name - const rows = - mode && !["auto", "bypassPermissions"].includes(mode) - ? [mode, "auto", "bypassPermissions"] - : ["auto", "bypassPermissions"] - if (!home) { - const next = mode === "auto" ? "bypassPermissions" : "auto" - const hint = "点击切换为「" + modes[next] + "」" - return ( - - { - if (!disabled && mode) onChange(next) - }} - /> - } - > - - -
-
- {rows.map((id) => ( -
-
-
-
{help[id]}
-
- ))} -
-

{hint}

-
-
-
- ) - } - return ( - - - } - > - - - - 执行权限 - { - if (!disabled && v !== mode) onChange(v) - }} - > - {rows.map((id) => ( - - - ))} - - - - - ) -} - -type Named = { id: string; name: string; description?: string } -async function readExperts( - ch: DeviceChannel, - session: string -): Promise { - const value = await ch.request("_monkeyai/session/resources", { - sessionId: session, - }) - if (!row(value) || value.sessionId !== session) - throw new Error("无法确认当前会话的专家。") - const items = - row(value.snapshot) && Array.isArray(value.snapshot.items) - ? value.snapshot.items.filter(row) - : [] - const experts = items - .filter( - (x) => - x.kind === "expert" && - x.available === true && - typeof x.id === "string" && - typeof x.name === "string" - ) - .map((x) => ({ - id: String(x.id), - name: String(x.name), - description: - typeof x.description === "string" ? x.description : undefined, - })) - const expert = value.expert - if ( - row(expert) && - typeof expert.id === "string" && - typeof expert.name === "string" - ) - experts.push({ - id: expert.id, - name: expert.name, - description: - typeof expert.description === "string" ? expert.description : undefined, - }) - return experts -} -function ExpertPanel({ - items, - value, - disabled, - onSelect, -}: { - items: Named[] - value?: string - disabled: boolean - onSelect: (id: string) => void -}) { - const [query, setQuery] = useState("") - const list = useRef(null) - const [height, setHeight] = useState() - const visible = items.filter((e) => - (e.name + " " + (e.description ?? "")) - .toLocaleLowerCase() - .includes(query.trim().toLocaleLowerCase()) - ) - return ( - <> - { - if (!query) setHeight(list.current?.clientHeight) - setQuery(e.target.value) - if (list.current) list.current.scrollTop = 0 - }} - onKeyDown={(e) => { - if (e.key === "ArrowDown") { - e.preventDefault() - list.current - ?.querySelector( - '[role="menuitemradio"]:not([aria-disabled="true"])' - ) - ?.focus() - } - if (e.key !== "Escape" && e.key !== "Tab") e.stopPropagation() - }} - /> -
- {visible.length > 1 && visible[0].id === "" && ( -

置顶

- )} - - {visible.map((e) => ( - - - {e.id ? ( - - ) : ( - - )} - - - {e.name} - {e.description} - - - ))} - - {!visible.length &&

没有匹配的专家

} -
-
- 管理专家 -
- - ) -} -type Options = { - session: string - channel?: DeviceChannel - choice?: ComposerChoice - knownExperts: string[] - disabled: boolean - configuring: boolean - running: boolean - onExpert: (v: string) => void - showMention: boolean - pickFiles?: () => void - fileHint?: string -} -export function ComposerTools({ - session, - channel, - choice, - knownExperts, - disabled, - configuring, - running, - onExpert, - showMention, - pickFiles, - fileHint, -}: Options) { - const [result, setResult] = useState<{ - ch: DeviceChannel - session: string - data?: Named[] - error?: string - }>() - const seq = useRef(0) - const current = - result?.ch === channel && result?.session === session ? result : undefined - const load = (open: boolean) => { - if (!open || !channel || !session) return - const n = ++seq.current - void readExperts(channel, session).then( - (data) => { - if (n === seq.current) setResult({ ch: channel, session, data }) - }, - (e) => { - if (n === seq.current) - setResult({ - ch: channel, - session, - error: e instanceof Error ? e.message : "设备未返回资源清单。", - }) - } - ) - } - const experts = new Map( - knownExperts.map((id): [string, Named] => [id, { id, name: id }]) - ) - for (const x of current?.data ?? []) experts.set(x.id, x) - const id = choice?.expertId - const roleName = id - ? (experts.get(id)?.name ?? id) - : choice - ? "通用助理" - : "角色未确认" - const roles = ( - e.id && e.id !== "monkeyai-design" - ), - ]} - value={id} - disabled={disabled || running || configuring} - onSelect={onExpert} - /> - ) - return ( -
- - - - - {id ? ( - - ) : ( - - )} - - {roleName} - - - {roles} - - -
- ) -} diff --git a/monkeyai/web/src/pages/client/composer-drafts.ts b/monkeyai/web/src/pages/client/composer-drafts.ts deleted file mode 100644 index fed56c685..000000000 --- a/monkeyai/web/src/pages/client/composer-drafts.ts +++ /dev/null @@ -1,179 +0,0 @@ -import { - validQuotes, - type MessageQuote, -} from "../../lib/device-message-quotes.ts" -import type { DraftFile } from "../../lib/device-uploads.ts" -import type { QueueState } from "../../lib/device-workspace.ts" - -export function draftKey( - user: string, - machine: string, - session: string, - project: string -) { - return ( - "monkeyai.web.draft:" + - JSON.stringify([ - user, - machine, - session ? "session" : "new", - session || project, - ]) - ) -} - -type Draft = { - text: string - files?: DraftFile[] - pendingFiles?: DraftFile[] - quotes?: MessageQuote[] - pending?: string - pendingOperation?: string - receiptState?: QueueState - pendingQuotes?: MessageQuote[] - destination?: string -} -// 二进制内容只留在当前页。刷新后保留文件占位,要求重选,不能无附件误发。 -function metadata(value: unknown): DraftFile[] | undefined { - if (!Array.isArray(value)) return - return value.flatMap((f) => - f && - typeof f.id === "string" && - typeof f.name === "string" && - Number.isSafeInteger(f.size) && - f.size >= 0 - ? [{ id: f.id, name: f.name, size: f.size }] - : [] - ) -} - -export function composerDrafts() { - const memory = new Map() - function read(key: string): Draft { - const cached = memory.get(key) - if (cached) return cached - try { - const value = JSON.parse(localStorage.getItem(key) || "null") - if (typeof value?.text === "string") { - const [, , kind, id] = JSON.parse( - key.slice("monkeyai.web.draft:".length) - ) - const session = kind === "session" ? id : "" - return { - text: value.text, - destination: value.destination, - pending: value.pending, - pendingOperation: value.pendingOperation, - receiptState: value.receiptState, - files: metadata(value.files), - pendingFiles: metadata(value.pendingFiles), - quotes: validQuotes(value.quotes, session) ? value.quotes : undefined, - pendingQuotes: validQuotes(value.pendingQuotes, session) - ? value.pendingQuotes - : undefined, - } - } - } catch { - /* 无持久存储时仍可编辑。 */ - } - try { - return { text: sessionStorage.getItem(key) || "" } - } catch { - return { text: "" } - } - } - function update(key: string, change: Partial, durable = false) { - const next = { ...read(key), ...change } - try { - if ( - next.text || - next.quotes?.length || - next.files?.length || - next.pending !== undefined || - next.destination !== undefined - ) - localStorage.setItem( - key, - JSON.stringify({ - ...next, - files: metadata(next.files), - pendingFiles: metadata(next.pendingFiles), - }) - ) - else localStorage.removeItem(key) - } catch { - if (durable) throw new Error("无法保存发送记录,消息未发送。") - /* 当前页面的内存副本仍然可用。 */ - } - memory.set(key, next) - try { - sessionStorage.removeItem(key) - } catch { - /* 旧草稿存储不可用。 */ - } - } - return { - records(user: string, machine: string) { - const keys = new Set(memory.keys()) - try { - for (let i = 0; i < localStorage.length; i++) - keys.add(localStorage.key(i) || "") - } catch { - /* 仍可查看本页记录。 */ - } - return [...keys] - .filter((k) => k.startsWith("monkeyai.web.draft:")) - .flatMap((key) => { - try { - const [u, m, kind, session] = JSON.parse( - key.slice("monkeyai.web.draft:".length) - ) - const entry = read(key) - return u === user && - m === machine && - kind === "session" && - entry.pending !== undefined - ? [{ key, session: String(session), entry }] - : [] - } catch { - return [] - } - }) - }, - read, - update, - begin( - key: string, - text: string, - quotes?: MessageQuote[], - files?: DraftFile[], - operationId?: string - ) { - update( - key, - { - text: "", - quotes: undefined, - pending: text, - pendingOperation: operationId, - receiptState: "pending", - pendingQuotes: quotes, - files: undefined, - pendingFiles: files, - }, - !!operationId - ) - }, - settle(key: string, accepted: boolean) { - if (accepted) - update(key, { - pending: undefined, - pendingOperation: undefined, - receiptState: undefined, - pendingQuotes: undefined, - pendingFiles: undefined, - }) - else update(key, { receiptState: "outcome_unknown" }) - }, - } -} diff --git a/monkeyai/web/src/pages/client/composer-file.tsx b/monkeyai/web/src/pages/client/composer-file.tsx deleted file mode 100644 index 007325f91..000000000 --- a/monkeyai/web/src/pages/client/composer-file.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import { useEffect, useRef } from "react" -import { Paperclip } from "lucide-react" -import type { DraftFile } from "@/lib/device-uploads" - -export function ComposerFile({ - entry, - disabled, - onRemove, -}: { - entry: DraftFile - disabled: boolean - onRemove: () => void -}) { - const img = useRef(null) - const preview = - entry.file && - ["image/png", "image/jpeg", "image/webp", "image/gif"].includes( - entry.file.type - ) - useEffect(() => { - if (!img.current || !entry.file) return - const url = URL.createObjectURL(entry.file) - img.current.src = url - return () => URL.revokeObjectURL(url) - }, [entry.file]) - return ( -
- - {preview ? ( - - ) : ( - - )} - - - {entry.name} - - {!entry.file && 需重选} - -
- ) -} diff --git a/monkeyai/web/src/pages/client/composer-quotes.css b/monkeyai/web/src/pages/client/composer-quotes.css deleted file mode 100644 index 15c613c9c..000000000 --- a/monkeyai/web/src/pages/client/composer-quotes.css +++ /dev/null @@ -1,139 +0,0 @@ -.dw-quote-action-row { - display: flex; - margin-top: 4px; -} -[data-role="user"] > .dw-quote-action-row { - justify-content: flex-end; -} -.dw-quote-action { - display: grid; - place-items: center; - width: 22px; - height: 22px; - border-radius: 4px; - color: var(--muted-foreground); -} -.dw-quote-action:hover { - color: var(--foreground); - background: var(--muted); -} -.dw-quote-action[aria-disabled="true"] { - cursor: not-allowed; -} -@media (hover: hover) { - article:not(:hover):not(:focus-within) - > .dw-quote-action-row - .dw-quote-action { - opacity: 0; - } -} -.dq-quotes { - display: flex; - flex: none; - flex-wrap: wrap; - align-content: flex-start; - gap: 6px; - min-width: 0; - padding: 16px calc(var(--composer-inset) + 2.5rem) 8px var(--composer-inset); - max-height: min(30dvh, 200px); - overflow: auto; -} -.dw-composer .dc-editor:has(.dq-quotes) > textarea { - padding-top: 0; - min-height: calc(3.2em + 8px); -} -.dw-composer[data-expanded] .dc-editor:has(.dq-quotes) > textarea { - min-height: 0; -} -.dq-quote { - display: flex; - align-items: center; - gap: 6px; - flex: 0 0 180px; - max-width: 100%; - min-width: 0; - height: 28px; - padding: 4px 6px; - border-radius: 6px; - background: color-mix(in srgb, var(--muted) 65%, transparent); - color: var(--foreground); - font-size: 12px; - line-height: 18px; -} -.dq-quote-trigger { - display: flex; - align-items: center; - gap: 6px; - min-width: 0; - flex: 1; - height: 100%; - border-radius: 4px; - text-align: left; - cursor: pointer; -} -.dq-quote-icon { - display: grid; - place-items: center; - flex: none; - width: 18px; - height: 18px; - color: var(--muted-foreground); -} -.dq-quote-title { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} -.dq-quote-remove { - display: grid; - place-items: center; - flex: none; - width: 20px; - height: 20px; - border-radius: 4px; - color: var(--muted-foreground); - font-size: 14px; -} -.dq-quote-remove:hover:not(:disabled) { - color: var(--foreground); - background: var(--accent); -} -.dq-quote-popover[data-slot="popover-content"] { - display: flex; - flex-direction: column; - gap: 8px; - width: 360px; - max-width: calc(100vw - 24px); - max-height: min(320px, var(--available-height, calc(100dvh - 24px))); - padding: 12px 14px; - border-radius: 12px; - overflow: hidden; -} -.dq-quote-heading { - display: flex; - align-items: center; - gap: 8px; - flex: none; - color: var(--muted-foreground); - font-size: 11px; -} -.dq-quote-heading button:hover { - text-decoration: underline; -} -.dq-quote-text { - min-height: 0; - max-height: 240px; - overflow: auto; - scrollbar-color: var(--muted-foreground) transparent; - overscroll-behavior: contain; - white-space: pre-wrap; - overflow-wrap: anywhere; - font-size: 13px; - line-height: 1.65; - user-select: text; -} -.dq-quote-warning { - flex-basis: 100%; - font-size: 12px; - color: var(--muted-foreground); -} diff --git a/monkeyai/web/src/pages/client/composer-quotes.tsx b/monkeyai/web/src/pages/client/composer-quotes.tsx deleted file mode 100644 index 973052bbc..000000000 --- a/monkeyai/web/src/pages/client/composer-quotes.tsx +++ /dev/null @@ -1,115 +0,0 @@ -import { useMemo, useState } from "react" -import { - Popover, - PopoverContent, - PopoverTrigger, -} from "@/components/ui/popover" -import type { MessageQuote } from "@/lib/device-message-quotes" -import { parseUserMarkdown, type UserMarkdownInline } from "@/lib/user-markdown" -import "./composer-quotes.css" - -function inlineText(p: UserMarkdownInline): string { - return p.type === "strong" ? p.children.map(inlineText).join("") : p.text -} -export function ComposerQuote({ - quote, - disabled, - onRemove, - onViewSource, -}: { - quote: MessageQuote - disabled: boolean - onRemove: () => void - onViewSource: () => void -}) { - const [open, setOpen] = useState(false) - const display = useMemo( - () => - parseUserMarkdown(quote.text) - .map((b) => - b.type === "code" - ? b.text - : b.type === "heading" - ? b.children.map(inlineText).join("") - : b.lines.map((l) => l.map(inlineText).join("")).join("\n") - ) - .join("\n") || quote.text, - [quote.text] - ) - const chars = Array.from(display.replace(/\s+/gu, " ").trim()) - const date = new Date(quote.at) - return ( - -
- - - - - - {chars.slice(0, 100).join("")} - {chars.length > 100 ? "…" : ""} - - - -
- interaction === "keyboard"} - finalFocus={(interaction) => interaction === "keyboard"} - > -
- {quote.role === "user" ? "你" : "助手"} - {Number.isFinite(date.getTime()) && ( - - )} - -
-
- {display} -
-
-
- ) -} diff --git a/monkeyai/web/src/pages/client/device-chat-message.tsx b/monkeyai/web/src/pages/client/device-chat-message.tsx deleted file mode 100644 index c03f8c314..000000000 --- a/monkeyai/web/src/pages/client/device-chat-message.tsx +++ /dev/null @@ -1,826 +0,0 @@ -import { - Fragment, - memo, - useEffect, - useId, - useMemo, - useState, - type ReactNode, -} from "react" -import { - Tooltip, - TooltipTrigger, - TooltipContent, -} from "@/components/ui/tooltip" -import { - parseUserMarkdown, - type UserMarkdownInline, -} from "@/lib/device-user-markdown" -import { errorSummary, friendlyError } from "@/lib/device-chat-errors" -import { Marked } from "marked" -import { useUserMarkdown } from "./user-markdown-preference" -import type { MessageQuote } from "@/lib/device-message-quotes" -import DOMPurify from "dompurify" -import hljs from "highlight.js/lib/common" -import { - finalReplyIndex, - type ChatPart, - type Message, -} from "@/lib/device-workspace" -import { FileText, ChevronRight, CircleAlert } from "lucide-react" -import "./device-chat.css" -import { HugeiconsIcon } from "@hugeicons/react" -import { - Copy01Icon, - Alert02Icon, - ArrowRight01Icon, - Settings02Icon, - ComputerTerminal01Icon, - File01Icon, - FileEditIcon, - Search01Icon, - Globe02Icon, - CodeIcon, - BookOpen01Icon, - Tick02Icon, - QuoteIcon, - Edit02Icon, - Comment01Icon, -} from "@hugeicons/core-free-icons" - -const escape = (s: string) => - s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">") -const markdown = new Marked({ - breaks: true, - renderer: { - html: ({ text }) => escape(text), - image: ({ text }) => escape(text), - code({ raw, text, lang }) { - const lines = raw.trimEnd().split("\n"), - fence = /^ {0,3}(`{3,}|~{3,})/.exec(lines[0])?.[1] - const close = lines.at(-1)?.trim() || "" - const closed = - !fence || - (lines.length > 1 && - close.length >= fence.length && - [...close].every((c) => c === fence[0])) - const language = lang?.split(/\s/)[0] - const body = - language && closed && hljs.getLanguage(language) - ? hljs.highlight(text, { language }).value - : escape(text) - const count = text.split("\n").length - const compact = count <= 3 && language !== "diff" - const title = - (language && hljs.getLanguage(language)?.name) || language || "纯文本" - const numbers = Array.from({ length: count }, (_, i) => i + 1).join("\n") - return ( - '
' + - escape(title) + - '
" +
-        body +
-        "
" - ) - }, - }, -}) -const userTags = [ - "p", - "br", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "strong", - "code", - "pre", - "span", -] -const assistantTags = [ - "div", - "figure", - "figcaption", - ...userTags, - "em", - "del", - "a", - "ul", - "ol", - "li", - "blockquote", - "hr", - "table", - "thead", - "tbody", - "tr", - "td", - "th", -] -function inline(parts: UserMarkdownInline[]): ReactNode { - return parts.map((part, i) => - part.type === "code" ? ( - {part.text} - ) : part.type === "strong" ? ( - {inline(part.children)} - ) : ( - part.text - ) - ) -} -const UserBody = memo(function UserBody({ text }: { text: string }) { - return ( -
- {parseUserMarkdown(text).map((b, i) => - b.type === "code" ? ( -
-            {b.text}
-          
- ) : b.type === "heading" ? ( -
- {inline(b.children)} -
- ) : ( -
- {b.lines.map((line, j) => ( - - {j > 0 && "\n"} - {inline(line)} - - ))} -
- ) - )} -
- ) -}) -function UserBubble({ text }: { text: string }) { - const markdown = useUserMarkdown() - const [open, setOpen] = useState(false), - contentId = useId() - const characters = Array.from(text), - long = characters.length > 180 || text.split("\n").length > 6 - return ( -
-
- {long && !open ? ( -

- {characters.slice(0, 180).join("")}… -

- ) : markdown ? ( - - ) : ( -

{text}

- )} -
- {long && ( - - )} -
- ) -} -const Body = memo(function Body({ text }: { text: string }) { - const html = useMemo( - () => - DOMPurify.sanitize(markdown.parse(text, { async: false }), { - ALLOWED_TAGS: assistantTags, - ALLOWED_ATTR: ["class", "href", "start"], - ALLOWED_URI_REGEXP: /^(?:https?:\/\/|mailto:)/i, - }), - [text] - ) - return ( -
- ) -}) -const labels: Record = { - pending: "等待执行", - in_progress: "执行中", - completed: "已完成", - failed: "失败", -} -function FooterAction({ - label, - icon, - onClick, - unavailable, -}: { - label: string - icon: typeof QuoteIcon - onClick?: () => void - unavailable?: string -}) { - return ( - - } - type="button" - className="dc-copy" - aria-label={label} - aria-disabled={!onClick} - onClick={onClick} - > - - - {label} - {!onClick && unavailable ? " · " + unavailable : ""} - - - ) -} -function CopyText({ - text, - action = "复制消息", -}: { - text: string - action?: string -}) { - const [state, setState] = useState<"idle" | "copied" | "failed">("idle") - useEffect(() => { - if (state === "idle") return - const timer = setTimeout(() => setState("idle"), 2000) - return () => clearTimeout(timer) - }, [state]) - const label = - state === "copied" - ? "已复制" - : state === "failed" - ? "复制失败,点击重试" - : action - return ( - - } - type="button" - className="dc-copy" - data-state={state} - aria-label={label} - onClick={async () => { - try { - await navigator.clipboard.writeText(text) - setState("copied") - } catch { - setState("failed") - } - }} - > - {state === "copied" ? ( - - ) : state === "failed" ? ( - - ) : ( - - )} - - {state === "idle" ? "" : label} - - - - {state === "failed" ? "复制失败,请重试" : label} - - - ) -} -// Phosphor lightbulb-filament,MIT;见 public/licenses/phosphor-icons.txt。 -function ThoughtIcon() { - return ( - - ) -} -type ToolPart = Extract -function actionIcon(name: string) { - switch (name) { - case "Cmd": - case "Bash": - case "PowerShell": - return ComputerTerminal01Icon - case "Read": - case "McpReadResource": - return File01Icon - case "Write": - case "Edit": - case "apply_patch": - case "TaskUpdate": - case "NotebookEdit": - return FileEditIcon - case "Grep": - case "Glob": - case "WebSearch": - case "ToolSearch": - case "CapabilitySearch": - case "SkillSearch": - return Search01Icon - case "WebFetch": - return Globe02Icon - case "LSP": - return CodeIcon - case "Skill": - case "SkillLoad": - return BookOpen01Icon - default: - return Settings02Icon - } -} -function upstreamErrorMessage(raw: string): string | undefined { - let value: unknown = raw.replace(/^API error \d{3}[^:\r\n]*:\s*/, '') - let message: string | undefined - // 网关可能把上游 JSON 再编码成 error.message 字符串;只沿明确的 error / message 字段解包。 - for (let depth = 0; depth < 12; depth++) { - if (typeof value === 'string') { - try { value = JSON.parse(value) } - catch { return message } - } else if (value && typeof value === 'object' && !Array.isArray(value)) { - const object = value as { error?: unknown; message?: unknown } - if (typeof object.error === 'string' || (object.error && typeof object.error === 'object')) { - value = object.error - } else if (typeof object.message === 'string') { - message = object.message - value = message - } else return message - } else return message - } - return message -} - -function ErrorNotice({ text, raw }: { text: string; raw?: string }) { - const [open, setOpen] = useState(false) - const id = useId() - const message = open && raw ? upstreamErrorMessage(raw) : undefined - return ( -
-
-
- {open && raw?.trim() &&
-
原始报错
- {message && message !== raw &&

{message}

} -
{raw}
-
} -
- ) -} - -function Block({ - part, - user, - live, - childrenCalls = [], -}: { - part: ChatPart - user: boolean - live: boolean - childrenCalls?: ToolPart[] -}) { - if (part.type === "text") - return user ? : - if (part.type === "tool_call") { - const single = childrenCalls.length === 1 ? childrenCalls[0] : undefined - const status = single?.status === "failed" ? "failed" : part.status - const icons = childrenCalls.map((p) => actionIcon(p.name)) - const icon = - status === "failed" - ? Alert02Icon - : icons.length - ? icons.every((i) => i === icons[0]) - ? icons[0] - : Settings02Icon - : actionIcon(part.name) - const shown = single ?? part - const expandable = - childrenCalls.length > 1 || - shown.input !== undefined || - shown.output !== undefined - const Row = expandable ? "details" : "div" - const Trigger = expandable ? "summary" : "button" - const label = - childrenCalls.length > 1 - ? "批量执行" - : shown.name === "TaskOutput" - ? "查看任务结果" - : shown.title - return ( - 1 || undefined} - > - - - {childrenCalls.length > 1 ? ( -
    - {childrenCalls.map((c) => ( -
  1. - -
  2. - ))} -
- ) : ( - <> - {shown.input !== undefined && ( - <> - 输入 -
-                  {typeof shown.input === "string"
-                    ? shown.input
-                    : JSON.stringify(shown.input, null, 2)}
-                
- - )} - {shown.output !== undefined && ( - <> - 输出{shown.truncated ? "(节选)" : ""} -
{shown.output}
- - )} - - )} -
- ) - } - if (part.type === "error") return - if (part.type === "thought") - return ( -
- - - 思考过程 - - -
- ) - if (part.type === "file") - return ( -
-
- ) - return

{part.text}

-} -function TracePanel({ - label, - open, - toggle, - thought = false, - working = false, - children, -}: { - label: string - open: boolean - toggle: () => void - thought?: boolean - working?: boolean - children: ReactNode -}) { - const id = useId() - return ( -
- -
-
{children}
-
-
- ) -} -function TraceGroup({ - parts, - live, - working, - embedded, -}: { - parts: ChatPart[] - live: boolean - working: boolean - embedded: boolean -}) { - const [manual, setManual] = useState() - const thought = parts.every((p) => p.type === "thought"), - open = manual ?? (working && !thought) - const content = thought ? ( - (p.type === "thought" ? p.text : "")).join("")} - /> - ) : ( -
-
    - {parts.map( - (p, i) => - !( - p.type === "tool_call" && - p.parentId && - parts.some( - (parent) => - parent.type === "tool_call" && - parent.name === "ExecuteCode" && - !parent.parentId && - parent.id === p.parentId - ) - ) && ( -
  1. - - child.type === "tool_call" && - child.parentId === p.id - ) - : undefined - } - /> -
  2. - ) - )} -
-
- ) - if (embedded && !thought) return content - return ( - setManual(!open)} - > - {content} - - ) -} -export function ChatMessage({ - message: m, - continued, - live, - active, - onReuse, - onQuote, -}: { - message: Message - continued: boolean - live: boolean - active: boolean - onReuse?: (text: string) => void - onQuote?: (quote: MessageQuote) => void -}) { - // 用户正在读详情时,回复结束也不把这段记录移进新的折叠容器。 - const [reading, setReading] = useState(false) - const [historyOpen, setHistoryOpen] = useState(false) - const user = m.role === "user", - split = user || reading ? 0 : finalReplyIndex(m, continued) - const inHistory = (i: number) => - i < split && ["text", "tool_call", "thought"].includes(m.parts[i].type) - const history: ReactNode[] = [], - visible: ReactNode[] = [] - for (let i = 0; i < m.parts.length; i++) { - const part = m.parts[i], - start = i, - embedded = inHistory(i), - target = embedded ? history : visible - if (!user && (part.type === "tool_call" || part.type === "thought")) { - while ( - i + 1 < m.parts.length && - ["tool_call", "thought"].includes(m.parts[i + 1].type) - ) - i++ - target.push( - - ) - } else - target.push() - } - const time = user ? m.at : (m.endedAt ?? m.at) - const date = time === undefined ? undefined : new Date(time) - const fullTime = date?.toLocaleString("zh-CN", { - year: "numeric", - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - hourCycle: "h23", - }) - const seconds = - !user && m.endedAt !== undefined && m.startedAt !== undefined - ? Math.max(0, Math.round((m.endedAt - m.startedAt) / 1000)) - : undefined - const hours = Math.floor((seconds ?? 0) / 3600), - minutes = Math.floor((seconds ?? 0) / 60) % 60, - rest = (seconds ?? 0) % 60 - const elapsed = - seconds === undefined - ? undefined - : seconds === 0 - ? "不到 1 秒" - : hours - ? hours + "小时" + (minutes ? minutes + "分钟" : "") - : (minutes ? minutes + "分钟" : "") + (rest ? rest + "秒" : "") - const copyBody = m.parts - .slice(historyOpen ? 0 : split) - .flatMap((p) => (p.type === "text" ? [p.text] : [])) - .join("\n\n") - return ( -
{ - if (!row || split) return - const toggle = () => setReading(!!row.querySelector("details[open]")) - row.addEventListener("toggle", toggle, true) - return () => row.removeEventListener("toggle", toggle, true) - }} - className="dc-message" - data-role={m.role} - aria-label={user ? "你" : "助手"} - > - {split > 0 && ( - setHistoryOpen(!historyOpen)} - > - {history} - - )} - {visible} - {!active && (date || copyBody) && ( -
- - {date && ( - - - } - > - {!user && - m.endedAt !== undefined && - (continued ? "本段结束于 " : "结束于 ")} - {date.toLocaleTimeString("zh-CN", { - hour: "2-digit", - minute: "2-digit", - hourCycle: "h23", - })} - - - {fullTime} - - - )} - {elapsed && 用时 {elapsed}} - - {(copyBody || !user) && ( - - {m.quoteSource && ( - onQuote(m.quoteSource!) : undefined} - unavailable="当前连接不可添加引用" - /> - )} - {copyBody && } - {user ? ( - p.type === "file") - ? () => onReuse(copyBody) - : undefined - } - unavailable={ - m.parts.some((p) => p.type === "file") - ? "当前无法复用附件" - : "当前无法编辑草稿" - } - /> - ) : ( - - )} - - )} -
- )} -
- ) -} diff --git a/monkeyai/web/src/pages/client/device-chat.css b/monkeyai/web/src/pages/client/device-chat.css deleted file mode 100644 index cbc74ba64..000000000 --- a/monkeyai/web/src/pages/client/device-chat.css +++ /dev/null @@ -1,723 +0,0 @@ -.dc-trace { - min-width: 0; - color: var(--muted-foreground); -} -.dc-trace-trigger { - display: flex; - align-items: center; - gap: 7px; - max-width: 100%; - min-height: 24px; - margin-top: -3px; - padding: 3px 7px 3px 0; - border-radius: 6px; - background: transparent; - font-size: 14px; - font-weight: 400; - line-height: 1.5; - text-align: left; -} -.dc-trace-trigger:is(:hover, :focus-visible) { - color: var(--foreground); - background: color-mix(in srgb, var(--muted) 65%, transparent); -} -.dc-trace-trigger:focus-visible { - outline: 2px solid var(--ring); - outline-offset: 2px; -} -.dc-trace-trigger > svg:last-of-type, -.dc-trace-trigger small { - opacity: 0; - transition: - transform 140ms, - opacity 140ms; -} -.dc-trace-trigger:is(:hover, :focus-visible) > :is(svg:last-of-type, small) { - opacity: 1; -} -.dc-trace-trigger[aria-expanded="true"] > svg:last-of-type { - transform: rotate(90deg); -} -@media (hover: none) { - .dc-trace-trigger > svg:last-of-type { - opacity: 0.65; - } -} -.dc-trace-motion { - display: grid; - grid-template-rows: 0fr; - visibility: hidden; - overflow-anchor: none; - transition: - grid-template-rows 240ms cubic-bezier(0.33, 0, 0.2, 1), - visibility 0s 240ms; -} -.dc-trace-motion[data-open="true"] { - grid-template-rows: 1fr; - visibility: visible; - transition-delay: 0s; -} -.dc-trace-motion > div { - min-height: 0; - min-width: 0; - overflow: clip; -} -.dc-trace-viewport[data-working="true"] { - max-height: 208px; - overflow-y: auto; - scrollbar-width: thin; -} -.dc-trace-steps { - list-style: none; - margin: 3px 0 2px 12px; - padding-left: 18px; -} -.dc-trace-steps > li { - position: relative; - min-width: 0; -} -.dc-trace-steps > li:not(:last-child) { - padding-bottom: 2px; - display: flow-root; -} -.dc-trace-steps > li:not(:last-child)::before { - content: ""; - position: absolute; - left: -19.5px; - top: 24px; - bottom: -2px; - width: 1px; - background: repeating-linear-gradient( - to bottom, - currentColor 0 2px, - transparent 2px 4px - ); - opacity: 0.4; -} -.dc-trace-steps .dc-record > :is(summary, .dc-tool-label) > svg:first-child { - position: absolute; - left: -28px; - top: 4px; - width: 18px; - height: 18px; -} -@media (prefers-reduced-motion: reduce) { - .dc-trace-motion, - .dc-trace-trigger > svg:last-of-type, - .dc-trace-trigger small { - transition: none; - } -} -.dc-column { - width: 100%; - max-width: 900px; - min-width: 0; - margin-inline: auto; - padding: 24px 16px; - display: flex; - flex-direction: column; - gap: 16px; -} -.dc-message { - min-width: 0; - display: flex; - flex-direction: column; - gap: 8px; -} -.dc-message[data-role="user"] { - max-width: calc(100% - 3rem); - align-self: flex-end; - align-items: flex-end; - gap: 4px; -} -.dc-user-bubble { - min-width: 0; - max-width: 100%; - padding: 10px 16px; - border-radius: 16px 16px 4px 16px; - background: var(--primary); - color: var(--primary-foreground); - overflow-wrap: anywhere; -} -.dark .dc-user-bubble { - background: #252525; - color: #dfdfdf; -} -.dc-user-bubble .dc-markdown, -.dc-user-preview { - font-size: 1rem; - line-height: 1.5; -} -.dc-user-preview { - white-space: pre-wrap; - display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: 6; - overflow: hidden; -} -.dc-user-toggle { - margin-top: 8px; - font-size: 0.75rem; - color: inherit; - text-decoration: underline; - text-underline-offset: 3px; -} -.dc-user-bubble :is(pre, code) { - color: inherit; - background: color-mix(in srgb, currentColor 14%, transparent); -} -.dc-user-bubble pre code { - background: transparent; -} -.dc-footer, -.dc-date, -.dc-activity { - color: var(--muted-foreground); - font-size: 0.75rem; - line-height: 16px; - font-variant-numeric: tabular-nums; -} -.dc-footer { - min-height: 22px; - display: flex; - align-items: center; - gap: 4px; -} -.dc-date { - text-align: center; - padding: 4px 0; -} -.dc-activity { - display: flex; - align-items: center; - gap: 7px; - min-width: 0; - white-space: nowrap; - font-size: 14px; - line-height: 20px; - min-height: 22px; -} -.dc-message[data-role="assistant"] + .dc-activity { - margin-top: calc(0.125rem - 1rem); -} -.dc-activity-glyph { - display: inline-grid; - grid-template-columns: repeat(3, 4px); - grid-auto-rows: 4px; - gap: 1px; - flex: none; - margin-inline: 4px; - color: var(--primary); -} -.dc-activity-glyph i { - border-radius: 50%; - background: currentColor; - opacity: 0.15; - animation: dc-glyph 864ms cubic-bezier(0.77, 0, 0.175, 1) infinite; -} -@keyframes dc-glyph { - 0%, - 62%, - 100% { - opacity: 0.15; - } - 18%, - 42% { - opacity: 1; - } -} -.dc-activity-status { - display: flex; - align-items: center; - gap: 7px; - min-width: 0; -} -.dc-activity-verb { - overflow: hidden; - text-overflow: ellipsis; - font-weight: 500; - background: linear-gradient( - 90deg, - var(--dc-ink, var(--foreground)) 0 36%, - var(--dc-glint, var(--muted-foreground)) 50%, - var(--dc-ink, var(--foreground)) 64% 100% - ); - background-size: 220% 100%; - background-clip: text; - -webkit-text-fill-color: transparent; - animation: dc-shine 2.2s linear infinite; -} -@keyframes dc-shine { - from { - background-position: 120% 0; - } - to { - background-position: -120% 0; - } -} -.dc-activity-time { - flex: none; -} -.dc-activity[data-stalled] { - --dc-ink: #98601a; - --dc-glint: #d6b27e; -} -.dark .dc-activity[data-stalled] { - --dc-ink: #deb57b; - --dc-glint: #8a6a3e; -} -.dc-activity[data-stalled] .dc-activity-glyph { - color: var(--dc-ink); -} -@media (prefers-reduced-motion: reduce) { - .dc-activity-verb { - animation: none; - background: none; - -webkit-text-fill-color: var(--dc-ink, var(--foreground)); - } -} -.dc-pagination { - text-align: center; - min-height: 1px; - overflow-anchor: none; -} -.dc-pagination:has(> .sr-only:not(:focus)) { - height: 1px; - margin-bottom: -17px; -} -.dc-latest { - z-index: 1; - background: var(--background); - box-shadow: 0 6px 18px -8px rgb(0 0 0 / 0.3); -} -.dc-markdown { - font-size: 16px; - line-height: 1.75; - overflow-wrap: anywhere; -} -.dc-markdown > * + * { - margin-top: 0.55em; -} -.dc-markdown :is(h1, h2, h3, h4, h5, h6) { - font-weight: 650; - line-height: 1.45; -} -.dc-markdown h1 { - font-size: 1.375em; -} -.dc-markdown h2 { - font-size: 1.25em; -} -.dc-markdown h3 { - font-size: 1.125em; -} -.dc-message[data-role="assistant"] .dc-markdown { - color: #000000eb; -} -.dark .dc-message[data-role="assistant"] .dc-markdown { - color: var(--foreground); -} -.dc-markdown :is(p, ul, ol) { - margin-block: 0.5em; -} -.dc-markdown li { - margin-block: 0.25em; -} -.dc-markdown li > p:first-child { - margin-top: 0; -} -.dc-markdown li > p:last-child { - margin-bottom: 0; -} -.dc-markdown :is(h1, h2, h3, h4, h5, h6) { - margin: 1em 0 0.5em; -} -.dc-markdown hr { - margin: 1.5em 0; -} -.dc-markdown blockquote { - color: var(--muted-foreground); - margin-block: 0.75em; -} -.dc-markdown .dc-code { - margin: 1em 0; - min-width: 0; - border: 1px solid var(--border); - border-radius: 8px; - overflow: hidden; - background: var(--background); -} -.dc-markdown .dc-code-compact { - margin: 10px 0; -} -.dc-code figcaption { - display: flex; - align-items: center; - gap: 6px; - padding: 6px 12px; - background: var(--muted); - color: var(--muted-foreground); - font: - 500 12px/18px ui-sans-serif, - system-ui; -} -.dc-code figcaption::before { - content: ""; - font-family: monospace; -} -.dc-code-compact figcaption { - padding: 3px 10px; -} -.dc-code-scroll { - display: flex; - max-height: 480px; - overflow: auto; - padding-block: 8px; -} -.dc-code-compact .dc-code-scroll { - padding-block: 4px; -} -.dc-code-scroll .dc-lines, -.dc-code-scroll pre { - font: - 400 14px/22px ui-monospace, - monospace; - white-space: pre; -} -.dc-code-scroll .dc-lines { - user-select: none; - text-align: right; - color: var(--muted-foreground); - padding: 0 12px; -} -.dc-markdown .dc-code-scroll pre { - flex: none; - margin: 0; - padding: 0 12px 0 0; - max-width: none; - overflow: visible; - background: transparent; - font-size: 14px; -} -.dc-attachment { - display: flex; - gap: 8px; - align-items: center; - max-width: 100%; - width: fit-content; - padding: 10px 12px; - border-radius: 8px; - border: 1px solid var(--border); - font-size: 14px; -} -.dc-attachment span { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} -.dc-attachment svg { - flex: none; - color: var(--muted-foreground); -} -.dc-footer-info { - opacity: 0.75; - font-variant-numeric: tabular-nums; -} -.dc-footer-info, -.dc-footer-actions { - display: flex; - align-items: center; - gap: 6px; - min-height: 22px; -} -.dc-duration::before { - content: "·"; - margin-right: 6px; - opacity: 0.6; -} -.dc-message:hover .dc-footer-info, -.dc-message:focus-within .dc-footer-info { - opacity: 1; -} -.dc-footer-info time { - white-space: nowrap; - border-radius: 3px; -} -.dc-footer-info time:focus-visible { - outline: 2px solid var(--ring); - outline-offset: 2px; -} -.dc-message[data-role="assistant"] > .dc-footer { - margin-top: -6px; -} -.dc-message[data-role="assistant"] .dc-footer { - flex-direction: column; - align-items: flex-start; - gap: 2px; -} -.dc-message[data-role="user"] .dc-footer { - flex-direction: row-reverse; - padding-right: 3px; -} -.dc-message[data-role="user"] .dc-footer-actions { - flex-direction: row-reverse; -} -.dc-footer-actions .dc-copy[aria-disabled="true"] { - color: var(--muted-foreground); - cursor: not-allowed; -} -.dc-copy { - display: inline-grid; - place-items: center; - width: 22px; - height: 22px; - border-radius: 4px; - color: var(--muted-foreground); -} -.dc-copy:hover { - background: var(--muted); - color: var(--foreground); -} -@media (hover: hover) { - .dc-copy { - opacity: 0; - } - .dc-message:hover .dc-copy, - .dc-message:focus-within .dc-copy, - .dc-copy[data-state="copied"], - .dc-copy[data-state="failed"] { - opacity: 1; - } -} -.dc-markdown ol, -.dc-markdown ul { - padding-inline-start: 1.5em; -} -.dc-markdown ol { - list-style: decimal; -} -.dc-markdown ul { - list-style: disc; -} -.dc-markdown a { - text-decoration: underline; -} -.dc-markdown blockquote { - border-left: 2px solid currentColor; - padding-left: 0.8em; -} -.dc-markdown pre, -.dc-record pre, -.dc-error pre { - max-width: 100%; - overflow-x: auto; - white-space: pre; - background: var(--muted); - padding: 0.65em 0.9em; - border-radius: 0.5em; - font-size: 0.87em; -} -.dc-markdown table { - display: block; - overflow: auto; -} -.dc-markdown :is(th, td) { - border: 1px solid var(--border); - padding: 0.25em 0.6em; -} -.dc-markdown .hljs-keyword, -.dc-markdown .hljs-literal { - color: #9455b3; -} -.dc-markdown .hljs-string { - color: #34825f; -} -.dc-markdown .hljs-comment { - color: #747b82; -} -.dc-record, -.dc-error { - min-width: 0; - overflow-wrap: anywhere; -} -.dc-record summary, -.dc-error summary { - cursor: pointer; - font-size: 0.875rem; -} -.dc-record > summary, -.dc-record > button.dc-tool-label, -.dc-error-line { - display: flex; - align-items: center; - gap: 6px; - min-height: 26px; - list-style: none; -} -.dc-record > summary::-webkit-details-marker, -.dc-error summary::-webkit-details-marker { - display: none; -} -.dc-record > :is(summary, .dc-tool-label) { - width: 100%; - max-width: 100%; - height: 26px; - padding: 1px 4px 1px 0; - gap: 8px; - border-radius: 4px; - color: var(--muted-foreground); -} -.dc-tool-label:disabled { - cursor: default; - font-size: 0.875rem; -} -.dc-record > summary:is(:hover, :focus-visible) { - color: var(--foreground); -} -.dc-record > summary:focus-visible { - outline: 2px solid var(--ring); - outline-offset: 2px; -} -.dc-record > summary > .dc-chevron { - opacity: 0; - transition: - opacity 140ms, - transform 140ms; -} -.dc-record > summary:is(:hover, :focus-visible) > .dc-chevron { - opacity: 0.65; -} -@media (hover: none) { - .dc-record > summary > .dc-chevron { - opacity: 0.65; - } -} -.dc-record[data-live="true"]:is( - [data-status="pending"], - [data-status="in_progress"] - ) - > .dc-tool-label - > svg:first-child { - color: var(--primary); -} -.dc-trace-trigger > .dc-thought-icon { - margin-inline: -2px; -} -.dc-step-label, -.dc-step-object { - min-width: 0; - overflow: hidden; - white-space: nowrap; - text-overflow: ellipsis; -} -.dc-step-object { - opacity: 0.8; -} -.dc-trace-steps.dc-program-steps { - margin-top: 2px; -} -.dc-record svg, -.dc-error svg { - flex-shrink: 0; -} -.dc-record[data-status="failed"] > .dc-tool-label > svg:first-child { - color: var(--destructive); -} -.dc-record > pre, -.dc-record > p, -.dc-history > :not(summary) { - margin-block: 4px; - margin-inline-start: 12px; -} -.dc-chevron { - transition: transform 0.12s; -} -details[open] > summary > .dc-chevron { - transform: rotate(90deg); -} -@media (prefers-reduced-motion: reduce) { - .dc-chevron { - transition: none; - } -} -.dc-markdown :not(pre) > code { - padding: 0.1em 0.3em; - border-radius: 4px; - background: var(--muted); - font-size: 0.9em; -} -.dc-user-bubble .dc-markdown :not(pre) > code { - background: color-mix(in srgb, currentColor 14%, transparent); -} -.dc-record small { - color: var(--muted-foreground); -} -.dc-error { - color: var(--destructive); -} -.dc-error-line { - font-size: 0.875rem; - padding-block: 6px; - text-align: center; -} -.dc-error-line::before, -.dc-error-line::after { - content: ""; - flex: 1; - min-width: 8px; - height: 1px; - background: color-mix(in srgb, var(--destructive) 30%, transparent); -} -.dc-error-line > span { - min-width: 0; - user-select: text; -} -.dc-error-toggle { - display: inline-flex; - align-items: center; - flex-shrink: 0; - gap: 2px; - min-height: 24px; - padding: 0 2px; - border: 0; - background: transparent; - font-size: 0.75rem; - cursor: pointer; - color: var(--muted-foreground); -} -.dc-error-toggle:hover { color: var(--foreground); } -.dc-error-toggle:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; border-radius: 3px; } -.dc-error-toggle[aria-expanded="true"] svg { transform: rotate(90deg); } -.dc-error-details p { - margin: 8px 0 12px; - white-space: pre-wrap; - font-size: 0.875rem; - color: var(--foreground); -} -.dc-error-details { - margin: 6px auto 0; - max-width: 760px; - padding: 12px 14px; - border-radius: 8px; - background: var(--muted); - color: var(--muted-foreground); -} -.dc-error-heading { - display: flex; - align-items: center; - justify-content: space-between; - font-size: 0.75rem; -} -.dc-error-heading .dc-copy { - opacity: 1; -} -.dc-error-details pre { - margin: 0; - padding: 0; - max-height: 320px; - overflow: auto; - white-space: pre-wrap; - overflow-wrap: anywhere; - font-size: 0.75rem; - line-height: 1.7; -} diff --git a/monkeyai/web/src/pages/client/device-composer.css b/monkeyai/web/src/pages/client/device-composer.css deleted file mode 100644 index 49b299914..000000000 --- a/monkeyai/web/src/pages/client/device-composer.css +++ /dev/null @@ -1,737 +0,0 @@ -.dw-composer { - container: remote-composer / inline-size; - --composer-inset: 24px; - --composer-control: 34px; -} -.dw-composer .dw-frame { - border: 1px solid rgb(0 0 0 / 4%); - border-radius: 24px; - background: var(--card); - box-shadow: - 0 4px 16px -4px rgb(0 0 0 / 4%), - 0 16px 48px -20px rgb(0 0 0 / 10%); -} -.dw-composer .dw-frame:focus-within { - border-color: rgb(0 0 0 / 6%); -} -.dark .dw-composer .dw-frame { - background: #343434; - border-color: rgb(255 255 255 / 2.5%); - box-shadow: 0 16px 40px -24px rgb(0 0 0 / 70%); -} -.dark .dw-composer .dw-frame:focus-within { - border-color: rgb(255 255 255 / 8.4%); -} -/* 光带放在外层,沿卡片上边线移动,不被编辑区的圆角裁掉。 */ -.dark .dw-home .dw-composer:not([data-expanded]) { - position: relative; -} -.dark .dw-home .dw-composer::before { - --dc-edge-peak: 0.62; - content: ""; - position: absolute; - z-index: 2; - top: 0; - left: 40%; - width: 20%; - height: 1px; - pointer-events: none; - background: linear-gradient( - 90deg, - transparent, - rgb(197 214 226 / 0) 14%, - rgb(226 236 242 / calc(var(--dc-edge-peak) * 0.4)) 34%, - rgb(255 255 255 / var(--dc-edge-peak)) 50%, - rgb(226 236 242 / calc(var(--dc-edge-peak) * 0.4)) 66%, - transparent - ); - animation: dc-edge-drift 9s ease-in-out infinite; -} -.dark .dw-home .dw-composer:focus-within::before { - --dc-edge-peak: 0.94; -} -@keyframes dc-edge-drift { - 0%, 18%, 82%, 100% { left: 32%; } - 50% { left: 48%; } -} -.dw-composer .dc-editor > textarea { - padding: 20px calc(var(--composer-inset) + 2rem) 8px var(--composer-inset); - min-height: calc(3.2em + 28px); - font-size: 16px; - line-height: 1.6; - color: var(--foreground); -} -.dw-composer .dc-editor > textarea::placeholder { - color: var(--muted-foreground); -} -@media (max-width: 640px) { - .dw-home .dw-composer .dc-editor > textarea { - padding-top: 14px; - font-size: 14px; - } -} -.dw-composer .dw-frame > .dw-tools { - justify-content: flex-start; - border: none; - padding: 6px 14px 8px 15px; - gap: 6px; -} -.dw-composer :is(.dw-folder, .dw-device-label) { - margin-right: auto; - height: var(--composer-control); - max-width: 65%; - padding-inline: 8px; - border-radius: 10px; - font-size: 14px; - font-weight: 400; - color: var(--muted-foreground); -} -.dw-composer .dw-folder { - position: relative; - gap: 4px; -} -.dw-composer .dw-folder:hover, -.dw-composer .dw-folder:focus-within { - background: var(--muted); - color: var(--foreground); -} -.dw-composer .dw-folder select { - min-width: 0; - height: 100%; - appearance: none; - padding-right: 16px; - background: transparent; - font: inherit; - color: inherit; - text-overflow: ellipsis; - cursor: pointer; -} -.dw-composer .dw-folder option { - color: var(--foreground); - background: var(--card); -} -.dw-composer .dw-folder > svg:last-child { - position: absolute; - right: 8px; - pointer-events: none; -} -.dw-composer .dw-turn-action { - flex: none; - width: 32px; - height: 32px; - padding: 0; -} -.dw-composer .dw-turn-action:disabled { - opacity: 1; - background: color-mix(in srgb, var(--primary) 50%, var(--background)); - color: var(--primary-foreground); -} -.dw-composer .dq-header { - padding-left: calc(var(--composer-inset) - 6px); -} -.dw-composer .dq-list { - padding-left: calc(var(--composer-inset) - 3px); -} -.dw-composer .dw-footnote, -.dw-composer .dw-feedback { - text-align: start; - padding-inline: 14px; - line-height: 1.5; -} -.dw-composer details.dw-feedback { - padding-block: 8px; - border-radius: 10px; - background: var(--muted); -} -@container remote-composer (max-width: 600px) { - .dw-frame { - --composer-inset: 20px; - --composer-control: 30px; - } - .dw-composer .dw-frame > .dw-tools { - padding: 6px 12px 8px 13px; - } - .dw-composer :is(.dw-folder, .dw-device-label) { - font-size: 12px; - } -} -@container remote-composer (max-width: 420px) { - .dw-frame { - --composer-inset: 14px; - --composer-control: 28px; - } - .dw-composer .dw-frame > .dw-tools { - padding: 4px 8px 8px; - gap: 2px; - } -} -.dc-editor { - position: relative; - min-height: 0; - flex: 1; -} -.dc-file-drop { - position: absolute; - inset: 4px; - z-index: 5; - display: grid; - place-items: center; - border: 1px dashed var(--ring); - border-radius: 14px; - background: var(--card); - color: var(--muted-foreground); - font-size: 13px; - pointer-events: none; -} -.dc-tools-left, -.dc-actions, -.dc-composer-footer, -.dc-chip { - display: flex; - align-items: center; - min-width: 0; -} -.dc-tools-left { - gap: 4px; - flex: 1 1 auto; -} -.dc-actions { - gap: 6px; - margin-left: auto; - flex-shrink: 0; -} -.dc-chip { - height: var(--composer-control); - padding: 0 8px; - gap: 6px; - border-radius: 10px; - background: transparent; - color: var(--muted-foreground); - font: inherit; - font-size: 14px; - white-space: nowrap; -} -.dc-chip:disabled { - opacity: 0.5; - cursor: default; -} -.dc-chip:hover:not(:disabled), -.dc-chip[data-popup-open] { - background: var(--muted); - color: var(--foreground); -} -.dc-chip svg { - flex: none; -} -.dc-chip span:not(.dc-avatar) { - overflow: hidden; - text-overflow: ellipsis; -} -.dc-chip[data-trusted] { - color: #98601a; -} -.dark .dc-chip[data-trusted] { - color: #deb57b; -} -.dc-plus { - justify-content: center; - width: var(--composer-control); - padding: 0; - flex: none; -} -.dc-plus .dc-plus-icon { - transition: transform 180ms cubic-bezier(0.22, 1, 0.36, 1); -} -.dc-plus[aria-expanded="true"] .dc-plus-icon { - transform: rotate(45deg); -} -button.dc-plus:is(:hover, [aria-expanded="true"], [data-popup-open]) { - background: transparent; -} -.dc-menu.dc-plus-menu { - width: max-content; - min-width: min(196px, calc(100vw - 24px)); - max-height: calc(var(--available-height, 100dvh) / var(--workspace-scale, 1)); - padding-inline: 10px; - overflow: hidden auto; - overscroll-behavior: contain; - scrollbar-width: none; - font-family: system-ui, sans-serif; -} -.dc-plus-menu::-webkit-scrollbar { - display: none; -} -.dc-plus-menu [role="menuitemcheckbox"] { - min-height: 32px; - gap: 12px; - padding: 6px 36px 6px 12px; - border-radius: 10px; - font-size: 14px; - line-height: 1.4; -} -.dc-plus-menu [role="menuitemcheckbox"]:is(:hover, :focus, [data-highlighted]) { - background: var(--muted); - color: var(--foreground); -} -.dc-plus-menu [data-slot="dropdown-menu-separator"] { - margin-inline: 12px; -} -.dc-plus-menu [data-slot="dropdown-menu-sub-trigger"][data-disabled] { - opacity: 0.4; - pointer-events: none; -} -.dc-plus-menu [data-slot="dropdown-menu-sub-trigger"] > svg:last-child { - width: 12px; - height: 12px; - color: var(--muted-foreground); -} -.dc-role { - color: color-mix(in oklab, var(--foreground) 55%, var(--muted-foreground)); - border: 1px solid transparent; - line-height: 20px; - padding-left: 2px; - max-width: 12em; -} -.dc-avatar { - width: 20px; - height: 20px; - display: grid; - place-items: center; - border-radius: 50%; - background: var(--muted); - color: var(--foreground); - flex: none; -} -.dc-menu.dc-expert-menu { - display: flex; - flex-direction: column; - gap: 8px; - width: 360px; - min-width: 0; - max-width: calc(min(var(--available-width, 100vw), 100vw - 24px) / var(--workspace-scale, 1)); - max-height: min(460px, calc(var(--available-height, 100dvh) / var(--workspace-scale, 1))); - padding: 8px; - overflow: hidden; - font-family: system-ui, sans-serif; -} -.dc-expert-search { - flex: none; - height: 28px; - width: 100%; - padding: 0 10px; - border: 1px solid var(--border); - border-radius: 8px; - background: var(--background); - font-size: 12px; -} -.dc-expert-list { - min-height: 0; - max-height: 280px; - overflow: auto; - overscroll-behavior: contain; - scrollbar-width: thin; - scrollbar-color: var(--muted-foreground) transparent; - scrollbar-gutter: stable; -} -.dc-expert-list::-webkit-scrollbar-track { - background: transparent; -} -.dc-expert-menu [role="menuitemradio"] { - align-items: flex-start; - gap: 8px; - padding-block: 8px; - cursor: pointer; -} -.dc-expert-icon { - display: grid; - place-items: center; - width: 24px; - height: 24px; - margin-top: 1px; - flex: none; - border-radius: 6px; - overflow: hidden; -} -.dc-expert-icon img { - width: 100%; - height: 100%; - object-fit: cover; -} -.dc-expert-copy { - min-width: 0; - flex: 1; -} -.dc-expert-copy > span, -.dc-expert-copy small { - display: block; - overflow: hidden; - white-space: nowrap; - text-overflow: ellipsis; - line-height: 20px; -} -.dc-expert-copy small { - margin-top: 2px; - min-height: 16px; - line-height: 16px; -} -.dc-expert-label, -.dc-expert-empty { - padding: 3px 8px; - font-size: 12px; - color: var(--muted-foreground); -} -.dc-expert-empty { - padding: 18px 8px; - text-align: center; -} -.dc-expert-footer { - flex: none; - border-top: 1px solid var(--border); - padding-top: 6px; -} -.dc-expert-footer [role="menuitem"] { - padding-inline: 8px; -} -@container remote-composer (max-width:420px) { - .dc-chip.dc-role { - padding-inline: 3px; - } -} -.dc-expand { - position: absolute; - z-index: 4; - top: 10px; - right: 10px; - color: var(--muted-foreground); - opacity: 0; - transition: - opacity 140ms ease, - background-color 140ms ease, - color 140ms ease; -} -.dw-frame:hover .dc-expand, -.dc-expand:focus-visible, -.dw-composer[data-expanded] .dc-expand { - opacity: 1; -} -.dc-composer-footer { - gap: 12px; - padding: 9px 10px 0; - justify-content: flex-end; - color: var(--muted-foreground); - font-size: 12px; -} -.dc-composer-footer .dc-chip { - height: 26px; - font-size: 12px; - max-width: 100%; - border-radius: 7px; -} -.dc-composer-footer .dc-workspace { - max-width: 45%; - margin-right: auto; -} -.dc-composer-footer.dc-environment { - flex: none; - justify-content: space-between; - min-height: 40px; - padding: 0 8px 0 15px; - border-top: 1px solid color-mix(in srgb, var(--border) 48%, transparent); -} -.dc-environment .dc-chip { - height: 28px; - gap: 5px; - border-radius: 8px; - font-weight: 400; -} -.dc-environment .dc-permission { - padding-right: 6px; - flex: none; - line-height: 16px; -} -.dc-environment .dw-footnote:not([data-warning]) { - position: absolute; - width: 1px; - height: 1px; - overflow: hidden; - clip-path: inset(50%); -} -.dc-actions .dc-mode { - width: auto; - gap: 4px; - justify-content: center; - line-height: 20px; -} -.dw-composer .dc-composer-footer .dw-footnote { - min-width: 0; - margin: 0; - padding: 0; - opacity: 0.65; - white-space: nowrap; -} -.dc-menu { - width: 256px; - max-width: calc(100vw - 24px); - max-height: min(55dvh, 380px, var(--available-height, 380px)); - padding: 6px; - border: 1px solid var(--border); - border-radius: 16px; - box-shadow: - 0 8px 28px #00000010, - 0 2px 6px #00000006; - overflow: auto; -} -.dc-menu.dc-project-options { - width: 240px; -} -.dc-menu.dc-mode-options { - width: 288px; -} -:is(.dc-mode-options, .dc-mode-bubble)[data-closed] { - pointer-events: none; -} -.dc-mode-options [data-slot="dropdown-menu-label"] { - line-height: 1.4; -} -.dc-menu :is([role="menuitem"], [role="menuitemradio"]) { - min-height: 32px; - gap: 12px; - padding: 6px 12px; - border-radius: 10px; - font-size: 14px; - line-height: 1.4; -} -.dc-menu [role="menuitemradio"] { - padding-right: 30px; -} -.dc-menu.dc-mode-options [role="menuitemradio"] { - align-items: flex-start; - font-weight: 400; - background: transparent; - box-shadow: none; - transition: none; -} -.dc-menu.dc-mode-options - [role="menuitemradio"]:is(:hover, :focus-visible, [data-highlighted]) { - background: var(--muted); - color: var(--foreground); -} -.dc-mode-options [role="menuitemradio"] > svg { - margin-top: 2px; -} -.dc-mode-copy { - display: flex; - flex-direction: column; - gap: 2px; - min-width: 0; -} -.dc-menu.dc-mode-options .dc-mode-copy small { - color: var(--muted-foreground); - line-height: 1.45; - white-space: normal; -} -/* 续聊气泡只说明档位,切换动作在按钮上。 */ -.dc-mode-bubble { - width: min(280px, calc(100vw - 24px)); - max-height: none; - overflow: visible; - border-radius: var(--radius-md); - background: var(--foreground); - color: var(--background); - padding: 6px 12px; - box-shadow: 0 2px 10px rgb(0 0 0 / 6%); - font: - 400 12px/1.6 system-ui, - sans-serif; -} -.dark .dc-mode-bubble { - box-shadow: 0 2px 10px rgb(0 0 0 / 16%); -} -.dc-mode-bubble dl { - display: grid; - gap: 8px; -} -.dc-mode-bubble dl > div:not([data-current]) { - opacity: 0.7; -} -.dc-mode-heading { - display: flex; - align-items: center; - gap: 6px; - font-weight: 500; -} -.dc-mode-heading svg { - opacity: 0.85; -} -.dc-current-mode { - margin-left: 2px; - padding: 0 5px; - border: 1px solid currentColor; - border-radius: 999px; - font-size: 10px; - line-height: 14px; - opacity: 0.85; -} -.dc-mode-description { - display: block; - opacity: 0.8; -} -.dc-mode-instruction { - margin-top: 12px; - opacity: 0.6; -} - -.dc-menu [data-slot="dropdown-menu-label"] { - padding: 7px 9px 5px; - font-size: 12px; - font-weight: 400; - color: var(--muted-foreground); -} -.dc-composer-activity { - display: flex; - align-items: center; - justify-content: space-between; - color: var(--muted-foreground); - font-size: 12px; - padding: 0 8px 4px; -} -.dc-composer-activity .dc-stop-link { - height: 24px; - font-size: 12px; -} -.dc-menu small, -.dc-menu-note { - display: block; - color: var(--muted-foreground); - font-size: 12px; - font-weight: 400; - white-space: normal; - line-height: 1.5; -} -.dc-menu-note, -.dc-resource { - padding: 5px 8px; - overflow-wrap: anywhere; -} -.dc-resource { - font-size: 13px; -} -.dc-scrim { - position: absolute; - inset: 0; - background: rgb(0 0 0 / 20%); - z-index: 45; -} -.dw-composer[data-expanded] { - position: absolute; - z-index: 46; - inset: 0; - margin: auto; - width: min(880px, calc(100% - clamp(16px, 4%, 48px))); - height: min(640px, calc(100% - clamp(24px, 8%, 96px))); - border: 1px solid var(--border); - border-radius: 16px; - background: var(--card); - box-shadow: 0 24px 72px -20px rgb(0 0 0 / 32%); - padding: 0; - overflow: auto; - display: flex; - flex-direction: column; -} -.dark .dw-composer[data-expanded] { - background: var(--popover); -} -.dw-composer[data-expanded] .dw-frame { - border: 0; - border-radius: inherit; - background: transparent; - box-shadow: none; - display: flex; - flex: 1; - min-height: 0; - flex-direction: column; -} -.dw-composer[data-expanded] .dc-editor { - display: flex; - flex-direction: column; -} -.dw-composer[data-expanded] .dc-editor > textarea { - flex: 1; - min-height: 0; - max-height: none; -} -.dw-composer[data-expanded] .dc-composer-footer, -.dw-composer[data-expanded] > .dw-feedback { - padding-bottom: 10px; -} -@media (hover: none) { - .dc-expand { - opacity: 1; - } -} -@media (prefers-reduced-motion: reduce) { - .dark .dw-home .dw-composer::before { - animation: none; - } - .dc-plus .dc-plus-icon, - .dc-expand { - transition: none; - } -} -@container remote-composer (max-width:600px) { - .dc-environment.dc-composer-footer { - padding-left: 11px; - } - .dc-actions .dc-mode { - width: var(--composer-control); - padding-inline: 0; - } - .dc-chip { - font-size: 12px; - } - .dc-mode span { - display: none; - } - .dc-tools-left, - .dc-actions { - gap: 2px; - } -} -@container remote-composer (max-width:480px) { - .dc-role-name { - display: none; - } -} -@container remote-composer (max-width:440px) { - .dc-composer-footer .dw-footnote:not([data-warning]):not([data-browsing]) { - display: none; - } - .dw-composer .dc-composer-footer .dw-footnote[data-browsing] { - white-space: normal; - overflow-wrap: anywhere; - } - .dc-composer-footer:has([data-warning]) { - flex-wrap: wrap; - } - .dc-composer-footer .dw-footnote[data-warning] { - white-space: normal; - order: 1; - flex-basis: 100%; - } - .dc-composer-footer .dc-permission { - margin-left: auto; - } - .dc-composer-footer .dc-workspace { - max-width: 60%; - } -} -@container remote-composer (max-width:420px) { - .dc-composer-footer.dc-environment { - padding-left: 5px; - } -} -@container remote-composer (max-width:300px) { - .dc-composer-footer.dc-environment { - padding-left: 3px; - } -} diff --git a/monkeyai/web/src/pages/client/device-composer.tsx b/monkeyai/web/src/pages/client/device-composer.tsx deleted file mode 100644 index 3d313034d..000000000 --- a/monkeyai/web/src/pages/client/device-composer.tsx +++ /dev/null @@ -1,706 +0,0 @@ -import { - useEffect, - useId, - useLayoutEffect, - useRef, - useState, - useSyncExternalStore, - type RefObject, -} from "react" -import { ArrowUp, LoaderCircle, Square } from "lucide-react" -import { HugeiconsIcon } from "@hugeicons/react" -import { Maximize01Icon, Minimize01Icon } from "@hugeicons/core-free-icons" -import "./device-composer.css" -import { Button } from "@/components/ui/button" -import type { PlanStep, Project } from "@/lib/device-workspace" -import type { DeviceChannel } from "@/lib/device-connection" -import { DeviceQueue, type QueueDispatch } from "./device-queue" -import { DeviceTaskPlan } from "./device-task-plan" -import { ComposerQuote } from "./composer-quotes" -import { ComposerFile } from "./composer-file" -import type { DraftFile } from "@/lib/device-uploads" -import type { MessageQuote } from "@/lib/device-message-quotes" -import { DeviceModelPicker } from "./device-model-picker" -import { - newModelSelection, - type NewModelDraft, - type Selection, -} from "@/lib/device-models" -import { useDeviceModelCatalog } from "./use-device-model-catalog" -import { - ComposerTools, - PermissionControl, - WorkspaceControl, -} from "./composer-controls" -import type { ComposerChoice } from "@/lib/device-composer-options" -import { stopTarget, stopTurn, type Turn } from "@/lib/device-turn" - -type StopAttempt = { - channel: DeviceChannel - id: string - result: "waiting" | "unknown" | Awaited> -} -const stopFeedback = { - waiting: "正在请求设备停止所选轮次…", - stopped: "设备已确认停止所选轮次。", - expired: "所选轮次已不再运行,未停止其他轮次。", - notStopped: "设备匹配到所选轮次,但未确认停止。", - unknown: "停止结果未确认,请核对会话状态。", -} - -const touchQuery = "(pointer: coarse)" -function watchTouch(callback: () => void) { - const media = matchMedia(touchQuery) - media.addEventListener("change", callback) - return () => media.removeEventListener("change", callback) -} -const touchInput = () => matchMedia(touchQuery).matches - -export function DeviceComposer({ - focusRequest, - session, - inputHistory, - project, - projects, - controlsChannel, - choice, - knownExperts, - optionsDisabled, - configuring, - onOption, - onModelConfirmed, - draft, - editor: input, - quotes, - files, - onFiles, - onRemoveFile, - onAuthorizeFiles, - attachmentIssue, - quoteLimit, - onViewSource, - onRemoveQuote, - onDraft, - onProject, - onSend, - disabled, - sending, - pending, - notice, - queueChannel, - turn, - plan, -}: { - focusRequest: number - session: string - inputHistory?: readonly string[] - project: string - projects: Project[] - controlsChannel?: DeviceChannel - choice?: ComposerChoice - knownExperts: string[] - optionsDisabled: boolean - configuring: boolean - onOption: (change: { mode: string } | { expertId: string }) => void - onModelConfirmed: (next: NonNullable) => void - draft: string - editor: RefObject - quotes: MessageQuote[] - files: DraftFile[] - onFiles: (files: File[]) => void - onRemoveFile: (id: string) => void - onAuthorizeFiles?: () => void - attachmentIssue: string - quoteLimit: number - onViewSource: (q: MessageQuote) => void - onRemoveQuote: (id: string) => void - onDraft: (text: string) => void - onProject: (id: string) => void - onSend: (selection?: Selection) => void - disabled: boolean - sending: boolean - pending?: string - notice: string - queueChannel?: DeviceChannel - turn?: Turn - plan?: PlanStep[] -}) { - const hint = useId() - const picker = useRef(null) - const [dragging, setDragging] = useState(false) - const dragDepth = useRef(0) - const hasInput = !!draft.trim() || !!files.length - const mobile = useSyncExternalStore(watchTouch, touchInput) - const composing = useRef(false) - const [expanded, setExpanded] = useState(false) - const form = useRef(null) - const toggleExpanded = (value: boolean) => { - setExpanded(value) - input.current?.focus({ preventScroll: true }) - } - const queue = useRef<{ next(): void }>(null) - const [dispatch, setDispatch] = useState() - const queueState = - dispatch?.channel === queueChannel && dispatch?.session === session - ? dispatch - : undefined - const activeDispatch = queueState?.submitting ? queueState : undefined - const recallEnabled = !!( - queueChannel?.canWrite && - inputHistory?.length && - queueState && - !queueState.hasMessages && - !activeDispatch && - !sending && - pending === undefined && - !files.length && - !configuring && - !quotes.length - ) - const [browsing, setBrowsing] = useState<{ - entries: readonly string[] - index: number - channel: DeviceChannel - } | null>(null) - if ( - browsing && - (!recallEnabled || - browsing.channel !== queueChannel || - draft !== browsing.entries[browsing.index]) - ) - setBrowsing(null) - const [attempt, setAttempt] = useState() - const stopLock = useRef(false) - const [modelBusy, setModelBusy] = useState(false) - const catalog = useDeviceModelCatalog(controlsChannel) - const [modelDraft, setModelDraft] = useState({}) - const selection = session - ? undefined - : newModelSelection(catalog.models, modelDraft) - function changeModelDraft(change: Selection) { - const model = change.model ?? selection?.model - setModelDraft((prior) => ({ - ...prior, - ...(change.model || change.thinking ? { model } : {}), - ...(model && change.thinking - ? { depths: { ...prior.depths, [model]: change.thinking } } - : {}), - ...(change.mediaModels - ? { mediaModels: { ...prior.mediaModels, ...change.mediaModels } } - : {}), - })) - } - const target = stopTarget( - queueChannel, - session, - turn, - activeDispatch?.preparation - ) - const sameChannel = attempt && attempt.channel === queueChannel - const waiting = sameChannel && attempt.result === "waiting" - const handled = - sameChannel && - attempt.id === target?.id && - (attempt.result === "stopped" || attempt.result === "expired") - const stopDisabled = !!waiting || !!handled || sending - async function stop() { - if (!target || !queueChannel || stopDisabled || stopLock.current) return - stopLock.current = true - const selected = { channel: queueChannel, id: target.id } - setAttempt({ ...selected, result: "waiting" }) - try { - const result = await stopTurn(queueChannel, session, target) - setAttempt({ ...selected, result }) - } catch { - setAttempt({ ...selected, result: "unknown" }) - } finally { - stopLock.current = false - } - } - const feedback = - attempt && - (attempt.result === "waiting" && !sameChannel - ? stopFeedback.unknown - : stopFeedback[attempt.result]) - const compositionEnd = useRef(-Infinity) - useLayoutEffect(() => { - const el = input.current - if (el) { - el.style.height = "auto" - if (!expanded) el.style.height = el.scrollHeight + "px" - } - }, [draft, expanded, input, quotes.length]) - useEffect(() => { - if (!mobile) input.current?.focus({ preventScroll: true }) - }, [session, project, mobile, focusRequest, input]) - const selected = projects.find((p) => p.id === project) - const hasPlan = !!plan?.length - const running = turn?.status === "running" || !!activeDispatch - const planActivity = activeDispatch - ? activeDispatch.preparing - ? "正在准备会话…" - : "正在发送…" - : turn?.status === "error" - ? "执行出错" - : turn?.status === "interrupted" - ? "本轮已中断" - : undefined - const showStopLink = !!target && hasInput - const noticeLine = notice && ( -

- {notice} -

- ) - const permission = ( - onOption({ mode })} - /> - ) - const footer = ( -
- {!session && ( - - )} -

- {!session && project && (!selected || selected.missing) - ? "项目目录不可用,请选择其他工作区。" - : browsing - ? "历史 " + - (browsing.index + 1) + - "/" + - browsing.entries.length + - " · ↑ 更早 · ↓ " + - (browsing.index ? "更新" : "返回空草稿") - : expanded - ? "Esc 收起输入框" - : mobile - ? "换行后,点箭头发送。" - : recallEnabled && !draft - ? "↑ 浏览输入历史 · Enter 发送" - : turn?.status === "running" && hasInput - ? target - ? "Enter 加入待发送 · Esc 停止" - : "Enter 加入待发送" - : "Enter 发送 · Shift + Enter 换行"} -

- {!session && permission} -
- ) - return ( - <> - {(hasPlan || showStopLink) && ( -
- {hasPlan ? ( - - ) : ( - - {target?.field === "preparationId" ? "正在准备" : "运行中"} - - )} - {showStopLink && ( - - )} -
- )} - {expanded && ( -