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,
- }}
- >
-
-
- )
-}
-
-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"
- />
-
- {selected && (
-
- )}
-
-
-
- )
-}
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: "",
- claude: "",
- cohere: "",
- deepseek: "",
- doubao: "",
- gemini: "",
- grok: "",
- hunyuan: "",
- internlm: "",
- kimi: "",
- meta: "",
- minimax: "",
- mistral: "",
- openai: "",
- qwen: "",
- spark: "",
- stepfun: "",
- wenxin: "",
- yi: "",
- 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 && (
-
- )}
- {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}
-
-
-
-
- {deviceStatus(d.status)}
-
- {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 (
-
- )
-}
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)
- }}
- />
- }
- >
-
- {name}
-
-
-
-
- {rows.map((id) => (
-
-
-
-
- {modes[id] ?? id}
- {id === mode && (
- 当前
- )}
-
- - {help[id]}
-
- ))}
-
-
{hint}
-
-
-
- )
- }
- return (
-
-
- }
- >
-
- {name}
-
-
-
-
- 执行权限
- {
- if (!disabled && v !== mode) onChange(v)
- }}
- >
- {rows.map((id) => (
-
-
-
- {modes[id] ?? id}
- {help[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) +
- '"
- )
- },
- },
-})
-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 (
-
-
-
- {raw?.trim() ? errorSummary(text) : friendlyError(text)}
- {!!raw?.trim() && }
-
- {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}
- >
-
-
- {label}
- {shown.name === "TaskOutput" &&
- shown.title !== label &&
- shown.title !== shown.name && (
- {shown.title}
- )}
-
- {!live && (status === "in_progress" || status === "pending")
- ? "上次同步时:"
- : ""}
- {labels[status] || ""}
-
- {expandable && (
-
- )}
-
- {childrenCalls.length > 1 ? (
-
- {childrenCalls.map((c) => (
- -
-
-
- ))}
-
- ) : (
- <>
- {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 (
-
-
- {part.text}
-
- )
- 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 (
-
-
-
-
- )
-}
-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
- )
- ) && (
- -
-
- child.type === "tool_call" &&
- child.parentId === p.id
- )
- : undefined
- }
- />
-
- )
- )}
-
-
- )
- 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) && (
-
- )}
-
- )
-}
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 && (
- toggleExpanded(false)}
- />
- )}
-
- >
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-connection-page.tsx b/monkeyai/web/src/pages/client/device-connection-page.tsx
deleted file mode 100644
index 8869c2dd1..000000000
--- a/monkeyai/web/src/pages/client/device-connection-page.tsx
+++ /dev/null
@@ -1,926 +0,0 @@
-import {
- useCallback,
- useEffect,
- useLayoutEffect,
- useMemo,
- useRef,
- useState,
-} from "react"
-import { useLocation, useNavigate } from "react-router-dom"
-import { QueueRecovery } from "./queue-recovery"
-import { MessageSquare } from "lucide-react"
-import { HugeiconsIcon } from "@hugeicons/react"
-import { SidebarLeftIcon } from "@hugeicons/core-free-icons"
-import { Button } from "@/components/ui/button"
-import {
- connectWorkspaceDevice,
- type ConnectionStatus,
- type DeviceChannel,
-} from "@/lib/device-connection"
-import {
- createSession,
- readHistory,
- directory,
- refreshedRead,
- sendMessage,
- type SessionSnapshot,
-} from "@/lib/device-workspace"
-import {
- beginDeviceAuthorization,
- restoreDeviceGrant,
- validMachineId,
-} from "@/lib/workspace-oauth"
-import { DeviceConversation } from "./device-conversation"
-import { DeviceNavigation } from "./device-navigation"
-import {
- SidebarRemoteConnection,
- type DeviceDirectorySnapshot,
-} from "./device-sidebar-remote"
-import { sidebarCompletions } from "@/lib/device-sidebar-completions"
-import {
- applySidebarAction,
- readSidebarFolder,
- type SidebarAction,
-} from "@/lib/device-sidebar-actions"
-import { DeviceComposer } from "./device-composer"
-import {
- configureComposer,
- type ComposerChoice,
-} from "@/lib/device-composer-options"
-import { composerDrafts, draftKey } from "./composer-drafts"
-import { validateFile, type UploadedFile } from "@/lib/device-uploads"
-import { appendQuote, type MessageQuote } from "@/lib/device-message-quotes"
-import { BrandLogo } from "@/components/brand-logo"
-import {
- Sheet,
- SheetTrigger,
- SheetContent,
- SheetTitle,
-} from "@/components/ui/sheet"
-import { useBranding } from "@/hooks/use-branding"
-import { useIsMobile } from "@/hooks/use-mobile"
-import "./device-workspace.css"
-
-const starting: ConnectionStatus = {
- phase: "connecting",
- detail: "正在连接设备…",
-}
-const reason = (e: unknown) =>
- e instanceof Error ? e.message : "操作未完成,请重试。"
-
-type SidebarIndex = Awaited
>
-const sidebarCacheKey = "monkeyai.web.sidebar-index.v1"
-
-function cachedSidebar(
- user: string,
- machine: string
-): SidebarIndex | undefined {
- try {
- const grant = restoreDeviceGrant(user)
- if (!grant?.canReadSessions) return
- const saved = JSON.parse(sessionStorage.getItem(sidebarCacheKey) || "null")
- if (
- saved?.user === user &&
- saved.machine === machine &&
- saved.expiresAt === grant.expiresAt &&
- Array.isArray(saved.index?.projects) &&
- Array.isArray(saved.index.sessions)
- )
- return saved.index
- } catch {
- /* 缓存不可用时等待设备返回目录。 */
- }
-}
-
-export function DeviceConnectionPage({
- user,
- machine,
-}: {
- user: string
- machine: string
-}) {
- const { state, search, pathname } = useLocation(),
- navigate = useNavigate()
- const session = new URLSearchParams(search).get("session") || ""
- const name =
- typeof state?.name === "string" && state.name ? state.name : machine
- const [status, setStatus] = useState(starting)
- const [channel, setChannel] = useState()
- const notices = useMemo(
- () => ({ ch: channel, turns: sidebarCompletions() }),
- [channel]
- )
- const [badges, setBadges] = useState<{
- ch: DeviceChannel
- ids: Set
- }>()
- const current = useRef(undefined)
- const [ready, setReady] = useState<
- SessionSnapshot & {
- ch: DeviceChannel
- id: string
- }
- >()
- const onReady = useCallback(
- (
- ch: DeviceChannel,
- id: string,
- { turn, config, plan }: SessionSnapshot,
- updatedAt: string
- ) => {
- if (ch !== notices.ch) return
- if (
- turn.status === "idle" &&
- document.visibilityState === "visible" &&
- notices.turns.read(id, updatedAt)
- ) {
- setBadges((prev) => {
- if (prev?.ch !== ch || !prev.ids.has(id)) return prev
- const ids = new Set(prev.ids)
- ids.delete(id)
- return { ch, ids }
- })
- }
- setReady((prior) => ({
- ch,
- id,
- turn:
- prior?.ch === ch &&
- prior.id === id &&
- (prior.turn.modelState?.revision ?? -1) >
- (turn.modelState?.revision ?? -1)
- ? { ...turn, modelState: prior.turn.modelState }
- : turn,
- plan,
- config:
- prior?.ch === ch &&
- prior.id === id &&
- (prior.config.revision ?? -1) > (config.revision ?? -1)
- ? prior.config
- : config,
- }))
- },
- [notices]
- )
- const [attempt, retry] = useState(0),
- [authorizing, setAuthorizing] = useState(false)
- const [index, setIndex] = useState(() =>
- cachedSidebar(user, machine)
- )
- const [listError, setListError] = useState(""),
- [revision, refresh] = useState(0)
- const project = typeof state?.projectId === "string" ? state.projectId : ""
- const key = draftKey(user, machine, session, project)
- const [drafts] = useState(composerDrafts)
- const [, redraw] = useState(0)
- const {
- text: draft,
- quotes = [],
- files = [],
- pending,
- destination = project,
- } = drafts.read(key)
- const editor = useRef(null)
- const transcript = useRef(null)
- function update(change: Parameters[1]) {
- drafts.update(key, change)
- redraw((n) => n + 1)
- }
- const [menu, setMenu] = useState(false),
- [sending, setSending] = useState(false)
- const lock = useRef(false)
- const menuRequest = useRef(null)
- const [menuBusy, setMenuBusy] = useState(false)
- const [menuError, setMenuError] = useState("")
- const [menuNotice, setMenuNotice] = useState("")
- const activePage = useRef({ session, project })
- useEffect(() => {
- activePage.current = { session, project }
- }, [session, project])
- const readFolder = useCallback(
- async (path: string, offset?: number, revision?: string) => {
- if (!channel || current.current !== channel)
- throw new Error("设备未连接。")
- const page = await readSidebarFolder(
- channel,
- user,
- machine,
- path,
- offset,
- revision
- )
- if (current.current !== channel)
- throw new Error("设备连接已更换,请重新打开目录。")
- return page
- },
- [channel, user, machine]
- )
- async function act(op: SidebarAction) {
- const ch = current.current
- if (!ch?.canWrite || ch !== channel)
- throw new Error("当前连接不能修改设备数据。")
- if (menuRequest.current === ch || lock.current)
- throw new Error("另一个操作尚未完成。")
- if (
- op.kind === "delete" &&
- op.ids.some(
- (id) =>
- !index?.sessions.some((s) => s.id === id && s.status !== "running")
- )
- )
- throw new Error("所选会话已变化或正在运行,请重新选择。")
- menuRequest.current = ch
- setMenuBusy(true)
- setMenuError("")
- setMenuNotice("")
- try {
- const result = await applySidebarAction(ch, op)
- if (current.current !== ch)
- throw new Error("设备连接已更换,请刷新核对结果。")
- const active = activePage.current
- if (
- (op.kind === "delete" && result.succeeded.includes(active.session)) ||
- (op.kind === "removeProject" &&
- !active.session &&
- active.project === op.id)
- )
- select("")
- if (op.kind === "flag" || op.kind === "delete") {
- const verb =
- op.kind === "delete"
- ? "删除"
- : (op.value ? "" : "取消") +
- (op.field === "pinned" ? "置顶" : "归档")
- const summary = verb + "成功 " + result.succeeded.length + " 个"
- if (result.failures.length) {
- setMenuError(
- summary +
- ",失败 " +
- result.failures.length +
- " 个:" +
- result.failures[0].reason
- )
- } else if (op.ids.length > 1) setMenuNotice(summary)
- }
- return result
- } finally {
- if (current.current === ch) refresh((n) => n + 1)
- if (menuRequest.current === ch) {
- menuRequest.current = null
- setMenuBusy(false)
- }
- }
- }
- const [notice, setNotice] = useState("")
- const selectedProject = index?.projects.find((p) => p.id === destination)
- const [newOptions, setNewOptions] = useState<{
- key: string
- value: ComposerChoice
- }>()
- const newChoice =
- newOptions?.key === key ? newOptions.value : { mode: "auto", expertId: "" }
- const [configuring, setConfiguring] = useState(false)
- const configRequest = useRef(null)
- // 路由或通道已变更时,旧会话的设置回执不能改写新会话的就绪状态。
- useLayoutEffect(
- () => () => {
- if (configRequest.current !== null) {
- configRequest.current = null
- setConfiguring(false)
- }
- },
- [session, channel]
- )
- const liveReady =
- channel && ready?.ch === channel && ready.id === session ? ready : undefined
- const config = liveReady?.config
- const quoteLimit = liveReady?.ch.quoteLimit ?? 0
- function addQuote(quote: MessageQuote) {
- if (
- !liveReady ||
- !channel?.canWrite ||
- current.current !== channel ||
- !quoteLimit ||
- lock.current ||
- pending !== undefined ||
- session !== quote.sessionId
- )
- return
- try {
- update({
- quotes: appendQuote(
- drafts.read(key).quotes ?? [],
- quote,
- session,
- quoteLimit
- ),
- })
- setNotice("")
- editor.current?.focus({ preventScroll: true })
- } catch (e) {
- setNotice(reason(e))
- }
- }
- function viewSource(quote: MessageQuote) {
- if (quote.sessionId !== session) return
- const row = transcript.current?.querySelector(
- `[data-message-id="${CSS.escape(quote.messageId)}"]`
- )
- if (!row) {
- setNotice("原文不在当前已加载的消息中,请先加载更早的消息。")
- return
- }
- row.scrollIntoView({ block: "center" })
- row.focus({ preventScroll: true })
- }
- const revisionSeen =
- config?.revision ??
- (index?.sessions.find((s) => s.id === session)?.revision === 0
- ? 0
- : undefined)
- async function changeOption(change: { mode: string } | { expertId: string }) {
- if (
- lock.current ||
- configRequest.current ||
- !channel?.canWrite ||
- current.current !== channel
- )
- return
- if (!session) {
- setNewOptions({ key, value: { ...newChoice, ...change } })
- return
- }
- if (!liveReady || revisionSeen === undefined) return
- const request = Symbol()
- configRequest.current = request
- const isCurrent = () =>
- configRequest.current === request && current.current === channel
- setConfiguring(true)
- setNotice("")
- try {
- await configureComposer(channel, session, revisionSeen, change)
- } catch (e) {
- if (isCurrent()) setNotice(reason(e))
- } finally {
- try {
- if (isCurrent()) {
- const page = await readHistory(channel, session)
- if (isCurrent())
- setReady((prior) =>
- prior?.ch === channel &&
- prior.id === session &&
- (prior.config.revision ?? -1) <= (page.config.revision ?? -1)
- ? {
- ...prior,
- config: page.config,
- turn: { ...prior.turn, modelState: page.turn.modelState },
- }
- : prior
- )
- }
- } catch {
- if (isCurrent()) {
- setReady(undefined)
- setNotice("未确认会话设置,请刷新后核对。")
- }
- }
- if (configRequest.current === request) {
- configRequest.current = null
- setConfiguring(false)
- }
- }
- }
- function select(id: string, p = "") {
- setMenu(false)
- if (id && id === session) return
- configRequest.current = null
- setConfiguring(false)
- // 新建页的执行权限只针对本次任务,不带到下一个项目或下一次新建。
- setNewOptions(undefined)
- setReady(undefined)
- setNotice("")
- navigate(
- {
- pathname,
- search: id ? "?" + new URLSearchParams({ session: id }) : "",
- },
- {
- state: { name, platform: state?.platform, projectId: p },
- replace: true,
- }
- )
- }
- useEffect(() => {
- let active = true
- const grant = restoreDeviceGrant(user)
- if (!validMachineId(machine) || !grant?.canReadSessions) {
- queueMicrotask(() => {
- if (active)
- setStatus(
- !validMachineId(machine)
- ? { phase: "failed", detail: "设备地址无效,请返回设备列表。" }
- : {
- phase: "failed",
- detail: "请授权工作台连接设备并访问会话。",
- needsAuthorization: true,
- }
- )
- })
- return () => {
- active = false
- }
- }
- const stop = connectWorkspaceDevice(user, machine, grant, (s, ch) => {
- if (s.needsAuthorization) {
- setIndex(undefined)
- try {
- sessionStorage.removeItem(sidebarCacheKey)
- } catch {
- /* 存储不可用。 */
- }
- }
- current.current = ch
- setChannel(ch)
- setStatus(s)
- })
- return () => {
- current.current = undefined
- stop()
- }
- }, [user, machine, attempt])
- useEffect(() => {
- if (!channel) return
- const listing = refreshedRead(
- async () => {
- const started = notices.turns.version
- return { started, value: await directory(channel) }
- },
- ({ value, started }) => {
- setIndex(value)
- try {
- const grant = restoreDeviceGrant(user)
- if (grant?.canReadSessions)
- sessionStorage.setItem(
- sidebarCacheKey,
- JSON.stringify({
- user,
- machine,
- expiresAt: grant.expiresAt,
- index: value,
- })
- )
- } catch {
- /* 写入失败不影响当前列表。 */
- }
- setBadges({
- ch: channel,
- ids: notices.turns.list(value.sessions, started),
- })
- setListError("")
- },
- (e) => setListError(reason(e)),
- 1500
- )
- const off = channel.listen((method, id, params) => {
- if (method === "_monkeyai/session/state") {
- notices.turns.observe(id, params)
- listing.schedule()
- }
- })
- void listing.run()
- return () => {
- listing.stop()
- off()
- }
- }, [channel, revision, notices, user, machine])
- async function authorize() {
- setAuthorizing(true)
- try {
- location.assign(
- await beginDeviceAuthorization(user, {
- machineId: machine,
- name,
- sessionId: session || undefined,
- projectId: !session && project ? project : undefined,
- })
- )
- } catch (e) {
- setNotice(reason(e))
- setAuthorizing(false)
- }
- }
- const usable =
- !!channel?.canWrite &&
- (session || !destination || !!selectedProject) &&
- (!session || (ready?.ch === channel && ready.id === session))
- const attachmentIssue = !channel?.canWrite
- ? "需要会话控制授权。"
- : !channel.fileGrant
- ? "请通过「添加附件」授权上传文件。"
- : !channel.uploads
- ? "当前设备不支持附件上传。"
- : ""
- function addFiles(incoming: File[]) {
- if (lock.current || pending !== undefined) return
- if (attachmentIssue || !channel?.uploads) {
- setNotice(attachmentIssue)
- return
- }
- try {
- const next = [...(drafts.read(key).files || [])]
- for (const file of incoming) {
- validateFile(file, channel.uploads)
- const missing = next.findIndex(
- (f) => !f.file && f.name === file.name && f.size === file.size
- )
- if (missing >= 0) next[missing] = { ...next[missing], file }
- else
- next.push({
- id: crypto.randomUUID(),
- name: file.name,
- size: file.size,
- file,
- })
- }
- update({ files: next })
- setNotice("")
- } catch (e) {
- setNotice(reason(e))
- }
- }
- const validInput =
- (draft.trim() || (files.length && !quotes.length)) &&
- (!files.length || (!attachmentIssue && files.every((f) => f.file)))
- async function send(selection?: import("@/lib/device-models").Selection) {
- if (
- !channel ||
- current.current !== channel ||
- pending !== undefined ||
- quotes.length > quoteLimit ||
- !usable ||
- lock.current ||
- configRequest.current ||
- !validInput ||
- (!session && selectedProject?.missing)
- )
- return
- lock.current = true
- setSending(true)
- setNotice("")
- let id = session
- let target = key
- let queueAttempted = false
- const uploaded: UploadedFile[] = []
- try {
- if (!id) {
- id = await createSession(channel, selectedProject, newChoice, selection)
- target = draftKey(user, machine, id, "")
- drafts.update(target, { text: draft, files })
- drafts.update(key, {
- text: "",
- files: undefined,
- destination: undefined,
- })
- // 离开设备页后,迟到的建会话回执不能把用户导航回来。
- if (current.current === channel) select(id)
- refresh((n) => n + 1)
- }
- for (const [i, entry] of files.entries()) {
- if (!channel.upload || !entry.file || current.current !== channel)
- throw new Error("附件来源或连接已变更。")
- const progress = (n: number) =>
- setNotice(
- "正在上传附件 " +
- (i + 1) +
- "/" +
- files.length +
- " · " +
- entry.name +
- " · " +
- (entry.size ? Math.floor((n * 100) / entry.size) : 100) +
- "%"
- )
- progress(0)
- uploaded.push(await channel.upload(id, entry.file, progress))
- }
- if (current.current !== channel) throw new Error("连接已变更。")
- const operationId = crypto.randomUUID()
- drafts.begin(target, draft, quotes, files, operationId)
- redraw((n) => n + 1)
- if (current.current !== channel) throw new Error("连接已变更。")
- queueAttempted = true
- await sendMessage(
- channel,
- id,
- draft.trim(),
- quotes,
- uploaded,
- operationId
- )
- if (current.current !== channel) throw new Error("连接已变更。")
- drafts.settle(target, true)
- for (const { uploadId } of uploaded)
- void channel
- .request("_monkeyai/uploads/cancel", { sessionId: id, uploadId })
- .catch(() => {})
- setNotice("设备已接收任务。")
- refresh((n) => n + 1)
- } catch (e) {
- if (queueAttempted) drafts.settle(target, false)
- else
- for (const { uploadId } of uploaded)
- void channel
- .request("_monkeyai/uploads/cancel", { sessionId: id, uploadId })
- .catch(() => {})
- setNotice(
- reason(e) +
- (files.length && id && !queueAttempted
- ? " 消息未发送,附件和草稿已保留。"
- : id
- ? " 请核对会话记录;不会自动重发。"
- : " 未确认会话是否创建,原文已保留。")
- )
- } finally {
- lock.current = false
- setSending(false)
- }
- }
- const title =
- index?.sessions.find((s) => s.id === session)?.title ||
- (session ? "当前会话" : "新会话")
- const isMobile = useIsMobile()
- const focusAfterDrawer = useRef(false)
- const [focusRequest, focusComposer] = useState(0)
- const directoryCache = useRef(null)
- const [collapsed, setCollapsed] = useState(false)
- const { branding } = useBranding()
- const nav = (
-
- }
- onNewSession={(p) => {
- focusAfterDrawer.current = isMobile
- select("", p)
- focusComposer((n) => n + 1)
- }}
- compact={!isMobile && collapsed}
- onToggle={() => (isMobile ? setMenu(false) : setCollapsed((v) => !v))}
- completed={badges && badges.ch === channel ? badges.ids : undefined}
- projects={index?.projects || []}
- sessions={index?.sessions || []}
- loaded={!!index}
- connected={!!channel}
- writable={!!channel?.canWrite}
- canBrowseFolders={!!channel?.canBrowseFolders}
- menuBusy={menuBusy}
- onAction={act}
- onReadFolder={readFolder}
- onMenuError={setMenuError}
- busy={sending}
- session={session}
- project={project}
- error={[menuError, listError].filter(Boolean).join(" ")}
- notice={menuNotice}
- onRefresh={() => refresh((n) => n + 1)}
- onSelect={(id, p) => {
- if (id && id === session) {
- setMenu(false)
- return
- }
- select(id, p)
- }}
- />
- )
- const composer = (inputHistory?: readonly string[]) => (
- s.expertId)
- .filter((id) => id && id !== "monkeyai-design")
- )
- )}
- optionsDisabled={
- !channel?.canWrite ||
- sending ||
- (!!session && (!liveReady || revisionSeen === undefined))
- }
- configuring={configuring}
- onOption={(change) => void changeOption(change)}
- onModelConfirmed={(next) =>
- setReady((prior) =>
- prior &&
- prior.ch === channel &&
- prior.id === session &&
- (prior.config.revision ?? -1) <= next.revision
- ? {
- ...prior,
- config: { ...prior.config, revision: next.revision },
- turn: { ...prior.turn, modelState: next },
- }
- : prior
- )
- }
- sending={sending}
- notice={notice}
- draft={draft}
- files={files}
- onFiles={addFiles}
- onRemoveFile={(id) => update({ files: files.filter((f) => f.id !== id) })}
- onAuthorizeFiles={
- channel?.canWrite && !channel.fileGrant && !authorizing
- ? () => void authorize()
- : undefined
- }
- attachmentIssue={attachmentIssue}
- editor={editor}
- quotes={quotes}
- quoteLimit={quoteLimit}
- onViewSource={viewSource}
- onRemoveQuote={(id) =>
- update({ quotes: quotes.filter((q) => q.messageId !== id) })
- }
- pending={sending ? undefined : pending}
- onDraft={(text) => update({ text })}
- onProject={(destination) => update({ destination })}
- onSend={(selection) => void send(selection)}
- disabled={
- configuring ||
- quotes.length > quoteLimit ||
- !validInput ||
- sending ||
- pending !== undefined ||
- !usable ||
- (!session && !!selectedProject?.missing)
- }
- />
- )
- return (
-
-
- {!isMobile && (
-
- )}
- {isMobile && (
-
{
- if (open) focusAfterDrawer.current = false
- setMenu(open)
- }}
- >
-
- }
- >
-
-
-
- focusAfterDrawer.current ? (editor.current ?? true) : true
- }
- >
- 项目和会话
- {nav}
-
-
- )}
-
- redraw((n) => n + 1)}
- submitting={sending ? session : undefined}
- />
- {(status.phase === "failed" || (channel && !channel.canWrite)) && (
-
-
- {channel
- ? "当前为只读访问。你可以阅读会话,授权后可发送任务。"
- : status.detail}
-
- {status.needsAuthorization || (channel && !channel.canWrite) ? (
-
- ) : (
- status.phase === "failed" &&
- validMachineId(machine) && (
-
- )
- )}
-
- )}
- {session ? (
- <>
-
- 0 &&
- pending === undefined &&
- !sending
- ? addQuote
- : undefined
- }
- key={session}
- session={session}
- channel={channel}
- onReady={onReady}
- onReuse={
- channel?.canWrite && !sending && pending === undefined
- ? (text) => {
- if (lock.current) return
- update({
- text: draft.trim()
- ? draft.trimEnd() + "\n" + text
- : text,
- })
- const input = editor.current
- input?.focus({ preventScroll: true })
- requestAnimationFrame(() => {
- if (input && document.activeElement === input)
- input.setSelectionRange(
- input.value.length,
- input.value.length
- )
- })
- }
- : undefined
- }
- />
- >
- ) : (
-
-
-
-
- {branding.product_name}
-
-
- {selectedProject
- ? "工作区:" + selectedProject.name
- : "有什么任务要交给这台设备?"}
-
- {composer()}
-
-
- )}
-
-
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-conversation.tsx b/monkeyai/web/src/pages/client/device-conversation.tsx
deleted file mode 100644
index dc11393cd..000000000
--- a/monkeyai/web/src/pages/client/device-conversation.tsx
+++ /dev/null
@@ -1,344 +0,0 @@
-import {
- Fragment,
- useCallback,
- useEffect,
- useLayoutEffect,
- useMemo,
- type ReactNode,
- type RefObject,
- useRef,
- useState,
-} from "react"
-import { Alert, AlertDescription } from "@/components/ui/alert"
-import { HugeiconsIcon } from "@hugeicons/react"
-import { Alert02Icon } from "@hugeicons/core-free-icons"
-import { friendlyError } from "@/lib/device-chat-errors"
-import { Button } from "@/components/ui/button"
-import { ArrowDown } from "lucide-react"
-import { DeviceReplyActivity } from "./device-reply-activity"
-import { ChatMessage } from "./device-chat-message"
-import type { DeviceChannel } from "@/lib/device-connection"
-import type { MessageQuote } from "@/lib/device-message-quotes"
-import {
- readHistory,
- readJoinedHistory,
- mergeLatest,
- replyActivity,
- refreshedRead,
- type HistoryWindow,
- type SessionSnapshot,
-} from "@/lib/device-workspace"
-
-export function DeviceConversation({
- channel,
- session,
- onReady,
- onReuse,
- onQuote,
- transcript: timeline,
- renderComposer,
-}: {
- channel?: DeviceChannel
- session: string
- onReady: (
- channel: DeviceChannel,
- session: string,
- snapshot: SessionSnapshot,
- updatedAt: string
- ) => void
- onQuote?: (quote: MessageQuote) => void
- transcript: RefObject
- renderComposer: (history?: readonly string[]) => ReactNode
- onReuse?: (text: string) => void
-}) {
- const [{ messages, older }, setHistory] = useState({
- messages: [],
- older: null,
- })
- const [synced, setSynced] = useState(),
- [status, setStatus] = useState("")
- const [sessionError, setSessionError] = useState("")
- const [error, setError] = useState(""),
- [olderError, setOlderError] = useState("")
- const [revision, retry] = useState(0),
- [away, setAway] = useState(false),
- [loadingOlder, setLoadingOlder] = useState(false)
- const history = useMemo(
- () =>
- messages.flatMap((m) => (m.recallText ? [m.recallText] : [])).reverse(),
- [messages]
- )
- const sentinel = useRef(null)
- const stick = useRef(true),
- tailIds = useRef | undefined>(undefined),
- generation = useRef(0),
- busy = useRef(false)
- const anchor = useRef<{ row: HTMLElement; top: number } | null>(null)
- const live = !!channel && synced === channel
- const activity = live && !error ? replyActivity(status, messages.at(-1)) : ""
- const remember = useCallback(() => {
- const el = timeline.current
- if (!el || stick.current) return
- const top = el.getBoundingClientRect().top
- const row = Array.from(
- el.querySelectorAll("[data-message-id]")
- ).find((r) => r.getBoundingClientRect().bottom > top)
- anchor.current = row ? { row, top: row.getBoundingClientRect().top } : null
- }, [])
- useEffect(() => {
- if (!channel) return
- const current = ++generation.current
- const controller = new AbortController()
- let subscribed = false
- const reader = refreshedRead(
- async () => {
- if (!subscribed && channel.canWrite) {
- await channel.request("_monkeyai/session/subscribe", {
- sessionId: session,
- })
- subscribed = true
- }
- return readJoinedHistory(
- channel,
- session,
- tailIds.current,
- controller.signal
- )
- },
- (page) => {
- remember()
- setHistory((previous) => mergeLatest(previous, page))
- tailIds.current = page.tailIds
- if (!busy.current) setLoadingOlder(false)
- setSynced(channel)
- setStatus(page.status)
- setSessionError(page.sessionError)
- setError("")
- onReady(channel, session, page, page.updatedAt)
- },
- (e) => setError(e instanceof Error ? e.message : "未能读取会话。")
- )
- const off = channel.listen((method, id) => {
- if (
- id === session &&
- (method === "session/update" || method.startsWith("_monkeyai/session/"))
- )
- reader.schedule()
- })
- void reader.run()
- const onVisible = () => {
- if (document.visibilityState === "visible") reader.schedule()
- }
- document.addEventListener("visibilitychange", onVisible)
- return () => {
- document.removeEventListener("visibilitychange", onVisible)
- generation.current = current + 1
- controller.abort()
- busy.current = false
- reader.stop()
- off()
- }
- }, [channel, session, revision, onReady, remember])
- useLayoutEffect(() => {
- const el = timeline.current,
- saved = anchor.current
- if (!el) return
- if (stick.current) el.scrollTop = el.scrollHeight
- else if (saved?.row.isConnected)
- el.scrollTop += saved.row.getBoundingClientRect().top - saved.top
- anchor.current = null
- }, [messages])
- const earlier = useCallback(async () => {
- if (!live || !channel || !older || busy.current) return
- const current = generation.current
- busy.current = true
- setLoadingOlder(true)
- try {
- const page = await readHistory(channel, session, older)
- if (current !== generation.current) return
- stick.current = false
- remember()
- setHistory((prior) =>
- prior.older !== older
- ? prior
- : {
- messages: [
- ...new Map(
- [...page.messages, ...prior.messages].map((m) => [m.id, m])
- ).values(),
- ],
- older: page.older === older ? null : page.older,
- }
- )
- setOlderError("")
- } catch (e) {
- if (current === generation.current)
- setOlderError(e instanceof Error ? e.message : "未能读取更早的消息。")
- } finally {
- if (current === generation.current) {
- busy.current = false
- setLoadingOlder(false)
- }
- }
- }, [live, channel, older, remember, session])
- useEffect(() => {
- const el = timeline.current,
- target = sentinel.current
- if (!el || !target || !live || olderError) return
- const observer = new IntersectionObserver(
- ([entry]) => {
- if (
- entry.isIntersecting &&
- (!stick.current || el.scrollHeight <= el.clientHeight)
- )
- void earlier()
- },
- { root: el, rootMargin: "240px 0px 0px" }
- )
- observer.observe(target)
- return () => observer.disconnect()
- }, [earlier, live, olderError, away])
- const conversation = (
-
-
{
- if (
- e.target instanceof Element &&
- e.target.closest("summary,.dc-user-toggle,.dc-trace-trigger")
- ) {
- stick.current = false
- setAway(true)
- }
- }}
- onScroll={(e) => {
- const el = e.currentTarget
- stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80
- setAway(!stick.current)
- }}
- >
-
- {older && (
-
-
- {olderError &&
{olderError}
}
-
- )}
- {error && (
-
- {error}{" "}
-
-
- )}
- {!error && !messages.some((m) => m.parts.length) && (
-
- {synced
- ? "这条会话还没有可显示的消息。"
- : channel
- ? "正在读取会话…"
- : "连接后读取会话。"}
-
- )}
- {messages.map(
- (m, i) =>
- m.parts.length > 0 && (
-
- {m.at !== undefined &&
- (i === 0 ||
- messages[i - 1].at === undefined ||
- new Date(m.at).toDateString() !==
- new Date(messages[i - 1].at!).toDateString()) && (
-
- {new Date(m.at).toLocaleDateString()}
-
- )}
-
-
- )
- )}
- {synced && !live && (
-
- {channel ? "正在同步会话…" : "连接已断开,显示上次同步的记录。"}
-
- )}
- {activity && (
-
- )}
- {sessionError && (
-
-
- {friendlyError(sessionError)}
-
- )}
-
-
- {away && (
-
- )}
-
- )
- return (
- <>
- {conversation}
-
- {renderComposer(live && !error && !loadingOlder ? history : undefined)}
-
- >
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-model-picker.tsx b/monkeyai/web/src/pages/client/device-model-picker.tsx
deleted file mode 100644
index 84ac0db8c..000000000
--- a/monkeyai/web/src/pages/client/device-model-picker.tsx
+++ /dev/null
@@ -1,563 +0,0 @@
-import { useEffect, useId, useRef, useState } from "react"
-import { Check } from "lucide-react"
-import { HugeiconsIcon } from "@hugeicons/react"
-import {
- AiBrain01Icon,
- ArrowDown01Icon,
- Settings01Icon,
-} from "@hugeicons/core-free-icons"
-import { Tabs as BaseTabs } from "@base-ui/react/tabs"
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover"
-import type { DeviceChannel } from "@/lib/device-connection"
-import type { useDeviceModelCatalog } from "./use-device-model-catalog"
-import { useBranding } from "@/hooks/use-branding"
-import {
- isRecord,
- modelState,
- switchSetting,
- thinkingLevel,
- type ChatModel,
- type ModelState,
- type Selection,
-} from "@/lib/device-models"
-
-import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
-import { modelBrand } from "@/lib/device-model-brand/model-brand"
-import { depthLabel, DeviceThinkingDepth } from "./device-thinking-depth"
-const kinds = { text: "对话", image: "图片", video: "视频" } as const
-const positiveCount = (n?: number): n is number =>
- typeof n === "number" && Number.isFinite(n) && n > 0
-const shortTokens = (n: number) =>
- n >= 1_000_000
- ? Math.round(n / 100_000) / 10 + "M"
- : n >= 1000
- ? Math.round(n / 1000) + "K"
- : String(Math.round(n))
-const groups = [
- { source: "系统模型", title: "团队", category: "team" },
- { source: "我的模型", title: "我创建的", category: "mine" },
- { source: "分享给我", title: "他人分享", category: "shared" },
-] as const
-const nameOrder = new Intl.Collator("zh-CN-u-co-pinyin", {
- numeric: true,
- sensitivity: "base",
-})
-
-function modelDetails(model: ChatModel, workspace: string) {
- const owner =
- model.group === "系统模型"
- ? workspace || "团队"
- : model.group === "我的模型"
- ? "我的"
- : model.owner.trim() || "共享"
- const rate =
- model.rate !== undefined && Number.isFinite(model.rate) && model.rate >= 0
- ? model.rate + "×"
- : "—"
- const title = [
- model.name,
- owner,
- model.group === "系统模型" && "积分倍率:" + rate,
- !model.ready && "模型不可用",
- ]
- .filter(Boolean)
- .join(" · ")
- return { owner, rate, title }
-}
-
-function ModelRow({
- model,
- category,
- selected,
- disabled,
- workspace,
- onSelect,
-}: {
- model: ChatModel
- category: (typeof groups)[number]["category"]
- selected: boolean
- disabled: boolean
- workspace: string
- onSelect: () => void
-}) {
- const brand = modelBrand(model.upstream || model.name)
- const { owner, rate, title } = modelDetails(model, workspace)
- return (
-
- )
-}
-export function DeviceModelPicker({
- channel,
- catalog,
- session,
- snapshot,
- draft,
- onDraft,
- blocked,
- onBusy,
- onConfirmed,
-}: {
- channel: DeviceChannel
- catalog: ReturnType
- session: string
- snapshot?: ModelState
- draft?: Selection
- onDraft: (s: Selection) => void
- blocked: false | "running" | "readonly"
- onBusy: (b: boolean) => void
- onConfirmed: (next: ModelState) => void
-}) {
- const [open, show] = useState(false),
- [query, search] = useState(""),
- [writeError, fail] = useState(""),
- [busy, setBusy] = useState(false),
- [confirmed, confirm] = useState()
- const [requestedKind, setKind] = useState("text")
- const { branding } = useBranding()
- const { models, loading, reload } = catalog
- const error = writeError || catalog.error
- const listRef = useRef(null)
- const panelId = useId()
- const lock = useRef(false),
- active = useRef(true)
- useEffect(() => {
- active.current = true
- return () => {
- active.current = false
- onBusy(false)
- }
- }, [onBusy])
- const state =
- confirmed && (!snapshot || confirmed.revision > snapshot.revision)
- ? confirmed
- : snapshot
- const value = session ? state : draft,
- model = models.find((m) => m.id === value?.model)
- const disabled =
- !!blocked || busy || !channel.canWrite || Boolean(session && !state)
- async function choose(change: Selection) {
- if (disabled || lock.current) return
- if (!session) {
- onDraft(change)
- return true
- }
- if (!state) return
- lock.current = true
- setBusy(true)
- onBusy(true)
- fail("")
- try {
- const next = await switchSetting(channel, session, state, change)
- if (active.current) {
- confirm(next)
- onConfirmed(next)
- }
- return true
- } catch (e) {
- if (active.current)
- fail(e instanceof Error ? e.message : "设备未确认切换。")
- // 冲突或断线后只回读,不重发写入。
- try {
- const page = await channel.history(session)
- if (
- active.current &&
- isRecord(page) &&
- isRecord(page.session) &&
- page.session.id === session
- )
- confirm(modelState(page.session))
- } catch {
- /* 保留原始错误 */
- }
- } finally {
- lock.current = false
- if (active.current) {
- setBusy(false)
- onBusy(false)
- }
- }
- }
- const currentMedia = (type: "image" | "video") =>
- models.find(
- (m) => m.kind === type && m.ready && m.id === value?.mediaModels?.[type]
- ) ?? models.find((m) => m.kind === type && m.ready)
- const media = { image: currentMedia("image"), video: currentMedia("video") }
- const tabs = (["text", "image", "video"] as const).filter(
- (k) => session || k === "text" || media[k]
- )
- const kind = tabs.includes(requestedKind) ? requestedKind : "text"
- const selected = kind === "text" ? value?.model : media[kind]?.id
- const visible = models
- .filter(
- (m) =>
- m.kind === kind &&
- (kind === "text" || m.ready) &&
- [
- m.name,
- m.upstream,
- m.owner,
- m.group,
- modelDetails(m, branding.workspace_name).owner,
- ]
- .join(" ")
- .toLocaleLowerCase()
- .includes(query.trim().toLocaleLowerCase())
- )
- .sort(
- (a, b) => nameOrder.compare(a.name, b.name) || a.id.localeCompare(b.id)
- )
- const used = snapshot?.context?.used
- const size = [snapshot?.context?.size, model?.window].find(positiveCount)
- const ratio = positiveCount(used) && size ? used / size : undefined
- const level =
- ratio === undefined
- ? undefined
- : ratio >= 1
- ? "full"
- : ratio >= 0.8
- ? "high"
- : undefined
- const percentage = ratio === undefined ? "" : Math.round(ratio * 100) + "%"
- const contextLabel = positiveCount(used)
- ? "上下文:已用 " +
- Math.round(used).toLocaleString("zh-CN") +
- " / 容量 " +
- (size ? Math.round(size).toLocaleString("zh-CN") : "—") +
- " tokens" +
- (percentage ? "(" + percentage + ")" : "")
- : ""
- const modelLabel =
- model?.name || value?.model || (session ? "默认模型" : "选择模型")
- const modelTitle = [
- !session && model
- ? modelDetails(model, branding.workspace_name).title
- : modelLabel,
- contextLabel,
- !session &&
- value?.thinking &&
- "思考深度:" + depthLabel(thinkingLevel(value.thinking)),
- !session && media.image && "图片:" + media.image.name,
- !session && media.video && "视频:" + media.video.name,
- ]
- .filter(Boolean)
- .join(" · ")
- return (
-
-
{
- show(v)
- if (v) setKind("text")
- search("")
- }}
- >
-
- {modelLabel}
- {level && (
-
- )}
-
-
- 1 || undefined}
- className="dw-model-popup w-[340px] max-w-[calc(100vw-16px)] gap-0 overflow-y-auto overscroll-contain p-1.5"
- >
- {!busy && (blocked || !channel.canWrite) && (
-
- {blocked === "running"
- ? "任务执行中,结束后才能切换模型和思考深度"
- : "当前只能查看模型,不能修改设置。"}
-
- )}
-
- {tabs.length > 1 && (
-
{
- setKind(k as keyof typeof kinds)
- search("")
- if (listRef.current) listRef.current.scrollTop = 0
- }}
- className="shrink-0 gap-0"
- >
- {
- if (
- ["ArrowLeft", "ArrowRight", "Home", "End"].includes(e.key)
- )
- e.stopPropagation()
- }}
- >
-
- {tabs.map((k) => (
-
- {kinds[k]}
-
- ))}
-
-
- )}
-
1 ? "tabpanel" : undefined}
- aria-labelledby={
- tabs.length > 1 ? panelId + "-" + kind : undefined
- }
- className="flex min-h-0 flex-auto flex-col"
- >
-
-
-
- {groups.map(({ source, title, category }) => {
- const rows = visible.filter((m) => m.group === source)
- return (
- rows.length > 0 && (
-
- {title}
- {rows.map((m) => (
- {
- if (kind === "text" && m.id === value?.model) {
- show(false)
- return
- }
- if (
- await choose(
- kind === "text"
- ? { model: m.id }
- : { mediaModels: { [kind]: m.id } }
- )
- )
- show(false)
- }}
- />
- ))}
-
- )
- )
- })}
-
- {!visible.length && (
-
- {loading
- ? "正在读取模型…"
- : error
- ? "目录暂不可用"
- : query
- ? "没有匹配的模型"
- : "此分类暂无模型"}
-
- )}
-
-
-
- {kind === "text" && model && model.levels.length > 1 && (
- void choose({ thinking })}
- />
- )}
- {kind === "text" && session && model && positiveCount(used) && (
- <>
-
-
-
- 上下文
-
- {shortTokens(used)}
- {size ? " / " + shortTokens(size) + " · " + percentage : ""}
-
-
- {ratio !== undefined && (
-
-
-
- )}
-
-
- {level
- ? "快满了,压缩后可以继续长对话"
- : "释放上下文空间,继续对话"}
-
-
-
-
- >
- )}
- {busy && (
-
- 正在切换…
-
- )}
- {error && (
-
- {error}{" "}
-
-
- )}
-
-
-
-
-
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-navigation.tsx b/monkeyai/web/src/pages/client/device-navigation.tsx
deleted file mode 100644
index 8c0bae921..000000000
--- a/monkeyai/web/src/pages/client/device-navigation.tsx
+++ /dev/null
@@ -1,734 +0,0 @@
-import {
- useEffect,
- useMemo,
- useRef,
- useState,
- type ComponentProps,
- type ReactNode,
-} from "react"
-import { RefreshCw } from "lucide-react"
-import { HugeiconsIcon } from "@hugeicons/react"
-import {
- Alert02Icon,
- Archive02Icon,
- ArchiveRestoreIcon,
- Cancel01Icon,
- CheckmarkSquare02Icon,
- Delete02Icon,
- Edit02Icon,
- Folder01Icon,
- Folder02Icon,
- FolderOpenIcon,
- MoreHorizontalIcon,
- MessageAdd02Icon,
- NoteEditIcon,
- PinIcon,
- PinOffIcon,
- SidebarLeftIcon,
-} from "@hugeicons/core-free-icons"
-import { Button } from "@/components/ui/button"
-import { WorkspaceSettings } from "./workspace-settings"
-import { WorkspaceIdentity } from "./workspace-identity"
-import { BrandLogo } from "@/components/brand-logo"
-import { useBranding } from "@/hooks/use-branding"
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-import type { Project, Session } from "@/lib/device-workspace"
-import type {
- SidebarAction,
- SidebarActionResult,
-} from "@/lib/device-sidebar-actions"
-import {
- SidebarDialog,
- type SidebarPrompt,
- type ReadFolder,
-} from "./device-sidebar-dialog"
-import { SidebarSearch } from "./device-sidebar-search"
-import { DeviceSessionTitle } from "./device-session-title"
-import { DeviceSessionAvatar } from "./device-session-avatar"
-import { timeGroup, timestamp } from "./device-sidebar-groups"
-import "./device-sidebar-list.css"
-
-type IconType = ComponentProps["icon"]
-function Entry({
- icon,
- label,
- onClick,
- disabled,
- danger,
-}: {
- icon: IconType
- label: string
- onClick: () => void
- disabled?: boolean
- danger?: boolean
-}) {
- return (
-
-
- {label}
-
- )
-}
-
-export function DeviceNavigation({
- remoteConnection,
- onNewSession,
- compact,
- onToggle,
- projects,
- sessions,
- completed,
- session,
- project,
- loaded,
- connected,
- writable,
- canBrowseFolders,
- menuBusy,
- onAction,
- onReadFolder,
- onMenuError,
- busy,
- error,
- notice,
- onSelect,
- onRefresh,
-}: {
- remoteConnection: ReactNode
- onNewSession: (project?: string) => void
- compact: boolean
- onToggle: () => void
- projects: Project[]
- sessions: Session[]
- completed?: ReadonlySet
- session: string
- project: string
- loaded: boolean
- connected: boolean
- writable: boolean
- canBrowseFolders: boolean
- menuBusy: boolean
- onAction: (op: SidebarAction) => Promise
- onReadFolder: ReadFolder
- onMenuError: (message: string) => void
- busy: boolean
- error: string
- notice: string
- onSelect: (id: string, project?: string) => void
- onRefresh: () => void
-}) {
- const { branding, workspaceLabel } = useBranding()
- const toggleRef = useRef(null)
- const refocus = useRef(false)
- useEffect(() => {
- if (refocus.current) toggleRef.current?.focus({ preventScroll: true })
- refocus.current = false
- }, [compact])
- const toggleLabel = compact ? "展开侧栏" : "收起侧栏"
- const foldButton = (
-
- )
- const [opened, setOpened] = useState>({})
- const scroll = useRef(null)
- const opener = useRef(null)
- const [dialog, setDialog] = useState<{
- target: SidebarPrompt
- returnTo: HTMLElement | null
- } | null>(null)
- const [picked, setPicked] = useState>(() => new Set())
- const lastPick = useRef("")
- const selected = sessions.filter(
- (s) => picked.has(s.id) && s.status !== "running"
- )
- const blocked = !writable || menuBusy || busy
- const prompt = (target: SidebarPrompt) =>
- setDialog({ target, returnTo: opener.current })
- const confirmDelete = (items: Session[]) => {
- if (items.length)
- prompt({
- kind: "delete",
- ids: items.map((s) => s.id),
- name: items[0].title,
- operationId: crypto.randomUUID(),
- })
- }
- function visibleIds() {
- return Array.from(
- scroll.current?.querySelectorAll("[data-pick-id]") ?? [],
- (e) => e.dataset.pickId!
- )
- }
- function pick(s: Session, range = false) {
- if (s.status === "running") return
- const visible = visibleIds(),
- a = visible.indexOf(lastPick.current),
- b = visible.indexOf(s.id)
- const ids =
- range && a >= 0 && b >= 0
- ? visible.slice(Math.min(a, b), Math.max(a, b) + 1)
- : [s.id]
- lastPick.current = s.id
- setPicked((prev) => {
- const next = new Set(prev)
- for (const id of ids) {
- if (prev.has(s.id)) next.delete(id)
- else next.add(id)
- }
- return next
- })
- }
- async function flag(
- items: Session[],
- field: "pinned" | "archived",
- value: boolean,
- clear = false
- ) {
- try {
- const result = await onAction({
- kind: "flag",
- ids: items.map((s) => s.id),
- field,
- value,
- })
- if (clear)
- setPicked((prev) => {
- const next = new Set(prev)
- for (const id of result.succeeded) next.delete(id)
- return next
- })
- } catch (e) {
- onMenuError(e instanceof Error ? e.message : "设备操作失败。")
- }
- }
- function note() {
- return (
- !canBrowseFolders && (
-
- {!connected
- ? "设备未连接"
- : !writable
- ? "当前设备连接为只读"
- : "当前连接不支持浏览设备目录"}
-
- )
- )
- }
- const sorted = useMemo(
- () =>
- [...sessions].sort(
- (a, b) => timestamp(b.updatedAt) - timestamp(a.updatedAt)
- ),
- [sessions]
- )
- const current = sorted.find((s) => s.id === session)
- const context = projects.find(
- (p) => p.id === (session ? current?.projectId : project)
- )
- const archived = sorted
- .filter((s) => s.archivedAt)
- .sort((a, b) => timestamp(b.archivedAt) - timestamp(a.archivedAt))
- const pinned = sorted.filter((s) => s.pinned && !s.archivedAt)
- const regular = sorted.filter((s) => !s.pinned && !s.archivedAt)
- const ids = new Set(projects.map((p) => p.id))
- const loose = regular.filter((s) => !ids.has(s.projectId))
- const archiveOpen = opened.archive ?? !!current?.archivedAt
- function toggle(key: string, value: boolean) {
- setOpened((prev) => ({ ...prev, [key]: !value }))
- }
- function select(id: string, p?: string) {
- const target = sorted.find((s) => s.id === id)
- if (target || p)
- setOpened((prev) => ({
- ...prev,
- ...(target?.archivedAt ? { archive: true } : {}),
- [(target?.archivedAt ? "a:" : "p:") + (target?.projectId || p || "")]:
- true,
- }))
- onSelect(id, p)
- }
- useEffect(() => {
- const el = scroll.current?.querySelector(
- '[aria-current="page"]'
- )
- if (el) el.scrollIntoView({ block: "nearest" })
- }, [session, current?.id, current?.pinned, current?.archivedAt, loaded])
- function row(s: Session) {
- const running = s.status === "running",
- done = completed?.has(s.id)
- const target = {
- id: s.id,
- name: s.title,
- cwd: s.cwd,
- userTitle: s.userTitle,
- }
- return (
-
-
-
- {
- opener.current = e.currentTarget
- }}
- className="dw-item-action"
- >
-
-
-
- {note()}
- prompt({ ...target, kind: "renameSession" })}
- />
- prompt({ ...target, kind: "browse" })}
- />
-
- {!s.archivedAt && (
- void flag([s], "pinned", !s.pinned)}
- />
- )}
- void flag([s], "archived", !s.archivedAt)}
- />
- pick(s)}
- />
-
- confirmDelete([s])}
- />
-
-
-
- )
- }
- function folder(p: Project, items: Session[], archive = false) {
- const target = { id: p.id, name: p.name, cwd: p.cwd }
- const key = (archive ? "a:" : "p:") + p.id
- const active =
- context?.id === p.id &&
- (archive ? !!current?.archivedAt : !current?.archivedAt)
- const expanded = opened[key] ?? active
- const missing = !archive && p.missing
- return (
-
-
-
- {!archive && (
-
- {
- opener.current = e.currentTarget
- }}
- className="dw-item-action"
- >
-
-
-
- {note()}
- select("", p.id)}
- />
- prompt({ ...target, kind: "browse" })}
- />
-
- prompt({ ...target, kind: "renameProject" })}
- />
- prompt({ ...target, kind: "relocate" })}
- />
- prompt({ ...target, kind: "removeProject" })}
- />
-
-
- )}
-
- {expanded && items.length > 0 && (
-
{items.map(row)}
- )}
-
- )
- }
- return (
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-queue.css b/monkeyai/web/src/pages/client/device-queue.css
deleted file mode 100644
index dc717f2fd..000000000
--- a/monkeyai/web/src/pages/client/device-queue.css
+++ /dev/null
@@ -1,212 +0,0 @@
-.dq-messages {
- width: 100%;
- min-width: 0;
- padding: 9px 0 7px;
- border-bottom: 1px solid
- color-mix(in oklch, var(--foreground) 7%, transparent);
- color: var(--foreground);
- font-size: 12px;
- font-weight: 400;
- cursor: default;
-}
-.dq-header {
- display: flex;
- align-items: center;
- gap: 7px;
- min-height: 22px;
- padding: 0 14px 3px;
-}
-.dq-title {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- margin-right: auto;
- padding: 1px 6px;
- border: 0;
- border-radius: 6px;
- appearance: none;
- background: none;
- color: var(--muted-foreground);
- font: inherit;
- font-size: 12px;
- font-weight: 500;
- cursor: pointer;
-}
-.dq-title:hover {
- color: var(--foreground);
-}
-.dq-title[aria-expanded="true"] {
- background: color-mix(in oklch, var(--foreground) 6%, transparent);
-}
-.dq-title:focus-visible {
- outline: 2px solid var(--ring);
- outline-offset: 2px;
-}
-.dq-title svg {
- opacity: 0.55;
- transition: transform 0.15s;
-}
-.dq-count {
- color: var(--muted-foreground);
- font-size: 12px;
- opacity: 0.7;
- font-variant-numeric: tabular-nums;
-}
-.dq-state {
- color: var(--muted-foreground);
- font-size: 12px;
-}
-.dq-resume {
- height: 21px;
- padding-inline: 5px;
- font-weight: 400;
- color: var(--muted-foreground);
-}
-.dq-list {
- --list-drop-start: 17px;
- max-height: 132px;
- overflow-y: auto;
- scrollbar-width: none;
- padding: 3px 10px;
- margin: 0;
- list-style: none;
-}
-.dq-list::-webkit-scrollbar {
- display: none;
-}
-.dq-item {
- position: relative;
- display: flex;
- align-items: center;
- gap: 6px;
- padding: 3px 3px 3px 1px;
- border-radius: 5px;
- outline: none;
-}
-.dq-item:hover,
-.dq-item:focus-within {
- background: color-mix(in oklch, var(--foreground) 3%, transparent);
-}
-.dq-item:focus-visible {
- box-shadow: inset 0 0 0 1px var(--ring);
-}
-.dq-grip {
- display: flex;
- flex-shrink: 0;
- justify-content: center;
- align-items: center;
- width: 15px;
- height: 22px;
- color: var(--muted-foreground);
- opacity: 0.35;
- cursor: grab;
-}
-.dq-item:hover .dq-grip,
-.dq-item:focus-within .dq-grip {
- opacity: 0.75;
-}
-.dq-content {
- display: flex;
- flex: 1;
- flex-direction: column;
- align-items: stretch;
- gap: 6px;
- min-width: 0;
-}
-.dq-content > .dq-state {
- flex-shrink: 0;
- white-space: nowrap;
-}
-.dq-text {
- flex: 0 1 auto;
- min-width: 0;
- overflow: hidden;
- margin: 0;
- white-space: nowrap;
- text-overflow: ellipsis;
- line-height: 22px;
- user-select: text;
-}
-.dq-actions {
- display: flex;
- flex-shrink: 0;
- align-items: center;
- gap: 1px;
-}
-.dq-actions button {
- width: 22px;
- height: 22px;
- color: var(--muted-foreground);
-}
-.dq-actions button:hover {
- color: var(--foreground);
-}
-.dq-secondary-action {
- opacity: 0;
-}
-.dq-item:hover .dq-secondary-action,
-.dq-item:focus-within .dq-secondary-action {
- opacity: 1;
-}
-.dq-send-now {
- opacity: 0.5;
-}
-.dq-item:hover .dq-send-now,
-.dq-item:focus-within .dq-send-now {
- opacity: 1;
-}
-.dq-warning {
- margin: 0;
- padding: 5px 14px;
- color: var(--muted-foreground);
- font-size: 12px;
-}
-@media (hover: none) {
- .dq-secondary-action {
- opacity: 0.7;
- }
-}
-@media (prefers-reduced-motion: reduce) {
- .dq-title svg {
- transition: none;
- }
-}
-.dq-title[aria-expanded="false"] svg {
- transform: rotate(-90deg);
-}
-.dq-actions button {
- display: grid;
- place-items: center;
- border-radius: 5px;
-}
-.dq-actions button:hover:not(:disabled) {
- background: var(--muted);
-}
-.dq-messages button:focus-visible {
- outline: 2px solid var(--ring);
- outline-offset: -2px;
-}
-.dq-messages button:disabled {
- cursor: default;
- opacity: 0.35;
-}
-.dq-editor {
- padding: 4px 16px;
-}
-.dw-frame .dq-editor textarea {
- border: 1px solid var(--border);
- border-radius: 6px;
- padding: 6px 8px;
- font-size: 13px;
- min-height: 48px;
-}
-.dq-warning button {
- text-decoration: underline;
-}
-@media (hover: none) {
- .dq-actions button,
- .dq-grip {
- min-width: 30px;
- min-height: 32px;
- }
-}
diff --git a/monkeyai/web/src/pages/client/device-queue.tsx b/monkeyai/web/src/pages/client/device-queue.tsx
deleted file mode 100644
index accd3d5a6..000000000
--- a/monkeyai/web/src/pages/client/device-queue.tsx
+++ /dev/null
@@ -1,472 +0,0 @@
-import {
- useEffect,
- useImperativeHandle,
- useRef,
- useState,
- type Ref,
-} from "react"
-import { Button } from "@/components/ui/button"
-import {
- ArrowUpRight,
- ChevronDown,
- GripVertical,
- Pencil,
- Play,
- X,
-} from "lucide-react"
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-import "./device-queue.css"
-import type { DeviceChannel } from "@/lib/device-connection"
-import type { Preparation } from "@/lib/device-turn"
-import { refreshedRead } from "@/lib/device-workspace"
-
-const object = (v: unknown): v is Record =>
- !!v && typeof v === "object"
-function snapshot(result: unknown, session: string) {
- if (!object(result) || result.sessionId !== session || !object(result.queue))
- throw new Error("设备未返回当前会话的队列。")
- const q = result.queue
- if (!Array.isArray(q.messages) || typeof q.paused !== "boolean")
- throw new Error("设备返回的队列格式无效。")
- const messages = q.messages.map((m: unknown) => {
- if (!object(m) || typeof m.id !== "string" || typeof m.text !== "string")
- throw new Error("待发消息格式无效。")
- const restricted =
- [m.attachments, m.quotes, m.canvasNodes].some(
- (v) => v != null && (!Array.isArray(v) || v.length > 0)
- ) || !!m.quote
- return {
- id: m.id,
- text: m.text,
- restricted,
- editing: Array.isArray(q.editingIds) && q.editingIds.includes(m.id),
- submitting: q.submittingId === m.id,
- uncertain:
- q.dispatchingId === m.id ||
- (object(m.steer) && m.steer.state === "unconfirmed"),
- steering: !!m.steer,
- }
- })
- const preparation =
- typeof q.preparationId === "string" &&
- q.submittingId &&
- typeof result.eventSeq === "number"
- ? { id: q.preparationId, seq: result.eventSeq }
- : undefined
- return {
- paused: q.paused,
- submitting: !!q.submittingId,
- preparing: q.preparing === true,
- messages,
- preparation,
- }
-}
-type Queue = ReturnType
-export type QueueDispatch = {
- channel: DeviceChannel
- session: string
- submitting: boolean
- hasMessages: boolean
- preparing: boolean
- preparation?: Preparation
-}
-type Edit = { id: string; editId: string; text: string }
-const reason = (e: unknown) =>
- e instanceof Error ? e.message : "设备未确认队列操作。"
-const method = "_monkeyai/session/queue"
-
-export function DeviceQueue({
- channel,
- session,
- blocked,
- onDispatch,
- ref,
-}: {
- channel: DeviceChannel
- session: string
- blocked: boolean
- onDispatch: (value: QueueDispatch | undefined) => void
- ref: Ref<{ next(): void }>
-}) {
- const [queue, setQueue] = useState()
- const [collapsed, setCollapsed] = useState(false)
- const [error, setError] = useState("")
- const [busy, setBusy] = useState(false)
- const [edit, setEdit] = useState()
- const lease = useRef(undefined)
- const live = useRef(false),
- lock = useRef(false),
- version = useRef(0)
- const reload = useRef<() => void>(() => {})
- useEffect(() => {
- live.current = true
- const reader = refreshedRead(
- async () => {
- const rev = version.current
- return { rev, value: snapshot(await channel.queue(session), session) }
- },
- ({ rev, value }) => {
- if (rev === version.current && !lock.current) {
- setQueue(value)
- onDispatch({
- channel,
- session,
- submitting: value.submitting,
- hasMessages: value.messages.length > 0,
- preparing: value.preparing,
- preparation: value.preparation
- ? { channel, session, ...value.preparation }
- : undefined,
- })
- }
- },
- (e) => {
- setQueue(undefined)
- onDispatch(undefined)
- setError(reason(e))
- }
- )
- reload.current = reader.schedule
- const off = channel.listen((m, id) => {
- if (m === "_monkeyai/session/state" && id === session) reader.schedule()
- })
- void reader.run()
- return () => {
- live.current = false
- off()
- reader.stop()
- if (lease.current) {
- const { id, editId } = lease.current
- void channel
- .request(method, {
- sessionId: session,
- action: "endEdit",
- id,
- editId,
- })
- .catch(() => {})
- }
- }
- }, [channel, session, onDispatch])
- const disabled = blocked || busy || !channel.canWrite
- async function act(
- action: string,
- fields: Record = {},
- start?: Edit
- ) {
- if (disabled || lock.current) return
- lock.current = true
- version.current++
- setBusy(true)
- setError("")
- if (start) lease.current = start
- try {
- const reply = await channel.request(method, {
- sessionId: session,
- action,
- ...fields,
- ...(action === "sendNow"
- ? { _meta: { operationId: crypto.randomUUID() } }
- : {}),
- })
- if (!object(reply) || reply.sessionId !== session)
- throw new Error("设备未确认当前会话的队列操作。")
- if (!live.current) return
- if (start) setEdit(start)
- if (action === "endEdit" || action === "update") {
- lease.current = undefined
- setEdit(undefined)
- }
- } catch (e) {
- if (live.current) {
- setError(reason(e) + " 请核对最新队列。")
- // 开始编辑的回执可能丢失,保留原令牌供用户释放,不重放写入。
- if (start) setEdit(start)
- }
- } finally {
- if (live.current) {
- version.current++
- lock.current = false
- setBusy(false)
- setQueue(undefined)
- reload.current()
- }
- }
- }
- const eligible = (m: Queue["messages"][number]) =>
- !m.restricted && !m.editing && !m.submitting && !m.steering && !m.uncertain
- useImperativeHandle(ref, () => ({
- next() {
- if (!queue || queue.paused || queue.submitting || edit) return
- const first = queue.messages.find(eligible)
- if (first) void act("sendNow", { id: first.id })
- },
- }))
- if (!error && !edit && !queue?.messages.length) return null
- return (
-
-
-
- {queue?.paused && (
- <>
- {" "}
-
已暂停
-
- >
- )}
-
- {error && (
-
- {error}{" "}
-
-
- )}
- {edit && (
-
-
- )}
-
- {queue?.messages.map((m, i) => (
-
- ))}
-
-
- )
-}
-
-function QueueRow({
- queue,
- i,
- disabled,
- act,
-}: {
- queue: Queue
- i: number
- disabled: boolean
- act: (
- action: string,
- fields: Record,
- start?: Edit
- ) => Promise
-}) {
- const m = queue.messages[i]
- const locked =
- disabled ||
- m.restricted ||
- m.editing ||
- m.submitting ||
- (m.steering && !m.uncertain)
- const movable = !locked && !m.uncertain
- const move = (down: boolean) => {
- if (!movable || (down ? i === queue.messages.length - 1 : i === 0)) return
- void act("move", {
- id: m.id,
- beforeId: down
- ? (queue.messages[i + 2]?.id ?? null)
- : queue.messages[i - 1].id,
- })
- }
- const state = m.restricted
- ? "含附件或引用,请在客户端操作"
- : m.submitting
- ? "正在提交…"
- : m.editing
- ? "编辑中"
- : m.uncertain
- ? "发送结果待确认,请先核对记录"
- : m.steering
- ? "已交付,等待接收"
- : ""
- const sendLabel = m.uncertain ? "核对后重发" : "立即发送"
- return (
- {
- if (
- !disabled &&
- e.dataTransfer.types.includes("application/x-dw-queue")
- )
- e.preventDefault()
- }}
- onDrop={(e) => {
- const id = e.dataTransfer.getData("application/x-dw-queue")
- const source = queue.messages.find((item) => item.id === id)
- if (
- disabled ||
- !source ||
- source.restricted ||
- source.editing ||
- source.submitting ||
- source.uncertain ||
- source.steering ||
- id === m.id
- )
- return
- e.preventDefault()
- const rect = e.currentTarget.getBoundingClientRect()
- const beforeId =
- e.clientY < rect.top + rect.height / 2
- ? m.id
- : (queue.messages[i + 1]?.id ?? null)
- if (beforeId !== id) void act("move", { id, beforeId })
- }}
- >
-
- 1}
- onDragStart={(e) => {
- e.dataTransfer.setData("application/x-dw-queue", m.id)
- e.dataTransfer.effectAllowed = "move"
- }}
- onKeyDown={(e) => {
- if (e.altKey && ["ArrowDown", "ArrowUp"].includes(e.key)) {
- e.preventDefault()
- move(e.key === "ArrowDown")
- }
- }}
- >
-
-
-
- move(false)}>
- 上移
-
- move(true)}
- >
- 下移
-
-
-
-
-
- {m.text}
-
- {state &&
{state}}
-
- {!m.restricted && !m.editing && (
-
-
-
-
-
- )}
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-reply-activity.tsx b/monkeyai/web/src/pages/client/device-reply-activity.tsx
deleted file mode 100644
index c63fe4dae..000000000
--- a/monkeyai/web/src/pages/client/device-reply-activity.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-import { useEffect, useMemo, useReducer } from "react"
-import type { Message } from "@/lib/device-workspace"
-
-function duration(ms: number) {
- const total = Math.max(1, Math.round(ms / 1000)),
- hours = Math.floor(total / 3600),
- minutes = Math.floor(total / 60) % 60,
- seconds = total % 60
- if (hours) return hours + "小时" + (minutes ? minutes + "分钟" : "")
- return (minutes ? minutes + "分钟" : "") + (seconds ? seconds + "秒" : "")
-}
-
-export function DeviceReplyActivity({
- label,
- last,
-}: {
- label: string
- last?: Message
-}) {
- const message =
- last?.role === "assistant" && last.endedAt === undefined ? last : undefined
- const busy =
- message?.parts.some(
- (p) =>
- p.type === "tool_call" &&
- (p.status === "pending" || p.status === "in_progress")
- ) ?? false
- const at = message?.at,
- id = message?.id
- // 设备时间只与设备起点相减;快照到达后的增量用本机时钟。
- const seen = useMemo(() => ({ at, id, local: performance.now() }), [at, id])
- const quiet = useMemo(
- () => ({ seen, busy, local: performance.now() }),
- [seen, busy]
- )
- const [, tick] = useReducer((n) => n + 1, 0)
- useEffect(() => {
- const timer = setInterval(tick, 1000)
- return () => clearInterval(timer)
- }, [])
- const now = performance.now(),
- stalled = !busy && now - quiet.local >= 20000
- const verb = stalled ? "等待模型响应…" : label
- const elapsed =
- at !== undefined && message?.startedAt !== undefined
- ? duration(
- Math.max(0, at - message.startedAt) + Math.max(0, now - seen.local)
- )
- : undefined
- return (
-
-
- {[0, 1, 2, 7, -1, 3, 6, 5, 4].map((step, i) => (
-
- ))}
-
-
-
- {verb}
-
- {elapsed && {elapsed}}
-
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-session-avatar.tsx b/monkeyai/web/src/pages/client/device-session-avatar.tsx
deleted file mode 100644
index 30a82626c..000000000
--- a/monkeyai/web/src/pages/client/device-session-avatar.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { HugeiconsIcon } from "@hugeicons/react"
-import { GraduationCapIcon } from "@hugeicons/core-free-icons"
-import { memo, type CSSProperties } from "react"
-import { expertAvatarColors } from "@/lib/device-expert-color"
-import general from "@/assets/sidebar-general-assistant.png"
-import design from "@/assets/sidebar-design-expert.png"
-
-export const DeviceSessionAvatar = memo(function DeviceSessionAvatar({
- expertId,
-}: {
- expertId: string
-}) {
- const src = !expertId
- ? general
- : expertId === "monkeyai-design"
- ? design
- : undefined
- const name = !expertId ? "通用助理" : src ? "设计专家" : expertId
- return (
-
- {src ? (
-
- ) : (
-
- )}
-
- )
-})
diff --git a/monkeyai/web/src/pages/client/device-session-title.css b/monkeyai/web/src/pages/client/device-session-title.css
deleted file mode 100644
index 8669448eb..000000000
--- a/monkeyai/web/src/pages/client/device-session-title.css
+++ /dev/null
@@ -1,40 +0,0 @@
-.dw-row > .dw-session-title {
- --dw-title-fade: 26px;
- --dw-title-clear: 0px;
- min-width: 0;
- text-overflow: clip;
- mask-image: linear-gradient(
- to right,
- black calc(100% - var(--dw-title-fade)),
- transparent calc(100% - var(--dw-title-clear))
- );
-}
-.dw-session-title > span {
- display: block;
- width: max-content;
-}
-.dw-session-row:is(
- :hover,
- :focus-within,
- :has(.dw-item-action[aria-expanded="true"])
- )
- .dw-session-title {
- --dw-title-fade: 34px;
- --dw-title-clear: 18px;
-}
-@media (max-width: 47.999rem), (hover: none) {
- .dw-row > .dw-session-title {
- --dw-title-fade: 34px;
- --dw-title-clear: 18px;
- }
-}
-@media (prefers-reduced-motion: reduce) {
- .dw-row > .dw-session-title {
- margin-inline-end: 18px;
- mask-image: none;
- text-overflow: ellipsis;
- }
- .dw-session-title > span {
- display: inline;
- }
-}
diff --git a/monkeyai/web/src/pages/client/device-session-title.tsx b/monkeyai/web/src/pages/client/device-session-title.tsx
deleted file mode 100644
index e1ac88d98..000000000
--- a/monkeyai/web/src/pages/client/device-session-title.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-import { useEffect, useRef } from "react"
-import "./device-session-title.css"
-
-const delayMs = 300
-const pixelsPerSecond = 40
-
-export function DeviceSessionTitle({ title }: { title: string }) {
- const frame = useRef(null)
- const label = useRef(null)
-
- useEffect(() => {
- const clip = frame.current
- const text = label.current
- const button = clip?.closest("button")
- const row = button?.closest(".dw-session-row")
- const menu = row?.querySelector(".dw-item-action")
- if (!clip || !text || !button || !row || !menu) return
-
- const motion = window.matchMedia("(prefers-reduced-motion: reduce)")
- let active = false
- let timer: number | undefined
- let animation: Animation | undefined
- let lastDistance: number | undefined
-
- function move() {
- if (!active || !clip || !text) return
- const fade =
- parseFloat(
- getComputedStyle(clip).getPropertyValue("--dw-title-fade")
- ) || 0
- const distance = Math.max(
- 0,
- text.getBoundingClientRect().width -
- clip.getBoundingClientRect().width +
- fade
- )
- if (distance === lastDistance) return
- lastDistance = distance
- animation?.cancel()
- if (!distance) return
-
- // 与客户端一样,长标题只延长匀速段,不拉长起停时间。
- const ramp = Math.min(0.2, distance / (2 * pixelsPerSecond))
- const duration = distance / pixelsPerSecond + ramp
- const edge = (pixelsPerSecond * ramp) / 2
- const shift = (px: number) => `translateX(${-px}px)`
- animation = text.animate(
- [
- {
- transform: shift(0),
- offset: 0,
- easing: "cubic-bezier(.333333,0,.666667,.333333)",
- },
- { transform: shift(edge), offset: ramp / duration },
- {
- transform: shift(distance - edge),
- offset: 1 - ramp / duration,
- easing: "cubic-bezier(.333333,.666667,.666667,1)",
- },
- { transform: shift(distance), offset: 1 },
- ],
- { duration: duration * 1000, fill: "forwards" }
- )
- }
- const resize = new ResizeObserver(move)
- function reset() {
- window.clearTimeout(timer)
- resize.disconnect()
- animation?.cancel()
- lastDistance = undefined
- }
- const update = () => {
- const next =
- !motion.matches &&
- (row.matches(":hover") ||
- !!row.querySelector(":focus-visible") ||
- menu.getAttribute("aria-expanded") === "true")
- if (next === active) return
- active = next
- reset()
- if (active)
- timer = window.setTimeout(() => {
- move()
- resize.observe(clip)
- resize.observe(text)
- }, delayMs)
- }
- const syncMotion = () => {
- if (motion.matches) button.title = title
- else button.removeAttribute("title")
- update()
- }
- const events = ["mouseenter", "mouseleave", "focusin", "focusout"]
- for (const event of events) row.addEventListener(event, update)
- const menuState = new MutationObserver(update)
- menuState.observe(menu, {
- attributes: true,
- attributeFilter: ["aria-expanded"],
- })
- motion.addEventListener("change", syncMotion)
- syncMotion()
- return () => {
- reset()
- menuState.disconnect()
- motion.removeEventListener("change", syncMotion)
- for (const event of events) row.removeEventListener(event, update)
- }
- }, [title])
-
- return (
-
- {title}
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-sidebar-dialog.tsx b/monkeyai/web/src/pages/client/device-sidebar-dialog.tsx
deleted file mode 100644
index 34fde96e4..000000000
--- a/monkeyai/web/src/pages/client/device-sidebar-dialog.tsx
+++ /dev/null
@@ -1,365 +0,0 @@
-import { useEffect, useRef, useState } from "react"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog"
-import type {
- FolderPage,
- SidebarAction,
- SidebarActionResult,
-} from "@/lib/device-sidebar-actions"
-
-export type SidebarPrompt =
- | {
- kind:
- | "renameProject"
- | "renameSession"
- | "relocate"
- | "removeProject"
- | "browse"
- id: string
- name: string
- cwd: string
- userTitle?: boolean
- }
- | { kind: "delete"; ids: string[]; name: string; operationId: string }
-export type ReadFolder = (
- path: string,
- offset?: number,
- revision?: string
-) => Promise
-const message = (error: unknown) =>
- error instanceof Error ? error.message : "无法完成操作。"
-
-function FolderBrowser({
- initial,
- read,
- onPick,
-}: {
- initial: string
- read: ReadFolder
- onPick?: (path: string) => void
-}) {
- const [query, load] = useState<{
- path: string
- offset?: number
- revision?: string
- }>({ path: initial })
- const [page, setPage] = useState(null)
- const [error, setError] = useState("")
- const [loading, setLoading] = useState(true)
- useEffect(() => {
- let active = true
- void read(query.path, query.offset, query.revision)
- .then((value) => {
- if (active)
- setPage((prev) =>
- query.offset &&
- prev?.path === value.path &&
- prev.revision === value.revision
- ? { ...value, entries: [...prev.entries, ...value.entries] }
- : value
- )
- })
- .catch((e) => {
- if (active) setError(message(e))
- })
- .finally(() => {
- if (active) setLoading(false)
- })
- return () => {
- active = false
- }
- }, [query, read])
- function go(path: string, offset?: number, revision?: string) {
- setLoading(true)
- setError("")
- if (!offset) setPage(null)
- load({ path, offset, revision })
- }
- return (
-
-
- {page?.path || query.path || "设备目录"}
-
- {loading &&
正在读取目录…
}
- {error && (
-
- {error}{" "}
-
- {" · "}
-
-
- )}
- {page && (
- <>
-
- {page.parent && (
-
- )}
- {page.entries.map((entry) => (
-
- ))}
- {!page.entries.length && !loading && (
-
没有子文件夹
- )}
- {page.nextOffset !== null && (
-
- )}
-
- {onPick && (
-
- )}
- >
- )}
-
- )
-}
-
-export function SidebarDialog({
- target,
- act,
- read,
- canBrowseFolders,
- close,
- returnTo,
-}: {
- target: SidebarPrompt
- act: (op: SidebarAction) => Promise
- read: ReadFolder
- canBrowseFolders: boolean
- close: () => void
- returnTo: HTMLElement | null
-}) {
- const relocating = target.kind === "relocate",
- browsing = target.kind === "browse",
- destructive = target.kind === "removeProject" || target.kind === "delete"
- const [value, setValue] = useState(relocating ? target.cwd : target.name)
- const [open, setOpen] = useState(true)
- const [picker, setPicker] = useState(browsing),
- [busy, setBusy] = useState(false),
- [error, setError] = useState("")
- const cancel = useRef(null),
- input = useRef(null),
- lock = useRef(false)
- const title =
- target.kind === "renameSession"
- ? "重命名会话"
- : target.kind === "renameProject"
- ? "重命名项目"
- : relocating
- ? "重新指定「" + target.name + "」的文件夹"
- : browsing
- ? "打开工作区目录"
- : target.kind === "removeProject"
- ? "移除项目「" + target.name + "」?"
- : "删除" +
- (target.kind === "delete" && target.ids.length > 1
- ? "这 " + target.ids.length + " 个会话"
- : "会话「" + target.name + "」") +
- "?"
- async function submit(text: string) {
- if (!open || lock.current || target.kind === "browse") return
- lock.current = true
- setBusy(true)
- setError("")
- try {
- if (target.kind === "delete")
- await act({
- kind: "delete",
- ids: target.ids,
- operationId: target.operationId,
- })
- else if (target.kind === "removeProject")
- await act({ kind: target.kind, id: target.id })
- else await act({ kind: target.kind, id: target.id, value: text })
- setOpen(false)
- } catch (e) {
- setError(message(e))
- } finally {
- lock.current = false
- setBusy(false)
- }
- }
- return (
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-sidebar-groups.ts b/monkeyai/web/src/pages/client/device-sidebar-groups.ts
deleted file mode 100644
index 261b56de5..000000000
--- a/monkeyai/web/src/pages/client/device-sidebar-groups.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import type { Session } from "@/lib/device-workspace"
-
-export const timestamp = (s: string) => Date.parse(s) || 0
-export function timeGroup(session: Session, now = new Date()) {
- const t = Date.parse(session.updatedAt)
- if (!Number.isFinite(t)) return "会话"
- const start = new Date(now).setHours(0, 0, 0, 0)
- if (t >= start) return "今天"
- if (t >= start - 86400000) return "昨天"
- return t >= start - 7 * 86400000 ? "过去 7 天" : "更早"
-}
diff --git a/monkeyai/web/src/pages/client/device-sidebar-list.css b/monkeyai/web/src/pages/client/device-sidebar-list.css
deleted file mode 100644
index 65be82a1e..000000000
--- a/monkeyai/web/src/pages/client/device-sidebar-list.css
+++ /dev/null
@@ -1,227 +0,0 @@
-.dw-navigation .dw-sidebar-list {
- --dw-list-hover: rgb(var(--sidebar-foreground-rgb) / 4%);
- --dw-list-current: rgb(var(--sidebar-foreground-rgb) / 6%);
- --dw-list-pressed: rgb(var(--sidebar-foreground-rgb) / 8%);
- display: flex;
- flex-direction: column;
- gap: 10px;
- padding: 10px 14px 16px;
- scroll-padding-block: 10px 16px;
-}
-.dw-navigation .dw-sidebar-list > section {
- flex: none;
- margin: 0;
-}
-.dw-navigation .dw-sidebar-list h3 {
- display: flex;
- align-items: center;
- height: 24px;
- padding-inline: 9px 4px;
- margin: 0 0 4px;
- color: var(--muted-foreground);
- font-size: 13px;
- font-weight: 500;
-}
-.dw-sidebar-list .dw-row {
- height: 32px;
- min-height: 32px;
- padding: 6px 8px;
- font-size: 15px;
- line-height: 20px;
- font-weight: 400;
- color: rgb(var(--sidebar-foreground-rgb) / 80%);
-}
-.dw-sidebar-list .dw-row > svg {
- width: 15px;
- height: 15px;
- margin-inline: 0.5px;
-}
-.dw-sidebar-list .dw-row > .dw-missing-folder {
- color: var(--destructive);
-}
-.dw-sidebar-list .dw-row > .dw-session-avatar {
- display: inline-grid;
- place-items: center;
- flex: 0 0 20px;
- height: 20px;
-}
-.dw-session-avatar img {
- object-fit: contain;
- border-radius: 2px;
-}
-.dw-session-avatar svg {
- color: var(--dw-avatar-light);
-}
-.dark .dw-session-avatar svg {
- color: var(--dw-avatar-dark);
-}
-.dw-sidebar-list .dw-row > .dw-completed-chip {
- flex: none;
- display: inline-flex;
- align-items: center;
- height: 20px;
- padding-inline: 6px;
- border-radius: 4px;
- font-size: 12px;
- line-height: 1;
- color: var(--color-emerald-600);
- background: rgb(0 153 102 / 9%);
-}
-.dark .dw-sidebar-list .dw-row > .dw-completed-chip {
- color: var(--color-emerald-400);
- background: rgb(0 212 146 / 9%);
-}
-.dw-sidebar-list .dw-session-row:has(.dw-completed-chip) .dw-session-title {
- --dw-title-fade: 8px;
- --dw-title-clear: 0px;
-}
-@media (hover: hover) and (min-width: 48rem) {
- .dw-session-row:is(:hover, :focus-within, :has([aria-expanded="true"]))
- .dw-completed-chip {
- visibility: hidden;
- }
-}
-/* 窄屏三点按钮常驻,保留独立触控区域,不盖住提醒。 */
-@media (hover: none), (max-width: 47.999rem) {
- .dw-session-row:has(.dw-completed-chip) > .dw-row {
- padding-inline-end: 32px;
- }
-}
-.dw-sidebar-list .dw-session-row + .dw-session-row,
-.dw-sidebar-list .dw-sidebar-folder + .dw-sidebar-folder {
- margin-top: 2px;
-}
-.dw-sidebar-list .dw-project-children {
- margin-inline-start: 24px;
- padding: 2px 0 4px;
- border: 0;
-}
-
-/* 高亮铺满包含菜单的整行;子会话悬停时,不点亮父文件夹。 */
-.dw-sidebar-list .dw-project-row {
- position: relative;
- border-radius: 7px;
-}
-.dw-item-action {
- position: absolute;
- inset-inline-end: 4px;
- top: 50%;
- transform: translateY(-50%);
- display: grid;
- place-items: center;
- width: 20px;
- height: 20px;
- padding: 0;
- border-radius: 8px;
- color: var(--muted-foreground);
-}
-.dw-item-action:is(:hover, :focus-visible, [aria-expanded="true"]) {
- color: var(--sidebar-accent-foreground);
- background: var(--sidebar-accent);
-}
-.dw-item-action:focus-visible {
- outline: 2px solid var(--sidebar-ring);
-}
-.dw-sidebar-popup[data-slot="dropdown-menu-content"] {
- width: max-content;
- min-width: min(180px, calc(100vw - 24px));
- max-width: calc(100vw - 24px);
- padding: 8px;
- border-radius: 8px;
- box-shadow:
- 0 0 0 1px rgb(0 0 0 / 5%),
- 0 4px 24px rgb(0 0 0 / 8%);
-}
-.dark .dw-sidebar-popup[data-slot="dropdown-menu-content"] {
- box-shadow:
- 0 0 0 1px rgb(255 255 255 / 8%),
- 0 4px 24px rgb(0 0 0 / 20%);
-}
-.dw-sidebar-popup [data-slot="dropdown-menu-item"] {
- gap: 12px;
- border-radius: 6px;
- white-space: nowrap;
-}
-.dw-sidebar-popup [data-slot="dropdown-menu-separator"] {
- margin-inline: 8px;
-}
-.dw-sidebar-popup [data-slot="dropdown-menu-item"][data-highlighted] {
- background: var(--accent);
-}
-.dw-sidebar-popup [data-variant="destructive"][data-highlighted] {
- background: color-mix(in srgb, var(--destructive) 10%, transparent);
-}
-.dw-sidebar-list .dw-session-row[data-picked] {
- box-shadow: inset 0 0 0 1px var(--sidebar-ring);
-}
-.dw-selection-tools {
- display: flex;
- align-items: center;
- gap: 2px;
- padding: 4px 8px;
- font-size: 12px;
-}
-.dw-selection-tools > span {
- margin-inline-end: auto;
-}
-.dw-project-row:not(.dw-session-row):has(> .dw-item-action) > .dw-row {
- padding-inline-end: 28px;
-}
-@media (hover: hover) and (min-width: 48rem) {
- .dw-project-row:not(:hover, :focus-within)
- > .dw-item-action:not([aria-expanded="true"]) {
- opacity: 0;
- pointer-events: none;
- }
-}
-@media (hover: none), (max-width: 47.999rem) {
- .dw-item-action::after {
- content: "";
- position: absolute;
- inset: -6px -4px;
- }
-}
-.dw-sidebar-list .dw-project-row > .dw-row {
- background: transparent;
-}
-.dw-sidebar-list
- .dw-project-row:is(
- :hover,
- :has(:focus-visible),
- :has([aria-haspopup="menu"][aria-expanded="true"])
- ),
-.dw-sidebar-list .dw-archive-toggle:is(:hover, :focus-visible) {
- background: var(--dw-list-hover);
-}
-.dw-sidebar-list .dw-project-row:has(> [aria-current="page"]) {
- background: var(--dw-list-current);
-}
-.dw-sidebar-list .dw-project-row:has(> .dw-row:active),
-.dw-sidebar-list .dw-archive-toggle:active {
- background: var(--dw-list-pressed);
-}
-.dw-sidebar-list .dw-row[aria-current="page"] {
- font-weight: 400;
-}
-.dw-sidebar-list .dw-archive-toggle {
- font-size: 13px;
- color: var(--muted-foreground);
- font-weight: 500;
-}
-.dw-sidebar-list .dw-archive-toggle > svg {
- width: 17px;
- height: 17px;
- margin-inline: -0.5px;
-}
-.dw-archive-lid {
- transform-origin: 12.5% 33.333%;
- transition: transform 180ms ease;
-}
-.dw-archive-toggle[aria-expanded="true"] .dw-archive-lid {
- transform: rotate(-13deg) scaleY(0.6);
-}
-@media (prefers-reduced-motion: reduce) {
- .dw-archive-lid {
- transition: none;
- }
-}
diff --git a/monkeyai/web/src/pages/client/device-sidebar-remote.tsx b/monkeyai/web/src/pages/client/device-sidebar-remote.tsx
deleted file mode 100644
index 26dcc08a4..000000000
--- a/monkeyai/web/src/pages/client/device-sidebar-remote.tsx
+++ /dev/null
@@ -1,235 +0,0 @@
-import { useEffect, useState, type RefObject } from "react"
-import { useNavigate } from "react-router-dom"
-import { ComputerIcon, Tick02Icon } from "@hugeicons/core-free-icons"
-import { HugeiconsIcon } from "@hugeicons/react"
-import { DevicePlatformIcon } from "@/components/device-platform-icon"
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-import {
- deviceStatus,
- isDeviceOnline,
- DirectoryError,
- listWorkspaceDevices,
- type WorkspaceDevice,
-} from "@/lib/workspace-devices"
-import { restoreDeviceGrant, validMachineId } from "@/lib/workspace-oauth"
-
-export type DeviceDirectorySnapshot = { token: string; rows: WorkspaceDevice[] }
-type DirectoryCache = RefObject
-
-export function SidebarRemoteConnection({
- cache,
- user,
- machine,
- name,
- platform,
- compact,
- busy,
-}: {
- cache: DirectoryCache
- user: string
- machine: string
- name: string
- platform: string
- compact: boolean
- busy: boolean
-}) {
- const [resolved, setResolved] = useState<{ user: string; device: WorkspaceDevice }>()
- useEffect(() => {
- if (platform) return
- const grant = restoreDeviceGrant(user)
- if (!grant?.canReadSessions) return
- const controller = new AbortController()
- void listWorkspaceDevices(grant.token, controller.signal).then((rows) => {
- if (controller.signal.aborted || restoreDeviceGrant(user)?.token !== grant.token) return
- const device = rows.find((row) => row.machine_id === machine)
- if (device) setResolved({ user, device })
- }).catch(() => { /* 目录不可用时保留路由中的设备名称。 */ })
- return () => controller.abort()
- }, [user, machine, platform])
- const device = !platform && resolved?.user === user && resolved.device.machine_id === machine
- ? resolved.device : undefined
- const label = device?.display_name || name
- const devicePlatform = platform || device?.platform
- return (
-
-
-
- {!compact && (
- <>
- 远程连接
-
- {devicePlatform && }
- {label}
-
- >
- )}
-
-
-
-
- 管理设备…
-
-
- )
-}
-
-function DeviceChoices({
- cache,
- user,
- machine,
- busy,
-}: {
- cache: DirectoryCache
- user: string
- machine: string
- busy: boolean
-}) {
- const navigate = useNavigate()
- const [revision, setRevision] = useState(0)
- const [devices, setDevices] = useState(() => {
- const grant = restoreDeviceGrant(user),
- snapshot = cache.current
- return grant?.canReadSessions && snapshot?.token === grant.token
- ? snapshot.rows
- : null
- })
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState("")
- useEffect(() => {
- const controller = new AbortController()
- async function load() {
- try {
- const grant = restoreDeviceGrant(user)
- if (!grant?.canReadSessions || cache.current?.token !== grant.token) {
- cache.current = null
- setDevices(null)
- }
- if (!grant?.canReadSessions)
- throw new DirectoryError(
- 401,
- "请前往我的设备,确认工作台授权后再连接。"
- )
- const rows = await listWorkspaceDevices(grant.token, controller.signal)
- if (controller.signal.aborted) return
- const current = restoreDeviceGrant(user)
- if (!current?.canReadSessions || current.token !== grant.token)
- throw new DirectoryError(401, "工作台授权已变化,请刷新设备列表。")
- cache.current = { token: grant.token, rows }
- setDevices(rows)
- } catch (e) {
- if (controller.signal.aborted) return
- if (
- e instanceof DirectoryError &&
- (e.status === 401 || e.status === 403)
- ) {
- cache.current = null
- setDevices(null)
- }
- setError(e instanceof Error ? e.message : "无法获取设备列表。")
- } finally {
- if (!controller.signal.aborted) setLoading(false)
- }
- }
- void load()
- return () => controller.abort()
- }, [user, revision, cache])
- function connect(d: WorkspaceDevice) {
- if (
- busy ||
- loading ||
- !!error ||
- d.machine_id === machine ||
- !isDeviceOnline(d) ||
- !validMachineId(d.machine_id)
- )
- return
- const grant = restoreDeviceGrant(user)
- if (!grant?.canReadSessions || grant.token !== cache.current?.token) {
- cache.current = null
- setDevices(null)
- setError("授权已失效,请前往我的设备重新授权。")
- return
- }
- navigate("/client/devices/" + d.machine_id, {
- state: { name: d.display_name || d.machine_id, platform: d.platform },
- })
- }
- return (
- <>
-
- {loading && devices === null && (
-
- 正在获取设备列表…
-
- )}
- {error && (
-
- {error}
- {devices !== null && " 当前显示上次获取的结果。"}
-
- )}
- {devices?.length === 0 && (
-
- 当前账号还没有已登记的执行设备。
-
- )}
- {devices?.map((d) => {
- const current = d.machine_id === machine
- const label = d.display_name || d.machine_id
- return (
-
connect(d)}
- >
-
- {label}
- {current ? (
-
- ) : (
- {deviceStatus(d.status)}
- )}
-
- )
- })}
-
- {error && (
- {
- setLoading(true)
- setError("")
- setRevision((v) => v + 1)
- }}>重试
- )}
- >
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-sidebar-search.css b/monkeyai/web/src/pages/client/device-sidebar-search.css
deleted file mode 100644
index f15553047..000000000
--- a/monkeyai/web/src/pages/client/device-sidebar-search.css
+++ /dev/null
@@ -1,163 +0,0 @@
-/* 居中只靠布局;缩放以面板中心为轴,不作用于遮罩。 */
-@media (prefers-reduced-motion: no-preference) {
- .ui-fade-only.dw-search-backdrop {
- transition: opacity 200ms linear;
- }
- .ui-fade-only.dw-search-panel {
- transition:
- opacity 200ms linear,
- transform 200ms cubic-bezier(0, 0, 0, 1);
- }
- .dw-search-panel:is([data-starting-style], [data-ending-style]) {
- transform: scale(0.75);
- }
- .dw-search-panel[data-ending-style] {
- transition-timing-function: linear, cubic-bezier(1, 0, 1, 1);
- }
- @starting-style {
- .dw-search-panel[data-open] {
- transform: scale(0.75);
- }
- }
-}
-.dw-search-panel[data-slot="dialog-content"] {
- --dw-search-top: max(12vh, env(safe-area-inset-top, 0px));
- inset: var(--dw-search-top) 0 auto;
- margin: 0 auto;
- display: flex;
- flex-direction: column;
- gap: 0;
- width: min(40rem, calc(100% - 2rem));
- max-width: none;
- max-height: min(34rem, calc(100vh - var(--dw-search-top) - 2rem));
- max-height: min(34rem, calc(100dvh - var(--dw-search-top) - 2rem));
- padding: 0;
- overflow: hidden;
-}
-.dw-search-field,
-.dw-search-footer,
-.dw-search-option {
- display: flex;
- align-items: center;
-}
-.dw-search-field {
- flex: none;
- gap: 10px;
- height: 52px;
- padding: 0 16px;
- border-bottom: 1px solid var(--border);
- color: var(--muted-foreground);
-}
-.dw-search-field input {
- min-width: 0;
- height: 100%;
- flex: 1;
- border: 0;
- background: transparent;
- color: var(--foreground);
- font-size: 15px;
- outline: none;
-}
-.dw-search-field input::placeholder {
- color: var(--muted-foreground);
-}
-.dw-search-results {
- min-height: 0;
- overflow-y: auto;
- overscroll-behavior: contain;
- padding: 6px;
-}
-.dw-search-heading {
- padding: 8px 10px 4px;
- font-size: 12px;
- font-weight: 500;
- color: var(--muted-foreground);
-}
-.dw-search-option {
- width: 100%;
- height: 36px;
- gap: 10px;
- padding: 0 10px;
- border-radius: 8px;
- color: var(--foreground);
- font-size: 14px;
- text-align: start;
-}
-.dw-search-option[aria-selected="true"] {
- background: var(--muted);
-}
-.dw-search-option:disabled {
- opacity: 0.55;
-}
-.dw-search-option > svg,
-.dw-search-option small,
-.dw-search-tag {
- flex: none;
- color: var(--muted-foreground);
-}
-.dw-search-title,
-.dw-search-option small {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-.dw-search-title {
- flex: 1;
- min-width: 0;
-}
-.dw-search-option[data-archived] .dw-search-title {
- color: var(--muted-foreground);
-}
-.dw-search-option small {
- max-width: 40%;
- font-size: 12px;
-}
-.dw-search-tag {
- padding: 1px 6px;
- border-radius: 4px;
- background: var(--muted);
- font-size: 11px;
-}
-.dw-search-option[aria-selected="true"] .dw-search-tag {
- background: var(--background);
-}
-.dw-search-option mark {
- background: transparent;
- color: var(--primary);
- font-weight: 600;
-}
-.dw-search-empty,
-.dw-search-more {
- padding: 10px;
- font-size: 12px;
- color: var(--muted-foreground);
-}
-.dw-search-empty {
- padding-block: 28px;
- text-align: center;
-}
-.dw-search-footer {
- flex: none;
- gap: 16px;
- height: 36px;
- padding: 0 14px;
- border-top: 1px solid var(--border);
- font-size: 12px;
- color: var(--muted-foreground);
-}
-.dw-search-footer span,
-.dw-search-footer kbd {
- display: inline-flex;
- align-items: center;
- gap: 4px;
-}
-.dw-search-footer kbd {
- height: 20px;
- min-width: 20px;
- justify-content: center;
- border-radius: 4px;
- background: var(--muted);
- padding: 0 4px;
- font: inherit;
- font-weight: 500;
-}
diff --git a/monkeyai/web/src/pages/client/device-sidebar-search.tsx b/monkeyai/web/src/pages/client/device-sidebar-search.tsx
deleted file mode 100644
index 31d132529..000000000
--- a/monkeyai/web/src/pages/client/device-sidebar-search.tsx
+++ /dev/null
@@ -1,271 +0,0 @@
-import { useEffect, useId, useRef, useState } from "react"
-import { HugeiconsIcon } from "@hugeicons/react"
-import {
- AiBeautifyIcon,
- Alert02Icon,
- BubbleChatIcon,
- FolderOpenIcon,
- Search01Icon,
-} from "@hugeicons/core-free-icons"
-import { Button } from "@/components/ui/button"
-import {
- Dialog,
- DialogContent,
- DialogTitle,
- DialogTrigger,
-} from "@/components/ui/dialog"
-import type { Project, Session } from "@/lib/device-workspace"
-
-import { timeGroup } from "./device-sidebar-groups"
-import "./device-sidebar-search.css"
-
-function Highlight({ text, query }: { text: string; query: string }) {
- const at = query ? text.toLowerCase().indexOf(query) : -1
- if (at < 0) return text
- return (
- <>
- {text.slice(0, at)}
- {text.slice(at, at + query.length)}
- {text.slice(at + query.length)}
- >
- )
-}
-
-export function SidebarSearch({
- projects,
- sessions,
- busy,
- onSelect,
-}: {
- projects: Project[]
- sessions: Session[]
- busy: boolean
- onSelect: (id: string, project?: string) => void
-}) {
- const [open, setOpen] = useState(false)
- const [query, setQuery] = useState("")
- const [index, setIndex] = useState(0)
- const input = useRef(null)
- const list = useRef(null)
- const id = useId()
- const afterClose = useRef<(() => void) | null>(null)
- function toggle(next: boolean) {
- setOpen(next)
- if (next) {
- afterClose.current = null
- setQuery("")
- setIndex(0)
- }
- }
- useEffect(() => {
- function key(e: KeyboardEvent) {
- if (
- (e.metaKey || e.ctrlKey) &&
- e.key.toLowerCase() === "k" &&
- !e.isComposing
- ) {
- e.preventDefault()
- toggle(true)
- }
- }
- window.addEventListener("keydown", key)
- return () => window.removeEventListener("keydown", key)
- }, [])
- const q = query.trim().toLowerCase()
- const hit = (s: string) => s.toLowerCase().includes(q)
- const found = sessions.filter((s) =>
- q ? hit(s.title) || (!s.isDefaultWorkspace && hit(s.cwd)) : !s.archivedAt
- )
- const projectNames = new Map(projects.map((p) => [p.id, p.name]))
- const options = [
- ...projects
- .filter((p) => q && (hit(p.name) || hit(p.cwd)))
- .map((p) => ({
- key: "p:" + p.id,
- title: p.name,
- icon: p.missing ? Alert02Icon : FolderOpenIcon,
- archived: false,
- path: p.cwd,
- detail: p.cwd,
- group: "项目",
- disabled: p.missing,
- select: () => onSelect("", p.id),
- })),
- ...found.slice(0, 50).map((s) => ({
- key: "s:" + s.id,
- title: s.title,
- icon: s.expertId === "monkeyai-design" ? AiBeautifyIcon : BubbleChatIcon,
- archived: !!s.archivedAt,
- path: s.isDefaultWorkspace ? "" : s.cwd,
- detail:
- projectNames.get(s.projectId) ||
- (q && !hit(s.title)
- ? s.cwd.split(/[\\/]/).filter(Boolean).at(-1)
- : "") ||
- "",
- group: timeGroup(s),
- disabled: false,
- select: () => onSelect(s.id),
- })),
- ]
- const selectable = options.flatMap((o, i) => (o.disabled ? [] : [i]))
- const active = selectable.includes(index)
- ? index
- : (selectable.find((i) => i >= index) ?? selectable.at(-1) ?? -1)
- function choose(i: number) {
- const item = options[i]
- if (!item || busy || item.disabled) return
- // 窄屏选中结果会关闭整个侧栏抽屉,等搜索弹窗淡出后再导航。
- afterClose.current = item.select
- toggle(false)
- }
- useEffect(() => {
- list.current
- ?.querySelector('[aria-selected="true"]')
- ?.scrollIntoView({ block: "nearest" })
- }, [active, query])
- return (
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-task-plan.css b/monkeyai/web/src/pages/client/device-task-plan.css
deleted file mode 100644
index 4a48c1a4f..000000000
--- a/monkeyai/web/src/pages/client/device-task-plan.css
+++ /dev/null
@@ -1,118 +0,0 @@
-.dc-plan-row {
- display: flex;
- align-items: flex-start;
- gap: 4px;
- min-width: 0;
- margin-bottom: 6px;
-}
-.dc-plan {
- min-width: 0;
- flex: 1;
- font: 400 12px/18px var(--font-sans, system-ui, sans-serif);
- letter-spacing: normal;
-}
-.dc-plan-trigger {
- display: flex;
- align-items: center;
- gap: 8px;
- width: 100%;
- min-width: 0;
- padding: 4px 6px;
- border-radius: 6px;
- text-align: left;
- cursor: pointer;
-}
-.dc-plan-trigger:hover {
- background: color-mix(in oklab, var(--muted) 40%, transparent);
-}
-.dc-plan[data-complete] .dc-plan-trigger {
- width: auto;
- max-width: 100%;
- color: var(--muted-foreground);
-}
-.dc-plan-label {
- flex: 1;
- min-width: 0;
- overflow: hidden;
- white-space: nowrap;
- text-overflow: ellipsis;
- font-weight: 500;
-}
-.dc-plan[data-complete] .dc-plan-label {
- flex: initial;
- font-weight: 400;
-}
-.dc-plan-count,
-.dc-plan-chevron {
- flex: none;
- color: var(--muted-foreground);
-}
-.dc-plan-count {
- font-variant-numeric: tabular-nums;
-}
-.dc-plan-chevron {
- transition: transform 120ms;
-}
-.dc-plan-trigger[aria-expanded="true"] .dc-plan-chevron {
- transform: rotate(180deg);
-}
-.dc-plan-dot {
- display: block;
- flex: none;
- width: 5px;
- height: 5px;
- margin: 0 4px;
- border-radius: 50%;
- background: var(--muted-foreground);
- opacity: 0.45;
-}
-.dc-plan-steps {
- margin: 0;
- padding: 4px 6px 8px;
- max-height: 180px;
- overflow: auto;
- scrollbar-width: thin;
- list-style: none;
-}
-.dc-plan-steps li {
- display: flex;
- align-items: baseline;
- gap: 9px;
- padding: 3px 0;
- overflow-wrap: anywhere;
-}
-.dc-plan-steps [data-status="completed"] {
- color: var(--muted-foreground);
-}
-.dc-plan-steps [data-status="in_progress"] {
- font-weight: 500;
-}
-.dc-plan-marker {
- display: grid;
- place-items: center;
- flex: none;
- align-self: flex-start;
- width: 13px;
- height: 18px;
-}
-.dc-plan-running {
- width: 9px;
- height: 9px;
- border: 1.5px solid var(--color-blue-500, #2b7fff);
- border-radius: 50%;
-}
-.dc-plan-row .dc-stop-link {
- flex: none;
- height: 22px;
- margin-top: 2px;
- padding-inline: 6px;
- gap: 4px;
- font-size: 12px;
- font-weight: 400;
- color: var(--muted-foreground);
-}
-@media (prefers-reduced-motion: reduce) {
- .dc-plan-chevron {
- transition: none;
- }
-}
diff --git a/monkeyai/web/src/pages/client/device-task-plan.tsx b/monkeyai/web/src/pages/client/device-task-plan.tsx
deleted file mode 100644
index 9f7b4c6ba..000000000
--- a/monkeyai/web/src/pages/client/device-task-plan.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import { useId, useState } from "react"
-import { HugeiconsIcon } from "@hugeicons/react"
-import { ArrowDown01Icon, Tick02Icon } from "@hugeicons/core-free-icons"
-import type { PlanStep } from "@/lib/device-workspace"
-import "./device-task-plan.css"
-
-const statusLabel = {
- pending: "待开始",
- in_progress: "进行中",
- completed: "已完成",
-}
-
-export function DeviceTaskPlan({
- plan,
- running,
- activity,
-}: {
- plan: PlanStep[]
- running: boolean
- activity?: string
-}) {
- const [open, setOpen] = useState(false)
- const listId = useId()
- const done = plan.filter((step) => step.status === "completed").length
- const complete = !activity && !running && done === plan.length
- const live = running && !activity
- const label =
- activity ??
- (live
- ? plan.find((step) => step.status === "in_progress")?.content ||
- "任务执行中"
- : complete
- ? "计划已完成"
- : "任务计划")
- return (
-
-
-
- {open && (
-
- {plan.map((step, index) => (
- -
-
- {step.status === "completed" ? (
-
- ) : (
-
- )}
-
-
- {statusLabel[step.status]}:
- {step.content}
-
-
- ))}
-
- )}
-
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-thinking-depth.tsx b/monkeyai/web/src/pages/client/device-thinking-depth.tsx
deleted file mode 100644
index f50cbe25e..000000000
--- a/monkeyai/web/src/pages/client/device-thinking-depth.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import {
- useId,
- useLayoutEffect,
- useRef,
- useState,
- type CSSProperties,
-} from "react"
-import {
- thinkingLevel,
- thinkingFromLevel,
- type Thinking,
-} from "@/lib/device-models"
-
-const labels: Record = {
- off: "关闭",
- on: "开启",
- minimal: "最低",
- low: "较低",
- medium: "中等",
- high: "较高",
- xhigh: "更高",
- max: "最高",
-}
-
-export function depthLabel(level: string) {
- return labels[level] ?? level
-}
-
-export function DeviceThinkingDepth({
- levels,
- thinking,
- disabled,
- onSelect,
-}: {
- levels: string[]
- thinking?: Thinking
- disabled: boolean
- onSelect: (next: Thinking) => void
-}) {
- const id = useId()
- const value = thinking
- ? thinkingLevel(thinking)
- : levels.includes("medium")
- ? "medium"
- : levels.find((level) => level !== "off")
- const track = useRef(null)
- const selected = useRef(null)
- const [box, setBox] = useState<{
- left: number
- top: number
- width: number
- height: number
- } | null>(null)
- useLayoutEffect(() => {
- const item = selected.current,
- group = track.current
- if (!item || !group) {
- setBox(null)
- return
- }
- function measure() {
- if (!item) return
- const {
- offsetLeft: left,
- offsetTop: top,
- offsetWidth: width,
- offsetHeight: height,
- } = item
- setBox((prev) =>
- prev &&
- prev.left === left &&
- prev.top === top &&
- prev.width === width &&
- prev.height === height
- ? prev
- : { left, top, width, height }
- )
- }
- measure()
- const observer = new ResizeObserver(measure)
- observer.observe(group)
- for (const option of group.querySelectorAll("label"))
- observer.observe(option)
- return () => observer.disconnect()
- }, [levels, value])
-
- return (
- <>
-
-
- >
- )
-}
diff --git a/monkeyai/web/src/pages/client/device-workspace.css b/monkeyai/web/src/pages/client/device-workspace.css
deleted file mode 100644
index 1603b6842..000000000
--- a/monkeyai/web/src/pages/client/device-workspace.css
+++ /dev/null
@@ -1,867 +0,0 @@
-/* 与客户端共用“项目导航 / 900px 阅读列 / 底部输入”的布局,不模拟原生窗口装饰。 */
-.dw-shell {
- position: fixed;
- inset: 0;
- overflow: hidden;
- background-color: #f1f1f2;
-}
-.dark .dw-shell {
- background-color: #272829;
-}
-.dw-shell {
- min-height: 0;
- display: flex;
- flex-direction: column;
- color: var(--foreground);
-}
-.dw-shell,
-.dw-navigation {
- font-family:
- system-ui,
- -apple-system,
- "Noto Sans SC Variable",
- sans-serif;
-}
-.dw-device-label,
-.dw-folder,
-.dw-chat-header {
- display: flex;
- align-items: center;
- gap: 6px;
-}
-.dw-body,
-.dw-main,
-.dw-navigation {
- flex: 1;
- min-height: 0;
- min-width: 0;
- display: flex;
-}
-.dw-main,
-.dw-navigation {
- flex-direction: column;
-}
-.dw-main {
- position: relative;
- margin: 6px;
- border: 1px solid var(--border);
- border-radius: 22px;
- background: var(--background);
- overflow: hidden;
-}
-.dw-rail {
- --dw-compact-width: 48px;
- width: 256px;
- flex: none;
- overflow: hidden;
- display: flex;
-}
-.dw-rail[data-compact] {
- width: var(--dw-compact-width);
-}
-@media (prefers-reduced-motion: no-preference) {
- .dw-rail {
- transition: width 200ms linear;
- }
-}
-.dw-nav-header {
- display: flex;
- flex: none;
- align-items: center;
- gap: 2px;
- padding: 12px 12px 8px;
- min-height: 56px;
-}
-.dw-header-logo {
- width: 28px;
- height: 28px;
- flex: none;
- object-fit: contain;
- border-radius: 31.25%;
-}
-.dw-nav-header > .dw-header-logo {
- align-self: flex-start;
-}
-.dw-header-brand {
- flex: 1;
- min-width: 0;
- margin-inline: 2px 4px;
-}
-.dw-header-brand > * {
- display: block;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-.dw-header-brand strong {
- font-size: 16px;
- line-height: 20px;
- font-weight: 600;
-}
-.dw-header-brand small {
- font-size: 11px;
- line-height: 16px;
- color: var(--muted-foreground);
-}
-.dw-nav-header button[aria-expanded="true"]:not(:hover) {
- background: transparent;
-}
-.dw-navigation[data-compact] > :not(.dw-nav-header, .dw-nav-actions) {
- display: none;
-}
-.dw-navigation[data-compact] .dw-nav-header {
- /* 固定窄栏的图标轴,收起时不随正在变窄的容器横移。 */
- width: calc(var(--dw-compact-width) - 1px);
- flex-direction: column;
- gap: 18px;
- padding-inline: 0;
-}
-@media (max-width: 767px) {
- .dw-nav-header {
- padding: 16px 12px 10px 16px;
- }
- .dw-header-logo {
- width: 32px;
- height: 32px;
- }
- .dw-header-brand {
- margin-inline-start: 7px;
- }
-}
-.dw-nav-actions,
-.dw-nav-scroll {
- padding: 12px;
-}
-.dw-nav-actions {
- display: grid;
- flex: none;
- gap: 3px;
- padding: 4px 14px 0;
- margin-bottom: 12px;
-}
-.dw-shortcut {
- display: flex;
- align-items: center;
- min-width: 0;
- gap: 8px;
- height: 32px;
- padding: 0 8px;
- border-radius: 7px;
- font-size: 15px;
- text-align: start;
-}
-.dw-shortcut > svg {
- flex: none;
-}
-.dw-shortcut:enabled:is(:hover, :focus-visible),
-.dw-shortcut[aria-expanded="true"],
-.dw-shortcut[aria-current="page"] {
- background: rgb(var(--sidebar-foreground-rgb) / 6%);
-}
-.dw-shortcut:disabled {
- opacity: 0.5;
-}
-.dw-navigation[data-compact] .dw-nav-actions {
- width: calc(var(--dw-compact-width) - 1px);
- justify-items: center;
- gap: 6px;
- padding: 0;
-}
-.dw-navigation[data-compact] .dw-shortcut {
- width: 32px;
- padding: 0;
- justify-content: center;
-}
-.dw-selected-device {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- line-height: 16px;
-}
-.dw-shortcut small {
- margin-inline-start: auto;
- min-width: 0;
- max-width: 42%;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- color: var(--muted-foreground);
- font-size: 11px;
-}
-.dw-search {
- display: flex;
- gap: 8px;
- align-items: center;
- padding: 7px 10px;
- border: 1px solid var(--border);
- border-radius: 9px;
- color: var(--muted-foreground);
- background: var(--background);
-}
-.dw-search input {
- min-width: 0;
- width: 100%;
- background: transparent;
- color: var(--foreground);
- font-size: 13px;
- outline: 0;
-}
-.dw-search:focus-within,
-.dw-frame:focus-within {
- border-color: var(--ring);
-}
-.dw-nav-scroll {
- flex: 1;
- overflow: auto;
- scrollbar-color: var(--muted-foreground) transparent;
- padding-block: 10px 16px;
- scroll-padding-block: 10px 16px;
- --dw-list-fade: linear-gradient(to bottom, transparent, black 10px, black calc(100% - 16px), transparent);
- -webkit-mask-image: var(--dw-list-fade);
- mask-image: var(--dw-list-fade);
-}
-.dw-nav-scroll section {
- margin: 12px 0 24px;
-}
-.dw-nav-scroll section:first-child { margin-top: 0; }
-.dw-nav-scroll section:last-child { margin-bottom: 0; }
-.dw-nav-scroll h3,
-.dw-empty,
-.dw-nav-footer {
- color: var(--muted-foreground);
- font-size: 12px;
-}
-.dw-nav-scroll h3 {
- font-weight: 600;
- margin: 0 9px 6px;
-}
-.dw-empty,
-.dw-nav-error {
- padding: 7px 9px;
-}
-.dw-nav-error {
- font-size: 12px;
- color: var(--destructive);
- overflow-wrap: anywhere;
-}
-.dw-row {
- display: flex;
- align-items: center;
- gap: 8px;
- width: 100%;
- min-width: 0;
- min-height: 34px;
- text-align: start;
- padding: 6px 9px;
- border-radius: 7px;
- font-size: 13px;
-}
-.dw-row:hover,
-.dw-row[aria-current="page"] {
- background: var(--muted);
-}
-.dw-row[aria-current="page"] {
- font-weight: 600;
-}
-.dw-row > svg {
- flex: none;
- color: var(--muted-foreground);
-}
-.dw-row > span,
-.dw-device-label span,
-.dw-chat-header h2,
-.dw-home h2 span {
- overflow: hidden;
- white-space: nowrap;
- text-overflow: ellipsis;
-}
-.dw-row > span {
- flex: 1;
-}
-.dw-project-row {
- display: flex;
- align-items: center;
-}
-.dw-project-children {
- margin-inline-start: 16px;
- padding-inline-start: 4px;
- border-inline-start: 1px solid var(--border);
-}
-.dw-nav-footer {
- display: flex;
- gap: 4px;
- align-items: center;
- flex: none;
- padding: 10px 16px 12px 20px;
-}
-.dw-sidebar-identity {
- display: flex;
- align-items: center;
- min-width: 0;
- min-height: 32px;
- flex: 1;
- gap: 4px;
-}
-.dw-sidebar-identity .dw-sidebar-avatar,
-.dw-sidebar-avatar :is(span, img) {
- border-radius: 7px;
-}
-.dw-sidebar-identity .dw-sidebar-avatar {
- width: 28px;
- height: 28px;
-}
-.dw-sidebar-identity .font-medium {
- font-size: 13px;
- line-height: 17px;
- color: var(--foreground);
-}
-.dw-sidebar-identity .text-muted-foreground {
- font-size: 11px;
- line-height: 13px;
-}
-.dw-nav-footer > button {
- width: 26px;
- height: 26px;
- border-radius: 6px;
-}
-.dw-chat-header,
-.dw-banner {
- padding: 10px 20px;
- flex: none;
- border-bottom: 1px solid var(--border);
-}
-.dw-chat-header {
- min-height: 44px;
- font-size: 14px;
- font-weight: 600;
-}
-.dw-chat-header svg,
-.dw-folder svg,
-.dw-device-label svg {
- flex: none;
-}
-.dw-banner {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 10px;
- flex-wrap: wrap;
- background: var(--muted);
- color: var(--foreground);
- font-size: 13px;
-}
-.dw-home {
- min-height: 0;
- flex: 1;
- overflow: auto;
-}
-.dw-home-inner,
-.dw-reply {
- width: calc(100% - 32px);
- max-width: 900px;
- margin-inline: auto;
-}
-.dw-home-inner {
- padding: clamp(72px, 16vh, 176px) 0 48px;
-}
-.dw-home h2 {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 12px;
- font-size: clamp(24px, 3vw, 32px);
- font-weight: 650;
- letter-spacing: -0.02em;
-}
-.dw-home h2 img {
- width: 1.25em;
- height: 1.25em;
- border-radius: 24%;
- object-fit: contain;
-}
-.dw-home-inner > p {
- text-align: center;
- color: var(--muted-foreground);
- font-size: 14px;
- margin: 8px 0 30px;
- overflow-wrap: anywhere;
-}
-.dw-reply {
- flex: none;
- padding: 8px 0 max(8px, env(safe-area-inset-bottom));
-}
-.dw-frame {
- border: 1px solid var(--border);
- border-radius: 23px;
- background: var(--card);
- box-shadow: 0 4px 16px rgb(0 0 0 / 0.045);
- overflow: hidden;
-}
-.dw-frame textarea {
- display: block;
- width: 100%;
- resize: none;
- min-height: 64px;
- max-height: min(26vh, 220px);
- overflow-y: auto;
- padding: 14px 18px 6px;
- line-height: 1.65;
- font-size: 15px;
- background: transparent;
- outline: 0;
-}
-.dw-tools {
- container: dw-tools / inline-size;
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 8px;
- padding: 5px 10px 8px 15px;
-}
-.dw-home .dw-tools {
- border-top: 1px solid var(--border);
- padding-top: 7px;
-}
-.dw-model-trigger {
- height: 34px;
-}
-/* 外壳只跟随锚点可用空间,分类、回执和列表长度不参与浮层的尺寸测量。 */
-.dw-model-popup {
- /* 定位层给出的是未缩放的可用高度;内容使用界面缩放后的 CSS 像素。 */
- --model-height-limit: calc(var(--available-height, 100dvh) / var(--workspace-scale, 1));
- box-sizing: border-box;
- contain: size;
- height: min(560px, 85dvh);
- max-height: var(--model-height-limit);
- overflow-x: hidden;
- overflow-anchor: none;
-}
-.dw-model-popup > :not(.dw-model-categories) {
- flex-shrink: 0;
-}
-.dw-home .dc-tools-left {
- flex: none;
-}
-.dw-home .dc-actions {
- flex: 0 1 auto;
-}
-.dw-home .dw-model-trigger {
- font-size: 14px;
-}
-@container dw-tools (max-width: 600px) {
- .dw-home .dw-model-trigger {
- font-size: 12px;
- }
-}
-.dw-model-popup[data-new] {
- animation: none;
- height: 560px;
- max-height: min(600px, var(--model-height-limit));
- border: 1px solid var(--border);
- border-radius: 16px;
- box-shadow: 0 8px 28px #00000010, 0 2px 6px #00000006;
-}
-.dw-model-popup[data-new]:not([data-kinds]) {
- contain: none;
- height: auto;
-}
-.dw-model-popup[data-new]:not([data-kinds]) .dw-model-list {
- flex-basis: auto;
- max-height: 288px;
-}
-.dw-model-footer::before {
- content: "";
- display: block;
- height: 1px;
- margin: 6px 4px;
- background: color-mix(in oklab, var(--border) 70%, transparent);
-}
-.dw-model-footer button {
- min-height: 32px;
- padding: 6px 12px;
- gap: 12px;
- font-size: 12px;
-}
-.dw-model-categories {
- display: flex;
- min-height: 0;
- flex: 1 1 auto;
- flex-direction: column;
-}
-.dw-model-list {
- flex: 1 1 0px;
- min-height: 0;
- overflow: hidden auto;
- overflow-anchor: none;
- scrollbar-width: thin;
- scrollbar-color: color-mix(in oklab, var(--foreground) 25%, transparent)
- transparent;
-}
-.dw-model-grid {
- display: grid;
- grid-template-columns: 27px minmax(0, 1fr) max-content;
- column-gap: 10px;
-}
-.dw-model-group,
-.dw-model-row {
- display: grid;
- grid-column: 1 / -1;
- min-width: 0;
-}
-.dw-model-group {
- grid-template-columns: subgrid;
-}
-.dw-model-group h3 {
- grid-column: 1 / -1;
- padding: 3px 9px 1px;
- color: var(--muted-foreground);
- font-size: 12px;
- font-weight: 400;
- line-height: 1.4;
-}
-.dw-model-row {
- position: relative;
- grid-template-columns: 18px minmax(0, 1fr) max-content;
- grid-template-columns: subgrid;
- align-items: center;
- gap: 10px;
- min-height: 38px;
- padding: 7px 28px 7px 9px;
- border-radius: 10px;
- line-height: 1.4;
- font-size: 14px;
- text-align: start;
-}
-.dw-model-row[aria-pressed="true"] {
- background: color-mix(in oklab, var(--muted) 65%, transparent);
-}
-.dw-model-row:enabled:is(:hover, :focus-visible) {
- background: var(--accent);
- color: var(--accent-foreground);
-}
-.dw-model-row[data-unavailable] {
- opacity: 0.5;
-}
-.dw-model-icon {
- display: grid;
- place-items: center;
- width: 18px;
- height: 18px;
- color: var(--muted-foreground);
-}
-.dw-model-icon[data-brand="Kimi"] img {
- filter: brightness(0);
-}
-.dark
- .dw-model-icon:is(
- [data-brand="Grok"],
- [data-brand="OpenAI"],
- [data-brand="Kimi"]
- )
- img {
- filter: brightness(0) invert(1);
-}
-.dw-model-name,
-.dw-model-owner {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-.dw-model-row[data-category="mine"] .dw-model-name {
- grid-column: 2 / -1;
-}
-.dw-model-owner,
-.dw-model-rate {
- color: var(--muted-foreground);
- text-align: end;
- font-size: 12px;
-}
-.dw-model-owner {
- max-width: 112px;
-}
-.dw-model-rate {
- font-variant-numeric: tabular-nums;
- white-space: nowrap;
-}
-.dw-model-check {
- position: absolute;
- right: 8px;
- top: 50%;
- transform: translateY(-50%);
- pointer-events: none;
-}
-.dw-model-tabs [data-slot="tabs-trigger"][data-active] {
- background: transparent;
- border-color: transparent;
- box-shadow: none;
-}
-.dw-model-tab-indicator {
- position: absolute;
- z-index: -1;
- inset: 0 auto auto 0;
- width: var(--active-tab-width);
- height: var(--active-tab-height);
- transform: translate(var(--active-tab-left), var(--active-tab-top));
- pointer-events: none;
-}
-.dw-depth-divider,
-.dw-context-divider {
- height: 1px;
- margin: 6px 4px;
- background: color-mix(in oklab, var(--border) 70%, transparent);
-}
-.dw-depth,
-.dw-context {
- min-width: 0;
- padding: 2px 9px 6px;
-}
-.dw-depth-head,
-.dw-context-head {
- display: flex;
- align-items: baseline;
- justify-content: space-between;
- gap: 8px;
- margin-bottom: 8px;
- color: var(--muted-foreground);
- font-size: 12px;
-}
-.dw-depth-head > :first-child,
-.dw-context-head > :first-child {
- flex-shrink: 0;
- color: var(--foreground);
- font-size: 14px;
-}
-.dw-depth-head > :last-child,
-.dw-context-head > :last-child {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-.dw-depth-track {
- position: relative;
- isolation: isolate;
- display: flex;
- gap: 2px;
- padding: 2px;
- border-radius: 9px;
- background: var(--emboss-well, var(--muted));
- box-shadow: var(--emboss-inset-sm, none);
-}
-.dw-context-value {
- font-variant-numeric: tabular-nums;
-}
-.dw-context-meter {
- height: 4px;
- overflow: hidden;
- border-radius: 2px;
- background: color-mix(in oklab, var(--foreground) 8%, transparent);
-}
-.dw-context-meter > i {
- display: block;
- height: 100%;
- border-radius: inherit;
- background: var(
- --dw-context-color,
- color-mix(in oklab, var(--foreground) 62%, transparent)
- );
-}
-[data-context-level="high"]:is(.dw-context, .dw-context-dot) {
- --dw-context-color: #98601a;
-}
-.dark [data-context-level="high"]:is(.dw-context, .dw-context-dot) {
- --dw-context-color: #deb57b;
-}
-[data-context-level="full"]:is(.dw-context, .dw-context-dot) {
- --dw-context-color: var(--destructive);
-}
-.dw-context[data-context-level] .dw-context-value {
- color: var(--dw-context-color);
-}
-.dw-context-dot {
- background: var(--dw-context-color);
-}
-.dw-context-foot {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 8px;
- min-width: 0;
- margin-top: 6px;
- font-size: 12px;
- color: var(--muted-foreground);
-}
-.dw-context-foot span {
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-.dw-context-foot button:disabled {
- flex-shrink: 0;
- min-height: 24px;
- padding: 0 6px;
- border-radius: 6px;
- color: var(--foreground);
- opacity: 0.45;
-}
-.dw-depth-option {
- position: relative;
- display: grid;
- place-items: center;
- flex: 1 1 0;
- min-width: 0;
- min-height: 28px;
- padding: 0 4px;
- border-radius: 7px;
- color: var(--muted-foreground);
- font-size: 12px;
- white-space: nowrap;
-}
-.dw-depth-option input {
- position: absolute;
- inset: 0;
- width: 100%;
- height: 100%;
- margin: 0;
- opacity: 0;
- cursor: pointer;
-}
-.dw-depth-option input:disabled {
- cursor: default;
-}
-.dw-depth-option[data-off] {
- flex: 0 0 auto;
- padding-inline: 10px;
-}
-.dw-depth-option[data-off] + label {
- margin-inline-start: 5px;
-}
-.dw-depth-option[data-off] + label::before {
- content: "";
- position: absolute;
- inset-inline-start: -4px;
- top: 7px;
- bottom: 7px;
- width: 1px;
- background: color-mix(in oklab, var(--foreground) 12%, transparent);
-}
-.dw-depth:not(:disabled)
- .dw-depth-option:is(:hover, :focus-within):not([data-selected]) {
- color: var(--foreground);
- background: color-mix(in oklab, var(--background) 55%, transparent);
-}
-.dw-depth-option:has(input:focus-visible) {
- outline: 2px solid var(--ring);
- outline-offset: -2px;
-}
-.dw-depth-option[data-selected] {
- color: var(--foreground);
- font-weight: 500;
-}
-.dw-depth-indicator {
- border-radius: 7px;
- background: var(--emboss-control, var(--background));
- box-shadow: var(--emboss-raise-sm, 0 1px 2px rgb(0 0 0 / 8%));
-}
-.dark .dw-depth-indicator {
- background: var(
- --emboss-control,
- color-mix(in oklab, var(--foreground) 14%, transparent)
- );
- box-shadow: var(--emboss-raise-sm, none);
-}
-@media (prefers-reduced-motion: no-preference) {
- .dw-depth-option {
- transition:
- color 180ms ease,
- background-color 180ms ease;
- }
- .dw-model-tab-indicator {
- transition:
- transform 220ms cubic-bezier(0.2, 0.8, 0.2, 1),
- width 220ms cubic-bezier(0.2, 0.8, 0.2, 1),
- height 220ms cubic-bezier(0.2, 0.8, 0.2, 1);
- }
-}
-@media (prefers-reduced-motion: no-preference) {
- .dw-model-chevron {
- transition:
- transform 140ms,
- rotate 140ms;
- }
-}
-@container dw-tools (max-width: 600px) {
- .dw-model-trigger {
- height: 30px;
- }
-}
-@container dw-tools (max-width: 420px) {
- .dw-model-trigger {
- height: 28px;
- padding-inline: 6px;
- }
-}
-@container dw-tools (max-width: 300px) {
- .dw-model-trigger {
- padding-inline: 4px;
- }
- .dw-model-chevron {
- display: none;
- }
-}
-.dw-folder,
-.dw-device-label {
- min-width: 0;
- color: var(--muted-foreground);
- font-size: 12px;
-}
-.dw-folder select {
- max-width: min(48vw, 225px);
- height: 32px;
- background: var(--card);
- color: var(--foreground);
-}
-.dw-footnote,
-.dw-feedback {
- margin-top: 7px;
- text-align: center;
- color: var(--muted-foreground);
- font-size: 12px;
-}
-.dw-feedback {
- color: var(--foreground);
- overflow-wrap: anywhere;
-}
-.dw-navigation :focus-visible,
-.dw-shell :is(a, button, select):focus-visible {
- outline: 2px solid var(--ring);
- outline-offset: 1px;
-}
-@media (max-width: 767px) {
- .dw-home {
- scrollbar-color: var(--muted-foreground) transparent;
- }
- .dw-home-inner {
- padding-top: clamp(44px, 11vh, 88px);
- }
- .dw-home-inner,
- .dw-reply {
- width: calc(100% - 24px);
- }
- .dw-row {
- min-height: 42px;
- }
- .dw-frame textarea {
- font-size: 16px;
- }
- .dw-banner {
- justify-content: flex-start;
- }
- .dw-folder select {
- max-width: 52vw;
- }
- .dw-nav-footer {
- padding-left: 10px;
- padding-bottom: max(12px, env(safe-area-inset-bottom));
- }
-}
diff --git a/monkeyai/web/src/pages/client/identity-preference.ts b/monkeyai/web/src/pages/client/identity-preference.ts
deleted file mode 100644
index 84f615296..000000000
--- a/monkeyai/web/src/pages/client/identity-preference.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { useSyncExternalStore } from "react"
-
-const key = "monkeyai.web.hide-identity"
-export function maskName(name: string) {
- return (Array.from(name.trim())[0] ?? "") + "***"
-}
-export function maskEmail(email: string) {
- const at = email.indexOf("@")
- return at > 0
- ? maskName(email.slice(0, at)) + email.slice(at)
- : maskName(email)
-}
-
-let fallback = false
-let memoryOnly = false
-function snapshot() {
- if (memoryOnly) return fallback
- try {
- return localStorage.getItem(key) === "1"
- } catch {
- return fallback
- }
-}
-function subscribe(onChange: () => void) {
- window.addEventListener(key, onChange)
- window.addEventListener("storage", onChange)
- return () => {
- window.removeEventListener(key, onChange)
- window.removeEventListener("storage", onChange)
- }
-}
-function update(value: boolean) {
- fallback = value
- try {
- localStorage.setItem(key, value ? "1" : "0")
- memoryOnly = false
- } catch {
- memoryOnly = true
- }
- window.dispatchEvent(new Event(key))
-}
-export function useIdentityPreference() {
- return [useSyncExternalStore(subscribe, snapshot), update] as const
-}
diff --git a/monkeyai/web/src/pages/client/queue-recovery.tsx b/monkeyai/web/src/pages/client/queue-recovery.tsx
deleted file mode 100644
index c05e2aa41..000000000
--- a/monkeyai/web/src/pages/client/queue-recovery.tsx
+++ /dev/null
@@ -1,178 +0,0 @@
-import { useEffect, useRef, useState } from "react"
-import { Button } from "@/components/ui/button"
-import type { DeviceChannel } from "@/lib/device-connection"
-import { queueReceipt, type QueueState } from "@/lib/device-workspace"
-import type { composerDrafts } from "./composer-drafts"
-
-const labels: Record = {
- pending: "正在提交",
- accepted: "已受理",
- running: "正在处理",
- completed: "已确认",
- failed: "提交失败",
- outcome_unknown: "结果尚未确认",
- not_found: "执行设备暂未找到这次提交",
-}
-type Drafts = ReturnType
-type Row = ReturnType[number]
-
-export function QueueRecovery({
- drafts,
- user,
- machine,
- channel,
- open,
- changed,
- submitting,
-}: {
- drafts: Drafts
- user: string
- machine: string
- channel?: DeviceChannel
- open: (id: string) => void
- changed: () => void
- submitting?: string
-}) {
- const rows = drafts
- .records(user, machine)
- .filter(
- (r) => !(r.session === submitting && r.entry.receiptState === "pending")
- )
- const [busy, setBusy] = useState(false),
- [error, setError] = useState("")
- const live = useRef(channel)
- live.current = channel
- const unresolved = rows.filter(
- (r) =>
- r.entry.pendingOperation &&
- !["completed", "failed"].includes(r.entry.receiptState || "")
- )
- async function check(row: Row) {
- const id = row.entry.pendingOperation
- if (!channel || !id) throw new Error("缺少可查询的设备提交记录。")
- const state = await queueReceipt(channel, row.session, id, user, machine)
- if (
- live.current !== channel ||
- drafts.read(row.key).pendingOperation !== id
- )
- throw new Error("提交记录已变更。")
- drafts.update(row.key, { receiptState: state })
- changed()
- return state
- }
- const fingerprint = JSON.stringify(
- unresolved.map((r) => r.entry.pendingOperation)
- )
- const refresh = useRef(async () => {})
- refresh.current = async () => {
- for (const row of unresolved) await check(row)
- }
- useEffect(() => {
- if (!channel) return
- let active = true
- setError("")
- void refresh.current().catch((e) => {
- if (active) setError(String(e.message || e))
- })
- return () => {
- active = false
- }
- }, [channel, fingerprint])
- async function perform(fn: () => Promise) {
- setBusy(true)
- setError("")
- try {
- await fn()
- } catch (e) {
- setError(e instanceof Error ? e.message : String(e))
- } finally {
- setBusy(false)
- }
- }
- async function restore(row: Row) {
- const state = await check(row)
- if (state !== "failed" && state !== "not_found") {
- open(row.session)
- return
- }
- const d = drafts.read(row.key)
- if (d.text || d.files?.length || d.quotes?.length)
- throw new Error("当前会话已有草稿,请先处理后再恢复。")
- drafts.update(
- row.key,
- {
- text: d.pending || "",
- files: d.pendingFiles,
- quotes: d.pendingQuotes,
- pending: undefined,
- pendingOperation: undefined,
- pendingQuotes: undefined,
- pendingFiles: undefined,
- receiptState: undefined,
- },
- true
- )
- changed()
- open(row.session)
- }
- if (!rows.length) return null
- return (
-
-
-
- 查看 {rows.length} 条提交记录
-
-
- {rows.map((row) => (
-
- 发送消息
- {labels[row.entry.receiptState || "outcome_unknown"]}
-
-
-
-
- ))}
-
-
- {!!unresolved.length && (
-
- )}
- {error &&
{error}
}
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/use-device-model-catalog.ts b/monkeyai/web/src/pages/client/use-device-model-catalog.ts
deleted file mode 100644
index 4affc9f3c..000000000
--- a/monkeyai/web/src/pages/client/use-device-model-catalog.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { useEffect, useState } from "react"
-import type { DeviceChannel } from "@/lib/device-connection"
-import type { ChatModel } from "@/lib/device-models"
-
-export function useDeviceModelCatalog(channel?: DeviceChannel) {
- const [attempt, retry] = useState(0)
- const [result, setResult] = useState<{
- channel: DeviceChannel
- attempt: number
- models: ChatModel[]
- error?: string
- }>()
- useEffect(() => {
- if (!channel) return
- let live = true
- channel.models().then(
- (models) => {
- if (live) setResult({ channel, attempt, models })
- },
- (error) => {
- if (live)
- setResult({
- channel,
- attempt,
- models: [],
- error:
- error instanceof Error ? error.message : "无法读取模型目录。",
- })
- }
- )
- return () => {
- live = false
- }
- }, [channel, attempt])
- const current =
- result?.channel === channel && result?.attempt === attempt
- ? result
- : undefined
- return {
- models: current?.models ?? [],
- error: current?.error,
- loading: !!channel && !current,
- reload: () => retry((n) => n + 1),
- }
-}
diff --git a/monkeyai/web/src/pages/client/user-markdown-body.tsx b/monkeyai/web/src/pages/client/user-markdown-body.tsx
deleted file mode 100644
index 9236f1566..000000000
--- a/monkeyai/web/src/pages/client/user-markdown-body.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import { Fragment, memo } from "react"
-import { parseUserMarkdown, type UserMarkdownInline } from "@/lib/user-markdown"
-
-function inlines(nodes: UserMarkdownInline[]) {
- return nodes.map((node, i) => {
- if (node.type === "code")
- return (
-
- {node.text}
-
- )
- if (node.type === "strong")
- return {inlines(node.children)}
- return node.text
- })
-}
-export const UserMarkdownBody = memo(function UserMarkdownBody({
- text,
-}: {
- text: string
-}) {
- return parseUserMarkdown(text).map((block, i) => {
- if (block.type === "code")
- return (
-
- {block.text}
-
- )
- if (block.type === "heading")
- return (
-
- {inlines(block.children)}
-
- )
- return (
-
- {block.lines.map((line, j) => (
-
- {j > 0 && "\n"}
- {inlines(line)}
-
- ))}
-
- )
- })
-})
diff --git a/monkeyai/web/src/pages/client/user-markdown-preference.ts b/monkeyai/web/src/pages/client/user-markdown-preference.ts
deleted file mode 100644
index 37c7cbafa..000000000
--- a/monkeyai/web/src/pages/client/user-markdown-preference.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { useSyncExternalStore } from "react"
-
-const key = "monkeyai.web.renderUserMarkdown"
-const changed = "monkeyai:user-markdown-change"
-let fallback = true
-
-function current() {
- try {
- return localStorage.getItem(key) !== "false"
- } catch {
- return fallback
- }
-}
-function subscribe(notify: () => void) {
- const onStorage = (e: StorageEvent) => {
- if (e.key === key || e.key === null) notify()
- }
- window.addEventListener("storage", onStorage)
- window.addEventListener(changed, notify)
- return () => {
- window.removeEventListener("storage", onStorage)
- window.removeEventListener(changed, notify)
- }
-}
-export function useUserMarkdown() {
- return useSyncExternalStore(subscribe, current)
-}
-export function setUserMarkdown(enabled: boolean) {
- fallback = enabled
- try {
- localStorage.setItem(key, String(enabled))
- } catch {
- /* 无持久存储时,本页仍可切换。 */
- }
- window.dispatchEvent(new Event(changed))
-}
diff --git a/monkeyai/web/src/pages/client/workspace-accent.tsx b/monkeyai/web/src/pages/client/workspace-accent.tsx
deleted file mode 100644
index 61c2bc4d0..000000000
--- a/monkeyai/web/src/pages/client/workspace-accent.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import { useId } from "react"
-import { useTheme } from "@/components/theme-provider"
-import {
- ColorSelector,
- ColorSelectorItem,
- ColorSelectorLabel,
- ColorSelectorList,
-} from "@/components/ui/color-selector"
-import { accents, type Accent } from "@/lib/accent"
-
-export function AccentControl() {
- const {
- accentPreference: { accent, color, setAccent },
- } = useTheme()
- const id = useId()
- return (
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/workspace-appearance.tsx b/monkeyai/web/src/pages/client/workspace-appearance.tsx
deleted file mode 100644
index 6a1508cae..000000000
--- a/monkeyai/web/src/pages/client/workspace-appearance.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { flushSync } from "react-dom"
-import { useTheme } from "@/components/theme-provider"
-import { themes, type Theme } from "@/lib/themes"
-import { Button } from "@/components/ui/button"
-import { AccentControl } from "./workspace-accent"
-import { InterfaceSizeControl } from "./workspace-interface-size"
-
-const labels: Record = {
- system: "跟随系统",
- light: "浅色",
- dark: "深色",
- "century-blue": "冰川蓝",
- "textured-gray": "磨砂灰",
-}
-
-function revealTheme(event: React.MouseEvent, apply: () => void) {
- const root = document.documentElement
- if (
- !document.startViewTransition ||
- window.matchMedia("(prefers-reduced-motion: reduce)").matches ||
- root.hasAttribute("data-theme-reveal")
- ) {
- apply()
- return
- }
- const rect = event.currentTarget.getBoundingClientRect()
- const x = event.detail ? event.clientX : rect.left + rect.width / 2
- const y = event.detail ? event.clientY : rect.top + rect.height / 2
- root.style.setProperty("--theme-origin", x + "px " + y + "px")
- root.setAttribute("data-theme-reveal", "")
- const clear = () => {
- root.removeAttribute("data-theme-reveal")
- root.style.removeProperty("--theme-origin")
- }
- try {
- const transition = document.startViewTransition(() => flushSync(apply))
- void transition.finished.then(clear, clear)
- } catch {
- clear()
- apply()
- }
-}
-
-export function AppearancePanel() {
- const { theme, setTheme } = useTheme()
-
- return (
-
- 外观
-
-
- 主题
-
- {themes.map((value) => (
-
- ))}
-
-
-
-
-
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/workspace-identity.tsx b/monkeyai/web/src/pages/client/workspace-identity.tsx
deleted file mode 100644
index ef3b6dbcf..000000000
--- a/monkeyai/web/src/pages/client/workspace-identity.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { useAuth } from "@/hooks/use-auth"
-import { UserAvatar } from "@/components/user-avatar"
-import {
- maskEmail,
- maskName,
- useIdentityPreference,
-} from "./identity-preference"
-
-export function WorkspaceIdentity({ sidebar = false }: { sidebar?: boolean }) {
- const { user } = useAuth()
- const [hidden] = useIdentityPreference()
- if (!user) return null
- const name = user.name && (hidden ? maskName(user.name) : user.name)
- const email = user.email && (hidden ? maskEmail(user.email) : user.email)
- const identity = (
-
-
- {name || email}
-
- {name && email && (
-
- {email}
-
- )}
-
- )
- if (!sidebar) return identity
- return (
-
-
- {identity}
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/workspace-interface-size.tsx b/monkeyai/web/src/pages/client/workspace-interface-size.tsx
deleted file mode 100644
index cc4df5e90..000000000
--- a/monkeyai/web/src/pages/client/workspace-interface-size.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import { useEffect, useId, useRef, useState } from "react"
-import {
- observeInterfaceSize,
- readInterfaceSize,
- saveInterfaceSize,
- sizes,
- type InterfaceSize,
-} from "@/lib/interface-size"
-
-const labels = ["最小", "较小", "稍小", "标准", "较大", "最大"]
-export function InterfaceSizeControl() {
- const id = useId()
- const input = useRef(null)
- const [size, setSize] = useState(readInterfaceSize)
- const [draft, setDraft] = useState(null)
- const index = sizes.indexOf(draft ?? size)
- function commit(next: InterfaceSize) {
- saveInterfaceSize(next)
- setSize(next)
- setDraft(null)
- }
- useEffect(() => observeInterfaceSize(setSize), [])
- useEffect(() => {
- const slider = input.current!
- // 原生 change 在拖动结束时提交,避免缩放期间滑块从指针下移开。
- const finish = () => commit(sizes[slider.valueAsNumber])
- slider.addEventListener("change", finish)
- return () => slider.removeEventListener("change", finish)
- }, [])
- return (
-
-
-
-
-
-
-
-
-
- 侧栏、对话和工作区一起调整,松开滑块后生效。
-
-
-
-
-
setDraft(sizes[e.currentTarget.valueAsNumber])}
- onPointerCancel={() => setDraft(null)}
- onBlur={() => setDraft(null)}
- />
-
-
- 小
- 标准
- 大
-
-
- {sizes[index] !== 100 && (
-
- )}
-
-
- )
-}
diff --git a/monkeyai/web/src/pages/client/workspace-settings.css b/monkeyai/web/src/pages/client/workspace-settings.css
deleted file mode 100644
index 116c3f8ae..000000000
--- a/monkeyai/web/src/pages/client/workspace-settings.css
+++ /dev/null
@@ -1,90 +0,0 @@
-@import "misans/lib/Normal/MiSansVF.min.css";
-
-[data-workspace-settings] {
- font-family: "MiSans VF", "Noto Sans SC Variable", system-ui, sans-serif;
- --font-heading: inherit;
- --font-weight-normal: 330;
- --font-weight-medium: 380;
- --font-weight-semibold: 450;
- font-weight: var(--font-weight-normal);
- /* 用布局居中,让浮层从第一帧起就不依赖位移或缩放。 */
- inset: 0;
- margin: auto;
- translate: none;
- transform: none;
- transition: none;
-}
-
-/* 百分比跟随固定定位的可用高度;只抵消外框和上下留白的缩放。 */
-.workspace-settings-panel {
- height: min(calc(48rem / var(--workspace-scale, 1)), calc(100% - 2rem / var(--workspace-scale, 1)));
-}
-
-@keyframes workspace-settings-reveal {
- from {
- opacity: 0;
- }
- to {
- opacity: 1;
- }
-}
-
-.workspace-theme-group {
- background: var(--muted);
-}
-:root:not(.dark):not([data-theme]) .workspace-theme-group {
- background: #f7f7f7;
-}
-:root:not(.dark):not([data-theme]) .workspace-theme-group button[aria-pressed="false"]:not(:hover) {
- background: #f0f0f0;
-}
-:root[data-theme] [data-workspace-settings] {
- border: 1px solid var(--settings-edge);
- border-radius: 22px;
- box-shadow: var(--settings-shadow);
-}
-:root[data-theme] [data-slot="dialog-overlay"]:has(~ [data-workspace-settings]) {
- background-color: var(--settings-overlay);
-}
-:root[data-theme="century-blue"] [data-workspace-settings] {
- color: rgb(27 27 27);
- --secondary-foreground-rgb: 27 27 27;
- --muted-foreground-rgb: 51 51 51;
-}
-
-html[data-theme-reveal]::view-transition-old(root) {
- animation: none;
- mix-blend-mode: normal;
-}
-html[data-theme-reveal]::view-transition-new(root) {
- mix-blend-mode: normal;
- animation: workspace-theme-reveal 700ms cubic-bezier(0.4, 0, 0.2, 1) both;
-}
-@keyframes workspace-theme-reveal {
- from { clip-path: circle(0% at var(--theme-origin)); }
- to { clip-path: circle(150% at var(--theme-origin)); }
-}
-@media (prefers-reduced-motion: reduce) {
- html[data-theme-reveal]::view-transition-new(root) { animation: none; }
-}
-
-[data-workspace-settings][data-open] {
- animation: workspace-settings-reveal 200ms ease-out backwards;
-}
-@keyframes workspace-settings-dismiss {
- from {
- opacity: 1;
- }
- to {
- opacity: 0;
- }
-}
-[data-workspace-settings][data-closed] {
- animation: workspace-settings-dismiss 160ms ease-in both;
-}
-@media (prefers-reduced-motion: reduce) {
- [data-workspace-settings][data-open],
- [data-workspace-settings][data-closed] {
- animation: none;
- }
-}
diff --git a/monkeyai/web/src/pages/client/workspace-settings.tsx b/monkeyai/web/src/pages/client/workspace-settings.tsx
deleted file mode 100644
index 9fbde84b2..000000000
--- a/monkeyai/web/src/pages/client/workspace-settings.tsx
+++ /dev/null
@@ -1,398 +0,0 @@
-import { useEffect, useRef, useState } from "react"
-import {
- Coins01Icon,
- PaintBoardIcon,
- RefreshIcon,
- Settings02Icon,
- UserIcon,
-} from "@hugeicons/core-free-icons"
-import { HugeiconsIcon } from "@hugeicons/react"
-import { useBranding } from "@/hooks/use-branding"
-import { Checkbox } from "@/components/ui/checkbox"
-import { Badge } from "@/components/ui/badge"
-import {
- maskEmail,
- maskName,
- useIdentityPreference,
-} from "./identity-preference"
-import "./workspace-settings.css"
-import { BalanceCard } from "./balance-card"
-import { AppearancePanel } from "./workspace-appearance"
-import { Button } from "@/components/ui/button"
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from "@/components/ui/dialog"
-import { useAuth } from "@/hooks/use-auth"
-import { restoreDeviceGrant } from "@/lib/workspace-oauth"
-import {
- lastBalance,
- readBalance,
- rememberBalance,
-} from "@/lib/workspace-balance"
-
-function Credits({ user }: { user: string }) {
- const [account, setAccount] = useState(() => lastBalance(user))
- const [error, setError] = useState("")
- const [retry, setRetry] = useState(0)
- const [loading, setLoading] = useState(false)
- useEffect(() => {
- const controller = new AbortController()
- let pending = false
- let paused = false
- async function load() {
- if (document.hidden || pending || paused) return
- pending = true
- setLoading(true)
- try {
- const grant = restoreDeviceGrant(user)
- if (!grant) {
- paused = true
- rememberBalance(null)
- setAccount(null)
- throw new Error("请先完成工作台授权,再查看积分。")
- }
- const response = await fetch("/api/v1/billing/account", {
- headers: { Authorization: "Bearer " + grant.token },
- credentials: "omit",
- redirect: "error",
- cache: "no-store",
- signal: controller.signal,
- })
- paused = [401, 403, 404].includes(response.status)
- if (
- !controller.signal.aborted &&
- [401, 403].includes(response.status)
- ) {
- rememberBalance(null)
- setAccount(null)
- }
- if (!response.ok)
- throw new Error(
- response.status === 401
- ? "工作台授权已失效,请重新授权。"
- : "无法获取积分,请重试。"
- )
- const data = readBalance(await response.json(), user)
- if (!data) throw new Error("积分数据格式无效,请重试。")
- if (!controller.signal.aborted) {
- rememberBalance(data)
- setAccount(data)
- setError("")
- }
- } catch (err) {
- if (!controller.signal.aborted)
- setError(
- err instanceof Error && !(err instanceof TypeError)
- ? err.message
- : "无法获取积分,请重试。"
- )
- } finally {
- pending = false
- if (!controller.signal.aborted) setLoading(false)
- }
- }
- void load()
- const timer = window.setInterval(load, 15000)
- document.addEventListener("visibilitychange", load)
- return () => {
- controller.abort()
- window.clearInterval(timer)
- document.removeEventListener("visibilitychange", load)
- }
- }, [user, retry])
- return (
-
-
- 我的积分
-
-
-
- {error && (
-
- {error}
- {account && " 以下为上次获取的数据。"}
-
- )}
- {!account && !error && (
-
- 正在获取积分…
-
- )}
-
- )
-}
-
-function AccountPanel({ onLogout }: { onLogout: () => void }) {
- const { user } = useAuth()
- const { branding } = useBranding()
- const [hidden, setHidden] = useIdentityPreference()
- return (
-
- 账号
-
-
-
- - 当前账号
- -
- {user?.name || user?.email}
-
- - 团队名称
- -
- {branding.workspace_name || "—"}
-
- - 服务器
- -
- 私有化部署
-
- {window.location.origin}
-
-
-
-
-
-
-
-
-
- 此设备上的账号
-
- 此处显示当前浏览器登录的账号。
-
- {user && (
-
- -
-
-
-
- {user.name
- ? hidden
- ? maskName(user.name)
- : user.name
- : hidden
- ? maskEmail(user.email)
- : user.email}
-
- 当前
-
-
- 私有化部署 ·{" "}
- {window.location.host}
-
-
-
-
-
- )}
-
-
-
-
-
-
- )
-}
-
-function BillingPanel() {
- const { user } = useAuth()
- return user &&
-}
-
-const sections = [
- { id: "account", label: "账号", icon: UserIcon, Panel: AccountPanel },
- { id: "billing", label: "积分", icon: Coins01Icon, Panel: BillingPanel },
- { id: "appearance", label: "外观", icon: PaintBoardIcon, Panel: AppearancePanel },
-] as const
-
-export function WorkspaceSettings({ iconOnly = false }: { iconOnly?: boolean }) {
- const { logout } = useAuth()
- const [open, setOpen] = useState(false)
- const [section, setSection] = useState<(typeof sections)[number]>(sections[0])
- const [confirm, setConfirm] = useState(false)
- const [busy, setBusy] = useState(false)
- const popup = useRef(null)
- const lock = useRef(false)
- const [error, setError] = useState("")
- async function signOut() {
- if (lock.current) return
- lock.current = true
- setBusy(true)
- setError("")
- try {
- await logout()
- } catch {
- setError("退出失败,请重试。")
- } finally {
- lock.current = false
- setBusy(false)
- }
- }
- return (
-
- )
-}
diff --git a/monkeyai/web/src/pages/login-page.tsx b/monkeyai/web/src/pages/login-page.tsx
index f5178a056..8b33a0695 100644
--- a/monkeyai/web/src/pages/login-page.tsx
+++ b/monkeyai/web/src/pages/login-page.tsx
@@ -7,7 +7,7 @@ import {
import { HugeiconsIcon } from "@hugeicons/react"
import { useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
-import { Link, Navigate, useLocation, useNavigate } from "react-router-dom"
+import { Link, Navigate, useLocation } from "react-router-dom"
import { useAppToast } from "@/components/animated-toast-provider"
import { LocalizedMessage } from "@/components/localized-message"
@@ -47,8 +47,6 @@ export function LoginPage() {
const { showToast } = useAppToast()
const { isLoading, sessionFailed, refresh, acceptLogin, user } = useAuth()
const location = useLocation()
- const navigate = useNavigate()
- const reauthenticate = location.state?.reauthenticate === true
const [oauthSubmitting, setOauthSubmitting] = useState("")
const [providers, setProviders] = useState([])
const { branding } = useBranding()
@@ -60,7 +58,7 @@ export function LoginPage() {
}, [branding, t])
useEffect(() => {
- if (isLoading || sessionFailed || (user && !reauthenticate)) return
+ if (isLoading || sessionFailed || user) return
const controller = new AbortController()
api<{ providers: LoginProvider[] }>("/api/auth/v1/providers", {
signal: controller.signal,
@@ -74,7 +72,7 @@ export function LoginPage() {
}
})
return () => controller.abort()
- }, [isLoading, sessionFailed, user, reauthenticate])
+ }, [isLoading, sessionFailed, user])
useEffect(() => {
if (!oauthError || shownOauthError.current === oauthError) return
@@ -109,8 +107,8 @@ export function LoginPage() {
)
- if (!reauthenticate && user?.role === "user") return
- if (!reauthenticate && user)
+ if (user?.role === "user") return
+ if (user)
return (
@@ -201,7 +199,7 @@ export function LoginPage() {
teamName={branding.workspace_name}
toolName={branding.product_name}
onOAuthLogin={startOAuthLogin}
- onAuthenticated={(account) => { acceptLogin(account); if (reauthenticate) navigate("/client", { replace: true }) }}
+ onAuthenticated={acceptLogin}
/>
diff --git a/monkeyai/web/test/device-chat-flow.test.mjs b/monkeyai/web/test/device-chat-flow.test.mjs
deleted file mode 100644
index e42a34a8c..000000000
--- a/monkeyai/web/test/device-chat-flow.test.mjs
+++ /dev/null
@@ -1,141 +0,0 @@
-import assert from "node:assert/strict"
-import test from "node:test"
-import {
- readHistory,
- finalReplyIndex,
- readJoinedHistory,
- mergeLatest,
- replyActivity,
-} from "../src/lib/device-workspace.ts"
-import { parseUserMarkdown } from "../src/lib/device-user-markdown.ts"
-
-test("仅结束的助手答复可折叠过程,工具结束和会话空闲不代表回复结束", async () => {
- const history = async () => ({
- session: { id: "s", status: "idle" },
- toolCalls: { t: { title: "查找", status: "completed", output: "结果" } },
- messages: [
- {
- id: "a",
- role: "assistant",
- parts: [
- { type: "tool_call", toolCallId: "t" },
- { type: "error", reason: "异常" },
- { type: "text", text: "答复" },
- ],
- },
- ],
- })
- const {
- messages: [msg],
- } = await readHistory({ history }, "s")
- assert.deepEqual(
- msg.parts.map((p) => p.type),
- ["tool_call", "error", "text"]
- )
- assert.equal(msg.parts[0].output, "结果")
- assert.equal(finalReplyIndex(msg, false), 0)
- const ended = { ...msg, endedAt: 1000 }
- assert.equal(finalReplyIndex(ended, false), 2)
- assert.equal(finalReplyIndex(ended, true), 0)
- assert.equal(
- finalReplyIndex({ ...ended, parts: [...ended.parts, msg.parts[0]] }, false),
- 0
- )
-})
-test("用户正文保留列表与链接原文,围栏代码不解析标题", () => {
- const blocks = parseUserMarkdown(
- "- [条目](地址)\n## 标题\n~~~js\n# 注释\n~~~"
- )
- assert.equal(blocks[0].lines[0][0].text, "- [条目](地址)")
- assert.equal(blocks[1].type, "heading")
- assert.equal(blocks[2].text, "# 注释")
-})
-
-test("重连跨过多页:补到已读区间,保留手动上翻的旧页,状态以最新快照为准", async () => {
- const ids = (a, b) =>
- Array.from({ length: b - a + 1 }, (_, i) => String(a + i))
- const calls = []
- const ch = {
- history: async (_id, cursor) => {
- calls.push(cursor)
- const end = cursor ? Number(cursor) : 135
- return {
- session: { id: "s", status: cursor ? "idle" : "running" },
- olderCursor: String(end - 30),
- messages: ids(end - 29, end).map((id) => ({
- id,
- role: "assistant",
- parts: [],
- })),
- }
- },
- }
- const fresh = await readJoinedHistory(
- ch,
- "s",
- new Set(ids(31, 60)),
- new AbortController().signal
- )
- const previous = { messages: ids(11, 60).map((id) => ({ id })), older: "10" }
- const joined = mergeLatest(previous, fresh)
- assert.deepEqual(calls, [undefined, "105", "75"])
- assert.deepEqual(
- joined.messages.map((m) => m.id),
- ids(11, 135)
- )
- assert.equal(joined.older, "10")
- assert.equal(fresh.status, "running")
-})
-test("补页游标循环不发布残缺时间线,后续刷新可重试", async () => {
- const ch = {
- history: async () => ({
- session: { id: "s" },
- messages: [],
- olderCursor: "same",
- }),
- }
- await assert.rejects(
- readJoinedHistory(ch, "s", new Set(["old"]), new AbortController().signal),
- /游标/
- )
-})
-test("运行提示只使用末条未结束的助手消息;快照标记正文已有错误时不重复展示", async () => {
- const tool = {
- type: "tool_call",
- name: "Read",
- status: "in_progress",
- title: "读取文件",
- },
- last = { role: "assistant", parts: [tool, { type: "text" }] }
- assert.equal(replyActivity("running", last), "正在读取文件…")
- assert.equal(
- replyActivity("running", { ...last, parts: [{ type: "thought" }] }),
- "正在思考…"
- )
- assert.equal(
- replyActivity("running", { ...last, parts: [{ type: "text" }] }),
- "正在回复…"
- )
- assert.equal(
- replyActivity("running", { ...last, endedAt: 100 }),
- "正在调用模型…"
- )
- assert.equal(replyActivity("idle", last), "")
- for (const inBody of [false, true]) {
- const ch = {
- history: async () => ({
- session: {
- id: "s",
- status: "error",
- lastError: "读取失败",
- lastErrorInTranscript: inBody,
- },
- messages: [],
- }),
- }
- assert.equal(
- (await readHistory(ch, "s")).sessionError,
- inBody ? "" : "读取失败"
- )
- }
-})
diff --git a/monkeyai/web/test/device-message-quotes.test.mjs b/monkeyai/web/test/device-message-quotes.test.mjs
deleted file mode 100644
index efb864177..000000000
--- a/monkeyai/web/test/device-message-quotes.test.mjs
+++ /dev/null
@@ -1,92 +0,0 @@
-import test from "node:test"
-import assert from "node:assert/strict"
-import {
- appendQuote,
- deviceQuoteLimit,
- quoteFromMessage,
-} from "../src/lib/device-message-quotes.ts"
-import {
- composerDrafts,
- draftKey,
-} from "../src/pages/client/composer-drafts.ts"
-import { sendMessage } from "../src/lib/device-workspace.ts"
-
-const source = { id: "a", role: "user", at: 1720000000000 }
-const quote = quoteFromMessage("s", source, [
- { type: "text", text: "**原文**\n\n设计偏好:不要引用" },
- { type: "tool_call", text: "不要引用" },
-])
-test("源消息身份和原文随队列提交,能力不够或跨会话时不发包", async () => {
- const requests = []
- const channel = {
- canWrite: true,
- quoteLimit: deviceQuoteLimit({
- agentCapabilities: {
- _meta: { messageQuotes: { version: 1, multiple: true } },
- },
- }),
- request: async (method, p) => {
- requests.push(p)
- return { sessionId: p.sessionId }
- },
- }
- assert.equal(quote.text, "**原文**")
- assert.equal(
- quoteFromMessage("s", source, [{ type: "error", reason: "诊断" }]),
- undefined
- )
- const first = appendQuote([], quote, "s", channel.quoteLimit),
- second = { ...quote, messageId: "b", role: "assistant" }
- assert.equal(appendQuote(first, quote, "s", 1), first)
- assert.throws(() => appendQuote(first, second, "s", 1))
- assert.throws(() =>
- appendQuote(first, { ...second, text: "甲".repeat(64000) }, "s", 16)
- )
- await sendMessage(channel, "s", "追问", first)
- await sendMessage(channel, "s", "再问", [quote, second])
- assert.deepEqual(
- requests.map(({ text, quote, quotes }) => ({ text, quote, quotes })),
- [
- { text: "追问", quote, quotes: undefined },
- { text: "再问", quote: undefined, quotes: [quote, second] },
- ]
- )
- await assert.rejects(sendMessage(channel, "other", "提问", first))
- await assert.rejects(sendMessage(channel, "s", " ", first))
- await assert.rejects(
- sendMessage({ ...channel, quoteLimit: 0 }, "s", "提问", first)
- )
- assert.equal(requests.length, 2)
-})
-test("仅有引用也能恢复草稿,未确认的引用与发送期间输入的新草稿分开", () => {
- const keys = new Map(),
- storage = {
- getItem: (k) => keys.get(k),
- setItem: (k, v) => keys.set(k, v),
- removeItem: (k) => keys.delete(k),
- }
- const original = Object.getOwnPropertyDescriptor(globalThis, "localStorage")
- Object.defineProperty(globalThis, "localStorage", {
- configurable: true,
- value: storage,
- })
- try {
- const key = draftKey("user", "machine", "s", ""),
- other = draftKey("user", "machine", "other", "")
- const drafts = composerDrafts()
- drafts.update(key, { quotes: [quote] })
- assert.deepEqual(composerDrafts().read(key).quotes, [quote])
- assert.equal(drafts.read(other).quotes, undefined)
- drafts.begin(key, "正在发送", [quote])
- drafts.update(key, { text: "新草稿" })
- drafts.settle(key, false)
- assert.deepEqual(composerDrafts().read(key).pendingQuotes, [quote])
- assert.equal(drafts.read(key).text, "新草稿")
- drafts.settle(key, true)
- assert.equal(drafts.read(key).pendingQuotes, undefined)
- assert.equal(drafts.read(key).text, "新草稿")
- } finally {
- if (original) Object.defineProperty(globalThis, "localStorage", original)
- else delete globalThis.localStorage
- }
-})
diff --git a/monkeyai/web/test/device-new-model.test.mjs b/monkeyai/web/test/device-new-model.test.mjs
deleted file mode 100644
index 8e24a1c6b..000000000
--- a/monkeyai/web/test/device-new-model.test.mjs
+++ /dev/null
@@ -1,84 +0,0 @@
-import assert from "node:assert/strict"
-import test from "node:test"
-import { newModelSelection } from "../src/lib/device-models.ts"
-import { createSession } from "../src/lib/device-workspace.ts"
-
-const model = (
- id,
- kind = "text",
- levels = ["off", "low", "medium", "high"],
- ready = true
-) => ({ id, kind, levels, ready })
-const catalog = [
- model("image", "image"),
- model("unavailable", "text", [], false),
- model("z"),
- model("a", "text", ["on"]),
-]
-
-test("新建会话首选目录中可用的对话模型,创建参数不夹带媒体回显", async () => {
- const selection = newModelSelection(catalog, {})
- assert.deepEqual(selection, {
- model: "z",
- thinking: { enabled: true, effort: "medium" },
- })
- await createSession(
- {
- canWrite: true,
- request: async (method, { _meta: { operationId, ...meta } }) => {
- assert.equal(method, "session/new")
- assert.ok(operationId)
- assert.deepEqual(meta, {
- ...selection,
- mode: "auto",
- profile: "specialist",
- })
- return { sessionId: "new" }
- },
- },
- undefined,
- { mode: "auto", expertId: "specialist" },
- selection
- )
-})
-
-test("切换模型仅取本模型的草稿档位,保留显式媒体选择", () => {
- const draft = {
- model: "z",
- depths: { z: { enabled: true, effort: "high" } },
- mediaModels: { image: "image" },
- }
- assert.equal(newModelSelection(catalog, draft).thinking.effort, "high")
- assert.deepEqual(newModelSelection(catalog, { ...draft, model: "a" }), {
- model: "a",
- thinking: { enabled: true },
- mediaModels: { image: "image" },
- })
- assert.equal(newModelSelection([catalog[3], ...catalog], draft).model, "z")
-})
-
-test("无可用对话模型时不指定模型与思考,不阻止普通发送", () => {
- assert.deepEqual(
- newModelSelection([], {
- model: "removed",
- depths: { removed: { enabled: false } },
- }),
- {}
- )
- assert.deepEqual(newModelSelection(catalog.slice(0, 2), {}), {})
-})
-
-test("可关闭则保留关闭,协议档位变化后重新选择有效档位", () => {
- const draft = { depths: { z: { enabled: false } } }
- assert.deepEqual(newModelSelection(catalog, draft).thinking, {
- enabled: false,
- })
- assert.deepEqual(
- newModelSelection([model("z", "text", ["low", "medium"])], draft).thinking,
- { enabled: true, effort: "low" }
- )
- assert.deepEqual(
- newModelSelection([model("z", "text", ["high"])], {}).thinking,
- { enabled: true, effort: "high" }
- )
-})
diff --git a/monkeyai/web/test/device-plan.test.mjs b/monkeyai/web/test/device-plan.test.mjs
deleted file mode 100644
index 177fbfa4f..000000000
--- a/monkeyai/web/test/device-plan.test.mjs
+++ /dev/null
@@ -1,37 +0,0 @@
-import test from "node:test"
-import assert from "node:assert/strict"
-import { readHistory } from "../src/lib/device-workspace.ts"
-
-test("只读快照按设备顺序恢复计划,更新和移除不会沿用上一次的步骤", async () => {
- const session = { id: "active", status: "running" }
- const messages = [
- {
- id: "m",
- role: "assistant",
- parts: [{ type: "text", text: "1. 不从消息猜计划" }],
- },
- ]
- const ch = { canWrite: false, history: async () => ({ session, messages }) }
- const steps = [
- { content: "已核对", status: "completed" },
- { content: "正在核对", status: "in_progress" },
- { content: "等候", status: "pending" },
- ]
- session.plan = steps.map((step) => ({ ...step, priority: "medium" }))
- assert.deepEqual((await readHistory(ch, "active")).plan, steps)
- session.plan[1].status = "completed"
- assert.equal((await readHistory(ch, "active")).plan[1].status, "completed")
- for (const plan of [
- [],
- null,
- [steps[0], { content: "无效状态", status: "other" }],
- ]) {
- session.plan = plan
- const page = await readHistory(ch, "active")
- assert.deepEqual(page.plan, [])
- assert.equal(page.messages[0].text, messages[0].parts[0].text)
- }
- delete session.plan
- assert.deepEqual((await readHistory(ch, "active")).plan, [])
- await assert.rejects(readHistory(ch, "other"), /会话消息无效/)
-})
diff --git a/monkeyai/web/test/device-queue-recovery.test.mjs b/monkeyai/web/test/device-queue-recovery.test.mjs
deleted file mode 100644
index d345e3466..000000000
--- a/monkeyai/web/test/device-queue-recovery.test.mjs
+++ /dev/null
@@ -1,73 +0,0 @@
-import assert from "node:assert/strict"
-import test from "node:test"
-import {
- composerDrafts,
- draftKey,
-} from "../src/pages/client/composer-drafts.ts"
-import { queueReceipt, sendMessage } from "../src/lib/device-workspace.ts"
-
-test("设备入队后断线,刷新页面用原编号查询,不再次入队", async (t) => {
- const values = new Map()
- const original = Object.getOwnPropertyDescriptor(globalThis, "localStorage")
- Object.defineProperty(globalThis, "localStorage", {
- configurable: true,
- value: {
- setItem: (k, v) => values.set(k, v),
- getItem: (k) => values.get(k) ?? null,
- },
- })
- t.after(() =>
- original
- ? Object.defineProperty(globalThis, "localStorage", original)
- : delete globalThis.localStorage
- )
- const key = draftKey("user", "device", "session", "")
- const id = crypto.randomUUID(),
- calls = []
- const channel = {
- canWrite: true,
- async request(method, params) {
- calls.push(method)
- if (method === "_monkeyai/session/queue") {
- assert.equal(params.id, id)
- assert.equal(params._meta.operationId, id)
- throw new Error("回执丢失")
- }
- assert.equal(params.operationId, id)
- return {
- version: 1,
- method: "_monkeyai/session/queue",
- state: "completed",
- operationId: id,
- target: { userId: "user", machineId: "device" },
- sessionId: "session",
- clientMessageId: id,
- result: { sessionId: "session", clientMessageId: id, action: "add" },
- }
- },
- }
- const drafts = composerDrafts()
- drafts.begin(key, "任务", [], [], id)
- await assert.rejects(
- sendMessage(channel, "session", "任务", [], [], id),
- /回执丢失/
- )
- drafts.settle(key, false)
- const saved = composerDrafts().read(key)
- assert.equal(saved.pending, "任务")
- assert.equal(saved.text, "")
- assert.equal(
- await queueReceipt(
- channel,
- "session",
- saved.pendingOperation,
- "user",
- "device"
- ),
- "completed"
- )
- assert.deepEqual(calls, [
- "_monkeyai/session/queue",
- "_monkeyai/operations/get",
- ])
-})
diff --git a/monkeyai/web/test/device-sidebar-actions.test.mjs b/monkeyai/web/test/device-sidebar-actions.test.mjs
deleted file mode 100644
index b694f942f..000000000
--- a/monkeyai/web/test/device-sidebar-actions.test.mjs
+++ /dev/null
@@ -1,65 +0,0 @@
-import assert from "node:assert/strict"
-import test from "node:test"
-import {
- applySidebarAction,
- readSidebarFolder,
-} from "../src/lib/device-sidebar-actions.ts"
-
-test("批量整理逐项报告结果,可以只重试失败的会话", async () => {
- const sent = []
- const ch = {
- canWrite: true,
- async request(method, params) {
- assert.equal(method, "_monkeyai/session/flags")
- sent.push(params.sessionId)
- if (params.sessionId === "B" && sent.length === 2)
- throw new Error("设备忙")
- },
- }
- const op = {
- kind: "flag",
- ids: ["A", "B", "C"],
- field: "archived",
- value: true,
- }
- const result = await applySidebarAction(ch, op)
- assert.deepEqual(result, {
- succeeded: ["A", "C"],
- failures: [{ id: "B", reason: "设备忙" }],
- })
- assert.deepEqual(
- await applySidebarAction(ch, {
- ...op,
- ids: result.failures.map((f) => f.id),
- }),
- { succeeded: ["B"], failures: [] }
- )
- assert.deepEqual(sent, ["A", "B", "C", "B"])
-})
-
-test("缺少目录能力不发请求;返回主目录不沿用旧路径", async () => {
- const requests = []
- const ch = {
- canWrite: true,
- canBrowseFolders: false,
- async request(method, params) {
- assert.equal(method, "_monkeyai/directories/list")
- requests.push(params)
- if (params.path) throw new Error("目录不存在")
- return {
- target: { userId: "u", machineId: "m" },
- path: "/home/u",
- parent: "/home",
- entries: [],
- nextOffset: null,
- revision: "r",
- }
- },
- }
- await assert.rejects(readSidebarFolder(ch, "u", "m", "/old"), /不支持/)
- assert.deepEqual(requests, [])
- ch.canBrowseFolders = true
- await assert.rejects(readSidebarFolder(ch, "u", "m", "/old"), /目录不存在/)
- assert.equal((await readSidebarFolder(ch, "u", "m", "")).path, "/home/u")
- assert.deepEqual(requests, [{ path: "/old" }, {}])
-})
diff --git a/monkeyai/web/test/device-sidebar-completions.test.mjs b/monkeyai/web/test/device-sidebar-completions.test.mjs
deleted file mode 100644
index 588324ccb..000000000
--- a/monkeyai/web/test/device-sidebar-completions.test.mjs
+++ /dev/null
@@ -1,70 +0,0 @@
-import test from "node:test"
-import assert from "node:assert/strict"
-import { sidebarCompletions } from "../src/lib/device-sidebar-completions.ts"
-
-const end = "2026-11-01T11:00:00Z",
- before = "2026-11-01T10:59:59Z"
-function fixture() {
- const tracker = sidebarCompletions()
- const event = (seq, extra = {}, status = "idle") =>
- tracker.observe("s", {
- eventSeq: seq,
- state: { status, updatedAt: end },
- finish: true,
- ...extra,
- })
- const visible = (extra = {}, version = tracker.version) =>
- tracker
- .list([{ id: "s", status: "idle", updatedAt: end, ...extra }], version)
- .has("s")
- return { tracker, event, visible }
-}
-test("真实轮次成功后才提醒,旧快照、旧回执、历史空闲都不是新完成", () => {
- const { tracker, event, visible } = fixture()
- assert.equal(visible(), false)
- event(1, { finish: false })
- assert.equal(visible(), false)
- event(2)
- assert.equal(visible({}, 1), false)
- assert.equal(visible(), true)
- tracker.read("s", before)
- assert.equal(visible(), true)
- tracker.read("s", end)
- assert.equal(visible(), false)
- event(2)
- assert.equal(visible(), false)
- event(5, {}, "running")
- event(4)
- assert.equal(visible(), false)
- event(6)
- assert.equal(visible({ readAt: end }), false)
-})
-test("等待子代理与交互收尾,不把连续队列、定时收尾、错误或中断当成成功", () => {
- const { event, visible } = fixture()
- event(1)
- assert.equal(visible({ agentsRunning: true }), false)
- assert.equal(visible({ pendingInteraction: true }), false)
- assert.equal(visible(), true)
- event(2, { queueContinues: true })
- assert.equal(visible(), false)
- event(3, { scheduleFinished: true })
- assert.equal(visible(), false)
- event(4, {}, "error")
- assert.equal(visible(), false)
- event(5, {}, "interrupted")
- assert.equal(visible(), false)
-})
-test("目标暂停不报完成,后续普通轮次可正常提醒", () => {
- const { event, visible } = fixture()
- event(
- 1,
- { finish: false, goalSummary: { status: "active", is_current: true } },
- "running"
- )
- event(2)
- assert.equal(visible({ goalStatus: "active" }), false)
- assert.equal(visible({ goalStatus: "paused" }), false)
- event(3, { finish: false }, "running")
- event(4)
- assert.equal(visible(), true)
-})
diff --git a/monkeyai/web/test/device-uploads.test.mjs b/monkeyai/web/test/device-uploads.test.mjs
deleted file mode 100644
index 7f949b68f..000000000
--- a/monkeyai/web/test/device-uploads.test.mjs
+++ /dev/null
@@ -1,102 +0,0 @@
-import test from "node:test"
-import assert from "node:assert/strict"
-import { createHash } from "node:crypto"
-import { uploadLimits, uploadFile } from "../src/lib/device-uploads.ts"
-import {
- composerDrafts,
- draftKey,
-} from "../src/pages/client/composer-drafts.ts"
-
-function fixture(fault) {
- let slot
- const calls = [],
- bytes = []
- const transport = {
- user: "u",
- machine: "m",
- limits: { maxFileBytes: 64, maxChunkBytes: 2 },
- rpc: async (m, p) => {
- calls.push(m)
- if (m.endsWith("/cancel")) return {}
- if (m.endsWith("/create"))
- slot = {
- ...p,
- target: {
- userId: "u",
- machineId: fault === "target" ? "other" : "m",
- },
- }
- if (m.endsWith("/complete")) {
- assert.equal(p.sessionId, "s")
- assert.equal(p.uploadId, slot.uploadId)
- assert.ok(p._meta.operationId)
- return {
- ...slot,
- state: "completed",
- offset: slot.size,
- sha256: fault === "digest" ? "other" : slot.sha256,
- }
- }
- return { ...slot, state: "uploading", offset: 0 }
- },
- chunk: async (id, s, offset, body) => {
- assert.equal(s, "s")
- assert.equal(id, slot.uploadId)
- assert.equal(offset, bytes.length)
- bytes.push(...new Uint8Array(await body.arrayBuffer()))
- return new Response(null, {
- status: 204,
- headers: {
- "Upload-Offset": String(fault === "offset" ? 99 : bytes.length),
- "Upload-Length": String(slot.size),
- },
- })
- },
- }
- return { transport, bytes, calls, slot: () => slot }
-}
-test("附件逐块传到当前会话,确认摘要后才返回 uploadId", async () => {
- const f = fixture(),
- result = await uploadFile(
- f.transport,
- "s",
- new File(["hello"], "说明.txt"),
- () => {}
- )
- assert.equal(Buffer.from(f.bytes).toString(), "hello")
- assert.equal(
- f.slot().sha256,
- createHash("sha256").update("hello").digest("hex")
- )
- assert.deepEqual(result, { name: "说明.txt", uploadId: f.slot().uploadId })
- for (const fault of ["target", "offset", "digest"]) {
- const f = fixture(fault)
- await assert.rejects(
- uploadFile(f.transport, "s", new File(["hello"], "说明.txt"), () => {})
- )
- assert.ok(f.calls.at(-1).endsWith("/cancel"))
- if (fault === "target") assert.equal(f.bytes.length, 0)
- }
- assert.equal(uploadLimits({}), undefined)
- assert.equal(
- uploadLimits({
- agentCapabilities: {
- _meta: { uploads: { version: 1, maxFileBytes: 64, maxChunkBytes: 0 } },
- },
- }),
- undefined
- )
-})
-test("仅附件发送收不到回执时保留待核对的原文件,不转成可自动重发的空草稿", () => {
- const d = composerDrafts(),
- key = draftKey("u", "m", "s", ""),
- files = [
- { id: "a", name: "说明.txt", size: 1, file: new File(["a"], "说明.txt") },
- ]
- d.begin(key, "", [], files)
- d.settle(key, false)
- assert.equal(d.read(key).pending, "")
- assert.equal(d.read(key).pendingFiles[0].file, files[0].file)
- d.settle(key, true)
- assert.equal(d.read(key).pendingFiles, undefined)
-})
diff --git a/monkeyai/web/test/device-workspace.test.mjs b/monkeyai/web/test/device-workspace.test.mjs
deleted file mode 100644
index 31d510415..000000000
--- a/monkeyai/web/test/device-workspace.test.mjs
+++ /dev/null
@@ -1,104 +0,0 @@
-import assert from "node:assert/strict"
-import test from "node:test"
-import {
- beginDeviceAuthorization,
- completeDeviceAuthorization,
- restoreDeviceGrant,
- saveDeviceGrant,
-} from "../src/lib/workspace-oauth.ts"
-import { refreshedRead, sendMessage } from "../src/lib/device-workspace.ts"
-
-test("授权只按实际授予的 scope 恢复;只读用户不会发出写请求", async (t) => {
- const origin = "http://localhost:5173",
- store = new Map()
- for (const [name, value] of Object.entries({
- location: { origin },
- sessionStorage: {
- setItem: (k, v) => store.set(k, v),
- getItem: (k) => store.get(k) ?? null,
- removeItem: (k) => store.delete(k),
- },
- })) {
- const prior = Object.getOwnPropertyDescriptor(globalThis, name)
- Object.defineProperty(globalThis, name, { configurable: true, value })
- t.after(() => {
- if (prior) Object.defineProperty(globalThis, name, prior)
- else delete globalThis[name]
- })
- }
- let scopes = "device:connect session:read"
- t.mock.method(globalThis, "fetch", async (url) =>
- Response.json(
- url === "/oauth/token"
- ? {
- token_type: "Bearer",
- access_token: "fixture",
- expires_in: 60,
- scope: scopes,
- }
- : { id: "u" }
- )
- )
- const target = {
- machineId: "00000000-0000-4000-8000-000000000001",
- name: "设备",
- sessionId: "s",
- }
- for (const [write, files, upload] of [
- [false, false, false],
- [false, false, true],
- [true, false, false],
- [true, true, false],
- [true, true, true],
- ]) {
- scopes =
- "device:connect session:read" +
- (write ? " session:control" : "") +
- (files ? " files:read" : "") +
- (upload ? " files:write" : "")
- const url = new URL(await beginDeviceAuthorization("u", target), origin)
- assert.equal(
- url.searchParams.get("scope"),
- "device:connect session:read session:control environment:read environment:manage files:read files:write"
- )
- const grant = await completeDeviceAuthorization(
- "u",
- new URLSearchParams({
- code: "fixture",
- state: url.searchParams.get("state"),
- })
- )
- assert.deepEqual(grant.target, target)
- saveDeviceGrant("u", grant)
- assert.equal(!!restoreDeviceGrant("u").canControlSessions, write)
- assert.equal(!!restoreDeviceGrant("u").canReadFiles, files)
- assert.equal(!!restoreDeviceGrant("u").canUploadFiles, write && upload)
- }
- await assert.rejects(
- sendMessage(
- { canWrite: false, request: () => assert.fail("只读授权不可发包") },
- "s",
- "test"
- ),
- /控制授权/
- )
-})
-
-test("切换会话或断开连接后忽略在途历史响应", async () => {
- let done
- const read = new Promise((resolve) => {
- done = resolve
- })
- const applied = []
- const refresh = refreshedRead(
- () => read,
- (v) => applied.push(v),
- (e) => assert.fail(String(e))
- )
- const pending = refresh.run()
- refresh.schedule()
- refresh.stop()
- done("旧会话")
- await pending
- assert.deepEqual(applied, [])
-})
diff --git a/monkeyai/web/test/workspace-balance.test.mjs b/monkeyai/web/test/workspace-balance.test.mjs
deleted file mode 100644
index 911d3e3ae..000000000
--- a/monkeyai/web/test/workspace-balance.test.mjs
+++ /dev/null
@@ -1,44 +0,0 @@
-import assert from "node:assert/strict"
-import test from "node:test"
-import {
- lastBalance,
- readBalance,
- rememberBalance,
-} from "../src/lib/workspace-balance.ts"
-
-test("余额可以在本标签页恢复,不会跨账号显示,清除后不可恢复", (t) => {
- let saved = null
- const descriptor = Object.getOwnPropertyDescriptor(
- globalThis,
- "sessionStorage"
- )
- Object.defineProperty(globalThis, "sessionStorage", {
- configurable: true,
- value: {
- getItem: () => saved,
- setItem: (_, value) => {
- saved = value
- },
- removeItem: () => {
- saved = null
- },
- },
- })
- t.after(() => {
- if (descriptor)
- Object.defineProperty(globalThis, "sessionStorage", descriptor)
- else delete globalThis.sessionStorage
- })
- const overview = readBalance(
- { user_id: "a", balance: "-0.000001", quota: "0.00" },
- "a"
- )
- assert.ok(overview)
- rememberBalance(overview)
- assert.deepEqual(lastBalance("a"), overview)
- assert.equal(lastBalance("b"), null)
- rememberBalance(null)
- assert.equal(lastBalance("a"), null)
- saved = '{"user_id":"a","balance":"无效","quota":"0"}'
- assert.equal(lastBalance("a"), null)
-})
diff --git a/monkeyai/web/test/workspace-cloud-list.test.mjs b/monkeyai/web/test/workspace-cloud-list.test.mjs
deleted file mode 100644
index 4e1f7852e..000000000
--- a/monkeyai/web/test/workspace-cloud-list.test.mjs
+++ /dev/null
@@ -1,100 +0,0 @@
-import assert from "node:assert/strict"
-import test from "node:test"
-import {
- environments,
- workspaceDeviceList,
-} from "../src/lib/workspace-cloud.ts"
-
-const env = {
- id: "a",
- name: "我的云电脑",
- machine_id: null,
- phase: "pending",
- desired: "running",
- generation: 1,
- observed_generation: 0,
- connectable: false,
- spec: { runtime_package: { architecture: "arm64" } },
-}
-const endpoint = {
- machine_id: "m",
- display_name: env.name,
- platform: "linux",
- arch: "arm64",
- status: "online",
-}
-
-test("申请、绑定设备和就绪始终使用同一张卡片和同一套计数", () => {
- const pending = workspaceDeviceList([], [env])
- assert.equal(pending.summary, "共 1 台设备 · 1 台申请中")
- assert.equal(pending.rows[0].arch, "arm64")
- const bound = { ...env, machine_id: "m", phase: "starting" }
- const binding = workspaceDeviceList([endpoint], [bound])
- assert.equal(binding.summary, pending.summary)
- assert.deepEqual(binding.rows, [{ ...pending.rows[0], machine_id: "m" }])
- const ready = workspaceDeviceList(
- [endpoint],
- [{ ...bound, phase: "running", connectable: true }]
- )
- assert.equal(ready.summary, "共 1 台设备 · 1 台在线")
- assert.equal(ready.rows[0].key, pending.rows[0].key)
- assert.equal(
- workspaceDeviceList([{ ...endpoint, machine_id: "other" }], [bound])
- .summary,
- "共 2 台设备 · 1 台在线 · 1 台申请中"
- )
-})
-
-test("只有已确认的创建失败才移除设备;查询失败、运行异常及已停止均保留", async (t) => {
- let status = "succeeded",
- unavailable = false,
- reads = 0
- let snapshot = {
- ...env,
- phase: "failed",
- observed_generation: 1,
- machine_id: "m",
- }
- t.mock.method(globalThis, "fetch", async (url, init) => {
- assert.equal(init.method, undefined)
- if (!url.includes("/operations?"))
- return Response.json({ items: [snapshot], page: 1 })
- reads++
- return unavailable
- ? new Response(null, { status: 503 })
- : Response.json({
- items: [
- {
- id: "op",
- kind: "create",
- generation: 1,
- desired: "running",
- status,
- },
- ],
- page: 1,
- })
- })
- const known = new Set()
- const read = async () =>
- workspaceDeviceList(
- [endpoint],
- await environments("fixture", new AbortController().signal, known)
- )
- assert.equal((await read()).rows[0].status, "failed")
- unavailable = true
- assert.equal((await read()).rows.length, 1)
- unavailable = false
- status = "failed"
- assert.equal((await read()).rows.length, 0)
- const count = reads
- assert.equal((await read()).summary, "共 0 台设备 · 0 台在线")
- assert.equal(reads, count)
- snapshot = {
- ...snapshot,
- generation: 2,
- desired: "stopped",
- phase: "stopped",
- }
- assert.equal((await read()).rows[0].status, "stopped")
-})
diff --git a/monkeyai/web/test/workspace-devices.test.mjs b/monkeyai/web/test/workspace-devices.test.mjs
deleted file mode 100644
index e5380e47a..000000000
--- a/monkeyai/web/test/workspace-devices.test.mjs
+++ /dev/null
@@ -1,200 +0,0 @@
-import assert from "node:assert/strict"
-import { createHash } from "node:crypto"
-import test from "node:test"
-import { isSafeClientLaunchURL } from "../src/lib/client-callback.ts"
-import {
- beginDeviceAuthorization,
- clearDeviceGrant,
- completeDeviceAuthorization,
- restoreDeviceGrant,
- saveDeviceGrant,
-} from "../src/lib/workspace-oauth.ts"
-import { listWorkspaceDevices } from "../src/lib/workspace-devices.ts"
-
-const origin = "http://localhost:5173"
-function browser(t) {
- const values = new Map()
- for (const [name, value] of Object.entries({
- location: { origin },
- window: { location: { origin } },
- sessionStorage: {
- setItem: (k, v) => values.set(k, v),
- removeItem: (k) => values.delete(k),
- getItem: (k) => values.get(k) ?? null,
- },
- })) {
- const original = Object.getOwnPropertyDescriptor(globalThis, name)
- Object.defineProperty(globalThis, name, { configurable: true, value })
- t.after(() => {
- if (original) Object.defineProperty(globalThis, name, original)
- else delete globalThis[name]
- })
- }
- return values
-}
-
-test("普通 HTTP 缺少 crypto.subtle 时仍生成有效的 PKCE S256 挑战", async (t) => {
- const values = browser(t)
- location.origin = "http://192.0.2.1:5173"
- const original = Object.getOwnPropertyDescriptor(globalThis, "crypto")
- const getRandomValues = crypto.getRandomValues.bind(crypto)
- Object.defineProperty(globalThis, "crypto", { configurable: true, value: { getRandomValues } })
- t.after(() => Object.defineProperty(globalThis, "crypto", original))
- const url = new URL(await beginDeviceAuthorization("test-user"), location.origin)
- const { verifier } = JSON.parse([...values.values()][0])
- assert.equal(url.pathname, "/oauth/authorize")
- assert.equal(url.searchParams.get("code_challenge_method"), "S256")
- assert.equal(url.searchParams.get("code_challenge"), createHash("sha256").update(verifier).digest("base64url"))
-})
-
-test("同标签页刷新只恢复同账号的短期访问令牌", (t) => {
- const values = browser(t)
- const grant = { token: "short-lived", expiresAt: Date.now() + 60_000 }
- saveDeviceGrant("alice", { ...grant, refresh_token: "must-not-persist" })
- assert.deepEqual(JSON.parse([...values.values()][0]), {
- user: "alice",
- ...grant,
- })
- assert.deepEqual(restoreDeviceGrant("alice"), grant)
- assert.equal(restoreDeviceGrant("bob"), null)
- assert.equal(restoreDeviceGrant("alice"), null)
- saveDeviceGrant("alice", grant)
- clearDeviceGrant()
- assert.equal(restoreDeviceGrant("alice"), null)
-})
-
-test("过期、损坏或退出会话的设备授权不会恢复", (t) => {
- const values = browser(t)
- saveDeviceGrant("alice", { token: "expired", expiresAt: Date.now() })
- const [key] = values.keys()
- assert.equal(restoreDeviceGrant("alice"), null)
- assert.equal(values.has(key), false)
- values.set(key, "not-json")
- assert.equal(restoreDeviceGrant("alice"), null)
- assert.equal(values.has(key), false)
- saveDeviceGrant("alice", { token: "valid", expiresAt: Date.now() + 60_000 })
- assert.equal(restoreDeviceGrant(null), null)
- assert.equal(values.has(key), false)
-})
-
-test("同源回调和 PKCE 授权码只兑换一次,令牌与当前账号匹配", async (t) => {
- browser(t)
- let exchanges = 0
- const fetchMock = t.mock.method(globalThis, "fetch", async (url, init) => {
- if (url === "/oauth/token") {
- exchanges++
- assert.equal(
- createHash("sha256")
- .update(init.body.get("code_verifier"))
- .digest("base64url"),
- request.get("code_challenge")
- )
- return Response.json({
- access_token: "fixture",
- token_type: "Bearer",
- expires_in: 60,
- })
- }
- assert.equal(url, "/api/v1/me")
- assert.equal(init.headers.Authorization, "Bearer fixture")
- return Response.json({ id: "test-user" })
- })
- const entry = new URL(await beginDeviceAuthorization("test-user"), origin)
- assert.equal(fetchMock.mock.callCount(), 0)
- assert.equal(entry.origin + entry.pathname, origin + "/oauth/authorize")
- const request = entry.searchParams
- assert.equal(request.get("redirect_uri"), origin + "/client/oauth/callback")
- assert.equal(
- request.get("scope"),
- "device:connect session:read session:control environment:read environment:manage files:read files:write"
- )
- assert.equal(request.get("client_id"), "monkeyai-web")
- const redirect = request.get("redirect_uri"),
- params = new URLSearchParams({
- code: "fixture",
- state: request.get("state"),
- })
- assert.equal(
- isSafeClientLaunchURL("monkeyai-web", redirect, redirect + "?" + params, origin + "/client-login", []),
- true
- )
- assert.equal(
- isSafeClientLaunchURL(
- "monkeyai-web",
- origin + "/login",
- origin + "/login?" + params,
- origin + "/client-login", []
- ),
- false
- )
- assert.equal(
- (await completeDeviceAuthorization("test-user", params)).token,
- "fixture"
- )
- await assert.rejects(completeDeviceAuthorization("test-user", params))
- assert.equal(exchanges, 1)
- await beginDeviceAuthorization("test-user")
- await assert.rejects(completeDeviceAuthorization("test-user", params))
- assert.equal(exchanges, 1)
-})
-
-test("远端授权页只返回同源或已登记的本地来源,且须与申请地址一致", (t) => {
- browser(t)
- window.location.origin = "https://auth.example.test"
- const local = origin + "/client/oauth/callback"
- const remote = window.location.origin + "/client/oauth/callback"
- const valid = (registered, destination = registered, origins = []) =>
- isSafeClientLaunchURL(
- "monkeyai-web",
- registered,
- destination + "?code=c&state=s",
- window.location.origin + "/client-login",
- origins
- )
- assert.equal(valid(local), false)
- assert.ok(valid(local, local, [origin]))
- assert.ok(valid(remote))
- assert.equal(valid(remote, local, [origin]), false)
- assert.equal(valid(local, remote, [origin]), false)
- for (const other of [
- "https://other.example.test/client/oauth/callback",
- "http://localhost:5174/client/oauth/callback",
- origin + "/login",
- ])
- assert.equal(valid(other), false)
-})
-
-test("设备列表分页只发 Bearer、保留离线设备、权限错误不是空列表", async (t) => {
- const pages = []
- const request = t.mock.method(globalThis, "fetch", async (url, init) => {
- assert.equal(init.headers.Authorization, "Bearer sample")
- assert.equal(init.credentials, "omit")
- const parsed = new URL(url, origin)
- assert.equal(parsed.pathname, "/api/v1/endpoints")
- assert.equal(parsed.searchParams.get("capability"), "execute")
- const page = Number(parsed.searchParams.get("page"))
- pages.push(page)
- return Response.json({
- page,
- total: 101,
- items: Array.from({ length: page === 1 ? 100 : 1 }, (_, i) => ({
- machine_id: page + ":" + i,
- status: page === 1 ? "online" : "offline",
- })),
- })
- })
- const result = await listWorkspaceDevices(
- "sample",
- new AbortController().signal
- )
- assert.deepEqual(pages, [1, 2])
- assert.equal(result.length, 101)
- assert.equal(result.at(-1).status, "offline")
- for (const status of [401, 403]) {
- request.mock.mockImplementation(async () => new Response(null, { status }))
- await assert.rejects(
- listWorkspaceDevices("sample", new AbortController().signal),
- { status }
- )
- }
-})
diff --git a/monkeyai/web/vite.config.ts b/monkeyai/web/vite.config.ts
index b60cf7c1e..dae927ef5 100644
--- a/monkeyai/web/vite.config.ts
+++ b/monkeyai/web/vite.config.ts
@@ -3,10 +3,6 @@ import react from "@vitejs/plugin-react"
import { defineConfig } from "vite"
const backend = process.env.MONKEYAI_DEV_BACKEND_URL ?? "http://localhost:8080"
-const backendURL = new URL(backend)
-const isLocalBackend = ["localhost", "127.0.0.1", "[::1]"].includes(
- backendURL.hostname
-)
const apiBackend =
process.env.MONKEYAI_DEV_API_URL ?? "https://work.chaitin.net"
@@ -39,27 +35,8 @@ export default defineConfig({
ws: true,
},
"/endpoints": { target: apiBackend, changeOrigin: true, secure: false },
- "/api": { target: apiBackend, changeOrigin: true },
- "/oauth": {
- target: backend,
- changeOrigin: true,
- configure(proxy) {
- proxy.on("proxyRes", (response) => {
- const location = response.headers.location
- if (!location) return
- const target = new URL(location, backendURL)
- if (
- target.origin === backendURL.origin &&
- target.pathname === "/client-login"
- ) {
- // Remote consent must be submitted from the authorization server's own origin.
- response.headers.location = isLocalBackend
- ? target.pathname + target.search
- : target.href
- }
- })
- },
- },
+ "/api": { target: apiBackend, changeOrigin: true, secure: false },
+ "/oauth": backend,
"/mcp": backend,
"/v1": backend,
"/.well-known/oauth-authorization-server": {