Initial Commit

This commit is contained in:
Draculabo committed 2025-12-23 01:38:53 +08:00
commit d0417339c1
158 files changed
+31368

No files matched your search

+455
View File
@@ -0,0 +1,455 @@
# OpenSpec Instructions
Instructions for AI coding assistants using OpenSpec for spec-driven development.
## TL;DR Quick Checklist
- Search existing work: `openspec spec list --long`, `openspec list` (use `rg` only for full-text search)
- Decide scope: new capability vs modify existing capability
- Pick a unique `change-id`: kebab-case, verb-led (`add-`, `update-`, `remove-`, `refactor-`)
- Scaffold: `proposal.md`, `tasks.md`, `design.md` (only if needed), and delta specs per affected capability
- Write deltas: use `## ADDED|MODIFIED|REMOVED|RENAMED Requirements`; include at least one `#### Scenario:` per requirement
- Validate: `openspec validate [change-id] --strict` and fix issues
- Request approval: Do not start implementation until proposal is approved
## Three-Stage Workflow
### Stage 1: Creating Changes
Create proposal when you need to:
- Add features or functionality
- Make breaking changes (API, schema)
- Change architecture or patterns
- Optimize performance (changes behavior)
- Update security patterns
Triggers (examples):
- "Help me create a change proposal"
- "Help me plan a change"
- "Help me create a proposal"
- "I want to create a spec proposal"
- "I want to create a spec"
Loose matching guidance:
- Contains one of: `proposal`, `change`, `spec`
- With one of: `create`, `plan`, `make`, `start`, `help`
Skip proposal for:
- Bug fixes (restore intended behavior)
- Typos, formatting, comments
- Dependency updates (non-breaking)
- Configuration changes
- Tests for existing behavior
**Workflow**
1. Review `openspec/project.md`, `openspec list`, and `openspec list --specs` to understand current context.
2. Choose a unique verb-led `change-id` and scaffold `proposal.md`, `tasks.md`, optional `design.md`, and spec deltas under `openspec/changes/<id>/`.
3. Draft spec deltas using `## ADDED|MODIFIED|REMOVED Requirements` with at least one `#### Scenario:` per requirement.
4. Run `openspec validate <id> --strict` and resolve any issues before sharing the proposal.
### Stage 2: Implementing Changes
Track these steps as TODOs and complete them one by one.
1. **Read proposal.md** - Understand what's being built
2. **Read design.md** (if exists) - Review technical decisions
3. **Read tasks.md** - Get implementation checklist
4. **Implement tasks sequentially** - Complete in order
5. **Confirm completion** - Ensure every item in `tasks.md` is finished before updating statuses
6. **Update checklist** - After all work is done, set every task to `- [x]` so the list reflects reality
7. **Approval gate** - Do not start implementation until the proposal is reviewed and approved
### Stage 3: Archiving Changes
After deployment, create separate PR to:
- Move `changes/[name]/` → `changes/archive/YYYY-MM-DD-[name]/`
- Update `specs/` if capabilities changed
- Use `openspec archive <change-id> --skip-specs --yes` for tooling-only changes (always pass the change ID explicitly)
- Run `openspec validate --strict` to confirm the archived change passes checks
## Before Any Task
**Context Checklist:**
- [ ] Read relevant specs in `specs/[capability]/spec.md`
- [ ] Check pending changes in `changes/` for conflicts
- [ ] Read `openspec/project.md` for conventions
- [ ] Run `openspec list` to see active changes
- [ ] Run `openspec list --specs` to see existing capabilities
**Before Creating Specs:**
- Always check if capability already exists
- Prefer modifying existing specs over creating duplicates
- Use `openspec show [spec]` to review current state
- If request is ambiguous, ask 1–2 clarifying questions before scaffolding
### Search Guidance
- Enumerate specs: `openspec spec list --long` (or `--json` for scripts)
- Enumerate changes: `openspec list` (or `openspec change list --json` - deprecated but available)
- Show details:
- Spec: `openspec show <spec-id> --type spec` (use `--json` for filters)
- Change: `openspec show <change-id> --json --deltas-only`
- Full-text search (use ripgrep): `rg -n "Requirement:|Scenario:" openspec/specs`
## Quick Start
### CLI Commands
```bash
# Essential commands
openspec list # List active changes
openspec list --specs # List specifications
openspec show [item] # Display change or spec
openspec validate [item] # Validate changes or specs
openspec archive <change-id> [--yes|-y] # Archive after deployment (add --yes for non-interactive runs)
# Project management
openspec init [path] # Initialize OpenSpec
openspec update [path] # Update instruction files
# Interactive mode
openspec show # Prompts for selection
openspec validate # Bulk validation mode
# Debugging
openspec show [change] --json --deltas-only
openspec validate [change] --strict
```
### Command Flags
- `--json` - Machine-readable output
- `--type change|spec` - Disambiguate items
- `--strict` - Comprehensive validation
- `--no-interactive` - Disable prompts
- `--skip-specs` - Archive without spec updates
- `--yes`/`-y` - Skip confirmation prompts (non-interactive archive)
## Directory Structure
```
openspec/
├── project.md # Project conventions
├── specs/ # Current truth - what IS built
│ └── [capability]/ # Single focused capability
│ ├── spec.md # Requirements and scenarios
│ └── design.md # Technical patterns
├── changes/ # Proposals - what SHOULD change
│ ├── [change-name]/
│ │ ├── proposal.md # Why, what, impact
│ │ ├── tasks.md # Implementation checklist
│ │ ├── design.md # Technical decisions (optional; see criteria)
│ │ └── specs/ # Delta changes
│ │ └── [capability]/
│ │ └── spec.md # ADDED/MODIFIED/REMOVED
│ └── archive/ # Completed changes
```
## Creating Change Proposals
### Decision Tree
```
New request?
├─ Bug fix restoring spec behavior? → Fix directly
├─ Typo/format/comment? → Fix directly
├─ New feature/capability? → Create proposal
├─ Breaking change? → Create proposal
├─ Architecture change? → Create proposal
└─ Unclear? → Create proposal (safer)
```
### Proposal Structure
1. **Create directory:** `changes/[change-id]/` (kebab-case, verb-led, unique)
2. **Write proposal.md:**
```markdown
# Change: [Brief description of change]
## Why
[1-2 sentences on problem/opportunity]
## What Changes
- [Bullet list of changes]
- [Mark breaking changes with **BREAKING**]
## Impact
- Affected specs: [list capabilities]
- Affected code: [key files/systems]
```
3. **Create spec deltas:** `specs/[capability]/spec.md`
```markdown
## ADDED Requirements
### Requirement: New Feature
The system SHALL provide...
#### Scenario: Success case
- **WHEN** user performs action
- **THEN** expected result
## MODIFIED Requirements
### Requirement: Existing Feature
[Complete modified requirement]
## REMOVED Requirements
### Requirement: Old Feature
**Reason**: [Why removing]
**Migration**: [How to handle]
```
If multiple capabilities are affected, create multiple delta files under `changes/[change-id]/specs/<capability>/spec.md`—one per capability.
4. **Create tasks.md:**
```markdown
## 1. Implementation
- [ ] 1.1 Create database schema
- [ ] 1.2 Implement API endpoint
- [ ] 1.3 Add frontend component
- [ ] 1.4 Write tests
```
5. **Create design.md when needed:**
Create `design.md` if any of the following apply; otherwise omit it:
- Cross-cutting change (multiple services/modules) or a new architectural pattern
- New external dependency or significant data model changes
- Security, performance, or migration complexity
- Ambiguity that benefits from technical decisions before coding
Minimal `design.md` skeleton:
```markdown
## Context
[Background, constraints, stakeholders]
## Goals / Non-Goals
- Goals: [...]
- Non-Goals: [...]
## Decisions
- Decision: [What and why]
- Alternatives considered: [Options + rationale]
## Risks / Trade-offs
- [Risk] → Mitigation
## Migration Plan
[Steps, rollback]
## Open Questions
- [...]
```
## Spec File Format
### Critical: Scenario Formatting
**CORRECT** (use #### headers):
```markdown
#### Scenario: User login success
- **WHEN** valid credentials provided
- **THEN** return JWT token
```
**WRONG** (don't use bullets or bold):
```markdown
- **Scenario: User login** ❌
**Scenario**: User login ❌
### Scenario: User login ❌
```
Every requirement MUST have at least one scenario.
### Requirement Wording
- Use SHALL/MUST for normative requirements (avoid should/may unless intentionally non-normative)
### Delta Operations
- `## ADDED Requirements` - New capabilities
- `## MODIFIED Requirements` - Changed behavior
- `## REMOVED Requirements` - Deprecated features
- `## RENAMED Requirements` - Name changes
Headers matched with `trim(header)` - whitespace ignored.
#### When to use ADDED vs MODIFIED
- ADDED: Introduces a new capability or sub-capability that can stand alone as a requirement. Prefer ADDED when the change is orthogonal (e.g., adding "Slash Command Configuration") rather than altering the semantics of an existing requirement.
- MODIFIED: Changes the behavior, scope, or acceptance criteria of an existing requirement. Always paste the full, updated requirement content (header + all scenarios). The archiver will replace the entire requirement with what you provide here; partial deltas will drop previous details.
- RENAMED: Use when only the name changes. If you also change behavior, use RENAMED (name) plus MODIFIED (content) referencing the new name.
Common pitfall: Using MODIFIED to add a new concern without including the previous text. This causes loss of detail at archive time. If you aren’t explicitly changing the existing requirement, add a new requirement under ADDED instead.
Authoring a MODIFIED requirement correctly:
1) Locate the existing requirement in `openspec/specs/<capability>/spec.md`.
2) Copy the entire requirement block (from `### Requirement: ...` through its scenarios).
3) Paste it under `## MODIFIED Requirements` and edit to reflect the new behavior.
4) Ensure the header text matches exactly (whitespace-insensitive) and keep at least one `#### Scenario:`.
Example for RENAMED:
```markdown
## RENAMED Requirements
- FROM: `### Requirement: Login`
- TO: `### Requirement: User Authentication`
```
## Troubleshooting
### Common Errors
**"Change must have at least one delta"**
- Check `changes/[name]/specs/` exists with .md files
- Verify files have operation prefixes (## ADDED Requirements)
**"Requirement must have at least one scenario"**
- Check scenarios use `#### Scenario:` format (4 hashtags)
- Don't use bullet points or bold for scenario headers
**Silent scenario parsing failures**
- Exact format required: `#### Scenario: Name`
- Debug with: `openspec show [change] --json --deltas-only`
### Validation Tips
```bash
# Always use strict mode for comprehensive checks
openspec validate [change] --strict
# Debug delta parsing
openspec show [change] --json | jq '.deltas'
# Check specific requirement
openspec show [spec] --json -r 1
```
## Happy Path Script
```bash
# 1) Explore current state
openspec spec list --long
openspec list
# Optional full-text search:
# rg -n "Requirement:|Scenario:" openspec/specs
# rg -n "^#|Requirement:" openspec/changes
# 2) Choose change id and scaffold
CHANGE=add-two-factor-auth
mkdir -p openspec/changes/$CHANGE/{specs/auth}
printf "## Why\n...\n\n## What Changes\n- ...\n\n## Impact\n- ...\n" > openspec/changes/$CHANGE/proposal.md
printf "## 1. Implementation\n- [ ] 1.1 ...\n" > openspec/changes/$CHANGE/tasks.md
# 3) Add deltas (example)
cat > openspec/changes/$CHANGE/specs/auth/spec.md << 'EOF'
## ADDED Requirements
### Requirement: Two-Factor Authentication
#### Scenario: OTP required
- **WHEN** valid credentials are provided
- **THEN** an OTP challenge is required
EOF
# 4) Validate
openspec validate $CHANGE --strict
```
## Multi-Capability Example
```
openspec/changes/add-2fa-notify/
├── proposal.md
├── tasks.md
└── specs/
├── auth/
│ └── spec.md # ADDED: Two-Factor Authentication
└── notifications/
└── spec.md # ADDED: OTP email notification
```
auth/spec.md
```markdown
## ADDED Requirements
### Requirement: Two-Factor Authentication
...
```
notifications/spec.md
```markdown
## ADDED Requirements
### Requirement: OTP Email Notification
...
```
## Best Practices
### Simplicity First
- Default to <100 lines of new code
- Single-file implementations until proven insufficient
- Avoid frameworks without clear justification
- Choose boring, proven patterns
### Complexity Triggers
Only add complexity with:
- Performance data showing current solution too slow
- Concrete scale requirements (>1000 users, >100MB data)
- Multiple proven use cases requiring abstraction
### Clear References
- Use `file.ts:42` format for code locations
- Reference specs as `specs/auth/spec.md`
- Link related changes and PRs
### Capability Naming
- Use verb-noun: `user-auth`, `payment-capture`
- Single purpose per capability
- 10-minute understandability rule
- Split if description needs "AND"
### Change ID Naming
- Use kebab-case, short and descriptive: `add-two-factor-auth`
- Prefer verb-led prefixes: `add-`, `update-`, `remove-`, `refactor-`
- Ensure uniqueness; if taken, append `-2`, `-3`, etc.
## Tool Selection Guide
| Task | Tool | Why |
|------|------|-----|
| Find files by pattern | Glob | Fast pattern matching |
| Search code content | Grep | Optimized regex search |
| Read specific files | Read | Direct file access |
| Explore unknown scope | Task | Multi-step investigation |
## Error Recovery
### Change Conflicts
1. Run `openspec list` to see active changes
2. Check for overlapping specs
3. Coordinate with change owners
4. Consider combining proposals
### Validation Failures
1. Run with `--strict` flag
2. Check JSON output for details
3. Verify spec file format
4. Ensure scenarios properly formatted
### Missing Context
1. Read project.md first
2. Check related specs
3. Review recent archives
4. Ask for clarification
## Quick Reference
### Stage Indicators
- `changes/` - Proposed, not yet built
- `specs/` - Built and deployed
- `archive/` - Completed changes
### File Purposes
- `proposal.md` - Why and what
- `tasks.md` - Implementation steps
- `design.md` - Technical decisions
- `spec.md` - Requirements and behavior
### CLI Essentials
```bash
openspec list # What's in progress?
openspec show [item] # View details
openspec validate --strict # Is it correct?
openspec archive <change-id> [--yes|-y] # Mark complete (add --yes for automation)
```
Remember: Specs are truth. Changes are proposals. Keep them in sync.
@@ -0,0 +1,30 @@
# 设计:多语言支持
## 架构
应用使用 `react-i18next` 进行国际化,并配合 `i18next-browser-languagedetector` 进行语言检测。配置集中在 `src/localization/i18n.ts` 中。
### 语言资源
翻译资源将作为 JSON 对象构建在 `i18n.ts` 中(如果太大则分文件)。
我们将在 `resources` 对象中添加 `zh-CN` 键。
### 默认语言策略
我们将引入 `LanguageDetector` 插件。
`i18n.use(LanguageDetector).init({...})` 将被配置为首先检查 `localStorage`,然后检查 `navigator`(浏览器/系统语言)。
`fallbackLng` 将保持为 `'en'`,作为最后的兜底。
### 键映射
我们将把现有的英文字符串映射到语义键(例如 `home.title`, `settings.theme`)。
## 数据流
1. 应用启动。
2. `i18next` 初始化,通过 `LanguageDetector` 确定语言:
* 检查 `localStorage` 是否有保存的偏好。
* 如果无,检查 `navigator.language`。
* 如果检测到的语言受支持(`en` 或 `zh-CN`),则使用该语言。
* 否则,使用 `fallbackLng` (`en`)。
3. 组件使用 `useTranslation` hook 根据当前语言获取字符串。
@@ -0,0 +1,41 @@
# 提案:应用本地化(自动检测系统语言)
**变更 ID:** `localize-app-auto-detect`
## 摘要
为 Antigravity Manager 应用添加多语言支持,并根据用户的操作系统语言自动设置默认语言。如果系统语言不受支持,则回退到英语。这包括更新 i18n 配置,添加中文翻译资源,并集成语言检测插件。
## 动机
为了提供最佳的用户体验,应用应该能够适应用户的首选语言环境。自动检测系统语言可以减少用户的配置步骤,提供更自然的初次使用体验。
## 建议变更
1. **集成语言检测:** 安装并配置 `i18next-browser-languagedetector` 以自动检测用户语言。
2. **更新 i18n 配置:** 修改 `src/localization/i18n.ts`,启用语言检测,并设置适当的回退语言(英语)。
3. **添加中文资源:** 为 `zh-CN` 创建一个新的翻译资源文件,包含所有应用字符串。
4. **更新语言操作:** 确保 `src/actions/language.ts` 正确处理自动检测和手动覆盖的逻辑。
5. **UI 更新:** 确保所有 UI 组件使用翻译键而不是硬编码字符串。
## 考虑的替代方案
* **强制默认中文:** 已拒绝,为了适应更广泛的国际用户群体,并尊重用户的系统设置。
* **强制默认英语:** 已拒绝,同上。
## 风险
* **检测失败:** 在某些特殊环境(如 Linux 某些发行版)下,语言检测可能不准确,需要确保回退机制可靠。
## 验收标准
1. **自动检测:**
* 在系统语言设置为中文(简体)的环境下启动应用,应用界面默认显示为中文。
* 在系统语言设置为英语或其他非中文语言的环境下启动应用,应用界面默认显示为英语。
2. **手动切换:**
* 用户可以在设置页面将语言从中文切换到英语,界面应立即更新,无需重启。
* 用户可以在设置页面将语言从英语切换到中文,界面应立即更新,无需重启。
3. **持久化:**
* 用户手动更改语言后,重启应用,应用应保持用户选择的语言,而不是重新检测系统语言。
4. **完整性:**
* 应用的所有可见文本(包括主页、设置页、状态栏、弹窗提示)都应正确显示对应的语言,没有遗漏的硬编码字符串。
@@ -0,0 +1,59 @@
# 规格:本地化
## ADDED Requirements
### Requirement: 自动语言检测
应用在首次启动时 MUST 自动检测用户的系统语言并设置相应的界面语言。
#### Scenario: 系统语言为中文
Given 用户首次打开应用
And 用户的系统语言设置为中文 (zh-CN)
And 本地存储中没有保存语言偏好
When 应用加载时
Then 界面应该显示为简体中文 (`zh-CN`)
#### Scenario: 系统语言为其他(非中文)
Given 用户首次打开应用
And 用户的系统语言设置为法语 (fr)
And 本地存储中没有保存语言偏好
When 应用加载时
Then 界面应该回退显示为英语 (`en`)
### Requirement: 语言切换
用户 MUST 能够在支持的语言之间切换,且手动选择 MUST 覆盖自动检测。
#### Scenario: 切换语言
Given 用户在设置页面
When 用户从语言下拉菜单中选择 "English"
Then 界面应该立即切换为英语
And 偏好应该保存到本地存储
### Requirement: 持久化
用户的手动语言偏好 MUST 在会话之间持久化,并优先于系统语言。
#### Scenario: 持久化语言偏好
Given 用户已手动选择 "English" 作为首选语言
And 用户的系统语言设置为中文
When 用户重启应用
Then 界面应该显示为英语(尊重用户选择)
## MODIFIED Requirements
### Requirement: i18n 配置更新
i18n 配置 MUST 更新以支持语言检测插件。
#### Scenario: i18n 配置
`src/localization/i18n.ts` 文件必须更新为:
1. 集成 `i18next-browser-languagedetector`。
2. 配置检测顺序:`['localStorage', 'navigator']`。
3. 包含 `zh-CN` 资源对象。
@@ -0,0 +1,10 @@
# 任务:应用本地化(自动检测系统语言)
* \[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 -->
@@ -0,0 +1,33 @@
# Change: Support WSL Environment
## Summary
Enable Antigravity Manager running in WSL (Windows Subsystem for Linux) to manage the Antigravity application installed on the Windows host.
## Motivation
Users running the manager in a WSL development environment need to interact with the actual Antigravity instance running on Windows, as Antigravity is a Windows application.
## Proposed Changes
### 1. Path Resolution (`src/utils/paths.ts`)
* Implement `isWsl()` utility function.
* In `getAppDataDir()`: If WSL, return the Windows AppData path (e.g., `/mnt/c/Users/<User>/AppData/Roaming/Antigravity`).
* In `getAntigravityExecutablePath()`: If WSL, return the Windows executable path (e.g., `/mnt/c/Users/<User>/AppData/Local/Programs/Antigravity/Antigravity.exe`).
* **Challenge:** Determining the correct Windows username.
* **Strategy:** Assume Windows username matches WSL username, or scan `/mnt/c/Users` for a likely candidate (excluding Public, Default, etc.).
### 2. Process Management (`src/ipc/process/handler.ts`)
* In `isProcessRunning()`: If WSL, execute `tasklist.exe` (via `/mnt/c/Windows/System32/tasklist.exe`) to check for `Antigravity.exe`.
* In `startAntigravity()`: If WSL, execute the Windows executable directly.
* In `closeAntigravity()`: If WSL, use `taskkill.exe` (via `/mnt/c/Windows/System32/taskkill.exe`).
## Acceptance Criteria
* \[ ] Application detects it is running in WSL.
* \[ ] Database file is correctly located on the Windows file system.
* \[ ] "Start" button successfully launches Antigravity on Windows.
* \[ ] "Stop" button successfully terminates Antigravity on Windows.
* \[ ] Process status (Running/Stopped) is correctly reflected in the UI.
@@ -0,0 +1,5 @@
# Tasks: Support WSL Environment
* \[ ] Update `src/utils/paths.ts` to implement `isWsl` and handle Windows paths. <!-- id: update-paths -->
* \[ ] Update `src/ipc/process/handler.ts` to support `tasklist.exe` and `taskkill.exe` in WSL. <!-- id: update-process-handler -->
* \[ ] Verify database connection and process management in WSL. <!-- id: verify-wsl -->
+163
View File
@@ -0,0 +1,163 @@
# Project Context
## Purpose
Antigravity Manager 是一个综合性的 Antigravity 增强工具,旨在打破 AI 开发的资源限制。它不仅解决了 Antigravity IDE 客户端无法原生支持多账号切换的痛点,还引入了企业级的 AI 服务账号池管理功能。通过接管应用的配置状态和云端 API 资源,它允许用户在无限个本地账号和云端 AI 服务之间无缝切换,实现 "无限" 的 AI 调用体验。
**核心目标:**
* **本地多账号切换**:无缝切换 Antigravity IDE 的本地用户状态,保护数据完整性(自动备份)。
* **AI 资源池管理**(新):集中管理 Google Gemini、Claude 3.5 等 AI 服务的账号池。
* **智能配额监控**(新):实时监控 API 配额(Quota)和健康度,提供可视化仪表盘。
* **自动资源调度**(新):当当前账号配额耗尽时,自动切换到最佳可用账号(Token 保活与轮询)。
* **跨平台支持**:统一的 macOS、Windows、Linux 体验。
## 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** - 应用打包和分发
## Project Conventions
### Code Style
* TypeScript strict mode
* ESLint + Prettier 自动格式化
* 函数和变量使用 camelCase
* 组件使用 PascalCase
* 接口使用 PascalCase,以 I 开头(可选)
* 类型使用 PascalCase
* 2 空格缩进
* 单引号字符串
* 尾随逗号
### Architecture Patterns
```
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/ # 测试文件
```
**设计模式:**
* **关注点分离**:主进程处理系统操作和网络代理,渲染进程处理 UI。
* **Service 层**:引入 Service 层处理复杂的配额轮询和 Token 刷新逻辑。
* **类型安全 IPC**:使用 oRPC 确保主进程和渲染进程之间的类型安全通信。
* **状态管理**:React Query 管理服务器状态和异步配额数据。
### Testing Strategy
* **单元测试(Vitest)**:测试 IPC 处理程序、Service 逻辑、工具函数。
* **集成测试(Vitest)**:测试完整的 IPC 流程。
* **端到端测试(Playwright)**:测试用户工作流。
* **覆盖率目标**:核心逻辑 >80%。
### Git Workflow
* **主分支**:`main`
* **开发分支**:`develop`
* **提交规范**:语义化提交 (feat, fix, docs, refactor, test, chore)
## Domain Context
### 1. Antigravity IDE 数据结构(本地)
**数据库位置:**
* macOS: `~/Library/Application Support/Antigravity/User/globalStorage/state.vscdb`
* Windows: `%APPDATA%/Antigravity/User/globalStorage/state.vscdb`
* Linux: `~/.config/Antigravity/state.vscdb`
**关键数据库键:**
* `antigravityAuthStatus`: 认证状态和用户信息。
### 2. AI 服务资源结构(云端/新)
**账号模型:**
```json
{
"id": "uuid",
"provider": "google" | "anthropic",
"email": "[email protected]",
"auth_token": "oauth2_token...",
"refresh_token": "...",
"quota_limit": 1000,
"quota_used": 450,
"reset_time": "ISO 8601",
"status": "active" | "rate_limited" | "expired"
}
```
### 3. 进程管理策略
* **三阶段关闭**:优雅关闭 -> SIGTERM -> SIGKILL。
## Important Constraints
### 技术约束
* **数据库访问**:访问本地 IDE 数据库时需注意文件锁。
* **网络访问**:需要访问外部 API (Google/Anthropic) 以获取配额信息。
* **凭证安全**:OAuth Token 和 Refresh Token 必须使用系统级加密存储 (Keytar / SQLite Encrypted)。
* **并发控制**:轮询配额时需注意频率,避免触发 API 封控。
### 用户体验约束
* **响应时间**:账号切换应在 5 秒内完成。
* **静默运行**:支持最小化到托盘,后台自动刷新 Token。
* **数据安全**:切换前必须自动备份当前状态。
## External Dependencies
### 系统依赖
* **Antigravity IDE**:本地管理目标。
* **SQLite**:本地数据读取。
### Node.js 依赖(重点)
* `better-sqlite3`: 数据库访问。
* `electron`: 桌面框架。
* `node-fetch` / `axios`: 网络请求。
* `tar` / `adm-zip`: 备份压缩。
### 外部服务
* **Google Gemini API**: 用于配额检查。
* **Anthropic API**: 用于配额检查。
* **OAuth 2.0 端点**: 用于账号授权。
### 文件系统依赖
* `~/.antigravity-agent/`
* `accounts.json`: 本地 IDE 账号索引。
* `cloud_accounts.db`: (新) 云端账号池数据库 (SQLite)。
* `backups/`: 备份文件。
* `app.log`: 应用日志。