Initial commit

Made-with: Cursor
This commit is contained in:
monster committed 2026-03-09 15:42:50 +08:00
commit 3cdabf77c3
239 files changed
+49516

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.ctcode/
.vscode/
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+68
View File
@@ -0,0 +1,68 @@
# 定义 stages
stages:
- build
- docker
# 定义变量
variables:
NODE_VERSION: "20"
DOCKER_IMAGE_NAME: "chaitin-registry.cn-hangzhou.cr.aliyuncs.com/monkeycode/frontend"
# 缓存 node_modules 和 pnpm 缓存
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- monkeycode-ai/node_modules/
- .pnpm-store/
# 构建阶段
build:
stage: build
image: node:${NODE_VERSION}
before_script:
- corepack enable
- corepack prepare pnpm@latest --activate
- cd monkeycode-ai
- pnpm install --frozen-lockfile
script:
# 生成 sitemap
- sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list.d/debian.sources
- apt-get update && apt-get install -y python3 python3-pip
- pip3 install requests --break-system-packages -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
- python3 scripts/generate-sitemap.py
# 构建项目
- pnpm run build
artifacts:
paths:
- monkeycode-ai/dist/
expire_in: 1 week
only:
- main
- develop
- merge_requests
# Docker 镜像构建阶段
docker:
stage: docker
image: portus.in.chaitin.net/library/docker:buildx
before_script:
- cp -r ./monkeycode-ai/dist ./docker/dist
- cd docker
- docker login -u "$ALI_CR_USER" -p "$ALI_CR_PASSWORD" chaitin-registry.cn-hangzhou.cr.aliyuncs.com
- docker buildx create --name builder --use --bootstrap --driver-opt image=portus.in.chaitin.net/library/buildkit:buildx-stable-1
script:
- |
if [ -n "$CI_COMMIT_TAG" ]; then
TAG=$CI_COMMIT_TAG
else
TAG=$CI_COMMIT_SHORT_SHA
fi
- docker buildx build --platform linux/amd64 -t $DOCKER_IMAGE_NAME:$TAG --push .
- docker buildx build --platform linux/amd64 -t $DOCKER_IMAGE_NAME:latest --push .
dependencies:
- build
only:
- main
- develop
tags:
- docker
+96
View File
@@ -0,0 +1,96 @@
MonkeyCode 是由长亭科技推出的企业级 AI 开发平台,致力于为开发者提供更专业、更可靠、更可扩展的 AI Coding 体验。
MonkeyCode 不只是一个 AI 编程工具,而是一个面向专业团队的 AI 研发基础设施,它覆盖了 **`需求 → 设计 → 开发 → Review`** 全流程,提供了安全、隔离、可并行的开发环境。
:::alert {variant="default"}
MonkeyCode 当前仅提供了 SaaS 版,地址见 [https://monkeycode-ai.com/](https://monkeycode-ai.com/)
后续还计划推出 **离线部署版** 和 **开源版**,以满足更多企业和社区用户的需求,敬请期待。
:::
## ✨ 产品定位
- 企业级 AI Coding 平台
- 面向专业开发者与研发团队
- 支持真实工程场景,支持复杂项目与多人协作
- 不只是写代码,而是参与 **`需求 → 设计 → 开发 → Review`** 的完整研发流程
## 🔥 开始使用
见 [上手指南](https://monkeycode.docs.baizhi.cloud/node/019afd79-5842-7a4e-9ade-e2c566e73d32)
## 🚀 AI 智能开发任务
智能任务是 MonkeyCode 提供的核心能力,支持通过自然语言驱动 AI 执行开发任务。
<img src="https://monkeycode.docs.baizhi.cloud/static-file/6229f59f-4333-4999-b0ff-897bc1e493fc/7278f971-1857-4f67-baa6-896f12327e77.png" width="350" />
<img src="https://monkeycode.docs.baizhi.cloud/static-file/aa3c3109-460c-47d5-bdd5-c14241d309c7/480af390-a2b3-457b-b4f0-206d3e920474.png" width="350" />
MonkeyCode 本身不实现 AI Coding Agent,它的开发能力由业内顶尖工具 `OpenAI Codex` 和 `Claude Code` 驱动。
对于已经在使用 Codex 或 Claude Code 的用户,无需改变使用习惯,可无缝迁移至 MonkeyCode。
同时,MonkeyCode 也对国内主流模型做了完整适配,让用户在使用 `OpenAI Codex` 和 `Claude Code` 的过程中也可以使用国产模型,包括但不限于:DeepSeek、Qwen、Kimi、GLM 等。
> 关于智能任务的更多介绍见 [智能任务](https://monkeycode.docs.baizhi.cloud/node/019b25dd-a7f9-7455-9312-22da2b2cf346)
## 🚀 在线开发环境
MonkeyCode 提供了灵活、安全的在线开发环境方案:本地开发机 + 云端控制。
<img src="https://monkeycode.docs.baizhi.cloud/static-file/a80862b7-169c-4e18-9dc8-243421f9a74e/f587f49f-6f79-4774-906f-1cd040b93ad1.png" width="350" />
<img src="https://monkeycode.docs.baizhi.cloud/static-file/afb91814-f2e7-45b1-8cc4-afdad5bb66a0/63a356cb-ce00-40fb-a901-960512301f79.png" width="350" />
用户在自己本地的开发机上安装 MonkeyCode 探针程序,让本地开发机与 MonkeyCode 平台建立连接,通过 MonkeyCode Web 页面远程驱动本地算力。
每次执行开发任务都会自动创建一台虚拟机,所有 AI 操作仅在虚拟机内执行,即使发生破坏性操作,也不会影响真实开发环境,任务失败可直接重试,系统会重新创建新的虚拟机。
支持多个 AI 任务并行运行,每个任务使用独立的虚拟开发环境,任务之间完全隔离、互不影响。
支持 PC 与移动端访问,用户无需随身携带电脑即可随时随地驱动 AI 执行研发任务。
> 关于开发环境的更多介绍见 [开发环境](https://monkeycode.docs.baizhi.cloud/node/019b25de-570b-72dc-b0f3-3055419ff13f)
## 🚀 SDD 协作开发
:::alert {variant="default"}
SDD(Specification-Driven Development)又叫“规范驱动开发”,它是一种软件开发方法,它强调在编写任何实际代码之前,必须首先编写一份详尽、精确、可执行的规范。。
:::
相比 “Vibe coding”,MonkeyCode 更强调可控性、可追溯性与工程质量。
MonkeyCode 内置了标准的 SDD 开发流程 **`原始需求 -> 产品设计 -> 技术设计 -> 任务列表`**,每个阶段都有 AI 深度参与,可支持专业的研发任务。
MonkeyCode 支持多角色协作推进项目:
- 产品经理:需求拆解与产品设计
- 项目管理:流程与进度管理
- 研发工程师:技术设计与实现
最终,AI 会基于 TODO List 逐步执行开发任务,实现对大型项目的系统化管理。
> 关于 SDD 协作开发的更多介绍见 [SDD 开发](https://monkeycode.docs.baizhi.cloud/node/019b25dd-f3ae-76eb-b374-6cc85efba66b)
## 🚀 Git 集成
<img src="https://monkeycode.docs.baizhi.cloud/static-file/67f1f51b-7eed-423a-9fb7-15b954302316/9610e052-216a-41ed-9787-62249f6d4de9.png" width="350" />
<img src="https://monkeycode.docs.baizhi.cloud/static-file/13a3380c-d626-4457-a711-e28a3054882f/4fe1e6cc-bf32-466b-82e1-7b437e4b3b0b.png" width="350" />
MonkeyCode 已经与 GitHub、GitLab、Gitea、Gitee 深度集成,可以在线直接使用,也支持在独立部署的私有化 GitLab 中集成。
常见使用场景:
- 在 Issue 中 at @MonkeyCode,他可以参与需求讨论,给出有价值的技术建议,还可以根据 Issue 描述直接实现需求
- 在 PR / MR 中 at @MonkeyCode,他会自动进行代码 Review,提出改进建议
- 将 MonkeyCode 接入 DevOps 流程,在代码提交时自动触发 AI Review
> 关于 Git 集成的更多介绍见 [Git 集成](https://monkeycode.docs.baizhi.cloud/node/019a6cdc-9a3e-7243-8885-727ba6573694)
## 特色
- **工具无关性**:底层工具支持 OpenAI Codex、Claude Code 等,如果你已经熟悉了某种 Agent,可以无缝切换到 MonkeyCode 上。
- **模型无关性**:兼容 GPT、Claude、Deepseek、GLM、Kimi、Qwen、Doubao 等大模型,或其他本地模型。
- **SDD 驱动的项目管理**:将技术设计严格管理起来,解决 AI 写代码随意放飞自我的问题,让 AI 完善 code review 和 unit test 流程,让工程师聚焦于业务需求和架构设计,而不是繁琐的编码任务。
- **随时随地执行研发任务**:开发形式不再局限,可以通过 IDE 发起任务,也可以通过 MonkeyCode 在线页面发起任务,还可以通过 git 平台发起任务,甚至可以通过 API 接入其他开发平台
- **开发环境隔离**:允许用户将自己的开发机接入 MonkeyCode,任务启动时会创建一个全新的操作系统供当前任务使用。
- **企业级配置**:专为企业研发团队打造的研发管理模式,支持调用离线大模型,支持在企业内网中使用。
+655
View File
@@ -0,0 +1,655 @@
# MonkeyCode AI 使用指南
欢迎使用 MonkeyCode AI!本文档将帮助你快速上手,了解如何完成各项操作。
---
## 一、产品简介
MonkeyCode 是面向研发团队的企业级 AI 开发平台,覆盖 **需求 → 设计 → 开发 → 代码审查** 全流程。你可以用自然语言描述需求,让 AI 帮你写代码、做设计、做 Review。
---
## 二、登录与账号
### 登录
1. 打开登录页,选择 **用户登录** 或 **团队管理登录**
2. 输入邮箱和密码
3. 完成验证码验证
4. 点击登录
- **用户登录**:进入个人控制台,使用智能任务、项目管理等功能
- **团队管理登录**:进入企业管理后台,管理团队资源
### 找回密码
在登录页点击「找回密码」,输入注册邮箱,系统会发送重置链接到你的邮箱。点击邮件中的链接,按提示设置新密码即可。
---
## 三、控制台导航
登录后进入控制台,左侧是导航栏:
- **智能任务**:进入智能任务页,创建和管理 AI 开发任务
- **代码审查**:配置 Git 机器人,自动审查 PR/MR
- **开发项目**:展示项目列表。点击「+」可**创建项目**(需输入项目名称并关联 Git 仓库),点击刷新图标可刷新列表。点击某个项目会展开子菜单:**项目**(进入项目文档页)、**需求**(进入需求列表,旁显示待处理数量)、**任务**(进入任务列表)
- **配置**:绑定 Git 身份、配置模型、宿主机等
底部可查看账户余额和点数,点击头像可退出登录。
---
## 四、智能任务
### 如何创建一个任务
1. **输入任务内容**
在输入框中用自然语言描述你的需求,例如:「为这个项目添加用户登录功能」。
2. **选择任务类型**
点击「开发 / 设计 / 审查」按钮选择:
- **开发**:让 AI 根据需求写代码
- **设计**:让 AI 输出技术方案和设计文档
- **审查**:让 AI 审查代码,提出改进建议
3. **选择代码来源**
点击「代码」按钮:
- **我的仓库**:展开后选择 GitHub 或 Gitee。若已绑定,会显示你的仓库列表(支持搜索、按账号分组);若未绑定,会提示「去绑定」并跳转到配置页
- **其他仓库**:输入完整的 Git 仓库地址,按回车确认;下方会显示历史使用过的仓库供快速选择
- **ZIP 文件**:选择本地的 .zip 压缩包上传(最大 10MB),上传成功后该文件会作为代码来源
4. **选择技能(可选)**
点击「技能」按钮,按标签分类展示技能列表。勾选需要的技能以扩展 AI 能力,部分默认技能不可取消。
5. **语音输入(可选)**
点击麦克风按钮,用语音描述任务,系统会自动转为文字。
6. **点击「执行」**
会弹出参数配置窗口,确认后即可开始执行。
### 任务参数配置
执行前可以调整:
- **开发工具**:Claude Code、OpenAI Codex 或 OpenCode
- **大模型**:选择要使用的 AI 模型(含免费和付费选项)
- **仓库分支**:不填则使用主分支
- **身份凭证**:使用私有仓库时,需选择已绑定的 Git 身份
子账号还可以选择宿主机和系统镜像。
### 查看任务列表
任务创建后会在下方以卡片形式展示,每个卡片显示:
- 任务摘要
- 关联的仓库或文件
- 状态:等待执行、正在执行、任务完成、执行失败
- 任务类型和创建时间
点击任务卡片,会在新窗口打开任务开发页面。
---
## 五、任务开发页面
任务执行时,会打开任务开发页面,你可以在这里与 AI 协作。
### 页面布局
- **左侧**:项目文件树,可展开/折叠目录
- **中间**:与 AI 的对话区域,以及文件预览
- **右侧**:终端输出,展示 AI 执行的命令
### 与 AI 对话
- 当 AI 执行完毕、等待你的反馈时,底部输入框会变为可输入状态
- 输入补充说明或新指令,点击发送,AI 会继续执行
- 可以随时点击「重启会话」重新开始
### 查看 AI 的执行进度
- 对话区域会展示 AI 的 TODO 计划,以及每个步骤的完成状态
- 执行中会显示耗时,你可以点击停止按钮中断执行
### 提交代码变更
当 AI 修改了代码后,你可以:
1. 点击「提交变更」打开变更列表
2. 勾选要提交的文件(可全选或部分选择)
3. 点击某个文件可查看具体改动(Diff 视图)
4. 选择「提交选中」或「全部提交」完成提交
### 查看和编辑文件
- 在左侧文件树点击文件,中间会显示文件内容(超过 1MB 的文件会提示无法预览)
- 支持多种展示方式:代码高亮、Markdown 渲染、图片预览、JSON 格式化等
- 文件详情区域有 Tab 可切换:**预览/文本**(查看内容)、**Diff**(查看与上一版本的差异)、**提交历史**
- 代码类文件可直接在编辑器中修改,修改后点击保存即可
### 其他功能
**在线预览**
当任务中运行了 Web 服务(如前端开发服务器)时:
1. 点击顶部栏的「在线预览」按钮
2. 在弹窗中查看该环境已开放的端口列表
3. 若端口尚未开放,需先「开放端口」:系统会获取你的 IP 并加入白名单,开放后可通过生成的访问地址在浏览器中预览
4. 若端口已开放,直接复制访问地址在浏览器中打开即可
**续期**
开发环境有回收时间,即将到期时顶部会显示倒计时:
1. 点击倒计时区域
2. 在弹窗中选择要续期的时长
3. 确认后开发环境的使用时间会延长
**布局**
点击顶部的布局图标,在菜单中可勾选或取消「项目文件」「终端」面板的显示,便于按需调整工作区布局。
---
## 六、代码审查
在「代码审查」页面,可以配置 Git 机器人,让 AI 自动审查你的合并请求(PR/MR)。
### 审查任务
切换到「审查任务」标签:
- 以卡片形式展示所有由机器人触发的审查任务
- 每个卡片显示关联的 PR/MR、状态、平台等,点击可跳转到对应 Git 平台的 PR 页面
- 点击「刷新」可更新列表
- 若无任务,会显示「如何使用?」链接,可查看配置说明
### 创建审查机器人
1. 切换到「机器人」标签
2. 点击「创建审查机器人」
3. 填写:
- **备注**:可选,便于区分多个机器人
- **Git 平台**:GitLab、GitHub 或 Gitee
- **Access Token**:在对应平台的设置中生成,用于机器人访问仓库
- **宿主机**:选择运行审查任务的机器(MonkeyCode 内置或自有宿主机)
4. 提交后,系统会显示 Webhook 地址和 Secret Token,并提示在 Git 平台配置
### 在 Git 平台配置
将生成的 Webhook 地址和 Secret Token 配置到你的 Git 仓库或组织的 Webhook 设置中。配置完成后,当有 PR/MR 创建或更新时,Git 平台会向该地址发送事件,MonkeyCode 收到后自动触发 AI 进行代码审查。具体配置步骤因平台而异,可参考各平台的 Webhook 文档。
### 管理机器人
每个机器人卡片右侧有「更多」菜单:
- **编辑**:修改备注、Token、宿主机等配置
- **查看 Webhook**:再次查看 Webhook 地址和 Secret Token,可复制
- **权限管理**:选择可将该机器人分享给哪些团队成员,被分享的成员可以使用该机器人
- **删除**:移除不再使用的机器人(需确认)
---
## 七、开发项目
### 如何创建项目
1. 在左侧「开发项目」区域点击「+」按钮
2. 输入项目名称
3. 选择仓库来源:
- **GitHub**:需已绑定 GitHub,会加载你授权的仓库列表(支持搜索、按账号分组),从中选择要关联的仓库
- **Gitee**:需已绑定 Gitee,会加载你授权的仓库列表,从中选择
- **其他**:直接输入仓库 URL,并选择匹配的身份凭证
4. 若选 GitHub/Gitee 但未绑定,会提示「去绑定」并跳转到配置页
5. 提交后,项目会出现在侧边栏,并自动进入该项目页面
### 项目页面
进入项目后,可以看到:
- **项目信息**:名称、描述、仓库状态(未绑定仓库时会显示提示)
- **文件树**:树形展示仓库结构,点击目录可展开/折叠,点击文件可在下方预览内容
- **文档预览**:点击文件后,下方会显示文件内容。若未指定文件,会优先尝试加载 `.monkeycode/docs/INDEX.md` 或 `README.md`
### 启动 AI 操作
点击「启动 AI」按钮:
- **发起对话**:与 AI 对话,基于当前项目上下文进行操作
- **生成项目文档**:让 AI 自动生成项目架构和设计文档
### 项目设置
点击「更多」菜单:
- **修改名称**:在弹窗中修改项目名称和描述,保存即可
- **项目成员**:在弹窗中从团队成员列表中勾选或取消勾选协作成员,保存后这些成员将拥有该项目的读写权限
- **移除项目**:删除项目(不可恢复,请谨慎操作)
### 项目需求
在项目内切换到「需求」标签:
1. 点击「创建需求」
2. 输入需求标题和原始需求说明(支持 Markdown)
3. 提交后,需求会出现在列表中
**需求详情**:点击某个需求可查看和编辑:
- 标题:点击可修改
- 原始需求、技术方案:可编辑并保存
- 状态:进行中、已完成、已关闭
- 优先级:高、中、低
**从需求启动任务**:在需求详情的「更多操作」中:
- **启动设计任务**:让 AI 基于需求输出技术方案
- **启动开发任务**:让 AI 基于需求直接开发
### 项目任务
切换到「任务」标签,可查看该项目下的所有任务,点击任务卡片可进入任务开发页面。
---
## 八、配置
在「配置」页面,可以管理各类基础设置。
### Git 平台身份凭证
用于在 Git 仓库中拉取和提交代码。
**绑定 GitHub**:点击「绑定 GitHub」,按提示完成 GitHub App 安装和授权。
**绑定 Gitee**:点击「绑定 Gitee」,在弹窗中完成 OAuth 授权。
**绑定其他平台**(如 GitLab、Gitea):
1. 点击「绑定」→「绑定其他平台」
2. 选择平台类型,填写 Base URL、Access Token、邮箱、用户名
3. 提交即可
**管理**:已绑定的身份可修改备注或移除。
### AI 大模型
平台提供部分免费模型,你也可以添加自己的 API 模型。
**添加**:
1. 点击「添加模型」
2. 填写 API Token 和模型 API 地址(默认百智云,可改为自建或第三方)
3. 选择接口类型(如 OpenAI Chat、Anthropic 等,需与模型兼容)
4. 点击「获取模型列表」拉取该地址下的可用模型
5. 从列表中选择要添加的模型
6. 保存前会进行连接检查,通过后即可使用
**管理**:可设为默认、检查连接、修改或移除(仅自己添加的模型可编辑和删除)。
### 系统镜像
配置任务运行时的操作系统环境(Docker 镜像)。不同镜像提供不同的预装环境和工具。
**添加**:点击「添加镜像」,输入镜像名称(如 `docker.io/library/ubuntu:24.04`),可选填写备注,保存即可。
**管理**:可设为默认、修改备注、移除。
### 宿主机
若希望任务在你自己的机器上执行,需先将机器接入为宿主机。
1. 点击「绑定宿主机」或「获取安装命令」
2. 弹窗会显示一段安装命令,点击可复制
3. 以 root 权限登录你的 Linux 服务器,粘贴并执行该命令
4. 执行成功后刷新页面,宿主机会出现在列表中
**管理**:可修改备注、设为默认、移除。
### 开发环境(虚拟机)
展示你名下所有开发环境,包括任务自动创建的以及手动创建的。
**查看列表**:每个环境显示名称、状态(运行中/待机/离线)、系统、配置、创建时间等。可切换「显示离线环境」来查看已回收的环境。
**创建**:
1. 点击「创建开发环境」
2. 选择宿主机(或 MonkeyCode 免费宿主机)
3. 选择系统镜像、CPU 核数、内存大小
4. 选择回收时间(如 1 小时后、3 天后等)
5. 可选:填写仓库地址、分支、身份凭证,创建时会预拉取代码
6. 点击创建
**操作**:续期、删除、进入终端、打开文件管理
---
## 九、终端
从开发环境列表点击「终端」进入终端页面。需在 URL 中指定环境 ID(通常从开发环境列表点击进入时会自动带上)。
### 首次连接
若该环境没有已有连接,会弹出选择框:
- **使用已有连接**:列出该环境下已有的终端会话,选择其中一个连接
- **新建连接**:创建新的终端会话
选择后即可进入终端界面。也可以关闭某个不再需要的终端连接。
### 常用功能
- **重新连接**:断线后点击「重新连接」重新建立连接
- **在线预览**:与任务开发页面的在线预览相同,可配置端口转发,在浏览器中访问运行中的 Web 服务
- **文件管理**:跳转到该环境的文件管理页面
- **远程协助**:
1. 点击「远程协助」
2. 选择模式:**只读**(对方只能看,不能操作)或 **控制**(对方可输入命令)
3. 点击「生成连接信息」
4. 复制连接地址和密码,发送给对方
5. 对方在浏览器打开地址、输入密码后即可连接
- **配色方案**:在下拉框中选择终端主题,选择后会保存,下次进入自动应用
---
## 十、文件管理
从开发环境列表点击「文件管理」进入。默认进入该环境的 `/workspace` 目录。
### 浏览文件
- 顶部面包屑显示当前路径,点击任意一级可快速跳转
- 点击「上级目录」返回上一级
- 点击文件夹进入该目录
- 点击文件:若为目录则进入,若为普通文件且小于 1MB 则打开编辑弹窗;超过 1MB 会提示无法在线编辑
### 新建
点击「新建」下拉:
- **创建文件夹**:输入文件夹名称(相对于当前路径),保存后会在当前目录下创建
- **创建文件**:输入文件名(含路径),保存后创建空文件
- **上传文件**:选择本地文件,上传到当前目录
### 文件操作
每个文件/文件夹右侧有「更多」菜单:
- **复制**:在弹窗中选择或输入目标路径,将文件复制到该位置
- **移动**:在弹窗中选择或输入目标路径,将文件移动到该位置
- **下载**:将文件下载到本地
- **删除**:删除该文件或文件夹(需确认,删除目录会递归删除其内容)
### 编辑文件
在编辑弹窗中修改内容后,点击保存即可写入。支持多种文件类型的语法高亮。
---
## 十一、开发者广场
在开发者广场可以浏览和分享内容。未登录时可浏览,发布需先登录。
### 浏览
- 在搜索框输入关键词,点击「搜索」或按回车,可筛选帖子
- 每个卡片显示封面图、标题、描述、作者、浏览量
- 点击卡片进入详情页查看完整内容
### 发布
点击「发布」后,先选择发布类型:
**写一篇文章**
- 输入标题、正文(支持 Markdown)
- 可上传图片:点击上传区域选择图片,或拖拽图片到编辑区
- 点击发布,审核通过后会显示在广场上
**分享你执行过的任务**
- 从下拉列表中选择要分享的任务
- 输入标题和说明
- 可选:通过「选择文件」从该任务的开发环境中勾选要打包的代码文件,分享时会一并打包供他人下载
- 点击发布,审核通过后会显示在广场上
---
## 十二、公开任务
展示他人公开分享的任务列表。每个任务以卡片形式展示,点击可进入任务详情页,查看任务描述、执行过程或关联的代码文件等。
---
## 十三、远程协助
当你在终端页面使用「远程协助」功能时,会生成一个连接地址和密码。将地址和密码发送给对方后:
- **只读模式**:对方在浏览器中打开地址、输入密码后,只能看到你的终端画面,无法输入或操作
- **控制模式**:对方可以看到终端画面,并且可以输入命令、进行操作
适用于需要他人协助排查问题、或进行远程演示等场景。
---
## 十四、企业管理后台
使用团队管理员账号登录后,可进入企业管理后台。左侧导航包含:仪表盘、成员管理、开发环境、镜像管理、AI 大模型、操作记录、管理员。下面分别说明每个页面的功能和操作方式。
### 仪表盘
当前为「敬请期待」状态,后续将提供团队概览数据。
---
### 成员管理
成员管理页面分为两个区域:**团队成员** 和 **分组**。
#### 团队成员
**查看成员列表**
- 页面展示所有团队成员,每人显示头像、姓名、邮箱、加入时间、最后使用时间
- 顶部显示「当前成员数量 / 成员上限」
**添加成员**
1. 点击「添加成员」按钮(若已达成员上限则按钮不可用)
2. 在弹窗的文本框中输入邮箱地址
3. 支持批量添加:多个邮箱用分号、逗号或换行分隔,例如:`user1@example.com; user2@example.com`
4. 点击「添加」完成
**管理成员**
每个成员右侧有「更多」菜单:
- **设为禁用**:禁用后该成员无法登录,名称会显示删除线
- **设为启用**:将已禁用的成员恢复为可用状态
- **重置密码**:系统会向该成员邮箱发送密码重置邮件,成员通过邮件链接自行设置新密码
#### 分组
分组用于将成员归类,便于后续为宿主机、镜像、模型等资源分配使用权限。
**添加分组**
1. 点击「添加分组」
2. 输入分组名称
3. 点击「添加」
**管理分组**
每个分组右侧有「更多」菜单:
- **修改名称**:修改分组名称
- **调整成员**:打开成员选择框,勾选或取消勾选成员,点击「保存」更新该分组的成员列表
- **删除**:删除该分组(需确认)
**查看分组成员**
点击分组下方的「X 个成员」,可弹窗查看该分组下的成员列表。
---
### 开发环境(宿主机)
管理团队接入的宿主机,宿主机用于创建开发环境(虚拟机)。
**绑定宿主机**
1. 点击「绑定宿主机」
2. 弹窗会显示一段安装命令
3. 以 root 权限登录你的 Linux 服务器,复制并执行该命令
4. 执行成功后,刷新页面,宿主机会出现在列表中
**查看宿主机列表**
每个宿主机卡片显示:
- 备注或名称、IP
- 状态(在线/离线等)
- 核数、内存、架构
- 开发环境数量及正在使用的数量
- 所属分组
- 当前正在使用的开发环境及占用者
**修改宿主机**
1. 点击宿主机右侧「更多」→「修改」
2. 可修改:
- **备注**:便于识别的名称
- **可使用该宿主机的分组**:勾选哪些分组的成员可以使用该宿主机创建开发环境
3. 点击「保存」
**移除宿主机**
点击「更多」→「移除」,确认后该宿主机将从团队中移除。
---
### 镜像管理
管理团队可用的系统镜像,用于构建开发环境。
**绑定镜像**
1. 点击「绑定」按钮
2. 填写:
- **镜像名称**:Docker 镜像地址,例如 `docker.io/library/ubuntu:24.04`
- **备注**:可选,便于识别
- **可使用该配置的分组**:勾选哪些分组的成员可以使用该镜像
3. 点击「保存」
**查看镜像列表**
每个镜像显示名称、备注、完整镜像地址、所属分组。
**修改镜像**
1. 点击镜像右侧「更多」→「修改」
2. 可修改备注和可使用该镜像的分组
3. 点击「保存」
**移除镜像**
点击「更多」→「移除」,确认后该镜像将从团队中移除。
---
### AI 大模型
管理团队可用的 AI 模型,供成员在任务中使用。
**添加模型**
1. 点击「添加模型」或卡片上的添加按钮
2. 填写:
- **API Token**:模型服务的 API 密钥
- **模型 API 地址**:默认百智云地址,可改为自建或第三方地址
- **接口类型**:根据模型选择(如 OpenAI Chat、Anthropic 等)
3. 点击「获取模型列表」拉取该地址下的可用模型
4. 选择要添加的模型
5. **可使用该配置的分组**:勾选哪些分组的成员可以使用该模型
6. 点击「保存」,系统会先检查连接,通过后完成添加
**查看模型列表**
每个模型显示名称、接口类型、健康状态、所属分组。
**管理模型**
每个模型右侧有「更多」菜单:
- **检查**:测试模型连接是否正常,弹窗显示检查结果
- **修改**:修改 API 配置、分组等
- **移除**:从团队中移除该模型(需确认)
---
### 操作记录
查看团队内的操作日志,便于审计和排查问题。
**查看记录列表**
表格展示每条记录的时间、用户、操作类型、来源 IP。
**操作**
- **每页显示**:可选择每页 10、20、50、100 条
- **翻页**:使用底部的「首页」「上一页」「下一页」按钮
- **查看请求**:点击某条记录的「查看请求」,弹窗显示该次操作的请求内容(JSON 格式)
- **查看响应**:点击「查看响应」,弹窗显示该次操作的响应内容
---
### 管理员
管理拥有企业管理后台权限的管理员账号。
**查看管理员列表**
展示所有管理员,每人显示头像、姓名、邮箱、加入时间、最后使用时间。
**添加管理员**
1. 点击「添加管理员」
2. 输入邮箱地址和姓名
3. 点击「添加」
4. 系统会向该邮箱发送邀请,对方按邮件指引完成注册后即可登录管理后台
**重置密码**
点击某管理员右侧「更多」→「重置密码」,确认后系统会向该管理员邮箱发送密码重置邮件。
---
## 十五、常见问题
**Q:如何创建项目?**
A:在左侧「开发项目」区域点击「+」按钮,输入项目名称,选择仓库来源(GitHub、Gitee 或输入其他仓库地址),从列表中选择要关联的仓库后提交即可。若选 GitHub/Gitee 需先完成绑定,详见「七、开发项目」→「如何创建项目」。
**Q:如何绑定 GitHub?**
A:进入「配置」→「Git 平台身份凭证」→ 点击「绑定 GitHub」,按页面提示完成 GitHub App 安装即可。
**Q:任务执行失败怎么办?**
A:可在任务开发页面点击重试,或回到智能任务页重新创建任务。系统会重新创建开发环境。
**Q:如何接入自己的电脑作为开发环境?**
A:进入「配置」→「宿主机」→ 点击「获取安装命令」,将命令复制到本地终端执行。执行成功后,你的电脑会出现在宿主机列表中。
**Q:子账号和主账号有什么区别?**
A:子账号在创建任务时可以选择宿主机和系统镜像;主账号会使用团队或系统默认配置。
**Q:强力模型如何收费?**
A:使用账户余额或赠送点数。使用前请确保余额充足,可在控制台底部查看当前余额。
---
如有更多问题,可点击页面顶部的「帮助文档」查看官方文档,或扫码加入微信交流群。
+13
View File
@@ -0,0 +1,13 @@
node_modules
npm-debug.log
.git
.gitignore
README.md
.env
.nyc_output
coverage
.vscode
.idea
*.log
.DS_Store
.eslintcache
+17
View File
@@ -0,0 +1,17 @@
# 直接使用 nginx 镜像,因为应用已经在 CI 中构建完成
FROM nginx:alpine
# 复制构建产物到 nginx 目录
COPY dist/ /usr/share/nginx/html/
COPY nginx.conf /etc/nginx/nginx.conf
# 复制启动脚本
COPY start.sh /start.sh
RUN chmod +x /start.sh
# 暴露端口
EXPOSE 80
# 使用启动脚本启动
CMD ["/start.sh"]
+15
View File
@@ -0,0 +1,15 @@
version: '3.8'
services:
frontend:
image: chaitin-registry.cn-hangzhou.cr.aliyuncs.com/monkeycode/frontend:latest
container_name: saas-web-frontend
ports:
- "80:80"
restart: unless-stopped
networks:
- saas-network
networks:
saas-network:
driver: bridge
+47
View File
@@ -0,0 +1,47 @@
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log;
# 基本设置
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip 压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# 处理前端路由(SPA)
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存
location ~* \.(js|css|png|svg|ttf)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
}
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
# 启动 nginx
nginx -g "daemon off;"
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+100
View File
@@ -0,0 +1,100 @@
# MonkeyCode 智能开发平台
MonkeyCode 是一个全新的 AI 编程体验平台,不仅仅是 AI 编程工具,更是对传统研发模式的变革,让你的研发团队效率 Max。
## 技术栈
- **前端框架**: React 19
- **构建工具**: Vite 7
- **开发语言**: TypeScript 5.9
- **样式方案**: Tailwind CSS 4
- **UI 组件**: Radix UI + shadcn/ui
- **路由管理**: React Router 7
- **终端模拟**: xterm.js
- **代码编辑**: Ace Editor
- **Markdown**: MDX Editor
## 功能特性
- 🤖 **AI 任务管理** - 智能任务分配与执行
- 🖥️ **云端开发环境** - 虚拟机管理与远程开发
- 📁 **文件管理** - 在线文件浏览与编辑
- 💻 **Web 终端** - 支持多主题的终端模拟器
- 👥 **团队协作** - 团队成员管理与权限控制
- 🔗 **Git 集成** - 支持 GitHub、GitLab、Gitea、Gitee
- 🎨 **主题切换** - 支持明暗主题
## 快速开始
### 环境要求
- Node.js >= 18
- pnpm >= 8
### 安装依赖
```bash
pnpm install
```
### 启动开发服务器
```bash
pnpm dev
```
### 构建生产版本
```bash
pnpm build
```
### 预览生产版本
```bash
pnpm preview
```
## 项目结构
```
src/
├── api/ # API 接口定义(自动生成)
├── components/ # 组件
│ ├── common/ # 通用组件(图标、终端等)
│ ├── console/ # 控制台相关组件
│ │ ├── files/ # 文件管理组件
│ │ ├── nav/ # 导航组件
│ │ ├── project/ # 项目管理组件
│ │ ├── settings/ # 设置组件
│ │ ├── task/ # 任务组件
│ │ └── vm/ # 虚拟机组件
│ ├── manager/ # 管理后台组件
│ ├── ui/ # shadcn/ui 基础组件
│ └── welcome/ # 首页组件
├── hooks/ # 自定义 Hooks
├── lib/ # 工具库
├── pages/ # 页面
│ ├── console/ # 控制台页面
│ │ ├── manager/ # 团队管理页面
│ │ └── user/ # 用户控制台页面
│ └── ... # 其他页面
└── utils/ # 工具函数
```
## API 生成
项目使用 [swagger-typescript-api](https://github.com/acacode/swagger-typescript-api) 从 Swagger 文档自动生成 TypeScript API 客户端:
```bash
pnpm api
```
## 相关链接
- [用户文档](https://monkeycode.docs.baizhi.cloud/)
- [获取邀请码](https://monkeycode.docs.baizhi.cloud/node/019a6b8a-ee52-7d69-85fb-a429a8ca40c5)
## License
Private
+22
View File
@@ -0,0 +1,22 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/index.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {}
}
+23
View File
@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
@@ -0,0 +1 @@
window._iconfont_svg_string_5023051='<svg><symbol id="icon-qwen" viewBox="0 0 1024 1024"><path d="M955 607.2L843.6 412.1l47.8-91.6c6.6-8.7 8.3-21.5 5.6-31.8L835.7 178c-4.7-7.3-12.8-11.8-21.5-12H586.3l-51-89.2c-3.6-7-10.5-11.8-18.3-12.7H396.7c-8.9 0.2-15.2 6.7-19.6 14.4l-1.9 3.1-113.8 195.1H152.2c-9-0.2-17.5 4.3-22.3 12L67 400.1c-4 8-4 17.5 0 25.5l113.1 196.7-51 89.2c-4 8-4 17.4 0 25.5l58.1 102c4.7 7.8 13.2 12.7 22.3 12.7h227.8l54.9 95.5c4.2 7.2 11.6 11.9 19.9 12.8h129c8.9-0.2 17.1-5 21.5-12.7L775 750.5h100.4c8.9-0.8 16.9-5.8 21.5-13.5L955 634.3c5.4-8.3 5.4-18.9 0-27.1zM814.1 620L756 512.5 517 933.7l-65.3-107.5H212.8l57.4-104.3H392L153 302.2h125L396.7 90.3l59.7 104.3-61.3 107.5H873l-60.5 106.8 120.3 211H814.1z" fill="#605BEC" ></path><path d="M511.4 660.5l149-238.9H361.7l149.7 238.9z m0 0" fill="#605BEC" ></path></symbol><symbol id="icon-claude" viewBox="0 0 1024 1024"><path d="M235.52 662.18666667l179.08622187-100.5795552 2.95822293-8.64711147-2.95822293-4.77866667h-8.6471104l-30.03733334-1.8204448-102.4-2.73066666-88.74666666-3.64088854-86.016-4.55111146-21.61777814-4.5511104L56.88888853 504.26311147l2.048-13.42577814 18.2044448-12.288 25.94133334 2.2755552 57.5715552 3.8684448 86.47111146 5.9164448 62.57777814 3.64088854 92.84266666 9.78488853h14.7911104l2.048-5.91644373-5.00622186-3.6408896-3.8684448-3.64088854-89.42933334-60.52977813-96.7111104-64.17066667-50.7448896-36.864-27.53422186-18.6595552-13.88088854-17.52177813-5.9164448-38.22933333 24.8035552-27.53422187 33.45066667 2.2755552 8.41955627 2.27555627 33.90577706 25.94133333 72.36266667 55.97866667L393.67111147 383.43111147l13.88088853 11.60533333 5.46133333-3.8684448 0.68266667-2.73066667-6.144-10.4675552-51.4275552-92.84266666L301.2835552 190.6915552l-24.34844373-39.1395552-6.37155627-23.43822187a115.05208853 115.05208853 0 0 1-3.86844373-27.76177813l28.44444373-38.45688853L310.84088853 56.88888853l37.77422294 5.00622294 15.92888853 13.88088853 23.43822187 53.70311147 38.00177813 84.65066666 58.93688853 114.9155552 17.29422294 34.13333334 9.32977706 31.63022186 3.41333334 9.7848896h5.9164448v-5.46133333l4.77866666-64.85333333 8.87466667-79.4168896 8.64711147-102.4 2.95822186-28.8995552 14.336-34.5884448 28.4444448-18.6595552 22.07288854 10.69511146 18.2044448 25.94133334-2.50311147 16.8391104-10.92266667 70.31466666-21.16266666 110.1368896-13.88088854 73.728h7.96444374l9.32977813-9.32977813 37.31911147-49.60711147 62.57777706-78.2791104 27.76177814-31.17511146 32.31288853-34.36088854 20.70755627-16.384h39.1395552l28.8995552 42.78044374-12.97066667 44.14577813-40.27733333 51.2-33.45066667 43.2355552-48.01422187 64.62577813-30.03733333 51.65511147 2.73066667 4.096 7.05422186-0.68266667 108.3164448-22.98311146 58.48177814-10.69511147 69.8595552-12.06044373 31.63022186 14.7911104 3.41333334 15.01866666-12.5155552 30.72-74.63822187 18.432-87.6088896 17.52177814-130.38933333 30.9475552-1.59288854 1.13777813 1.8204448 2.2755552 58.70933334 5.46133333 25.0311104 1.36533334h61.44l114.4604448 8.41955626 30.03733333 19.79733334 17.97688853 24.12088853-2.95822186 18.432-46.19377814 23.43822187-62.12266666-14.7911104-145.18044374-34.5884448-49.83466666-12.5155552h-6.82666667v4.096l41.4151104 40.50488853 76.00355627 68.72177813 95.11822186 88.5191104 4.77866667 21.84533334-12.288 17.29422293-12.97066667-1.8204448-83.7404448-62.80533333-32.31288853-28.4444448-73.04533333-61.44h-4.77866667v6.37155626l16.83911147 24.576 88.97422186 133.5751104 4.55111147 40.96-6.37155627 13.42577814-22.9831104 7.9644448-25.25866666-4.55111147-52.11022294-73.04533333-53.7031104-82.37511147-43.23555626-73.728-5.23377707 2.95822293-25.48622293 275.34222187-12.06044374 14.1084448-27.76177813 10.6951104-22.98311147-17.52177707-12.288-28.4444448 12.288-55.97866666 14.79111147-73.04533334 12.0604448-58.02666666 10.92266667-72.13511147 6.3715552-23.89333333-0.45511147-1.59288854-5.23377707 0.68266667-54.38577813 74.63822187-82.83022187 111.72977813-65.536 70.08711147-15.70133333 6.144-27.07911147-14.1084448 2.50311147-25.03111147 15.24622187-22.30044373 90.56711146-115.14311147 54.61333334-71.4524448 35.2711104-41.1875552v-5.9164448h-2.2755552l-240.52622187 156.33066667-42.7804448 5.46133333-18.432-17.29422187 2.2755552-28.4444448 8.64711147-9.32977706 72.36266666-49.83466667h-0.2275552l0.91022187 0.91022187z" fill="#D97757" ></path></symbol><symbol id="icon-doubao" viewBox="0 0 1024 1024"><path d="M944.99271147 444.46151111c-143.81511147-96.0284448-295.36711147-110.4099552-295.36711147-110.4099552s7.64586667 219.3635552-10.0124448 285.80977707c-0.45511147 9.10222187-11.01368853 70.2691552-40.1408 147.18293333-10.0124448 26.30542187-22.48248853 51.65511147-36.81848853 76.00355627a689.9939552 689.9939552 0 0 1-83.64942187 119.0115552c111.86631147-45.42008853 191.64728853-86.47111147 289.1776-163.93102187 114.688-90.3395552 214.08426667-237.568 176.81066667-353.6668448z" fill="#37E1BE" ></path><path d="M357.62631147 403.36497778c147.6835552-94.16248853 288.1763552-73.59146667 291.5441770Line truncated
+30
View File
@@ -0,0 +1,30 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/logo.png" />
<script src="/iconfont.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MonkeyCode 智能开发平台</title>
<!-- SEO 元标签 -->
<meta name="description" content="MonkeyCode AI 是一个智能代码生成平台,通过AI驱动的编程助手、自动化工作流和智能开发工具,帮助开发者更快速地构建应用程序。" />
<meta name="keywords" content="AI代码生成, 智能编程, 开发者工具, 自动化编程, 代码助手, AI开发平台, MonkeyCode, 人工智能编程" />
<meta name="author" content="MonkeyCode AI" />
<meta name="robots" content="index, follow" />
<link rel="canonical" href="https://monkeycode-ai.com" />
</head>
<body>
<div id="root" class="font-google-sans-code"></div>
<script type="module" src="/src/main.tsx"></script>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-RQQN0BK11M"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-RQQN0BK11M');
</script>
</body>
</html>
+98
View File
@@ -0,0 +1,98 @@
{
"name": "monkeycode-ai",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview",
"api": "sta --path ${SWAGGER_URL:-https://monkeycode-ai.com/swagger/swagger.json} --output src/api"
},
"dependencies": {
"@cap.js/widget": "^0.1.32",
"@mdxeditor/editor": "^3.52.1",
"@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-aspect-ratio": "^1.1.8",
"@radix-ui/react-avatar": "^1.1.11",
"@radix-ui/react-collapsible": "^1.1.12",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-hover-card": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-progress": "^1.1.8",
"@radix-ui/react-radio-group": "^1.3.8",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-toggle": "^1.1.10",
"@radix-ui/react-toggle-group": "^1.1.11",
"@radix-ui/react-tooltip": "^1.2.8",
"@tabler/icons-react": "^3.35.0",
"@tailwindcss/vite": "^4.1.17",
"@types/react-syntax-highlighter": "^15.5.13",
"@uiw/react-json-view": "2.0.0-alpha.40",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-unicode11": "^0.8.0",
"@xterm/addon-web-links": "^0.11.0",
"@xterm/addon-webgl": "^0.18.0",
"@xterm/xterm": "^5.5.0",
"ace-builds": "^1.43.4",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"dayjs": "^1.11.19",
"diff": "^8.0.3",
"gray-matter": "^4.0.3",
"jszip": "^3.10.1",
"lucide-react": "^0.553.0",
"mermaid": "^11.12.2",
"next-themes": "^0.4.6",
"react": "^19.2.0",
"react-ace": "^14.0.1",
"react-diff-view": "^3.3.2",
"react-dom": "^19.2.0",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.6",
"react-router-dom": "^7.9.5",
"react-syntax-highlighter": "^16.1.0",
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
"remark": "^15.0.1",
"remark-frontmatter": "^5.0.0",
"remark-gfm": "^4.0.1",
"yaml": "^2.4.0",
"sonner": "^2.0.7",
"streamsaver": "^2.0.6",
"strip-markdown": "^6.0.0",
"tailwind-merge": "^3.4.0",
"tailwindcss": "^4.1.17",
"uuid": "^13.0.0",
"vaul": "^1.1.2"
},
"devDependencies": {
"vite-plugin-node-polyfills": "^0.23.0",
"@eslint/js": "^9.39.1",
"@types/node": "^24.10.0",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2",
"@types/streamsaver": "^2.0.5",
"@vitejs/plugin-react": "^5.1.0",
"baseline-browser-mapping": "^2.9.19",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"swagger-typescript-api": "^12.0.4",
"tw-animate-css": "^1.4.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.3",
"vite": "^7.2.2"
}
}
+9467
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
let wasm,WASM_VECTOR_LEN=0,cachedUint8ArrayMemory0=null;function getUint8ArrayMemory0(){return null!==cachedUint8ArrayMemory0&&0!==cachedUint8ArrayMemory0.byteLength||(cachedUint8ArrayMemory0=new Uint8Array(wasm.memory.buffer)),cachedUint8ArrayMemory0}const cachedTextEncoder="undefined"!=typeof TextEncoder?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},encodeString="function"==typeof cachedTextEncoder.encodeInto?function(e,t){return cachedTextEncoder.encodeInto(e,t)}:function(e,t){const n=cachedTextEncoder.encode(e);return t.set(n),{read:e.length,written:n.length}};function passStringToWasm0(e,t,n){if(void 0===n){const n=cachedTextEncoder.encode(e),i=t(n.length,1)>>>0;return getUint8ArrayMemory0().subarray(i,i+n.length).set(n),WASM_VECTOR_LEN=n.length,i}let i=e.length,o=t(i,1)>>>0;const r=getUint8ArrayMemory0();let a=0;for(;a<i;a++){const t=e.charCodeAt(a);if(t>127)break;r[o+a]=t}if(a!==i){0!==a&&(e=e.slice(a)),o=n(o,i,i=a+3*e.length,1)>>>0;const t=getUint8ArrayMemory0().subarray(o+a,o+i);a+=encodeString(e,t).written,o=n(o,i,a,1)>>>0}return WASM_VECTOR_LEN=a,o}export function solve_pow(e,t){const n=passStringToWasm0(e,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),i=WASM_VECTOR_LEN,o=passStringToWasm0(t,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN,a=wasm.solve_pow(n,i,o,r);return BigInt.asUintN(64,a)}async function __wbg_load(e,t){if("function"==typeof Response&&e instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if("application/wasm"==e.headers.get("Content-Type"))throw t;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",t)}const n=await e.arrayBuffer();return await WebAssembly.instantiate(n,t)}{const n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}}function __wbg_get_imports(){const e={wbg:{}};return e.wbg.__wbindgen_init_externref_table=function(){const e=wasm.__wbindgen_export_0,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)},e}function __wbg_init_memory(e,t){}function __wbg_finalize_init(e,t){return wasm=e.exports,__wbg_init.__wbindgen_wasm_module=t,cachedUint8ArrayMemory0=null,wasm.__wbindgen_start(),wasm}function initSync(e){if(void 0!==wasm)return wasm;void 0!==e&&(Object.getPrototypeOf(e)===Object.prototype?({module:e}=e):console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));const t=__wbg_get_imports();__wbg_init_memory(t),e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e));return __wbg_finalize_init(new WebAssembly.Instance(e,t),e)}async function __wbg_init(e){if(void 0!==wasm)return wasm;void 0!==e&&(Object.getPrototypeOf(e)===Object.prototype?({module_or_path:e}=e):console.warn("using deprecated parameters for the initialization function; pass a single object instead")),void 0===e&&(e=new URL("cap_wasm_bg.wasm",import.meta.url));const t=__wbg_get_imports();("string"==typeof e||"function"==typeof Request&&e instanceof Request||"function"==typeof URL&&e instanceof URL)&&(e=fetch(e)),__wbg_init_memory(t);const{instance:n,module:i}=await __wbg_load(await e,t);return __wbg_finalize_init(n,i)}export{initSync};export default __wbg_init;
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

+1
View File
@@ -0,0 +1 @@
window._iconfont_svg_string_5023051='<svg><symbol id="icon-zhipu" viewBox="0 0 1024 1024"><path d="M939.19763001 522.8741211V285.31340288a1.78646243 1.78646243 0 0 0-1.048576-1.66995399L512.97090333 46.19923911A1.94180779 1.94180779 0 0 0 512 45.96622222v99.42053888c0 192.937984 161.75255666 377.33201579 361.29268622 377.33201579a268.74614557 268.74614557 0 0 0-12.03920555 0.23301689h77.90531243v-0.03883577z" fill="#988EFF" ></path><path d="M84.80236999 522.8741211v246.10467157c0 0.73788643 0.3883611 1.39810133 1.00974023 1.74762667l425.17814955 245.83281778A1.94180779 1.94180779 0 0 0 512 1016.86992555v-102.99346489c0-199.81198222-161.71372089-390.76932267-361.29268622-390.76932267 4.03895979 0 8.0002469-0.03883577 12.03920555-0.23301689H84.80236999v0.07767268z" fill="#6253FF" ></path><path d="M84.80236999 522.8741211V285.31340288c0-0.73788643 0.3883611-1.39810133 1.00974023-1.66995399l425.17814955-237.40537401A1.94180779 1.94180779 0 0 1 512 45.96622222v99.42053888c0 192.937984-161.71372089 377.33201579-361.29268622 377.33201579 4.03895979 0 8.0002469 0.03883577 12.03920555 0.23301689H84.80236999v-0.03883577z" fill="#988EFF" ></path><path d="M939.19763001 522.8741211v246.10467157a1.94180779 1.94180779 0 0 1-1.048576 1.74762667l-425.17815068 245.83281778A1.94180779 1.94180779 0 0 1 512 1016.86992555v-102.99346489c0-199.81198222 161.75255666-390.76932267 361.29268622-390.76932267-4.03895979 0-8.0002469-0.03883577-12.03920555-0.23301689h77.90531243v0.07767268z" fill="#6253FF" ></path><path d="M512.07767267 145.46443378c0 192.89914823 161.75255666 377.29317888 361.29268623 377.29317888l-11.96153401 0.15534535c3.96128711 0.19418112 8.0002469 0.23301689 11.96153401 0.23301689-199.54012957 0-361.29268622 190.95734045-361.29268623 390.76932267 0-198.06435555-158.91751822-387.35174201-355.97213468-390.65281423v-0.23301689l6.71865401-0.11650844-6.79632555-0.11650844v-0.2330169c197.132288-3.18456377 356.04980622-185.90864157 356.04980622-377.09899889z" fill="#F7F8FA" ></path></symbol><symbol id="icon-minimax" viewBox="0 0 1169 1024"><path d="M476.53797594 473.26486343V826.44034906c-23.85146438 119.59950469-182.51685937 88.75722281-183.20309813 2.05590188-0.75279937-108.975 0-217.26563625 0-325.41846281V377.65369625c0-15.6944175-3.42650343-28.10014125-17.13345468-37.90153594-26.73047719-20.01246844-58.80555094 3.4958775-59.49085125 32.35069406-1.50841125 38.72370844-0.75467438 76.62524437-1.50841219 114.80052469 0 30.15698062 0 59.42335219 0.68530125 89.51095969C196.21717438 708.89862125 35.70118625 686.89774999 32 577.16807563V485.32746875c0-30.02010844 58.80555094-37.07936156 55.92747469 7.88142656-1.91902969 22.27461655-0.68623781 45.23547188-1.43997469 67.30477969-0.68436281 39.40900969 59.56022531 65.93324062 73.74716813 1.50747375 0.68530031-53.11689844 0.68530031-106.23379687 0.68530124-159.83068781 0-67.16696906 19.05342188-121.86071531 90.26469657-126.93250313 30.84228188-2.74120313 51.33474187 10.14357562 71.00502843 32.4181922 7.54018313 7.88236406 25.35893906 32.89912125 26.04517688 60.10865344 0 25.08519375 0.68436281 50.03257689 0.68436281 75.39245249 0 50.03163938-0.68436281 100.33889813-0.68436281 150.3724125 0 32.41819219 0.68436281 64.493265 0.68436281 96.15772031 0 40.16368406 0 80.87579625-0.68436281 121.10697938-0.68530031 52.294725 62.91735469 51.54098813 73.13030437-0.82217344 0-61.68456375 0.68436281-122.61445312 0.68436282-184.29901688 0-151.94832281-0.68436281-303.89758313-0.68436282-455.77840687 0-15.76379156-2.1937125-59.49085125 6.16864313-75.39151594C471.94524219-13.69800719 606.69073625 33.5239925 607.92446469 123.10338875c2.60433001 183.54527906 0 369.14646094 0.68530125 553.1023575 0 63.80890219-51.81473344 50.10195001-54.69280875 25.15362937 0-191.42670656 0-383.60714906 0.68436281-574.76010937-2.53495594-47.97667406-73.677795-41.46491156-77.79053625-7.05925406-1.37060156 39.47744531-0.68436281 79.64112937-1.37060156 119.05107656v234.39909187h0.68530031l0.4799925 0.27468283z" fill="#D4367A" ></path><path d="M684.82532937 470.45428719v259.34834906-612.04571812c23.16522656-120.41980313 181.7631225-89.09846719 182.44842282-2.32964719 0.75373687 108.22220062 0 217.19720063 0.75373687 325.35002625 0 41.53428563 0 83.20544343-0.68530031 124.73972906 0 16.44909188 4.04336812 28.03170563 17.81969344 38.58683625 26.04423938 19.53341344 58.05181406-3.42650343 59.49085125-32.76131156 1.43997562-37.96997156 0.68623781-75.93994311 0.68623781-114.86989875v-88.96253156c19.87559531-132.483345 179.91252938-110.48247375 183.27059719-0.75373688V699.16753906c0 30.15604406-58.12024969 37.28373375-55.51591969-7.81392843 1.57591031-22.95991781 0-285.87258094 0.82217344-308.90093438 1.37060156-38.72370844-59.62772437-66.00261469-73.74716906-0.82217344v159.00851344c0 68.12695313-19.12185844 121.92915188-90.94999782 127.7546775-67.71445969 1.57591031-94.92492938-45.23547188-97.11864093-92.52684562V254.42237937c0-40.91742094 0-80.87485875 0.68623781-121.0385428 0.68436281-52.2937875-62.91829219-52.2937875-73.Line truncated
Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

+631
View File
@@ -0,0 +1,631 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MonkeyCode - 企业级 AI 开发平台</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/theme/black.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/plugin/highlight/monokai.min.css">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--r-background-color: #0a0e17;
--r-main-font: 'Noto Sans SC', -apple-system, BlinkMacSystemFont, sans-serif;
--r-heading-font: 'Noto Sans SC', -apple-system, BlinkMacSystemFont, sans-serif;
--r-code-font: 'JetBrains Mono', monospace;
--r-main-color: #e8eaed;
--r-heading-color: #fff;
--r-link-color: #64ffda;
--r-link-color-hover: #9effd8;
--r-selection-background-color: rgba(100, 255, 218, 0.3);
--accent-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
--cyan-glow: #64ffda;
--purple-glow: #a78bfa;
--orange-glow: #fb923c;
}
.reveal {
font-weight: 400;
}
.reveal .slides {
text-align: left;
}
.reveal .slides section {
padding: 50px 60px;
box-sizing: border-box;
height: 100%;
}
.reveal h1, .reveal h2, .reveal h3 {
text-transform: none;
font-weight: 700;
letter-spacing: -0.02em;
}
.reveal h1 {
font-size: 2.5em;
background: var(--accent-gradient);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.reveal h2 {
font-size: 1.8em;
color: var(--cyan-glow);
margin-bottom: 0.6em;
}
.reveal h3 {
font-size: 1.15em;
color: var(--purple-glow);
}
.reveal p, .reveal li {
font-size: 0.95em;
line-height: 1.7;
color: #b8c0cc;
}
.reveal ul {
list-style: none;
padding-left: 0;
margin-top: 20px;
}
.reveal ul li {
position: relative;
padding-left: 1.8em;
margin-bottom: 0.7em;
}
.reveal ul li::before {
content: "▹";
position: absolute;
left: 0;
color: var(--cyan-glow);
font-size: 1em;
}
.reveal code {
font-family: var(--r-code-font);
background: rgba(100, 255, 218, 0.1);
border: 1px solid rgba(100, 255, 218, 0.2);
border-radius: 4px;
padding: 0.1em 0.4em;
color: var(--cyan-glow);
font-size: 0.9em;
}
/* Title slide styling */
.title-slide {
text-align: center !important;
display: flex !important;
flex-direction: column;
justify-content: center;
align-items: center;
}
.title-slide h1 {
font-size: 3.5em;
margin-bottom: 0.2em;
}
.title-slide .subtitle {
font-size: 1.2em;
color: #8892a6;
font-weight: 300;
}
.title-slide .company {
font-size: 0.9em;
color: var(--orange-glow);
margin-top: 30px;
}
/* Flow diagram */
.flow-box {
display: inline-flex;
align-items: center;
gap: 12px;
background: rgba(100, 255, 218, 0.08);
border: 1px solid rgba(100, 255, 218, 0.2);
border-radius: 8px;
padding: 12px 20px;
margin: 20px 0;
}
.flow-box .step {
background: linear-gradient(135deg, #667eea, #764ba2);
color: white;
padding: 8px 16px;
border-radius: 6px;
font-size: 0.85em;
font-weight: 500;
}
.flow-box .arrow {
color: var(--cyan-glow);
font-size: 1.2em;
}
/* Feature cards */
.feature-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 24px;
margin-top: 30px;
}
.feature-grid.three-col {
grid-template-columns: repeat(3, 1fr);
}
.feature-card {
background: linear-gradient(145deg, rgba(30, 41, 59, 0.8), rgba(15, 23, 42, 0.9));
border: 1px solid rgba(100, 255, 218, 0.15);
border-radius: 14px;
padding: 24px;
transition: all 0.3s ease;
}
.feature-card:hover {
border-color: rgba(100, 255, 218, 0.4);
transform: translateY(-3px);
box-shadow: 0 15px 30px rgba(100, 255, 218, 0.08);
}
.feature-card h3 {
margin-top: 0;
font-size: 1.05em;
}
.feature-card p {
font-size: 0.85em;
margin-bottom: 0;
}
/* Icon styling */
.icon {
font-size: 1.8em;
margin-bottom: 12px;
display: block;
}
/* Highlight box */
.highlight-box {
background: linear-gradient(135deg, rgba(102, 126, 234, 0.15), rgba(118, 75, 162, 0.1));
border-left: 3px solid var(--purple-glow);
padding: 16px 24px;
border-radius: 0 10px 10px 0;
margin: 20px 0;
}
.highlight-box p {
margin: 0;
font-size: 0.9em;
}
/* Two column layout */
.two-col {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 40px;
align-items: start;
}
/* Tag list */
.tag-list {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 16px;
}
.tag {
background: rgba(167, 139, 250, 0.15);
border: 1px solid rgba(167, 139, 250, 0.3);
color: var(--purple-glow);
padding: 6px 14px;
border-radius: 20px;
font-size: 0.8em;
}
/* Animated background */
.reveal .slides::before {
content: "";
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background:
radial-gradient(ellipse at 20% 80%, rgba(102, 126, 234, 0.15) 0%, transparent 50%),
radial-gradient(ellipse at 80% 20%, rgba(167, 139, 250, 0.1) 0%, transparent 50%),
radial-gradient(ellipse at 50% 50%, rgba(240, 147, 251, 0.05) 0%, transparent 70%);
pointer-events: none;
z-index: -1;
}
/* CTA button */
.cta-button {
display: inline-block;
padding: 14px 36px;
background: var(--accent-gradient);
color: white;
text-decoration: none;
border-radius: 50px;
font-weight: 600;
font-size: 1em;
margin-top: 30px;
transition: all 0.3s ease;
box-shadow: 0 8px 30px rgba(102, 126, 234, 0.3);
}
.cta-button:hover {
transform: scale(1.05);
box-shadow: 0 12px 40px rgba(102, 126, 234, 0.5);
}
/* Center helper */
.centered {
text-align: center !important;
display: flex !important;
flex-direction: column;
justify-content: center;
align-items: center;
}
/* Slide number */
.reveal .slide-number {
font-family: var(--r-code-font);
font-size: 0.8em;
color: #8892a6;
background: transparent;
}
/* Progress bar */
.reveal .progress {
height: 3px;
background: rgba(100, 255, 218, 0.1);
}
.reveal .progress span {
background: var(--accent-gradient);
}
/* Role cards */
.role-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
margin-top: 24px;
}
.role-card {
background: rgba(30, 41, 59, 0.6);
border: 1px solid rgba(100, 255, 218, 0.1);
border-radius: 10px;
padding: 20px;
text-align: center;
}
.role-card .role-icon {
font-size: 2em;
margin-bottom: 10px;
}
.role-card h4 {
color: var(--cyan-glow);
font-size: 0.95em;
margin: 0 0 8px 0;
}
.role-card p {
font-size: 0.8em;
margin: 0;
}
/* Git platforms */
.platform-list {
display: flex;
gap: 16px;
margin: 20px 0;
flex-wrap: wrap;
}
.platform {
background: rgba(100, 255, 218, 0.08);
border: 1px solid rgba(100, 255, 218, 0.2);
padding: 10px 20px;
border-radius: 8px;
font-size: 0.9em;
color: var(--cyan-glow);
}
/* Quote */
.quote {
font-size: 1.1em;
font-style: italic;
color: #e8eaed;
border-left: 3px solid var(--cyan-glow);
padding-left: 24px;
margin: 24px 0;
}
/* Compact list */
.compact-list li {
margin-bottom: 0.5em;
font-size: 0.88em;
}
</style>
</head>
<body>
<div class="reveal">
<div class="slides">
<!-- Slide 1: Title -->
<section class="title-slide">
<h1>MonkeyCode</h1>
<p class="subtitle">企业级 AI 开发平台</p>
<p class="company">长亭科技 出品</p>
<p style="margin-top: 50px; color: #64ffda; font-size: 0.75em;">
按 <code>Space</code> 或 <code>→</code> 键继续
</p>
</section>
<!-- Slide 2: 产品介绍 -->
<section>
<h2>什么是 MonkeyCode?</h2>
<p style="font-size: 1.05em; color: #e8eaed; margin-bottom: 24px;">
MonkeyCode 不只是一个 AI 编程工具,而是一个<strong style="color: var(--cyan-glow);">面向专业团队的 AI 研发基础设施</strong>
</p>
<div class="flow-box">
<span class="step">需求</span>
<span class="arrow">→</span>
<span class="step">设计</span>
<span class="arrow">→</span>
<span class="step">开发</span>
<span class="arrow">→</span>
<span class="step">Review</span>
</div>
<p>覆盖研发全流程,提供安全、隔离、可并行的开发环境</p>
<div class="highlight-box">
<p>📢 当前提供 SaaS 版,后续计划推出<strong style="color: var(--purple-glow);"> 离线部署版</strong> 和 <strong style="color: var(--purple-glow);">开源版</strong></p>
</div>
</section>
<!-- Slide 3: 产品定位 -->
<section>
<h2>✨ 产品定位</h2>
<ul>
<li class="fragment">企业级 AI Coding 平台</li>
<li class="fragment">面向专业开发者与研发团队</li>
<li class="fragment">支持真实工程场景,支持复杂项目与多人协作</li>
<li class="fragment">不只是写代码,而是参与完整研发流程</li>
</ul>
<div class="flow-box fragment" style="margin-top: 40px;">
<span class="step">需求</span>
<span class="arrow">→</span>
<span class="step">设计</span>
<span class="arrow">→</span>
<span class="step">开发</span>
<span class="arrow">→</span>
<span class="step">Review</span>
</div>
</section>
<!-- Slide 4: AI 智能任务 -->
<section>
<h2>🚀 AI 智能任务</h2>
<p>核心能力:通过<strong style="color: var(--cyan-glow);">自然语言</strong>驱动 AI 执行任务</p>
<div class="two-col" style="margin-top: 24px;">
<div>
<h3>底层能力</h3>
<p>由业内顶尖工具驱动:</p>
<div class="tag-list">
<span class="tag">OpenAI Codex</span>
<span class="tag">Claude Code</span>
</div>
<p style="margin-top: 16px; font-size: 0.85em;">已使用 Codex 或 Claude Code?<br>可无缝迁移至 MonkeyCode</p>
</div>
<div>
<h3>国产模型适配</h3>
<p>完整支持国内主流模型:</p>
<div class="tag-list">
<span class="tag">DeepSeek</span>
<span class="tag">Qwen</span>
<span class="tag">Kimi</span>
<span class="tag">GLM</span>
<span class="tag">Doubao</span>
</div>
</div>
</div>
</section>
<!-- Slide 5: SDD 项目开发 -->
<section>
<h2>🚀 SDD 项目开发</h2>
<p>基于 <strong style="color: var(--cyan-glow);">SDD(规范驱动开发)</strong> 的项目开发模式</p>
<p style="font-size: 0.85em; color: #8892a6;">相比 "Vibe coding",更强调可控性、可追溯性与工程质量</p>
<div class="flow-box" style="margin: 24px 0;">
<span class="step">原始需求</span>
<span class="arrow">→</span>
<span class="step">产品设计</span>
<span class="arrow">→</span>
<span class="step">技术设计</span>
<span class="arrow">→</span>
<span class="step">任务列表</span>
</div>
<div class="role-grid">
<div class="role-card fragment">
<div class="role-icon">👔</div>
<h4>产品经理</h4>
<p>需求拆解与产品设计</p>
</div>
<div class="role-card fragment">
<div class="role-icon">📋</div>
<h4>项目管理</h4>
<p>流程与进度管理</p>
</div>
<div class="role-card fragment">
<div class="role-icon">💻</div>
<h4>研发工程师</h4>
<p>技术设计与实现</p>
</div>
</div>
</section>
<!-- Slide 6: Git Review Bot -->
<section>
<h2>🚀 Git Review Bot</h2>
<p>深度集成主流 Git 平台,支持 AI 驱动的代码审查</p>
<div class="platform-list">
<span class="platform">GitHub</span>
<span class="platform">GitLab</span>
<span class="platform">Gitea</span>
<span class="platform">Gitee</span>
</div>
<h3 style="margin-top: 24px;">使用场景</h3>
<ul class="compact-list">
<li class="fragment">在 PR / MR 中 <code>@MonkeyCode</code>,自动进行代码 Review</li>
<li class="fragment">接入 DevOps 流程,代码提交时自动触发 AI Review</li>
<li class="fragment">支持独立部署的私有化 GitLab 集成</li>
</ul>
</section>
<!-- Slide 7: 在线开发环境 -->
<section>
<h2>🚀 在线开发环境</h2>
<p>灵活、安全的开发环境:<strong style="color: var(--cyan-glow);">本地开发机 + 云端控制</strong></p>
<div class="feature-grid" style="margin-top: 24px;">
<div class="feature-card fragment">
<span class="icon">🔒</span>
<h3>环境隔离</h3>
<p>每次任务自动创建虚拟机,AI 操作仅在虚拟机内执行,不影响真实环境</p>
</div>
<div class="feature-card fragment">
<span class="icon">⚡</span>
<h3>并行运行</h3>
<p>多个 AI 任务并行,每个任务独立虚拟环境,互不影响</p>
</div>
<div class="feature-card fragment">
<span class="icon">🔄</span>
<h3>失败重试</h3>
<p>任务失败可直接重试,系统自动创建新虚拟机</p>
</div>
<div class="feature-card fragment">
<span class="icon">📱</span>
<h3>多端访问</h3>
<p>支持 PC 与移动端,随时随地驱动 AI 执行研发任务</p>
</div>
</div>
</section>
<!-- Slide 8: 特色功能 -->
<section>
<h2>✨ 核心特色</h2>
<div class="feature-grid three-col" style="margin-top: 20px;">
<div class="feature-card fragment">
<span class="icon">🔧</span>
<h3>工具无关性</h3>
<p>支持 Codex、Claude Code 等,无缝切换</p>
</div>
<div class="feature-card fragment">
<span class="icon">🤖</span>
<h3>模型无关性</h3>
<p>兼容 GPT、Claude、DeepSeek、Kimi 等</p>
</div>
<div class="feature-card fragment">
<span class="icon">📐</span>
<h3>SDD 驱动</h3>
<p>严格管理技术设计,解决 AI 放飞自我问题</p>
</div>
<div class="feature-card fragment">
<span class="icon">🌐</span>
<h3>多入口触发</h3>
<p>IDE / Web / Git / API 多种方式发起任务</p>
</div>
<div class="feature-card fragment">
<span class="icon">🛡️</span>
<h3>环境隔离</h3>
<p>任务启动创建全新 OS,安全可控</p>
</div>
<div class="feature-card fragment">
<span class="icon">🏢</span>
<h3>企业级配置</h3>
<p>支持离线大模型,支持企业内网使用</p>
</div>
</div>
</section>
<!-- Slide 9: CTA -->
<section class="centered">
<h1>开始使用 MonkeyCode</h1>
<p style="font-size: 1em; color: #8892a6; margin: 20px 0;">
让 AI 成为你的研发基础设施
</p>
<a href="https://monkeycode-ai.com/" class="cta-button" target="_blank">立即体验</a>
<p style="margin-top: 40px; font-size: 0.8em; color: #64ffda;">
monkeycode-ai.com
</p>
</section>
<!-- Slide 10: Thank you -->
<section class="centered">
<h1>感谢观看</h1>
<p class="subtitle" style="font-size: 1em; color: #8892a6;">Q & A</p>
<p style="margin-top: 40px; font-size: 0.85em; color: var(--orange-glow);">
长亭科技 · MonkeyCode 团队
</p>
</section>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/plugin/highlight/highlight.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/plugin/notes/notes.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/plugin/markdown/markdown.min.js"></script>
<script>
Reveal.initialize({
hash: true,
slideNumber: 'c/t',
progress: true,
center: false,
transition: 'slide',
transitionSpeed: 'default',
backgroundTransition: 'fade',
plugins: [RevealHighlight, RevealNotes, RevealMarkdown],
// 16:9 宽高比
width: 1920,
height: 1080,
// 自适应缩放
margin: 0.04,
minScale: 0.2,
maxScale: 2.0,
// 键盘控制
keyboard: true,
// 触摸滑动
touch: true,
// 循环播放
loop: false,
// 右下角控制按钮
controls: true,
// 显示幻灯片编号
showSlideNumber: 'all',
});
</script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

+14
View File
@@ -0,0 +1,14 @@
# MonkeyCode AI 搜索引擎爬虫规则
User-agent: *
Allow: /
# 禁止爬取
Disallow: /console/
Disallow: /manager/
Disallow: /api/
Disallow: /assets/
# 站点地图
Sitemap: https://monkeycode-ai.com/sitemap.xml
+111
View File
@@ -0,0 +1,111 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://monkeycode-ai.com/</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=04578092-ea28-11f0-a0c6-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=48011724-e918-11f0-9d83-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=35ec3ff8-e25d-11f0-8eed-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=804108d2-e25c-11f0-89d9-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=df529c62-e259-11f0-8cbb-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=c7715082-e24c-11f0-9a94-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=50811b7a-e1a6-11f0-aa70-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=8b35c356-e1a1-11f0-b3d3-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=82050ad2-e19f-11f0-b3d3-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=11982c64-e19c-11f0-bc80-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=779ac4dc-e19b-11f0-bc80-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=f3b02f36-e19a-11f0-bc80-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=e8508b86-e19a-11f0-bc80-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=62a8346e-e197-11f0-a613-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=7e6ef8ec-e190-11f0-b405-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://monkeycode-ai.com/playground/detail?id=642b8e42-e18f-11f0-a3ff-caeba0df967f</loc>
<lastmod>2026-01-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
</urlset>
Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Sitemap 生成脚本
从 API 读取广场内容,生成 sitemap.xml
运行方式: python scripts/generate-sitemap.py
"""
import requests
import os
from datetime import datetime
# 配置
SITE_URL = 'https://monkeycode-ai.com'
API_URL = f'{SITE_URL}/api/v1/playground-posts'
OUTPUT_PATH = os.path.join(os.path.dirname(__file__), '../public/sitemap.xml')
# 静态页面配置
STATIC_PAGES = [
{'path': '/', 'changefreq': 'weekly', 'priority': '1.0'},
{'path': '/playground', 'changefreq': 'daily', 'priority': '0.8'},
]
def get_today():
"""获取今天的日期"""
return datetime.now().strftime('%Y-%m-%d')
def fetch_playground_posts():
"""从 API 获取广场帖子列表"""
try:
response = requests.get(API_URL, timeout=10)
response.raise_for_status()
data = response.json()
if data.get('code') == 0:
return data.get('data', {}).get('playground_posts', [])
else:
print(f'❌ API 返回错误: {data.get("message")}')
return []
except requests.RequestException as e:
print(f'❌ 请求 API 失败: {e}')
return []
def generate_url_entry(loc, lastmod, changefreq, priority):
"""生成单个 URL 条目"""
return f''' <url>
<loc>{loc}</loc>
<lastmod>{lastmod}</lastmod>
<changefreq>{changefreq}</changefreq>
<priority>{priority}</priority>
</url>'''
def generate_sitemap():
"""生成完整的 sitemap"""
today = get_today()
url_entries = []
# 添加静态页面
for page in STATIC_PAGES:
entry = generate_url_entry(
loc=f"{SITE_URL}{page['path']}",
lastmod=today,
changefreq=page['changefreq'],
priority=page['priority']
)
url_entries.append(entry)
# 从 API 获取广场帖子
posts = fetch_playground_posts()
print(f'📥 获取到 {len(posts)} 个广场帖子')
for post in posts:
post_id = post.get('id')
if not post_id:
continue
# 使用帖子的更新时间,如果没有则用今天
updated_at = post.get('updated_at')
if updated_at:
lastmod = datetime.fromtimestamp(updated_at).strftime('%Y-%m-%d')
else:
lastmod = today
entry = generate_url_entry(
loc=f"{SITE_URL}/playground/detail?id={post_id}",
lastmod=lastmod,
changefreq='weekly',
priority='0.6'
)
url_entries.append(entry)
# 组装 sitemap
sitemap = f'''<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{chr(10).join(url_entries)}
</urlset>
'''
return sitemap
def main():
print('🚀 开始生成 sitemap...')
sitemap = generate_sitemap()
# 确保输出目录存在
output_dir = os.path.dirname(OUTPUT_PATH)
os.makedirs(output_dir, exist_ok=True)
# 写入文件
with open(OUTPUT_PATH, 'w', encoding='utf-8') as f:
f.write(sitemap)
print(f'✅ sitemap.xml 生成成功!')
print(f'📍 输出路径: {os.path.abspath(OUTPUT_PATH)}')
if __name__ == '__main__':
main()
+42
View File
@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
+79
View File
@@ -0,0 +1,79 @@
import { Route, BrowserRouter, Routes, Navigate } from "react-router-dom"
import { ThemeProvider, ThemePathListener } from "@/components/theme-provider"
import LoginPage from "@/pages/login"
import WelcomePage from "@/pages/welcome"
import UserConsolePage from "@/pages/console/user/page"
import ManagerConsolePage from "@/pages/console/manager/page"
import SettingsPage from "@/pages/console/user/settings"
import TasksPage from "@/pages/console/user/tasks"
import IDEIDE from "@/pages/console/user/ide-ide"
import GitBotsPage from "@/pages/console/user/git-bots"
import TerminalPage from "@/pages/console/user/terminal"
import FileManagerPage from "@/pages/console/user/file-manager"
import { Toaster } from "@/components/ui/sonner"
import SharedTerminalPage from "@/pages/shared-terminal"
import TeamManagerMembers from "./pages/console/manager/members"
import TeamManagerDashboard from "./pages/console/manager/dashboard"
import TeamManagerModels from "@/pages/console/manager/models"
import TeamManagerImages from "@/pages/console/manager/images"
import TeamManagerLogs from "@/pages/console/manager/logs"
import TeamManagerHosts from "./pages/console/manager/hosts"
import ResetPasswordPage from "./pages/resetpassword"
import FindPasswordPage from "./pages/findpassword"
import TeamManagerManager from "./pages/console/manager/manager"
import ProjectPage from "./pages/console/user/project/project"
import PlaygroundPage from "./pages/playground"
import PlaygroundDetailPage from "./pages/playground-detail"
import PublicTaskPage from "./pages/public-task"
import PostCreatePage from "./pages/post-create"
import ProjectIssuesPage from "./pages/console/user/project/issues"
import ProjectTasksPage from "./pages/console/user/project/tasks"
import TaskDevelopPage from "./pages/console/user/task/task-dev"
function App() {
return (
<ThemeProvider defaultTheme="light" storageKey="monkeycode-theme">
<BrowserRouter>
<ThemePathListener />
<Routes>
<Route path="/" element={<WelcomePage />} />
<Route path="/playground" element={<PlaygroundPage />} />
<Route path="/playground/create" element={<PostCreatePage />} />
<Route path="/playground/detail" element={<PlaygroundDetailPage />} />
<Route path="/tasks/public" element={<PublicTaskPage />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/findpassword" element={<FindPasswordPage />} />
<Route path="/resetpassword" element={<ResetPasswordPage />} />
<Route path="/console" element={<UserConsolePage />}>
<Route index element={<Navigate to="/console/tasks" replace />} />
<Route path="tasks" element={<TasksPage />} />
<Route path="project/:projectId/docs/*" element={<ProjectPage />} />
<Route path="project/:projectId/issues" element={<ProjectIssuesPage />} />
<Route path="project/:projectId/tasks" element={<ProjectTasksPage />} />
<Route path="gitbot" element={<GitBotsPage />} />
<Route path="ide" element={<IDEIDE />} />
<Route path="settings" element={<SettingsPage />} />
</Route>
<Route path="/console/terminal" element={<TerminalPage />} />
<Route path="/console/files" element={<FileManagerPage />} />
<Route path="/console/task/develop/:taskId" element={<TaskDevelopPage />} />
<Route path="/sharedterminal" element={<SharedTerminalPage />} />
<Route path="/manager" element={<ManagerConsolePage />}>
<Route index element={<Navigate to="/manager/dashboard" replace />} />
<Route path="dashboard" element={<TeamManagerDashboard />} />
<Route path="members" element={<TeamManagerMembers />} />
<Route path="hosts" element={<TeamManagerHosts />} />
<Route path="images" element={<TeamManagerImages />} />
<Route path="models" element={<TeamManagerModels />} />
<Route path="logs" element={<TeamManagerLogs />} />
<Route path="manager" element={<TeamManagerManager />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</BrowserRouter>
<Toaster position="top-center" />
</ThemeProvider>
)
}
export default App
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

@@ -0,0 +1,64 @@
import { apiRequest } from "@/utils/requestUtils"
import { createContext, useContext, useEffect, useState } from "react"
type AuthProviderProps = {
children: React.ReactNode
}
type AuthProviderState = {
isLoggedIn: boolean
isLoading: boolean
checkAuth: () => void
}
const initialState: AuthProviderState = {
isLoggedIn: false,
isLoading: true,
checkAuth: () => null,
}
const AuthProviderContext = createContext<AuthProviderState>(initialState)
export function AuthProvider({ children }: AuthProviderProps) {
const [isLoggedIn, setIsLoggedIn] = useState(false)
const [isLoading, setIsLoading] = useState(true)
const checkAuth = async () => {
setIsLoading(true)
await apiRequest('v1UsersStatusList', {}, [],
() => {
setIsLoggedIn(true)
},
() => {
setIsLoggedIn(false)
}
)
setIsLoading(false)
}
useEffect(() => {
checkAuth()
}, [])
const value = {
isLoggedIn,
isLoading,
checkAuth,
}
return (
<AuthProviderContext.Provider value={value}>
{children}
</AuthProviderContext.Provider>
)
}
export const useAuth = () => {
const context = useContext(AuthProviderContext)
if (context === undefined)
throw new Error("useAuth must be used within an AuthProvider")
return context
}
@@ -0,0 +1,18 @@
import React from 'react';
type IconProps = {
name: string;
style?: React.CSSProperties;
[key: string]: any;
};
function Icon({ name, style = {}, ...props }: IconProps) {
return (
<svg style={style} {...props}>
<use xlinkHref={`#icon-${name}`} />
</svg>
);
};
export default Icon;
@@ -0,0 +1,166 @@
import { useState, useRef } from "react"
import { Api } from "@/api/Api"
import { toast } from "sonner"
import { IconLoader, IconEdit, IconEye } from "@tabler/icons-react"
import AceEditor from "react-ace"
import type { IAceEditor } from "react-ace/lib/types"
import "@/utils/ace-theme"
import { Markdown } from "@/components/common/markdown"
interface MarkdownEditorProps {
disabled?: boolean
value: string
onChange: (value: string) => void
height?: string
className?: string
placeholder?: string
onAddImage?: (imageUrl: string) => void
defaultMode?: "edit" | "preview"
}
export default function MarkdownEditor({
disabled = false,
value,
onChange,
height = "100%",
className = "",
placeholder,
onAddImage,
defaultMode = "edit",
}: MarkdownEditorProps) {
const [uploading, setUploading] = useState(false)
const [mode, setMode] = useState<"edit" | "preview">(defaultMode)
const editorRef = useRef<IAceEditor | null>(null)
const handlePaste = async (e: React.ClipboardEvent) => {
const items = e.clipboardData?.items
if (!items) return
for (const item of items) {
if (item.type.startsWith('image/')) {
e.preventDefault()
const file = item.getAsFile()
if (!file) continue
setUploading(true)
try {
const api = new Api()
const response = await api.api.v1UploaderCreate({
usage: 'spec',
file: file,
})
if (response.data?.code === 0 && response.data?.data) {
const imageUrl = response.data.data
const markdownImage = `![image](${imageUrl})`
// 在当前光标位置插入 markdown 图片
if (editorRef.current) {
const editor = editorRef.current
editor.session.insert(editor.getCursorPosition(), markdownImage)
editor.focus()
} else {
// 如果没有 editor 引用,直接追加到内容末尾
onChange(value + markdownImage)
}
onAddImage?.(imageUrl)
toast.success("图片上传成功")
} else {
toast.error("图片上传失败: " + (response.data?.message || '未知错误'))
}
} catch (error) {
toast.error("图片上传失败: " + (error as Error).message)
} finally {
setUploading(false)
}
break
}
}
}
return (
<div
className={`break-all overflow-hidden border rounded-md focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px] bg-[white] relative h-full flex flex-col ${className}`}
onPaste={handlePaste}
>
{/* Toolbar */}
<div className="flex items-center justify-between px-3 py-2 border-b bg-muted/30 shrink-0">
<div className="text-xs text-muted-foreground">
{mode === "edit" ? "编辑模式 - Markdown" : "预览模式"}
</div>
<div className="flex items-center gap-1">
<button
type="button"
onClick={() => setMode("preview")}
className={`p-1.5 rounded-md transition-colors ${
mode === "preview"
? "bg-primary text-primary-foreground"
: "hover:bg-muted text-muted-foreground"
}`}
title="预览"
>
<IconEye className="size-4" />
</button>
<button
type="button"
onClick={() => setMode("edit")}
className={`p-1.5 rounded-md transition-colors ${
mode === "edit"
? "bg-primary text-primary-foreground"
: "hover:bg-muted text-muted-foreground"
}`}
title="编辑"
>
<IconEdit className="size-4" />
</button>
</div>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto relative">
{uploading && (
<div className="absolute inset-0 bg-background/50 flex items-center justify-center z-10">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<IconLoader className="size-4 animate-spin" />
正在上传图片...
</div>
</div>
)}
{mode === "edit" ? (
<div className="w-full h-full p-1">
<AceEditor
mode="markdown"
theme="monkeycode"
width="100%"
readOnly={disabled}
height={height}
onChange={onChange}
value={value}
showPrintMargin={false}
wrapEnabled={true}
placeholder={placeholder}
onLoad={(editor) => {
editorRef.current = editor
}}
showGutter={false}
setOptions={{
fontFamily: "var(--font-google-sans-code)",
fontSize: 12,
}}
/>
</div>
) : (
<div className="p-2 prose prose-sm max-w-none h-0">
{value ? (
<Markdown allowHtml>{value}</Markdown>
) : (
<p className="text-muted-foreground italic">{placeholder || "暂无内容"}</p>
)}
</div>
)}
</div>
</div>
)
}
@@ -0,0 +1,277 @@
import { useEffect, useRef, useState } from "react"
import ReactMarkdown from "react-markdown"
import remarkGfm from "remark-gfm"
import rehypeRaw from "rehype-raw"
import rehypeSanitize from "rehype-sanitize"
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"
import mermaid from "mermaid"
import { Link, useLocation } from "react-router-dom"
import "@/utils/markdown.css"
import { cn } from "@/lib/utils"
// 动态导入 gray-matter 和 Buffer
let matter: any = null
let Buffer: any = null
async function initGrayMatter() {
if (matter && Buffer) return
try {
const [{ default: matterModule }, { Buffer: BufferModule }] = await Promise.all([
import("gray-matter"),
import("buffer")
])
matter = matterModule
Buffer = BufferModule
// 设置全局 Buffer
if (typeof window !== 'undefined') {
(window as any).Buffer = Buffer
}
if (typeof globalThis !== 'undefined') {
(globalThis as any).Buffer = Buffer
}
} catch (err) {
console.error("Failed to load gray-matter:", err)
}
}
// 初始化 mermaid 配置
mermaid.initialize({
startOnLoad: false,
theme: "default",
securityLevel: "loose",
suppressErrorRendering: true,
})
interface MermaidProps {
chart: string
}
function Mermaid({ chart }: MermaidProps) {
const containerRef = useRef<HTMLDivElement>(null)
const [svg, setSvg] = useState<string>("")
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const renderChart = async () => {
if (!containerRef.current) return
try {
// 使用唯一 ID 避免冲突
const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`
const { svg } = await mermaid.render(id, chart)
setSvg(svg)
setError(null)
} catch (err) {
console.error("Mermaid render error:", err)
setError(err instanceof Error ? err.message : "Failed to render diagram")
}
}
renderChart()
}, [chart])
if (error) {
return (
<div className="p-4 border border-red-300 bg-red-50 rounded-md text-red-700">
<p className="font-semibold">Mermaid 渲染错误</p>
<pre className="text-sm mt-2 whitespace-pre-wrap">{error}</pre>
<pre className="text-sm mt-2 p-2 bg-red-100 rounded overflow-x-auto">{chart}</pre>
</div>
)
}
return (
<div
ref={containerRef}
className="mermaid-container flex justify-center my-4"
dangerouslySetInnerHTML={{ __html: svg }}
/>
)
}
interface MarkdownProps {
children: string
/** 是否允许渲染原始 HTML(会自动进行安全处理) */
allowHtml?: boolean
/** 是否允许渲染站内链接 */
allowInternalLink?: boolean
className?: string
}
/**
* 判断是否为站内链接
* 站内链接包括:相对路径、以 / 开头的绝对路径、同域名的完整 URL
*/
function isInternalLink(href: string | undefined): boolean {
if (!href) return false
try {
const url = new URL(href, window.location.origin)
return url.origin === window.location.origin
} catch {
// 如果解析失败,当作站内链接处理
return true
}
}
/**
* 将相对路径解析为绝对路径
* @param href 原始链接
* @param currentPath 当前页面路径
*/
function resolveRelativePath(href: string, currentPath: string): string {
// 如果已经是绝对路径,直接返回
if (href.startsWith('/')) {
return href
}
// 处理相对路径
// 获取当前路径的目录部分(去掉最后的文件名/路由段)
const basePath = currentPath.endsWith('/')
? currentPath.slice(0, -1)
: currentPath.substring(0, currentPath.lastIndexOf('/')) || '/'
// 使用 URL API 解析相对路径
try {
const resolved = new URL(href, `http://dummy${basePath}/`).pathname
return resolved
} catch {
// 解析失败时返回原始 href
return href
}
}
export function Markdown({ children, allowHtml = false, allowInternalLink = true, className }: MarkdownProps) {
const location = useLocation()
const [frontMatter, setFrontMatter] = useState<Record<string, any>>({})
const [content, setContent] = useState<string>(children)
const [isLoading, setIsLoading] = useState(true)
// 初始化并解析 front matter
useEffect(() => {
let mounted = true
async function parseFrontMatter() {
await initGrayMatter()
if (!mounted || !matter) {
setContent(children)
setIsLoading(false)
return
}
try {
const result = matter(children)
if (mounted) {
setFrontMatter(result.data || {})
setContent(result.content)
}
} catch (err) {
console.error("Failed to parse front matter:", err)
if (mounted) {
setContent(children)
}
} finally {
if (mounted) {
setIsLoading(false)
}
}
}
parseFrontMatter()
return () => {
mounted = false
}
}, [children])
const hasFrontMatter = Object.keys(frontMatter).length > 0
if (isLoading) {
return <div className={cn("markdown-body pb-2", className)}>Loading...</div>
}
return (
<div className={cn("markdown-body pb-2", className)}>
{/* 渲染 front matter */}
{hasFrontMatter && (
<div className="overflow-x-auto mb-4 border-b">
<table className="w-full text-sm">
<tbody>
{Object.entries(frontMatter).map(([key, value]) => (
<tr key={key} className="border-b border-border/50 last:border-0">
<td className="py-2 pr-4 font-medium text-muted-foreground align-top w-32">
{key}
</td>
<td className="py-2 break-words">
{typeof value === 'object' && value !== null ? (
<pre className="text-xs bg-background p-2 rounded overflow-x-auto">
{JSON.stringify(value, null, 2)}
</pre>
) : (
<span>{String(value)}</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{/* 渲染 markdown 内容 */}
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={allowHtml ? [rehypeRaw, rehypeSanitize] : []}
components={{
a({ href, children, ...props }) {
if (isInternalLink(href)) {
const absolutePath = resolveRelativePath(href as string, location.pathname)
return <Link to={allowInternalLink ? absolutePath : ""} {...props}>{children}</Link>
} else {
return (
<a href={href} target="_blank" {...props}>
{children}
</a>
)
}
},
p({children, ...props}) {
if (typeof children === 'string') {
return (children as string).split('\n').map((line: string, index: number) => (
<p key={index} {...props}>{line}</p>
))
} else {
return <p {...props}>{children}</p>
}
},
pre({children}) {
const childElement = children as React.ReactElement | undefined
const props = childElement?.props as { children?: string; className?: string } | undefined
const code = props?.children ?? ''
const language = props?.className?.replace('language-', '').trim() || 'text'
// 检测是否是 mermaid 代码块
if (language === 'mermaid') {
return <Mermaid chart={String(code).trim()} />
}
return (
<SyntaxHighlighter
language={language}
PreTag="pre"
wrapLines={true}
>
{code}
</SyntaxHighlighter>
)
}
}}
>
{content}
</ReactMarkdown>
</div>
)
}
@@ -0,0 +1,250 @@
import { Terminal as XTerm } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import { WebglAddon } from '@xterm/addon-webgl';
import { Unicode11Addon } from '@xterm/addon-unicode11';
import { WebLinksAddon } from '@xterm/addon-web-links';
import '@xterm/xterm/css/xterm.css';
import React from 'react';
import themes from '@/utils/terminalThemes';
import { b64decode, b64encode } from '@/utils/common';
import { toast } from 'sonner';
const isWebglSupported = (): boolean => {
if (typeof document === 'undefined') {
return false;
}
try {
const canvas = document.createElement('canvas');
return Boolean(canvas.getContext('webgl2') || canvas.getContext('webgl'));
} catch (error) {
return false;
}
};
interface TerminalProps {
ws: string
theme: string
signal: number
onTitleChanged: ((env: string) => void) | null
onUserNameChanged: ((userName: string, userAvatar: string) => void) | null
onConnectionStatusChanged: ((status: 'connecting' | 'connected' | 'disconnected') => void) | null
}
export default function Terminal({
ws = '',
theme = '',
signal = 0,
onTitleChanged = null,
onUserNameChanged = null,
onConnectionStatusChanged = null,
}: TerminalProps) {
// 验证 theme 是否为合法值,如果不是则从 localStorage 读取,再不行就设置为 MonkeyCode
const validTheme = React.useMemo(() => {
// 如果传入的 theme 是合法值,直接使用
if (theme && theme in themes) {
return theme;
}
// 否则从 localStorage 读取
const savedTheme = localStorage.getItem('terminalTheme');
if (savedTheme && savedTheme in themes) {
return savedTheme;
}
// 最后使用默认值
return 'MonkeyCode';
}, [theme]);
const terminalDiv = React.useRef(null);
const xtermInstance = React.useRef<XTerm | null>(null);
const websocketInstance = React.useRef<WebSocket | null>(null);
const fitAddonRef = React.useRef<FitAddon | null>(null);
const [connecting, setConnecting] = React.useState(false);
const [connected, setConnected] = React.useState(false);
const pingLooper = React.useRef<number | null>(null);
React.useEffect(() => {
onConnectionStatusChanged?.(connecting ? 'connecting' : connected ? 'connected' : 'disconnected');
}, [connecting, connected])
const handleResize = () => {
if (xtermInstance.current) {
fitAddonRef.current?.fit();
// 判断 websocket 是否连接成功(readyState === 1 表示 OPEN 状态)
if (websocketInstance.current && websocketInstance.current.readyState === 1) {
websocketInstance.current.send(JSON.stringify({
type: "resize",
data: JSON.stringify({
row: xtermInstance.current?.rows,
col: xtermInstance.current?.cols
})
}));
}
}
};
React.useEffect(() => {
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
if (connected) {
event.preventDefault();
event.returnValue = ''; // Chrome 需要设置 returnValue
return ''; // 其他浏览器
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []);
// 使用 ResizeObserver 监听容器大小变化
React.useEffect(() => {
if (!terminalDiv.current) return;
const resizeObserver = new ResizeObserver(() => {
handleResize();
});
resizeObserver.observe(terminalDiv.current);
return () => {
resizeObserver.disconnect();
};
}, []);
React.useEffect(() => {
if (xtermInstance.current) {
xtermInstance.current.options.theme = { ...themes[validTheme as keyof typeof themes] };
xtermInstance.current.focus();
}
}, [validTheme])
const resetTerminal = () => {
if (xtermInstance.current) {
xtermInstance.current.dispose();
xtermInstance.current = null;
}
if (websocketInstance.current) {
websocketInstance.current.close();
websocketInstance.current = null;
}
if (pingLooper.current) {
clearInterval(pingLooper.current);
pingLooper.current = null;
}
setConnecting(false);
setConnected(false);
}
const connectTerminal = async () => {
if (!ws) {
return;
}
resetTerminal();
xtermInstance.current = new XTerm({
allowProposedApi: true,
theme: themes[validTheme as keyof typeof themes],
fontFamily: '"Google Sans Code"',
fontSize: 13,
});
xtermInstance.current.open(terminalDiv.current as unknown as HTMLElement);
const fitAddon = new FitAddon();
fitAddonRef.current = fitAddon;
const unicode11Addon = new Unicode11Addon();
const webLinksAddon = new WebLinksAddon();
xtermInstance.current.loadAddon(fitAddon);
if (isWebglSupported()) {
const webglAddon = new WebglAddon();
xtermInstance.current.loadAddon(webglAddon);
}
xtermInstance.current.loadAddon(unicode11Addon);
xtermInstance.current.loadAddon(webLinksAddon);
fitAddonRef.current.fit();
xtermInstance.current.onTitleChange((title) => {
onTitleChanged?.(title);
});
xtermInstance.current.onData((data) => {
if (websocketInstance.current && websocketInstance.current.readyState === WebSocket.OPEN) {
websocketInstance.current.send(JSON.stringify({
type: "data",
data: b64encode(data)
}));
}
});
connectWebSocket();
}
const connectWebSocket = () => {
setConnecting(true);
websocketInstance.current = new WebSocket(ws);
websocketInstance.current.onopen = () => {
pingLooper.current = window.setInterval(() => {
if (websocketInstance.current && websocketInstance.current.readyState === WebSocket.OPEN) {
websocketInstance.current.send(JSON.stringify({ type: "ping" }));
}
}, 5000);
};
websocketInstance.current.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'data') {
const decodedData = b64decode(data.data);
xtermInstance.current?.write(decodedData);
} else if (data.type === 'connected') {
const connectData = JSON.parse(data.data);
onUserNameChanged?.(connectData.username, connectData.avatar_url || "/logo-colored.png");
toast.success('终端连接成功');
setConnecting(false);
setConnected(true);
xtermInstance.current?.focus();
// 等待 DOM 更新后再触发 resize
requestAnimationFrame(() => {
handleResize();
});
} else if (data.type === 'resize') {
const { col, row } = JSON.parse(data.data);
xtermInstance.current?.resize(col, row);
} else if (data.type === 'error') {
toast.error(`错误:${data.data}`);
}
};
websocketInstance.current.onclose = (event) => {
if (websocketInstance.current === event.target) {
setConnecting(false);
setConnected(false);
}
};
websocketInstance.current.onerror = (event) => {
if (websocketInstance.current === event.target) {
setConnecting(false);
setConnected(false);
toast.error('终端连接发生错误');
}
};
}
React.useEffect(() => {
if (signal > 0) {
connectTerminal();
}
}, [signal])
return (
<div className='h-full w-full p-2 pr-0' style={{
backgroundColor: themes[validTheme as keyof typeof themes].background,
}}>
<div ref={terminalDiv} className='w-full h-full'>
</div>
</div>
)
}
@@ -0,0 +1,314 @@
import { ConstsGitPlatform, ConstsOwnerType, type DomainGitIdentity, type DomainHost, type DomainImage, type DomainModel, type DomainProject, type DomainUser, type DomainVirtualMachine } from '@/api/Api';
import { getImageShortName } from '@/utils/common';
import { apiRequest } from '@/utils/requestUtils';
import React, { createContext, useContext, useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
type CommonData = {
user: DomainUser;
reloadUser: () => void;
hosts: DomainHost[];
vms: DomainVirtualMachine[];
loadingHosts: boolean;
hostsInited: boolean;
reloadHosts: () => void;
models: DomainModel[];
loadingModels: boolean;
reloadModels: () => void;
images: DomainImage[];
loadingImages: boolean;
reloadImages: () => void;
identities: DomainGitIdentity[];
loadingIdentities: boolean;
reloadIdentities: () => void;
balance: number;
bonus: number;
reloadWallet: () => void;
members: DomainUser[];
loadingMembers: boolean;
reloadMembers: () => void;
projects: DomainProject[];
loadingProjects: boolean;
reloadProjects: () => void;
};
const DataContext = createContext<CommonData | null>(null);
export const DataProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [userInfo, setUserInfo] = useState<DomainUser>({});
const [hosts, setHosts] = useState<DomainHost[]>([]);
const [hostsInited, setHostsInited] = useState<boolean>(false);
const [loadingHosts, setLoadingHosts] = useState(true);
const [models, setModels] = useState<DomainModel[]>([]);
const [loadingModels, setLoadingModels] = useState(true);
const [images, setImages] = useState<DomainImage[]>([]);
const [loadingImages, setLoadingImages] = useState(true);
const [identities, setIdentities] = useState<DomainGitIdentity[]>([]);
const [loadingIdentities, setLoadingIdentities] = useState(true);
const [balance, setBalance] = useState(0);
const [bonus, setBonus] = useState(0);
const [members, setMembers] = useState<DomainUser[]>([]);
const [loadingMembers, setLoadingMembers] = useState(true);
const [projects, setProjects] = useState<DomainProject[]>([]);
const [loadingProjects, setLoadingProjects] = useState(true);
const fetchUserInfo = () => {
apiRequest('v1UsersStatusList', {}, [], (resp) => {
setUserInfo(resp.data?.user || {});
})
}
const fetchHosts = async () => {
setLoadingHosts(true)
await apiRequest('v1UsersHostsList', {}, [],(resp) => {
if (resp.code === 0) {
setHosts(resp.data?.hosts || [])
} else {
toast.error("获取宿主机列表失败: " + resp.message)
}
})
setTimeout(() => {
setHostsInited(true)
setLoadingHosts(false)
}, 500)
}
const showHosts = useMemo(() => {
return hosts.filter((host: DomainHost) => !host.id?.startsWith("public_host"))
}, [hosts])
const vms = useMemo(() => {
const allVms = hosts.flatMap((host) => {
const hostVms = host.virtualmachines || []
return hostVms.map((vm) => {
// 为每个 VM 添加所属 host 信息
const vmWithHost = {
...vm,
host: vm.host || host, // 如果 VM 本身已有 host 信息则保留,否则使用所属的 host
}
return vmWithHost
})
})
const sortedVms = allVms.sort((a, b) => {
// 正在运行的排在最上面
let aRunning = 0
if (a.status === 'offline') {
aRunning = 5
}
let bRunning = 0
if (b.status === 'offline') {
bRunning = 5
}
if (aRunning === bRunning) {
return (b.created_at as number) - (a.created_at as number)
}
return aRunning - bRunning
})
return sortedVms
}, [hosts])
const fetchModels = async () => {
setLoadingModels(true)
await apiRequest('v1UsersModelsList', {}, [], (resp) => {
if (resp.code === 0) {
const modelsList = resp.data?.models || [];
// 排序:先按 owner.type (private > team > public),然后按名字
const sortedModels = [...modelsList].sort((a, b) => {
// 定义 owner.type 的优先级
const getOwnerTypePriority = (type?: ConstsOwnerType): number => {
if (type === ConstsOwnerType.OwnerTypePrivate) return 1;
if (type === ConstsOwnerType.OwnerTypeTeam) return 2;
if (type === ConstsOwnerType.OwnerTypePublic) return 0;
return 3; // 未知类型排在最后
};
const priorityA = getOwnerTypePriority(a.owner?.type);
const priorityB = getOwnerTypePriority(b.owner?.type);
// 先按 owner.type 排序
if (priorityA !== priorityB) {
return priorityA - priorityB;
}
// 如果 owner.type 相同,按名字排序
const nameA = a.model || '未知模型';
const nameB = b.model || '未知模型';
return nameA.localeCompare(nameB);
});
setModels(sortedModels);
} else {
toast.error("获取模型列表失败: " + resp.message)
}
});
setTimeout(() => {
setLoadingModels(false)
}, 500)
}
const fetchImages = async () => {
setLoadingImages(true)
await apiRequest('v1UsersImagesList', {}, [], (resp) => {
if (resp.code === 0) {
const imagesList = resp.data?.images || [];
// 排序:先按 owner.type (private > team > public),然后按名字
const sortedImages = [...imagesList].sort((a, b) => {
// 定义 owner.type 的优先级
const getOwnerTypePriority = (type?: ConstsOwnerType): number => {
if (type === ConstsOwnerType.OwnerTypePrivate) return 0;
if (type === ConstsOwnerType.OwnerTypeTeam) return 1;
if (type === ConstsOwnerType.OwnerTypePublic) return 2;
return 3; // 未知类型排在最后
};
const priorityA = getOwnerTypePriority(a.owner?.type);
const priorityB = getOwnerTypePriority(b.owner?.type);
// 先按 owner.type 排序
if (priorityA !== priorityB) {
return priorityA - priorityB;
}
// 如果 owner.type 相同,按名字排序
const nameA = a.remark || getImageShortName(a.name || '');
const nameB = b.remark || getImageShortName(b.name || '');
return nameA.localeCompare(nameB);
});
setImages(sortedImages);
} else {
toast.error("获取镜像列表失败: " + resp.message)
}
})
setTimeout(() => {
setLoadingImages(false)
}, 500)
}
const fetchIdentities = () => {
setLoadingIdentities(true)
apiRequest('v1UsersGitIdentitiesList', {}, [], (resp) => {
if (resp.code === 0) {
const list = resp.data || [];
// 隐藏 platform 为 internal 的身份凭证
setIdentities(list.filter((i: DomainGitIdentity) => i.platform !== ConstsGitPlatform.GitPlatformInternal));
} else {
toast.error("获取身份列表失败: " + resp.message)
}
})
setTimeout(() => {
setLoadingIdentities(false)
}, 500)
}
const fetchWallet = () => {
apiRequest('v1UsersWalletList', {}, [], (resp) => {
if (resp.code === 0) {
setBalance(resp.data?.balance / 1000);
setBonus(resp.data?.bonus / 1000);
} else {
toast.error("获取余额失败: " + resp.message);
}
})
}
const fetchMembers = async () => {
setLoadingMembers(true)
await apiRequest('v1UsersMembersList', {}, [], (resp) => {
if (resp.code === 0) {
setMembers(resp.data || [])
} else {
toast.error("获取协作成员失败: " + resp.message)
}
})
setLoadingMembers(false)
}
const fetchProjects = async () => {
setLoadingProjects(true)
await apiRequest('v1UsersProjectsList', {}, [], (resp) => {
if (resp.code === 0) {
setProjects(resp.data?.projects || [])
} else {
toast.error("获取项目列表失败: " + resp.message)
}
})
setLoadingProjects(false)
}
useEffect(() => {
fetchUserInfo();
fetchHosts();
fetchModels();
fetchImages();
fetchIdentities();
fetchWallet();
fetchMembers();
fetchProjects();
}, []);
return (
<DataContext.Provider value={{
user: userInfo,
reloadUser: fetchUserInfo,
hosts: showHosts,
vms: vms,
loadingHosts: loadingHosts,
hostsInited: hostsInited,
reloadHosts: fetchHosts,
models: models,
loadingModels: loadingModels,
reloadModels: fetchModels,
images: images,
loadingImages: loadingImages,
reloadImages: fetchImages,
identities: identities,
loadingIdentities: loadingIdentities,
reloadIdentities: fetchIdentities,
balance: balance,
bonus: bonus,
reloadWallet: fetchWallet,
members: members,
loadingMembers: loadingMembers,
reloadMembers: fetchMembers,
projects: projects,
loadingProjects: loadingProjects,
reloadProjects: fetchProjects,
}}>
{children}
</DataContext.Provider>
);
};
export const useCommonData = () => {
const ctx = useContext(DataContext);
if (!ctx) throw new Error('useCommonData must be used within DataProvider');
return ctx;
};
@@ -0,0 +1,134 @@
import { useState, useEffect } from "react"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Field, FieldLabel } from "@/components/ui/field"
import { Spinner } from "@/components/ui/spinner"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { normalizePath } from "@/utils/common"
interface CopyFileDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
sourcePath: string
envid: string
baseDir?: string
onSuccess?: () => void
}
const generateNewFileName = (fileName: string): string => {
// 在文件名后添加 _new
const lastDotIndex = fileName.lastIndexOf('.')
if (lastDotIndex > 0) {
// 有扩展名的情况:test.txt -> test_new.txt
const nameWithoutExt = fileName.substring(0, lastDotIndex)
const ext = fileName.substring(lastDotIndex)
return nameWithoutExt + '_new' + ext
} else {
// 没有扩展名的情况:test -> test_new
return fileName + '_new'
}
}
export default function CopyFileDialog({
open,
onOpenChange,
sourcePath,
envid,
baseDir = '',
onSuccess,
}: CopyFileDialogProps) {
const [targetDir, setTargetDir] = useState('')
const [targetFileName, setTargetFileName] = useState('')
const [copying, setCopying] = useState(false)
useEffect(() => {
if (open && sourcePath) {
// 从源文件路径推断目标目录和文件名
const pathParts = sourcePath.split('/')
const fileName = pathParts[pathParts.length - 1]
const dirPath = pathParts.slice(0, -1).join('/')
setTargetDir(dirPath || './')
setTargetFileName(generateNewFileName(fileName))
}
}, [open, sourcePath])
const handleCopy = async () => {
if (!sourcePath || !targetFileName.trim() || !envid) {
toast.error('请填写完整信息')
return
}
// API 调用时添加 baseDir 前缀
const fullSourcePath = normalizePath(baseDir + '/' + sourcePath)
const fullTargetPath = normalizePath(baseDir + '/' + targetDir + '/' + targetFileName.trim())
setCopying(true)
await apiRequest('v1UsersFilesCopyCreate', {
id: envid,
source: fullSourcePath,
target: fullTargetPath
}, [], (resp) => {
if (resp.code === 0) {
toast.success(`已复制文件 "${targetFileName.trim()}"`)
onOpenChange(false)
if (onSuccess) {
onSuccess()
}
} else {
toast.error("复制文件失败: " + resp.message);
}
})
setCopying(false)
}
const handleCancel = () => {
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>复制文件</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<Field>
<FieldLabel>源文件路径</FieldLabel>
<Input
value={sourcePath || './'}
readOnly
className="bg-muted"
/>
</Field>
<Field>
<FieldLabel>目标目录</FieldLabel>
<Input
value={targetDir}
onChange={(e) => setTargetDir(e.target.value)}
autoFocus
/>
</Field>
<Field>
<FieldLabel>新文件名称</FieldLabel>
<Input
value={targetFileName}
onChange={(e) => setTargetFileName(e.target.value)}
/>
</Field>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel}>
取消
</Button>
<Button onClick={handleCopy} disabled={!sourcePath || !targetDir.trim() || !targetFileName.trim() || copying}>
{copying && <Spinner />}
确认复制
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,136 @@
import { useState, useEffect } from "react"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Field, FieldLabel } from "@/components/ui/field"
import { Spinner } from "@/components/ui/spinner"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { normalizePath } from "@/utils/common"
import AceEditor from "react-ace"
import "ace-builds/src-noconflict/theme-github"
import "ace-builds/src-noconflict/theme-terminal"
import { useTheme } from "@/components/theme-provider"
interface CreateFileDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
targetDir: string
envid: string
baseDir?: string
onSuccess?: () => void
}
export default function CreateFileDialog({
open,
onOpenChange,
targetDir,
envid,
baseDir = '',
onSuccess,
}: CreateFileDialogProps) {
const { theme } = useTheme()
const [fileName, setFileName] = useState('')
const [fileContent, setFileContent] = useState('')
const [creating, setCreating] = useState(false)
useEffect(() => {
if (open) {
setFileName('')
setFileContent('')
}
}, [open])
const handleCreate = async () => {
if (!fileName.trim() || !envid) {
toast.error('请输入文件名称')
return
}
const filePath = normalizePath(baseDir + '/' + targetDir + '/' + fileName.trim())
setCreating(true)
await apiRequest('v1UsersFilesSaveUpdate', {
id: envid,
path: filePath,
content: fileContent
}, [], (resp) => {
if (resp.code === 0) {
toast.success(`已创建文件 "${fileName.trim()}"`)
onOpenChange(false)
if (onSuccess) {
onSuccess()
}
} else {
toast.error("创建文件失败: " + resp.message);
}
})
setCreating(false)
}
const handleCancel = () => {
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>创建文件</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<Field>
<FieldLabel>目标目录</FieldLabel>
<Input
value={targetDir || './'}
readOnly
className="bg-muted"
/>
</Field>
<Field>
<FieldLabel>新文件名称</FieldLabel>
<Input
value={fileName}
onChange={(e) => setFileName(e.target.value)}
autoFocus
/>
</Field>
<Field>
<FieldLabel>文件内容</FieldLabel>
<div className="border rounded-md overflow-hidden p-0 overflow-y-hidden">
<AceEditor
mode="text"
theme={theme === 'dark' ? 'terminal' : 'github'}
value={fileContent}
onChange={setFileContent}
width="100%"
fontSize={13}
showPrintMargin={false}
highlightActiveLine={false}
height="30vh"
setOptions={{
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
enableSnippets: true,
showLineNumbers: false,
showGutter: false,
tabSize: 2,
useWorker: false,
}}
/>
</div>
</Field>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel}>
取消
</Button>
<Button onClick={handleCreate} disabled={!fileName.trim() || !fileContent.trim() || creating}>
{creating && <Spinner />}
创建
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,102 @@
import { useState, useEffect } from "react"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Field, FieldLabel } from "@/components/ui/field"
import { Spinner } from "@/components/ui/spinner"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { normalizePath } from "@/utils/common"
interface CreateFolderDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
targetDir: string
envid: string
baseDir?: string
onSuccess?: () => void
}
export default function CreateFolderDialog({
open,
onOpenChange,
targetDir,
envid,
baseDir = '',
onSuccess,
}: CreateFolderDialogProps) {
const [folderName, setFolderName] = useState('')
const [creating, setCreating] = useState(false)
useEffect(() => {
if (open) {
setFolderName('')
}
}, [open])
const handleCreate = async () => {
if (!folderName.trim() || !envid) {
toast.error('请输入文件夹名称')
return
}
const folderPath = normalizePath(baseDir + '/' + targetDir + '/' + folderName.trim())
setCreating(true)
await apiRequest('v1UsersFoldersCreate', {
id: envid,
path: folderPath
}, [], (resp) => {
if (resp.code === 0) {
toast.success(`已创建文件夹 "${folderName.trim()}"`)
onOpenChange(false)
if (onSuccess) {
onSuccess()
}
} else {
toast.error("创建文件夹失败: " + resp.message);
}
})
setCreating(false)
}
const handleCancel = () => {
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>创建文件夹</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<Field>
<FieldLabel>目标目录</FieldLabel>
<Input
value={targetDir || './'}
readOnly
className="bg-muted"
/>
</Field>
<Field>
<FieldLabel>新文件夹名称</FieldLabel>
<Input
value={folderName}
onChange={(e) => setFolderName(e.target.value)}
autoFocus
/>
</Field>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel}>
取消
</Button>
<Button onClick={handleCreate} disabled={!folderName.trim() || creating}>
{creating && <Spinner />}
创建
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,167 @@
import { useState, useEffect } from "react"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import AceEditor from "react-ace"
import "ace-builds/src-noconflict/mode-text"
import "ace-builds/src-noconflict/mode-javascript"
import "ace-builds/src-noconflict/mode-typescript"
import "ace-builds/src-noconflict/mode-python"
import "ace-builds/src-noconflict/mode-json"
import "ace-builds/src-noconflict/mode-yaml"
import "ace-builds/src-noconflict/mode-markdown"
import "ace-builds/src-noconflict/mode-html"
import "ace-builds/src-noconflict/mode-css"
import "ace-builds/src-noconflict/mode-sql"
import "ace-builds/src-noconflict/mode-sh"
import "ace-builds/src-noconflict/mode-dockerfile"
import "ace-builds/src-noconflict/theme-github"
import "ace-builds/src-noconflict/theme-monokai"
import "ace-builds/src-noconflict/ext-language_tools"
import { useTheme } from "@/components/theme-provider"
import { Spinner } from "@/components/ui/spinner"
import { Empty, EmptyHeader, EmptyMedia } from "@/components/ui/empty"
interface FileEditorProps {
open: boolean
onOpenChange: (open: boolean) => void
path: string | null
envid: string
}
const getLanguageMode = (fileName: string): string => {
const ext = fileName.split('.').pop()?.toLowerCase()
const modeMap: Record<string, string> = {
'js': 'javascript',
'jsx': 'javascript',
'ts': 'typescript',
'tsx': 'typescript',
'py': 'python',
'sh': 'sh',
'bash': 'sh',
'zsh': 'sh',
'fish': 'sh',
'sql': 'sql',
'html': 'html',
'htm': 'html',
'css': 'css',
'json': 'json',
'yaml': 'yaml',
'yml': 'yaml',
'md': 'markdown',
'markdown': 'markdown',
'dockerfile': 'dockerfile',
}
return modeMap[ext || ''] || 'text'
}
export default function FileEditor({
open,
onOpenChange,
path,
envid,
}: FileEditorProps) {
const [content, setContent] = useState("")
const [loading, setLoading] = useState(false)
const [saving, setSaving] = useState(false)
const { theme } = useTheme()
const [languageMode, setLanguageMode] = useState("text")
useEffect(() => {
if (open && path) {
setLanguageMode(getLanguageMode(path || ""))
fetchFileContent()
} else {
setContent("")
}
}, [open, path])
const fetchFileContent = async () => {
if (!path || !envid) return
setLoading(true)
fetch(`/api/v1/users/files/download?id=${envid}&path=${encodeURIComponent(path)}`).then(resp => {
if (!resp.ok) {
throw new Error(`${resp.status}`);
}
return resp.text()
}).then(text => {
setContent(text)
}).catch(err => {
toast.error(`文件读取失败:${err.message}`)
}).finally(() => {
setLoading(false)
})
}
const handleSave = async () => {
if (!path || !envid) return
setSaving(true)
await apiRequest('v1UsersFilesSaveUpdate', {
id: envid,
path: path,
content: content,
}, [], (resp) => {
if (resp.code === 0) {
toast.success('文件保存成功')
onOpenChange(false)
} else {
toast.error("文件保存失败: " + resp.message);
}
})
setSaving(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-[90vw] flex flex-col sm:max-w-[60vw]">
<DialogHeader>
<DialogTitle>{path}</DialogTitle>
</DialogHeader>
{loading ? (
<Empty className="bg-muted">
<EmptyHeader>
<EmptyMedia variant="icon">
<Spinner className="size-6" />
</EmptyMedia>
</EmptyHeader>
</Empty>
) : (
<div className="border h-[60vh]">
<AceEditor
mode={languageMode}
theme={theme === 'dark' ? 'monokai' : 'github'}
value={content}
onChange={setContent}
width="100%"
height="100%"
fontSize={14}
showPrintMargin={false}
highlightActiveLine={false}
setOptions={{
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
enableSnippets: true,
showLineNumbers: true,
tabSize: 2,
useWorker: false,
}}
/>
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
取消
</Button>
<Button onClick={handleSave} disabled={loading || saving}>
{saving && <Spinner className="size-4 mr-2" />}
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,418 @@
import { useState, useEffect, useCallback } from "react"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { apiRequest } from "@/utils/requestUtils"
import { normalizePath } from "@/utils/common"
import { ConstsFileKind, type TypesFile } from "@/api/Api"
import { toast } from "sonner"
import { IconChevronDown, IconChevronRight, IconFile, IconFolder, IconFolderOpen } from "@tabler/icons-react"
import { Spinner } from "@/components/ui/spinner"
import { cn } from "@/lib/utils"
interface TreeNode {
file: TypesFile
path: string
depth: number
children?: TreeNode[]
isLoading?: boolean
}
interface FilePickerDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
envid?: string
onSelect: (filePaths: string[]) => void
defaultSelectedFiles?: string[]
}
const ROOT_PATH = '/workspace'
export default function FilePickerDialog({
open,
onOpenChange,
envid,
onSelect,
defaultSelectedFiles = [],
}: FilePickerDialogProps) {
const [treeNodes, setTreeNodes] = useState<TreeNode[]>([])
const [loading, setLoading] = useState(false)
const [expandedDirs, setExpandedDirs] = useState<Set<string>>(new Set())
const [selectedFiles, setSelectedFiles] = useState<string[]>([])
const sortFiles = (files: TypesFile[]) => {
return [...files].sort((a, b) => {
const getTypePriority = (file: TypesFile) => {
if (file.kind === 'symlink') {
return file.symlink_kind === 'dir' ? 0 : 2
}
return file.kind === 'dir' ? 0 : 2
}
const priorityA = getTypePriority(a)
const priorityB = getTypePriority(b)
if (priorityA !== priorityB) {
return priorityA - priorityB
}
return (a.name || '').localeCompare(b.name || '')
})
}
const fetchFiles = useCallback(async (path: string, depth: number): Promise<TreeNode[]> => {
if (!envid) return []
let result: TreeNode[] = []
await apiRequest('v1UsersFoldersList', {
id: envid,
path: path
}, [], (resp) => {
if (resp.code === 0) {
// Filter out . and .. entries
const filteredFiles = (resp.data || []).filter(
(file: TypesFile) => file.name !== '.' && file.name !== '..'
)
const sortedFiles = sortFiles(filteredFiles)
result = sortedFiles.map(file => ({
file,
path: normalizePath(path + '/' + file.name),
depth,
}))
} else {
toast.error("获取文件列表失败: " + resp.message)
}
})
return result
}, [envid])
useEffect(() => {
if (open) {
setSelectedFiles(defaultSelectedFiles)
setExpandedDirs(new Set([ROOT_PATH])) // Auto expand workspace
setLoading(true)
fetchFiles(ROOT_PATH, 1).then(children => {
// Create root workspace node with children
const rootNode: TreeNode = {
file: { name: 'workspace', kind: ConstsFileKind.FileKindDir },
path: ROOT_PATH,
depth: 0,
children,
}
setTreeNodes([rootNode])
setLoading(false)
})
}
}, [open, defaultSelectedFiles, fetchFiles])
const isDirectory = (file: TypesFile) => {
return file.kind === 'dir' || (file.kind === 'symlink' && file.symlink_kind === 'dir')
}
const handleExpandToggle = async (node: TreeNode, e: React.MouseEvent) => {
e.stopPropagation()
const dirPath = node.path
const isExpanded = expandedDirs.has(dirPath)
if (isExpanded) {
// Collapse: remove from expanded set
setExpandedDirs(prev => {
const next = new Set(prev)
next.delete(dirPath)
return next
})
} else {
// Expand: load children if not loaded
if (!node.children) {
// Mark as loading
setTreeNodes(prev => updateNodeChildren(prev, dirPath, [], true))
const children = await fetchFiles(dirPath, node.depth + 1)
setTreeNodes(prev => updateNodeChildren(prev, dirPath, children, false))
}
setExpandedDirs(prev => {
const next = new Set(prev)
next.add(dirPath)
return next
})
}
}
const updateNodeChildren = (nodes: TreeNode[], targetPath: string, children: TreeNode[], isLoading: boolean): TreeNode[] => {
return nodes.map(node => {
if (node.path === targetPath) {
return { ...node, children, isLoading }
}
if (node.children) {
return { ...node, children: updateNodeChildren(node.children, targetPath, children, isLoading) }
}
return node
})
}
// Get all file paths under a node (recursively)
const getAllFilesUnderNode = (node: TreeNode): string[] => {
const files: string[] = []
if (!isDirectory(node.file)) {
files.push(node.path)
} else if (node.children) {
for (const child of node.children) {
files.push(...getAllFilesUnderNode(child))
}
}
return files
}
// Check directory selection state
const getDirSelectionState = (node: TreeNode): 'none' | 'some' | 'all' => {
if (!node.children || node.children.length === 0) {
return 'none'
}
const allFiles = getAllFilesUnderNode(node)
if (allFiles.length === 0) return 'none'
const selectedCount = allFiles.filter(f => selectedFiles.includes(f)).length
if (selectedCount === 0) return 'none'
if (selectedCount === allFiles.length) return 'all'
return 'some'
}
// Check if a directory has unloaded content (itself or child directories)
const hasUnloadedContent = (node: TreeNode): boolean => {
// If this directory itself hasn't been loaded
if (!node.children) return true
// Check child directories
for (const child of node.children) {
if (isDirectory(child.file)) {
// This child is a directory - check if it's loaded
if (!child.children) {
return true // Unloaded directory found
}
// Recursively check
if (hasUnloadedContent(child)) {
return true
}
}
}
return false
}
const handleFileToggle = (filePath: string) => {
setSelectedFiles(prev =>
prev.includes(filePath)
? prev.filter(f => f !== filePath)
: [...prev, filePath]
)
}
const handleDirToggle = async (node: TreeNode) => {
// If not expanded, expand first to load children
if (!node.children) {
setTreeNodes(prev => updateNodeChildren(prev, node.path, [], true))
const children = await fetchFiles(node.path, node.depth + 1)
setTreeNodes(prev => updateNodeChildren(prev, node.path, children, false))
// After loading, select all files
const allFiles = children.flatMap(child => {
if (!isDirectory(child.file)) {
return [child.path]
}
return []
})
setSelectedFiles(prev => {
const newSelected = [...prev]
for (const file of allFiles) {
if (!newSelected.includes(file)) {
newSelected.push(file)
}
}
return newSelected
})
// Also expand
setExpandedDirs(prev => {
const next = new Set(prev)
next.add(node.path)
return next
})
return
}
const state = getDirSelectionState(node)
const allFiles = getAllFilesUnderNode(node)
if (state === 'all') {
// Unselect all
setSelectedFiles(prev => prev.filter(f => !allFiles.includes(f)))
} else {
// Select all
setSelectedFiles(prev => {
const newSelected = [...prev]
for (const file of allFiles) {
if (!newSelected.includes(file)) {
newSelected.push(file)
}
}
return newSelected
})
}
}
const handleConfirm = () => {
onSelect(selectedFiles)
onOpenChange(false)
}
const getFileIcon = (file: TypesFile, isExpanded: boolean) => {
const kind = file.kind === 'symlink' ? file.symlink_kind : file.kind
switch (kind) {
case 'dir':
return isExpanded
? <IconFolderOpen className="h-4 w-4 text-yellow-500" />
: <IconFolder className="h-4 w-4 text-yellow-500" />
case 'file':
default:
return <IconFile className="h-4 w-4" />
}
}
const formatFileSize = (size?: number) => {
if (size === undefined || size === null) return ''
if (size < 1024) return `${size} B`
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)} MB`
return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`
}
const renderNode = (node: TreeNode): React.ReactNode => {
const isDir = isDirectory(node.file)
const isExpanded = expandedDirs.has(node.path)
const isSelected = selectedFiles.includes(node.path)
const dirState = isDir ? getDirSelectionState(node) : null
const hasUnloaded = isDir && hasUnloadedContent(node)
const paddingLeft = node.depth * 16 + 12
return (
<div key={node.path}>
<div
className={cn(
"flex items-center gap-2 py-3 cursor-pointer border-b",
(isSelected || dirState === 'all') ? "bg-primary/10" : "hover:bg-muted",
isDir && "font-medium"
)}
style={{ paddingLeft }}
onClick={() => isDir ? handleDirToggle(node) : handleFileToggle(node.path)}
>
{/* Chevron for directories, spacer for files */}
{isDir ? (
<div
className="flex items-center size-4"
onClick={(e) => handleExpandToggle(node, e)}
>
{node.isLoading ? (
<Spinner className="size-4" />
) : isExpanded ? (
<IconChevronDown className="size-4" />
) : (
<IconChevronRight className="size-4" />
)}
</div>
) : (
<div className="size-4" />
)}
{/* Checkbox */}
<Checkbox
checked={isDir ? dirState === 'all' : isSelected}
indeterminate={isDir ? dirState === 'some' : false}
onClick={(e) => {
e.stopPropagation()
if (isDir) {
handleDirToggle(node)
} else {
handleFileToggle(node.path)
}
}}
/>
{getFileIcon(node.file, isExpanded)}
<span className="truncate text-sm">{node.file.name}</span>
{isDir && hasUnloaded && (
<span className="text-muted-foreground text-xs flex-shrink-0">
(子目录未完全加载)
</span>
)}
<span className="flex-1" />
{node.file.kind === 'symlink' && node.file.symlink_target && (
<span className="text-muted-foreground text-xs pr-3">
→ {node.file.symlink_target}
</span>
)}
{!isDir && node.file.size !== undefined && (
<span className="text-muted-foreground text-xs pr-3 flex-shrink-0">
{formatFileSize(node.file.size)}
</span>
)}
</div>
{isDir && isExpanded && node.children && (
<>
{node.children.length === 0 ? (
<div
className="text-muted-foreground text-xs py-1 border-b"
style={{ paddingLeft: paddingLeft + 24 }}
>
(空目录)
</div>
) : (
node.children.map(child => renderNode(child))
)}
</>
)}
</div>
)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>选择产出物</DialogTitle>
</DialogHeader>
<div className="h-[50vh] overflow-y-auto border rounded-md">
{loading ? (
<div className="flex items-center justify-center h-full">
<Spinner className="size-6" />
</div>
) : treeNodes.length === 0 ? (
<div className="flex items-center justify-center h-full text-muted-foreground py-8">
此目录为空
</div>
) : (
<div className="flex flex-col">
{treeNodes.map(node => renderNode(node))}
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
取消
</Button>
<Button onClick={handleConfirm}>
确定
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,120 @@
import { useState, useEffect } from "react"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Field, FieldLabel } from "@/components/ui/field"
import { Spinner } from "@/components/ui/spinner"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { normalizePath } from "@/utils/common"
interface MoveFileDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
sourcePath: string
envid: string
baseDir?: string
onSuccess?: () => void
}
export default function MoveFileDialog({
open,
onOpenChange,
sourcePath,
envid,
baseDir = '',
onSuccess,
}: MoveFileDialogProps) {
const [targetDir, setTargetDir] = useState('')
const [targetFileName, setTargetFileName] = useState('')
const [moving, setMoving] = useState(false)
useEffect(() => {
if (open && sourcePath) {
// 从源文件路径推断目标目录和文件名
const pathParts = sourcePath.split('/')
const fileName = pathParts[pathParts.length - 1]
const dirPath = pathParts.slice(0, -1).join('/')
setTargetDir(dirPath || './')
setTargetFileName(fileName)
}
}, [open, sourcePath])
const handleMove = async () => {
if (!sourcePath || !targetFileName.trim() || !envid) {
toast.error('请填写完整信息')
return
}
// API 调用时添加 baseDir 前缀
const fullSourcePath = normalizePath(baseDir + '/' + sourcePath)
const fullTargetPath = normalizePath(baseDir + '/' + targetDir + '/' + targetFileName.trim())
setMoving(true)
await apiRequest('v1UsersFilesMoveUpdate', {
id: envid,
source: fullSourcePath,
target: fullTargetPath
}, [], (resp) => {
if (resp.code === 0) {
toast.success(`已移动文件 "${targetFileName.trim()}"`)
onOpenChange(false)
if (onSuccess) {
onSuccess()
}
} else {
toast.error("移动文件失败: " + resp.message);
}
})
setMoving(false)
}
const handleCancel = () => {
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>移动文件</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<Field>
<FieldLabel>源文件路径</FieldLabel>
<Input
value={sourcePath}
readOnly
className="bg-muted"
/>
</Field>
<Field>
<FieldLabel>目标目录</FieldLabel>
<Input
value={targetDir}
onChange={(e) => setTargetDir(e.target.value)}
autoFocus
/>
</Field>
<Field>
<FieldLabel>新文件名称</FieldLabel>
<Input
value={targetFileName}
onChange={(e) => setTargetFileName(e.target.value)}
/>
</Field>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel}>
取消
</Button>
<Button onClick={handleMove} disabled={!sourcePath || !targetDir.trim() || !targetFileName.trim() || moving}>
{moving && <Spinner />}
确认移动
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,130 @@
import { useState, useEffect } from "react"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Field, FieldLabel } from "@/components/ui/field"
import { Spinner } from "@/components/ui/spinner"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { normalizePath } from "@/utils/common"
interface UploadFileDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
targetDir: string
envid: string
baseDir?: string
onSuccess?: () => void
}
export default function UploadFileDialog({
open,
onOpenChange,
targetDir,
envid,
baseDir = '',
onSuccess,
}: UploadFileDialogProps) {
const [fileName, setFileName] = useState('')
const [uploadFile, setUploadFile] = useState<File | null>(null)
const [uploading, setUploading] = useState(false)
useEffect(() => {
if (open) {
setFileName('')
setUploadFile(null)
}
}, [open])
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0] || null
setUploadFile(file)
setFileName(file?.name || '')
}
const handleUpload = async () => {
if (!uploadFile || !envid) {
toast.error('请选择要上传的文件')
return
}
if (!fileName.trim()) {
toast.error('请输入文件名称')
return
}
const filePath = normalizePath(baseDir + '/' + targetDir + '/' + fileName.trim())
setUploading(true)
await apiRequest('v1UsersFilesUploadCreate', {
id: envid,
path: filePath
}, [], (resp) => {
if (resp.code === 0) {
toast.success(`已上传文件 "${fileName.trim()}"`)
onOpenChange(false)
if (onSuccess) {
onSuccess()
}
} else {
toast.error("上传文件失败: " + resp.message);
}
}, undefined, {
file: uploadFile
})
setUploading(false)
}
const handleCancel = () => {
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>上传文件</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<Field>
<FieldLabel>目标目录</FieldLabel>
<Input
value={targetDir || './'}
readOnly
className="bg-muted"
/>
</Field>
<Field>
<FieldLabel>新文件名称</FieldLabel>
<Input
value={fileName}
onChange={(e) => setFileName(e.target.value)}
autoFocus
/>
</Field>
<Field>
<FieldLabel>选择文件</FieldLabel>
<Input
type="file"
onChange={handleFileChange}
/>
</Field>
{uploadFile && (
<p className="mt-2 text-sm text-muted-foreground">
已选择: {uploadFile.name} ({(uploadFile.size / 1024).toFixed(2)} KB)
</p>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel}>
取消
</Button>
<Button onClick={handleUpload} disabled={!uploadFile || !fileName.trim() || uploading}>
{uploading && <Spinner />}
上传
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,199 @@
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Field, FieldContent, FieldLabel } from "@/components/ui/field"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { useState, useEffect } from "react"
import { Api, ConstsGitPlatform, ConstsHostStatus } from "@/api/Api"
import { toast } from "sonner"
import type { DomainGitBot, DomainHost } from "@/api/Api"
import Icon from "@/components/common/Icon"
import { Badge } from "@/components/ui/badge"
import { useCommonData } from "../data-provider"
import { getHostBadges } from "@/utils/common"
interface CreateGitBotDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onSuccess?: (bot: DomainGitBot) => void
}
export function CreateGitBotDialog({ open, onOpenChange, onSuccess }: CreateGitBotDialogProps) {
const [remark, setRemark] = useState("")
const [platform, setPlatform] = useState<ConstsGitPlatform>(ConstsGitPlatform.GitPlatformGitLab)
const [accessToken, setAccessToken] = useState("")
const [selectedHostId, setSelectedHostId] = useState<string>("")
const [loading, setLoading] = useState(false)
const { hosts } = useCommonData()
useEffect(() => {
if (open) {
const defaultHost = hosts.sort((a, _) => {
return a.status === ConstsHostStatus.HostStatusOnline ? -1 : 1
}).filter((host: DomainHost) => (
host.status === ConstsHostStatus.HostStatusOnline
)).find((host: DomainHost) => (
host.is_default === true
)) || hosts[0]
if (defaultHost?.id) {
setSelectedHostId(defaultHost?.id)
} else {
setSelectedHostId("public_host")
}
}
}, [open, hosts])
const handleSubmit = async () => {
if (!accessToken) {
toast.error("请输入 Access Token")
return
}
setLoading(true)
try {
const api = new Api()
const res = await api.api.v1UsersGitBotsCreate({
host_id: selectedHostId,
name: remark || undefined,
token: accessToken,
platform: platform,
})
if (res.data.code === 0) {
toast.success("创建成功")
onOpenChange(false)
setRemark("")
setPlatform(ConstsGitPlatform.GitPlatformGitLab)
setAccessToken("")
setSelectedHostId("")
if (res.data.data && onSuccess) {
onSuccess(res.data.data)
}
} else {
toast.error(res.data.message || "创建失败")
}
} catch {
toast.error("创建失败")
} finally {
setLoading(false)
}
}
const handleCancel = () => {
setRemark("")
setPlatform(ConstsGitPlatform.GitPlatformGitLab)
setAccessToken("")
setSelectedHostId("")
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>创建审查机器人</DialogTitle>
<DialogDescription>
配置一个新的机器人来自动审查你的合并请求
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-4">
<Field>
<FieldLabel>备注</FieldLabel>
<FieldContent>
<Input
placeholder="输入备注"
value={remark}
onChange={(e) => setRemark(e.target.value)}
/>
</FieldContent>
</Field>
<Field>
<FieldLabel>宿主机</FieldLabel>
<FieldContent>
<Select value={selectedHostId} onValueChange={setSelectedHostId}>
<SelectTrigger className="w-full">
<SelectValue placeholder="请选择宿主机" />
</SelectTrigger>
<SelectContent>
<SelectItem value={"public_host"}>
<div className="flex items-center gap-2">
<span>MonkeyCode</span>
<Badge variant="outline">平台内置</Badge>
</div>
</SelectItem>
{hosts.map((host) => {
return (
<SelectItem key={host.id} value={host.id!} disabled={host.status !== ConstsHostStatus.HostStatusOnline}>
<div className="flex items-center gap-2">
<span>{host.remark || `${host.name}-${host.external_ip}`}</span>
{getHostBadges(host)}
</div>
</SelectItem>
)
})}
</SelectContent>
</Select>
</FieldContent>
</Field>
<Field>
<FieldLabel>Git 平台类型</FieldLabel>
<FieldContent>
<Select value={platform} onValueChange={(value) => setPlatform(value as ConstsGitPlatform)}>
<SelectTrigger className="w-full">
<SelectValue placeholder="请选择" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ConstsGitPlatform.GitPlatformGitLab}>
<Icon name="GitLab" />GitLab
</SelectItem>
<SelectItem value={ConstsGitPlatform.GitPlatformGithub}>
<Icon name="GitHub-Uncolor" />GitHub
</SelectItem>
<SelectItem value={ConstsGitPlatform.GitPlatformGitee}>
<Icon name="Gitee" />Gitee
</SelectItem>
<SelectItem value={ConstsGitPlatform.GitPlatformGitea}>
<Icon name="Gitea" />Gitea
</SelectItem>
</SelectContent>
</Select>
</FieldContent>
</Field>
<Field>
<FieldLabel>Access Token</FieldLabel>
<FieldContent>
<Input
type="password"
placeholder="请输入 Access Token"
value={accessToken}
onChange={(e) => setAccessToken(e.target.value)}
/>
</FieldContent>
</Field>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel} disabled={loading}>
取消
</Button>
<Button onClick={handleSubmit} disabled={loading}>
{loading ? "创建中..." : "创建"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,181 @@
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Field, FieldContent, FieldLabel } from "@/components/ui/field"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { useState, useEffect } from "react"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import type { DomainGitBot } from "@/api/Api"
import { ConstsGitPlatform, ConstsHostStatus } from "@/api/Api"
import Icon from "@/components/common/Icon"
import { Badge } from "@/components/ui/badge"
import { useCommonData } from "../data-provider"
import { getHostBadges } from "@/utils/common"
interface EditGitBotDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
bot: DomainGitBot | null
onSuccess: () => void
}
export function EditGitBotDialog({ open, onOpenChange, bot, onSuccess }: EditGitBotDialogProps) {
const [name, setName] = useState("")
const [token, setToken] = useState("")
const [selectedHostId, setSelectedHostId] = useState<string>("")
const [platform, setPlatform] = useState<ConstsGitPlatform>(ConstsGitPlatform.GitPlatformGitLab)
const [loading, setLoading] = useState(false)
const { hosts } = useCommonData()
useEffect(() => {
if (open && bot) {
setName(bot.name || "")
setToken(bot.token || "")
setPlatform(bot.platform || ConstsGitPlatform.GitPlatformGitLab)
// 设置宿主机
if (bot.host?.id) {
setSelectedHostId(bot.host.id)
} else {
setSelectedHostId("public_host")
}
}
}, [open, bot])
const handleSubmit = async () => {
if (!bot?.id) {
toast.error("机器人信息不完整")
return
}
setLoading(true)
await apiRequest('v1UsersGitBotsUpdate', {
id: bot.id,
host_id: selectedHostId,
platform: platform,
name: name || undefined,
token: token || undefined,
}, [], (resp) => {
if (resp.code === 0) {
toast.success("更新成功")
onOpenChange(false)
onSuccess()
} else {
toast.error("更新失败: " + resp.message)
}
})
setLoading(false)
}
const handleCancel = () => {
setName("")
setToken("")
setSelectedHostId("")
setPlatform(ConstsGitPlatform.GitPlatformGitLab)
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>修改审查机器人</DialogTitle>
</DialogHeader>
<Field>
<FieldLabel>备注名称</FieldLabel>
<FieldContent>
<Input
placeholder="输入备注名称"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</FieldContent>
</Field>
<Field>
<FieldLabel>宿主机</FieldLabel>
<FieldContent>
<Select value={selectedHostId} onValueChange={setSelectedHostId}>
<SelectTrigger className="w-full">
<SelectValue placeholder="请选择宿主机" />
</SelectTrigger>
<SelectContent>
<SelectItem value={"public_host"}>
<div className="flex items-center gap-2">
<span>MonkeyCode</span>
<Badge variant="outline">平台内置</Badge>
</div>
</SelectItem>
{hosts.map((host) => {
return (
<SelectItem key={host.id} value={host.id!} disabled={host.status !== ConstsHostStatus.HostStatusOnline}>
<div className="flex items-center gap-2">
<span>{host.remark || `${host.name}-${host.external_ip}`}</span>
{getHostBadges(host)}
</div>
</SelectItem>
)
})}
</SelectContent>
</Select>
</FieldContent>
</Field>
<Field>
<FieldLabel>Git 平台类型</FieldLabel>
<FieldContent>
<Select value={platform} onValueChange={(value) => setPlatform(value as ConstsGitPlatform)}>
<SelectTrigger className="w-full">
<SelectValue placeholder="请选择" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ConstsGitPlatform.GitPlatformGitLab}>
<Icon name="GitLab" />GitLab
</SelectItem>
<SelectItem value={ConstsGitPlatform.GitPlatformGithub}>
<Icon name="GitHub-Uncolor" />GitHub
</SelectItem>
<SelectItem value={ConstsGitPlatform.GitPlatformGitee}>
<Icon name="Gitee" />Gitee
</SelectItem>
<SelectItem value={ConstsGitPlatform.GitPlatformGitea}>
<Icon name="Gitea" />Gitea
</SelectItem>
</SelectContent>
</Select>
</FieldContent>
</Field>
<Field>
<FieldLabel>Access Token</FieldLabel>
<FieldContent>
<Input
type="password"
placeholder="留空则不修改"
value={token}
onChange={(e) => setToken(e.target.value)}
/>
</FieldContent>
</Field>
<DialogFooter>
<Button variant="outline" onClick={handleCancel} disabled={loading}>
取消
</Button>
<Button onClick={handleSubmit} disabled={loading}>
{loading ? "保存中..." : "保存"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,176 @@
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"
import { Checkbox } from "@/components/ui/checkbox"
import type { DomainGitBot } from "@/api/Api"
import { useEffect, useState, useRef } from "react"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { IconLoader } from "@tabler/icons-react"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
import { useCommonData } from "../data-provider"
interface EditGitBotPermissionDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
bot?: DomainGitBot | null
onSuccess?: () => void
}
export default function EditGitBotPermissionDialog({
open,
onOpenChange,
bot,
onSuccess,
}: EditGitBotPermissionDialogProps) {
const [selectedUserIds, setSelectedUserIds] = useState<string[]>([])
const [loading, setLoading] = useState(false)
const [selectOpen, setSelectOpen] = useState(false)
const selectRef = useRef<HTMLDivElement>(null)
const { members } = useCommonData()
useEffect(() => {
if (open && bot) {
// 加载已有的用户权限
const existingIds = (bot.users || [])
.map(u => u.id)
.filter(Boolean) as string[]
setSelectedUserIds(existingIds)
} else if (!open) {
setSelectedUserIds([])
setSelectOpen(false)
}
}, [open, bot])
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (selectRef.current && !selectRef.current.contains(event.target as Node)) {
setSelectOpen(false)
}
}
if (selectOpen) {
document.addEventListener("mousedown", handleClickOutside)
}
return () => {
document.removeEventListener("mousedown", handleClickOutside)
}
}, [selectOpen])
const handleUserCheckboxChange = (userId: string, checked: boolean) => {
if (checked) {
setSelectedUserIds([...selectedUserIds, userId])
} else {
setSelectedUserIds(selectedUserIds.filter(id => id !== userId))
}
}
const handleSave = async () => {
if (!bot?.id) {
toast.error("机器人信息不完整")
return
}
setLoading(true)
await apiRequest('v1UsersGitBotsShareCreate', {
id: bot.id,
user_ids: selectedUserIds
}, [], (resp) => {
if (resp.code === 0) {
toast.success("权限修改成功")
onOpenChange(false)
onSuccess?.()
} else {
toast.error("修改权限失败: " + resp.message)
}
})
setLoading(false)
}
const handleCancel = () => {
setSelectedUserIds([])
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>修改查看权限</DialogTitle>
<DialogDescription>
以下成员可以看到 "{bot?.name || '机器人'}" 执行过的任务
</DialogDescription>
</DialogHeader>
<div className="relative" ref={selectRef}>
<Button
type="button"
variant="outline"
role="combobox"
aria-expanded={selectOpen}
className="w-full justify-between"
onClick={() => setSelectOpen(!selectOpen)}
disabled={loading}
>
<span className="truncate">
{selectedUserIds.length === 0
? "请选择成员"
: selectedUserIds.length === 1
? members.find((m) => m.id === selectedUserIds[0])?.name ||
members.find((m) => m.id === selectedUserIds[0])?.email ||
"已选择 1 名成员"
: `已选择 ${selectedUserIds.length} 名成员`}
</span>
<ChevronDown className={cn("ml-2 h-4 w-4 shrink-0 opacity-50 transition-transform", selectOpen && "rotate-180")} />
</Button>
{selectOpen && (
<div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-md">
<div className="max-h-[200px] overflow-auto p-1">
{members.length === 0 ? (
<div className="py-6 text-center text-sm text-muted-foreground">
暂无可选的成员
</div>
) : (
members.map((member) => {
const isChecked = selectedUserIds.includes(member.id || "")
return (
<div
key={member.id}
className="flex items-center gap-2 rounded-sm px-2 py-1.5 hover:bg-accent cursor-pointer"
onClick={() => handleUserCheckboxChange(member.id || "", !isChecked)}
>
<Checkbox
checked={isChecked}
onCheckedChange={(checked) => handleUserCheckboxChange(member.id || "", checked as boolean)}
onClick={(e) => e.stopPropagation()}
/>
<img
src={member.avatar_url || "/logo-colored.png"}
alt={member.name || ''}
className="w-5 h-5 rounded-full object-cover"
/>
<span className="text-sm truncate">{member.name || member.email}</span>
</div>
)
})
)}
</div>
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel} disabled={loading}>
取消
</Button>
<Button onClick={handleSave} disabled={loading}>
{loading && <IconLoader className="size-4 animate-spin" />}
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,273 @@
import { Item, ItemActions, ItemContent, ItemGroup, ItemTitle } from "@/components/ui/item"
import { useState, useEffect, forwardRef, useImperativeHandle } from "react"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import type { DomainGitBot } from "@/api/Api"
import { Button } from "@/components/ui/button"
import { IconCopy, IconFolder, IconLoader, IconLink, IconPencil, IconTrash } from "@tabler/icons-react"
import { MoreVertical } from "lucide-react"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from "@/components/ui/empty"
import { EditGitBotDialog } from "./edit-git-bot-dialog"
import EditGitBotPermissionDialog from "./edit-git-bot-permission-dialog"
import { Avatar } from "@/components/ui/avatar"
import { AvatarFallback } from "@/components/ui/avatar"
import { getGitPlatformIcon } from "@/utils/common"
import { IconLock } from "@tabler/icons-react"
import { Label } from "@/components/ui/label"
export interface GitBotConfigRef {
fetchGitBots: () => void
showWebhook: (bot: DomainGitBot) => void
}
export const GitBotConfig = forwardRef<GitBotConfigRef>(function GitBotConfig(_, ref) {
const [gitBots, setGitBots] = useState<DomainGitBot[]>([])
const [loading, setLoading] = useState(false)
const [editDialogOpen, setEditDialogOpen] = useState(false)
const [editingBot, setEditingBot] = useState<DomainGitBot | null>(null)
const [webhookDialogOpen, setWebhookDialogOpen] = useState(false)
const [webhookBot, setWebhookBot] = useState<DomainGitBot | null>(null)
const [permissionDialogOpen, setPermissionDialogOpen] = useState(false)
const [permissionBot, setPermissionBot] = useState<DomainGitBot | null>(null)
useImperativeHandle(ref, () => ({
fetchGitBots,
showWebhook: (bot: DomainGitBot) => {
setWebhookBot(bot)
setWebhookDialogOpen(true)
}
}))
const fetchGitBots = async () => {
setLoading(true)
await apiRequest('v1UsersGitBotsList', {}, [], (resp) => {
if (resp.code === 0) {
setGitBots(resp.data?.bots || [])
} else {
toast.error("获取机器人列表失败: " + resp.message)
}
})
setLoading(false)
}
useEffect(() => {
fetchGitBots()
}, [])
const handleEdit = (bot: DomainGitBot) => {
setEditingBot(bot)
setEditDialogOpen(true)
}
const handleViewWebhook = (bot: DomainGitBot) => {
setWebhookBot(bot)
setWebhookDialogOpen(true)
}
const handleEditPermission = (bot: DomainGitBot) => {
setPermissionBot(bot)
setPermissionDialogOpen(true)
}
const handleCopyWebhook = () => {
if (webhookBot?.webhook_url) {
navigator.clipboard.writeText(webhookBot.webhook_url)
toast.success("WebHook 地址已复制到剪贴板")
}
}
const handleCopySecretToken = () => {
if (webhookBot?.secret_token) {
navigator.clipboard.writeText(webhookBot.secret_token)
toast.success("Secret Token 已复制到剪贴板")
}
}
const handleDelete = (bot: DomainGitBot) => {
if (!bot.id) {
toast.error("机器人信息不完整")
return
}
apiRequest('v1UsersGitBotsDelete', {}, [bot.id], (resp) => {
if (resp.code === 0) {
toast.success("机器人删除成功")
fetchGitBots()
} else {
toast.error("删除机器人失败: " + resp.message)
}
})
}
if (loading) {
return (
<div className="flex w-full h-full">
<Empty className="border border-dashed">
<EmptyHeader>
<EmptyMedia variant="icon">
<IconLoader className="animate-spin" />
</EmptyMedia>
<EmptyDescription>正在加载...</EmptyDescription>
</EmptyHeader>
</Empty>
</div>
)
}
if (gitBots.length === 0) {
return (
<div className="flex w-full h-full">
<Empty className="border border-dashed">
<EmptyHeader>
<EmptyMedia variant="icon">
<IconFolder />
</EmptyMedia>
<EmptyDescription>暂无机器人配置</EmptyDescription>
</EmptyHeader>
</Empty>
</div>
)
}
return (
<>
<ItemGroup className="flex flex-col gap-4">
{gitBots.map((bot, index) => (
<Item key={index} variant="outline" className="hover:border-primary/50" size="sm">
<ItemContent>
<ItemTitle className="flex flex-row gap-2 items-center">
<Avatar>
<AvatarFallback>
{getGitPlatformIcon(bot.platform)}
</AvatarFallback>
</Avatar>
{bot.name}
</ItemTitle>
</ItemContent>
<ItemActions>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm">
<MoreVertical className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleViewWebhook(bot)}>
<IconLink />
WebHook
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleEditPermission(bot)}>
<IconLock />
权限
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleEdit(bot)}>
<IconPencil />
修改
</DropdownMenuItem>
<AlertDialog>
<AlertDialogTrigger asChild>
<DropdownMenuItem
className="text-destructive"
onSelect={(e) => { e.preventDefault() }}
>
<IconTrash />
删除
</DropdownMenuItem>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确认删除</AlertDialogTitle>
<AlertDialogDescription>
确定要删除机器人 "{bot.name || '未知'}" 吗?此操作不可撤销。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction onClick={() => handleDelete(bot)}>
确认删除
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</DropdownMenuContent>
</DropdownMenu>
</ItemActions>
</Item>
))}
</ItemGroup>
<EditGitBotDialog
open={editDialogOpen}
onOpenChange={setEditDialogOpen}
bot={editingBot}
onSuccess={fetchGitBots}
/>
<EditGitBotPermissionDialog
open={permissionDialogOpen}
onOpenChange={setPermissionDialogOpen}
bot={permissionBot}
onSuccess={fetchGitBots}
/>
<Dialog open={webhookDialogOpen} onOpenChange={setWebhookDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>WebHook 信息</DialogTitle>
<DialogDescription>
将 webhook 地址和 secret token 配置到 {webhookBot?.platform?.toLowerCase()} 中
</DialogDescription>
</DialogHeader>
<Label>WebHook 地址</Label>
<div className="flex gap-2">
<Input
value={webhookBot?.webhook_url || ''}
readOnly
className="flex-1"
/>
<Button variant="outline" size="icon" onClick={handleCopyWebhook}>
<IconCopy className="size-4" />
</Button>
</div>
<Label>Secret Token</Label>
<div className="flex gap-2">
<Input
value={webhookBot?.secret_token || ''}
readOnly
className="flex-1"
/>
<Button variant="outline" size="icon" onClick={handleCopySecretToken}>
<IconCopy className="size-4" />
</Button>
</div>
</DialogContent>
</Dialog>
</>
)
})
@@ -0,0 +1,181 @@
import type { DomainGitBotTask } from "@/api/Api"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia } from "@/components/ui/empty"
import { Item, ItemContent, ItemDescription, ItemFooter, ItemTitle } from "@/components/ui/item"
import { Spinner } from "@/components/ui/spinner"
import { getGitPlatformIcon } from "@/utils/common"
import { apiRequest } from "@/utils/requestUtils"
import { IconAlertTriangle, IconCircleCheck, IconFolder, IconLoader, IconReload } from "@tabler/icons-react"
import dayjs from "dayjs"
import { BookOpenIcon } from "lucide-react"
import React, { forwardRef, useCallback, useImperativeHandle, useEffect, useRef, useState } from "react"
import { toast } from "sonner"
const PAGE_SIZE = 24;
export interface GitBotTasksRef {
fetchTasks: () => Promise<void>
}
export const GitBotTasks = forwardRef<GitBotTasksRef>(function GitBotTasks(_, ref) {
const [tasks, setTasks] = useState<DomainGitBotTask[]>([])
const [page, setPage] = useState(1)
const [hasMore, setHasMore] = useState(true)
const [loading, setLoading] = useState(false)
const [initialLoading, setInitialLoading] = useState(true)
const loadMoreRef = useRef<HTMLDivElement>(null)
const loadingRef = useRef(false)
const fetchTasksImpl = useCallback((pageNum: number, append: boolean) => {
if (loadingRef.current) return
loadingRef.current = true
setLoading(true)
const resetLoading = () => {
loadingRef.current = false
setLoading(false)
}
apiRequest("v1UsersGitBotsTasksList", { page: pageNum, size: PAGE_SIZE }, [], (resp) => {
if (resp.code === 0) {
const newTasks = resp.data?.tasks || []
setTasks(prev => append ? [...prev, ...newTasks] : newTasks)
setHasMore(newTasks.length >= PAGE_SIZE)
setPage(pageNum)
} else {
toast.error("获取任务列表失败: " + resp.message)
}
resetLoading()
setInitialLoading(false)
}, () => {
resetLoading()
setInitialLoading(false)
})
}, [])
const fetchTasks = useCallback(() => {
setPage(1)
setHasMore(true)
fetchTasksImpl(1, false)
}, [fetchTasksImpl])
const loadMore = useCallback(() => {
if (!loading && hasMore) {
fetchTasksImpl(page + 1, true)
}
}, [loading, hasMore, page, fetchTasksImpl])
useImperativeHandle(ref, () => ({
fetchTasks
}))
useEffect(() => {
fetchTasksImpl(1, false)
}, [])
useEffect(() => {
const el = loadMoreRef.current
if (!el) return
const observer = new IntersectionObserver(
(entries) => {
if (entries[0]?.isIntersecting && hasMore && !loading) {
loadMore()
}
},
{ rootMargin: "200px" }
)
observer.observe(el)
return () => observer.disconnect()
}, [hasMore, loading, loadMore])
if (initialLoading && tasks.length === 0) {
return (
<div className="flex w-full h-full">
<Empty className="border border-dashed">
<EmptyHeader>
<EmptyMedia variant="icon">
<IconLoader className="animate-spin" />
</EmptyMedia>
<EmptyDescription>正在加载...</EmptyDescription>
</EmptyHeader>
</Empty>
</div>
)
}
if (tasks.length === 0) {
return (
<div className="flex w-full h-full">
<Empty className="border border-dashed">
<EmptyHeader>
<EmptyMedia variant="icon">
<IconFolder />
</EmptyMedia>
<EmptyDescription>暂无任务</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<div className="flex gap-2">
<Button variant="outline" onClick={fetchTasks}>
<IconReload />
刷新
</Button>
<Button variant="default" asChild>
<a href="https://monkeycode.docs.baizhi.cloud/node/019bd94c-2fd8-7276-9382-74e3a0d4a397" target="_blank">
<BookOpenIcon />
如何使用?
</a>
</Button>
</div>
</EmptyContent>
</Empty>
</div>
)
}
return (
<div className="flex flex-col gap-4">
<div className="grid grid-cols-[repeat(auto-fill,minmax(350px,1fr))] gap-4 w-full">
{tasks.map((task, index) => {
return (
<Item variant={"outline"} key={task.id || index} className="group hover:border-primary/50">
<ItemContent>
<ItemTitle
className="font-normal whitespace-normal line-clamp-1 break-all hover:underline group-hover:text-primary cursor-pointer"
onClick={() => {
window.open(task.pull_request?.url || "", "_blank")
}}
>
{task.pull_request?.title}
</ItemTitle>
<ItemDescription className="whitespace-normal line-clamp-1 break-all">
{task.repo?.repo_name}
</ItemDescription>
</ItemContent>
<ItemFooter className="flex flex-row gap-2 justify-between border-t pt-3 text-xs text-muted-foreground">
<div className="flex flex-row gap-2">
<Badge variant="outline">
{task.status === "finished" && <><IconCircleCheck />任务完成</>}
{task.status === "error" && <><IconAlertTriangle />执行失败</>}
{task.status === "pending" && <><Spinner />等待执行</>}
{task.status === "processing" && <><Spinner />正在执行</>}
</Badge>
<Badge variant="outline">
{getGitPlatformIcon(task.bot?.platform)}
{task.bot?.name}
</Badge>
</div>
{dayjs.unix(task.created_at || 0).fromNow()}
</ItemFooter>
</Item>
)
})}
</div>
<div ref={loadMoreRef} className="flex justify-center py-8">
{loading && <Spinner className="size-6" />}
</div>
</div>
)
})
@@ -0,0 +1,221 @@
import { SidebarMenu, SidebarMenuItem, SidebarMenuButton } from "@/components/ui/sidebar";
import { Dialog } from "@radix-ui/react-dialog";
import { DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { DialogContent } from "@/components/ui/dialog";
import { IconInfoCircle, IconWallet } from "@tabler/icons-react";
import { useEffect, useState, useRef, useCallback } from "react";
import { apiRequest } from "@/utils/requestUtils";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { toast } from "sonner";
import { Spinner } from "@/components/ui/spinner";
import { Label } from "@/components/ui/label";
import type { DomainTransactionLog } from "@/api/Api";
import { Item, ItemContent, ItemGroup, ItemTitle } from "@/components/ui/item";
import dayjs from "dayjs";
import { cn } from "@/lib/utils";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useCommonData } from "../data-provider";
export default function NavBalance() {
const [transcations, setTranscations] = useState<DomainTransactionLog[]>([]);
const [exchangeCode, setExchangeCode] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [page, setPage] = useState<number>(1);
const [hasNextPage, setHasNextPage] = useState(false);
const [isLoadingMore, setIsLoadingMore] = useState(false);
const loadMoreRef = useRef<HTMLDivElement>(null);
const { balance, bonus, reloadWallet, user } = useCommonData();
const fetchTranscations = async () => {
setIsLoadingMore(true);
await apiRequest('v1UsersWalletTransactionList', {
size: 10,
page: page
}, [], (resp) => {
if (resp.code === 0) {
const newTransactions = resp.data?.transactions || [];
setTranscations(prev => [...prev, ...newTransactions]);
setHasNextPage(resp.data?.page?.has_next_page || false);
setPage(page + 1);
} else {
toast.error(resp.message || "获取交易记录失败");
}
});
setIsLoadingMore(false);
}
const loadMore = useCallback(() => {
if (hasNextPage && !isLoadingMore) {
fetchTranscations();
}
}, [hasNextPage, isLoadingMore]);
const handleExchange = async () => {
if (!exchangeCode.trim()) {
toast.error("请输入兑换码");
return;
}
setIsLoading(true);
await apiRequest('v1UsersWalletExchangeCreate', { code: exchangeCode.trim() }, [], (resp) => {
if (resp.code === 0) {
toast.success("兑换成功");
setExchangeCode("");
reloadWallet();
} else {
toast.error(resp.message || "兑换失败");
}
})
setIsLoading(false);
}
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) {
loadMore();
}
},
{ threshold: 0.1 }
);
const currentRef = loadMoreRef.current;
if (currentRef) {
observer.observe(currentRef);
}
return () => {
if (currentRef) {
observer.unobserve(currentRef);
}
};
}, [loadMore]);
const handleOpenChange = (open: boolean) => {
if (open) {
setTranscations([]);
setHasNextPage(false);
fetchTranscations();
} else {
setPage(1)
}
};
const handleCopyInvitationLink = () => {
const invitationLink = `https://monkeycode-ai.com/?ic=${user.id}`;
navigator.clipboard.writeText(invitationLink);
toast.success("邀请链接已复制到剪贴板");
}
return (
<Dialog onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton className="cursor-pointer">
<IconWallet className="size-5" />
余额: {Math.ceil(balance + bonus).toLocaleString()} 点
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>点数余额</DialogTitle>
<DialogDescription>
点数用来兑换计算资源,详情见
<a className="text-primary hover:underline mx-1"
href="https://monkeycode.docs.baizhi.cloud/node/019b2134-e832-7425-a916-137fe8bb4c8c"
target="_blank">
说明
</a>
</DialogDescription>
</DialogHeader>
<div className="flex gap-2 border rounded-md p-4">
<div className="flex flex-1 flex-row gap-2">
<div className="text-3xl content-end text-primary">
{Math.ceil(balance + bonus).toLocaleString()}
</div>
<div className="content-end text-muted-foreground">点</div>
</div>
<Separator orientation="vertical" className="mx-4" />
<div className="flex flex-1 flex-col gap-2">
<Label className="text-muted-foreground">充值余额: {Math.ceil(balance).toLocaleString()} 点</Label>
<Label className="text-muted-foreground">赠送余额: {Math.ceil(bonus).toLocaleString()} 点</Label>
</div>
</div>
<Label>兑换点数</Label>
<div className="flex gap-2">
<Input
placeholder="请输入兑换码"
value={exchangeCode}
onChange={(e) => setExchangeCode(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleExchange()}
/>
<Button
variant="outline"
onClick={handleExchange}
disabled={isLoading}
>
{isLoading && <Spinner />}
兑换
</Button>
</div>
<div className="flex flex-row items-center -mb-3">
<Label className="">邀请注册</Label>
<Button variant="link" size="sm" className="cursor-pointer" onClick={() => {
window.open(`https://monkeycode.docs.baizhi.cloud/node/019b2134-e832-7425-a916-137fe8bb4c8c`, '_blank')
}}>
活动说明
</Button>
</div>
<div className="flex flex-row justify-between gap-2 mb-2">
<Input value="邀请好友注册并激活,可获得 2000 点数" readOnly />
<Button variant="outline" onClick={handleCopyInvitationLink}>复制邀请链接</Button>
</div>
<Label className="">交易记录</Label>
<ItemGroup className="flex flex-col gap-2 overflow-y-auto max-h-[300px] -mx-2 px-2">
{transcations.map((transaction) => (
<Item key={Math.random().toString()} variant="outline" size="sm">
<ItemContent>
<ItemTitle className="flex flex-row w-full">
<div className={cn("flex flex-1 flex-row items-center", (transaction.kind === "signup_bonus" || transaction.kind === "voucher_exchange" || transaction.kind === "invitation_reward") ? "text-primary" : "")}>
{(transaction.kind === "signup_bonus" || transaction.kind === "voucher_exchange" || transaction.kind === "invitation_reward") ? "+" : "-"}
{Math.ceil((transaction.amount || 0) / 1000).toLocaleString()}
</div>
<Tooltip>
<TooltipTrigger asChild>
<div className="flex flex-row items-center gap-1 text-muted-foreground text-xs font-normal cursor-pointer">
{transaction.kind === "signup_bonus" && "新用户注册赠送"}
{transaction.kind === "voucher_exchange" && "通过兑换码领取"}
{transaction.kind === "invitation_reward" && "邀请注册奖励"}
{transaction.kind === "vm_consumption" && "开发环境消耗"}
{transaction.kind === "model_consumption" && "大模型消耗"}
<IconInfoCircle className="size-3" />
</div>
</TooltipTrigger>
<TooltipContent>
{transaction.remark}
</TooltipContent>
</Tooltip>
<div className="text-muted-foreground text-xs ml-4">
{dayjs((transaction.created_at || 0) * 1000).format("YYYY-MM-DD HH:mm:ss")}
</div>
</ItemTitle>
</ItemContent>
</Item>
))}
{hasNextPage && (
<div ref={loadMoreRef} className="flex justify-center py-2">
{isLoadingMore && <Spinner className="size-4" />}
</div>
)}
</ItemGroup>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,45 @@
import {
Bot,
Github,
} from "lucide-react"
import { Link, useLocation } from "react-router-dom"
import {
SidebarGroup,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar"
export default function NavMain() {
const location = useLocation()
return (
<SidebarGroup>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
isActive={location.pathname === "/console/tasks"}
asChild
>
<Link to="/console/tasks">
<Bot />
<span>智能任务</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton
isActive={location.pathname === "/console/gitbot"}
asChild
>
<Link to="/console/gitbot">
<Github />
<span>代码审查</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroup>
)
}
@@ -0,0 +1,100 @@
import { Link, useLocation } from "react-router-dom"
import { useState } from "react"
import {
SidebarGroup,
SidebarGroupLabel,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
} from "@/components/ui/sidebar"
import { useCommonData } from "../data-provider"
import { IconBook, IconCalendarCode, IconFolderCode, IconPlus, IconReload, IconSubtask } from "@tabler/icons-react"
import { FolderOpenDot } from "lucide-react"
import { Button } from "@/components/ui/button"
import AddProjectDialog from "../project/add-project"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
export default function NavProject() {
const location = useLocation()
const [addDialogOpen, setAddDialogOpen] = useState(false)
const { projects, loadingProjects, reloadProjects } = useCommonData()
return (
<SidebarGroup>
<SidebarGroupLabel className="flex items-center justify-between pr-0">
<Label>开发项目</Label>
<div className="flex items-center gap-0.5">
<Button
variant="ghost"
size="icon"
className="size-5"
onClick={reloadProjects}
disabled={loadingProjects}
>
<IconReload className={`size-3.5 ${loadingProjects ? 'animate-spin' : ''}`} />
</Button>
<Button
variant="ghost"
size="icon"
className="size-5"
onClick={() => setAddDialogOpen(true)}
>
<IconPlus className="size-3.5" />
</Button>
</div>
</SidebarGroupLabel>
<AddProjectDialog
open={addDialogOpen}
onOpenChange={setAddDialogOpen}
onSuccess={reloadProjects}
/>
<SidebarMenu>
{projects.length > 0 ? projects.map((project) => (
<SidebarMenuItem key={project.id}>
<SidebarMenuButton asChild>
<Link to={`/console/project/${project.id}/docs/`}>
{location.pathname.startsWith(`/console/project/${project.id}/`) ? <FolderOpenDot /> : <IconFolderCode />}
<span>{project.name}</span>
</Link>
</SidebarMenuButton>
{location.pathname.startsWith(`/console/project/${project.id}/`) && <SidebarMenuSub>
<SidebarMenuSubItem className="flex flex-col gap-1">
<SidebarMenuSubButton isActive={location.pathname.startsWith(`/console/project/${project.id}/docs/`)} asChild>
<Link to={`/console/project/${project.id}/docs/`}>
<IconBook />
项目
</Link>
</SidebarMenuSubButton>
<SidebarMenuSubButton isActive={location.pathname === `/console/project/${project.id}/issues`} asChild>
<Link to={`/console/project/${project.id}/issues`}>
<IconCalendarCode />
需求
<Badge variant="outline">{project.open_issue_count || 0}</Badge>
</Link>
</SidebarMenuSubButton>
<SidebarMenuSubButton isActive={location.pathname === `/console/project/${project.id}/tasks`} asChild>
<Link to={`/console/project/${project.id}/tasks`}>
<IconSubtask />
任务
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
</SidebarMenuSub>}
</SidebarMenuItem>
)) : (
<SidebarMenuItem>
<SidebarMenuButton disabled>
暂无项目
</SidebarMenuButton>
</SidebarMenuItem>
)}
</SidebarMenu>
</SidebarGroup>
)
}
@@ -0,0 +1,425 @@
import {
ChevronsUpDown
} from "lucide-react"
import {
Avatar,
AvatarFallback,
AvatarImage,
} from "@/components/ui/avatar"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import React from "react"
import { apiRequest } from "@/utils/requestUtils"
import { useNavigate } from "react-router-dom"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Spinner } from "@/components/ui/spinner"
import { Button } from "@/components/ui/button"
import { toast } from "sonner"
import { IconLockCode, IconLogout, IconUserHexagon, IconUpload } from "@tabler/icons-react"
import { useCommonData } from "@/components/console/data-provider"
export default function NavUser() {
const { isMobile } = useSidebar()
const [showLogoutDialog, setShowLogoutDialog] = React.useState(false);
const [showChangePasswordDialog, setShowChangePasswordDialog] = React.useState(false);
const [currentPassword, setCurrentPassword] = React.useState<string>('');
const [newPassword, setNewPassword] = React.useState<string>('');
const [confirmPassword, setConfirmPassword] = React.useState<string>('');
const [changingPassword, setChangingPassword] = React.useState<boolean>(false);
const [showChangeNameDialog, setShowChangeNameDialog] = React.useState(false);
const [newName, setNewName] = React.useState<string>('');
const [changingName, setChangingName] = React.useState<boolean>(false);
const [showChangeAvatarDialog, setShowChangeAvatarDialog] = React.useState(false);
const [avatarFile, setAvatarFile] = React.useState<File | null>(null);
const [avatarPreview, setAvatarPreview] = React.useState<string>('');
const [changingAvatar, setChangingAvatar] = React.useState<boolean>(false);
const navigate = useNavigate()
const { user, reloadUser } = useCommonData()
const handleLogout = () => {
apiRequest('v1UsersLogoutCreate', {}, [], (resp) => {
if (resp.code === 0) {
navigate('/');
} else {
toast.error('登出失败: ' + resp.message);
}
});
};
const handleChangePassword = async () => {
// 验证新密码和确认密码是否一致
if (newPassword !== confirmPassword) {
toast.error('新密码和确认密码不一致');
return;
}
// 验证密码长度
if (newPassword.length < 6) {
toast.error('新密码长度至少为6位');
return;
}
setChangingPassword(true);
await apiRequest('v1UsersPasswordsChangeUpdate', {
current_password: currentPassword,
new_password: newPassword,
confirm_password: confirmPassword,
}, [], (resp) => {
if (resp?.code === 0) {
toast.success('密码修改成功');
setShowChangePasswordDialog(false);
setCurrentPassword('');
setNewPassword('');
setConfirmPassword('');
} else {
toast.error(`密码修改失败:${resp?.message || '未知错误'}`);
}
})
setChangingPassword(false);
};
const handleChangeName = async () => {
// 验证昵称不能为空
if (!newName.trim()) {
toast.error('昵称不能为空');
return;
}
setChangingName(true);
await apiRequest('v1UsersUpdate', { name: newName.trim() }, [], (resp) => {
if (resp?.code === 0) {
toast.success('昵称修改成功');
reloadUser?.();
setShowChangeNameDialog(false);
setNewName('');
} else {
toast.error(`昵称修改失败:${resp?.message || '未知错误'}`);
}
})
setChangingName(false);
};
const handleAvatarFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0] || null;
if (file) {
// 验证文件类型
if (!file.type.startsWith('image/')) {
toast.error('请选择图片文件');
return;
}
// 验证文件大小(例如限制为 5MB)
if (file.size > 5 * 1024 * 1024) {
toast.error('图片大小不能超过 5MB');
return;
}
setAvatarFile(file);
// 创建预览
const reader = new FileReader();
reader.onloadend = () => {
setAvatarPreview(reader.result as string);
};
reader.readAsDataURL(file);
}
};
const handleChangeAvatar = async () => {
if (!avatarFile) {
toast.error('请选择头像文件');
return;
}
setChangingAvatar(true);
// 第一步:上传文件到 OSS
await apiRequest('v1UploaderCreate', { usage: 'avatar', file: avatarFile }, [], async (uploadResp) => {
if (uploadResp?.code === 0 && uploadResp?.data) {
// 第二步:更新用户头像地址
await apiRequest('v1UsersUpdate', { avatar_url: uploadResp.data }, [], (updateResp) => {
if (updateResp?.code === 0) {
toast.success('头像修改成功');
setShowChangeAvatarDialog(false);
setAvatarFile(null);
setAvatarPreview('');
// 重新加载用户信息以获取最新的头像URL
reloadUser?.();
} else {
toast.error(`头像修改失败:${updateResp?.message || '未知错误'}`);
}
});
} else {
toast.error(`头像上传失败:${uploadResp?.message || '未知错误'}`);
}
});
setChangingAvatar(false);
};
return (
<>
<SidebarMenu>
<SidebarMenuItem>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuButton
size="lg"
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
>
<Avatar className="h-8 w-8 rounded-lg">
<AvatarImage src={user?.avatar_url || "/logo-colored.png"} alt={user?.name || '未知用户'} />
<AvatarFallback className="rounded-lg">{user?.name?.charAt(0) || '-'}</AvatarFallback>
</Avatar>
<div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-medium">{user?.name || '未知用户'}{user?.team ? ` - ${user?.team?.name}` : ''}</span>
<span className="truncate text-xs">{user?.email || '-'}</span>
</div>
<ChevronsUpDown className="ml-auto size-4" />
</SidebarMenuButton>
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
side={isMobile ? "bottom" : "right"}
align="end"
sideOffset={4}
>
<DropdownMenuLabel className="p-0 font-normal">
<div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
<Avatar
className="h-8 w-8 rounded-lg cursor-pointer hover:opacity-50 transition-opacity"
onClick={() => setShowChangeAvatarDialog(true)}
>
<AvatarImage src={user?.avatar_url || "/logo-colored.png"} alt={user?.name || '未知用户'} />
<AvatarFallback className="rounded-lg">{user?.name?.charAt(0) || '-'}</AvatarFallback>
</Avatar>
<div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-medium">{user?.name || '未知用户'}{user?.team ? ` - ${user?.team?.name}` : ''}</span>
<span className="truncate text-xs">{user?.email || '-'}</span>
</div>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => {
setNewName(user?.name || '');
setShowChangeNameDialog(true);
}}>
<IconUserHexagon />
修改昵称
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShowChangePasswordDialog(true)}>
<IconLockCode />
修改密码
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setShowLogoutDialog(true)}>
<IconLogout />
登出
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<AlertDialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确认登出</AlertDialogTitle>
<AlertDialogDescription>
您确定要登出吗?登出后需要重新登录才能继续使用。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction onClick={handleLogout}>
确认登出
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</SidebarMenuItem>
</SidebarMenu>
<Dialog open={showChangeNameDialog} onOpenChange={setShowChangeNameDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>修改昵称</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="new-name">昵称</Label>
<Input
id="new-name"
type="text"
placeholder="请输入新昵称"
value={newName}
onChange={(e) => setNewName(e.target.value)}
autoComplete="name"
/>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => {
setShowChangeNameDialog(false);
setNewName('');
}}
>
取消
</Button>
<Button
onClick={handleChangeName}
disabled={changingName || !newName.trim()}
>
{changingName && <Spinner className="size-4 mr-2" />}
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={showChangePasswordDialog} onOpenChange={setShowChangePasswordDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>修改密码</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="current-password">当前密码</Label>
<Input
id="current-password"
type="password"
placeholder="请输入当前密码"
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
autoComplete="current-password"
/>
</div>
<div className="space-y-2">
<Label htmlFor="new-password">新密码</Label>
<Input
id="new-password"
type="password"
placeholder="请输入新密码"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
autoComplete="new-password"
/>
</div>
<div className="space-y-2">
<Label htmlFor="confirm-password">确认新密码</Label>
<Input
id="confirm-password"
type="password"
placeholder="请再次输入新密码"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
autoComplete="new-password"
/>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => {
setShowChangePasswordDialog(false);
setCurrentPassword('');
setNewPassword('');
setConfirmPassword('');
}}
>
取消
</Button>
<Button
onClick={handleChangePassword}
disabled={changingPassword || !currentPassword || !newPassword || !confirmPassword}
>
{changingPassword && <Spinner className="size-4 mr-2" />}
确认修改
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={showChangeAvatarDialog} onOpenChange={setShowChangeAvatarDialog}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>修改头像</DialogTitle>
</DialogHeader>
<div className="flex justify-center">
<label
htmlFor="avatar-file"
className="relative cursor-pointer group"
>
<Avatar className="h-32 w-32 rounded-lg border-2 border-border group-hover:border-primary transition-colors">
{avatarPreview ? (
<>
<AvatarImage src={avatarPreview} alt="头像预览" />
<AvatarFallback className="rounded-lg">预览</AvatarFallback>
</>
) : (
<>
<AvatarImage src={user?.avatar_url || "/logo-colored.png"} alt="当前头像" />
<AvatarFallback className="rounded-lg text-3xl">
{user?.name?.charAt(0) || '-'}
</AvatarFallback>
</>
)}
</Avatar>
<div className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 rounded-lg transition-opacity">
<IconUpload className="h-8 w-8 text-white" />
</div>
<input
id="avatar-file"
type="file"
accept="image/*"
onChange={handleAvatarFileChange}
className="hidden"
/>
</label>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => {
setShowChangeAvatarDialog(false);
setAvatarFile(null);
setAvatarPreview('');
}}
>
取消
</Button>
<Button
onClick={handleChangeAvatar}
disabled={changingAvatar || !avatarFile}
>
{changingAvatar && <Spinner className="size-4 mr-2" />}
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
)
}
@@ -0,0 +1,62 @@
import * as React from "react"
import NavProject from "./nav-project"
import NavUser from "./nav-user"
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar"
import NavBalance from "./nav-balance"
import NavMain from "./nav-main"
import { Link } from "react-router-dom"
import { Settings } from "lucide-react"
export default function UserSidebar({
...props
}: React.ComponentProps<typeof Sidebar>) {
return (
<Sidebar variant="inset" {...props}>
<SidebarHeader>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton size="lg" asChild>
<a href="/">
<img src="/logo-colored.png" alt="MonkeyCode AI" className="size-8" />
<div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-medium">MonkeyCode AI</span>
<span className="truncate text-xs">智能开发平台</span>
</div>
</a>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarHeader>
<SidebarContent>
<NavMain />
<NavProject />
</SidebarContent>
<SidebarFooter>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
tooltip="配置"
isActive={location.pathname === "/console/settings"}
asChild
>
<Link to="/console/settings">
<Settings />
<span>配置</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
<NavBalance />
<NavUser />
</SidebarFooter>
</Sidebar>
)
}
@@ -0,0 +1,386 @@
import {
ConstsGitPlatform,
type DomainAuthRepository,
type DomainGitIdentity,
} from "@/api/Api"
import { Button } from "@/components/ui/button"
import {
RadioGroup,
RadioGroupItem,
} from "@/components/ui/radio-group"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
import { cn } from "@/lib/utils"
import { getGitPlatformIcon } from "@/utils/common"
import { apiRequest } from "@/utils/requestUtils"
import { IconCheck, IconChevronDown, IconGitBranch, IconLoader } from "@tabler/icons-react"
import Icon from "@/components/common/Icon"
import { useCallback, useEffect, useMemo, useState } from "react"
import { useNavigate } from "react-router-dom"
import { toast } from "sonner"
import { Spinner } from "@/components/ui/spinner"
import { useCommonData } from "@/components/console/data-provider"
interface RepoOption {
gitIdentityId: string
username: string
repository: DomainAuthRepository
}
interface AddProjectDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onSuccess?: () => void
}
export default function AddProjectDialog({
open,
onOpenChange,
onSuccess,
}: AddProjectDialogProps) {
const [name, setName] = useState("")
const [selectedSource, setSelectedSource] = useState<string>("")
const [identityRepoOptions, setIdentityRepoOptions] = useState<RepoOption[]>([])
const [loadingIdentityRepos, setLoadingIdentityRepos] = useState(false)
const [selectedRepoValue, setSelectedRepoValue] = useState("")
const [repoPopoverOpen, setRepoPopoverOpen] = useState(false)
const [loading, setLoading] = useState(false)
const navigate = useNavigate()
const { identities } = useCommonData()
const selectedIdentityId = selectedSource
const selectedIdentity = useMemo(
() => identities.find((i) => i.id === selectedIdentityId),
[identities, selectedIdentityId]
)
const selectedRepo = identityRepoOptions.find(
(o) => `${o.gitIdentityId}:${o.repository.url || ""}` === selectedRepoValue
)
const selectedRepoLabel = selectedRepo
? (selectedRepo.repository.full_name || selectedRepo.repository.url || "").replace(
`${selectedRepo.username}/`,
""
)
: ""
const identityLabel = (identity: DomainGitIdentity) =>
identity.remark || identity.username || identity.base_url || "未命名身份"
const loadReposForIdentity = useCallback(
async (identityId: string) => {
setLoadingIdentityRepos(true)
setIdentityRepoOptions([])
await apiRequest(
"v1UsersGitIdentitiesDetail",
{},
[identityId],
(detailResp) => {
if (detailResp.code !== 0) {
setLoadingIdentityRepos(false)
return
}
const identity = identities.find((i) => i.id === identityId)
const authorizedRepositories = detailResp.data?.authorized_repositories || []
const repos: RepoOption[] = []
for (const repo of authorizedRepositories) {
if (!repo.url?.trim()) continue
repos.push({
gitIdentityId: identityId,
username: identity?.username || identity?.remark || "未命名身份",
repository: repo,
})
}
setIdentityRepoOptions(repos)
setLoadingIdentityRepos(false)
},
() => setLoadingIdentityRepos(false)
)
},
[identities]
)
useEffect(() => {
if (open && selectedIdentityId) {
loadReposForIdentity(selectedIdentityId)
} else if (open && !selectedIdentityId) {
setIdentityRepoOptions([])
}
}, [open, selectedIdentityId, loadReposForIdentity])
useEffect(() => {
if (selectedIdentityId) {
setSelectedRepoValue("")
}
}, [selectedIdentityId])
const handleSave = async () => {
if (!name.trim()) {
toast.error("请输入项目名称")
return
}
const createReq: {
name: string
description?: string
platform?: ConstsGitPlatform
git_identity_id?: string
repo_url?: string
} = { name: name.trim() }
if (!selectedIdentityId) {
toast.error("请选择身份")
return
}
if (!selectedRepoValue) {
toast.error("请选择要关联的仓库")
return
}
const repo = identityRepoOptions.find(
(o) => `${o.gitIdentityId}:${o.repository.url || ""}` === selectedRepoValue
)
if (!repo?.repository.url) {
toast.error("请选择可用仓库")
return
}
createReq.platform = selectedIdentity?.platform as ConstsGitPlatform
createReq.git_identity_id = repo.gitIdentityId
createReq.repo_url = repo.repository.url
setLoading(true)
await apiRequest(
"v1UsersProjectsCreate",
createReq,
[],
(resp) => {
if (resp.code === 0) {
toast.success("项目创建成功")
onOpenChange(false)
setName("")
setSelectedSource("")
setSelectedRepoValue("")
setIdentityRepoOptions([])
onSuccess?.()
if (resp.data?.id) {
navigate(`/console/project/${resp.data.id}/docs/`)
}
} else {
toast.error(resp.message || "创建项目失败")
}
}
)
setLoading(false)
}
const handleCancel = () => {
onOpenChange(false)
setName("")
setSelectedSource("")
setSelectedRepoValue("")
setIdentityRepoOptions([])
}
const canSubmit = name.trim() && selectedIdentityId && selectedRepoValue
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>创建项目</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="name">项目名称</Label>
<Input
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="请输入项目名称"
disabled={loading}
/>
</div>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label>代码仓库</Label>
{identities.length > 0 ? (
<RadioGroup
value={selectedSource}
onValueChange={(v) => {
setSelectedSource(v)
setSelectedRepoValue("")
setIdentityRepoOptions([])
}}
className="grid grid-cols-2 gap-2"
disabled={loading}
>
{identities.map((identity) => (
<label
key={identity.id}
htmlFor={`repo-source-${identity.id}`}
className={cn(
"flex min-h-9 cursor-pointer items-center gap-2 rounded-md border border-input px-3 py-2 text-sm transition-colors hover:bg-muted/30",
selectedSource === identity.id && "text-primary"
)}
>
<RadioGroupItem
value={identity.id || ""}
id={`repo-source-${identity.id}`}
className="shrink-0"
/>
{getGitPlatformIcon(identity.platform)}
<span className="truncate">{identityLabel(identity)}</span>
</label>
))}
</RadioGroup>
) : (
<div className="flex items-center justify-between gap-3 p-3 rounded-lg border border-dashed bg-muted/30">
<p className="text-sm text-muted-foreground">
尚未绑定 Git 账号,请先绑定
</p>
<Button
variant="outline"
size="sm"
onClick={() => {
onOpenChange(false)
navigate("/console/settings")
}}
>
去设置
</Button>
</div>
)}
</div>
{selectedIdentityId ? (
<div className="flex flex-col gap-2">
<Label>选择仓库</Label>
<Popover open={repoPopoverOpen} onOpenChange={setRepoPopoverOpen} modal={true}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={repoPopoverOpen}
className="w-full justify-between font-normal"
disabled={loading}
>
<span className={cn(!selectedRepoValue && "text-muted-foreground")}>
{loadingIdentityRepos
? "正在获取仓库..."
: selectedRepoValue
? selectedRepoLabel
: identityRepoOptions.length === 0
? "暂无仓库,点击重试"
: "请选择仓库"}
</span>
<IconChevronDown className="ml-2 size-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
{loadingIdentityRepos ? (
<div className="flex items-center gap-2 py-6 text-sm text-muted-foreground justify-center">
<Spinner />
正在获取仓库...
</div>
) : identityRepoOptions.length === 0 ? (
<div className="p-4">
<p className="mb-3 text-sm">暂无仓库或获取失败,请点击重试。</p>
<Button
type="button"
size="sm"
onClick={() => loadReposForIdentity(selectedIdentityId)}
>
重试
</Button>
</div>
) : (
<Command>
<CommandInput placeholder="搜索仓库..." />
<CommandList className="max-h-48">
<CommandEmpty>未找到匹配的仓库</CommandEmpty>
{identityRepoOptions.map((option) => {
const value = `${option.gitIdentityId}:${option.repository.url || ""}`
const repoName = (
option.repository.full_name || option.repository.url || ""
).replace(`${option.username}/`, "")
const desc = option.repository.description
return (
<CommandItem
key={value}
value={`${repoName} ${desc || ""} ${option.username}`}
onSelect={() => {
setSelectedRepoValue(value)
setRepoPopoverOpen(false)
}}
className={cn(
"cursor-pointer flex flex-col items-start gap-0.5 py-1",
selectedRepoValue === value &&
"bg-muted/50 data-[selected=true]:bg-muted/70"
)}
>
<div className="flex items-center gap-2 w-full min-w-0">
<IconGitBranch className="size-4 shrink-0" />
<span className="truncate flex-1 text-sm">{repoName}</span>
<IconCheck
className={cn(
"size-4 shrink-0",
selectedRepoValue === value ? "opacity-100" : "opacity-0"
)}
/>
</div>
<span
className="text-xs text-muted-foreground truncate w-full pl-6"
title={desc || undefined}
>
{desc || "暂无描述"}
</span>
</CommandItem>
)
})}
</CommandList>
</Command>
)}
</PopoverContent>
</Popover>
</div>
) : null}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel} disabled={loading}>
取消
</Button>
<Button onClick={handleSave} disabled={loading || !canSubmit}>
{loading && <IconLoader className="size-4 animate-spin" />}
创建
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,101 @@
import { useState, useCallback, useEffect } from "react"
import { apiRequest } from "@/utils/requestUtils"
import { type DomainProjectCommitEntry } from "@/api/Api"
import { IconLoader, IconReport } from "@tabler/icons-react"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from "@/components/ui/empty"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import dayjs from "dayjs"
interface CommitHistoryDialogProps {
projectId: string
open: boolean
onOpenChange: (open: boolean) => void
}
export const CommitHistoryDialog = ({ projectId, open, onOpenChange }: CommitHistoryDialogProps) => {
const [historyLogs, setHistoryLogs] = useState<DomainProjectCommitEntry[]>([])
const [loading, setLoading] = useState(false)
const fetchHistoryLogs = useCallback(async () => {
if (!projectId) return
setLoading(true)
setHistoryLogs([])
await apiRequest('v1UsersProjectsTreeLogsDetail', {
limit: 50
}, [projectId], (resp) => {
if (resp.code === 0 && resp.data?.entries) {
setHistoryLogs(resp.data.entries)
}
})
setLoading(false)
}, [projectId])
useEffect(() => {
if (open) {
fetchHistoryLogs()
}
}, [open, fetchHistoryLogs])
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[700px] max-h-[80vh] flex flex-col">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<IconReport className="h-5 w-5" />
修改历史
</DialogTitle>
</DialogHeader>
<div className="flex-1 min-h-0 overflow-auto">
{loading ? (
<Empty className="border">
<EmptyHeader>
<EmptyMedia variant="icon">
<IconLoader className="animate-spin" />
</EmptyMedia>
<EmptyDescription>正在加载...</EmptyDescription>
</EmptyHeader>
</Empty>
) : historyLogs.length === 0 ? (
<Empty className="border">
<EmptyHeader>
<EmptyMedia variant="icon">
<IconReport />
</EmptyMedia>
<EmptyDescription>暂无修改记录</EmptyDescription>
</EmptyHeader>
</Empty>
) : (
<div className="space-y-2">
{historyLogs.map((entry, index) => (
<div
key={entry.commit?.sha || index}
className="px-4 py-3 border rounded-md hover:bg-accent/50 transition-colors"
>
<div className="flex items-start gap-4">
<Avatar className="size-6 shrink-0">
<AvatarImage src="/logo-colored.png" />
<AvatarFallback>{(entry.commit?.author?.name || 'U').charAt(0).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 flex flex-col gap-2">
<div className="text-sm break-all whitespace-pre-wrap line-clamp-2">
{entry.commit?.message || '无提交信息'}
</div>
<div className="text-xs text-muted-foreground">
{entry.commit?.author?.name || '未知用户'} 修改于 {entry.commit?.author?.when ? dayjs.unix(entry.commit.author.when).fromNow() : '-'}
</div>
</div>
</div>
</div>
))}
</div>
)}
</div>
</DialogContent>
</Dialog>
)
}
export default CommitHistoryDialog
@@ -0,0 +1,104 @@
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useEffect, useState } from "react"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { IconLoader } from "@tabler/icons-react"
import MarkdownEditor from "@/components/common/markdown-editor"
interface CreateIssueDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
projectId: string
onSuccess?: () => void
}
export default function CreateIssueDialog({
open,
onOpenChange,
projectId,
onSuccess,
}: CreateIssueDialogProps) {
const [title, setTitle] = useState("")
const [body, setBody] = useState("")
const [loading, setLoading] = useState(false)
useEffect(() => {
if (!open) {
setTitle("")
setBody("")
}
}, [open])
const handleSave = async () => {
if (!title.trim()) {
toast.error("请输入需求标题")
return
}
setLoading(true)
await apiRequest('v1UsersProjectsIssuesCreate', {
title: title.trim(),
requirement_document: body.trim()
}, [projectId], (resp) => {
if (resp.code === 0) {
toast.success("需求创建成功")
onOpenChange(false)
onSuccess?.()
} else {
toast.error(resp.message || "创建需求失败")
}
}
)
setLoading(false)
}
const handleCancel = () => {
setTitle("")
setBody("")
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>创建需求</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="title">需求标题</Label>
<Input
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="请输入需求标题"
disabled={loading}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="body">原始需求说明</Label>
<MarkdownEditor
value={body}
onChange={setBody}
disabled={loading}
className="min-h-60 max-h-[50vh]"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel} disabled={loading}>
取消
</Button>
<Button onClick={handleSave} disabled={loading || !title.trim()}>
{loading && <IconLoader className="size-4 animate-spin" />}
创建
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,93 @@
import { useState, useCallback, useEffect } from "react"
import { apiRequest } from "@/utils/requestUtils"
import { cn } from "@/lib/utils"
import { IconFileText } from "@tabler/icons-react"
import { b64decode } from "@/utils/common"
import { Markdown } from "@/components/common/markdown"
import { Label } from "@/components/ui/label"
import { type DomainProject } from "@/api/Api"
interface DocsViewerProps {
project?: DomainProject
ref?: string
docPath?: string
candidatePaths?: string[]
className?: string
}
export const DocsViewer = ({ project, ref: gitRef, docPath, candidatePaths, className }: DocsViewerProps) => {
const [content, setContent] = useState<string>('')
const [resolvedPath, setResolvedPath] = useState<string>('')
const fetchWithCandidates = useCallback(async () => {
if (!project?.id) {
setContent('')
setResolvedPath('')
return
}
const paths = candidatePaths && candidatePaths.length > 0
? candidatePaths
: docPath ? [docPath] : []
if (paths.length === 0) {
setContent('')
setResolvedPath('')
return
}
for (const path of paths) {
let found = false
await apiRequest('v1UsersProjectsTreeBlobDetail', {
path,
ref: gitRef
}, [project.id], (resp) => {
if (resp.code === 0 && resp.data?.content) {
setContent(b64decode(resp.data.content))
setResolvedPath(path)
found = true
}
})
if (found) {
window.scrollTo(0, 0)
return
}
}
setContent('')
setResolvedPath('')
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [project?.id, docPath, gitRef])
useEffect(() => {
fetchWithCandidates()
}, [fetchWithCandidates])
const displayPath = resolvedPath || docPath || ''
const renderHeader = () => {
return (
<div className="px-4 py-2 flex items-center border-b bg-muted/50">
<Label className="flex items-center h-6">
<IconFileText className="size-4" />
{displayPath}
</Label>
</div>
)
}
if (!content) {
return null
}
return (
<div className={cn("flex flex-1 flex-col border rounded-md", className)}>
{renderHeader()}
<div className="p-4">
<Markdown>{content}</Markdown>
</div>
</div>
)
}
export default DocsViewer
@@ -0,0 +1,174 @@
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Checkbox } from "@/components/ui/checkbox"
import type { DomainProject, ConstsProjectCollaboratorRole, DomainCreateCollaboratorItem } from "@/api/Api"
import { useEffect, useState, useRef } from "react"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { IconLoader } from "@tabler/icons-react"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
import { useCommonData } from "../data-provider"
interface EditCollaboratorsDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
project?: DomainProject | null
onSuccess?: () => void
}
export default function EditCollaboratorsDialog({
open,
onOpenChange,
project,
onSuccess,
}: EditCollaboratorsDialogProps) {
const [selectedCollaboratorIds, setSelectedCollaboratorIds] = useState<string[]>([])
const [loading, setLoading] = useState(false)
const [selectOpen, setSelectOpen] = useState(false)
const selectRef = useRef<HTMLDivElement>(null)
const { members } = useCommonData()
useEffect(() => {
if (open && project) {
// 加载已有的协作者
const existingIds = (project.collaborators || [])
.map(c => c.id)
.filter(Boolean) as string[]
setSelectedCollaboratorIds(existingIds)
} else if (!open) {
setSelectedCollaboratorIds([])
setSelectOpen(false)
}
}, [open, project])
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (selectRef.current && !selectRef.current.contains(event.target as Node)) {
setSelectOpen(false)
}
}
if (selectOpen) {
document.addEventListener("mousedown", handleClickOutside)
}
return () => {
document.removeEventListener("mousedown", handleClickOutside)
}
}, [selectOpen])
const handleCollaboratorCheckboxChange = (userId: string, checked: boolean) => {
if (checked) {
setSelectedCollaboratorIds([...selectedCollaboratorIds, userId])
} else {
setSelectedCollaboratorIds(selectedCollaboratorIds.filter(id => id !== userId))
}
}
const handleSave = async () => {
setLoading(true)
// 构建协作者列表
const collaborators: DomainCreateCollaboratorItem[] = selectedCollaboratorIds.map(userId => ({
user_id: userId,
permission: "read_write" as ConstsProjectCollaboratorRole
}))
await apiRequest('v1UsersProjectsUpdate', {
collaborators
}, [project?.id!], (resp) => {
if (resp.code === 0) {
toast.success("协作成员修改成功")
onOpenChange(false)
onSuccess?.()
} else {
toast.error("修改协作成员失败: " + resp.message)
}
}
)
setLoading(false)
}
const handleCancel = () => {
setSelectedCollaboratorIds([])
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>修改成员</DialogTitle>
</DialogHeader>
<div className="relative" ref={selectRef}>
<Button
type="button"
variant="outline"
role="combobox"
aria-expanded={selectOpen}
className="w-full justify-between"
onClick={() => setSelectOpen(!selectOpen)}
disabled={loading}
>
<span className="truncate">
{selectedCollaboratorIds.length === 0
? "请选择协作成员"
: selectedCollaboratorIds.length === 1
? members.find((m) => m.id === selectedCollaboratorIds[0])?.name ||
members.find((m) => m.id === selectedCollaboratorIds[0])?.email ||
"已选择 1 名成员"
: `已选择 ${selectedCollaboratorIds.length} 名成员`}
</span>
<ChevronDown className={cn("ml-2 h-4 w-4 shrink-0 opacity-50 transition-transform", selectOpen && "rotate-180")} />
</Button>
{selectOpen && (
<div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-md">
<div className="max-h-[200px] overflow-auto p-1">
{members.length === 0 ? (
<div className="py-6 text-center text-sm text-muted-foreground">
暂无可选的协作成员
</div>
) : (
members.map((member) => {
const isChecked = selectedCollaboratorIds.includes(member.id || "")
return (
<div
key={member.id}
className="flex items-center gap-2 rounded-sm px-2 py-1.5 hover:bg-accent cursor-pointer"
onClick={() => handleCollaboratorCheckboxChange(member.id || "", !isChecked)}
>
<Checkbox
checked={isChecked}
onCheckedChange={(checked) => handleCollaboratorCheckboxChange(member.id || "", checked as boolean)}
onClick={(e) => e.stopPropagation()}
/>
<img
src={member.avatar_url || "/logo-colored.png"}
alt={member.name || ''}
className="w-5 h-5 rounded-full object-cover"
/>
<span className="text-sm truncate">{member.name || member.email}</span>
</div>
)
})
)}
</div>
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel} disabled={loading}>
取消
</Button>
<Button onClick={handleSave} disabled={loading}>
{loading && <IconLoader className="size-4 animate-spin" />}
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,109 @@
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import type { DomainProject } from "@/api/Api"
import { useEffect, useState } from "react"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { IconLoader } from "@tabler/icons-react"
interface EditProjectNameDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
project?: DomainProject
onSuccess?: () => void
}
export default function EditProjectNameDialog({
open,
onOpenChange,
project,
onSuccess,
}: EditProjectNameDialogProps) {
const [name, setName] = useState("")
const [description, setDescription] = useState("")
const [loading, setLoading] = useState(false)
useEffect(() => {
if (open && project) {
setName(project.name || "")
setDescription(project.description || "")
} else if (!open) {
setName("")
setDescription("")
}
}, [open, project])
const handleSave = async () => {
if (!name.trim()) {
toast.error("请输入项目名称")
return
}
setLoading(true)
await apiRequest('v1UsersProjectsUpdate', {
name: name.trim(),
description: description.trim(),
}, [project?.id!], (resp) => {
if (resp.code === 0) {
toast.success("项目修改成功")
onOpenChange(false)
onSuccess?.()
} else {
toast.error("修改项目失败: " + resp.message)
}
}
)
setLoading(false)
}
const handleCancel = () => {
setName("")
setDescription("")
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>修改项目</DialogTitle>
</DialogHeader>
<div className="space-y-2">
<Label htmlFor="project-name">项目名称</Label>
<Input
id="project-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="请输入项目名称"
disabled={loading}
/>
</div>
<div className="space-y-2">
<Label htmlFor="project-description">项目描述</Label>
<Textarea
id="project-description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="请输入项目描述(选填)"
disabled={loading}
className="break-all"
/>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel} disabled={loading}>
取消
</Button>
<Button onClick={handleSave} disabled={loading || !name.trim()}>
{loading && <IconLoader className="size-4 animate-spin" />}
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,468 @@
import { useState, useCallback, memo, useMemo } from "react"
import { apiRequest } from "@/utils/requestUtils"
import { type DomainProject, type DomainProjectTreeEntry } from "@/api/Api"
import { cn } from "@/lib/utils"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
import { IconFileText, IconFolder, IconFolderOpen, IconLoader, IconReload, IconGitBranch, IconFile, IconFileSymlink, IconReport, IconDownload } from "@tabler/icons-react"
import { CommitHistoryDialog } from "./commit-history-dialog"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from "@/components/ui/empty"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { useEffect } from "react"
import { b64decode } from "@/utils/common"
import AceEditor from "react-ace"
import "ace-builds/src-noconflict/mode-text"
import "ace-builds/src-noconflict/mode-javascript"
import "ace-builds/src-noconflict/mode-typescript"
import "ace-builds/src-noconflict/mode-python"
import "ace-builds/src-noconflict/mode-json"
import "ace-builds/src-noconflict/mode-yaml"
import "ace-builds/src-noconflict/mode-markdown"
import "ace-builds/src-noconflict/mode-html"
import "ace-builds/src-noconflict/mode-css"
import "ace-builds/src-noconflict/mode-sql"
import "ace-builds/src-noconflict/mode-sh"
import "ace-builds/src-noconflict/mode-dockerfile"
import dayjs from "dayjs"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
type TreeEntry = DomainProjectTreeEntry
const getLanguageMode = (fileName: string): string => {
const ext = fileName.split('.').pop()?.toLowerCase()
const modeMap: Record<string, string> = {
'js': 'javascript',
'jsx': 'javascript',
'ts': 'typescript',
'tsx': 'typescript',
'py': 'python',
'sh': 'sh',
'bash': 'sh',
'zsh': 'sh',
'fish': 'sh',
'sql': 'sql',
'html': 'html',
'htm': 'html',
'css': 'css',
'json': 'json',
'yaml': 'yaml',
'yml': 'yaml',
'md': 'markdown',
'markdown': 'markdown',
'dockerfile': 'dockerfile',
}
return modeMap[ext || ''] || 'text'
}
// 文件模式枚举
const FileMode = {
UNKNOWN: 0, // 未知文件
REGULAR: 1, // 普通文件
EXECUTABLE: 2, // 可执行文件
SYMLINK: 3, // 符号连接
DIRECTORY: 4, // 目录
SUBMODULE: 5, // Git Submodule
} as const
interface ProjectFileManagerProps {
project?: DomainProject
onFileSelect?: (entry: TreeEntry) => void
onLoaded?: () => void
className?: string
}
// 判断是否为目录
const isDirectory = (entry: TreeEntry) => {
return entry.mode === FileMode.DIRECTORY
}
// 文件排序:目录在前,文件在后,按名称排序
const sortEntries = (entries: TreeEntry[]) => {
return [...entries].sort((a, b) => {
const aIsDir = isDirectory(a)
const bIsDir = isDirectory(b)
if (aIsDir !== bIsDir) {
return aIsDir ? -1 : 1
}
return (a.name || '').localeCompare(b.name || '')
})
}
// 获取文件图标
const getFileIcon = (entry: TreeEntry, isOpen?: boolean, loading?: boolean) => {
if (loading) {
return <IconLoader className="h-4 w-4 shrink-0 animate-spin" />
}
switch (entry.mode) {
case FileMode.DIRECTORY:
return isOpen
? <IconFolderOpen className="h-4 w-4 text-amber-500 shrink-0" />
: <IconFolder className="h-4 w-4 text-amber-500 shrink-0" />
case FileMode.SYMLINK:
return <IconFileSymlink className="h-4 w-4 text-muted-foreground shrink-0" />
case FileMode.SUBMODULE:
return <IconGitBranch className="h-4 w-4 text-amber-500 shrink-0" />
case FileMode.REGULAR:
case FileMode.EXECUTABLE:
default:
return <IconFileText className="h-4 w-4 text-muted-foreground shrink-0" />
}
}
// 格式化文件大小
const formatSize = (size?: number) => {
if (size === undefined || size === null) return ''
if (size < 1024) return `${size} B`
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
return `${(size / 1024 / 1024).toFixed(1)} MB`
}
interface TreeNodeProps {
entry: TreeEntry
projectId: string
depth: number
onFileSelect?: (entry: TreeEntry) => void
}
const TreeNode = memo(({ entry, projectId, depth, onFileSelect }: TreeNodeProps) => {
const [isOpen, setIsOpen] = useState(false)
const [children, setChildren] = useState<TreeEntry[]>([])
const [loading, setLoading] = useState(false)
const [loaded, setLoaded] = useState(false)
const isDir = isDirectory(entry)
const loadChildren = useCallback(async () => {
if (loaded || !isDir) return
setLoading(true)
await apiRequest('v1UsersProjectsTreeDetail', {
recursive: false,
path: entry.path
}, [projectId], (resp) => {
if (resp.code === 0) {
setChildren(sortEntries(resp.data || []))
setLoaded(true)
}
})
setLoading(false)
}, [projectId, entry.path, isDir, loaded])
const handleToggle = useCallback((open: boolean) => {
setIsOpen(open)
if (open && !loaded) {
loadChildren()
}
}, [loaded, loadChildren])
const handleClick = useCallback(() => {
if (isDir) {
handleToggle(!isOpen)
} else if (onFileSelect) {
onFileSelect(entry)
}
}, [isDir, isOpen, handleToggle, onFileSelect, entry])
const paddingLeft = depth * 16
if (isDir) {
return (
<Collapsible open={isOpen} onOpenChange={handleToggle}>
<CollapsibleTrigger asChild>
<div
className="flex items-center gap-1.5 py-2.5 px-4 hover:bg-accent/50 rounded-sm cursor-pointer select-none group border-b border-border/50"
style={{ paddingLeft: `${paddingLeft + 12}px` }}
>
{getFileIcon(entry, isOpen, loading)}
<span className="text-sm truncate flex-1 group-hover:text-primary">{entry.name}</span>
<div className="text-muted-foreground text-xs shrink-0">
-
</div>
<div className="text-muted-foreground text-xs shrink-0 w-30 text-right">
{dayjs.unix(entry.last_modified_at || 0).fromNow()}
</div>
</div>
</CollapsibleTrigger>
<CollapsibleContent>
{children.map((child) => (
<TreeNode
key={child.path}
entry={child}
projectId={projectId}
depth={depth + 1}
onFileSelect={onFileSelect}
/>
))}
</CollapsibleContent>
</Collapsible>
)
}
return (
<div
className="flex items-center gap-1.5 py-2.5 px-4 hover:bg-accent/50 group rounded-sm cursor-pointer select-none border-b border-border/50"
style={{ paddingLeft: `${paddingLeft + 12}px` }}
onClick={handleClick}
>
{getFileIcon(entry)}
<div className="text-sm truncate flex-1 group-hover:text-primary">
{entry.name}
</div>
<div className="text-muted-foreground text-xs shrink-0">
{formatSize(entry.size)}
</div>
<div className="text-muted-foreground text-xs shrink-0 w-30 text-right">
{dayjs.unix(entry.last_modified_at || 0).fromNow()}
</div>
</div>
)
})
TreeNode.displayName = 'TreeNode'
export const ProjectFileManager = ({ project, onFileSelect, onLoaded, className }: ProjectFileManagerProps) => {
const [entries, setEntries] = useState<TreeEntry[]>([])
const [loading, setLoading] = useState(true)
const [refreshKey, setRefreshKey] = useState(0)
// 文件内容对话框状态
const [dialogOpen, setDialogOpen] = useState(false)
const [selectedFile, setSelectedFile] = useState<TreeEntry | null>(null)
const [fileContent, setFileContent] = useState<string>('')
const [fileLoading, setFileLoading] = useState(false)
// 修改历史对话框状态
const [historyDialogOpen, setHistoryDialogOpen] = useState(false)
const languageMode = useMemo(() => {
return selectedFile?.name ? getLanguageMode(selectedFile.name) : 'text'
}, [selectedFile])
const fetchRootEntries = useCallback(async () => {
if (!project?.id) {
setEntries([])
setLoading(false)
return
}
setLoading(true)
await apiRequest('v1UsersProjectsTreeDetail', {
recursive: false,
path: ''
}, [project?.id], (resp) => {
if (resp.code === 0) {
setEntries(sortEntries(resp.data || []))
} else {
setEntries([])
}
})
setLoading(false)
onLoaded?.()
}, [project?.id, onLoaded])
useEffect(() => {
fetchRootEntries()
}, [project?.id, fetchRootEntries, refreshKey])
const handleRefresh = useCallback(() => {
setRefreshKey(prev => prev + 1)
}, [])
// 获取文件内容
const fetchFileContent = useCallback(async (entry: TreeEntry) => {
if (!project?.id) return
setFileLoading(true)
setFileContent('')
await apiRequest('v1UsersProjectsTreeBlobDetail', {
path: entry.path || '',
}, [project?.id], (resp) => {
if (resp.code === 0 && resp.data?.content) {
setFileContent(b64decode(resp.data?.content))
}
})
setFileLoading(false)
}, [project?.id])
// 处理文件点击
const handleFileClick = useCallback((entry: TreeEntry) => {
setSelectedFile(entry)
setDialogOpen(true)
fetchFileContent(entry)
// 如果有外部回调也调用
if (onFileSelect) {
onFileSelect(entry)
}
}, [fetchFileContent, onFileSelect])
const Header = (
<div className="px-4 py-2 flex items-center justify-between border-b bg-muted/50">
<Label className="flex items-center">
<IconFolderOpen className="size-4" />
项目文件
</Label>
<div className="flex items-center gap-1">
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-sm"
className="size-6 cursor-pointer"
onClick={() => {
setHistoryDialogOpen(true)
}}
disabled={loading}
>
<IconReport className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
查看修改历史
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-sm"
className="size-6 cursor-pointer"
onClick={handleRefresh}
disabled={loading}
>
<IconReload className={cn("h-4 w-4", loading && "animate-spin")} />
</Button>
</TooltipTrigger>
<TooltipContent>
刷新文件列表
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-sm"
className="size-6"
disabled={loading}
>
<a href={`/api/v1/users/projects/${project?.id}/tree/archive`} download={`${project?.name}.zip`} target="_blank">
<IconDownload className="h-4 w-4" />
</a>
</Button>
</TooltipTrigger>
<TooltipContent>
下载项目文件
</TooltipContent>
</Tooltip>
</div>
{/* 修改历史对话框 */}
<CommitHistoryDialog
projectId={project?.id || ''}
open={historyDialogOpen}
onOpenChange={setHistoryDialogOpen}
/>
</div>
)
if (!project?.id) {
return null
}
if (loading) {
return (
<div className={cn("flex flex-col border rounded-md", className)}>
{Header}
<Empty className="opacity-50">
<EmptyHeader>
<EmptyMedia variant="icon">
<IconLoader className="animate-spin" />
</EmptyMedia>
<EmptyDescription>正在加载...</EmptyDescription>
</EmptyHeader>
</Empty>
</div>
)
}
if (entries.length === 0) {
return (
<div className={cn("flex flex-col border rounded-md", className)}>
{Header}
<Empty className="opacity-50">
<EmptyHeader>
<EmptyMedia variant="icon">
<IconFolder />
</EmptyMedia>
<EmptyDescription>当前项目没有文件</EmptyDescription>
</EmptyHeader>
</Empty>
</div>
)
}
return (
<>
<div className={cn("flex flex-col border rounded-md", className)}>
{Header}
<div className="flex-1">
<div className="p-1">
{entries.map((entry) => (
<TreeNode
key={`${refreshKey}-${entry.path}`}
entry={entry}
projectId={project?.id || ''}
depth={0}
onFileSelect={handleFileClick}
/>
))}
</div>
</div>
</div>
{/* 文件内容对话框 */}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent className="sm:max-w-[80vw] xl:max-w-[60vw] h-[80vh] flex flex-col">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<IconFile className="h-5 w-5" />
<span className="truncate">{selectedFile?.path}</span>
</DialogTitle>
</DialogHeader>
<div className="flex-1 min-h-0 overflow-hidden rounded-md border">
{fileLoading ? (
<Empty className="opacity-50 h-full">
<EmptyHeader>
<EmptyMedia variant="icon">
<IconLoader className="animate-spin" />
</EmptyMedia>
</EmptyHeader>
</Empty>
) : (
<AceEditor
mode={languageMode}
theme="monkeycode"
width="100%"
height="100%"
readOnly={true}
value={fileContent}
showPrintMargin={false}
showGutter={true}
setOptions={{
fontFamily: "var(--font-google-sans-code)",
fontSize: 12,
}}
/>
)}
</div>
</DialogContent>
</Dialog>
</>
)
}
export default ProjectFileManager
@@ -0,0 +1,109 @@
import { ConstsCliName, ConstsTaskSubType, ConstsTaskType } from "@/api/Api"
import { useCommonData } from "@/components/console/data-provider"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Spinner } from "@/components/ui/spinner"
import { packAndUploadFilesAsZip, selectHost, selectImage, selectModel } from "@/utils/common"
import { apiRequest } from "@/utils/requestUtils"
import { IconSparkles } from "@tabler/icons-react"
import { useState } from "react"
import { toast } from "sonner"
interface GenerateDocDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
projectId: string
projectName: string
}
export default function GenerateDocDialog({
open,
onOpenChange,
projectId,
projectName
}: GenerateDocDialogProps) {
const [selectedFiles, setSelectedFiles] = useState<File[]>([])
const [submitting, setSubmitting] = useState<boolean>(false)
const { images, models, hosts } = useCommonData()
const handleOpenChange = (open: boolean) => {
onOpenChange(open)
if (!open) {
// 重置表单状态
setSelectedFiles([])
}
}
const handleSubmit = async () => {
setSubmitting(true)
let repoInfo: { zip_url?: string; repo_filename?: string } = {}
if (selectedFiles.length > 0) {
try {
const { accessUrl, filename } = await packAndUploadFilesAsZip(selectedFiles)
repoInfo = {
zip_url: accessUrl,
repo_filename: filename,
}
} catch (error) {
toast.error((error as Error).message)
setSubmitting(false)
return
}
}
// 创建任务
await apiRequest('v1UsersTasksCreate', {
content: `为项目 "${projectName}" 生成设计文档`,
cli_name: ConstsCliName.CliNameOpencode,
model_id: selectModel(models, false),
image_id: selectImage(images, false),
host_id: selectHost(hosts, false),
repo: repoInfo,
resource: {
core: 2,
memory: 8 * 1024 * 1024 * 1024,
life: 2 * 60 * 60,
},
extra: {
project_id: projectId,
},
task_type: ConstsTaskType.TaskTypeDesign,
sub_type: ConstsTaskSubType.TaskSubTypeGenerateDocs,
}, [], (resp) => {
if (resp.code === 0) {
toast.success('文档生成任务已启动')
handleOpenChange(false)
window.open(`/console/task/develop/${resp.data?.id}`, "_blank")
} else {
toast.error(resp.message || '任务启动失败')
}
})
setSubmitting(false)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>生成项目文档</DialogTitle>
<DialogDescription>
AI 将根据你的需求为你生成项目架构设计文档
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
onClick={handleSubmit}
disabled={submitting}
>
{submitting ? <Spinner /> : <IconSparkles className="size-4" />}
生成文档
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,78 @@
import { ConstsProjectIssuePriority, ConstsProjectIssueStatus, type DomainProjectIssue } from "@/api/Api"
import { Separator } from "@/components/ui/separator"
import { cn } from "@/lib/utils"
import dayjs from "dayjs"
import IssueMenu from "./issue-menu"
import { IconChevronDown, IconCircleDot, IconCancel, IconCircleCheck, IconChevronUp, IconChevronsUp, IconAlertTriangle } from "@tabler/icons-react"
import { useMemo } from "react"
import { Badge } from "@/components/ui/badge"
import { getStatusName } from "@/utils/common"
interface IssueCardProps {
issue: DomainProjectIssue
projectId: string
onViewIssue: (issue: DomainProjectIssue) => void
}
export default function IssueCard({ issue, projectId, onViewIssue }: IssueCardProps) {
const priority = useMemo(() => {
switch (issue.priority) {
case ConstsProjectIssuePriority.ProjectIssuePriorityThree:
return <>
<IconChevronsUp className="text-primary" />
高优先级
</>
case ConstsProjectIssuePriority.ProjectIssuePriorityTwo:
return <>
<IconChevronUp className="text-primary" />
中优先级
</>
case ConstsProjectIssuePriority.ProjectIssuePriorityOne:
return <>
<IconChevronDown className="" />
低优先级
</>
default:
return null
}
}, [issue.priority])
return (
<div className={cn("border rounded-md flex flex-col group hover:border-primary/50 p-2 gap-1 cursor-default", issue.status === ConstsProjectIssueStatus.ProjectIssueStatusClosed ? "bg-muted/30" : "", issue.status === ConstsProjectIssueStatus.ProjectIssueStatusCompleted ? "bg-muted/30" : "")}>
<div className="flex flex-row items-center gap-2">
<Badge
variant="secondary"
className={cn(
issue.status === ConstsProjectIssueStatus.ProjectIssueStatusOpen ? 'text-primary bg-primary/20' : '',
issue.status === ConstsProjectIssueStatus.ProjectIssueStatusClosed ? 'text-muted-foreground' : '',
issue.status === ConstsProjectIssueStatus.ProjectIssueStatusCompleted ? 'text-primary' : '',
)}>
{issue.status === ConstsProjectIssueStatus.ProjectIssueStatusOpen ? <IconCircleDot /> : null}
{issue.status === ConstsProjectIssueStatus.ProjectIssueStatusClosed ? <IconCancel /> : null}
{issue.status === ConstsProjectIssueStatus.ProjectIssueStatusCompleted ? <IconCircleCheck /> : null}
{getStatusName(issue.status as ConstsProjectIssueStatus)}
</Badge>
<div
className={cn("flex-1 text-sm group-hover:text-primary cursor-pointer hover:underline line-clamp-1 break-all", issue.status === ConstsProjectIssueStatus.ProjectIssueStatusClosed && "line-through text-muted-foreground hover:line-through", issue.status === ConstsProjectIssueStatus.ProjectIssueStatusCompleted && "text-muted-foreground")}
onClick={() => onViewIssue(issue)}
>
{issue.title}
</div>
<IssueMenu issue={issue} projectId={projectId} />
</div>
<div className="text-xs text-muted-foreground line-clamp-2 break-all">{issue.summary}</div>
<Separator className="my-2" />
<div className="flex flex-row gap-2 items-center text-xs text-muted-foreground">
<Badge variant="outline" className={cn("flex flex-row gap-1 items-center", issue.status === ConstsProjectIssueStatus.ProjectIssueStatusCompleted ? "text-muted-foreground" : "", issue.status === ConstsProjectIssueStatus.ProjectIssueStatusClosed ? "text-muted-foreground" : "")}>
{priority}
</Badge>
{!issue.design_document && <Badge variant="outline" className={cn(issue.status === ConstsProjectIssueStatus.ProjectIssueStatusCompleted ? "text-muted-foreground" : "", issue.status === ConstsProjectIssueStatus.ProjectIssueStatusClosed ? "text-muted-foreground" : "")}>
<IconAlertTriangle />
缺少设计文档
</Badge>}
<div className="flex-1 text-right">{dayjs((issue.created_at || 0) * 1000).fromNow()}创建</div>
</div>
</div>
)
}
@@ -0,0 +1,103 @@
import { type DomainProjectIssue, ConstsCliName, ConstsTaskSubType, ConstsTaskType } from "@/api/Api"
import { useCommonData } from "@/components/console/data-provider"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Spinner } from "@/components/ui/spinner"
import { selectHost, selectImage, selectModel } from "@/utils/common"
import { apiRequest } from "@/utils/requestUtils"
import { IconSparkles } from "@tabler/icons-react"
import { useMemo, useState } from "react"
import { toast } from "sonner"
interface IssueDesignDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
issue?: DomainProjectIssue
projectId: string
onConfirm?: () => void
}
export default function IssueDesignDialog({
open,
onOpenChange,
issue,
projectId,
onConfirm
}: IssueDesignDialogProps) {
const [submitting, setSubmitting] = useState<boolean>(false)
const { images, models, hosts } = useCommonData()
const handleOpenChange = (open: boolean) => {
onOpenChange(open)
}
const renderPrompt = useMemo(() => {
let prompt = `为需求 "${issue?.title}" 设计技术方案`
if (issue?.requirement_document) {
prompt += `
原始需求如下:
\`\`\`
${issue?.requirement_document?.replaceAll("`", "\\`")}
\`\`\`
`
}
return prompt
}, [issue])
const handleConfirm = async () => {
setSubmitting(true)
// 创建任务
await apiRequest('v1UsersTasksCreate', {
content: renderPrompt,
cli_name: ConstsCliName.CliNameOpencode,
model_id: selectModel(models, false),
image_id: selectImage(images, false),
host_id: selectHost(hosts, false),
resource: {
core: 2,
memory: 8 * 1024 * 1024 * 1024,
life: 2 * 60 * 60,
},
extra: {
project_id: projectId,
issue_id: issue?.id,
},
task_type: ConstsTaskType.TaskTypeDesign,
sub_type: ConstsTaskSubType.TaskSubTypeGenerateDesign,
}, [], (resp) => {
if (resp.code === 0) {
toast.success('方案设计任务已启动')
onConfirm?.()
handleOpenChange(false)
window.open(`/console/task/develop/${resp.data?.id}`, "_blank")
} else {
toast.error(resp.message || '任务启动失败')
}
})
setSubmitting(false)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>设计任务 (AI)</DialogTitle>
<DialogDescription>
AI 将根据需求自动生成技术方案
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button onClick={handleConfirm} disabled={submitting}>
{submitting ? <Spinner /> : <IconSparkles className="size-4" />}
开始设计
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,322 @@
import { ConstsProjectIssuePriority, ConstsProjectIssueStatus, type DomainProjectIssue } from "@/api/Api"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { apiRequest } from "@/utils/requestUtils"
import { IconCancel, IconCircleCheck, IconCircleChevronDown, IconCircleChevronsUp, IconCircleChevronUp, IconCircleDot, IconLoader } from "@tabler/icons-react"
import dayjs from "dayjs"
import { useEffect, useState } from "react"
import { toast } from "sonner"
import MarkdownEditor from "@/components/common/markdown-editor"
import { Input } from "@/components/ui/input"
import IssueMenu from "./issue-menu"
import { getStatusName } from "@/utils/common"
import { Markdown } from "@/components/common/markdown"
interface ViewIssueDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
issue?: DomainProjectIssue
projectId: string
onSuccess?: () => void
}
export default function ViewIssueDialog({
open,
onOpenChange,
issue,
projectId,
onSuccess,
}: ViewIssueDialogProps) {
const [loading, setLoading] = useState(false)
const [issueData, setIssueData] = useState<DomainProjectIssue | undefined>(issue)
const [isEditingTitle, setIsEditingTitle] = useState(false)
const [editingTitle, setEditingTitle] = useState("")
const [isEditingRequirementDocument, setIsEditingRequirementDocument] = useState(false)
const [editingRequirementDocument, setEditingRequirementDocument] = useState("")
const [isEditingDesignDocument, setIsEditingDesignDocument] = useState(false)
const [editingDesignDocument, setEditingDesignDocument] = useState("")
useEffect(() => {
if (!open) {
setIsEditingTitle(false)
setEditingTitle("")
setIsEditingRequirementDocument(false)
setEditingRequirementDocument("")
setIsEditingDesignDocument(false)
setEditingDesignDocument("")
}
}, [open])
useEffect(() => {
if (issue) {
setIssueData(issue)
setIsEditingTitle(false)
}
}, [issue])
const handleTitleClick = () => {
setEditingTitle(issueData?.title || "")
setIsEditingTitle(true)
}
const handleTitleSave = async () => {
if (!issueData?.id || loading) return
const newTitle = editingTitle.trim()
if (!newTitle || newTitle === issueData.title) {
setIsEditingTitle(false)
return
}
setLoading(true)
await apiRequest('v1UsersProjectsIssuesUpdate', { title: newTitle }, [projectId, issueData.id], (resp) => {
if (resp.code === 0) {
toast.success("标题更新成功")
setIssueData({ ...issueData, title: newTitle })
onSuccess?.()
} else {
toast.error(resp.message || "更新失败")
}
})
setLoading(false)
setIsEditingTitle(false)
}
const handleTitleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
handleTitleSave()
} else if (e.key === 'Escape') {
setIsEditingTitle(false)
}
}
const saveIssueData = async () => {
if (!issueData?.id || loading) return
if (editingRequirementDocument) {
issueData.requirement_document = editingRequirementDocument
}
if (editingDesignDocument) {
issueData.design_document = editingDesignDocument
}
setLoading(true)
await apiRequest('v1UsersProjectsIssuesUpdate', issueData, [projectId, issueData?.id], (resp) => {
if (resp.code === 0) {
setIsEditingRequirementDocument(false)
setEditingRequirementDocument("")
setIsEditingDesignDocument(false)
setEditingDesignDocument("")
toast.success("保存成功")
onSuccess?.()
} else {
toast.error(resp.message || "保存失败")
}
})
setLoading(false)
}
const handleStatusChange = async (status: ConstsProjectIssueStatus) => {
if (!issueData?.id || loading) return
setLoading(true)
await apiRequest('v1UsersProjectsIssuesUpdate', { status }, [projectId, issueData?.id], (resp) => {
if (resp.code === 0) {
toast.success("状态更新成功")
onSuccess?.()
} else {
toast.error(resp.message || "更新失败")
}
})
setLoading(false)
}
const handlePriorityChange = async (priority: ConstsProjectIssuePriority) => {
if (!issueData?.id || loading) return
setLoading(true)
await apiRequest('v1UsersProjectsIssuesUpdate', { priority }, [projectId, issueData?.id], (resp) => {
if (resp.code === 0) {
toast.success("优先级更新成功")
onSuccess?.()
} else {
toast.error(resp.message || "更新失败")
}
})
setLoading(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-[90vw] sm:max-w-[80vw] max-h-[90vh]">
<DialogHeader>
<DialogTitle className="text-xl break-all pr-6">
{isEditingTitle ? (
<Input
value={editingTitle}
onChange={(e) => setEditingTitle(e.target.value)}
onBlur={handleTitleSave}
onKeyDown={handleTitleKeyDown}
autoFocus
className="text-xl"
disabled={loading}
/>
) : (
<span
onClick={handleTitleClick}
className="cursor-pointer hover:bg-muted py-1 -my-1 rounded transition-colors"
>
{issueData?.title || "无标题"}
</span>
)}
</DialogTitle>
</DialogHeader>
<div className="flex flex-row gap-6 max-h-[calc(90vh-120px)]">
<div className="flex flex-col gap-6 flex-4 overflow-x-auto p-1 -m-1">
<div className="flex flex-col gap-2">
<div className="flex flex-row gap-2 items-center">
<Label className="flex-1">原始需求</Label>
{isEditingRequirementDocument ? (
<>
<Button variant="outline" className="text-xs h-6" size="sm" onClick={() => {
setIsEditingRequirementDocument(false)
setEditingRequirementDocument("")
}}>取消</Button>
<Button variant="default" className="text-xs h-6" size="sm" onClick={() => { saveIssueData() }}>保存</Button>
</>
) : (
<Button variant="outline" className="text-xs h-6" size="sm" onClick={() => {
setEditingRequirementDocument(issueData?.requirement_document || "");
setIsEditingRequirementDocument(true)
}}>编辑</Button>
)}
</div>
{isEditingRequirementDocument ? (
<div className="min-h-100">
<MarkdownEditor
value={editingRequirementDocument}
onChange={(value) => {
setEditingRequirementDocument(value)
}} />
</div>
) : (
<div className="border rounded-md p-2 min-h-10 bg-neutral-50">
<Markdown>{issueData?.requirement_document || "暂无内容"}</Markdown>
</div>
)}
</div>
<div className="flex flex-col gap-2">
<div className="flex flex-row gap-2 items-center">
<Label className="flex-1">技术方案</Label>
{isEditingDesignDocument ? (
<>
<Button variant="outline" className="text-xs h-6" size="sm" onClick={() => {
setIsEditingDesignDocument(false)
setEditingDesignDocument("")
}}>取消</Button>
<Button variant="default" className="text-xs h-6" size="sm" onClick={() => { saveIssueData() }}>保存</Button>
</>
) : (
<Button variant="outline" className="text-xs h-6" size="sm" onClick={() => {
setEditingDesignDocument(issueData?.design_document || "");
setIsEditingDesignDocument(true)
}}>编辑</Button>
)}
</div>
{isEditingDesignDocument ? (
<div className="min-h-100">
<MarkdownEditor
value={editingDesignDocument}
onChange={(value) => {
setEditingDesignDocument(value)
}} />
</div>
) : (
<div className="border rounded-md p-2 min-h-10 bg-neutral-50">
<Markdown>{issueData?.design_document || "暂无内容"}</Markdown>
</div>
)}
</div>
</div>
<div className="flex flex-col gap-6 flex-1 overflow-y-auto pr-2">
<div className="flex flex-col gap-2">
<Label>状态</Label>
<Select value={issueData?.status} onValueChange={(value) => { handleStatusChange(value as ConstsProjectIssueStatus)}} disabled={loading}>
<SelectTrigger className="w-full">
{loading ? <IconLoader className="size-4 animate-spin" /> : <SelectValue placeholder="选择状态" />}
</SelectTrigger>
<SelectContent>
<SelectItem value={ConstsProjectIssueStatus.ProjectIssueStatusOpen}>
<IconCircleDot className="text-primary" />
{getStatusName(ConstsProjectIssueStatus.ProjectIssueStatusOpen)}
</SelectItem>
<SelectItem value={ConstsProjectIssueStatus.ProjectIssueStatusCompleted}>
<IconCircleCheck className="" />
{getStatusName(ConstsProjectIssueStatus.ProjectIssueStatusCompleted)}
</SelectItem>
<SelectItem value={ConstsProjectIssueStatus.ProjectIssueStatusClosed}>
<IconCancel className="" />
{getStatusName(ConstsProjectIssueStatus.ProjectIssueStatusClosed)}
</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2">
<Label>优先级</Label>
<Select value={issueData?.priority?.toString()} onValueChange={(value) => { handlePriorityChange(parseInt(value, 10) as ConstsProjectIssuePriority)}} disabled={loading}>
<SelectTrigger className="w-full">
{loading ? <IconLoader className="size-4 animate-spin" /> : <SelectValue placeholder="选择优先级" />}
</SelectTrigger>
<SelectContent>
<SelectItem value={ConstsProjectIssuePriority.ProjectIssuePriorityThree.toString()}>
<IconCircleChevronsUp className="text-primary" />
高
</SelectItem>
<SelectItem value={ConstsProjectIssuePriority.ProjectIssuePriorityTwo.toString()}>
<IconCircleChevronUp className="text-primary" />
中
</SelectItem>
<SelectItem value={ConstsProjectIssuePriority.ProjectIssuePriorityOne.toString()}>
<IconCircleChevronDown />
低
</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-3 text-sm">
<Label>创建者</Label>
<div className="flex flex-row gap-2 items-center">
<Avatar className="size-5">
<AvatarImage src={issueData?.user?.avatar_url || "/logo-colored.png"} />
<AvatarFallback>{(issueData?.user?.name || "-").charAt(0).toUpperCase()}</AvatarFallback>
</Avatar>
<span>{issueData?.user?.name || "未知用户"}</span>
</div>
</div>
<div className="flex flex-col gap-3 text-sm">
<Label>创建时间</Label>
<span>{issueData?.created_at ? dayjs(issueData?.created_at * 1000).format("YYYY-MM-DD HH:mm") : "-"}</span>
</div>
<div className="flex flex-row gap-2 border rounded-md px-2 py-1 bg-muted/30">
<Label className="flex-1">更多操作</Label>
<IssueMenu issue={issue} projectId={projectId} />
</div>
</div>
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,108 @@
import { type DomainProjectIssue, ConstsCliName, ConstsTaskType } from "@/api/Api"
import { useCommonData } from "@/components/console/data-provider"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Spinner } from "@/components/ui/spinner"
import { selectHost, selectImage, selectModel } from "@/utils/common"
import { apiRequest } from "@/utils/requestUtils"
import { IconSparkles } from "@tabler/icons-react"
import { useMemo, useState } from "react"
import { toast } from "sonner"
interface IssueDevelopDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
issue?: DomainProjectIssue
projectId: string
onConfirm?: () => void
}
export default function IssueDevelopDialog({
open,
onOpenChange,
issue,
projectId,
onConfirm
}: IssueDevelopDialogProps) {
const [submitting, setSubmitting] = useState<boolean>(false)
const { images, models, hosts } = useCommonData()
const handleOpenChange = (open: boolean) => {
onOpenChange(open)
}
const renderPrompt = useMemo(() => {
let prompt = `为需求 "${issue?.title}" 执行开发任务`
if (issue?.requirement_document) {
prompt += `
详细描述如下:
\`\`\`
${issue?.requirement_document?.replaceAll("`", "\\`")}
\`\`\`
技术方案如下:
\`\`\`
${issue?.design_document?.replaceAll("`", "\\`")}
\`\`\`
`
}
return prompt
}, [issue])
const handleConfirm = async () => {
setSubmitting(true)
// 创建任务
await apiRequest('v1UsersTasksCreate', {
content: renderPrompt,
cli_name: ConstsCliName.CliNameOpencode,
model_id: selectModel(models, false),
image_id: selectImage(images, false),
host_id: selectHost(hosts, false),
resource: {
core: 2,
memory: 8 * 1024 * 1024 * 1024,
life: 2 * 60 * 60,
},
extra: {
project_id: projectId,
issue_id: issue?.id,
},
task_type: ConstsTaskType.TaskTypeDevelop,
}, [], (resp) => {
if (resp.code === 0) {
toast.success('开发任务已启动')
onConfirm?.()
handleOpenChange(false)
window.open(`/console/task/develop/${resp.data?.id}`, "_blank")
} else {
toast.error(resp.message || '任务启动失败')
}
})
setSubmitting(false)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>开发任务 (AI)</DialogTitle>
<DialogDescription>
AI 将根据需求和技术方案自动生成开发任务
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button onClick={handleConfirm} disabled={submitting}>
{submitting ? <Spinner /> : <IconSparkles className="size-4" />}
开始开发
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,35 @@
import { type DomainProjectIssue } from "@/api/Api";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty";
import { CalendarDays } from "lucide-react";
import IssueCard from "./issue-card";
export default function ProjectIssueList({ issues, projectId, onViewIssue }: { issues: DomainProjectIssue[], projectId: string, onViewIssue: (issue: DomainProjectIssue) => void }) {
if (issues.length === 0) {
return (
<Empty className="border">
<EmptyHeader>
<EmptyMedia variant="icon">
<CalendarDays />
</EmptyMedia>
<EmptyTitle>暂无内容</EmptyTitle>
<EmptyDescription>
可以点击右上角的 “创建需求”
</EmptyDescription>
</EmptyHeader>
</Empty>
)
}
return (
<div className="flex-1 rounded-md flex flex-col gap-3">
{issues.map((issue) => (
<IssueCard
key={issue.id}
issue={issue}
projectId={projectId}
onViewIssue={onViewIssue}
/>
))}
</div>
)
}
@@ -0,0 +1,61 @@
import { type DomainProjectIssue } from "@/api/Api"
import { Button } from "@/components/ui/button"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { IconDeviceImacCode, IconSparkles, IconTrash } from "@tabler/icons-react"
import { MoreVertical } from "lucide-react"
import { useState } from "react"
import IssueDesignDialog from "./issue-design-dialog"
import IssueDevelopDialog from "./issue-dev-dialog"
interface IssueMenuProps {
issue?: DomainProjectIssue
projectId: string
}
export default function IssueMenu({ issue, projectId }: IssueMenuProps) {
const [designDialogOpen, setDesignDialogOpen] = useState(false)
const [developDialogOpen, setDevelopDialogOpen] = useState(false)
if (!issue) {
return null
}
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm">
<MoreVertical className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setDesignDialogOpen(true)}>
<IconSparkles />
启动设计任务
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setDevelopDialogOpen(true)}>
<IconDeviceImacCode />
启动开发任务
</DropdownMenuItem>
<DropdownMenuItem>
<IconTrash />
移除
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<IssueDesignDialog
open={designDialogOpen}
onOpenChange={setDesignDialogOpen}
issue={issue}
projectId={projectId}
/>
<IssueDevelopDialog
open={developDialogOpen}
onOpenChange={setDevelopDialogOpen}
issue={issue}
projectId={projectId}
/>
</>
)
}
@@ -0,0 +1,219 @@
import { type DomainProject } from "@/api/Api"
import { useCommonData } from "@/components/console/data-provider"
import EditCollaboratorsDialog from "@/components/console/project/edit-collaborators"
import EditProjectNameDialog from "@/components/console/project/edit-project-name"
import GenerateDocDialog from "@/components/console/project/generate-doc-dialog"
import StartDevelopTaskDialog from "@/components/console/project/start-develop-task-dialog"
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Item, ItemActions, ItemContent, ItemDescription, ItemMedia, ItemTitle } from "@/components/ui/item"
import { isProjectRepoUnbound } from "@/utils/project"
import { apiRequest } from "@/utils/requestUtils"
import { IconBook, IconBrandGithub, IconLoader, IconPencil, IconSparkles, IconTrash, IconUsers } from "@tabler/icons-react"
import { MoreVertical } from "lucide-react"
import { useState } from "react"
import { useNavigate } from "react-router-dom"
import { toast } from "sonner"
interface ProjectInfoProps {
project?: DomainProject
onRefresh: () => void
}
const ProjectInfo = ({
project,
onRefresh,
}: ProjectInfoProps) => {
const [isEditNameDialogOpen, setIsEditNameDialogOpen] = useState(false)
const [isEditCollaboratorsDialogOpen, setIsEditCollaboratorsDialogOpen] = useState(false)
const [editingProject, setEditingProject] = useState<DomainProject | undefined>(undefined)
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
const [deletingProject, setDeletingProject] = useState<DomainProject | undefined>(undefined)
const [deleteLoading, setDeleteLoading] = useState(false)
const [emptyDocDialogOpen, setEmptyDocDialogOpen] = useState(false)
const [conversationDialogOpen, setConversationDialogOpen] = useState(false)
const navigate = useNavigate()
const { projects, reloadProjects } = useCommonData()
const handleEditProjectName = () => {
if (!project) return
setEditingProject(project)
setIsEditNameDialogOpen(true)
}
const handleEditCollaborators = () => {
if (!project) return
setEditingProject(project)
setIsEditCollaboratorsDialogOpen(true)
}
const handleDeleteClick = () => {
if (!project) return
setDeletingProject(project)
setDeleteDialogOpen(true)
}
const handleDeleteConfirm = async () => {
if (!deletingProject?.id) return
setDeleteLoading(true)
await apiRequest('v1UsersProjectsDelete', {}, [deletingProject.id], (resp) => {
if (resp.code === 0) {
toast.success("项目已删除")
setDeleteDialogOpen(false)
setDeletingProject(undefined)
// 找到删除后的第一个项目
const remainingProjects = projects.filter(p => p.id !== deletingProject.id)
reloadProjects()
if (remainingProjects.length > 0) {
navigate(`/console/project/${remainingProjects[0].id}/docs/`)
} else {
navigate('/console/tasks')
}
} else {
toast.error(resp.message || "删除项目失败")
}
})
setDeleteLoading(false)
}
const handleGenerateDoc = () => {
if (!project) return
setEmptyDocDialogOpen(true)
}
const handleStartConversation = () => {
if (!project || isRepoUnbound) return
setConversationDialogOpen(true)
}
const isRepoUnbound = isProjectRepoUnbound(project)
return (
<>
<Item variant="outline" key={project?.id}>
<ItemMedia>
<Avatar>
<AvatarImage src="" />
<AvatarFallback>
{project?.platform === "github"
? <IconBrandGithub className="size-5" />
: (project?.name || " ").charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
</ItemMedia>
<ItemContent>
<ItemTitle className="font-bold">
{project?.name || "-"}
</ItemTitle>
<ItemDescription className="flex flex-row gap-2 items-center">
{isRepoUnbound && (
<span className="text-amber-600">未绑定仓库</span>
) || (
<span>{project?.description || "暂无描述"}</span>
)}
</ItemDescription>
</ItemContent>
<ItemActions>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="secondary" size="sm" disabled={isRepoUnbound}>
<IconSparkles className="size-4" />
启动 AI
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={handleStartConversation}>
<IconSparkles />
发起对话
</DropdownMenuItem>
<DropdownMenuItem onClick={handleGenerateDoc}>
<IconBook />
生成项目文档
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm">
<MoreVertical className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={handleEditProjectName}>
<IconPencil />
修改名称
</DropdownMenuItem>
<DropdownMenuItem onClick={handleEditCollaborators}>
<IconUsers />
项目成员
</DropdownMenuItem>
<DropdownMenuItem
className="text-destructive"
onClick={handleDeleteClick}
>
<IconTrash />
移除项目
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</ItemActions>
</Item>
<EditProjectNameDialog
open={isEditNameDialogOpen}
onOpenChange={setIsEditNameDialogOpen}
project={editingProject}
onSuccess={onRefresh}
/>
<EditCollaboratorsDialog
open={isEditCollaboratorsDialogOpen}
onOpenChange={setIsEditCollaboratorsDialogOpen}
project={editingProject}
onSuccess={onRefresh}
/>
{/* 删除项目确认对话框 */}
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确认删除</AlertDialogTitle>
<AlertDialogDescription>
确定要删除项目 "{deletingProject?.name}" 吗?此操作不可撤销,项目内的所有数据都将被删除。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleteLoading}>取消</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteConfirm}
disabled={deleteLoading}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteLoading && <IconLoader className="size-4 animate-spin mr-2" />}
确认删除
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<GenerateDocDialog
open={emptyDocDialogOpen}
onOpenChange={setEmptyDocDialogOpen}
projectId={project?.id || ''}
projectName={project?.name || ''}
/>
<StartDevelopTaskDialog
open={conversationDialogOpen}
onOpenChange={setConversationDialogOpen}
project={project}
/>
</>
)
}
export default ProjectInfo
@@ -0,0 +1,79 @@
import { ConstsCliName, ConstsTaskType, type DomainProject } from "@/api/Api"
import { useCommonData } from "@/components/console/data-provider"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Spinner } from "@/components/ui/spinner"
import { selectHost, selectImage, selectModel } from "@/utils/common"
import { apiRequest } from "@/utils/requestUtils"
import { IconSparkles } from "@tabler/icons-react"
import { useState } from "react"
import { toast } from "sonner"
interface StartDevelopTaskDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
project?: DomainProject
}
export default function StartDevelopTaskDialog({
open,
onOpenChange,
project
}: StartDevelopTaskDialogProps) {
const [submitting, setSubmitting] = useState<boolean>(false)
const { images, models, hosts } = useCommonData()
const handleSubmit = async () => {
setSubmitting(true)
// 创建任务
await apiRequest('v1UsersTasksCreate', {
content: `你好,MonkeyCode`,
cli_name: ConstsCliName.CliNameOpencode,
model_id: selectModel(models, false),
image_id: selectImage(images, false),
host_id: selectHost(hosts, false),
resource: {
core: 2,
memory: 8 * 1024 * 1024 * 1024,
life: 2 * 60 * 60,
},
extra: {
project_id: project?.id,
},
task_type: ConstsTaskType.TaskTypeDevelop,
}, [], (resp) => {
if (resp.code === 0) {
toast.success('对话任务已启动')
onOpenChange(false)
window.open(`/console/task/develop/${resp.data?.id}`, "_blank")
} else {
toast.error(resp.message || '任务启动失败')
}
})
setSubmitting(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>发起对话</DialogTitle>
<DialogDescription>
与 AI 对话,对项目 "{project?.name}" 进行操作
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
onClick={handleSubmit}
disabled={submitting}
>
{submitting ? <Spinner /> : <IconSparkles className="size-4" />}
开始对话
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,243 @@
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Field, FieldContent, FieldLabel } from "@/components/ui/field"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { ConstsGitPlatform } from "@/api/Api"
import Icon from "@/components/common/Icon"
import { CircleQuestionMark } from 'lucide-react'
interface AddIdentityProps {
open: boolean
onOpenChange: (open: boolean) => void
onRefresh?: () => void
}
export default function AddIdentity({
open,
onOpenChange,
onRefresh,
}: AddIdentityProps) {
const [accessToken, setAccessToken] = useState("")
const [baseUrl, setBaseUrl] = useState("")
const [email, setEmail] = useState("")
const [username, setUsername] = useState("")
const [remark, setRemark] = useState("")
const [platform, setPlatform] = useState<ConstsGitPlatform | "">("")
// 验证邮箱格式
const isValidEmail = (email: string): boolean => {
const emailRegex = /^[a-zA-Z0-9+\-\_\.]+@[0-9a-zA-Z\.-]+$/
return emailRegex.test(email)
}
// 验证用户名格式(禁止括号、引号等特殊字符,允许 Unicode 字符)
const isValidUsername = (username: string): boolean => {
// 禁止的字符:括号、引号、空格等
const forbiddenChars = /[!@#$%\^\&\*\[\]\(\)\<\>'"]/
return !forbiddenChars.test(username)
}
// 根据平台类型自动设置 Base URL(Gitee 使用 OAuth 绑定,不在此表单中)
useEffect(() => {
if (platform) {
switch (platform) {
case ConstsGitPlatform.GitPlatformGitLab:
setBaseUrl("https://gitlab.com")
break
case ConstsGitPlatform.GitPlatformGitea:
setBaseUrl("https://gitea.com")
break
default:
setBaseUrl("")
}
} else {
setBaseUrl("")
}
}, [platform])
const handleSave = () => {
if (!accessToken.trim()) {
toast.error("请输入 Access Token")
return
}
if (!baseUrl.trim()) {
toast.error("请输入 Base URL")
return
}
if (!email.trim()) {
toast.error("请输入 Email")
return
}
if (!isValidEmail(email.trim())) {
toast.error("请输入有效的邮箱地址")
return
}
if (!username.trim()) {
toast.error("请输入用户名")
return
}
if (!isValidUsername(username.trim())) {
toast.error("用户名不能包含括号、引号等特殊字符")
return
}
if (!platform) {
toast.error("请选择 Git 平台类型")
return
}
apiRequest('v1UsersGitIdentitiesCreate', {
access_token: accessToken.trim(),
base_url: baseUrl.trim(),
email: email.trim(),
username: username.trim(),
platform: platform as ConstsGitPlatform,
remark: remark.trim() || undefined,
}, [], (resp) => {
if (resp.code === 0) {
toast.success("Git 身份绑定成功")
setAccessToken("")
setBaseUrl("")
setEmail("")
setUsername("")
setRemark("")
setPlatform("")
onOpenChange(false)
onRefresh?.()
} else {
toast.error("绑定 Git 身份失败: " + resp.message)
}
})
}
const handleCancel = () => {
setAccessToken("")
setBaseUrl("")
setEmail("")
setUsername("")
setRemark("")
setPlatform("")
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>绑定 Git 身份</DialogTitle>
</DialogHeader>
<div className="grid gap-4">
<div className="flex gap-4">
<Field className="flex-1">
<FieldLabel>Git 平台类型</FieldLabel>
<FieldContent>
<Select value={platform} onValueChange={(value) => setPlatform(value as ConstsGitPlatform)}>
<SelectTrigger className="w-full">
<SelectValue placeholder="请选择" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ConstsGitPlatform.GitPlatformGitLab}>
<Icon name="GitLab" />GitLab
</SelectItem>
<SelectItem value={ConstsGitPlatform.GitPlatformGitea}>
<Icon name="Gitea" />Gitea
</SelectItem>
</SelectContent>
</Select>
</FieldContent>
</Field>
<Field className="flex-[2]">
<FieldLabel>Git 平台地址</FieldLabel>
<FieldContent>
<Input
placeholder="例如: https://gitlab.com"
value={baseUrl}
onChange={(e) => setBaseUrl(e.target.value)}
/>
</FieldContent>
</Field>
</div>
<Field>
<div className="flex items-center justify-between gap-2">
<FieldLabel>Access Token</FieldLabel>
<Button
type="button"
variant="link"
size="sm"
asChild
className="h-auto p-0 text-foreground"
>
<a href="https://monkeycode.docs.baizhi.cloud/node/019a95ee-6277-7412-842a-587f25330ae6" target="_blank" rel="noopener noreferrer">
<CircleQuestionMark />如何获取
</a>
</Button>
</div>
<FieldContent>
<Input
placeholder="请输入 Access Token"
value={accessToken}
onChange={(e) => setAccessToken(e.target.value)}
/>
</FieldContent>
</Field>
<div className="flex gap-4">
<Field className="flex-1">
<FieldLabel>Username</FieldLabel>
<FieldContent>
<Input
placeholder="请输入用户名"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</FieldContent>
</Field>
<Field className="flex-1">
<FieldLabel>Email</FieldLabel>
<FieldContent>
<Input
type="email"
placeholder="请输入邮箱地址"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</FieldContent>
</Field>
</div>
<Field>
<FieldLabel>备注</FieldLabel>
<FieldContent>
<Input
placeholder="可选"
value={remark}
onChange={(e) => setRemark(e.target.value)}
/>
</FieldContent>
</Field>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel}>
取消
</Button>
<Button onClick={handleSave}>
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,97 @@
import { useState } from "react"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Field, FieldContent, FieldLabel } from "@/components/ui/field"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
interface AddImageProps {
open: boolean
onOpenChange: (open: boolean) => void
onRefresh?: () => void
}
export default function AddImage({
open,
onOpenChange,
onRefresh,
}: AddImageProps) {
const [imageName, setImageName] = useState("")
const [remark, setRemark] = useState("")
const handleSave = () => {
if (!imageName.trim()) {
toast.error("请输入镜像名称")
return
}
apiRequest('v1UsersImagesCreate', { image_name: imageName.trim(), remark: remark.trim() || undefined }, [], (resp) => {
if (resp.code === 0) {
toast.success("镜像绑定成功")
setImageName("")
setRemark("")
onOpenChange(false)
onRefresh?.()
} else {
toast.error("绑定镜像失败: " + resp.message)
}
})
}
const handleCancel = () => {
setImageName("")
setRemark("")
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogTrigger asChild>
<Button variant={"outline"} size="sm">绑定</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>绑定系统镜像</DialogTitle>
</DialogHeader>
<div className="grid gap-4">
<Field>
<FieldLabel>镜像名称</FieldLabel>
<FieldContent>
<Input
placeholder="docker.io/library/ubuntu:24.04"
value={imageName}
onChange={(e) => setImageName(e.target.value)}
/>
</FieldContent>
</Field>
<Field>
<FieldLabel>备注</FieldLabel>
<FieldContent>
<Input
value={remark}
onChange={(e) => setRemark(e.target.value)}
/>
</FieldContent>
</Field>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel}>
取消
</Button>
<Button onClick={handleSave}>
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,310 @@
import { useState } from "react"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Field, FieldContent, FieldDescription, FieldLabel } from "@/components/ui/field"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import type { DomainProviderModelListItem } from "@/api/Api"
import { ConstsInterfaceType } from "@/api/Api"
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Spinner } from "@/components/ui/spinner"
import { CircleQuestionMark } from 'lucide-react'
import { getModelUrlDescription, modelProviderList } from "@/utils/common"
interface AddModelProps {
open: boolean
onOpenChange: (open: boolean) => void
onRefresh?: () => void
}
export default function AddModel({
open,
onOpenChange,
onRefresh,
}: AddModelProps) {
const [model, setModel] = useState("")
const [apiToken, setApiToken] = useState("")
const [baseUrl, setBaseUrl] = useState("https://model-square.app.baizhi.cloud/v1")
const [interfaceType, setInterfaceType] = useState<ConstsInterfaceType>(ConstsInterfaceType.InterfaceTypeOpenAIChat)
const [modelList, setModelList] = useState<DomainProviderModelListItem[]>([])
const [loadingModels, setLoadingModels] = useState(false)
const [saving, setSaving] = useState(false)
const fetchModelList = async () => {
if (!apiToken.trim()) {
toast.error("请先输入 API Token")
return
}
if (modelProviderList[baseUrl.trim()]) {
setModelList(modelProviderList[baseUrl.trim()])
return
}
setLoadingModels(true)
await apiRequest('getProviderModelList', {
api_key: apiToken.trim(),
base_url: baseUrl.trim() || "https://model-square.app.baizhi.cloud/v1",
provider: "BaiZhiCloud",
}, [], (resp) => {
if (resp.code === 0) {
const models = resp.data?.models || []
setModelList(models)
if (models.length === 0) {
toast.warning("未获取到可用模型")
} else {
toast.success(`获取到 ${models.length} 个可用模型`)
}
} else {
toast.error("获取模型列表失败: " + resp.message)
}
})
setLoadingModels(false)
}
const handleSave = async () => {
if (!apiToken.trim()) {
toast.error("请输入 API Token")
return
}
if (!model.trim()) {
toast.error("请选择模型名称")
return
}
if (!baseUrl.trim()) {
toast.error("请输入模型 API 地址")
return
}
setSaving(true)
// 先进行健康检查
const healthCheckData = {
api_key: apiToken.trim(),
model: model.trim(),
base_url: baseUrl.trim(),
interface_type: interfaceType,
provider: "BaiZhiCloud",
}
await apiRequest('v1UsersModelsHealthCheckCreate', healthCheckData, [], async (resp) => {
if (resp.code === 0) {
if (resp.data?.success) {
// 健康检查通过,继续保存
const requestData: any = {
provider: "BaiZhiCloud",
model: model.trim(),
base_url: baseUrl.trim(),
api_key: apiToken.trim(),
interface_type: interfaceType,
}
await apiRequest('v1UsersModelsCreate', requestData, [], (resp) => {
if (resp.code === 0) {
toast.success("模型绑定成功")
setModel("")
setApiToken("")
setBaseUrl("https://model-square.app.baizhi.cloud/v1")
setInterfaceType(ConstsInterfaceType.InterfaceTypeOpenAIChat)
setModelList([])
onOpenChange(false)
onRefresh?.()
} else {
toast.error("绑定模型失败: " + resp.message)
}
})
} else {
toast.error("模型配置检查失败: " + resp.data?.error)
}
}
})
setSaving(false)
}
const handleCancel = () => {
setModel("")
setApiToken("")
setBaseUrl("https://model-square.app.baizhi.cloud/v1")
setInterfaceType(ConstsInterfaceType.InterfaceTypeOpenAIChat)
setModelList([])
onOpenChange(false)
}
// 对模型列表进行分组和排序
const getGroupedModels = () => {
const groups: Record<string, DomainProviderModelListItem[]> = {}
modelList.forEach((item) => {
const modelName = item.model || ""
const parts = modelName.split("-")
const groupKey = parts.length > 0 ? parts[0] : "其他"
if (!groups[groupKey]) {
groups[groupKey] = []
}
groups[groupKey].push(item)
})
// 对每个组内的模型按字符串排序
Object.keys(groups).forEach((key) => {
groups[key].sort((a, b) => {
const aName = a.model || ""
const bName = b.model || ""
return aName.localeCompare(bName)
})
})
// 对组名进行排序
const sortedGroupKeys = Object.keys(groups).sort()
return { groups, sortedGroupKeys }
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogTrigger asChild>
<Button variant={"outline"} size="sm">绑定</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>绑定 AI 大模型</DialogTitle>
</DialogHeader>
<div className="grid gap-4">
<Field>
<FieldLabel>接口格式</FieldLabel>
<FieldContent>
<Select
value={interfaceType}
onValueChange={(value) => setInterfaceType(value as ConstsInterfaceType)}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="请选择接口格式类型" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ConstsInterfaceType.InterfaceTypeOpenAIResponse}>
OpenAI Responses
</SelectItem>
<SelectItem value={ConstsInterfaceType.InterfaceTypeOpenAIChat}>
OpenAI Chat
</SelectItem>
<SelectItem value={ConstsInterfaceType.InterfaceTypeAnthropic}>
Anthropic
</SelectItem>
</SelectContent>
</Select>
</FieldContent>
</Field>
<Field>
<FieldLabel>模型 API 地址</FieldLabel>
<FieldContent>
<Input
placeholder="请输入模型 API 地址"
value={baseUrl}
onChange={(e) => setBaseUrl(e.target.value)}
/>
</FieldContent>
<FieldDescription>{getModelUrlDescription(baseUrl, interfaceType)}</FieldDescription>
</Field>
<Field>
<div className="flex items-center justify-between gap-2">
<FieldLabel>API Token</FieldLabel>
<Button
type="button"
variant="link"
size="sm"
asChild
className="h-auto p-0 text-foreground"
>
<a href="https://monkeycode.docs.baizhi.cloud/" target="_blank">
<CircleQuestionMark />如何获得
</a>
</Button>
</div>
<FieldContent>
<Input
placeholder="请输入 API Token"
value={apiToken}
onChange={(e) => setApiToken(e.target.value)}
/>
</FieldContent>
</Field>
<Field>
<FieldLabel>模型名称</FieldLabel>
<FieldContent>
<Select
value={model}
onValueChange={setModel}
onOpenChange={(open) => {
if (open && apiToken.trim() && !loadingModels) {
fetchModelList()
}
}}
disabled={loadingModels || !apiToken.trim()}
>
<SelectTrigger className="w-full">
<SelectValue placeholder={loadingModels ? "加载中..." : "请选择模型"} />
</SelectTrigger>
<SelectContent>
{loadingModels ? (
<div className="flex items-center justify-center py-4">
<Spinner />
<span className="ml-2 text-sm text-muted-foreground">加载模型中...</span>
</div>
) : modelList.length > 0 ? (() => {
const { groups, sortedGroupKeys } = getGroupedModels()
return (
<>
{sortedGroupKeys.map((groupKey) => (
<SelectGroup key={groupKey}>
<SelectLabel>{groupKey}</SelectLabel>
{groups[groupKey].map((item, index) => (
<SelectItem key={`${groupKey}-${index}`} value={item.model || ""}>
{item.model}
</SelectItem>
))}
</SelectGroup>
))}
</>
)
})() : (
<div className="py-4 text-center text-sm text-muted-foreground">
{apiToken.trim() ? "暂无可用模型" : "请先输入 API Token"}
</div>
)}
</SelectContent>
</Select>
</FieldContent>
</Field>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel} disabled={saving}>
取消
</Button>
<Button onClick={handleSave} disabled={!model.trim() || saving}>
{saving && <Spinner className="size-4" />}
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,276 @@
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Field, FieldContent, FieldLabel } from "@/components/ui/field"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import type { DomainGitIdentity } from "@/api/Api"
import { ConstsGitPlatform } from "@/api/Api"
import Icon from "@/components/common/Icon"
import { CircleQuestionMark } from 'lucide-react'
interface EditIdentityProps {
open: boolean
onOpenChange: (open: boolean) => void
identity: DomainGitIdentity | null
onRefresh?: () => void
trigger?: React.ReactNode
}
export default function EditIdentity({
open,
onOpenChange,
identity,
onRefresh,
trigger,
}: EditIdentityProps) {
const [accessToken, setAccessToken] = useState("")
const [baseUrl, setBaseUrl] = useState("")
const [email, setEmail] = useState("")
const [username, setUsername] = useState("")
const [remark, setRemark] = useState("")
const [platform, setPlatform] = useState<ConstsGitPlatform | "">("")
const isInstallationApp = identity?.is_installation_app === true
// 验证邮箱格式
const isValidEmail = (email: string): boolean => {
const emailRegex = /^[a-zA-Z0-9+\-\_\.]+@[0-9a-zA-Z\.-]+$/
return emailRegex.test(email)
}
// 验证用户名格式(禁止括号、引号等特殊字符,允许 Unicode 字符)
const isValidUsername = (username: string): boolean => {
// 禁止的字符:括号、引号、空格等
const forbiddenChars = /[!@#$%\^\&\*\[\]\(\)\<\>'"]/
return !forbiddenChars.test(username)
}
useEffect(() => {
if (identity) {
setUsername(identity.username || "")
setBaseUrl(identity.base_url || "")
setEmail(identity.email || "")
setRemark(identity.remark || "")
setPlatform(identity.platform || "")
setAccessToken(identity.access_token || "")
}
}, [identity])
const handleSave = () => {
if (!identity?.id) {
toast.error("身份信息不完整")
return
}
if (!baseUrl.trim()) {
toast.error("请输入 Base URL")
return
}
if (!email.trim()) {
toast.error("请输入 Email")
return
}
if (!isValidEmail(email.trim())) {
toast.error("请输入有效的邮箱地址")
return
}
if (!username.trim()) {
toast.error("请输入用户名")
return
}
if (!isValidUsername(username.trim())) {
toast.error("用户名不能包含括号、引号等特殊字符")
return
}
if (!platform) {
toast.error("请选择 Git 平台类型")
return
}
const updateData: {
access_token?: string
base_url: string
email: string
username: string
platform: ConstsGitPlatform
remark?: string
} = {
base_url: baseUrl.trim(),
email: email.trim(),
username: username.trim(),
platform: platform as ConstsGitPlatform,
remark: remark.trim(),
}
// 如果用户输入了 Access Token,则更新
if (accessToken.trim()) {
updateData.access_token = accessToken.trim()
} else if (identity.access_token) {
// 如果用户没有输入新值,但原值存在,则保持原值
updateData.access_token = identity.access_token
}
apiRequest('v1UsersGitIdentitiesUpdate', updateData, [identity.id], (resp) => {
if (resp.code === 0) {
toast.success("身份修改成功")
setAccessToken("")
setBaseUrl("")
setEmail("")
setUsername("")
setRemark("")
setPlatform("")
onOpenChange(false)
onRefresh?.()
} else {
toast.error("修改 Git 身份失败: " + resp.message)
}
})
}
const handleCancel = () => {
setAccessToken("")
setBaseUrl("")
setEmail("")
setUsername("")
setRemark("")
setPlatform("")
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
{trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>}
<DialogContent>
<DialogHeader>
<DialogTitle>修改 Git 身份</DialogTitle>
</DialogHeader>
<div className="grid gap-4">
<div className="flex gap-4">
<Field className="flex-1">
<FieldLabel>Git 平台类型</FieldLabel>
<FieldContent>
<Select
value={platform}
onValueChange={(value) => setPlatform(value as ConstsGitPlatform)}
disabled
>
<SelectTrigger className="w-full">
<SelectValue placeholder="请选择" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ConstsGitPlatform.GitPlatformGithub}>
<Icon name="GitHub-Uncolor" className="fill-foreground" />GitHub
</SelectItem>
<SelectItem value={ConstsGitPlatform.GitPlatformGitLab}>
<Icon name="GitLab" />GitLab
</SelectItem>
<SelectItem value={ConstsGitPlatform.GitPlatformGitea}>
<Icon name="Gitea" />Gitea
</SelectItem>
<SelectItem value={ConstsGitPlatform.GitPlatformGitee}>
<Icon name="Gitee" />Gitee
</SelectItem>
</SelectContent>
</Select>
</FieldContent>
</Field>
<Field className="flex-[2]">
<FieldLabel>Git 平台地址</FieldLabel>
<FieldContent>
<Input
placeholder="例如: https://github.com"
value={baseUrl}
onChange={(e) => setBaseUrl(e.target.value)}
disabled
/>
</FieldContent>
</Field>
</div>
{!isInstallationApp && (
<Field>
<div className="flex items-center justify-between gap-2">
<FieldLabel>Access Token</FieldLabel>
<Button
type="button"
variant="link"
size="sm"
asChild
className="h-auto p-0 text-foreground"
>
<a href="https://monkeycode.docs.baizhi.cloud/node/019a95ee-6277-7412-842a-587f25330ae6" target="_blank" rel="noopener noreferrer">
<CircleQuestionMark />如何获取
</a>
</Button>
</div>
<FieldContent>
<Input
placeholder="请输入 Access Token"
value={accessToken}
onChange={(e) => setAccessToken(e.target.value)}
/>
</FieldContent>
</Field>
)}
<div className="flex gap-4">
<Field className="flex-1">
<FieldLabel>Username</FieldLabel>
<FieldContent>
<Input
placeholder="请输入用户名"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</FieldContent>
</Field>
<Field className="flex-1">
<FieldLabel>Email</FieldLabel>
<FieldContent>
<Input
type="email"
placeholder="请输入邮箱地址"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</FieldContent>
</Field>
</div>
<Field>
<FieldLabel>备注</FieldLabel>
<FieldContent>
<Input
placeholder="可选"
value={remark}
onChange={(e) => setRemark(e.target.value)}
/>
</FieldContent>
</Field>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel}>
取消
</Button>
<Button onClick={handleSave}>
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,110 @@
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Field, FieldContent, FieldLabel } from "@/components/ui/field"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
interface EditImageProps {
open: boolean
onOpenChange: (open: boolean) => void
image: { id: string; image_name: string; remark: string } | null
onRefresh?: () => void
trigger?: React.ReactNode
}
export default function EditImage({
open,
onOpenChange,
image,
onRefresh,
trigger,
}: EditImageProps) {
const [imageName, setImageName] = useState("")
const [remark, setRemark] = useState("")
useEffect(() => {
if (image) {
setImageName(image.image_name)
setRemark(image.remark)
}
}, [image])
const handleSave = () => {
if (!image?.id) {
toast.error("镜像信息不完整")
return
}
if (!imageName.trim()) {
toast.error("请输入镜像名称")
return
}
apiRequest('v1UsersImagesUpdate',
{ image_name: imageName.trim(), remark: remark.trim() },
[image.id],
() => {
toast.success("镜像修改成功")
setImageName("")
setRemark("")
onOpenChange(false)
onRefresh?.()
}
)
}
const handleCancel = () => {
setImageName("")
setRemark("")
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
{trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>}
<DialogContent>
<DialogHeader>
<DialogTitle>修改操作系统镜像</DialogTitle>
</DialogHeader>
<div className="grid gap-4">
<Field>
<FieldLabel>镜像名称</FieldLabel>
<FieldContent>
<Input
value={imageName}
onChange={(e) => setImageName(e.target.value)}
/>
</FieldContent>
</Field>
<Field>
<FieldLabel>备注</FieldLabel>
<FieldContent>
<Input
value={remark}
onChange={(e) => setRemark(e.target.value)}
/>
</FieldContent>
</Field>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel}>
取消
</Button>
<Button onClick={handleSave}>
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,319 @@
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Field, FieldContent, FieldDescription, FieldLabel } from "@/components/ui/field"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import type { DomainModel, DomainProviderModelListItem } from "@/api/Api"
import { ConstsInterfaceType } from "@/api/Api"
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Spinner } from "@/components/ui/spinner"
import { getModelUrlDescription, modelProviderList } from "@/utils/common"
interface EditModelProps {
open: boolean
onOpenChange: (open: boolean) => void
model?: DomainModel
onRefresh?: () => void
}
export default function EditModel({
open,
onOpenChange,
model,
onRefresh,
}: EditModelProps) {
const [apiToken, setApiToken] = useState("")
const [baseUrl, setBaseUrl] = useState("")
const [selectedModel, setSelectedModel] = useState("")
const [interfaceType, setInterfaceType] = useState<ConstsInterfaceType>(ConstsInterfaceType.InterfaceTypeOpenAIChat)
const [modelList, setModelList] = useState<DomainProviderModelListItem[]>([])
const [loadingModels, setLoadingModels] = useState(false)
const [saving, setSaving] = useState(false)
useEffect(() => {
if (model && open) {
setApiToken(model.api_key || "")
setBaseUrl(model.base_url || "https://model-square.app.baizhi.cloud/v1")
setSelectedModel(model.model || "")
setInterfaceType(model.interface_type || ConstsInterfaceType.InterfaceTypeOpenAIChat)
setModelList([])
}
}, [model, open])
const fetchModelList = async () => {
if (!apiToken.trim()) {
toast.error("请先输入 API Token")
return
}
if (modelProviderList[baseUrl.trim()]) {
setModelList(modelProviderList[baseUrl.trim()])
return
}
setLoadingModels(true)
await apiRequest('getProviderModelList', {
api_key: apiToken.trim(),
base_url: baseUrl.trim() || model?.base_url || "https://model-square.app.baizhi.cloud/v1",
provider: model?.provider || "BaiZhiCloud",
}, [], (resp) => {
if (resp.code === 0) {
const models = resp.data?.models || []
setModelList(models)
if (models.length === 0) {
toast.warning("未获取到可用模型")
} else {
toast.success(`获取到 ${models.length} 个可用模型`)
}
} else {
toast.error("获取模型列表失败: " + resp.message)
setModelList([])
}
})
setLoadingModels(false)
}
const handleSave = async () => {
if (!model?.id) {
toast.error("模型信息不完整")
return
}
if (!apiToken.trim()) {
toast.error("请输入 API Token")
return
}
if (!selectedModel.trim()) {
toast.error("请选择模型名称")
return
}
if (!baseUrl.trim()) {
toast.error("请输入模型 API 地址")
return
}
setSaving(true)
// 先进行健康检查
const provider = model.provider || "BaiZhiCloud"
const healthCheckData = {
api_key: apiToken.trim(),
model: selectedModel.trim(),
base_url: baseUrl.trim(),
interface_type: interfaceType,
provider: provider,
}
await apiRequest('v1UsersModelsHealthCheckCreate', healthCheckData, [], async (resp) => {
if (resp.code === 0) {
if (resp.data?.success) {
// 健康检查通过,继续保存
const requestData: any = {
api_key: apiToken.trim(),
model: selectedModel.trim(),
base_url: baseUrl.trim(),
interface_type: interfaceType,
}
// 如果 provider 存在,也一起更新
if (model.provider) {
requestData.provider = model.provider
}
await apiRequest('v1UsersModelsUpdate', requestData, [model.id!], (resp) => {
if (resp.code === 0) {
toast.success("模型修改成功")
setApiToken("")
setBaseUrl("")
setSelectedModel("")
setInterfaceType(ConstsInterfaceType.InterfaceTypeOpenAIChat)
setModelList([])
onOpenChange(false)
onRefresh?.()
}
})
} else {
toast.error("模型配置检查失败: " + resp.data?.error)
}
}
})
setSaving(false)
}
const handleCancel = () => {
setApiToken("")
setBaseUrl("")
setSelectedModel("")
setInterfaceType(ConstsInterfaceType.InterfaceTypeOpenAIChat)
setModelList([])
onOpenChange(false)
}
// 对模型列表进行分组和排序
const getGroupedModels = () => {
const groups: Record<string, DomainProviderModelListItem[]> = {}
modelList.forEach((item) => {
const modelName = item.model || ""
const parts = modelName.split("-")
const groupKey = parts.length > 0 ? parts[0] : "其他"
if (!groups[groupKey]) {
groups[groupKey] = []
}
groups[groupKey].push(item)
})
// 对每个组内的模型按字符串排序
Object.keys(groups).forEach((key) => {
groups[key].sort((a, b) => {
const aName = a.model || ""
const bName = b.model || ""
return aName.localeCompare(bName)
})
})
// 对组名进行排序
const sortedGroupKeys = Object.keys(groups).sort()
return { groups, sortedGroupKeys }
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>修改 AI 大模型</DialogTitle>
</DialogHeader>
<div className="grid gap-4">
<Field>
<FieldLabel>接口格式</FieldLabel>
<FieldContent>
<Select
value={interfaceType}
onValueChange={(value) => setInterfaceType(value as ConstsInterfaceType)}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="请选择接口格式类型" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ConstsInterfaceType.InterfaceTypeOpenAIResponse}>
OpenAI Responses
</SelectItem>
<SelectItem value={ConstsInterfaceType.InterfaceTypeOpenAIChat}>
OpenAI Chat
</SelectItem>
<SelectItem value={ConstsInterfaceType.InterfaceTypeAnthropic}>
Anthropic
</SelectItem>
</SelectContent>
</Select>
</FieldContent>
</Field>
<Field>
<FieldLabel>模型 API 地址</FieldLabel>
<FieldContent>
<Input
placeholder="请输入模型 API 地址"
value={baseUrl}
onChange={(e) => setBaseUrl(e.target.value)}
/>
</FieldContent>
<FieldDescription>
{getModelUrlDescription(baseUrl, interfaceType)}
</FieldDescription>
</Field>
<Field>
<FieldLabel>API Token</FieldLabel>
<FieldContent>
<Input
placeholder="请输入 API Token"
value={apiToken}
onChange={(e) => setApiToken(e.target.value)}
/>
</FieldContent>
</Field>
<Field>
<FieldLabel>模型名称</FieldLabel>
<FieldContent>
<Select
value={selectedModel}
onValueChange={setSelectedModel}
onOpenChange={(open) => {
if (open && apiToken.trim() && !loadingModels) {
fetchModelList()
}
}}
disabled={loadingModels || !apiToken.trim()}
>
<SelectTrigger className="w-full">
<SelectValue placeholder={loadingModels ? "加载中..." : selectedModel || "请选择模型"} />
</SelectTrigger>
<SelectContent>
{loadingModels ? (
<div className="flex items-center justify-center py-4">
<Spinner />
<span className="ml-2 text-sm text-muted-foreground">加载模型中...</span>
</div>
) : modelList.length > 0 ? (() => {
const { groups, sortedGroupKeys } = getGroupedModels()
return (
<>
{sortedGroupKeys.map((groupKey) => (
<SelectGroup key={groupKey}>
<SelectLabel>{groupKey}</SelectLabel>
{groups[groupKey].map((item, index) => (
<SelectItem key={`${groupKey}-${index}`} value={item.model || ""}>
{item.model}
</SelectItem>
))}
</SelectGroup>
))}
</>
)
})() : selectedModel ? (
<SelectItem value={selectedModel}>
{selectedModel}
</SelectItem>
) : (
<div className="py-4 text-center text-sm text-muted-foreground">
{apiToken.trim() ? "暂无可用模型" : "请先输入 API Token"}
</div>
)}
</SelectContent>
</Select>
</FieldContent>
</Field>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCancel} disabled={saving}>
取消
</Button>
<Button onClick={handleSave} disabled={!selectedModel.trim() || saving}>
{saving && <Spinner className="size-4" />}
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,337 @@
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import {
Card,
CardAction,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip"
import {
Item,
ItemActions,
ItemContent,
ItemDescription,
ItemGroup,
ItemTitle,
} from "@/components/ui/item"
import {
HardDrive,
MoreVertical,
} from "lucide-react"
import { apiRequest } from "@/utils/requestUtils"
import { getHostBadges } from "@/utils/common"
import { toast } from "sonner"
import { type DomainHost, ConstsOwnerType, TypesVirtualMachineStatus } from "@/api/Api"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from "@/components/ui/empty"
import { Spinner } from "@/components/ui/spinner"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { IconAlertHexagon, IconPencil, IconStar, IconTrash } from "@tabler/icons-react"
import { useCommonData } from "../data-provider"
export default function Hosts() {
const [open, setOpen] = useState(false)
const [command, setCommand] = useState<string>("")
const [loadingCommand, setLoadingCommand] = useState(false)
const [remarkDialogOpen, setRemarkDialogOpen] = useState(false)
const [editingHost, setEditingHost] = useState<DomainHost | null>(null)
const [remarkInput, setRemarkInput] = useState("")
const [remarkLoading, setRemarkLoading] = useState(false)
const { hosts, reloadHosts, loadingHosts } = useCommonData();
const fetchInstallCommand = async () => {
setLoadingCommand(true)
await apiRequest('v1UsersHostsInstallCommandList', {}, [], (resp) => {
if (resp.code === 0) {
setCommand(resp.data?.command || "")
} else {
toast.error("获取安装命令失败: " + resp.message)
}
})
setLoadingCommand(false)
}
useEffect(() => {
if (open) {
fetchInstallCommand()
}
}, [open])
const handleCopy = async () => {
if (!command) return
try {
await navigator.clipboard.writeText(command)
toast.success("命令已复制到剪贴板")
} catch (error) {
toast.error("复制失败")
console.error("复制失败:", error)
}
}
const handleDelete = (host: DomainHost) => {
if (!host.id) {
toast.error("宿主机信息不完整")
return
}
apiRequest('v1UsersHostsDelete', {}, [host.id], (resp) => {
if (resp.code === 0) {
toast.success("宿主机移除成功")
reloadHosts()
} else {
toast.error("移除宿主机失败: " + resp.message)
}
})
}
const handleSetDefault = async (host: DomainHost) => {
if (!host.id) {
toast.error("宿主机信息不完整")
return
}
await apiRequest('v1UsersHostsUpdate', { is_default: true }, [host.id], (resp) => {
if (resp.code === 0) {
toast.success("设置成功")
} else {
toast.error("设置默认宿主机失败: " + resp.message)
}
})
reloadHosts?.()
}
const handleOpenRemarkDialog = (host: DomainHost) => {
setEditingHost(host)
setRemarkInput(host.remark || "")
setRemarkDialogOpen(true)
}
const handleUpdateRemark = async () => {
if (!editingHost?.id) {
toast.error("宿主机信息不完整")
return
}
setRemarkLoading(true)
await apiRequest('v1UsersHostsUpdate', { remark: remarkInput }, [editingHost.id], (resp) => {
if (resp.code === 0) {
toast.success("备注修改成功")
setRemarkDialogOpen(false)
setEditingHost(null)
setRemarkInput("")
reloadHosts?.()
} else {
toast.error("修改备注失败: " + resp.message)
}
})
setRemarkLoading(false)
}
const loadHosts = () => {
return (
<Empty className="border border-dashed">
<EmptyHeader>
<EmptyMedia variant="icon">
<Spinner className="size-6" />
</EmptyMedia>
<EmptyDescription>
正在加载宿主机列表...
</EmptyDescription>
</EmptyHeader>
</Empty>
)
}
const noHosts = () => {
return (
<Empty className="border border-dashed">
<EmptyHeader>
<EmptyMedia variant="icon">
<IconAlertHexagon />
</EmptyMedia>
<EmptyDescription>
暂无配置,请先绑定宿主机
</EmptyDescription>
</EmptyHeader>
</Empty>
)
}
const listHosts = () => {
return (
<ItemGroup className="flex flex-col gap-4">
{hosts.map((host: DomainHost) => (
<Item key={host.id} variant="outline" className="hover:border-primary/50" size="sm">
<ItemContent>
<ItemTitle className="break-all">
{host.remark || `${host.name}-${host.external_ip}`}
{getHostBadges(host)}
</ItemTitle>
<ItemDescription className="hidden md:block">
共 {host.virtualmachines?.length || 0} 个开发环境,{host.virtualmachines?.filter((vm) => vm.status !== TypesVirtualMachineStatus.VirtualMachineStatusOffline).length || 0} 个正在使用
</ItemDescription>
</ItemContent>
<ItemActions>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm">
<MoreVertical className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleSetDefault(host)} disabled={host.is_default}>
<IconStar />
设为默认
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleOpenRemarkDialog(host)} disabled={host.owner?.type !== ConstsOwnerType.OwnerTypePrivate}>
<IconPencil />
修改备注
</DropdownMenuItem>
<AlertDialog>
<AlertDialogTrigger asChild>
<DropdownMenuItem
className="text-destructive"
onSelect={(e) => { e.preventDefault() }}
disabled={host.owner?.type !== ConstsOwnerType.OwnerTypePrivate}
>
<IconTrash />
移除
</DropdownMenuItem>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确认移除</AlertDialogTitle>
<AlertDialogDescription>
确定要移除宿主机 "{host.remark || `${host.name}-${host.external_ip}`}" 吗?此操作不可撤销。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
handleDelete(host)
}}
>
确认移除
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</DropdownMenuContent>
</DropdownMenu>
</ItemActions>
</Item>
))}
</ItemGroup>
)
}
return (
<>
<Card className="w-full shadow-none">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<HardDrive />
开发环境宿主机
</CardTitle>
<CardDescription>
用于在宿主机上创建开发环境
</CardDescription>
<CardAction>
<Button variant={"outline"} size="sm" onClick={() => setOpen(true)}>绑定</Button>
</CardAction>
</CardHeader>
<CardContent>
{loadingHosts ? loadHosts() : hosts.length === 0 ? noHosts() : listHosts()}
</CardContent>
</Card>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="sm:max-w-3xl">
<DialogHeader>
<DialogTitle>绑定宿主机</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
以 root 权限登录你的 Linux 服务器,并执行以下命令
</p>
<Tooltip>
<TooltipTrigger asChild>
<pre
className="bg-muted p-4 rounded-md whitespace-pre-wrap break-words text-sm cursor-pointer hover:text-primary"
onClick={handleCopy}
>
<code className="code-font">{loadingCommand ? "正在生成安装命令..." : command}</code>
</pre>
</TooltipTrigger>
<TooltipContent>
<p>复制命令</p>
</TooltipContent>
</Tooltip>
<p className="text-sm text-muted-foreground">
执行完毕后刷新页面,你将会看到宿主机信息
</p>
</div>
</DialogContent>
</Dialog>
<Dialog open={remarkDialogOpen} onOpenChange={setRemarkDialogOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>修改备注</DialogTitle>
<DialogDescription>
为宿主机 "{editingHost?.remark || `${editingHost?.name}-${editingHost?.external_ip}`}" 设置备注
</DialogDescription>
</DialogHeader>
<Input
id="remark"
placeholder="请输入备注信息"
value={remarkInput}
onChange={(e) => setRemarkInput(e.target.value)}
/>
<DialogFooter>
<Button variant="outline" onClick={() => setRemarkDialogOpen(false)}>
取消
</Button>
<Button onClick={handleUpdateRemark} disabled={remarkLoading}>
{remarkLoading ? "保存中..." : "保存"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
)
}
@@ -0,0 +1,461 @@
import { useState } from "react"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import {
Card,
CardAction,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import {
Item,
ItemActions,
ItemContent,
ItemDescription,
ItemGroup,
ItemMedia,
ItemTitle,
} from "@/components/ui/item"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import AddIdentity from "@/components/console/settings/add-identity"
import EditIdentity from "@/components/console/settings/edit-identity"
import { ChevronDown, MoreVertical } from "lucide-react"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { type DomainGitIdentity, ConstsGitPlatform } from "@/api/Api"
import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia } from "@/components/ui/empty"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Badge } from "@/components/ui/badge"
import { IconPasswordFingerprint, IconPencil, IconPlugConnected, IconTrash } from "@tabler/icons-react"
import { getGitPlatformIcon, getGithubAppInstallUrl } from "@/utils/common"
import Icon from "@/components/common/Icon"
import { useCommonData } from "../data-provider"
import { Spinner } from "@/components/ui/spinner"
export default function Identities() {
const githubAppInstallUrl = getGithubAppInstallUrl()
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [giteeBindLoading, setGiteeBindLoading] = useState(false)
const [giteaBindLoading, setGiteaBindLoading] = useState(false)
const [gitlabBindLoading, setGitlabBindLoading] = useState(false)
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
const [editingIdentity, setEditingIdentity] = useState<DomainGitIdentity | null>(null)
const { identities, reloadIdentities, loadingIdentities } = useCommonData();
const hasGitHubIdentity = identities.some(
(identity) => identity.platform === ConstsGitPlatform.GitPlatformGithub
)
const hasGiteeIdentity = identities.some(
(identity) => identity.platform === ConstsGitPlatform.GitPlatformGitee
)
const hasGiteaIdentity = identities.some(
(identity) => identity.platform === ConstsGitPlatform.GitPlatformGitea
)
const hasGitLabIdentity = identities.some(
(identity) => identity.platform === ConstsGitPlatform.GitPlatformGitLab
)
const handleGiteeBind = () => {
setGiteeBindLoading(true)
apiRequest('v1GiteeAuthorizeUrlList', {}, [], (resp) => {
setGiteeBindLoading(false)
if (resp.code === 0 && resp.data?.url) {
const popup = window.open(resp.data.url, "_blank")
if (popup) {
const checkClosed = setInterval(() => {
if (popup.closed) {
clearInterval(checkClosed)
reloadIdentities()
}
}, 500)
}
} else {
toast.error(resp.message || "获取 Gitee 授权地址失败")
}
}, () => {
setGiteeBindLoading(false)
})
}
const handleGiteaBind = () => {
setGiteaBindLoading(true)
apiRequest('v1GiteaAuthorizeUrlList', {}, [], (resp) => {
setGiteaBindLoading(false)
if (resp.code === 0 && resp.data?.url) {
const popup = window.open(resp.data.url, "_blank")
if (popup) {
const checkClosed = setInterval(() => {
if (popup.closed) {
clearInterval(checkClosed)
reloadIdentities()
}
}, 500)
}
} else {
toast.error(resp.message || "获取 Gitea 授权地址失败")
}
}, () => {
setGiteaBindLoading(false)
})
}
const handleGitLabBind = () => {
setGitlabBindLoading(true)
apiRequest('v1GitlabAuthorizeUrlList', { base: 'https://gitlab.com' }, [], (resp) => {
setGitlabBindLoading(false)
if (resp.code === 0 && resp.data?.url) {
const popup = window.open(resp.data.url, "_blank")
if (popup) {
const checkClosed = setInterval(() => {
if (popup.closed) {
clearInterval(checkClosed)
reloadIdentities()
}
}, 500)
}
} else {
toast.error(resp.message || "获取 GitLab 授权地址失败")
}
}, () => {
setGitlabBindLoading(false)
})
}
const handleEdit = (identity: DomainGitIdentity) => {
setEditingIdentity(identity)
setIsEditDialogOpen(true)
}
const handleEditCancel = () => {
setEditingIdentity(null)
setIsEditDialogOpen(false)
}
const handleDelete = (identity: DomainGitIdentity) => {
if (!identity.id) {
toast.error("身份信息不完整")
return
}
apiRequest('v1UsersGitIdentitiesDelete', {}, [identity.id], (resp) => {
if (resp.code === 0) {
toast.success("身份移除成功")
reloadIdentities()
} else {
toast.error("移除身份失败: " + resp.message)
}
})
}
const loadIdentities = () => {
return (
<Empty className="border border-dashed">
<EmptyHeader>
<EmptyMedia variant="icon">
<Spinner className="size-6" />
</EmptyMedia>
</EmptyHeader>
<EmptyContent>
<EmptyDescription>
正在加载身份列表...
</EmptyDescription>
</EmptyContent>
</Empty>
)
}
const githubConnectCard = () => (
<Item variant="outline" className="hover:border-primary/50 border-dashed" size="sm">
<ItemMedia className="hidden sm:flex">
<Avatar>
<AvatarFallback>
<Icon name="GitHub-Uncolor" className="fill-foreground size-4" />
</AvatarFallback>
</Avatar>
</ItemMedia>
<ItemContent>
<ItemTitle className="flex items-center gap-2 break-all">
GitHub
<Badge variant="secondary" className="font-normal">未绑定</Badge>
</ItemTitle>
<ItemDescription className="hidden md:block">
点击绑定 GitHub 身份,用于同步代码、提交代码等操作
</ItemDescription>
</ItemContent>
<ItemActions>
<Button
variant="outline"
size="sm"
onClick={() => githubAppInstallUrl && window.open(githubAppInstallUrl, "_blank")}
disabled={!githubAppInstallUrl}
>
绑定
</Button>
</ItemActions>
</Item>
)
const giteeConnectCard = () => (
<Item variant="outline" className="hover:border-primary/50 border-dashed" size="sm">
<ItemMedia className="hidden sm:flex">
<Avatar>
<AvatarFallback>
<Icon name="Gitee" className="size-4" />
</AvatarFallback>
</Avatar>
</ItemMedia>
<ItemContent>
<ItemTitle className="flex items-center gap-2 break-all">
Gitee
<Badge variant="secondary" className="font-normal">未绑定</Badge>
</ItemTitle>
<ItemDescription className="hidden md:block">
点击绑定 Gitee 身份,用于同步代码、提交代码等操作
</ItemDescription>
</ItemContent>
<ItemActions>
<Button
variant="outline"
size="sm"
onClick={handleGiteeBind}
disabled={giteeBindLoading}
>
{giteeBindLoading ? "获取中..." : "绑定"}
</Button>
</ItemActions>
</Item>
)
const giteaConnectCard = () => (
<Item variant="outline" className="hover:border-primary/50 border-dashed" size="sm">
<ItemMedia className="hidden sm:flex">
<Avatar>
<AvatarFallback>
<Icon name="Gitea" className="size-4" />
</AvatarFallback>
</Avatar>
</ItemMedia>
<ItemContent>
<ItemTitle className="flex items-center gap-2 break-all">
Gitea
<Badge variant="secondary" className="font-normal">未绑定</Badge>
</ItemTitle>
<ItemDescription className="hidden md:block">
点击绑定 Gitea 身份,用于同步代码、提交代码等操作
</ItemDescription>
</ItemContent>
<ItemActions>
<Button
variant="outline"
size="sm"
onClick={handleGiteaBind}
disabled={giteaBindLoading}
>
{giteaBindLoading ? "获取中..." : "绑定"}
</Button>
</ItemActions>
</Item>
)
const gitlabConnectCard = () => (
<Item variant="outline" className="hover:border-primary/50 border-dashed" size="sm">
<ItemMedia className="hidden sm:flex">
<Avatar>
<AvatarFallback>
<Icon name="GitLab" className="size-4" />
</AvatarFallback>
</Avatar>
</ItemMedia>
<ItemContent>
<ItemTitle className="flex items-center gap-2 break-all">
GitLab
<Badge variant="secondary" className="font-normal">未绑定</Badge>
</ItemTitle>
<ItemDescription className="hidden md:block">
点击绑定 GitLab 身份,用于同步代码、提交代码等操作
</ItemDescription>
</ItemContent>
<ItemActions>
<Button
variant="outline"
size="sm"
onClick={handleGitLabBind}
disabled={gitlabBindLoading}
>
{gitlabBindLoading ? "获取中..." : "绑定"}
</Button>
</ItemActions>
</Item>
)
const identityItems = () =>
identities.map((identity) => (
<Item key={identity.id} variant="outline" className="hover:border-primary/50" size="sm">
<ItemMedia className="hidden sm:flex">
<Avatar>
<AvatarFallback>
{getGitPlatformIcon(identity.platform)}
</AvatarFallback>
</Avatar>
</ItemMedia>
<ItemContent>
<ItemTitle className="break-all">
{identity.remark || identity.username}
</ItemTitle>
<ItemDescription className="hidden md:block">
{identity.base_url}
</ItemDescription>
</ItemContent>
<ItemActions>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm">
<MoreVertical className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleEdit(identity)}>
<IconPencil />
修改
</DropdownMenuItem>
<AlertDialog>
<AlertDialogTrigger asChild>
<DropdownMenuItem
className="text-destructive"
onSelect={(e) => { e.preventDefault() }}
>
<IconTrash />
移除
</DropdownMenuItem>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确认移除</AlertDialogTitle>
<AlertDialogDescription>
确定要移除身份 "{identity.username}" 吗?此操作不可撤销。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
handleDelete(identity)
}}
>
确认移除
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</DropdownMenuContent>
</DropdownMenu>
</ItemActions>
</Item>
))
return (
<Card className="w-full shadow-none">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<IconPasswordFingerprint />
Git 平台身份凭证
</CardTitle>
<CardDescription>
用于在 Git 仓库中提交代码和拉取代码的身份凭证
</CardDescription>
<CardAction>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
绑定
<ChevronDown className="ml-1 size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => githubAppInstallUrl && window.open(githubAppInstallUrl, "_blank")}
disabled={!githubAppInstallUrl}
>
<Icon name="GitHub-Uncolor" className="fill-foreground size-4" />
绑定 GitHub 身份
</DropdownMenuItem>
<DropdownMenuItem
onClick={handleGiteeBind}
disabled={giteeBindLoading}
>
<Icon name="Gitee" className="size-4" />
绑定 Gitee 身份
</DropdownMenuItem>
<DropdownMenuItem
onClick={handleGiteaBind}
disabled={giteaBindLoading}
>
<Icon name="Gitea" className="size-4" />
绑定 Gitea 身份
</DropdownMenuItem>
<DropdownMenuItem
onClick={handleGitLabBind}
disabled={gitlabBindLoading}
>
<Icon name="GitLab" className="size-4" />
绑定 GitLab 身份
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setIsDialogOpen(true)}>
<IconPlugConnected className="size-4" />
绑定其他平台
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<AddIdentity
open={isDialogOpen}
onOpenChange={setIsDialogOpen}
onRefresh={reloadIdentities}
/>
</CardAction>
</CardHeader>
<CardContent>
{loadingIdentities ? (
loadIdentities()
) : (
<ItemGroup className="flex flex-col gap-4">
{!hasGitHubIdentity && githubConnectCard()}
{!hasGiteeIdentity && giteeConnectCard()}
{!hasGiteaIdentity && giteaConnectCard()}
{!hasGitLabIdentity && gitlabConnectCard()}
{identityItems()}
</ItemGroup>
)}
</CardContent>
<EditIdentity
open={isEditDialogOpen}
onOpenChange={(open) => {
if (!open) {
handleEditCancel()
}
}}
identity={editingIdentity}
onRefresh={reloadIdentities}
/>
</Card>
)
}
@@ -0,0 +1,250 @@
import { useState } from "react"
import Icon from "@/components/common/Icon"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import {
Card,
CardAction,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import {
Item,
ItemActions,
ItemContent,
ItemDescription,
ItemGroup,
ItemMedia,
ItemTitle,
} from "@/components/ui/item"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { getImageShortName, getOSFromImageName, getOwnerTypeBadge } from "@/utils/common"
import AddImage from "../settings/add-image"
import EditImage from "../settings/edit-image"
import {
Box,
MoreVertical,
} from "lucide-react"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { ConstsOwnerType, type DomainImage } from "@/api/Api"
import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia } from "@/components/ui/empty"
import { Spinner } from "@/components/ui/spinner"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { IconAlertHexagon, IconPencil, IconStar, IconTrash } from "@tabler/icons-react"
import { useCommonData } from "../data-provider"
import { Badge } from "@/components/ui/badge"
export default function Images() {
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
const [editingImage, setEditingImage] = useState<DomainImage | null>(null)
const { images, reloadImages, loadingImages } = useCommonData();
const handleEdit = (image: DomainImage) => {
setEditingImage(image)
setIsEditDialogOpen(true)
}
const handleEditCancel = () => {
setEditingImage(null)
setIsEditDialogOpen(false)
}
const handleDelete = (image: DomainImage) => {
if (!image.id) {
toast.error("镜像信息不完整")
return
}
apiRequest('v1UsersImagesDelete', {}, [image.id], (resp) => {
if (resp.code === 0) {
toast.success("镜像移除成功")
reloadImages()
} else {
toast.error("移除镜像失败: " + resp.message)
}
})
}
const handleSetDefault = async (image: DomainImage) => {
if (!image.id) {
toast.error("镜像信息不完整")
return
}
await apiRequest('v1UsersImagesUpdate', { is_default: true }, [image.id], (resp) => {
if (resp.code === 0) {
toast.success("设置成功")
} else {
toast.error("设置默认镜像失败: " + resp.message)
}
})
reloadImages()
}
const loadImages = () => {
return (
<Empty className="border border-dashed">
<EmptyHeader>
<EmptyMedia variant="icon">
<Spinner className="size-6" />
</EmptyMedia>
</EmptyHeader>
<EmptyContent>
<EmptyDescription>
正在加载镜像列表...
</EmptyDescription>
</EmptyContent>
</Empty>
)
}
const noImages = () => {
return (
<Empty className="border border-dashed">
<EmptyHeader>
<EmptyMedia variant="icon">
<IconAlertHexagon />
</EmptyMedia>
</EmptyHeader>
<EmptyContent>
<EmptyDescription>
暂无配置,请先绑定镜像
</EmptyDescription>
</EmptyContent>
</Empty>
)
}
const listImages = () => {
return (
<ItemGroup className="flex flex-col gap-4">
{images.map((image) => (
<Item key={image.name} variant="outline" className="hover:border-primary/50" size="sm">
<ItemMedia className="hidden sm:flex">
<Avatar>
<AvatarFallback>
<Icon name={getOSFromImageName(image.name || '')} className="size-4" />
</AvatarFallback>
</Avatar>
</ItemMedia>
<ItemContent>
<ItemTitle className="break-all">
{image.remark || getImageShortName(image.name || '')}
{image.is_default && <Badge>默认</Badge>}
{getOwnerTypeBadge(image.owner)}
</ItemTitle>
<ItemDescription className="hidden md:block">
{image.name}
</ItemDescription>
</ItemContent>
<ItemActions>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm">
<MoreVertical className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleSetDefault(image)} disabled={image.is_default}>
<IconStar />
设为默认
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleEdit(image)} disabled={image.owner?.type !== ConstsOwnerType.OwnerTypePrivate}>
<IconPencil />
修改
</DropdownMenuItem>
<AlertDialog>
<AlertDialogTrigger asChild>
<DropdownMenuItem
className="text-destructive"
onSelect={(e) => { e.preventDefault() }}
>
<IconTrash />
移除
</DropdownMenuItem>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确认移除</AlertDialogTitle>
<AlertDialogDescription>
确定要移除镜像 "{image.remark || getImageShortName(image.name || '')}" 吗?此操作不可撤销。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
handleDelete(image)
}}
>
确认移除
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</DropdownMenuContent>
</DropdownMenu>
</ItemActions>
</Item>)
)}
</ItemGroup>
)
}
return (
<Card className="w-full shadow-none">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Box />
系统镜像
</CardTitle>
<CardDescription>
使用 Docker 镜像,用于构建开发环境
</CardDescription>
<CardAction>
<AddImage
open={isDialogOpen}
onOpenChange={setIsDialogOpen}
onRefresh={reloadImages}
/>
</CardAction>
</CardHeader>
<CardContent>
{loadingImages ? loadImages() : images.length === 0 ? noImages() : listImages()}
</CardContent>
<EditImage
open={isEditDialogOpen}
onOpenChange={(open) => {
if (!open) {
handleEditCancel()
}
}}
image={editingImage ? { id: editingImage.id || '', image_name: editingImage.name || '', remark: editingImage.remark || '' } : null}
onRefresh={reloadImages}
/>
</Card>
)
}
@@ -0,0 +1,322 @@
import { useState } from "react"
import { Button } from "@/components/ui/button"
import {
Card,
CardAction,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import {
Bot,
MoreVertical,
} from "lucide-react"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import {
Item,
ItemActions,
ItemContent,
ItemGroup,
ItemMedia,
ItemTitle,
} from "@/components/ui/item"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { apiRequest } from "@/utils/requestUtils"
import { toast } from "sonner"
import { ConstsOwnerType, type DomainModel } from "@/api/Api"
import AddModel from "../settings/add-model"
import EditModel from "../settings/edit-model"
import Icon from "@/components/common/Icon"
import { getBrandFromModelName, getInterfaceTypeBadge, getModelHealthBadge, getOwnerTypeBadge } from "@/utils/common"
import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia } from "@/components/ui/empty"
import { Spinner } from "@/components/ui/spinner"
import { Badge } from "@/components/ui/badge"
import { IconAlertHexagon, IconCheck, IconHeartRateMonitor, IconLoader, IconPencil, IconStar, IconTrash, IconX } from "@tabler/icons-react"
import { useCommonData } from "../data-provider"
export default function Models() {
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
const [selectedModel, setSelectedModel] = useState<DomainModel | undefined>(undefined)
const [isCheckDialogOpen, setIsCheckDialogOpen] = useState(false)
const [checkingModel, setCheckingModel] = useState<DomainModel | undefined>(undefined)
const [checkStatus, setCheckStatus] = useState<'checking' | 'success' | 'error'>('checking')
const [checkMessage, setCheckMessage] = useState<string>('')
const { models, reloadModels, loadingModels } = useCommonData();
const handleSetDefault = async (model: DomainModel) => {
if (!model.id) {
toast.error("模型信息不完整")
return
}
await apiRequest('v1UsersModelsUpdate', {
is_default: true,
}, [model.id], (resp) => {
if (resp.code === 0) {
toast.success("设置成功")
} else {
toast.error("设置默认模型失败: " + resp.message)
}
})
reloadModels?.()
}
const handleEdit = (model: DomainModel) => {
setSelectedModel(model)
setIsEditDialogOpen(true)
}
const handleDelete = (model: DomainModel) => {
if (!model.id) {
toast.error("模型信息不完整")
return
}
apiRequest('v1UsersModelsDelete', {}, [model.id], (resp) => {
if (resp.code === 0) {
toast.success("模型移除成功")
reloadModels?.()
} else {
toast.error("移除模型失败: " + resp.message)
}
})
}
const handleCheck = async (model: DomainModel) => {
if (!model.id) {
toast.error("模型信息不完整")
return
}
// 打开检查对话框
setCheckingModel(model)
setCheckStatus('checking')
setCheckMessage('正在检查模型配置...')
setIsCheckDialogOpen(true)
await apiRequest('v1UsersModelsHealthCheckDetail', {}, [model.id], (resp) => {
if (resp.code === 0) {
if (resp.data?.success) {
setCheckStatus('success')
setCheckMessage('模型连接正常')
toast.success("检查成功")
reloadModels?.()
} else {
setCheckStatus('error')
setCheckMessage(resp.data?.error || '检查失败')
toast.error("检查失败: " + resp.data?.error)
}
} else {
setCheckStatus('error')
setCheckMessage(resp.message || '检查失败')
toast.error("检查失败: " + resp.message)
}
})
}
const loadModels = () => {
return (
<Empty className="border border-dashed">
<EmptyHeader>
<EmptyMedia variant="icon">
<Spinner className="size-6" />
</EmptyMedia>
</EmptyHeader>
<EmptyContent>
<EmptyDescription>
正在加载模型列表...
</EmptyDescription>
</EmptyContent>
</Empty>
)
}
const noModels = () => {
return (
<Empty className="border border-dashed">
<EmptyHeader>
<EmptyMedia variant="icon">
<IconAlertHexagon />
</EmptyMedia>
</EmptyHeader>
<EmptyContent>
<EmptyDescription>
暂无配置,请先绑定模型
</EmptyDescription>
</EmptyContent>
</Empty>
)
}
const listModels = () => {
return (
<ItemGroup className="flex flex-col gap-4">
{models.map((model) => (
<Item key={model.id} variant="outline" className="hover:border-primary/50" size="sm">
<ItemMedia className="hidden md:flex">
<Avatar>
<AvatarFallback>
<Icon name={getBrandFromModelName(model.model || '')} className="size-4" />
</AvatarFallback>
</Avatar>
</ItemMedia>
<ItemContent>
<ItemTitle className="break-all">
{getModelHealthBadge(model)}
{model.model || '未知模型'}
{model.is_default && <Badge>默认</Badge>}
{getInterfaceTypeBadge(model.interface_type)}
{getOwnerTypeBadge(model.owner)}
</ItemTitle>
</ItemContent>
<ItemActions>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm">
<MoreVertical className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleSetDefault(model)} disabled={model.is_default}>
<IconStar />
设为默认
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleCheck(model)}>
<IconHeartRateMonitor />
检查
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleEdit(model)} disabled={model.owner?.type !== ConstsOwnerType.OwnerTypePrivate}>
<IconPencil />
修改
</DropdownMenuItem>
<AlertDialog>
<AlertDialogTrigger asChild>
<DropdownMenuItem
className="text-destructive"
onSelect={(e) => { e.preventDefault() }}
disabled={model.owner?.type !== ConstsOwnerType.OwnerTypePrivate}
>
<IconTrash />
移除
</DropdownMenuItem>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确认移除</AlertDialogTitle>
<AlertDialogDescription>
确定要移除模型 "{model.model || '未知模型'}" 吗?此操作不可撤销。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
handleDelete(model)
}}
>
确认移除
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</DropdownMenuContent>
</DropdownMenu>
</ItemActions>
</Item>
))}
</ItemGroup>
)
}
return (
<Card className="w-full shadow-none">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Bot />
AI 大模型
</CardTitle>
<CardDescription>
配置 AI 大模型,用于代码生成和分析项目
</CardDescription>
<CardAction>
<AddModel
open={isDialogOpen}
onOpenChange={setIsDialogOpen}
onRefresh={reloadModels}
/>
</CardAction>
</CardHeader>
<CardContent>
{loadingModels ? loadModels() : models.length === 0 ? noModels() : listModels()}
</CardContent>
<EditModel
open={isEditDialogOpen}
onOpenChange={setIsEditDialogOpen}
model={selectedModel}
onRefresh={reloadModels}
/>
{/* 模型检查对话框 */}
<Dialog open={isCheckDialogOpen} onOpenChange={(open) => {
// 只有在检查完成时才允许关闭
if (checkStatus !== 'checking') {
setIsCheckDialogOpen(open)
}
}}>
<DialogContent>
<DialogHeader>
<DialogTitle>检查模型配置</DialogTitle>
<DialogDescription>
检查模型 "{checkingModel?.model || '未知模型'}" 的配置是否正确
</DialogDescription>
</DialogHeader>
<div className="border border-dashed rounded-md p-4 items-center justify-center flex flex-col gap-4">
<div className="flex flex-row gap-2 items-center justify-center py-2">
<div className="flex items-center justify-center bg-muted rounded-md p-2">
{checkStatus === 'checking' && <IconLoader className="size-6 animate-spin" />}
{checkStatus === 'success' && <IconCheck className="size-6" />}
{checkStatus === 'error' && <IconX className="size-6" />}
</div>
<div className="text-md font-bold text-center">
{checkStatus === 'checking' && '正在检查...'}
{checkStatus === 'success' && '检查成功'}
{checkStatus === 'error' && '检查失败'}
</div>
</div>
<div className="break-all text-xs text-muted-foreground max-h-[100px] overflow-y-auto text-center">
{checkMessage}
</div>
</div>
</DialogContent>
</Dialog>
</Card>
)
}
@@ -0,0 +1,364 @@
import { Button } from "@/components/ui/button";
import {
Empty,
EmptyContent,
EmptyDescription,
EmptyHeader,
EmptyMedia,
EmptyTitle,
} from "@/components/ui/empty";
import { apiRequest } from "@/utils/requestUtils";
import {
IconCircle,
IconCircleCheck,
IconClockHour4,
IconDotsVertical,
IconFolderOpen,
IconReload,
IconTerminal2
} from "@tabler/icons-react"
import { CirclePlusIcon, MonitorCloud, MoreVertical, Server } from "lucide-react";
import { toast } from "sonner";
import { Spinner } from "@/components/ui/spinner";
import { useEffect, useState, useMemo } from "react";
import {
ItemGroup,
Item,
ItemContent,
ItemTitle,
ItemDescription,
ItemActions,
ItemMedia,
} from "@/components/ui/item";
import CreateVM from "@/components/console/vm/vm-add";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import Icon from "@/components/common/Icon";
import { getOSFromImageName, humanTime, translateStatus, getStatusBadgeProps, formatMemory, renderHoverCardContent, getVmMessage, getLastCondition } from "@/utils/common";
import { Badge } from "@/components/ui/badge";
import dayjs from "dayjs";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { IconTrash } from "@tabler/icons-react";
import { type DomainVirtualMachine, GitInChaitinNetAiMonkeycodeMonkeycodeAiEntTypesConditionType, TypesVirtualMachineStatus } from "@/api/Api";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { HoverCard, HoverCardTrigger } from "@/components/ui/hover-card";
import { useCommonData } from "@/components/console/data-provider";
import { VmRenewDialog } from "@/components/console/vm/vm-renew";
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Switch } from "@/components/ui/switch";
export default function VmsPage() {
const [createDialogOpen, setCreateDialogOpen] = useState(false)
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
const [vmToDelete, setVmToDelete] = useState<DomainVirtualMachine | null>(null)
const [showOfflineVms, setShowOfflineVms] = useState(false)
const [renewDialogOpen, setRenewDialogOpen] = useState(false)
const [vmToRenew, setVmToRenew] = useState<DomainVirtualMachine | null>(null)
const { reloadHosts, loadingHosts, hostsInited, vms } = useCommonData();
const showVms = useMemo(() => {
if (showOfflineVms) {
return vms
} else {
return vms.filter(vm => vm.status !== TypesVirtualMachineStatus.VirtualMachineStatusOffline)
}
}, [vms, showOfflineVms])
useEffect(() => {
let timeoutId: ReturnType<typeof setTimeout>;
const poll = () => {
reloadHosts();
// 检查 vms 里是否有 pending 状态的机器
const hasPending = vms.some(vm => vm.status === 'pending');
timeoutId = setTimeout(poll, hasPending ? 3000 : 30000);
};
poll();
return () => {
clearTimeout(timeoutId);
};
}, []);
const handleDeleteVM = (vm: DomainVirtualMachine) => {
setVmToDelete(vm)
setDeleteDialogOpen(true)
}
const confirmDeleteVM = () => {
if (!vmToDelete) {
return
}
const vm = vmToDelete
if (!vm.id) {
toast.error("无法获取开发环境 ID")
setDeleteDialogOpen(false)
setVmToDelete(null)
return
}
const hostId = vm.host?.id
if (!hostId) {
toast.error("无法获取宿主机 ID")
setDeleteDialogOpen(false)
setVmToDelete(null)
return
}
apiRequest('v1UsersHostsVmsDelete', {}, [hostId, vm.id], (resp) => {
if (resp.code === 0) {
toast.success("开发环境移除成功")
reloadHosts()
} else {
toast.error(resp.message || "移除开发环境失败")
}
setDeleteDialogOpen(false)
setVmToDelete(null)
})
}
const handleRenewVM = (vm: DomainVirtualMachine) => {
setVmToRenew(vm)
setRenewDialogOpen(true)
}
const handleRenewDialogOpenChange = (open: boolean) => {
setRenewDialogOpen(open)
if (!open) {
setVmToRenew(null)
}
}
const loadVms = () => {
return (
<Empty className="border border-dashed">
<EmptyHeader>
<EmptyMedia variant="icon">
<Spinner className="size-6" />
</EmptyMedia>
</EmptyHeader>
<EmptyContent>
<EmptyDescription>
正在加载开发环境列表...
</EmptyDescription>
</EmptyContent>
</Empty>
)
}
const NoVms = () => {
return (
<Empty className="border h-full">
<EmptyHeader>
<EmptyMedia variant="icon">
<Server />
</EmptyMedia>
<EmptyTitle>没有开发环境</EmptyTitle>
<EmptyDescription>
还没有创建任何开发环境
</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<div className="flex gap-2">
<Button variant="outline" onClick={() => reloadHosts()}>
<IconReload />
刷新
</Button>
<Button onClick={() => setCreateDialogOpen(true)}>
<CirclePlusIcon />
创建开发环境
</Button>
</div>
</EmptyContent>
</Empty>
)
}
const VmsList = () => {
return (
<ItemGroup className="flex flex-col gap-4">
{showVms?.map((vm) => (
<Item key={vm.id} variant="outline" className="hover:border-primary/50" size={"sm"}>
<ItemMedia className="hidden sm:flex">
<Avatar>
<AvatarFallback>
{vm.status === 'pending' ? (
<Spinner className="size-4" />
) : (
<Icon name={getOSFromImageName(vm.os || '')} className="size-4" />
)}
</AvatarFallback>
</Avatar>
</ItemMedia>
<ItemContent>
<HoverCard>
<HoverCardTrigger asChild>
<ItemTitle className="flex items-center gap-2 break-all">
{vm.name || "未命名开发环境"}
<Badge {...getStatusBadgeProps(vm.status)}>{translateStatus(vm.status)}</Badge>
{vm.host?.arch !== 'x86_64' && <Badge variant={"outline"} className="hidden md:flex">{vm.host?.arch}</Badge>}
</ItemTitle>
</HoverCardTrigger>
{renderHoverCardContent([
{title: "开发环境名称", content: vm.name || "未命名开发环境"},
{title: "开发环境状态", content: translateStatus(vm.status)},
{title: "开发环境状态信息", content: getVmMessage(vm)},
{title: "宿主机", content: vm.host?.remark || `${vm.host?.name}-${vm.host?.external_ip}`},
{title: "操作系统", content: vm.os || "未知"},
{title: "资源限制", content: `${vm.cores} 核 CPU,${formatMemory(vm.memory)} 内存`},
{title: "创建时间", content: dayjs.unix(vm.created_at as number).format("YYYY-MM-DD HH:mm:ss")},
{title: "回收时间", content: vm.life_time_seconds ? dayjs.unix(new Date().getTime() / 1000).add(vm.life_time_seconds as number, 'seconds').format("YYYY-MM-DD HH:mm:ss") : "永不回收"},
])}
</HoverCard>
<ItemDescription className="line-clamp-1 truncate">
{vm.status === TypesVirtualMachineStatus.VirtualMachineStatusOnline && <>
{Boolean(vm.cores) && `${vm.cores} 核 CPU,`}
{Boolean(vm.memory) && `${formatMemory(vm.memory)} 内存,`}
{`${dayjs.unix(vm.created_at as number).fromNow()}创建,`}
{vm.life_time_seconds === 0 ? "永不回收" : `${humanTime(vm.life_time_seconds as number)}后回收`}
</>}
{vm.status === TypesVirtualMachineStatus.VirtualMachineStatusOffline && <>
{getLastCondition(vm)?.type === GitInChaitinNetAiMonkeycodeMonkeycodeAiEntTypesConditionType.ConditionTypeFailed ? (
getVmMessage(vm)
) : (
'已离线'
)
}
</>}
{vm.status === TypesVirtualMachineStatus.VirtualMachineStatusPending && getVmMessage(vm)}
</ItemDescription>
</ItemContent>
<ItemActions className="w-full md:w-auto flex">
<Button variant="ghost" size="sm" className="flex-1 bg-secondary md:bg-transparent" disabled={vm.status !== TypesVirtualMachineStatus.VirtualMachineStatusOnline} onClick={() => window.open(`/console/terminal?envid=${vm.id}`, '_blank')}>
<IconTerminal2 />
终端
</Button>
<Button variant="ghost" size="sm" className="flex-1 bg-secondary md:bg-transparent" disabled={vm.status !== TypesVirtualMachineStatus.VirtualMachineStatusOnline} onClick={() => window.open(`/console/files?envid=${vm.id}&path=/workspace`, '_blank')}>
<IconFolderOpen />
文件
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm" className="bg-secondary md:bg-transparent">
<IconDotsVertical />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
disabled={vm.life_time_seconds === 0 || vm.status !== TypesVirtualMachineStatus.VirtualMachineStatusOnline}
onClick={() => handleRenewVM(vm)}
>
<IconClockHour4 className="size-4" />
续期
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onClick={() => handleDeleteVM(vm)}
>
<IconTrash className="size-4" />
移除
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</ItemActions>
</Item>
))}
</ItemGroup>
)
}
return (
<Card className="w-full shadow-none">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<MonitorCloud />
开发环境
</CardTitle>
<CardDescription>
用于在宿主机上创建开发环境
</CardDescription>
<CardAction className="">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm">
<MoreVertical className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setCreateDialogOpen(true)}>
<CirclePlusIcon />
创建开发环境
</DropdownMenuItem>
<DropdownMenuItem onClick={reloadHosts} disabled={loadingHosts}>
<IconReload className={loadingHosts ? "animate-spin" : ""} />
刷新
</DropdownMenuItem>
<DropdownMenuItem onClick={(e) => {
setShowOfflineVms(!showOfflineVms)
e.preventDefault()
}}>
{showOfflineVms ? <IconCircleCheck className="text-primary" /> : <IconCircle /> }
离线开发环境
<Switch checked={showOfflineVms} onCheckedChange={setShowOfflineVms} />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</CardAction>
</CardHeader>
<CardContent>
{loadingHosts && !hostsInited ? loadVms() : vms.length === 0 ? <NoVms /> : <VmsList />}
<CreateVM
open={createDialogOpen}
onOpenChange={setCreateDialogOpen}
onSuccess={reloadHosts}
/>
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确认移除</AlertDialogTitle>
<AlertDialogDescription>
确定要移除开发环境 "{vmToDelete?.name || '未命名开发环境'}" 吗?此操作不可撤销。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => {
setDeleteDialogOpen(false)
setVmToDelete(null)
}}>
取消
</AlertDialogCancel>
<AlertDialogAction
onClick={confirmDeleteVM}
>
确认移除
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<VmRenewDialog
open={renewDialogOpen}
onOpenChange={handleRenewDialogOpenChange}
hostId={vmToRenew?.host?.id}
vmId={vmToRenew?.id}
onSuccess={reloadHosts}
/>
</CardContent>
</Card>
)
}
@@ -0,0 +1,183 @@
import { useState, useEffect, useRef } from "react"
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupTextarea } from "@/components/ui/input-group"
import { IconCommand, IconMenu4, IconRecycle, IconReload, IconSend, IconTerminal2 } from "@tabler/icons-react"
import React from "react"
import { VoiceInputButton } from "./voice-input-button"
import type { AvailableCommand, AvailableCommands, TaskStreamStatus } from "@/components/console/task/ws-manager"
import { Button } from "@/components/ui/button"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
interface TaskChatInputBoxProps {
streamStatus: TaskStreamStatus
availableCommands: AvailableCommands | null
onSend: (content: string) => void
sending: boolean
queueSize: number
sendResetSession: () => void
sendReloadSession: () => void
}
export const TaskChatInputBox = ({ streamStatus, availableCommands, onSend, sending, queueSize, sendResetSession, sendReloadSession }: TaskChatInputBoxProps) => {
const [content, setContent] = useState('')
const [isComposing, setIsComposing] = useState(false)
const [resetDialogOpen, setResetDialogOpen] = useState(false)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const handleSend = () => {
if (content.trim() === '') {
return
}
onSend(content)
}
const handleTextRecognized = (text: string) => {
setContent(text)
}
useEffect(() => {
if (!sending) {
setContent('')
}
}, [sending])
// 处理键盘事件
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
// 如果正在输入法组合过程中,不触发提交
if (isComposing) {
return
}
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
handleSend()
}
}
// 处理输入法组合开始
const handleCompositionStart = () => {
setIsComposing(true)
}
// 处理输入法组合结束
const handleCompositionEnd = () => {
setIsComposing(false)
}
const disabled = React.useMemo(() => {
return sending || streamStatus !== 'waiting' || queueSize > 0
}, [sending, streamStatus, queueSize])
return (
<div className="relative w-full">
<InputGroup>
<InputGroupTextarea
ref={textareaRef}
className="min-h-8 max-h-48 text-sm break-all"
placeholder={disabled ? '任务正在执行,暂时无法输入' : '在这里描述你的需求,Shift+Enter 换行,Enter 发送。'}
value={content}
disabled={disabled}
onChange={(e) => setContent(e.target.value)}
onKeyDown={handleKeyDown}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd} />
<InputGroupAddon align="block-end">
<div className="flex flex-row justify-between w-full">
<div className="flex flex-row gap-2 items-center">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon-sm" className="rounded-full" disabled={disabled}>
<IconMenu4 />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem onClick={() => setResetDialogOpen(true)}>
<IconRecycle />
重置上下文
</DropdownMenuItem>
<DropdownMenuItem onClick={() => sendReloadSession()}>
<IconReload />
重新加载开发工具
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon-sm" className="rounded-full" disabled={disabled}>
<IconTerminal2 />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
{availableCommands?.commands?.map((command: AvailableCommand, index: number) => (
<DropdownMenuItem key={index} className="flex flex-col gap-1 items-start" onClick={() => setContent(`/${command.name}`)}>
<div className="flex flex-row gap-2 items-center">
<IconCommand />
<div className="font-bold text-xs">/{command.name}</div>
{command.input?.hint && <div className="text-muted-foreground text-xs">[{command.input.hint}]</div>}
</div>
<div className="text-xs text-muted-foreground pl-6">
{command.description}
</div>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="flex flex-row gap-2 items-center">
<VoiceInputButton
onTextRecognized={handleTextRecognized}
disabled={disabled}
/>
<InputGroupButton
className="flex flex-row gap-2 items-center"
variant="default"
size="sm"
onClick={handleSend}
disabled={content.trim() === '' || disabled}
>
<IconSend />
发送
</InputGroupButton>
</div>
</div>
</InputGroupAddon>
</InputGroup>
{/* Reset Session 确认对话框 */}
<AlertDialog open={resetDialogOpen} onOpenChange={setResetDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>重置上下文</AlertDialogTitle>
<AlertDialogDescription>
确定要重置当前上下文吗?后续操作将会基于新的上下文进行。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
sendResetSession()
setResetDialogOpen(false)
}}
>
确认
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
@@ -0,0 +1,268 @@
import { MessageItem, type MessageType } from "./message"
import React from "react"
import { Button } from "@/components/ui/button"
import { ChevronsDownUp, ChevronsUpDown } from "lucide-react"
import { Label } from "@/components/ui/label"
import { stripMarkdown } from "@/utils/common"
import ReactMarkdown from "react-markdown"
import remarkGfm from "remark-gfm"
import { IconCircle, IconCircleCheck, IconLoader, IconPlayerStopFilled, IconSparkles, IconSubtask } from "@tabler/icons-react"
import type { AvailableCommands, PlanEntry, RepoFileChange, TaskPlan, TaskStreamStatus, TaskWebSocketManager } from "./ws-manager"
import { TaskChatInputBox } from "./chat-inputbox"
import { cn } from "@/lib/utils"
import { FileChangesDialog } from "./file-changes-dialog"
import type { ConstsCliName } from "@/api/Api"
interface TaskChatPanelProps {
messages: MessageType[]
cli?: ConstsCliName
streamStatus: TaskStreamStatus
disabled: boolean
thinkingMessage: string
plan: TaskPlan | null
availableCommands: AvailableCommands | null
sending: boolean
queueSize: number
sendUserInput: (content: string) => void
sendCancelCommand: () => void
sendResetSession: () => void
sendReloadSession: () => void
fileChanges: string[]
fileChangesMap: Map<string, RepoFileChange>
taskManager: TaskWebSocketManager | null
}
export const TaskChatPanel = ({ messages, cli, streamStatus, disabled, thinkingMessage, plan, availableCommands, sending, sendUserInput, sendCancelCommand, sendResetSession, sendReloadSession, queueSize, fileChanges, fileChangesMap, taskManager }: TaskChatPanelProps) => {
const [thinkingOpened, setThinkingOpened] = React.useState(false)
const [planOpened, setPlanOpened] = React.useState(false)
const [timeCost, setTimeCost] = React.useState(0)
const scrollContainerRef = React.useRef<HTMLDivElement>(null)
const [showSubmitButton, setShowSubmitButton] = React.useState(false)
const [fileChangesDialogOpen, setFileChangesDialogOpen] = React.useState(false)
React.useEffect(() => {
setShowSubmitButton(streamStatus === 'waiting')
}, [streamStatus])
React.useEffect(() => {
if (!plan) {
return
}
setPlanOpened(plan.entries.some((entry: PlanEntry) => entry.status !== 'completed'))
}, [plan])
const thinkingSummary = React.useMemo(() => {
const textThinkingMesssage = stripMarkdown(thinkingMessage)
if (textThinkingMesssage.length <= 200) {
return textThinkingMesssage
}
return textThinkingMesssage.slice(-200)
}, [thinkingMessage])
React.useEffect(() => {
if (streamStatus === 'executing') {
setTimeCost(0)
const timer = setInterval(() => {
setTimeCost(prev => prev + 100)
}, 100)
return () => clearInterval(timer)
}
}, [streamStatus])
// 自动滚动到底部
React.useEffect(() => {
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollTop = scrollContainerRef.current.scrollHeight
}
}, [streamStatus])
const renderTaskStatus = () => {
if (streamStatus === 'inited') {
return <div className="w-full flex items-center justify-center mt-2">
<div className="text-xs border rounded-full px-2 py-1 w-fit flex items-center gap-2 text-muted-foreground">
<IconLoader className="size-4 animate-spin" />
正在初始化
</div>
</div>
} else if (streamStatus === 'executing') {
return <div className="w-full flex items-center justify-center mt-2">
<div className="text-xs border rounded-full px-2 py-1 w-fit flex items-center gap-2 text-muted-foreground">
<IconLoader className="size-4 animate-spin" />
任务执行耗时 {(timeCost / 1000).toFixed(1)} 秒
{!disabled && <Button variant="ghost" size="icon-sm" className="size-5 cursor-pointer" onClick={sendCancelCommand}>
<IconPlayerStopFilled className="size-4" />
</Button>}
</div>
</div>
} else if (streamStatus === 'waiting') {
return null
} else if (streamStatus === 'finished') {
return <div className="w-full flex items-center justify-center mt-2">
<div className="text-xs border rounded-full px-2 py-1 w-fit flex items-center gap-2 text-muted-foreground">
任务已终止
</div>
</div>
} else if (streamStatus === 'error') {
return <div className="w-full flex items-center justify-center mt-2">
<div className="text-xs border rounded-full px-2 py-1 w-fit flex items-center gap-2 text-muted-foreground">
连接异常断开,请刷新重试
</div>
</div>
} else {
return null
}
}
const renderPlan = () => {
if (!plan || plan.entries.length === 0) {
return null
}
if (planOpened) {
return plan.entries.map((entry: PlanEntry, index: number) => (
<div key={index} className="flex items-center gap-2">
{entry.status === 'in_progress' && streamStatus === 'executing' ? (
<IconLoader className="min-w-3 size-3 animate-spin" />
) : (
entry.status === 'completed' ? (
<IconCircleCheck className="min-w-3 size-3 text-primary" />
) : (
<IconCircle className="min-w-3 size-3 text-muted-foreground" />
)
)}
<div className={cn("line-clamp-1 text-xs", entry.status === 'completed' ? 'text-muted-foreground' : '', (entry.status === 'in_progress' && streamStatus === 'executing') ? 'text-primary' : '')}>
{entry.content}
</div>
</div>
))
} else {
const firstInProgress = plan.entries.find((entry: PlanEntry) => entry.status === 'in_progress')
if (!firstInProgress || streamStatus !== 'executing') {
return null
}
return <div className="flex items-center gap-2">
{firstInProgress.status === 'in_progress' ? (
<IconLoader className="min-w-3 size-3 animate-spin" />
) : (
firstInProgress.status === 'completed' ? (
<IconCircleCheck className="min-w-3 size-3 text-primary" />
) : (
<IconCircle className="min-w-3 size-3 text-muted-foreground" />
)
)}
<div className="line-clamp-1 text-xs text-primary">
{firstInProgress.content}
</div>
</div>
}
}
return (
<div className="flex flex-col gap-2 h-full w-full">
{thinkingSummary && <div className="flex w-full flex-col gap-2 border rounded-md p-2">
<div className="flex items-center justify-between">
<Label>
<IconSparkles className="size-4 text-primary" />
思考过程
</Label>
<Button variant={thinkingOpened ? "secondary" : "ghost"} size="icon-sm" className="size-5" onClick={() => setThinkingOpened(!thinkingOpened)}>
{thinkingOpened ? <ChevronsDownUp className="size-4" /> : <ChevronsUpDown className="size-4" />}
</Button>
</div>
{thinkingOpened ? (<div className="w-full">
<div className="user-message-markdown text-sm max-h-80 overflow-y-auto opacity-60 text-xs px-2 -mx-2">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{thinkingMessage}</ReactMarkdown>
</div>
</div>): (<div className="w-full max-w-full overflow-hidden relative h-4">
<div className="text-xs text-muted-foreground absolute right-0 min-w-full whitespace-nowrap">
{thinkingSummary}
</div>
</div>)}
</div>}
{plan && plan.entries.length > 0 && <div className="flex w-full flex-col gap-2 border rounded-md p-2">
<div className="flex items-center justify-between">
<Label>
<IconSubtask className="size-4 text-primary" />
执行步骤 ({plan.entries.filter((entry: PlanEntry) => entry.status === 'completed').length}/{plan.entries.length})
</Label>
<Button variant={planOpened ? "secondary" : "ghost"} size="icon-sm" className="size-5" onClick={() => setPlanOpened(!planOpened)}>
{planOpened ? <ChevronsDownUp className="size-4" /> : <ChevronsUpDown className="size-4" />}
</Button>
</div>
<div className="flex flex-col gap-2 max-h-48 overflow-y-auto">
{renderPlan()}
</div>
</div>}
<div ref={scrollContainerRef} className="h-full overflow-y-auto p-2 border rounded-md">
<div className="flex flex-col justify-end min-h-full gap-1">
{messages.filter((message) => message.type !== 'agent_thought_chunk').map((message) => (
<div key={message.id} id={`message-${message.id}`} className="scroll-mt-4">
<MessageItem message={message as MessageType} cli={cli} />
</div>
))}
{renderTaskStatus()}
{!disabled && fileChanges.length > 0 && showSubmitButton ? (
<div className="flex flex-row px-3 py-2 border rounded-md items-center bg-muted/50 mt-2">
<div
className="flex-1 text-xs cursor-pointer hover:text-primary transition-colors"
onClick={() => setFileChangesDialogOpen(true)}
>
{fileChanges.length} 个文件被修改,是否提交保存
</div>
<Button variant="ghost" size="sm" className="h-6 text-xs" onClick={() => {
setShowSubmitButton(false)
}}>
不急
</Button>
<Button variant="ghost" size="sm" className="h-6 text-xs" onClick={() => {
sendUserInput("用 git 提交所有修改,并推送到远程仓库")
}}>
提交
</Button>
</div>
) : null}
</div>
</div>
<FileChangesDialog
open={fileChangesDialogOpen}
onOpenChange={setFileChangesDialogOpen}
fileChanges={fileChanges}
fileChangesMap={fileChangesMap}
taskManager={taskManager}
onSubmit={(selectedFiles) => {
if (selectedFiles.length === fileChanges.length) {
sendUserInput("用 git 提交所有修改,并推送到远程仓库")
} else {
sendUserInput(`用 git 提交以下文件的修改,并推送到远程仓库: \n${selectedFiles.map((file) => `- ${file}`).join('\n')}`)
}
setShowSubmitButton(false)
}}
onCancel={() => {
setShowSubmitButton(false)
}}
/>
{disabled ? (
<div className="flex items-center justify-center w-ful border bg-muted/50 rounded-md p-2 text-xs text-muted-foreground">
开发环境不可用
</div>
) : (
<TaskChatInputBox
streamStatus={streamStatus}
availableCommands={availableCommands}
onSend={sendUserInput}
sending={sending}
queueSize={queueSize}
sendResetSession={sendResetSession}
sendReloadSession={sendReloadSession}
/>
)}
</div>
)
}
Loaded 100 of 239 files, more files were not shown because too many files have changed in this diff. Show more