docs: translate repository documentation to English (#72)
This commit is contained in:
8 files changed
+456
-441
No files matched your search
@@ -20,157 +20,169 @@ Keep this managed block so 'openspec update' can refresh the instructions.
|
||||
|
||||
<!-- OPENSPEC:END -->
|
||||
|
||||
# 用户指南
|
||||
# User Guide
|
||||
|
||||
本文是 AI 助手在本仓库工作的用户级指南。中文为主、工具与脚本偏好统一、并纳入你补充的技术栈与开发注意事项。
|
||||
This document is a user-level guide for AI assistants working in this repository. It standardizes language, tool/script preferences, and development notes for the current tech stack.
|
||||
|
||||
## 💬 沟通约定
|
||||
## 💬 Communication Conventions
|
||||
|
||||
- **语言**: 对话、待办、代码相关内容(注释、UI 文案、提交信息、PR 描述等)统一使用中文。
|
||||
- **结论先行**: 回答先给出核心结论/摘要,再补充细节。
|
||||
- **引用**: 引用具体代码时,务必给出完整文件路径(如 `src/main.ts:42`)。
|
||||
- **Language**: Use English consistently for conversation, TODOs, and code-related content (comments, UI copy, commit messages, PR descriptions, and similar artifacts).
|
||||
- **Conclusion first**: Start with the core conclusion/summary, then provide details.
|
||||
- **References**: When citing code, always provide full file paths (for example, `src/main.ts:42`).
|
||||
|
||||
## 💻 运行环境与工具
|
||||
## 💻 Runtime and Tooling
|
||||
|
||||
- **Runtime**: Node.js (Electron 环境)
|
||||
- **Node**: 建议 Node.js 20+
|
||||
- **包管理器**: `npm` (本项目包含 package-lock.json,强制使用 npm)
|
||||
- **构建工具**: Electron Forge + Vite
|
||||
- **终端环境**: Windows (PowerShell) / 可安全使用 VSCode MCP 工具
|
||||
- **Runtime**: Node.js (Electron environment)
|
||||
- **Node**: Recommended Node.js 20+
|
||||
- **Package manager**: `npm` (this project includes `package-lock.json`; use npm only)
|
||||
- **Build tools**: Electron Forge + Vite
|
||||
- **Terminal**: Windows (PowerShell) / VSCode MCP tools can be used safely
|
||||
|
||||
## 🧩 技术栈总览 (Tech Stack)
|
||||
## 🧩 Tech Stack Overview
|
||||
|
||||
- **Frontend**:
|
||||
- React 19, TypeScript
|
||||
- Tailwind CSS v4, `clsx`, `tailwind-merge`, `tailwindcss-animate`
|
||||
- Radix UI (Primitives), Lucide React (Icons), Sonner (Toast)
|
||||
- Radix UI (Primitives), Lucide React (Icons), Simple Icons (`@icons-pack/react-simple-icons`)
|
||||
- `class-variance-authority` (CVA), `react-i18next` + `i18next`
|
||||
- TanStack Router (Routing), TanStack Query (State Management)
|
||||
- Components: 模块化设计,`src/components`
|
||||
- Components: Modular design under `src/components`
|
||||
- **Backend (Electron Main/Server)**:
|
||||
- Electron (Main/Preload/Renderer 架构)
|
||||
- NestJS (用于内部代理/网关服务,由 Main Process 启动)
|
||||
- Better-SQLite3 (本地数据库), Drizzle ORM (如果后续引入) / Raw SQL
|
||||
- ORPC (Type-safe RPC)
|
||||
- Zod (Validation)
|
||||
- Electron (Main/Preload/Renderer architecture)
|
||||
- NestJS (internal proxy/gateway service, started by main process)
|
||||
- Better-SQLite3 (local database), Drizzle ORM / Raw SQL
|
||||
- ORPC (type-safe RPC)
|
||||
- gRPC (`@grpc/grpc-js`, `@grpc/proto-loader`)
|
||||
- Logging: `winston` + `winston-daily-rotate-file`
|
||||
- Zod (validation)
|
||||
- **Testing**:
|
||||
- Vitest (Unit/Integration Tests)
|
||||
- Playwright (E2E Tests)
|
||||
- Vitest (unit/integration), Testing Library
|
||||
- Playwright (E2E)
|
||||
|
||||
## 📁 目录结构
|
||||
## 📁 Directory Structure
|
||||
|
||||
```plaintext
|
||||
.
|
||||
├─ src/
|
||||
│ ├─ components/ # React UI 组件 (ui/ 存放基础组件)
|
||||
│ ├─ hooks/ # Custom React Hooks
|
||||
│ ├─ ipc/ # Electron IPC 处理逻辑 (Database, Config, etc.)
|
||||
│ ├─ layouts/ # 页面布局组件
|
||||
│ ├─ lib/ # 通用工具库
|
||||
│ ├─ routes/ # TanStack Router 路由定义
|
||||
│ ├─ server/ # NestJS 后端服务逻辑 (Gateway/Proxy)
|
||||
│ ├─ services/ # 业务服务层
|
||||
│ ├─ styles/ # 全局样式 (Tailwind class)
|
||||
│ ├─ types/ # TypeScript 类型定义
|
||||
│ ├─ utils/ # 通用工具函数
|
||||
│ ├─ App.tsx # React 应用入口
|
||||
│ ├─ main.ts # Electron 主进程入口
|
||||
│ ├─ preload.ts # Electron 预加载脚本
|
||||
│ └─ renderer.ts # Electron 渲染进程入口
|
||||
├─ forge.config.ts # Electron Forge 配置
|
||||
│ ├─ actions/ # App actions and flow orchestration
|
||||
│ ├─ assets/ # Static assets
|
||||
│ ├─ components/ # React UI components (base components under ui/)
|
||||
│ ├─ constants/ # Constants
|
||||
│ ├─ hooks/ # Custom React hooks
|
||||
│ ├─ ipc/ # Electron IPC logic (Database, Config, etc.)
|
||||
│ ├─ layouts/ # Layout components
|
||||
│ ├─ lib/ # Shared low-level utilities
|
||||
│ ├─ localization/ # i18n translation resources
|
||||
│ ├─ mocks/ # Mock data for tests and development
|
||||
│ ├─ routes/ # TanStack Router route definitions
|
||||
│ ├─ server/ # NestJS backend logic (Gateway/Proxy)
|
||||
│ ├─ services/ # Service layer
|
||||
│ ├─ styles/ # Global styles (Tailwind classes)
|
||||
│ ├─ tests/ # Test code
|
||||
│ ├─ types/ # TypeScript type definitions
|
||||
│ ├─ utils/ # Utility functions
|
||||
│ ├─ App.tsx # React app entry
|
||||
│ ├─ main.ts # Electron main entry
|
||||
│ ├─ preload.ts # Electron preload script
|
||||
│ └─ renderer.ts # Electron renderer entry
|
||||
├─ forge.config.ts # Electron Forge config
|
||||
└─ package.json
|
||||
```
|
||||
|
||||
## 🧱 组件架构(Component Architecture)
|
||||
## 🧱 Component Architecture
|
||||
|
||||
- **模块化组件**: 每个组件使用独立目录,至少包含 `.tsx` 以及可能的样式或子组件。
|
||||
- **共享能力**: 通用函数置于 `src/utils/`,底层通用封装置于 `src/lib/`。
|
||||
- **服务层**: 统一在 `src/services/` 或 `src/ipc/` 中封装数据访问,前端仅依赖 IPC 或 RPC 调用。
|
||||
- **Modular components**: Each component should have its own directory, with at least a `.tsx` file and optional styles/subcomponents.
|
||||
- **Shared capabilities**: General helpers in `src/utils/`; low-level shared wrappers in `src/lib/`.
|
||||
- **Service layer**: Centralize data access in `src/services/` or `src/ipc/`; frontend should consume IPC or RPC only.
|
||||
|
||||
## 📦 常用脚本 (Scripts)
|
||||
## 📦 Common Scripts
|
||||
|
||||
所有命令使用 `npm` 执行:
|
||||
Use `npm` for all commands:
|
||||
|
||||
- **开发 (Dev)**:
|
||||
- `npm start` - 启动 Electron 开发环境 (Electron Forge)
|
||||
- `npm run lint` - 运行 ESLint 检查
|
||||
- `npm run format` - 运行 Prettier 格式化检查
|
||||
- **Development (Dev)**:
|
||||
- `npm start` - Start Electron dev environment (Electron Forge)
|
||||
- `npm run lint` - Run ESLint checks
|
||||
- `npm run format` - Run Prettier check
|
||||
- `npm run format:write` - Auto-format with Prettier
|
||||
- `npm run type-check` - Run TypeScript type check
|
||||
|
||||
- **构建 (Build)**:
|
||||
- `npm run package` - 打包应用 (生成的只有应用包)
|
||||
- `npm run make` - 构建并生成分发安装包 (Make)
|
||||
- `npm run publish` - 发布应用
|
||||
- **Build**:
|
||||
- `npm run package` - Package app (application bundle only)
|
||||
- `npm run make` - Build and generate distributable installers
|
||||
- `npm run publish` - Publish app
|
||||
|
||||
- **测试 (Test)**:
|
||||
- `npm test` - 运行 Vitest 单元测试
|
||||
- `npm run test:unit` - 同上
|
||||
- `npm run test:e2e` - 运行 Playwright 端到端测试
|
||||
- `npm run test:all` - 运行所有测试
|
||||
- **Testing**:
|
||||
- `npm test` - Run Vitest tests
|
||||
- `npm run test:watch` - Run Vitest in watch mode
|
||||
- `npm run test:unit` - Same as above for unit-focused runs
|
||||
- `npm run test:e2e` - Run Playwright E2E tests
|
||||
- `npm run test:all` - Run all tests
|
||||
|
||||
### 运行单个测试 (Running Single Tests)
|
||||
### Running a Single Test
|
||||
|
||||
- 单元测试: `npm run test:unit path/to/test.test.ts`
|
||||
- E2E 测试: `npm run test:e2e path/to/test.spec.ts`
|
||||
- 类型检查: `npm run type-check`
|
||||
- Unit test: `npm run test:unit path/to/test.test.ts`
|
||||
- E2E test: `npm run test:e2e path/to/test.spec.ts`
|
||||
- Type check: `npm run type-check`
|
||||
|
||||
## 🧪 开发注意事项(Development Notes)
|
||||
## 🧪 Development Notes
|
||||
|
||||
- **Build**: 构建阶段忽略 TS/ESLint 错误(如有特定配置或 CI 要求,请以实际为准)。
|
||||
- **DevTools**: 项目集成了 `code-inspector-plugin`,开发时支持从页面元素直接跳转代码(Shift+Click)。
|
||||
- **React**: React Strict Mode 关闭。
|
||||
- **NestJS**: 作为 Electron 子进程运行,日志输出在主进程控制台。
|
||||
- **Build**: Build stage may ignore TS/ESLint errors depending on project/CI configuration.
|
||||
- **DevTools**: `code-inspector-plugin` is integrated; use `Shift + Click` on page elements to jump to source code.
|
||||
- **React**: React Strict Mode is disabled.
|
||||
- **NestJS**: Runs as an Electron child process; logs are visible in main-process console.
|
||||
|
||||
## �️ 安全与数据 (Security & Data)
|
||||
## Security and Data
|
||||
|
||||
- **安全**: 绝不提交密钥;敏感配置使用环境变量;验证所有用户输入;敏感数据加密存储。
|
||||
- **数据库**: 使用 Better-SQLite3;所有操作封装在 Services 层;必须使用 Prepared Statements;独立测试 DB 操作。
|
||||
- **国际化**: 使用 `react-i18next`;Key 使用 kebab-case;翻译文件存放在 `src/localization/`。
|
||||
- **Security**: Never commit secrets; use environment variables for sensitive config; validate all user input; encrypt sensitive data.
|
||||
- **Database**: Use Better-SQLite3; encapsulate operations in services layer; always use prepared statements; test DB operations independently.
|
||||
- **i18n**: Use `react-i18next`; keys should use kebab-case; translation files are stored in `src/localization/`.
|
||||
|
||||
## �📝 代码规范 (Conventions)
|
||||
## 📝 Conventions
|
||||
|
||||
- **文件命名**:
|
||||
- 组件: PascalCase (e.g., `Button.tsx`)
|
||||
- 工具/配置: camelCase 或 kebab-case
|
||||
- **导入路径**: 使用 `@/` 别名指向 `src/` 目录。
|
||||
- **类型安全**: 严禁使用 `any`,利用 Zod 和 TypeScript 确保全链路类型安全。
|
||||
- **组件设计**:
|
||||
- 优先使用 Radix UI Primitives。
|
||||
- 样式使用 Tailwind Utility Classes,避免 CSS Modules (除非必要)。
|
||||
- **API 通信**: 前端调用后端优先使用 ORPC 客户端或 IPC,确保类型推导。
|
||||
- **File naming**:
|
||||
- Components: PascalCase (for example, `Button.tsx`)
|
||||
- Tools/config: camelCase or kebab-case
|
||||
- **Import paths**: Use `@/` alias for `src/`.
|
||||
- **Type safety**: Avoid `any`; enforce end-to-end type safety with Zod + TypeScript.
|
||||
- **Component design**:
|
||||
- Prefer Radix UI Primitives.
|
||||
- Use Tailwind utility classes; avoid CSS Modules unless necessary.
|
||||
- **API communication**: Frontend should prioritize ORPC client or IPC for strong type inference.
|
||||
|
||||
### 命名约定 (Naming Specifics)
|
||||
### Naming Specifics
|
||||
|
||||
- **Functions/Variables**: camelCase (e.g., `handleClick`, `isCurrent`)
|
||||
- **Constants**: UPPER_SNAKE_CASE (e.g., `LOCAL_STORAGE_KEYS`)
|
||||
- **Functions/Variables**: camelCase (for example, `handleClick`, `isCurrent`)
|
||||
- **Constants**: UPPER_SNAKE_CASE (for example, `LOCAL_STORAGE_KEYS`)
|
||||
- **Files**:
|
||||
- Services: `ServiceName.service.ts`
|
||||
- Types: `type-name.ts`
|
||||
|
||||
### 导入组织 (Import Organization)
|
||||
### Import Organization
|
||||
|
||||
```typescript
|
||||
// 1. React 和核心库
|
||||
// 1. React and core libraries
|
||||
import React, { useEffect } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
|
||||
// 2. 外部依赖 (按字母顺序)
|
||||
// 2. External dependencies (alphabetical order)
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
|
||||
// 3. 内部导入 (使用 @ 别名)
|
||||
// 3. Internal imports (using @ alias)
|
||||
import { Account } from '@/types/account';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
```
|
||||
|
||||
### 组件结构 (Component Structure)
|
||||
### Component Structure
|
||||
|
||||
```typescript
|
||||
// 1. 导入
|
||||
// 1. Imports
|
||||
import React, { useState } from 'react';
|
||||
|
||||
// 2. 类型定义
|
||||
// 2. Type definitions
|
||||
interface ComponentProps { /* props */ }
|
||||
|
||||
// 3. 组件实现
|
||||
// 3. Component implementation
|
||||
export const Component: React.FC<ComponentProps> = ({ prop1 }) => {
|
||||
// 4. Hooks
|
||||
const { t } = useTranslation();
|
||||
@@ -179,14 +191,14 @@ export const Component: React.FC<ComponentProps> = ({ prop1 }) => {
|
||||
};
|
||||
```
|
||||
|
||||
> 提交前请确保执行 `npm run lint` 和 `npm run format`。
|
||||
> Before commit, run `npm run lint` and `npm run format`.
|
||||
|
||||
## 📝 终端输出与引用规范
|
||||
## 📝 Terminal Output and References
|
||||
|
||||
- 代码块优先,避免 Markdown 表格与 mermaid(Claude 代码块渲染更稳定)。
|
||||
- 表格(如需)左对齐;中文字符等宽注意显示差异。
|
||||
- Prefer code blocks; avoid Markdown tables and Mermaid unless necessary.
|
||||
- If tables are used, keep them left-aligned and check display consistency.
|
||||
|
||||
示例:
|
||||
Example:
|
||||
|
||||
```plaintext
|
||||
+------+---------+---------+
|
||||
@@ -197,77 +209,77 @@ export const Component: React.FC<ComponentProps> = ({ prop1 }) => {
|
||||
+------+---------+---------+
|
||||
```
|
||||
|
||||
### 引用规范(References)
|
||||
### Reference Rules
|
||||
|
||||
- 外部资源:使用完整可点击链接(Issue、文档、API 参考)。
|
||||
- 源码位置:使用完整文件路径(可附行号)。
|
||||
- External resources: use full clickable links (issues, docs, API references).
|
||||
- Source code location: use full file paths (optionally with line numbers).
|
||||
|
||||
示例:
|
||||
Example:
|
||||
|
||||
```plaintext
|
||||
- “resolveFilePath 负责该逻辑”
|
||||
- “VSCode 在撤销操作上存在既知限制”
|
||||
- "resolveFilePath owns this logic"
|
||||
- "VSCode has a known limitation in undo behavior"
|
||||
|
||||
🔗 References:
|
||||
References:
|
||||
- resolveFilePath: src/utils/workspace.ts:40
|
||||
- VSCode undo limitation: https://github.com/microsoft/vscode/issues/77190
|
||||
```
|
||||
|
||||
## 🏷️ Markdown 书写
|
||||
## 🏷️ Markdown Writing
|
||||
|
||||
- 代码块语言不要留空,无法确定时使用 `plaintext`。
|
||||
- 标题后保留一行空行,便于渲染与阅读。
|
||||
- Always specify a language for fenced code blocks; use `plaintext` if unsure.
|
||||
- Keep one blank line after headings for readability.
|
||||
|
||||
## 换行规范
|
||||
## Line-Break Rule
|
||||
|
||||
return 等语句不要与其他语句在同一行,而是单独保持一行
|
||||
`return` and similar statements should not share a line with other statements. Keep them on separate lines.
|
||||
|
||||
## 💭 注释规范
|
||||
## 💭 Commenting Rules
|
||||
|
||||
- 必注释场景:复杂业务/算法、特殊行为、重要设计取舍、关键参考链接。
|
||||
- 原则:
|
||||
- 注释“为什么”(Why),非“做了什么”(What)、非变更记录(Changelog)。
|
||||
- 修改代码时同步更新注释(过时注释比无注释更糟)。
|
||||
- 优先使用 JSDoc,复杂函数先给高层概览,函数体内按步骤(1、2、3…)标注关键过程。
|
||||
- 中英文之间适当空格,提升可读性;不要为删除的旧代码写注释。
|
||||
- Required comment scenarios: complex business logic/algorithms, non-obvious behaviors, important design tradeoffs, and key reference links.
|
||||
- Principles:
|
||||
- Explain **why**, not **what**, and not changelog history.
|
||||
- Update comments whenever related code changes.
|
||||
- Prefer JSDoc; for complex functions, start with high-level overview, then annotate key steps (1, 2, 3...).
|
||||
- Keep spacing between English and Chinese words if both appear for readability; do not comment deleted legacy code.
|
||||
|
||||
“质量自检”问题:六个月后新同事看到这条注释能得到什么有用信息?若答案是“没有”,删掉它。
|
||||
Quality self-check: six months later, what useful context does a new teammate gain from this comment? If the answer is "none", remove it.
|
||||
|
||||
示例:
|
||||
Example:
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* 处理支付请求,多步骤校验
|
||||
* Handle payment request with multi-step validation.
|
||||
*/
|
||||
function processPayment(request: PaymentRequest) {
|
||||
// 1. 数据校验
|
||||
// 2. 风控评估(低/中/高差异处理)
|
||||
// 3. 网关调用
|
||||
// 4. 用户通知
|
||||
// 1. Input validation
|
||||
// 2. Risk evaluation (low/medium/high paths)
|
||||
// 3. Gateway call
|
||||
// 4. User notification
|
||||
}
|
||||
|
||||
export enum BudgetType {
|
||||
Free = 'free',
|
||||
/** ✅ 推荐使用 JSDoc,而不是行尾注释 */
|
||||
/** ✅ Prefer JSDoc over end-of-line comments */
|
||||
Package = 'package',
|
||||
}
|
||||
```
|
||||
|
||||
## 🛠️ 开发指南
|
||||
## 🛠️ Development Guide
|
||||
|
||||
### 通用原则
|
||||
### General Principles
|
||||
|
||||
- 优先稳定与可维护性,其次再谈性能优化。
|
||||
- 面对不确定性:明确假设、取舍与验证方案;先沟通再实施。
|
||||
- 信任既定前置条件,避免对承诺不变量的过度防御;若出现冲突,更新方案而非额外兜底。
|
||||
- 老代码重构保守推进,新功能实现可采用更现代方式。
|
||||
- 避免过早优化:先以简单直接的实现达成功能,确需时再优化(避免先行加缓存/抖动或拆分成过多文件)。
|
||||
- 对于 if,while 等条件、循环语句必须加上花括号,不能与return、break、continue 等语句同级。
|
||||
- Prioritize stability and maintainability before optimization.
|
||||
- For uncertainty, state assumptions/tradeoffs/validation approach clearly, then implement.
|
||||
- Trust agreed preconditions; avoid excessive defensive coding against guaranteed invariants.
|
||||
- Refactor legacy code conservatively; use modern approaches for new features where appropriate.
|
||||
- Avoid premature optimization: implement simple and direct first; optimize only when justified.
|
||||
- Always use braces for control flow (`if`, `while`, and similar statements).
|
||||
|
||||
### 错误处理 (Error Handling)
|
||||
### Error Handling
|
||||
|
||||
```typescript
|
||||
// 异步操作使用 try-catch
|
||||
// Use try-catch for async operations
|
||||
try {
|
||||
const result = await someOperation();
|
||||
return result;
|
||||
@@ -276,92 +288,92 @@ try {
|
||||
throw new Error('Failed to complete operation');
|
||||
}
|
||||
|
||||
// 使用正确的错误类型
|
||||
// Use proper error typing
|
||||
if (error instanceof Error) {
|
||||
/* 处理 Error 实例 */
|
||||
/* handle Error instance */
|
||||
}
|
||||
```
|
||||
|
||||
### 新功能实现
|
||||
### New Feature Implementation
|
||||
|
||||
- 代码应清晰、可读、可复用、有效率且可测试。
|
||||
- 倾向选用成熟可靠的现代 API。
|
||||
- Code should be clear, readable, reusable, efficient, and testable.
|
||||
- Prefer mature and reliable modern APIs.
|
||||
|
||||
### 重构与修 Bug
|
||||
### Refactoring and Bug Fixing
|
||||
|
||||
- 倾向增量式改动;如需大重构,先就范围对齐再推进。
|
||||
- 保持原结构与风格,避免过度抽象引入新风险。
|
||||
- Prefer incremental changes; align scope first before large refactors.
|
||||
- Preserve existing structure and style; avoid over-abstraction risk.
|
||||
|
||||
### 开发生命周期(Checklist)
|
||||
### Development Lifecycle Checklist
|
||||
|
||||
探索/规划:
|
||||
Exploration / planning:
|
||||
|
||||
- \[ ] 充分理解需求,分步思考与列计划(3–6 步)
|
||||
- \[ ] 优先查阅文档与既有方案
|
||||
- \[ ] 通过阅读实际代码验证想法
|
||||
- \[ ] 形成 TODO 列表
|
||||
- \[ ] Fully understand requirements; break down into 3-6 steps
|
||||
- \[ ] Review documentation and existing solutions first
|
||||
- \[ ] Validate ideas by reading actual code
|
||||
- \[ ] Build a TODO list
|
||||
|
||||
实现/重构/修复:
|
||||
Implementation / refactor / fix:
|
||||
|
||||
- [ ] 阅读相关模板与周边代码,沿用既有模式
|
||||
- [ ] Fail fast:对非法输入/状态抛错,尽早暴露问题
|
||||
- [ ] 在约束内尽力提升前端交互与体验
|
||||
- [ ] Review related templates and surrounding code; follow existing patterns
|
||||
- [ ] Fail fast on invalid inputs/states
|
||||
- [ ] Improve frontend interaction and UX within constraints
|
||||
|
||||
验收/校验:
|
||||
Acceptance / validation:
|
||||
|
||||
- \[ ] 通过测试或临时脚本验证实现
|
||||
- \[ ] 多次增量修改后回看是否可合并为一次更连贯的修改
|
||||
- \[ ] 运行质量检查
|
||||
- \[ ] 更新相关文档
|
||||
- \[ ] Validate implementation through tests or temporary scripts
|
||||
- \[ ] After multiple incremental edits, evaluate whether changes should be consolidated
|
||||
- \[ ] Run quality checks
|
||||
- \[ ] Update related docs
|
||||
|
||||
总结/输出:
|
||||
Summary / output:
|
||||
|
||||
- \[ ] 检查输出格式要求
|
||||
- \[ ] 列出与原计划偏差与关键决策,便于人工复核
|
||||
- \[ ] 提供优化建议
|
||||
- \[ ] 在结尾提供完整引用链接
|
||||
- \[ ] Verify output formatting requirements
|
||||
- \[ ] List deviations from plan and key decisions for human review
|
||||
- \[ ] Provide optimization suggestions
|
||||
- \[ ] Include full references at the end
|
||||
|
||||
## 🔍 代码质量与 Lint
|
||||
## 🔍 Code Quality and Lint
|
||||
|
||||
- 变量命名具描述性(如 `mutationObserver`、`button`、`element`),避免 `mo`、`btn`、`el`。
|
||||
- 检查缺失的重要注释,并保持注释语言一致。
|
||||
- 使用 VSCode MCP 诊断工具查看 TS/ESLint 报告并修复关键问题。
|
||||
- 若新增/修改测试,需运行并修复测试后再提交。
|
||||
- Use descriptive variable names (`mutationObserver`, `button`, `element`) and avoid `mo`, `btn`, `el`.
|
||||
- Check for missing critical comments and keep comment language consistent.
|
||||
- Use VSCode MCP diagnostics for TS/ESLint issues and fix key findings.
|
||||
- If tests are added/updated, run and fix them before submission.
|
||||
|
||||
## ⛔ 需要显式确认的操作
|
||||
## ⛔ Operations Requiring Explicit Confirmation
|
||||
|
||||
- 运行具有破坏性的命令
|
||||
- 执行 `git commit`、`git push`
|
||||
- 新建测试文件(先由维护者进行人工审核)
|
||||
- Running destructive commands
|
||||
- Executing `git commit` or `git push`
|
||||
- Creating new test files (maintainer review required first)
|
||||
|
||||
## 🔧 工具偏好与命令
|
||||
## 🔧 Tool Preferences and Commands
|
||||
|
||||
包与脚本:
|
||||
Packages and scripts:
|
||||
|
||||
- `npm install` (或简写 `npm i`)
|
||||
- `npm install` (or `npm i`)
|
||||
|
||||
Shell:
|
||||
Shell:
|
||||
|
||||
- 在工作区根目录执行命令。
|
||||
- 路径建议使用引号包裹。
|
||||
- Run commands in repository root.
|
||||
- Quote file paths when appropriate.
|
||||
|
||||
Web 搜索:
|
||||
Web search:
|
||||
|
||||
- `WebSearch` 获取最新内容;不足时用 `mcp__SearXNG__search` 聚合搜索
|
||||
- Use `WebSearch` for latest information; use `mcp__SearXNG__search` when needed.
|
||||
|
||||
文档/用法检索:
|
||||
Documentation/usage lookup:
|
||||
|
||||
- `context7` 获取依赖的最新用法
|
||||
- Use `context7` for latest dependency usage.
|
||||
|
||||
VSCode MCP (如可用):
|
||||
VSCode MCP (if available):
|
||||
|
||||
- `mcp__vscode-mcp__get_references` 辅助重构范围判定
|
||||
- `mcp__vscode-mcp__rename_symbol` 安全重命名
|
||||
- `mcp__vscode-mcp__get_symbol_lsp_info` 获取类型/签名/定义等信息
|
||||
- `mcp__vscode-mcp__get_references` for refactor impact analysis
|
||||
- `mcp__vscode-mcp__rename_symbol` for safe renaming
|
||||
- `mcp__vscode-mcp__get_symbol_lsp_info` for types/signatures/definitions
|
||||
|
||||
## 🚨 本地质量检查(可选流程)
|
||||
## 🚨 Local Quality Checks (Optional Flow)
|
||||
|
||||
在完成一组修改后并行执行三类检查,而非直接跑全量 lint:
|
||||
After a set of changes, run these three checks in parallel instead of full lint immediately:
|
||||
|
||||
```plaintext
|
||||
Task(subagent_type: "quick-code-review", description: "Code review", prompt: "[change description]")
|
||||
@@ -369,16 +381,16 @@ Task(subagent_type: "diagnostics", description: "Diagnostics", prompt: "[same as
|
||||
Task(subagent_type: "run-related-tests", description: "Run tests", prompt: "[same as above]")
|
||||
```
|
||||
|
||||
change description 示例:
|
||||
`change description` example:
|
||||
|
||||
```plaintext
|
||||
- Modified files: 相对路径列表
|
||||
- Context: 需求/业务背景
|
||||
- Modified files: list of relative paths
|
||||
- Context: requirement/business background
|
||||
```
|
||||
|
||||
流程:初检 → 修复关键问题 → 复检 → 迭代至关键问题清零。
|
||||
Flow: initial check -> fix key issues -> re-check -> iterate until key issues are resolved.
|
||||
|
||||
注意:上述工具为只读分析,需自行修复;传入精确文件路径,避免用笼统目录。
|
||||
Note: these tools are read-only analyzers; you still need to apply fixes manually. Pass precise file paths, not broad directories.
|
||||
|
||||
<skills_system priority="1">
|
||||
|
||||
|
||||
+60
-60
@@ -1,96 +1,96 @@
|
||||
# 云端账号管理与智能切换 (Cloud Account Features)
|
||||
# Cloud Account Management and Intelligent Switching
|
||||
|
||||
本文档详细介绍了 Antigravity Manager 中实现的云端 AI 账号管理与切换功能。该功能允许用户管理多个 Google 账号,监控 API 配额,并一键无缝切换 IDE 的当前活动账号。
|
||||
This document explains the cloud AI account management and switching capabilities in Antigravity Manager. The feature allows users to manage multiple Google accounts, monitor API quotas, and seamlessly switch the active IDE account with one click.
|
||||
|
||||
## 1. 核心功能
|
||||
## 1. Core Features
|
||||
|
||||
### 1.1 账号池管理
|
||||
### 1.1 Account Pool Management
|
||||
|
||||
- **添加账号**:支持通过 Google OAuth 授权码添加账号。
|
||||
- **列表展示**:展示所有已添加的账号,包括头像、邮箱、最后使用时间。
|
||||
- **状态监控**:实时显示账号状态(Active, Rate Limited, Expired)以及是否为当前活动账号。
|
||||
- **删除账号**:支持从本地数据库中移除账号。
|
||||
- **Add accounts**: Add accounts via Google OAuth authorization code.
|
||||
- **List view**: Display all added accounts, including avatar, email, and last used time.
|
||||
- **Status monitoring**: Show real-time account status (Active, Rate Limited, Expired) and whether the account is currently active.
|
||||
- **Delete accounts**: Remove accounts from the local database.
|
||||
|
||||
### 1.2 配额实时监控
|
||||
### 1.2 Real-Time Quota Monitoring
|
||||
|
||||
- **多模型支持**:分别监控 `gemini-pro`, `claude-3-5-sonnet` 等模型的配额使用情况。
|
||||
- **可视化展示**:通过进度条和颜色(绿/黄/红)直观展示剩余配额百分比。
|
||||
- **自动/手动刷新**:支持手动刷新配额,系统也会在切换前自动检查。
|
||||
- **Multi-model support**: Track quota usage for models such as `gemini-pro`, `claude-3-5-sonnet`, and more.
|
||||
- **Visual indicators**: Use progress bars and color states (green/yellow/red) to show remaining quota percentage.
|
||||
- **Auto/manual refresh**: Support manual quota refresh; the system also checks quota automatically before switching.
|
||||
|
||||
### 1.4 智能自动切换 (Intelligent Auto-Switching)
|
||||
### 1.4 Intelligent Auto-Switching
|
||||
|
||||
- **无限池模式**:当检测到当前账号配额不足(<5%)或被限流时,系统会自动寻找最佳备用账号并切换。
|
||||
- **后台监控**:内置 `CloudMonitorService`, 默认每 5 分钟轮询一次所有账号的 Quota 状态。
|
||||
- **全局开关**:用户可在界面上一键开启或关闭此功能。
|
||||
- **Unlimited pool mode**: When the current account quota is low (`<5%`) or rate-limited, the system automatically finds and switches to the best backup account.
|
||||
- **Background monitoring**: Built-in `CloudMonitorService` polls quota status for all accounts every 5 minutes by default.
|
||||
- **Global toggle**: Users can enable or disable this feature with one click in the UI.
|
||||
|
||||
## 2. 技术实现
|
||||
## 2. Technical Implementation
|
||||
|
||||
### 2.1 数据库设计 (`cloud_accounts.db`)
|
||||
### 2.1 Database Design (`cloud_accounts.db`)
|
||||
|
||||
使用 SQLite 存储账号信息,独立于 IDE 的本地数据库。
|
||||
Account information is stored in SQLite, independent from the IDE's local database.
|
||||
|
||||
```sql
|
||||
CREATE TABLE accounts (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
provider TEXT NOT NULL, -- 'google' | 'anthropic'
|
||||
email TEXT NOT NULL, -- 邮箱
|
||||
name TEXT, -- 显示名称
|
||||
avatar_url TEXT, -- 头像 URL
|
||||
token_json TEXT NOT NULL, -- OAuth Token (JSON)
|
||||
quota_json TEXT, -- 配额数据 (JSON)
|
||||
created_at INTEGER NOT NULL, -- 创建时间戳
|
||||
last_used INTEGER NOT NULL, -- 最后使用时间戳
|
||||
status TEXT DEFAULT 'active', -- 账号状态
|
||||
is_active INTEGER DEFAULT 0 -- 是否为当前 IDE 活动账号
|
||||
email TEXT NOT NULL, -- Email
|
||||
name TEXT, -- Display name
|
||||
avatar_url TEXT, -- Avatar URL
|
||||
token_json TEXT NOT NULL, -- OAuth token (JSON)
|
||||
quota_json TEXT, -- Quota data (JSON)
|
||||
created_at INTEGER NOT NULL, -- Created timestamp
|
||||
last_used INTEGER NOT NULL, -- Last-used timestamp
|
||||
status TEXT DEFAULT 'active', -- Account status
|
||||
is_active INTEGER DEFAULT 0 -- Whether this is the currently active IDE account
|
||||
);
|
||||
|
||||
-- 全局配置表
|
||||
-- Global settings table
|
||||
CREATE TABLE settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
```
|
||||
|
||||
### 2.2 IPC 接口设计
|
||||
### 2.2 IPC Interface Design
|
||||
|
||||
后端通过 `src/ipc/cloud` 提供以下 oRPC 接口:
|
||||
The backend exposes the following oRPC interfaces via `src/ipc/cloud`:
|
||||
|
||||
- `addGoogleAccount(authCode: string)`: 交换 Token 并保存账号。
|
||||
- `listCloudAccounts()`: 获取账号列表。
|
||||
- `refreshAccountQuota(accountId: string)`: 刷新指定账号的配额和 Token。
|
||||
- `switchCloudAccount(accountId: string)`: 执行账号切换流程。
|
||||
- `deleteCloudAccount(accountId: string)`: 删除账号。
|
||||
- `getAutoSwitchEnabled()` / `setAutoSwitchEnabled(enabled)`: 获取/设置自动切换开关。
|
||||
- `forcePollCloudMonitor()`: 手动触发后台轮询。
|
||||
- `addGoogleAccount(authCode: string)`: Exchange token and save account.
|
||||
- `listCloudAccounts()`: Get account list.
|
||||
- `refreshAccountQuota(accountId: string)`: Refresh quota and token for a specific account.
|
||||
- `switchCloudAccount(accountId: string)`: Run the account switch workflow.
|
||||
- `deleteCloudAccount(accountId: string)`: Delete an account.
|
||||
- `getAutoSwitchEnabled()` / `setAutoSwitchEnabled(enabled)`: Get/set auto-switch state.
|
||||
- `forcePollCloudMonitor()`: Manually trigger background polling.
|
||||
|
||||
### 2.3 Token 注入原理 (`ProtobufUtils`)
|
||||
### 2.3 Token Injection Mechanism (`ProtobufUtils`)
|
||||
|
||||
IDE 将鉴权信息存储在 `state.vscdb` 的 `ItemTable` 表中,key 为 `jetskiStateSync.agentManagerInitState`。
|
||||
value 是一个 Base64 编码的 Protobuf 二进制数据。
|
||||
The IDE stores authentication data in the `ItemTable` table of `state.vscdb`, under the key `jetskiStateSync.agentManagerInitState`.
|
||||
The value is Base64-encoded Protobuf binary.
|
||||
|
||||
我们实现了 `src/utils/protobuf.ts` 工具类,能够:
|
||||
We implemented `src/utils/protobuf.ts`, which can:
|
||||
|
||||
1. **解码**:解析 Varint 和 Length-Delimited 字段。
|
||||
2. **修改**:定位并移除旧的 Field 6 (OAuthTokenInfo)。
|
||||
3. **重构**:根据新的 Access Token 和 Refresh Token 构建新的 Field 6 并插入。
|
||||
1. **Decode**: Parse Varint and length-delimited fields.
|
||||
2. **Modify**: Locate and remove old Field 6 (`OAuthTokenInfo`).
|
||||
3. **Rebuild**: Build a new Field 6 using new access/refresh tokens and insert it.
|
||||
|
||||
### 2.4 切换流程
|
||||
### 2.4 Switching Workflow
|
||||
|
||||
1. **Token 检查**:检查目标账号 Token 是否临期,如需刷新则自动刷新。
|
||||
2. **停止进程**:优雅关闭 Antigravity 进程。
|
||||
3. **注入 Token**:调用 `CloudAccountRepo.injectCloudToken` 修改 IDE 数据库。
|
||||
4. **更新状态**:将目标账号标记为 `is_active = 1`,其他账号设为 0。
|
||||
5. **重启进程**:重新启动 IDE,使其加载新的凭证。
|
||||
1. **Token check**: Check whether the target account token is near expiration; refresh automatically if needed.
|
||||
2. **Stop process**: Gracefully stop the Antigravity process.
|
||||
3. **Inject token**: Call `CloudAccountRepo.injectCloudToken` to update the IDE database.
|
||||
4. **Update state**: Mark target account as `is_active = 1`, set others to `0`.
|
||||
5. **Restart process**: Restart the IDE so it loads new credentials.
|
||||
|
||||
### 2.5 自动切换逻辑 (`AutoSwitchService`)
|
||||
### 2.5 Auto-Switch Logic (`AutoSwitchService`)
|
||||
|
||||
1. **监控**:`CloudMonitorService` 定时(5分钟)轮询所有账号配额。
|
||||
2. **判断**:如果当前活动账号的所有关键模型配额低于 5%,或状态为 `rate_limited`。
|
||||
3. **择优**:从账号池中筛选状态为 `active` 且配额充足的账号,按配额剩余量排序。
|
||||
4. **执行**:自动调用 `switchCloudAccount` 完成切换,并通知用户。
|
||||
1. **Monitor**: `CloudMonitorService` polls quotas for all accounts every 5 minutes.
|
||||
2. **Evaluate**: If all key model quotas of the active account are below `5%`, or status is `rate_limited`.
|
||||
3. **Select**: Filter accounts with `active` status and sufficient quota, then sort by remaining quota.
|
||||
4. **Execute**: Automatically call `switchCloudAccount` and notify the user.
|
||||
|
||||
### 2.6 安全加固 (Security Hardening)
|
||||
### 2.6 Security Hardening
|
||||
|
||||
- **密钥管理**:使用操作系统原生凭据管理器(Windows Credential Manager / macOS Keychain)通过 `keytar` 库安全存储 Master Key(AES-256)。
|
||||
- **数据加密**:所有敏感数据(`token_json`, `quota_json`)在存入 SQLite 数据库前均使用 `AES-256-GCM` 算法加密。
|
||||
- **自动迁移**:应用启动时会自动检测并迁移旧的明文数据,确保安全性平滑升级。
|
||||
- **Key management**: Use native OS credential stores (Windows Credential Manager / macOS Keychain) via `keytar` to securely store the AES-256 master key.
|
||||
- **Data encryption**: Encrypt all sensitive fields (`token_json`, `quota_json`) with `AES-256-GCM` before writing to SQLite.
|
||||
- **Auto migration**: Automatically detect and migrate legacy plaintext data at startup to ensure a smooth security upgrade.
|
||||
@@ -1,30 +1,30 @@
|
||||
# 设计:多语言支持
|
||||
# Design: Multilingual Support
|
||||
|
||||
## 架构
|
||||
## Architecture
|
||||
|
||||
应用使用 `react-i18next` 进行国际化,并配合 `i18next-browser-languagedetector` 进行语言检测。配置集中在 `src/localization/i18n.ts` 中。
|
||||
The application uses `react-i18next` for i18n and `i18next-browser-languagedetector` for language detection. Configuration is centralized in `src/localization/i18n.ts`.
|
||||
|
||||
### 语言资源
|
||||
### Language Resources
|
||||
|
||||
翻译资源将作为 JSON 对象构建在 `i18n.ts` 中(如果太大则分文件)。
|
||||
我们将在 `resources` 对象中添加 `zh-CN` 键。
|
||||
Translation resources are built as JSON objects in `i18n.ts` (or split into files if they grow large).
|
||||
We add a `zh-CN` key in the `resources` object.
|
||||
|
||||
### 默认语言策略
|
||||
### Default Language Strategy
|
||||
|
||||
我们将引入 `LanguageDetector` 插件。
|
||||
`i18n.use(LanguageDetector).init({...})` 将被配置为首先检查 `localStorage`,然后检查 `navigator`(浏览器/系统语言)。
|
||||
`fallbackLng` 将保持为 `'en'`,作为最后的兜底。
|
||||
We introduce the `LanguageDetector` plugin.
|
||||
`i18n.use(LanguageDetector).init({...})` is configured to check `localStorage` first, then `navigator` (browser/system language).
|
||||
`fallbackLng` remains `'en'` as the final fallback.
|
||||
|
||||
### 键映射
|
||||
### Key Mapping
|
||||
|
||||
我们将把现有的英文字符串映射到语义键(例如 `home.title`, `settings.theme`)。
|
||||
Existing English strings are mapped to semantic keys (for example, `home.title`, `settings.theme`).
|
||||
|
||||
## 数据流
|
||||
## Data Flow
|
||||
|
||||
1. 应用启动。
|
||||
2. `i18next` 初始化,通过 `LanguageDetector` 确定语言:
|
||||
* 检查 `localStorage` 是否有保存的偏好。
|
||||
* 如果无,检查 `navigator.language`。
|
||||
* 如果检测到的语言受支持(`en` 或 `zh-CN`),则使用该语言。
|
||||
* 否则,使用 `fallbackLng` (`en`)。
|
||||
3. 组件使用 `useTranslation` hook 根据当前语言获取字符串。
|
||||
1. App starts.
|
||||
2. `i18next` initializes and determines language via `LanguageDetector`:
|
||||
* Check whether `localStorage` has a saved preference.
|
||||
* If not, check `navigator.language`.
|
||||
* If detected language is supported (`en` or `zh-CN`), use it.
|
||||
* Otherwise, use `fallbackLng` (`en`).
|
||||
3. Components use `useTranslation` to resolve strings for the active language.
|
||||
@@ -1,41 +1,41 @@
|
||||
# 提案:应用本地化(自动检测系统语言)
|
||||
# Proposal: App Localization (Automatic System Language Detection)
|
||||
|
||||
**变更 ID:** `localize-app-auto-detect`
|
||||
**Change ID:** `localize-app-auto-detect`
|
||||
|
||||
## 摘要
|
||||
## Summary
|
||||
|
||||
为 Antigravity Manager 应用添加多语言支持,并根据用户的操作系统语言自动设置默认语言。如果系统语言不受支持,则回退到英语。这包括更新 i18n 配置,添加中文翻译资源,并集成语言检测插件。
|
||||
Add multilingual support to Antigravity Manager and automatically set the default UI language based on the user's OS language. If the OS language is unsupported, fall back to English. This includes updating i18n configuration, adding Chinese translation resources, and integrating a language detection plugin.
|
||||
|
||||
## 动机
|
||||
## Motivation
|
||||
|
||||
为了提供最佳的用户体验,应用应该能够适应用户的首选语言环境。自动检测系统语言可以减少用户的配置步骤,提供更自然的初次使用体验。
|
||||
To provide a better user experience, the app should adapt to users' preferred language environment. Automatically detecting system language reduces setup effort and improves first-run experience.
|
||||
|
||||
## 建议变更
|
||||
## Proposed Changes
|
||||
|
||||
1. **集成语言检测:** 安装并配置 `i18next-browser-languagedetector` 以自动检测用户语言。
|
||||
2. **更新 i18n 配置:** 修改 `src/localization/i18n.ts`,启用语言检测,并设置适当的回退语言(英语)。
|
||||
3. **添加中文资源:** 为 `zh-CN` 创建一个新的翻译资源文件,包含所有应用字符串。
|
||||
4. **更新语言操作:** 确保 `src/actions/language.ts` 正确处理自动检测和手动覆盖的逻辑。
|
||||
5. **UI 更新:** 确保所有 UI 组件使用翻译键而不是硬编码字符串。
|
||||
1. **Integrate language detection:** Install and configure `i18next-browser-languagedetector` to auto-detect user language.
|
||||
2. **Update i18n config:** Modify `src/localization/i18n.ts` to enable language detection and define a fallback language (English).
|
||||
3. **Add Chinese resources:** Create `zh-CN` translation resources covering all app strings.
|
||||
4. **Update language actions:** Ensure `src/actions/language.ts` correctly handles auto-detection and manual override.
|
||||
5. **UI updates:** Ensure all UI components use translation keys instead of hardcoded text.
|
||||
|
||||
## 考虑的替代方案
|
||||
## Alternatives Considered
|
||||
|
||||
* **强制默认中文:** 已拒绝,为了适应更广泛的国际用户群体,并尊重用户的系统设置。
|
||||
* **强制默认英语:** 已拒绝,同上。
|
||||
* **Force default Chinese:** Rejected, to support a broader international user base and respect system settings.
|
||||
* **Force default English:** Rejected, same reason.
|
||||
|
||||
## 风险
|
||||
## Risks
|
||||
|
||||
* **检测失败:** 在某些特殊环境(如 Linux 某些发行版)下,语言检测可能不准确,需要确保回退机制可靠。
|
||||
* **Detection failure:** In certain environments (for example, some Linux distros), language detection may be inaccurate. Fallback behavior must remain reliable.
|
||||
|
||||
## 验收标准
|
||||
## Acceptance Criteria
|
||||
|
||||
1. **自动检测:**
|
||||
* 在系统语言设置为中文(简体)的环境下启动应用,应用界面默认显示为中文。
|
||||
* 在系统语言设置为英语或其他非中文语言的环境下启动应用,应用界面默认显示为英语。
|
||||
2. **手动切换:**
|
||||
* 用户可以在设置页面将语言从中文切换到英语,界面应立即更新,无需重启。
|
||||
* 用户可以在设置页面将语言从英语切换到中文,界面应立即更新,无需重启。
|
||||
3. **持久化:**
|
||||
* 用户手动更改语言后,重启应用,应用应保持用户选择的语言,而不是重新检测系统语言。
|
||||
4. **完整性:**
|
||||
* 应用的所有可见文本(包括主页、设置页、状态栏、弹窗提示)都应正确显示对应的语言,没有遗漏的硬编码字符串。
|
||||
1. **Automatic detection:**
|
||||
* When OS language is Simplified Chinese, app defaults to Chinese on first launch.
|
||||
* When OS language is English or another non-Chinese language, app defaults to English on first launch.
|
||||
2. **Manual switching:**
|
||||
* Users can switch from Chinese to English in Settings, and UI updates immediately without restart.
|
||||
* Users can switch from English to Chinese in Settings, and UI updates immediately without restart.
|
||||
3. **Persistence:**
|
||||
* After users manually change language, app restart preserves the selected language instead of re-detecting.
|
||||
4. **Completeness:**
|
||||
* All visible strings (home page, settings page, status bar, popups) render correctly in the selected language with no leftover hardcoded text.
|
||||
@@ -1,59 +1,59 @@
|
||||
# 规格:本地化
|
||||
# Spec: Localization
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: 自动语言检测
|
||||
### Requirement: Automatic Language Detection
|
||||
|
||||
应用在首次启动时 MUST 自动检测用户的系统语言并设置相应的界面语言。
|
||||
On first launch, the application MUST automatically detect the user's system language and set the corresponding UI language.
|
||||
|
||||
#### Scenario: 系统语言为中文
|
||||
#### Scenario: System language is Chinese
|
||||
|
||||
Given 用户首次打开应用
|
||||
And 用户的系统语言设置为中文 (zh-CN)
|
||||
And 本地存储中没有保存语言偏好
|
||||
When 应用加载时
|
||||
Then 界面应该显示为简体中文 (`zh-CN`)
|
||||
Given the user opens the app for the first time
|
||||
And the user's system language is set to Chinese (`zh-CN`)
|
||||
And no language preference is saved in local storage
|
||||
When the app loads
|
||||
Then the UI should be displayed in Simplified Chinese (`zh-CN`)
|
||||
|
||||
#### Scenario: 系统语言为其他(非中文)
|
||||
#### Scenario: System language is non-Chinese
|
||||
|
||||
Given 用户首次打开应用
|
||||
And 用户的系统语言设置为法语 (fr)
|
||||
And 本地存储中没有保存语言偏好
|
||||
When 应用加载时
|
||||
Then 界面应该回退显示为英语 (`en`)
|
||||
Given the user opens the app for the first time
|
||||
And the user's system language is set to French (`fr`)
|
||||
And no language preference is saved in local storage
|
||||
When the app loads
|
||||
Then the UI should fall back to English (`en`)
|
||||
|
||||
### Requirement: 语言切换
|
||||
### Requirement: Language Switching
|
||||
|
||||
用户 MUST 能够在支持的语言之间切换,且手动选择 MUST 覆盖自动检测。
|
||||
Users MUST be able to switch between supported languages, and manual selection MUST override automatic detection.
|
||||
|
||||
#### Scenario: 切换语言
|
||||
#### Scenario: Switch language
|
||||
|
||||
Given 用户在设置页面
|
||||
When 用户从语言下拉菜单中选择 "English"
|
||||
Then 界面应该立即切换为英语
|
||||
And 偏好应该保存到本地存储
|
||||
Given the user is on the settings page
|
||||
When the user selects "English" from the language dropdown
|
||||
Then the UI should switch to English immediately
|
||||
And the preference should be saved to local storage
|
||||
|
||||
### Requirement: 持久化
|
||||
### Requirement: Persistence
|
||||
|
||||
用户的手动语言偏好 MUST 在会话之间持久化,并优先于系统语言。
|
||||
The user's manual language preference MUST persist across sessions and take precedence over system language.
|
||||
|
||||
#### Scenario: 持久化语言偏好
|
||||
#### Scenario: Persist language preference
|
||||
|
||||
Given 用户已手动选择 "English" 作为首选语言
|
||||
And 用户的系统语言设置为中文
|
||||
When 用户重启应用
|
||||
Then 界面应该显示为英语(尊重用户选择)
|
||||
Given the user has manually selected "English" as preferred language
|
||||
And the user's system language is Chinese
|
||||
When the user restarts the app
|
||||
Then the UI should display English (respecting user preference)
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: i18n 配置更新
|
||||
### Requirement: Update i18n Configuration
|
||||
|
||||
i18n 配置 MUST 更新以支持语言检测插件。
|
||||
i18n configuration MUST be updated to support the language detection plugin.
|
||||
|
||||
#### Scenario: i18n 配置
|
||||
#### Scenario: i18n configuration
|
||||
|
||||
`src/localization/i18n.ts` 文件必须更新为:
|
||||
`src/localization/i18n.ts` must be updated to:
|
||||
|
||||
1. 集成 `i18next-browser-languagedetector`。
|
||||
2. 配置检测顺序:`['localStorage', 'navigator']`。
|
||||
3. 包含 `zh-CN` 资源对象。
|
||||
1. Integrate `i18next-browser-languagedetector`.
|
||||
2. Configure detection order as `['localStorage', 'navigator']`.
|
||||
3. Include `zh-CN` resource objects.
|
||||
@@ -1,10 +1,10 @@
|
||||
# 任务:应用本地化(自动检测系统语言)
|
||||
# Tasks: App Localization (Automatic System Language Detection)
|
||||
|
||||
* \[x] 安装 `i18next-browser-languagedetector` 依赖。 <!-- id: install-dependency -->
|
||||
* \[x] 更新 `src/localization/i18n.ts` 以配置语言检测器并包含 `zh-CN` 资源。 <!-- id: update-i18n-config -->
|
||||
* \[x] 验证 `src/actions/language.ts` 逻辑,确保与自动检测兼容。 <!-- id: verify-language-actions -->
|
||||
* \[x] 更新 `src/components/StatusBar.tsx` 以使用翻译。 <!-- id: localize-statusbar -->
|
||||
* \[x] 更新 `src/components/AccountCard.tsx` 以使用翻译。 <!-- id: localize-accountcard -->
|
||||
* \[x] 更新 `src/pages/index.tsx`(主页)以使用翻译。 <!-- id: localize-homepage -->
|
||||
* \[x] 更新 `src/pages/settings.tsx` 以使用翻译并添加语言切换器。 <!-- id: localize-settings -->
|
||||
* \[x] 运行应用验证语言检测和手动切换功能。 <!-- id: verify-localization -->
|
||||
* \[x] Install `i18next-browser-languagedetector`. <!-- id: install-dependency -->
|
||||
* \[x] Update `src/localization/i18n.ts` to configure language detection and include `zh-CN` resources. <!-- id: update-i18n-config -->
|
||||
* \[x] Verify `src/actions/language.ts` logic is compatible with auto-detection. <!-- id: verify-language-actions -->
|
||||
* \[x] Update `src/components/StatusBar.tsx` to use translations. <!-- id: localize-statusbar -->
|
||||
* \[x] Update `src/components/AccountCard.tsx` to use translations. <!-- id: localize-accountcard -->
|
||||
* \[x] Update `src/pages/index.tsx` (home page) to use translations. <!-- id: localize-homepage -->
|
||||
* \[x] Update `src/pages/settings.tsx` to use translations and add a language switcher. <!-- id: localize-settings -->
|
||||
* \[x] Run the app to verify language detection and manual switching. <!-- id: verify-localization -->
|
||||
+98
-95
@@ -2,105 +2,108 @@
|
||||
|
||||
## Purpose
|
||||
|
||||
Antigravity Manager 是一个综合性的 Antigravity 增强工具,旨在打破 AI 开发的资源限制。它不仅解决了 Antigravity IDE 客户端无法原生支持多账号切换的痛点,还引入了企业级的 AI 服务账号池管理功能。通过接管应用的配置状态和云端 API 资源,它允许用户在无限个本地账号和云端 AI 服务之间无缝切换,实现 "无限" 的 AI 调用体验。
|
||||
Antigravity Manager is a comprehensive enhancement tool for Antigravity, designed to remove AI development resource limits. It not only solves the lack of native multi-account switching in Antigravity IDE, but also introduces enterprise-grade AI account pool management. By taking control of app configuration state and cloud API resources, it allows users to switch seamlessly between unlimited local accounts and cloud AI services for an effectively "unlimited" AI usage experience.
|
||||
|
||||
**核心目标:**
|
||||
**Core goals:**
|
||||
|
||||
* **本地多账号切换**:无缝切换 Antigravity IDE 的本地用户状态,保护数据完整性(自动备份)。
|
||||
* **AI 资源池管理**(新):集中管理 Google Gemini、Claude 3.5 等 AI 服务的账号池。
|
||||
* **智能配额监控**(新):实时监控 API 配额(Quota)和健康度,提供可视化仪表盘。
|
||||
* **自动资源调度**(新):当当前账号配额耗尽时,自动切换到最佳可用账号(Token 保活与轮询)。
|
||||
* **跨平台支持**:统一的 macOS、Windows、Linux 体验。
|
||||
* **Local multi-account switching**: Seamlessly switch Antigravity IDE local user state while protecting data integrity (automatic backup).
|
||||
* **AI resource pool management (new)**: Centrally manage account pools for Google Gemini, Claude 3.5, and similar services.
|
||||
* **Intelligent quota monitoring (new)**: Monitor API quota and health in real time with a visual dashboard.
|
||||
* **Automatic resource scheduling (new)**: Automatically switch to the best available account when the current one runs out of quota (token keepalive + polling).
|
||||
* **Cross-platform support**: Consistent macOS, Windows, and Linux experience.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
* **Electron 39** - 跨平台桌面应用框架
|
||||
* **React 19.2** - UI 框架
|
||||
* **TypeScript 5.9** - 类型安全的开发语言
|
||||
* **Shadcn UI** - 现代化 UI 组件库
|
||||
* **Tailwind CSS 4** - 样式框架
|
||||
* **oRPC** - 类型安全的 IPC 通信
|
||||
* **TanStack Router** - 文件路由
|
||||
* **React Query** - 服务器状态管理
|
||||
* **better-sqlite3** - SQLite 数据库访问
|
||||
* **Vite** - 构建工具
|
||||
* **Vitest** - 单元测试
|
||||
* **Playwright** - 端到端测试
|
||||
* **Electron Forge** - 应用打包和分发
|
||||
* **Electron 39** - Cross-platform desktop framework
|
||||
* **React 19.2** - UI framework
|
||||
* **TypeScript 5.9** - Type-safe development language
|
||||
* **Shadcn UI** - Modern UI component library
|
||||
* **Tailwind CSS 4** - Styling framework
|
||||
* **oRPC** - Type-safe IPC communication
|
||||
* **TanStack Router** - File-based routing
|
||||
* **React Query** - Server state management
|
||||
* **better-sqlite3** - SQLite data access
|
||||
* **Vite** - Build tool
|
||||
* **Vitest** - Unit testing
|
||||
* **Playwright** - End-to-end testing
|
||||
* **Electron Forge** - Packaging and distribution
|
||||
|
||||
## Project Conventions
|
||||
|
||||
### Code Style
|
||||
|
||||
* TypeScript strict mode
|
||||
* ESLint + Prettier 自动格式化
|
||||
* 函数和变量使用 camelCase
|
||||
* 组件使用 PascalCase
|
||||
* 接口使用 PascalCase,以 I 开头(可选)
|
||||
* 类型使用 PascalCase
|
||||
* 2 空格缩进
|
||||
* 单引号字符串
|
||||
* 尾随逗号
|
||||
* TypeScript strict mode
|
||||
* ESLint + Prettier auto-formatting
|
||||
* Use camelCase for functions and variables
|
||||
* Use PascalCase for components
|
||||
* Use PascalCase for interfaces, optionally prefixed with `I`
|
||||
* Use PascalCase for types
|
||||
* 2-space indentation
|
||||
* Single-quoted strings
|
||||
* Trailing commas
|
||||
|
||||
### Architecture Patterns
|
||||
|
||||
```
|
||||
```plaintext
|
||||
src/
|
||||
├── main.ts # Electron 主进程
|
||||
├── preload.ts # 预加载脚本
|
||||
├── renderer.ts # 渲染进程入口
|
||||
├── ipc/ # IPC 通信层
|
||||
│ ├── account/ # 本地 IDE 账号管理 IPC
|
||||
│ ├── cloud/ # 云端 AI 资源管理 IPC(新)
|
||||
│ ├── database/ # 数据库操作 IPC
|
||||
│ └── process/ # 进程管理 IPC
|
||||
├── services/ # 业务逻辑服务层(新)
|
||||
│ ├── QuotaService.ts # 配额监控服务
|
||||
│ └── TokenService.ts # Token 保活服务
|
||||
├── actions/ # 渲染进程操作(oRPC 客户端)
|
||||
├── components/ # React 组件
|
||||
├── routes/ # 页面路由
|
||||
├── layouts/ # 布局组件
|
||||
├── utils/ # 工具函数
|
||||
├── types/ # TypeScript 类型定义
|
||||
└── tests/ # 测试文件
|
||||
├── main.ts # Electron main process
|
||||
├── preload.ts # Preload script
|
||||
├── renderer.ts # Renderer entry
|
||||
├── ipc/ # IPC communication layer
|
||||
│ ├── account/ # Local IDE account IPC
|
||||
│ ├── cloud/ # Cloud AI resource IPC (new)
|
||||
│ ├── database/ # Database operation IPC
|
||||
│ └── process/ # Process management IPC
|
||||
├── services/ # Business service layer (new)
|
||||
│ ├── QuotaService.ts # Quota monitoring service
|
||||
│ └── TokenService.ts # Token keepalive service
|
||||
├── actions/ # Renderer actions (oRPC client)
|
||||
├── components/ # React components
|
||||
├── routes/ # Page routes
|
||||
├── layouts/ # Layout components
|
||||
├── utils/ # Utility functions
|
||||
├── types/ # TypeScript type definitions
|
||||
└── tests/ # Test files
|
||||
```
|
||||
|
||||
**设计模式:**
|
||||
**Design patterns:**
|
||||
|
||||
* **关注点分离**:主进程处理系统操作和网络代理,渲染进程处理 UI。
|
||||
* **Service 层**:引入 Service 层处理复杂的配额轮询和 Token 刷新逻辑。
|
||||
* **类型安全 IPC**:使用 oRPC 确保主进程和渲染进程之间的类型安全通信。
|
||||
* **状态管理**:React Query 管理服务器状态和异步配额数据。
|
||||
* **Separation of concerns**: Main process handles system operations and network proxy; renderer handles UI.
|
||||
* **Service layer**: Encapsulates complex quota polling and token refresh logic.
|
||||
* **Type-safe IPC**: Uses oRPC to enforce type-safe communication between main and renderer.
|
||||
* **State management**: React Query manages server state and async quota data.
|
||||
|
||||
### Testing Strategy
|
||||
|
||||
* **单元测试(Vitest)**:测试 IPC 处理程序、Service 逻辑、工具函数。
|
||||
* **集成测试(Vitest)**:测试完整的 IPC 流程。
|
||||
* **端到端测试(Playwright)**:测试用户工作流。
|
||||
* **覆盖率目标**:核心逻辑 >80%。
|
||||
* **Unit tests (Vitest)**: IPC handlers, service logic, utility functions.
|
||||
* **Integration tests (Vitest)**: End-to-end IPC flow.
|
||||
* **End-to-end tests (Playwright)**: User workflows.
|
||||
* **Coverage target**: Core logic > 80%.
|
||||
|
||||
### Git Workflow
|
||||
|
||||
* **主分支**:`main`
|
||||
* **开发分支**:`develop`
|
||||
* **提交规范**:语义化提交 (feat, fix, docs, refactor, test, chore)
|
||||
* **Main branch**: `main`
|
||||
* **Development branch**: `develop`
|
||||
* **Commit style**: Conventional commits (`feat`, `fix`, `docs`, `refactor`, `test`, `chore`)
|
||||
|
||||
## Domain Context
|
||||
|
||||
### 1. Antigravity IDE 数据结构(本地)
|
||||
### 1. Antigravity IDE Data Structure (Local)
|
||||
|
||||
**Database locations:**
|
||||
|
||||
**数据库位置:**
|
||||
* macOS: `~/Library/Application Support/Antigravity/User/globalStorage/state.vscdb`
|
||||
* Windows: `%APPDATA%/Antigravity/User/globalStorage/state.vscdb`
|
||||
* Linux: `~/.config/Antigravity/User/globalStorage/state.vscdb`
|
||||
|
||||
**关键数据库键:**
|
||||
* `antigravityAuthStatus`: 认证状态和用户信息。
|
||||
**Key database fields:**
|
||||
|
||||
### 2. AI 服务资源结构(云端/新)
|
||||
* `antigravityAuthStatus`: Authentication status and user information.
|
||||
|
||||
### 2. AI Service Resource Structure (Cloud / New)
|
||||
|
||||
**Account model:**
|
||||
|
||||
**账号模型:**
|
||||
```json
|
||||
{
|
||||
"id": "uuid",
|
||||
@@ -115,49 +118,49 @@ src/
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 进程管理策略
|
||||
### 3. Process Management Strategy
|
||||
|
||||
* **三阶段关闭**:优雅关闭 -> SIGTERM -> SIGKILL。
|
||||
* **Three-phase shutdown**: Graceful close -> SIGTERM -> SIGKILL.
|
||||
|
||||
## Important Constraints
|
||||
|
||||
### 技术约束
|
||||
### Technical Constraints
|
||||
|
||||
* **数据库访问**:访问本地 IDE 数据库时需注意文件锁。
|
||||
* **网络访问**:需要访问外部 API (Google/Anthropic) 以获取配额信息。
|
||||
* **凭证安全**:OAuth Token 和 Refresh Token 必须使用系统级加密存储 (Keytar / SQLite Encrypted)。
|
||||
* **并发控制**:轮询配额时需注意频率,避免触发 API 封控。
|
||||
* **Database access**: Handle file locks when accessing local IDE databases.
|
||||
* **Network access**: External API access (Google/Anthropic) is required for quota retrieval.
|
||||
* **Credential security**: OAuth and refresh tokens must use system-level encrypted storage (Keytar / encrypted SQLite).
|
||||
* **Concurrency control**: Quota polling frequency must be controlled to avoid API throttling or blocking.
|
||||
|
||||
### 用户体验约束
|
||||
### UX Constraints
|
||||
|
||||
* **响应时间**:账号切换应在 5 秒内完成。
|
||||
* **静默运行**:支持最小化到托盘,后台自动刷新 Token。
|
||||
* **数据安全**:切换前必须自动备份当前状态。
|
||||
* **Response time**: Account switching should complete within 5 seconds.
|
||||
* **Silent mode**: Support tray minimization and background token refresh.
|
||||
* **Data safety**: Always back up current state before switching.
|
||||
|
||||
## External Dependencies
|
||||
|
||||
### 系统依赖
|
||||
### System Dependencies
|
||||
|
||||
* **Antigravity IDE**:本地管理目标。
|
||||
* **SQLite**:本地数据读取。
|
||||
* **Antigravity IDE**: Local target to manage.
|
||||
* **SQLite**: Local data reads.
|
||||
|
||||
### Node.js 依赖(重点)
|
||||
### Node.js Dependencies (Key)
|
||||
|
||||
* `better-sqlite3`: 数据库访问。
|
||||
* `electron`: 桌面框架。
|
||||
* `node-fetch` / `axios`: 网络请求。
|
||||
* `tar` / `adm-zip`: 备份压缩。
|
||||
* `better-sqlite3`: Database access.
|
||||
* `electron`: Desktop framework.
|
||||
* `node-fetch` / `axios`: Network requests.
|
||||
* `tar` / `adm-zip`: Backup compression.
|
||||
|
||||
### 外部服务
|
||||
### External Services
|
||||
|
||||
* **Google Gemini API**: 用于配额检查。
|
||||
* **Anthropic API**: 用于配额检查。
|
||||
* **OAuth 2.0 端点**: 用于账号授权。
|
||||
* **Google Gemini API**: For quota checks.
|
||||
* **Anthropic API**: For quota checks.
|
||||
* **OAuth 2.0 endpoints**: For account authorization.
|
||||
|
||||
### 文件系统依赖
|
||||
### Filesystem Dependencies
|
||||
|
||||
* `~/.antigravity-agent/`
|
||||
* `accounts.json`: 本地 IDE 账号索引。
|
||||
* `cloud_accounts.db`: (新) 云端账号池数据库 (SQLite)。
|
||||
* `backups/`: 备份文件。
|
||||
* `app.log`: 应用日志。
|
||||
* `~/.antigravity-agent/`
|
||||
* `accounts.json`: Local IDE account index.
|
||||
* `cloud_accounts.db`: (new) Cloud account pool database (SQLite).
|
||||
* `backups/`: Backup files.
|
||||
* `app.log`: Application log.
|
||||
Reference in new issue
Block a user